问:
Picasso can't load image inside StorageReference's onSuccess method
When trying Picasso on the runtime onStart() method it normally loads the image from Firebase using the download link from the console.

But when I try to load an image inside StorageReference onSuccess method it just won't work.

This class is extending Fragment:

```<code>@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == GALLERY_IN && resultCode == Activity.RESULT_OK) {
        isGranted = true;
        String path = FireStorage.retUID() + "/";
        showIndProgress();
        Uri uri = data.getData();

        StorageReference childPathRef = FireStorage.storageRef.child(path + uri.getLastPathSegment());
        childPathRef.putFile(uri)
                .addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                        if(task.isSuccessful()) {
                            Picasso.with(mContext).load(task.getResult().getDownloadUrl())
                                    .into(profView);

                            Picasso.Builder build = new Picasso.Builder(mContext);
                            build.listener(new Picasso.Listener() {
                                @Override
                                public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
                                    Toast.makeText(mContext, "exception\n" + exception.toString(), Toast.LENGTH_SHORT).show();

                                }
                            });
                            progressDialog.dismiss();
                        } else {
                            //failed
                        }

                    }
                });

    }

}
</code>```

This is my FirebaseStorage instance on another Class:

```<code>public static FirebaseStorage storage = FirebaseStorage.getInstance();
public static StorageReference storageRef =
                           storage.getReferenceFromUrl("gs://myurl.appspot.com/");
</code>```

Manifest:

```<code><uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />
</code>```

My XML layout:

```<code><RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:background="@drawable/gcover"
    android:id="@+id/relativeLayout">

    <de.hdodenhof.circleimageview.CircleImageView xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/profPhoto"
        android:clickable="true"
        android:layout_width="120dp"
        android:layout_height="120dp"
        android:padding="20dp"
        android:src="@drawable/default_prof"
        android:scaleType="centerCrop"
        app:civ_border_color="@color/trans"
        app:civ_border_width="2dp"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>
</code>```

My views initialization:

```<code>@Override
public View onCreateView(LayoutInflater inflater,
                         ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_prof, container, false);
    profView = (CircleImageView) view.findViewById(R.id.profPhoto);

    btn1 = (Button) view.findViewById(R.id.btn_1);
    btn2 = (Button) view.findViewById(R.id.btn_2);
    btn3 = (Button) view.findViewById(R.id.btn_3);
    return view;
}
</code>```

答:
Limitations for de.hdodenhof.circleimageview.CircleImageView

The ScaleType is always CENTER_CROP and you'll get an exception if you try to change it. This is (currently) by design as it's perfectly fine for profile images.

Enabling adjustViewBounds is not supported as this requires an unsupported ScaleType

If you use an image loading library like Picasso or Glide, you need to disable their fade animations to avoid messed up images. For Picasso use the noFade() option, for Glide use dontAnimate(). If you want to keep the fadeIn animation, you have to fetch the image into a Target and apply a custom animation yourself when receiving the Bitmap.

Using a TransitionDrawable with CircleImageView doesn't work properly and leads to messed up images.

Body:
When trying Picasso on the runtime onStart() method it normally loads the image from Firebase using the download link from the console.

But when I try to load an image inside StorageReference onSuccess method it just won't work.

This class is extending Fragment:

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);

    if (requestCode == GALLERY_IN && resultCode == Activity.RESULT_OK) {
        isGranted = true;
        String path = FireStorage.retUID() + "/";
        showIndProgress();
        Uri uri = data.getData();

        StorageReference childPathRef = FireStorage.storageRef.child(path + uri.getLastPathSegment());
        childPathRef.putFile(uri)
                .addOnCompleteListener(new OnCompleteListener<UploadTask.TaskSnapshot>() {
                    @Override
                    public void onComplete(@NonNull Task<UploadTask.TaskSnapshot> task) {
                        if(task.isSuccessful()) {
                            Picasso.with(mContext).load(task.getResult().getDownloadUrl())
                                    .into(profView);

                            Picasso.Builder build = new Picasso.Builder(mContext);
                            build.listener(new Picasso.Listener() {
                                @Override
                                public void onImageLoadFailed(Picasso picasso, Uri uri, Exception exception) {
                                    Toast.makeText(mContext, "exception\n" + exception.toString(), Toast.LENGTH_SHORT).show();

                                }
                            });
                            progressDialog.dismiss();
                        } else {
                            //failed
                        }

                    }
                });

    }

}

This is my FirebaseStorage instance on another Class:

public static FirebaseStorage storage = FirebaseStorage.getInstance();
public static StorageReference storageRef =
                           storage.getReferenceFromUrl("gs://myurl.appspot.com/");

Manifest:

<uses-permission android:name="android.permission.INTERNET"/>
<uses-permission android:name="android.permission.ACCESS_NETWORK_STATE"/>
<uses-permission android:name="android.permission.READ_EXTERNAL_STORAGE" />

My XML layout:

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:background="@drawable/gcover"
    android:id="@+id/relativeLayout">

    <de.hdodenhof.circleimageview.CircleImageView xmlns:app="http://schemas.android.com/apk/res-auto"
        android:id="@+id/profPhoto"
        android:clickable="true"
        android:layout_width="120dp"
        android:layout_height="120dp"
        android:padding="20dp"
        android:src="@drawable/default_prof"
        android:scaleType="centerCrop"
        app:civ_border_color="@color/trans"
        app:civ_border_width="2dp"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

My views initialization:

@Override
public View onCreateView(LayoutInflater inflater,
                         ViewGroup container,
                         Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_prof, container, false);
    profView = (CircleImageView) view.findViewById(R.id.profPhoto);

    btn1 = (Button) view.findViewById(R.id.btn_1);
    btn2 = (Button) view.findViewById(R.id.btn_2);
    btn3 = (Button) view.findViewById(R.id.btn_3);
    return view;
}


来源: stackexchange

问:
How can I iterate over a list of lists?
I'm trying to sort through a list of lists. How could I go about printing or iterating over the first and last elements in each list? non-working code below:

```<code>from numpy import *
xs=[[1.,2.,3.],[4.,5.,6.],[7.,8.,9.]]

for i in xs:
    for j in xs[i]:
        print(xs[1],xs[-1])
</code>```

Traceback error if needed:

```<code>runfile('/Users/Alex/untitled9.py', wdir='/Users/Alex')
Traceback (most recent call last):

  File "<ipython-input-14-8a28382c7f81>", line 1, in <module>
    runfile('/Users/Alex/untitled9.py', wdir='/Users/Alex')

  File "/anaconda/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 880, in runfile
    execfile(filename, namespace)

  File "/anaconda/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "/Users/Alex/untitled9.py", line 13, in <module>
    for j in xs[i]:

TypeError: list indices must be integers or slices, not list
</code>```

答:
When you iterate over a list you get an item from each member of the list, and if that item is a list you can create a second loop to iterate over the item, like this:

```<code>for items in xs:
    for elem in items:
        # in here you get each element of the inner list
</code>```

To get the first and last value though, You don't need that you can as answered previously:

```<code>for item in xs:
    print(item[0], item[-1]
</code>```

And if you are feeling a little funny you could even store those in your own list by using a comprehensive list, like so:

funny_list= [[item[0], item[-1]] for item in xs]

ContentLicense: CC BY-SA 3.0

Title: How can I iterate over a list of lists?

Body:
I'm trying to sort through a list of lists. How could I go about printing or iterating over the first and last elements in each list? non-working code below:

from numpy import *
xs=[[1.,2.,3.],[4.,5.,6.],[7.,8.,9.]]

for i in xs:
    for j in xs[i]:
        print(xs[1],xs[-1])

Traceback error if needed:

runfile('/Users/Alex/untitled9.py', wdir='/Users/Alex')
Traceback (most recent call last):

  File "<ipython-input-14-8a28382c7f81>", line 1, in <module>
    runfile('/Users/Alex/untitled9.py', wdir='/Users/Alex')

  File "/anaconda/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 880, in runfile
    execfile(filename, namespace)

  File "/anaconda/lib/python3.6/site-packages/spyder/utils/site/sitecustomize.py", line 102, in execfile
    exec(compile(f.read(), filename, 'exec'), namespace)

  File "/Users/Alex/untitled9.py", line 13, in <module>
    for j in xs[i]:

TypeError: list indices must be integers or slices, not list

Body:
When you iterate over a list you get an item from each member of the list, and if that item is a list you can create a second loop to iterate over the item, like this:

for items in xs:
    for elem in items:
        # in here you get each element of the inner list

To get the first and last value though, You don't need that you can as answered previously:

for item in xs:
    print(item[0], item[-1]

And if you are feeling a little funny you could even store those in your own list by using a comprehensive list, like so:

funny_list= [[item[0], item[-1]] for item in xs]


问:
Using --become for ansible_connection=local
With a personal user account (userx) I run the ansible playbook on all my specified hosts. In ansible.cfg the remote user (which can become root) to be used is:

```<code>remote_user = ansible
</code>```

For the remote hosts this all works fine. It connects as the user Ansible, and executes all tasks as wished for, also changing information (like /etc/ssh/sshd_config) which requires root rights.

But now I also want to execute the playbook on the Ansible host itself. I put the following in my inventory file:

```<code>localhost ansible_connection=local
</code>```

which now indeed executes on localhost. But as userx, and this results in "Access denied" for some task it needs to do.

This is of course somewhat expected, since remote_user tells something about remote, not the local user. But still, I expected that the playbook would --become locally too, to execute the tasks as root (e.g. sudo su -). It seems no to do that.

Running the playbook with --become -vvv tells me

```<code><localhost> ESTABLISH LOCAL CONNECTION FOR USER: userx
</code>```

and it seems not to try to execute the tasks with sudo. And without using sudo, the task fails.

How can I tell ansible to to use sudo / become on the local connection too?

答:
Nothing special is required. Proof:

The playbook:

```<code>---
- hosts: localhost
  gather_facts: no
  connection: local
  tasks:
    - command: whoami
      register: whoami
    - debug:
        var: whoami.stdout
</code>```

The execution line:

```<code>ansible-playbook playbook.yml --become
</code>```

The result:

```<code>PLAY [localhost] ***************************************************************************************************

TASK [command] *****************************************************************************************************
changed: [localhost]

TASK [debug] *******************************************************************************************************
ok: [localhost] => {
    "changed": false,
    "whoami.stdout": "root"
}

PLAY RECAP *********************************************************************************************************
localhost                  : ok=2    changed=1    unreachable=0    failed=0
</code>```

The ESTABLISH LOCAL CONNECTION FOR USER: message will always show the current user, as it the account used "to connect".

Later the command(s) called from the module get(s) executed with elevated permissions.

Of course, you can add become: yes on either play level or for individual tasks.

Body:
With a personal user account (userx) I run the ansible playbook on all my specified hosts. In ansible.cfg the remote user (which can become root) to be used is:

remote_user = ansible

For the remote hosts this all works fine. It connects as the user Ansible, and executes all tasks as wished for, also changing information (like /etc/ssh/sshd_config) which requires root rights.

But now I also want to execute the playbook on the Ansible host itself. I put the following in my inventory file:

localhost ansible_connection=local

which now indeed executes on localhost. But as userx, and this results in "Access denied" for some task it needs to do.

This is of course somewhat expected, since remote_user tells something about remote, not the local user. But still, I expected that the playbook would --become locally too, to execute the tasks as root (e.g. sudo su -). It seems no to do that.

Running the playbook with --become -vvv tells me

<localhost> ESTABLISH LOCAL CONNECTION FOR USER: userx

and it seems not to try to execute the tasks with sudo. And without using sudo, the task fails.

How can I tell ansible to to use sudo / become on the local connection too?

Body:
Nothing special is required. Proof:

The playbook:

---
- hosts: localhost
  gather_facts: no
  connection: local
  tasks:
    - command: whoami
      register: whoami
    - debug:
        var: whoami.stdout

The execution line:

ansible-playbook playbook.yml --become

The result:

PLAY [localhost] ***************************************************************************************************

TASK [command] *****************************************************************************************************
changed: [localhost]

TASK [debug] *******************************************************************************************************
ok: [localhost] => {
    "changed": false,
    "whoami.stdout": "root"
}

PLAY RECAP *********************************************************************************************************
localhost                  : ok=2    changed=1    unreachable=0    failed=0

The ESTABLISH LOCAL CONNECTION FOR USER: message will always show the current user, as it the account used "to connect".

Later the command(s) called from the module get(s) executed with elevated permissions.

Of course, you can add become: yes on either play level or for individual tasks.


问:
How to use an absolute filename in ProGuard?
Like the title: "How to use an absolute filename in ProGuard?"
This should be easy but i can't find what syntax to use.

This is my config file related code:

```<code>-injars ../../libs
-outjars ../bin/out/proguard/classes-processed.jar
-libraryjars E:/_development/android/adt-bundle-windows-x86_64-20130219/sdk/platforms/android-18/android.jar
</code>```

I'm using AndroidStudio and unfortunatly it doesnt generate a the proguard config file for me.

The ProGuard documentation on filenames only specifies relative paths.

答:
This worked</p>

```<code>file('/Users/<user-folder>/path/to/file/filename.ext')
</code>```

Body:
Like the title: "How to use an absolute filename in ProGuard?"
This should be easy but i can't find what syntax to use.

This is my config file related code:

-injars ../../libs
-outjars ../bin/out/proguard/classes-processed.jar
-libraryjars E:/_development/android/adt-bundle-windows-x86_64-20130219/sdk/platforms/android-18/android.jar

I'm using AndroidStudio and unfortunatly it doesnt generate a the proguard config file for me.

The ProGuard documentation on filenames only specifies relative paths.

Body:
This worked

file('/Users/<user-folder>/path/to/file/filename.ext')


问:
Center a title but subtitle is center "right"
I need to center a title and in the next line, i have to write a subtitle that ends at the right of the title. Example:

```<code>                     Here is my title
                             subtitle
</code>```

Could someone help me?

答:
You can solve this by using Custom Data Attributes and Pseudo-Elements or using simple css, it totally depends on you. Below is the solution:

.page-title {
 text-align: center;
}
h1 {
 display: inline-block;
 position: relative;
}
h1:after {
 content: attr(data-subtitle);
 position: absolute;
 top: 100%;
 right: 0px;
}
.another h1 {
 margin-bottom: 40px;
}
.another span {
 position: absolute;
 top: 100%;
 right: 0px;
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><div class="page-title">
 <h1 data-subtitle="subtitle">Here is my title</h1>
</div>
<div class="page-title another">
 <h1>Here is my title <span>subtitle</span></h1>
</div></code>```

Body:
I need to center a title and in the next line, i have to write a subtitle that ends at the right of the title. Example:

                     Here is my title
                             subtitle

Could someone help me?

Body:
You can solve this by using Custom Data Attributes and Pseudo-Elements or using simple css, it totally depends on you. Below is the solution:

.page-title {
 text-align: center;
}
h1 {
 display: inline-block;
 position: relative;
}
h1:after {
 content: attr(data-subtitle);
 position: absolute;
 top: 100%;
 right: 0px;
}
.another h1 {
 margin-bottom: 40px;
}
.another span {
 position: absolute;
 top: 100%;
 right: 0px;
}

<div class="page-title">
 <h1 data-subtitle="subtitle">Here is my title</h1>
</div>
<div class="page-title another">
 <h1>Here is my title <span>subtitle</span></h1>
</div>


问:
Projections' Angle of Line in Space
Start of line (yellow) and axes are at [xc,yc,zc]

End of line is at [xp,yp,zc].

a,b, c are the angles which line makes in space.

What I need are the angles which line's projections (black line) create on xy,yz and xz planes.

A_y_to_z: Projected line's angle from y axis to z axis on xz plane.

A_z_to_x: Angle from z to x axis on zx plane.

A_x_to_y: Angle from x to y axis on xy plane.

Writing code on Matlab

答:
You can calculate the projection angle to any plane by:

Obtaining the direction of the line, d = (xp - xc, yp - yc, zp - zc)

Normalizing d

Calculating the dot-product with the normal of the plane, dot(d, n) = d.x * n.x + d.y * n.y + d.z * n.z

Calculating the angle to the normal by a = acos(dot(d, n))

Finally obtaining the angle to the plane by taking b = 90 - a (assuming units in degrees - NB most math library functions use radians)

Special case: if dot(d, n) < 0, then the angle a will be greater than 90 degrees. In this case if you only want the acute angle, do b = a - 90 instead of 90 - a.

e.g. To calculate the angle to the xy plane, use n = (0, 0, 1), i.e. the z-axis, which is the normal to that plane.

Title: Projections' Angle of Line in Space


问:
PHP Button click not reloading the page
I have button.php and this code is there in button.php

```<code><a href="Cancel.php<button type="button">Cancel</button></a>
</code>```

I have Cancel.php

```<code><?php
//Do something
header("location:button.php")
?>
</code>```

When I click the Cancel button it should process something and return to the same PHP file.
It's returning but not reloading or updating the page content.
Is there any method to reload or my method of coding is wrong? Can I use jQuery here? Please help me!

答:
You have to add simple a hyper link like below:

```<code><?php
<a href="Cancel.php">Cancel</a>
?>
</code>```

Not need to button in hyper link you can do it another way with the button like the below:

```<code><button type="button" onclick="location.href='Cancel.php';">Cancel</button>
</code>```

ContentLicense: CC BY-SA 4.0

Title: PHP Button click not reloading the page

Body:
I have button.php and this code is there in button.php

<a href="Cancel.php<button type="button">Cancel</button>

I have Cancel.php

<?php
//Do something
header("location:button.php")
?>

When I click the Cancel button it should process something and return to the same PHP file.
It's returning but not reloading or updating the page content.
Is there any method to reload or my method of coding is wrong? Can I use jQuery here? Please help me!

Body:
You have to add simple a hyper link like below:

<?php
<a href="Cancel.php">Cancel</a>
?>

Not need to button in hyper link you can do it another way with the button like the below:

<button type="button" onclick="location.href='Cancel.php';">Cancel</button>


问:
Syntax error or access violation: 1055 Expression #8 of SELECT list is not in GROUP BY clause and contains nonaggregated column
i tried the CakePHP 3.x "Bookmaker Tutorial" and i followed the instruction step by step. Unfortunately, at the end of the first chapter i get the attached error:

```<code>Error: SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #8 of SELECT list
is not in GROUP BY clause and contains nonaggregated column 'wis.Tags.id' which is not
functionally dependent on columns in GROUP BY clause; this is incompatible with
sql_mode=only_full_group_by
</code>```

Furthermore, i get the information to check my "BookmarksTags" table but i do not have to creat one before. I little bit confused.

```<code>Please try correcting the issue for the following table aliases:

BookmarksTags
</code>```

I already google my problem and i found information to update the "my.cnf" with a extra line. i already try but nothing happed. I also check the spelling and downloaded the "bookmarker-tutorial" from github but i still get this error above.

I use MySQL 5.7.11 and PHP 5.6.14.

答:
I'm using Laravel 5.4 and facing same problem.

I try to set strict into false on config/database.php and it works.

```<code>'connections' => [
    'mysql' => [
        'strict' => false,
    ]
]
</code>```

However it's better to edit sql query than suppress it's warning.

Body:
i tried the CakePHP 3.x "Bookmaker Tutorial" and i followed the instruction step by step. Unfortunately, at the end of the first chapter i get the attached error:

Error: SQLSTATE[42000]: Syntax error or access violation: 1055 Expression #8 of SELECT list
is not in GROUP BY clause and contains nonaggregated column 'wis.Tags.id' which is not
functionally dependent on columns in GROUP BY clause; this is incompatible with
sql_mode=only_full_group_by

Furthermore, i get the information to check my "BookmarksTags" table but i do not have to creat one before. I little bit confused.

Please try correcting the issue for the following table aliases:

BookmarksTags

I already google my problem and i found information to update the "my.cnf" with a extra line. i already try but nothing happed. I also check the spelling and downloaded the "bookmarker-tutorial" from github but i still get this error above.

I use MySQL 5.7.11 and PHP 5.6.14.

Body:
I'm using Laravel 5.4 and facing same problem.

I try to set strict into false on config/database.php and it works.

'connections' => [
    'mysql' => [
        'strict' => false,
    ]
]

However it's better to edit sql query than suppress it's warning.


问:
c# dllimport of MsiGetShortcutTarget(msi.dll) failed with error 1603 under Windows 7
I want to resolve an advertised MSI shortcut in c# as described here:
How to parse "special" .lnk files, aka. MSI shortcuts aka. Windows Installer advertised shortcuts using C#

```<code>[DllImport("msi.dll", CharSet = CharSet.Auto)]
private static extern UInt32 MsiGetShortcutTarget(
    string szShortcutTarget,
    [Out] StringBuilder szProductCode,
    [Out] StringBuilder szFeatureId,
    [Out] StringBuilder szComponentCode);

public static string ParseShortcut(string file)
{
    StringBuilder product = new StringBuilder(MaxGuidLength + 1);
    StringBuilder feature = new StringBuilder(MaxFeatureLength + 1);
    StringBuilder component = new StringBuilder(MaxGuidLength + 1);

    UInt32 res = MsiGetShortcutTarget(file, product, feature, component);
    ...
}
</code>```

I use VS 2010 and tried with different settings for "Platform target" and/or "Target framework". MsiGetShortcutTarget always returns 1603 (A fatal error occurred during installation) under Windows 7.

I tried to do the same with c++ and I can resolve the Shortcut and everything is fine. I also tested with a msi.dll, that I copied from a Windows XP and this dll can resolve the Shortcut with the C# code. I have no idea why the c# code won't work with the msi.dll under Windows 7.

I testet MsiGetComponentPath with a known product GUID and component GUID to resolve the target path in c# with the dll, that returns 1603 for MsiGetShortcutTarget and it works perfectly. So only MsiGetComponentPath fails under Windows 7 and I don't know why it went wrong.

答:
This seems related to the way COM is initialized.

If I add [STAThread] to my Main method, it works fine (well, if you actually use StringBuilder instead of char[] for your arguments :-), but I get a return value of 1603 when using MTA.

ContentLicense: CC BY-SA 2.5

Body:
I want to resolve an advertised MSI shortcut in c# as described here:
How to parse "special" .lnk files, aka. MSI shortcuts aka. Windows Installer advertised shortcuts using C#

[DllImport("msi.dll", CharSet = CharSet.Auto)]
private static extern UInt32 MsiGetShortcutTarget(
    string szShortcutTarget,
    [Out] StringBuilder szProductCode,
    [Out] StringBuilder szFeatureId,
    [Out] StringBuilder szComponentCode);

public static string ParseShortcut(string file)
{
    StringBuilder product = new StringBuilder(MaxGuidLength + 1);
    StringBuilder feature = new StringBuilder(MaxFeatureLength + 1);
    StringBuilder component = new StringBuilder(MaxGuidLength + 1);

    UInt32 res = MsiGetShortcutTarget(file, product, feature, component);
    ...
}

I use VS 2010 and tried with different settings for "Platform target" and/or "Target framework". MsiGetShortcutTarget always returns 1603 (A fatal error occurred during installation) under Windows 7.

I tried to do the same with c++ and I can resolve the Shortcut and everything is fine. I also tested with a msi.dll, that I copied from a Windows XP and this dll can resolve the Shortcut with the C# code. I have no idea why the c# code won't work with the msi.dll under Windows 7.

I testet MsiGetComponentPath with a known product GUID and component GUID to resolve the target path in c# with the dll, that returns 1603 for MsiGetShortcutTarget and it works perfectly. So only MsiGetComponentPath fails under Windows 7 and I don't know why it went wrong.


问:
Spline interpolation in interp1 without filling nan values in
I have tide observations each 5 min, I want to interpolate it into a 1 min interval.

I tried to do it in Python but it takes too much time, so I have moved to MATLAB. The problem is that the spline method fills NaN values.

The image below explains the problem, I want to have a spline interpolation without the NaN values being filled. How can I chance my interp1 function to do so?

```<code>file='NANTES_5min_nan.txt'
[date, hauteur] = lecture_hfs(file);
vect=[date(1):1/24/60:date(end)];
h_interp=interp1(date,hauteur,vect,'spline');

h_interp_lin=interp1(date,hauteur,vect,'linear');
</code>```

the second figure is from Python interpolation. the results are good but unfortunately it's only for 1 month data. when I want to apply it for the whole data (17 years) the execution never ends   here is the link for python figure

答:
Instead of using vect directly as query points, you can replace the values of vect which are near a NaN value in hauteur by NaN. This can be done by using another (linear) interpolation:

```<code>temp = date; % copy of the original dates
temp(isnan(hauteur))=NaN; % set the values which are NaN in hauteur to NaN
h_interp = interp1(date,hauteur,interp1(date,temp,vect),'spline'); % the inner interpolation results in vect with NaNs where appropriate
</code>```

A bit messy and there might be more elegant ways, but I was fascinated by the possibility to solve this by nesting another interpolation.

Body:
I have tide observations each 5 min, I want to interpolate it into a 1 min interval.

I tried to do it in Python but it takes too much time, so I have moved to MATLAB. The problem is that the spline method fills NaN values.

The image below explains the problem, I want to have a spline interpolation without the NaN values being filled. How can I chance my interp1 function to do so?

file='NANTES_5min_nan.txt'
[date, hauteur] = lecture_hfs(file);
vect=[date(1):1/24/60:date(end)];
h_interp=interp1(date,hauteur,vect,'spline');

h_interp_lin=interp1(date,hauteur,vect,'linear');

the second figure is from Python interpolation. the results are good but unfortunately it's only for 1 month data. when I want to apply it for the whole data (17 years) the execution never ends   here is the link for python figure

Body:
Instead of using vect directly as query points, you can replace the values of vect which are near a NaN value in hauteur by NaN. This can be done by using another (linear) interpolation:

temp = date; % copy of the original dates
temp(isnan(hauteur))=NaN; % set the values which are NaN in hauteur to NaN
h_interp = interp1(date,hauteur,interp1(date,temp,vect),'spline'); % the inner interpolation results in vect with NaNs where appropriate

A bit messy and there might be more elegant ways, but I was fascinated by the possibility to solve this by nesting another interpolation.


答:
In the code you have given:

```<code>for i in xs:
    for j in xs[i]:
        print(xs[1],xs[-1])
</code>```

in the outer for loop, the variable i stores the inner arrays, so in the inner for loop, when you do xs[i], it gives an error. This is because you can only use integers as indices in an array (which makes sense, since you would want the the 0th or 1st or 2nd element, there is no such thing like [1,2,3]th element, which xs[i] in the code you have written essentially means).

Now, in order to simply iterate over the multidimensional array:

```<code>for i in xs:
    for j in i:
        print(j)
    print("\n")
</code>```

This will give:

```<code>[1.0, 2.0, 3.0]
[4.0, 5.0, 6.0]
[7.0, 8.0, 9.0]
</code>```

If you want to print only the first and last items of the inner lists, this would do:

```<code>for i in xs:
    print(i[0], i[-1], "\n")
</code>```

Hope this helps

Title: How can I iterate over a list of lists?

Body:
In the code you have given:

for i in xs:
    for j in xs[i]:
        print(xs[1],xs[-1])

in the outer for loop, the variable i stores the inner arrays, so in the inner for loop, when you do xs[i], it gives an error. This is because you can only use integers as indices in an array (which makes sense, since you would want the the 0th or 1st or 2nd element, there is no such thing like [1,2,3]th element, which xs[i] in the code you have written essentially means).

Now, in order to simply iterate over the multidimensional array:

for i in xs:
    for j in i:
        print(j)
    print("\n")

This will give:

[1.0, 2.0, 3.0]
[4.0, 5.0, 6.0]
[7.0, 8.0, 9.0]

If you want to print only the first and last items of the inner lists, this would do:

for i in xs:
    print(i[0], i[-1], "\n")

Hope this helps


答:
You can use JS.

```<code><a href="#" onClick="window.location.reload();return false;">Cancel</a>
</code>```

And in PHP

```<code><a href="Cancel.php>Cancel</a>
</code>```

Title: PHP Button click not reloading the page

Body:
You can use JS.

<a href="#" onClick="window.location.reload();return false;">Cancel</a>

And in PHP

<a href="Cancel.php>Cancel</a>


问:
How to escape '[' and ']' in GLOB?
I'm trying to use GLOB operator to determine if some characters are presented in a string:

```<code>SELECT *
FROM Test
WHERE num GLOB '*[~!?.;:+=()<>_#%&/\\]*'
</code>```

It works fine with '][' at the beginning of the pattern:

```<code>WHERE num GLOB '*[][~!?.;:+=()<>_#%&/\\]*'
</code>```

But it returns nothing when placing '[]' anywhere in the pattern:

```<code>WHERE num GLOB '*[[]~!?.;:+=()<>_#%&/\\]*'
</code>```

What's the reason of such behaviour?

答:
The ] character ends a character list. So [[] is a character list that contains only [.

An empty character list would not make sense, so as an exception, putting the ] directly behind the opening [ ([]...]) can be used to include the ] character in the list. But that is the only exception.

(For similar reasons, - as a literal character must be the last one in the list.)

Title: How to escape '[' and ']' in GLOB?

Body:
I'm trying to use GLOB operator to determine if some characters are presented in a string:

SELECT *
FROM Test
WHERE num GLOB '*[~!?.;:+=()<>_#%&/\\]*'

It works fine with '][' at the beginning of the pattern:

WHERE num GLOB '*[][~!?.;:+=()<>_#%&/\\]*'

But it returns nothing when placing '[]' anywhere in the pattern:

WHERE num GLOB '*[[]~!?.;:+=()<>_#%&/\\]*'

What's the reason of such behaviour?


问:
Loop to be used before function call in matlab
```<code>function output=Input(data,T)
[x,cmap]=imread('abc.tiff');

data=im2double(x);

ID_notNaN=find(~isnan(SWI));
D=data(:,1);
X=data(:,2);

F=nan(length(data(:,1)),1);
P(ID_notNaN)=SWI;
output=[data(:,1),data(:,2)];
</code>```

I want to apply the same function on all the 365 datasets I am having, but function can't work with any loop. Help me out with this

答:
I cant seem to find where you get variables SWI and P from, so make sure these are accessible to the function somehow.

Below is a brute force way of reading all (365?) files in a specific folder and feeding them through your algorithm one by one.

Hope this helps!

```<code>% Location of files to be read
folder = 'C:\foo\siffer\second try\';
% Type of files to read. Leave as '' if you wish any ending.
ending = 'tiff';

% Find all files in that folder
files = dir(folder);
numFiles = length(a);
el = length(ending);

% Loop through all found files
for i = 1:numFiles
    filename = files(i).name;
    nameLength = length(filename);
    % Ignore files with improper filename
    if nameLength<el+1
        % Not enough letters for containing .tiff
        continue
    elseif strcmp(filename(nameLength + (-el+1:0)) , ending)
          % The file indeed has the right format

          % Either just call your function here
          % %    output=Input(data,T);
          % or paste the content of the
          % function like i did :

          [x,cmap]=imread([folder,filename]);

          data=im2double(x);

          ID_notNaN=find(~isnan(SWI));
          D=data(:,1);
          X=data(:,2);

          F=nan(length(data(:,1)),1);
          P(ID_notNaN)=SWI;
          output=[data(:,1),data(:,2)];

    end

end
</code>```

Body:
function output=Input(data,T)
[x,cmap]=imread('abc.tiff');

data=im2double(x);

ID_notNaN=find(~isnan(SWI));
D=data(:,1);
X=data(:,2);

F=nan(length(data(:,1)),1);
P(ID_notNaN)=SWI;
output=[data(:,1),data(:,2)];

I want to apply the same function on all the 365 datasets I am having, but function can't work with any loop. Help me out with this

Body:
I cant seem to find where you get variables SWI and P from, so make sure these are accessible to the function somehow.

Below is a brute force way of reading all (365?) files in a specific folder and feeding them through your algorithm one by one.

Hope this helps!

% Location of files to be read
folder = 'C:\foo\siffer\second try\';
% Type of files to read. Leave as '' if you wish any ending.
ending = 'tiff';

% Find all files in that folder
files = dir(folder);
numFiles = length(a);
el = length(ending);

% Loop through all found files
for i = 1:numFiles
    filename = files(i).name;
    nameLength = length(filename);
    % Ignore files with improper filename
    if nameLength<el+1
        % Not enough letters for containing .tiff
        continue
    elseif strcmp(filename(nameLength + (-el+1:0)) , ending)
          % The file indeed has the right format

          % Either just call your function here
          % %    output=Input(data,T);
          % or paste the content of the
          % function like i did :

          [x,cmap]=imread([folder,filename]);

          data=im2double(x);

          ID_notNaN=find(~isnan(SWI));
          D=data(:,1);
          X=data(:,2);

          F=nan(length(data(:,1)),1);
          P(ID_notNaN)=SWI;
          output=[data(:,1),data(:,2)];

    end

end


问:
Oracle SQL 'OVER' partition error
I'm trying to use this code on Oracle and it errors out. The 'partition' statement is highlighted. How do I fix this ?</p>

```<code>select
case when b.c_1 = 1 then b.workkey else null end workkey,
b.total_value total_value,
b.namekey namekey
from (select distinct workkey,total_value,namekey,
      rownum() over (partition by workkey) as c_1
      from report.arturdup
     ) b
</code>```

答:
The correct function is row_number():

```<code>select (case when b.c_1 = 1 then b.workkey end) as workkey,
       b.total_value as total_value,
       b.namekey as namekey
from (select distinct workkey, total_value, namekey,
             row_number() over (partition by workkey order by b.workkey) as c_1
      from report.arturdup
     ) b;
</code>```

Note:  You don't need a subquery for this:

```<code>select (case when row_number() over (partition by workkey order by workkey) = 1
             then b.workkey
        end) as workkey,
       b.total_value,
       b.namekey
from report.arturdup;
</code>```

Notes:

In most databases, order by is required (in some it is not, but I always use order by.

else NULL is redundant.

You don't need to assign a column alias that is already the name of the column.

I always use as for column aliases.

Title: Oracle SQL 'OVER' partition error

Body:
I'm trying to use this code on Oracle and it errors out. The 'partition' statement is highlighted. How do I fix this ?

select
case when b.c_1 = 1 then b.workkey else null end workkey,
b.total_value total_value,
b.namekey namekey
from (select distinct workkey,total_value,namekey,
      rownum() over (partition by workkey) as c_1
      from report.arturdup
     ) b

Body:
The correct function is row_number():

select (case when b.c_1 = 1 then b.workkey end) as workkey,
       b.total_value as total_value,
       b.namekey as namekey
from (select distinct workkey, total_value, namekey,
             row_number() over (partition by workkey order by b.workkey) as c_1
      from report.arturdup
     ) b;

Note:  You don't need a subquery for this:

select (case when row_number() over (partition by workkey order by workkey) = 1
             then b.workkey
        end) as workkey,
       b.total_value,
       b.namekey
from report.arturdup;

Notes:

In most databases, order by is required (in some it is not, but I always use order by.

else NULL is redundant.

You don't need to assign a column alias that is already the name of the column.

I always use as for column aliases.


问:
Laravel Checking If a Record Exists
I am new to Laravel. How do I find if a record exists?

$user = User::where('email', '=', Input::get('email'));
```

What can I do here to see if $user has a record?

答:
```<code>$user = User::where('email', request('email'))->first();
return (count($user) > 0 ? 'Email Exist' : 'Email Not Exist');
</code>```

Title: Laravel Checking If a Record Exists

Body:
I am new to Laravel. How do I find if a record exists?

$user = User::where('email', '=', Input::get('email'));

What can I do here to see if $user has a record?


问:
Windows error LNK1179
I compiled an exe on windows VS 2005, a c++ program that link to other libs of mine.
It compiled and suddenly it doesn't with an error of LNK1170 COMDAT "

I can't understand what happened and how to solve the problem.

Thanks

答:
Anyway, check the official documentation about it:

http://msdn.microsoft.com/en-us/library/cddbs9aw%28VS.80%29.aspx

http://msdn.microsoft.com/en-us/library/aa234469%28VS.60%29.aspx

And if you check codeguru, a guy found another way to solve a problem similar to yours:

Project->Settings->C++ tab, Debug cathegory: Inline function expansion: change from 'None' to 'Only _inline'.

Title: Windows error LNK1179


问:
Order By TableName and columnname
Lets say I have a table with following columns:

```<code>Id,TableName,Columnname
</code>```

Normally If I would like to do a select with ordering on TableName Primary and ColumnName secondary I would do

```<code>Select * From MyTable Order By TableName,ColumnName
</code>```

Now say I would like a special case of ordering depending on TableName

```<code>Select * From MyTable Order By Case
When TableName = 'Foo' Then '1'
When TableName = 'Bar' Then '2'
When TableName = 'Test' Then '3'
ELSE 1000 END;
</code>```

How do I combine the second alternative with the first alternative, that is special ordering on first TableName and then order the Columnnames with that TableName?

I'm running Microsoft SQL

Thanks in advance.

答:
Just add column in order list, like any other ORDER BY :)

```<code>Select * From MyTable Order By Case
When TableName = 'Foo' Then '1'
When TableName = 'Bar' Then '2'
When TableName = 'Test' Then '3'
ELSE 1000 END, ColumnName;
</code>```

Title: Order By TableName and columnname

Body:
Lets say I have a table with following columns:

Id,TableName,Columnname

Normally If I would like to do a select with ordering on TableName Primary and ColumnName secondary I would do

Select * From MyTable Order By TableName,ColumnName

Now say I would like a special case of ordering depending on TableName

Select * From MyTable Order By Case
When TableName = 'Foo' Then '1'
When TableName = 'Bar' Then '2'
When TableName = 'Test' Then '3'
ELSE 1000 END;

How do I combine the second alternative with the first alternative, that is special ordering on first TableName and then order the Columnnames with that TableName?

I'm running Microsoft SQL

Thanks in advance.

Body:
Just add column in order list, like any other ORDER BY :)

Select * From MyTable Order By Case
When TableName = 'Foo' Then '1'
When TableName = 'Bar' Then '2'
When TableName = 'Test' Then '3'
ELSE 1000 END, ColumnName;


问:
Update Query takes only one row as value - Access 2000?
I am unable to understand why my Update Query takes only the value in the last row and puts it in all other, in the same column.

Here are pictures:

So, I need to calculate percent(PBrojProdPoTip), given BrojProdPoTip and VkBrojProdPoTip which is the sum.

```<code>PBrojProdPoTip = BrojProdPoTip * 100 / VkBrojProdPoTip
</code>```

If you try the last value, 244 out of 18248 gives 01.34%

```<code>P = 244 * 100 / 18248 = 1.34%
</code>```

What do I do wrong? Why it takes only one value?

答:
I found much better solution. The main table which I fill with data, already contained the values, so i just removed helper table T10_nezbirni and replaced its values with [T10-promet].[BrojProdPoTip].

Here is a screenshot:

Body:
I am unable to understand why my Update Query takes only the value in the last row and puts it in all other, in the same column.

Here are pictures:

So, I need to calculate percent(PBrojProdPoTip), given BrojProdPoTip and VkBrojProdPoTip which is the sum.

PBrojProdPoTip = BrojProdPoTip * 100 / VkBrojProdPoTip

If you try the last value, 244 out of 18248 gives 01.34%

P = 244 * 100 / 18248 = 1.34%

What do I do wrong? Why it takes only one value?


问:
Central + local cache with PHP
I have a multi server setup where all servers run the same code and need to share the same cache. The amount of cached data is huge and is in a separate memcached server.

This does work but the memcached server is slow. Slow meaning it takes about 0.3 ms in the best case. This sounds like fast but APC is a lot faster and in my experience more reliable.

Building a cache that locally stores only data it needed, reads from APC first and has fallback to memcached is trivial. The hard problem is deleting keys and clearing the cache. I have thought about creating a daemon in each node and broadcasting the delete and clear commands to all of them but this gets very complicated very fast. Especially since APC is not shared between CLI and FPM. So my question is has this problem been solved already?

答:
We have a similar setup. But our case is more of read only data. But occasionally we flush the data in 2 levels of caches.

We had a script to flush the selected keys in 2 levels of cache @ once. We deleted the keys in memcache and then in all the apc caches of cluster(write through approach). Since our case is more of caching read only data - it is working well.

May be you want to try this!

The flush has 2 components:

Doing the delete in memcache (memcache delete api call)

A php component for deleting a given key from APC cache.

Since the php component exists in all nodes of our server cluster and we know the list of servers @ any given instance. We trigger set of curl calls of the APC delete component.

Title: Central + local cache with PHP


问:
Submitting iOS app to app store - internationalisation
I'm about to submit an app to app store. The app is in my native language (Persian) and it aims only at the persian speakers. I didn't go through using the process of internatiolization and stuff because it wouldn't make sense. However, when I entered iTunes Connect, I had to choose a language for it and Persian wasn't among the languages you could choose, so I chose English. The list of languages at iTunes Connect was quite small and did not cover more than 20 languages. Anyway, is that going to be problematic for my app? </p>

<p>I haven't submitted my app officially, I'm just going through the final steps and I'm anxious that it might cause a problem. </p>

答:
When you are trying to select Primary Language while creating New App in iTunes connect, probably you can the

Have you checked '?' - Question mark it contains one FAQ.

From Resources & Help section

Why am I not seeing my localization language listed as a selection for Primary Language?

If the localization has not been approved, you must submit a version with this localization to be approved by App Review before you can select it as your primary language.

If the screenshots for that localization are being derived from another localization’s screenshots, you must first manually add screenshots for the language you wish to be your primary. If the Ready for Sale version of your app is using screenshots from another language, you will need to submit an update to your app before you can select the new language.

Body:
I'm about to submit an app to app store. The app is in my native language (Persian) and it aims only at the persian speakers. I didn't go through using the process of internatiolization and stuff because it wouldn't make sense. However, when I entered iTunes Connect, I had to choose a language for it and Persian wasn't among the languages you could choose, so I chose English. The list of languages at iTunes Connect was quite small and did not cover more than 20 languages. Anyway, is that going to be problematic for my app?

I haven't submitted my app officially, I'm just going through the final steps and I'm anxious that it might cause a problem.


问:
parse regex fuzzy logic rules
There are some fuzzy logic string rules like:

IF Input1.A AND Input2.B Then Output1.A

IF Input1.A AND (NOT Input2.B) AND Input3.C Then Output1.A

I want to capture groups after AND and after Then.

and also capture (NOT Input2.B) with its parentheses.

and also after IF.

答:
Something like this pattern:

```<code>(?:IF|AND|THEN\s*)(?<token>.+?)(?=\s*(?:AND|THEN|$))
</code>```

"match a keyword, then reluctantly match anything, only up to the next AND/THEN/EOL"

and this will work in Python:

```<code>(?:IF|AND|THEN\s*)(?P<token>.+?)(?=\s*(?:AND|THEN|$))
</code>```

Title: parse regex fuzzy logic rules

Body:
Something like this pattern:

(?:IF|AND|THEN\s*)(?<token>.+?)(?=\s*(?:AND|THEN|$))

"match a keyword, then reluctantly match anything, only up to the next AND/THEN/EOL"

and this will work in Python:

(?:IF|AND|THEN\s*)(?P<token>.+?)(?=\s*(?:AND|THEN|$))


问:
WM_KEYDOWN repeat count?
The MSDN documentation says that the LParam first 15 bits is used for repeat count , but it says that it is not accumulative

Now unless i am missing something here, why does it call it a repeat count but says it is not accumulative?

This is an oxymoron statement? It says it does but it doesn't? Or am i missing something here?

I Actually tested it and masked it with bitwise operator to extract those first 15 bits with LParam&0xFFFFand no matter how much i hold down the key , this value remains as 1

Unless i am doing something wrong or missing something, i dont know what is the point of this counter which doesnt count? Or am i misunderstanding something and doing this the wrong way and there is something that needs to be done to use this

It would be much more effective and convenient to have this counter so that i dont have to run all this other code to count the repeat count for the keys pressed and held , so is it possible to be done using those first 15 bits? maybe increment those first 15 bits?

答:
Lets start at the documentation:

The repeat count for the current message. The value is the number of times the keystroke is autorepeated as a result of the user holding down the key.

This part is relatively straight forward. The repeat count field is the number of 'presses' the key had.

If the keystroke is held long enough, multiple messages are sent.

Multiple messages can be sent, depending on your message loop. Windows will keep sending you messages as long as the key is down, so you can keep processing repeats.

However, the repeat count is not cumulative.

The repeat count doesn't carry over between messages. In other words, each message represents the number of repeats since the last time you processed a WM_KEYDOWN message.

The reason you never see a repeat count above 1 is that you're processing window messages too quickly. You can see higher numbers by putting a delay into your WM_KEYDOWN message handler to allow more repeats to queue into the next message. (In C# here because there's less boilerplate code, but you should be able to translate it to whatever language you use.)

```<code>private const int WM_KEYDOWN = 0x0100;
protected override void WndProc(ref Message m)
{
    if (m.Msg == WM_KEYDOWN)
    {
        System.Threading.Thread.Sleep(1000);
        this.Text = $"Keydown Count: {m.LParam.ToInt32() & 0xFF}";
    }
    base.WndProc(ref m);
}
</code>```

Running this code, I see repeat counts near 20-30.

If you need the total number of repeats, you will need to keep a running tally from the first WM_KEYDOWN until the WM_KEYUP. The design is so that you can process the events as they come in. (Picture a text box:  responsiveness demands that you process the keys as they come in, rather than wait till the key is released.)

Title: WM_KEYDOWN repeat count?

Body:
Lets start at the documentation:

The repeat count for the current message. The value is the number of times the keystroke is autorepeated as a result of the user holding down the key.

This part is relatively straight forward. The repeat count field is the number of 'presses' the key had.

If the keystroke is held long enough, multiple messages are sent.

Multiple messages can be sent, depending on your message loop. Windows will keep sending you messages as long as the key is down, so you can keep processing repeats.

However, the repeat count is not cumulative.

The repeat count doesn't carry over between messages. In other words, each message represents the number of repeats since the last time you processed a WM_KEYDOWN message.

The reason you never see a repeat count above 1 is that you're processing window messages too quickly. You can see higher numbers by putting a delay into your WM_KEYDOWN message handler to allow more repeats to queue into the next message. (In C# here because there's less boilerplate code, but you should be able to translate it to whatever language you use.)

private const int WM_KEYDOWN = 0x0100;
protected override void WndProc(ref Message m)
{
    if (m.Msg == WM_KEYDOWN)
    {
        System.Threading.Thread.Sleep(1000);
        this.Text = $"Keydown Count: {m.LParam.ToInt32() & 0xFF}";
    }
    base.WndProc(ref m);
}

Running this code, I see repeat counts near 20-30.

If you need the total number of repeats, you will need to keep a running tally from the first WM_KEYDOWN until the WM_KEYUP. The design is so that you can process the events as they come in. (Picture a text box:  responsiveness demands that you process the keys as they come in, rather than wait till the key is released.)


问:
Passing data(value) of form field from one route to another in angular 2
I'm trying to pass data of a form in one component(view) to another component in another completely different component by routing to it but when i check my console in this view it just shows undefined(A method attached to the submit button logs prints out the data on the console). I click on a button which sends me to the second route but I am also using a data service to send the information in one of the form fields to another route.
Sender component

```<code>    import { Component, OnInit, Injectable} from '@angular/core';
    import { Router } from '@angular/router';
    import { Data }  from './data';

    @Component({
      selector: 'home-app',
      templateUrl: 'home.component.html',
      styles: [`
      i{color:white;margin-left:-90px;margin-top:2px;margin-right:12px;}
      .logo{margin-top:-10px;}
      #banner{margin:-18px;margin-top:-70px;transform:scaleY(0.85)}
      #btn{transform:scale(1.4)}
      #img{margin: 0; padding: 0;display: inline-block;vertical-align:top;}
      #imgcontainer p{ font-size: 32px; margin-left:-107px;}
      #imgcontainer{cursor:pointer}
      `],
    })
    @Injectable()
    export class HomeComponent implements OnInit{
       public userName;
       onSubmit(){
         console.log(this.userName);
         this.router.navigate(['/makeyourlist'])
       }
    public constructor(private router: Router,private userData: Data){
    this.userData.name = this.userName;
    }
     ngOnInit() { }
    }
</code>```

The service.ts code

```<code>    import { Injectable } from '@angular/core';
    @Injectable()
    export class Data{
       public name: any;
       public constructor() { }
    }
</code>```

The receiver component

```<code>            import { Component, OnInit } from '@angular/core';
            import { Router } from '@angular/router';
            // import { NameService } from './name.service';
            import { Data }  from './data';
            import { HomeComponent } from './home.component';

            @Component({
                selector: 'to-do',
                templateUrl: 'todo.component.html',
                styles: [`
                   .body{background-color: #F4F4F4}
                   i{color:black;}
                   .logo{margin-top:-10px; padding:0;margin:0}
                   #img{transform:scale(0.4);margin-left:0px;
                       padding:0;margin:0}
                   #side{background-color:grey;color:white;height:100%}
                   #i{font-size:20px;}

                `],

             })

             export class ToDoComponent implements OnInit{
                user(){
                    alert(this.userData.name);
                }
                public constructor(private userData:Data) {
                  console.log(this.userData.name);
                }
                ngOnInit() {}
             }
</code>```

答:
don't use decorator @Injectable() in components. It's only for services.

I see you're trying to share data between components using service.ts.

That's ok. It's "Shared service".

It well-described here

https://angular.io/guide/component-interaction#parent-and-children-communicate-via-a-service

Body:
I'm trying to pass data of a form in one component(view) to another component in another completely different component by routing to it but when i check my console in this view it just shows undefined(A method attached to the submit button logs prints out the data on the console). I click on a button which sends me to the second route but I am also using a data service to send the information in one of the form fields to another route.
Sender component

    import { Component, OnInit, Injectable} from '@angular/core';
    import { Router } from '@angular/router';
    import { Data }  from './data';

    @Component({
      selector: 'home-app',
      templateUrl: 'home.component.html',
      styles: [`
      i{color:white;margin-left:-90px;margin-top:2px;margin-right:12px;}
      .logo{margin-top:-10px;}
      #banner{margin:-18px;margin-top:-70px;transform:scaleY(0.85)}
      #btn{transform:scale(1.4)}
      #img{margin: 0; padding: 0;display: inline-block;vertical-align:top;}
      #imgcontainer p{ font-size: 32px; margin-left:-107px;}
      #imgcontainer{cursor:pointer}
      `],
    })
    @Injectable()
    export class HomeComponent implements OnInit{
       public userName;
       onSubmit(){
         console.log(this.userName);
         this.router.navigate(['/makeyourlist'])
       }
    public constructor(private router: Router,private userData: Data){
    this.userData.name = this.userName;
    }
     ngOnInit() { }
    }

The service.ts code

    import { Injectable } from '@angular/core';
    @Injectable()
    export class Data{
       public name: any;
       public constructor() { }
    }

The receiver component

            import { Component, OnInit } from '@angular/core';
            import { Router } from '@angular/router';
            // import { NameService } from './name.service';
            import { Data }  from './data';
            import { HomeComponent } from './home.component';

            @Component({
                selector: 'to-do',
                templateUrl: 'todo.component.html',
                styles: [`
                   .body{background-color: #F4F4F4}
                   i{color:black;}
                   .logo{margin-top:-10px; padding:0;margin:0}
                   #img{transform:scale(0.4);margin-left:0px;
                       padding:0;margin:0}
                   #side{background-color:grey;color:white;height:100%}
                   #i{font-size:20px;}

                `],

             })

             export class ToDoComponent implements OnInit{
                user(){
                    alert(this.userData.name);
                }
                public constructor(private userData:Data) {
                  console.log(this.userData.name);
                }
                ngOnInit() {}
             }


问:
Permission to provision new site collection through workflow
I am stuck onto a very strange situation.

I have a workflow that i use to provision new site on my web application. This workflow uses one custom workflow activity to provision the site using followoing statement.

---other code omited for clarity----

SPSiteCollection.Add()

This statement is throwing followign exception when my applicaiton pool account is not same as Central Admin applicaiton pool account.

Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))
  at
  Microsoft.SharePoint.SPGlobal.HandleUnauthorizedAccessException(UnauthorizedAccessException
  ex)     at
  Microsoft.SharePoint.Library.SPRequest.CreateSite(Guid
  gApplicationId, String bstrUrl, Int32
  lZone, Guid gSiteId, Guid gDatabaseId,
  String bstrDat

after a lot of googling and findings i have zeroed down to the Applicaiton Pool account permission.

The workflow code always runs under the System account (the applicaiton pool identity). In order to create new SharePoint site collection,  the application pool requires access to "SharePoint_Config" database.

When my web application is running under the applicaiton pool credential of Central Admin,  it has all the access to the configuration database.  But when i am running the under any other applicaiton pool identity which has less permission.  it throws exception, even if i give DBO permission to the applicaiton pool account in the Configuration database.

My applicaiton event log has following entry :-

Event Source: Windows SharePoint
  Services 3 Event Category: Database
  Event ID: 3760 Date:  2/3/2010
  Time:  2:36:16 AM User:  N/A
  Computer: SHAREPOINT20 Description:
  SQL Database 'SharePoint_Config' on
  SQL Server instance 'houspsr001' not
  found. Additional error information
  from SQL Server is included below.

Cannot open database
  "SharePoint_Config" requested by the
  login. The login failed. Login failed
  for user 'DOMAIN\WebAppPool'.

For more information, see Help and
  Support Center at
  http://go.microsoft.com/fwlink/events.asp.

My question is...is it mendatory to run such code under the applicaiton pool account of central admin.

Any workaround for this....?

My question

答:
As Im not allowed to comment on Sudhir's answer, Im posting my remark as an answer. I used basically the same code which Sudhir proposes as a solution. The impersonation works, but it has a security flaw. If you store your password as a plain text (managed) string it may be moved within memory and even stored to the hard disk because of paging. This makes it easy for aunothrized persons to spy your credentials.

It is therefor recommended to use SecureString for this purpose. How this can be used in conjunction with SecureString can be looked up on MSDN. The main difference to Sudhir's solution is to use a different overload of LogonUser, namely

```<code>[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern bool LogonUser(String username, String domain,
                                      IntPtr password, int logonType,
                                      int logonProvider, ref IntPtr token);
</code>```

and use it like this (this code is from MSDN):

```<code>// Marshal the SecureString to unmanaged memory.
passwordPtr = Marshal.SecureStringToGlobalAllocUnicode(pwdSecureString);

// Call LogonUser, passing the unmanaged (and decrypted) copy of
// the SecureString password.
returnValue = LogonUser(userName, domainName, passwordPtr,
                        LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
                        ref tokenHandle);

// Zero-out and free the unmanaged string reference.
Marshal.ZeroFreeGlobalAllocUnicode(passwordPtr);
</code>```

This way the password is only encrypted right before we use it to do the user login. Afterwards the plaintext password is freed from memory immediatelly.

Body:
As Im not allowed to comment on Sudhir's answer, Im posting my remark as an answer. I used basically the same code which Sudhir proposes as a solution. The impersonation works, but it has a security flaw. If you store your password as a plain text (managed) string it may be moved within memory and even stored to the hard disk because of paging. This makes it easy for aunothrized persons to spy your credentials.

It is therefor recommended to use SecureString for this purpose. How this can be used in conjunction with SecureString can be looked up on MSDN. The main difference to Sudhir's solution is to use a different overload of LogonUser, namely

[DllImport("advapi32.dll", SetLastError = true, CharSet = CharSet.Unicode)]
internal static extern bool LogonUser(String username, String domain,
                                      IntPtr password, int logonType,
                                      int logonProvider, ref IntPtr token);

and use it like this (this code is from MSDN):

// Marshal the SecureString to unmanaged memory.
passwordPtr = Marshal.SecureStringToGlobalAllocUnicode(pwdSecureString);

// Call LogonUser, passing the unmanaged (and decrypted) copy of
// the SecureString password.
returnValue = LogonUser(userName, domainName, passwordPtr,
                        LOGON32_LOGON_INTERACTIVE, LOGON32_PROVIDER_DEFAULT,
                        ref tokenHandle);

// Zero-out and free the unmanaged string reference.
Marshal.ZeroFreeGlobalAllocUnicode(passwordPtr);

This way the password is only encrypted right before we use it to do the user login. Afterwards the plaintext password is freed from memory immediatelly.


问:
remove emoticons in R using tm package
I'm using the tm package to clean up a Twitter Corpus. However, the package is unable to clean up emoticons.

Here's a replicated code:

```<code>July4th_clean <- tm_map(July4th_clean, content_transformer(tolower))
Error in FUN(content(x), ...) : invalid input 'RT ElleJohnson Love of country is encircling the globes ������������������ july4thweekend July4th FourthOfJuly IndependenceDay NotAvailableOnIn' in 'utf8towcs'
</code>```

Can someone point me in the right direction to remove the emoticons using the tm package?

Thank you,

Luis

答:
You can use gsub to get rid of all non-ASCII characters.

```<code>Texts = c("Let the stormy clouds chase, everyone from the place ☁  ♪ ♬",
    "See you soon brother ☮ ",
    "A boring old-fashioned message" )

gsub("[^\x01-\x7F]", "", Texts)
[1] "Let the stormy clouds chase, everyone from the place    "
[2] "See you soon brother  "
[3] "A boring old-fashioned message"
</code>```

Details:
You can specify character classes in regex's with [ ].  When the class description starts with ^ it means everything except these characters. Here, I have specified everything except characters 1-127, i.e. everything except standard ASCII and I have specified that they should be replaced with the empty string.

Title: remove emoticons in R using tm package

Body:
I'm using the tm package to clean up a Twitter Corpus. However, the package is unable to clean up emoticons.

Here's a replicated code:

July4th_clean <- tm_map(July4th_clean, content_transformer(tolower))
Error in FUN(content(x), ...) : invalid input 'RT ElleJohnson Love of country is encircling the globes ������������������ july4thweekend July4th FourthOfJuly IndependenceDay NotAvailableOnIn' in 'utf8towcs'

Can someone point me in the right direction to remove the emoticons using the tm package?

Thank you,

Luis

Body:
You can use gsub to get rid of all non-ASCII characters.

Texts = c("Let the stormy clouds chase, everyone from the place ☁  ♪ ♬",
    "See you soon brother ☮ ",
    "A boring old-fashioned message" )

gsub("[^\x01-\x7F]", "", Texts)
[1] "Let the stormy clouds chase, everyone from the place    "
[2] "See you soon brother  "
[3] "A boring old-fashioned message"

Details:
You can specify character classes in regex's with [ ].  When the class description starts with ^ it means everything except these characters. Here, I have specified everything except characters 1-127, i.e. everything except standard ASCII and I have specified that they should be replaced with the empty string.


问:
routing based on parameter value in camel context file
Hi I have a route which is

```<code><route id="invokeGetMortgageAccountDetails">
<from uri="direct:invokeGetMortgageAccountDetails" />
<removeHeaders pattern="operationNamespace" />
<setHeader headerName="operationName">
<constant>getMortgageDetailsRequest</constant>
</setHeader>
<to uri="cxf:bean:getBastionAcctDetailsClient" />
<removeHeaders pattern="*" />
</route>
</code>```

Now i want to change the 'to uri' if length of parameter account is equal to 8.

I am new to Apache camel and there is not very helpful information on internet.

I am using camel version 2.15 and i tried passing an extra property called length of account number in exchange and tried to match with value in route but it did not work.

Processor:

public void processMortgage(final Exchange exchange) throws
  ServiceException {        MessageContentsList messageContentsList =
  (MessageContentsList) exchange.getIn().getBody();         List
  paramsList = new ArrayList();         String systemID =
  messageContentsList.get(0).toString().trim();         String brandID =
  messageContentsList.get(1).toString().trim();         String account =
  messageContentsList.get(2).toString().trim();         String len =
  Integer.toString(account.length());               paramsList.add(Constants.HUB);
            paramsList.add(brandID.toUpperCase());          paramsList.add(account);
            exchange.setProperty(Constants.SystemID, systemID);
            exchange.setProperty(len, len);
            exchange.setProperty(Constants.ErrorCode, null);
            exchange.setProperty("mortgageAccountNumber",
  Integer.parseInt(account));                               }
        exchange.getIn().setBody(paramsList);           }

Route Config:

```<code><route id="invokeGetMortgageAccountDetails">
<from uri="direct:invokeGetMortgageAccountDetails" />           <removeHeaders pattern="operationNamespace" />
<setHeader headerName="operationName">
<constant>getMortgageDetailsRequest</constant>           </setHeader>            <choice>
                <when>
                    <simple>${body.len} == '8'</simple>
                    <to uri="cxf:bean:getPhoebusClient" />
                </when>
                <otherwise>
                    <to uri="cxf:bean:getBastionAcctDetailsClient" />
                </otherwise>
 </choice>
   <removeHeaders pattern="*" />
 </route>
</code>```

答:
If you are using Apache Camel version > 2.16 then you can use the

Dynamic To Endpoint

You will probably need to use Spring Expression Language to build your dynamic uri

Body:
Hi I have a route which is

<route id="invokeGetMortgageAccountDetails">
<from uri="direct:invokeGetMortgageAccountDetails" />
<removeHeaders pattern="operationNamespace" />
<setHeader headerName="operationName">
<constant>getMortgageDetailsRequest</constant>
</setHeader>
<to uri="cxf:bean:getBastionAcctDetailsClient" />
<removeHeaders pattern="*" />
</route>

Now i want to change the 'to uri' if length of parameter account is equal to 8.

I am new to Apache camel and there is not very helpful information on internet.

I am using camel version 2.15 and i tried passing an extra property called length of account number in exchange and tried to match with value in route but it did not work.

Processor:

public void processMortgage(final Exchange exchange) throws
  ServiceException {        MessageContentsList messageContentsList =
  (MessageContentsList) exchange.getIn().getBody();         List
  paramsList = new ArrayList();         String systemID =
  messageContentsList.get(0).toString().trim();         String brandID =
  messageContentsList.get(1).toString().trim();         String account =
  messageContentsList.get(2).toString().trim();         String len =
  Integer.toString(account.length());               paramsList.add(Constants.HUB);
            paramsList.add(brandID.toUpperCase());          paramsList.add(account);
            exchange.setProperty(Constants.SystemID, systemID);
            exchange.setProperty(len, len);
            exchange.setProperty(Constants.ErrorCode, null);
            exchange.setProperty("mortgageAccountNumber",
  Integer.parseInt(account));                               }
        exchange.getIn().setBody(paramsList);           }

Route Config:

<route id="invokeGetMortgageAccountDetails">
<from uri="direct:invokeGetMortgageAccountDetails" />           <removeHeaders pattern="operationNamespace" />
<setHeader headerName="operationName">
<constant>getMortgageDetailsRequest</constant>           </setHeader>            <choice>
                <when>
                    <simple>${body.len} == '8'</simple>
                    <to uri="cxf:bean:getPhoebusClient" />
                </when>
                <otherwise>
                    <to uri="cxf:bean:getBastionAcctDetailsClient" />
                </otherwise>
 </choice>
   <removeHeaders pattern="*" />
 </route>


问:
difference between bytebuffer.flip() and bytebuffer.rewind()
I am aware that flip() set the current buffer position to 0 and set the limit to the previous buffer position whereas rewind() just set the current buffer position to 0.

In the following code, either I use rewind() or flip() i get the same result.

```<code>byte b = 127;
bb.put(b);
bb.rewind();//or flip();

System.out.println(bb.get());
bb.rewind();// or flip();
System.out.println(bb.get());
</code>```

Could you provide me with a real example where the difference of these 2 methods really matters? Thanks in advance.

答:
From the source code, they are very similar. You can see the follow:

```<code>public final Buffer flip() {
    limit = position;
    position = 0;
    mark = -1;
    return this;
}

public final Buffer rewind() {
    position = 0;
    mark = -1;
    return this;
}
</code>```

So the difference is the flip set the limit to the position, while rewind not.
Consider you have allocated a buffer with 8 bytes, you have filled the buffer with 4 bytes, then the position is set to 3, just show as follow:

```<code>    [ 1  1  1  1  0  0  0  0]
               |           |
flip           limit       |
rewind                     limit
</code>```

So rewind just used limit has set appropriately.

Body:
I am aware that flip() set the current buffer position to 0 and set the limit to the previous buffer position whereas rewind() just set the current buffer position to 0.

In the following code, either I use rewind() or flip() i get the same result.

byte b = 127;
bb.put(b);
bb.rewind();//or flip();

System.out.println(bb.get());
bb.rewind();// or flip();
System.out.println(bb.get());

Could you provide me with a real example where the difference of these 2 methods really matters? Thanks in advance.

Body:
From the source code, they are very similar. You can see the follow:

public final Buffer flip() {
    limit = position;
    position = 0;
    mark = -1;
    return this;
}

public final Buffer rewind() {
    position = 0;
    mark = -1;
    return this;
}

So the difference is the flip set the limit to the position, while rewind not.
Consider you have allocated a buffer with 8 bytes, you have filled the buffer with 4 bytes, then the position is set to 3, just show as follow:

    [ 1  1  1  1  0  0  0  0]
               |           |
flip           limit       |
rewind                     limit

So rewind just used limit has set appropriately.


问:
How can I add a phone number to an existing contact via Intent?
I'm trying to mimic the native behaviour of adding a phone number to an existing contact. The native behaviour has the following steps:

Tapping on the "Add to a contact"/ "Update existing" opens the native contacts list Activity where the user has the option to choose a contact.

Tapping on a contact opens the native edit contact activity and adds the selected phone number as an alternative phone number field (i.e. work).

Can I achieve this using an intent?

Similarly, I'm adding a contact using an intent. Here is my code:

```<code>Intent intent = new Intent(Intent.ACTION_INSERT, ContactsContract.Contacts.CONTENT_URI);
intent.putExtra(ContactsContract.Intents.Insert.PHONE,phoneNumber);
intent.putExtra("finishActivityOnSaveCompleted", true);
dialog.dismiss();
context.startActivity(intent);
</code>```

答:
this is the way to do it:</p>

```<code>Intent i = new Intent(Intent.ACTION_INSERT_OR_EDIT);
i.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
i.putExtra(Insert.NAME, "TESTTEST");
i.putExtra(Insert.PHONE, "209384");
startActivity(i);
</code>```

Body:
I'm trying to mimic the native behaviour of adding a phone number to an existing contact. The native behaviour has the following steps:

Tapping on the "Add to a contact"/ "Update existing" opens the native contacts list Activity where the user has the option to choose a contact.

Tapping on a contact opens the native edit contact activity and adds the selected phone number as an alternative phone number field (i.e. work).

Can I achieve this using an intent?

Similarly, I'm adding a contact using an intent. Here is my code:

Intent intent = new Intent(Intent.ACTION_INSERT, ContactsContract.Contacts.CONTENT_URI);
intent.putExtra(ContactsContract.Intents.Insert.PHONE,phoneNumber);
intent.putExtra("finishActivityOnSaveCompleted", true);
dialog.dismiss();
context.startActivity(intent);

Body:
this is the way to do it:

Intent i = new Intent(Intent.ACTION_INSERT_OR_EDIT);
i.setType(ContactsContract.Contacts.CONTENT_ITEM_TYPE);
i.putExtra(Insert.NAME, "TESTTEST");
i.putExtra(Insert.PHONE, "209384");
startActivity(i);


问:
Linux GTK2/GTK3 recent files browser not showing recent shell created files
If a touch a new file or take a screenshot with scrot/escrotum, no "new files" are visible in GTK2/GTK3 file browser in the tab "Recent Files" (you can easily see an example of it in the CTRL+O window of browser like Firefox or Chrome.

What should I do to see my recently "hand" edited or created files to also be updated in the GTK Recent Files file browser?

Example:

```<code>$touch words.txt
$scrot image.jpg
</code>```

Both generated files will not be visible in the Recent Files GTK tab.

Thank you

答:
So based on my comment above, here's a small python script called recent that adds the files passed as arguments to the recent files. That could of course be improved to have better handling of URIs instead of assuming all files are local, clean the recent file list, remove specific entries, etc. It could also be rewritten in C to avoid running a full python interpreter just for that.

```<code>#! /usr/bin/env python

import os.path
import sys

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GObject, GLib

def main():
    recent_mgr = Gtk.RecentManager.get_default()
    for filename in sys.argv[1:]:
        uri = GLib.filename_to_uri(os.path.abspath(filename))
        recent_mgr.add_item(uri)

    GObject.idle_add(Gtk.main_quit)
    Gtk.main()

if __name__ == '__main__':
    main()
</code>```

Body:
If a touch a new file or take a screenshot with scrot/escrotum, no "new files" are visible in GTK2/GTK3 file browser in the tab "Recent Files" (you can easily see an example of it in the CTRL+O window of browser like Firefox or Chrome.

What should I do to see my recently "hand" edited or created files to also be updated in the GTK Recent Files file browser?

Example:

$touch words.txt
$scrot image.jpg

Both generated files will not be visible in the Recent Files GTK tab.

Thank you

Body:
So based on my comment above, here's a small python script called recent that adds the files passed as arguments to the recent files. That could of course be improved to have better handling of URIs instead of assuming all files are local, clean the recent file list, remove specific entries, etc. It could also be rewritten in C to avoid running a full python interpreter just for that.

#! /usr/bin/env python

import os.path
import sys

import gi
gi.require_version('Gtk', '3.0')
from gi.repository import Gtk, GObject, GLib

def main():
    recent_mgr = Gtk.RecentManager.get_default()
    for filename in sys.argv[1:]:
        uri = GLib.filename_to_uri(os.path.abspath(filename))
        recent_mgr.add_item(uri)

    GObject.idle_add(Gtk.main_quit)
    Gtk.main()

if __name__ == '__main__':
    main()


问:
Redirects to the page even if url is wrong
Hello I have a problem that in my opinion is linked to permalinks, but I'm not quite sure.

The problem is that my site does only care about the last part of the argument in the url.

For example https://apriori.photo/kontakty/price does not exist. But it 301 redirects to https://apriori.photo/arenda-fotostudii/price/

I tried deactivating all the plugins and setting a default wordpress theme, the problem stays.

My permalink structure is : /%category%/%postname%/

答:
WordPress has a feature where it automatically tries to redirect to a page which it deems to be 'the correct page' based on it's name. In your case, because the page ends with 'price', WP finds another page with a similar path and thinks it should redirect there.

To prevent this, you can disable the redirect using the following:

```<code>// In functions.php
remove_action('template_redirect', 'redirect_canonical');
</code>```

Body:
WordPress has a feature where it automatically tries to redirect to a page which it deems to be 'the correct page' based on it's name. In your case, because the page ends with 'price', WP finds another page with a similar path and thinks it should redirect there.

To prevent this, you can disable the redirect using the following:

// In functions.php
remove_action('template_redirect', 'redirect_canonical');


问:
Xvarnish (cachewall) with mod_pagespeed
There is an issue where I have a cpanel server with cachewall (Xvarnish used to be called) and mod_pagspeed installed.

Cachewall/Xvarnish has https support enabled.

The issue is that even though the header of the website is showing that both Cachewall and modpagespeed is running, I'm getting flooded with this in my apache error log:

```<code>[Mon Jul 03 20:45:49.060050 2017] [pagespeed:error] [pid 31223:tid 112490802050816] [mod_pagespeed 1.11.33.4-0 @31223] Serf status 120171(APR does not understand this error code) polling for 1 threaded fetches for 0.05 seconds
[Mon Jul 03 20:45:49.060071 2017] [pagespeed:error] [pid 31223:tid 112490802050816] [mod_pagespeed 1.11.33.4-0 @31223] Serf status 120171(APR does not understand this error code) polling for 1 threaded fetches for 0.05 seconds
[Mon Jul 03 20:45:49.910183 2017] [pagespeed:warn] [pid 31225:tid 112490799363840] [mod_pagespeed 1.11.33.4-0 @31225] Fetch timed out: https://www.example.com/wp-includes/js/jquery/jquery.js?ver=1.12.4 (connecting to:139.xx.xx.xx:82) (1) waiting for 50 ms
</code>```

Not sure whats going on here.

答:
I think you have to understand the cache flow when using both varnish and page_speed.

Please check the link bellow for details:
https://www.sonassi.com/help/troubleshooting/understanding-cache-flow-when-using-pagespeed-and-varnish

Clear all page_speed cache and varnish cache, then restart both varnish and apache.

Title: Xvarnish (cachewall) with mod_pagespeed

Body:
There is an issue where I have a cpanel server with cachewall (Xvarnish used to be called) and mod_pagspeed installed.

Cachewall/Xvarnish has https support enabled.

The issue is that even though the header of the website is showing that both Cachewall and modpagespeed is running, I'm getting flooded with this in my apache error log:

[Mon Jul 03 20:45:49.060050 2017] [pagespeed:error] [pid 31223:tid 112490802050816] [mod_pagespeed 1.11.33.4-0 @31223] Serf status 120171(APR does not understand this error code) polling for 1 threaded fetches for 0.05 seconds
[Mon Jul 03 20:45:49.060071 2017] [pagespeed:error] [pid 31223:tid 112490802050816] [mod_pagespeed 1.11.33.4-0 @31223] Serf status 120171(APR does not understand this error code) polling for 1 threaded fetches for 0.05 seconds
[Mon Jul 03 20:45:49.910183 2017] [pagespeed:warn] [pid 31225:tid 112490799363840] [mod_pagespeed 1.11.33.4-0 @31225] Fetch timed out: https://www.example.com/wp-includes/js/jquery/jquery.js?ver=1.12.4 (connecting to:139.xx.xx.xx:82) (1) waiting for 50 ms

Not sure whats going on here.


问:
Array Conversion To List Error
could someone explain to me what happens in the next lines of code and why it works?

```<code>Integer[] myray = {1,2,3,4,5};
List<Integer> l = new ArrayList<Integer>(Arrays.asList(myray));
l.add(6);
System.out.println(l);
</code>```

The code above works fine. It converts an array to a list and then adds another element.
But the following code dose  not work

```<code>Integer[] myray = {1,2,3,4,5};
List<Integer> l = (Arrays.asList(myray));
l.add(6);
System.out.println(l);
</code>```

The above code gives me the following error:
Exception in thread "main" java.lang.UnsupportedOperationException
Can someone please tell me the difference between the two conversions and why only the first one works??
Thanks in advance

答:
Arrays.asList(myray) returns a fixed sized List implementation (java.util.Arrays.ArrayList) backed by an array, so you can't add elements to it (or remove elements from it).

When you create a new java.util.ArrayList and pass to its constructor the fixed sized List you got from Arrays.asList (as you do in your first snippet), you get a normal java.util.ArrayList to which you can add elements.

Title: Array Conversion To List Error

Body:
could someone explain to me what happens in the next lines of code and why it works?

Integer[] myray = {1,2,3,4,5};
List<Integer> l = new ArrayList<Integer>(Arrays.asList(myray));
l.add(6);
System.out.println(l);

The code above works fine. It converts an array to a list and then adds another element.
But the following code dose  not work

Integer[] myray = {1,2,3,4,5};
List<Integer> l = (Arrays.asList(myray));
l.add(6);
System.out.println(l);

The above code gives me the following error:
Exception in thread "main" java.lang.UnsupportedOperationException
Can someone please tell me the difference between the two conversions and why only the first one works??
Thanks in advance


问:
Keras model fit creating squares in Jupyter notebook output
I am using Keras 2.0.2 with TensorFlow as:

I am running a simple model:

```<code>from keras.layers.core import Lambda, Flatten, Dense
from keras.models import Sequential
from keras.optimizers import Adam

model = Sequential([
    Lambda(norm_inp, input_shape=(1, 28, 28)),
    Flatten(),
    Dense(10, activation="softmax")
])

model.compile(optimizer=Adam(), loss='categorical_crossentropy', metrics=['accuracy'])

def run_fit(model, lr = 0.0001, epochs = 1):
    model.optimizer.lr = lr

    model.fit(x_train_processed, y_train_processed, epochs=epochs, verbose=1,
              validation_data=(x_test_processed, y_test_processed))

run_fit(model, 0.0001, 1)
</code>```

But when I am running this in Jupyter I am getting squares in the output.

I tried searching for this, but I couldn't find anything relevant.

答:
Try verbose=0 or verbose=2.

You also might want to use keras-tqdm: https://github.com/bstriner/keras-tqdm

Body:
I am using Keras 2.0.2 with TensorFlow as:

I am running a simple model:

from keras.layers.core import Lambda, Flatten, Dense
from keras.models import Sequential
from keras.optimizers import Adam

model = Sequential([
    Lambda(norm_inp, input_shape=(1, 28, 28)),
    Flatten(),
    Dense(10, activation="softmax")
])

model.compile(optimizer=Adam(), loss='categorical_crossentropy', metrics=['accuracy'])

def run_fit(model, lr = 0.0001, epochs = 1):
    model.optimizer.lr = lr

    model.fit(x_train_processed, y_train_processed, epochs=epochs, verbose=1,
              validation_data=(x_test_processed, y_test_processed))

run_fit(model, 0.0001, 1)

But when I am running this in Jupyter I am getting squares in the output.

I tried searching for this, but I couldn't find anything relevant.


问:
AttributeError: 'NoneType' object has no attribute 'decode'
```<code>names, plot_dicts = [], []
for repo_dict in repo_dicts:
    names.append(repo_dict['name'])
    plot_dict = {
        'value': repo_dict['stargazers_count'],
        'label': repo_dict['description'],
        'xlink': repo_dict['owner']['html_url'],
        }
    plot_dicts.append(plot_dict)

my_style = LS('#333366', base_style=LCS)
chart = pygal.Bar(style=my_style, x_label_rotation=45, show_legend=False)
chart.title = 'Most-Stared Python Project On Github'
chart.x_labels = names
chart.add('', plot_dicts)

chart.render_to_file('new_repos.svg')
</code>```

*If I run this, there will be an error.

```<code>Traceback (most recent call last):
  File "new_repos.py", line 54, in <module>
    chart.render_to_file('new_repos.svg')
  File "C:\Users\Cao Kangkang\AppData\Roaming\Python\Python36\site-packages\pygal\graph\public.py", line 114, in render_to_file
    f.write(self.render(is_unicode=True, **kwargs))
  File "C:\Users\Cao Kangkang\AppData\Roaming\Python\Python36\site-packages\pygal\graph\public.py", line 52, in render
    self.setup(**kwargs)
  File "C:\Users\Cao Kangkang\AppData\Roaming\Python\Python36\site-packages\pygal\graph\base.py", line 217, in setup
    self._draw()
  File "C:\Users\Cao Kangkang\AppData\Roaming\Python\Python36\site-packages\pygal\graph\graph.py", line 933, in _draw
    self._plot()
  File "C:\Users\Cao Kangkang\AppData\Roaming\Python\Python36\site-packages\pygal\graph\bar.py", line 146, in _plot
    self.bar(serie)
  File "C:\Users\Cao Kangkang\AppData\Roaming\Python\Python36\site-packages\pygal\graph\bar.py", line 116, in bar
    metadata)
  File "C:\Users\Cao Kangkang\AppData\Roaming\Python\Python36\site-packages\pygal\util.py", line 234, in decorate
    metadata['label'])
  File "C:\Users\Cao Kangkang\AppData\Roaming\Python\Python36\site-packages\pygal\_compat.py", line 62, in to_unicode
    return string.decode('utf-8')
AttributeError: 'NoneType' object has no attribute 'decode'
</code>```

*How ever if I change part of the code to this, the error will disappear, *however the description will be ignored in the chart.

```<code>names, plot_dicts = [], []
for repo_dict in repo_dicts:
    names.append(repo_dict['name'])
    plot_dict = {
        'value': repo_dict['stargazers_count'],
        #'label': repo_dict['description'],
        'xlink': repo_dict['owner']['html_url'],
        }
    plot_dicts.append(plot_dict)
</code>```

*I don't know why, Can anyone help me with this problem?

答:
May be the API didn't match the description, so you can use ifelse to solve it. Just like this.

```<code>description = repo_dict['description']
if not description:
    description = 'No description provided'

plot_dict = {
    'value': repo_dict['stargazers_count'],
    'label': description,
    'xlink': repo_dict['html_url'],
}
plot_dicts.append(plot_dict)`
</code>```

If the web API returns the value null, it means there's no result, so you can solve it with if statement. Maybe here, the items shadowsocks didn't return anything, so it maybe something went wrong.

Body:
names, plot_dicts = [], []
for repo_dict in repo_dicts:
    names.append(repo_dict['name'])
    plot_dict = {
        'value': repo_dict['stargazers_count'],
        'label': repo_dict['description'],
        'xlink': repo_dict['owner']['html_url'],
        }
    plot_dicts.append(plot_dict)

my_style = LS('#333366', base_style=LCS)
chart = pygal.Bar(style=my_style, x_label_rotation=45, show_legend=False)
chart.title = 'Most-Stared Python Project On Github'
chart.x_labels = names
chart.add('', plot_dicts)

chart.render_to_file('new_repos.svg')

*If I run this, there will be an error.

Traceback (most recent call last):
  File "new_repos.py", line 54, in <module>
    chart.render_to_file('new_repos.svg')
  File "C:\Users\Cao Kangkang\AppData\Roaming\Python\Python36\site-packages\pygal\graph\public.py", line 114, in render_to_file
    f.write(self.render(is_unicode=True, **kwargs))
  File "C:\Users\Cao Kangkang\AppData\Roaming\Python\Python36\site-packages\pygal\graph\public.py", line 52, in render
    self.setup(**kwargs)
  File "C:\Users\Cao Kangkang\AppData\Roaming\Python\Python36\site-packages\pygal\graph\base.py", line 217, in setup
    self._draw()
  File "C:\Users\Cao Kangkang\AppData\Roaming\Python\Python36\site-packages\pygal\graph\graph.py", line 933, in _draw
    self._plot()
  File "C:\Users\Cao Kangkang\AppData\Roaming\Python\Python36\site-packages\pygal\graph\bar.py", line 146, in _plot
    self.bar(serie)
  File "C:\Users\Cao Kangkang\AppData\Roaming\Python\Python36\site-packages\pygal\graph\bar.py", line 116, in bar
    metadata)
  File "C:\Users\Cao Kangkang\AppData\Roaming\Python\Python36\site-packages\pygal\util.py", line 234, in decorate
    metadata['label'])
  File "C:\Users\Cao Kangkang\AppData\Roaming\Python\Python36\site-packages\pygal\_compat.py", line 62, in to_unicode
    return string.decode('utf-8')
AttributeError: 'NoneType' object has no attribute 'decode'

*How ever if I change part of the code to this, the error will disappear, *however the description will be ignored in the chart.

names, plot_dicts = [], []
for repo_dict in repo_dicts:
    names.append(repo_dict['name'])
    plot_dict = {
        'value': repo_dict['stargazers_count'],
        #'label': repo_dict['description'],
        'xlink': repo_dict['owner']['html_url'],
        }
    plot_dicts.append(plot_dict)

*I don't know why, Can anyone help me with this problem?

Body:
May be the API didn't match the description, so you can use ifelse to solve it. Just like this.

description = repo_dict['description']
if not description:
    description = 'No description provided'

plot_dict = {
    'value': repo_dict['stargazers_count'],
    'label': description,
    'xlink': repo_dict['html_url'],
}
plot_dicts.append(plot_dict)`

If the web API returns the value null, it means there's no result, so you can solve it with if statement. Maybe here, the items shadowsocks didn't return anything, so it maybe something went wrong.


问:
Erasing a container element using iterators
My current homework assignment has me creating an iterator class for a list. I'm stuck at creating a good erase(iterator where) function.

Current code (reduced to fit question):

```<code>class List
{
    class _Iter
    {
        friend class List;
    public:
        _Iter(ListElem *pCurr, List *pList);

        /* *, ->, ++, --, == and != operators overloaded */

    private:
        ListElem *pCurr_; List *pList_;
    };

    typedef _Iter iterator;

    iterator erase(iterator where);
};
</code>```

with the erase being implemented like so:

```<code>// Precondition: List has been checked for size > 0.
List::iterator List::erase(List::iterator& where)
{
    // Erasing only element in list.
    if(where == end() && where == begin())
    {
        pop_back(); // or pop_front();
        return iterator(0, this);
    }

    // Elem at end
    if(where == end())
    {
        pop_back();
        return end();
    }
    else
    {
        // Elem at beginning
        if(where == begin())
        {
            pop_front();
            return ++begin();
        }
    }

    // Elem somewhere between beginning and end.
    iterator temp(where);
    // The node next to pCurr_ should point to the one before pCurr_
    where.pCurr_->next->prev = where.pCurr_->prev;
    // The node before pCurr_ should point to the one after pCurr_
    where.pCurr_->prev->next = where.pCurr_->next;
    // Return the node after pCurr_
    ++temp;
    delete where.pCurr_;
    --size_;
    return temp;
}
</code>```

The first three cases- only element, element at end and element at beginning- are all okay. Coded fine and need absolutely no knowledge and private access to _Iters members. However, if the element is not in those positions, then I have (seemingly) no choice but to violate the encapsulation and change pCurr_ (element of the list) directly.

Is there any way to avoid this? I looked inside the STL list, but they used some other functions _Next_Node_(/* stuff */) and _Prev_Node_(/* stuff */) that weren't very useful to me. Google searches give me helpful results on how to use the erase function, not how to write it myself.

Question:  Is there a way in which I can erase the element pointed to by my iterator without having to grab it's pCurr_ member?

答:
Do not use identifiers beginning with underscore followed by an uppercase letter. They are reserved for standard library and system writers. Although you are writing your own list class, you are not actually writing the standard library.

end() is normally one element past the end of the list, not the last element. (To get the actual last iterator of the list you can do l.rbegin().base() as it happens).

Pass the iterator by value, not non-const reference.

Why are you so concerned with modifying pCurr?

Body:
My current homework assignment has me creating an iterator class for a list. I'm stuck at creating a good erase(iterator where) function.

Current code (reduced to fit question):

class List
{
    class _Iter
    {
        friend class List;
    public:
        _Iter(ListElem *pCurr, List *pList);

        /* *, ->, ++, --, == and != operators overloaded */

    private:
        ListElem *pCurr_; List *pList_;
    };

    typedef _Iter iterator;

    iterator erase(iterator where);
};

with the erase being implemented like so:

// Precondition: List has been checked for size > 0.
List::iterator List::erase(List::iterator& where)
{
    // Erasing only element in list.
    if(where == end() && where == begin())
    {
        pop_back(); // or pop_front();
        return iterator(0, this);
    }

    // Elem at end
    if(where == end())
    {
        pop_back();
        return end();
    }
    else
    {
        // Elem at beginning
        if(where == begin())
        {
            pop_front();
            return ++begin();
        }
    }

    // Elem somewhere between beginning and end.
    iterator temp(where);
    // The node next to pCurr_ should point to the one before pCurr_
    where.pCurr_->next->prev = where.pCurr_->prev;
    // The node before pCurr_ should point to the one after pCurr_
    where.pCurr_->prev->next = where.pCurr_->next;
    // Return the node after pCurr_
    ++temp;
    delete where.pCurr_;
    --size_;
    return temp;
}

The first three cases- only element, element at end and element at beginning- are all okay. Coded fine and need absolutely no knowledge and private access to _Iters members. However, if the element is not in those positions, then I have (seemingly) no choice but to violate the encapsulation and change pCurr_ (element of the list) directly.

Is there any way to avoid this? I looked inside the STL list, but they used some other functions _Next_Node_(/* stuff */) and _Prev_Node_(/* stuff */) that weren't very useful to me. Google searches give me helpful results on how to use the erase function, not how to write it myself.

Question:  Is there a way in which I can erase the element pointed to by my iterator without having to grab it's pCurr_ member?