问:
Using geocoder in ListView
I have an app that displays a ListView with Cards, and these cards have already the latitude and longitude information. I need to show in each card the address of that location. First i was calling Geocoder directly in each card and it really works, but the app takes a long time to answer. So I read the documentation and it recommends:

you should not call it from the main, user interface (UI) thread of
  your app

So it recommends to create a service and use the Geocoder there. The problem is that i can't implement the suggested code to each card (elements of the ListView). My code is the following. I have a FeaturesFragment:

```<code>@Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View myView = inflater.inflate(R.layout.features_layout, container, false);

        // Used to operate the database
        PhotoDAO photoDAO = new PhotoDAO(getActivity());
        //Receives the cursor with the result of the search
        final Cursor cursor = photoDAO.searchAll();

        // list that shows the items. Cards are set into the adapter
        ListView listView = (ListView) myView.findViewById(R.id.list);
        PhotoAdapter adapter = new PhotoAdapter(getActivity(), cursor);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                String description = cursor.getString(cursor.getColumnIndexOrThrow(PhotoContract.PhotoEntry.COLUMN_PHOTO_DESCRIPTION));
                String path = cursor.getString(cursor.getColumnIndexOrThrow(PhotoContract.PhotoEntry.COLUMN_PHOTO_PATH));
                Long id_photo = cursor.getLong(cursor.getColumnIndexOrThrow(PhotoContract.PhotoEntry._ID));

                Log.v(TAG, path);
                Intent i = new Intent(getActivity(), PhotoDescriptionActivity.class);
                i.putExtra("id", id_photo);
                i.putExtra("path", path);
                i.putExtra("description", description);
                startActivity(i);
            }
        });

        return myView;
    }
</code>```

I'm using a custon CursorAdapter called PhotoAdapter that is:
(the commented part is the old geocoder code)

```<code>@Override
    public void bindView(View view, Context context, Cursor cursor) {

        // First, select the category to show on the card
        int id_cat = cursor.getInt(cursor.getColumnIndexOrThrow(PhotoEntry.COLUMN_ID_CATEGORY));
        CategoryDAO categoryDAO = new CategoryDAO(context);
        Category category = categoryDAO.search(String.valueOf(id_cat));

        // Get the object located at this position in the list
        String path = cursor.getString(cursor.getColumnIndexOrThrow(PhotoEntry.COLUMN_PHOTO_PATH));
        String description = cursor.getString(cursor.getColumnIndexOrThrow(PhotoEntry.COLUMN_PHOTO_DESCRIPTION));
        String time = cursor.getString(cursor.getColumnIndexOrThrow(PhotoEntry.COLUMN_PHOTO_TIME));
        Double latitude = cursor.getDouble(cursor.getColumnIndexOrThrow(PhotoEntry.COLUMN_PHOTO_LATITUDE));
        Double longitude = cursor.getDouble(cursor.getColumnIndexOrThrow(PhotoEntry.COLUMN_PHOTO_LONGITUDE));
        Date dt = FormatDateTimeUtil.stringToDate(time, FormatDateTimeUtil.FORMAT_DATE);

        TextView txtCategory = (TextView) view.findViewById(R.id.text_category);
        ImageView imageResource = (ImageView) view.findViewById(R.id.photo_card);
        ExpandableTextView txtDescription = (ExpandableTextView) view.findViewById(R.id.expand_text_view);
        TextView txtTime = (TextView) view.findViewById(R.id.text_time);
        TextView txtCity = (TextView) view.findViewById(R.id.text_city);

        String cidade;
        String estado;
        String pais;

        /*Geocoder gcd = new Geocoder(context, Locale.getDefault());
        try {
            List<Address> add = gcd.getFromLocation(latitude, longitude, 1);

            if (add.size() > 0) {
                cidade = add.get(0).getLocality();
                estado = add.get(0).getAdminArea();
                pais = add.get(0).getCountryName();

                txtCity.setText(cidade+", "+estado+". "+pais);
            } else {
                txtCity.setText(R.string.location_unknown);
            }

        } catch (IOException e) {
            Log.e(TAG, "It wasn't possible to get location");
            e.printStackTrace();
        }*/

        //controls the heap to load images, preventing a memory overload
        Glide.with(context).load(path).into(imageResource);
        txtDescription.setText(description);

        txtTime.setText(FormatDateTimeUtil.dateToString(dt));

        txtCategory.setText(category.getDescription());

    }
</code>```

So how can I use the service in each element of the ListView? Or is there some other way to get these locations?

答:
I fixed the problem by using a GeocoderHandler and other thread like this:

PhotoAdapter

```<code>public void bindView(View view, Context ctx, Cursor cursor) {

    final Context context = ctx;

    appLocationService = new AppLocationService(
            context);

    // First, select the category to show on the card
    int id_cat = cursor.getInt(cursor.getColumnIndexOrThrow(PhotoEntry.COLUMN_ID_CATEGORY));
    CategoryDAO categoryDAO = new CategoryDAO(context);
    Category category = categoryDAO.search(String.valueOf(id_cat));

    // Get the object located at this position in the list
    final String id = cursor.getString(cursor.getColumnIndexOrThrow(PhotoEntry._ID));
    final String path = cursor.getString(cursor.getColumnIndexOrThrow(PhotoEntry.COLUMN_PHOTO_PATH));
    final String description = cursor.getString(cursor.getColumnIndexOrThrow(PhotoEntry.COLUMN_PHOTO_DESCRIPTION));
    final String time = cursor.getString(cursor.getColumnIndexOrThrow(PhotoEntry.COLUMN_PHOTO_TIME));
    final Double latitude = cursor.getDouble(cursor.getColumnIndexOrThrow(PhotoEntry.COLUMN_PHOTO_LATITUDE));
    final Double longitude = cursor.getDouble(cursor.getColumnIndexOrThrow(PhotoEntry.COLUMN_PHOTO_LONGITUDE));

    Date dt = FormatDateTimeUtil.stringToDate(time, FormatDateTimeUtil.FORMAT_DATE);

    TextView txtCategory = (TextView) view.findViewById(R.id.text_category);
    ImageView imageResource = (ImageView) view.findViewById(R.id.photo_card);
    ExpandableTextView txtDescription = (ExpandableTextView) view.findViewById(R.id.expand_text_view);
    TextView txtTime = (TextView) view.findViewById(R.id.text_time);
    txtCity = (TextView) view.findViewById(R.id.text_city);

    //controls the heap to load images, preventing a memory overload
    Glide.with(context).load(path).into(imageResource);
    txtDescription.setText(description);
    txtTime.setText(FormatDateTimeUtil.dateToString(dt));
    txtCategory.setText(category.getDescription());

    LocationAddress locationAddress = new LocationAddress();
    locationAddress.getAddressFromLocation(latitude, longitude,
            getApplicationContext(), new GeocoderHandler());

    imageResource.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(v.getContext(), PhotoDescriptionActivity.class);
            i.putExtra("id", id);
            i.putExtra("path", path);
            i.putExtra("description", description);
            v.getContext().startActivity(i);
        }
    });
}

private class GeocoderHandler extends Handler {
    @Override
    public void handleMessage(Message message) {
        String locationAddress;
        switch (message.what) {
            case 1:
                Bundle bundle = message.getData();
                locationAddress = bundle.getString("address");
                break;
            default:
                locationAddress = null;
        }
        txtCity.setText(locationAddress);
    }
}
</code>```

In my FeaturesFragment I just removed the clicklistener because it had to be moved to PhotoAdapter.
Using the GeocoderHandler for each card the location is loaded in background, not hindering the user interface. As reference, i used the answer of EricLarch in this link

Title: Using geocoder in ListView

Body:
I have an app that displays a ListView with Cards, and these cards have already the latitude and longitude information. I need to show in each card the address of that location. First i was calling Geocoder directly in each card and it really works, but the app takes a long time to answer. So I read the documentation and it recommends:

you should not call it from the main, user interface (UI) thread of
  your app

So it recommends to create a service and use the Geocoder there. The problem is that i can't implement the suggested code to each card (elements of the ListView). My code is the following. I have a FeaturesFragment:

@Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View myView = inflater.inflate(R.layout.features_layout, container, false);

        // Used to operate the database
        PhotoDAO photoDAO = new PhotoDAO(getActivity());
        //Receives the cursor with the result of the search
        final Cursor cursor = photoDAO.searchAll();

        // list that shows the items. Cards are set into the adapter
        ListView listView = (ListView) myView.findViewById(R.id.list);
        PhotoAdapter adapter = new PhotoAdapter(getActivity(), cursor);
        listView.setAdapter(adapter);

        listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

                String description = cursor.getString(cursor.getColumnIndexOrThrow(PhotoContract.PhotoEntry.COLUMN_PHOTO_DESCRIPTION));
                String path = cursor.getString(cursor.getColumnIndexOrThrow(PhotoContract.PhotoEntry.COLUMN_PHOTO_PATH));
                Long id_photo = cursor.getLong(cursor.getColumnIndexOrThrow(PhotoContract.PhotoEntry._ID));

                Log.v(TAG, path);
                Intent i = new Intent(getActivity(), PhotoDescriptionActivity.class);
                i.putExtra("id", id_photo);
                i.putExtra("path", path);
                i.putExtra("description", description);
                startActivity(i);
            }
        });

        return myView;
    }

I'm using a custon CursorAdapter called PhotoAdapter that is:
(the commented part is the old geocoder code)

@Override
    public void bindView(View view, Context context, Cursor cursor) {

        // First, select the category to show on the card
        int id_cat = cursor.getInt(cursor.getColumnIndexOrThrow(PhotoEntry.COLUMN_ID_CATEGORY));
        CategoryDAO categoryDAO = new CategoryDAO(context);
        Category category = categoryDAO.search(String.valueOf(id_cat));

        // Get the object located at this position in the list
        String path = cursor.getString(cursor.getColumnIndexOrThrow(PhotoEntry.COLUMN_PHOTO_PATH));
        String description = cursor.getString(cursor.getColumnIndexOrThrow(PhotoEntry.COLUMN_PHOTO_DESCRIPTION));
        String time = cursor.getString(cursor.getColumnIndexOrThrow(PhotoEntry.COLUMN_PHOTO_TIME));
        Double latitude = cursor.getDouble(cursor.getColumnIndexOrThrow(PhotoEntry.COLUMN_PHOTO_LATITUDE));
        Double longitude = cursor.getDouble(cursor.getColumnIndexOrThrow(PhotoEntry.COLUMN_PHOTO_LONGITUDE));
        Date dt = FormatDateTimeUtil.stringToDate(time, FormatDateTimeUtil.FORMAT_DATE);

        TextView txtCategory = (TextView) view.findViewById(R.id.text_category);
        ImageView imageResource = (ImageView) view.findViewById(R.id.photo_card);
        ExpandableTextView txtDescription = (ExpandableTextView) view.findViewById(R.id.expand_text_view);
        TextView txtTime = (TextView) view.findViewById(R.id.text_time);
        TextView txtCity = (TextView) view.findViewById(R.id.text_city);

        String cidade;
        String estado;
        String pais;

        /*Geocoder gcd = new Geocoder(context, Locale.getDefault());
        try {
            List<Address> add = gcd.getFromLocation(latitude, longitude, 1);

            if (add.size() > 0) {
                cidade = add.get(0).getLocality();
                estado = add.get(0).getAdminArea();
                pais = add.get(0).getCountryName();

                txtCity.setText(cidade+", "+estado+". "+pais);
            } else {
                txtCity.setText(R.string.location_unknown);
            }

        } catch (IOException e) {
            Log.e(TAG, "It wasn't possible to get location");
            e.printStackTrace();
        }*/

        //controls the heap to load images, preventing a memory overload
        Glide.with(context).load(path).into(imageResource);
        txtDescription.setText(description);

        txtTime.setText(FormatDateTimeUtil.dateToString(dt));

        txtCategory.setText(category.getDescription());

    }

So how can I use the service in each element of the ListView? Or is there some other way to get these locations?

Body:
I fixed the problem by using a GeocoderHandler and other thread like this:

PhotoAdapter

public void bindView(View view, Context ctx, Cursor cursor) {

    final Context context = ctx;

    appLocationService = new AppLocationService(
            context);

    // First, select the category to show on the card
    int id_cat = cursor.getInt(cursor.getColumnIndexOrThrow(PhotoEntry.COLUMN_ID_CATEGORY));
    CategoryDAO categoryDAO = new CategoryDAO(context);
    Category category = categoryDAO.search(String.valueOf(id_cat));

    // Get the object located at this position in the list
    final String id = cursor.getString(cursor.getColumnIndexOrThrow(PhotoEntry._ID));
    final String path = cursor.getString(cursor.getColumnIndexOrThrow(PhotoEntry.COLUMN_PHOTO_PATH));
    final String description = cursor.getString(cursor.getColumnIndexOrThrow(PhotoEntry.COLUMN_PHOTO_DESCRIPTION));
    final String time = cursor.getString(cursor.getColumnIndexOrThrow(PhotoEntry.COLUMN_PHOTO_TIME));
    final Double latitude = cursor.getDouble(cursor.getColumnIndexOrThrow(PhotoEntry.COLUMN_PHOTO_LATITUDE));
    final Double longitude = cursor.getDouble(cursor.getColumnIndexOrThrow(PhotoEntry.COLUMN_PHOTO_LONGITUDE));

    Date dt = FormatDateTimeUtil.stringToDate(time, FormatDateTimeUtil.FORMAT_DATE);

    TextView txtCategory = (TextView) view.findViewById(R.id.text_category);
    ImageView imageResource = (ImageView) view.findViewById(R.id.photo_card);
    ExpandableTextView txtDescription = (ExpandableTextView) view.findViewById(R.id.expand_text_view);
    TextView txtTime = (TextView) view.findViewById(R.id.text_time);
    txtCity = (TextView) view.findViewById(R.id.text_city);

    //controls the heap to load images, preventing a memory overload
    Glide.with(context).load(path).into(imageResource);
    txtDescription.setText(description);
    txtTime.setText(FormatDateTimeUtil.dateToString(dt));
    txtCategory.setText(category.getDescription());

    LocationAddress locationAddress = new LocationAddress();
    locationAddress.getAddressFromLocation(latitude, longitude,
            getApplicationContext(), new GeocoderHandler());

    imageResource.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Intent i = new Intent(v.getContext(), PhotoDescriptionActivity.class);
            i.putExtra("id", id);
            i.putExtra("path", path);
            i.putExtra("description", description);
            v.getContext().startActivity(i);
        }
    });
}

private class GeocoderHandler extends Handler {
    @Override
    public void handleMessage(Message message) {
        String locationAddress;
        switch (message.what) {
            case 1:
                Bundle bundle = message.getData();
                locationAddress = bundle.getString("address");
                break;
            default:
                locationAddress = null;
        }
        txtCity.setText(locationAddress);
    }
}

In my FeaturesFragment I just removed the clicklistener because it had to be moved to PhotoAdapter.
Using the GeocoderHandler for each card the location is loaded in background, not hindering the user interface. As reference, i used the answer of EricLarch in this link


来源: stackexchange

问:
Run .sh file using exec Laravel PHP
I am trying to run a .sh file that will import a excel file to my database. Both files are in same directory inside the public folder. For some reason the exec command isn't being executed or neither any error occurs.

.sh file colde:

```<code>IFS=,
while read column1
      do
        echo "SQL COMMAND GOES HERE"

done < file.csv | mysql --user='myusername' --password='mypassword' -D databasename;
echo "finish"
</code>```

In my php file i have tried following:

```<code>$content = file_get_contents('folder_name/file_name.sh');
echo exec($content);
</code>```

And:

```<code>shell_exec('sh /folder_name/file_name.sh');
</code>```

Note: I can directly execute the sh file from gitbash however I want it to be done using function in Laravel controller. I'm using windows OS.

答:
you can use Process Component of Symfony that is already in Laravel http://symfony.com/doc/current/components/process.html</p>

```<code>use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;

$process = new Process('sh /folder_name/file_name.sh');
$process->run();

// executes after the command finishes
if (!$process->isSuccessful()) {
    throw new ProcessFailedException($process);
}

echo $process->getOutput();
</code>```

ContentLicense: CC BY-SA 3.0

Title: Run .sh file using exec Laravel PHP

Body:
I am trying to run a .sh file that will import a excel file to my database. Both files are in same directory inside the public folder. For some reason the exec command isn't being executed or neither any error occurs.

.sh file colde:

IFS=,
while read column1
      do
        echo "SQL COMMAND GOES HERE"

done < file.csv | mysql --user='myusername' --password='mypassword' -D databasename;
echo "finish"

In my php file i have tried following:

$content = file_get_contents('folder_name/file_name.sh');
echo exec($content);

And:

shell_exec('sh /folder_name/file_name.sh');

Note: I can directly execute the sh file from gitbash however I want it to be done using function in Laravel controller. I'm using windows OS.

Body:
you can use Process Component of Symfony that is already in Laravel http://symfony.com/doc/current/components/process.html

use Symfony\Component\Process\Process;
use Symfony\Component\Process\Exception\ProcessFailedException;

$process = new Process('sh /folder_name/file_name.sh');
$process->run();

// executes after the command finishes
if (!$process->isSuccessful()) {
    throw new ProcessFailedException($process);
}

echo $process->getOutput();


问:
how to align progress bar in webview Android?
I wrote simple web view application in android but the progress bar is showing the very top of the application click
here to view the image.
actually, I want to do like this click here

This is my
Main activity

```<code>public class MainActivity extends AppCompatActivity implements MyWebChromeClient.ProgressListener {

WebView wv;
private ProgressBar mProgressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    wv=(WebView) findViewById(R.id.webview);
    WebSettings settings = wv.getSettings();
    settings.setJavaScriptEnabled(true);
    settings.getLoadsImagesAutomatically();
    settings.getBuiltInZoomControls();
    settings.setSaveFormData(true);
    settings.setEnableSmoothTransition(true);
    settings.setNeedInitialFocus(true);
    settings.setSavePassword(true);
    settings.setDomStorageEnabled(true);
    settings.setPluginState(WebSettings.PluginState.ON);
    // add progress bar
    mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
    wv.loadUrl("https://www.w3schools.com/");
    wv.setWebChromeClient(new MyWebChromeClient(this));
    wv.setWebViewClient(new WebViewClient(){
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            mProgressBar.setVisibility(View.VISIBLE);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            mProgressBar.setVisibility(View.GONE);

        }
    });
}

@Override
public void onBackPressed() {
    if(wv.canGoBack()){

        wv.goBack();
    }
    else{
        super.onBackPressed();
    }
}

@Override
public void onUpdateProgress(int progressValue) {
    mProgressBar.setProgress(progressValue);
    if (progressValue == 100) {
        mProgressBar.setVisibility(View.INVISIBLE);
    }
}}
</code>```

In this layout i added webview and progressbar.

activity_main.xml

```<code> <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.johnson.apple.MainActivity">
    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
    <ProgressBar
        android:id="@+id/progressBar"
        android:minHeight="2dip"
        android:maxHeight="2dip"
        android:progressDrawable="@drawable/bg_progress_bar_webview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        style="@android:style/Widget.ProgressBar.Horizontal" />
</RelativeLayout>
</code>```

Hope anyone can help me
Thnaks in advance

答:
add android:layout_centerInParent="true" to your progressBar layout

like this:

```<code><ProgressBar
android:id="@+id/progressBar"
android:minHeight="2dip"
android:maxHeight="2dip"
android:progressDrawable="@drawable/bg_progress_bar_webview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
style="@android:style/Widget.ProgressBar.Horizontal" />
</code>```

ContentLicense: CC BY-SA 4.0

Body:
I wrote simple web view application in android but the progress bar is showing the very top of the application click
here to view the image.
actually, I want to do like this click here

This is my
Main activity

public class MainActivity extends AppCompatActivity implements MyWebChromeClient.ProgressListener {

WebView wv;
private ProgressBar mProgressBar;
@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    wv=(WebView) findViewById(R.id.webview);
    WebSettings settings = wv.getSettings();
    settings.setJavaScriptEnabled(true);
    settings.getLoadsImagesAutomatically();
    settings.getBuiltInZoomControls();
    settings.setSaveFormData(true);
    settings.setEnableSmoothTransition(true);
    settings.setNeedInitialFocus(true);
    settings.setSavePassword(true);
    settings.setDomStorageEnabled(true);
    settings.setPluginState(WebSettings.PluginState.ON);
    // add progress bar
    mProgressBar = (ProgressBar) findViewById(R.id.progressBar);
    wv.loadUrl("https://www.w3schools.com/");
    wv.setWebChromeClient(new MyWebChromeClient(this));
    wv.setWebViewClient(new WebViewClient(){
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            view.loadUrl(url);
            return true;
        }

        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            super.onPageStarted(view, url, favicon);
            mProgressBar.setVisibility(View.VISIBLE);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            super.onPageFinished(view, url);
            mProgressBar.setVisibility(View.GONE);

        }
    });
}

@Override
public void onBackPressed() {
    if(wv.canGoBack()){

        wv.goBack();
    }
    else{
        super.onBackPressed();
    }
}

@Override
public void onUpdateProgress(int progressValue) {
    mProgressBar.setProgress(progressValue);
    if (progressValue == 100) {
        mProgressBar.setVisibility(View.INVISIBLE);
    }
}}

In this layout i added webview and progressbar.

activity_main.xml

 <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/activity_main"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.johnson.apple.MainActivity">
    <WebView
        android:id="@+id/webview"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_centerVertical="true"
        android:layout_centerHorizontal="true" />
    <ProgressBar
        android:id="@+id/progressBar"
        android:minHeight="2dip"
        android:maxHeight="2dip"
        android:progressDrawable="@drawable/bg_progress_bar_webview"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        style="@android:style/Widget.ProgressBar.Horizontal" />
</RelativeLayout>

Hope anyone can help me
Thnaks in advance

Body:
add android:layout_centerInParent="true" to your progressBar layout

like this:

<ProgressBar
android:id="@+id/progressBar"
android:minHeight="2dip"
android:maxHeight="2dip"
android:progressDrawable="@drawable/bg_progress_bar_webview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerHorizontal="true"
style="@android:style/Widget.ProgressBar.Horizontal" />


问:
How much space (in binary/in memory) does a Java interface take?
I'm trying to understand how much space a java interface will take up, both on disk in the binary, and on a per instantiated object basis. Obligatory "every JVM implementation may be different" disclaimer, I am more interested not in a 100% exact answer, but in understanding the essentials of how this is handled.

If we assume a simple interface (no static final vars, no default implementations), how much space does this take in binary? I assume the human readable class name will need to be stored, for debugging/reflection, plus possibly some unique class identifier? When an object that implements this interface is instantiated, how many extra bytes of overhead does the interface add to the in-memory representation of the object, if any?

答:
how much space a java interface will take up, both on disk in the binary, and on a per instantiated object basis.

On disk in the binary:

Definitive answer: See file size of .class file.

Short answer: It depends, as Jim Garrison said.

Long answer: It depends on: length of package name, length of interface name, number of methods, length of method names, number of parameters, type of parameters, length of parameter names, type of return type, whether debug information is included, version of bytecode, ... and more ...

On a per instantiated object basis:

None.


问:
Bot Service Node.js deployment from a non-root directory
I have bot service and following structure:

```<code>git-root
¦
+--- mybot(bot service app)
¦    ¦
¦    +--- messages (all js code; ex. index.js)
¦    +--- PostDeployScripts (default script created from template, no changes)
¦
+--- other app
</code>```

Taken the recommendation from another post. I do: Azure -> My Bot -> Settings -> App Settings -> (PROJECT = mybot) -> Save -> Continuous Integration -> Sync.

Result: The bot is not deployed from the mybot directory.

Few notes:

I would prefer to avoid any configuration files in the git-root

All suggestions in the web Ive found have a link to .csproj file, which I don't have. I'm using default Bot Service template and Intellij IDEA for coding.

答: You'll need to have a custom deployment script that tells azure how to deploy your app. That deployment script goes in your gitroot. If you don't want to commit the .deployment file in the root of your git repo, you can configure it through app settings instead. You'd have to configure an app setting for the command to point to your custom deployment script. See this wiki for more info https://github.com/projectkudu/kudu/wiki/Customizing-deployments

Body:
I have bot service and following structure:

git-root
¦
+--- mybot(bot service app)
¦    ¦
¦    +--- messages (all js code; ex. index.js)
¦    +--- PostDeployScripts (default script created from template, no changes)
¦
+--- other app

Taken the recommendation from another post. I do: Azure -> My Bot -> Settings -> App Settings -> (PROJECT = mybot) -> Save -> Continuous Integration -> Sync.

Result: The bot is not deployed from the mybot directory.

Few notes:

I would prefer to avoid any configuration files in the git-root

All suggestions in the web Ive found have a link to .csproj file, which I don't have. I'm using default Bot Service template and Intellij IDEA for coding.


问:
UITableView left margin checkmark buttons - Swift
I'm trying to add check marks to my UItableview cells. I want to checkmarks to display like circle buttons on the left margin like this image:

I am unable to get the checkmarks in the left margin with my code and instead I keep getting checkmarks on the right that display only when tapped. Here is my current code:

```<code>override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
if let cell = tableView.cellForRowAtIndexPath(indexPath) {
    cell.accessoryType = .None
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let cell = tableView.cellForRowAtIndexPath(indexPath) {
    cell.accessoryType = .Checkmark

}
}
</code>```

Any idea on how i can get the checkmarks to display on the left like the image?

答:
I've made for you whole sample application for this.

just try this.
And this is what it looks like.

Body:
I'm trying to add check marks to my UItableview cells. I want to checkmarks to display like circle buttons on the left margin like this image:

I am unable to get the checkmarks in the left margin with my code and instead I keep getting checkmarks on the right that display only when tapped. Here is my current code:

override func tableView(tableView: UITableView, didDeselectRowAtIndexPath indexPath: NSIndexPath) {
if let cell = tableView.cellForRowAtIndexPath(indexPath) {
    cell.accessoryType = .None
}
}
override func tableView(tableView: UITableView, didSelectRowAtIndexPath indexPath: NSIndexPath) {
if let cell = tableView.cellForRowAtIndexPath(indexPath) {
    cell.accessoryType = .Checkmark

}
}

Any idea on how i can get the checkmarks to display on the left like the image?


问:
Accessing a Promises Value outside of its context
I understand to access a value of a Promise, I will use the "then" callback attach to it.

However, I was wondering how I can affect the context outside of it?

```<code>let outsideVar = 0;
promiseA.then(value => {
    outsideVar = 1;
})
console.log(outsideVar); //0
</code>```

As you can see I would like to change outsideVar to 1

[Edit] This question was to see if promises can affect global variables outside of it and if there were any possibilities to do that.

Unfortunately, it is not possible.

答:
Your problem isn't changing your outsideVar, it's that you're checking it way too soon.

The Promise is async, so you need to wait until it is complete to output.

```<code>let outsideVar = 0;
promiseA.then(value => {
     outsideVar = 1;
}).then(() => console.log(outsideVar));
</code>```

Once you start using a Promise, you need to keep writing async code.

You could use await and async, if you're using a preprocessor like Babel with es2017 presets.

There are some caveats with them though:

You can't run it directly at the top-level, it'd have to be in a function marked async.

The code is still running asynchronously, it just looks synchronous. Be aware of this difference or weird things will happen.

Here is the example:

```<code>let outsideVar = 0;
const doSomething = async () => {
    await Promise.resolve(); // something that is async
    outsideVar = 1;
};

await doSomething();
console.log(outsideVar);
</code>```

Body:
I understand to access a value of a Promise, I will use the "then" callback attach to it.

However, I was wondering how I can affect the context outside of it?

let outsideVar = 0;
promiseA.then(value => {
    outsideVar = 1;
})
console.log(outsideVar); //0

As you can see I would like to change outsideVar to 1

[Edit] This question was to see if promises can affect global variables outside of it and if there were any possibilities to do that.

Unfortunately, it is not possible.

Body:
Your problem isn't changing your outsideVar, it's that you're checking it way too soon.

The Promise is async, so you need to wait until it is complete to output.

let outsideVar = 0;
promiseA.then(value => {
     outsideVar = 1;
}).then(() => console.log(outsideVar));

Once you start using a Promise, you need to keep writing async code.

You could use await and async, if you're using a preprocessor like Babel with es2017 presets.

There are some caveats with them though:

You can't run it directly at the top-level, it'd have to be in a function marked async.

The code is still running asynchronously, it just looks synchronous. Be aware of this difference or weird things will happen.

Here is the example:

let outsideVar = 0;
const doSomething = async () => {
    await Promise.resolve(); // something that is async
    outsideVar = 1;
};

await doSomething();
console.log(outsideVar);


问:
Read a compressed file *with custom extension* with spark
I want to read gzip compressed files into a RDD[String] using an equivalent of sc.textFile("path/to/file.Z").

Except my file extension if not gz but is Z instead, so the file is not recognised as being gzipped.

I cannot rename them as it would break production code. I do not want to copy them as they are massive and many. I guess I could use some kind of symlinks but I want to see if there is a way with scala/spark first (I am on my local windows machine for now).

How can I read this file efficiently?

答:
Here there's a workaround to fix this problem http://arjon.es/2015/10/02/reading-compressed-data-with-spark-using-unknown-file-extensions/

The relevant section:

...extend GzipCodec and override the getDefaultExtension method.

```<code>package smx.ananke.spark.util.codecs

import org.apache.hadoop.io.compress.GzipCodec

class TmpGzipCodec extends GzipCodec {

  override def getDefaultExtension(): String = ".gz.tmp" // You should change it to ".Z"

}
</code>```

Now we just registered this codec, setting
  spark.hadoop.io.compression.codecs on SparkConf:

```<code>val conf = new SparkConf()

// Custom Codec that process .gz.tmp extensions as a common Gzip format
conf.set("spark.hadoop.io.compression.codecs", "smx.ananke.spark.util.codecs.TmpGzipCodec")

val sc = new SparkContext(conf)

val data = sc.textFile("s3n://my-data-bucket/2015/09/21/13/*")
</code>```

Body:
Here there's a workaround to fix this problem http://arjon.es/2015/10/02/reading-compressed-data-with-spark-using-unknown-file-extensions/

The relevant section:

...extend GzipCodec and override the getDefaultExtension method.

package smx.ananke.spark.util.codecs

import org.apache.hadoop.io.compress.GzipCodec

class TmpGzipCodec extends GzipCodec {

  override def getDefaultExtension(): String = ".gz.tmp" // You should change it to ".Z"

}

Now we just registered this codec, setting
  spark.hadoop.io.compression.codecs on SparkConf:

val conf = new SparkConf()

// Custom Codec that process .gz.tmp extensions as a common Gzip format
conf.set("spark.hadoop.io.compression.codecs", "smx.ananke.spark.util.codecs.TmpGzipCodec")

val sc = new SparkContext(conf)

val data = sc.textFile("s3n://my-data-bucket/2015/09/21/13/*")


问:
How to get Postback button value in the callback url in Facebook messenger bot?
I am trying to get "Start" button payload value in my call back url, its not happening. But i can get user typed text messages, and based on text messages I am able to send response as well. Lets given an example if user typing PHP (as a text message) I can send short description about PHP and i am showing 2 button 1 is more info it contains url, and one more button continue to chat

if user click Start button, i am not getting the value for the same in my callback url. Note i have selected all the events in my app settings

And my callback code

```<code><?php
date_default_timezone_set('Asia/Calcutta');
$access_token = "SFt44EAAWnrB7cYxIBAKeTHDZA7PuFOveOLs3OgZBPLgjMN7k8hXZAtBHktERWlm4uZCkSDVRo9r7PhKUZC1celZA9117Xcc6FDUKZCEbxRpZCM80rVDlb4H7ZAJkDVKJ2iuIFkDBoeG37a60KZBkCEtTVlCFIG8YWsQtHjKa7xP0TCF1kzZAcAZDZD";
$verify_token = "hdb201744_token";
$hub_verify_token = null;
if(isset($_REQUEST['hub_challenge']))
{
$challenge = $_REQUEST['hub_challenge'];
$hub_verify_token = $_REQUEST['hub_verify_token'];
}
if ($hub_verify_token === $verify_token)
{
echo $challenge;
}

$message_to_reply = '';
$input = json_decode(file_get_contents('php://input'), true);
$sender = $input['entry'][0]['messaging'][0]['sender']['id'];

$postback = $input['entry'][0]['messaging'][0]['postback']['payload'];
if (!empty($postback)) {
$message = $input['entry'][0]['messaging'][0]['postback']['payload'];

}
else
{
$message = $input['entry'][0]['messaging'][0]['message']['text'];

}

$message = trim($message);

if($message=='start')
{
$message_to_reply = "Thanks to continue, You can use bot now";

}

else
{

function getDescription($keyword)
{
$url='http://lookup.dbpedia.org/api/search.asmx/KeywordSearch?QueryString='.urlencode($keyword).'&MaxHits=1';
$xml=simplexml_load_file($url);
return $xml->Result->Description;
}

$message_to_reply = getDescription($message);

}

$message_to_reply = trim($message_to_reply);

//API Url
$url = 'https://graph.facebook.com/v2.6/me/messages?access_token='.$access_token;
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = '{
"recipient":{
"id":"'.$sender.'"
},
"message":{

"attachment":{
"type":"template",
"payload":{
"template_type":"button",
"sharable":true,
"text":"'.$message_to_reply.'",
"buttons":[
{
"type":"web_url",
"url":"http://php.net/manual/en/intro-whatis.php",
"title":"More Info"
},
{
"type":"postback",
"title":"Start",
"payload":"start"
}
]
}
}
}
}';

//$abb = json_encode($jsonData);
//print_r($abb);
//Encode the array into JSON.
$jsonDataEncoded = $jsonData;
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
//Execute the request
if(!empty($input['entry'][0]['messaging'][0]['message'])){
$result = curl_exec($ch);
}
?>
</code>```

I am using php.

答:
trying changing those lines

$postback = $input['entry'][0]['messaging'][0]['postback']['payload'];

if (!empty($postback)) {
  $message = $input['entry'][0]['messaging'][0]['postback']['payload'];

}

With those

$postback=json_decode($input['entry'][0]['messaging'][0]['postback'],true);

if (!empty($postback)) {
  $message = $postback['payload'];

}

Body:
I am trying to get "Start" button payload value in my call back url, its not happening. But i can get user typed text messages, and based on text messages I am able to send response as well. Lets given an example if user typing PHP (as a text message) I can send short description about PHP and i am showing 2 button 1 is more info it contains url, and one more button continue to chat

if user click Start button, i am not getting the value for the same in my callback url. Note i have selected all the events in my app settings

And my callback code

<?php
date_default_timezone_set('Asia/Calcutta');
$access_token = "SFt44EAAWnrB7cYxIBAKeTHDZA7PuFOveOLs3OgZBPLgjMN7k8hXZAtBHktERWlm4uZCkSDVRo9r7PhKUZC1celZA9117Xcc6FDUKZCEbxRpZCM80rVDlb4H7ZAJkDVKJ2iuIFkDBoeG37a60KZBkCEtTVlCFIG8YWsQtHjKa7xP0TCF1kzZAcAZDZD";
$verify_token = "hdb201744_token";
$hub_verify_token = null;
if(isset($_REQUEST['hub_challenge']))
{
$challenge = $_REQUEST['hub_challenge'];
$hub_verify_token = $_REQUEST['hub_verify_token'];
}
if ($hub_verify_token === $verify_token)
{
echo $challenge;
}

$message_to_reply = '';
$input = json_decode(file_get_contents('php://input'), true);
$sender = $input['entry'][0]['messaging'][0]['sender']['id'];

$postback = $input['entry'][0]['messaging'][0]['postback']['payload'];
if (!empty($postback)) {
$message = $input['entry'][0]['messaging'][0]['postback']['payload'];

}
else
{
$message = $input['entry'][0]['messaging'][0]['message']['text'];

}

$message = trim($message);

if($message=='start')
{
$message_to_reply = "Thanks to continue, You can use bot now";

}

else
{

function getDescription($keyword)
{
$url='http://lookup.dbpedia.org/api/search.asmx/KeywordSearch?QueryString='.urlencode($keyword).'&MaxHits=1';
$xml=simplexml_load_file($url);
return $xml->Result->Description;
}

$message_to_reply = getDescription($message);

}

$message_to_reply = trim($message_to_reply);

//API Url
$url = 'https://graph.facebook.com/v2.6/me/messages?access_token='.$access_token;
//Initiate cURL.
$ch = curl_init($url);
//The JSON data.
$jsonData = '{
"recipient":{
"id":"'.$sender.'"
},
"message":{

"attachment":{
"type":"template",
"payload":{
"template_type":"button",
"sharable":true,
"text":"'.$message_to_reply.'",
"buttons":[
{
"type":"web_url",
"url":"http://php.net/manual/en/intro-whatis.php",
"title":"More Info"
},
{
"type":"postback",
"title":"Start",
"payload":"start"
}
]
}
}
}
}';

//$abb = json_encode($jsonData);
//print_r($abb);
//Encode the array into JSON.
$jsonDataEncoded = $jsonData;
//Tell cURL that we want to send a POST request.
curl_setopt($ch, CURLOPT_POST, 1);
//Attach our encoded JSON string to the POST fields.
curl_setopt($ch, CURLOPT_POSTFIELDS, $jsonDataEncoded);
//Set the content type to application/json
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/json'));
//curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: application/x-www-form-urlencoded'));
//Execute the request
if(!empty($input['entry'][0]['messaging'][0]['message'])){
$result = curl_exec($ch);
}
?>

I am using php.


问:
How do I create an SSIS package that executes a bat file
I am trying to create a job in SQL Server Management Studio using an SSIS package to execute a bat file.  The bat file sets in motion an FTP transfer as well as file renaming and archiving.  I have tested the bat file and it executes properly with all steps completed.  The problem I am running into is with the SSIS package.  I am not a frequent user of Visual Studio so it is quite possible I am overlooking something.  On the control flow tab I added an "Execute process task".  I specified both the file path for the bat file and the working directory.  I verified this set up against other existing jobs we have in place that also execute bat files.  When I tell the job to run, it says it has completed successfully with no errors.  When I manually verify the results, the bat file has not been executed.  I do not know what I am overlooking here.  The SSIS package and the bat file reside on the same server, and the appropriate shares exist for the file transfer.  Any ideas as to what I may have missed would be appreciated.</p>

答:
Why? Why not do this inside SSIS using the supplied FTP Task? In addition you can do all the file renaming you want using the File System Task.

FTP Task: https://learn.microsoft.com/en-us/sql/integration-services/control-flow/ftp-task

File System Task: https://learn.microsoft.com/en-us/sql/integration-services/control-flow/file-system-task

Updated after latest comment:

If the built-in component doesnt work for you, have you considered 3rd party components such as https://winscp.net/eng/docs/guide_ssis

That component seems to use WinSCP as a backend


问:
WPF: context menu in TreeViewItem binding to root
I have TreeView control and I need to bind property from root (window/usercontrol) DataContext in context menu in that treeview.

```<code>    <TextBox Text="{Binding Header}"></TextBox>
    <TreeView ItemsSource="{Binding Items}" Grid.Row="1">
        <TreeView.ItemContainerStyle>
            <Style TargetType="{x:Type TreeViewItem}">
                <Setter Property="ContextMenu">
                    <Setter.Value>
                        <ContextMenu>
                            <MenuItem Header="{{ BINDING TO HEADER PROPERTY FROM WINDOW DATACONTEXT}}"/>
                        </ContextMenu>
                    </Setter.Value>
                </Setter>
            </Style>
        </TreeView.ItemContainerStyle>
    </TreeView>

    public ObservableCollection<string> Items { get; set; }
    public string Header { get { return _header; } set { _header = value; } }
</code>```

I've tried multiple things: I've added x:Name="WindowRoot" to Window and {Binding Header, ElementName=WindowRoot} but it didn't work, I've tried multiple FindAncestor and RelativeSource but it didn't work.

Can someone help me?

Edit:

This is simplified case, in my normal application I use Unity + Prism, so ViewModel is AutoDiscovered (prism:ViewModelLocator.AutoWireViewModel="True") and it generally works. By "works" I mean: TreeView shows items from my collection, so it is connected, the problem is with context menu binding only.

In this simplified example I have ugly and simple code-behind, because I only want to test this ContextMenu binding:

```<code>public partial class MainWindow : Window
{
    public ObservableCollection<string> Items { get; set; }
    private string _header = "testtest";
    public string Header { get { return _header ; } set { _header  = value; } }
    public MainWindow()
    {
        Items = new ObservableCollection<string>();
        Items.Add("ItemTest");
        InitializeComponent();
        this.DataContext = this;
    }
}
</code>```

答:
You could bind the Tag property of the TreeViewItem to the parent window or user control using a {RelativeSource} and then bind the Header property of the MenuItem to the Tag property of the PlacementTarget of the ContextMenu:

```<code><TreeView x:Name="tv" ItemsSource="{Binding Items}" Grid.Row="1">
    <TreeView.ItemContainerStyle>
        <Style TargetType="{x:Type TreeViewItem}">
            <Setter Property="Tag" Value="{Binding RelativeSource={RelativeSource AncestorType=Window}}" />
            <Setter Property="ContextMenu">
                <Setter.Value>
                    <ContextMenu>
                        <MenuItem Header="{Binding PlacementTarget.Tag.DataContext.Header, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
                    </ContextMenu>
                </Setter.Value>
            </Setter>
        </Style>
    </TreeView.ItemContainerStyle>
</TreeView>
</code>```

The reason you cannot bind directly to any property of the window from the MenuItem is that a ContextMenu resides in a different element tree than the parent window or user control.

Body:
I have TreeView control and I need to bind property from root (window/usercontrol) DataContext in context menu in that treeview.

    <TextBox Text="{Binding Header}"></TextBox>
    <TreeView ItemsSource="{Binding Items}" Grid.Row="1">
        <TreeView.ItemContainerStyle>

        </TreeView.ItemContainerStyle>
    </TreeView>

    public ObservableCollection<string> Items { get; set; }
    public string Header { get { return _header; } set { _header = value; } }

I've tried multiple things: I've added x:Name="WindowRoot" to Window and {Binding Header, ElementName=WindowRoot} but it didn't work, I've tried multiple FindAncestor and RelativeSource but it didn't work.

Can someone help me?

Edit:

This is simplified case, in my normal application I use Unity + Prism, so ViewModel is AutoDiscovered (prism:ViewModelLocator.AutoWireViewModel="True") and it generally works. By "works" I mean: TreeView shows items from my collection, so it is connected, the problem is with context menu binding only.

In this simplified example I have ugly and simple code-behind, because I only want to test this ContextMenu binding:

public partial class MainWindow : Window
{
    public ObservableCollection<string> Items { get; set; }
    private string _header = "testtest";
    public string Header { get { return _header ; } set { _header  = value; } }
    public MainWindow()
    {
        Items = new ObservableCollection<string>();
        Items.Add("ItemTest");
        InitializeComponent();
        this.DataContext = this;
    }
}

Body:
You could bind the Tag property of the TreeViewItem to the parent window or user control using a {RelativeSource} and then bind the Header property of the MenuItem to the Tag property of the PlacementTarget of the ContextMenu:

<TreeView x:Name="tv" ItemsSource="{Binding Items}" Grid.Row="1">
    <TreeView.ItemContainerStyle>
        <Style TargetType="{x:Type TreeViewItem}">
            <Setter Property="Tag" Value="{Binding RelativeSource={RelativeSource AncestorType=Window}}" />
            <Setter Property="ContextMenu">
                <Setter.Value>
                    <ContextMenu>
                        <MenuItem Header="{Binding PlacementTarget.Tag.DataContext.Header, RelativeSource={RelativeSource AncestorType=ContextMenu}}"/>
                    </ContextMenu>
                </Setter.Value>
            </Setter>
        </Style>
    </TreeView.ItemContainerStyle>
</TreeView>

The reason you cannot bind directly to any property of the window from the MenuItem is that a ContextMenu resides in a different element tree than the parent window or user control.


问:
Can i use JQuery/Javascript with Ionic instead of Typescript
I'm developing mobile applications using Visual Studio 2017 and Apache Cordova.
I've always coded using JQuery and Javascript however i have never written a code using Typescript.

When searching the web almost everyone is using Typescript with Ionic. (thinking of starting to benefit and use the Ionic Framework)
Is it the same if i use JQuery or Javascript instead of Typescript with Ionic?

Or its recommended that i learn Typescript and start using it with Ionic?

Thank you for the clarification.

This is how i usually write the code for Cordova using JQuery:

```<code>function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
    var j = Math.floor(Math.random() * (i + 1));
    var temp = array[i];
    array[i] = array[j];
    array[j] = temp;
}
return array;
}

function beginGame() {

$('#info').hide();

var level = 0;

$('#game_title h2').html('Level 1');
$('#game_question h3').html('What is the most common language?');

$('#game_body').html('');
var gameBody = document.getElementById('game_body');
var columnAnswer, buttonAnswer;

var answers = [['Arabic', ''], ['Spanish', ''], ['English', 'right_answer'], ['Chinese', '']];
var arr = shuffleArray(answers);
console.log(arr);

for (var i = 0; i < arr.length; i++) {
    columnAnswer = document.createElement('div');
    columnAnswer.className = 'col-xs-12';

    buttonAnswer = document.createElement('button');
    buttonAnswer.id = 'answer_button_'+i;
    buttonAnswer.className = 'btn btn-primary btn-sx answer_button ' + arr[i][1];
    buttonAnswer.type = 'button';
    buttonAnswer.innerHTML = arr[i][0];
    //buttonAnswer.setAttribute('onclick', 'onQuoteClick(' + quotes[i].id + ')');
    console.log(buttonAnswer);
    columnAnswer.appendChild(buttonAnswer);

    gameBody.appendChild(columnAnswer);
}

$('.answer_button').click(function () {
    var button_id = $(this).attr('id');
    if ($('#' + button_id).hasClass('right_answer')) {
        //alert('Right Answer');
        $('#info').show();
        fillInformation();
    } else {
        alert('Wrong Answer');
    }
});

}
function fillInformation() {
$('#game_title h2').html('English');
$('#info_image img').attr("src", './images/level_1.png');
$('#info_text h5').html('English Language');
}
</code>```

答: You should be able to use JQuery and Javascript with Ionic, however, you may lose the Angular capabilities Ionic offers. You could write ES6 javascript in the ts files as well. Otherwise, I'd recommend using Typescript which isn't too difficult to learn imo. Hope this helps.</p>

Body:
I'm developing mobile applications using Visual Studio 2017 and Apache Cordova.
I've always coded using JQuery and Javascript however i have never written a code using Typescript.

When searching the web almost everyone is using Typescript with Ionic. (thinking of starting to benefit and use the Ionic Framework)
Is it the same if i use JQuery or Javascript instead of Typescript with Ionic?

Or its recommended that i learn Typescript and start using it with Ionic?

Thank you for the clarification.

This is how i usually write the code for Cordova using JQuery:

function shuffleArray(array) {
for (var i = array.length - 1; i > 0; i--) {
    var j = Math.floor(Math.random() * (i + 1));
    var temp = array[i];
    array[i] = array[j];
    array[j] = temp;
}
return array;
}

function beginGame() {

$('#info').hide();

var level = 0;

$('#game_title h2').html('Level 1');
$('#game_question h3').html('What is the most common language?');

$('#game_body').html('');
var gameBody = document.getElementById('game_body');
var columnAnswer, buttonAnswer;

var answers = [['Arabic', ''], ['Spanish', ''], ['English', 'right_answer'], ['Chinese', '']];
var arr = shuffleArray(answers);
console.log(arr);

for (var i = 0; i < arr.length; i++) {
    columnAnswer = document.createElement('div');
    columnAnswer.className = 'col-xs-12';

    buttonAnswer = document.createElement('button');
    buttonAnswer.id = 'answer_button_'+i;
    buttonAnswer.className = 'btn btn-primary btn-sx answer_button ' + arr[i][1];
    buttonAnswer.type = 'button';
    buttonAnswer.innerHTML = arr[i][0];
    //buttonAnswer.setAttribute('onclick', 'onQuoteClick(' + quotes[i].id + ')');
    console.log(buttonAnswer);
    columnAnswer.appendChild(buttonAnswer);

    gameBody.appendChild(columnAnswer);
}

$('.answer_button').click(function () {
    var button_id = $(this).attr('id');
    if ($('#' + button_id).hasClass('right_answer')) {
        //alert('Right Answer');
        $('#info').show();
        fillInformation();
    } else {
        alert('Wrong Answer');
    }
});

}
function fillInformation() {
$('#game_title h2').html('English');
$('#info_image img').attr("src", './images/level_1.png');
$('#info_text h5').html('English Language');
}


问:
javascript on click image src change
I want to code that when I click on a image the src of this image changes to another src. But it doesn't work. Can someone help me?</p>

```<code><?php require_once("php/config.php"); ?>
<!DOCTYPE html>
<html>
<head>
<title> test </title>
<script type="text/javascript" src="javascript/liabary.js"></script>
</head>
    <body>
        <img id="img" onclick="next()" src="img/bildergalerie/bild3.jpg" id="b3" width="1000" height="500" alt="image" />
        <script type="text/javascript">

        function next() {
            var img = document.getElementByIdName("img");
            img.src = "image2.jpg";
        }
        </script>
    </body>
</html>
</code>```

答:
Since you have an ID attached to your image I suggest you to use getElementById() which only returns a single element instead of a collection.

function next() {
  var img = document.getElementById("myImg");
  img.src = "http://noticias.universia.com.br/net/images/consejos-profesionales/m/mo/mot/motivos-influenciar-mudar-imagem-profissional-noticias.jpg";
}```
<pre class="snippet-code-html lang-html prettyprint-override"><code><img class="img" id="myImg" onclick="next()" src="http://www.apicius.es/wp-content/uploads/2012/07/IMG-20120714-009211.jpg" id="b3" width="300" height="150" alt="image" /></code>```

Title: javascript on click image src change

Body:
I want to code that when I click on a image the src of this image changes to another src. But it doesn't work. Can someone help me?

<?php require_once("php/config.php"); ?>
<!DOCTYPE html>

<title> test </title>

Body:
Since you have an ID attached to your image I suggest you to use getElementById() which only returns a single element instead of a collection.

function next() {
  var img = document.getElementById("myImg");
  img.src = "http://noticias.universia.com.br/net/images/consejos-profesionales/m/mo/mot/motivos-influenciar-mudar-imagem-profissional-noticias.jpg";
}

<img class="img" id="myImg" onclick="next()" src="http://www.apicius.es/wp-content/uploads/2012/07/IMG-20120714-009211.jpg" id="b3" width="300" height="150" alt="image" />


问:
Regex for a shared path
I am having issues with a regex for server paths. I have many paths and they can differentiate like:

```<code>\\server1\folder\file
</code>```

or

```<code>\\server2\folder\subfolder\file
</code>```

I need to get the server name out of it and only the server name. I have tried using

```<code>[\\(.*?)\\]
</code>```

which gets the inverse of what I want and multiple parts rather than just the server name. What is the proper expression?

答:
This regex matches everything between the \\ and the first \:

```<code>(?<=\\\\)[^\\]*
</code>```

Explanation

(?<=\\\\)  - starts with double \

[^\\]*     - matches any character except \

Title: Regex for a shared path

Body:
I am having issues with a regex for server paths. I have many paths and they can differentiate like:

\\server1\folder\file

or

\\server2\folder\subfolder\file

I need to get the server name out of it and only the server name. I have tried using

[\\(.*?)\\]

which gets the inverse of what I want and multiple parts rather than just the server name. What is the proper expression?

Body:
This regex matches everything between the \\ and the first \:

(?<=\\\\)[^\\]*

Explanation

(?<=\\\\)  - starts with double \

[^\\]*     - matches any character except \


问:
Linq return intersection of one property in a list of objects
I have a an IEnumerable of a set of objects that contains a set of Scores.
I need to create one last object at the end of the IEnumerable that will define the Total Score.

This object contains the same columns and each will be an intersection of the properties of the objects in the list.
Ex: the property in the totalscore will represent the intersection of all the others, if at least one Fail then it should present Fail. Pass is only if all objects in the list have Pass score

This is the score definition:

```<code>public enum Score
{
    NotRated = 0x00,
    Pass = 0x01,
    Fail = 0x03
}
</code>```

I already converted the IEnumerable to a List and added a new item like this:

```<code>projectedResult.Add(
            new
            {
                Title = "Total Result",

                IOTest = from rst in projectedResult
                         rst.IOTest ... #### *1 ####,
            }
        );
</code>```

*1 - this is where I need the intersection of the same property across all objects in projectedResult

答:
Given your definition of values, and the lack of desired results if the values aren't the same,</p>

```<code>IOTest = (Score)projectedResult.Aggregate(0x00, (ttlrst, rst) => ttlrst | rst.IOTest )
</code>```

Body:
I have a an IEnumerable of a set of objects that contains a set of Scores.
I need to create one last object at the end of the IEnumerable that will define the Total Score.

This object contains the same columns and each will be an intersection of the properties of the objects in the list.
Ex: the property in the totalscore will represent the intersection of all the others, if at least one Fail then it should present Fail. Pass is only if all objects in the list have Pass score

This is the score definition:

public enum Score
{
    NotRated = 0x00,
    Pass = 0x01,
    Fail = 0x03
}

I already converted the IEnumerable to a List and added a new item like this:

projectedResult.Add(
            new
            {
                Title = "Total Result",

                IOTest = from rst in projectedResult
                         rst.IOTest ... #### *1 ####,
            }
        );

*1 - this is where I need the intersection of the same property across all objects in projectedResult

Body:
Given your definition of values, and the lack of desired results if the values aren't the same,

IOTest = (Score)projectedResult.Aggregate(0x00, (ttlrst, rst) => ttlrst | rst.IOTest )


问:
Chef - How Reboot VM and continue performing actions
In a Chef recipe, I need to perform a reboot on a Node after doing some actions,
and after the reboot is done, I need to continue doing another actions:

Recipe:
  -action 1
  -action 2
  -reboot
  -action3
  -action4....

I have checked some existing cookbook in the community: reboot-handler, chef-reboot, chef-restart, chef-dominous, but I cannot make any of them work.

Is there some method in Chef to get what I need?
Please provide detailed examples.

Thanks a lot for the help.

答:
I have done it using FLAG file method, example given below.
Example of domain join-

Blockquote

```<code>---------------------------Script Start------------------------

    powershell_script 'Domain_Join' do
    guard_interpreter :powershell_script
    code -domainJoin
    $currentTime = Get-Date
    $currentTimeString = $currentTime.ToString()

  $systemDomain = (Get-WmiObject Win32_ComputerSystem).Domain
  If (($systemDomain) -eq 'domainName')
  {
    Try {
  write-host "$env:computerName is DOMAIN MEMBER"
  Remove-Item C:\\DomainJoinFlag.txt -ErrorAction Stop
  Unregister-ScheduledTask -TaskName "Chef client schedule_DJ" -Confirm:$false
  } # end of Try
          Catch [System.Management.Automation.ItemNotFoundException]
            { write-host "Server is already domain member, Or Exception raised due to either missing FLAG file or Server startup schedule task configuration."
              eventcreate /t INFORMATION /ID 0909 /L APPLICATION /SO "ChefClient_$env:computerName" /D "Server is already domain member, Or Exception raised due to either missing FLAG file or Server startup schedule task configuration. Refer to the CHEF reciepie for DomainJoin or check Administrative credentials for creting schedule task"}
            }
    else { write-host "$env:computerName is NOT domain member, joining the server to the domain. Server will be rebooting in a while..."
            eventcreate /t INFORMATION /ID 0909 /L APPLICATION /SO "ChefClient_$env:computerName" /D "Joining the server : $env:ComputerName to the domain ININLAB.COM (Server Time): $currentTimeString"
            New-Item C:\\DomainJoinFlag.txt -type file -force
            write-host "$env:computerName DOMAIN JOIN INITIATED for the server"
            $cred = New-Object System.Management.Automation.PsCredential("domain\\domain_user", (ConvertTo-SecureString "Password" -AsPlainText -Force))
            Add-Computer -DomainName "domainName" -Credential $cred -OUPath "OU=HyperV,OU=Infrastructure,OU=Servers,DC=domain,DC=name"
            shutdown -r -t 120
            } #end_of_else
            domainJoin
  notifies :run, 'windows_task[Chef client schedule_DJ]', :immediately
end

windows_task 'Chef client schedule_DJ' do
  user 'SYSTEM'
  command 'chef-client -L C:\chef\chef-client_after_reboot_domainJoin.log'
  run_level :highest
  frequency :onstart
  frequency_modifier 30
  action :create
  only_if { ::File.exist?('C:\\DomainJoinFlag.txt') }
end

---------------------------Script Ends------------------------
</code>```

Body:
I have done it using FLAG file method, example given below.
Example of domain join-

Blockquote

---------------------------Script Start------------------------

    powershell_script 'Domain_Join' do
    guard_interpreter :powershell_script
    code -domainJoin
    $currentTime = Get-Date
    $currentTimeString = $currentTime.ToString()

  $systemDomain = (Get-WmiObject Win32_ComputerSystem).Domain
  If (($systemDomain) -eq 'domainName')
  {
    Try {
  write-host "$env:computerName is DOMAIN MEMBER"
  Remove-Item C:\\DomainJoinFlag.txt -ErrorAction Stop
  Unregister-ScheduledTask -TaskName "Chef client schedule_DJ" -Confirm:$false
  } # end of Try
          Catch [System.Management.Automation.ItemNotFoundException]
            { write-host "Server is already domain member, Or Exception raised due to either missing FLAG file or Server startup schedule task configuration."
              eventcreate /t INFORMATION /ID 0909 /L APPLICATION /SO "ChefClient_$env:computerName" /D "Server is already domain member, Or Exception raised due to either missing FLAG file or Server startup schedule task configuration. Refer to the CHEF reciepie for DomainJoin or check Administrative credentials for creting schedule task"}
            }
    else { write-host "$env:computerName is NOT domain member, joining the server to the domain. Server will be rebooting in a while..."
            eventcreate /t INFORMATION /ID 0909 /L APPLICATION /SO "ChefClient_$env:computerName" /D "Joining the server : $env:ComputerName to the domain ININLAB.COM (Server Time): $currentTimeString"
            New-Item C:\\DomainJoinFlag.txt -type file -force
            write-host "$env:computerName DOMAIN JOIN INITIATED for the server"
            $cred = New-Object System.Management.Automation.PsCredential("domain\\domain_user", (ConvertTo-SecureString "Password" -AsPlainText -Force))
            Add-Computer -DomainName "domainName" -Credential $cred -OUPath "OU=HyperV,OU=Infrastructure,OU=Servers,DC=domain,DC=name"
            shutdown -r -t 120
            } #end_of_else
            domainJoin
  notifies :run, 'windows_task[Chef client schedule_DJ]', :immediately
end

windows_task 'Chef client schedule_DJ' do
  user 'SYSTEM'
  command 'chef-client -L C:\chef\chef-client_after_reboot_domainJoin.log'
  run_level :highest
  frequency :onstart
  frequency_modifier 30
  action :create
  only_if { ::File.exist?('C:\\DomainJoinFlag.txt') }
end

---------------------------Script Ends------------------------


问:
How can I create N variables in for?
I need some way to create N variables(number greater than 1) by for?

for example, something like that:

```<code> int N=1000;
 for(int i=0; i < N; i++){
    char* var_i = malloc(sizeof(1));
    }
</code>```

NOTE: I know that the code above is not working, I wrote it just for explain my intent.

答:
If you want to declare N count variables...</p>

```<code>#include<stdio.h>
#define CHUNK 64

const int N=10; //count of the variables

int main(void){
    char* vars[N], i; //declare the array of variables

    for(i=0;i<N;i++){ //alloc variables
        vars[i]=(char*)malloc(CHUNK*sizeof(char));
        if(!vars[i]){
            printf("out of memory!");
            return 1;
        }
    }

    //do stuff

    //free memory
    for(i=0;i<N;i++)
        free(vars[i]);

    return 0;
}
</code>```

Title: How can I create N variables in for?

Body:
I need some way to create N variables(number greater than 1) by for?

for example, something like that:

 int N=1000;
 for(int i=0; i < N; i++){
    char* var_i = malloc(sizeof(1));
    }

NOTE: I know that the code above is not working, I wrote it just for explain my intent.

Body:
If you want to declare N count variables...

#include<stdio.h>
#define CHUNK 64

const int N=10; //count of the variables

int main(void){
    char* vars[N], i; //declare the array of variables

    for(i=0;i<N;i++){ //alloc variables
        vars[i]=(char*)malloc(CHUNK*sizeof(char));
        if(!vars[i]){
            printf("out of memory!");
            return 1;
        }
    }

    //do stuff

    //free memory
    for(i=0;i<N;i++)
        free(vars[i]);

    return 0;
}


问:
IIS 7.5 Tracing area "...." is not recognized - HTTP Error 500.0 - Internal Server Error
Everything was working fine and all of a sudden I started getting the following error for all my web projects and websites. One thing is for sure that this is IIS issue since the compiler is not even reach the code.

Error Message:

HTTP Error 500.0 - Internal Server Error

Tracing area "Authentication,Security,Filter,StaticFile,CGI,Compression,Cache,RequestNotifications,Module,FastCGI,WebSocket,Rewrite,RequestRouting,iisnode" is not recognized

I've already tried following things one by one but no luck:

Re-install Tracing - 'Turn Windows features on or off',

Re-install IIS,

aspnet_regiis -i (also tried with -u),

Removed ISAPI .DLL

Windows Features:

I'm using Visual Studio 2013 to build a web project (asp.net C#).

I would really appreciate any help/information on this Issue.

答:
From Richard Marr's Blog here, following solutions are listed and second solution worked for me.

Using Programs and Features find the Extension that is missing  trace areas, right click select REPAIR.

Manually add the trace areas to the Applicationhost.config file as shown below. Remember to add in the "WWW Server" xml Node.


问:
NGINX: Limit the number of connections to an upstream server
I am using NGINX as a reverse proxy to an upstream server.

Is there any way that I can limit the number of simultaneous connections NGINX establishes to the upstream server?

The desired behaviour is:

NGINX keeps a maximum of n connections to the upstream

If clients make (n + m) connections then m connections should be queued and submitted to the upstream server as soon as an established connection becomes free.

The NGINX documentation alludes to a couple of parameters in the module ngx_http_upstream_module namely max_conns and queue. The problem is that these parameters are only available in the commercial version of NGINX.

Is there any other way of achieving this behaviour without resorting to the commercial version of NGINX?

答:
For the max_conns parameter docs states that:

Since version 1.5.9 and prior to version 1.11.5, this parameter was available as part of our commercial subscription.

So, now it is available in the free public version.


问:
js call base class constructor
Is it possible to call a baseclass constructor from a class?

```<code>class BaseCls {
}

class Cls extend BaseCls {
    constructor(options){
        super(options)
    }
}

var instance = new Cls();
</code>```

Now I want an instance of the baseclas. Something like this:

```<code>var baseInstance = new Cls.parent()
</code>```

I know that I could just call new BaseCls(), but doing it the other way allows me to have only one import.

答:
The superclass is the prototype of the subclass* (which is why superclass static methods are accessible on the subclass), so Object.getPrototypeOf will give you the superclass:

class BaseCls {
    constructor() {
      console.log("BaseCls");
    }
}

class Cls extends BaseCls {
    constructor(options){
        super(options)
        console.log("Cls");
    }
}

var base = Object.getPrototypeOf(Cls);
var instance = new base();```
</div>
</div>
</p>

<p>You don't have to separate the statements, but if you want to combine them, you have to put <code>()</code> around the call to <code>Object.getPrototypeOf</code> (otherwise <code>new</code> tries to consume it):</p>

```var instance = new (Object.getPrototypeOf(Cls))();
```

<p>And of course, if you wanted to do this generically from a reference to an instance of <code>Cls</code>, it would be:</p>

```var superInstance = new (Object.getPrototypeOf(instance.constructor))();
```

<p>...provided <code>instance</code> doesn't have an own <code>constructor</code> property. Or the rather more convoluted:</p>

```var superInstance = new (Object.getPrototypeOf(Object.getPrototypeOf(instance).constructor))();
```

<p>...if it may have its own <code>constructor</code> property.</p>

<hr>

<p>* Yes, really. When you use <code>B extends A</code>, there are <em>two parallel</em> lines of inheritance set up: <code>A.prototype</code> is made the prototype of <code>B.prototype</code>, <strong>and</strong> <code>A</code> is made the prototype of <code>B</code> (whereas in ES5 and earlier, the prototype of a function was always <code>Function.prototype</code>).</p>

<p>Given:</p>

```class A {
}

class B extends A {
}
```

<p>the inheritance looks like this:</p>

```
B −−−−−−−−−−−−−−> A −−−−−−−−−−−−−−> Function.prototype

B.prototype −−−−> A.prototype −−−−> Object.prototype
```

<p><div class="snippet" data-lang="js" data-hide="true" data-console="true" data-babel="false">
<div class="snippet-code snippet-currently-hidden">
<pre class="snippet-code-js lang-js prettyprint-override"><code>class A {
}
class B extends A {
}
console.log(Object.getPrototypeOf(B) === A);
console.log(Object.getPrototypeOf(A) === Function.prototype);
console.log(Object.getPrototypeOf(B.prototype) === A.prototype);
console.log(Object.getPrototypeOf(A.prototype) === Object.prototype);</code>```

Title: js call base class constructor

Body:
Is it possible to call a baseclass constructor from a class?

class BaseCls {
}

class Cls extend BaseCls {
    constructor(options){
        super(options)
    }
}

var instance = new Cls();

Now I want an instance of the baseclas. Something like this:

var baseInstance = new Cls.parent()

I know that I could just call new BaseCls(), but doing it the other way allows me to have only one import.

Body:
The superclass is the prototype of the subclass* (which is why superclass static methods are accessible on the subclass), so Object.getPrototypeOf will give you the superclass:

class BaseCls {
    constructor() {
      console.log("BaseCls");
    }
}

class Cls extends BaseCls {
    constructor(options){
        super(options)
        console.log("Cls");
    }
}

var base = Object.getPrototypeOf(Cls);
var instance = new base();

You don't have to separate the statements, but if you want to combine them, you have to put () around the call to Object.getPrototypeOf (otherwise new tries to consume it):

var instance = new (Object.getPrototypeOf(Cls))();

And of course, if you wanted to do this generically from a reference to an instance of Cls, it would be:

var superInstance = new (Object.getPrototypeOf(instance.constructor))();

...provided instance doesn't have an own constructor property. Or the rather more convoluted:

var superInstance = new (Object.getPrototypeOf(Object.getPrototypeOf(instance).constructor))();

...if it may have its own constructor property.

* Yes, really. When you use B extends A, there are two parallel lines of inheritance set up: A.prototype is made the prototype of B.prototype, and A is made the prototype of B (whereas in ES5 and earlier, the prototype of a function was always Function.prototype).

Given:

class A {
}

class B extends A {
}

the inheritance looks like this:

B −−−−−−−−−−−−−−> A −−−−−−−−−−−−−−> Function.prototype

B.prototype −−−−> A.prototype −−−−> Object.prototype

class A {
}
class B extends A {
}
console.log(Object.getPrototypeOf(B) === A);
console.log(Object.getPrototypeOf(A) === Function.prototype);
console.log(Object.getPrototypeOf(B.prototype) === A.prototype);
console.log(Object.getPrototypeOf(A.prototype) === Object.prototype);


问:
Is using COUNT(*) or SELECT * a good idea?
I've heard several times that you shouldn't perform COUNT(*) or SELECT * for performance reasons, but wasn't able to dig up some further information about it.

I can imagine that the database is then using all columns for the action, which can be an impressive performance loss, but I'm not sure about that. Does somebody have further information about the topic?

答:
COUNT(*) is different from COUNT(column1) !

COUNT(*) returns the number of records, and does NOT use more resources, while COUNT(column1) counts the number of records where column1 is non null.

For SELECT, it is different. SELECT * will of course request more data.

ContentLicense: CC BY-SA 2.5


问:
Rspec: execute code in let and return value
I have a following code for assigning value to variable before execute test:

```<code> let!(:cash_payment){
    cash_payment = PaymentMethod.find_by_id(1)
    create(:payment_method, :cash) unless cash_payment
    return cash_payment
  }
</code>```

The problem is: after run that code block, ruby doesn't return value of cash_payment object back to cash_payment. So after that, in my test, reference to cash_payment will be nil. Please tell me how.

答:
find PaymentMethod with id 1 or create a new one:

```<code>let!(:cash_payment) { PaymentMethod.find(1) || create(:payment_method, :cash) }
</code>```

Body:
I have a following code for assigning value to variable before execute test:

 let!(:cash_payment){
    cash_payment = PaymentMethod.find_by_id(1)
    create(:payment_method, :cash) unless cash_payment
    return cash_payment
  }

The problem is: after run that code block, ruby doesn't return value of cash_payment object back to cash_payment. So after that, in my test, reference to cash_payment will be nil. Please tell me how.

Body:
find PaymentMethod with id 1 or create a new one:

let!(:cash_payment) { PaymentMethod.find(1) || create(:payment_method, :cash) }


问:
Preventing refresh upon AJAX request
I have a form in my code, and I would simply like to display the fields from that form on my webpage, using AJAX. I tried e.preventDefault() and return false but none of these seem to be working.

I trigger the submit through a button click event.

My Jquery code:

```<code>$("body").on('click', '#save', function (e) {//button which triggers submit
    $('form').submit();
    e.preventDefault();
});

$('#form').on('submit', function(e){
    e.preventDefault();
    e.stopPropagation();
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    $.ajax({
        type: 'POST',
        url: '/results',
        data: $('#form').serializeArray(),
        success: function (data) {
            //if no error from backend validation is thrown
            return false;
            $('#tabShow').html(data);
        },
        error: function () {
            alert('error');
        }
    });
</code>```

My form html is : <form class="form-horizontal" method="POST" action="/results" id="form">

In my web.php:

```<code>Route::post('/results', function() {
$m=Request::all();
var_dump($m);
});
</code>```

The problem with this code is that it refreshes the current page that I am on.
I have a save button, which should submit the form. I can't use a type submit because of my other functions.

Thank you for the help.

答: Try using return false at the end of your script (also remove preventDefault() )

Title: Preventing refresh upon AJAX request

Body:
I have a form in my code, and I would simply like to display the fields from that form on my webpage, using AJAX. I tried e.preventDefault() and return false but none of these seem to be working.

I trigger the submit through a button click event.

My Jquery code:

$("body").on('click', '#save', function (e) {//button which triggers submit
    $('form').submit();
    e.preventDefault();
});

$('#form').on('submit', function(e){
    e.preventDefault();
    e.stopPropagation();
    $.ajaxSetup({
        headers: {
            'X-CSRF-TOKEN': $('meta[name="csrf-token"]').attr('content')
        }
    });
    $.ajax({
        type: 'POST',
        url: '/results',
        data: $('#form').serializeArray(),
        success: function (data) {
            //if no error from backend validation is thrown
            return false;
            $('#tabShow').html(data);
        },
        error: function () {
            alert('error');
        }
    });

My form html is : <form class="form-horizontal" method="POST" action="/results" id="form">

In my web.php:

Route::post('/results', function() {
$m=Request::all();
var_dump($m);
});

The problem with this code is that it refreshes the current page that I am on.
I have a save button, which should submit the form. I can't use a type submit because of my other functions.

Thank you for the help.


问:
With scrapy, perform an action in a pipeline, for every n items scraped
After every time that a fixed number of scraped items in a scrapy pipeline has been processed, I'd like to perform a certain action. For example, after every 100 items, a database commit should be performed. Is there a recommended way to do this with scrapy?</p>

答:
You can use scrapy Pipelines.
in pipelines.py:

```<code>class MyPipeline:
    count = 0
    def process_item(self, item, spider)
        count += 1
        if count == 100:
            count = 0
            # do something
</code>```

and activate it in your settings.py:

```<code>ITEM_PIPELINES = {
    'mypackage.pipelines.MyPipeline': 100
}
</code>```

Body:
You can use scrapy Pipelines.
in pipelines.py:

class MyPipeline:
    count = 0
    def process_item(self, item, spider)
        count += 1
        if count == 100:
            count = 0
            # do something

and activate it in your settings.py:

ITEM_PIPELINES = {
    'mypackage.pipelines.MyPipeline': 100
}


问:
Tools, rules or processes for checking internal consistency of XML config files
I've worked on projects that have very complex XML configuration, and one problem that's faced is maintaining the internal consistency of the XML.

In this case I don't mean the strict XML schema consistency, but rather the higher level relation between the nodes used. Most problems were caused by implicit linking between information encoded in the XML, and implicit relation of that information to the codebase. Examples might be:

XML node data implicitly linked to enums in code

Business objects in the same config that are related (in that they share information that needs to be consistent) without any explicit relation between them

Code in XML to be compiled and parsed at runtime

It struck me that a) this might become a practice of increasing frequency and b) that in some cases we're implicitly creating a new coding language that's not compile-time checked -- and in fact has few checks at all until it's run.

Is anyone else out there facing similar scenarios, and are there any tools or approaches that make the problem more tractable? I'd like some general examples that are technology-agnostic -- my own specific experience has been with C# and with config for proprietary systems.

Note: although I have an answer to this below, I've no intent of taking my own as the final answer.

答:
Did you try Schematron?
http://www.schematron.com/

It's a higher level language targeted at validating XML semantically, not just syntactically.

See also Wikipedia: http://en.wikipedia.org/wiki/Schematron


问:
How to store multiple return values?
I just came to know that in Python 3.5 we can return multiple values.
So I tried to work out a piece of code that can use this feature , But the problem is that how do I store these multiple values? Kindly refer to the followig code.

```<code>def input1():
    stu=input("Enter Student Name")
    marks=int(input("Enter Student marks"))
    return stu,marks

def assign():
    s=[]
    m=[]
    i=0
    while True:
        #s[i],m[i]=input1()
        a=int(input("0 to exit"))
        i+=1
        if a==0:
            print(s)
            print(m)
            break
</code>```

stu is a string and marks is an integer.
I want to store both the values simultaneously in the arrays s[] and m[].
Just below the while block is the syntax I intended to use, but it obviously doesn't work.

Output:

Enter Student NameR
Enter Student marks45

Traceback (most recent call last):
    File "School_Rank.py", line 19, in <module>
        assign()
    File "School_Rank.py", line 12, in assign
        s[i],m[i]=input1()
    IndexError: list assignment index out of range
```

答:
These "multiple values" in the return statement is actually a tuple. So, you can assign each value of the returned tuple into two identifiers and then append these values into the lists. Here's a piece of code:

```<code>def input1():
    stu = input('Enter student name: ')
    marks = input('Enter student marks: ')

    return stu, marks

def assign():
    s = []
    m = []

    stu, marks = input1()
    s.append(stu)
    m.append(marks)
    .#etc...
</code>```

You're getting an error because you're trying to access the position i and then set its value to whatever you want when the position i doesn't exist yet. I hope I helped you.

Title: How to store multiple return values?

Body:
I just came to know that in Python 3.5 we can return multiple values.
So I tried to work out a piece of code that can use this feature , But the problem is that how do I store these multiple values? Kindly refer to the followig code.

def input1():
    stu=input("Enter Student Name")
    marks=int(input("Enter Student marks"))
    return stu,marks

def assign():
    s=[]
    m=[]
    i=0
    while True:
        #s[i],m[i]=input1()
        a=int(input("0 to exit"))
        i+=1
        if a==0:
            print(s)
            print(m)
            break

stu is a string and marks is an integer.
I want to store both the values simultaneously in the arrays s[] and m[].
Just below the while block is the syntax I intended to use, but it obviously doesn't work.

Output:

Enter Student NameR
Enter Student marks45

Traceback (most recent call last):
    File "School_Rank.py", line 19, in <module>
        assign()
    File "School_Rank.py", line 12, in assign
        s[i],m[i]=input1()
    IndexError: list assignment index out of range

Body:
These "multiple values" in the return statement is actually a tuple. So, you can assign each value of the returned tuple into two identifiers and then append these values into the lists. Here's a piece of code:

def input1():
    stu = input('Enter student name: ')
    marks = input('Enter student marks: ')

    return stu, marks

def assign():
    s = []
    m = []

    stu, marks = input1()
    s.append(stu)
    m.append(marks)
    .#etc...

You're getting an error because you're trying to access the position i and then set its value to whatever you want when the position i doesn't exist yet. I hope I helped you.


问:
Rendering components in different containers while sharing state
I have an HTML page pre-rendered by WordPress and three React components: <App />, <Component /> and <AnotherComponent />.

There are two ID div containers inside the HTML page (div id="component" and div id="anotherComponent") that are separated and I want to render React components on. Also they share some state. I want to use <App /> to write all the logic and event handling and then pass state (this.props.counter) to each component.

I would like to use ReactDOM.render(<Component />, document.getElementById('component')); for each component and use the <App /> to control the logic but how would I pass state to each component, and what would I render() in the <App />.

What is the best way to go with this one?

答:
ReactDOM.render is like the main method of a React application. All the react related concepts like components, state, and context starts from here. You can call ReactDOM.render multiple times on the same page with the same container DOM node or different container DOM nodes. If the container is the same, this will perform an update on it and only mutate the DOM as necessary to reflect the latest React element. But if container nodes are different, it will create two different React roots and those are totally independent of each other. There is no shared state or context between these two React roots and it's pretty much like running two different React applications on the same page.

Also, after rendering root element with ReactDOM.render into a container node, all other descendant elements will be rendered inside it by React and we don't have any control to change where they get rendered (this will change in the future).

So in your case, if you want to render these two components in different container nodes, you won't be able to have an App component which keeps a shared state or event handling. But instead of that you can create two different React roots and share objects and methods between them via props.

```<code>const data = {/*...*/}

ReactDOM.render(<Component data={data} />,
  document.getElementById('component'));

ReactDOM.render(<AnotherComponent data={data} />,
  document.getElementById('anotherComponent'));
</code>```

However, if you want to change these props at some point you will have to rerender the root component manually. As an example, if you have a counter variable which updates in every second you have to rerender your roots with each new value.

```<code>let couter = 0

setInterval(function(){
  counter++

  ReactDOM.render(<Component data={data} />,
    document.getElementById('component'));

  ReactDOM.render(<AnotherComponent data={data} />,
    document.getElementById('anotherComponent'));

}, 1000)
</code>```

Another good alternative will be using a Redux like state management library. You can have a single store and share it between two roots. I highly recommend this approach if you need to share a very complex state between two roots.

```<code>const store = createStore(/* ... */)

// ...

ReactDOM.render(
    <Provider store={store}>
        <Component />
    </Provider>,
    document.getElementById('component')
);

ReactDOM.render(
    <Provider store={store}>
        <AnotherComponent />
    </Provider>,
    document.getElementById('anotherComponent')
);
</code>```

When you use Redux, you will connect your Component and AnotherComponent to the store with connect higher-order component. Under the hood, this will subscribe your component to store changes and rerender the component when the state is changed using component's forceUpdate method. So you don't have to manually call the ReactDOM.render method as long as you change the state by dispatching actions to the store.

Body:
ReactDOM.render is like the main method of a React application. All the react related concepts like components, state, and context starts from here. You can call ReactDOM.render multiple times on the same page with the same container DOM node or different container DOM nodes. If the container is the same, this will perform an update on it and only mutate the DOM as necessary to reflect the latest React element. But if container nodes are different, it will create two different React roots and those are totally independent of each other. There is no shared state or context between these two React roots and it's pretty much like running two different React applications on the same page.

Also, after rendering root element with ReactDOM.render into a container node, all other descendant elements will be rendered inside it by React and we don't have any control to change where they get rendered (this will change in the future).

So in your case, if you want to render these two components in different container nodes, you won't be able to have an App component which keeps a shared state or event handling. But instead of that you can create two different React roots and share objects and methods between them via props.

const data = {/*...*/}

ReactDOM.render(<Component data={data} />,
  document.getElementById('component'));

ReactDOM.render(<AnotherComponent data={data} />,
  document.getElementById('anotherComponent'));

However, if you want to change these props at some point you will have to rerender the root component manually. As an example, if you have a counter variable which updates in every second you have to rerender your roots with each new value.

let couter = 0

setInterval(function(){
  counter++

  ReactDOM.render(<Component data={data} />,
    document.getElementById('component'));

  ReactDOM.render(<AnotherComponent data={data} />,
    document.getElementById('anotherComponent'));

}, 1000)

Another good alternative will be using a Redux like state management library. You can have a single store and share it between two roots. I highly recommend this approach if you need to share a very complex state between two roots.

const store = createStore(/* ... */)

// ...

ReactDOM.render(
    <Provider store={store}>
        <Component />
    </Provider>,
    document.getElementById('component')
);

ReactDOM.render(
    <Provider store={store}>
        <AnotherComponent />
    </Provider>,
    document.getElementById('anotherComponent')
);

When you use Redux, you will connect your Component and AnotherComponent to the store with connect higher-order component. Under the hood, this will subscribe your component to store changes and rerender the component when the state is changed using component's forceUpdate method. So you don't have to manually call the ReactDOM.render method as long as you change the state by dispatching actions to the store.


问:
Table not updated when user logout
What is the proper way to indicate in your db when a user is logout of an application.

```<code>session::start();
$username = session::check()["username"];
$link->query("UPDATE admin SET isOnline = 0 WHERE username = '".$username."'");
session::destroy();
exit;
</code>```

This is my current implementation.

答:
This is what I used: </p>

```<code>$query = "UPDATE Logins SET logouttime='$logouttime' WHERE Email='$Email' AND
            fromproxy='$pipaddress' AND fromip='$ipaddress'";
unset($_SESSION);
</code>```

Title: Table not updated when user logout

Body:
What is the proper way to indicate in your db when a user is logout of an application.

session::start();
$username = session::check()["username"];
$link->query("UPDATE admin SET isOnline = 0 WHERE username = '".$username."'");
session::destroy();
exit;

This is my current implementation.

Body:
This is what I used:

$query = "UPDATE Logins SET logouttime='$logouttime' WHERE Email='$Email' AND
            fromproxy='$pipaddress' AND fromip='$ipaddress'";
unset($_SESSION);


问:
Simplest Way to Automate Appending De-Duped Data to BigQuery from Google Cloud
I'm not a developer so please bear with me on this. I wasn't able to follow the PHP-based answer at Google BigQuery - Automating a Cron Job, so I don't know if that's even the same thing as what I'm looking for.

Anyway, I use Google Cloud to store data, and several times throughout the day data is uploaded into CSVs there. I use BigQuery to run jobs to populate BigQuery tables with the data there.

Because of reasons beyond my control, the CSVs have duplicate data. So what I want to do is basically create a daily ETL to append all new data to the existing tables, perhaps running at 1 am every day:

Identify new files that have not been added (something like date = today - 1)

Run a job on all the CSVs from step 1 to convert them to a temporary BigQuery table

De-dupe the BigQuery table via SQL (I can do this in a variety of ways)

Insert the de-duped temp table into the BigQuery table.

Delete the temp table

So basically I'm stuck at square 1 - I don't know how to do any of this in an automated fashion. I know BigQuery has an API, and there's some documentation on cron jobs, and there's something called Cloud Dataflow, but before going down those rabbit holes I was hoping someone else may have had experience with this and could give me some hints. Like I said, I'm not a developer so if there's a more simplistic way to accomplish this that would be easier for me to run with.

Thanks for any help anyone can provide!

答:
So no offense to Graham Polley but I ended up using a different approach. Thanks to these pages (and a TON of random Batch file Google searching and trial and error):

how to get yesterday's date in a batch file

https://cloud.google.com/bigquery/bq-command-line-tool

cscript //nologo C:\Desktop\yester.vbs > C:\Desktop\tempvar.txt &&

set /p zvar =< C:\Desktop\tempvar.txt &&

del C:\Desktop\tempvar.txt &&

bq load
    --skip_leading_rows=1
    data.data_%%zvar:~0,4%%%%zvar:~4,2%%%%zvar:~6,2%%_1
    gs://mybucket/data/%%zvar:~0,4%%-%%zvar:~4,2%%-%%zvar:~6,2%%*.csv.gz
    Timestamp:TIMESTAMP,TransactionID:STRING &&

bq query --destination_table=data.data_%%zvar:~0,4%%%%zvar:~4,2%%%%zvar:~6,2%%2 "SELECT * FROM data.data%%zvar:~0,4%%%%zvar:~4,2%%%%zvar:~6,2%%_1 group by 1,2" &&

bq cp -a data.data_%%zvar:~0,4%%%%zvar:~4,2%%%%zvar:~6,2%%_2 data.data &&

bq rm -f data.data_%%zvar:~0,4%%%%zvar:~4,2%%%%zvar:~6,2%%_1 &&

bq rm -f data.data_%%zvar:~0,4%%%%zvar:~4,2%%%%zvar:~6,2%%_2

A VB script called yester.vbs prints out yesterday's date in YYYYMMDD format. This is saved as a variable which is used to search for yesterday's data files in GCS and output to a table, from which a de-duped (via grouping by all columns) table is created. This is then appended to the main table, and the two intermediate tables are deleted.

The double percent signs are shown because it's saved as .CMD file and run through Windows Task Scheduler.