text
stringlengths 8
267k
| meta
dict |
|---|---|
Q: Will Widget Support in WP7? I want to develop an application for WP7 using HTML,CSS and Javascript something Similar to Nokia WRT(Web Widget) Will this Support in WP7? .Will the app require signing ? Can I use Metro style for WP7?
A: Windows Phone 7 (and 7.5) applications are written either using the XNA framework (for gaming style applications) or Silverlight (for "apps"). Windows Mobile 6.5 (and prior) have applications either using the compact edition of WinForms, or using embedded C++.
The current design guide for the Silverlight applications for Windows Mobile 7.x is virtually identical to that for Metro on Windows 8 (there are even a bunch of controls to help you out).
As for using a HTML/CSS/JS application; it may work in browser, but I'm not aware of any ways to (nor plans to allow) distribute apps of this type to Windows Mobile 7.x devices.
A: There's no support for widgets but you may be interested in PhoneGap as that now has beta support for WP7 and is similar to web widgets.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593852",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Will Facebook migration affect my application? I have a Facebook application installed on a Facebook fan page which is a tab that displays a flash banner.
That is all. I am installing SSL on my domain. Do I need to change anything else? Should I update to OAuth 2.0 or that is not necessary for such a tab?
A: There should be no other changes based on SSL: as long as you configure your application's secure URL correctly, everything else should be the same.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593855",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Passing NSMutableArray between classes with method Okay, so i hope im on the right track with this.
So this is my first class's .h file, im just declaring the method here:
-(NSMutableArray *)get;
Now lets jump into the .m file of that first class, this is the method:
-(NSMutableArray *)get {
return testArray;
}
I have a NSMutableArray called testArray, it is filled with 2 NSStrings.
I need to pass that array along to my next class
Of course in the next class i import first class.
Now i need to get the value of testArray in the second class. here is what im doing (not even sure if im doing it right)
True_FalseViewController *controller = [[True_FalseViewController alloc]init];
NSMutableArray *array = [[NSMutableArray alloc]init];
[controller get]; //here i call the method
NSLog(@"%d", array.count);
NSLog(@"%@", array);
What do i do from here?
The method returns a NSMutableArray, but i have no idea to get it into the other array called array.
Thanks for any help you can give,
Jacob
A: Why do not you save return value in array? :
NSMutableArray *array = [controller get];
And that's all.
A: array = [[NSMutableArray alloc] initWithArray:[controller Get]];
A: Are you initializing (alloc + init) the testArray in your first class .m??
A: Have you checked if the testArray from the first class has a value before you return it?
Try to check if testArray has some value:
NSLog(@"%@",testArray);
It's possible that your testArray doesn't have any value to return in the first place.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593866",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: android editText is cursor visible? Is there any way to know if on a edit text is visible or not the cursor? I need to know so I can adapt a delete method. Thanks
A:
public static final int getSelectionStart (CharSequence text) Since:
API Level 1
Return the offset of the selection anchor or cursor, or -1 if there is
no selection or cursor.
So if it returns -1 you know there is no cursor.
EDIT:
editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
@Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
// cursor visible!!!
}
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593871",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: key search in php multidimensional associative array $array = array(
'the-1'=> array('name'=>'lorem','pos'=>array('top'=>'90','left'=>'80'),'zindex'=>2),
'the-2'=> array('name'=>'ipsum','pos'=>array('top'=>'190','left'=>'180'),'zindex'=>1),
'the-3'=> array('name'=>'lorem ipsum','pos'=>array('top'=>'20','left'=>'30'),'zindex'=>3)
);
How to check zindex key exist in above php array.
A: You have a method called array_key_exists for that. Of course you need to do some (recursive) looping if you don't know how deep the array with the value is located.
A: Maybe you should thing on using array_walk_recursive function in this way
<?php
$sweet = array('a' => 'apple', 'b' => 'banana');
$fruits = array('sweet' => $sweet, 'sour' => 'lemon');
function test_print($item, $key)
{
echo "$key holds $item\n";
}
array_walk_recursive($fruits, 'test_print');
?>
this is just a print example taken from php.net, but easily you can adapt it to fit your needs (adding the array_key_exist in the callback function, for example)
A: I'm not completely sure what you're wanting here, so here are a variety of tests you can run on zindex. These all use a foreach loop and array_key_exists.
If you want to check each item in the outer array to see if it has a zindex:
This loops through each element, and simply checks to see if the element has a zindex key of some sort.
foreach( $array as $key => $element ) {
if( array_key_exists('zindex',$element) ) {
echo "Key '$key' has a zindex of ".$element['zindex']."\n<br>\n";
} else {
echo "Fail!! Key '$key' has no zindex!\n<br>\n";
}
}
If you are just looking for there to be any zindex key at all:
This loops through until it finds an element that has a zindex. If a zindex is found, the function returns true, otherwise it returns false.
function find_zindex( $array ) {
foreach( $array as $key => $element ) {
if( array_key_exists('zindex',$element) ) {
echo "Key '$key' has a zindex of ".$element['zindex']."\n<br>\n";
return true;
}
}
return false;
}
if( find_zindex( $array ) ) {
echo "A zindex was found\n<br>\n";
} else {
echo "Fail: no zindex was found\n<br>\n";
}
If you're looking for a particular zindex value in your array:
This loops through, looking for a particular zindex that has a particular value. If it is found, then the key for the outside array is returned. Otherwise null is returned.
function find_zindex( $array, $search_key ) {
foreach( $array as $key => $element ) {
if( array_key_exists('zindex',$element) && $element['zindex']==$search_key ) {
echo "Key '$key' has a zindex of ".$element['zindex']."\n<br>\n";
return $key;
}
}
return null;
}
$key = find_zindex( $array, 3 );
if( $key ) {
echo "The zindex was found at '$key'\n<br>\n";
} else {
echo "Fail: the zindex was not found\n<br>\n";
}
$key = find_zindex( $array, 4 );
if( $key ) {
echo "The zindex was found at '$key'\n<br>\n";
} else {
echo "Fail: the zindex was not found\n<br>\n";
}
If you want an array of every key that has a particular zindex:
This loops through, building an array that contains every element that matches the supplied zindex search value. When done, it returns the new array of elements. If nothing is found, it returns an empty array that will test as false.
function find_zindex( $array, $search_key ) {
$result = array();
foreach( $array as $key => $element ) {
if( array_key_exists('zindex',$element) && $element['zindex']==$search_key ) {
echo "Key '$key' has a zindex of ".$element['zindex']."\n<br>\n";
$result[] = $key;
}
}
return $result;
}
$key = find_zindex( $array, 3 );
if( $key ) {
echo 'The zindex was found at:';
print_r( $key );
echo "\n<br>\n";
} else {
echo "Fail: the zindex was not found\n<br>\n";
}
$key = find_zindex( $array, 4 );
if( $key ) {
echo 'The zindex was found at:';
print_r( $key );
echo "\n<br>\n";
} else {
echo "Fail: the zindex was not found\n<br>\n";
}
If you are often trying to find data by the zindex, you will want to redesign your array:
This creates a second array that just has references to the elements in the first array. If you run this, you can see that the data is shared because the one assignment will set 'name' to 'new_name' in both arrays. Notice that each element of the outer array now has both an index and a zindex.
This assumes every element in $array has a zindex and the value of the zindex is unique. If some elements don't have a zindex or have duplicate zindexes, then you will need to modify this some.
$array = array(
'the-1'=> array('name'=>'lorem','pos'=>array('top'=>'90','left'=>'80'),'index'=>'the-1','zindex'=>2),
'the-2'=> array('name'=>'ipsum','pos'=>array('top'=>'190','left'=>'180'),'index'=>'the-2','zindex'=>1),
'the-3'=> array('name'=>'lorem ipsum','pos'=>array('top'=>'20','left'=>'30'),'index'=>'the-3','zindex'=>3)
);
$zarray = array();
foreach( $array as &$value ) {
$zarray[$value['zindex']] =& $value;
}
// optional: order the entries in zarray by their key
ksort($zarray)
print_r($array);
echo "\n<br>\n";
print_r($zarray);
echo "\n<br>\n<br>\n<br>\n<br>\n<br>\n";
$array['the-1']['name']='new_name';
print_r($array);
echo "\n<br>\n";
print_r($zarray);
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593872",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: PHP regexp for checking letters except W, w, P, p I need a regexp pattern, that checks if string contains letters excepting W, w, P, p.
$pattern = ''; // I need this pattern
preg_match($pattern, '123123'); // false
preg_match($pattern, '123123a'); // true
preg_match($pattern, '123123W'); // false
preg_match($pattern, '123123w'); // false
preg_match($pattern, '123123P'); // false
preg_match($pattern, '123123p'); // false
preg_match($pattern, '123123WwPp'); // false
preg_match($pattern, 'abcWwPp'); // true
preg_match($pattern, 'abc'); // true
Thank you in advance.
A: If you only care for ASCII letters, check for
[^\W\d_WP]
and make the search case-insensitive:
preg_match('/[^\W\d_WP]/i', $subject)
[^\W\d_WP] matches a character that is alphanumeric, substracting digits, underscore, W and P from the list of allowed characters. [^\W] looks counterintuitive since it means "not a non-alphanumeric character", but that double negative pays off because I can then substract other characters from the result.
If you care about Unicode letters, use
preg_match('/[^\PLWP]/iu', $subject)
\PL matches any character that is not a Unicode letter (opposite of \pL)
A: Search for the range outside of w and p - like this
/[a-oq-vx-z]/i
Note the i at the end for case insensitive
A: This is not an answer but a little program to check Tim Pietzcker expression: it works according to the test provided by Billy.
<?php
error_reporting(E_ALL);
$pattern = '/[^\W\d_WP]/i';
assert(!preg_match($pattern, '123123'));
assert(preg_match($pattern, '123123a'));
assert(!preg_match($pattern, '123123W'));
assert(!preg_match($pattern, '123123w'));
assert(!preg_match($pattern, '123123P'));
assert(!preg_match($pattern, '123123p'));
assert(!preg_match($pattern, '123123WwPp'));
assert(preg_match($pattern, 'abcWwPp'));
assert(preg_match($pattern, 'abc'));
?>
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593873",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Screen orientation in tablet I am using the same code for both tablets and mobile, and I want to write an app for Xlarge screens with landscape. I wrote one condition but when I am rotating into portrait it generates an exception.
I have declared the condition:
final boolean isPortrait = getResources().getConfiguration().orientation ==Configuration.ORIENTATION_PORTRAIT;
I want code with if else condition using xlarge and landscape orientations but it should work for only tablets but while coming to mobile it should not work.
A: There are two methods to make an application full screen. The first simply states the application supports a specific dpi. The following code in the Manifest supports all dpis.
<supports-screens android:smallScreens="true"
android:normalScreens="true"
android:largeScreens="true"
android:xlargeScreens="true"
android:anyDensity="true" />
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593877",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Validation in MVP pattern I am creating a program which utilizes MVP architecture. Please tell me which is the best place to write the validation. Someone told me that the code in presenter should only contains logic to handle events raised from the GUI and format values collected from the model so that view can display values without any overhear. Is this correct?
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593882",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Disable auto focus on edit text I have an edit text:
<LinearLayout android:id="@+id/linearLayout7" android:layout_width="match_parent" android:layout_height="wrap_content">
<EditText android:layout_height="wrap_content" android:layout_width="wrap_content" android:layout_weight="1" android:id="@+id/editText1" android:text="3">
<requestFocus></requestFocus>
</EditText>
<Button android:text="Button" android:layout_height="wrap_content" android:layout_width="wrap_content" android:id="@+id/button2"></Button>
</LinearLayout>
and then some other stuff underneath
The problem I'm having is that right when the app starts the focus is on the input, i dont want focus to be on input right when the app starts.
I tried removing the
<requestFocus></requestFocus>
thing and it didn't do anything.
A: <LinearLayout
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_width="0px"
android:layout_height="0px" />
<EditText android:text=""
android:id="@+id/EditText01"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="@string/hint">
</EditText>
No other coding needed, it's a simple and clear solution.
A: If you want clear the default focus on the edit text then use the following 2 attributes
android:focusable="false"
android:focusableInTouchMode="true"
inside the parent Linear layout.
for example:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="false"
android:focusableInTouchMode="true"
android:orientation="vertical">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="email id"
android:inputType="textEmailAddress"
android:maxLines="1"
/>
</LinearLayout>
If you want to hide the keyboard on activity creation use these attributes inside manifest file activity tag
for example:
<activity
android:configChanges="screenSize|orientation|keyboardHidden"
android:screenOrientation="portrait"
android:name=".activities.LoginActivity"
android:windowSoftInputMode="stateHidden|adjustResize"/>
If you want to hide the keyboard on button click or on some event occur use the following code
public void onClick(View v) {
try {
//InputMethodManager is used to hide the virtual keyboard from the user after finishing the user input
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm.isAcceptingText()) {
imm.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
} catch (NullPointerException e) {
Log.e("Exception", e.getMessage() + ">>");
}
}
} catch (NullPointerException e) {
Log.e("Exception", e.getMessage() + ">>");
}
If you want to take off the focus from edit text fields after leaving the activity
@Override
protected void onResume() {
super.onResume();
mEmail.clearFocus();
mPassword.clearFocus();
}
And finally If you want to clear the data in the edit text fields on submitting the form use
@Override
protected void onResume() {
super.onResume();
mEmail.getText().clear();
mPassword.getText().clear();
}
A: You can use window soft input mode hidden for hide keyboard and android:focusable="false" and android:focusableInTouchMode="true"
<activity
android:name=".MainActivity"
android:windowSoftInputMode="stateHidden"
android:label="@string/app_name"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
A: try this code in LinearLayout
<LinearLayout
android:focusable="true"
android:focusableInTouchMode="true"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<EditText
android:hint="Search..."
android:drawableRight="@drawable/ic_search"
android:id="@+id/search_tab_hotbird_F"
android:layout_width="match_parent"
android:layout_height="wrap_content" />
<android.support.v7.widget.RecyclerView
android:id="@+id/recyHotbird_F"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="4dp">
</android.support.v7.widget.RecyclerView>
</LinearLayout>
A: It worked for me, wish also will help you.
Either :
android:windowSoftInputMode="stateAlwaysHidden"
add this property to your Manifest.xml file under that specific activity where you want to disable auto focus.
Cons: It will only hide your soft keyboard, will cursor will be still there.
Else :
android:focusableInTouchMode="true"
add this property to your UI xml file (under parent layout), so that it will hide focus also the keyboard both.
A: Add the android:focusable="true" and android:focusableInTouchMode="true" elements in the parent layout of EditText as follow;
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/linearLayout7" android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:focusable="true" android:focusableInTouchMode="true">
I think, it should help you.
See also;
Android Developers official guide on handling touch and input
A: NO More work... just add android:windowSoftInputMode="stateAlwaysHidden"
to activity tag of the Manifest.xml file .
A: <EditText
android:id="@+id/input"
android:layout_width="0dp"
android:layout_height="48dp"
android:focusable="false"
android:focusableInTouchMode="false" />
detailInputView = (EditText) debugToolsView.findViewById(R.id.input);
detailInputView.setOnTouchListener(new View.OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
detailInputView.setFocusable(true);
detailInputView.setFocusableInTouchMode(true);
return false;
}
});
A: Just add the following to your main layout view xml tag:
android:focusableInTouchMode="true"
A: Hei Lee,
There are several way to do this, Mudassir has give a way to you to do that.
If the idea doesn't work, then do just simple thing-
In your AndroidManifest>Activity add this simple code:
android:windowSoftInputMode="stateHidden"
Nothing need to do in EditText in XML, all will be work and no focus will appear.
Look the real life example code:
<activity
android:name=".MainActivity"
android:windowSoftInputMode="stateHidden"
android:label="@string/app_name"
>
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
A: for clear default requestFocuse you should set your View's parent focusable="true" like this below
<android.support.constraint.ConstraintLayout
android:id="@+id/coordinatorChild"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:focusable="true"
android:focusableInTouchMode="true">
A: Before I make visible the parent view I do this (and it is working fine) Edit text is not focused automatically just if I touch it. (parentView is including edit text)
...
parentView.setFocusable(true);
parentView.setFocusableInTouchMode(true);
objProperties.setVisibility(VISIBLE);
...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593887",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "84"
}
|
Q: jQTouch - unable to find proper documentation/reference I'm learning jQTouch from scratch. What is the best way to learn it?
I don't seem to be able to find any proper documentation, does that mean the best way is to dig into the css itself? And keep trying?
A: It really depends what "proper documentation" means to you. They have certainly got some documentation, although I agree that it can be made much more comprehensive.
You should start with their Getting Started article. Then have a look at the available initialisation options, callback events, animations, etc. These are all listed on their wiki homepage.
The best resource is probably the demo, that you would be able to see most of the actions with a WebKit browser.
Peepcode has a nice introductory video tutorial on jQTouch that costs a little bit. If you're evaluating it, you may want to give it a go.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593889",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Using map function in python If you have the following code, how exactly is it following the documentation: map(function, iterable,...)?
x = sorted(map(int, dat[0].split()))
Is int a function and if so, why isn't it expressed as such?
A: int is a constructor so it's callable so you can use it with map
A: In your case dat[0] is as string, and split() generates a list of strings, by splitting the input string at whitespaces.
Eg
"1 11".split()
returns
["1", "11"]
The map function has two input arguments:
*
*The first argument is something which can be called (in Python you say it is a callable), eg a function. int is not realy a function but such a thing (Python slang: it is an object).
Eg int("3") return 3. So int when applied to a string tries to convert this string to an integer, and gives the integer value back.
*The second argument is something you can iterate over, in your case it is a list.
If you then call the map function, the first argument is applied to all elements from the second argument.
So
map(int, ["1", "11"])
returns
[1, 11]
If you combine what I explained you understand that
map(int, "1 11".split())
returns
[1, 11]
A: When you ask "why isn't it expressed as such" I suppose you mean, why doesn't it have brackets like a function? The answer is that if you put the brackets in then you get what the function does instead of the function itself. Compare what happens when you enter int() versus int.
A: Think of it like this
def map( function, iterable ):
return ( function(x) for x in iterable )
In x = sorted(map(int, dat[0].split())) the function, int, is being named, not evaluated. This code provides a function object to the map function. The map function will evaluate the given function.
A: The syntax of map in the simplest form is:
map(func, sequence)
It will apply the function "func" on each element of the sequence and return the sequence. Just in case you don't know, int() is a function.
>>> int(2.34)
2
>>> int("2")
2
>>> a = ["1", "101", "111"]
>>> map(int, a)
[1, 101, 111]
Now, I will give you my implementation of map().
>>> for index in range(len(a)):
... a[index] = int(a[index])
...
>>> a
[1, 101, 111]
If you have understood the concept, let's take a step further. We converted the strings to int using base 10 (which is the default base of int() ). What if you want to convert it using base 2?
>>> a = ["1", "101", "111"]
>>> for index in range(len(a)):
... a[index] = int(a[index], 2) # We have an additional parameter to int()
...
>>> a
[1, 5, 7]
To get the same result using map(), we will use a lambda function
>>> a = ["1", "101", "111"]
>>> map(lambda x: int(x, 2), a)
[1, 5, 7]
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593895",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How can i change number of days in a month for Fullcalendar? The problem is Persian (Iranian) months are different from Georgian months, for example 7th month of year is Mehr in Iranian Calendar and is 30 days, but July is 31 (7th month of Georgians).
Is there a way to change Date() object (change number of days) in javascript or something similar to get fullcalendar act like a Persian calendar?
A: things like this you are best to google first
Persian Calendar Picker
or
Persian Date()
A: Using JavaScript extensions would be good at this. Please refer the following links which has explanation as well as the source:
http://intldate.codeplex.com/
In jQuery
http://keith-wood.name/calendars.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593896",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: .NET: DDD and ASMX, avoid multiple namespaces on proxy classes I am new to DDD and at the moment I try to refactor a project towards a domain driven architecture. The project has a client and a server side (ASMX webservice). Now I created a class libary called "Domain" which is referenced by the client application as well as by the server.
Now I want my SOAP communication to be based on my domain model. But as you know the ASMX webservice creates some kind of proxy class library within the client as soon as a web reference is established.
This results in having each domain entity and value object twice under different namespaces.
*
*Is it possible to use the domain model for communication directly and avoid the generation of the ASMX proxy classes?
*How are DTOs used within DDD? As you know, some domain parts might not be serializable (e.g. NHibernate / IList usage) so in the past I often created simpler DTO-versions of my entity classes. Is it a common practice to define DTO entities within the domain?
A: If you were to use WCF, you could have the service interface and DTO classes in a shared assembly that both the client and the server referenced. Converting your project to use WCF may not be too hard, but there is a lot of learning to do before you get started.
A shared interface assembly is only a good ideal if you wish the client and server to be tightly joined, hence it does not work well unless both side are owned by the same team.
Often trying to use the same classes on the server and client lean to deign problem, however sharing classes when it does fit the design saves a lot of work.
(Sorry I don’t think you can used a shared assembly with asmx, it is more a concept from the remoting side of .net history)
A: It is not possible to use original domain model (obtained by a reference -not a WEB reference- to the domain model) for communication with the ASMX: you must use the model exposed by asmx that is similar but not the same (i.e. List are transformed in Array).
It's possible -and easy- create many classes from many web-services having the same namespace.
Create a .bat file like this
"C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\wsdl.exe" /sharetypes /o:C:\code\MyProxy.cs /namespace:MyProxies http://website/FirstService.asmx http://website/SecondService.asmx
Pause
Where
-"C:\Program Files\Microsoft SDKs\Windows\v7.0A\bin\wsdl.exe" is wsdl.exe with relative path (it must be on your PC)
-/sharetypes means that you want only 1 namespace in the output
- /o:C:\code\MyProxy.cs is the .cs file name that will contain all the classes created
- /namespace:MyProxies is the namespace for all the classes created
- http://website/FirstService.asmx http://website/SecondService.asmx is the list of webservices that you need to call
- Pause means that you want window's shel to remain open to read the feedback of the operations.
NOTE
1) All instructions must be in one line (don't press enter); Pause in the second line.
2) If /o:C:\code\MyProxy.cs will be part of your solution (i think so) and you use source control, the file must be checked out to be overwritten by wsdl.exe
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593898",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: How to get information about key container through certificate public key in CryptoAPI? In C# I can do this by using
public static CspKeyContainerInfo GetKeyConatinerInformation(X509Certificate2 certificate)
{
if (certificate == null)
throw new ArgumentNullException("certificate");
ICspAsymmetricAlgorithm key = certificate.PublicKey.Key as ICspAsymmetricAlgorithm;
if (key == null)
throw new InvalidOperationException("Unknown key type");
return key.CspKeyContainerInfo;
}
I want to know how can i get this by using C++ and lib CryptoAPI
A: Here is a program written by Mounir IDRASSI. This will provide you with the information you are looking for.
Also look for the related answer here.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593900",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: asp.net : how to send a array from client to server web method In ASP.NET, I have collected a list of selected items from a checkbox in an array at the client side. Now I need to pass the array from client to server's ASMX web method. How do I do this?
A: Client-Side Web Service Calls with AJAX Extensions
Calling Web Services from Client Script
A: Add a JSON library to your page, use json2.js here. That gives you a function to serialize javascript arrays into JSON strings.
You can then pass it into your webmethod:
[WebMethod]
public void MyWebMethod(List<string> someValues)
{
// Use someValues...
}
Here's the javascript you need
var arrayData = ["1","2","3"]; // Your array goes here
$.ajax({
type: "POST",
url: "MyWebService.asmx/MyWebMethod",
data: JSON.stringify({ someValues: arrayData }),
contentType: "application/json; charset=utf-8",
dataType: "json",
success: function()
{
// Your success function...
}
});
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593902",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Find Control using javascript inside an ASP:Login control I have an ASP Login control box on the page which is customized.
Inside the Login control we have Username and password textboxes.
I want to find username and password controls with a javascript function.
var Username= document.getElementById("<%=UserName.ClientID%>");
But this code does not compile and gives compile time error
UserName not found in this context.
and if I write the client side id :
var username = document.getElementById("login_LoginUser_UserName");
it executes properly, but I want to find the client id rather than using a hardcoded id here.
A: The only way which I know is:
var Username = document.getElementById("<%= Login1.FindControl("UserName").ClientID %>");
var Password = document.getElementById("<%= Login1.FindControl("Password").ClientID %>");
It will returns the client Id of the controls inside of Login control.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593903",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Samsung Galaxy S II (Android 2.2.3) with MS Exchance Mail Account Zimbra Server
In my Samsung S2 I have a Microsoft Exchange Mail Account and use a Zimbra Mail Server.
The standard email app doesn’t render my html mail. I get all the html source code with the mail text. The synchronization with my calendar and mails works perfectly.
I installed a second mail app called “touchdown” (only 30 day trial) which is able to render the mails correctly. So I guess it’s not the fault of Zimbra.
Does anybody know why I can’t render the mails with the standard mail app? And more important – is there a way or workaround to chance the rendering for html mails?
Help would be much appreciated.
bye
A: I do believe that the problem is caused by the new version of Zimbra (7). I have the problem myself, but i just got the phone yesterday and HTML rendering didn't work at all yet. However, a customer of our company told us, that he has the problem only sience Zimbra was updated to the new version.
Edit: As I found out, the problem is on the Samsung Galaxy SII site. However, Zimbra 7.1.3 has kind of a fix for this, it uses the old protocol version for Samsung phones. Update Zimbra, re-create the account on the phone. The Headers wont show anymore. No HTML-Mail though.
A: Timo's answer is correct.
However if you still have Zimbra6 ther's another problem in the server implementation of ActiveSync protocol.
Zimbra replies to the Android client saying he's AS Protocol version 2.5, so the client won't ask for html emails.
Some other clients, like iPhones, ignores server version and just always ask for html email, regardless of the server.
This behavior was fixed in Zimbra 7:
http://bugzilla.zimbra.com/show_bug.cgi?id=18608
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593905",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Emacs revert-buff (s-u): what is s-u? The emacs help page for the M-x revert-buffer command says that it is bound to "s-u". What the heck is s-u? I know M-x is Meta-x (usually alt-x), and I know that C-x is Control-x. But what is s-u?
A: On Mac OS X 10.6.8 (Snow Leopard) with Emacs: 23.3.1, s-u corresponds to Cmd-u.
A: The "s-" modifier is the "super" key, which on a standard PC keyboard is the window key.
This makes such shortcuts unusable on Windows AFAIK, but I have a few bound on my Linux.
I don't know what key this corresponds to on an Apple keyboard though.
A: *
*What does "s-[keyname]" refer to in Emacs, and how do I tell Emacs to ignore it?
*https://superuser.com/questions/204946/what-is-emacs-keybinding-s-u
Summary: It's your "Super" key.
(Emacs is nothing if not consistent with their naming - apparently it's usually Meta)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593907",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "10"
}
|
Q: Google visualization API - Bar Chart / Line Chart - Custom Tooltip How to format the tooltip text of Google Visualization Api based Line and Bar Charts.
I want custom text and images in the tooltip.
Thanks
A: Just drop this code into Google's Visualization playground as an example I'm using bar chart and editing the text of the tooltip:
function drawVisualization() {
data = new google.visualization.DataTable()
data.addColumn('string', 'Date');
data.addColumn('number');
data.addColumn({type:'string',role:'tooltip'});
data.addRow();
base = 10;
data.setValue(0, 0, 'Datapoint1');
data.setValue(0, 1, base++);
data.setValue(0, 2, " This is my tooltip1 ");
data.addRow();
data.setValue(1, 0, 'Datapoint2');
data.setValue(1, 1, base++);
data.setValue(1, 2, "This is my second tooltip2");
// Draw the chart.
var chart = new google.visualization.BarChart(document.getElementById('visualization'));
chart.draw(data, {legend:'none', width:600, height:400});
}
A: There seems to be some details on how to do this here
http://code.google.com/apis/chart/interactive/docs/examples.html
Scroll down to the bottom, its the last example.
A: Paste this at: https://code.google.com/apis/ajax/playground/?type=visualization#simple_dashboard
function drawVisualization() {
// Prepare the data
var data = new google.visualization.DataTable();
data.addColumn('string', 'Name');
data.addColumn('number', 'Donuts eaten');
data.addColumn({'type': 'string', 'role': 'tooltip', 'p': {'html': true}});
data.addRows([
['Sven', 16, createCustomHTMLContent('https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcRnV6emFCNN90Nt-HQcd_x5umqdoSpagUp5fwOqc5QYnVpEHHF8', 16)],
['Kurt', 46, createCustomHTMLContent('http://173.199.167.192/customavatars/avatar296423_1.gif', 46)],
['Sofie', 27, createCustomHTMLContent('https://encrypted-tbn0.gstatic.com/images?q=tbn:ANd9GcSbv9ijKCwG3eJS9uUTxPzJ5F8zqYRAA5uRkyfz5lniC7TN8t96', 27)],
['Lisa', 29, createCustomHTMLContent('https://encrypted-tbn2.gstatic.com/images?q=tbn:ANd9GcQLZSgX1oDVc5psdBdqzG8oU-1vqTEIMXw-FDvoSLOg0oJ-0VLv', 29)],
['Lajla', 19, createCustomHTMLContent('http://static3.depositphotos.com/1001992/155/i/950/depositphotos_1550168-Portrait-of-a-beauty-young-female-face.jpg', 19)],
['Elsa', 38, createCustomHTMLContent('http://os1.i.ua/3/2/10725917_2535e604.jpg', 38)],
]);
function createCustomHTMLContent(flagURL, totalEaten) {
return '<div style="padding:5px 5px 5px 5px;">' +
'<img src="' + flagURL + '" style="width:75px;height:50px"/><br/>' +
'<table>' +
'<tr>' +
'<td><img src="http://2.bp.blogspot.com/-hPs6JLOBj4I/UTBQWNhHFaI/AAAAAAAABOQ/LROTO_TAYRQ/s72-c/donat-makanan-lemak-trans.jpg" style="width:25px;height:25px"/><td/>' +
'<td><b>' + totalEaten + '<b/><td/>' +
'<tr/>' +
'<table/>' +
'<div/>';
}
// Define a slider control for the 'Donuts eaten' column
var slider = new google.visualization.ControlWrapper({
'controlType': 'NumberRangeFilter',
'containerId': 'control1',
'options': {
'filterColumnLabel': 'Donuts eaten',
'ui': {'labelStacking': 'vertical'}
}
});
// Define a pie chart
var piechart = new google.visualization.ChartWrapper({
'chartType': 'ColumnChart',
'containerId': 'chart1',
'options': {
'width': 600,
'height': 300,
'legend': 'bottom',
'tooltip': {
'isHtml': true
},
'pieSliceText': 'value'
}
});
// Create the dashboard.
new google.visualization.Dashboard(document.getElementById('dashboard')).
// Configure the slider to affect the piechart
bind(slider, piechart).
// Draw the dashboard
draw(data);
}
A: Here you have some examples with tooltips
Link
So there is example with column chart:
function drawChart() {
var dataTable = new google.visualization.DataTable();
dataTable.addColumn('string', 'Country');
// Use custom HTML content for the domain tooltip.
dataTable.addColumn({'type': 'string', 'role': 'tooltip', 'p': {'html': true}});
dataTable.addColumn('number', 'Gold');
dataTable.addColumn('number', 'Silver');
dataTable.addColumn('number', 'Bronze');
dataTable.addRows([
['USA', createCustomHTMLContent('http://upload.wikimedia.org/wikipedia/commons/2/28/Flag_of_the_USA.svg', 46, 29, 29), 46, 29, 29],
['China', createCustomHTMLContent('http://upload.wikimedia.org/wikipedia/commons/f/fa/Flag_of_the_People%27s_Republic_of_China.svg', 38, 27, 23), 38, 27, 23],
['UK', createCustomHTMLContent('http://upload.wikimedia.org/wikipedia/commons/a/ae/Flag_of_the_United_Kingdom.svg', 29, 17, 19), 29, 17, 19]
]);
var options = {
title: 'London Olympics Medals',
colors: ['#FFD700', '#C0C0C0', '#8C7853'],
// This line makes the entire category's tooltip active.
focusTarget: 'category',
// Use an HTML tooltip.
tooltip: { isHtml: true }
};
// Create and draw the visualization.
new google.visualization.ColumnChart(document.getElementById('custom_html_content_div')).draw(dataTable, options);
}
function createCustomHTMLContent(flagURL, totalGold, totalSilver, totalBronze) {
return '<div style="padding:5px 5px 5px 5px;">' +
'<img src="' + flagURL + '" style="width:75px;height:50px"><br/>' +
'<table id="medals_layout">' + '<tr>' +
'<td><img src="http://upload.wikimedia.org/wikipedia/commons/1/15/Gold_medal.svg" style="width:25px;height:25px"/></td>' +
'<td><b>' + totalGold + '</b></td>' + '</tr>' + '<tr>' +
'<td><img src="http://upload.wikimedia.org/wikipedia/commons/0/03/Silver_medal.svg" style="width:25px;height:25px"/></td>' +
'<td><b>' + totalSilver + '</b></td>' + '</tr>' + '<tr>' +
'<td><img src="http://upload.wikimedia.org/wikipedia/commons/5/52/Bronze_medal.svg" style="width:25px;height:25px"/></td>' +
'<td><b>' + totalBronze + '</b></td>' + '</tr>' + '</table>' + '</div>';
}e
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593909",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: CakePHP: False positive authError with ACL I have set up a working ACL system with CakePHP inside my company's existing site. Access restriction works perfect, groups and single users that don't have the right to visit a specific portion of the site get an authError message explaining that they don't have the proper rights.
The only problem is that in Firefox I sometimes get -what I'd like to call- false positives. This means that, even though a user has access to a certain controller and action, the authError still pops up. The strange thing is, the view still renders properly, and except for the authError there is nothing wrong. Everything works, users can see what they need to see. Only sometimes the authError is still displayed.
Now this randomly occurs sometimes in Firefox, but in IE8 this happens all the time. Even though a user has full access to the whole site, the authError message is still displayed on every single page in IE8. I haven't checked if this problem persists in other IE browsers, but since it happens in both IE8 and FF, my thoughts were that they probably exist in others too.
Now I can't get my head around why this is happening, since there is no real pattern here. In FF the authError randomly gives a false positive, and in IE8 it is just displayed all the time.
One could argue that for some reason the users rights are checked after the authError message has been given a 'go' to appear. Resulting in proper access even though the error message has already been displayed. I already checked whether or not the loading time of the page had anything to do with it, but this does not seem to be the case.
Are there users around that have any idea what could be the cause of this problem? Thanks in advance!
A: I am not entirely sure why that happens and I dont know if you were able to figure out your issue. However, I am also running ACL and had a similar issue and figure I would post it here and hopefully help someone.
I had an Articles controller that I needed the index and view actions to be public. No matter what I did, nothing worked. I would still get the same not authorized error. After many sleepless nights of trying and trying, I came to find out that, although I am requesting the view action for example, any other actions that are referenced in the view action, like getRelated or getComments would have to be added as well.
The issue was fixed, or so I thought. However, intermittently, the error would pop up again and again. Same issue, same error. Now, I was able to access the View action but not the Index, although everything seemed good with the $this->Auth->allow
After many more head scratching, I came to find out that I had to do the same with my Categories Controller. In this controller I had created a getRelated action that would retrieve all Articles related to a specific article based on its category.
As soon as I did that, now all my problems went away and I have not experience a similar issue. Now I can actually concentrate into other sections of my project.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593910",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: Why DHTML behavior not work in IE8 if document.write is executed in ? We have a 3rd party web application which works on in IE6, but not works in IE8.
The sample code is like below, the "message from .htc" message will popup in IE6, but not popup in IE8.
test.html
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/>
<script type='text/javascript'>
//if comment the following line, or move this script in <body>,
//then HTC will work in IE8
document.write ("<h1>document.write() in <head></h1> some calendar codes");
</script>
</head>
<body style='behavior:url(test.htc)'>
HTML Components test
</body>
</html>
test.htc
<script type='text/javascript'>
alert ("message from .htc");
</script>
Why this happened? Any compatible documents to explain this?
Solution
As @Quentin said or another expert from http://social.msdn.microsoft.com/Forums/en-US/iewebdevelopment/thread/c1f546f6-d7e1-4b46-a1c9-8f02eaf1286b said, IE8 probably make rules strictly compared to IE6, and IE8 may treat it as an corrupt HTML document.
So, I decide to to use document.createElement to create elements dynamically instead of document.write, and insert these elements to DOM after some seconds delay. After some tests, it finally worked both in this test.html and real application.
test-ie8-compatible.html
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv='Content-Type' content='text/html; charset=UTF-8'/>
<script type='text/javascript'>
function Delay_CreateCalendar()
{
var oContainer = document.createElement ("div");
var oCalendarIFrame = document.createElement ("iframe");
oContainer.appendChild (oCalendarIFrame);
document.body.insertBefore (oContainer);
}
setTimeout (Delay_CreateCalendar, 2000);
</script>
</head>
<body style='behavior:url(test.htc)'>
dhtml HTC 测试
</body>
</html>
A: Presumably, despite the namespace, you are serving the document as text/html. In HTML the start and end tags for the head and body element are optional. H1 elements are not allowed inside the head.
Thus, when you document.write and H1 inside the end, you trigger the end of the head and the start of the body.
I assume that IE then ignores the start tag for the body element as it would create a second body (which also isn't allowed).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593913",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Uniformely distribute as many items as possible among a set of carriers Problem:
*
*there n boxes b_1, ... b_n
*box b_i has weight w_i and cost c_i
*there are m persons p_1, .... p_m
*person p_i has strength s_i and money m_i, and so she/he can carry a number of boxes such that the sum of their weights is less than or equal to s_i, and the sum of their costs is less than or equal to m_i
How do I distribute the boxes among the persons such that the maximum number of boxes is uniformly distributed among the m persons? In other words, I want to distribute as many boxes as possible (ideally all the n boxes) among the m persons, in such a way that all the persons uses approximately the same strength to carry the weight of their respective boxes, and spend approximately the same amount of money to take them.
Questions:
*
*what kind of problem is this? It looks like a Bin packing problem, but I think it's different
*What is a good algorithm to solve it?
A: This is a multiobjective optimization problem.
The objectives are:
*
*Distribute as many boxes as possible
*All the persons uses approximately the same strength
*All the persons uses approximately the same money
and the constrains:
*
*Weight of each box
*Strength of each person
*Money of each person
It looks like a variation of a multiple-constraints multiple-nested-knapsack problem.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593916",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Windows Service + read from database I am new To windows service. I need a windows service that reads an entry from a table from database. I have a CONSOLE APP where I add new project WINDOWS SERVICE. I already have a method that access the database, and other methods. I can put a thread on start that reads the database. Where do I put the thread? ( how can I do that). Where on WINDOWS SERVICE I add those methods? I have the Windows Service like this:
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
do
{
thread.start();
bool variab = readFromDatabase (Database table);
}
}
protected override void OnStop()
{
}
A: I suggest that you create a class in which you do everything you need and create in in the service:
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
YourClass cl = new YourClass();
cl.DoWhatYouNeed(...);
}
protected override void OnStop()
{
}
This gives you opportunity to run and test your class separate from service, maybe during debug release.
A: With windows services usually a method is created to execute the main loop of the service, in a separated thread. Otherwise the service could become unresponsive. For example, you can have a method called MainLoop to execute the service logic. Use the OnStart method only to do the initializing tasks, such as read configuration values or start the threads of the service. And use the OnStop to executing cleaning tasks, stopping threads, etc...
Thread _workerThread;
bool _shouldStop;
public Service1()
{
InitializeComponent();
}
protected override void OnStart(string[] args)
{
try{
_workerThread = new Thread(new ThreadStart(MainLoop));
_shouldStop = false;
_workerThread.Start();
}
catch{}
}
private void MainLoop()
{
while (!_shouldStop)
{
try{
//your logic here
}
catch{}
}
}
protected override void OnStop()
{
_shouldStop = true;
}
A: You must put your code or class, which contain data access logic in OnStart method
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593924",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Not working properly while using S7GraphView I want to draw a line graph in iphone and am using S7GraphView for it.But when I compile my app it is showing so many errors like:
"CGContextSetFillColorWithColor", referenced from:
-[S7GraphView drawRect:] in S7GraphView.o
"_CGContextFillRect", referenced from:
-[S7GraphView drawRect:] in S7GraphView.o
"_CGContextSetLineDash", referenced from:
-[S7GraphView drawRect:] in S7GraphView.o
"_CGContextSetLineWidth", referenced from:
-[S7GraphView drawRect:] in S7GraphView.o
"_CGContextMoveToPoint", referenced from:
-[S7GraphView drawRect:] in S7GraphView.o
"_CGContextAddLineToPoint", referenced from:
-[S7GraphView drawRect:] in S7GraphView.o
"_CGContextClosePath", referenced from:
-[S7GraphView drawRect:] in S7GraphView.o
"_CGContextSetStrokeColorWithColor", referenced from:
-[S7GraphView drawRect:] in S7GraphView.o
"_CGContextStrokePath", referenced from:
-[S7GraphView drawRect:] in S7GraphView.o
"_CGContextFillPath", referenced from:
-[S7GraphView drawRect:] in S7GraphView.o
Can anybody help me?
A: Try linking you application to Quartz.framework and/or QuartzCore.framework.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593930",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How do Clojure programmers use Macros? My understanding is Clojure's homoiconicity exists so as to make writing macros easier.
Based on this stackoverflow thread, it looks like Macros are used sparingly, except for DSLs in which higher-order functions are not to be used.
Could someone share some examples of how macros are used in real-life?
A: It's correct that homoiconicity makes writing Clojure macros very easy. Basically they enable you to write code that builds whatever code you want, exploiting the "code is data" philosophy of Lisp.
Macros in a homoiconic language are also extremely powerful. There's a fun example presentation I found where they implement a LINQ-like query syntax in just three lines of Clojure.
In general, Clojure macros are potentially useful for many reasons:
*
*Control structures - it's possible to create certain control structures using macros that can never be represented as functions. For example, you can't write if as a function, because if it was a function then it would have to evaluate all three arguments, whereas with a macro you can make it only evaluate two (the condition value and either the true or false expression)
*Compile time optimisation - sometimes you want to optimise your code based on a constant that is known or can be computed at compile time. For example, you could create a "logging" function that logs only if the code was compiled in debug mode, but creates zero overhead in the production application.
*Code generation / boilerplate elimination - if you need to produce a lot of very similar code with similar structure, then you can use macros to automatically generate these from a few parameters. If you hate boilerplate, then macros are your friends.
*Creating new syntax - if you see the need for a particular piece of syntax that would be useful (perhaps encapsulating a common pattern) then you can create a macro to implement this. Some DSLs for example can be simplified with additional syntax.
*Creating a new language with entirely new semantics (Credits to SK-Logic!) theoretically you could even go so far to create a new language using macros, which would effectively compile your new language down into Clojure. The new langauge would not even have to be Lisp-like: it could parse and compile arbitrary strings for example.
One important piece of advice is only use macros if you need them and functions won't work. Most problems can be solved with functions. Apart for the fact that macros are overkill for simple cases, functions have some intrinsic advantages: they are more flexible, can be stored in data structures, can be passed as parameters to higher order functions, are a bit easier for people to understand etc.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593931",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "12"
}
|
Q: How an interface can replace a class? I created a Method called GetStudentMarks(). The return-type of this method is generic List<StudentMark>.The code works well even when i replaced the List<StudentMark> with generic IList<StudentMark>. How can an interface replace a class while interface contain only the declarations?
A: An interface cannot replace a class. It's just a blueprint for a class that has some implementation that corresponds by the guidelines that are set by the interface. So, you mostly will have one interface and than 1 or multiple classes that have some implementation for that interface like so:
public interface IMyInterface{
IList<string> SomeList { get; }
}
public class MyClass : IMyInterface {
public IList<string> SomeList {
get {
return new List<string>(){ "a", "b" , "c" };
}
}
}
A: It doesn't matter if the return type is interface or a solid class. Since inside the method you're returning the full type, the type is casted to the declared return type before returning the actual data so everything works as expected.
public IList<string> MyStrings()
{
return new List<string>(); // Cast happens here just before return (List -> IList)
}
Later if you require, you can cast the return type (IList) back to the solid class (List) and use it that way.
A: Interface can not replace the Class. Interface can create an abstraction layer that hides actual object implementation beyound interface (that's why it's called interface).
Look on Polymorphism for explanation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593932",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: avoid auto release of NSMutable array..... iphone app I have a NSmutablearray
after i read datas from it, i cant read the same data(index) again
Error:
"EXC_BAD_ACCESS"
in interface
NSMutableArray *ticketList;
@property (nonatomic, retain) NSMutableArray *ticketList;
assigning value
self.ticketList = [NSMutableArray arrayWithArray:[results objectForKey:@"tickets"]];
reading value
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
static NSString *CellIdentifier = @"ticketCell";
ticketCell *cell = (ticketCell *)[tableView dequeueReusableCellWithIdentifier:CellIdentifier];
if (cell == nil) {
[self.cellNib instantiateWithOwner:self options:nil];
cell = tmpCell;
self.tmpCell = nil;
}
else {
// Nothing to do here. Because in either way we change the values of the cell later.
}
cell.useDarkBackground = (indexPath.row % 2 == 0);
// Configure the data for the cell.
int rowID = indexPath.row;
NSDictionary *currentTicket = [ticketList objectAtIndex:(int)(indexPath.row)];
NSString *tikid = [currentTicket objectForKey:@"number"];
cell.ticketID = [currentTicket objectForKey:@"number"];
cell.ticketStatus = [currentTicket objectForKey:@"status"];
cell.ticketOpenDate = [currentTicket objectForKey:@"oDate"];
cell.ticketEndDate = [currentTicket objectForKey:@"eDate"];
cell.ticketCategory = [currentTicket objectForKey:@"category"];
cell.ticketPriority = [currentTicket objectForKey:@"priority"];
cell.ticketInfo = [currentTicket objectForKey:@"info"];
return cell;
}
A: use this
ticketList = [[NSMutableArray alloc]initWithArray:[results objectForKey:@"tickets"]];
instead of
self.ticketList = [NSMutableArray arrayWithArray:[results objectForKey:@"tickets"]];
use this
NSDictionary *currentTicket = [ticketList objectAtIndex:indexPath.row];
instead of
NSDictionary *currentTicket = [ticketList objectAtIndex:(int)(indexPath.row)];
A: You have to alloc array properly:
ticketList = [[NSMutableArray alloc] initWithArray:[results objectForKey:@"tickets"]];
And also maybe try to alloc currentTicket:
NSDictionary *currentTicket = [[NSDictionary alloc] initWithDictionary:[ticketList objectAtIndex:indexPath.row]];
A: Sounds like somewhere you're doing something like this:
[currentTicket release];
If so, don't. The currentTicket pointer doesn't belong to you.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593933",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: iPhone App: not resuming audio session in AVAudio Player In my iPhone App I am Playing music using AVAudioPlayer. when my App runs in background that time also it is running for tht I wrote this code
in AppDelegate on
-- application didFinishLaunchingWithOptions
audioManager= [[AudioManager alloc] init];
audioManager.delegate=self;
audioManager.soundFile=[[[NSBundle mainBundle] pathForResource:@"mysong" ofType:@"wav"] stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]];
[audioManager setFileForPlay];
[audioManager.player setNumberOfLoops:-1];
[audioManager.player setVolume:.5];
[audioManager play];
-(void) playerBeginInterruption:(AVAudioPlayer *)p{
[usdef setValue:@"START" forKey:@"LOCATIONMANAGER"];
[locationManager startUpdatingLocation];
[p pause];
// audioManager=nil;
}
-(void) playerBeginInterruptionInBackground:(AVAudioPlayer *)p{
[usdef setValue:@"START" forKey:@"LOCATIONMANAGER"];
[locationManager startUpdatingLocation];
[p pause];
//audioManager=nil;
}
-(void) playerEndInterruption:(AVAudioPlayer *)p{
NSLog(@"Inteerpt END");
[p prepareToPlay];
[p play];
[usdef setValue:@"STOP" forKey:@"LOCATIONMANAGER"];
}
-(void) playerEndInterruptionInBackgroud:(AVAudioPlayer *)p{
NSLog(@"Inteerpt END BG");
// [self performSelector:@selector(allocaudioManager)];
[p prepareToPlay];
[p play];
[usdef setValue:@"STOP" forKey:@"LOCATIONMANAGER"];
// [locationManager stopUpdatingLocation];
}
now i have created saperate classes for audio manager which handels the delegate methods
in .h file
#import <Foundation/Foundation.h>
#import <AudioToolbox/AudioToolbox.h>
#import <AVFoundation/AVFoundation.h>
@protocol AudioManagerDelegate;
@interface AudioManager : NSObject <AVAudioPlayerDelegate> {
AVAudioPlayer *player;
NSString *soundFile;
BOOL inBackground;
id<AudioManagerDelegate> delegate;
}
@property (nonatomic, assign) id<AudioManagerDelegate>delegate;
@property (nonatomic, retain) NSString *soundFile;
@property (nonatomic, assign) AVAudioPlayer *player;
@property (nonatomic, assign) BOOL inBackground;
- (void)play;
- (void)pause;
- (void)stop;
- (void)registerForBackgroundNotifications;
-( void) setFileForPlay;
@end
@protocol AudioManagerDelegate <NSObject>
@optional
- (void)playerDidFinishPlayingInBackground:(AVAudioPlayer*)p;
- (void)playerDidFinishPlaying:(AVAudioPlayer*)p;
- (void)playerBeginInterruption:(AVAudioPlayer*)p;
- (void)playerBeginInterruptionInBackground:(AVAudioPlayer*)p;
- (void)playerEndInterruption:(AVAudioPlayer *)p;
- (void)playerEndInterruptionInBackgroud:(AVAudioPlayer *)p;
@end
in .m file
@implementation AudioManager
@synthesize delegate;
@synthesize player;
@synthesize inBackground;
@synthesize soundFile;
void RouteChangeListener(void *inClientData, AudioSessionPropertyID inID,UInt32 inDataSize, const void *inData);
-(id) init
{
if((self=[super init]))
{
OSStatus result = AudioSessionInitialize(NULL, NULL, NULL, NULL);
if (result)
NSLog(@"Error initializing audio session! %ld", result);
[[AVAudioSession sharedInstance] setDelegate: self];
NSError *setCategoryError = nil;
[[AVAudioSession sharedInstance] setCategory: AVAudioSessionCategoryPlayback error: &setCategoryError];
if (setCategoryError)
NSLog(@"Error setting category! %@", setCategoryError);
result = AudioSessionAddPropertyListener (kAudioSessionProperty_AudioRouteChange, RouteChangeListener, self);
if (result)
NSLog(@"Could not add property listener! %ld", result);
return self;
}
return nil;
}
-(void) setFileForPlay{
self.player=nil;
player = [[AVAudioPlayer alloc] initWithData:[NSData dataWithContentsOfFile:self.soundFile] error:nil];//initWithContentsOfURL:[NSURL URLWithString:self.soundFile] error:nil];
if (self.player)
{
player.delegate = self;
}
}
-(void) play{
[self.player play];
}
-(void)pause{
[self.player pause];
NSLog(@"in Pause");
}
-(void)stop{
[self.player stop];
NSLog(@"in stop");
}
void RouteChangeListener(void *inClientData, AudioSessionPropertyID inID,UInt32 inDataSize, const void *inData){
AudioManager* This = (AudioManager*)inClientData;
if (inID == kAudioSessionProperty_AudioRouteChange) {
CFDictionaryRef routeDict = (CFDictionaryRef)inData;
NSNumber* reasonValue = (NSNumber*)CFDictionaryGetValue(routeDict, CFSTR(kAudioSession_AudioRouteChangeKey_Reason));
int reason = [reasonValue intValue];
if (reason == kAudioSessionRouteChangeReason_OldDeviceUnavailable) {
[This stop];
}
}
}
- (void)audioPlayerDidFinishPlaying:(AVAudioPlayer *)p successfully:(BOOL)flag
{
if (flag == NO)
NSLog(@"Playback finished unsuccessfully");
[p setCurrentTime:0.];
if (inBackground)
{
[delegate playerDidFinishPlayingInBackground:p];
}
else
{
[delegate playerDidFinishPlaying:p];
}
}
- (void)playerDecodeErrorDidOccur:(AVAudioPlayer *)p error:(NSError *)error
{
NSLog(@"ERROR IN DECODE: %@\n", error);
}
// we will only get these notifications if playback was interrupted
- (void)audioPlayerBeginInterruption:(AVAudioPlayer *)p
{
NSLog(@"Interruption begin ");
// the object has already been paused, we just need to update UI
if (inBackground)
{
[delegate playerBeginInterruptionInBackground:p];
}
else
{
[delegate playerBeginInterruption:p];
}
}
- (void)audioPlayerEndInterruption:(AVAudioPlayer *)p withFlags:(NSUInteger)flags
{
if(inBackground)
{
[delegate playerEndInterruptionInBackgroud:p];
}
else
{
[delegate playerEndInterruption:p];
}
NSLog(@"Interruption ended. Resuming playback");
}
- (void)registerForBackgroundNotifications
{
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(setInBackgroundFlag)
name:UIApplicationWillResignActiveNotification
object:nil];
[[NSNotificationCenter defaultCenter] addObserver:self
selector:@selector(clearInBackgroundFlag)
name:UIApplicationWillEnterForegroundNotification
object:nil];
}
- (void)setInBackgroundFlag
{
inBackground = true;
}
- (void)clearInBackgroundFlag
{
inBackground = false;
}
@end
Now the problem is if I am Playing any songs form ipod library and stop the song and closing the ipod library, my original avaudioplayer which was playing before starting ipos library is not resuming means it is not playong song again
what could be wrong?
is there any demo project or sample code which can help me?
Please help and suggest.
A: You shouldn't have to call pause on the AVAudioPlayer (p in your code) in audioPlayerBeginInterruption: the player should not be playing at that stage because of the interruption. In audioPlayerEndInterruption: the following usually works for me:
[p prepareToPlay];
[p play];
The Audio Session Cookbook in the iOS docs has a section on "Handling Interruptions with the AVAudioPlayer Class" that should also help.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593936",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: What is the input for PushEndPointDemo? I can run the sample code. It shows PushPointEndDemo EditText and Register button. Now the problem is I don't know what I give in that box to register through the emulator.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593939",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to do Font Smoothing for AWT/Swing Application? I need to do font smoothing for a AWT application on Windows System.
On doing googling I came to know that I can set following VM argument in Eclipse.
-Dawt.useSystemAAFontSettings=gasp
But this is not yielding any positive results.
If anyone is having a better idea on how to achieve Font Smoothing, then kindly let me know.
EDIT After Answer By Andrew
I added the following snippet of code in paint method
public class BottomSubmitButtons extends Canvas {
@Override
public void paint(Graphics g) {
Graphics2D g2 = (Graphics2D)g;
RenderingHints rh = new RenderingHints(
RenderingHints.KEY_TEXT_ANTIALIASING,
RenderingHints.VALUE_TEXT_ANTIALIAS_GASP);
g2.setRenderingHints(rh);
}
}
This seems to have improved the smoothing in one of the sub panel.
But doing the same in other panel is not yielding any smoothing. Also the TextField boxes are going invisible by default, though they becomes visible once I click in that area
A: Play with the values for RenderingHints.KEY_TEXT_LCD_CONTRAST. When you find something that works, use that as the command line value.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593944",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "6"
}
|
Q: specifying newline type during xml serialization with LSOutput I am serializing an org.w3c.dom.Document (stored in the variable _document) to a text file (represented by the variable _file) using the snippet below. It works fine.
The file produced by the snippet has Unix-style newlines ('\n', 0x0A). However, this is running on Windows and I would like to have it use the DOS newline standard instead ( '\r\n', 0x0D0A) because the file will often be opened and read by administrators using notepad.exe.
Can I somehow specify the newline type to be used in the serialization below?
(In the snippet _document is of type org.w3c.dom.Document and _file is of type java.io.File.)
DOMImplementation domImplementation = _document.getImplementation();
DOMImplementationLS domImplementationLS
= (DOMImplementationLS) domImplementation.getFeature("LS", "3.0");
LSSerializer serializer = domImplementationLS.createLSSerializer();
LSOutput lsOutput = domImplementationLS.createLSOutput();
OutputStream outputStream = new FileOutputStream(_file);
lsOutput.setByteStream(outputStream);
serializer.write(_document, lsOutput);
outputStream.close();
A: LSSerializer.setNewLine
http://download.oracle.com/javase/1,5.0/docs/guide/plugin/dom/org/w3c/dom/ls/LSSerializer.html#setNewLine(java.lang.String)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593947",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: noob: android button I have two button b1 and b2 .If button b1 is pressed then perform a query q1 else if button b2 is pressed then perform an another query q2.
if(b1_click)
{
mCursor=//query
}
else if(b2_click)
{
mCursor=//query
}
Please tell me how can i implement this.How to implement b1_click method or any inbuilt method which tell that button is pressed.I tried
Cursor c;
c=//querys
if(b1.isPressed())
{
next.setOnClickListener
(
new View.OnClickListener()
{
@Override public void onClick(View v) {
c=db.getData1(); (getData1 method return cursor)
}
}
);
}
tv.append(c.getString(column_number) (tv=TextView)
"Same as above for b2"
It is saying that cursor (c) should be final
Help?
A: First of all I would recommend going through some tutorials Hello Android and you could also follow the code and samples in Common Tasks and How to do them in Android.
If you would read this carefully you would know that is very simple, something like this:
public class MyActiviy extends Activity implements OnClickListener{
protected void onCreate(Bundle savedInstance){
super.onCreate(savedInstance);
setContentView(R.layout.myLayout);
findViewById(R.id.Button1).setOnClickListener(this);
findViewById(R.id.Button2).setOnClickListener(this);
//more code...
}
public void onClick(View v){
switch(v.getId()){
case R.id.Button1:
//Button1 pressedd...do stuff
break;
case R.id.Button2:
//Button2 pressed...do some other stuff
break;
default:
break;
}
}
}
A: Try creating your OnClickListeners as private classes:
private class Button1ClickedListener implements OnClickListener {
public void onClick( View v ) {
//Do what needs to be done when button 1 is clicked.
}
}
private class Button2ClickedListener implements OnClickListener {
public void onClick( View v ) {
//Do what needs to be done when button 2 is clicked.
}
}
Then you set the onClick-listeners:
b1.setOnClickListener( new Button1ClickedListener() );
b2.setOnClickListener( new Button1ClickedListener() );
If you need the OnClickListeners to be able to use the cursor, you just need to declare it as a private field in the parent class of the OnClickListeners.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593949",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: How can I watch a file system directory to see when files are added to it? In c# winforms application, I want to choose a directory from network and after that, when any body put a file in it, I want to see a message such as "A file added."
for example I can get filepaths.
string[] filePaths = Directory.GetFiles(@"c:\MyDir\", "*.bmp");
should I run this code 5 minutes later and should I check the differences?
A: You could use the FileSystemWatcher class and subscribe for different events happening on the file system such as files and folders being created, deleted, modified, ...
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593955",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "3"
}
|
Q: How is Pagination done in iPhone or Xcode? I would like to know how PAGINATION is done using a "SWIPE".
Got a page with the name "Account Details" and this "Account Details" page should have around 4 PAGEs within that Account Details of 4 more accounts.
These has got the information about the BANKING account details. So how is the PAGINATION done. for these 4 PAGEs keeping "Account Details" as the main page.
Please help me....!!!!!!
A: If i correctly understand what you want, you should use UIScrollView!
Add this to your viewDidLoad:
UIScrollView *scrollView = [[UIScrollView alloc] initWithFrame:self.view.bounds];
scrollView.contentSize = CGSizeMake(4 * self.view.bounds.width, 1); // 1 = hack to disable possible verticalBouncing
scrollView.pagingEnabled = YES;
/* add your pages as subviews here */
[self.view addSubview:scrollView];
[scrollView release];
A: You should be using the UIPageControl. Very straightforward.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593961",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Which Android Platform/API is required to develop honeycomb tablet android applications? I want to create an Android app for the Honeycomb tablet.
What Android Platform/API Level is required to do so?
Thanks in advance.
A: I would use the 3.0 because this is the first Honeycomb release. You should not have backward comptability issues. But using the latest (3.2) release will cause problems with the earlier releases.
A: For Honeycomb you should use android 3.0.
A:
I want to create an Android app for the Honeycomb tablet.
Sweet!!!
What Android Platform/API Level is required to do so?
Honeycomb (API v11)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593967",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-3"
}
|
Q: RegEx to split camelCase or TitleCase (advanced) I found a brilliant RegEx to extract the part of a camelCase or TitleCase expression.
(?<!^)(?=[A-Z])
It works as expected:
*
*value -> value
*camelValue -> camel / Value
*TitleValue -> Title / Value
For example with Java:
String s = "loremIpsum";
words = s.split("(?<!^)(?=[A-Z])");
//words equals words = new String[]{"lorem","Ipsum"}
My problem is that it does not work in some cases:
*
*Case 1: VALUE -> V / A / L / U / E
*Case 2: eclipseRCPExt -> eclipse / R / C / P / Ext
To my mind, the result shoud be:
*
*Case 1: VALUE
*Case 2: eclipse / RCP / Ext
In other words, given n uppercase chars:
*
*if the n chars are followed by lower case chars, the groups should be: (n-1 chars) / (n-th char + lower chars)
*if the n chars are at the end, the group should be: (n chars).
Any idea on how to improve this regex?
A: It seems you are making this more complicated than it needs to be. For camelCase, the split location is simply anywhere an uppercase letter immediately follows a lowercase letter:
(?<=[a-z])(?=[A-Z])
Here is how this regex splits your example data:
*
*value -> value
*camelValue -> camel / Value
*TitleValue -> Title / Value
*VALUE -> VALUE
*eclipseRCPExt -> eclipse / RCPExt
The only difference from your desired output is with the eclipseRCPExt, which I would argue is correctly split here.
Addendum - Improved version
Note: This answer recently got an upvote and I realized that there is a better way...
By adding a second alternative to the above regex, all of the OP's test cases are correctly split.
(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])
Here is how the improved regex splits the example data:
*
*value -> value
*camelValue -> camel / Value
*TitleValue -> Title / Value
*VALUE -> VALUE
*eclipseRCPExt -> eclipse / RCP / Ext
Edit:20130824 Added improved version to handle RCPExt -> RCP / Ext case.
A: To handle more letters than just A-Z:
s.split("(?<=\\p{Ll})(?=\\p{Lu})|(?<=\\p{L})(?=\\p{Lu}\\p{Ll})");
Either:
*
*Split after any lowercase letter, that is followed by uppercase letter.
E.g parseXML -> parse, XML.
or
*
*Split after any letter, that is followed by upper case letter and lowercase letter.
E.g. XMLParser -> XML, Parser.
In more readable form:
public class SplitCamelCaseTest {
static String BETWEEN_LOWER_AND_UPPER = "(?<=\\p{Ll})(?=\\p{Lu})";
static String BEFORE_UPPER_AND_LOWER = "(?<=\\p{L})(?=\\p{Lu}\\p{Ll})";
static Pattern SPLIT_CAMEL_CASE = Pattern.compile(
BETWEEN_LOWER_AND_UPPER +"|"+ BEFORE_UPPER_AND_LOWER
);
public static String splitCamelCase(String s) {
return SPLIT_CAMEL_CASE.splitAsStream(s)
.collect(joining(" "));
}
@Test
public void testSplitCamelCase() {
assertEquals("Camel Case", splitCamelCase("CamelCase"));
assertEquals("lorem Ipsum", splitCamelCase("loremIpsum"));
assertEquals("XML Parser", splitCamelCase("XMLParser"));
assertEquals("eclipse RCP Ext", splitCamelCase("eclipseRCPExt"));
assertEquals("VALUE", splitCamelCase("VALUE"));
}
}
A: Brief
Both top answers here provide code using positive lookbehinds, which, is not supported by all regex flavours. The regex below will capture both PascalCase and camelCase and can be used in multiple languages.
Note: I do realize this question is regarding Java, however, I also see multiple mentions of this post in other questions tagged for different languages, as well as some comments on this question for the same.
Code
See this regex in use here
([A-Z]+|[A-Z]?[a-z]+)(?=[A-Z]|\b)
Results
Sample Input
eclipseRCPExt
SomethingIsWrittenHere
TEXTIsWrittenHERE
VALUE
loremIpsum
Sample Output
eclipse
RCP
Ext
Something
Is
Written
Here
TEXT
Is
Written
HERE
VALUE
lorem
Ipsum
Explanation
*
*Match one or more uppercase alpha character [A-Z]+
*Or match zero or one uppercase alpha character [A-Z]?, followed by one or more lowercase alpha characters [a-z]+
*Ensure what follows is an uppercase alpha character [A-Z] or word boundary character \b
A: You can use StringUtils.splitByCharacterTypeCamelCase("loremIpsum") from Apache Commons Lang.
A: Another solution would be to use a dedicated method in commons-lang: StringUtils#splitByCharacterTypeCamelCase
A: The following regex works for all of the above examples:
public static void main(String[] args)
{
for (String w : "camelValue".split("(?<!(^|[A-Z]))(?=[A-Z])|(?<!^)(?=[A-Z][a-z])")) {
System.out.println(w);
}
}
It works by forcing the negative lookbehind to not only ignore matches at the start of the string, but to also ignore matches where a capital letter is preceded by another capital letter. This handles cases like "VALUE".
The first part of the regex on its own fails on "eclipseRCPExt" by failing to split between "RPC" and "Ext". This is the purpose of the second clause: (?<!^)(?=[A-Z][a-z]. This clause allows a split before every capital letter that is followed by a lowercase letter, except at the start of the string.
A: I couldn't get aix's solution to work (and it doesn't work on RegExr either), so I came up with my own that I've tested and seems to do exactly what you're looking for:
((^[a-z]+)|([A-Z]{1}[a-z]+)|([A-Z]+(?=([A-Z][a-z])|($))))
and here's an example of using it:
; Regex Breakdown: This will match against each word in Camel and Pascal case strings, while properly handling acrynoms.
; (^[a-z]+) Match against any lower-case letters at the start of the string.
; ([A-Z]{1}[a-z]+) Match against Title case words (one upper case followed by lower case letters).
; ([A-Z]+(?=([A-Z][a-z])|($))) Match against multiple consecutive upper-case letters, leaving the last upper case letter out the match if it is followed by lower case letters, and including it if it's followed by the end of the string.
newString := RegExReplace(oldCamelOrPascalString, "((^[a-z]+)|([A-Z]{1}[a-z]+)|([A-Z]+(?=([A-Z][a-z])|($))))", "$1 ")
newString := Trim(newString)
Here I'm separating each word with a space, so here are some examples of how the string is transformed:
*
*ThisIsATitleCASEString => This Is A Title CASE String
*andThisOneIsCamelCASE => and This One Is Camel CASE
This solution above does what the original post asks for, but I also needed a regex to find camel and pascal strings that included numbers, so I also came up with this variation to include numbers:
((^[a-z]+)|([0-9]+)|([A-Z]{1}[a-z]+)|([A-Z]+(?=([A-Z][a-z])|($)|([0-9]))))
and an example of using it:
; Regex Breakdown: This will match against each word in Camel and Pascal case strings, while properly handling acrynoms and including numbers.
; (^[a-z]+) Match against any lower-case letters at the start of the command.
; ([0-9]+) Match against one or more consecutive numbers (anywhere in the string, including at the start).
; ([A-Z]{1}[a-z]+) Match against Title case words (one upper case followed by lower case letters).
; ([A-Z]+(?=([A-Z][a-z])|($)|([0-9]))) Match against multiple consecutive upper-case letters, leaving the last upper case letter out the match if it is followed by lower case letters, and including it if it's followed by the end of the string or a number.
newString := RegExReplace(oldCamelOrPascalString, "((^[a-z]+)|([0-9]+)|([A-Z]{1}[a-z]+)|([A-Z]+(?=([A-Z][a-z])|($)|([0-9]))))", "$1 ")
newString := Trim(newString)
And here are some examples of how a string with numbers is transformed with this regex:
*
*myVariable123 => my Variable 123
*my2Variables => my 2 Variables
*The3rdVariableIsHere => The 3 rdVariable Is Here
*12345NumsAtTheStartIncludedToo => 12345 Nums At The Start Included Too
A: You can use the expression below for Java:
(?<=[a-z])(?=[A-Z])|(?<=[A-Z])(?=[A-Z][a-z])|(?=[A-Z][a-z])|(?<=\\d)(?=\\D)|(?=\\d)(?<=\\D)
A: Instead of looking for separators that aren't there you might also considering finding the name components (those are certainly there):
String test = "_eclipse福福RCPExt";
Pattern componentPattern = Pattern.compile("_? (\\p{Upper}?\\p{Lower}+ | (?:\\p{Upper}(?!\\p{Lower}))+ \\p{Digit}*)", Pattern.COMMENTS);
Matcher componentMatcher = componentPattern.matcher(test);
List<String> components = new LinkedList<>();
int endOfLastMatch = 0;
while (componentMatcher.find()) {
// matches should be consecutive
if (componentMatcher.start() != endOfLastMatch) {
// do something horrible if you don't want garbage in between
// we're lenient though, any Chinese characters are lucky and get through as group
String startOrInBetween = test.substring(endOfLastMatch, componentMatcher.start());
components.add(startOrInBetween);
}
components.add(componentMatcher.group(1));
endOfLastMatch = componentMatcher.end();
}
if (endOfLastMatch != test.length()) {
String end = test.substring(endOfLastMatch, componentMatcher.start());
components.add(end);
}
System.out.println(components);
This outputs [eclipse, 福福, RCP, Ext]. Conversion to an array is of course simple.
A: I can confirm that the regex string ([A-Z]+|[A-Z]?[a-z]+)(?=[A-Z]|\b) given by ctwheels, above, works with the Microsoft flavour of regex.
I would also like to suggest the following alternative, based on ctwheels' regex, which handles numeric characters: ([A-Z0-9]+|[A-Z]?[a-z]+)(?=[A-Z0-9]|\b).
This able to split strings such as:
DrivingB2BTradeIn2019Onwards
to
Driving B2B Trade in 2019 Onwards
A: A JavaScript Solution
/**
* howToDoThis ===> ["", "how", "To", "Do", "This"]
* @param word word to be split
*/
export const splitCamelCaseWords = (word: string) => {
if (typeof word !== 'string') return [];
return word.replace(/([A-Z]+|[A-Z]?[a-z]+)(?=[A-Z]|\b)/g, '!$&').split('!');
};
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593969",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "91"
}
|
Q: Insert into table with Identity and foreign key columns I was trying to insert values from one table to another from two different databases.
My issue is I have two tables with a relation and the first table is having an identity column also.
eg table first(id, Name) - table second(id, address)
So now both the table exist with values in a db and i am trying to copy values from this db to another db.
So when I insert values from first db to second db the the first table will insert values for the Id column by itself so now I have to link that id to the second table.
How can I do that?
UPDATE using MSSQL server 2000
A: You can use @scope_identity immediately after your insert in SQL server 2000 which will give you the last id within the current scope but I'm not sure how that would work with bulk inserting of data
http://msdn.microsoft.com/en-us/library/ms190315.aspx
A: If this were SQL Server 2005 or later I would suggest using the output clause in your insert statement to retrieve the ids just inserted, but that was not available in SQL Server 2000.
If your data contains some column or series of columns which is unique other than the identity column, then you can query your first table based on that series of columns to get the ids and use that to populate your second table.
A: If the target tables were empty you could use SET IDENTITY_INSERT ON - this would allow to insert original values to identity columns, and you will not have to update referenced IDs. Of course if there is any existing ids that can overlap inserted ids - that is not the solution.
If names in first tables are unique, you could boild mapping between new and old ids and perform update something like this:
UPDATE S
SET S.id = F.id
FROM second S
INNER JOIN first_original FO ON FO.id = S.id
INNER JOIN first F ON F.name = FO.name
If names are not unique, then original ids should be saved in "first" in order to provide mapping between old and new ids. It can be temporary new column that can be deleted after ids in "second" will be updated.
Or as Rich Andrews said you could use @scope_identity, but in this case you will have to perform insert one by one - declare a cursor on source table, insert each record, get its new id and insert it into "second" table.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593972",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Get "closest" Key in Visual Basic Dictionary In Visual Basic I have a Dictionary which holds a Date as a key and a custom class as value (I will use a String in the example).
I keep track of a list where a date is saved with a value.
For example, lets say I have a dictionary with the following values:
Dim dict As Dictionary(Of Date, String)
dict.Add(DateTime.Now, "test one") // Suppose the time of this date is 12:03:10
dict.Add(DateTime.Now, "test two") // Suppose the time of this date is 13:07:20
dict.Add(DateTime.Now, "test three") // Suppose the time of this date is 14:15:30
dict.Add(DateTime.Now, "test four") // Suppose the time of this date is 15:19:40
Now the system gives me a date which does not have a value, but needs one similar to the first previous date.
Let's say I get the date with time 14:00:00, I will need the value of "test two" because 13:07:20 is the first key lower than 14:00:00 (a key which is not actually available in the dictionary keys).
Assuming that the list could be very big, is there a way/what would be the best way to find the key I am looking for?
A: The Keys method will give you an array containing all the keys.
Dim k As Variant
k = dict.Keys
You can then loop through that array to find the key that satisfies the criterion. Here's an example, not thoroughly checked...
Dim myDate As Variant
Dim myKey As Variant
myDate = 1234 ' or whatever your target date is
Dim i As Long
myKey = k(0)
For i = 1 To UBound(k)
If k(i) < myDate And k(i) > myKey Then
myKey = k(i)
End If
Next i
myKey should now contain the key that satisfies your criterion.
A: (Couldnt post on my own question within 8 hours...)
Using my dictionary and using the dict.Keys I did:
Dim lookupDate As Date = Date.Parse("01/01/2008 12:17:39")
Dim query = dict.Keys.AsQueryable().Where(Function(singleKey) singleKey < lookupDate)
Dim result As String = query.Last().ToString()
This solution should have better performance because of the iQueryable if im correct.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593974",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Why Clojure/Lisp Programs are faster than other dynamic languages? Based on language shootouts in a past few years, Clojure and other Lisps consistently perform better than most other dynamic languages. Why is that so?
Is it because of its homoiconicity?
Edit:
I did not know that Clojure is compiled into bytecode just like Java and Scala.
This stackoverflow thread threw light on why Clojure reaps the advantage of being both compiled and interpreted.
A: It is almost impossible to answer this question - it depends very much on how well the benchmark code is written, what exactly is being tested, whether you are allowed to use libraries that exploit native code, whether you are writing "idiomatic" code or optimising for performance etc.
So as always, you should treat all microbenchmarks with caution.
Having said that, the following reasons might give Clojure an advantage however in certain circumstances:
*
*Clojure is always compiled - first down to bytecode, then down to native code by the JVM JIT compiler. This can give it a speed advantage in many cases, particularly over langauges that rely on some form of interpretation. In theory at least, you should be able to match pure Java speed in any circumstance where Clojure enables you to produce the same bytecode (which is reasonably often, though not always....)
*Clojure can exploit JVM primitives and static typing - despite being a dynamic language, Clojure will compile statically types or primitive code if you give it enough hints. This can easily give a 10x boost in performance, though at the expense of making your code a bit longer/uglier.....
*Clojure has heavily optimised certain data structures and operations - in particular the immutable persistent data structures and certain functional programming constructs like "reduce".
*Macros enable powerful compile-time optimisations - if you use macros cleverly, you can do some quite sophisticated optimisations at compile time, effectively using code-generation to produce the code that will be most efficient at runtime. This is an advantage many Lisps share (especially Common Lisp, which was one of the big inspirations for Clojure). As nulvinge points out, homoiconicity isn't strictly necessary to achieve this (C++ also has macros!), but being a homoiconic language makes macros a lot easier.
*The modern JVMs are brilliantly engineered - Clojure takes advantage of the thousands of man-years of engineering that have gone into the JVM, the Java runtime libraries, the garbage collection algorithms etc. Non-JVM languages don't get these benefits.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593975",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "14"
}
|
Q: C# IComparer is returning unexpected result when comparing same strings I have a situation where all of my list members have same ID (Id is string and not Integer). As part of business rules I need to sort the list in ascending order. My original implementation is quite similar to below. I was expecting to get unchanged list after applying sort as all list members have same ID but to my surprise the result is different.
Below is my original list before Sort.
Id: D1.2 Name: Pachycephalosaurus
Id: D1.2 Name: Amargasaurus
Id: D1.2 Name: Mamenchisaurus
Id: D1.2 Name: Deinonychus
Id: D1.2 Name: Coelophysis
Id: D1.2 Name: Oviraptor
Id: D1.2 Name: Tyrannosaur
Sort with alternate comparer:
Id: D1.2 Name: Pachycephalosaurus
Id: D1.2 Name: Oviraptor
Id: D1.2 Name: Coelophysis
Id: D1.2 Name: Deinonychus
Id: D1.2 Name: Mamenchisaurus
Id: D1.2 Name: Amargasaurus
Id: D1.2 Name: Tyrannosaur
Code
class Program
{
static void Main(string[] args)
{
new ComparerIssue().MainMethod();
Console.ReadKey();
}
}
internal class DinoComparer : IComparer<Dinosaur>
{
public int Compare(Dinosaur dinosaur1, Dinosaur dinosaur2)
{
return Compare(dinosaur1.Id, dinosaur2.Id);
}
private int Compare(string x, string y)
{
if (x == y)
{
return 1; //I have tried using 1 and 0; -1 throws exception
}
return x.CompareTo(y);
}
}
public class ComparerIssue
{
public void MainMethod()
{
List<Dinosaur> dinosaurs = new List<Dinosaur>();
dinosaurs.Add(new Dinosaur() { Id = "D1.2", Name = "Pachycephalosaurus" });
dinosaurs.Add(new Dinosaur() { Id = "D1.2", Name = "Amargasaurus" });
dinosaurs.Add(new Dinosaur() { Id = "D1.2", Name = "Mamenchisaurus" });
dinosaurs.Add(new Dinosaur() { Id = "D1.2", Name = "Deinonychus" });
dinosaurs.Add(new Dinosaur() { Id = "D1.2", Name = "Coelophysis" });
dinosaurs.Add(new Dinosaur() { Id = "D1.2", Name = "Oviraptor" });
dinosaurs.Add(new Dinosaur() { Id = "D1.2", Name = "Tyrannosaur" });
Display(dinosaurs);
DinoComparer dc = new DinoComparer();
Console.WriteLine("\nSort with alternate comparer:");
dinosaurs.Sort(dc);
Display(dinosaurs);
}
private static void Display(IEnumerable<Dinosaur> list)
{
Console.WriteLine();
foreach (Dinosaur dinosaur in list)
{
Console.WriteLine("Id: " + dinosaur.Id + " Name: " + dinosaur.Name);
}
}
}
public class Dinosaur
{
public string Id { get; set; }
public string Name { get; set; }
}
A: You should return only return x.CompareTo(y); from your private int Compare(string x, string y) method, since you are comparing only based on strings...
Like this:
private int Compare(string x, string y)
{
return x.CompareTo(y);
}
Hope it helps,
Ivan
A: You're violating the implied contract of IComparer since, Compare(dino1,dino2) and Compare(dino2,dino1) will return that dino1 is greater than dino2 and dino2 is greater than dino1. Since you're not properly defining an order, the results will tend to be "random" at best.
If you can't define a total order based purely on the ID values, then just using the ID values can't be the basis for your IComparer implementation.
A: You're breaking the contract for IComparable; when your Ids are equal, you're actually saying one is greater than the other (so needs to be sorted)
From the documentation:
Less than zero This object is less than the other parameter.
Zero This object is equal to other.
Greater than zero This object is greater than other.
An alternate implementation for your Compare would be:
private int Compare(string x, string y)
{
return x.CompareTo(y);
// There would be potential to do secondary sorts if the line above only returned zero - you'd obviously need to capture and test the result...
}
A: From MSDN:
This method uses Array.Sort, which uses the QuickSort algorithm. This
implementation performs an unstable sort; that is, if two elements are
equal, their order might not be preserved. In contrast, a stable sort
preserves the order of elements that are equal.
(my emphasis)
Which is exactly what you see happen.
EDIT
As hinted by others, you can use the linq method OrderBy, which does perform a stable sort:
var d2 = dinosaurs.OrderBy(d => d.Id).ToList();
A: Personally I would use the answer from icesar, but use the static string.Compare method instead:
return string.Compare(x, y);
This makes the compare a little "safer", you don't have to check for nulls.
Alternatively a simple LINQ statement will do the job:
myList = myList.OrderBy(p => p.ID).ThenBy(p => p.Name);
You should also note that sorting by ID as a string will lead to erroneous results once you get a few items in the list; 21 will be placed before 3. You may want to consider casting it to an int at some stage.
A: Sadly, as far as I know, there is no stable sort method implemented in Frameworks. You'll have to do it yourself.
This
http://www.csharp411.com/c-stable-sort/
is a nice example of stable sort method.
A: I sincerely thanks everyone for the feedback. I have implemented stable sort using insertion method found at http://www.csharp411.com/c-stable-sort/. I am including the final code for reference.
internal class DinoComparer : IComparer<Dinosaur>
{
public int Compare(Dinosaur dinosaur1, Dinosaur dinosaur2)
{
return Compare(dinosaur1.Id, dinosaur2.Id);
}
private int Compare(string x, string y)
{
return x.CompareTo(y);
}
}
public class ComparerIssue
{
public void MainMethod()
{
List<Dinosaur> dinosaurs = new List<Dinosaur>();
dinosaurs.Add(new Dinosaur() { Id = "D1.2", Name = "Pachycephalosaurus" });
dinosaurs.Add(new Dinosaur() { Id = "D1.2", Name = "Amargasaurus" });
dinosaurs.Add(new Dinosaur() { Id = "D1.2", Name = "Mamenchisaurus" });
dinosaurs.Add(new Dinosaur() { Id = "D1.2", Name = "Deinonychus" });
dinosaurs.Add(new Dinosaur() { Id = "D1.2", Name = "Coelophysis" });
dinosaurs.Add(new Dinosaur() { Id = "D1.2", Name = "Oviraptor" });
dinosaurs.Add(new Dinosaur() { Id = "D1.2", Name = "Tyrannosaur" });
Display(dinosaurs);
//Console.WriteLine("\nSort with unstable comparer:");
//dinosaurs.Sort(new DinoComparer());
Console.WriteLine("\nSort with stable comparer:");
dinosaurs = (List<Dinosaur>)InsertionSort.Sort(dinosaurs, new DinoComparer().Compare);
Display(dinosaurs);
}
private static void Display(IEnumerable<Dinosaur> list)
{
Console.WriteLine();
foreach (Dinosaur dinosaur in list)
{
Console.WriteLine("Id: " + dinosaur.Id + " Name: " + dinosaur.Name);
}
}
}
public class Dinosaur
{
public string Id { get; set; }
public string Name { get; set; }
}
public class InsertionSort
{
public static IList<T> Sort<T>(IList<T> list, Comparison<T> comparison)
{
if (list == null)
throw new ArgumentNullException("list");
if (comparison == null)
throw new ArgumentNullException("comparison");
int count = list.Count;
for (int j = 1; j < count; j++)
{
T key = list[j];
int i = j - 1;
for (; i >= 0 && comparison(list[i], key) > 0; i--)
{
list[i + 1] = list[i];
}
list[i + 1] = key;
}
return list;
}
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593979",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: generating Localizable.strings creates strange output When I use genstrings -o en.lproj *.m it generates the Localizable.strings file with entries in this structure:
/* this is the text: %@ ID: %02X */
"this is the text: %@ ID: %02X" = "this is the text: %1$@ ID: %2$X";
Please notice that it makes from %@ -> %1$@
Why is this? I always have to change it back to %@ manually.
Thanks
A: Did you use the "-j" option? It produces java localized string (which have the format like %1$@).
[EDIT]
Sorry, looked at the wrong manual page. Please use the option -noPositionalParameters to turn off generation of positional parameters. -> Info's here
A: You don't need to change it back, since %1$@ refers to the first argument given to your format string.
Actually, in a case different from yours, it might happen that the order of the arguments changes from a translation to another. For example, if your code uses a format to display some player property value like:
let fmt = NSLocalizedString("Player property value", comment: "The player property value")
String(format:fmt, playerName, playerProperty, value)
You might have in the "en.lproj/Localizable.strings":
/* The player property value */
"Player property value" = "Player %1$@'s %2$@ is %3$d"
and in the "fr.lproj/Localizable.strings":
/* The player property value */
"Player property value" = "Le %2$@ du joueur %1$@ is %3$d"
or:
/* The player property value */
"Player property value" = "Le joueur %1$@ a %3$d points de %2$@"
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593982",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Sometimes my icons in my list view are not showing My problem is that I have implemented a custom arrayadapter, that fetches images from an url and sets them to an imageview. It works, sort of. Sometimes some of the images are not showing up. Somtimes it's only one image, somtimes it's three and in no apparent order. Only thing that's reasonably consistent is that it seems to be image number 3 in my arraylist.
My custom adapter:
public CustomAdapter( Context context, int textViewResourceId, List items )
{
super( context, textViewResourceId, items );
this.items = items;
}
@Override
public View getView( int position, View convertView, ViewGroup parent )
{
View v = convertView;
if ( v == null )
{
LayoutInflater vi = ( LayoutInflater ) getContext().getSystemService( Context.LAYOUT_INFLATER_SERVICE );
v = vi.inflate( R.layout.list_item, parent, false );
}
Object o = items.get( position );
if ( o != null )
{
TextView textView = ( TextView ) v.findViewById( R.id.listItem );
ImageView imageView = ( ImageView ) v.findViewById( R.id.icon );
if ( textView != null )
{
textView.setText( o.toString() );
}
if ( imageView != null )
{
if ( o instanceof XmlGuide )
{
try
{
imageView.setImageBitmap( downloadIcon( ( ( XmlGuide ) o ).getIcon() ) );
}
catch( Exception e )
{
e.printStackTrace();
}
}
}
}
return v;
}
private Bitmap downloadIcon( String uri ) throws Exception
{
URL url = new URL( uri );
InputStream stream = url.openStream();
Bitmap icon = BitmapFactory.decodeStream( stream );
stream.close();
return icon;
}
A: having a blocking network part during your getView is not recommanded.
use
setImageUri(Uri.parse(o.getIcon());
is certainly better.
A: I finally figured out the problem. The problem is that Android < 2.3 is not handling jpg images very well. There is one fix, which will fix this in most cases, but not all.
You can read more about it here: http://code.google.com/p/android/issues/detail?id=6066
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593986",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Processing my own escape characters using Regular expression First of all I have to apologize for my poor English, Please let me explain my case,
Assume that I have 2 text boxes for a user to input. On the server side, I want to combine the
two strings as a single string delimited by ',' character. For example, If a user
inputs the first text box as "hello world" and the second text box "foo bar",
the final string should be "hello world,foo bar". This string needs to be split
later on for other operations to utilize its content. So when the string is split, as the
',' character is used as a delimitor, the result string
will be
string[0] = "hello world"
string[1] = "foo bar"
respectively.
Of course this is vulnerable when a user types ',' character in their string, resulting
in a string that cannot be split correctly. For example, when the user enters "hello,world"
in the first text box and "foo,bar" in the second text box, the final string would be
"hello,world,foo,bar" and the split result would wrongly be 4 separate strings.
I came up with an idea of custom escape characters.That is if a user inputs ',' character, it must be prepended with '/'
character on the server side. For example, If a user inputs "hello,world" and "foo,bar"
, the final string will be "hello/,world,foo/,bar" which can now be split because the exact
delimitor is known which is a single ',' character without '/' character prepending it.
I wrote some java code to process it as follows:
String testText = "hello/,world,foo/,bar";
String[] split = testText.split("[^/],");
for(int i=0; i<split.length; i++)
{
System.out.println(split[i]);
}
The returned result is
string[0] = hello/,worl
string[1] = foo/,bar
which is incorrect because the 'd' character of the word "world" is lost.
It seems that the delimiter for this case is some character which is not / followed by ',' which is quite understandable.
But I want something like "split the string with the delimiter ',' which only follows the character that is not '/' character. So apply to my case, only ',' character in the middle
of the string will be split so the final result will be correct as follows:
string[0] = hello/,world
string[1] = foo/,bar
I realize that I may have to rewrite my regular expression but I don't know how.
Any suggestion would be welcome.
A: Use a negative look behind
testText.split("(?<!/),");
The neagative lookbehind ensures that there is no / before the , without matching it.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593990",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Confusion with Entity Framework versions I am having hard time understanding the Entity Framework versions released by Microsoft. I have a base entity framework version of 4.1 which didn't support enums by itself. After the June 2011 CTP was released I was excited to use it so that I can get LINQ support for enums. So I planned to develop my application for the time being using enums support of June 2011 CTP, hoping that by the time my application was ready, the next version would appear and support enums. After June 2011 CTP, the Entity Framework 4.1 Update 1 was released which to my understanding doesn't support enums. After that version 4.2 appeared and I doubt again whether it supports enums. So being the first time that I am developing application using Microsoft technologies, I am a little confused. I have a couple of issues
*
*If CTP version is released, then shouldn't the next release be based on that rather than discontinuing what was supported earlier in the CTP as a major feature ?
*If I need to deploy my application(with EntityFramework June 2011 CTP) on a separate machine for testing, will I need to install anything extra for the Entity Framework June 2011 CTP version to work.
Please pardon me if I don't understand the versions of Entity Framework correctly. Also the first issue above may be my ignorance, but what I am primarily concerned with is the second issue.
A: *
*No. CTP is preview of something that can be released. But when it will be released nobody knows. It even be never released or the final version doesn't have to include enums at all. Current CTP doesn't have go live licence so you can easily invest into development of something that would never reach production code.
*You will need .NET 4.0 and that CTP.
CTPs are only for previewing new API not for real development because any next CTP version or RTM version can introduce breaking changes or remove features previously available in CTP. In case of EF this already happened before releasing EF 4.1 where custom conventions were completely removed from RTM so it can happen again. In case of enums I somehow hope that support will be either completely redesigned or removed because current implementation is not sufficient.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7593997",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Retrieving the intent values from another class My question is a bit basic. I've been learning to code on JAVA and android. Here I am a bit confused on how to call the values that I have sent via an intent.
In my first activity this is the intent that I am using.
Intent intent = new Intent(MainActivity.this, Secondactivity.class);
String regName1 = regName;
intent.putExtra(regName1, regNameSplit[0]);
startActivity(intent);
Here regName1 will contain three values. SessionID,URL,Name split by "-".
In my SecondActivity
public class Secondactivity extends Activity {
public final String TAG = "###---Secondactivity---###";
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.secondactivity);
Log.i(TAG,"before if statement");
if (getIntent().getStringExtra("regName1") != null){
getIntent().getStringExtra("regName1").split("-");
String[] str = "regName";
Log.i(TAG, ""+str[0]+str[1]+str[2])
}
}
}
The value if regName1 always comes as null.
A: and you are sure that the content of the variable regName is actually "regName"?
cause you set the value using
intent.putExtra(regName, ... )
and you get the value using
intent.getStringExtra("regName")
A: use firstactivity
dont use
String regname1=regname;
just:
intent.putExtra("regName1", regNameSplit[0]);
in second Activity
if (getIntent().getStringExtra("regName1") != null){
//
}
A: This line
intent.putExtra(regName1, regNameSplit[0]);
Needs to be like this instead
intent.putExtra("regName1", regNameSplit[0]); // note the quotes
BUT you are using regName1 as a variable... how do you expect the second class to know that variable?
Use a string resource instead.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594003",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: how to get phone number from my Contacts on android programing i have EditText and button on my form.
how to do this:
when i press the button i want to open all my Contacts,
and when i pick one - i what that his phone number will be in the EditText
thanks in advance
A: use this links May be it's useful for you.
http://www.java2s.com/Open-Source/Android/Contact/spelldial/org/ravelin/android/ContactAccessor.java.htm
http://developer.android.com/resources/samples/ContactManager/index.html
http://code.google.com/p/android-business-card/source/browse/trunk/android-business-card/BusinessCard/src/com/example/android/?r=3#android%2Fbusinesscard
A: In this post you can read contact list.
How to call Android contacts list?
there are some methods...
Then set EditText with contact list content
void setText(CharSequence text, TextView.BufferType type)
Sets the text that this TextView is to display (see setText(CharSequence)) and also sets whether it is stored in a styleable/spannable buffer and whether it is editable.
:-)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594004",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Fetching column data using IRow::GetColumns (OLE DB)(MSSQL) In my application I am trying to read data from a VARCHAR(4000) column. Since the column is 4000 bytes, I have an application buffer which is big enough to handle it. But at the moment I have only 10 bytes of data in the column. After doing IRow->GetColumns(), not sure how to copy only 10 bytes of data. I do the following, but get all 4000 bytes, so when the data is printed, it is 10 characters of actual data padded with 3990 whitespaces.
retcode = WideCharToMultiByte(CP_UTF8, 0, (WCHAR*)pDBColumnAccess[nCol].pData, -1, (char *)pReadBuf, pDBColumnAccess[nCol].cbDataLen, NULL, NULL);
I thought pDBColumnAccess.cbDataLen would have only 10, but it has the value 4000.
How to read the exact number of bytes from the column?
Thanks.
A: Figured out a way for this, not sure if this is the actual solution or just a workaround.
If ANSI_PADDING is set to OFF before the table is created, padding of whitespaces after the actual data will not happen. You can see the property value "TrimTrailingBlanks" in sp_help of the table.
Thanks.
A: You should be setting a DBBINDING that includes DBPART_LENGTH to get the length of the field. To illustrate this, I've created some VARCHAR data in SQL Server using the following DDL:
CREATE TABLE NEWS
(
ID INT NOT NULL,
ARTICLE NVARCHAR(4000)
);
INSERT INTO NEWS (1, 'Today is a sunny day.');
Then I use the following ATL based C++ code sample to read the ARTICLE field. If you put breakpoints in the code, you will see it will come back with
*
*data.nArticleLength = 21
*data.szArticle = "Today is a sunny day."
Here's the code sample sample:
#include <stdio.h>
#include <tchar.h>
#include <windows.h>
#include <oledb.h>
#include <atlbase.h>
int _tmain(int argc, _TCHAR* argv[])
{
HRESULT hr = S_OK;
hr = CoInitializeEx(NULL, COINIT_MULTITHREADED);
// Connect to SQL Server.
CComPtr<IDBInitialize> spIDBInitialize;
hr = spIDBInitialize.CoCreateInstance(OLESTR("SQLNCLI"));
CComPtr<IDBProperties> spIDBProperties;
hr = spIDBInitialize->QueryInterface(IID_IDBProperties, (void**) &spIDBProperties);
CComVariant varDataSource(OLESTR("InsertYourSQLServer"));
CComVariant varCatalog(_T("InsertYourDatabase"));
CComVariant varUserID(_T("InsertYourUserName"));
CComVariant varPassword(_T("InsertYourPassword"));
DBPROP rgProps[4] =
{
{ DBPROP_INIT_DATASOURCE, DBPROPOPTIONS_REQUIRED, 0, DB_NULLID, varDataSource },
{ DBPROP_INIT_CATALOG, DBPROPOPTIONS_REQUIRED, 0, DB_NULLID, varCatalog },
{ DBPROP_AUTH_USERID, DBPROPOPTIONS_REQUIRED, 0, DB_NULLID, varUserID },
{ DBPROP_AUTH_PASSWORD, DBPROPOPTIONS_REQUIRED, 0, DB_NULLID, varPassword }
};
DBPROPSET propSet = {rgProps, 4, DBPROPSET_DBINIT};
hr = spIDBProperties->SetProperties(1, &propSet);
spIDBProperties = NULL;
hr = spIDBInitialize->Initialize();
// Execute the query.
CComPtr<IDBCreateSession> spIDBCreateSession;
hr = spIDBInitialize->QueryInterface(IID_IDBCreateSession, (void**) &spIDBCreateSession);
CComPtr<IDBCreateCommand> spIDBCreateCommand;
hr = spIDBCreateSession->CreateSession(NULL, IID_IDBCreateCommand, (IUnknown**) &spIDBCreateCommand);
spIDBCreateSession = NULL;
CComPtr<ICommandText> spICommandText;
hr = spIDBCreateCommand->CreateCommand(NULL, IID_ICommandText, (IUnknown**) &spICommandText);
spIDBCreateCommand = NULL;
hr = spICommandText->SetCommandText(DBGUID_SQL, OLESTR("SELECT ID, ARTICLE FROM NEWS"));
DBROWCOUNT cRowsAffected = 0;
CComPtr<IRowset> spIRowset;
hr = spICommandText->Execute(NULL, IID_IRowset, NULL, &cRowsAffected, (IUnknown**) &spIRowset);
spICommandText = NULL;
// Retrieve records.
HROW hRow = NULL;
HROW *rghRow = &hRow;
DBCOUNTITEM cRowsObtained = 0;
hr = spIRowset->GetNextRows(DB_NULL_HCHAPTER, 0, 1, &cRowsObtained, &rghRow);
while (hr == S_OK && cRowsObtained == 1)
{
// Fetch the ARTICLE field.
struct
{
DBSTATUS dbArticleStatus;
ULONG nArticleLength;
char szArticle[4000 + 4];
} data = {0};
DBBINDING Binding = {0};
Binding.iOrdinal = 2;
Binding.obValue = sizeof(DBSTATUS) + sizeof(ULONG);
Binding.obLength = sizeof(DBSTATUS);
Binding.obStatus = 0;
Binding.pTypeInfo = NULL;
Binding.pObject = NULL;
Binding.pBindExt = NULL;
Binding.dwPart = DBPART_STATUS | DBPART_LENGTH | DBPART_VALUE;
Binding.dwMemOwner = DBMEMOWNER_CLIENTOWNED;
Binding.eParamIO = DBPARAMIO_NOTPARAM;
Binding.cbMaxLen = 4000 + 1;
Binding.wType = DBTYPE_STR;
Binding.dwFlags = 0;
Binding.bPrecision = 0;
Binding.bScale = 0;
CComPtr<IAccessor> spIAccessor;
hr = spIRowset->QueryInterface(IID_IAccessor, (void**) &spIAccessor);
HACCESSOR hAccessor = NULL;
hr = spIAccessor->CreateAccessor(DBACCESSOR_ROWDATA, 1, &Binding, 0, &hAccessor, NULL);
hr = spIRowset->GetData(hRow, hAccessor, &data);
DBREFCOUNT cRefCount = 0;
hr = spIAccessor->ReleaseAccessor(hAccessor, &cRefCount);
spIAccessor = NULL;
// @@TODO: Do something with data.szArticle and data.nArticleLength
// ...
// Fetch next row of data.
hr = spIRowset->ReleaseRows(1, rghRow, NULL, NULL, NULL);
cRowsObtained = 0;
hr = spIRowset->GetNextRows(DB_NULL_HCHAPTER, 0, 1, &cRowsObtained, &rghRow);
}
// Release everything
spIRowset = NULL;
spIDBInitialize = NULL;
CoUninitialize();
return 0;
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594005",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to open thumbnail wrapper of the image gallery automatically when the page loads ? (jQuery) I need to tell you that i'm very new to jquery and still learning, please don't laugh at this. I wanted to have an image gallery on my website and found this beautiful gallery that uses jquery. Here is the link for it:
http://tympanus.net/Tutorials/ThumbnailsNavigationGallery/
So there is this snippet that helps the user to click on the album or rather the arrow next to it, to open and close the thumbnail wrapper for the album. All I want is for the first album to open automatically when the webpage is loaded completely. I guess we might have to use the .load() method but I'm not sure how to use it. The code that is inserted here has both the functions to open and close the album, I just wanted to automate the opening part.
//clicking on the menu items (up and down arrow)
//makes the thumbs div appear, and hides the current
//opened menu (if any)
$list.find('.st_arrow_down').live('click', function () {
var $this = $(this);
hideThumbs();
$this.addClass('st_arrow_up').removeClass('st_arrow_down');
var $elem = $this.closest('li');
$elem.addClass('current').animate({
'height': '170px'
}, 200);
var $thumbs_wrapper = $this.parent().next();
$thumbs_wrapper.show(200);
});
$list.find('.st_arrow_up').live('click', function () {
var $this = $(this);
$this.addClass('st_arrow_down').removeClass('st_arrow_up');
hideThumbs();
});
I tried getting help from the original author of this script but unfortunately she is not responding. Looking forward to your kind assistance. Thanks in advance!!
A: This 2 lines:
$list.find('.st_arrow_down').live
and
$list.find('.st_arrow_up').live
search for HTML elements with class="st_arrow_down" or class="st_arrow_down"
and bind event "click" on these
This code on
$(document).ready(function () {
var $elem = $('.album').first();
$elem.addClass('current').animate({'height':'170px'},200);
$elem.show(200);
var cnt = $elem.find('.st_wrapper').first().css('display','block');
});
When DOM is ready, you search first album then show animation and display the imgs
Bye
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594009",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: to get link clicked in javascript/firefox-adon Below is a code snippet for a Firefox add-on whose part of the job is to get the navigation details of the user (from which page to which page etc), but the code I used doesn't seem to work:
window.document.onunload = function()
{
alert(document.location.href);
alert(document.referrer);
}
IMPORTANT NOTE: The onunload event for the window is called when the browser is closed. I want the function to be called when each page in the browser is unloaded.
A: The event handler should be binded to the window object, not to window.document. Any event listener which would be applied using <body on{name of event} ...> should dynamically be added to window instead of document / document.body.
A: window.onunload = funcRef;
For example: <title>onunload test</title>
<script type="text/javascript">
window.onunload = unloadPage;
function unloadPage()
{
alert("unload event detected!");
}
</script>
Refer DOM section in Firefox/XUL: https://developer.mozilla.org/en/DOM/window.onunload
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594019",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Grant application access to UAC protected registry section I have a legacy USB device driver which reads and writes data from and to the Windows registry to HKEY_LOCAL_MACHINE/SOFTWARE/COMPANY/PRODUCT.
I am not able to change this so I need a workaround because I noticed that on Windows Vista and Windows 7 with UAC enabled the function that performs the write returns an error. My guess is that is simply has no access rights.
My current workaround is to launch my application with administrative privileges but as you might guess this is not a very nice solution. Since the registry is accessed when the USB device is initialized when the application starts I also cannot simply request a relaunch.
I know that I can give access rights to certain folders on the system with cacls from my installer (which runs with administrative privileges) but is there something similar I can do to grant this to this specific registry entry? (I would like both grant and revoke commands.)
A: Giving non-admin users write permissions to HKLM should be avoided. If you still need to do it, however, you could use SetACL to set/remove permissions. SetACL is available as a standalone command-line executable and as a COM object.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594023",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Converting String to float in ios Hello friends I Have a float type variable ,which contains a total price of specific item,so first I have converted into NSString..below is my code
float total;
[grandTotal setText:[NSString stringWithFormat:**@"$%.2f"**,total]];
so here grandTotal is of type UILabel..where I want the total in the format which I have written in the code
now again when i try to covert to do this
float previousTotal = [[grandTotal text] floatValue];
I am getting value of previousTotal = zero.
So I think their is issue with $ sign how to solve this is issue..
A: In your case you can solve it by using
float previousTotal = [[[grandTotal text] stringByReplacingOccurrencesOfString:@"$" withString:@""] floatValue];
But I think it is better to pass directly your float value.
A: I think its better to use
float previousTotal=total;
that is fare and simple.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594031",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Horrible "Callback chains" in winforms application I'm working on a winforms application that is very complicated, and has massive callback chains being passed around all over the place.
As an example loosely based on this code, there could be a "Manager" class, that spawns a class "SetUpWorkerThreads" class, which creates a "HandleWorker" thread for say 10 workers.
The worker thread needs to call back to the manager class on occasion, to achieve this the code looks like this:
public class Manager
{
public delegate void SomethingHappenedHandler();
private void Init()
{
var x = new SetUpWorkerThreads(SomethingHappened);
}
private void SomethingHappened()
{
// Handle something happened
}
}
public class SetUpWorkerThreads
{
private readonly Manager.SomethingHappenedHandler _somethingHappened;
public SetUpWorkerThreads(Manager.SomethingHappenedHandler somethingHappened)
{
_somethingHappened = somethingHappened;
}
public void SetupTheThreads()
{
// Contrived!
for (int x=0; x<10; x++)
{
var worker = new Worker(_somethingHappened);
new Thread(worker.DoingSomething).Start();
}
}
}
public class Worker
{
private readonly Manager.SomethingHappenedHandler _somethingHappened;
public Worker(Manager.SomethingHappenedHandler somethingHappened)
{
_somethingHappened = somethingHappened;
}
public void DoingSomething()
{
// ... Do Something
_somethingHappened();
}
}
In reality, there can be many more classes involved, each passing around a mass of callbacks for various things. I realise that poor class/application design is playing a part in this, but are there better ways to go about handling these interactions between classes, specifically in winforms apps, and when a lot of threading is going on?
A: I can't see that the threading makes it more or less problematic.
One alternative is to use events instead of callbacks, but that won't break up the long chains and will give you an unsubscribing hell too.
One possible approach is to create an object responsible for handling all the events. Either as a singleton or as a single object that you pass to all your threads (instead of the callbacks). Then you can have a simple interface on the EventRouter object to raise events from the threads. You can then subscribe to events on the EventRouter where you need to handle "something happened".
Edit
Something the GoF pattern Mediator but with a publisher-subscriber twist.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594037",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Generate colors with JavaScript I want to add functionality to my application that randomly generates a color scheme based on some color, for example #0080C8. So, when I click a button, it takes the base color and generates a list of colors, each generated with its own parameter, for example, lighten by 20% for one, and darken by 10% for another one.
So, what I wonder about, is there a ready-to-use JS library that has such methods like darken, lighten, and so on?
A: See this JQuery plugin:
http://www.xarg.org/project/jquery-color-plugin-xcolor/
A: color blender is an oldie but a goodie. i love it. http://meyerweb.com/eric/tools/color-blend/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594040",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Display image if flash is not installed I have a simple aspx web page that includes a flash video. I'd like to replace the video with a jpeg for those browsers that don't support flash. Does anyone know of an example showing how to do this?
Here's the flash div from my aspx:
<div id="flash">
<object classid="clsid:D27CDB6E-AE6D-11cf-96B8-444553540000" codebase="http://download.macromedia.com/pub/shockwave/cabs/flash/swflash.cab#version=7,0,19,0"
width="600" height="197" title=""
style="z-index: 1; font-family: georgia;">
<param name="movie" value="intro.swf" />
<param name="quality" value="high" />
<param name="wmode" value="opaque" />
<embed src="intro.swf" quality="high" pluginspage="http://www.macromedia.com/go/getflashplayer"
type="application/x-shockwave-flash" width="600" height="197"></embed>
</object>
</div>
A: Generally, I would recommend using SwfObject for embedding Flash in HTML, and taking care of Flash Player detection. It has become more or less the de facto standard for doing so, and has a really simple mechanism for what you want to do, to display alternative content when Flash Player is not available.
http://code.google.com/p/swfobject/
Edit: I see now that Adrian already mentioned SwfObject in his answer.
A: HttpContext.Current.Request.Browser.ActiveXControls
You can find how it works on that link.
I recommend to implement the fallback on the client side(browser) also.
http://blog.deconcept.com/swfobject/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594042",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: can we use `:method => :post` parameter in `link_to` tag to hide parameter from URL? In the API for link_to, you can see, you can pass an arguement, :method => :post. In Rails 2, it creates a form with POST verb and submits the form on clicking the link. But, can this be used to pass hidden fields to the form without appearing in URL? I mean building something like this:
<form name="test_form" action="/test/view" method="post">
<input type="hidden" id="flag" name="flag" value=3 />
</form>
<a href="#" onclick="document.form.test_form.submit()">View</a>
that is something which does not make the flag parameter to appear in the url. I tried using link_to with :method => :post, but I am not sure how to pass the parameter flag to the link_to. When I tried this link_to "View", {:controller => :test, :action => :view, :flag => 1}, :method => :post, it is creating a form, but the url is still /test/view?flag=1.
A: I believe all params passed to link_to will become a part of the URL. The solution is to either create a form by hand, or write your own helper to achieve exactly what you want.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594047",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Make a jquery tooltip dynamic How can make a dynamic jQuery tooltip with .mousemove, as that when mouse enter on words Tooltip1 Or Tooltip2 Or Tooltip3 show contents same tooltip.
Here is a sample of my html: http://jsfiddle.net/JGx52/4/
<ul>
<li class="style">
<div class="tooltip" style="bottom: 406px; left: 565px; opacity: 0.9; display: none; ">
Simple or Rich A simple call such as $("img[title]").tooltip(); will enable tooltips by taking advantage of the element's title attribute. If you want complex tooltips with images, tables, forms and links that's possible by placing the tooltip element manually next to the trigger element. Configure design, timing and positioning Use CSS to create rounded borders, arrows, gradients or shadows. Big or small, high or low. Use the configuration to tweak pre and post-delays and positioning to your personal needs. Fading, sliding, dynamic Tooltip comes with two built-in effects: toggle, and fade and one separate effect, slide, and you can easily build your own effects. The dynamic plugin will dynamically change the tooltip's position so that it always stays in the viewport. File size: 1.10 Kb This tool has all the features and configuration options you'll possibly need, such as effect and a plugin framework, scripting API and an event model. A smaller codebase is easier to control and results in snappier behaviour. Without gzipping the size is 3.5 Kb.
</div>
<a href="" class="tool_tip" title="">ToolTip1</a></li>
<li class="style">
<div class="tooltip">
jQuery Lint (edge)
</div>
<a href="" class="tool_tip" title="">ToolTip2</a></li>
<li class="style">
<div class="tooltip">
Please read the documentation. For updates please follow our blog, tweets or become a fan.
</div>
<a href="" class="tool_tip" title="">ToolTip3</a></li>
</ul>
A: I'm not entirely sure how you want this presented, but with the provided CSS and markup, this works:
$('a.tool_tip').hover(function() {
$(this).prev('.tooltip').show();
}, function() {
$(this).prev('.tooltip').hide();
});
A: i think this is what you are looking for http://jsfiddle.net/jalbertbowdenii/QGTTN/10/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594049",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: PHP content management system which tracks content through git Are there any content management systems which use git for tracking content and support markdowns? I have heard of git-blog and WiGit , any other suggestions would be appreciated.
A: Take a look at Phrozn: http://www.phrozn.info/en/ - it's pretty much a port of Jekyll to PHP.
A: I made Orbiter (on GitHub) for creating simple websites out of markdown documents via PHP. It uses Mustache for templating and supports Markdown by default. It uses plain text files as source documents so you can use both Git and Dropbox for syncing the documents. It is also dynamic, which means you don't have to manually "generate" your website after every update.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594054",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "8"
}
|
Q: SQLite: Order by 'insertOrderinDB' i need to know how to make a select with the insert order in DB without making any index field by my own . May be this posible?
And , the insertion order in a transaction is linear-mode? (first insert sentences -> first insert )
DB CREATION:
private static final String CREATE_TABLE_SONGS = "CREATE TABLE IF NOT EXISTS SONGS (" +
"LIST_ID int NOT NULL, " +
"PLAY_ID int NOT NULL, " + //ID of the song in the list
"SONG_ID int NOT NULL, " + //ID of the song
"TITLE varchar(200) NOT NULL," +
"TIME int NOT NULL, " +
"PROVIDER int NOT NULL, " +
"PROVIDER_ID varchar(200) NOT NULL, " +
"SONG_STATE int NOT NULL, " +
"PRIMARY KEY (LIST_ID,PLAY_ID));";
And then
db.execSQL(CREATE_TABLE_SONGS);
A: order by _id
should do, given the autoincrement nature of the id.
A: SQLite tables have a "secret" column called ROWID the value of which increases as you add rows. It can serve as a proxy for "order entered into table". ROWID is basically a "free" auto-incrementing integer primary key column for the table.
Note that by definition SQL databases have no notion of row ordering. While I would be surprised if the behavior of ROWID every changed in SQLite (since it's existence and behavior is documented), as a rule if you want to retrieve rows in an ordered fashion in SQL databases you're responsible for storing the ordering information yourself.
A: The best-practices method of sorting rows by the temporal order in which they have been inserted is to use a timestamp column which is assigned as a default value the date-time corresponding to "now", as the row is being inserted. This is easy to do in SQLite.
sqlite database default time value 'now'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594055",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Need to create a histogram in Python for a corpus import nltk
from nltk.book import *
from nltk.corpus import brown
corpus_text = brown.words()
word_freq = FreqDist(corpus_text)
word_hist = dict()
for k,v in word_freq.iteritems():
if key in word_hist:
word_hist[v] = word_hist[v] + 1
else:
word_hist[v] = 1
print word_hist.viewkeys()
print word_hist.viewvalues()
I'm making a mistake at the dictionary handling here. Need to create a dictionary that has
it's keys as the words from the freqdict and the values as the number of the corresponding word. how do I perform this increment?
I'm certain that
word_hist[v] = word_hist[v] + 1
else:
word_hist[v] = 1
has a bug.
A: Of course. It seems you are replacing the word_hist dict with one of its values (plus 1). Try
word_hist[v] = word_hist[v] + 1
or even better
word_hist[v] += 1
instead.
EDIT: There is another bug:
for k,v in word_freq.iteritems():
if key in word_hist:
word_hist[v] = word_hist[v] + 1
else:
word_hist[v] = 1
makes no sense. key is tested for presence in word_hist, but then v is used.
I don't know what key is, but either use k or v for both.
A: from collections import defaultdict
word_hist = defaultdict(int)
for k,v in word_freq.iteritems():
word_hist[v] +=1
A: that definitely has a bug, but so does the previous line.
if key in word_hist:
word_hist[v] = word_hist[v] + 1
else:
word_hist[v] = 1
should be
if k in word_hist:
word_hist[k] = word_hist[k] + 1
else:
word_hist[k] = 1
you don't need to take v from the word_freq.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594056",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Highlighting table rows only on the first 3 app uses I want to highlight -color-my app's new rows when i release a new update or when i add a new row. Also, i want to keep them highlighted only when the user uses my app at least 3 times. How can i do it?
Thanks in advance
A: Store in the NSUserDefaults a value for each new table row remembering how many times they've been viewed. Increment a number in the applicationHasFinishedLaunching for each of the rows. If the row's view count is more than 3, remove it. When rendering look up the row id in the NSUserDefaults and check to see if it should be highlighted.
Adding new rows..
[[NSUserDefaults standardUserDefaults] setInteger:0 forKey:myRowId];
Rendering..
if ([(NSInteger*)[[NSUserDefaults standardUserDefaults] integerForKey:myRowId] intValue] < 3) {
// render highlighted...
} else {
// render normal
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594058",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: Combining two separate ADTs into one Hey guys I'm trying to get started on my CS assignment (second year C paper).
In this course we have created a Binary Search Tree ADT and also a Red Black Tree ADT. We have to combine them into one more general "Tree" ADT which will either choose to be a Red Black Tree or A Binary Search Tree depending on user input.
I have started by defining a new enumerated type; treetype_t which can either be set to RBT or BST... my first question is how do I declare the struct since I don't know which ADT will be selected? e.g. in my bst.c file I have:
struct bstnode {
char *key;
bst left;
bst right;
};
and in my RBT file I have:
struct rbtnode {
char *key;
colour_t colour;
rbt left;
rbt right;
};
My first idea was to have an if statement such as
if (treetype_t == RBT){
struct rbtnode {
char *key;
colour_t colour;
rbt left;
rbt right;
};
}
else{
struct bstnode {
char *key;
bst left;
bst right;
};
}
However I don't think this will work... I can't think of another approach - any ideas?
A: Structure definitions can't be changed at run-time as in your code. You can only change them at compile time using the preprocessor's #if/#ifdef directive, but that's too early since at that moment you don't yet have the user input (unless the user can modify the source code directly and recompile it).
What you can do is combine those structures into one by using the union keyword:
struct rbtnode {
char *key;
colour_t colour;
rbt left;
rbt right;
};
struct bstnode {
char *key;
bst left;
bst right;
};
union bst_or_rbt_node {
struct bstnode bst_node;
struct rbtnode rbt_node;
};
Then you use either the rbt_node member of the union or the bst_node member depending on the user input.
Make sure you allocate enough space for bst_or_rbt_node (safest would be using sizeof(bst_or_rbt_node)).
Also, I hope rbt and bst are pointer types.
It's not necessary to use unions, but at your current level it may be a little easier to deal with them than with pointers to e.g. void, pointer casts.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594061",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: get multiple data from webservice using SOAP in android Im getting single data from web service using SOAP in android and displayed well.But when i need to retrieve multiple set of values from web services..How could i do that?For ex.from a webservice.,im getting 10 set of student records with fields stu.Name,stuRegno.,stuAge.After getting response of this.,i need to parse it to stored into local db with corresponding field names.How could i do that?
My code:
public class Main extends Activity {
private static final String METHOD_NAME = "TopGoalScorers";
private static final String SOAP_ACTION = "http://footballpool.dataaccess.eu/data/TopGoalScorers";
private static final String NAMESPACE = "http://footballpool.dataaccess.eu";
private static final String URL = "http://footballpool.dataaccess.eu/data/info.wso?WSDL";
//Called when the activity is first created.
@Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
setContentView(R.layout.main);
//Buttons deaktiviert alles automatisch
SoapObject request = new SoapObject(NAMESPACE, METHOD_NAME);
request.addProperty("iTopN", 3);// username von Preferences abgeholt
//request.addProperty("intB", 4);
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
Toast.makeText(getApplicationContext(), request.toString(), Toast.LENGTH_LONG).show();
envelope.setOutputSoapObject(request);
AndroidHttpTransport androidHttpTransport = new AndroidHttpTransport (URL);
try {
androidHttpTransport.call(SOAP_ACTION, envelope);
//Parse Response
SoapObject resultsRequestSOAP = (SoapObject) envelope.getResponse();
String xy = resultsRequestSOAP.getProperty(0).toString();
((TextView)findViewById(R.id.lblStatus)).setText(xy);
} catch(Exception E) {
((TextView)findViewById(R.id.lblStatus)).setText("ERROR:" + E.getClass().getName() + ": " + E.getMessage());
}
}
}
A: I don't understand what is your problem. You need to convert resultsRequestSOAP to appropriate data format(for example String) and parse it(for example through SAX) and in your parser collect all data in a container(for example List).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594062",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: HTML , Display IDs of every Text boxes , when I make focus At my web page, I have several text box controls (eg. Input type="text" ...)
What I would like to do is display every ID for every text box whenever or whatever text box i make focus event.
I already try this.
alert($("*:focus").attr("id"));
But it return undefined message.
So, Please let me know is there any way to know that which text box, i mean text box ID, is I already focused dynamically.
A: Setting a variable on focus, and removing the variable on blur will do the job:
var currentFocus = null; //to be defined in the global scope, if you want
// to access this property across your whole script
$("input").focus(function(){
currentFocus = this.id;
}).blur(function(){
currentFocus = null;
});
A: You may need to look if it has an ID or not. I made an example: http://jsbin.com/opocoz/2/edit
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594063",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Stay in same column while navigating up and down in a vim editor I have set nowrap so that I can view a file properly. So what happens is that when navigating up or down in the file, if there is an empty line in between, vim takes me to the beginning of that line. I lose the view that I had previously, and I get it back only after I move a few lines up where there is text in them. This is rather irritating as while reading this particular file I am usually horizontally scrolled to a position much beyond the starting few columns that fit on the screen. Navigating to an empty line causes this view to be lost and I get completely empty view (because nothing is written in those columns in those rows). Is there any work around for this ?
A: You need to set the virtualedit option:
set virtualedit=all
See :help virtualedit for an explanation.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594064",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: Using an alpha transparent mask on a QWidget? Is it possible to assign an alpha-transparent mask to a QWidget? I know how to set a mask using setMask but it seems it only supports black&white masks. Is it possible to make it support a true alpha channel?
i.e. currently I have a PNG like this:
and a widget like this:
If I load my PNG in a QPixmap and set it as a mask, I get this (notice the edges):
However I would like to get this (smooth edges):
Any idea how to do that?
Note: I'm doing some more complex drawing on the widget, which must be restricted to the mask area, so I cannot simply set my PNG as the widget's background image.
A: I think your best route is in QPainter's composition modes.
For example:
QPixmap PixmapToBeMasked(Size);
PixmapToBeMasked.fill(QColor(255, 255, 255, 120));
QPixmap Mask = DoSomethingToGetAMask();
QPainter Painter(&PixmapToBeMasked);
Painter.setCompositionMode(QPainter::CompositionMode_DestinationIn);
Painter.drawPixmap(0, 0, Mask.width(), Mask.height(), Mask);
That will handle drawing your widget nicely. If you still need to mask mouse events you might need to do some extra work though.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594066",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Extend HttpServlet implement ServletContextListener Is it a good practice for a class to extend HttpServlet and implement ServletContextListener?
public Myclass extends HttpServlet implements ServletcontextListener {
}
What are the pros and cons of doing this?
A: Some thoughts:
*
*You will have at least two instances of your class. The container create one as ServletContextListener and at least one as HttpServlet when your servlet get an incoming request.
*Since the 2+ instances you cannot use instance (just static) members to share data.
*It's easier if other classes don't use the data/objects that you initialize and share in the listener because you don't have to put these data/objects to the application scope in the ServletContextListener and retrieve them in the HttpServlet.
*If your initialization logic is complex maybe it's worth to separate it from the servlet code (e.g. putting the initialization code to a different class and using the application scope to get the shared objects in the servlet).
A: It all depends on you, the implementer. ServletcontextListener has its particular purpose. Make sure you know what it is for before using it.
In case you are creating an HTTP servlet you must extend HttpServlet.If your class wants to "receive notifications about changes to the servlet context of the web application" (copied from javadocs) it is part of, you have to implement ServletcontextListener.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594076",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Android : some problems when converting drawable image to byte array I want to convert an image in my app to a Base64 encoded string. This image may be of any type like jpeg, png etc.
What I have done is, I converted the drawable to a Bitmap. Then I converted this Bitmap to ByteArrayOutputStream using compress metheod And I am converting this ByteArrayOutputStream to byte array. And then I am encoding it to Base64 using encodeToString().
I can display the image using the above method if the image is of PNG or JPEG.
ByteArrayOutputStream objByteOutput = new ByteArrayOutputStream();
imgBitmap.compress(CompressFormat.JPEG, 0, objByteOutput);
But the problem is if the image is in any other types than PNG or JPEG, how can I display the image?
Or please suggest me some another method to get byte array from Bitmap.
Thank you...
A: I'd suggest using
http://developer.android.com/reference/android/graphics/Bitmap.html#copyPixelsToBuffer(java.nio.Buffer)
and specify a ByteBuffer, then you can use .array() on the ByteBuffer if it is implemented (it's an optional method) or .get(byte[]) to get it if .array() doesn't exist.
Update:
In order to determine the size of the buffer to create you should use Bitmap.getByteCount(). However this is only present on API 12 and up, so you would need to use Bitmap.getWidth()*Bitmap.getHeight()*4 - the reason for 4 is that the Bitmap uses a series of pixels (internal representation may be less but shouldn't ever be more), each being an ARGB value with 0-255 hence 4 bytes per pixel.
You can get the same with Bitmap.getHeight() * Bitmap.getRowBytes() - here's some code I used to verify this worked:
BitmapDrawable bmd = (BitmapDrawable) getResources().getDrawable(R.drawable.icon);
Bitmap bm = bmd.getBitmap();
ByteBuffer byteBuff = ByteBuffer.allocate(bm.getWidth() * bm.getHeight() * 4);
byteBuff.rewind();
bm.copyPixelsToBuffer(byteBuff);
byte[] tmp = new byte[bm.getWidth() * bm.getHeight() * 4];
byteBuff.rewind();
byteBuff.get(tmp);
It's not nice code, but it gets the byte array out.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594077",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Is there an SDK out for Windows Run Time (WinRT)? Is there some kind of SDK out for WinRT.? Can we develop applications for it now?
Is VS2010 usable for developing or will some other IDE be shipped? Also, is C++ necessary to develop performance-oriented apps in WinRT, or will the C# applications give equivalent performance? Can development be done on Win7?
I am curious about this because I missed out when WPF was released and I don't want to miss out on this.
A: Take a look at the Windows Dev Center where you can download a copy of Windows 8, complete with all the new tools for developing for it.
A: Visual Studio 11 Developer Preview is also available on Subscriber Downloads if you do have a subscription, and it includes the WinRT SDK and runs on Windows 7 and other operating systems. So you can build it and debug it, but you still have to run your code on a Windows 8 machine.
Performance-wise, WinRT doesn't change the guidance for whether to use native code. The APIs will behave near identically regardless of what language you choose, so make the decision between C++ and C# just as you would today.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594078",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: CSS Break line when content overflows
I am wondering how to break a line with css when content reaches the width of a div, as I am making a blogging system.
-Matthew
A: Use CSS property word-wrap: break-word.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594079",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: how to send mail from mysql using stored-procedures? Is there any mail packages available in mysql?
I am using phpmyadmin tool to manage mysql Db.
I want to send email using stored-procedures in mysql.
A: No there is not and You should not do this because it can affect mysql performance.
My advice is to write a simple script that send e-mails according to data from table.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594081",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: WP7 MediaElement Unable to Reposition the stream I am using MediaElement for video playback in my app. I have added controls for play, pause, rewind and forward. In the forward button's event handler, I am trying to forward the video clip for 5 seconds. the code I have used to do that is given below.
if(myMediaElement.CanSeek)
{
myMediaElement.Position = TimeSpan.FromSeconds(2);
myMediaElement.Play();
}
But the video clip does not forward, instead it stops the video playback. Can anyone please tell me what is going wrong.
A: You need to start playing the stream before you can set the position.
Move the call to CanSeek and the setting of the position until after the MediaOpened event has been raised.
See the remarks in MSDN http://msdn.microsoft.com/en-us/library/system.windows.controls.mediaelement.position(v=VS.95).aspx for confirmation.
A: Using valueconverter sample here, with Slider adjustments, to get the positions
http://diggthedrazen.com/2011/07/08/using-an-ivalueconverter-to-create-a-player-with-a-seek-bar-on-windows-phone/
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594084",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to get the absolute path of the contact URI? I am getting uri as content://com.android.contacts/data/592 . I need to convert this in to absolute path . How to achieve this.Thanks in advance.
A: contacts are not stored in files , they are stored in a database , you can use the content resolver to get that contact information.
http://developer.android.com/reference/android/content/ContentResolver.html
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594089",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: What is the command to make Sublime Text my core editor? So I'm trying to set up GitHub for the first time ever and I want Sublime Text to be my core editor, how exactly do I do that? Sorry if this is a noob question, I am a noob :/
A: As this ranked highly when I was searching Google for Mac instructions, here is a combination of solutions I found.
First I set up a command line utility matching "subl" to Sublime Text from any terminal instance with this terminal command.
sudo ln -s "/Applications/Sublime Text 2.app/Contents/SharedSupport/bin/subl" /bin/subl
Then I do a similar git config command to the Windows solution above, but with a -w parameter at the end.
git config --global core.editor "subl -w"
A: Enter this command in a prompt:
git config --global core.editor "C:/Program Files/Sublime Text 2/sublime_text.exe"
It will then pop up when prompted for a commit message, or any other edition task, but if it was already open it won't work since it uses the same instance. Don't know how to workaround this.
A: Since build 3010 of Sublime Text 3, the subl.exe helper is included by default. So, combining CharlesB and Ted's answers gives you the best answer --
type in a prompt (cmd.exe or git_bash):
setx SUBLIME c:\path\to\sublime\install\dir
git config --global core.editor "subl.exe -w"
Note the presence/absence of quotes. git config requires them, whereas setx does NOT. Also, while you're at it, try using a path\to\sublime that doesn't use spaces. That way you can use this with both MSysGit and Cygwin Git.
A: I had to manually edit the .gitconfig file in my user directory within Windows. The editor required single quotes around it, like so:
[core]
editor = 'C:/Program Files/Sublime Text 3/sublime_text.exe'
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594091",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "20"
}
|
Q: SSRS 2008: How to repeat on new page one row of table header I have table with 3 rows of header, and I needed repeat on new page only second row, first and third is not needed in the pages, excepts first page.
If I set the properies "RepeatOnNewPage" in the second row only, SSRS show the error: "The TablixMember must have the same value set for the RepeatOnNewPage property as those following or preceding the dynamic TablixMember"
If I set this property in the all (3) rows of header - all ok, but I need only one :)
How to repeat only second row on new page?
A: *
*Go at Column Groups
*Click on the black arrow at the last
*Select advanced mode.
*Go at "Row Group"..
*In row group you will get LOTS of "static", out of which just select TOP MOST
*Go to properties
A. For VS: press F4
B. For report builder... View->Properties
*In that select for row headers
a. Fixed Data: True
b. Keepwithgroup: After
c. Repeatonpage: True...
And for main headers
a. Fixed Data: True
b. Keepwithgroup: Before
c. Repeatonpage: True
A: I am not sure why, but this seemed to work for me.
For your 3 header rows advanced properties,
(Static) KeepTogether= false, KeepWithGroup=None, RepeatOnNewPage= TRUE
(Static the one you want) KeepTogether= True, KeepWithGroup=After, RepeatOnNewPage= TRUE
(Static) KeepTogether= false, KeepWithGroup=None, RepeatOnNewPage= TRUE
When i tried this with the top and bottom rows repeat on new page False it gave me the error you described. I changed these to true just to try. I expected them to Repeat on new page but they didnt. My first page had all 3 and the rest just had the middle.
Hope this works for you!
A: Set property RepeatOnNewPage = True for all rows of table. Select static row from Row Groups window.
You must have to set RepeatOnNewPage property for all static rows.
If any static row is not set RepeatOnNewPage property than it dosen't work and give error.
A: So just to help clarify the answer based on success from working on my table. When I did the above action on the top-most static row, I got an error message. My table has three headers that are grouped and all need to be included in the repeatOnNewPage function. In order to successfully run my report, needed to repeat the step for all the static row headers.
Static (for each row): FixedData = True, Keepwithgroup = After, and RepeatOnNewPage = True
I also went into Tablix properties and checked both boxes under Row Headers for Repeat header rows on each page & Keep header visible while scrolling.
It was a very happy moment when i did not receive an error message after completing this scenario. good luck.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594094",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "7"
}
|
Q: RESTLet 2.0.9 - query regarding multiple @Get and @Post annotations? I am new to RESTLet and using 2.0.9. What I want to do is have multiple methods with @Get & @POST annotation. I have access to the VO classes (value objects) and so I don't need to use JSON or XML representation. I have used the excellent tutorial available at http://wiki.restlet.org/docs_2.0/13-restlet/21-restlet/318-restlet/303-restlet.html#dsy303-restlet_jse. I have designed the following classes:
User - VO POJO with attributes for an User.
UserResource inteface:
public interface UserResource
{
@Get
public User userLogin();
}
For single @Get annotation, the client code works fine.
ClientResource cr = new ClientResource(url);
// Get the Contact object
UserResource resource = cr.wrap(UserResource.class);
User user = resource.userLogin();*
Now, I want to use multiple methods with @Get annotation. For e.g., have two/three flavors of getUser objects similar to what we have in normal DAO layer in single JVM.
User getUser(int userId)
User getUser(String domain, String username)
boolean isUserNew(int userid)*
and similar multiple methods to update and add users [@POST annotation]:
int addUser(User user)
int updateUser(int userId, User user)
Is it possible to achieve some thing like this ? If not what are the alternative ? Where can I get documentation for Annotations @Get, @Post ?
A: I think the way this is meant to be done is having:
*
*UsersResource with a @Get annotated method that fecthes a user by it's unique id;
*UsersDomainUsernameResource (similar fetch logic...)
@Get methods will then handle various cases:
for example:
*
*myserverside.com/users/100
*myserverside.com/users/domain/username
when it comes to your example boolean isUserNew(int userid) it is not a REST operation.
Keep in mind REST only means basic CRUD operations.
I think you'd just have to get the user's representation and then perform whatever check you need (isNew... isBlonde...)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594096",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: GWT + Spring hosted mode not working I have a following problem, probably somebody can help me?
I had an Spring MVC application, quite basic one, with a few simple jsp pages.
Also I had an Spring Security integrated with it.
Now I need to add some GWT widget to one page. No problem so far, I've added <div> to the page, added GWT module, all all needed GWT logic.
When I compile GWT and then deploy application to tomcat - everything works perfectly, I open app, login into it, open my page and see GWT UI components.
Now I want to open my application in hosted mode. There problems begin.
When I start hosted mode, Jetty starts, Spring framework initialize, and then my jsp (translated as .htm) open without hosted mode param ?gwt.codesvr=127.0.0.1:9997. After opening my page I see nothing if I delete compiled gwt code.
When I manually add "?gwt.codesvr=127.0.0.1:9997" hosted mode start and GWT module begin to load. This is when I get an error:
12:57:15.589 [ERROR] [rehabrental] Failed to load module 'testmodule'
from user agent 'Mozilla/5.0 (Windows; U; Windows NT 6.1; ru;
rv:1.9.2.23) Gecko/20110920 Firefox/3.6.23' at 127.0.0.1:63260
java.lang.NoSuchFieldError: warningThreshold at
com.google.gwt.dev.javac.JdtCompiler.getCompilerOptions(JdtCompiler.java:413)
at
com.google.gwt.dev.javac.JdtCompiler$CompilerImpl.<init>(JdtCompiler.java:228)
at
com.google.gwt.dev.javac.JdtCompiler.doCompile(JdtCompiler.java:700)
at
com.google.gwt.dev.javac.CompilationStateBuilder$CompileMoreLater.compile(CompilationStateBuilder.java:235)
at
com.google.gwt.dev.javac.CompilationStateBuilder.doBuildFrom(CompilationStateBuilder.java:447)
at
com.google.gwt.dev.javac.CompilationStateBuilder.buildFrom(CompilationStateBuilder.java:370)
at
com.google.gwt.dev.cfg.ModuleDef.getCompilationState(ModuleDef.java:360)
at
com.google.gwt.dev.DevModeBase$UiBrowserWidgetHostImpl.createModuleSpaceHost(DevModeBase.java:110)
at
com.google.gwt.dev.shell.OophmSessionHandler.loadModule(OophmSessionHandler.java:197)
at java.lang.Thread.run(Unknown Source)
A: Do you use eclipse ?. If so you need rearrange your exported modules as JDT classes causes problems with the GWT compiler. See comment #7 in this GWT issue about pushing GWT dependencies above others, so that they are picked up first by the compiler.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594099",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Sitecore global url to specific url Currently I am facing the following problem:
A website, which I have to make for a company, has different locations. But the content of a few pages is for all locations the same. Now I have created a global folder with the items for all the locations. But now I am facing the following problem: when accessing the global items from the website of a specific location I get the global url. But what I want is that the specific location url remains the same structure, for example:
*
*Now it is www.url.com/global/subfolder/itemname
*And what I want is www.url.com/location1/subfolder/itemname
Does anybody have any solution(s)/suggestion(s) for this problem?
Does anybody also have a solution for creating a menu to insert these global items but also to insert the location specific items?
Some more information about my Sitecore content structure
*
*Global: contains the global items for alle locations
*Corporate: the corporate website of the company
*Location1: the website of location1
*Location2: the website of location2
A: If I understand you correctly, this is what I'd do. It might not be the prettiest solution. But it'll work.
You have your "data" items in /global/subfolder/itemname
then just create some templates, which are "dummy" pages, that only contain a link to the global item (and perhaps the few fields that could differ (perhaps contact email for the specifik location).
Then you make a sublayout that bascially jsut gets the referenced item and uses that instead of Sitecore.Context.Item.
Then create an instance of the "dummy" template in /location1/subfolder/itemname and reference it to /global/subfolder/itemname
That way you URLs will be correct and the data will be the same.
Another and probably smarter solution (if you have enabled proxies) is to create a proxy that takes
/global/subfolder/itemname as source and points to /location1/subfolder/ as target (or you could take /global/subfolder and check "include children".
Here is a Guide on how to use proxies in 5.3:
http://sdn.sitecore.net/Articles/Administration/Using%20Proxy%20Items%20in%205,-d-,3.aspx
A: Adam Weber was right, cloning is your best solution:
*
*Create your Global section, with all the child items you need
*For each of your local sections, clone the global section and place it where you'd like it to appear within your local menu
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594100",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "4"
}
|
Q: dynamic bind to a resource but in a state animation I have defined a visual state in which a button has a glow effect.
But I want to have a variable BlurRadius in that state.
My approach was adding a resource and change that resource in code behind.
But changes doesn't affect the visual controls.
here is xaml code :
<Window
xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
xmlns:Microsoft_Windows_Themes="clr-namespace:Microsoft.Windows.Themes;assembly=PresentationFramework.Aero" xmlns:System="clr-namespace:System;assembly=mscorlib" xmlns:i="http://schemas.microsoft.com/expression/2010/interactivity" xmlns:ei="http://schemas.microsoft.com/expression/2010/interactions" x:Class="blend1.question"
Title="question" Height="300" Width="300">
<Window.Resources>
<Style x:Key="ButtonFocusVisual">
<Setter Property="Control.Template">
<Setter.Value>
<ControlTemplate>
<Rectangle Margin="2" SnapsToDevicePixels="true" Stroke="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}" StrokeThickness="1" StrokeDashArray="1 2"/>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
<LinearGradientBrush x:Key="ButtonNormalBackground" EndPoint="0,1" StartPoint="0,0">
<GradientStop Color="#F3F3F3" Offset="0"/>
<GradientStop Color="#EBEBEB" Offset="0.5"/>
<GradientStop Color="#DDDDDD" Offset="0.5"/>
<GradientStop Color="#CDCDCD" Offset="1"/>
</LinearGradientBrush>
<SolidColorBrush x:Key="ButtonNormalBorder" Color="#FF707070"/>
<System:Double x:Key="d1">10</System:Double>
<Style x:Key="ButtonStyle1" TargetType="{x:Type Button}">
<Setter Property="FocusVisualStyle" Value="{StaticResource ButtonFocusVisual}"/>
<Setter Property="Background" Value="{StaticResource ButtonNormalBackground}"/>
<Setter Property="BorderBrush" Value="{StaticResource ButtonNormalBorder}"/>
<Setter Property="BorderThickness" Value="1"/>
<Setter Property="Foreground" Value="{DynamicResource {x:Static SystemColors.ControlTextBrushKey}}"/>
<Setter Property="HorizontalContentAlignment" Value="Center"/>
<Setter Property="VerticalContentAlignment" Value="Center"/>
<Setter Property="Padding" Value="1"/>
<Setter Property="Template">
<Setter.Value>
<ControlTemplate TargetType="{x:Type Button}">
<Microsoft_Windows_Themes:ButtonChrome x:Name="Chrome" BorderBrush="{TemplateBinding BorderBrush}" Background="{TemplateBinding Background}" RenderMouseOver="{TemplateBinding IsMouseOver}" RenderPressed="{TemplateBinding IsPressed}" RenderDefaulted="{TemplateBinding IsDefaulted}" SnapsToDevicePixels="true">
<Microsoft_Windows_Themes:ButtonChrome.Effect>
<DropShadowEffect BlurRadius="0" ShadowDepth="0"/>
</Microsoft_Windows_Themes:ButtonChrome.Effect>
<VisualStateManager.VisualStateGroups>
<VisualStateGroup x:Name="CommonStates">
<VisualState x:Name="Normal"/>
<VisualState x:Name="MouseOver"/>
<VisualState x:Name="Pressed"/>
<VisualState x:Name="Disabled"/>
</VisualStateGroup>
<VisualStateGroup x:Name="FocusStates">
<VisualState x:Name="Unfocused"/>
<VisualState x:Name="Focused"/>
</VisualStateGroup>
<VisualStateGroup x:Name="ValidationStates">
<VisualState x:Name="Valid"/>
<VisualState x:Name="InvalidFocused"/>
<VisualState x:Name="InvalidUnfocused"/>
</VisualStateGroup>
<VisualStateGroup x:Name="mySG">
<VisualState x:Name="sMouseOver">
<Storyboard>
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Effect).(DropShadowEffect.BlurRadius)" Storyboard.TargetName="Chrome">
<EasingDoubleKeyFrame KeyTime="0" Value="{StaticResource d1}"/>
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Effect).(DropShadowEffect.ShadowDepth)" Storyboard.TargetName="Chrome">
<EasingDoubleKeyFrame KeyTime="0" Value="0"/>
</DoubleAnimationUsingKeyFrames>
<ColorAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Effect).(DropShadowEffect.Color)" Storyboard.TargetName="Chrome">
<EasingColorKeyFrame KeyTime="0" Value="Red"/>
</ColorAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
<VisualState x:Name="sMouseOut">
<Storyboard>
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Effect).(DropShadowEffect.BlurRadius)" Storyboard.TargetName="Chrome">
<EasingDoubleKeyFrame KeyTime="0" Value="0"/>
</DoubleAnimationUsingKeyFrames>
<DoubleAnimationUsingKeyFrames Storyboard.TargetProperty="(UIElement.Effect).(DropShadowEffect.ShadowDepth)" Storyboard.TargetName="Chrome">
<EasingDoubleKeyFrame KeyTime="0" Value="0"/>
</DoubleAnimationUsingKeyFrames>
</Storyboard>
</VisualState>
</VisualStateGroup>
</VisualStateManager.VisualStateGroups>
<ContentPresenter HorizontalAlignment="{TemplateBinding HorizontalContentAlignment}" Margin="{TemplateBinding Padding}" RecognizesAccessKey="True" SnapsToDevicePixels="{TemplateBinding SnapsToDevicePixels}" VerticalAlignment="{TemplateBinding VerticalContentAlignment}"/>
</Microsoft_Windows_Themes:ButtonChrome>
<ControlTemplate.Triggers>
<Trigger Property="IsKeyboardFocused" Value="true">
<Setter Property="RenderDefaulted" TargetName="Chrome" Value="true"/>
</Trigger>
<Trigger Property="ToggleButton.IsChecked" Value="true">
<Setter Property="RenderPressed" TargetName="Chrome" Value="true"/>
</Trigger>
<Trigger Property="IsEnabled" Value="false">
<Setter Property="Foreground" Value="#ADADAD"/>
</Trigger>
</ControlTemplate.Triggers>
</ControlTemplate>
</Setter.Value>
</Setter>
</Style>
</Window.Resources>
<Grid Margin="1">
<Button x:Name="button" Content="Button" HorizontalAlignment="Left" Margin="16.4,8,0,0" VerticalAlignment="Top" Width="75" Style="{DynamicResource ButtonStyle1}" >
<Button.Effect>
<DropShadowEffect BlurRadius="0" ShadowDepth="0" Color="Red"/>
</Button.Effect>
<i:Interaction.Triggers>
<i:EventTrigger EventName="MouseEnter">
<ei:GoToStateAction TargetObject="{Binding ElementName=button}" StateName="sMouseOver"/>
</i:EventTrigger>
<i:EventTrigger EventName="MouseLeave">
<ei:GoToStateAction TargetObject="{Binding ElementName=button}" StateName="sMouseOut"/>
</i:EventTrigger>
</i:Interaction.Triggers>
</Button>
<Button Content="increase" HorizontalAlignment="Right" Margin="0,8,30.8,0" VerticalAlignment="Top" Width="75" Click="Button_Click"/>
</Grid>
</Window>
and here is the code behind :
/// <summary>
/// Interaction logic for question.xaml
/// </summary>
public partial class question : Window
{
public question()
{
InitializeComponent();
}
private void Button_Click(object sender, System.Windows.RoutedEventArgs e)
{
// TODO: Add event handler implementation here.
double d= (double)Resources["d1"];
Resources["d1"]=d+10;
MessageBox.Show(Resources["d1"].ToString());
}
}
How should I dynamic bind to a resource in a state ? and what about the condition in which I use a DependencyProperty in my window class for varying BlurRadius ? and If there is another logical approach let me know.
Thanks in advance.
A: It was impossible. :)
Thanks for all who contributed to this answer.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594105",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Pointcut for usage of operator "==" with specific types is it possible to write an AspectJ pointcut that matches the usage of a specific operator with a specific type?
Some background information: I'm working on a project where we have to use a legacy Java library (pre 5.0, before the enum keyword) which comes with several "pseudo-enum" types, i.e. normal Java classes that define static constants of its own type. Those "feel" very much like enums, but using them like enums can result in an error. Therefore I'd like AspectJ to mark uses of == with objects of one of these types as an error, if that is possible. I have googled this and consulted the normally very helpful book AspectJ in action, but so far without success. Any help is appreciated.
A: == is not the same as equals(), and is implemented by the JVM, and as far as I can tell cannot be modified by aspectj. Also, I don't think that AspectJ is the correct tool for this job.
A better approach would be to implement a Checkstyle rule or similar for your project to allow you indicate these points. You could have them as errors or warnings. See Writing Checks for Checkstyle for more information.
This would require some coding, but so would the aspectJ solution.
Checkstyle has an eclipse plugin as well as a maven plugin, so you could have these errors appearing as you work in the IDE.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594110",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: Inserting non-default tab stops into a RichTextBox Is it possible to write code to insert a non-default tab stop into the document of a RichTextBox? For example, the equivalent of the MS-Word right-tab or decimal-tab?
Thanks,
Firoz
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594111",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Screenshot from form I want to get screenshot of screen under my form, so I hide it first and show after capturing. But on my Windows 7 form is not completely minimize, so I get form on screenshot. How can I be sure that my form is competely minimize?
WindowState = FormWindowState.Minimized;
Bitmap screenshot = ScreenUtils.ScreenShot();
background = screenshot;
WindowState = FormWindowState.Normal;
P.S. Hide() and Show() have the same problem.
A: Did you try to build in a sleep before making a screenshot?
A: you could set your forms opacity to 0, call refresh to make sure the painting is done, capture, reset opacity to 1 and call refresh again
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594112",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: float format variable with integer value in string I was facing with one minor issue, and I'm wondering: Why?
here we have some string:
[NSString stringWithFormat@"%.3f/%.3f/%.3f/%i", 1.0, 1.0, 1, 1];
in this case, result is 1.000/1.000/1/abra-kadabra like 34875689.
Why it's happens? Of course, I know, when we change the third value to 1.0, then everything will be okay.
So, please, explain me the deep proces of this operation.
A: Since you wrote %f, the compiler expects a float but recognizes an int. Writing 1 instead of 1.0 tells the compiler it's an integer constant instead of 1.0, which is a float constant.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594121",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: String Uppercase in java pattern Everyone, I've been try to solve this since yesterday.
What is the representation of pattern that contain (A-Z)* and (\\p{Punct})* and (0-9)* and (\\s), and all char of the pattern were Uppercase.
i.e,
*
*PATTERN {001}
*OTHERS PATTERN (002-005)
edit :
just moment ago, i got this patter for question above:
(([A-Z])*|(\\p{Punct})*|([0-9])*|(\\s)*)*
the new problem is getting the uppercase sub String from some String which separated with "|":
then, I used code look like below :
String theString = "";
String theUppercase = "";
Pattern level5Patter = Pattern.compile("(([A-Z])*|(\\p{Punct})*|([0-9])*|(\\s)*)*\\|");
Matcher level5Matcher = level5Patter.matcher(strFileContent);
while(level5Matcher.find()){
String resultLevel5 = level5Matcher.group();
if(resultLevel5.toUpperCase().equals(resultLevel5)){
System.out.println(resultLevel5);
}
else{
theString=theString+resultLevel5;
}
}
the sub string will look like below :
TITLE OF THIS DATA IS ALWAYS UPPERCASE AND SOMETIME CONTAIN NUMERIC 1.0.0.0.0 EVEN PUNCTUATION {}
The String source is look like below:
Head 1|Head 1.0|Head 1.0.0|Head 1.0.0.0|TITLE OF THIS DATA IS ALWAYS UPPERCASE AND SOMETIME CONTAIN NUMERIC 1.0.0.0.0 EVEN PUNCTUATION {}|first data description sometime contains UPPERCASE and numeric 1010 and punctuation {}|01234|Head 1|Head 1.0|Head 1.0.0|Head 1.0.0.1|TITLE OF THIS DATA IS ALWAYS UPPERCASE AND SOMETIME CONTAIN NUMERIC 1.0.0.1.0 EVEN PUNCTUATION|first data description sometime contains UPPERCASE and numeric 1010 and punctuation {}|56789|
Thanks in advance.
A: Create a character class and put everything in, that you want to allow
Pattern p = Pattern.compile("^[A-Z0-9\\p{P}\\s]+$");
[A-Z0-9\\p{P}\\s] this is a character class, that allows A-Z, 0-9, Punctuation and Whitespace.
^ is an anchor for the start of the string
$ is an anchor for the end of the string
+ is a quantifier that allows
A more unicode approach would be
^[\\p{Lu}\\p{N}\\p{P}\\s]+$
\\p{Lu} an uppercase letter that has a lowercase variant.
\\p{N} any kind of numeric character in any script.
See here on regular-expressions.info for more information
A: I must admit it is not entirely clear to me what you are asking. Could you try to rephrase your question?
Under the assumption that you are trying to combine some character classes, in other words, you want a pattern that accepts any string consisting of any sequence of characters from the character classes '[A-Z]', '\p{Punct}' and '[0-9]', this would become something like: '([A-Z0-9]|\p{Punct})*'. Beware of double escaping when encoding this as a String:
Pattern p = new Pattern("([A-Z0-9]|\\p{Punct})*");
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594122",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "-1"
}
|
Q: subclassing a singleton What is the recommended way, if any, to subclass a singleton? For example, I would like to make a subclass of AVAudioSession that adds a couple properties and makes the singleton its own AVAudioSessionDelegate.
Right now, I am overriding sharedInstance to allocate my own class, then call my own class' init method. I am not sure if the other singleton methods need to be protected like a regular singleton, as the super class already is a singleton:
@interface PdAudioSession : AVAudioSession <AVAudioSessionDelegate>
@implementation PdAudioSession
+ (PdAudioSession *)sharedInstance {
static PdAudioSession *myInstance = nil;
@synchronized (self) {
if (!myInstance) {
myInstance = [[PdAudioSession alloc] init];
}
}
return myInstance;
}
- (id)init {
self = [super init];
if (self) {
self.delegate = self;
}
return self;
}
A: Rather than subclass the singleton, why not just create a new class that contains an AVAudioSession object. That way you can create it when you initialize your new class, you can add properties to this new class and also provide itself as a delegate.
Composition is the preferred design pattern in Cocoa over subclassing.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594129",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Why md5 always changes on a certain file? I have this task that needs investigation as to why the md5 value of a file keeps changing.
Example:
*
*I need to generate the diagnostic file of a certain machine.
*After generating the file, it produces a .zip file, say, Diag.zip which contains all the information/files of that certain machine.
*Inside Diag.zip file contain a .xls, say, Data.xls which contains all the summary of all files in that certain machine, includes, the directory of the file, file version, file size, create time and md5.
*Then save all the information of Data.xls in database.
After a day or so, do it again back in Step 1-4.
Then when I queried all the save data of Data.xls in the database in a 2 weeks range, and it shows that almost all files in that certain machine have its md5 value changed.
The question is: Why is it that md5 value always changed every time I generated a new diagnostic files?
A: There seems to be an issue with excel files, in particular Excel 2003 xls files. Whenever they get opened in Excel, even if they don't get changed and don't get saved, Excel automatically updates some of the file's metadata, such as the "Document Properties and Personal Information" and "Last Accessed Statistics". Therefore, the file every time it gets opened changes a little bit, and this makes that the MD5 changes also.
One way to avoid this problem is to remove "document properties and personal information".
Remove hidden data and personal information from Office documents. Excel 2007: Remove Hidden Data and Personal Information from Office Documents
Remove hidden data and personal information from Office documents. Excel 2013, Excel 2010: Remove Hidden Data and Personal Information by Inspecting Workbooks
Other way to avoid this would be to use xlsx files. I have been trying to replicate this behavior in xlsx files, but it seems it only happens on xls (2003).
A: The MD5 is based on a lot of things. But I can assume filesize, filename & creationdate.
If one of those changes, the md5 hash changes. The exact same file will always return the exact same md5 hash. A new file always generates a new md5 hash.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594130",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How to create Google Calendar Quick Add feature in Java? I am working on a school project that requires a little bit of Natural Language Processing. We have to implement a feature that is similar to Google Calendar Quick Add feature in Java.
http://www.google.com/support/calendar/bin/answer.py?answer=36604
I have done some research on NLP and so far have not managed to successfully implement the feature using LingPipe.
Is there any other Java library than could help me implement this feature?
Thanks.
A: Yes< I ve actually done this for russian langauge via this toolkit
A: try JChronic, the ruby port of Chronic
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594138",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: System.Windows.FrameworkElement.Style got an exception when i call a silverlight xap in sharepoint. Hope anybody can help me out this problem. Here the exception:
Message: Unhandled Error in Silverlight Application Set Property
'System.Windows.FrameworkElement.Style' threw an exception. [Line: 84
Position: 335] at System.Windows.Application.LoadComponent(Object
component, Uri resourceLocator) bei
Project.MainPage.InitializeComponent() bei
Project.MainPage..ctor(String eldoradoUrl, String eldoradoUser) bei
Project.App.Application_Startup(Object sender, StartupEventArgs e)
bei MS.Internal.CoreInvokeHandler.InvokeEventHandler(Int32 typeIndex,
Delegate handlerDelegate, Object sender, Object args) bei
MS.Internal.JoltHelper.FireEvent(IntPtr unmanagedObj, IntPtr
unmanagedObjArgs, Int32 argsTypeIndex, Int32 actualArgsTypeIndex,
String eventName)
And here is the xaml code line where the error supposed:
<fseld:EldoradoDocCreationView x:Name="ProtoEldoradoDocCreationView" Grid.Row="0"
MaxColumnCount="2" FieldMargins="34 5 5 5"
RestrictToProperties="ProcedureName, FileItemText"
CurrentItem="{Binding ProtoEldoradoDoc}" CommandButtonsVisibility="None"
Margin="25,18,47,0" FontSize="10" Height="69" VerticalAlignment="Top" />
Thanks for your replies in advance !
A: Does your Silverlight XAP work outside of Sharepoint? If no first correct the error outside, you will easier isolate the problem and may get more detailed exception information.
If it does work without Sharepoint then rather look at external assemblies that could contain styles that are not found in this context.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594140",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: How to move a Textview dynamically on the screen? (framelayout) I have a app that shows the camera view on the screen on a FrameLayout. The screen is in fixed LandScape mode.
I need to write a textView with dynamically determined coordinates of the screen. The coordinates are determined in percentages, for example :
write the textview on the coorinates x=80% of the screen & y=20% of the screen. write the textview on the coorinates x=35% of the screen & y=55% of the screen.
how to do it? i already have the percentages, i only need to know how to use them to write the textview on the desired position of the frameLayout
code examples are welcome
i tried with this but doesn't works, the textview isn't moved:
TextView poi..... etc etc
poi.setLayoutParams(new LayoutParams((int)(w*(xCoordPercent/100)), h/2));
thanks
A: MarginLayoutParams params=(MarginLayoutParams )poi.getLayoutParams();
params.leftMargin=80;
//here 100 means 100px,not 80% of the width of the parent view
//you may need a calculation to convert the percentage to pixels.
params.topMargin=50;
poi.setLayoutParams(params);
This may help.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594143",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "5"
}
|
Q: How to duplicate form content in jQuery? I have form:
<form action="" method="post">
<div id="fields_1">
<input name="field1_1" type="...
<input name="field2_1" type="...
<input name="field3_1" type="...
<input name="field4_1" type="...
</div>
<a href="#" onclick="duplicate();">Duplicate</a>
</form>
and i want to duplicate on click all fields but different names, for example when I click "Duplicate" it shows:
<form action="" method="post">
<div id="fields_1">
<input name="field1_1" type="...
<input name="field2_1" type="...
<input name="field3_1" type="...
<input name="field4_1" type="...
</div>
<div id="fields_2">
<input name="field1_2" type="...
<input name="field2_2" type="...
<input name="field3_2" type="...
<input name="field4_2" type="...
</div>
<a href="#" onclick="duplicate();">Duplicate</a>
</form>
How to do it?
A: http://api.jquery.com/clone/
$('#fields_1').clone().attr("id","fields_2").appendTo('#yrContainer');
Where yrContainer is either the form, or maybe a new div container. If you need to change input names shown below, and here jsFiddle.
$("#myButton").click( function () {
var fields = $('#fields_1').clone().attr("id","fields_2");
var inputs = fields.find("input");
inputs.each(function(i) {
$(this).attr("name", "field"+i+"_2");
});
fields.appendTo('#yrContainer')
})
A: First: Add class="items" to the container
<div id="fields_1" class="items">
...
</div>
Second: Move out of the form the 'Duplicate' link.
</form>
<a href="#" onclick="duplicate();">Duplicate</a>
Third: Try with this code:
function duplicate(){
// Get content to clone
var line_to_clone = $('#fields_1').html();
// Get new line id
var next_line_id = $('.items').length + 1;
// Add the div container
var line_to_clone = '<div id="fields_' + next_line_id + '" class="items">' + line_to_clone + '</div>';
// Create new line
var new_line = line_to_clone.replace(/_1/gi, "_" + next_line_id);
// Render it
$('form').append(new_line);
}
A: Where is the duplicate() function. That would be the pure javascript way the way you have written it. For Jquery you need to have a clone method, rather than writing anything called duplicate(). Should be very brief and crisp.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594149",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Reliable way to know user's last connected DateTime? I'd like to add a bit of functionality to my site, which shows "new stuff" since the last time the user was on the site. My site is ASP.NET MVC/C#/Razor based.
What's a reliable way to get/set that DateTime?
Update: sorry I didn't include this originally... I'm not using the built-in membership code. My site uses the Facebook C# SDK, log in is through Fb, I store to a standard Members table.
A: Personally, I am using asp.net membership provider which allows me to store the last time (DateTime) the users logged in. This could be a solution to set that DateTime. Then, you can always get that value just before performing the login function.
A: If you are using Asp.Net Member ship then you can get last login date by
MembershipUser user = Membership.GetUser(login.UserName);
DateTime dtLastLogin = user.LastLoginDate;
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594155",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Ghost table border in FireFox 6 when setting the border-width to 2px Compare the following two examples in FireFox 6:
*
*http://jsfiddle.net/utKw9/7/
*http://jsfiddle.net/utKw9/9/
The only difference is the border-width changed from 1px to 2px. But this results into a ghost border displayed across a "row-span" cell to the right from the cell where we have set the border width.
Is it a FireFox 6 bug? Will they fix it? Is there solution to overcome this problem?
Thanks!
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594157",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: consume web service to fill local db Hi I am trying to fill my local db on app star from .NET web service but not working... need help
public class MitsAndroidApplication extends Application {
private static String SOAP_ACTION = "http://tempuri.org/";
private static final String NAMESPACE = "http://tempuri.org/";
private static final String URL = "http://...../anka/CL3M.asmx";
public String WSReturnVal ="";
@Override
public void onCreate() {
super.onCreate();
DbHelper dbh = new DbHelper(this);
SQLiteDatabase db = dbh.getWritableDatabase();
String sqlString = "SELECT " + Doktorlar.KEY_ROWID + " FROM " + Doktorlar.DATABASE_TABLE ;
Cursor aCursor = db.rawQuery(sqlString, null);
aCursor.moveToFirst();
int doktorNumber = aCursor.getCount();
String sqlStringIl = "SELECT " + Iller.KEY_ROWID + " FROM " + Iller.DATABASE_TABLE ;
Cursor ilCursor = db.rawQuery(sqlString, null);
ilCursor.moveToFirst();
int ilNumber = ilCursor.getCount();
dbh.close();
if(doktorNumber == 0) {
loadDoktorData();
}
if(ilNumber == 0) {
loadilData();
}
}
private void loadDoktorData() {
String [] paramvalues = new String[4];
paramvalues[0] = "GetDoktors"; paramvalues[1] = "45!ghUvb0PsXc";
paramvalues[2] = "mummesilid"; paramvalues[3] = "81";
LoadDoktorsWebServiceTask task = new LoadDoktorsWebServiceTask();
task.execute(paramvalues); //Doktorlar artık WSReturnVal da
}
private void loadilData() {
String [] paramvalues = new String[4];
paramvalues[0] = "GetIller"; paramvalues[1] = "45!ghUvb0PsXc";
LoadIllerWebServiceTask task = new LoadIllerWebServiceTask();
task.execute(paramvalues); //Iller artık WSReturnVal da
}
private class LoadDoktorsWebServiceTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String response = "";
try {
//for (String url : urls) {
Log.i("ABC", "do in bg doktor ws");
DbHelper dbh = new DbHelper(getApplicationContext());
SQLiteDatabase db = dbh.getWritableDatabase();
String yontemadi = urls[0].toString();
SOAP_ACTION = NAMESPACE + yontemadi;
SoapObject request = new SoapObject(NAMESPACE, yontemadi);
request.addProperty("pass", "45!ghUvb0PsXc");
if(urls.length>2) //demekki baska parametreler var , once parametreadi sonrada value bu array icinde geliyor. s˝ral˝ olarak
{
for(int i=2; i<=urls.length-2; i=i+2)
{
request.addProperty(urls[i].toString(), urls[i+1].toString());
}
}
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(URL);
httpTransport.call(SOAP_ACTION, envelope);
String result;
result = ((SoapPrimitive) envelope.getResponse()).toString();
response = result;
WSReturnVal = response;
if(WSReturnVal!="")
{
String ayrac1 = "^", ayrac2="|";
String[] iller = WSReturnVal.split(ayrac1); //birden cok doktor var
for(int i=0;i<iller.length;i++)
{ Log.i("abc", "do in bg doktor ws before db write");
String[] ildegerleri = iller[i].split(ayrac2);
//gelen her bir row için
dbh.InsertIl(db, ildegerleri[1], Integer.parseInt(ildegerleri[0]));
}
//gelen her bir row için
//dbh.InsertIl(db, name, il_id);
//çağrılacak
dbh.close();
}
SystemClock.sleep(200);
}
catch (XmlPullParserException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
return response;
}
@Override
protected void onPostExecute(String result) {
WSReturnVal = "";
//tv.setText(result);
Toast.makeText(getApplicationContext(), "Web Service is accessed", Toast.LENGTH_SHORT).show();
}
}
private class LoadIllerWebServiceTask extends AsyncTask<String, Void, String> {
@Override
protected String doInBackground(String... urls) {
String response = "";
try {
//for (String url : urls) {
Log.i("abc", "do in bg iller ws");
String yontemadi = urls[0].toString();
SOAP_ACTION = NAMESPACE + yontemadi;
SoapObject request = new SoapObject(NAMESPACE, yontemadi);
request.addProperty("pass", "45!ghUvb0PsXc");
if(urls.length>2) //demekki baska parametreler var , once parametreadi sonrada value bu array icinde geliyor. s˝ral˝ olarak
{
for(int i=2; i<=urls.length-2; i=i+2)
{
request.addProperty(urls[i].toString(), urls[i+1].toString());
}
}
SoapSerializationEnvelope envelope = new SoapSerializationEnvelope(SoapEnvelope.VER11);
envelope.dotNet = true;
envelope.setOutputSoapObject(request);
HttpTransportSE httpTransport = new HttpTransportSE(URL);
httpTransport.call(SOAP_ACTION, envelope);
String result;
result = ((SoapPrimitive) envelope.getResponse()).toString();
response = result;
WSReturnVal = response;
if(WSReturnVal!="")
{
String[] doktorlar;
String ayrac1 = "^", ayrac2="|";
if(!WSReturnVal.contains(ayrac1)) {
doktorlar = new String[1];
doktorlar[0] = WSReturnVal; //tek doktor
}
else
doktorlar = WSReturnVal.split(ayrac1); //birden cok doktor var
for(int i=0;i<doktorlar.length;i++)
{
DbHelper dbh = new DbHelper(getApplicationContext());
SQLiteDatabase db = dbh.getWritableDatabase();
String[] doktordegerleri = doktorlar[i].split(ayrac2);
//gelen her bir row için
dbh.insertDoktor(db, Integer.parseInt(doktordegerleri[0]), doktordegerleri[1], doktordegerleri[2], doktordegerleri[3], doktordegerleri[4], Integer.parseInt(doktordegerleri[7]), doktordegerleri[5], doktordegerleri[6]);
dbh.close();
}
SystemClock.sleep(200);
}
}
catch (XmlPullParserException e) {
e.printStackTrace();
}
catch (Exception e) {
e.printStackTrace();
}
return response;
}
@Override
protected void onPostExecute(String result) {
WSReturnVal = "";
//tv.setText(result);
Toast.makeText(getApplicationContext(), "Web Service is accessed", Toast.LENGTH_SHORT).show();
}
}
}
What is not working is no error, and no result can be added to my local db.
But there is this error on LOgCat
09-29 11:02:45.218: ERROR/SQLiteDatabase(12529): close() was never explicitly called on database '/data/data/com.tugce.MitsActionBar/databases/MyDB1'
09-29 11:02:45.218: ERROR/SQLiteDatabase(12529): android.database.sqlite.DatabaseObjectNotClosedException: Application did not close the cursor or database object that was opened here
09-29 11:02:45.218: ERROR/SQLiteDatabase(12529): at android.database.sqlite.SQLiteDatabase.(SQLiteDatabase.java:1980)
09-29 11:02:45.218: ERROR/SQLiteDatabase(12529): at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:977)
09-29 11:02:45.218: ERROR/SQLiteDatabase(12529): at android.database.sqlite.SQLiteDatabase.openDatabase(SQLiteDatabase.java:956)
09-29 11:02:45.218: ERROR/SQLiteDatabase(12529): at android.database.sqlite.SQLiteDatabase.openOrCreateDatabase(SQLiteDatabase.java:1021)
09-29 11:02:45.218: ERROR/SQLiteDatabase(12529): at android.app.ContextImpl.openOrCreateDatabase(ContextImpl.java:750)
09-29 11:02:45.218: ERROR/SQLiteDatabase(12529): at android.content.ContextWrapper.openOrCreateDatabase(ContextWrapper.java:221)
09-29 11:02:45.218: ERROR/SQLiteDatabase(12529): at android.database.sqlite.SQLiteOpenHelper.getWritableDatabase(SQLiteOpenHelper.java:149)
09-29 11:02:45.218: ERROR/SQLiteDatabase(12529): at com.tugce.MitsActionBar.MitsAndroidApplication$LoadDoktorsWebServiceTask.doInBackground(MitsAndroidApplication.java:129)
09-29 11:02:45.218: ERROR/SQLiteDatabase(12529): at com.tugce.MitsActionBar.MitsAndroidApplication$LoadDoktorsWebServiceTask.doInBackground(MitsAndroidApplication.java:1)
09-29 11:02:45.218: ERROR/SQLiteDatabase(12529): at android.os.AsyncTask$2.call(AsyncTask.java:252)
09-29 11:02:45.218: ERROR/SQLiteDatabase(12529): at java.util.concurrent.FutureTask$Sync.innerRun(FutureTask.java:305)
09-29 11:02:45.218: ERROR/SQLiteDatabase(12529): at java.util.concurrent.FutureTask.run(FutureTask.java:137)
09-29 11:02:45.218: ERROR/SQLiteDatabase(12529): at java.util.concurrent.ThreadPoolExecutor.runWorker(ThreadPoolExecutor.java:1081)
09-29 11:02:45.218: ERROR/SQLiteDatabase(12529): at java.util.concurrent.ThreadPoolExecutor$Worker.run(ThreadPoolExecutor.java:574)
09-29 11:02:45.218: ERROR/SQLiteDatabase(12529): at java.lang.Thread.run(Thread.java:1020)
A: What is not working: WEB-service response, local db or something else ?
Can you show your log?
1) Check Web-service response(you can do it through browser:getting String open as .xml).
2) Check sqlite db (you can do it through plugin for eclipse on emulator).
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594158",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: function call with '$' as parameter I have a script which contains the following piece of code:
(function ($) {
// ...
})($);
Can anyone explain how to read it?
A: *
*Create an anonymous function
*Let it take one argument which will be called $
*Call the function immediately
*Pass it one argument which is whatever the value of $ is in the outer scope.
If the $ in the outer scope changes (by having a new value assign to it) then the value for $ in the inner scope will be protected from the change (since it is a different variable).
This also provides a clean scope for all other variables declared inside the function (if they use var as they should).
A: '$' is a legal variable in JavaScript. It could have just as easily been someCrazyLongVariableName
A: It kind of defeats the purpose of encapsulating the $ sign into an anonymous function.
It's a self executing anonymous function that takes $ as argument.
In most of the cases, you use this markup to avoid js libraries collisions : say that you want to use jQuery and prototype in your project. Very nice, but they both use the '$' sign... how to overcome this?
// jquery code here
(function($){
alert($ === jQuery);// the $ is a shortcut to jQuery
})(jQuery);
// non-jquery code here - ex: prototype
alert($ === jQuery);// the $ is NOT a shortcut to jQuery ANYMORE
A: If you're not thinking about the $ in particular, the extract is creating a javascript function and calling it in a single statement.
I'm not 100% sure, but i guess that the 2 $ variables would be a different scope.
I found this page useful, if a little verbose: -
http://www.authenticsociety.com/blog/JavaScript_DollarSign
In summary, it's no different to calling the variable a, but should be avoided.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594162",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Whats wrong with this print order have a look at this code:
#include<stdio.h>
#include <unistd.h>
int main()
{
int pipefd[2],n;
char buf[100];
if(pipe(pipefd)<0)
printf("Pipe error");
printf("\nRead fd:%d write fd:%d\n",pipefd[0],pipefd[1]);
if(write(pipefd[1],"Hello Dude!\n",12)!=12)
printf("Write error");
if((n=read(pipefd[0],buf,sizeof(buf)))<=0)
printf("Read error");
write(1,buf,n);
return 0;
}
I expect the printf to print Read fd and write fd before Hello Dude is read from the pipe. But thats not the case... see here. When i tried the same program in our college computer lab my output was
Read fd:3 write fd:4
Hello Dude!
also few of our friends observed that, changing the printf statement to contain more number of \n characters changed the output order... for example..printf("\nRead fd:%d\n write fd:%d\n",pipefd[0],pipefd[1]); meant that Read fd is printed then the message Hello Dude! then the write fd is printed. What is this behaviour??
Note: Out lab uses a linux server on which we run terminals, i don't remember the compiler version though.
A: It's because printf to the standard output stream is buffered but write to the standard output file descriptor is not.
That means the behaviour can change based on what sort of buffering you have. In C, standard output is line buffered if it can be determined to be connected to an interactive device. Otherwise it's fully buffered (see here for a treatise on why this is so).
Line buffered means it will flush to the file descriptor when it sees a newline. Fully buffered means it will only flush when the buffer fills (for example, 4K worth of data), or when the stream is closed (or when you fflush).
When you run it interactively, the flush happens before the write because printf encounters the \n and flushes automatically.
However, when you run it otherwise (such as by redirecting output to a file or in an online compiler/executor where it would probably do the very same thing to capture data for presentation), the flush happens after the write (because printf is not flushing after every line).
In fact, you don't need all that pipe stuff in there to see this in action, as per the following program:
#include <stdio.h>
#include <unistd.h>
int main (void) {
printf ("Hello\n");
write (1, "Goodbye\n", 8);
return 0;
}
When I execute myprog ; echo === ; myprog >myprog.out ; cat myprog.out, I get:
Hello
Goodbye
===
Goodbye
Hello
and you can see the difference that the different types of buffering makes.
If you want line buffering regardless of redirection, you can try:
setvbuf (stdin, NULL, _IOLBF, BUFSIZ);
early on in your program - it's implementation defined whether an implementation supports this so it may have no effect but I've not seen many where it doesn't work.
A: You shouldn't mix calls to write and printf on single file descriptor. Change write to fwrite.
Functions which use FILE are buffered. Functions which use file descriptors are not. This is why you may get mixed order.
You can also try calling fflush before write.
A: When you write onto the same file, or pipe, or whatever by two means at once (direct IO and output stream) you can get this behaviour. The reason is that the output stream is buffered.
With fflush() you can control that behaviour.
A: What is happening is that printf writes to stdout in a buffered way -- the string is kept in a buffer before being output -- while the 'write' later on writes to stdout unbuffered. This can have the effect that the output from 'write' appears first if the buffer from the printf is only flushed later on.
You can explicitly flush using fflush() -- but even better would be not to mix buffered and non-buffered writes to the same output. Type man printf, man fflush, man fwrite etc. on your terminal to learn more about what these commands do exactly.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594163",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: How do I send actions to a UIImage Subview, delegated from a UIAlertView Essentially I have a UIAlertView that pops up. When a user selects a button it calls itself, and based on the button index it brings up a UIImageView subview. My question is, because the UIImageView takes up a good portion of the screen it lays on top of the UIAlertView, so the cancel button is unseen. I was wondering if I could create actions on the UIImageView so that if it is clicked or touched up inside, the UIAlertView/UIImageView would resign and disappear?
Someone please help, I've been tooling around this for hours.
Here is the code from the button being clicked, and the button index.
- (void)alertView:(UIAlertView *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex {
// the user clicked one of the OK/Cancel buttons
if (buttonIndex == 0)
{
// exit(0);
}
else
{
UIAlertView *successAlert = [[UIAlertView alloc] initWithTitle:@"molecule" message:molURL delegate:nil cancelButtonTitle:@"OK" otherButtonTitles:nil];
UIImageView *imageView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, 280, 260)];
NSString *MyURL = molURL;
NSString *apURL = [NSString stringWithFormat:@"%@",MyURL];
NSURL * imageURL = [NSURL URLWithString:apURL];
NSData * imageData = [NSData dataWithContentsOfURL:imageURL];
UIImage * image1 = [UIImage imageWithData:imageData];
//UIImage *bkgImg = [[UIImage alloc] initWithContentsOfFile:path];
[imageView setImage:image1];
[successAlert addSubview:imageView];
[successAlert show];
}
}
A: MyImageView.h
#import <UIKit/UIKit.h>
@interface MyImageView : UIImageView {
}
@end
MyImageView.m
#import "MyImageView.h"
@implementation MyImageView
- (id)initWithFrame:(CGRect)frame {
self = [super initWithFrame:frame];
if (self) {
self.userInteractionEnabled=YES;
}
return self;
}
-(void) touchesBegan:(NSSet *)touches withEvent:(UIEvent *)event{
[UIView animateWithDuration:2.0f animations:^(void) {
self.alpha=0.0f;
super.hidden =YES;
UIAlertView *alert=(UIAlertView*)self.superview;
alert.alpha=0.0f;
[alert dismissWithClickedButtonIndex:0 animated:YES];
//or
//[alert removeFromSuperview];
}];
}
- (void)dealloc {
[super dealloc];
}
@end
MyViewController.h
@class MyImageView;
MyViewController.m
#import "MyImageView.h"
then while create imageView
MyImageView *specialImageView =[[MyImageView alloc]initWithFrame:CGRectMake(0, 0, 280, 260)];
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594168",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Q: Display PDF in IFrame when button is clicked in JSF I already coded one but it opens a new tab, what I want is to display the pdf inside the Iframe (the same page where the user inputted the data) when a command button is clicked. Thanks for the help!
A: You can use the rendered attribute to render content conditionally.
E.g.
<h:commandButton value="Show PDF" action="#{bean.showPdf}" />
<h:panelGroup rendered="#{not empty bean.pdfUrl}">
<iframe src="#{bean.pdfUrl}"></iframe>
</h:panelGroup>
with
public void showPdf() {
pdfUrl = "/context/filename.pdf";
}
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594183",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "0"
}
|
Q: cmd run automatically -> shell commands to view a sqlite database for android I want to run a 'adb shell' -> to view a sqlite database for android.
I need to run commands automatically in a CMD file.
But I only can get access to the shell #,not to sqlite3
sqlite.cmd (file)
cd "C:\android-sdk-windows\platform-tools"
adb shell
sqlite3 /data/data/ileran.game/databases/ilearn.db
If to run manually cmd console and write all this commands -> it`s working
A: Try executing shell as one command:
adb shell "sqlite3 /data/data/ileran.game/databases/ilearn.db"
Update
To start this and then take the input and redirect it to adb shell command you must use redirection operators. I'm not expert on Windows command shell, but try something like this:
0>adb shell "sqlite3 /data/data/ileran.game/databases/ilearn.db"
Read more about CMD redirection: http://www.microsoft.com/resources/documentation/windows/xp/all/proddocs/en-us/redirection.mspx?mfr=true
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594184",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Calling HTTPS from HTTP through AJAX for login I know its violates the Same origin policy, and that is why it is not possible through simple ajax request. I could use JSONP. But using JSONP for login doesn't sound secure ( no post only get ).
So is there a more secure way of implementing login into https through ajax ?
A: Not only does it violate the same origin policy, but since the page you are calling from is insecure it has the potential to be interfered with and leak all the data you are trying to keep secure.
Use HTTPS for the entire process.
Better yet, keep using HTTPS while people are logged in, otherwise you will have the Firesheep problem.
A: As we've discussed in the comments below, this is what Facebook does for their registration page, although there are some vulnerabilities to this method. While it won't appear secure to the user (no lock icon), the actual request is done over HTTPS. If you controlled the entirety of the receiving page, there would be nothing less secure about doing a JSONP request over GET. However, a man-in-the-middle attack could modify the receiving page on load, and cause the returned credentials to be sent to an attacker.
On the plus side though, no one that's just sniffing packets is going to be able to get the credentials: an attack would have to be fairly targeted.
Regarding cookies, technically, JSONP could "return" cookies; you'd just return name-value pairs of the cookies you wanted to set, and have a function on the receiving page set them.
But unless the browser treats <script>s differently, and it might, you should be able to set a cookie in the normal way using the Response Headers of your JSONP response.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594193",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "13"
}
|
Q: Python: Conditional elements in array A question from a complete Python novice.
I have a column array where I need to force certain values to zero depending on a conditional statement applied to another array. I have found two solutions, which both provide the correct answer. But they are both quite time consuming for the larger arrays I typically need (>1E6 elements) - also I suspect that it is poor programming technique. The two versions are:
from numpy import zeros,abs,multiply,array,reshape
def testA(y, f, FC1, FC2):
c = zeros((len(f),1))
for n in xrange(len(f)):
if abs(f[n,0]) >= FC1 and abs(f[n,0]) <= FC2:
c[n,0] = 1.
w = multiply(c,y)
return w
def testB(y, f, FC1, FC2):
z = [(abs(f[n,0])>=FC1 and abs(f[n,0])<=FC2) for n in xrange(len(f))]
z = multiply(array(z,dtype=float).reshape(len(f),1), y)
return z
The input arrays are column arrays as this matches the post processing to be done. The test can be done like:
>>> from numpy.random import normal as randn
>>> fs, N = 1.E3, 2**22
>>> f = fs/N*arange(N).reshape((N,1))
>>> x = randn(size=(N,1))
>>> w1 = testA(x,f,200.,550.)
>>> z1 = testB(x,f,200.,550.)
On my laptop testA takes 18.7 seconds and testB takes 19.3 - both for N=2**22. In testB I also tried to include "z = [None]*len(f)" to preallocate as suggested in another thread but this doesn't really make any difference.
I have two questions, which I hope to have the same answer:
*
*What is the "correct" Python solution to this problem?
*Is there anything I can do to get the answer faster?
I have deliberately not used any time at all using compiled Python for example - I wanted to have some working code first. Hopefully also something, which is good Python style. I hope to be able to get the execution time for N=2**22 below two seconds or so. This particular operation will be used many times so the execution time does matter.
I apologize in advance if the question is stupid - I haven't been able to find an answer in the overwhelming amount of not always easily accessible Python documentation or in another thread.
A: use bool array to access elements in array y:
def testC(y, f, FC1, FC2):
f2 = abs(f)
idx = (f2>=FC1) & (f2<=FC2)
y[~idx] = 0
return y
A: All of these are slower than HYRY solution by a large factor:
How about
( x[1] if FC1<=abs(x[0])<=FC2 else 0 for x in itertools.izip(f,x) )
If you need to do random access (very slow)
[ x[1] if FC1<=abs(x[0])<=FC2 else 0 for x in itertools.izip(f,x) ]
or you can also use map
map(lambda x: x[1] if FC1<=abs(x[0])<=FC2 else 0 , itertools,izip(f,x))
or using vectorize (faster than A and B but much much slower than C)
b1v = np.vectorize(lambda a,b: a if 200<=abs(b)<=550 else 0)
b1 = b1v(f,x)
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594204",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "2"
}
|
Q: Mobile jquery page transition issue I'm new to jquery mobile. Recently, I was working on mobile jquery + phonegap for ipad. I found various issues especially with page transition. I google out and found an issue here as well https://github.com/jquery/jquery-mobile/issues/455 but couldn't found any way out.
Using a4.0 mobile jquery:
1) I used $.mobile.changePage(url,"fade") method as I want to have transition effect when an external .html page is requested. But I noticed a strange issue that no javascript could run on that page( On the other.html, I have a div which fetch some data from database based on requested page using javascript and sqlite database). I googled out and found that this was because $.mobile.changePage calls through ajax.
2) I even tried out window.location.href=url, but no transition effect was shown.
Using b3 mobile jquery:
When used this version I found that blinky effect when transition was used as been discussed on https://github.com/jquery/jquery-mobile/issues/455 .
What I want is smooth transition like flip,fade etc. So please guide what i should do to get desired result.
A: I have seen similar problems just using standard data-role pages especially in going back. I think JQuery Mobile is aware of this as a CSS/CSS3 compatible fix. March 2012 is ETA.
A: You will probably have to ditch the transition for this as they use AJAX.
For external links in jQuery mobile, you need to use 'rel="external"' on your link.
|
{
"language": "en",
"url": "https://stackoverflow.com/questions/7594210",
"timestamp": "2023-03-29T00:00:00",
"source": "stackexchange",
"question_score": "1"
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.