text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Android: possible to access kernel modules directly without rooting the phone? Can Android apps access /dev or /sys without rooting the device?
I have permission problems when doing this from an Activity.
Can it work and the native layer?
A:
Can Android apps access /dev or /sys without rooting the device?
AFAIK, no.
Can it work and the native layer?
If you mean, "can I write an NDK library to access /dev/ or /sys/?", the language in which you write the code will not matter. It is a matter of processes, users, and permissions.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599929",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Adobe Flash CS3 sound in movieclip There's an animation (MovieClip) in my scene. There's a sound accompanying animation. I inserted it into the first frame of the animation.
I want this animation to be inactive initially. I plan to activate it when some button is pressed.
I don't know how to set it "inactive" from within Adobe Flash workspace, so I just put in constructor of my scene:
MovieClip(getChildByName("MyAnim")).stop();
By it does not prevent that sound to start playing when my scene appears!
How do I manage it?
A: Put the sound on frame two in your movieclip. Then go to that frame when you click the button.
private function onButtonClick(event : MouseEvent) : void
{
mySoundClip.gotoAndStop(2);
}
A: In my experience, it usually isn't a good idea to insert sounds directly onto the timeline in flash. I strongly advice to import the .mp3 into the Flash program and play it by code using the AS3 Sound class.
EDIT: This way, the sound won't play until you use the Sound Class .play() method, which you could do at the beginning of your animation on the timeline OR from the button that activates it.
Here is a nice Republic of Code tutorial giving you a step by step on how to play a Sound file using the AS3 Sound Class.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599933",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Clearing items in Combobox if user selection changed I am developing an windowsform application . It consists of a combobox with list of servernames and one more for list of databases for selected servername and one more for list of tables for selected database . when user selects servername and clicks button it displays the database names in tht server . If user changes his mind and selects another servername still i am having same list of databases of first selected . My database list should refresh each time depending upon the server slection change how can i achive this
Here is my sample code :
public MainForm()
{
InitializeComponent();
// FileHelper = new SqlDatabaseDataExport.FileHelper.FileUtilHelper();
dt = SmoApplication.EnumAvailableSqlServers(false);
if (dt.Rows.Count > 0)
{
foreach (DataRow dr in dt.Rows)
{
ServernamesList_combobox.Items.Add(dr["Name"]);
}
// ServernamesList_combobox.Items.Add("10.80.104.30\\webx");
DisplayMainWindow("Server list added");
Logger.Log("Server List added");
}
Authentication_combobox.Items.Add("Windows Authentication");
Authentication_combobox.Items.Add("Sql Authentication");
}
/// <summary>
/// Generating list of databases with in the selected Server and list of
/// selected tables with in the selected
/// databse
/// </summary>
/// <param name="sender"></param>
/// <param name="e"></param>
private void DatabasenamesList_combobox_SelectedIndexChanged(object sender, EventArgs e)
{
dbName = DatabasenamesList_combobox.SelectedItem.ToString();
connectionString = GetConnectionString();
string mySelectQuery = "select [name] from sys.tables WHERE type = 'U' AND is_ms_shipped = 0 ORDER BY [name];";
SqlConnection con = new SqlConnection(connectionString);
SqlCommand myCommand = new SqlCommand(mySelectQuery, con);
con.Open();
SqlDataReader myReader = myCommand.ExecuteReader();
try
{
while (myReader.Read())
{
SelectTables.Items.Add(myReader.GetString(0));
}
}
finally
{
myReader.Close();
con.Close();
}
}
private void button1_Click_1(object sender, EventArgs e)
{
serveName = ServernamesList_combobox.SelectedItem.ToString();
if (string.IsNullOrEmpty(serveName))
{
MessageBox.Show("Please select servername");
return;
}
if (Authentication_combobox.SelectedItem == null)
{
MessageBox.Show("Please select authentication");
return;
}
String conxString = string.Empty;
if (Authentication_combobox.SelectedItem == "Windows Authentication")
{
conxString = "Data Source=" + serveName + "; Integrated Security=True;";
}
if (Authentication_combobox.SelectedItem == "Sql Authentication")
{
if (string.IsNullOrEmpty(Username.Text))
{
MessageBox.Show("Please Enter Valid User name");
return;
}
if (string.IsNullOrEmpty(Password.Text))
{
MessageBox.Show("Please Enter Valid Password");
return;
}
conxString = "Data Source=" + serveName + "; Integrated Security=False;User ID =" + Username.Text + ";Password=" + Password.Text;
}
using (SqlConnection sqlConx = new SqlConnection(conxString))
{
try
{
sqlConx.Open();
MessageBox.Show("Connection established successfully");
}
catch (Exception ex)
{
MessageBox.Show("Exception" + ex);
MessageBox.Show(" Please enter valid Credentials");
return;
}
DataTable tblDatabases = sqlConx.GetSchema("Databases");
sqlConx.Close();
foreach (DataRow row in tblDatabases.Rows)
{
Databases.Add(row["database_name"].ToString());
}
foreach (var database in Databases)
{
DatabasenamesList_combobox.Items.Add(database);
}
}
}
A: Add a SelectedIndexChanged event to your DatabasenamesList_combobox.
In the code for that method, simply call your code to populate your database. Right nnow everything is stuffed into 'button1'. Move out your procedure into one called something like
private void PopulateDatabases(string serverName)
{
//populate Databases
//.. your code here ...
//clear the list
DatabasenamesList.Items.Clear();
foreach (var database in Databases)
{
DatabasenamesList_combobox.Items.Add(database);
}
}
There are many other ways to clean up this code, such as in your:
catch (Exception ex)
how do you know an exception is from not having the right authentication type? You should catch a specific type of exception and handle it separately.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599935",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Drop down selection control I have a nice little UserControl that is a draggable box with some text in. To the right hand side of the control is a little clickable arrow, which when clicked, I'd like to get a few options pop out of the right of the control.
I have already got a PopoutWindow class, which inherits ToolStripDropDown, which allows me to pop up get a new control to 'pop out' of the right hand side of this arrow with the following usage.
MyPopoutWindow options = new MyPopoutWindow ();
PopoutWindow popout = new PopoutWindow(options);
popout.Show(arrowButton, arrowButton.Width, 0);
MyPopoutWindow is (currently) a custom UserControl, which I want to be the same as the popped-out body of a ComboBox, or a ToolStripMenu.
Does anyone know of a Winforms control I can use or inherit to get this effect? I've tried using ToolStripDropDownMenu and ToolStripDropDown but I get the following Exception:
Top-level control cannot be added to a control.
Thanks,
A: The solution was actually quite obvious (isn't it always!). As I mentioned in the question, I'd tried using a ToolStripDropDown but that threw an Exception.
To solve this, I've got MyPopoutWindow to inherit ToolStripDropDown, but in the constructor, set the TopLevel property to false. This worked!
public MyPopoutWindow()
{
TopLevel = false;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599936",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Scope issue on a try catch statement I have a n00b/basic issue about the try catch on java.
Ini myIni;
try {
myIni = new Ini(new FileReader(myFile));
} catch (IOException e) {
e.printStackTrace();
}
myIni.get("toto");
and the error message that follows :
variable myIni might not have been initialized
Is the scope of the try only restricted to the try area ?
How can I fetch the result of myIni in the following code ?
A: To avoid the message, you need to set a default value before the try statement.
Or you need to put the call to the get() method in the try statement.
A: Yes, the scope of the try is restricted to that. In fact the scope starts with { and ends with }, thus this would also create a sub-scope
void foo() {
{
Ini myIni = new Ini(new FileReader(myFile));
}
myIni.get("toto"); //error here, since myIni is out of scope
}
To fix your issue, initialize myIni with null, and be aware that if the try fails, myIni.get("toto"); would result in a NullPointerException.
So you'd need to either account for that or throw another exception from your catch block.
Check for null:
Ini myIni = null;
try {
myIni = new Ini(new FileReader(myFile));
} catch (IOException e) {
e.printStackTrace();
}
if( myIni != null ) {
myIni.get("toto");
//access the rest of myIni
} else {
//handle initialization error
}
Throw exception:
Ini myIni = null;
try {
myIni = new Ini(new FileReader(myFile));
} catch (IOException e) {
e.printStackTrace();
throw new MyCustomInitFailedException(); //throw any exception that might be appropriate, possibly wrapping e
}
myIni.get("toto");
As already suggested by @khachik you could also put the try block around your entire usage of myIni if that's possible and appropriate. What solution you choose depends on your other requirements and your design.
A: In your the correct way to do what you want is to put myIni.get("toto"); inside the try block:
try {
Ini myIni = new Ini(new FileReader(myFile));
myIni.get("toto");
} catch (IOException e) {
e.printStackTrace();
}
Don't do Ini myIni = null; as some answers suggested. In this case, your code will throw NullPointerException, if an IOException is thrown on the initialization of myIni.
A:
Is the scope of the try only restricted to the try area ? The answer is yes. The issue you having is you've forgotting to initialize your object.
Try this:
Ini myIni=null;
try {
myIni = new Ini(new FileReader(myFile));
} catch (IOException e) {
e.printStackTrace();
}
To avoid your program from recieving NullPointerException, performing a check to make sure the called within the try block resulted in the Object been build with some data.
if(myIni !=null)
{
myIni.get("toto");
}
Alternative if you do not want to call myIni outside the try/catch block because if an exception occurs, the object will in effect be null, then you can do as follows.
try {
Ini myIni= new Ini(new FileReader(myFile));
myIni.get("toto");
} catch (IOException e) {
e.printStackTrace();
}
A: This is the way of the compiler to say that the initialization of myIni might fail. Because the myIni = new Ini(new FileReader(myFile)); line might throw an exception.
If it fails when you get to the line myIni.get("toto"); myIni would not have been initialized.
You have 2 choices:
*
*Put the myIni.get("toto"); inside the try block.
*Assign an initial null value to myIni when you define it and check for null outside of the try block.
A: Just put myIni.get("toto") inside the try catch block, or write Ini myIni = null; in the first row. Note that if you do the second variant you might get a NullPointerException if the file is not found, or cannot be read for any other reason...
cheers!
P
A: write Ini myIni = null; and that's it
A: In the catch statement, you don't define the value of the variable. Therefore, the variable won't have a value if you catch then run myIni.get("toto");. You'd want to do something like this:
Ini myIni = null;
try {
myIni = new Ini(new FileReader(myFile));
} catch (IOException e) {
e.printStackTrace();
}
myIni.get("toto");
Even so, you'll get an NPE when running get().
A: in your code, if an exception happens, the variable myIni could not be instantiated, that's why the compiler rises such a warning.
you can change it to:
Ini myIni = null;
try {
myIni = new Ini(new FileReader(myFile));
} catch (IOException e) {
e.printStackTrace();
}
if(myIni!=null){
myIni.get("toto");
}
A: As @khachik pointed out, it is best to declare and initialize the variable inside the try block itself. Initialize like below, outside the try bock only if you feel supremely confident which is indistinguishable from arrogance.
Ini myIni = null;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599941",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How to change visibility in dynamically generated content Javascript and PHP Hi Everyone so here's the problem, I think it's mostly a little problem with my lack of knowledge in Javascript but here's what I did:
JS Code:
function mostrarResul(idFold, Id)
{
if($(idFold).css(visibility) == "none")
{
$(idFold).css(visibility, inline);
$(Id).detach();
$(Id).append("<a id='"+Id+"' class='showmore' onclick='mostrarResul("+idFold+", "+Id+")'>ver menos</a>");
}else
{
$(idFold).css(visibility, none);
$(Id).detach();
$(Id).append("<a id='"+Id+"' class='showmore' onclick='mostrarResul("+idFold+", "+Id+")'>ver más</a>");
}
}
PHP Code:
$idFolder = $item[_folder_name];
$idFolder = strtolower($idFolder);
$idFolder = str_replace(" ", "_", $idFolder);
echo "<div class='result'>";
echo "<div class='item'>
<label><a onclick='mostrarResul($idFolder, $id)'>".$item[_folder_name]."</a></label>";
$news = process_all("SELECT * FROM _tips WHERE _folder = '$item[_folder_name]' ORDER BY _date_create LIMIT 0,20");
echo "<div class='itemNews' id='".$idFolder."' style='display:none'>";
echo "<ul>";
if ($news) foreach( $news as $n)
{
echo "<a href='/consejos-recomendaciones/".$n[_permalink]."'>".$n[_subject]."</a><br/>";
}
echo "</ul";
echo "</div>";
echo "<a id='".$id."' class='showmore' onclick='mostrarResul($idFolder, $id)'>ver más</a>
</div>";
echo "</div>";
$id += 1;
Ok so the JS code is supposed to change the visibility attribute depending on it's current state and detach & append code depending on the same things, my real problem is when sending the variables to the JS and manipulating them, any tips??
Hi again, Someone said before that I could do this using Jquery.js and I wanted to ask how???, I'm already using jquery for other things and wanted to now how to use it when I'm creating the Id for the tags???
Solved.
The other thing is, do you guys now what function in PHP 5.2 returns a string of a length that I want, example
String Val= "Hello everyone";
(function to manipulate string)
and the new string val is "Hello".
A: The answer to your last question is substr. http://php.net/manual/en/function.substr.php
So in your case, it would be
$var = "Hello everyone";
$new_var = substr($var, 0, 5);
echo $var . ' - ' . $new_var;
Output would be: Hello everyone - Hello
A: So, your problem (that I see) is that everything inside .css() should be in quotes. I assume you're using jQuery? If not already, you need to include it in your page head, like this:
<script src="http://ajax.googleapis.com/ajax/libs/jquery/1.6.4/jquery.min.js"></script>
then everything you write in jQuery should not be without quotes:
$(idFold).css(visibility, inline);
but should be like this:
$(idFold).css('visibility', 'inline');
Also, the hidden property not "none" is the correct property for visibility
http://www.w3schools.com/cssref/pr_class_visibility.asp has more info on it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599942",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to show nested json data/ extjs4? i have a function that return 7 values, i used a tuple to return them since they dont have the same type
then i serelizes it
so i can read my resulted json in my js script , and i can access it via ItemN
take a look at the code:
public JArray getJsonData( )
{
//my queries here//
var vl = new List<Tuple<string, string, string, int, int, double, string >>();
vl.Add(new Tuple<string, string, string,int, int, double, string>
(item.Date , item.Adress, name, item.login, pwd, role, id));
}
JArray o = JArray.FromObject(vl);
return o;
}
my extjs4 store:
var myStore2 = new Ext.data.JsonStore({
fields: ['Item1', 'Item2', 'Item3', 'Item4', 'Item5', 'Item6', 'Item7'] ,
data: []
});
the problem is that now i need to return another element which make them 8 elements in my tuple
so i get this funny error
the eight element of an eight tuple must be a tuple
so i add my eight element as a tuple as requested.
the problem is that now i get this json format: (notice 'Rest' at the end)
{Item1:"27-09-2011",Item2:"LA",Item3:"armance",Item4:"astrocybernaute",Item5:"P@ssw0rd",Item6:"Admin",Item7,Rest : {Item1 : 26 }}
the problem is that i dont know how to access it in my extjs4 store. Item8 of course doesnt work,Rest doesnt work,item1 doesnt either!!
any idea plz?
thank you for ur time
EDIT this is my new store after Matt Greer suggestion
Ext.define('MyModel', {
extends: 'Ext.data.Model',
fields: [
{ name: 'Item1' },
{ name: 'Item2' },
{ name: 'Item3' },
{ name: 'Item4' },
{ name: 'Item5' },
{ name: 'Item6' },
{ name: 'Item7' },
{ name: 'Item8', mapping: 'Rest.Item1' }
]
});
var myStore2 = new Ext.data.JsonStore({
model: 'MyModel',
proxy: {
type: 'ajax',
url: '',
autoLoad :true,
reader: {
type: 'json'
}
}
});
but it still not working
SOLUTION
I want to point out that Store.loadData does not respect the field mapping
The issue is that the sencha team changed loadData's behavior, AND it's not something that's documented in a way that is clear.
Add the following to your code base (above your app code, but below ext-all.js):
Ext.override(Ext.data.Store, {
loadDataViaReader : function(data, append) {
var me = this,
result = me.proxy.reader.read(data),
records = result.records;
me.loadRecords(records, { addRecords: append });
me.fireEvent('load', me, result.records, true);
}
});
then use:
mystore2.loadDataViaReader(data)
A: I'm not sure where that Tuple error is coming from. octuples are supported by .NET as shown here
Give this a try
var myTuple = Tuple.Create(3,4,5,8,12,4,12,99);
myTuple should be a octuple of 8 ints.
But, if you still get that error and you must work around it in Ext, you can use mappings. You need to define a Model, and in the Model's fields use a mapping to grab that last value:
Ext.define('MyModel', {
extends: 'Ext.data.Model',
fields: [
{ name: 'field1' },
// fields 2 through 7
{ name: 'field8', mapping: 'Rest.Item1' }
]
});
var myStore = new Ext.data.JsonStore({
model: 'MyModel',
// ...
});
I've never actually tried defining fields right on the store, I assume Ext is creating a Model automatically for you. So you could probably do the mapping right in the store as well.
A: Your solution run when we used the loadData method, and when the proxy used is a Memory proxy.
In fact, It seems that EXTJS can not map datas when its a memory proxy. but when its a Ajaxs proxy it can map the datas and fields.
Exemples with memory proxy
var fields = [
{name: 'id', mapping: 'id'},
{name: 'code', mapping: 'code'},
{name: 'code', mapping: 'exercice'},
{name: 'code', mapping: 'code'},
{name: 'typeDocument', mapping: 'typeDocument'},
{name: 'utilisateur', mapping: 'editionJobs[0].utilisateur'},
{name: 'dateCreation', mapping: 'editionJobs[0].dateCreation'},
{name: 'jobId', mapping: 'editionJobs[0].id'},
{name: 'avenant', mapping: 'editionJobs[0].avenant'},
{name: 'etat', mapping: 'editionJobs[0].etat'}
];
var data = [];
store = new Ext.data.Store({
fields: fields,
proxy: {
type: 'memory',
reader: {
type: 'json',
root: 'listDossier'
}
},
listeners: {
load: function(store, records, options) {
store.fireEvent('datachanged', store);
}
}
});
Ext.getCmp('listeEditionDossierGridPanel').getStore().loadDataViaReader(listDossier); // OK, thx for the method ;)
Ext.getCmp('listeEditionDossierGridPanel').getStore().loadData(listDossier); // Not ok
Other exemple with Ajax Proxy :
var fields = [
{name: 'code', mapping : 'code'},
{name: 'avis', mapping : 'demande.avis'},
{name: 'commentaire', mapping : 'demande.commentaire'},
{name: 'id', mapping: 'demande.id'}
];
store = new Ext.data.Store({
fields: fields,
autoLoad: true,
proxy: {
type: 'ajax',
extraParams: {jsonRequest:JSON.stringify(valeurs)},
url : 'chargerDossiersEligibles.do',
reader: {
type: 'json',
root: 'dossiersEligibles'
}
}
});
In this case all is fine and the datas can map.
Cheers
Benoit
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599946",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Associative array in CouchDB keys? I haven't seen any mention of this around, but is there any way to deal with an associative array key in CouchDB?:
map: function(doc) { if (...) { emit({ one: doc.one, two: doc.two, ... }); } }
I have a need for some rather dynamic and complex queries, this would help solve that problem (but I'm guessing this completely breaks everything).
A: All keys are always sorted along one dimension only. Associative array (object) keys are supported by CouchDB. The sort order is well-defined, however it is basically arbitrary and much less intuitive than, for example, arrays, where we all know that the first/leftmost element is most significant.
Additionally, different programming languages, client libraries, and JSON serializers might (and do!) change the order of the keys in the associative array. (Often it does not matter because in Javascript, or in most languages really, key order is undefined.)
The CouchDB collation specification describes the sort order of all valid JSON data, including associative arrays (objects).
Maybe you can simulate associative arrays by flattening it into an array and sorting the keys, all o the client side.
{"foo":"This value is foo", "A":65, "the":"end"}
becomes
["A", 65, "foo", "This value is foo", "the", "end"]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599951",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: ASP.NET Web Service return arraylist of different object types I got a problem when I tried ASP.NET WebService to return arraylist of several object types.
Suppose I have a Book object and a Table object.
I added Book and Table objects to an ArrayList.
After that I return that arraylist in webservice. It does not allow me to do.
How can I make it be able to return several object types?
A: Can you not define a complex object (DTO in this examle) that contains the other objects and return the populated DTO in you webmethod:
[OperationContract]
Dto GetBooksAndTables();
[DataContract]
public class Dto
{
[DataMember]
public Book[] Books { get; set; }
[DataMember]
public Table[] Tables { get; set; }
}
[DataContract]
public class Book
{
[DataMember]
public string BookName {get; set; }
//etc...
}
[DataContract]
public class Table
{
[DataMember]
public string TableName {get; set; }
//etc...
}
Have you looked at http://wcf.codeplex.com/wikipage?title=WCF%20HTTP - it makes building .NET services much easier. It's on NuGet.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599954",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android finish Activity and start another one I'm curious about one thing. How can I finish my current activity and start another one.
Example :
MainActivity
--(starts)--> LoginActivity
--(if success, starts)--> SyncActivity
--(if success start)--> MainActivity (with updated data).
So I want when SyncActivity starts MainActivity after succesfull sync and if I press back button not to return to SyncActivity or any other activity opened before SynActivity.
I've tried with this code :
Intent intent = new Intent(Synchronization.this, MainActivity.class);
intent.addFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(intent);
this.finish();
but it's not working properly. Any ideas how to get the things to work properly?
A: Use
Intent intent = new Intent(SyncActivity.this, MainActivity.class);
intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
startActivity(intent);
A: Judging from your OP, I'm not sure if you absolutely must initialize your mainActivity twice..
Android is designed so that an app is never really closed by the user.
Concentrate on overriding the android lifecycle methods such as OnResume and OnPause to save UI data, etc.
Hence, you don't need to explicitly finish() the main activity (and really shouldn't). To receive login or sync data from the previous activities, just override the OnActivityResult() method. However, to do this you must start the activity using startActivityForResult(intent). So for each activity you should do this:
Main activity:
static public int LOGIN_RETURN_CODE = 1;
to start login:
Intent intent = new Intent(MainActivity.this, LogInActivity.class);
startActivityForResult(intent, LOGIN_RETURN_CODE);
to recieve login info:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case LOGIN_RETURN_CODE:
//do something with bundle attached
}
}
Login activity:
static public int SYNC_RETURN_CODE = 2;
to start sync:
Intent intent = new Intent(LogInActivity.this, SyncActivity.class);
startActivityForResult(intent,SYNC_RETURN_CODE);
to recieve info and return to Main:
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
switch (requestCode) {
case MainActivity.SYNC_RETURN_CODE:
Intent intent = new Intent(...);
intent.setResult(RESULT_OK);
finish();
}
}
This might not all compile, but hopefully you get the idea.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599955",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "27"
}
|
Q: Site not working header Sorry for my English. I editing site in asp and I have a problem, the header is not visible http://edusf.ru/project/default1.aspx
But the normal version, with a working header http://edusf.ru/project/
I can not understand the problem. Here is the code page default1.aspx
<%@ Page Language="C#" AutoEventWireup="true" Inherits="Bitrix.UI.BXPublicPage, Main" Title="Демо страница" %>
<script runat="server" id="@__bx_pagekeywords">
public override void SetPageKeywords(System.Collections.Generic.IDictionary<string, string> keywords)
{
keywords[@"keywords"]=@"";
keywords[@"description"]=@"";
keywords[@"ShowLeftColumn"]=@"";
}
</script>
<asp:Content ID="Content1" ContentPlaceHolderID="bxcontent" runat="server" >
<head>
<link rel="stylesheet" type="text/css" href="style.css" />
<script type="text/javascript" src="jquery.js"></script>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<script type="text/javascript">
$(function(){
$("#about-button").css({
opacity: 0.3
});
$("#contact-button").css({
opacity: 0.3
});
$("#page-wrap div.button").click(function(){
$clicked = $(this);
if ($clicked.css("opacity") != "1" && $clicked.is(":not(animated)")) {
$clicked.animate({
opacity: 1,
borderWidth: 5
}, 600 );
var idToLoad = $clicked.attr("id").split('-');
$("#content").find("div:visible").fadeOut("fast", function(){
$(this).parent().find("#"+idToLoad[0]).fadeIn();
})
}
$clicked.siblings(".button").animate({
opacity: 0.5,
borderWidth: 1
}, 600 );
});
});
</script>
</head>
<body>
<div id="page-wrap">
<div id="home-button" class="button">
<img src="button-1.png" alt="home" class="button" />
</div>
<img style="float: left;" src="devide.png" width="2" height="24" />
<div id="about-button" class="button">
<img src="button-2.png" alt="about" class="button">
</div>
<img style="float: left;" src="devide.png" width="2" height="24" />
<div id="contact-button" class="button">
<img src="button-3.png" alt="contact" class="button">
</div>
<div class="clear"></div>
<div id="content">
<div id="home">
<p><h1>Социальный образовательный портал</h1>
<table class="st2">
<tbody>
<tr><td class="left" style="-moz-border-top-colors: none; -moz-border-right-colors: none; -moz-border-bottom-colors: none; -moz-border-left-colors: none; -moz-border-image: none;">
<p>Социальный образовательный портал – это веб-сервис для обучения через общение всех участников учебного процесса. Как и в любой системе обучения в данном сервисе есть возможность изучения курсов и прохождения тестов. Но главный принцип работы пользователей в сервисе – общение, интерактивное взаимодействие в решении задач и создание личного виртуального пространства.</p>
</td><td class="right" style="-moz-border-top-colors: none; -moz-border-right-colors: none; -moz-border-bottom-colors: none; -moz-border-left-colors: none; -moz-border-image: none;">
<p>Участвуя в жизни портала, каждый пользователь сервиса становится частью информационного пространства учебного заведения или организации. Если в привычном понимании портал - это обширная и систематизированная база учебных материалов и документов, то социальный образовательный портал - это актуальные знания каждого из его участников в динамике.</p>
</td></tr>
</tbody>
</table>
<table class="st2">
<tbody>
<tr><td class="left" style="-moz-border-top-colors: none; -moz-border-right-colors: none; -moz-border-bottom-colors: none; -moz-border-left-colors: none; -moz-border-image: none;">
<p><img height="236" width="370" src="/project/src001.jpg" alt="Социальный образовательный портал" /></p>
</td><td class="right" style="-moz-border-top-colors: none; -moz-border-right-colors: none; -moz-border-bottom-colors: none; -moz-border-left-colors: none; -moz-border-image: none;">
<p><img height="236" width="370" src="/project/src002.jpg" alt="Социальный образовательный портал" /></p>
</td></tr>
</tbody>
</table>
<table class="st3">
<tbody>
<tr><td class="left" style="-moz-border-top-colors: none; -moz-border-right-colors: none; -moz-border-bottom-colors: none; -moz-border-left-colors: none; -moz-border-image: none;">
<p>В отличие от традиционных систем дистанционного обучения (СДО), данный сервис усиливает направляющую роль преподавателя. Активность обучаемых видна преподавателям, что способствует их профессиональной ориентации, раскрытию творческого потенциала и вовлечению в общественную жизнь. </p>
</td><td class="middle" style="-moz-border-top-colors: none; -moz-border-right-colors: none; -moz-border-bottom-colors: none; -moz-border-left-colors: none; -moz-border-image: none;">
<p>Обучаемые также могут наблюдать активность друг друга, что делает процесс обучения прозрачным, мотивирует к соперничеству и достижению лучших результатов в учебной и не учебной деятельности.</p>
</td><td class="right" style="-moz-border-top-colors: none; -moz-border-right-colors: none; -moz-border-bottom-colors: none; -moz-border-left-colors: none; -moz-border-image: none;">
<p>В СДО под самостоятельной работой обучаемых фактически подразумевается его изоляция от друзей и от более качественных и актуальных учебных материалов, а Социальный образовательный портал предлагает коллективную работу по выработке и накоплению знаний, где самостоятельность означает лидерство. </p>
</td></tr>
</tbody>
</table>
<p style="text-align: center;"><img height="251" width="810" src="/project/diag001.jpg" alt="Социальный образовательный портал" style="margin-top: 20px; margin-bottom: 20px;" /></p>
<table class="st2">
<tbody>
<tr><td class="left" style="-moz-border-top-colors: none; -moz-border-right-colors: none; -moz-border-bottom-colors: none; -moz-border-left-colors: none; -moz-border-image: none;">
<p>В Социальном образовательном портале используются средства неформального общения, знакомые пользователям по популярным социальным сервисам. Это помогает пользователям более активно взаимодействовать друг с другом: делиться полезной информацией, интенсивно использовать навыки общения, коллективно решать задачи, и выполнять групповые учебные и творческие проекты.</p>
<p>Используя социальный образовательный портал, Вы получаете управление интеллектуальным капиталом Вашей организации и творческим потенциалом Ваших студентов и работников. В процессе взаимодействия пользователей генерируются уникальные новые решения и информационные ресурсы. Вы можете применять их для последующего цикла обучения и в целях совершенствования бизнес-процессов Вашей организации.</p>
</td><td class="right" style="-moz-border-top-colors: none; -moz-border-right-colors: none; -moz-border-bottom-colors: none; -moz-border-left-colors: none; -moz-border-image: none;">
<p><strong>Социальный образовательный портал включает в себя взаимодополняющий функционал продуктов трёх типов:</strong></p>
<ul>
<li>система управления сайтом (администрирование, управление правами пользователей, учебные группы, настройка интерфейса, обновление учебного контента, добавление общих компонент: новости, объявления, галереи); </li>
<li>система дистанционного обучения (курсы и тесты в формате SCORM, статистика обучения, вебинары, календари событий, управление проектным обучением); </li>
<li>социальная сеть (блоги, группы друзей, фотоальбомы, комментарии, хранение документов, события, закладки и обмен ими).
<br />
Все пользователи сервиса имеют одинаковый набор инструментов, отличающийся только возможностями, зависящими от роли (студент, преподаватель, куратор и др.) </li>
</ul>
</td></tr>
</tbody>
</table>
</p>
</div>
<div id="about">
<p>Cтраница находится в разработке</p>
</div>
<div id="contact">
<p>Cтраница находится в разработке</p>
</div>
</div>
</div>
</body>
</asp:Content>
A: In your non-working example, the header image from styles.css which is looking at: http://edusf.ru/project/images/head.jpg which is throwing a 404, not found. It is overriding the setting from template_styles.css
In your working example is getitng it from template_styles.css, and getting the following working image http://edusf.ru/bitrix/templates/edusf/images/head.jpg
|
{
"language": "ru",
"url": "https://stackoverflow.com/questions/7599956",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Unit testing LINQ to SQL CRUD operations using Moq I've had a look around at other questions, but nothing really matches what I'm looking for... mainly because I'm not 100% certain on what it is I'm looking for!
Basically I'm working on a new project at the moment, I've created my abstraction layer for DB entities and set the DAC to be repositories. I'm wanting to use unit testing for this with Mock objects, however I've hit a intellectual wall with CRUD (specifically C) operations, my unit test class:
[TestClass]
public class RepositoryTest
{
private Mock<IPersonRepository> _repository;
private IList<IPerson> _personStore;
[TestInitialize()]
public void Initialize()
{
_personStore= new List<IPerson>() {
new Person() { Name = "Paul" },
new Person() { Name = "John" },
new Person() { Name = "Bob" },
new Person() { Name = "Bill" },
};
_repository = new Mock<IPersonRepository>();
_repository.Setup(r => r.Entirely()).Returns(_personStore.AsQueryable());
}
[TestCleanup()]
public void Cleanup()
{
_personStore.Clear();
}
[TestMethod()]
public void Can_Query_Repository()
{
IEnumerable<IPerson> people = _repository.Object.Entirely();
Assert.IsTrue(people.Count() == 4);
Assert.IsTrue(people.ElementAt(0).Name == "Paul");
Assert.IsTrue(people.ElementAt(1).Name == "John");
Assert.IsTrue(people.ElementAt(2).Name == "Bob");
Assert.IsTrue(people.ElementAt(3).Name == "Bill");
}
[TestMethod()]
public void Can_Add_Person()
{
IPerson newPerson = new Person() { Name = "Steve" };
_repository.Setup(r => r.Create(newPerson));
// all this Create method does in the repository is InsertOnSubmit(IPerson)
// then SubmitChanges on the data context
_repository.Object.Create(newPerson);
IEnumerable<IPerson> people = _repository.Object.Entirely();
Assert.IsTrue(people.Count() == 5);
}
}
My Can_Query_Repository method is successful, however the Can_Add_Person method fails assertion. Now, do I need to do:
*
*Setup the .Create method of the Mock repository to add the element to the _personStore?
*Do something else similar?
*Abandon all hope as what I want to achieve isn't possible and I'm doing it all wrong!
As always, any help / advice appreciated!
A: Ideally you would do some integration tests for those, but if you want to unit test it, there are possible avenues, including one that wasn't mentioned in the comments of the original question.
The first one.
When testing your crud, you can use .Verify to check that the Create methods have really been called.
mock.Verify(foo => foo.Execute("ping"));
With Verify, you can check that the argument was a certain argument, of a certain type and the number of times the method was actually called.
The second one.
Or if you want to verify the actual objects that have been added in the repository's collection, what you could do is use the .Callback method on your mock.
In your test create a list that will receive the objects you create.
Then on the same line where you call your setup add a callback that will insert the created objects in the list.
In your asserts you can check the elements in the list, including their properties to make sure the correct elements have been added.
var personsThatWereCreated = new List<Person>();
_repository.Setup(r => r.Create(newPerson)).Callback((Person p) => personsThatWereCreated.Add(p));
// test code
// ...
// Asserts
Assert.AreEuqal(1, personsThatWereCreated.Count());
Assert.AreEqual("Bob", personsThatWereCreated.First().FirstName);
Granted in your actual example, you create the person and then add it in the setup. Using the callback method here would not be useful.
You could also use this technique to increment a variable to count the number of times it was called.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599957",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: What is the meaning of the HTTP header Vary:* As far as I know, the HTTP Header Vary specifies a comma separated list of HTTP headers that need to be considered by caches together with the URL when deciding if a request is a cache hit or miss.
If that header is omitted, means that only the URL will be considered.
But what happen when the header is Vary:* ?
RFC 2616 14.4
A Vary field value of *** signals that unspecified parameters not
limited to the request-headers (e.g., the network address of the
client), play a role in the selection of the response representation.
The * value MUST NOT be generated by a proxy server; it may only be
generated by an origin server.
RFC 2616 13.6
A Vary header field-value of * always fails to match and subsequent
requests on that resource can only be properly interpreted by the
origin server.
Does it means that all requests with this header are going to be a cache miss?
I find out that ASP.NET is returning that HTTP header if you use their OutputCacheAttribute, and you have to disable explicitly that behaviour if you don't want the header, or you want to specify custom headers, so I (want to) believe it is unlikely.
Which is the practical meaning of Vary:* ?
Thanks.
A: Vary:* tells caches that the response has been chosen based on aspects beyond the usual aspects of HTTP content negotiation (e.g. Accept, Accept-Language, Accept-Charset).
Effectively this tells the cache not to cache the response. That is the meaning of "subsequent requests on that resource can only be properly interpreted by the origin server". The cache must forward these requests to the origin server.
Edit: Vary is orthogonal to caching. Consider this:
GET /foo HTTP/1.1
200 Ok
Cache-Control: maxage=60
Content-Location: /foo.html
Vary: *
Vary:* tells caches that the response cannot be cached for requests to /foo. But because of the Content-Location header, caches can still store the response for requests to /foo.html.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599964",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "11"
}
|
Q: Changing Text in Javascript I am not asking anybody to code for me. Please just tell me what I am missing or what I have done wrong with my codes.
My javascript program should run like this:
*
*Upon pressing a button, a simple multiplication table should appear and overwrite the words "The Table should be here".
*Pressing another button, another simple multiplication button should appear and overwrite the previous multiplication table.
I am able to make the multiplication tables come out but the problem is, it does not overwrite the previous table. It just creates another table at the bottom of the previous one. Please Help. This is not a home work.. I am very new and just trying to learn all the possibilities of creating a somewhat complex program using simple codes.
<script type="text/javascript">
function x()
{
var a=1;
for(a=0;a<=10;a++)
{
var total = 2 * a;
var newHeading = document.createElement("p");
var h1Text = document.createTextNode("2 x " + a + " = " + total);
newHeading.appendChild(h1Text);
document.getElementById("dname1").appendChild(newHeading);
}
}
function y(total)
{
var a=0;
for(a=0;a<=10;a++)
{
var total = 3 * a;
var newHeading = document.createElement("p");
var h1Text = document.createTextNode("3 x " + a + " = " + total);
newHeading.appendChild(h1Text);
document.getElementById("dname2").appendChild(newHeading);
}
}
</script>
</head>
<body>
<h1>Date and Hours</h1>
<p>Click a button</p>
<p id="dname1">Table of 2 should be here</p>
<p id="dname2">Table of 3 should be here</br></p>
<button type="button" onclick="x()">Table of Two</button>
<button type="button" onclick="y()">Table of Three</button>
A: You should clear both tables before appending anything: http://jsfiddle.net/2NtXH/2/.
// setting the innerHTML to an empty string basically removes its contents
document.getElementById("dname1").innerHTML = "";
document.getElementById("dname2").innerHTML = "";
A: if you want to use jQuery, simply do this
$("#dname1").html("");
$("#dname2").html("");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599968",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: cake php, how to populate a drop down selection based on another drop down selection? I have a table something like this:
id test attr dim
1 test1 a1 d1
2 test2 a2 d2
3 test3 a1 d3
4 test3 a1 d2
I am creating a drop down field that shows the attr as having only two options a1 and a2. Based on a selection of either a1 or a2 i would like to do is something like:
if (a1 is selected){$a == a1} else {$a == a2}
$test = mysql_query("SELECT dim FROM xxx WHERE attr = $a")
and fill up the second drop down with the results from that query that could be d1, d2 or d3
and so on, on multiple drop down lists if I need to.
I know how to do this in regular php but not sure how to do it in CakePHP.
Any ideas?
Edit: I'm not sure if i need to use any ajax, this should be working without it
A: You can do with help of ajax->observefield
eg:
$options = array('url' => 'getcounties', 'update' => 'ExampleCountyI
$ajax->observeField('ExampleStateId', $options);
UPDATED
observeField is not more available in CakePHP js helper here it's equivalent way to the same for newer CakePHP version >= 2.x
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599971",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Android ActionBar Tab Navigation I am following http://www.youtube.com/watch?v=gMu8XhxUBl8 example. Setting up the tabs is working fine. On each tab, I am using a cursor to get the data from SQLite and display it. where should I write that code ? In TabActivity ? In AFragmentTab ?
A: In your AFragmentTab
Im sure this is where your work if any will take place.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599973",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to do join with multiple conditions in mysql How can i it in single query
Get mID for uID(1) (33,34,35)
select text where mID (33,34,35){based on the above result}
select Name where uID(user id of mID in table b (5,6)){based on the above result}
Output
txt1 user5
txt3 user6
The only id I know is uID. How to do this in a single query.
TableA TableB TableC
uID mID mID Text uID uID Name
1 33 33 txt1 5 1 user1
2 34 34 txt2 5 2 user2
1 35 35 txt3 6 5 user5
2 33 6 user6
2 34
A: select b.Text, c.Name
from TableA a
inner join TableB b on a.mID = b.mID
inner join TableC c on b.uID = c.uID
where a.uID = 1
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599974",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can I unit test a Grails controller when using a custom property editor? I'd like to use the technique described here: Grails bind request parameters to enum
to automatically bind the String representation of an enum to a domain instance.
The technique works fine, but my existing controller unit tests fail because the custom editors are not loaded during unit testing. I'd hate to switch to integration tests for every controller just for this data-binding technique.
Is there a way to unit test a controller action when you have a custom property editor?
A: As far as I know, spring application context isnt available in unit tests, and hence your property registrars and property editors won't have been registered. so custom property editors won't work in unit tests. However, grails uses GrailsDataBinder - which is subclass of DataBinder You might be able to do some meta programming and metaClass stuff so that your custom property editor gets registered and found when bind() is called.
A: In Grails 2.x you can define your extra beans in your unit test, just use defineBeans as the first thing in your setup:
@TestFor(MyController)
class MyControllerTests {
@Before
void setup() {
defineBeans {
myCustomEditorRegistrar(MyCustomEditorRegistrar)
}
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: NSInternalInconsistencyException when using KVO I'm trying to use a KVO example I got from an iPhone tutorial book, but get this exception
Terminating app due to uncaught exception 'NSInternalInconsistencyException', reason: '<UINavigationController: 0x139630>: An -observeValueForKeyPath:ofObject:change:context: message was received but not handled.
Key path: dataUpdated
Observed object: <FilterDetailsController: 0x1b9930>
Change: {
kind = 1;
}
Context: 0x0'
Call stack at first throw:
(
0 CoreFoundation 0x320d3987 __exceptionPreprocess + 114
1 libobjc.A.dylib 0x3271849d objc_exception_throw + 24
2 CoreFoundation 0x320d37c9 +[NSException raise:format:arguments:] + 68
3 CoreFoundation 0x320d3803 +[NSException raise:format:] + 34
4 Foundation 0x35c316e9 -[NSObject(NSKeyValueObserving) observeValueForKeyPath:ofObject:change:context:] + 60
5 Foundation 0x35bd4a3d NSKeyValueNotifyObserver + 216
6 Foundation 0x35bd46e5 NSKeyValueDidChange + 236
7 Foundation 0x35bcc3f5 -[NSObject(NSKeyValueObserverNotification) didChangeValueForKey:] + 76
8 Foundation 0x35c30d87 _NSSetObjectValueAndNotify + 98
9 Lucid Dreaming App 0x000108e3 -[FilterDetailsController adjustFilterDetails:] + 138
10 CoreFoundation 0x3207afed -[NSObject(NSObject) performSelector:withObject:withObject:] + 24
11 UIKit 0x323b3ea5 -[UIApplication sendAction:to:from:forEvent:] + 84
12 UIKit 0x323b3e45 -[UIApplication sendAction:toTarget:fromSender:forEvent:] + 32
13 UIKit 0x323b3e17 -[UIControl sendAction:to:forEvent:] + 38
14 UIKit 0x323b3b69 -[UIControl(Internal) _sendActionsForEvents:withEvent:] + 356
15 UIKit 0x323b43c7 -[UIControl touchesEnded:withEvent:] + 342
16 UIKit 0x323a9d4d -[UIWindow _sendTouchesForEvent:] + 368
17 UIKit 0x323a96c7 -[UIWindow sendEvent:] + 262
18 UIKit 0x3239499f -[UIApplication sendEvent:] + 298
19 UIKit 0x323942df _UIApplicationHandleEvent + 5090
20 GraphicsServices 0x35472f03 PurpleEventCallback + 666
21 CoreFoundation 0x320686ff __CFRUNLOOP_IS_CALLING_OUT_TO_A_SOURCE1_PERFORM_FUNCTION__ + 26
22 CoreFoundation 0x320686c3 __CFRunLoopDoSource1 + 166
23 CoreFoundation 0x3205af7d __CFRunLoopRun + 520
24 CoreFoundation 0x3205ac87 CFRunLoopRunSpecific + 230
25 CoreFoundation 0x3205ab8f CFRunLoopRunInMode + 58
26 GraphicsServices 0x354724ab GSEventRunModal + 114
27 GraphicsServices 0x35472557 GSEventRun + 62
28 UIKit 0x323c7d21 -[UIApplication _run] + 412
29 UIKit ...
I start by
[advancedController addObserver:self.navigationController forKeyPath:@"dataUpdated" options:0 context:nil];
within self.navigation controller, I have the observation method defined:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
NSLog(@"2 Observed change for: %@",keyPath);
// if (context == <#context#>) {
// <#code to be executed upon observing keypath#>
// } else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
// }
}
within advancedController I have a NSNumber property
@property(nonatomic,retain)NSNumber* dataUpdated;
When I hit a button, I expect the observer to fire.
- (IBAction)adjustFilterDetails:(id)sender {
self.dataUpdated = [NSNumber numberWithInt:[self.dataUpdated intValue]+1];
}
Do I need to implement some protocol or explicitly state that I will update the value? I read that NSKeyValueObserving is an "informal" protocol. Thank you for your help!
I have figured out the answer to my own question. I had the KVO protocol method defined within a ViewController, however, I have accidentally registered the Navigation controller for the View controller to observe the value. The correct object is found by getting the view controller like this:
[advancedController addObserver:(RootViewController*)self.navigationController. topViewController forKeyPath:@"dataUpdated" options:0 context:nil];
A: Your problem is the call to super. You shouldn't pass this method to super for properties that you observed yourself. You commented out the code that was there to help you with this.
A possible correct observation would be (note the context):
[advancedController addObserver:self.navigationController forKeyPath:@"dataUpdated" options:0 context:self];
And then the correct observer would be:
- (void)observeValueForKeyPath:(NSString *)keyPath ofObject:(id)object change:(NSDictionary *)change context:(void *)context
{
if (context == self) {
NSLog(@"2 Observed change for: %@",keyPath);
} else {
[super observeValueForKeyPath:keyPath ofObject:object change:change context:context];
}
}
Dave Dribin provides another approach to using context correctly, along with the backstory of why it's necessary, in Proper Key-Value Observer Usage.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599979",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: XSLT Transformation value of select - Blank output? Please advise, noob to XSLT transformation.
What am I missing from the following XSLvalue-of? I have the following XML data. Then in my transformation listed below I am referencing these elements but I get empty fields in my output. I must be using the incorrect syntax on the <xsl:value-of select="./userInfo/addressMap/entry[2]/firstName"/>
<userInfo>
<addressMap>
<entry>
<key>2</key>
<value>
<addressField1>21941 Main Drive</addressField1>
<addressField2>Apt XYZ</addressField2>
<addressType>0</addressType>
<city>Lake Forest</city>
<emailId>krystal@bogus.com</emailId>
<firstName>Krystal M</firstName>
<lastName>Obama</lastName>
<phoneNo>9495551212</phoneNo>
<state>CA</state>
<zipCode>92630</zipCode>
</value>
</entry>
</addressMap>
</userInfo>
<table border="0" width="600" cellpadding="5" cellspacing="5">
<tr bgcolor="#cccccc" style="font-size:14px; font-weight:bold;">
<td align="left">SHIPPING INFO</td>
<td align="left">BILLING INFO</td>
</tr>
<tr bgcolor="#ffffff" style="font-size:12px;">
<td align="left"><table border="0">
<tr>
<td><xsl:value-of select="./userInfo/addressMap/entry[2]/firstName"/> 
<xsl:value-of select="./userInfo/addressMap/entry[2]/lastName"/></td>
</tr>
<tr>
<td><xsl:value-of select="./userInfo/addressMap/entry[2]/addressField1"/></td>
</tr>
<xsl:choose>
<xsl:when test="./userInfo/addressMap/entry[2]/addressField2 and ./userInfo/addressMap/entry[2]/addressField2 != ''">
<tr>
<td><xsl:value-of select="./userInfo/addressMap/entry[2]/addressField2"/></td>
</tr>
</xsl:when>
<xsl:otherwise>
<tr>
<td> </td>
</tr>
</xsl:otherwise>
</xsl:choose>
<tr>
<td><xsl:value-of select="./userInfo/addressMap/entry[2]/city"/>, 
<xsl:value-of select="./userInfo/addressMap/entry[2]/state"/> 
<xsl:value-of select="./userInfo/addressMap/entry[2]/zipCode"/> USA </td>
</tr>
<tr>
<td><xsl:value-of select="./userInfo/addressMap/entry[2]/phoneNo"/></td>
</tr>
</table>
Here is my entire xml data.
<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<cart>
<basketQuantity>0</basketQuantity>
<cartTotals>
<amtDueToBePaid>35.4</amtDueToBePaid>
<discountList>Employee Discount</discountList>
<giftWrapping>0.0</giftWrapping>
<preferredMemberAmountCharged>0.0</preferredMemberAmountCharged>
<preferredMemberSavings>0.0</preferredMemberSavings>
<promoCodeSavings>0.0</promoCodeSavings>
<promoShipping>0.0</promoShipping>
<regularMerchandise>59.0</regularMerchandise>
<regularShipping>0.0</regularShipping>
<saleMerchandise>59.0</saleMerchandise>
<savings>23.6</savings>
<shippingSavings>0.0</shippingSavings>
<subTotal>35.4</subTotal>
<tax>0.0</tax>
<taxableMerchandise>35.4</taxableMerchandise>
<total>35.4</total>
</cartTotals>
<errorAndWarnings/>
<itemsList>
<discountMap>
<entry>
<key>Employee Discount</key>
<value>23.6</value>
</entry>
</discountMap>
<itemName>Rosette Smocked Top</itemName>
<productId>45711923</productId>
<promoPrice>0.0</promoPrice>
<quantity>1</quantity>
<regularPrice>59.0</regularPrice>
<returnValue>35.4</returnValue>
<salePrice>59.0</salePrice>
<savings>23.6</savings>
<taxCode>0.0</taxCode>
<unitTax>0.0</unitTax>
<upc>457119500004</upc>
<uuid>b18ffa87c0a86f6f14618000479d92c9</uuid>
</itemsList>
<orderPlaced>false</orderPlaced>
<pipelineSessionId>abcxyz</pipelineSessionId>
<shipping>
<availableShippingMap>
<entry>
<key>2</key>
<value>
<actualShippingCost>7.95</actualShippingCost>
<deliveryDays>0</deliveryDays>
<savings>0.0</savings>
<shippingDiscount>0.0</shippingDiscount>
<shippingMethodName>2nd Day</shippingMethodName>
</value>
</entry>
<entry>
<key>1</key>
<value>
<actualShippingCost>0.0</actualShippingCost>
<deliveryDays>0</deliveryDays>
<savings>0.0</savings>
<shippingDiscount>0.0</shippingDiscount>
<shippingMethodName>Standard Shipping</shippingMethodName>
</value>
</entry>
<entry>
<key>3</key>
<value>
<actualShippingCost>19.95</actualShippingCost>
<deliveryDays>0</deliveryDays>
<savings>0.0</savings>
<shippingDiscount>0.0</shippingDiscount>
<shippingMethodName>Overnight Delivery</shippingMethodName>
</value>
</entry>
</availableShippingMap>
<savings>0.0</savings>
<selectedShippingMethodId>1</selectedShippingMethodId>
<shippingCost>0.0</shippingCost>
<shippingPromo>0.0</shippingPromo>
</shipping>
<userInfo>
<addressMap>
<entry>
<key>2</key>
<value>
<addressField1>21941 Main Drive</addressField1>
<addressField2>Apt XYZ</addressField2>
<addressType>0</addressType>
<city>Lake Forest</city>
<emailId>krystal@bogus.com</emailId>
<firstName>Krystal M</firstName>
<lastName>Obama</lastName>
<phoneNo>9495551212</phoneNo>
<state>CA</state>
<zipCode>92630</zipCode>
</value>
</entry>
</addressMap>
</userInfo>
</cart>
A: The problem is the "entry[2]", it's not selecting the entry with key 2 as you intend it to.
Off the top of my head, that should be something like "./userInfo/addressMap/entry[string(key) = 2]/value/firstName".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599982",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: ListBox with hyperlink -> selection changed I want to do with xaml bindings such feature:
Listbox contains hyperlinks.
When hyperlink clicked - we go to another frame
But also SelectedItem must changed, and on another frame we show info about selected item.
I want it without subscribing click/selected events. Only declarative
Example of my listbox
<ListBox Grid.Row="1"
x:Name="OrderTypesListBox"
ItemsSource="{Binding OrderTypes, Mode=OneWay}"
SelectedItem="{Binding SelectedCall.OrderType, Mode=TwoWay}"
>
<ListBox.ItemTemplate>
<DataTemplate>
<StackPanel>
<TextBlock Text="{Binding Name}" />
<HyperlinkButton Style="{StaticResource LinkStyle}" NavigateUri="/WindowPage" TargetName="ContentFrame" Content="WindowPage"/>
</StackPanel>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
Now solve like that
<ListBox Grid.Row="1"
x:Name="OrderTypesListBox"
ItemsSource="{Binding OrderTypes, Mode=OneWay}"
SelectedItem="{Binding SelectedCall.OrderType, Mode=TwoWay}"
>
<ListBox.ItemTemplate>
<DataTemplate>
<HyperlinkButton
TargetName="ContentFrame"
NavigateUri="{Binding OrderTypeNextPage}"
Content="{Binding Name}"
Click="HyperlinkButton_Click"
Tag="{Binding}"
/>
</DataTemplate>
</ListBox.ItemTemplate>
</ListBox>
private void HyperlinkButton_Click(object sender, RoutedEventArgs e)
{
OrderTypesListBox.SelectedItem = (sender as HyperlinkButton).Tag;
}
A: Don't use a HyperlinkButton. Perform the needed actions when the SelectedItem changes in your ViewModel.
Edit: If you need to respond to all click events even if the item is already selected then you can use a Behavior to do this. Just create a behavior for the TextBlock that navigates on the TextBlock click event.
Edit2: Behaviors are pretty simple to code up and easy to use (and don't break the MVVM paradigm).
public class NavigatingTextBlockBehavior : Behavior<TextBlock>
{
protected override void OnAttached()
{
AssociatedObject.MouseLeftButtonDown += new MouseButtonEventHandler(OnMouseDown);
}
private void OnMouseDown(object sender, MouseButtonEventArgs e)
{
NavigationService.Navigate(new Uri("/WindowPage"));
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599993",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: SQL Server Compact does not support calls to HasRows property if the underlying cursor is not scrollable." What does this actually mean?
I am stepping through some code and when I look at the properties of my datareader under the locals window in vs2010, the DR.HasRows shows an error:
HasRows '(DR).HasRows' threw an exception of type 'System.InvalidOperationException' bool {System.InvalidOperationException}
base {"SQL Server Compact does not support calls to HasRows property if the underlying cursor is not scrollable."} System.SystemException {System.InvalidOperationException}
WHat is a cursor and how do I make it scrollable? :)
A: I got this error before and this is the solution:
bool hasRow = DR.Read();
if(hasRow)
{
//TODO
}
A: A better solution would be to force the result set into being scrollable. Do it this way:
SqlCeDataReader dr = command.ExecuteResultSet(ResultSetOptions.Scrollable);
Read about what types of cursors there are here
A: Just use a DR.read() in a while loop. If your query is set properly, you know it will only run once, but if you want to control it even further, simply use break after reading youd data:
while (DRder.Read())
{
//get your date from the reader.
//optional break, though it will do two things,
//1. ensure one record is returned
//2. Eliminate the need for the while loop to check again.
break;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7599994",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: String formatting with CSS I have a string with multiple lines as below separated by multiple spaces (or sometimes with single space):
"word1 word2 word3 word4
word5 word same6 word7 word8"
In my Javascript I am able to split using \n, but when I display the same in a CSS div, it ends up in a weird format:
"word1 word2 word3 word4 word5 word same6 word7 word8".
My CSS:
.block{
color: #000;
border: 1px solid #fff300;
padding:8px;
margin:4px;
width:80%;
display: block;
}
How can I format the string with CSS? The spacing is not uniform and there's no guarantee on the spacing between words (and a word can also have a single space).
A: in HTML white space is condensed unless the white-space style has been set to a different value.
You might want to add:
white-space: pre;
-or-
white-space: pre-wrap;
-or-
white-space: nowrap;
to get it formatted correctly.
A: Use white-space: pre. That should do the trick.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: is there a way to preload code in php in the Apache parent? I want to run some code in Apache at initialization before PHP requests are handled in the Apache child processes. This would have to happen in the Apache parent. It would setup some new global variables.
When the child runs, there would be these new variables there ready and waiting.
APC (and the like) are not an option since this code is kind of expensive to run.
I'm trying to avoid writing a PHP module.
A: Personally, I place php_value auto_prepend_file config.inc.php in .htaccess (or in httpd.conf) to get config.inc.php to run before any PHP scripts are executed to set up my global vars.
Note that this is run on every request, though, so if it's a large setup script, it will be expensive.
Also, this will not work if PHP is installed as CGI, in which case you'll need to set the auto_prepend_file setting in php.ini.
A: The best way to go would be as told by daiscog to use auto-prepend. If you need to set it within apache for some reason, you could pass them using environment variables:
Set them with apache as you like, https://httpd.apache.org/docs/2.2/env.html, and access them in PHP using $_ENV - while this wont obviously not work for "complex" php variables like arrays, you could use it to pass strings from apache to php.
A: Apache itself can not execute pre-loaded PHP code and set variables per parent. It's a compiled application and it only executes PHP code via the server api, it does not share much with PHP memory wise. That are basically two worlds.
However what works is a webserver that is build in PHP. Such a webserver can hold variables between HTTP requests. Infact all global variables. So your code must be compatbile with that pattern and cleanly shutdown the part that should get unloaded (the code will never get unloaded, only the global variables that get unset).
Such a webserver is appserver-in-php.
However I do not exactly understand how/why/for-what you want to prevent writing a PHP module (and which kind? compiled? In userspace?).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600015",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do I set the local port of a WCF simplex channel? I'd like to connect to a server through a certain local port (presumably, 80). Is this possible in a simplex scenario?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600017",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: WP7 Isolated Storage Text Document Read Line Is there a way using Isolated storage ie a Text document, to grab the text on a certain line.
I would like to save variables to a text document on my settings page of my app. Then go back to the main page and read the variable saved on line 3. I already know how to save them. just not read certain lines.
Also is the text document created by my app going to still be there if i close and reopen the app?
A: Try this
using( TextReader reader = new StreamReader(
new IsolatedStorageFileStream( "myFile.txt", System.IO.FileMode.Open,
IsolatedStorageFile.GetUserStoreForApplication() ) ) {
string line = reader.ReadLine(); // first line, discard
line = reader.ReadLine(); // second line, discard
line = reader.ReadLine(); // third line, read the variable value
}
However, you might be better off using the IsolatedStorageSettings class to store settings (the link contains example usage). Another option is to put all your settings into a serializable class and use an XmlSerializer to save / read the settings. Both these approaches would not require parsing the file manually.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600020",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to generate Serial numbers +Add 1 in select statement I know we can generate row_number in select statement. But row_number starts from 1, I need to generate from 2 and onwards.
example
party_code
----------
R06048
R06600
R06791
(3 row(s) affected)
I want it like
party_code serial number
---------- -------------
R06048 2
R06600 3
R06791 4
Current I am using below select statement for generate regular row number.
SELECT party_code, ROW_NUMBER() OVER (ORDER BY party_code) AS [serial number]
FROM myTable
ORDER BY party_code
How can modify above select statement and start from 2?
A: I don't know much about SQL Server but either one of these will work:
SELECT party_code, 1 + ROW_NUMBER() OVER (ORDER BY party_code) AS [serial number]
FROM myTable
ORDER BY party_code
OR
SELECT party_code, serial_numer + 1 AS [serial number] FROM
(SELECT party_code, ROW_NUMBER() OVER (ORDER BY party_code) AS [serial number]
FROM myTable)
ORDER BY party_code
A: SELECT party_code, 1 + ROW_NUMBER() OVER (ORDER BY party_code) AS [serial number]
FROM myTable
ORDER BY party_code
to add: ROW_NUMBER() has an unusual syntax, and can be confusing with the various OVER and PARTITION BY clauses, but when all is said and done it is still just a function with a numeric return value, and that return value can be manipulated in the same way as any other number.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600022",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: How to interact with web application from android application? I have a Java based web application which is developed using JSP/Servlets running on Tomcat server. This application is developed for customer support. A customer can directly login to the application with his credentials and raise any complaints reg. a specific product. He can also view all the complaints he has raised and their status. Also he can add comments to the complaints and also close them when he desires to.
Now I would like to develop an Android app where a customer can login with his credentials and do same operations as he used to do in the above said web application.
I have basic knowledge on Android and good amount of knowledge in Java. Can someone help me with some guidelines or sample source code to develop such kind of application. In particular after authenticating a customer with his credentials from an Android activity by sending HTTP request to the web application, how do we keep track of the session for that customer in order to display him the complaints raised by him or allowing him to add comments to his complaints in next activities (screens). To put it simple how to maintain sessions?
Thanks,
A: You question is pretty specific to your application. How you maintain a session with the server is pretty much up to you, but you can think of it as implementing the relationship between a web browser and a web server.
After your user logs in, the client should receive some kind of token from the server (similar to a cookie). All subsequent requests will pass along that token to authorize the user, so you'll have to persist it on the device. Your server will have a mapping of tokens to users.
I would recommend looking into OAUTH2 and maybe taking a look at some well used APIs like Twitter and Foursquare for some ideas about best practices.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600027",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Maven : error in opening zip file when running maven [ERROR] error: error reading C:\Users\suresh\.m2\repository\org\jdom\jdom\1.1\jdom-1.1.jar; error in opening zip file
[ERROR] error: error reading C:\Users\suresh\.m2\repository\javax\servlet\servlet-api\2.5\servlet-api-2.5.jar; error in opening zip file
[ERROR] error: error reading C:\Users\suresh\.m2\repository\org\apache\cxf\cxf-rt-bindings-http\2.2.1\cxf-rt-bindings-http-2.2.1.jar; error in opening zip file
[ERROR] error: error reading C:\Users\suresh\.m2\repository\org\codehaus\jra\jra\1.0-alpha-4\jra-1.0-alpha-4.jar; error in opening zip file
[ERROR] error: error reading C:\Users\suresh\.m2\repository\org\apache\cxf\cxf-api\2.2.1\cxf-api-2.2.1.jar; error in opening zip file
[ERROR] error: error reading C:\Users\suresh\.m2\repository\org\apache\cxf\cxf-common-utilities\2.2.1\cxf-common-utilities-2.2.1.jar; error in opening zip file
[INFO] 44 errors
How to resolve this error while running mvn clean install?
And I see that, starting from servlet-api, no packages are being created inside the local repository on my disk.
A: Probably, contents of the JAR files in your local .m2 repository are HTML saying "301 Moved Permanently". It seems that mvn does not handle "301 Moved Permanently" properly as expected. In such a case, download the JAR files manually from somewhere (the central repository, for example) and put them into your .m2 repository.
See also:
asm-3.1.jar; error in opening zip file
http://darutk-oboegaki.blogspot.jp/2012/07/asm-31jar-error-in-opening-zip-file.html
A: *
*go to the .m2/repository and delete the conflicting files
*mvn -U clean install
A: This error sometimes occurs. The files becomes corrupt.
A quick solution thats works for me, is:
*
*Go to your local repository (in general /.m2/) in your case I see that is C:\Users\suresh.m2)
*Search for the packages that makes conflicts (in general go to repository/org) and delete it
*Try again to install it
With that you force to get the actual files
good luck with that!
A: This error can occur when your connection gets interrupted during your dependencies are being downloaded.
Delete the relevant repository folder and run following command again to download a fresh copy of corrupted file.
mvn clean install
A: I just have this error. You can delete the files and run the compiling command again:
$ sudo rm /Users/Chaklader/.m2/repository/org/apache/poi/poi/3.17/poi-3.17.jar
$ sudo rm /Users/Chaklader/.m2/repository/com/fasterxml/jackson/core/jackson-databind/2.7.5/jackson-databind-2.7.5.jar
$ sudo rm /Users/Chaklader/.m2/repository/com/fasterxml/jackson/core/jackson-core/2.7.5/jackson-core-2.7.5.jar
Now, run the command for the clean compile:
$ mvn -U clean compile
A: I had a similar problem as well. The fix was a mix of both. I had a problem with asm-3.1 (as mentioned in the blog post linked by Takahiko. That jar was corrupt. I needed to manually get the jar from the maven central repository. Removing it and retrying just got the corrupt jar again. It then still failed on the asm-parent, which was a POM file containing the HTML with a 301. Again, it required manually getting the file myself. You may want to check what settings XML to see if you're set to a different repository, such as a local nexus server.
When the proper way to get the new one fails, manually grab it yourself.
A: Try to remove your repository in /.m2/repository/ and then do a mvn clean install to download the files again.
A: *
*I deleted the jar downloaded by maven
*manually download the jar from google
*place the jar in the local repo in place of deleted jar.
This resolved my problem.
Hope it helps
A: I had the same problem but previous solutions not work for me. The only solution works for me is the following URL.
https://enlightensoft.wordpress.com/2013/01/15/maven-error-reading-error-in-opening-zip-file/
[EDIT]
Here I explain more about it
Suppose you got an error like below
[ERROR] error: error reading C:\Users\user\.m2\repository\org\jdom\jdom\1.1\jdom-1.1.jar; error in opening zip file
Then you have to follow these steps.
*
*First, delete the existing jar C:\Users\user\.m2\repository\org\jdom\jdom\1.1\jdom-1.1.jar
*Then you have to manually download relevant jar from Maven central repository. You can download from this link here
*After that, you have to copy that downloaded jar into the previous directory.C:\Users\user\.m2\repository\org\jdom\jdom\1.1\
Then you can build your project using mvn clean install
hope this will help somebody.
A: I also encountered the same problem, my problem has been resolved.
The solution is:
According to error information being given, to find the corresponding jar in maven repository and deleted.
Then executed mvn install command after deleting.
A: Accidently I found a simple workaroud to this issue. Running Maven with -X option forces it to try other servers to download source code. Instead of trash HTML inside some jar files there is correct content.
mvn clean install -X > d:\log.txt
And in the log file you find messages like these:
Downloading: https://repository.apache.org/content/groups/public/org/apache/axis2/mex/1.6.1-wso2v2/mex-1.6.1-wso2v2-impl.jar
[DEBUG] Writing resolution tracking file D:\wso2_local_repository\org\apache\axis2\mex\1.6.1-wso2v2\mex-1.6.1-wso2v2-impl.jar.lastUpdated
Downloading: http://maven.wso2.org/nexus/content/groups/wso2-public/org/apache/axis2/mex/1.6.1-wso2v2/mex-1.6.1-wso2v2-impl.jar
You see, Maven switched repository.apache.org to maven.wso2.org when it encountered a download problem. So the following error is now gone:
[ERROR] error: error reading D:\wso2_local_repository\org\apache\axis2\mex\1.6.1-wso2v2\mex-1.6.1-wso2v2-impl.jar; error in opening zip file
A: This issue is a pain in my a$$, I have this issue in my Mac,
if I run
mvn clean install | grep "error reading"
[ERROR] error reading /Users/ducnguyen/.m2/repository/org/apache/velocity/velocity/1.7/velocity-1.7.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/commons-net/commons-net/3.3/commons-net-3.3.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/org/apache/commons/commons-lang3/3.0/commons-lang3-3.0.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/org/bouncycastle/bcprov-jdk15on/1.54/bcprov-jdk15on-1.54.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/javax/mail/mail/1.4/mail-1.4.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/org/apache/pdfbox/pdfbox/2.0.0/pdfbox-2.0.0.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/com/itextpdf/itextpdf/5.5.10/itextpdf-5.5.10.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/org/slf4j/slf4j-api/1.7.24/slf4j-api-1.7.24.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/com/aspose/aspose-pdf/11.5.0/aspose-pdf-11.5.0.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/org/apache/velocity/velocity/1.7/velocity-1.7.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/commons-net/commons-net/3.3/commons-net-3.3.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/org/apache/commons/commons-lang3/3.0/commons-lang3-3.0.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/org/bouncycastle/bcprov-jdk15on/1.54/bcprov-jdk15on-1.54.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/javax/mail/mail/1.4/mail-1.4.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/org/apache/pdfbox/pdfbox/2.0.0/pdfbox-2.0.0.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/com/itextpdf/itextpdf/5.5.10/itextpdf-5.5.10.jar; error in opening zip file
[ERROR] error reading /Users/ducnguyen/.m2/repository/org/slf4j/slf4j-api/1.7.24/slf4j-api-1.7.24.jar; error in opening zip file
Removing all corrupted libs is the only solution
So I want to remove all of them at once.
mvn clean install | grep "error reading" | awk '{print "rm " $4 | "/bin/sh" }'
The command needs AWK to take libPath string from column $4
Then rerun
mvn clean install
A: *
*I deleted the affected jar file from Maven external libraries
*Then I performed Maven > Reload project which fixed the library by reinstalling
This worked for me without manually downloading a .jar file
A: For me I should change the .m2 repo in the settings.xml file with another one because in Mac maven can't create a folder that start with point(.)
to solve that, open your maven/version/conf/settings.xml and specify the location of your repo folder like this :
<localRepository>../repo</localRepository>
don't forget to change it also in your IDE, in eclipse go to : Windows > Preferences > Maven > User Settings > Global Settings, and navigate to your settings.xml.
clean install your project.
hope this will help you.
A: This error occurs because of some file corruption.
But we don't need to delete whole .m2 folder.
Instead find which jar files get corrupted by looking at the error message in the console. And delete only the folders which contains those jar files.
Like in the question :
*
*C:\Users\suresh\.m2\repository\org\jdom\jdom\
*C:\Users\suresh\.m2\repository\javax\servlet\servlet-api\
*C:\Users\suresh\.m2\repository\org\apache\cxf\cxf-rt-bindings-http
*C:\Users\suresh\.m2\repository\org\codehaus\jra\jra
*C:\Users\suresh\.m2\repository\org\apache\cxf\cxf-api
*C:\Users\suresh\.m2\repository\org\apache\cxf\cxf-common-utilities
Delete these folders.
Then run.
mvn clean install -U
A: Deleting the entire local m2 repo may not be advisable. As in my case I have hundreds and hundreds of jars in my local, I don't want to re-download them all just for one jar.
Most of the above answers didn't work for me, here is what I did.
STEP:1: Ensure if you are downloading from the correct Maven repo in you settings.xml. In my case it was referring to http://central.maven.org/maven2/ as https://repo1.maven.org/maven2/. So it was getting corrupted or going otherwise?
STEP:2: Delete the folder containing the artifact and other details in your local machine.This will force it download it again upon next build
STEP:3: mvn clean install :).
Hope it helps.
A: I downloaded the jar file manually and replace the one in my local directory and it worked
A: You could also check if the required certificates are installed to make sure that it allows the dependencies to be downloaded.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600028",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "91"
}
|
Q: Is it possible to have dynamic values in tiles.xml in Struts2 Is it possible to pass dynamic values in tiles.xml as we do in struts.xml in Struts2? I have used ${parameter} to get dynamic values in config file but it doesnt seem to work. Any ideas?
A: You can pass wildcards to tiles from your struts actions, I've used this to do similar things for dynamic projects where each client might have a different CSS file for instance.
In your struts action you would have a tiles result type and you can pass the value such as:
<action name="{eventURL}/update" class="org.groundworkgroup.struts.actions.admin.UpdateEventSettings">
<result name="login" type="tiles">/login.tiles</result>
<result name="input" type="tiles">/admin.${#session.bean.pageID}.${#session.bean.fileID}.tiles</result>
<result name="success" type="tiles">/admin.${#session.bean.pageID}.${#session.bean.fileID}.tiles</result>
</action>
And then in your tiles.xml you would "plug in" the wildcards:
<definition name="/admin.*.*.tiles" extends="adminLayout">
<put-attribute name="title" value="Welcome" />
<put-attribute name="jsfile" value="{1}/js/{2}.js" />
<put-attribute name="cssfile" value="{1}/css/{2}.css" />
<put-attribute name="body" value="/WEB-INF/content/sites/admin/main.jsp" />
<put-attribute name="menu" value="/WEB-INF/content/sites/admin/menu.jsp" />
</definition>
In this particular example the struts action pageID is the project directory where the files are located and in the tiles.xml it is placed as wildcard {1}. The fileID is the filename associated with this particular action or user represented in the tiles.xml by {2}. You can use this set up to pass dynamic values to your tiles in order to control for example page states or JSP's to render or like in this example, custom css and js files.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600033",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Easy clock simulation for testing a project Consider testing the project you've just implemented. If it's using the system's clock in anyway, testing it would be an issue. The first solution that comes to mind is simulation; manually manipulate system's clock to fool all the components of your software to believe the time is ticking the way you want it to. How do you implement such a solution?
My solution is:
Using a virtual environment (e.g. VMWare Player) and installing a Linux (I leave the distribution to you) and manipulating virtual system's clock to create the illusion of time passing. The only problem is, clock is ticking as your code is running. Me, myself, am looking for a solution that time will actually stop and it won't change unless I tell it to.
Constraints:
You can't confine the list of components used in project, as they might be anything. For instance I used MySQL date/time functions and I want to fool them without amending MySQL's code in anyway (it's too costy since you might end up compiling every single component of your project).
A: Write a small program that changes the system clock when you want it, and how much you want it. For example, each second, change the clock an extra 59 seconds.
The small program should
*
*Either keep track of what it did, so it can undo it
*Use the Network Time Protocol to get the clock back to its old value (reference before, remember difference, ask afterwards, apply difference).
A: Encapsulate your system calls in their own methods, and you can replace the system calls with simulation calls for testing.
Edited to show an example.
I write Java games. Here's a simple Java Font class that puts the font for the game in one place, in case I decide to change the font later.
package xxx.xxx.minesweeper.view;
import java.awt.Font;
public class MinesweeperFont {
protected static final String FONT_NAME = "Comic Sans MS";
public static Font getBoldFont(int pointSize) {
return new Font(FONT_NAME, Font.BOLD, pointSize);
}
}
Again, using Java, here's a simple method of encapsulating a System call.
public static void printConsole(String text) {
System.out.println(text);
}
Replace every instance of System.out.println in your code with printConsole, and your system call exists in only one place.
By overriding or modifying the encapsulated methods, you can test them.
A: From your additional explanation in the comments (maybe you cold add them to your question?), my thoughts are:
You may already have solved 1 & 2, but they relate to the problem, if not the question.
1) This is a web application, so you only need to concern yourself with your server's clock. Don't trust any clock that is controlled by the client.
2) You only seem to need elapsed time as opposed to absolute time. Therefore why not keep track of the time at which the server request starts and ends, then add the elapsed server time back on to the remaining 'time-bank' (or whatever the constraint is)?
3) As far as testing goes, you don't need to concern yourself with any actual 'clock' at all. As Gilbert Le Blanc suggests, write a wrapper around your system calls that you can then use to return dummy test data. So if you had a method getTime() which returned the current system time, you could wrap it in another method or overload it with a parameter that returns an arbitrary offset.
A: Another solution would be to debug and manipulate values returned by time functions to set them to anything you want
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600036",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-4"
}
|
Q: deleting delegate on dealloc without an instance variable so i start a ASIFormDataRequest on my [viewDidLoad] in a UIViewController.
ASIFormDataRequest *detailRequest = [ASIFormDataRequest requestWithURL:url];
detailRequest.delegate = self;
[detailRequest startAsynchronous];
If my UIViewController gets released before my Request finishes, my app crashes.
If i add my ASIFormDataRequest as an instance variable for example
@property(nonatomic, retain) ASIFormDataRequest *detailRequest;
and nil the delegate on dealloc
-(void)dealloc {
if(self.detailRequest != nil) { self.detailRequest.delegate = nil; }
self.detailRequest = nil;
[super dealloc];
}
the app no longer crashes.
but i don't think it's necessary to create a instance variable just for this, especially if i have multiple requests.
is there a better way to do this?
A: I usually create an array and store all active requests in the array. When the request is completed I remove the request, and when the controller calls dealloc I cancel all of the requests and nil the delegate.
A: In order to release it you must have a pointer to it so yes, use an ivar. iars are not expensive.
A: By doing self.detailRequest = [ASIFormDataRequest requestWithURL:url]; I am guessing it is creating an autorelease object whose lifespan isn't bound to your controller class. If the creation and deletion of your object is bound to your controller, it's logical to use a instance variable.
More details about autorelease
A: You could do this:
detailRequest.delegate = [self retain];
and then call
[self autorelease];
In the ASIFormDataRequest callback method. That's what I generally tend to do, anyway.
That way, the request object retains its delegate for the duration of the request.
A: As this is the Asynchronous request so if you set delegate it means as soon as response comes your delegate methods will be called. Till that time your object should be alive to handle the response. So making it retain and releasing in the dealloc is fine and before than that you have to set delegate to nil. So that if response comes after releasing the method, framework should not be misguided to search for method of dead object.
To handle multiple request the best way is to create the array and number of objects you want to use. When you are done with the objects, in dealloc method iterate through each object and set delegate nil and release the object.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600039",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to store Mobile Numbers in asp.net Membership c# and SQL I have a web application which stores customer details like username, firstname and email address ... etc...etc..
I am using Asp.Net Membership, also my web page where i will allow customers to register I'm using CreateUserWizard.
I would like to know how to save customer mobile numbers using asp.net Membership. In my sql table I have all the asp.net membership tables. However wanted to know how to customize the table to allow mobile numbers to be saved into database.
Any ideas?
I Have Custom UserProfile Class where I have setup the mobile property and other properties. How Can I save all the details into separate columns in database??
public class UserProfile : ProfileBase
{
public static UserProfile GetUserProfile(string username)
{
return Create(username) as UserProfile;
}
public static UserProfile GetUserProfile()
{
return Create(Membership.GetUser().UserName) as UserProfile;
}
[SettingsAllowAnonymous(false)]
public string MobileNumber
{
get { return base["MobileNumber"].ToString(); }
set { base["MobileNumber"] = value; }
}
//Few other properties.....
}
Here is my webconfig settings
<providers>
<add name="SqlProvider" type="System.Web.Profile.SqlProfileProvider" connectionStringName="EXAMPLE" applicationName="EXAMPLE" description="SqlProfileProvider for SampleApplication"/>
</providers>
</profile>
A: Use Profile properties. In web.config add <profile> entry.
<profile>
<properties>
<add name="MobileNumber" />
</properties>
</profile>
A: Yes, just add the Profile property mentioned above and you can access this property by
Profile.MobileNumber = "12232";// to Save the Mobile No of current logged in user
ProfileProvider will automatically saves this for you in database.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600040",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: gnuplot missing data with expression evaluation I want to use the plot command in gnuplot with expression evaluation, i.e.
plot "-" using ($1):($2) with lines
1 10
2 20
3 ?
4 40
5 50
e
But I want it to ignore the missing data "?" in such a way that it connects the line (and doesn't break it between 2 and 4).
I tried set datafile missing "?",
but in agreement with the online-help it does not connect the lines. The following would, but I cannot use expression evaluation:
plot "-" using 1:2 with lines
1 10
2 20
3 ?
4 40
5 50
e
Any ideas how to connect the lines and use expression evaluation?
A: Two column data
If you set up a data file Data.csv
1 10
2 20
3 ?
4 40
5 50
you can plot your data with connected lines using
plot '<grep -v "?" Data.csv' u ($1):($2) w lp
More than two column data
For more than two columns you can make use of awk.
With a data file Data.csv
1 10 1
2 20 2
3 ? 3
4 40 ?
5 50 5
you can run a script over the data file for each plot like so:
plot "<awk '{if($2 != \"?\") print}' Data.csv" u ($1):($2) w lp, \
"<awk '{if($3 != \"?\") print}' Data.csv" u ($1):($3) w lp
A reference on scripting in gnuplot can be found here. The awk user manual here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600048",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Why are my CSS and Javascript files not being found by my HTML file rendered in UIWebView? Here is the code that is successfully loading the HTML into UIWebView:
- (void)viewDidLoad {
[super viewDidLoad];
NSString *filePath = [[NSBundle mainBundle] pathForResource:@"Player" ofType:@"html"];
NSData *htmlData = [NSData dataWithContentsOfFile:filePath];
if (htmlData) {
NSBundle *bundle = [NSBundle mainBundle];
NSString *path = [bundle bundlePath];
NSString *fullPath = [NSBundle pathForResource:@"Player" ofType:@"html" inDirectory:path];
[webView loadRequest:[NSURLRequest requestWithURL:[NSURL fileURLWithPath:fullPath]]];
}
}
Here is the top part of Player.html, the HTML file is being loaded and shown, just with zero styling or javascript action:
<head><title>
Course: Pegasus 1 of each
</title><link href="Content/css/jqueryui.css" type="text/css" media="screen" rel="Stylesheet" /><link href="Content/css/Templates.css" type="text/css" media="screen" rel="Stylesheet" /><link href="Scripts/fancybox/jquery.fancybox-1.3.4.css" type="text/css" media="screen" rel="Stylesheet" /><link href="Content/css/Pegasus.css" type="text/css" media="screen" rel="Stylesheet" />
<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.4.4/jquery.min.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.8.12/jquery-ui.min.js" type="text/javascript"></script>
<script src="https://ajax.microsoft.com/ajax/jquery.templates/beta1/jquery.tmpl.min.js" type="text/javascript"></script>
<script src="Scripts/browser.js" type="text/javascript"></script>
<script type="text/javascript" charset="utf-8" src="Scripts/jstree/jquery.tree.js"></script>
<script src="https://ajax.googleapis.com/ajax/libs/swfobject/2.2/swfobject.js" type="text/javascript"></script>
<script type="text/javascript" src="Scripts/fancybox/jquery.mousewheel-3.0.4.pack.js"></script>
<script type="text/javascript" src="Scripts/fancybox/jquery.easing-1.3.pack.js"></script>
<script type="text/javascript" src="Scripts/fancybox/jquery.fancybox-1.3.4.pack.js"></script>
<script type="text/javascript" src="Scripts/jquery.carouFredSel-2.5.5-packed.js"></script>
<script type="text/javascript" src="Scripts/jquery.qtip-1.0.min.js"></script>
<script type="text/javascript" src="Scripts/jquery.multifilterie.js"></script>
<script type="text/javascript" src="Scripts/pegasus.js"></script>
<script type="text/javascript" src="Scripts/jwplayer/jwplayer.js"></script>
<script src="Scripts/jquery.form.js" type="text/javascript"></script>
<script src="Scripts/raphael-min.js" type="text/javascript"></script>
<script type="text/javascript" src="Scripts/pegasus.quiz.js"></script>
Here is the Group structure, notice that the paths are relative to the root location of Player.html:
But this is what I am getting:
What should I do to make it find the files?
A: The group structure you see in Xcode is not a folder structure. It's a way to organize your project workspace.
During the Copy Bundle Resources build phase, the files are copied to the root of your app bundle.
Check your resource dir in ~/Library/Apllication Support/IPhone Simulator/4.x.x/Applications/uid here/your.app. You will see that there is no Scripts folder.
Something like
<script src="./browser.js" type="text/javascript"></script>
should work.
If you really need to have a folder structure in your app bundle, select "Create Folder References for any added folders" when you add the Scripts and Content folders to your project resources.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600051",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to add the 256 value only to negative numbers?Result i get from modorg is the same as modulus //arrays modulus and modrog
byte[] modulus ={-30, 0 , 25, 70,-25,-3,-2};
byte[] modorg=new byte[7];
//the loop that counts the elements
for (int j = 0; j < modulus.length; j++)
{
if (modulus[j] < 0)
{
modorg[j] = (byte) ((int)modulus[j] + 256);
}
else
{
modorg[j]=modorg[j];
}
}
A: Adding 256 to a byte is like adding 360 to a degree :)
You will get the same value.
You probably want to add 128?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600053",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Javascript FB.init oauth parameter for October 1st switchover I am wondering if the OAuth parameter in the FB.init call in the Javascript SDK will start defaulting to true after the October 1st deadline. The current documentation wasn't clear on this point. Obviously you can opt-in now by using oauth: true, however if I don't need to make changes to a whole lot of production code then I'd like to avoid it. Currently not including the parameter means OAuth is disabled.
A: So, it's Monday and I've seen absolutely no changes over the weekend with the facebook API in regards to Oct. 1st deadline. I'm hesitant to say that facebook was just blowing smoke? By the end of today, we may yet see something: "We will post an update on the rollout plan on Monday, Oct 3rd (the changes themselves will proceed as planned)." (from here)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600055",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: C++: What are R-Value references on a technical level (ASM)?
Possible Duplicate:
What is the difference between r-value references and l-value references? (CodeGen)
I was wondering, can anyone explain what R-Value references are on a technical level? By that I mean: What happens on assembler level when R-Value references are created.
For a small test to see what happens inside I wrote the following code:
char c = 255;
char &c2 = c;
char &c3 = std::move(c);
I know it makes no sense to create a R-Value reference to 'c', but just for the sake of testing I did it anyway, to see what it does. And here's the result:
unsigned char c = 255;
mov byte ptr [c],0FFh
unsigned char &c2 = c;
lea eax,[c]
mov dword ptr [c2],eax
unsigned char &&c3 = std::move(c);
lea eax,[c]
push eax
call std::move<unsigned char &> (0ED1235h)
add esp,4
mov dword ptr [c3],eax
I am by far no asm expert but it looks to me that, in this case, 'c3' is a regular reference to 'c' in the end.
If I bind the R-Value reference directly to a temporary (char &&c3 = 255), the last bit of assembler changes as such:
unsigned char &&c3 = 255;
mov byte ptr [ebp-29h],0FFh
lea eax,[ebp-29h]
mov dword ptr [c3],eax
From the looks of this change, I assume that c3 still actually is a reference to some memory location which holds the value 255. So it's a regular reference - the value is not copied/assigned to c3. Is this true?
Can anyone say if my assumptions are correct or if I am totally off the track? Until now I always thought of R-Value references to match a functions/methods signature (possibly a move-ctor) when it comes to calling resolution, so that the coder knows how to treat the data that is provided (for a move-ctor that would be moving the data instead of copying it).
To defend this rather stupid attempt I just presented: I don't intend to screw around with my code on asm level, I just want to unterstand what technical differences R-Value references introduced compared to the rest that has been around all these years.
Any insights and explanations are more than welcome!
Thanks!
A:
What happens on assembler level when R-Value references are created.
Whatever is needed to preserve high-level semantics. What compiler does exactly depends on what compiler vendor thought would be a good idea. Assembly has no concept of lvalues, rvalues, or references, so stop looking for them. Turn on the optimisations, and the code you're looking at will probably change (or might stop existing at all, if the variables are not used).
I just want to unterstand what technical differences R-Value references introduced compared to the rest that has been around all these years.
Rvalue references enable move semantics, and those in turn enables important optimisation opportunities. The standard doesn't say "oh, these are rvalue refs, and that's how you should implement them in assembly". Implementation might not even produce assembly, at all.
A: Rvalue reference is not different on asm level - it could be exactly the same as regular refernces (depends on how compiler sees it though). The difference exists only on C++ langiage level.
Information r-value reference is carrying is that referenced object is temporary, and anyone recieving it is free to modify it. Information about object location might be transfered exactly the same as with regular references (compiler might try to optimize it differently, but that's compiler's internal matter).
The difference between r-value refernce and non-const l-value reference is that every l-value will be automatically casted only to l-value reference (thus preventing accidental modifications), while r-value'd expressions will convert to both (with r-value ref. preffered), allowing move semantics and regular calls if move semantics is unsupported. std::move is doing nothing else than allowing non-automatic casting of l-values into r-values references.
A: Before optimization, a reference exists as a pointer containing the address of the bound object.
But the compiler tries very hard to optimize it away. Inlining especially may cause all use of a reference parameter inside a small function to be replaced by direct use of a register which contains the value of the bound object.
A: rvalue reference concept can be completely described on C++ level, there is no need to read Assembly code for this. You just need to get some minimal C++ class which allocates internal resources, and "stealing" rvalue reference resources by another object is obvious. Like in remote_integer class from this classic article: http://blogs.msdn.com/b/vcblog/archive/2009/02/03/rvalue-references-c-0x-features-in-vc10-part-2.aspx
Assembly translation for this code is pretty straightforward, but the difference is seen in C++ code. Regarding simple types like char - they can be used to demostrate some rvalue reference syntax features, but there is no sence to use rvalue references on such type - both on C++ and Assembly level. So, if you don't see any advantage in using char &&c in C++, there is nothing interesting also in Assembly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600057",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "9"
}
|
Q: jQuery .offset(position) not working properly Ok, continuing my adventure with this page. Now I have this in my page (some of the things are placeholders for now):
$(document).ready(function() {
$(":input")
.focus(function() {
var localOffset = 20;
var hint = $(this).attr("name"); // this is the placeholder part
if(hint !== undefined)
{
$('#form_entry_hint').html(hint);
var pos = $(this).offset();
// I added rounding because it didn't work - but still not working
pos.left = Math.round(pos.left + $(this).width() + localOffset);
pos.top = Math.round(pos.top - 3);
// the following alert is for debugging - it shows the correct values
alert("top: " + pos.top + "; left: " + pos.left);
$('#form_entry_hint').offset(pos); // this is the line that doesn't always work
$('#form_entry_hint').show();
}
})
.blur(function() {
$('#form_entry_hint').hide();
});
});
This works perfectly fine on the first focus. However on subsequent execution, the #form_entry_hint is being placed waaay down and to the right. Although the debugging shows the correct values (286, 418), when it's placed with .offset(pos), it ends up at (1199, 1692) - or somewhere near there with these numbers being different every time - but always way out of place.
What am I missing this time? :)
A: I get more consistent results by replacing $('#form_entry_hint').offset(pos);
With :
$('#form_entry_hint').css({ top: pos.top+'px', left: pos.left+'px' });
You'll need to set #form_entry_hint to position:absolute (or relative) if you haven't already.
EDIT: Thanks Kato for the simplification.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600058",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: When selecting all rows from android sqlite database for an application, it is returning the last entry for all the entries I am currently working on an android application. I have a sqlite database that stores text (that I just use as strings in my application) in four columns. I am trying to return all of the rows and columns from the table. I have created and inserted data into the table and verified it is there using sqlite3 from the adb shell. I use the same statement as I use in my program and it returns all the rows with all of the correct data. In my program I store all of the data in an ArrayList<ArrayList<String>> format by iterating through the cursor. It returns the correct number of ArrayList<String> that corresponds to the rows, but they all have the information from only the last row. Here is my code:
private static final String SELECT = "SELECT * FROM " + TABLE_NAME;
public ArrayList<ArrayList<String>> allRecipes()
{
ArrayList<ArrayList<String>> results = new ArrayList<ArrayList<String>>();
ArrayList<String> recipe = new ArrayList<String>();
Cursor cursor = db.rawQuery(SELECT, null);
if(cursor.moveToFirst())
{
do
{
recipe.clear();
recipe.add(cursor.getString(1));
recipe.add(cursor.getString(2));
recipe.add(cursor.getString(3));
recipe.add(cursor.getString(4));
results.add(recipe);
}while(cursor.moveToNext());
if(cursor != null && !cursor.isClosed())
cursor.close();
}
return results;
}
I then iterate through the ArrayLists in another part of my program and all of the information contained is just duplicates of the last row entered into the table. I have checked the ArrayLists in my other method as soon as it receives it, and they are all the same, so I am assuming it must be an issue in this code segment somehow. I have also tried the select statement with group by and order by clauses and it still does not work. Using the db.query() with correct parameters causes the same issues as well.
A: It happens because you add link to recipe in your array list, and change values of recipe on every iteration in cycle.
You should change code to this one
public ArrayList<ArrayList<String>> allRecipes()
{
ArrayList<ArrayList<String>> results = new ArrayList<ArrayList<String>>();
Cursor cursor = db.rawQuery(SELECT, null);
if(cursor.moveToFirst())
{
do
{
ArrayList<String> recipe = new ArrayList<String>();
recipe.add(cursor.getString(1));
recipe.add(cursor.getString(2));
recipe.add(cursor.getString(3));
recipe.add(cursor.getString(4));
results.add(recipe);
}while(cursor.moveToNext());
if(cursor != null && !cursor.isClosed())
cursor.close();
}
return results;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600060",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: i got an error 'System.Collections.Generic.IEnumerable' does not contain a definition how can i Pass multiple model to controller and bind the data to viewpage
i have list page in that page contains two tabs, one for active list and another one In active list.
how can i create a model and bind the data to viewpage.
how can i bind the data to view page, i used strong typed model
public class EventInfo
{
public string SUBSITE { get; set; }
public string TITLE { get; set; }
------
}
public class MyViewModel
{
public IEnumerable<SomeViewModel> Active { get; set; }
public IEnumerable<SomeViewModel> InActive { get; set; }
}
var model = new MyViewModel
{
Active = EventModel.EventList(ids, "", "", "", "", "", "", "", "1", "").ToList(),
InActive = EventModel.EventList(ids, "", "", "", "", "", "", "", "1", "1").ToList()
};
this is my view page code
<% foreach (var model in Model)
{ %>
<tr>
<td>
<%= Html.ActionLink(model.TITLE, "Detail", new { id = model.EVENT_ID })%>
</td>
I got an error
Description: An error occurred during the compilation of a resource required to service this request. Please review the following specific error details and modify your source code appropriately.
Compiler Error Message: CS1061: 'System.Collections.Generic.IEnumerable<EventListing.Models.MyViewModel>' does not contain a definition for 'Active' and no extension method 'Active' accepting a first argument of type 'System.Collections.Generic.IEnumerable<EventListing.Models.MyViewModel>' could be found (are you missing a using directive or an assembly reference?)
Source Error:
Line 221: </thead>
Line 222: <tbody>
Line 223: <% foreach (var model in Model.Active)
Line 224: { %>
Line 225: <tr>
A: Your ViewPage code does not match up with the error message you posted.
The ViewPage code shows that the Model you're passing is a collection of MyViewModel that you're looping through to display links.
The error message says that you're only passing a single MyViewModel and you want to loop through the Active collection.
Change your ViewPage so you're using
@model MyViewModel
instead of
@model IEnumerable<MyVieWModel>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600061",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Surface View Appears Black while the associated audio is playing in the background(android) I am basically running a set of video tracks using a custom media player. Every thing works fine until I press home button or go to any other screen, then on after returning to the video play screen I can only hear the audio track as the videos play and screen appears black.
I would also like to highlight another issue for which i have got a stop gap arrangement, which is when i switch videos in the playlist, the surface view retains the last frame or image of the video that was previously played. I have tried to invalidate(), force the layout and all possible ways to refresh screen that i could think of, yet I couldn't find an appropriate solution for both of the issues mentioned.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600062",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Calling a dialog in Dynamics 2011 and passing multiple recordIDs to it I want to allow the user to select one or many contacts from the contact entity, and then launch a dialog that accepts the record IDs. The idea is to add some custom configuration to the contacts.
I've currently got a custom action on a ribbon button that launches a dialog, but it only accepts one record Id. I can get access to the list of selected record Ids, thatisn't the problem, it is passing a list to the dialog using JavaScript.
I can't seem to find anything in the SDK or code snippets.
The nearest thing I found was this:
http://crmmongrel.blogspot.com/2011/06/launch-dialog-from-ribbon-button-in-crm.html
Anyone know if this is possible? I know the out of the box Send Direct E-Mail allows an email to be sent to the selected items, so I need something similar.
Should I be using dialogs or something else?
Here is a code snippet of the javascript that is called on the click of the ribbon button:
function LaunchModalDialog(SelectedControlSelectedItemReferences,dialogID, typeName)
{
// Get selected objects
var allItems = new Array
var allItems = SelectedControlSelectedItemReferences
// Just get first item for now as dialog only seems to accept one ID
var personId = allItems[0].Id;
personId = personId.replace(/\{/g, "");
personId = personId.replace(/\}/g, "");
// Load modal
var serverUri = Mscrm.CrmUri.create('/cs/dialog/rundialog.aspx');
var mypath = serverUri + '?DialogID={' + dialogID + '}&EntityName=' + typeName + '&ObjectId={' +personId + '}';
mypath = encodeURI(mypath);
// First item from selected contacts only
window.showModalDialog(mypath);
// Reload form.
window.location.reload(true);
}
A: You'll need to specify the SelectedControlAllItemIds parameter in your Ribbon for that button. Here is a link that describes it:
http://social.microsoft.com/Forums/en/crm/thread/79f959ac-0846-472f-bff1-4f5afe692a56
--Edit--
I'm sorry, I misunderstood - you meant launch an actual CRM Dialog, not just a normal HTML pop-up dialog window.
CRM Dialogs can't be used on multiple records by design, so you aren't going to be able to use them for this.
However, you should be able to create an HTML web resource file that you can launch from the Ribbon, passing in the SelectedControlAllItemIds parameter. That HTML web resource would then have some javascript that would update the selected contacts using the REST endpoints (see the SDK for more information).
Hope that helps!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600066",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: how to draw an interaction diagram I have 10 classes. I want to diagram out how they interact for my fellow developers. What diagram type is the best for this?
IE class 1 requests data object a from class 2 etc
A: A final answer does not seem to be possible. I recommend to create one (or more) sequence diagram(s) depending on the complexity of your use cases. A nice tutorial is available here (just googled for 'uml sequence diagram').
Edit: Just a reminder. UML can become very complex, so you may not want to document all interactions in detail. Describe the high-level concepts and keep THIS in mind.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600070",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: In JQGrid, Is it possible to use different formatter on grouping summary cell other than column formatter? is it possible to use different formatter for the data rows and the summary row? forexample, I want to add a summary info (summaryType= count) to a checkbox formatted column, summary value is shown as a checked checkbox. any ideas?
kinds, Alper
you can see screenshot from here:
A: I found your question very interesting, because I didn't known the answer immediately. Now I found time to reread the source code of the grouping module of jqGrid and create an example which you need.
First of all I prepared the demo which display the following results:
How you can see the summary row has many elements which are formatted in the different way:
To have summary line at the end of every grouping block we need to define groupSummary: [true] property in the groupingView parameter of jqGrid. Then we need to define summaryType property for all columns in the colModel where the summary row have not empty cell.
For example, in the simplest case I defined for the column 'amount' the property summaryType: 'sum'.
For the column 'tax' I defined summaryTpl additionally:
summaryTpl: '<i>{0}</i>', summaryType: 'sum'
As the result the summary for the 'tax' column contains italic text.
For the 'total' column I used different colors depend on the displayed value. The results having the value grater as 1000 are displayed in green. Other values are displayed in red color. The implementation is real custom formatter for the summary row:
//formatter: 'number',
formatter: function (cellval, opts, rwdat, act) {
if (opts.rowId === "") {
if (cellval > 1000) {
return '<span style="color:green">' +
$.fn.fmatter('number', cellval, opts, rwdat, act) +
'</span>';
} else {
return '<span style="color:red">' +
$.fn.fmatter('number', cellval, opts, rwdat, act) +
'</span>';
}
} else {
return $.fn.fmatter('number', cellval, opts, rwdat, act);
}
},
summaryType: 'sum'
Instead of formatter: 'number' I used custom formatter. I didn't want to implement the formatter: 'number' one more time, so I called the predefined 'number' formatter with respect of $.fn.fmatter('number', cellval, opts, rwdat, act).
The most important part of the above code is the line
if (opts.rowId === "") {
During formatting the grid cells the custom formatter will be called with the opts.rowId initialized as the row id. Only in case of formatting the summary row the opts.rowId will be the empty string (""). I use the fact to implement custom formatting.
In the column 'closed' I show one more trick. I use the summaryType defined as a function. One can use this to make some custom summary calculation another as the standard types: "sum", "min", "max", "count" and "avg". In the demo I display "count" of all and "count" of selected checkboxes and display the results in the summary. Moreover the summary cell has additionally checkbox which is checked if at least one checkbox in the group is checked. The corresponding code inclusive the custom formatter is the following:
formatter: function (cellval, opts, rwdat, act) {
if (opts.rowId === "") {
return '<span style="display:inline-block;top:-2px;position:relative;">' +
cellval.checkedCount + ' of ' + cellval.totalCount + '</span> ' +
$.fn.fmatter('checkbox', cellval.max, opts, rwdat, act);
} else {
return $.fn.fmatter('checkbox', cellval, opts, rwdat, act);
}
},
summaryType: function (val, name, record) {
if (typeof (val) === "string") {
val = {max: false, totalCount: 0, checkedCount: 0};
}
val.totalCount += 1;
if (record[name]) {
val.checkedCount += 1;
val.max = true;
}
return val;
}
We needs to hold tree different values which we calculate: totalCount, checkedCount and max. The code above shows that one can change the initial string val parameter to the object which hold all information which we need. During formatting the summary row the custom formatter will be called with the cellval initialized to the val object which we created before. In the way we can save any custom information and then display it.
I hope with respect of the demo you will be able create any summary grouping row which you need.
A: are you using a custom formatter? what you can do is make a custom formatter to display different things based on the input. I'm not sure if you are returning true or false as your input but something liek this should work:
function checkboxFormatter(cellvalue,options,rowObject){
if(typeof cellvalue == "number"){
return cellvalue;
}
else if(cellvalue == "true"){
return '<input type="checkbox" checked="checked" />';
}
else{
return '<input type="checkbox" />';
}
}
let me know if you have questions or if this is different then what you are thinking
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600071",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Updating number of columns in TableModel i use a DataModel which extends an AbstractTableModel for my Jtable.
When i use the constructor JTable main = new JTable(model);
everything works fine but when i add columns to my DataModel and call this.fireTableStructureChanged() the number of columns does not update as can be seen in the following example.
It shows a JTable initialised with my DataModel, which contained 3 rows and 3 columns. The DataModel has been updated to 4 rows and 4 columns but does only show 3 columns.
My Changeevent seems to be wrong because:
JTable.getColumnCount() shows 3
but DataModel.getColumnCount() shows 4
How can i tell the Table that the number of columns has changed and it should repaint them?
A: The JTable also has a TableColumnModel which holds all the columns to show. When you add another column to your model, the column model still has the old number of columns unless the table's autoCreateColumnsFromModel property is set to true (table.setAutoCreateColumnsFromModel(true)).
The other way would be to manually add another column to the column model.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600072",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Unrecognized selector sent? I've been mucking around with MonoTouch and the Xcode interface builder from some sample code which had an interface defined already.
After adding a button and giving it a click callback I found one of the buttons was no longer responding to clicks and instead crashing out:
2011-09-30 01:51:35.361 RedLaserSample[19437:707]
-[RLSampleViewController scanPressed]: unrecognized selector sent to
instance 0x17e1260 MonoTouch.Foundation.MonoTouchException:
Objective-C exception thrown. Name: NSInvalidArgumentException
Reason: -[RLSampleViewController scanPressed]: unrecognized selector
sent to instance 0x17e1260 at MonoTouch.UIKit.UIApplication.Main
(System.String[] args, System.String principalClassName, System.String
delegateClassName) [0x00000] in :0 at
RedLaserSample.Application.Main (System.String[] args) [0x00000] in
/Users/dev/Desktop/chrisbranson-RedLaserSample-0311fa6/RedLaserSample/Main.cs:28
Any ideas what could be causing this and how I could fix it?
A: Solved it, for some reason I had to re-add the click event in the Xcode builder.. perhaps the project being built with an older version of mono broke itself when a newer way of adding button callbacks was added in?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600075",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Is there a hot key available or configurable in Xcode for the "back button"? The backbutton in Xcode is super useful for me, especially when I CMD+CLICK to see a declaration, but I always have to use the mouse to click the arrow back button. Is this configurable to hot key?
Thanks!!!
A: ^⌘← unless I redefined that :P
Press "⌘," and go to Key Bindings to see the whole list. You can type "back" in the search box.
A: I have a Logitech mouse with physical back/forward buttons. By default these buttons map to ⌘[ and ⌘]. Unfortunately these keystrokes default in Xcode to Shift Left (outdent) and Shift Right (indent), which are not what I expect when using my mouse.
So I just remapped ⌘[ to Go Back and ⌘] to Go Forward, though I also had to remove a few conflicting key bindings in order to do it.
Works great now, and I don't have to install any horrible Logitech software (stick to hardware, Logitech!). ;)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600076",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Can I pass more than 2 parameters or an array with onCommand event in asp.net? the question is above and it is short. I am trying to pass more parameters through a button in a repeater itemtemplate
A: The CommandArgument property takes a string. So you could put several values into that property in a comma separated format, e.g:
button.CommandArgument = "param1,param2,param3";
Then in the OnClick event handler, simply split the CommandArgument property:
var parameters = e.CommandArgument.Split(',');
A: I would append the values to a string with a delimeter, like this:
CommandArgument='<%# String.Format("{0}|{1}|{2}", Eval("Column1"), Eval("Column2"), Eval("Column3"))'%>
When you get into the event handler, just split the string at the delimeter, like this:
var columnList = e.CommandArgument.Split('|');
A: I used a dumb way to walk around this problem.
pass all the stuff into CommandArgument and use string.split to get the parameter array.
CommandArgument='<%# Eval("PersonId") + ";" + Eval("PersonName") %>'
string[] paras = argu.Split(';');
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: System.InvalidOperationException: The type Database cannot be constructed I have been looking into refactoring some old code into a new WCF service, based on net 4.0 and have into a little difficulty with what should be a simple exercise!
The scenario;
WCF Service hosted over HTTP, implementing our ServiceContract, which connects to a local Sql Server.
When attempting to run a simple NUnit test against the Service Call, I get the following error;
* HelpManager.Tests.GetPage.GetPageById Fault
Exception:
System.ServiceModel.FaultException`1[System.ServiceModel.ExceptionDetail]:
Activation error occured while trying to get instance of type
Database, key "HelpManagement" (Fault Detail is equal to An
ExceptionDetail, likely created by
IncludeExceptionDetailInFaults=true, whose value is:
Microsoft.Practices.ServiceLocation.ActivationException: Activation
error occured while trying to get instance of type Database, key
"HelpManagement" ---->
Microsoft.Practices.Unity.ResolutionFailedException: Resolution of the
dependency failed, type =
"Microsoft.Practices.EnterpriseLibrary.Data.Database", name =
"HelpManagement". Exception occurred while: while resolving. Exception
is: InvalidOperationException - The type Database cannot be
constructed. You must configure the container to supply this value.
----------------------------------------------- At the time of the
exception, the container was:
Resolving
Microsoft.Practices.EnterpriseLibrary.Data.Database,HelpManagement
----> System.InvalidOperationException: The type Database cannot be
constructed. You must configure the container to supply this value.
at
Microsoft.Practices.ObjectBuilder2.DynamicMethodConstructorStrategy.GuardTypeIsNonPrimiti...).
Our (pretty standard) WCF web.config for this, looks like;
<configSections>
<section name="dataConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Data.Configuration.DatabaseSettings, Microsoft.Practices.EnterpriseLibrary.Data, Version=5.0.414.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" requirePermission="true"/>
</configSections>
<dataConfiguration defaultDatabase="HelpManagement"/>
<connectionStrings>
<add name="HelpManagement" connectionString="server=(local);database=ieq;uid=;pwd=" providerName="System.Data.SqlClient"/>
</connectionStrings>
and an example of the code used to call it;
private const string DB_HelpManagement = "HelpManagement";
var db = DatabaseFactory.CreateDatabase(DB_HelpManagement);
Google et al have been no fun. I have checked versions etc and they all appear to be referencing the same 5.0.14 from GAC, so unsure as to what the problem is.
Thanks in advance
A: I wonder about Microsoft.Practices.ObjectBuilder.dll and Microsoft.Practices.EnterpriseLibrary.Common -- are they referenced in the WCF project?
A: It sounds like it might be your configuration. Did you specify the dataConfiguration defaultDatabase value in your config file (e.g. web.config)?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600079",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Streaming text logfiles into RabbitMQ, then reconstructing at other end? Requirements
We have several servers (20-50) - Solaris 10 and Linux (SLES) - running a mix of different applications, each generating a bunch of log events into textfiles. We need to capture these to a separate monitoring box, where we can do analysis/reporting/alerts.
Current Approach
Currently, we use SSH with a remote "tail -f" to stream the logfiles from the servers onto the monitoring box. However, this is somewhat brittle.
New Approach
I'd like to replace this with RabbitMQ. The servers would publish their log events into this, and each monitoring script/app could then subscribe to the appropriate queue.
Ideally, we'd like the applications themselves to dump events directly into the RabbitMQ queue.
However, assuming that's not an option in the short term (we may not have source for all the apps), we need a way to basically "tail -f" the logfiles from disk. I'm most comfortable in Python, so I was looking at a Pythonic way of doing that - the consensus seems to be to just use a loop with readline() and sleep() to emulate "tail -f".
Questions
*
*Is there an easier way of "tail -f" a whole bunch of textfiles directly onto a RabbitMQ stream? Something inbuilt, or an extension we could leverage on? Any other tips/advice here?
*If we do write a Python wrapper to capture all the logfiles and publish them - I'd ideally like a single Python script to concurrently handle all the logfiles, rather than manually spinning up a separate instance for each logfile. How should we tackle this? Are there considerations in terms of performance, CPU usage, throughput, concurrency etc.?
*We need to subscribe to the queues, and then possibly dump the events back to disk and reconstruct the original logfiles. Any tips/advice on this? And we'd also like a single Python script we could startup to handle reconstructing all of the logfiles - rather than 50 separate instances of the same script - is that easily achievable?
Cheers,
Victor
PS: We did have a look at Facebook's Scribe, as well as Flume, and both seem a little heavyweight for our needs.
A: You seem to be describing centralized syslog with rabbitmq as the transport.
If you could live with syslog, take a look at syslog-ng. Otherwise, you might
save some time by using parts of logstash ( http://logstash.net/ ).
A: If it would be possible you can make the Application publish the events Asynchronously to RabbitMQ instead of writing it to log files. I have done this currently in Java.
But some times it is not possible to make the app log the way you want.
1 ) You can write a file tailer in python which publishes to AMQP. I don't know of anything which plugs in a File as the input to RabbitMQ. Have a look at http://code.activestate.com/recipes/436477-filetailpy/ and http://www.perlmonks.org/?node_id=735039 for tailing files.
2) You can create a Python Daemon which can tail all the given files either as processes or in a round robin fashion.
3) A similar approach to 2 can help you solve this. You can probably have a single queue for each log file.
A: If you are talking about application logging (as opposed to e.g. access logs such as Apache webserver logs), you can use a handler for stdlib logging which writes to AMQP middleware.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600083",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Rolling dice application for iPhone apps I am making an iPhone dice application and I wanted to create a button so that if I click it, it will generate a random number between 1 and 6 on the UITextField.
Can anyone help me out and give me a mathematical formula to generate such number?
Thanks
A: If you are using Objective-C, try:
#include <stdlib.h>
int random_number = (arc4random() % 6) + 1;
The 6 is needed because arc4random() % n results on a number from 0 to n-1.
A: #include <stdlib.h>
int r = arc4random() % 6;
Results between 0 and 5. Adjust with a +1 for 1 to 6.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600088",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: CALayerInvalid crash on resume I am seeing a CALayerInvalid crash every time my App resumes but only one a specific device. It's a 3rd Gen iPod Touch. Works fine on a 4th Gen or an iPad 1 or 2.
I've read some things about finding zombies but the debugger/instruments never seem to attach to the process earlier enough to detect the problem. I always see CALayerInvalid and it points to
retVal = UIApplicationMain(argc, argv, nil, NSStringFromClass([MyAppDelegate class]));
I believe it is crashing while loading the XIB that is large and has a lot of content.
I'm not sure how to continue to debug the issue.
thanks!
A: After tracking this for a while I notice that it was only happening on low resolution screens.
I don't know why but the issue was solve by removing a window. I had accidentally set my view controllers view to a window. So it places a window in a window. Removing this removed the crash.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600094",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Python Streaming : how to reduce to multiple outputs?(its possible with Java though) I read Hadoop in Action and found that in Java using MultipleOutputFormat and MultipleOutputs classes we can reduce the data to multiple files but what I am not sure is how to achieve the same thing using Python streaming.
for example:
/ out1/part-0000
mapper -> reducer
\ out2/part-0000
If anyone knows, heard, done similar thing, please let me know
A: The Dumbo Feathers, a set of java classes to use together with Dumbo (a python library that makes it easy to write efficient python M/R programs for hadoop), does this in its output classes.
Basically, in your python dumbo M/R job, you output a key that is a tuple of two elements - the first element being the name of the directory to output to, the second element being the actual key. The output class you've selected then inspects the tuple to find what output directory to use, and use MultipleOutputFormat to write to different subdirectories.
With dumbo, this is easy due to the use of typedbytes as output format, but I think it should be doable even if you have other output formats.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600095",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: MS CRM 2011 Install Failure "Action Microsoft.Crm.Setup.Server.InstallConfigDatabaseAction failed." I'm trying to install MS CRM 2011, and I continually get the
"Action Microsoft.Crm.Setup.Server.InstallConfigDatabaseAction failed.--->System.Security.Authentication.AuthenticationException: Logon failure: unknown user name or bad password.---> System.DirectoryServices.DirectoryServicesCOMException: Logon failure: unknown user name or bad password."
Error. I've tried to uninstall and Reinstall SQL 2008. I have to apply the SP1 patch to it everytime I create an instance - which goes through ok. I don't get any errors in the wizard until it actually starts the installation process. Afterward I continually get this error. Here is a copy of the log:
11:49:22| Error| Installer Complete: ConfigDBInstaller - Error encountered
11:49:22|Warning| Error reported while configuring _Deployment. Attempting rollback
11:49:22| Info| ConfigDBInstaller: Beginning uninstall operation
11:49:22| Info| Executing Uninstall action:Microsoft.Crm.Setup.Server.UnregisterRoleAction
11:49:22| Info| UnregisterRoleAction does not apply since _Deployment is not a explicit server role.
11:49:22| Info| CrmAction execution time; UnregisterRoleAction; 00:00:00.0050000
11:49:22| Info| ConfigDBInstaller: Uninstall completed
11:49:22| Error| Install exception.System.Exception: Action Microsoft.Crm.Setup.Server.InstallConfigDatabaseAction failed. ---> System.Security.Authentication.AuthenticationException: Logon failure: unknown user name or bad password.
---> System.DirectoryServices.DirectoryServicesCOMException: Logon failure: unknown user name or bad password.
at System.DirectoryServices.DirectoryEntry.Bind(Boolean throwIfFail)
at System.DirectoryServices.DirectoryEntry.Bind()
at System.DirectoryServices.DirectoryEntry.get_AdsObject()
at System.DirectoryServices.PropertyValueCollection.PopulateList()
at System.DirectoryServices.PropertyValueCollection..ctor(DirectoryEntry entry, String propertyName)
at System.DirectoryServices.PropertyCollection.get_Item(String propertyName)
at System.DirectoryServices.ActiveDirectory.PropertyManager.GetPropertyValue(DirectoryContext context, DirectoryEntry directoryEntry, String propertyName)
--- End of inner exception stack trace ---
at System.DirectoryServices.ActiveDirectory.PropertyManager.GetPropertyValue(DirectoryContext context, DirectoryEntry directoryEntry, String propertyName)
at System.DirectoryServices.ActiveDirectory.Domain.GetDomain(DirectoryContext context)
at Microsoft.Crm.Admin.AdminService.ConfigDBSecurity.SystemUserService.GetCaseSafeName(String domain, String accountName)
at Microsoft.Crm.Admin.AdminService.ConfigDBSecurity.SystemUserService.GetCaseSafeName(String name)
at Microsoft.Crm.Admin.AdminService.ConfigDBSecurity.SystemUserService.Create(String name, Guid defaultOrganizationId)
at Microsoft.Crm.Setup.Database.StandardConfigSqlStrategy.AddInitialUser()
at Microsoft.Crm.Setup.Database.DatabaseInstallerBase.Install()
at Microsoft.Crm.Setup.Server.InstallConfigDatabaseAction.Do(IDictionary parameters)
at Microsoft.Crm.Setup.Common.CrmAction.ExecuteAction(CrmAction action, IDictionary parameters, Boolean undo)
--- End of inner exception stack trace ---
at Microsoft.Crm.Setup.Common.CrmAction.ExecuteAction(CrmAction action, IDictionary parameters, Boolean undo)
at Microsoft.Crm.Setup.Common.Installer.Install(IDictionary stateSaver)
at Microsoft.Crm.Setup.Server.ServerRoleInstaller.Install(IDictionary stateSaver)
at Microsoft.Crm.Setup.Common.ComposedInstaller.InvokeInstall(Installer installer, IDictionary stateSaver)
at Microsoft.Crm.Setup.Common.ComposedInstaller.InternalInstall(IDictionary stateSaver)
at Microsoft.Crm.Setup.Common.ComposedInstaller.Install(IDictionary stateSaver)
at Microsoft.Crm.Setup.Server.ServerSetup.Install(IDictionary data)
at Microsoft.Crm.Setup.Common.SetupBase.ExecuteOperation()
11:49:22|Verbose| Method exit: Microsoft.Crm.Setup.Server.ServerSetup.ExecuteOperation
11:49:22| Info| ActivatePage(ServerSetupFinishPage)
Thanks, any and all help is much appreciated!
edit CRM 4.0 Was installed and working perfectly fine. I tried fresh install and upgrade of 2011 edition and im having these problems
A: Are you an administrator on your domain? The CRM setup process adds some groups to AD, so you'll need access on the domain to create those groups if you are the one running the setup process.
A: Figured out the problem. I had to reassign the Webserver and application roles on the server, then reinstall sql server. That fixed the issue. For some reason the sql server thought the name had changed or something - despite numerous reinstallations. Not sure why or how - but that fixed it
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600096",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Better Control over test suites in SenTesting Kit/OCUnit It seems that adding a class to my Xcode 4 Testing project that begins with test... automatically adds it to the testing run, but is there a way for me to have the test suites I want to run defined in a class so I can easily toggle them on and off? I would like to be able to manually register a suite then comment it out if it is not required. I don't want to have to add and remove classes from the Testing target.
A: In Xcode4 Edit Scheme, select "Test", click the disclosure triangle and click "Test". You will be able to select classes or individual tests.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600097",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Lost on membership provider I'm confused in the proper time to use SQLMembershipProvider vs my own custom provider. I'm building a system where users can create accounts; and then create objects in our system. When a user logs in, he should be able to see and edit the objects that he created.
Now, can I do this by using the SQLMembershipProvider? My understanding is that SQLMembershipProvider stores the users in its own database. If this is the case, how can I associate my objects with the user that created them? I've read about the Profile Properties system, but it doesn't seem like that would work, as that just adds extra information, like a postal code, to the .Net users object.
What would my object table look like; as in what would the column that says which user created the object be?
Or, do I just have to create a custom MembershipProvider which stores the users in my own database?
A: All you need is for your object table to have a UserId column that's a foreign key to the User table that the SQLMembershipProvider creates.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600100",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Why does NSRegularExpression not honor capture groups in all cases? Main problem: ObjC can tell me there were six matches when my pattern is, @"\\b(\\S+)\\b", but when my pattern is @"A b (c) or (d)", it only reports one match, "c".
Solution
Here's a function which returns the capture groups as an NSArray. I'm an Objective C newbie so I suspect there are better ways to do the clunky work than by creating a mutable array and assigning it at the end to an NSArray.
- (NSArray *)regexWithResults:(NSString *)haystack pattern:(NSString *)strPattern
{
NSArray *ar;
ar = [[NSArray alloc] init];
NSError *error = NULL;
NSArray *arTextCheckingResults;
NSMutableArray *arMutable = [[NSMutableArray alloc] init];
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:strPattern
options:NSRegularExpressionSearch error:&error];
arTextCheckingResults = [regex matchesInString:haystack
options:0
range:NSMakeRange(0, [haystack length])];
for (NSTextCheckingResult *ntcr in arTextCheckingResults) {
int captureIndex;
for (captureIndex = 1; captureIndex < ntcr.numberOfRanges; captureIndex++) {
NSString * capture = [haystack substringWithRange:[ntcr rangeAtIndex:captureIndex]];
//NSLog(@"Found '%@'", capture);
[arMutable addObject:capture];
}
}
ar = arMutable;
return ar;
}
Problem
I am accustomed to using parentheses to match capture groups in Perl in a manner like this:
#!/usr/bin/perl -w
use strict;
my $str = "This sentence has words in it.";
if(my ($what, $inner) = ($str =~ /This (\S+) has (\S+) in it/)) {
print "That $what had '$inner' in it.\n";
}
That code will produce:
That sentence had 'words' in it.
But in Objective C, with NSRegularExpression, we get different results. Sample function:
- (void)regexTest:(NSString *)haystack pattern:(NSString *)strPattern
{
NSError *error = NULL;
NSArray *arTextCheckingResults;
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:strPattern
options:NSRegularExpressionSearch
error:&error];
NSUInteger numberOfMatches = [regex numberOfMatchesInString:haystack options:0 range:NSMakeRange(0, [haystack length])];
NSLog(@"Pattern: '%@'", strPattern);
NSLog(@"Search text: '%@'", haystack);
NSLog(@"Number of matches: %lu", numberOfMatches);
arTextCheckingResults = [regex matchesInString:haystack options:0 range:NSMakeRange(0, [haystack length])];
for (NSTextCheckingResult *ntcr in arTextCheckingResults) {
NSString *match = [haystack substringWithRange:[ntcr rangeAtIndex:1]];
NSLog(@"Found string '%@'", match);
}
}
Calls to that test function, and the results show it is able to count the number of words in the string:
NSString *searchText = @"This sentence has words in it.";
[myClass regexTest:searchText pattern:@"\\b(\\S+)\\b"];
Pattern: '\b(\S+)\b'
Search text: 'This sentence has words in it.'
Number of matches: 6
Found string 'This'
Found string 'sentence'
Found string 'has'
Found string 'words'
Found string 'in'
Found string 'it'
But what if the capture groups are explicit, like so?
[myClass regexTest:searchText pattern:@".*This (sentence) has (words) in it.*"];
Result:
Pattern: '.*This (sentence) has (words) in it.*'
Search text: 'This sentence has words in it.'
Number of matches: 1
Found string 'sentence'
Same as above, but with \S+ instead of the actual words:
[myClass regexTest:searchText pattern:@".*This (\\S+) has (\\S+) in it.*"];
Result:
Pattern: '.*This (\S+) has (\S+) in it.*'
Search text: 'This sentence has words in it.'
Number of matches: 1
Found string 'sentence'
How about a wildcard in the middle?
[myClass regexTest:searchText pattern:@"^This (\\S+) .* (\\S+) in it.$"];
Result:
Pattern: '^This (\S+) .* (\S+) in it.$'
Search text: 'This sentence has words in it.'
Number of matches: 1
Found string 'sentence'
References:
NSRegularExpression
NSTextCheckingResult
NSRegularExpression matching options
A: I think if you change
// returns the range which matched the pattern
NSString *match = [haystack substringWithRange:ntcr.range];
to
// returns the range of the first capture
NSString *match = [haystack substringWithRange:[ntcr rangeAtIndex:1]];
You will get the expected result, for patterns containing a single capture.
See the doc page for NSTextCheckingResult:rangeAtIndex:
A result must have at least one range, but may optionally have more (for example, to represent regular expression capture groups).
Passing rangeAtIndex: the value 0 always returns the value of the the range property. Additional ranges, if any, will have indexes from 1 to numberOfRanges-1.
A: Change the NSTextCheckingResult:
- (void)regexTest:(NSString *)haystack pattern:(NSString *)strPattern
{
NSError *error = NULL;
NSArray *arTextCheckingResults;
NSRegularExpression *regex = [NSRegularExpression
regularExpressionWithPattern:strPattern
options:NSRegularExpressionSearch
error:&error];
NSRange stringRange = NSMakeRange(0, [haystack length]);
NSUInteger numberOfMatches = [regex numberOfMatchesInString:haystack
options:0 range:stringRange];
NSLog(@"Number of matches for '%@' in '%@': %u", strPattern, haystack, numberOfMatches);
arTextCheckingResults = [regex matchesInString:haystack options:NSRegularExpressionCaseInsensitive range:stringRange];
for (NSTextCheckingResult *ntcr in arTextCheckingResults) {
NSRange matchRange = [ntcr rangeAtIndex:1];
NSString *match = [haystack substringWithRange:matchRange];
NSLog(@"Found string '%@'", match);
}
}
NSLog output:
Found string 'words'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600103",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How to guarantee that app contains no memory leaks? How can one guarantee (or at least come reasonably close) that one's app contains no memory leaks?
What are the specific steps one should follow please?
I tried Product -> Analyze, which actually found a leak, however both before and after i fixed it Product -> Profile -> Leaks, none were shown.
In the image below, what should i be looking at? What is an indication of a leak?
A: Instruments finds leaks at runtime. You need click the "Record" button on left side of toolbar to run.
Check this link for more details on how to detect memory leaks with Instruments.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600110",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is the Declare function equivalent in a PHP database query? I'm rewriting some existing stored procedures in PHP but i'm not 100% sure what the DECLARE section of the stored procedure does. What is the PHP equivalent to this?
A: DECLARE just (go figure) declares variables and their types for use in the stored procs. It basically says "this is variable X, and its type is Y".
PHP has no such strict requirements. Mostly you can just start using a variable without explicitly declaring it in advance. It's a good idea to actually declare them before use, but not required.
The MySQL doc-page for DECLARE is here: http://dev.mysql.com/doc/refman/5.0/en/variables-in-stored-programs.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600114",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP trace for Form post A little background, I have a client that has a legacy php site that has been converted to python/django in the last 12 months. However they are still using the php site while phasing it out. Some new data is gathered in the old system and database structure from users still, but the clients would like it also to be available on the new site, which means inserting another mysql insert statement into the php code to write to the new site's database.
So the issue is the php developer is gone and not reachable. Also the code is a mess with multiple versions of each php file in multiple directories, zero version control. So I can find the code fragment that writes to the database, however it is in over 20 places. What I would love to be able to do is something comparable to the django, insert an 'assert Error' line in the form code upon POST and see the django error report traceback page, but this is php. So what are my best options here? Remember I am a python developer first and a php hack at best. Is there anything built into php that would allow me to see some type of traceback without too much hacking?
A: phptrace is a simple tool to trace php executing flows
$ ./phptrace -p 3130 -s # phptrace -p <PID> -s
phptrace 0.2.0 release candidate, published by infra webcore team
process id = 3130
script_filename = /home/xxx/opt/nginx/webapp/block.php
[0x7f27b9a99dc8] sleep /home/xxx/opt/nginx/webapp/block.php:6
[0x7f27b9a99d08] say /home/xxx/opt/nginx/webapp/block.php:3
[0x7f27b9a99c50] run /home/xxx/opt/nginx/webapp/block.php:10
A: If the MySQL server is version >= 5.0.2 then you could use triggers to keep the data up to date on the new site. That may prove easier than digging through all the PHP code (which you suggested you're not comfortable with).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600116",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Blackberry optimization - background image from disk or RAM? I'm curious if anyone has information on whether or not this is an actual optimization or unnecessary bloat.
I have some screens that are pushed and popped from the stack via user interaction and all of them have the same background image.
Instead of loading the image on each screen, I have implemented a static method which loads the image from disk the first time it's accessed, then keeps the bitmap in a static variable for future use.
Is there some way to profile this or is anyone aware of a downside to this?
public final class App {
private static Bitmap _bgBitmap = null;
/*
* Get a standard background for screens
* Method caches background in memory for less disk access
*/
public static Bitmap getScreenBackground(){
if (_bgBitmap == null){
try {
_bgBitmap = Bitmap.getBitmapResource("ScreenBG.jpg");
}
catch(Exception e){}
}
return _bgBitmap;
}
}
A: I suppose the only reason of having a Bitmap as a static field somewhere is to speed up creating another screen that also uses the same bitmap. IMHO this is a nice approach, however the answer to your question may differ depending on how exactly you use the bitmap:
*
*Do you draw it directly on Graphics instance in some paint()?
*Do you resize it before drawing?
*Do you create a Background instance from the bitmap? In this case you'll need to investigate whether the Background instance creates a copy of bitmap for its internal usage (in this case RAM consupmtion may be doubled (2 bitmaps), so it would be nice to share across screens the Background instance rather than the bitmap).
Another point - it sounds like there maybe a case when there is no screen instances that use the bitmap. If yes, then you could detect such case in order to nullify the _bgBitmap so if OS decides to free some RAM it could GC the bitmap instance. However if app workflow implies such screen to be created soon, then maybe it is cheaper to leave the bitmap alive.
Also, how large is the bitmap? If it is relatively small, then you can just don't bother yourself with further optimization (your current lazy loading is good enough). You can count size in bytes consumed in RAM by knowing its with and height: int size = 4 * width * height. You can also log/popup the time taken to load the bitmap from resources. If it is relatively small, then maybe don't even use the current lazy loading? Note the timings should be taken on real devices only, since BB simulators are in times faster than devices.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600117",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Using Server.MapPath in MVC3 I have the code
string xsltPath = System.Web.HttpContext.Current.Server.MapPath(@"App_Data") + "\\" + TransformFileName
It returns
C:\inetpub\wwwroot\websiteName\SERVICENAME\App_Data\FileName.xsl
Why am I getting the path to the ServiceController, SERVICENAME? I want the path to App_Data which is in
C:\inetpub\wwwroot\websiteName\App_Data\FileName.xsl
A: The answers given so far are what you are looking for, but I think, in your particular case, what you actual need is this:
AppDomain.CurrentDomain.GetData("DataDirectory").ToString()
This will still return the file path to the App_Data directory if that directory name changes in future versions of MVC or ASP.NET.
A: You need to specify that you want to start from the virtual root:
string xsltPath = Path.Combine(System.Web.HttpContext.Current.Server.MapPath(@"~/App_Data"), TransformFileName);
Additionally, it's better practice to use Path.Combine to combine paths rather than concatenate strings. Path.Combine will make sure you won't end up in a situation with double-path separators.
EDIT:
Can you define "absolute" and "relative" paths and how they compare to "physical" and "virtual" paths?
MSDN has a good explanation on relative, physical, and virtual paths. Take a look there.
A: Try doing like this (@"~/App_Data"). ~/ represents the root directory.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600118",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "23"
}
|
Q: PHP5-ldap and LDAPS under Apache2 (not working) vs CLI (working) I'm trying to connect to an LDAPS server using Apache2, PHP5.3, with the php5-ldap package.
When I set the code off using PHP-CLI, it works fine.
When I execute the same code under Apache2, the bind always fails.
I've set TLS_REQCERT to NEVER, hence the CLI version working.
What am I doing wrong?
Code:
<?php
// using anonymous ldap bind
// connect to ldap server
$ldapconn = ldap_connect("ldaps://XXX.XXX.com")
or die("Could not connect to LDAP server.");
if ($ldapconn)
{
// binding anonymously
$ldapbind = ldap_bind($ldapconn) or die("Couldn't bind\n");
if ($ldapbind) {
echo "LDAP anonymous bind successful...";
} else {
echo "LDAP anonymous bind failed...";
}
}
$res = ldap_search($ldapconn, 'ou=XXX,o=XXX', '(sn=XXX*)');
$info = ldap_get_entries($ldapconn, $res);
echo "<pre>" . var_dump($info) . "</pre>";
ldap_unbind($ldapconn);
?>
A: Review php.ini, and make sure the ext is being loaded with phpinfo(). Differint sapi's might try loading php.ini from differint locations, so also check the location of php.ini within phpinfo() and make sure it's loading the one your expecting.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600121",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Using RegEx for Data Transformation We have a requirement to transform the application specific XML data to a target XSD format specified by government agency. The government agency specifies the pattern using regular expression. Please see below for the sample
<! -- Date Type in the format of YYYY-MM-DD -->
<xsd:simpleType name="DateType">
<xsd:annotation>
<xsd:documentation>Base type for a date</xsd:documentation>
</xsd:annotation>
<xsd:restriction base="xsd:date">
<xsd:pattern value="[1-9][0-9]{3}\-.*" />
</xsd:restriction>
</xsd:simpleType>
We are building a custom .NET mapping and transformation solution to support application specific needs. The requirement is to use the regular expression specified in the target XSD to transform the source XML data to meet the pattern required by the target. For example, if the source date is of format mm-dd-yyyy, the program should convert the same to YYYY-MM-DD using the regular expression (1-9][0-9]{3}\-.*")
Likewise there are several RegEx pattern we should leverage based on the data type. Here are our questions:
*
*Is it a general practice to use RegEx for data transformation rather data validation?
*If yes, how would be approach this. Is there an established pattern or technique on how to leverage RegEx for data transformation?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600122",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Outlook 2010 addin Access is denied Im trying to create an outlook 2010 addin. I just created the standard project, when trying to run it i get the following error...
Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
***** Exception Text *******
System.UnauthorizedAccessException: Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
at System.Deployment.Internal.Isolation.IsolationInterop.GetUserStore(UInt32 Flags, IntPtr hToken, Guid& riid)
at System.Deployment.Internal.Isolation.IsolationInterop.GetUserStore()
at System.Deployment.Application.ComponentStore..ctor(ComponentStoreType storeType, SubscriptionStore subStore)
at System.Deployment.Application.SubscriptionStore..ctor(String deployPath, String tempPath, ComponentStoreType storeType)
at System.Deployment.Application.SubscriptionStore.get_CurrentUser()
at System.Deployment.Application.DeploymentManager..ctor(Uri deploymentSource, Boolean isUpdate, Boolean isConfirmed, DownloadOptions downloadOptions, AsyncOperation optionalAsyncOp)
at System.Deployment.Application.InPlaceHostingManager..ctor(Uri deploymentManifest, Boolean launchInHostProcess)
at Microsoft.VisualStudio.Tools.Applications.Deployment.IPHMProxy..ctor(Uri uri)
at Microsoft.VisualStudio.Tools.Applications.Deployment.ClickOnceAddInDeploymentManager.get_Proxy()
at Microsoft.VisualStudio.Tools.Applications.Deployment.ClickOnceAddInDeploymentManager.GetManifests(TimeSpan timeout)
at Microsoft.VisualStudio.Tools.Applications.Deployment.ClickOnceAddInDeploymentManager.InstallAddIn()
Anyone have an idea about this?
A: You might have some problem in your Local Settings folder. Try deleting it, reboot and it will be recreated. That's how I've solved a few access denied errors when dealing with QlickOnce.
The Local Settings-folder is hidden default. It's found here on Windows 7 (and Vista):
C:\Users\{user name}\AppData\Local
And here on Windows XP:
C:\Documents and Settings\{user name}\AppData\Local
A: I got the same issue on one of my team mate's machine after installing setup of word addin. I created installer using Installshield's limited edition. The issue was in registry entry. Path in Manifest entry was having "file:///" at start which was somehow causing error.
First I manually changed path in manifest registry (at HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Office\Word\Addins\YourAddin\Manifest) from "file:///C:/Program Files (x86)/...../My.vsto" to "C:/Program Files (x86)/...../My.vsto" and it worked. Then I fixed that in my setup project too.
Hope this helps somene.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600128",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to have maven build my project with all the dependencies in a separte folder, ready to package? How do I create a package of a Maven project that contains the jar with my classes, plus a directory like "lib" with all the needed dependencies? I'm using netbeans ...
A: You can copy required libs into a folder using Maven dependency plugin copy-dependencies goal.
In addition to that you can use Maven assembly plugin to create an archive containing your jar and this lib folder.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600135",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: FFMPEG and CPU utilization Is there a way to either set a maximum CPU utilization for ffmpeg, or
(preferably) to run ffmpeg at a lower priority so that it still runs
at 100% but gives up CPU to other processes as needed?
I am not sure if this is something I could set in ffmpeg itself or if
I need to run some sort of wrapper command or change a system setting.
A: I guess you are running this on Linux. A quick Google gave me this:
Changing Priority on Linux Processes
These guidelines are called niceness or nice value. The Linux niceness scale goes from -20 to 19. The lower the number the more priority that task gets. If the niceness value is high number like 19 the task will be set to the lowest priority and the CPU will process it whenever it gets a chance. The default nice value is zero.
Create new process with a specific priority:
nice -n [nice-value from -20 to 19] [command]
So, in your case:
nice -n 10 ffmpeg .....
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600142",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: JQuery - What can I do to make this work? http://jsfiddle.net/piezack/X8D4M/5/
I need the change created by clicking the button to be detected. At the moment you have to click inside the field and then outside for it to detect any change.
Thanks guys.
The code for the button CANNOT be altered. Good tries so far though.
Was overcomplicating things. Answer http://jsfiddle.net/piezack/X8D4M/56/
A: Example using trigger:
//waits till the document is ready
$(document).ready(function() {
$('button.butter').click(function() {
var $form6 = $('#FormCustomObject6Name');
$form6.val('Text has changed');
$form6.trigger('change')
});
$('#FormCustomObject6Name').change(function() {
var x = $('#FormCustomObject6Id').val();
$("a").filter(function() {
return this.href = 'http://www.msn.com'
}).attr('href', 'http://www.google.com/search?q=' + x);
alert(x);
});
});
A: i think that jmar has the right idea...if i understand correctly you want to be able to type whatever in the box and without clicking out of it to have the button change it to the text has changed.
i dont know if that alert is really necessary, but you can do this if the alert is not needed:
http://jsfiddle.net/X8D4M/24/
A: To trigger the change event simply add a .trigger after setting the value.
Also, you're selector for the link wasn't working so I just changed it to #link.
http://jsfiddle.net/X8D4M/22/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600144",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Executing POST_BUILD commands based upon file dependencies I have a DLL POST_BUILD step that copies the DLL to directory A. Suppose I then delete the file from directory A. I then hit F5 inside Visual Studio and the file is not copied.
What are my options here? How do I specify that there is a set of operations that must be executed both every time the DLL is linked, and when the file in directory A is out of date with (or missing)?
EDIT: This is specifically an unmanaged C++ project, and only has .vcproj files, generated by CMake. Therefore, editing the .vcproj is not practical in my workflow.
A: The post build commands are only executed when msbuild determines that the project needs to be rebuilt. It doesn't otherwise know that your project has a dependency on that file since it doesn't parse the post build commands, that's unpractical.
By far the simplest solution is to just not delete that file, there's little point. Another way to do it, making msbuild smarter, is to add the file to your project. Use Project + Add Existing Item. Set Build action = Content, Copy to Output Directory = Copy if Newer. It does clog up your project tree a bit of course.
A: Hans's approach is good too.
Rather than using the IDE hooks, you are better off by editing the project directly as msbuild provides a complete set of tasks for doing what you want.
If you edit the .csproj file (right click -> unload project -> edit) and add a post-build step, you'll get the dirty copy behaviour you want:
<Target Name="AfterBuild">
<ItemGroup>
<BuildArtifacts Include="MyDll.dll"/>
<FileWrites Include="$(DestDir)\*.*" />
</ItemGroup>
<Copy SourceFiles="@(BuildArtifacts)" DestinationFiles="->'$(DestDir)\%(Filename)%(Extension)'" />
</Target>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600146",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Ordering and Ordered and comparing Options Given:
case class Person(name: String)
and trying to do:
scala> List(Person("Tom"), Person("Bob")).sorted
results in a complaint about missing Ordering.
<console>:8: error: could not find implicit value for parameter ord: Ordering[Person]
List(Person("Tom"), Person("Bob")).sorted
However this:
case class Person(name: String) extends Ordered[Person] {
def compare(that: Person) = this.name compare that.name }
works fine as expected:
scala> List(Person("Tom"), Person("Bob")).sorted
res12: List[Person] = List(Person(Bob), Person(Tom))
although there's no Ordering or implicits involved.
Question #1: what's going on here? (My money is on something implicit...)
However, given the above and the fact that this:
scala> Person("Tom") > Person("Bob")
res15: Boolean = true
works, and that also this:
scala> List(Some(2), None, Some(1)).sorted
works out of the box:
res13: List[Option[Int]] = List(None, Some(1), Some(2))
I would expect that this:
scala> Some(2) > Some(1)
would also work, however it does not:
<console>:6: error: value > is not a member of Some[Int]
Some(2) > Some(1)
Question #2: why not, and how can I get it to work?
A: The definition of List's sorted method is:
def sorted [B >: A] (implicit ord: Ordering[B]): List[A]
So yes, implicit things are happening, but many classes in the standard library have implicit objects associated with them without you having to import them first.
The Ordering companion object defines a bunch of implicit orderings. Among these is an OptionOrdering and IntOrdering, which helps explain the ability of a list to call sorted.
To gain the ability to use operators when there is an implicit conversion available, you need to import that object, for example:
def cmpSome(l:Option[Int], r:Option[Int])(implicit ord:Ordering[Option[Int]]) = {
import ord._
l < r
}
scala> cmpSome(Some(0), Some(1))
res2: Boolean = true
A: If you install the slightly-too-magical-for-default-scope bonus implicits, you can compare options like so:
scala> import scala.math.Ordering.Implicits._
import scala.math.Ordering.Implicits._
scala> def cmpSome[T: Ordering](x: Option[T], y: Option[T]) = x < y
cmpSome: [T](x: Option[T], y: Option[T])(implicit evidence$1: Ordering[T])Boolean
The import gives you an implicit from an Ordering to the class with the infix operations, so that it's enough to have the Ordering without another import.
A: To answer your second question, why can't you do this: Some(2) > Some(1)
You can, with an import and working with Option[Int] rather than Some[Int].
@ import scala.math.Ordering.Implicits._
import scala.math.Ordering.Implicits._
@ Some(2) > Some(1) // doesn't work
cmd11.sc:1: value > is not a member of Some[Int]
val res11 = Some(2) > Some(1)
^
Compilation Failed
@ (Some(2): Option[Int]) > (Some(1): Option[Int]) // Option[Int] works fine
res11: Boolean = true
@ Option(2) > Option(1)
res12: Boolean = true
@ (None: Option[Int]) > (Some(1): Option[Int])
res13: Boolean = false
In practise your types will probably be of Option[Int] rather than Some[Int] so it won't be so ugly and you won't need the explicit upcasting.
A: Concerning your first question: Ordered[T] extends Comparable[T]. The Ordering companion object provides an implicit Ordering[T] for any value that can be converted into a Comparable[T]:
implicit def ordered[A <% Comparable[A]]: Ordering[A]
There is no implicit conversion A : Ordering => Ordered[A] - that's why Some(1) > Some(2) will not work.
It is questionable if it is a good idea to define such a conversion as you may end up wrapping your objects into Ordered instances and then create an Ordering of that again (and so on...). Even worse: you could create two Ordered instances with different Ordering instances in scope which is of course not what you want.
A: I assume you understand why sorted does not work when you do not pass in an Ordering and none is available in scope.
As to why the sorted function works when you extend your class from Ordered trait. The answer is that when you extend from Ordered trait, the code type checks as the trait contains function like <,> etc. So there is no need to do implicit conversion and hence no complains about the missing implicit Ordering.
As for your second question, Some(2) > Some(1) will not work because Some does not extend the trait Ordered, neither does there seem to be any implicit function in scope that implicitly converts a Some to something that has the function >
A: Thanks for a detailed question with examples.
My answer is based what I learnt from a great article here: http://like-a-boss.net/2012/07/30/ordering-and-ordered-in-scala.html
All credit to the author here.
Quoting the article:
Coming back to our Box example - the scala library defines an implicit conversion between Ordered[T] and Ordering[T] and vice-versa.
The companion object of Ordered in https://github.com/scala/scala/blob/2.12.x/src/library/scala/math/Ordered.scala provides the required conversion here:
/** Lens from `Ordering[T]` to `Ordered[T]` */
implicit def orderingToOrdered[T](x: T)(implicit ord: Ordering[T]): Ordered[T] =
new Ordered[T] { def compare(that: T): Int = ord.compare(x, that) }
However the reverse conversion isn't defined and I am not sure why?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600154",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "24"
}
|
Q: Jquery Selectors + Syntax I am trying to use a jQuery selector (this) to get an image nested on the same level.
Just a syntax error, any help would be appreciated. Thanks!
$(this).addClass('on');
$(this img).slideUp('fast');
$(this img.accordionButtonActive).slideDown('fast');
http://jsfiddle.net/zBrhH/
A: You can't do $(this img). But you can pass a second parameter which defines the scope, try this:
$('img', this)...
A: I think you want the effect like this:
http://jsfiddle.net/expertCode/zBrhH/
using:
$(this).addClass('on');
$('img', this).slideUp('fast');
$('img.accordionButtonActive', this).slideDown('fast');
I changed some events too. Try it ;)
A: $(this img).slideUp('fast');
should be
$(this).find("img").slideUp('fast');
Demo, with working accordion: http://jsfiddle.net/zBrhH/2/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600156",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to grab the last 12 months from cygwin "date" and use the months for git sync I'm trying to compare the trees of a repo as they were at the end of the month for the past 12 months, to see what changed. I am a newb - so far my code basically looks like this:
for month in Jan Feb Mar Apr May Jun Jul Aug Sep
git checkout $(git rev-list --before "$month 1 2011" -n 1 HEAD)
I'd like to make this work for the last 12 months, going back to the previous year. I want it to by dynamic - how do I make a loop that iterates over the last 12 months, ending on the current month? I want the month value to be a variable I can use both in for "..." and in my git checkout ... line.
Thanks!
A: You might want to try something like this:
for i in {1..12}; do
git checkout $(git rev-list --before "$(date -d "$(date -d +%Y-%m-15) -$i months" +%Y-%m)-01" -n 1 HEAD)
...
done
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is sparse matrix-vector multiplication available in Simulink/xPC? I am trying to make my control algorithm more efficient since my matrices are sparse. Currently, I am doing conventional matrix-vector multiplications in Simulink/xPC for a real-time application. I can not find a way to convert the matrix to a sparse one and perform that type of multiplication where it is compatible with xPC. Does anyone have an idea on how to do this?
A: It appears, at least as of earlier this year, that it is impossible to do sparse matrices in Simulink: see this Q&A on MathWorks' site. As the answerer is a Simulink software engineer, it seems authoritative. :)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600160",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: IBM Filenet P8 Integrated windows Auth A colleague of mine is trying to consume an intranet web service that's configured to use Integrated Windows Auth and he believes there's no way to configure IBM Filenet P8 to perform integrated Windows Auth.
I am very doubtful of that but everything I see in Google seems to be related to IBM File Net Share Point Connector. Is that the same thing?
Can anybody confirm that yes indeed, Integrated Windows Auth is not supported in IBM File NET P8?
If there's a way, can you provide quick steps on how to do this?
I don't use IBM Filenet P8 and I don't need to/want to know. I just want my colleague to be able to consume the web service.
A: The thing you are asking could mean any of several possibilities, but it probably does not refer to the IBM FileNet SharePoint Connector. The most likely thing that your colleague is facing is wanting to use web services to communicate with a FileNet P8 Content Engine (CE) or Process Engine (PE).
Both of those servers do indeed have web services exposed (referred to as CEWS and PEWS, respectively). And, both of them can work with IWA. From your question, it sounds like the server is already set up, and your colleague is trying to figure out the details of what to do in his client piece (or, rather, that he believes it simply cannot be done).
The details are bit much to go into here, but here are a couple of pieces of info that will hopefully send him down the right path. (I realize you weren't looking for a homework assignment; sorry! :-)
Here is the official product documentation, including the developer guide: http://publib.boulder.ibm.com/infocenter/p8docs/v5r1m0/index.jsp It's searchable, so searching for terms like "integrated windows authentication" or "kerberos" will turn up some interesting links.
Here is a free IBM Redbook specifically about developing with P8: Developing Applications with IBM FileNet P8 APIs, http://www.redbooks.ibm.com/abstracts/SG247743.html
Unless your colleague is in a position where the interface just must be web services, I would encourage him to look into the P8 CE .NET API. It's a full .NET compatible API, with all the niceties of OO and type safety that are sometimes a little awkward in web services work. It talks to the same CEWS listener that he is probably trying to use with web services. It's also pretty easy to get IWA going with that API.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600162",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Why Database is not used with 3D and Drawing softwares (to store points and other primitive shapes)? My question is why Databases are not used with Drawing, 3D Modelling, 3D Design, Game Engines and architecture etc. software to save the current state of the images or the stuff that is present on the screen or is the part of a project in a Database.
One obvious answer is the speed, the speed of retrieving or saving all the millions of triangles or points forming the geometry is very low, as there would be hundreds or thousands of queries per second, but is it really the cause? Considering the apparent advantages of using databases can allow sharing the design live over a network when it is being saved at a common location, and more than one people can work on it at a time or can use can give live feedback when something is being designed when it is being shared, specially when time based update is used, such as update after every 5 or 10 seconds, which is not as good as live synchronization, but should be quick enough. What is the basic problem in the use of Databases in this type of software that caused them not to be used this way, or new algorithms or techniques not being developed or studied for optimizing the benefits of using them this way? And why this idea wasn't researched a lot.
A: Your obvious answer is correct; I'm not an expert in that particular field but I'm at a point that even from a distance you can see that's (probably) the main reason.
This doesn't negate the possibility that such systems will use a database at some point.
Considering the apparent advantages of using databases can allow
sharing the design live over a network when it is being saved at a
common location...
True, but just because the information is being passed around doesn't mean that you have to store it in a database in order to be able to do that. Once something is in memory you can do anything with it - the issue with not persisting stuff is that you will lose data if the server fails / stops / etc.
I'll be interested to see if anyone has a more enlightened answer.
A: The short answer is essentially speed. The speed of writing information to a disk drive is an order of magnitude slower than writing it to ram. The speed of network access is in turn an order of magnitude slower than writing or reading a hard disk. Live sharing apps like the one you describe are indeed possible though, but wouldn't necessarily require what you would call a "database", nor would using a database be such a great idea. The reason more don't exist is that they are actually fiendishly difficult to program. Programming by itself is difficult enough, even just thinking in a straight line, with a single narrative. But to program something like that requires you to be able to accurately visualise multiple parallel dimensions acting on the same data simultaneously, without breaking anything. This is actually difficult.
A: Interesting discussion... I have a biased view towards avoiding adding too much "structure" (as in in the indexes, tables, etc. in a DBMS solution) to spacial problems or challenges beyond those that cannot be readily recreated from a much smaller subset of data. I think if the original poster would look at the problem from what is truly needed to answer the need/develop solutions ... he may not need to query a DBMS nearly as often... so the DBMS in question might relate to a 3D space but in fact be a small subset of total values in that space... in a similar way that digital displays do not concern themselves with every chnage in pixel (or voxel) value but only those that have changed. Since most 3D problems would have a much lower "refresh" rate vs video displays the hits on the DBMS would be infrequent enough to possibly make a 3D DB look "live".
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600164",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Specify CSS's for webkit/IE without separate CSS For IE I can use this:
.content {
*padding: 10px;
padding: 10px
}
By doing so, the *-part will only be used for IE. Is there a tric like this for webkit browsers too? (Whitout having them called to a special .css for webkit browsers?)
A: There's not such a hack for webkit-based browsers. However, you can achieve such an effect (in multiple browsers) using:
<script>
(function(){ //anonymous function to prevent leaking
var d = document.createElement("div");
d.style.cssText = "-webkit-border-radius:1px;"; // webkit, such as Chrome/Safari
if(/webkit/i.test(d.style.cssText)){
var style = document.createElement("style");
style.src = "webkit-only.css";
document.getElementsByTagName("head")[0].appendChild(style);
}
})();
</script>
The key behind this solution is that unknown CSS declarations are ignored by a browser. The -webkit- prefix will only be available in webkit-based browsers.
Similarly, the following prefixes can be used to detect other browser engines:
*
*-moz-border-radius:1px; - Gecko, such as Firefox
*-o-border-radius:0; - Opera
*-ms-border-radius:0; - Trident, such as Internet Explorer
There's a chance that your user has an ancient browser which don't support border-radius, but since Chrome is usually kept up-to-date (auto-update), the webkit solution should always work.
A: Found a decent hack. Seems to work at first sight :)
@media screen and (-webkit-min-device-pixel-ratio:0) {
div.panel-homepage div#plan-build-operate div.panel-pane ul.links a { padding-top: 20px;}
}
A: If you work with PHP, there is a function call :
get_browser()
check at : http://php.net/manual/fr/function.get-browser.php
This function returns an array of all the information about the client browser.
Add these informations as CSS class in your body tag.
You will be able to target specific browser without using CSS hack and
have a valid CSS code.
Good luck!
A: I found a new way instead of using get_browser() for those who doesn't have the extension installed. This new way is by using HTACCESS instead. You need the module "mod_setenvif" installed.
Here is the code you need to put in the .htaccess file.
It's a regexp over the HTTP_USER_AGENT server variable. If it matches, we create a USER_AGENT variable to store the matching browser name.
<IfModule mod_setenvif.c>
BrowserMatch "Mozilla" USER_AGENT=firefox
BrowserMatch "Safari" USER_AGENT=safari
BrowserMatch "Chrome" USER_AGENT=chrome
BrowserMatch "MSIE" USER_AGENT=ie
</IfModule>
Then, you can use the new server variable in your PHP code.
<body class="<?php echo $_SERVER['USER_AGENT'];?>">
Have a good day.
A: Use the following to target Webkit:
x:-webkit-any-link { padding: 10px; }
If you need to support IE7, add the following to filter this rule from applying to it:
* > /**/ .content, x:-webkit-any-link { padding: 10px; }
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600173",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Magento stock getting overwritten to 0 on some products I'm seeing an issue in our Magento 1.5.0.1 store where the stock is getting overwritten to 0 on some products. This seems to be happening automatically and I can't figure out why. I recently installed Lightspeed and SpeedBooster from Tinybrick, which may have something to do with it, but I have since disabled them and still no luck. I'm really at a loss here, so any thoughts, ideas, or debugging tips would be greatly appreciated.
Thanks!
Backtrace Data
2011-09-29T18:10:05+00:00 DEBUG (7): before save, QTY is 0 for 615906-2PK...printing backtrace
2011-09-29T18:10:05+00:00 DEBUG (7): [21] VPS_Stock_Model_Observer::catalog_product_save_before LINE 1265 (/chroot/home/valuepet/valuepetsupplies.com/html/app/code/core/Mage/Core/Model/App.php)
2011-09-29T18:10:05+00:00 DEBUG (7): [20] Mage_Core_Model_App::_callObserverMethod LINE 1246 (/chroot/home/valuepet/valuepetsupplies.com/html/app/code/core/Mage/Core/Model/App.php)
2011-09-29T18:10:05+00:00 DEBUG (7): [19] Mage_Core_Model_App::dispatchEvent LINE 416 (/chroot/home/valuepet/valuepetsupplies.com/html/app/Mage.php)
2011-09-29T18:10:05+00:00 DEBUG (7): [18] Mage::dispatchEvent LINE 391 (/chroot/home/valuepet/valuepetsupplies.com/html/app/code/core/Mage/Core/Model/Abstract.php)
2011-09-29T18:10:05+00:00 DEBUG (7): [17] Mage_Core_Model_Abstract::_beforeSave LINE 306 (/chroot/home/valuepet/valuepetsupplies.com/html/app/code/core/Mage/Catalog/Model/Abstract.php)
2011-09-29T18:10:05+00:00 DEBUG (7): [16] Mage_Catalog_Model_Abstract::_beforeSave LINE 474 (/chroot/home/valuepet/valuepetsupplies.com/html/app/code/core/Mage/Catalog/Model/Product.php)
2011-09-29T18:10:05+00:00 DEBUG (7): [15] Mage_Catalog_Model_Product::_beforeSave LINE 316 (/chroot/home/valuepet/valuepetsupplies.com/html/app/code/core/Mage/Core/Model/Abstract.php)
2011-09-29T18:10:05+00:00 DEBUG (7): [14] Mage_Core_Model_Abstract::save LINE 114 (/chroot/home/valuepet/valuepetsupplies.com/html/app/code/core/Mage/CatalogInventory/Model/Stock/Item/Api.php)
2011-09-29T18:10:05+00:00 DEBUG (7): [13] Mage_CatalogInventory_Model_Stock_Item_Api::update LINE ()
2011-09-29T18:10:05+00:00 DEBUG (7): [12] ::call_user_func_array LINE 404 (/chroot/home/valuepet/valuepetsupplies.com/html/app/code/core/Mage/Api/Model/Server/Handler/Abstract.php)
2011-09-29T18:10:05+00:00 DEBUG (7): [11] Mage_Api_Model_Server_Handler_Abstract::multiCall LINE ()
2011-09-29T18:10:05+00:00 DEBUG (7): [10] SoapServer::handle LINE 832 (/chroot/home/valuepet/valuepetsupplies.com/html/lib/Zend/Soap/Server.php)
2011-09-29T18:10:05+00:00 DEBUG (7): [9] Zend_Soap_Server::handle LINE 145 (/chroot/home/valuepet/valuepetsupplies.com/html/app/code/core/Mage/Api/Model/Server/Adapter/Soap.php)
2011-09-29T18:10:05+00:00 DEBUG (7): [8] Mage_Api_Model_Server_Adapter_Soap::run LINE 76 (/chroot/home/valuepet/valuepetsupplies.com/html/app/code/core/Mage/Api/Model/Server.php)
2011-09-29T18:10:05+00:00 DEBUG (7): [7] Mage_Api_Model_Server::run LINE 42 (/chroot/home/valuepet/valuepetsupplies.com/html/app/code/core/Mage/Api/controllers/IndexController.php)
2011-09-29T18:10:05+00:00 DEBUG (7): [6] Mage_Api_IndexController::indexAction LINE 418 (/chroot/home/valuepet/valuepetsupplies.com/html/app/code/core/Mage/Core/Controller/Varien/Action.php)
2011-09-29T18:10:05+00:00 DEBUG (7): [5] Mage_Core_Controller_Varien_Action::dispatch LINE 253 (/chroot/home/valuepet/valuepetsupplies.com/html/app/code/core/Mage/Core/Controller/Varien/Router/Standard.php)
2011-09-29T18:10:05+00:00 DEBUG (7): [4] Mage_Core_Controller_Varien_Router_Standard::match LINE 176 (/chroot/home/valuepet/valuepetsupplies.com/html/app/code/core/Mage/Core/Controller/Varien/Front.php)
2011-09-29T18:10:05+00:00 DEBUG (7): [3] Mage_Core_Controller_Varien_Front::dispatch LINE 340 (/chroot/home/valuepet/valuepetsupplies.com/html/app/code/core/Mage/Core/Model/App.php)
2011-09-29T18:10:05+00:00 DEBUG (7): [2] Mage_Core_Model_App::run LINE 627 (/chroot/home/valuepet/valuepetsupplies.com/html/app/Mage.php)
2011-09-29T18:10:05+00:00 DEBUG (7): [1] Mage::run LINE 80 (/chroot/home/valuepet/valuepetsupplies.com/html/index.php)
2011-09-29T18:10:05+00:00 DEBUG (7): END BACKTRACE
A: Place a before and after save event listener on the product and stock objects.
Have the listener check for a stock of "0".
If a stock of zero is detected, construct a stack trace via the information in debug_backtrace. You'll want to manually create this, as a circular reference in a backtrace's paramaters can potentially create infinite output.
Use the backtrace to determine where/when the stock is getting set to zero.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600174",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: AVFoundation AudioPlayer I'm trying to use the AudioPlayer class that's included in Apple's AVFoundation framework. The problem is xcode for some reason won't properly import the AVFoundation framework. I can't use the #import <AVFoundation/AVFoundation.h> to include the namespace, it won't work, and I don't know why. It shows up in the explorer on the left side, and I can use other namespaces and classes. If anyone can help, I'd be appreciative. Thanks.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600176",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Raphael and IE. Mouseout workaround I've run into an issue using Raphael for SVG effects on an IE browser. When I mouseover an object, the animation occurs as expected. On mouseout, however, the mouseout action is never called, so the object(s) are stuck in their mouseover state.
I've seen others complain about this issue in the past, but the only solution I saw was to force the mouseover event on every object to return everything != current object to their normal state. I'd rather not do a general "reset everything" because I have quite a few objects, so I'm wondering if anyone has an alternative they can suggest. I was thinking about storing the last object with the last triggered mouseover in a variable and only resetting that on every mouseover, which could work....
A: I had the same problem (map with regions that changed background on hover) and the deal-braker in IE9/Opera for me was the toFront() method. I removed that and it works fine.
A: I gone around this limitation by putting code inside anonymous function and then calling it via setTimeout inside event handler.
A: Since Raphael 2.0.2, there's been an issue in Raphael and Internet Explorer (all versions) where various manipulations of a path such as resetting a transform, .toFront(), or .toBack() called from hover() while hovering can cause hover ins to loop endlessly and/or hover outs to be missed.
While hover mostly works fine in IE for mouseout, there are a few things I've found that that can trip it up, causing it to a) ignore mouseouts as you describe and b) trigger the mouseover event recursively such that if you put a console.log in there, IE developer tools' console breaks and turns grey... which sometimes seems to also stop it recognising mouseouts.
Here are the things I've encountered which cause this:
*
*Resetting a transform, which would cause the element to move from under the mouse, then reapplying it putting the element back under the cursor. non-IE carries on like nothing happened and works fine, IE freaks out as described above.
*.toFront() and .toBack() - non-IE recognises the moved element as being the same element in the same X Y position, IE freaks out as described above.
There are some observations and demonstrations in this jsfiddle (read & uncomment the various comments).
A good workaround here, is to have some kind of flag like for example 'path.data( 'hoverIn', true );on mouse in and 'path.data( 'hoverIn', false ); on mouse out, then wrap any .toFront() or offending transforms in a check that !path.data( 'hoverIn' ) so that it can only happen once until the mouse out happens. Or, store a reference to the most recently hovered path somewhere after the toFront() or whatever, then don't toFront() or whatever if this path is also the most recently hovered one.
A: If you add a rect as a background underneath (and containing) the object you are trying to mouseout of, you can effectively get a mouseout effect by adding another hover event handler to the background rect.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600177",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: securing a WCF service for consumption by iphone I have a WCF service that needs to be secured to be consumed by an iphone app. I would like to know what my options are. I looked around the net and found that using SSL or api key or username/password over SSL is an option but I wasn't able to find any links about how to properly implement them for consumption by an iphone app. I'd really appreciate if someone could point me to the right direction.
A: Configure the WCF service for basicHttp binding and transport security. To make the client side of things work, you will need to implement an NSUrlConnection delegate. The phone will then be able to authenticate correctly. You can use the Keychain to store the user's credentials.
Stay away from the WS-* protocols that are typically turned on by wsHttp binding. These greatly increase the complexity of the XML you need to read and/or generate.
Although the phone can receive and send XML, it's not nearly as convenient as in .NET. You might want to consider a simpler serialization format such as JSON. This will require the use of webHttp binding.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600180",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Outlook Object Model - Hooking to the Conversation Cleanup Feature Outlook 2010 has a feature called Convesation Cleanup. This feature is implemented using the Conversation Header Outlook Object Model.
I would like to hook to this call and perform an action when triggered, yet I can't figure out how to catch it/hook on to it. Is anyone aware if this is possible? If its not, are you aware of any way around it? I have tried using outlook spy to view the event log when executing 'conversation cleanup' with no luck (nothing logged)... is there anyway of viewing deeper tracing of outlook events?
A: It turns out to be quite simple. The initial step is to obtain the idMso of the desired button to override. Microsoft provides a list of all the control ids for the Office suite however I found faster and more user friendly way of obtaining the idMso.
*
*Office Button/File -> Options -> Customize Ribbon -> Hover mouse on
desired command - idMso is displayed in brackets
Once we have the desired ids, we edit the Ribbon.xml by adding a set of commands to override the onAction/Enable settings of the button. See example bellow;
<?xml version="1.0" encoding="UTF-8"?>
<customUI xmlns="http://schemas.microsoft.com/office/2009/07/customui" onLoad="Ribbon_Load">
<commands>
<command idMso="IgnoreConversation" onAction ="FooRoutine" enabled="true"/>
</commands>
<ribbon>
</ribbon>
</customUI>
Last, we create the desired function on the Ribbon.vb which will be executed once the button is pressed.
I strongly suggest that you watch the 8 minute MSDN video where the steps above have been very well explained.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600181",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Design pattern import files alters behaviour I am developing an application where the program can do a number of operations. It relies on a XML file being imported and DB connection established. However, some of the functions can work without an xml file imported, and some can work only if the XML is imported or only if the DB is connected.
So, my question is what design pattern I should use in order to model this ? I read about the state pattern where an object's behaviour changes relative to the current state. Is this a good way of doing it ? For example, I can have several states : XML_FILE_IMPORTED_ONLY, DB_CONNECTED_ONLY, XML_IMPORTRED_AND_DB_CONNECTED, NOTHING_IMPORTED and based on the current state of the object relevant functions will be available ?
Any help will be much appreciated.
Regards,
Petar
A: You have two state machines, each controlling a portion of your overall state. Each state machine will perform transitions independent of the other.
XML Imported Statemachine
Initial state: Not Imported
*
*Not Imported. transitions: "import happens" -> Imported.
*Imported. transitions: "unload" -> Not Imported.
DB Connection Statemachine
Initial State: Not Connected
*
*Not Connected. transitions: "connect succeeded" -> Connected.
*Connected. transitions: "disconnect" -> Not Connected.
Edit: State machines are overkill for this problem.
The state machines in question each have two states with one transition in each direction. A much better way to represent this situation would be to use a boolean variable.
boolean dbConnected;
boolean xmlImported;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600182",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to use mod_rewrite to remove a query string withing a CMS I'm using a CMS that sends all requests to an index.php file using the following RewriteRule
RewriteRule .* index.php [L]
However in the news section of the site the CMS is generating news links like this: /news?month=201106
I want my news links like this: /news/month/201106 and I will achieve this with PHP code.
I know pretty much how to achieve the rewrite with Apache if it weren't for that catchall I would use something like this:
RewriteRule ^news/month/(.+)$ news?month=$1
However my problem is that the CMS is catching the calls and trying to find /news/month/201106 which it cannot and throws an CMS level 404
I've read up about making exceptions but I can't work out how to get:
*
*Apache to catch the rewrite before it gets sent to the catch all
*The CMS to then process the rewritten URL as normal (ie: receive news?month=201106 and process that as normal)
I'm sure this is probably down to the Rewrite flag and the order in which these directives are written but I just cannot get it to work.
A:
1) Apache to catch the rewrite before it gets sent to the catch all
You can do this by adding a RewriteCond before your RewriteRule .* index.php [L], so that it looks something like this:
RewriteCond %{REQUEST_URI} !^/news
RewriteRule .* index.php [L]
2) The CMS to then process the rewritten URL as normal (ie: receive news?month=201106 and process that as normal)
The 2nd rule that you had, RewriteRule ^news/month/(.+)$ news?month=$1 should take care of that.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600185",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: bash - determine a substring in one variable when an associated substring is known in another variable Assuming I had two strings, one acts a string of space delimited keys, and another acts as the associative space-delimited values for each of the keys in the first:
KEYS="key_1 key_2 key_3"
VALS="value1 aDifferentValue_2 theFinalValue"
So in this case, key_1 in $KEYS has an associated value of value1, key_2 had an associated value of aDifferentValue_2, and so on. Say the key in question was key_2, stored in variable $FIELD, what is the easiest way using sed and/or awk to find out that based off its word position, the value must be aDifferentValue_2? Is there a way to create an associative array using the substrings of $KEYS as the keys and $VALS as the values?
A: Since this is tagged bash, you can have actual associative arrays (bash v4):
KEYS="key_1 key_2 key_3"
VALS="value1 aDifferentValue_2 theFinalValue"
keys=( $KEYS )
vals=( $VALS )
declare -A map
for (( i=0; i<${#keys[@]}; i++ )); do
map["${keys[$i]}"]="${vals[$i]}"
done
for idx in "${!map[@]}"; do
echo "$idx -> ${map[$idx]}"
done
outputs
key_1 -> value1
key_2 -> aDifferentValue_2
key_3 -> theFinalValue
If you don't have bash v4, you can still use the keys and vals indexed arrays and:
get_key_idx() {
for (( i=0; i<${#keys[@]}; i++ )); do
if [[ "$key" = "${keys[$i]}" ]]; then
echo $i
return 0
fi
done
return 1
}
key="key_2"
if idx=$(get_key_idx $key); then
echo "$key -> ${vals[$idx]}"
else
echo "no mapping for $key"
fi
A: how about:
Variables:
/home/sirch>KEYS="key_1 key_2 key_3"
/home/sirch>VALS="value1 aDifferentValue_2 theFinalValue"
Code:
/home/sirch>cat s.awk
BEGIN{
split(keystring,key," ");
split(valstring,temp," ")
for(i=1;i<=length(key);i++)val[key[i]]=temp[i]
}
END{print val["key_2"]}
Output:
/home/sirch>awk -v "keystring=$KEYS" -v "valstring=$VALS" -v "query=key_02" -f s.awk f
aDifferentValue_2
At first the shell variables KEYS and VALS are set. Then they are exported to akw as strings.
These strings are then split on spaces, the resulting arrays saved in "key" and "temp". temp ist used to create the vinal hashmap "val". Now you can query for val["key_1"] etc. to get the corresponding value from the VALS-shell string.
To run this from a shell script, simply save the awk script to a file. Then set the shell variable query to your query string and call the awk-script from within your shell script with this variable. You will have give a dummy file, here "f", as argument to awk, to make this work.
HTH Chris
A: Pure POSIX shell:
#!/bin/sh
# set -x
assoc() {
keys="$1 "
values="$2 "
key=$3
while [ -n "$keys" -a -n "$values" ]; do
key_=${keys%% *}
keys=${keys#* }
value_=${values%% *}
values=${values#* }
if [ $key_ = $key ]; then
echo $value_
return 0
fi
done
return 1
}
keys='a b c'
values='1 2 3'
key=b
echo Value for key $key is _`assoc "$keys" "$values" "$key"`_
keys='a b c'
values='1 2 3'
key=xxx
echo Value for key $key is _`assoc "$keys" "$values" "$key"`_
keys='a b c'
values='1 2 3 4 5'
key=c
echo Value for key $key is _`assoc "$keys" "$values" "$key"`_
keys='a b c'
values='1 2'
key=c
echo Value for key $key is _`assoc "$keys" "$values" "$key"`_
When run:
bash# ./1.sh
Value for key b is _2_
Value for key xxx is __
Value for key c is _3_
Value for key c is __
A: Here's a bash-only alternative:
#!/bin/bash -x
KEYS="key_1 key_2 key_3"
VALS="value1 aDifferentValue_2 theFinalValue"
assoc() {
read fkey rkeys
read fval rvals
if [ "X$fkey" == "X$1" ] ; then echo $fval; exit 0; fi
if [ "X$rkeys" == "X" ] ; then exit 1; fi
echo -e "$rkeys\n$rvals" | assoc $1
}
echo -e "$KEYS\n$VALS" | assoc key_2
A: another AWK solution (maybe shorter?)
echo "$keys $vals"|awk '{t=NF/2;for(i=1;i<=t;i++)a[$i]=$(i+t);}{print a[KeyYouWANT]}'
test:
kent$ keys="key_1 key_2 key_3"
kent$ vals="value1 aDifferentValue_2 theFinalValue"
kent$ echo "$keys $vals"|awk '{t=NF/2;for(i=1;i<=t;i++)a[$i]=$(i+t);} END{print a["key_2"]}'
aDifferentValue_2
You could also put the keyStr you want in a variable
kent$ want=key_3
kent$ echo "$keys $vals"|awk -v x=$want '{t=NF/2;for(i=1;i<=t;i++)a[$i]=$(i+t);} END{print a[x]}'
theFinalValue
or you want to see a full list:
kent$ echo "$keys $vals"|awk '{t=NF/2;for(i=1;i<=t;i++)a[$i]=$(i+t);} END{for(x in a)print x,a[x]}'
key_1 value1
key_2 aDifferentValue_2
key_3 theFinalValue
A: Here's a sed solution:
keys="key_1 key_2 key_3" values="value_1 value_2 value_3" key="key_2" # variables used
str="$keys @@$values $key " # keys/values delimit by '@@' add key N.B. space after key!
sed -rn ':a;s/^(\S* )(.*@@)(\S* )(.*)/\2\4\1\3/;ta;s/^@@(\S* ).*\1(\S*).*/\2/p' <<<"$str"
# re-arrange keys/values into a lookup table then match on key using back reference
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600187",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Setting z-index in draggable start and stop events I want to fix this problem with the z-index of a draggable div. I have been setting the z-index to be around 99999. But this causes problems for other elements on the page. Instead of having a fixed z-index, it occurred to me that a better way could be to set the z-index in the draggable start and stop.
I have this code to do that.
$('#id').draggable({
start: function(event, ui) {
var $item = ui.draggable;
$item.css("z-index","999999");
},
stop: function(event, ui) {
var $item = ui.draggable;
$item.css("z-index","");
}
});
This should set the z-index when dragging starts, then set it to an empty string when dragging stops. But it doesn't do it. What could be wrong?
Someone suggested using the z-index for the ui-draggable-dragging class, but that did not fix the problem either.
.ui-draggable-dragging {
z-index:9999;
}
Is that class applied to the element automatically, must it be added in code?
A: The problem I was trying to fix is that the draggables did not go beyond the container. This happened because overflow was specified overflow:hidden. If I remove this, the code works.
A: Don't set it to an empty string. Set it to auto instead.
$(function(){ // Just to make sure we're clear, this must be here.
$('#id').draggable({
start: function(event, ui) {
$(this).css("z-index","999999");
},
stop: function(event, ui) {
$(this).css("z-index","auto");
}
});
});
This should, assuming everything else is proper, put it back to its natural z-index
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600188",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How can I get automatic dependency resolution in my scala scripts? I'm just learning scala coming out of the groovy/java world. My first script requires a 3rd party library TagSoup for XML/HTML parsing, and I'm loath to have to add it the old school way: that is, downloading TagSoup from its developer website, and then adding it to the class path.
Is there a way to resolve third party libraries in my scala scripts? I'm thinking Ivy, I'm thinking Grape.
Ideas?
The answer that worked best for me was to install n8:
curl https://raw.github.com/n8han/conscript/master/setup.sh | sh
cs harrah/xsbt --branch v0.11.0
Then I could import tagsoup fairly easily example.scala
/***
libraryDependencies ++= Seq(
"org.ccil.cowan.tagsoup" % "tagsoup" % "1.2.1"
)
*/
def getLocation(address:String) = {
...
}
And run using scalas:
scalas example.scala
Thanks for the help!
A: SBT (Simple Build Tool) seems to be the build tool of choice in the Scala world. It supports a number of different dependency resolution mechanisms: https://github.com/harrah/xsbt/wiki/Library-Management
A: Placed as an answer cause it doesn't fit in comment length constraint.
In addition to @Chris answer, I would like to recommend you some commons for sbt (which I personally think is absolutely superb). Although sbt denote Simple Build Tool, sometimes it is not so easy for first-timers to setup project with sbt (all this things with layouts, configs, and so on).
Use giter (g8) to create new project with predefined template (which g8 fetches from github.com). There are templates for Android app, unfiltered and more. Sometimes they are include some of the dependencies by default.
To create layout just type:
g8 gseitz/android-sbt-project
(An example for Android app)
Alternatively, use np pluggin for sbt, which provides interactive type-through way to create new project and basic layout.
A: A corrected and simplified version of the current main answer: use scalas.
You have to compose your script of 3 parts. One would be sbt, another would be a very simple wrapper around SBT called scalas, the last one is your custom script. Note that the first two scripts can be installed either globally (/usr/bin/, ~/bin/) or locally (in the same directory).
*
*the first part is sbt. If you already have it installed then good. If not, you can either install it, or use a very cool script from paulp: https://github.com/paulp/sbt-extras/blob/master/sbt BTW, that thing is a charming way to use sbt on Unix. Although not available on windows. Anyways...
*the second part is scalas. It's just an entrypoint to SBT.
#!/bin/sh
exec /path/to/sbt -Dsbt.main.class=sbt.ScriptMain -sbt-create \
-Dsbt.boot.directory=$HOME/.sbt/boot \
"$@"
*
*the last part is your custom script. Example:
#!/usr/bin/env scalas
/***
scalaVersion := "2.11.0"
libraryDependencies ++= Seq(
"org.joda" % "joda-convert" % "1.5",
"joda-time" % "joda-time" % "2.3"
)
*/
import org.joda.time._
println(DateTime.now())
//println(DateTime.now().minusHours(12).dayOfMonth())
A: While the answer is SBT, it could have been more helpful where scripts are regarded. See, SBT has a special thing for scripts, as described here. Once you get scalas installed, either by installing conscript and then running cs harrah/xsbt --branch v0.11.0, or simply by writing it yourself more or less like this:
#!/bin/sh
java -Dsbt.main.class=sbt.ScriptMain \
-Dsbt.boot.directory=/home/user/.sbt/boot \
-jar sbt-launch.jar "$@"
Then you can write your script like this:
#!/usr/bin/env scalas
!#
/***
scalaVersion := "2.9.1"
libraryDependencies ++= Seq(
"net.databinder" %% "dispatch-twitter" % "0.8.3",
"net.databinder" %% "dispatch-http" % "0.8.3"
)
*/
import dispatch.{ json, Http, Request }
import dispatch.twitter.Search
import json.{ Js, JsObject }
def process(param: JsObject) = {
val Search.text(txt) = param
val Search.from_user(usr) = param
val Search.created_at(time) = param
"(" + time + ")" + usr + ": " + txt
}
Http.x((Search("#scala") lang "en") ~> (_ map process foreach println))
You may also be interested in paulp's xsbtscript, which creates an xsbtscript shell that has the same thing as scalas (I guess the latter was based on the former), with the advantage that, without either conscript or sbt installed, you can get it ready with this:
curl https://raw.github.com/paulp/xsbtscript/master/setup.sh | sh
Note that it installs sbt and conscript.
And there's also paulp's sbt-extras, which is an alternative "sbt" command line, with more options. Note that it's still sbt, just the shell script that starts it is more intelligent.
A: What Daniel said. Although it's worth mentioning that the sbt docs carefully label this functionality "experimental".
Indeed, if you try to run the embedded script with scalaVersion := "2.10.3", you'll get not found: value !#
Luckily, the !# script header-closer is unnecessary here, so you can leave it out.
Under scalaVersion := "2.10.3", the script will need to have the file extension ".scala"; using the bash shell script file extension, ".sh", won't work.
Also, it isn't clear to me that the latest version of Dispatch (0.11.0) supports dispatch-twitter, which is used in the example.
For more about header-closers in this context, see Alvin Alexander's blog post on Scala scripting, or section 14.10 of his Scala Cookbook.
A: I have a build.gradle file with the following task:
task classpath(dependsOn: jar) << {
println "CLASSPATH=${tasks.jar.archivePath}:${configurations.runtime.asPath}"
}
Then, in my Scala script:
#!
script_dir=$(cd $(dirname "$0") >/dev/null; pwd -P)
classpath=$(cd ${script_dir} && ./gradlew classpath | grep '^CLASSPATH=' | sed -e 's|^CLASSPATH=||')
PATH=${SCALA_HOME}/bin:${PATH}
JAVA_OPTS="-Xmx4g -XX:MaxPermSize=1g" exec scala -classpath ${classpath} "$0" "$0" "$@"
!#
A: Note that we don't need a separate scalas executable in our PATH, since we can use the self-executing shell script trick.
Here's an example script, which reads its own content (via the $0 variable), chops off everything before an arbitrary marker (__BEGIN_SCRIPT__) and runs sbt on the result. We use process substitution to pretend this calculated content is a real file. One problem with this approach is that sbt will seek within the given file, i.e. it doesn't read it sequentially. That stops it working with the <(foo) form of process substitution, as found in bash; however zsh has a =(foo) form which is seekable.
#!/usr/bin/env zsh
set -e
# Find the line # in this file ($0) after the line beginning __BEGIN_SCRIPT__
LINENUM=$(awk '/^__BEGIN_SCRIPT__/ {print NR + 1; exit 0; }' "$0")
sbtRun() {
# Run the sbt command, such that it will fetch dependencies and execute a
# script
sbt -Dsbt.main.class=sbt.ScriptMain \
-sbt-create \
-Dsbt.boot.directory="$HOME/.sbt/boot" \
"$@"
}
# Run SBT on the contents of this file, starting at LINENUM
sbtRun =(tail -n+"$LINENUM" "$0")
exit 0
__BEGIN_SCRIPT__
/***
scalaVersion := "2.11.0"
libraryDependencies ++= Seq(
"org.joda" % "joda-convert" % "1.5",
"joda-time" % "joda-time" % "2.3"
)
*/
import org.joda.time._
println(DateTime.now())
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600189",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: BlackBerry - JavaLoader error when using the "screencapture" option
Possible Duplicate:
BlackBerry screen shot utility - from a desktop computer
I am attempting to use the JavaLoader tool to capture some screen shots of my Tourch 9850 ... the built-in screencapture cammand. I receive the following error:
"Retrieving screen data ... Error: buffer too small".
Any idea on how to address this error?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600190",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Delphi Memory Issue (FastMM4) Working on a project which uses factories to construct objects. I keep the pointers to the factory functions in vars globally (bad I know) and register them on initialization.
I recently was interested in seeing if the project had memory leaks so decided to download FastMM4 and have a look through. It came up with a few errors that I could fix but this one I'm a bit stumped on seems by me not freeing the memory related to the factory as shown in the code below I'm getting a small memory leak. Not ridiculous but annoying nevertheless.
What would I use to free the memory (if it is that) i've tried dispose(@factoryfunction) but seems to mangle everything. I'm not too good with low level pointer stuff always confuses the hell out of me so if someone could help that would be great.
I've included an example below that i've just written off the top of my head that illustrates the problem I'm having.
Cheers,
Barry
unit Test;
interface
uses classes;
type
TAFactoryFunction = reference to function (const aType : integer): TObject;
function testfunction (const aType : integer) : TObject;
implementation
function testfunction(const aType: integer) : TObject;
begin
result := TObject.Create;
end;
var
FactoryFunction : TAFactoryFunction
initialization
FactoryFunction := testfunction;
finalization
// possibly some freemem code here?
end.
A: I just tested this in Delphi 2010 and it appears to be a bug. The compiler should generate code to clean that up, but it isn't. Even writing FactoryFunction := nil, as David suggested, doesn't work.
You should report this in QC as an error.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600206",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: JSF multiple @ViewScoped and @ManagedBeans on same page results in null injection I have two classes as follows:
@ManagedBean( name = "randomBar")
@ViewScoped
public class Soap
{
private List<Cat> cats;
//getter/setter pair
}
@ManagedBean ( name = "marioPaint")
@ViewScoped
public class House
{
@ManagedProperty(value= "#{randomBar}")
private Soap soap
//getter/setter pair
...
public void printCatInformation()
{
System.out.println(soap.getCats()); //null
}
These are both on the same page. The Soap object is able to print to console it's size while House is unable to get anything beyond a null pointer. My question is how do I send that information back to the instance of Soap that is present inside of House?
Update:
This is running on Oracle 10.3.4 with Icefaces 2.0 (Mojarra).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600210",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Custom UINavigationController I'm beginner in IOS
I'm try create custom animation for UINavigationController
Tell me please Apple reject this code or not????
CATransition *transition = [CATransition animation];
transition.duration = 0.5;
transition.timingFunction = [CAMediaTimingFunction functionWithName:kCAMediaTimingFunctionEaseInEaseOut];
transition.type = kCATransitionReveal;
transition.subtype = kCATransitionFromBottom;
transition.delegate = self;
[self.navigationController.view.layer addAnimation:transition forKey:nil];
self.navigationController.navigationBarHidden = NO;
[self.navigationController pushViewController:myViewcontroller animated:NO];
Thanks!
A: like Mike said in his comment: please ask apple and/or take a look at the iOS App-Store-Review-Guidlines (if you dont have a developer-account: google for app store review guidlines )
A: If you are not using any private framework, you are not inheriting the control that apple does not allow to inherit (go to documentation of control you want to customize) you can certainly go and change it.
Now here comes the user experience, apple put a lot of efforts in making the user experience uniform so as far as you are not competing with apple they will be happy to approve your application.
I have seen my initial application got rejected many a time in initial days but now a days they do not put so many specs to dig into the code or other (my belief from the approval speed).
In case of navigation controller I believe you can go and customize it as par your need.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600211",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: Use custom ASP.NET MVC IValueProvider, without setting it globally? I want to be able to grab keys/values from a cookie and use that to bind a model.
Rather than building a custom ModelBinder, I believe that the DefaultModelBinder works well out of the box, and the best way to choose where the values come from would be to set the IValueProvider that it uses.
To do this I don't want to create a custom ValueProviderFactory and bind it globally, because I only want this ValueProvider to be used in a specific action method.
I've built an attribute that does this:
/// <summary>
/// Replaces the current value provider with the specified value provider
/// </summary>
[AttributeUsage(AttributeTargets.Method | AttributeTargets.Class, Inherited = true, AllowMultiple = true)]
public class SetValueProviderAttribute : ActionFilterAttribute
{
public SetValueProviderAttribute(Type valueProviderType)
{
if (valueProviderType.GetInterface(typeof(IValueProvider).Name) == null)
throw new ArgumentException("Type " + valueProviderType + " must implement interface IValueProvider.", "valueProviderType");
_ValueProviderType = valueProviderType;
}
private Type _ValueProviderType;
public override void OnActionExecuting(ActionExecutingContext filterContext)
{
IValueProvider valueProviderToAdd = GetValueProviderToAdd();
filterContext.Controller.ValueProvider = valueProviderToAdd;
}
private IValueProvider GetValueProviderToAdd()
{
return (IValueProvider)Activator.CreateInstance(_ValueProviderType);
}
}
Unfortunately, the ModelBinder and its IValueProvider are set BEFORE OnActionExecuting (why?????). Has anyone else figured out a way to inject a custom IValueProvider into the DefaultModelBinder without using the ValueProviderFactory?
A: Here is an alternative that lets you specify IValueProviders as attributes against an actions parameters.
This makes the IValueProviders transient and not Global.
public interface IControllerContextAware
{
ControllerContext ControllerContext { get; set; }
}
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Struct | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Parameter, AllowMultiple = false, Inherited = false)]
public class ValueProviderAttribute : CustomModelBinderAttribute
{
public Type[] ValueProviders { get; private set; }
public ValueProviderAttribute(params Type[] valueProviders)
{
if (valueProviders == null)
{
throw new ArgumentNullException("valueProviders");
}
foreach (var valueProvider in valueProviders.Where(valueProvider => !typeof(IValueProvider).IsAssignableFrom(valueProvider)))
{
throw new ArgumentException(string.Format(CultureInfo.CurrentCulture, "The valueProvider {0} must be of type {1}", valueProvider.FullName, typeof(IValueProvider)), "valueProviders");
}
ValueProviders = valueProviders;
}
public override IModelBinder GetBinder()
{
return new ValueProviderModelBinder
{
ValueProviderTypes = ValueProviders.ToList(),
CreateValueProvider = OnCreateValueProvider
};
}
protected virtual IValueProvider OnCreateValueProvider(Type valueProviderType, ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var valueProvider = (IValueProvider)Activator.CreateInstance(valueProviderType);
if (valueProvider is IControllerContextAware)
{
(valueProvider as IControllerContextAware).ControllerContext = controllerContext;
}
return valueProvider;
}
private class ValueProviderModelBinder : DefaultModelBinder
{
public IList<Type> ValueProviderTypes { get; set; }
public Func<Type, ControllerContext, ModelBindingContext, IValueProvider> CreateValueProvider { get; set; }
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
var valueProviders = from type in ValueProviderTypes
select CreateValueProvider(type, controllerContext, bindingContext);
bindingContext.ValueProvider = new ValueProviderCollection(valueProviders.Concat((Collection<IValueProvider>)bindingContext.ValueProvider).ToList());
return base.BindModel(controllerContext, bindingContext);
}
}
}
This is basically the code form the ModelBinderAttribute, but with a few tweaks.
It isn't sealed and so you can alter the way in which the IValueProviders are created if need be.
Here is a simple example which looks in another field, possibly a hidden or encrypted field, and takes the data and puts it into another property.
Here is the model, which has no knowledge of the IValueProvider, but does know about the hidden field.
public class SomeModel
{
[Required]
public string MyString { get; set; }
[Required]
public string MyOtherString { get; set; }
[Required]
public string Data { get; set; }
}
THen we have the IValueProvider, in this case, my provider knows explicitly about my model, but this doesn't have to be the case.
public class MyValueProvider : IValueProvider, IControllerContextAware
{
public ControllerContext ControllerContext { get; set; }
public bool ContainsPrefix(string prefix)
{
var containsPrefix = prefix == "MyString" && ControllerContext.HttpContext.Request.Params.AllKeys.Any(key => key == "Data");
return containsPrefix;
}
public ValueProviderResult GetValue(string key)
{
if (key == "MyString")
{
var data = ControllerContext.RequestContext.HttpContext.Request.Params["Data"];
var myString = data.Split(':')[1];
return new ValueProviderResult(myString, myString, CultureInfo.CurrentCulture);
}
return null;
}
}
and then the action that ties all this together:
[HttpGet]
public ActionResult Test()
{
return View(new SomeModel());
}
[HttpPost]
public ActionResult Test([ValueProvider(typeof(MyValueProvider))]SomeModel model)
{
return View(model);
}
A: Figured out how to do this. First, create a custom model binder that takes a value provider type in the constructor - but inherits from default modelbinder. This allows you to use standard model binding with a custom value provider:
/// <summary>
/// Uses default model binding, but sets the value provider it uses
/// </summary>
public class SetValueProviderDefaultModelBinder : DefaultModelBinder
{
private Type _ValueProviderType;
public SetValueProviderDefaultModelBinder(Type valueProviderType)
{
if (valueProviderType.GetInterface(typeof(IValueProvider).Name) == null)
throw new ArgumentException("Type " + valueProviderType + " must implement interface IValueProvider.", "valueProviderType");
_ValueProviderType = valueProviderType;
}
/// <summary>
/// Before binding the model, set the IValueProvider it uses
/// </summary>
public override object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
{
bindingContext.ValueProvider = GetValueProvider();
return base.BindModel(controllerContext, bindingContext);
}
private IValueProvider GetValueProvider()
{
return (IValueProvider)Activator.CreateInstance(_ValueProviderType);
}
}
Then we create a model binding attribute that will inject the value provider type in the custom model binder created above, and use that as the model binder:
/// <summary>
/// On the default model binder, replaces the current value provider with the specified value provider. Cannot use custom model binder with this.
[AttributeUsage(AttributeTargets.Class | AttributeTargets.Class | AttributeTargets.Enum | AttributeTargets.Interface | AttributeTargets.Parameter | AttributeTargets.Struct, AllowMultiple = false, Inherited = false)]
public class SetValueProviderAttribute : CustomModelBinderAttribute
{
// Originally, this was an action filter, that OnActionExecuting, set the controller's IValueProvider, expecting it to be picked up by the default model binder
// when binding the model. Unfortunately, OnActionExecuting occurs AFTER the IValueProvider is set on the DefaultModelBinder. The only way around this is
// to create a custom model binder that inherits from DefaultModelBinder, and in its BindModel method set the ValueProvider and then do the standard model binding.
public SetValueProviderAttribute(Type valueProviderType)
{
if (valueProviderType.GetInterface(typeof(IValueProvider).Name) == null)
throw new ArgumentException("Type " + valueProviderType + " must implement interface IValueProvider.", "valueProviderType");
_ValueProviderType = valueProviderType;
}
private Type _ValueProviderType;
public override IModelBinder GetBinder()
{
var modelBinder = new SetValueProviderDefaultModelBinder(_ValueProviderType);
return modelBinder;
}
}
A: You should still use a ValueProviderFactory in this case.
The method that you have to implement on your ValueProviderFactory has this signature:
IValueProvider GetValueProvider(ControllerContext controllerContext)
Within your implementation of that method you can inspect the controller context, and if the incoming request is for the controller/action that you want to leverage cookies on, return some CustomCookieValueProvider.
If you don't want to leverage cookies for the request, just return null and the framework will filter that out of from the list of Value Providers.
As a bonus, you might not want to hard code the logic for when to use the CustomCookieValueProvider into the ValueProviderFactory. You could, perhaps, leverage DataTokens to match when to use cookies with given routes. So add a route like this:
routes.MapRoute("SomeRoute","{controller}/{action}").DataTokens.Add("UseCookies", true);
Notice the DataTokens.Add() call in there, now inside you GetValueProvider method you could do something like this:
if (controllerContext.RouteData.DataTokens.ContainsKey("UseCookies"))
{
return new CustomCookieValueProvider(controllerContext.RequestContext.HttpContext.Request.Cookies);
}
return null;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600212",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: add link of custom module to user dashboard magento can someone tell me how to add a link of custom module to user dashbord left navigation in magento. I tried to add
<customer_account>
<reference name="left">
<block type="customer/account_navigation" name="customer_account_navigation" before="-" template="customer/account/navigation.phtml">
<action method="addLink" translate="label" module="customer">
<name>account_view</name>
<path>customer/account/view/</path>
<label>Account Details</label>
</action>
</block>
</reference>
</customer_account>
in my layout xml file but it is not working
thanks
A: Try this:
<customer_account>
<reference name="customer_account_navigation">
<action method="addLink" translate="label" module="customer">
<name>yournamespace_yourmodule</name>
<path>module/controller/action</path>
<label>Label</label>
</action>
</reference>
</customer_account>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600219",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: User CRUD in web application that handles registration and login with Devise I am currently working on application that is build on rails 3.0.9. All of a sudden the client decided that there should be a place to create a user and edit a user in the admin section of the website.
Now here is the case. The authentication and registration in the web application is handled by devise. If I try to implement a custom USER create method in my controller how should I hash the password in the very same way devise is doing so that I can store that in the database. This also applies to editing the already registered users as well.
I have tried to find the solution but no use. Any help in resolving this would be appreciated.
A: That's easy. You can setup another controller and form but set it up on your User model. Your form will need to include :email, :password, and :password_confirmation. When you do @user.save in your controller's create action, this will have devise take care of all the hashing requirements under the hood.
If you want to check that your save works (just for testing), add a bang at the end like @user.save! - this is only for testing. Either drop into rails console and you can see the newly added records or tail your log file.
Editing should work along the same lines and you can do @user.update_attribute() in your edit action, or @user.update_attributes() if you prefer mass assignment (this will be subject to any attr_accessible restrictions in your model)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600220",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: decrypt function - not showing readable string I have created this function for decrypt a password and its working but is showing strange characters like this ��5d[���������. I'm using oracle xe 10g
create or replace
function decrypt (val VARCHAR) return varchar2 is
input_string varchar2(2048) := val;
key_string VARCHAR2(10) := 'xpto';
decrypted_string VARCHAR2(2048);
begin
dbms_output.put_line(input_string);
dbms_obfuscation_toolkit.DESDecrypt(
input_string => input_string,
key_string => key_string,
decrypted_string => decrypted_string );
dbms_output.put_line('> decrypted string output : ' || decrypted_string);
return decrypted_string;
end;
What i'm i doing wrong it should appear a readable string.
A: *
*Why would you need to decode a password? Why not store it hashed?
*There are a few constraints with the size of the input string and the key size as well (explained in the online doc).
Here's a working example with Oracle 10.2.0.3:
SQL> VARIABLE v_in VARCHAR2(64);
SQL> VARIABLE v_enc VARCHAR2(64);
SQL> VARIABLE v_out VARCHAR2(64);
SQL> DECLARE
2 l_key VARCHAR2(8) := rpad('my_key', 8, 'x'); -- 64-bit key
3 BEGIN
4 -- input size must be a multiple of 8 bytes
5 :v_in := '12345678';
6 :v_enc := dbms_obfuscation_toolkit.desEncrypt(input_string => :v_in,
7 key_string => l_key);
8 :v_out := dbms_obfuscation_toolkit.desDecrypt(input_string => :v_enc,
9 key_string => l_key);
10 END;
11 /
PL/SQL procedure successfully completed
v_in
---------
12345678
v_enc
---------
þæHI«Ó¹-
v_out
---------
12345678
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600221",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Rails 3.0.9 Model attributes are lost on database query If i open the console and type in the following code, my model looses attributes. In all cases only the first attribute after the id is accessable. I had this problem on one server. My old server is working fine with the same code and same versions. Here the output:
irb(main):001:0> User.new
=> #<User id: nil, encrypted_uid: nil, encrypted_access_token: nil, created_at: nil, updated_at: nil>
irb(main):002:0> User.first
=> #<User id: 1, encrypted_uid: "I7lPHOYoGMNWki3cZtb5oA==\n">
ActiveModel::MissingAttributeError (missing attribute: encrypted_access_token):
Has anyone an idea to get it working? Thanks in advance.
A: I had to recreate the application and copy the model into hte new application. after that everything worked fine. No clue what was wrong.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600222",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to delete cache programmatically? I want to delete the cache files in my application programmatically.
How do i go about doing this in code?
I want to launch a service (which i already have set up to do this).
FYI - IDK why my acceptance rate is low. Ive accepted most or all of my answers.
A: I assume you're talking about the Context's cache directory?
This is one way:
File cacheDir = context.getCacheDir();
File[] files = cacheDir.listFiles();
if (files != null) {
for (File file : files)
file.delete();
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600228",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: iphone voip application exit code I'm implementing a voip application but I'm having a small problem with autorestart:
- the app is automatically started when the device is turned on
BUT:
- the app does not restart after the user kills it from the bottom bar.
Am I doing something wrong, or is there any way to force it to autorestart ? Or maybe a way to set the exit code ?
Thanks.
'code'
[window addSubview:mainViewController.view];
[window makeKeyAndVisible];
g_mainApp = self;
_site = false;
[StoreManager sharedManager];
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(handlePayment:) name: kProductFetchedNotification object: nil];
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(handlePayment:) name: kInAppPurchaseManagerBuyNotification object: nil];
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(handlePayment:) name: kInAppPurchaseManagerTransactionFailedNotification object: nil];
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(handlePayment:) name: kInAppPurchaseManagerTransactionSucceededNotification object: nil];
[[NSNotificationCenter defaultCenter] addObserver: self selector: @selector(handlePayment:) name: kInAppPurchaseManagerTransactionCanceledNotification object: nil];
[mainViewController FirstInit];
int cnt = 0;
while (cnt < 140)
{
if ([mainViewController GetConnex] != 0)
break;
[mainViewController Update];
[NSThread sleepForTimeInterval:0.1];
cnt++;
}
return YES;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600229",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How i can get hit test with image on canvas? I create image in this way:
var orc = new Image();
orc.src = "./orc.png";
I use image in objects like this:
function Character(hp, image){
this.hp = hp;
this.image = image;
};
I call it in several times, like:
unit245 = new Character(100, orc);
And I draw it in this way, for example:
ctx.drawImage(unit245.image, 15, 55, 100, 100);
How I can get mouse click or move above my unit245 on canvas?
I need something like this http://easeljs.com/examples/dragAndDrop.html but without any frameworks (except jquery)
A: There is no built in way. I've written a few tutorials on making movable and selectable shapes on a Canvas to help people get started with this sort of thing though.
In short you need to remember what you have drawn and where, and then check each mouse click to see if you have clicked on something.
A: HitTesting can be done by checking what is present at the current location over the canvas, which can be called upon mouse click or move event over the canvas (which is the basis of hit testing). This can be done by knowing what has been placed where, like the bounds of an image can be saved, and when user clicks somewhere or moved the mouse over the canvas, you can check whether it is inside the image bounds or outside it. Array or List can be used for this.
Here is how this can be done
A: You cannot. The canvas has no semblance of what your unit245 or Character object is. You will have to actually manually check the coordinates and see if they fall within the bounds that you have for the character.
For example (assuming your Canvas is a var named canvas):
canvas.onclick = function(e) {
if (e.x >= unit245.x && e.x <= unit245.x + unit245.width && e.y >= unit245.y && e.y <= unit245.y + unit245.height) {
alert("You clicked unit245!");
}
}
In your case:
unit245.x = 15
unit245.y = 55
unit245.width = 100
unit245.height = 100
A: function Item(img, x, y){
this.image = img;
this.x = x;
this.y = y;
this.canv = document.createElement("canvas");
this.canv.width = this.image.width;
this.canv.height = this.image.height;
this.ctx = this.canv.getContext('2d');
this.ctx.drawImage(this.image, 0, 0, CELL_SIZE, CELL_SIZE);
this.hit = function (mx, my) {
var clr;
clr = this.ctx.getImageData(mx - this.x, my - this.y, 1, 1).data;
if (clr[3] > 250) {
//On object
this.image = gold_glow;
} else {
//Leave object
this.image = gold;
}
};
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600231",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Getting the endpoints of sets across a range For the life of me, I can't see how to do this. I need to collect the non-overlapping endpoints of several sets within a range of numbers with python.
For example the user could input a range of 10 and two sets 2 and 3. I need to get the end points of these sets within this range such that:
set 2 groupings: 1-2,6-7
set 3 groupings: 3-5,8-10
The range, number of sets, and size of any individual set is arbitrary. I cannot fall outside the range, so no half sets.
I keep thinking there should be a simple formula for this, but I can't come up with it.
Edit
As requested for an example input of range 12, and sets 1, 2, and 3 the output should be:
set 1: 1,7
set 2: 2-3,8-9
set 3: 4-6,10-12
As near as I can figure, I'm looking at some kind of accumulator pattern. Something like this psuedo code:
for each miniRange in range:
for each set in sets:
listOfCurrSetEndpoints.append((start, end))
A: I don't think there's a good built-in solution to this. (It would be easier if there were a built-in equivalent to Haskell's scan function.) But this is concise enough:
>>> import itertools
>>> from collections import defaultdict
>>> partition_lengths = [1, 2, 3]
>>> range_start = 1
>>> range_end = 12
>>> endpoints = defaultdict(list)
>>> for p_len in itertools.cycle(partition_lengths):
... end = range_start + p_len - 1
... if end > range_end: break
... endpoints[p_len].append((range_start, end))
... range_start += p_len
...
>>> endpoints
defaultdict(<type 'list'>, {1: [(1, 1), (7, 7)], 2: [(2, 3), (8, 9)], 3: [(4, 6), (10, 12)]})
You can now format the endpoints dictionary for output however you like.
As an aside, I'm really confused by your use of "set" in this question, which is why I used "partition" instead.
A: I'm not exactly happy with it, but I did get a working program. If someone can come up with a better answer, I'll be happy to accept it instead.
import argparse, sys
if __name__ == "__main__":
parser = argparse.ArgumentParser(description='Take a number of pages, and the pages in several sets, to produce an output for copy and paste into the print file downloader', version='%(prog)s 2.0')
parser.add_argument('pages', type=int, help='Total number of pages to break into sets')
parser.add_argument('stapleset', nargs='+', type=int, help='number of pages in each set')
args = parser.parse_args()
data = {}
for c,s in enumerate(args.stapleset):
data[c] = []
currPage = 0
while currPage <= args.pages:
for c,s in enumerate(args.stapleset):
if currPage + 1 > args.pages:
pass
elif currPage + s > args.pages:
data[c].append((currPage+1,args.pages))
else:
data[c].append((currPage+1,currPage+s))
currPage = currPage + s
for key in sorted(data.iterkeys()):
for c,t in enumerate(data[key]):
if c > 0:
sys.stdout.write(",")
sys.stdout.write("{0}-{1}".format(t[0],t[1]))
sys.stdout.write("\n\n")
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7600235",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.