问:
How can I set a cookie with expire time?
I am setting a cookie with JavaScript and it is working fine but it is not taking the expire time I am giving. It keeps on taking session value regardless of what I give, below is the code which I took from here

```<code>var now = new Date();
var time = now.getTime();
var expireTime = time + 1000*60;
now.setTime(expireTime);
var tempExp = 'Wed, 31 Oct 2012 08:50:17 GMT';
document.cookie = aaa+'='+sStr+';expires='+now.toGMTString()+';path=/';
</code>```

I tried giving hard-coded value but still it is showing expire as session in chrome dev tool

```<code>var tempExp = 'Wed, 31 Oct 2012 08:50:17 GMT';
document.cookie = aaa+'='+sStr+';expires='+tempExp+';path=/';
</code>```

Any idea what I am doing wrong?

答:
document.cookie = "cookie_name=cookie_value; max-age=31536000; path=/";
```

Will set the value for a year.

ContentLicense: CC BY-SA 4.0

Body:
I am setting a cookie with JavaScript and it is working fine but it is not taking the expire time I am giving. It keeps on taking session value regardless of what I give, below is the code which I took from here

var now = new Date();
var time = now.getTime();
var expireTime = time + 1000*60;
now.setTime(expireTime);
var tempExp = 'Wed, 31 Oct 2012 08:50:17 GMT';
document.cookie = aaa+'='+sStr+';expires='+now.toGMTString()+';path=/';

I tried giving hard-coded value but still it is showing expire as session in chrome dev tool

var tempExp = 'Wed, 31 Oct 2012 08:50:17 GMT';
document.cookie = aaa+'='+sStr+';expires='+tempExp+';path=/';

Any idea what I am doing wrong?

Body:
document.cookie = "cookie_name=cookie_value; max-age=31536000; path=/";

Will set the value for a year.


来源: stackexchange

问:
Getting product variations from WC_Product_Variation
I have a WooCommerce webshop, where T-Shirts are being sold. When a person looks at the cart, I'd like to give them the option to change sized on a T-Shirt. Currently, the dropdown menu i made looks like this:

```<code><?php
    if ( $item->is_type( 'variation' ) ){
?>
<select name="" class="product-size">
<?php
    foreach ( $item->get_available_variations() as $variation ):
?>
        <option value="">test</option>
<?php
    endforeach;
?>
</select>
<?php
   }
? >
</code>```

However, this gives me the following error:

```<code>Fatal error: Uncaught Error: Call to undefined method WC_Product_Variation::get_available_variations()
</code>```

So then it hit me; my $item variable, is already a variation. Is there a way to get the other variations for the same product?

Thanks

答:
If you check type of your object, it is of class WC_Order_Item_Product. You can use this

```<code>$variationId = $item->get_variation_id();

$variableProduct = new WC_Product_Variable($variationId)

$allVariations = $variableProduct->get_available_variations();
</code>```

====================================

Oh I see. You can try this.

```<code>$parentData = $item->get_parent_id();
$variableProduct = new WC_Product_Variable($parentData)
$allVariations = $variableProduct->get_available_variations();
</code>```

ContentLicense: CC BY-SA 3.0

Body:
I have a WooCommerce webshop, where T-Shirts are being sold. When a person looks at the cart, I'd like to give them the option to change sized on a T-Shirt. Currently, the dropdown menu i made looks like this:

<?php
    if ( $item->is_type( 'variation' ) ){
?>
<select name="" class="product-size">
<?php
    foreach ( $item->get_available_variations() as $variation ):
?>
        <option value="">test</option>
<?php
    endforeach;
?>
</select>
<?php
   }
? >

However, this gives me the following error:

Fatal error: Uncaught Error: Call to undefined method WC_Product_Variation::get_available_variations()

So then it hit me; my $item variable, is already a variation. Is there a way to get the other variations for the same product?

Thanks

Body:
If you check type of your object, it is of class WC_Order_Item_Product. You can use this

$variationId = $item->get_variation_id();

$variableProduct = new WC_Product_Variable($variationId)

$allVariations = $variableProduct->get_available_variations();

====================================

Oh I see. You can try this.

$parentData = $item->get_parent_id();
$variableProduct = new WC_Product_Variable($parentData)
$allVariations = $variableProduct->get_available_variations();


问:
I want the code whih make like that at inno-setup (send file to temporary Folder and call it Through button)
When I open the  Installation file
It send file to temporary Folder

I want to make lik that (I want the code)
and
when the user press this button  it open the file which I choose before
(I want the code which it make all)
and don't tell me read any help or any paper
Because I do it and I understand it but I can't make it.

I want to make the about button to open the filer witch extracted to ehe temporary Folder when the user press it ,like this Installation file

the folder witch the file extracted in is  "IS-XXXX.temp" and it change every time the user open the Installation file and I can't know sure the path of the file every time.

so that : ExtractTemporaryFile('filename.rtf')
I can't understand it !!!

Or how I can use the temporary file Through the button if the path change every time. I see  what I want in this picture  but I can't make like it.

http://i53.tinypic.com/dc8z7p.jpg

How can I connect the button to the temporary file?

答:
for any one want this

see

http://news.jrsoftware.org/read/article.php?id=89926&group=jrsoftware.innosetup#89926

thanks

ContentLicense: CC BY-SA 2.5


问:
Unable to generate the cron expression using cron-utils
I am using cron-utils jar for generating cron expression

0 0 8 ? 1/1 5#3 *

3rd Thursday of every month at 8 o' clock

Below is my code for above expression:

CronBuilder withMonth = CronBuilder.cron(
      CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ)
).withYear(always()).withDoM(QuestionMark.questionMark())
.withMonth(on(3, SpecialChar.HASH));

withMonth.withDoW(on(5)).withHour(on(8)).withMinute(on(0)).withSecond(on(0));

Cron instance = withMonth.instance();
System.out.println(instance.asString());
```
<p>But I'm getting the following exception:</p>
```value missing for a#b cron expression
```

答:
finally found solution

```<code>.withDoW(on(NUM_DAY_WEEK,SpecialChar.HASH, NUM_DAY_MONTH);
</code>```

it will generate like 5#3

Body:
I am using cron-utils jar for generating cron expression

0 0 8 ? 1/1 5#3 *

3rd Thursday of every month at 8 o' clock

Below is my code for above expression:

CronBuilder withMonth = CronBuilder.cron(
      CronDefinitionBuilder.instanceDefinitionFor(CronType.QUARTZ)
).withYear(always()).withDoM(QuestionMark.questionMark())
.withMonth(on(3, SpecialChar.HASH));

withMonth.withDoW(on(5)).withHour(on(8)).withMinute(on(0)).withSecond(on(0));

Cron instance = withMonth.instance();
System.out.println(instance.asString());

But I'm getting the following exception:

value missing for a#b cron expression

Body:
finally found solution

.withDoW(on(NUM_DAY_WEEK,SpecialChar.HASH, NUM_DAY_MONTH);

it will generate like 5#3


问:
pandas replace column with mean for values
I have a pandas dataframe and want replace each value with the mean for it.

```<code>    ID    X     Y
    1     a     1
    2     a     2
    3     a     3
    4     b     2
    5     b     4
</code>```

How do I replace Y values with mean Y for every unique X?

```<code>    ID    X     Y
    1     a     2
    2     a     2
    3     a     2
    4     b     3
    5     b     3
</code>```

答:
Use transform:

```<code>df['Y'] = df.groupby('X')['Y'].transform('mean')
print (df)
   ID  X  Y
0   1  a  2
1   2  a  2
2   3  a  2
3   4  b  3
4   5  b  3
</code>```

For new column in another DataFrame use map with drop_duplicates:

```<code>df1 = pd.DataFrame({'X':['a','a','b']})
print (df1)
   X
0  a
1  a
2  b

df1['Y'] = df1['X'].map(df.drop_duplicates('X').set_index('X')['Y'])
print (df1)
   X  Y
0  a  2
1  a  2
2  b  3
</code>```

Another solution:

```<code>df1['Y'] = df1['X'].map(df.groupby('X')['Y'].mean())
print (df1)
   X  Y
0  a  2
1  a  2
2  b  3
</code>```

Body:
I have a pandas dataframe and want replace each value with the mean for it.

    ID    X     Y
    1     a     1
    2     a     2
    3     a     3
    4     b     2
    5     b     4

How do I replace Y values with mean Y for every unique X?

    ID    X     Y
    1     a     2
    2     a     2
    3     a     2
    4     b     3
    5     b     3

Body:
Use transform:

df['Y'] = df.groupby('X')['Y'].transform('mean')
print (df)
   ID  X  Y
0   1  a  2
1   2  a  2
2   3  a  2
3   4  b  3
4   5  b  3

For new column in another DataFrame use map with drop_duplicates:

df1 = pd.DataFrame({'X':['a','a','b']})
print (df1)
   X
0  a
1  a
2  b

df1['Y'] = df1['X'].map(df.drop_duplicates('X').set_index('X')['Y'])
print (df1)
   X  Y
0  a  2
1  a  2
2  b  3

Another solution:

df1['Y'] = df1['X'].map(df.groupby('X')['Y'].mean())
print (df1)
   X  Y
0  a  2
1  a  2
2  b  3


问:
iPhone OS Utility App - Flipside View and Main View communication
I am currently working on an iPhone 2.1 application. I am new to Objective C, coming from a Java background.

My application has as a base the Utility Application template available in Xcode with the iPhone SDK. Currently I have some controls, such as an UISlider and text box, in the FlipsideView. The UISlider already has a method which is being called when the value changes, using targets and selectors. However, I would also like to be able to read, from the MainView, the current (or last) value of the UISlider and textbox.

Keep in mind I am new to development on a Mac, and would appreciate any guidance as to where I should look up such information, be it through the use of delegates or perhaps I am missing something obvious in the structure of the template.

UPDATE:
I am taking a look at the structure and have some more details: The UISlider is being created in FlipsideView.m. I noticed that the Done button is created from RootViewController.m and probably I should move the UISlider code over there. I may incorrectly be using the View to keep code that would be more appropiate in a Controller.

答:
I'm in exactly the same situation: first iphone app, new to mac programming, creating a utility, sliders on the flipside.

By following the example and the free tutorial here (http://www.bestechvideos.com/2008/11/13/writing-iphone-app-free-episode) I determined that the sliders and other controls should be declared on the flipsideviewcontroller. (Which leave the view pretty empty - I guess the use of the Nib resource file for the UI leaves  the ...View.m class pretty much redundant?)

Wisequark's answer is a bit to general to help me though.
In terms of specifics:
 - I can't find that video is there a link?
 - Could we see some code showing the Controller-Model code?
 - How do I persist the values set on the slider without having to build UI to go in the system settings?

(BTW is an Answer the right place to add to the question?)

OwnerDisplayName: Hector Ramos

LastEditorDisplayName: Ned Batchelder

OwnerDisplayName: Rhubarb


问:
Why the Bottom Sheet is on the main screen?
I am trying to make an app with Bottom Sheet. But when I run the app, the Bottom Sheet shows in main screen. It means, the Bottom Sheet appears in the main screen without clicking on the Button. An image has been attested below for clear understanding. sample image

This is the MainActivity.java class:

```<code>package com.example.qurdadzze.b;
import android.support.design.widget.BottomSheetBehavior;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
Button btn;
NestedScrollView bottomsheet;
BottomSheetBehavior behavior;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn = (Button) findViewById(R.id.btn);
    bottomsheet = (NestedScrollView) findViewById(R.id.bottomsheet);
    behavior = BottomSheetBehavior.from(bottomsheet);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(behavior.getState()==BottomSheetBehavior.STATE_COLLAPSED)
                behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
            else
                behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
            behavior.setPeekHeight(0);
        }
    });
}
</code>```

And this is activity_main.xml:

```<code><?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context="com.example.qurdadzze.b.MainActivity">

    <Button
        android:id="@+id/btn"
        android:layout_width="150dp"
        android:layout_height="50dp"
        android:text="show bottom sheet"/>

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:background="#99cc99"
        android:elevation="100dp"
        android:id="@+id/bottomsheet"
        app:layout_behavior="@string/bottom_sheet_behavior">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="20sp"
            android:layout_gravity="center|top"
            android:gravity="center"
            android:text="it is me Bottom Sheet"/>

    </android.support.v4.widget.NestedScrollView>

</android.support.design.widget.CoordinatorLayout>
</code>```

答:
You will have to set peekheight of Bottomsheet.

android.support.design:behavior_peekHeight The height of the bottom sheet when it is collapsed.

Try using below code in your NestedScrollView:

```<code>app:behavior_peekHeight="50dp"
</code>```

For more details check below link:
http://www.truiton.com/2016/07/android-bottom-sheet-example/

Body:
I am trying to make an app with Bottom Sheet. But when I run the app, the Bottom Sheet shows in main screen. It means, the Bottom Sheet appears in the main screen without clicking on the Button. An image has been attested below for clear understanding. sample image

This is the MainActivity.java class:

package com.example.qurdadzze.b;
import android.support.design.widget.BottomSheetBehavior;
import android.support.v4.widget.NestedScrollView;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;

public class MainActivity extends AppCompatActivity {
Button btn;
NestedScrollView bottomsheet;
BottomSheetBehavior behavior;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn = (Button) findViewById(R.id.btn);
    bottomsheet = (NestedScrollView) findViewById(R.id.bottomsheet);
    behavior = BottomSheetBehavior.from(bottomsheet);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if(behavior.getState()==BottomSheetBehavior.STATE_COLLAPSED)
                behavior.setState(BottomSheetBehavior.STATE_EXPANDED);
            else
                behavior.setState(BottomSheetBehavior.STATE_COLLAPSED);
            behavior.setPeekHeight(0);
        }
    });
}

And this is activity_main.xml:

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:tools="http://schemas.android.com/tools"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context="com.example.qurdadzze.b.MainActivity">

    <Button
        android:id="@+id/btn"
        android:layout_width="150dp"
        android:layout_height="50dp"
        android:text="show bottom sheet"/>

    <android.support.v4.widget.NestedScrollView
        android:layout_width="match_parent"
        android:layout_height="300dp"
        android:background="#99cc99"
        android:elevation="100dp"
        android:id="@+id/bottomsheet"
        app:layout_behavior="@string/bottom_sheet_behavior">

        <TextView
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:textSize="20sp"
            android:layout_gravity="center|top"
            android:gravity="center"
            android:text="it is me Bottom Sheet"/>

    </android.support.v4.widget.NestedScrollView>

</android.support.design.widget.CoordinatorLayout>

Body:
You will have to set peekheight of Bottomsheet.

android.support.design:behavior_peekHeight The height of the bottom sheet when it is collapsed.

Try using below code in your NestedScrollView:

app:behavior_peekHeight="50dp"

For more details check below link:
http://www.truiton.com/2016/07/android-bottom-sheet-example/


问:
Click on bootstrap dropdown element and change the value
This is the dropdwon

```<code><div class="col-md-6">
             <div class="dropdown">
                <input  type="text" data-toggle="dropdown" id="search-input" class="form-control">
                <ul class="dropdown-menu" id="employee-list">
                  <!--filled by ajax -->
                </ul>
              </div>
        </div>
</code>```

and I get the list with aand itry to get the click event but nothing its done

```<code>$(document).ready( function(){
    $('#search-input').keyup(function(e){
        if($(this).val().length >= 3 /*&& e.which != 8*/ ){
            get_users($(this).val());
        }
    });

    $(".dropdown-menu li a").click(function(){
        alert('aaaa');
    });
});
</code>```

Ineed to click a list element and set the text of the input with the text of the clicked element but I can't handle the click event

```<code>function get_users($text){
    $.ajax({
      url: "asociate_ci.php",
      method: 'get',
      data: {
        'text': $text ,
        'option':'get_users'
      }
    })
      .done(function( response ) {
        var employees = JSON.parse(response);
        //console.dir(employees);
        $('#employee-list').empty();
        $.each(employees, function(){
            //console.log(this.last_name);
            $('#employee-list').append("<li ><a class='employee-li'>"+this.last_name+"</a></li>");
        });
        $('#search-input').focus();
      });
}
</code>```

答:
You need to use on using a single handler a for all elements that match your selector .dropdown-menu. This will be able to bind to dynamically created elements.

```<code>// $(".dropdown-menu") = watch for any changes to the dom inside this element
// 'click' = event type
// a = add click event to these elements
$('.dropdown-menu').on('click', 'a', function(){
    alert('aaaa');
});
</code>```

Body:
This is the dropdwon

                <input  type="text" data-toggle="dropdown" id="search-input" class="form-control">

and I get the list with aand itry to get the click event but nothing its done

$(document).ready( function(){
    $('#search-input').keyup(function(e){
        if($(this).val().length >= 3 /*&& e.which != 8*/ ){
            get_users($(this).val());
        }
    });

    $(".dropdown-menu li a").click(function(){
        alert('aaaa');
    });
});

Ineed to click a list element and set the text of the input with the text of the clicked element but I can't handle the click event

function get_users($text){
    $.ajax({
      url: "asociate_ci.php",
      method: 'get',
      data: {
        'text': $text ,
        'option':'get_users'
      }
    })
      .done(function( response ) {
        var employees = JSON.parse(response);
        //console.dir(employees);
        $('#employee-list').empty();
        $.each(employees, function(){
            //console.log(this.last_name);
            $('#employee-list').append("
"+this.last_name+"
");
        });
        $('#search-input').focus();
      });
}

Body:
You need to use on using a single handler a for all elements that match your selector .dropdown-menu. This will be able to bind to dynamically created elements.

// $(".dropdown-menu") = watch for any changes to the dom inside this element
// 'click' = event type
// a = add click event to these elements
$('.dropdown-menu').on('click', 'a', function(){
    alert('aaaa');
});


问:
Embedded Python 3.5 "python setup.py egg_info" failed with error code 1
I am attempting to "pip install" PyAutoGUI ( among other modules ) and I am getting the following error :

```<code>Collecting pyautogui
  Using cached PyAutoGUI-0.9.35.zip
  Complete output from command python setup.py egg_info:
running egg_info
creating pip-egg-info\PyAutoGUI.egg-info
writing top-level names to pip-egg-info\PyAutoGUI.egg-info\top_level.txt
writing requirements to pip-egg-info\PyAutoGUI.egg-info\requires.txt
writing pip-egg-info\PyAutoGUI.egg-info\PKG-INFO
writing dependency_links to pip-egg-info\PyAutoGUI.egg-info\dependency_links.txt
writing manifest file 'pip-egg-info\PyAutoGUI.egg-info\SOURCES.txt'
error: [Errno 2] No such file or directory: 'C:\\Users\\myDir\\Downloads\\python-3.5.0-embed-win32\\python35.zip\\lib2to3\\Grammar.txt'

----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in         C:\Users\myDir\AppData\Local\Temp\pip-build-aqcbpbui\pyautogui\
</code>```

This is being done on a Windows 10 Professional without admin rights ( hence the embedded method of using Python 3.5 ). I was able to pip install openpyxl without issue but when running the same command ( python -m pip install pyautogui ) I get the described error message and traceback found above. I've done clean extractions of the zip and found the same problem.

I searched through SO and only found questions that related to Mac environments and a single instance where the OS wasn't listed ( "python setup.py egg_info" failed with error code 1 ) which yielded no positive results ( actually ended up getting a different error message with the second suggested step...but...one issue at a time :P )

I've confirmed that the file in question (( 'C:\Users\myDir\Downloads\python-3.5.0-embed-win32\python35.zip\lib2to3\Grammar.txt' ))  exists and even unzipped the directory just to be sure ( leaving the zip there as well intact to keep myself covered ). I attempted Easy_install and it yielded a similar set of messages and end result error ( not posting it to reduce clutter of this post but will provide on request ).

Any advice would be thoroughly appreciated. Thank you.

答:
I faced the same problem while using 3.5.2 and 3.6.1 versions of the embedded python distribution zip for Windows.
Though, with the MSI installer, this problem does not arise.

I suspect, this has something to do with the way the python3X.zip file is read for \lib2to3\Grammar.txt.
Here is how I have resolved it :

I have renamed the python35.zip file to something else (.zipp etc ..)

I have created a folder "python.zip" inside my original extracted folder

Made sure that "\lib2to3\Grammar.txt" is accessible within this folder.

Ran "python -m pip install "

Worked like a charm  !

A hack probably, but, could not find a way around.

Body:
I am attempting to "pip install" PyAutoGUI ( among other modules ) and I am getting the following error :

Collecting pyautogui
  Using cached PyAutoGUI-0.9.35.zip
  Complete output from command python setup.py egg_info:
running egg_info
creating pip-egg-info\PyAutoGUI.egg-info
writing top-level names to pip-egg-info\PyAutoGUI.egg-info\top_level.txt
writing requirements to pip-egg-info\PyAutoGUI.egg-info\requires.txt
writing pip-egg-info\PyAutoGUI.egg-info\PKG-INFO
writing dependency_links to pip-egg-info\PyAutoGUI.egg-info\dependency_links.txt
writing manifest file 'pip-egg-info\PyAutoGUI.egg-info\SOURCES.txt'
error: [Errno 2] No such file or directory: 'C:\\Users\\myDir\\Downloads\\python-3.5.0-embed-win32\\python35.zip\\lib2to3\\Grammar.txt'

----------------------------------------
Command "python setup.py egg_info" failed with error code 1 in         C:\Users\myDir\AppData\Local\Temp\pip-build-aqcbpbui\pyautogui\

This is being done on a Windows 10 Professional without admin rights ( hence the embedded method of using Python 3.5 ). I was able to pip install openpyxl without issue but when running the same command ( python -m pip install pyautogui ) I get the described error message and traceback found above. I've done clean extractions of the zip and found the same problem.

I searched through SO and only found questions that related to Mac environments and a single instance where the OS wasn't listed ( "python setup.py egg_info" failed with error code 1 ) which yielded no positive results ( actually ended up getting a different error message with the second suggested step...but...one issue at a time :P )

I've confirmed that the file in question (( 'C:\Users\myDir\Downloads\python-3.5.0-embed-win32\python35.zip\lib2to3\Grammar.txt' ))  exists and even unzipped the directory just to be sure ( leaving the zip there as well intact to keep myself covered ). I attempted Easy_install and it yielded a similar set of messages and end result error ( not posting it to reduce clutter of this post but will provide on request ).

Any advice would be thoroughly appreciated. Thank you.


问:
How to use a shell variable inside sed when doing "d" command?
In my bash, I wish to delete lines from 1 to ${number}, like this:

```<code>number=10
sed '1,${number}d' myfile
</code>```

It failed with syntax error.
I also tried "\${number}", '"$number"', neithers works

I changed to double quote, it works under command line, but not inside bash script file. How to make it work?

答:
Enclose your sed expression in double quotes to interpolate the variable number:

```<code>sed "1,${number}d" file
</code>```

Body:
In my bash, I wish to delete lines from 1 to ${number}, like this:

number=10
sed '1,${number}d' myfile

It failed with syntax error.
I also tried "\${number}", '"$number"', neithers works

I changed to double quote, it works under command line, but not inside bash script file. How to make it work?

Body:
Enclose your sed expression in double quotes to interpolate the variable number:

sed "1,${number}d" file


问:
Is toJSON supported in Google Chrome?
when using JSON.stringify in Google Chrome it seems that toJSON isn't being called? I am using json2.js as a back-up for browsers that don't support it. I guess since Chrome supports JSON but not toJSON json2.js isn't being used at all?

Update

Here is an example: http://jsfiddle.net/GZzvZ/

Firefox: {"foo":"foo","bar":"bar"}

Chrome: {"bar":"bar"}

答:
```<code>var t = {};

t.toJSON = function () { alert('meuh'); return (''); }
JSON.stringify(t)
</code>```

Works perfectly fine for me.
It does alert, so it does call the toJSON method appropriately (in Chrome 8).

EDIT:

That's normal. Your Foo is a  function, and function objects are not allowed in JSON. Firefox is just being forgiving, I guess.

Well, actually I wonder, I don't find a clear answer in the standard. Considering you supply a toJSON() to provide your own serialization, should it be allowed or not. But anyway, that's the reason for your failure.

If you edit your jsFiddle example like this, the toJSON is called accordingly on foo.

```<code>var obj = function(){
    this.foo = 'test'; // OK
    //this.foo = function(){ }; KO
    this.foo.toJSON = function(){
        return 'foo';
    };

    this.bar = 'bar';
}

var ins = new obj();
var json = JSON.stringify( ins );
document.write( json );
</code>```

Title: Is toJSON supported in Google Chrome?

Body:
var t = {};

t.toJSON = function () { alert('meuh'); return (''); }
JSON.stringify(t)

Works perfectly fine for me.
It does alert, so it does call the toJSON method appropriately (in Chrome 8).

EDIT:

That's normal. Your Foo is a  function, and function objects are not allowed in JSON. Firefox is just being forgiving, I guess.

Well, actually I wonder, I don't find a clear answer in the standard. Considering you supply a toJSON() to provide your own serialization, should it be allowed or not. But anyway, that's the reason for your failure.

If you edit your jsFiddle example like this, the toJSON is called accordingly on foo.

var obj = function(){
    this.foo = 'test'; // OK
    //this.foo = function(){ }; KO
    this.foo.toJSON = function(){
        return 'foo';
    };

    this.bar = 'bar';
}

var ins = new obj();
var json = JSON.stringify( ins );
document.write( json );


问:
Xpages setvalue bug?

My database allow Anonymous to access the database and submit form to do process
It have 3 roles inside [Applicant],[Admin],[Reviewer]

problem:

I need to update "Email" field by combining 3 different "mail" field to combine it. So i use add element but it seem save wrong data, it give an extra [applicant]. Attached image will display how it display

```<code>var v;
//  Update mail 1 and mail 2 and mail3 into Email field!
if
(
    (document1.getValue("Mail1")!=null && document1.getValue("Mail1")!="")&&
    (document1.getValue("Mail2")!=null && document1.getValue("Mail2")!="")&&
    (document1.getValue("Mail3")!=null && document1.getValue("Mail3")!="")
)   //all not empty
    {
        v.addElement(document1.getValue("Mail1")+"@brookedockyard.com.my");
        v.addElement(document1.getValue("Mail2")+"@brookedockyard.com.my");
        v.addElement(document1.getValue("Mail3")+"@brookedockyard.com.my");
        document1.replaceItemValue("Email",v)

else if
(
    (document1.getValue("Mail1")!=null && document1.getValue("Mail1")!="")&&
    (document1.getValue("Mail2")==null && document1.getValue("Mail2")=="")&&
    (document1.getValue("Mail3")===null && document1.getValue("Mail3")=="")
)   //  only have mail 1
    {
        document1.replaceItemValue("Email", document1.getValue("Mail1")+"@brookedockyard.com.my")
    }
else if
(
    (document1.getValue("Mail1")!=null && document1.getValue("Mail1")!="")&&
    (document1.getValue("Mail2")!=null && document1.getValue("Mail2")!="")&&
    (document1.getValue("Mail3")==null && document1.getValue("Mail3")=="")
)   //  only have mail 1 and mail 2
    {
        v.addElement(document1.getValue("Mail1")+"@brookedockyard.com.my");
        v.addElement(document1.getValue("Mail2")+"@brookedockyard.com.my");
        document1.replaceItemValue("Email",v)

else if
(
    (document1.getValue("Mail1")!=null && document1.getValue("Mail1")!="")&&
    (document1.getValue("Mail2")==null && document1.getValue("Mail2")=="")&&
    (document1.getValue("Mail3")!=null && document1.getValue("Mail3")!="")
)       //  only have mail 1 and mail 3
    {
        v.addElement(document1.getValue("Mail1")+"@brookedockyard.com.my");
        v.addElement(document1.getValue("Mail3")+"@brookedockyard.com.my");
        document1.replaceItemValue("Email",v)

    }
</code>```

i am using serverside javascript to save document. But during save it add extra information inside the system.

答:
Create a request scoped bean.

faces-config.xml

```<code><managed-bean>
    <managed-bean-name>forgetSsjs</managed-bean-name>
    <managed-bean-class>demo.bean.ForgetSsjsBean
    </managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
</managed-bean>
</code>```

the bean

```<code>package demo.bean;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import java.util.Vector;

import javax.faces.FacesException;
import javax.faces.context.FacesContext;

import lotus.domino.NotesException;

import com.ibm.commons.util.StringUtil;
import com.ibm.xsp.model.domino.wrapped.DominoDocument;
import com.ibm.xsp.util.FacesUtil;

public class ForgetSsjsBean implements Serializable {

    private static final long serialVersionUID = 1L;

    public void saveTheDoc() {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        DominoDocument wrapper = (DominoDocument) FacesUtil.resolveVariable(facesContext,
                "document1");

        Set<String> emails = new HashSet<String>();

        try {
            for (int i = 1; i < 4; i++) {
                addEmail(wrapper.getItemValueString("Mail" + i), emails);
            }

            if (!emails.isEmpty()) {
                wrapper.replaceItemValue("Email", new Vector<String>(emails));
                wrapper.save();
            }
        } catch (NotesException e) {
            throw new FacesException(e);
        }
    }

    private void addEmail(String name, Set<String> emails) {
        if (StringUtil.isEmpty(name)) {
            return;
        }

        emails.add(name + "@brookedockyard.com.my");
    }

}
</code>```

Link your event handler action to the method you destine for saving the document:

the xsp page

```<code><xp:this.data>
    <xp:dominoDocument var="document1" ... />
</xp:this.data>

...

<xp:button id="button1" value="save this thing">
    <xp:eventHandler event="onclick" submit="true"
        refreshMode="partial" action="#{forgetSsjs.saveTheDoc}" />
</xp:button>
</code>```

Title: Xpages setvalue bug?

Body:
My database allow Anonymous to access the database and submit form to do process
It have 3 roles inside [Applicant],[Admin],[Reviewer]

problem:

I need to update "Email" field by combining 3 different "mail" field to combine it. So i use add element but it seem save wrong data, it give an extra [applicant]. Attached image will display how it display

var v;
//  Update mail 1 and mail 2 and mail3 into Email field!
if
(
    (document1.getValue("Mail1")!=null && document1.getValue("Mail1")!="")&&
    (document1.getValue("Mail2")!=null && document1.getValue("Mail2")!="")&&
    (document1.getValue("Mail3")!=null && document1.getValue("Mail3")!="")
)   //all not empty
    {
        v.addElement(document1.getValue("Mail1")+"@brookedockyard.com.my");
        v.addElement(document1.getValue("Mail2")+"@brookedockyard.com.my");
        v.addElement(document1.getValue("Mail3")+"@brookedockyard.com.my");
        document1.replaceItemValue("Email",v)

else if
(
    (document1.getValue("Mail1")!=null && document1.getValue("Mail1")!="")&&
    (document1.getValue("Mail2")==null && document1.getValue("Mail2")=="")&&
    (document1.getValue("Mail3")===null && document1.getValue("Mail3")=="")
)   //  only have mail 1
    {
        document1.replaceItemValue("Email", document1.getValue("Mail1")+"@brookedockyard.com.my")
    }
else if
(
    (document1.getValue("Mail1")!=null && document1.getValue("Mail1")!="")&&
    (document1.getValue("Mail2")!=null && document1.getValue("Mail2")!="")&&
    (document1.getValue("Mail3")==null && document1.getValue("Mail3")=="")
)   //  only have mail 1 and mail 2
    {
        v.addElement(document1.getValue("Mail1")+"@brookedockyard.com.my");
        v.addElement(document1.getValue("Mail2")+"@brookedockyard.com.my");
        document1.replaceItemValue("Email",v)

else if
(
    (document1.getValue("Mail1")!=null && document1.getValue("Mail1")!="")&&
    (document1.getValue("Mail2")==null && document1.getValue("Mail2")=="")&&
    (document1.getValue("Mail3")!=null && document1.getValue("Mail3")!="")
)       //  only have mail 1 and mail 3
    {
        v.addElement(document1.getValue("Mail1")+"@brookedockyard.com.my");
        v.addElement(document1.getValue("Mail3")+"@brookedockyard.com.my");
        document1.replaceItemValue("Email",v)

    }

i am using serverside javascript to save document. But during save it add extra information inside the system.

Body:
Create a request scoped bean.

faces-config.xml

<managed-bean>
    <managed-bean-name>forgetSsjs</managed-bean-name>
    <managed-bean-class>demo.bean.ForgetSsjsBean
    </managed-bean-class>
    <managed-bean-scope>request</managed-bean-scope>
</managed-bean>

the bean

package demo.bean;

import java.io.Serializable;
import java.util.HashSet;
import java.util.Set;
import java.util.Vector;

import javax.faces.FacesException;
import javax.faces.context.FacesContext;

import lotus.domino.NotesException;

import com.ibm.commons.util.StringUtil;
import com.ibm.xsp.model.domino.wrapped.DominoDocument;
import com.ibm.xsp.util.FacesUtil;

public class ForgetSsjsBean implements Serializable {

    private static final long serialVersionUID = 1L;

    public void saveTheDoc() {
        FacesContext facesContext = FacesContext.getCurrentInstance();
        DominoDocument wrapper = (DominoDocument) FacesUtil.resolveVariable(facesContext,
                "document1");

        Set<String> emails = new HashSet<String>();

        try {
            for (int i = 1; i < 4; i++) {
                addEmail(wrapper.getItemValueString("Mail" + i), emails);
            }

            if (!emails.isEmpty()) {
                wrapper.replaceItemValue("Email", new Vector<String>(emails));
                wrapper.save();
            }
        } catch (NotesException e) {
            throw new FacesException(e);
        }
    }

    private void addEmail(String name, Set<String> emails) {
        if (StringUtil.isEmpty(name)) {
            return;
        }

        emails.add(name + "@brookedockyard.com.my");
    }

}

Link your event handler action to the method you destine for saving the document:

the xsp page

<xp:this.data>
    <xp:dominoDocument var="document1" ... />
</xp:this.data>

...

<xp:button id="button1" value="save this thing">
    <xp:eventHandler event="onclick" submit="true"
        refreshMode="partial" action="#{forgetSsjs.saveTheDoc}" />
</xp:button>


问:
How can I replace image with javascript?
My view like this :

```<code><li id="thumbnail-view" class="count-photo">
    <div class="thumbnail">
        <img src="{{ asset('img/thumbs/'.$photo) }}" alt="">
        <a href="javascript:" class="thumbnail-check"><span class="fa fa-check-circle"></span></a>
        <ul class="list-inline list-edit">
            ...
        </ul>
    </div>
</li>
</code>```

My javascript like this :

```<code>var photo = 'flower.jpg';
var res = `<img src="{{ asset('img/thumbs/'+photo) }}" alt="">`
$('#thumbnail-view img').html(res);
</code>```

If the javascript code executed, I want to change the image

I try like that, but it does not work

How can I do it?

答:
Simple way</p>

```<code> var photo = 'flower.jpg';
 $('#thumbnail-view img').attr('src', photo);
</code>```

Body:
My view like this :

            ...

My javascript like this :

var photo = 'flower.jpg';
var res = `<img src="{{ asset('img/thumbs/'+photo) }}" alt="">`
$('#thumbnail-view img').html(res);

If the javascript code executed, I want to change the image

I try like that, but it does not work

How can I do it?

Body:
Simple way

 var photo = 'flower.jpg';
 $('#thumbnail-view img').attr('src', photo);


问:
How to Send Push notification in Ionic Framework?
How to send Push Notification in Android Hybrid Application using built on Ionic Framework.
I am Newbie, Please Guide me Step by Step how to send Push notification in ionic?
I saw a different tutorials on youtube and other websites but i am confused where to add those code which shown on these website. I have GCM Project Number (SENDER_ID)  but dont know where to put it.
Please Guide In details.
Thanks in Advance.

答:
Try using phonegap-plugin-push ? It is easy to implement and use.

Config :

```<code>    var push = PushNotification.init({
        "android": {
            "senderID": "Your-sender-ID",
            "forceShow": true, // To show notifications on screen as well
            "iconColor": "#403782",
            "badge": "true",
            "clearBadge": "true" // To clear app badge
        },
        "ios": {
            "alert": "true",
            "badge": "true",
            "clearBadge": "true",
            "sound": "true",
            "forceShow": "true"
        },
        "windows": {}
    });
</code>```

Device Registration :

```<code>    push.on('registration', function(data) {
            localStorage.setItem('pushToken', data.registrationId); // Save registration ID
    });
</code>```

Handle Notifications

```<code>    push.on('notification', function(data) {
        console.log(data);
        // Handle all requests here
        if (data.additionalData.$state == "mystate") {
            $state.go('app.conversations');
        }
    })
</code>```

Body:
Try using phonegap-plugin-push ? It is easy to implement and use.

Config :

    var push = PushNotification.init({
        "android": {
            "senderID": "Your-sender-ID",
            "forceShow": true, // To show notifications on screen as well
            "iconColor": "#403782",
            "badge": "true",
            "clearBadge": "true" // To clear app badge
        },
        "ios": {
            "alert": "true",
            "badge": "true",
            "clearBadge": "true",
            "sound": "true",
            "forceShow": "true"
        },
        "windows": {}
    });

Device Registration :

    push.on('registration', function(data) {
            localStorage.setItem('pushToken', data.registrationId); // Save registration ID
    });

Handle Notifications

    push.on('notification', function(data) {
        console.log(data);
        // Handle all requests here
        if (data.additionalData.$state == "mystate") {
            $state.go('app.conversations');
        }
    })


问:
Div tag get down while hover it
While I hover Div tag, Another Div tag will appear in front of the prev Div. When i didn't put any words, it works. but when i put h3 tag, the div goes down.

here is the HTML

```<code><div id="content">
    <h1 class="head-content">Biscuits</h1>
    <div class="line"></div>
    <a href="#">
        <div class="list-content">
            <div class="detail-content">
                <h3>Biscuits 1</h3>
                <p>Price: IDR 12000</p>
            </div>
        </div>
    </a>
    <a href="#">
        <div class="list-content">
            <div class="detail-content">

            </div>
        </div>
    </a>
    <a href="#">
        <div class="list-content">
            <div class="detail-content">

            </div>
        </div>
    </a>
</div>
</code>```

here is CSS

```<code>#content{
        width:50%;
    }
    .line{
        border-top: 5px solid black;
    }
    .list-content{
        display:inline-block;
        width:25%;
        height:200px;
        background-color: black;
        margin-top: 10px;
    }
    .detail-content{
        display: none;
    }
    .list-content:hover .detail-content{
        display: block;
        width:100%;
        height:75%;
        background-color: rgba(255,255,255,0.6);
    }
</code>```

thank you before

答:
Update below css part

```<code>.list-content:hover .detail-content {
  display: table;
  width: 100%;
  height: 75%;
  background-color: rgba(255, 255, 255, 0.6);
}
</code>```

#content {
  width: 50%;
}

.line {
  border-top: 5px solid black;
}

.list-content {
  display: inline-block;
  width: 25%;
  height: 200px;
  background-color: black;
  margin-top: 10px;
}

.detail-content {
  display: none;
}

.list-content:hover .detail-content {
  display: table;
  width: 100%;
  height: 75%;
  background-color: rgba(255, 255, 255, 0.6);
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div id="content">
  <h1 class="head-content">Biscuits</h1>
  <div class="line"></div>

    <div class="list-content">
      <div class="detail-content">
        <h3>Biscuits 1</h3>
        <p>Price: IDR 12000</p>
      </div>
    </div>

    <div class="list-content">
      <div class="detail-content">

      </div>
    </div>

    <div class="list-content">
      <div class="detail-content">

      </div>
    </div>

</div></code>```

Title: Div tag get down while hover it

Body:
While I hover Div tag, Another Div tag will appear in front of the prev Div. When i didn't put any words, it works. but when i put h3 tag, the div goes down.

here is the HTML

Biscuits

Biscuits 1

Price: IDR 12000

here is CSS

#content{
        width:50%;
    }
    .line{
        border-top: 5px solid black;
    }
    .list-content{
        display:inline-block;
        width:25%;
        height:200px;
        background-color: black;
        margin-top: 10px;
    }
    .detail-content{
        display: none;
    }
    .list-content:hover .detail-content{
        display: block;
        width:100%;
        height:75%;
        background-color: rgba(255,255,255,0.6);
    }

thank you before

Body:
Update below css part

.list-content:hover .detail-content {
  display: table;
  width: 100%;
  height: 75%;
  background-color: rgba(255, 255, 255, 0.6);
}

#content {
  width: 50%;
}

.line {
  border-top: 5px solid black;
}

.list-content {
  display: inline-block;
  width: 25%;
  height: 200px;
  background-color: black;
  margin-top: 10px;
}

.detail-content {
  display: none;
}

.list-content:hover .detail-content {
  display: table;
  width: 100%;
  height: 75%;
  background-color: rgba(255, 255, 255, 0.6);
}

<div id="content">
  <h1 class="head-content">Biscuits</h1>
  <div class="line"></div>
  <a href="#">
    <div class="list-content">
      <div class="detail-content">
        <h3>Biscuits 1</h3>
        <p>Price: IDR 12000</p>
      </div>
    </div>
  </a>
  <a href="#">
    <div class="list-content">
      <div class="detail-content">

      </div>
    </div>
  </a>
  <a href="#">
    <div class="list-content">
      <div class="detail-content">

      </div>
    </div>
  </a>
</div>


问:
Proper toolbar styling
I would like to avoid applying a style to the toolbars in all layouts, so I have a style I created for it:

```<code><style name="DarkToolbar" >
        <item name="android:textColorPrimary">@color/white</item>
        <item name="android:textColorSecondary">@color/white</item>
        <item name="android:background">@color/blue</item>
        <item name="android:elevation">4dp</item>
</style>
</code>```

And I added it to my theme as follows:

```<code><style name="Theme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/blue</item>
        <item name="colorPrimaryDark">@color/blue</item>
        <item name="colorAccent">@color/blue</item>
        <item name="android:toolbarStyle">@style/DarkToolbar</item>
</style>
</code>```

This is the resulting toolbar:

As you can see, the title and subtitle have the wrong formatting. If I remove the style from the theme and apply it directly to the toolbar in the layout, I get the following result instead:

Both images use the same style. One is applied through the app theme with

```<code><item name="android:toolbarStyle">@style/DarkToolbar</item>
</code>```

and the second one is applied directly to the toolbar with

```<code>style="@style/DarkToolbar"
</code>```

Does anyone know the reason for the difference?
Also, does anyone know why the

```<code><item name="android:textColorPrimary">@color/white</item>
<item name="android:textColorSecondary">@color/white</item>
</code>```

Are not being applied?

Thanks

答:
You are setting parent as no action bar in your theme, as this will give you the run time exception and null point exception as there is no action bar or tool bar to set the title/sub-title. Try adding parent in your theme with toolbar or action bar likes this.

<?xml version="1.0" encoding="utf-8"?>
<resources>

</resources>```

Title: Proper toolbar styling

Body:
I would like to avoid applying a style to the toolbars in all layouts, so I have a style I created for it:

And I added it to my theme as follows:

This is the resulting toolbar:

As you can see, the title and subtitle have the wrong formatting. If I remove the style from the theme and apply it directly to the toolbar in the layout, I get the following result instead:

Both images use the same style. One is applied through the app theme with

<item name="android:toolbarStyle">@style/DarkToolbar</item>

and the second one is applied directly to the toolbar with

style="@style/DarkToolbar"

Does anyone know the reason for the difference?
Also, does anyone know why the

<item name="android:textColorPrimary">@color/white</item>
<item name="android:textColorSecondary">@color/white</item>

Are not being applied?

Thanks

Body:
You are setting parent as no action bar in your theme, as this will give you the run time exception and null point exception as there is no action bar or tool bar to set the title/sub-title. Try adding parent in your theme with toolbar or action bar likes this.

<?xml version="1.0" encoding="utf-8"?>
<resources>

    <style name="DarkToolbar">
        <item name="android:textColorPrimary">@color/white</item>
        <item name="android:textColorSecondary">@color/white</item>
        <item name="android:background">@color/blue</item>
        <item name="android:elevation">4dp</item>
    </style>

    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <item name="colorPrimary">@color/blue</item>
        <item name="colorPrimaryDark">@color/blue</item>
        <item name="colorAccent">@color/blue</item>
        <item name="android:toolbarStyle">@style/DarkToolbar</item>
    </style>
</resources>


问:
Mercurial build on push
I'd like for a build to be done (on the server) each time a push is made to our central Mercurial repository.
Builds are usually kicked off on our build server by running a Visual Build file either manually or via a scheduled task.

What are the ways of achieving this?

Simple, low impact solutions are preferred.

答:
As Pablo suggested, you can do this with a hook, but you'll need an incoming hook on the server side. This hook runs "after a changeset has been pulled, pushed, or unbundled into the local repository" (hgrc manpage).

Edit the .hg/hgrc file of the repository located on the server and define your build hook as follows:

```<code>[hooks]
incoming = /path/to/executable-build-script
</code>```

Of course, the build script called here just needs to be a trigger for whatever build process you actually use.

Note that an incoming hook runs for every single changeset in a push. If you don't want this, use a changegroup hook -- it runs only once for each push, no matter how many changesets it carries.

Title: Mercurial build on push

Body:
As Pablo suggested, you can do this with a hook, but you'll need an incoming hook on the server side. This hook runs "after a changeset has been pulled, pushed, or unbundled into the local repository" (hgrc manpage).

Edit the .hg/hgrc file of the repository located on the server and define your build hook as follows:

[hooks]
incoming = /path/to/executable-build-script

Of course, the build script called here just needs to be a trigger for whatever build process you actually use.

Note that an incoming hook runs for every single changeset in a push. If you don't want this, use a changegroup hook -- it runs only once for each push, no matter how many changesets it carries.


问:
Could not load Spatialite extension in qSqlite ( QT 5.9)
I am trying to load Spatialite as extension in qSqlite ( Qt 5.9), I have done that before with Qt4.8, but I failed with the QT5.9.
I changed the sqlite.pri by removing "SQLITE_OMIT_LOAD_EXTENSION", and I did some change on the sqlite.c by removing the "#define SQLITE_OMIT_LOAD_EXTENSION 1", and adding "#define SQLITE_ENABLE_LOAD_EXTENSION 1".
I also add the following lines to openDatabase(....)

```<code>#if defined(SQLITE_ENABLE_LOAD_EXTENSION)
| SQLITE_LoadExtension|SQLITE_LoadExtFunc
#endif
</code>```

Now the "requet.setQuery("SELECT load_extension('spatialite')", dbProject);" function is recognized, but I got this message:
error "The specified procedure could not be found.\r\nUnable to fetch row"
If I take a look on my debug output in MSVC14, I can see that the spatialite.dll and all its dependencies have been loaded.

Notice: I tested this with my Spatialite and also the mod_spatialite that I download form their website.

Any ideas about this problem?
Thanks in advance.

答:
Based on the example here I have enabled spatialite in sqlite, the function enables that module. To do this you must link the sqlite3 library.

The modifications made are:

Change "SELECT load_extension('libspatialite.so')" to "SELECT load_extension('mod_spatialite')"

Change "SELECT InitSpatialMetadata()" to "SELECT InitSpatialMetadata(1)"

```<code>#include <sqlite3.h>
#include <QSqlDatabase>
#include <QSqlDriver>
#include <QSqlError>

int enable_spatialite(QSqlDatabase db){
    QVariant v = db.driver()->handle();
    if (v.isValid() && qstrcmp(v.typeName(), "sqlite3*")==0)
    {
        sqlite3_initialize();
        sqlite3 *db_handle = *static_cast<sqlite3 **>(v.data());

        if (db_handle != 0) {
            sqlite3_enable_load_extension(db_handle, 1);

            QSqlQuery query;

            query.exec("SELECT load_extension('mod_spatialite')");
            if (query.lastError() .isValid())
            {
                qDebug() << "Error: cannot load the Spatialite extension (" << query.lastError().text()<<")";
                return 0;
            }

            qDebug()<<"**** SpatiaLite loaded as an extension ***";

            query.exec("SELECT InitSpatialMetadata(1)");
            if (query.lastError() .isValid())
            {
                qDebug() << "Error: cannot load the Spatialite extension (" << query.lastError().text()<<")";
                return 0;
            }
            qDebug()<<"**** InitSpatialMetadata successful ***";

            return 1;
        }
    }
    return 0;
}
</code>```

Example:

```<code>int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QSqlDatabase db =  QSqlDatabase::addDatabase("QSQLITE");

    db.setDatabaseName("memory.db");
    if (!db.open()) {
        qDebug()<<"not open";
    }

    qDebug()<<enable_spatialite(db);

    QSqlQuery query;

    qDebug()<<query.exec("CREATE TABLE test_geom (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, measured_value DOUBLE NOT NULL);");
    qDebug()<<query.exec("SELECT AddGeometryColumn('test_geom', 'the_geom', 4326, 'POINT', 'XY');");

    for(int i=0; i< 10; i++){
        QString q = QString("INSERT INTO test_geom(id, name, measured_value, the_geom) VALUES (%1,'point %2', %3, GeomFromText('POINT(1.01 2.02)', 4326))")
                .arg("NULL").arg(i).arg(i);
        query.prepare(q);
        qDebug()<< i<<query.exec();
    }

    qDebug()<<query.exec("SELECT id, name, measured_value,  AsText(the_geom), ST_GeometryType(the_geom), ST_Srid(the_geom) FROM test_geom");

    while (query.next()) {
        QString str;
        for(int i=0; i < query.record().count(); i++)
            str += query.value(i).toString() + " ";
        qDebug()<<str;
    }
    return a.exec();
}
</code>```

Output:

```<code>**** SpatiaLite loaded as an extension ***
**** InitSpatialMetadata successful ***
1
true
true
0 true
1 true
2 true
3 true
4 true
5 true
6 true
7 true
8 true
9 true
true
"1 point 0 0 POINT(1.01 2.02) POINT 4326 "
"2 point 1 1 POINT(1.01 2.02) POINT 4326 "
"3 point 2 2 POINT(1.01 2.02) POINT 4326 "
"4 point 3 3 POINT(1.01 2.02) POINT 4326 "
"5 point 4 4 POINT(1.01 2.02) POINT 4326 "
"6 point 5 5 POINT(1.01 2.02) POINT 4326 "
"7 point 6 6 POINT(1.01 2.02) POINT 4326 "
"8 point 7 7 POINT(1.01 2.02) POINT 4326 "
"9 point 8 8 POINT(1.01 2.02) POINT 4326 "
"10 point 9 9 POINT(1.01 2.02) POINT 4326 "
</code>```

The complete example can be found here.

This code has been tested on linux Arch Linux 4.11.3-1-ARCH, Qt 5.8

Body:
I am trying to load Spatialite as extension in qSqlite ( Qt 5.9), I have done that before with Qt4.8, but I failed with the QT5.9.
I changed the sqlite.pri by removing "SQLITE_OMIT_LOAD_EXTENSION", and I did some change on the sqlite.c by removing the "#define SQLITE_OMIT_LOAD_EXTENSION 1", and adding "#define SQLITE_ENABLE_LOAD_EXTENSION 1".
I also add the following lines to openDatabase(....)

#if defined(SQLITE_ENABLE_LOAD_EXTENSION)
| SQLITE_LoadExtension|SQLITE_LoadExtFunc
#endif

Now the "requet.setQuery("SELECT load_extension('spatialite')", dbProject);" function is recognized, but I got this message:
error "The specified procedure could not be found.\r\nUnable to fetch row"
If I take a look on my debug output in MSVC14, I can see that the spatialite.dll and all its dependencies have been loaded.

Notice: I tested this with my Spatialite and also the mod_spatialite that I download form their website.

Any ideas about this problem?
Thanks in advance.

Body:
Based on the example here I have enabled spatialite in sqlite, the function enables that module. To do this you must link the sqlite3 library.

The modifications made are:

Change "SELECT load_extension('libspatialite.so')" to "SELECT load_extension('mod_spatialite')"

Change "SELECT InitSpatialMetadata()" to "SELECT InitSpatialMetadata(1)"

#include <sqlite3.h>
#include <QSqlDatabase>
#include <QSqlDriver>
#include <QSqlError>

int enable_spatialite(QSqlDatabase db){
    QVariant v = db.driver()->handle();
    if (v.isValid() && qstrcmp(v.typeName(), "sqlite3*")==0)
    {
        sqlite3_initialize();
        sqlite3 *db_handle = *static_cast<sqlite3 **>(v.data());

        if (db_handle != 0) {
            sqlite3_enable_load_extension(db_handle, 1);

            QSqlQuery query;

            query.exec("SELECT load_extension('mod_spatialite')");
            if (query.lastError() .isValid())
            {
                qDebug() << "Error: cannot load the Spatialite extension (" << query.lastError().text()<<")";
                return 0;
            }

            qDebug()<<"**** SpatiaLite loaded as an extension ***";

            query.exec("SELECT InitSpatialMetadata(1)");
            if (query.lastError() .isValid())
            {
                qDebug() << "Error: cannot load the Spatialite extension (" << query.lastError().text()<<")";
                return 0;
            }
            qDebug()<<"**** InitSpatialMetadata successful ***";

            return 1;
        }
    }
    return 0;
}

Example:

int main(int argc, char *argv[])
{
    QCoreApplication a(argc, argv);

    QSqlDatabase db =  QSqlDatabase::addDatabase("QSQLITE");

    db.setDatabaseName("memory.db");
    if (!db.open()) {
        qDebug()<<"not open";
    }

    qDebug()<<enable_spatialite(db);

    QSqlQuery query;

    qDebug()<<query.exec("CREATE TABLE test_geom (id INTEGER NOT NULL PRIMARY KEY AUTOINCREMENT, name TEXT NOT NULL, measured_value DOUBLE NOT NULL);");
    qDebug()<<query.exec("SELECT AddGeometryColumn('test_geom', 'the_geom', 4326, 'POINT', 'XY');");

    for(int i=0; i< 10; i++){
        QString q = QString("INSERT INTO test_geom(id, name, measured_value, the_geom) VALUES (%1,'point %2', %3, GeomFromText('POINT(1.01 2.02)', 4326))")
                .arg("NULL").arg(i).arg(i);
        query.prepare(q);
        qDebug()<< i<<query.exec();
    }

    qDebug()<<query.exec("SELECT id, name, measured_value,  AsText(the_geom), ST_GeometryType(the_geom), ST_Srid(the_geom) FROM test_geom");

    while (query.next()) {
        QString str;
        for(int i=0; i < query.record().count(); i++)
            str += query.value(i).toString() + " ";
        qDebug()<<str;
    }
    return a.exec();
}

Output:

**** SpatiaLite loaded as an extension ***
**** InitSpatialMetadata successful ***
1
true
true
0 true
1 true
2 true
3 true
4 true
5 true
6 true
7 true
8 true
9 true
true
"1 point 0 0 POINT(1.01 2.02) POINT 4326 "
"2 point 1 1 POINT(1.01 2.02) POINT 4326 "
"3 point 2 2 POINT(1.01 2.02) POINT 4326 "
"4 point 3 3 POINT(1.01 2.02) POINT 4326 "
"5 point 4 4 POINT(1.01 2.02) POINT 4326 "
"6 point 5 5 POINT(1.01 2.02) POINT 4326 "
"7 point 6 6 POINT(1.01 2.02) POINT 4326 "
"8 point 7 7 POINT(1.01 2.02) POINT 4326 "
"9 point 8 8 POINT(1.01 2.02) POINT 4326 "
"10 point 9 9 POINT(1.01 2.02) POINT 4326 "

The complete example can be found here.

This code has been tested on linux Arch Linux 4.11.3-1-ARCH, Qt 5.8


问:
how to access shopify Products via API without api-key and password?
i want to develop a chrome extension to see stats for any store which develop in shopify, can i access any store products without API-Key and Password in shopify?</p>

答:
No, you cant access products json without using api-key or permanent token of the store.
But still you want to access the product details you atleast needs the handler of the product.

Lets say your store is "abc.myshopify.com" and handler of your product is "xyz", then you can product json of xyz by HTTP GET call in following url

https://www.abc.myshopify.com/products/xyz.json

in general

```<code>https://www.[storename]/products/[product-handle].json
</code>```

Body:
No, you cant access products json without using api-key or permanent token of the store.
But still you want to access the product details you atleast needs the handler of the product.

Lets say your store is "abc.myshopify.com" and handler of your product is "xyz", then you can product json of xyz by HTTP GET call in following url

https://www.abc.myshopify.com/products/xyz.json

in general

https://www.[storename]/products/[product-handle].json


问:
How to wrap text within reactive splom lattice plot?
Within my shiny app, I am having my users select n number of attributes to plot within my splom() call, which essentially follows these steps:

User chooses a number.

User chooses variables.

Code subsets my data set based on users choices.

Splom is called in a very simple call, similar to: lplot <- splom(data_subset).

However, since the panels within splom() are being labeled based on the attribute name (which is reactive, so I can't label ahead of time) and the names are very long you can't read them.

Does anyone know if there is a way to wrap text within the splom panel outputs? The wrapping would be done on the attribute reactive value, so it wouldn't be done on a string.

This is what my output looks like:

答:
After subsetting in step 3, you can manipulate the names of the data subset to wrap appropriately.

```<code>## Subset the data in whatever way shiny does (here's a reproducible example)
irisSub <- subset(iris, select = grepl("Width", names(iris)))
</code>```

Then

Replace "word" separators with spaces. In your example, you probably just need "_"

```<code>names(irisSub) <- gsub("\\.|_", " ", names(irisSub))
</code>```

Wrap these strings at a fairly narrow width. You might have to experiment with other widths here.

```<code>wrapList <- strwrap(names(irisSub), width = 10, simplify = FALSE)
</code>```

Paste these strings back together with a linebreak (\n) in between and assign them to names of data subset

```<code>names(irisSub) <- vapply(wrapList, paste, collapse = "\n", FUN.VALUE = character(1))
</code>```

splom should respect the line breaks

```<code>splom(irisSub)
</code>```

Body:
After subsetting in step 3, you can manipulate the names of the data subset to wrap appropriately.

## Subset the data in whatever way shiny does (here's a reproducible example)
irisSub <- subset(iris, select = grepl("Width", names(iris)))

Then

Replace "word" separators with spaces. In your example, you probably just need "_"

names(irisSub) <- gsub("\\.|_", " ", names(irisSub))

Wrap these strings at a fairly narrow width. You might have to experiment with other widths here.

wrapList <- strwrap(names(irisSub), width = 10, simplify = FALSE)

Paste these strings back together with a linebreak (\n) in between and assign them to names of data subset

names(irisSub) <- vapply(wrapList, paste, collapse = "\n", FUN.VALUE = character(1))

splom should respect the line breaks

splom(irisSub)


问:
How to wait for email intent to finish and get result?
In my Android app, I am able to programmatically open up the default email editor with To, Subject, and Message using the following:

```<code>Intent emailIntent=new Intent(Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_EMAIL, toemail);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(Intent.EXTRA_TEXT, body);
emailIntent.setType("text/plain");
emailIntent.setClassName("com.android.email", "com.android.email.activity.MessageCompose");
startActivity(emailIntent);
</code>```

This works great, but I need to wait in my app until the user finishes with the email screen and also know whether the email was sent or discarded.

Anyone know how to do this?

答:
Normally, one could use startActivityForResult() which starts the second activity as a sub-activity. However, in the case of the email activity this doesn't appear to work, likely because of the internal implementation. Try searching before posting questions:

how can we use startActivityforResult() for Email intent?

The actual sending of an email is asynchronous by design, so the activity will likely return before the email is actually sent. I haven't tested this case specifically, but from the above link it seems that the activity returns once the user hits the send button. If this suffices for your use case then super, if you need to know if the email was actually sent you might be SOL.

Body:
In my Android app, I am able to programmatically open up the default email editor with To, Subject, and Message using the following:

Intent emailIntent=new Intent(Intent.ACTION_SEND);
emailIntent.putExtra(Intent.EXTRA_EMAIL, toemail);
emailIntent.putExtra(Intent.EXTRA_SUBJECT, subject);
emailIntent.putExtra(Intent.EXTRA_TEXT, body);
emailIntent.setType("text/plain");
emailIntent.setClassName("com.android.email", "com.android.email.activity.MessageCompose");
startActivity(emailIntent);

This works great, but I need to wait in my app until the user finishes with the email screen and also know whether the email was sent or discarded.

Anyone know how to do this?


问:
Error when testing a component which uses templateUrl
I can see in the test output that console.log(dummyComponentInstance); is being called and evaluating to undefined.

Also, console.log('beforeEach done'); is never logged.

dummy.component.spec.ts

```<code>import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { DummyComponent } from './dummy.component';

describe('DummyComponent', () => {

  let dummyComponentInstance: DummyComponent;
  let fixture: ComponentFixture<DummyComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [DummyComponent]
    })
      .compileComponents()
      .then(() => {
        fixture = TestBed.createComponent(DummyComponent);
        dummyComponentInstance = fixture.componentInstance;
        console.log('beforeEach done');
      });
  }));

  it('should work', () => {
    console.log(dummyComponentInstance);
    expect(dummyComponentInstance instanceof DummyComponent).toBe(true, 'should create DummyComponent');
  });
});
</code>```

dummy.component.ts

```<code>import { Component } from '@angular/core';

@Component({
  selector: 'dummy',
  templateUrl: './dummy.component.html'
})
export class DummyComponent {
  public initialized = false;
}
</code>```

Error after running the test:

```<code>07 06 2017 13:27:09.187:INFO [launcher]: Starting browser PhantomJS
07 06 2017 13:27:09.437:INFO [PhantomJS 2.1.1 (Linux 0.0.0)]: Connected on socket 4Vq49vX24cDAIZfjAAAA with id 34827962
LOG: undefined
PhantomJS 2.1.1 (Linux 0.0.0) DummyComponent should work FAILED
    invokeTask@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:605:36
    onInvokeTask@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:154:49
    invokeTask@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:604:48
    runTask@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:372:57
    drainMicroTaskQueue@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:765:42
    run@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:17951:29
    /tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:17964:31
    flush@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:17813:11
    resolvePromise@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:951:78
    resolvePromise@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:921:31
    /tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:998:31
    Expected false to be true, 'should create DummyComponent'.
    src/app/dummy.component.spec.js:21:98
</code>```

答:
Since my templateUrl file contains an angular form that needed to be setup in my TestBed object ..

```<code>beforeEach(async(() => {
  TestBed.configureTestingModule({
    declarations: [PageFormComponent],
    imports: [FormsModule]
  }).compileComponents()
    .then(() => {
      fixture = TestBed.createComponent(PageFormComponent);
      pageFormComponentInstance = fixture.componentInstance;
    });
}));
</code>```

Body:
I can see in the test output that console.log(dummyComponentInstance); is being called and evaluating to undefined.

Also, console.log('beforeEach done'); is never logged.

dummy.component.spec.ts

import { async, ComponentFixture, TestBed } from '@angular/core/testing';

import { DummyComponent } from './dummy.component';

describe('DummyComponent', () => {

  let dummyComponentInstance: DummyComponent;
  let fixture: ComponentFixture<DummyComponent>;

  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [DummyComponent]
    })
      .compileComponents()
      .then(() => {
        fixture = TestBed.createComponent(DummyComponent);
        dummyComponentInstance = fixture.componentInstance;
        console.log('beforeEach done');
      });
  }));

  it('should work', () => {
    console.log(dummyComponentInstance);
    expect(dummyComponentInstance instanceof DummyComponent).toBe(true, 'should create DummyComponent');
  });
});

dummy.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'dummy',
  templateUrl: './dummy.component.html'
})
export class DummyComponent {
  public initialized = false;
}

Error after running the test:

07 06 2017 13:27:09.187:INFO [launcher]: Starting browser PhantomJS
07 06 2017 13:27:09.437:INFO [PhantomJS 2.1.1 (Linux 0.0.0)]: Connected on socket 4Vq49vX24cDAIZfjAAAA with id 34827962
LOG: undefined
PhantomJS 2.1.1 (Linux 0.0.0) DummyComponent should work FAILED
    invokeTask@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:605:36
    onInvokeTask@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:154:49
    invokeTask@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:604:48
    runTask@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:372:57
    drainMicroTaskQueue@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:765:42
    run@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:17951:29
    /tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:17964:31
    flush@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:17813:11
    resolvePromise@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:951:78
    resolvePromise@/tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:921:31
    /tmp/karma-typescript-bundle-27168S216WqzJyZ6g.js:998:31
    Expected false to be true, 'should create DummyComponent'.
    src/app/dummy.component.spec.js:21:98

Body:
Since my templateUrl file contains an angular form that needed to be setup in my TestBed object ..

beforeEach(async(() => {
  TestBed.configureTestingModule({
    declarations: [PageFormComponent],
    imports: [FormsModule]
  }).compileComponents()
    .then(() => {
      fixture = TestBed.createComponent(PageFormComponent);
      pageFormComponentInstance = fixture.componentInstance;
    });
}));


问:
Issue while applying PATCH_SUPEE-9767_CE_1.9.3.0_v1-2017-05-25-09-09-56.sh in magento 1.9.2.4
I am facing issue while Applying PATCH_SUPEE-9767_CE_1.9.3.0_v1-2017-05-25-09-09-56.sh in magento 1.9.2.4.
Found below message after apply the patch. I am not aware about the steps to resolve the issue ... Please help me to resolve the issue.

I have seen below link but this is not working for me.

Patching Magento 1.9.2.0 with Security patch 9767

```<code>Checking if patch can be applied/reverted successfully...
ERROR: Patch can't be applied/reverted successfully.

patching file app/code/core/Mage/Admin/Model/Session.php
patching file app/code/core/Mage/Adminhtml/Block/Checkout/Formkey.php
patching file app/code/core/Mage/Adminhtml/Block/Notification/Symlink.php
patching file app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Filter/Date.php
patching file app/code/core/Mage/Adminhtml/Model/Config/Data.php
patching file app/code/core/Mage/Adminhtml/controllers/Catalog/Product/GalleryController.php
patching file app/code/core/Mage/Checkout/controllers/MultishippingController.php
patching file app/code/core/Mage/Checkout/controllers/OnepageController.php
Hunk #1 succeeded at 350 (offset 1 line).
Hunk #2 succeeded at 370 (offset 1 line).
Hunk #3 succeeded at 417 (offset 1 line).
Hunk #4 succeeded at 446 (offset 1 line).
Hunk #5 succeeded at 485 (offset 1 line).
patching file app/code/core/Mage/Checkout/etc/system.xml
patching file app/code/core/Mage/Cms/Model/Wysiwyg/Images/Storage.php
Hunk #1 succeeded at 282 (offset -1 lines).
patching file app/code/core/Mage/Core/Controller/Front/Action.php
patching file app/code/core/Mage/Core/Controller/Request/Http.php
patching file app/code/core/Mage/Core/Model/File/Validator/Image.php
patching file app/code/core/Mage/Core/etc/system.xml
patching file app/code/core/Mage/Customer/Model/Session.php
patching file app/code/core/Mage/Dataflow/Model/Convert/Adapter/Zend/Cache.php
patching file app/code/core/Mage/Dataflow/Model/Convert/Container/Abstract.php
patching file app/code/core/Mage/Dataflow/Model/Convert/Parser/Csv.php
patching file app/code/core/Mage/Dataflow/Model/Convert/Parser/Xml/Excel.php
patching file app/code/core/Mage/ImportExport/Model/Import/Uploader.php
patching file app/code/core/Mage/Sales/Model/Quote/Item.php
patching file app/code/core/Mage/Widget/Model/Widget/Instance.php
patching file app/code/core/Mage/XmlConnect/Helper/Image.php
patching file app/code/core/Mage/XmlConnect/controllers/Adminhtml/MobileController.php
patching file app/design/adminhtml/default/default/layout/main.xml
patching file app/design/adminhtml/default/default/template/notification/formkey.phtml
patching file app/design/adminhtml/default/default/template/notification/symlink.phtml
patching file app/design/adminhtml/default/default/template/page/head.phtml
patching file app/design/frontend/base/default/template/checkout/cart/shipping.phtml
Hunk #1 succeeded at 109 with fuzz 2.
patching file app/design/frontend/base/default/template/checkout/multishipping/billing.phtml
Hunk #1 succeeded at 91 with fuzz 2.
patching file app/design/frontend/base/default/template/checkout/multishipping/shipping.phtml
Hunk #1 succeeded at 126 with fuzz 2.
patching file app/design/frontend/base/default/template/checkout/onepage/billing.phtml
Hunk #1 succeeded at 201 with fuzz 1.
patching file app/design/frontend/base/default/template/checkout/onepage/payment.phtml
Hunk #1 succeeded at 35 (offset -1 lines).
patching file app/design/frontend/base/default/template/checkout/onepage/shipping.phtml
Hunk #1 succeeded at 141 with fuzz 1.
patching file app/design/frontend/base/default/template/checkout/onepage/shipping_method.phtml
Hunk #1 succeeded at 43 with fuzz 1.
patching file app/design/frontend/base/default/template/persistent/checkout/onepage/billing.phtml
Hunk #1 succeeded at 201 with fuzz 1 (offset 2 lines).
can't find file to patch at input line 900
Perhaps you used the wrong -p or --strip option?
The text leading up to this was:
--------------------------
|diff --git app/design/frontend/rwd/default/layout/page.xml app/design/frontend/rwd/default/layout/page.xml
|index 22a2fe6..b600f74 100644
|--- app/design/frontend/rwd/default/layout/page.xml
|+++ app/design/frontend/rwd/default/layout/page.xml
--------------------------
File to patch:
Skip this patch? [y]
Skipping patch.
1 out of 1 hunk ignored
patching file app/design/frontend/rwd/default/template/checkout/cart/shipping.phtml
can't find file to patch at input line 925
Perhaps you used the wrong -p or --strip option?
The text leading up to this was:
--------------------------
|diff --git app/design/frontend/rwd/default/template/checkout/multishipping/addresses.phtml app/design/frontend/rwd/default/template/checkout/multishipping/addresses.phtml
|index bf6dfcc..6cab97a 100644
|--- app/design/frontend/rwd/default/template/checkout/multishipping/addresses.phtml
|+++ app/design/frontend/rwd/default/template/checkout/multishipping/addresses.phtml
--------------------------
File to patch:
Skip this patch? [y]
Skipping patch.
1 out of 1 hunk ignored
patching file app/design/frontend/rwd/default/template/checkout/multishipping/billing.phtml
Hunk #1 succeeded at 93 with fuzz 2.
patching file app/design/frontend/rwd/default/template/checkout/onepage/payment.phtml
Hunk #1 succeeded at 36 (offset -1 lines).
patching file app/design/frontend/rwd/default/template/checkout/onepage/shipping.phtml
Hunk #1 succeeded at 142 with fuzz 1.
patching file app/design/frontend/rwd/default/template/persistent/checkout/onepage/billing.phtml
Hunk #1 succeeded at 201 with fuzz 1.
patching file app/etc/config.xml
Hunk #1 succeeded at 140 (offset -1 lines).
patching file app/locale/en_US/Mage_Adminhtml.csv
Hunk #1 succeeded at 1213 (offset -72 lines).
patching file app/locale/en_US/Mage_Core.csv
Hunk #1 succeeded at 391 (offset -16 lines).
patching file app/locale/en_US/Mage_Dataflow.csv
patching file app/locale/en_US/Mage_XmlConnect.csv
patching file downloader/Maged/Connect.php
patching file downloader/Maged/Controller.php
Hunk #1 succeeded at 417 (offset -4 lines).
Hunk #2 succeeded at 964 (offset -15 lines).
patching file downloader/Maged/Model/Session.php
Hunk #1 succeeded at 82 with fuzz 2.
Hunk #2 succeeded at 268 (offset -5 lines).
patching file js/lib/jquery/jquery-1.12.0.js
patching file js/lib/jquery/jquery-1.12.0.min.js
patching file js/lib/jquery/jquery-1.12.0.min.map
patching file js/varien/payment.js
patching file skin/frontend/base/default/js/opcheckout.js
Hunk #1 succeeded at 723 (offset 39 lines).
</code>```

So the error is basically at file location :

```<code>app/design/frontend/rwd/default/layout/page.xml
app/design/frontend/rwd/default/template/checkout/cart/shipping.phtml
app/design/frontend/rwd/default/template/checkout/multishipping/addresses.phtml
</code>```

Please suggest I should go for manual entry of the patching or not?

答:
The hunk error normally came because it will not match the file lines. In this case you can do 2 things.

Replace those three files with new same version Magento setup and then try to install the patch using SSH.

Install the patch manually. Because its RWD files so it will not affect your site if you are using your own custom theme.

In this patch in front end only form key is added in checkout and cart files so you can do it manually.

Thanks.

Body:
I am facing issue while Applying PATCH_SUPEE-9767_CE_1.9.3.0_v1-2017-05-25-09-09-56.sh in magento 1.9.2.4.
Found below message after apply the patch. I am not aware about the steps to resolve the issue ... Please help me to resolve the issue.

I have seen below link but this is not working for me.

Patching Magento 1.9.2.0 with Security patch 9767

Checking if patch can be applied/reverted successfully...
ERROR: Patch can't be applied/reverted successfully.

patching file app/code/core/Mage/Admin/Model/Session.php
patching file app/code/core/Mage/Adminhtml/Block/Checkout/Formkey.php
patching file app/code/core/Mage/Adminhtml/Block/Notification/Symlink.php
patching file app/code/core/Mage/Adminhtml/Block/Widget/Grid/Column/Filter/Date.php
patching file app/code/core/Mage/Adminhtml/Model/Config/Data.php
patching file app/code/core/Mage/Adminhtml/controllers/Catalog/Product/GalleryController.php
patching file app/code/core/Mage/Checkout/controllers/MultishippingController.php
patching file app/code/core/Mage/Checkout/controllers/OnepageController.php
Hunk #1 succeeded at 350 (offset 1 line).
Hunk #2 succeeded at 370 (offset 1 line).
Hunk #3 succeeded at 417 (offset 1 line).
Hunk #4 succeeded at 446 (offset 1 line).
Hunk #5 succeeded at 485 (offset 1 line).
patching file app/code/core/Mage/Checkout/etc/system.xml
patching file app/code/core/Mage/Cms/Model/Wysiwyg/Images/Storage.php
Hunk #1 succeeded at 282 (offset -1 lines).
patching file app/code/core/Mage/Core/Controller/Front/Action.php
patching file app/code/core/Mage/Core/Controller/Request/Http.php
patching file app/code/core/Mage/Core/Model/File/Validator/Image.php
patching file app/code/core/Mage/Core/etc/system.xml
patching file app/code/core/Mage/Customer/Model/Session.php
patching file app/code/core/Mage/Dataflow/Model/Convert/Adapter/Zend/Cache.php
patching file app/code/core/Mage/Dataflow/Model/Convert/Container/Abstract.php
patching file app/code/core/Mage/Dataflow/Model/Convert/Parser/Csv.php
patching file app/code/core/Mage/Dataflow/Model/Convert/Parser/Xml/Excel.php
patching file app/code/core/Mage/ImportExport/Model/Import/Uploader.php
patching file app/code/core/Mage/Sales/Model/Quote/Item.php
patching file app/code/core/Mage/Widget/Model/Widget/Instance.php
patching file app/code/core/Mage/XmlConnect/Helper/Image.php
patching file app/code/core/Mage/XmlConnect/controllers/Adminhtml/MobileController.php
patching file app/design/adminhtml/default/default/layout/main.xml
patching file app/design/adminhtml/default/default/template/notification/formkey.phtml
patching file app/design/adminhtml/default/default/template/notification/symlink.phtml
patching file app/design/adminhtml/default/default/template/page/head.phtml
patching file app/design/frontend/base/default/template/checkout/cart/shipping.phtml
Hunk #1 succeeded at 109 with fuzz 2.
patching file app/design/frontend/base/default/template/checkout/multishipping/billing.phtml
Hunk #1 succeeded at 91 with fuzz 2.
patching file app/design/frontend/base/default/template/checkout/multishipping/shipping.phtml
Hunk #1 succeeded at 126 with fuzz 2.
patching file app/design/frontend/base/default/template/checkout/onepage/billing.phtml
Hunk #1 succeeded at 201 with fuzz 1.
patching file app/design/frontend/base/default/template/checkout/onepage/payment.phtml
Hunk #1 succeeded at 35 (offset -1 lines).
patching file app/design/frontend/base/default/template/checkout/onepage/shipping.phtml
Hunk #1 succeeded at 141 with fuzz 1.
patching file app/design/frontend/base/default/template/checkout/onepage/shipping_method.phtml
Hunk #1 succeeded at 43 with fuzz 1.
patching file app/design/frontend/base/default/template/persistent/checkout/onepage/billing.phtml
Hunk #1 succeeded at 201 with fuzz 1 (offset 2 lines).
can't find file to patch at input line 900
Perhaps you used the wrong -p or --strip option?
The text leading up to this was:
--------------------------
|diff --git app/design/frontend/rwd/default/layout/page.xml app/design/frontend/rwd/default/layout/page.xml
|index 22a2fe6..b600f74 100644
|--- app/design/frontend/rwd/default/layout/page.xml
|+++ app/design/frontend/rwd/default/layout/page.xml
--------------------------
File to patch:
Skip this patch? [y]
Skipping patch.
1 out of 1 hunk ignored
patching file app/design/frontend/rwd/default/template/checkout/cart/shipping.phtml
can't find file to patch at input line 925
Perhaps you used the wrong -p or --strip option?
The text leading up to this was:
--------------------------
|diff --git app/design/frontend/rwd/default/template/checkout/multishipping/addresses.phtml app/design/frontend/rwd/default/template/checkout/multishipping/addresses.phtml
|index bf6dfcc..6cab97a 100644
|--- app/design/frontend/rwd/default/template/checkout/multishipping/addresses.phtml
|+++ app/design/frontend/rwd/default/template/checkout/multishipping/addresses.phtml
--------------------------
File to patch:
Skip this patch? [y]
Skipping patch.
1 out of 1 hunk ignored
patching file app/design/frontend/rwd/default/template/checkout/multishipping/billing.phtml
Hunk #1 succeeded at 93 with fuzz 2.
patching file app/design/frontend/rwd/default/template/checkout/onepage/payment.phtml
Hunk #1 succeeded at 36 (offset -1 lines).
patching file app/design/frontend/rwd/default/template/checkout/onepage/shipping.phtml
Hunk #1 succeeded at 142 with fuzz 1.
patching file app/design/frontend/rwd/default/template/persistent/checkout/onepage/billing.phtml
Hunk #1 succeeded at 201 with fuzz 1.
patching file app/etc/config.xml
Hunk #1 succeeded at 140 (offset -1 lines).
patching file app/locale/en_US/Mage_Adminhtml.csv
Hunk #1 succeeded at 1213 (offset -72 lines).
patching file app/locale/en_US/Mage_Core.csv
Hunk #1 succeeded at 391 (offset -16 lines).
patching file app/locale/en_US/Mage_Dataflow.csv
patching file app/locale/en_US/Mage_XmlConnect.csv
patching file downloader/Maged/Connect.php
patching file downloader/Maged/Controller.php
Hunk #1 succeeded at 417 (offset -4 lines).
Hunk #2 succeeded at 964 (offset -15 lines).
patching file downloader/Maged/Model/Session.php
Hunk #1 succeeded at 82 with fuzz 2.
Hunk #2 succeeded at 268 (offset -5 lines).
patching file js/lib/jquery/jquery-1.12.0.js
patching file js/lib/jquery/jquery-1.12.0.min.js
patching file js/lib/jquery/jquery-1.12.0.min.map
patching file js/varien/payment.js
patching file skin/frontend/base/default/js/opcheckout.js
Hunk #1 succeeded at 723 (offset 39 lines).

So the error is basically at file location :

app/design/frontend/rwd/default/layout/page.xml
app/design/frontend/rwd/default/template/checkout/cart/shipping.phtml
app/design/frontend/rwd/default/template/checkout/multishipping/addresses.phtml

Please suggest I should go for manual entry of the patching or not?


问:
How can I change a style via code that is stored in a resource dictionary in App.xaml on the fly?
I am trying to have the ability for several core colors throughout the app to be changeable on the fly by the user. My current idea is to have a single SolidColorBrush that is my "theme color" and then to reference that throughout my main styles.

```<code><SolidColorBrush x:Key="ReflectiveColor1" Color="#FF0E777B"></SolidColorBrush>
</code>```

This snippet is stored in a resourcedictionary that is reference in my App.xaml

```<code><Application.Resources>
    <ResourceDictionary Source="DictionaryAlienwareTheme.xaml">
    </ResourceDictionary>
</Application.Resources>
</code>```

When I try and access the color in my App.cs I get an error

```<code> Application.Current.Resources["ReflectiveColor1"] = Colors.Black;
</code>```

Error:

```<code>System.Runtime.InteropServices.COMException: 'No installed components were
detected.
Local values are not allowed in resource dictionary with Source set
</code>```

Is there anyway to make this work? I'm assuming this error is because it doesn't want us to modify styles stored there, but I don't know the workaround.

答:
Firstly, in your App.xaml if you want to reference the DictionaryAlienwareTheme.xaml you defined by yourself you need to merge the dictionaries to current app as @AVK said. More details please reference "Merged resource dictionaries" section of this article.

Secondly, after you use the merged resource, if you want to update the theme resource code behind you may need to use Application.Current.Resources.MergedDictionaries to visit the merged dictionaries instead of Application.Current.Resources. For example,

```<code>public MainPage()
{
   this.InitializeComponent();
   var mergedDict = Application.Current.Resources.MergedDictionaries.FirstOrDefault();
   ((SolidColorBrush)mergedDict["ReflectiveColor1"]).Color = Colors.Red;
}
</code>```

By the way, as above code snippet showed, ReflectiveColor1 is SolidColorBrush you cannot set color directly.

Body:
I am trying to have the ability for several core colors throughout the app to be changeable on the fly by the user. My current idea is to have a single SolidColorBrush that is my "theme color" and then to reference that throughout my main styles.

<SolidColorBrush x:Key="ReflectiveColor1" Color="#FF0E777B"></SolidColorBrush>

This snippet is stored in a resourcedictionary that is reference in my App.xaml

<Application.Resources>
    <ResourceDictionary Source="DictionaryAlienwareTheme.xaml">
    </ResourceDictionary>
</Application.Resources>

When I try and access the color in my App.cs I get an error

 Application.Current.Resources["ReflectiveColor1"] = Colors.Black;

Error:

System.Runtime.InteropServices.COMException: 'No installed components were
detected.
Local values are not allowed in resource dictionary with Source set

Is there anyway to make this work? I'm assuming this error is because it doesn't want us to modify styles stored there, but I don't know the workaround.

Body:
Firstly, in your App.xaml if you want to reference the DictionaryAlienwareTheme.xaml you defined by yourself you need to merge the dictionaries to current app as @AVK said. More details please reference "Merged resource dictionaries" section of this article.

Secondly, after you use the merged resource, if you want to update the theme resource code behind you may need to use Application.Current.Resources.MergedDictionaries to visit the merged dictionaries instead of Application.Current.Resources. For example,

public MainPage()
{
   this.InitializeComponent();
   var mergedDict = Application.Current.Resources.MergedDictionaries.FirstOrDefault();
   ((SolidColorBrush)mergedDict["ReflectiveColor1"]).Color = Colors.Red;
}

By the way, as above code snippet showed, ReflectiveColor1 is SolidColorBrush you cannot set color directly.


问:
Twitter - Time Zone of the Tweeet
What is the time zone used for tweets in Twitter API?</p>

答: Time zone is in the user settings under delivery options.</p>

Title: Twitter - Time Zone of the Tweeet


问:
adb error (error: protocol fault (couldn't read status): Invalid argument)
I am unable to connect to my phone using adb.
I am getting the following error:

```<code>D:\softwares\Development\Android\android-sdk-windows\platform-tools>adb devices -l
List of devices attached
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
error: protocol fault (couldn't read status): Invalid argument
</code>```

http://s18.postimg.org/7fdc8w9dl/screenshot_97.png

Previously i am getting this error in windows 8.1 then i have installed windows 10 and error resolved but now again i am unable to connect my cellphone with adb :(.

I am getting this error even if no device is connected.

Eclipse error:

```<code>[2015-10-24 13:25:02 - ddms] Failed to initialize Monitor Thread: Unable to establish loopback connection
[2015-10-24 13:25:02 - adb] error: protocol fault (couldn't read status): Invalid argument
[2015-10-24 13:25:02 - ddms] 'D:\softwares\Development\Android\android-sdk-windows\platform-tools\adb.exe,start-server' failed -- run manually if necessary
</code>```

Update:
Even adb tcp is also not working so i think this is not a driver issue.

ADB traces
http://s24.postimg.org/mtfdwf3id/screenshot_99.png

答:
Just Restart PC and everything mean Android Studio and your android Device
its working for me</p>

Body:
I am unable to connect to my phone using adb.
I am getting the following error:

D:\softwares\Development\Android\android-sdk-windows\platform-tools>adb devices -l
List of devices attached
* daemon not running. starting it now on port 5037 *
* daemon started successfully *
error: protocol fault (couldn't read status): Invalid argument

http://s18.postimg.org/7fdc8w9dl/screenshot_97.png

Previously i am getting this error in windows 8.1 then i have installed windows 10 and error resolved but now again i am unable to connect my cellphone with adb :(.

I am getting this error even if no device is connected.

Eclipse error:

[2015-10-24 13:25:02 - ddms] Failed to initialize Monitor Thread: Unable to establish loopback connection
[2015-10-24 13:25:02 - adb] error: protocol fault (couldn't read status): Invalid argument
[2015-10-24 13:25:02 - ddms] 'D:\softwares\Development\Android\android-sdk-windows\platform-tools\adb.exe,start-server' failed -- run manually if necessary

Update:
Even adb tcp is also not working so i think this is not a driver issue.

ADB traces
http://s24.postimg.org/mtfdwf3id/screenshot_99.png


问:
Updating parent entity with children that already exist EF
I have a model which consists of movies and actors, currently to update already existing movie (that is fill it with information and actors which star in it) I use this

```<code>    public void Update(Movie item)
    {
        db.Entry(item).State = EntityState.Modified;
    }
</code>```

But how do I make it so that if I add a movie which has actors that are already in DB, those are not added again and simply ignored?

答:
So you have a Movie class and an Actor class with a many-to-many relationship:
A movie can have many actors and an actor can appear in many movies.

See this link to see how the many-to-many is configured

If you configure the many-to-many correctly you won't have to worry that existing actors are added again if he appears in a new movie.

The following code will illustrate this:

```<code>public class Movie
{
    public int Id {get; set;}
    public string Title {get; set;}
    public virtual ICollection<Actor> Actors {get; set;}

}

public class Actor
{
    public int Id {get; set;}
    public string Name {get; set;}
    public virtual ICollection<Movie> Movies {get; set;}
}

public class MyDbContext : DbContext
{
    public DbSet<Movie> Movies {get; set;}
    public DbSet<Actor> Actors {get; set;}
}

public void Test()
{
    // create some actors
    var actor1 = new Actor() { Name = "Actor 1"}
    var actor2 = new Actor() { Name = "Actor 2" };
    var actor3 = new Actor() { Name = "Actor 3" };

    // add a movie with some of these actors
    var movieToAdd = new Movie()
    {
        Title = "Hello Dolly",
        Actors = new List<Actor>() {actor1, actor2},
    };
    var addedMovie = dbContext.Movies.Add(movieToAdd);
    dbContext.SaveChanges();

    // add another movie, with one existing actor and one not-existing actor
    var otherMovieToAdd = new Movie()
    {
        Title = "Dracula",
        Actors = new List<Actor>(){actor3, actor2},
    };
    var otherAddedMovie = dbContext.Movies.Add(otherMovieToAdd);
    dbContext.SaveChanges();

    // check the existing actors
    foreach (var actorName in dbContext.Actors.Select(actor => actor.Name))
    {
        Console.WriteLine(actorName);
    }
}
</code>```

The output will be

```<code>Actor 1
Actor 2
Actor 3
</code>```

Note, that although you didn't add any Actor specifically, they were added, because the movie in which they appeared were added. Any existing actor(one with an Id unequal to zero) are not added again.

So the answer to your question: if you configure the many-to-many relation correctly, you won't have to worry that existing actors are added twice.

Body:
I have a model which consists of movies and actors, currently to update already existing movie (that is fill it with information and actors which star in it) I use this

    public void Update(Movie item)
    {
        db.Entry(item).State = EntityState.Modified;
    }

But how do I make it so that if I add a movie which has actors that are already in DB, those are not added again and simply ignored?

Body:
So you have a Movie class and an Actor class with a many-to-many relationship:
A movie can have many actors and an actor can appear in many movies.

See this link to see how the many-to-many is configured

If you configure the many-to-many correctly you won't have to worry that existing actors are added again if he appears in a new movie.

The following code will illustrate this:

public class Movie
{
    public int Id {get; set;}
    public string Title {get; set;}
    public virtual ICollection<Actor> Actors {get; set;}

}

public class Actor
{
    public int Id {get; set;}
    public string Name {get; set;}
    public virtual ICollection<Movie> Movies {get; set;}
}

public class MyDbContext : DbContext
{
    public DbSet<Movie> Movies {get; set;}
    public DbSet<Actor> Actors {get; set;}
}

public void Test()
{
    // create some actors
    var actor1 = new Actor() { Name = "Actor 1"}
    var actor2 = new Actor() { Name = "Actor 2" };
    var actor3 = new Actor() { Name = "Actor 3" };

    // add a movie with some of these actors
    var movieToAdd = new Movie()
    {
        Title = "Hello Dolly",
        Actors = new List<Actor>() {actor1, actor2},
    };
    var addedMovie = dbContext.Movies.Add(movieToAdd);
    dbContext.SaveChanges();

    // add another movie, with one existing actor and one not-existing actor
    var otherMovieToAdd = new Movie()
    {
        Title = "Dracula",
        Actors = new List<Actor>(){actor3, actor2},
    };
    var otherAddedMovie = dbContext.Movies.Add(otherMovieToAdd);
    dbContext.SaveChanges();

    // check the existing actors
    foreach (var actorName in dbContext.Actors.Select(actor => actor.Name))
    {
        Console.WriteLine(actorName);
    }
}

The output will be

Actor 1
Actor 2
Actor 3

Note, that although you didn't add any Actor specifically, they were added, because the movie in which they appeared were added. Any existing actor(one with an Id unequal to zero) are not added again.

So the answer to your question: if you configure the many-to-many relation correctly, you won't have to worry that existing actors are added twice.


问:
Is it possible to have overlapping views with auto layout?
I'm trying to have to views overlap as shown in the picture below, but I couldn't figure out how would I go about doing it with auto layout.

I tried doing the bottom view programmatically, and it worked fine except for the button which I had laid out using interface builder.

If it's possible to have views overlap what are the constraints needed, and is there a way to let the button show on top of the view in the bottom without doing programmatically?

答:
You can do overlapping views using InterfaceBuilder. First create the top view i.e the one with image, give its constraints like top ,trailing,leading and bottom space. Then create the overlapping view.
The constraints for the overlapping view can be its trailing space, leading space,bottom space and height.
Then add those buttons inside that view.</p>