问:
Getting lat lon from geocodefarm using php
This is the endpoint - https://www.geocode.farm/v3/json/forward/?addr=WC2H%208LG&country=uk&lang=en&count=1

I want extract lat and lon from the json output using php.

```<code><?php
$url = "https://www.geocode.farm/v3/json/forward/?addr=WC2H%208LG&country=uk&lang=en&count=1";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT, 4);
$json = curl_exec($ch);
if(!$json) {
    echo curl_error($ch);
}
curl_close($ch);
$data = json_decode($json,true);
$results = $data['geocoding_results']['RESULTS'];
$data = $results->COORDINATES->Latitude[0];
print_r ($data);
?>
</code>```

I am getting a

Notice: "Trying to get property of non-object in" error

$result outputs the array.
The error is at getting the latitude off the array.

答:
I have test according to your output. </p>

```<code>$json =

'    { "geocoding_results": { "LEGAL_COPYRIGHT": { "copyright_notice": "Copyright (c) 2017 Geocode.Farm - All Rights Reserved.", "copyright_logo": "https:\/\/www.geocode.farm\/images\/logo.png", "terms_of_service": "https:\/\/www.geocode.farm\/policies\/terms-of-service\/", "privacy_policy": "https:\/\/www.geocode.farm\/policies\/privacy-policy\/" }, "STATUS": { "access": "FREE_USER, ACCESS_GRANTED", "status": "SUCCESS", "address_provided": "WC2H 8LG", "result_count": 1 }, "ACCOUNT": { "ip_address": "217.70.180.226", "distribution_license": "NONE, UNLICENSED", "usage_limit": "250", "used_today": "9", "used_total": "9", "first_used": "06 Jul 2017" }, "RESULTS": [ { "result_number": 1, "formatted_address": "London WC2H 8LG, UK", "accuracy": "UNKNOWN_ACCURACY", "ADDRESS": { "admin_2": "Greater London", "admin_1": "England", "postal_code": "WC2H 8LG", "country": "United Kingdom" }, "LOCATION_DETAILS": { "elevation": "UNAVAILABLE", "timezone_long": "UNAVAILABLE", "timezone_short": "Europe\/London" }, "COORDINATES": { "latitude": "51.5153684402766", "longitude": "-0.12855210617794" }, "BOUNDARIES": { "northeast_latitude": "51.5153684402766", "northeast_longitude": "-0.12855210617794", "southwest_latitude": "51.5140174197844", "southwest_longitude": "-0.12981378029212" } } ], "STATISTICS": { "https_ssl": "ENABLED, SECURE" } } }';

$json = json_decode($json);
echo "```";
print_r($json->geocoding_results->RESULTS[0]->COORDINATES);
</code>```

<p>Output</p>

```<code>stdClass Object
(
    [latitude] => 51.5153684402766
    [longitude] => -0.12855210617794
)
</code>```

<p>For getting lat and long</p>

```<code>$json->geocoding_results->RESULTS[0]->COORDINATES->latitude
$json->geocoding_results->RESULTS[0]->COORDINATES->longitude
</code>```

Body:
This is the endpoint - https://www.geocode.farm/v3/json/forward/?addr=WC2H%208LG&country=uk&lang=en&count=1

I want extract lat and lon from the json output using php.

<?php
$url = "https://www.geocode.farm/v3/json/forward/?addr=WC2H%208LG&country=uk&lang=en&count=1";
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL,$url);
curl_setopt($ch,CURLOPT_RETURNTRANSFER,1);
curl_setopt($ch,CURLOPT_CONNECTTIMEOUT, 4);
$json = curl_exec($ch);
if(!$json) {
    echo curl_error($ch);
}
curl_close($ch);
$data = json_decode($json,true);
$results = $data['geocoding_results']['RESULTS'];
$data = $results->COORDINATES->Latitude[0];
print_r ($data);
?>

I am getting a

Notice: "Trying to get property of non-object in" error

$result outputs the array.
The error is at getting the latitude off the array.

Body:
I have test according to your output.

$json =

'    { "geocoding_results": { "LEGAL_COPYRIGHT": { "copyright_notice": "Copyright (c) 2017 Geocode.Farm - All Rights Reserved.", "copyright_logo": "https:\/\/www.geocode.farm\/images\/logo.png", "terms_of_service": "https:\/\/www.geocode.farm\/policies\/terms-of-service\/", "privacy_policy": "https:\/\/www.geocode.farm\/policies\/privacy-policy\/" }, "STATUS": { "access": "FREE_USER, ACCESS_GRANTED", "status": "SUCCESS", "address_provided": "WC2H 8LG", "result_count": 1 }, "ACCOUNT": { "ip_address": "217.70.180.226", "distribution_license": "NONE, UNLICENSED", "usage_limit": "250", "used_today": "9", "used_total": "9", "first_used": "06 Jul 2017" }, "RESULTS": [ { "result_number": 1, "formatted_address": "London WC2H 8LG, UK", "accuracy": "UNKNOWN_ACCURACY", "ADDRESS": { "admin_2": "Greater London", "admin_1": "England", "postal_code": "WC2H 8LG", "country": "United Kingdom" }, "LOCATION_DETAILS": { "elevation": "UNAVAILABLE", "timezone_long": "UNAVAILABLE", "timezone_short": "Europe\/London" }, "COORDINATES": { "latitude": "51.5153684402766", "longitude": "-0.12855210617794" }, "BOUNDARIES": { "northeast_latitude": "51.5153684402766", "northeast_longitude": "-0.12855210617794", "southwest_latitude": "51.5140174197844", "southwest_longitude": "-0.12981378029212" } } ], "STATISTICS": { "https_ssl": "ENABLED, SECURE" } } }';

$json = json_decode($json);
echo "<pre>";
print_r($json->geocoding_results->RESULTS[0]->COORDINATES);

Output

stdClass Object
(
    [latitude] => 51.5153684402766
    [longitude] => -0.12855210617794
)

For getting lat and long

$json->geocoding_results->RESULTS[0]->COORDINATES->latitude
$json->geocoding_results->RESULTS[0]->COORDINATES->longitude


来源: stackexchange

问:
How to draw 2D matrix of squares on iOS?
What is the best way how to draw a matrix of squares on iOS using SpriteKit? I am complete iOS beginner and I'm not sure what is the correct approach.

I was thinking creating a sprite representing a picture of a square and than add that sprite several times to specific locations. The data in the matrix will change over time and I need to reflect that in what is being drawn on the screen, though the shape of the matrix will remain the same.

答:
update for Swift3 :</p>

```<code>func setupMap() {
    let tilesWide = 10
    let tilesTall = 10

    for i in 0..<tilesWide {
        for j in 0..<tilesTall {
            let tile = SKSpriteNode(color: SKColor.red, size: CGSize(width: 5, height: 5))
            tile.anchorPoint = .zero

            let x = CGFloat(i) * tile.size.width
            let y = CGFloat(j) * tile.size.height

            tile.position = CGPoint(x: x, y: y)
            self.addChild(tile)
        }
    }
}
</code>```

ContentLicense: CC BY-SA 3.0

Body:
update for Swift3 :

func setupMap() {
    let tilesWide = 10
    let tilesTall = 10

    for i in 0..<tilesWide {
        for j in 0..<tilesTall {
            let tile = SKSpriteNode(color: SKColor.red, size: CGSize(width: 5, height: 5))
            tile.anchorPoint = .zero

            let x = CGFloat(i) * tile.size.width
            let y = CGFloat(j) * tile.size.height

            tile.position = CGPoint(x: x, y: y)
            self.addChild(tile)
        }
    }
}


问:
C# SQL DataGridView change field before updating database
I have a WindowsForms app with a DataGridView bound to a SQL database. All columns except one ("ts_last_edit") are editable.
I want to update the "ts_last_edit" column only programmatically with the current DateTime every time someone changes some of the other columns AND saves the changes.
I tried this:

```<code>...
    this.MyTableAdapter.Adapter.RowUpdating += Adapter_RowUpdating;
...
private void Adapter_RowUpdating(object sender, SqlRowUpdatingEventArgs e)
{
  e.Row["ts_last_edit"]=DateTime.Now;
}
</code>```

But it did not work because e.Row is a read-only property apparently.

I tried changing the UPDATE SQL command and it works:

```<code>private void Adapter_RowUpdating(object sender, SqlRowUpdatingEventArgs e)
{
// pseudo code
string newSqlCommand= "STUFF CURRENT DATE AND TIME IN COLUMN ts_last_edit";
e.Command.CommandText = newSqlCommand;
}
</code>```

This works OK, but I was wondering if there is a better way to do it.
Thank you

答:
you need to merge changes back to dataset after updating the time</p>

```<code>private void brandBookBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
  this.Validate();
  var changes = dataSet1.GetChanges();
  if(changes!=null && changes.Tables["BrandBook"].Rows.Count>0)
  {
    foreach(row in changes.Tables["BrandBook"].Rows)
    {
      row["ts_last_edit"] = DateTime.Now;
    }
  }
  dataSet1.Merge(changes, false,System.Data.MissingSchemaAction.Add);
  this.brandBookBindingSource.EndEdit();
  this.tableAdapterManager.UpdateAll(this.dataSet1);
}
</code>```

Body:
I have a WindowsForms app with a DataGridView bound to a SQL database. All columns except one ("ts_last_edit") are editable.
I want to update the "ts_last_edit" column only programmatically with the current DateTime every time someone changes some of the other columns AND saves the changes.
I tried this:

...
    this.MyTableAdapter.Adapter.RowUpdating += Adapter_RowUpdating;
...
private void Adapter_RowUpdating(object sender, SqlRowUpdatingEventArgs e)
{
  e.Row["ts_last_edit"]=DateTime.Now;
}

But it did not work because e.Row is a read-only property apparently.

I tried changing the UPDATE SQL command and it works:

private void Adapter_RowUpdating(object sender, SqlRowUpdatingEventArgs e)
{
// pseudo code
string newSqlCommand= "STUFF CURRENT DATE AND TIME IN COLUMN ts_last_edit";
e.Command.CommandText = newSqlCommand;
}

This works OK, but I was wondering if there is a better way to do it.
Thank you

Body:
you need to merge changes back to dataset after updating the time

private void brandBookBindingNavigatorSaveItem_Click(object sender, EventArgs e)
{
  this.Validate();
  var changes = dataSet1.GetChanges();
  if(changes!=null && changes.Tables["BrandBook"].Rows.Count>0)
  {
    foreach(row in changes.Tables["BrandBook"].Rows)
    {
      row["ts_last_edit"] = DateTime.Now;
    }
  }
  dataSet1.Merge(changes, false,System.Data.MissingSchemaAction.Add);
  this.brandBookBindingSource.EndEdit();
  this.tableAdapterManager.UpdateAll(this.dataSet1);
}


问:
#springFormInput Sytex problem
#springFormInput("userForm.password" 'type="password"') is not working;

is it correct?

答:
Use #springFormPasswordInput("userForm.password" "")

(list of all macros)

ContentLicense: CC BY-SA 2.5

Title: #springFormInput Sytex problem


问:
Sorting data using array
This is my components.ts.
I want to write a fuction that sorts array by counts and i will use the sorted array datas in html to create a chart.</p>

```<code>import { Component } from '@angular/core';
@Component({
  selector: 'dashboard',
  styleUrls: ['./dashboard.scss'],
  templateUrl: './dashboard.html',
})
export class Dashboard {
  private data = [];
  constructor() {
    this.data = [{
      'maxTime': 30041,
      'minTime': 6453,
      'avgTime': 18949,
      'count': 4,
      'requestRouteTemplate': 'api/GetUserPostponesCountReport',
      'requestMethod': 'POST',
    },
  ...
  }
]
</code>```

答:
You can use sort function

```<code>this.data.sort(function(a,b){
    return a.count - b.count;
});
</code>```

For reference - sort

For tweaking- plunker

Title: Sorting data using array

Body:
This is my components.ts.
I want to write a fuction that sorts array by counts and i will use the sorted array datas in html to create a chart.

import { Component } from '@angular/core';
@Component({
  selector: 'dashboard',
  styleUrls: ['./dashboard.scss'],
  templateUrl: './dashboard.html',
})
export class Dashboard {
  private data = [];
  constructor() {
    this.data = [{
      'maxTime': 30041,
      'minTime': 6453,
      'avgTime': 18949,
      'count': 4,
      'requestRouteTemplate': 'api/GetUserPostponesCountReport',
      'requestMethod': 'POST',
    },
  ...
  }
]

Body:
You can use sort function

this.data.sort(function(a,b){
    return a.count - b.count;
});

For reference - sort

For tweaking- plunker


问:
TensorFlow while_loop converts variable to constant?
I'm trying to update a two dimensional tensor in a nested while_loop(). When passing the variable to the second loop however, I cannot updated it using tf.assign() as it throws this error:

```<code>ValueError: Sliced assignment is only supported for variables
</code>```

Somehow it works fine if I create the variable outside the while_loop and use it only in the first loop.

How can I modify my 2D tf variable in the second while loop?

(I'm using python 2.7 and TensorFlow 1.2)

My code:

```<code>import tensorflow as tf
import numpy as np

tf.reset_default_graph()

BATCH_SIZE = 10
LENGTH_MAX_OUTPUT = 31

it_batch_nr = tf.constant(0)
it_row_nr = tf.Variable(0, dtype=tf.int32)
it_col_nr = tf.constant(0)
cost = tf.constant(0)

it_batch_end = lambda it_batch_nr, cost: tf.less(it_batch_nr, BATCH_SIZE)
it_row_end = lambda it_row_nr, cost_matrix: tf.less(it_row_nr, LENGTH_MAX_OUTPUT+1)

def iterate_batch(it_batch_nr, cost):
    cost_matrix = tf.Variable(np.ones((LENGTH_MAX_OUTPUT+1, LENGTH_MAX_OUTPUT+1)), dtype=tf.float32)
    it_rows, cost_matrix = tf.while_loop(it_row_end, iterate_row, [it_row_nr, cost_matrix])
    cost = cost_matrix[0,0] # IS 1.0, SHOULD BE 100.0
    return tf.add(it_batch_nr,1), cost

def iterate_row(it_row_nr, cost_matrix):
    # THIS THROWS AN ERROR:
    cost_matrix[0,0].assign(100.0)
    return tf.add(it_row_nr,1), cost_matrix

it_batch = tf.while_loop(it_batch_end, iterate_batch, [it_batch_nr, cost])

sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
out = sess.run(it_batch)
print(out)
</code>```

答:
Got this to work, with @AlexandrePassos help, by placing the Variable outside the while_loop. However, I also had to force the execution of the commands using tf.control_dependencies() (as the operations are not directly used on the loop variable). The loop now looks like this:

```<code>cost_matrix = tf.Variable(np.ones((LENGTH_MAX_OUTPUT+1, LENGTH_MAX_OUTPUT+1)), dtype=tf.float32)

def iterate_batch(it_batch_nr, cost):
    it_rows = tf.while_loop(it_row_end, iterate_row, [it_row_nr])
    with tf.control_dependencies([it_rows]):
        cost = cost_matrix[0,0]
        return tf.add(it_batch_nr,1), cost

def iterate_row(it_row_nr):
    a = tf.assign(cost_matrix[0,0], 100.0)
    with tf.control_dependencies([a]):
        return tf.add(it_row_nr,1)
</code>```

Body:
I'm trying to update a two dimensional tensor in a nested while_loop(). When passing the variable to the second loop however, I cannot updated it using tf.assign() as it throws this error:

ValueError: Sliced assignment is only supported for variables

Somehow it works fine if I create the variable outside the while_loop and use it only in the first loop.

How can I modify my 2D tf variable in the second while loop?

(I'm using python 2.7 and TensorFlow 1.2)

My code:

import tensorflow as tf
import numpy as np

tf.reset_default_graph()

BATCH_SIZE = 10
LENGTH_MAX_OUTPUT = 31

it_batch_nr = tf.constant(0)
it_row_nr = tf.Variable(0, dtype=tf.int32)
it_col_nr = tf.constant(0)
cost = tf.constant(0)

it_batch_end = lambda it_batch_nr, cost: tf.less(it_batch_nr, BATCH_SIZE)
it_row_end = lambda it_row_nr, cost_matrix: tf.less(it_row_nr, LENGTH_MAX_OUTPUT+1)

def iterate_batch(it_batch_nr, cost):
    cost_matrix = tf.Variable(np.ones((LENGTH_MAX_OUTPUT+1, LENGTH_MAX_OUTPUT+1)), dtype=tf.float32)
    it_rows, cost_matrix = tf.while_loop(it_row_end, iterate_row, [it_row_nr, cost_matrix])
    cost = cost_matrix[0,0] # IS 1.0, SHOULD BE 100.0
    return tf.add(it_batch_nr,1), cost

def iterate_row(it_row_nr, cost_matrix):
    # THIS THROWS AN ERROR:
    cost_matrix[0,0].assign(100.0)
    return tf.add(it_row_nr,1), cost_matrix

it_batch = tf.while_loop(it_batch_end, iterate_batch, [it_batch_nr, cost])

sess = tf.InteractiveSession()
sess.run(tf.global_variables_initializer())
out = sess.run(it_batch)
print(out)

Body:
Got this to work, with @AlexandrePassos help, by placing the Variable outside the while_loop. However, I also had to force the execution of the commands using tf.control_dependencies() (as the operations are not directly used on the loop variable). The loop now looks like this:

cost_matrix = tf.Variable(np.ones((LENGTH_MAX_OUTPUT+1, LENGTH_MAX_OUTPUT+1)), dtype=tf.float32)

def iterate_batch(it_batch_nr, cost):
    it_rows = tf.while_loop(it_row_end, iterate_row, [it_row_nr])
    with tf.control_dependencies([it_rows]):
        cost = cost_matrix[0,0]
        return tf.add(it_batch_nr,1), cost

def iterate_row(it_row_nr):
    a = tf.assign(cost_matrix[0,0], 100.0)
    with tf.control_dependencies([a]):
        return tf.add(it_row_nr,1)


问:
Android fragment didn't show using recyclerview
I want to create navigation drawer using RecyclerView and use fragment. The menu on navigation drawer are using RecyclerView and when menu is clicked then change to selected fragment.

I have a problem when i click a menu but fragment didn't change

below is my MainActivity.java

```<code>   package com.ayotong.miranda;

import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

    //First We Declare Titles And Icons For Our Navigation Drawer List View
    //This Icons And Titles Are holded in an Array as you can see

    String TITLES[] = {"Home","Events","Mail","Shop"};
    int ICONS[] = {R.drawable.ic_home,R.drawable.ic_article,R.drawable.ic_stat,R.drawable.ic_about};

    //Similarly we Create a String Resource for the name and email in the header view
    //And we also create a int resource for profile picture in the header view

    String NAME = "Akash Bangad";
    String COND = "Healthy";
    int PROFILE = R.drawable.teh;
    int lastMenu = -1;

    private Toolbar toolbar;                              // Declaring the Toolbar Object

    RecyclerView mRecyclerView;                           // Declaring RecyclerView
    RecyclerView.Adapter mAdapter;                        // Declaring Adapter For Recycler View
    RecyclerView.LayoutManager mLayoutManager;            // Declaring Layout Manager as a linear layout manager
    DrawerLayout Drawer;                                  // Declaring DrawerLayout

    ActionBarDrawerToggle mDrawerToggle;                  // Declaring Action Bar Drawer Toggle

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

    /* Assinging the toolbar object ot the view
    and setting the the Action bar to our toolbar
     */
        toolbar = (Toolbar) findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle(null);

        mRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView); // Assigning the RecyclerView Object to the xml View

        mRecyclerView.setHasFixedSize(true);                            // Letting the system know that the list objects are of fixed size

        mAdapter = new MyAdapter(TITLES,ICONS,NAME,COND,PROFILE, this);

        mRecyclerView.setAdapter(mAdapter);                              // Setting the adapter to RecyclerView

        final GestureDetector mGestureDetector = new GestureDetector(MainActivity.this, new GestureDetector.SimpleOnGestureListener() {

            @Override public boolean onSingleTapUp(MotionEvent e) {
                return true;
            }

        });

        mRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
            @Override
            public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
                View child = recyclerView.findChildViewUnder(motionEvent.getX(),motionEvent.getY());

                if(child != null && mGestureDetector.onTouchEvent(motionEvent)){
                    Drawer.closeDrawers();
//                    Toast.makeText(MainActivity.this, "The Item Clicked is: " + recyclerView.getChildPosition(child), Toast.LENGTH_SHORT).show();

                    onTouchDrawer(recyclerView.getChildPosition(child));

                    return true;

                }

                return false;
            }

            @Override
            public void onTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {

            }
            @Override
            public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
            }
        });

        mLayoutManager = new LinearLayoutManager(this);                 // Creating a layout Manager

        mRecyclerView.setLayoutManager(mLayoutManager);                 // Setting the layout Manager

        Drawer = (DrawerLayout) findViewById(R.id.DrawerLayout);        // Drawer object Assigned to the view
        mDrawerToggle = new ActionBarDrawerToggle(this,Drawer,toolbar,R.string.openDrawer,R.string.closeDrawer){

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                // code here will execute once the drawer is opened( As I dont want anything happened whe drawer is
                // open I am not going to put anything here)
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                // Code here will execute once drawer is closed
            }

        }; // Drawer Toggle Object Made
        Drawer.setDrawerListener(mDrawerToggle); // Drawer Listener set to the Drawer toggle
        mDrawerToggle.syncState();               // Finally we set the drawer toggle sync State

    }

    private void openFragment(final Fragment fragment) {
        android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
        android.support.v4.app.FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.container,fragment);
        ft.commit();
    }

    public void onTouchDrawer(final int position) {

        if (lastMenu == position) return;

        switch (lastMenu = position) {
            case 1:
                openFragment(new Home_fragment());
                break;
            case 2:
                openFragment(new Stat_fragment());
                break;
            default:
                return;
        }
    }

}
</code>```

below is Main_activity.xml

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

<android.support.v4.widget.DrawerLayout

    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/DrawerLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:elevation="7dp">

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    tools:context=".MainActivity">

    <include
        android:id="@+id/tool_bar"
        layout="@layout/tool_bar"
        ></include>
    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </FrameLayout>

</LinearLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/RecyclerView"
        android:layout_width="230dp"
        android:layout_height="match_parent"
        android:layout_gravity="left"

        android:background="#ffffff"
        android:scrollbars="vertical">

    </android.support.v7.widget.RecyclerView>

</android.support.v4.widget.DrawerLayout>
</code>```

below is fragment_home.xml

```<code><?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="HOME MIRANDA"
        android:padding="8dp"
        android:textColor="#fff"
        android:background="@color/colorPrimary"
        android:textSize="28sp"
        android:id="@+id/textView"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

    <!--<android.support.v7.widget.RecyclerView-->
        <!--android:id="@+id/my_recycler_view"-->
        <!--android:scrollbars="vertical"-->
        <!--android:layout_width="match_parent"-->
        <!--android:layout_height="match_parent"/>-->

</RelativeLayout>
</code>```

below is fragment_home.java

```<code>package com.ayotong.miranda;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Home_fragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //returning our layout file
        //change R.layout.yourlayoutfilename for each of your fragments
        return inflater.inflate(R.layout.fragment_home, container, false);
    }
}
</code>```

Please help me to solve this so i can change fragment when menu on navigation drawer is clicked.

答: Try to call the openFragment() in the onItemTouchListener of the recycler view. Before loading the fragment try to close the drawer and then call the openFragment(). I think it should work. Also check whether the container id is correct.</p>

Body:
I want to create navigation drawer using RecyclerView and use fragment. The menu on navigation drawer are using RecyclerView and when menu is clicked then change to selected fragment.

I have a problem when i click a menu but fragment didn't change

below is my MainActivity.java

   package com.ayotong.miranda;

import android.content.Intent;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.widget.DrawerLayout;
import android.support.v7.app.ActionBarActivity;
import android.os.Bundle;
import android.support.v7.app.ActionBarDrawerToggle;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.support.v7.widget.Toolbar;
import android.view.GestureDetector;
import android.view.Menu;
import android.view.MenuItem;
import android.view.MotionEvent;
import android.view.View;
import android.widget.Toast;

public class MainActivity extends ActionBarActivity {

    //First We Declare Titles And Icons For Our Navigation Drawer List View
    //This Icons And Titles Are holded in an Array as you can see

    String TITLES[] = {"Home","Events","Mail","Shop"};
    int ICONS[] = {R.drawable.ic_home,R.drawable.ic_article,R.drawable.ic_stat,R.drawable.ic_about};

    //Similarly we Create a String Resource for the name and email in the header view
    //And we also create a int resource for profile picture in the header view

    String NAME = "Akash Bangad";
    String COND = "Healthy";
    int PROFILE = R.drawable.teh;
    int lastMenu = -1;

    private Toolbar toolbar;                              // Declaring the Toolbar Object

    RecyclerView mRecyclerView;                           // Declaring RecyclerView
    RecyclerView.Adapter mAdapter;                        // Declaring Adapter For Recycler View
    RecyclerView.LayoutManager mLayoutManager;            // Declaring Layout Manager as a linear layout manager
    DrawerLayout Drawer;                                  // Declaring DrawerLayout

    ActionBarDrawerToggle mDrawerToggle;                  // Declaring Action Bar Drawer Toggle

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main_activity);

    /* Assinging the toolbar object ot the view
    and setting the the Action bar to our toolbar
     */
        toolbar = (Toolbar) findViewById(R.id.tool_bar);
        setSupportActionBar(toolbar);
        getSupportActionBar().setTitle(null);

        mRecyclerView = (RecyclerView) findViewById(R.id.RecyclerView); // Assigning the RecyclerView Object to the xml View

        mRecyclerView.setHasFixedSize(true);                            // Letting the system know that the list objects are of fixed size

        mAdapter = new MyAdapter(TITLES,ICONS,NAME,COND,PROFILE, this);

        mRecyclerView.setAdapter(mAdapter);                              // Setting the adapter to RecyclerView

        final GestureDetector mGestureDetector = new GestureDetector(MainActivity.this, new GestureDetector.SimpleOnGestureListener() {

            @Override public boolean onSingleTapUp(MotionEvent e) {
                return true;
            }

        });

        mRecyclerView.addOnItemTouchListener(new RecyclerView.OnItemTouchListener() {
            @Override
            public boolean onInterceptTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {
                View child = recyclerView.findChildViewUnder(motionEvent.getX(),motionEvent.getY());

                if(child != null && mGestureDetector.onTouchEvent(motionEvent)){
                    Drawer.closeDrawers();
//                    Toast.makeText(MainActivity.this, "The Item Clicked is: " + recyclerView.getChildPosition(child), Toast.LENGTH_SHORT).show();

                    onTouchDrawer(recyclerView.getChildPosition(child));

                    return true;

                }

                return false;
            }

            @Override
            public void onTouchEvent(RecyclerView recyclerView, MotionEvent motionEvent) {

            }
            @Override
            public void onRequestDisallowInterceptTouchEvent(boolean disallowIntercept) {
            }
        });

        mLayoutManager = new LinearLayoutManager(this);                 // Creating a layout Manager

        mRecyclerView.setLayoutManager(mLayoutManager);                 // Setting the layout Manager

        Drawer = (DrawerLayout) findViewById(R.id.DrawerLayout);        // Drawer object Assigned to the view
        mDrawerToggle = new ActionBarDrawerToggle(this,Drawer,toolbar,R.string.openDrawer,R.string.closeDrawer){

            @Override
            public void onDrawerOpened(View drawerView) {
                super.onDrawerOpened(drawerView);
                // code here will execute once the drawer is opened( As I dont want anything happened whe drawer is
                // open I am not going to put anything here)
            }

            @Override
            public void onDrawerClosed(View drawerView) {
                super.onDrawerClosed(drawerView);
                // Code here will execute once drawer is closed
            }

        }; // Drawer Toggle Object Made
        Drawer.setDrawerListener(mDrawerToggle); // Drawer Listener set to the Drawer toggle
        mDrawerToggle.syncState();               // Finally we set the drawer toggle sync State

    }

    private void openFragment(final Fragment fragment) {
        android.support.v4.app.FragmentManager fm = getSupportFragmentManager();
        android.support.v4.app.FragmentTransaction ft = fm.beginTransaction();
        ft.replace(R.id.container,fragment);
        ft.commit();
    }

    public void onTouchDrawer(final int position) {

        if (lastMenu == position) return;

        switch (lastMenu = position) {
            case 1:
                openFragment(new Home_fragment());
                break;
            case 2:
                openFragment(new Stat_fragment());
                break;
            default:
                return;
        }
    }

}

below is Main_activity.xml

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

<android.support.v4.widget.DrawerLayout

    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/DrawerLayout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:elevation="7dp">

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"

    tools:context=".MainActivity">

    <include
        android:id="@+id/tool_bar"
        layout="@layout/tool_bar"
        ></include>
    <FrameLayout
        android:id="@+id/container"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </FrameLayout>

</LinearLayout>

    <android.support.v7.widget.RecyclerView
        android:id="@+id/RecyclerView"
        android:layout_width="230dp"
        android:layout_height="match_parent"
        android:layout_gravity="left"

        android:background="#ffffff"
        android:scrollbars="vertical">

    </android.support.v7.widget.RecyclerView>

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

below is fragment_home.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="HOME MIRANDA"
        android:padding="8dp"
        android:textColor="#fff"
        android:background="@color/colorPrimary"
        android:textSize="28sp"
        android:id="@+id/textView"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />

</RelativeLayout>

below is fragment_home.java

package com.ayotong.miranda;

import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Home_fragment extends Fragment {

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        //returning our layout file
        //change R.layout.yourlayoutfilename for each of your fragments
        return inflater.inflate(R.layout.fragment_home, container, false);
    }
}

Please help me to solve this so i can change fragment when menu on navigation drawer is clicked.


问:
Target server failed to respond exception with htmlunit and tor
I am using htmlunit to send request to a website and tor for anonimity. However I am getting

Target server failed to respond exception. I searched on google and found the following code.

```<code>HttpMethodRetryHandler myretryhandler = new HttpMethodRetryHandler() {
    public boolean retryMethod(
        final HttpMethod method,
        final IOException exception,
        int executionCount) {
        if (executionCount >= 5) {
            // Do not retry if over max retry count
            return false;
        }
        if (exception instanceof NoHttpResponseException) {
            // Retry if the server dropped connection on us
            return true;
        }
        if (!method.isRequestSent()) {
        // Retry if the request has not been sent fully or
        // if it's OK to retry methods that have been sent
        return true;
    }
    // otherwise do not retry
    return false;
    }
};

GetMethod httpget = new GetMethod("http://www.whatever.com/");
httpget.getParams().
setParameter(HttpMethodParams.RETRY_HANDLER, myretryhandler);
try {
    client.executeMethod(httpget);
    System.out.println(httpget.getStatusLine().toString());
} finally {
    httpget.releaseConnection();
}
</code>```

However I could not find how to do this in htmlunit. How can I achieve this?

答:
```<code>    final WebClient webClient = new WebClient(BrowserVersion.FIREFOX_45);
    webClient.getOptions().setTimeout(20000);
    webClient.getOptions().setThrowExceptionOnScriptError(false);
    webClient.getOptions().setThrowExceptionOnFailingStatusCode(false);
    webClient.getOptions().setCssEnabled(false);
    webClient.getOptions().setJavaScriptEnabled(true);
    webClient.getOptions().setUseInsecureSSL(true);
    webClient.getOptions().setRedirectEnabled(true);

    webClient.setConfirmHandler(new ConfirmHandler() {
        public boolean handleConfirm(Page page, String message) {
            return true;
        }
    });

    String binary = DatatypeConverter.printBase64Binary(auth.getBytes());
    webClient.addRequestHeader("Authorization", "Basic " + binary);

    //get General page
    final HtmlPage page = webClient.getPage("http://adress");
</code>```

Body:
I am using htmlunit to send request to a website and tor for anonimity. However I am getting

Target server failed to respond exception. I searched on google and found the following code.

HttpMethodRetryHandler myretryhandler = new HttpMethodRetryHandler() {
    public boolean retryMethod(
        final HttpMethod method,
        final IOException exception,
        int executionCount) {
        if (executionCount >= 5) {
            // Do not retry if over max retry count
            return false;
        }
        if (exception instanceof NoHttpResponseException) {
            // Retry if the server dropped connection on us
            return true;
        }
        if (!method.isRequestSent()) {
        // Retry if the request has not been sent fully or
        // if it's OK to retry methods that have been sent
        return true;
    }
    // otherwise do not retry
    return false;
    }
};

GetMethod httpget = new GetMethod("http://www.whatever.com/");
httpget.getParams().
setParameter(HttpMethodParams.RETRY_HANDLER, myretryhandler);
try {
    client.executeMethod(httpget);
    System.out.println(httpget.getStatusLine().toString());
} finally {
    httpget.releaseConnection();
}

However I could not find how to do this in htmlunit. How can I achieve this?


问:
is opening a web page in a new tab considered a popup?
When a website visitor clicks on a link, is opening that link contents in a new tab considered a popup? OR a popup must be in a new floating window?

And If this is not considered as popup, What about opening the link contents in a new tab + opening another URL in the original tab?

Example: what happens in coupons websites, when you click " show coupon ", you find a new tab opened showing the coupon, and the original tab redirects to another URL ( may be affiliate URL).

If this considered as popup, so why doesn't google chrome prevent it inspite of setting ( popup : not allowed )

答:
The term "popup" can mean any of the following depending on who you are talking to and the context:

A new window/tab

A new window of a specific size

A chunk of DOM added to the page which overlays other content

what happens in coupons websites, when you click " show coupon ", you
  find a new tab opened showing the coupon, and the original tab
  redirects to another URL ( may be affiliate URL).

If this considered as popup, so why doesn't google chrome prevent it
  inspite of setting ( popup : not allowed )

The rules for blocking new windows are quite complex, but the simplified version is:

You can open one new window with JS in response to the user doing something (usually a click).


问:
Flatten an irregular (arbitrarily nested) list of lists
Yes, I know this subject has been covered before:

Python idiom to chain (flatten) an infinite iterable of finite iterables?

Flattening a shallow list in Python

Comprehension for flattening a sequence of sequences?

How do I make a flat list out of a list of lists?

but as far as I know, all solutions, except for one, fail on a list like [[[1, 2, 3], [4, 5]], 6], where the desired output is [1, 2, 3, 4, 5, 6] (or perhaps even better, an iterator).

The only solution I saw that works for an arbitrary nesting is found in this question:

```<code>def flatten(x):
    result = []
    for el in x:
        if hasattr(el, "__iter__") and not isinstance(el, basestring):
            result.extend(flatten(el))
        else:
            result.append(el)
    return result
</code>```

Is this the best approach? Did I overlook something? Any problems?

答:
I'm new to python and come from a lisp background. This is what I came up with (check out the var names for lulz):

```<code>def flatten(lst):
    if lst:
        car,*cdr=lst
        if isinstance(car,(list,tuple)):
            if cdr: return flatten(car) + flatten(cdr)
            return flatten(car)
        if cdr: return [car] + flatten(cdr)
        return [car]
</code>```

Seems to work. Test:

```<code>flatten((1,2,3,(4,5,6,(7,8,(((1,2)))))))
</code>```

returns:

```<code>[1, 2, 3, 4, 5, 6, 7, 8, 1, 2]
</code>```

ContentLicense: CC BY-SA 4.0

Body:
Yes, I know this subject has been covered before:

Python idiom to chain (flatten) an infinite iterable of finite iterables?

Flattening a shallow list in Python

Comprehension for flattening a sequence of sequences?

How do I make a flat list out of a list of lists?

but as far as I know, all solutions, except for one, fail on a list like [[[1, 2, 3], [4, 5]], 6], where the desired output is [1, 2, 3, 4, 5, 6] (or perhaps even better, an iterator).

The only solution I saw that works for an arbitrary nesting is found in this question:

def flatten(x):
    result = []
    for el in x:
        if hasattr(el, "__iter__") and not isinstance(el, basestring):
            result.extend(flatten(el))
        else:
            result.append(el)
    return result

Is this the best approach? Did I overlook something? Any problems?

Body:
I'm new to python and come from a lisp background. This is what I came up with (check out the var names for lulz):

def flatten(lst):
    if lst:
        car,*cdr=lst
        if isinstance(car,(list,tuple)):
            if cdr: return flatten(car) + flatten(cdr)
            return flatten(car)
        if cdr: return [car] + flatten(cdr)
        return [car]

Seems to work. Test:

flatten((1,2,3,(4,5,6,(7,8,(((1,2)))))))

returns:

[1, 2, 3, 4, 5, 6, 7, 8, 1, 2]


问:
Issues when converting from Europe/London time to UTC
I am trying to convert a dateTime string from Europe/London time to UTC.

Googling tells me that UTC should be an hour behind Europe/London time but when I tried to write a unit test to verify this the time calculated results in the same epoch times. I also tried from another Timezone (Asia/Kolkata) and that works correctly. So I am quite confused and not sure what I'm doing wrong.

Here's the function I'm using (with a dateString of 2017-01-15 13:00:00 and both of the above mentioned timezones)

```<code>long getUTCTimeEpoch(final String dateString, @NonNull final String fromTimeZone) {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ROOT);
    formatter.setTimeZone(TimeZone.getTimeZone(fromTimeZone));
    try {
        Date inputTime = formatter.parse(dateString);
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(fromTimeZone));
        calendar.setTime(inputTime);
        Calendar utcCalendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
        utcCalendar.setTimeInMillis(calendar.getTimeInMillis());
        return utcCalendar.getTime().getTime();
    } catch (ParseException e) {
        return 0;
    }
}
</code>```

This works,

```<code>assertThat(getUTCTimeEpoch(timeString, "Asia/Kolkata"), is(1484465400000))
</code>```

and this fails,

```<code>assertThat(getUTCTimeEpoch(timeString, "Europe/London"), is(1484481600000))
</code>```

答:
2017-01-15 13:00:00 in London is also 2017-01-15 13:00:00 in UTC, because in January, London is not in Daylight Saving Time (DST) and its local time is the same as UTC. That's why you get the millis value 1484485200000.

UTC is one hour behind London only during DST, which normally occurs between March and October. If you use a date in July, for example, then there would be a 1-hour difference.

The millis value 1484481600000 is equivalent to 2017-01-15 12:00:00 (in both London and UTC). Just change the values accordingly and the test should pass.

Body:
I am trying to convert a dateTime string from Europe/London time to UTC.

Googling tells me that UTC should be an hour behind Europe/London time but when I tried to write a unit test to verify this the time calculated results in the same epoch times. I also tried from another Timezone (Asia/Kolkata) and that works correctly. So I am quite confused and not sure what I'm doing wrong.

Here's the function I'm using (with a dateString of 2017-01-15 13:00:00 and both of the above mentioned timezones)

long getUTCTimeEpoch(final String dateString, @NonNull final String fromTimeZone) {
    SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss", Locale.ROOT);
    formatter.setTimeZone(TimeZone.getTimeZone(fromTimeZone));
    try {
        Date inputTime = formatter.parse(dateString);
        Calendar calendar = Calendar.getInstance(TimeZone.getTimeZone(fromTimeZone));
        calendar.setTime(inputTime);
        Calendar utcCalendar = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
        utcCalendar.setTimeInMillis(calendar.getTimeInMillis());
        return utcCalendar.getTime().getTime();
    } catch (ParseException e) {
        return 0;
    }
}

This works,

assertThat(getUTCTimeEpoch(timeString, "Asia/Kolkata"), is(1484465400000))

and this fails,

assertThat(getUTCTimeEpoch(timeString, "Europe/London"), is(1484481600000))


答:
You are getting that error probably due to $data = $results->COORDINATES->Latitude[0];

That will not have any property when the address you have passed in url is not found by google and (and so lat long are not found) that object will be empty.

So you will try with another proper address, you will not get this error.

Title: Getting lat lon from geocodefarm using php


问:
How do you get CUDA cores count in jcuda?
How do I get the CUDA cores count in jcuda?

I've tried this but it doesn't produce the right output:

```<code>int cudacount = cudaDeviceAttr.cudaDevAttrMultiProcessorCount;
</code>```

It returns 16 but I have 1 Nvidia GPU with 640 cudacores.

The JavaDoc for the above property is available here.
Any help will be appreciated.

答:
It seems that this answer does almost exactly what you want. It's written in C, and the types are slightly different, so here's a Java version (it's hardly any different):

```<code>int getSPCount()
{
    final int mp    = cudaDeviceAttr.cudaDevAttrMultiProcessorCount;
    final int major = cudaDeviceAttr.cudaDevAttrComputeCapabilityMajor;
    final int minor = cudaDeviceAttr.cudaDevAttrComputeCapabilityMinor;

    switch (major)
    {
       case 2: // Fermi
           return (minor == 1) ? mp * 48 : mp * 32;
       case 3: // Kepler
           return mp * 192;
       case 5: // Maxwell
           return mp * 128;
       case 6: // Pascal
           if (minor == 1) {
               return mp * 128;
           }
           else if (minor == 0) {
               return mp * 64;
           }
    }
    throw new RuntimeException("Unknown device type");
}
</code>```

Use this function like so:

```<code>int cudacount = getSPCount();
</code>```

Body:
How do I get the CUDA cores count in jcuda?

I've tried this but it doesn't produce the right output:

int cudacount = cudaDeviceAttr.cudaDevAttrMultiProcessorCount;

It returns 16 but I have 1 Nvidia GPU with 640 cudacores.

The JavaDoc for the above property is available here.
Any help will be appreciated.

Body:
It seems that this answer does almost exactly what you want. It's written in C, and the types are slightly different, so here's a Java version (it's hardly any different):

int getSPCount()
{
    final int mp    = cudaDeviceAttr.cudaDevAttrMultiProcessorCount;
    final int major = cudaDeviceAttr.cudaDevAttrComputeCapabilityMajor;
    final int minor = cudaDeviceAttr.cudaDevAttrComputeCapabilityMinor;

    switch (major)
    {
       case 2: // Fermi
           return (minor == 1) ? mp * 48 : mp * 32;
       case 3: // Kepler
           return mp * 192;
       case 5: // Maxwell
           return mp * 128;
       case 6: // Pascal
           if (minor == 1) {
               return mp * 128;
           }
           else if (minor == 0) {
               return mp * 64;
           }
    }
    throw new RuntimeException("Unknown device type");
}

Use this function like so:

int cudacount = getSPCount();


问:
Change nltk.download() path directory from default ~/ntlk_data
I was trying to download/update python nltk packages on a computing server and it returned this [Errno 122] Disk quota exceeded: error.

Specifically:

```<code>[nltk_data] Downloading package stop words to /home/sh2264/nltk_data...
[nltk_data] Error downloading u'stopwords' from
[nltk_data] <https://raw.githubusercontent.com/nltk/nltk_data/gh-
[nltk_data] pages/packages/corpora/stopwords.zip>: [Errno 122]
[nltk_data] Disk quota exceeded:
[nltk_data] u'/home/sh2264/nltk_data/corpora/stopwords.zip
False
</code>```

How could I change the entire path for nltk packages, and what other changes should I make to ensure errorless loading of nltk?

答:
According to the documentation:

By default, packages are installed in either a system-wide directory (if Python has sufficient access to write to it); or in the current user’s home directory. However, the download_dir argument may be used to specify a different installation target, if desired.

To specify the download directory, use for example:

```<code>nltk.download('treebank', download_dir='/mnt/data/treebank')
</code>```

Body:
I was trying to download/update python nltk packages on a computing server and it returned this [Errno 122] Disk quota exceeded: error.

Specifically:

[nltk_data] Downloading package stop words to /home/sh2264/nltk_data...
[nltk_data] Error downloading u'stopwords' from
[nltk_data] <https://raw.githubusercontent.com/nltk/nltk_data/gh-
[nltk_data] pages/packages/corpora/stopwords.zip>: [Errno 122]
[nltk_data] Disk quota exceeded:
[nltk_data] u'/home/sh2264/nltk_data/corpora/stopwords.zip
False

How could I change the entire path for nltk packages, and what other changes should I make to ensure errorless loading of nltk?

Body:
According to the documentation:

By default, packages are installed in either a system-wide directory (if Python has sufficient access to write to it); or in the current user’s home directory. However, the download_dir argument may be used to specify a different installation target, if desired.

To specify the download directory, use for example:

nltk.download('treebank', download_dir='/mnt/data/treebank')


问:
Share project in Android Studio that has already been shared
I somehow imported an Android project to my Subversion SVN using an option "Import into Subversion" and "Checkout from Version Control". I realized that my import is not how I wanted. Probably I should have used "Share Project (Subversion)" in the first place, but now there's of course no "share" option anymore.

Is there any repository metadata that needs to be deleted on order to make "share" option available again?

Tried it with Settings -> Version Control and removed directory  but that didn't help.

答:
Is there any repository metadata that needs to be deleted on order to
  make "share" option available again?

Yes, there is. SVN places hidden .svn directory at the root of working copy. I guess that you should remove it and reopen the project to make 'Share' command available again. You could also checkout a new working copy of the imported/shared project.

Frankly speaking, those 'Import' and 'Share' commands in the IDE are kind of confusing. When you 'Import' a project, you simply add it to the remote SVN repository and commit this change. Importing does not make your local project a SVN working copy and does not enable any version-control capabilities. You should checkout a working copy of the project after importing it. On the other hand, when you 'Share' a project, you import it to remote Subversion repository and you also make your local copy to be SVN working copy enabling version-control capabilities.
Android Studio is based on IntelliJ IDEA. Therefore IDEA's documentation should also work for Android Studio. Read these help topics

Importing a Local Directory to Subversion Repository

Sharing Directory


问:
PhantomJS (Selenium) Cannot Load PDFs from direct urls
I was trying to save some PDF from a link via PhantomJS (selenium). So, I refered to this code that turns webpages to pdfs. and it worked just fine when I ran the exactly same code.

So, I have this pdf I wanted to save from a direct url and I tried that script... it didn't work. It just saves a PDF with 1 white page. That's all...

My Code :

```<code>from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

def execute(script, args):
    driver.execute('executePhantomScript', {'script': script, 'args' : args })

driver = webdriver.PhantomJS('phantomjs')

# hack while the python interface lags
driver.command_executor._commands['executePhantomScript'] = ('POST', '/session/$sessionId/phantom/execute')

driver.get('http://www.planetpublish.com/wp-content/uploads/2011/11/The_Scarlet_Letter_T.pdf')

try:
    WebDriverWait(driver, 40).until(EC.presence_of_element_located((By.ID, 'plugin')))
except Exception as TimeoutException:
    print("I waited for far too long and still couldn't fine the view.")
    pass

# set page format
# inside the execution script, webpage is "this"
pageFormat = '''this.paperSize = {format: "A4", orientation: "portrait" };'''
execute(pageFormat, [])

# render current page
render = '''this.render("test2.pdf")'''
execute(render, [])
</code>```

I'm not sure what's happening and why is it happening. Need some assistance.

EDIT: This is just the test PDF that I was trying to get via Selenium. There are some other PDFs which I need to get and that website is checking god-knows-what to decide whether it's a human or a bot. So, Selenium is the only way.

EDIT 2 : So, here's the website I was practicing on : http://services.ecourts.gov.in/ecourtindia/cases/case_no.php?state_cd=26&dist_cd=8&appFlag=web

Select "Cr Rev - Criminal Revision" from "Case Type" drop down and input any number in case number and year. Click on "Go".

This will show a little table, click on "view" and it should show a table on full page.

Scroll down to the "orders" table and you should see "Copy of order". That's the pdf I'm trying to get.I have tried requests as well and it did not work.

答:
If you're just looking at downloading PDFs which aren't protected behind some javascript or stuff (essentially straightforward stuff), I suggest using the requests library instead.

```<code>import requests
url ='http://www.planetpublish.com/wp-content/uploads/2011/11/The_Scarlet_Letter_T.pdf'
r = requests.get(url)

with open('The_Scarlet_Letter_T.pdf', 'wb') as f:
    f.write(r.content)

# If large file
with requests.get(url, stream=True) as r:
    with open('The_Scarlet_Letter_T.pdf', 'wb') as f:
        for chunk in r.iter_content(chunk_size=1024):
            if chunk:
                f.write(chunk)
</code>```

Body:
I was trying to save some PDF from a link via PhantomJS (selenium). So, I refered to this code that turns webpages to pdfs. and it worked just fine when I ran the exactly same code.

So, I have this pdf I wanted to save from a direct url and I tried that script... it didn't work. It just saves a PDF with 1 white page. That's all...

My Code :

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By

def execute(script, args):
    driver.execute('executePhantomScript', {'script': script, 'args' : args })

driver = webdriver.PhantomJS('phantomjs')

# hack while the python interface lags
driver.command_executor._commands['executePhantomScript'] = ('POST', '/session/$sessionId/phantom/execute')

driver.get('http://www.planetpublish.com/wp-content/uploads/2011/11/The_Scarlet_Letter_T.pdf')

try:
    WebDriverWait(driver, 40).until(EC.presence_of_element_located((By.ID, 'plugin')))
except Exception as TimeoutException:
    print("I waited for far too long and still couldn't fine the view.")
    pass

# set page format
# inside the execution script, webpage is "this"
pageFormat = '''this.paperSize = {format: "A4", orientation: "portrait" };'''
execute(pageFormat, [])

# render current page
render = '''this.render("test2.pdf")'''
execute(render, [])

I'm not sure what's happening and why is it happening. Need some assistance.

EDIT: This is just the test PDF that I was trying to get via Selenium. There are some other PDFs which I need to get and that website is checking god-knows-what to decide whether it's a human or a bot. So, Selenium is the only way.

EDIT 2 : So, here's the website I was practicing on : http://services.ecourts.gov.in/ecourtindia/cases/case_no.php?state_cd=26&dist_cd=8&appFlag=web

Select "Cr Rev - Criminal Revision" from "Case Type" drop down and input any number in case number and year. Click on "Go".

This will show a little table, click on "view" and it should show a table on full page.

Scroll down to the "orders" table and you should see "Copy of order". That's the pdf I'm trying to get.I have tried requests as well and it did not work.

Body:
If you're just looking at downloading PDFs which aren't protected behind some javascript or stuff (essentially straightforward stuff), I suggest using the requests library instead.

import requests
url ='http://www.planetpublish.com/wp-content/uploads/2011/11/The_Scarlet_Letter_T.pdf'
r = requests.get(url)

with open('The_Scarlet_Letter_T.pdf', 'wb') as f:
    f.write(r.content)

# If large file
with requests.get(url, stream=True) as r:
    with open('The_Scarlet_Letter_T.pdf', 'wb') as f:
        for chunk in r.iter_content(chunk_size=1024):
            if chunk:
                f.write(chunk)


问:
Javascript - Month Year range automatically on selectlist
I'm try to automacially create a select list that has the following:

```<code><select name="Range" id="ranges">
  <option value="July 2017">July 2017</option>
   <option value="June 2017">June 2017</option>
     <option value="May 2017">May 2017</option>
</code>```

all the way down to August 2015

```<code>     <option value="August 2015">August 2015</option>

</select>
</code>```

The first option must be the current Month and Year

is this possible to be automatically populated via javascript?

答:
My code, maybe it`s not very small and beautiful, but...)

let date = new Date();
let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

let currentYear = date.getFullYear();
let currentMonth = date.getMonth();

let lastYear = date.getFullYear() - 2;
let lastMonth = date.getMonth() + 1;

let objectOfDates = [];

for (let j = 0; j < months.length; j++) {
    objectOfDates.unshift(`${months[j]} ${currentYear - 1}`);
};

for (let i = 0; i <= currentMonth; i++) {
    objectOfDates.unshift(`${months[i]} ${currentYear}`);
};

for (let k = 11; k >= lastMonth; k--) {
    objectOfDates.push(`${months[k]} ${currentYear - 2}`);
};

let select = document.querySelector('select[name="Range"]');

objectOfDates.forEach(function(value){
    select.options.add(new Option(value, value));
});```
<pre class="snippet-code-html lang-html prettyprint-override"><code><select name="Range" id="ranges">
</select></code>```

Body:
I'm try to automacially create a select list that has the following:

<select name="Range" id="ranges">
  <option value="July 2017">July 2017</option>
   <option value="June 2017">June 2017</option>
     <option value="May 2017">May 2017</option>

all the way down to August 2015

     <option value="August 2015">August 2015</option>

</select>

The first option must be the current Month and Year

is this possible to be automatically populated via javascript?

Body:
My code, maybe it`s not very small and beautiful, but...)

let date = new Date();
let months = ["January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"];

let currentYear = date.getFullYear();
let currentMonth = date.getMonth();

let lastYear = date.getFullYear() - 2;
let lastMonth = date.getMonth() + 1;

let objectOfDates = [];

for (let j = 0; j < months.length; j++) {
    objectOfDates.unshift(`${months[j]} ${currentYear - 1}`);
};

for (let i = 0; i <= currentMonth; i++) {
    objectOfDates.unshift(`${months[i]} ${currentYear}`);
};

for (let k = 11; k >= lastMonth; k--) {
    objectOfDates.push(`${months[k]} ${currentYear - 2}`);
};

let select = document.querySelector('select[name="Range"]');

objectOfDates.forEach(function(value){
    select.options.add(new Option(value, value));
});

<select name="Range" id="ranges">
</select>


问:
Entity Framework: reload all child entities from query based on child entity attributes
Is there a way to elegantly load all child entities of an EF entity if the entity instance was loaded as the result of a query on child entity attributes?  Here is a simple example of what I'm asking:

First, some simple data tables:

```<code>CREATE TABLE Invoices
(
    InvoiceID int IDENTITY(1000,1) NOT NULL,
    Customer nvarchar(50) NOT NULL,
    InvoiceDate datetime NOT NULL,
    CONSTRAINT PK_Invoices PRIMARY KEY (InvoiceID)
)

CREATE TABLE InvoiceItems
(
    InvoiceItemID int IDENTITY(1,10) NOT NULL,
    InvoiceFK int NOT NULL,
    PurchasedItem varchar(24) NULL,
    Quantity decimal(10,2) NULL,
    ItemPrice money NULL,
    CONSTRAINT PK_InvoiceItems PRIMARY KEY (InvoiceItemID),
    CONSTRAINT FK_InvoiceItems_Invoice FOREIGN KEY (InvoiceFK)
        REFERENCES Invoices (InvoiceID)
)
</code>```

Now, what we want is to query the Invoice table based on a matching invoice item, but to then show all items for each selected invoice regardless of whether it matches the criteria:

```<code>var qryOrders = from ordr in ctx.InvoiceItems
                .Include("Invoice")
                where ordr.PurchasedItem == "Buggy Whips"
                select ordr;

foreach (var ordrItm in qryOrders)
{
    Console.WriteLine("Order " + ordrItm.Invoice.InvoiceID + " contains buggy whips");
    Console.WriteLine("Full contents of order:");

    foreach (var itm in ordrItm.Invoice.InvoiceItems)
    {
        //this will only show the buggy whip item
        Console.WriteLine(itm.PurchasedItem);
    }
}
</code>```

What I want is to show all order items in each order that contains "Buggy Whips", including items that are not buggy whips. If I were writing this in SQL, I would use a WHERE InvoiceID IN () clause with a subquery. My question is: can the Entity Framework make this happen in an elegant way? I've come up with some hacks that work, but nothing that feels right.

答:
Pretty confusing question - but i'll attempt to answer this statement:

What I want is to show all order items in each order that contains "Buggy Whips", including items that are not buggy whips.

I think you need to flip the InvoiceItems/Invoice around:

```<code>var query = ctx.Invoices.Include("InvoiceItems")
               .Where(x => x.InvoiceItems.Any(y => y.PurchasedItem == "Buggy Whips"))
               .Select(x => x.Invoices);
</code>```

That query will return a collection of Invoices, that have at least one purchased item of "Buggy Whips".

If you want to return a collection of Invoices where all of the purchased items are "Buggy Whips", replace .Any with .All.

Not sure if this is what your after.

A part that confuses me is this:

If I were writing this in SQL, I would use a WHERE InvoiceID IN () clause with a subquery

InvoiceID is on the Invoices table - but the item name (PurchasedItem) is on the InvoiceItems table - so how would that work?

Perhaps if you wrote an example SQL query we could help you convert it to LINQ-Entities.

Body:
Is there a way to elegantly load all child entities of an EF entity if the entity instance was loaded as the result of a query on child entity attributes?  Here is a simple example of what I'm asking:

First, some simple data tables:

CREATE TABLE Invoices
(
    InvoiceID int IDENTITY(1000,1) NOT NULL,
    Customer nvarchar(50) NOT NULL,
    InvoiceDate datetime NOT NULL,
    CONSTRAINT PK_Invoices PRIMARY KEY (InvoiceID)
)

CREATE TABLE InvoiceItems
(
    InvoiceItemID int IDENTITY(1,10) NOT NULL,
    InvoiceFK int NOT NULL,
    PurchasedItem varchar(24) NULL,
    Quantity decimal(10,2) NULL,
    ItemPrice money NULL,
    CONSTRAINT PK_InvoiceItems PRIMARY KEY (InvoiceItemID),
    CONSTRAINT FK_InvoiceItems_Invoice FOREIGN KEY (InvoiceFK)
        REFERENCES Invoices (InvoiceID)
)

Now, what we want is to query the Invoice table based on a matching invoice item, but to then show all items for each selected invoice regardless of whether it matches the criteria:

var qryOrders = from ordr in ctx.InvoiceItems
                .Include("Invoice")
                where ordr.PurchasedItem == "Buggy Whips"
                select ordr;

foreach (var ordrItm in qryOrders)
{
    Console.WriteLine("Order " + ordrItm.Invoice.InvoiceID + " contains buggy whips");
    Console.WriteLine("Full contents of order:");

    foreach (var itm in ordrItm.Invoice.InvoiceItems)
    {
        //this will only show the buggy whip item
        Console.WriteLine(itm.PurchasedItem);
    }
}

What I want is to show all order items in each order that contains "Buggy Whips", including items that are not buggy whips. If I were writing this in SQL, I would use a WHERE InvoiceID IN () clause with a subquery. My question is: can the Entity Framework make this happen in an elegant way? I've come up with some hacks that work, but nothing that feels right.

Body:
Pretty confusing question - but i'll attempt to answer this statement:

What I want is to show all order items in each order that contains "Buggy Whips", including items that are not buggy whips.

I think you need to flip the InvoiceItems/Invoice around:

var query = ctx.Invoices.Include("InvoiceItems")
               .Where(x => x.InvoiceItems.Any(y => y.PurchasedItem == "Buggy Whips"))
               .Select(x => x.Invoices);

That query will return a collection of Invoices, that have at least one purchased item of "Buggy Whips".

If you want to return a collection of Invoices where all of the purchased items are "Buggy Whips", replace .Any with .All.

Not sure if this is what your after.

A part that confuses me is this:

If I were writing this in SQL, I would use a WHERE InvoiceID IN () clause with a subquery

InvoiceID is on the Invoices table - but the item name (PurchasedItem) is on the InvoiceItems table - so how would that work?

Perhaps if you wrote an example SQL query we could help you convert it to LINQ-Entities.


问:
How to plot the sorted coefficients for a lm()/glm() regression model in R?
Let's say I were to execute a regression model in R:

```<code>library(data.table)
mtcars = as.data.table(mtcars)
dt = colSums(mtcars)

> dt
     mpg      cyl     disp       hp     drat       wt     qsec       vs
 642.900  198.000 7383.100 4694.000  115.090  102.952  571.160   14.000
      am     gear     carb
  13.000  118.000   90.000

model = lm(formula=mpg~cyl, data=dt)
</code>```

The way I would plot the coefficients of this model would be to use the following function, from Extract regression coefficient values

:

```<code>plot_coeffs <- function(mlr_model) {
  coeffs <- coefficients(mlr_model)
  mp <- barplot(coeffs, col="#3F97D0", xaxt='n', main="Regression Coefficients")
  lablist <- names(coeffs)
  text(mp, par("usr")[3], labels = lablist, srt = 45, adj = c(1.1,1.1), xpd = TRUE, cex=0.6)
}
</code>```

plot_coeffs(model)

However, this plot will not plot the coefficients in a sorted manner, e.g. greatest to least in descending order.

I have tried using order(coeffs) in the above function, but this doesn't seem to work. How does one easily plot the coefficients in decreasing order?

答:
You can also adapt your function to sort the coefficients:</p>

```<code>plot_coeffs_S <- function(mlr_model) {
  coeffs <- sort(coefficients(mlr_model), decreasing = TRUE)  ### changed
  mp <- barplot(coeffs, col="#3F97D0", xaxt='n', main="Regression Coefficients")
  lablist <- names(coeffs)
  text(mp, par("usr")[3], labels = lablist, srt = 45, adj = c(1.1,1.1), xpd = TRUE, cex=0.6)
}
</code>```

Body:
Let's say I were to execute a regression model in R:

library(data.table)
mtcars = as.data.table(mtcars)
dt = colSums(mtcars)

> dt
     mpg      cyl     disp       hp     drat       wt     qsec       vs
 642.900  198.000 7383.100 4694.000  115.090  102.952  571.160   14.000
      am     gear     carb
  13.000  118.000   90.000

model = lm(formula=mpg~cyl, data=dt)

The way I would plot the coefficients of this model would be to use the following function, from Extract regression coefficient values

:

plot_coeffs <- function(mlr_model) {
  coeffs <- coefficients(mlr_model)
  mp <- barplot(coeffs, col="#3F97D0", xaxt='n', main="Regression Coefficients")
  lablist <- names(coeffs)
  text(mp, par("usr")[3], labels = lablist, srt = 45, adj = c(1.1,1.1), xpd = TRUE, cex=0.6)
}

plot_coeffs(model)

However, this plot will not plot the coefficients in a sorted manner, e.g. greatest to least in descending order.

I have tried using order(coeffs) in the above function, but this doesn't seem to work. How does one easily plot the coefficients in decreasing order?

Body:
You can also adapt your function to sort the coefficients:

plot_coeffs_S <- function(mlr_model) {
  coeffs <- sort(coefficients(mlr_model), decreasing = TRUE)  ### changed
  mp <- barplot(coeffs, col="#3F97D0", xaxt='n', main="Regression Coefficients")
  lablist <- names(coeffs)
  text(mp, par("usr")[3], labels = lablist, srt = 45, adj = c(1.1,1.1), xpd = TRUE, cex=0.6)
}


问:
pyparsing partial match or recursion limit hit
Using pyparsing, I seem to be having trouble understanding why my grammar either matches partially or hits a recursion limit.

```<code>lparens = Suppress("(")
rparens = Suppress(")")
name = Word(alphanums, exact=1)
expression = Forward()
function = Group(Literal("λ") + OneOrMore(name) + Literal(".").suppress() + expression)
application = Group(expression + expression) #<-- the problem *I think*
exp1 = ( name | function | application )
exp2 = (lparens + exp1 + rparens) | exp1
expression << exp2
</code>```

So the following will parse but only picks up the "a" and does not apply the application step:

```<code>expression.parseString("ab") #result is: (['a'], {})
expression.parseString("(ab)") #result is: exception - recursion limit reached.
</code>```

In the first example why did it stop at 'a' and not apply the application step and run into the same infinite look it does in the second example?

In the second example it matches '(' and so it needs the ')' to finish the exp1. So it should parse the name 'a' and since there is no following ')' it should abandon that and try function (which fails) and then move on to application. Then it parses name 'a' (first match) and should move on to name 'b' completing the name, the application, and then match ')' to complete the exp1 and the expression.

Obviously this is not what happens.

edit: forgot to add the following works:

```<code>expression.parseString("((λa.a)(λa.a))")
</code>```

` #result: ([([(['λ', 'a', 'a'], {}), (['λ', 'a', 'a'], {})], {})], {})

adding setDebug() and setName() to the various elements and parsing '(ab)' yields:

```<code>Match expression at loc 0(1,1)
Match exp2 at loc 0(1,1)
Match lparens at loc 0(1,1)
Matched lparens -> []
Match exp1 at loc 1(1,2)
Match name at loc 1(1,2)
Matched name -> ['a']
Matched exp1 -> ['a']
Match rparens at loc 2(1,3)
Exception raised:Expected ")" (at char 2), (line:1, col:3)
Match name at loc 0(1,1)
Exception raised:Expected name (at char 0), (line:1, col:1)
Match function at loc 0(1,1)
Exception raised:Expected "λ" (at char 0), (line:1, col:1)
Match application at loc 0(1,1)
Match expression at loc 0(1,1)
Match exp2 at loc 0(1,1)
Match lparens at loc 0(1,1)
Matched lparens -> []
Match exp1 at loc 1(1,2)
Match name at loc 1(1,2)
Matched name -> ['a']
Matched exp1 -> ['a']
Match rparens at loc 2(1,3)
Exception raised:Expected ")" (at char 2), (line:1, col:3)
Match name at loc 0(1,1)
Exception raised:Expected name (at char 0), (line:1, col:1)
Match function at loc 0(1,1)
Exception raised:Expected "λ" (at char 0), (line:1, col:1)
Match application at loc 0(1,1)
Match expression at loc 0(1,1)
Match exp2 at loc 0(1,1)
Match lparens at loc 0(1,1)
Matched lparens -> []
Match exp1 at loc 1(1,2)
Match name at loc 1(1,2)
... etc etc etc...
</code>```

答:
In order to understand why your grammar doesn't get the job done, you first have to understand how pyparsing works. You seem to believe that pyparsing explores all possible paths until it finds one that correctly represents the entire input string. This is incorrect. See the following example:

```<code>exp1 = ( name | function | application )
exp1.parseString("ab") # outputs ['a']
</code>```

Here, "a" is a valid name and therefore a valid exp1. And that's the result you get. Pyparsing doesn't care about the extra "b". It found a match for exp1, so that's where it stops.

As for the infinite recursion, the problem is this:

```<code>application = Group(expression + expression)
exp1 = ( name | function | application )
exp2 = (lparens + exp1 + rparens) | exp1
expression << exp2
</code>```

This means that application is a valid exp1, which in turn is a valid exp2, which is a valid expression. This is a problem because application is made of expressions. So when pyparsing tries to parse an expression that's an application, it then has to parse another expression within the first one. This then continues infinitely.

Step by step, here's what happens when we call expression.parseString("(ab)") :

apply rule expression:

apply left side of rule exp2 (lparens + exp1 + rparens):

( matches lparens

a matches name

b doesn't match rparens -> abort

apply right side of rule exp2 (exp1):

apply first option in ( name | function | application ) (name):

( doesn't match name -> abort

apply 2nd option (function):

( doesn't match λ -> abort

apply 3rd option (application):

apply rule application (expression + expression):

apply rule expression:

go to start

See Paul McG's answer for a working implementation.

Body:
Using pyparsing, I seem to be having trouble understanding why my grammar either matches partially or hits a recursion limit.

lparens = Suppress("(")
rparens = Suppress(")")
name = Word(alphanums, exact=1)
expression = Forward()
function = Group(Literal("λ") + OneOrMore(name) + Literal(".").suppress() + expression)
application = Group(expression + expression) #<-- the problem *I think*
exp1 = ( name | function | application )
exp2 = (lparens + exp1 + rparens) | exp1
expression << exp2

So the following will parse but only picks up the "a" and does not apply the application step:

expression.parseString("ab") #result is: (['a'], {})
expression.parseString("(ab)") #result is: exception - recursion limit reached.

In the first example why did it stop at 'a' and not apply the application step and run into the same infinite look it does in the second example?

In the second example it matches '(' and so it needs the ')' to finish the exp1. So it should parse the name 'a' and since there is no following ')' it should abandon that and try function (which fails) and then move on to application. Then it parses name 'a' (first match) and should move on to name 'b' completing the name, the application, and then match ')' to complete the exp1 and the expression.

Obviously this is not what happens.

edit: forgot to add the following works:

expression.parseString("((λa.a)(λa.a))")

` #result: ([([(['λ', 'a', 'a'], {}), (['λ', 'a', 'a'], {})], {})], {})

adding setDebug() and setName() to the various elements and parsing '(ab)' yields:

Match expression at loc 0(1,1)
Match exp2 at loc 0(1,1)
Match lparens at loc 0(1,1)
Matched lparens -> []
Match exp1 at loc 1(1,2)
Match name at loc 1(1,2)
Matched name -> ['a']
Matched exp1 -> ['a']
Match rparens at loc 2(1,3)
Exception raised:Expected ")" (at char 2), (line:1, col:3)
Match name at loc 0(1,1)
Exception raised:Expected name (at char 0), (line:1, col:1)
Match function at loc 0(1,1)
Exception raised:Expected "λ" (at char 0), (line:1, col:1)
Match application at loc 0(1,1)
Match expression at loc 0(1,1)
Match exp2 at loc 0(1,1)
Match lparens at loc 0(1,1)
Matched lparens -> []
Match exp1 at loc 1(1,2)
Match name at loc 1(1,2)
Matched name -> ['a']
Matched exp1 -> ['a']
Match rparens at loc 2(1,3)
Exception raised:Expected ")" (at char 2), (line:1, col:3)
Match name at loc 0(1,1)
Exception raised:Expected name (at char 0), (line:1, col:1)
Match function at loc 0(1,1)
Exception raised:Expected "λ" (at char 0), (line:1, col:1)
Match application at loc 0(1,1)
Match expression at loc 0(1,1)
Match exp2 at loc 0(1,1)
Match lparens at loc 0(1,1)
Matched lparens -> []
Match exp1 at loc 1(1,2)
Match name at loc 1(1,2)
... etc etc etc...

Body:
In order to understand why your grammar doesn't get the job done, you first have to understand how pyparsing works. You seem to believe that pyparsing explores all possible paths until it finds one that correctly represents the entire input string. This is incorrect. See the following example:

exp1 = ( name | function | application )
exp1.parseString("ab") # outputs ['a']

Here, "a" is a valid name and therefore a valid exp1. And that's the result you get. Pyparsing doesn't care about the extra "b". It found a match for exp1, so that's where it stops.

As for the infinite recursion, the problem is this:

application = Group(expression + expression)
exp1 = ( name | function | application )
exp2 = (lparens + exp1 + rparens) | exp1
expression << exp2

This means that application is a valid exp1, which in turn is a valid exp2, which is a valid expression. This is a problem because application is made of expressions. So when pyparsing tries to parse an expression that's an application, it then has to parse another expression within the first one. This then continues infinitely.

Step by step, here's what happens when we call expression.parseString("(ab)") :

apply rule expression:

apply left side of rule exp2 (lparens + exp1 + rparens):

( matches lparens

a matches name

b doesn't match rparens -> abort

apply right side of rule exp2 (exp1):

apply first option in ( name | function | application ) (name):

( doesn't match name -> abort

apply 2nd option (function):

( doesn't match λ -> abort

apply 3rd option (application):

apply rule application (expression + expression):

apply rule expression:

go to start

See Paul McG's answer for a working implementation.


问:
Ruby query need to update
Relationship:

account has_many users

user has_one sima

primary_partner_id is "account_id" which is passing as params.

```<code>User.where(primary_partner_id: 2).map{|a| a.sima}.reject{ |e| e.to_s.empty?}
</code>```

Results as below:

```<code> [
    #<Sima id: 93, user_id: 7, interviewer_account_user_id: 1945, interviewer_completion_date: "2017-06-09", transcriber_account_user_id: nil, transcriber_completion_date: nil, biographer_account_user_id: nil, biographer_completion_date: nil, reviewer_account_user_id: nil, reviewer_completion_date: nil, status: "accepted", autobiographical_form: "27381", autobiographical_form_completion_date: nil, sima_level_id: "1", created_at: "2017-06-06 20:17:57", updated_at: "2017-06-09 10:04:33", autobiographical_form_comments: nil, on_hold: nil, comments: [{:comment=>"easylims.xlsx", :user_name=>"Mike Burns", :created_at=>2017-06-06 20:17:57 UTC}, {:comment=>"ok", :user_name=>"SIMA Admin", :created_at=>2017-06-06 20:19:33 UTC}], interviewer_id: nil, interviewer_start_date: nil, transcriber_start_date: nil, biographer_start_date: nil, reviewer_start_date: nil>,
    #<Sima id: 92, user_id: 1, interviewer_account_user_id: nil, interviewer_completion_date: nil, transcriber_account_user_id: nil, transcriber_completion_date: nil, biographer_account_user_id: nil, biographer_completion_date: nil, reviewer_account_user_id: nil, reviewer_completion_date: nil, status: "accepted", autobiographical_form: "27437", autobiographical_form_completion_date: nil, sima_level_id: "1", created_at: "2017-06-06 20:01:50", updated_at: "2017-06-06 20:22:50", autobiographical_form_comments: nil, on_hold: nil, comments: [{:comment=>"original_msg (1).txt", :user_name=>"bild_cloud@bild.org", :created_at=>2017-06-06 20:01:50 UTC}, {:comment=>"ok", :user_name=>"SIMA Admin", :created_at=>2017-06-06 20:22:05 UTC}], interviewer_id: nil, interviewer_start_date: nil, transcriber_start_date: nil, biographer_start_date: nil, reviewer_start_date: nil>
 ]
</code>```

Sima has field like status and I have three statuses as "pending, accepted, declined"

Question:

Now I want to show the result as per status which will pass by the user as params. So the result should be as per status from Sima. If params is status=" accepted" then Sima list will have only which has status "accepted"

答:
By doing this you can avoid N+1 Query problem

```<code>User.includes(:sima).where(sima: {status: params[:status]},primary_partner_id: params[:account_id]).map(&:sima)
</code>```

If you are using joins --> In map statement each time query will be called so that we are preferred to use includes, for more Information

you can refer this link

http://guides.rubyonrails.org/active_record_querying.html

Title: Ruby query need to update

Body:
Relationship:

account has_many users

user has_one sima

primary_partner_id is "account_id" which is passing as params.

User.where(primary_partner_id: 2).map{|a| a.sima}.reject{ |e| e.to_s.empty?}

Results as below:

 [
    #<Sima id: 93, user_id: 7, interviewer_account_user_id: 1945, interviewer_completion_date: "2017-06-09", transcriber_account_user_id: nil, transcriber_completion_date: nil, biographer_account_user_id: nil, biographer_completion_date: nil, reviewer_account_user_id: nil, reviewer_completion_date: nil, status: "accepted", autobiographical_form: "27381", autobiographical_form_completion_date: nil, sima_level_id: "1", created_at: "2017-06-06 20:17:57", updated_at: "2017-06-09 10:04:33", autobiographical_form_comments: nil, on_hold: nil, comments: [{:comment=>"easylims.xlsx", :user_name=>"Mike Burns", :created_at=>2017-06-06 20:17:57 UTC}, {:comment=>"ok", :user_name=>"SIMA Admin", :created_at=>2017-06-06 20:19:33 UTC}], interviewer_id: nil, interviewer_start_date: nil, transcriber_start_date: nil, biographer_start_date: nil, reviewer_start_date: nil>,
    #<Sima id: 92, user_id: 1, interviewer_account_user_id: nil, interviewer_completion_date: nil, transcriber_account_user_id: nil, transcriber_completion_date: nil, biographer_account_user_id: nil, biographer_completion_date: nil, reviewer_account_user_id: nil, reviewer_completion_date: nil, status: "accepted", autobiographical_form: "27437", autobiographical_form_completion_date: nil, sima_level_id: "1", created_at: "2017-06-06 20:01:50", updated_at: "2017-06-06 20:22:50", autobiographical_form_comments: nil, on_hold: nil, comments: [{:comment=>"original_msg (1).txt", :user_name=>"bild_cloud@bild.org", :created_at=>2017-06-06 20:01:50 UTC}, {:comment=>"ok", :user_name=>"SIMA Admin", :created_at=>2017-06-06 20:22:05 UTC}], interviewer_id: nil, interviewer_start_date: nil, transcriber_start_date: nil, biographer_start_date: nil, reviewer_start_date: nil>
 ]

Sima has field like status and I have three statuses as "pending, accepted, declined"

Question:

Now I want to show the result as per status which will pass by the user as params. So the result should be as per status from Sima. If params is status=" accepted" then Sima list will have only which has status "accepted"

Body:
By doing this you can avoid N+1 Query problem

User.includes(:sima).where(sima: {status: params[:status]},primary_partner_id: params[:account_id]).map(&:sima)

If you are using joins --> In map statement each time query will be called so that we are preferred to use includes, for more Information

you can refer this link

http://guides.rubyonrails.org/active_record_querying.html