text:
Q: Android create reusable style I want to create a style (or something i don't know its name),and then reuse it, my screen will have more than 100 items , each item contains from picture and a textview, i don't think it is a good way to make 100 layout in my xml file, i think that there is a way to create one time (that hold picture and a textview) and then in my activity i resue it. any suggestions please?

A: HEre is a link to Fragments From Android And below is code to a project using fragments
The code below also uses universalimageloader and ActionBarSherlock although i didnt really do much with the actionbar. This code also uses interfaces that communicate between the fragments and the main SherlockFragmentActivity.
I have shown 2 different fragments being used. List fragment that can load data from one site or another and a Details fragment that gets its data from a interface setup with the Fragment Control Activity.
The Details Fragment
import java.util.HashMap;

import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragment;
import com.nostra13.universalimageloader.core.DisplayImageOptions;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.display.RoundedBitmapDisplayer;

public class DetailsFrag extends SherlockFragment {
public static final String TAG = "detailsfrag";
private boolean typeFlag;
private GetData gd;
private DisplayImageOptions dio = null;
private ImageLoader il;
private ImageView image;
private TextView name;
private TextView data_box_1;
private TextView data_box_2;
private HashMap<String, Object> fragData;

static DetailsFrag newInstance() {
    DetailsFrag frag = new DetailsFrag();

    return frag;
}

public interface GetData {
    public HashMap<String, Object> getData();
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        gd = (GetData) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement GetData");
    }
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
}

@Override
public View onCreateView(LayoutInflater inflate, ViewGroup container,
        Bundle savedInstanceState) {
    setRetainInstance(true);
    setHasOptionsMenu(true);
    il = ImageLoader.getInstance();
    dio = new DisplayImageOptions.Builder()
            .showStubImage(R.drawable.kzfr_logo).cacheInMemory()
            .cacheOnDisc().displayer(new RoundedBitmapDisplayer(20))
            .build();
    View result = inflate.inflate(R.layout.details_frag, container, false);
    image = (ImageView) result.findViewById(R.id.image);
    data_box_1 = (TextView) result.findViewById(R.id.data_box_1);
    data_box_2 = (TextView) result.findViewById(R.id.data_box_2);
    name = (TextView) result.findViewById(R.id.name);

    fragData = gd.getData();

    String imagePath = (String) fragData.get("image");
    il.displayImage(imagePath, image, dio);
    Toast.makeText(getSherlockActivity(), "Image path " + imagePath,
            Toast.LENGTH_LONG).show();
    String title = (String) fragData.get("title");
    name.setText(title);
    String times = (String) fragData.get("times");
    data_box_1.setText(times);
    String data2 = (String) fragData.get("short_description");
    data_box_2.setText(data2);
    return result;
}

}

Here is the List Fragment
    import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;

import java.io.InputStreamReader;
import java.net.URL;
import java.net.URLConnection;
import java.util.HashMap;
import java.util.List;

import org.json.JSONArray;
import org.json.JSONException;

import android.app.Activity;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.ListView;
import android.widget.SimpleAdapter;

import com.actionbarsherlock.app.SherlockListFragment;

public class ListFrag extends SherlockListFragment {
public static final String TAG = "listfrag";
private boolean typeFlag;
private String mainUrl;
private SetDetails sd;
private List<HashMap<String, Object>> data;

static ListFrag newInstance(boolean type) {
    ListFrag frag = new ListFrag();
    Bundle args = new Bundle();
    args.putBoolean("type", type);
    frag.setArguments(args);
    return frag;
}

public interface SetDetails {
    public void setDetails(HashMap<String, Object> details);
}

@Override
public void onAttach(Activity activity) {
    super.onAttach(activity);
    try {
        sd = (SetDetails) activity;
    } catch (ClassCastException e) {
        throw new ClassCastException(activity.toString()
                + " must implement setDetails");
    }
}

@Override
public void onListItemClick(ListView l, View v, int position, long id) {
    super.onListItemClick(l, v, position, id);
    sd.setDetails(data.get(position));
}

@Override
public void onActivityCreated(Bundle savedInstanceState) {
    super.onActivityCreated(savedInstanceState);
    setRetainInstance(true);
    // set the type of the listview. Hosts or Programs.
    setType();
    if (typeFlag) {
        mainUrl = "http://website.org/api/dataset1";
    } else {
        mainUrl = "http://website.org/api/dataset2";
    }

    // begin a download task to download the data needed to populate the
    // correct list view.
    if (!checkAdapter()) {
        DownloadTask dlTask = new DownloadTask();
        dlTask.execute(mainUrl);
    } else {
        SimpleAdapter adapter = (SimpleAdapter) getListAdapter();
        adapter.notifyDataSetChanged();
    }
}

public boolean checkAdapter() {
    SimpleAdapter adapter = (SimpleAdapter) getListAdapter();
    if (adapter != null)
        return true;
    else
        return false;
}

@Override
public void onViewCreated(View view, Bundle savedInstanceState) {
    super.onViewCreated(view, savedInstanceState);
}

@Override
public void onResume() {
    super.onResume();
    // SimpleAdapter adapter = (SimpleAdapter) getListAdapter();
    // if (adapter != null)
    // adapter.notifyDataSetChanged();
}

private void setType() {
    Bundle args = this.getArguments();
    typeFlag = args.getBoolean("type");
}

private boolean checkType() {
    return typeFlag;
}

/*
 * This method connects to the specified url and returns data ready to be
 * parsed.
 */
private String downloadUrl(String strUrl) throws IOException {
    String data = "";
    InputStream in = null;

    try {
        URL url = new URL(strUrl);
        URLConnection urlConnect = (URLConnection) url.openConnection();
        urlConnect.connect();

        in = urlConnect.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(
                urlConnect.getInputStream()));

        StringBuffer sb = new StringBuffer();

        String line = "";

        while ((line = br.readLine()) != null) {
            sb.append(line);
        }
        data = sb.toString();
        br.close();

    } catch (Exception e) {
        Log.d("Exception while downloading url", e.toString());
    } finally {
        in.close();
    }
    return data;
}

private class DownloadTask extends AsyncTask<String, Integer, String> {
    String data = null;

    @Override
    protected String doInBackground(String... url) {
        try {
            data = downloadUrl(url[0]);
        } catch (Exception e) {
            Log.d("Background Task", e.toString());
        }
        return data;
    }

    @Override
    protected void onPostExecute(String result) {

        ListViewLoaderTask lvLoader = new ListViewLoaderTask();
        lvLoader.execute(result);
    }
}

private class ListViewLoaderTask extends
        AsyncTask<String, Void, ImageLoaderListAdapter> {
    ImageLoaderListAdapter adapter = null;
    int count;
    HashMap<String, Object> hm = null;
    String imgUrl = null;
    String url = "http://website.org/u/img/original/";

    @Override
    protected ImageLoaderListAdapter doInBackground(String... jsonStr) {
        List<HashMap<String, Object>> things = null;
        JSONArray jArray = null;
        try {
            jArray = new JSONArray(jsonStr[0]);
        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String[] from = { "title", "image", "short_description" };
        int[] to = { R.id.program_title, R.id.program_image,
                R.id.short_description };
        if (checkType()) {

            data1JSONParser data1Parser = new data1JSONParser();
            try {
                things = data1Parser.parse(jArray);
            } catch (Exception e) {
                Log.d("Exception", e.toString());
            }

        } else {

            data2JSONParser data2Parser = new data2JSONParser();
            try {
                things = data2Parser.parse(jArray);
            } catch (Exception e) {
                Log.d("Exception", e.toString());
            }
        }

        count = things.size();
        for (int i = 0; i < count; i++) {
            hm = (HashMap<String, Object>) things.get(i);
            imgUrl = (String) hm.get("image");
            if (!imgUrl.equalsIgnoreCase("false")) {
                imgUrl = url + imgUrl;
                hm.put("image", imgUrl);

            }
        }
                    //ImageLoaderListAdapter is a Simple List Adapter that uses Universal Image
                    //Loader to load its images if possible.
        adapter = new ImageLoaderListAdapter(getSherlockActivity()
                .getBaseContext(), things, R.layout.rowlayout, from, to);
        data = things;
        return adapter;
    }

    @Override
    protected void onPostExecute(ImageLoaderListAdapter adapter) {

        setListAdapter(adapter);
        ImageLoaderListAdapter ad = (ImageLoaderListAdapter) getListAdapter();
        ad.notifyDataSetChanged();
    }
}

}

Here is the Fragment Control Activity I
import java.util.ArrayList;
import java.util.HashMap;

import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;

import android.widget.Toast;

import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.appdomum.doublea.DayFragment.UpdateList;
import com.appdomum.doublea.DetailsFrag.GetData;
import com.appdomum.doublea.ListFrag.SetDetails;
import com.appdomum.doublea.RadioStream.OnProgramSelectedListener;
import com.appdomum.doublea.ScheduleFrag.UpdateSchedule;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.ImageLoaderConfiguration;

public class FragmentControl extends SherlockFragmentActivity implements
    GetData, SetDetails {
protected ImageLoader imageLoader = ImageLoader.getInstance();

private ListFrag data1Frag;
private ListFrag data2Frag;
private DetailsFrag detailsFrag;
private Fragment visible;
private Fragment mVisibleCached;
private boolean instanceStateSaved;
private HashMap<String, Object> details = null;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_fragment_control);
    setupFragments();
    ImageLoaderConfiguration config = ImageLoaderConfiguration
            .createDefault(getApplicationContext());
    imageLoader.init(config);
}

public void setupFragments() {
    final FragmentManager fm = getSupportFragmentManager();
    final FragmentTransaction ft = fm.beginTransaction();

    data1Frag = ((ListFrag) fm.findFragmentByTag("data1".TAG));
    if (data1Frag == null) {
        data1Frag = ListFrag.newInstance();
        ft.add(R.id.fragment_container, data1Frag , "data1".TAG);
    }
    visible = data1Frag ;

    ft.commit();
}

@Override
public void onBackPressed() {
    super.onBackPressed();
    visible = mVisibleCached;

}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getSupportMenuInflater()
            .inflate(R.menu.activity_fragment_control, menu);
    return true;
}

@Override
protected void onDestroy() {
    if (!instanceStateSaved) {
        imageLoader.stop();
    }
    super.onDestroy();
}

@Override
public void onSaveInstanceState(Bundle outState) {
    instanceStateSaved = true;
}

public void showFragment(int fragIn) {
    int inFrag = fragIn;
    final FragmentManager fm = getSupportFragmentManager();
    final FragmentTransaction ft = fm.beginTransaction();

    ft.setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
    if (visible != null) {

        ft.hide(visible);
        mVisibleCached = visible;

    }
    switch (fragIn) {
    case 0:
        data1Frag = ((ListFrag) fm.findFragmentByTag(data1));
        if (data1Frag == null) {
            data1Frag = ListFrag.newInstance(false);
            ft.replace(R.id.fragment_container, data1Frag ,
                    "data1");
        } else {
            ft.replace(R.id.fragment_container, data1Frag ,
                    "data1");

            if (!data1Frag .isVisible()) {
            }
        }
        ft.addToBackStack(null);
        visible = data1Frag ;
        break;
    case 1:
        data2Frag= ((ListFrag) fm.findFragmentByTag("data2"));
        if (data2Frag== null) {
            data2Frag= ListFrag.newInstance(true);
            ft.replace(R.id.fragment_container, data2Frag, "data2");
        } else {
            ft.replace(R.id.fragment_container, data2Frag, "data2");

            if (!data2Frag.isVisible()) {
            }
        }
        ft.addToBackStack(null);
        visible = data2Frag;
        break;
    case 2:
        detailsFrag = ((DetailsFrag) fm.findFragmentByTag(DetailsFrag.TAG));
        if (detailsFrag == null) {
            detailsFrag = DetailsFrag.newInstance();
            ft.replace(R.id.fragment_container, detailsFrag,
                    DetailsFrag.TAG);
        } else {
            ft.replace(R.id.fragment_container, detailsFrag,
                    DetailsFrag.TAG);
            if (!detailsFrag.isVisible()) {
            }
        }
        ft.addToBackStack(null);
        visible = detailsFrag;
        break;
    }
    ft.commit();
}

@Override
public HashMap<String, Object> getData() {
    return details;
}

@Override
public void setDetails(HashMap<String, Object> data) {
    this.details = data;
    showFragment(2);
}

}

Here is the layout for Fragment Control
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".FragmentControl" >

    <FrameLayout
        android:id="@+id/fragment_container"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" />

</RelativeLayout>

Layout for the Details Frag
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:background="@drawable/woodtileback"
android:padding="10dp" >

<TextView
    android:id="@+id/name"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:layout_centerHorizontal="true"
    android:paddingBottom="5dip"
    android:paddingTop="10dip"
    android:textAlignment="center" />

<ImageView
    android:id="@+id/image"
    android:layout_width="300dip"
    android:layout_height="300dip"
    android:layout_below="@id/name"
    android:layout_centerHorizontal="true"
    android:clickable="true"
    android:contentDescription="@string/programdescription" />

<TextView
    android:id="@+id/data_box_1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/image"
    android:layout_centerHorizontal="true"
    android:padding="5dp"
    android:textAlignment="center" />

<TextView
    android:id="@+id/data_box_2"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_below="@id/data_box_1"
    android:layout_centerHorizontal="true"
    android:padding="5dp"
    android:textAlignment="center" />

</RelativeLayout>

Layout for List Row
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingRight="5dp" >

<ImageView
    android:id="@+id/program_image"
    android:layout_width="100dip"
    android:layout_height="100dip"
    android:layout_alignParentLeft="true"
    android:layout_centerVertical="true"
    android:contentDescription="@string/programdescription"
    android:padding="5dp" />

<LinearLayout
    android:id="@+id/details"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_toRightOf="@id/program_image"
    android:orientation="vertical" >

    <TextView
        android:id="@+id/program_title"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="left" />

    <TextView
        android:id="@+id/short_description"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="left" />
</LinearLayout>

</RelativeLayout>


text:
Q: 1 IV, two levels; 2 DVs (one post-test only, one pre-test & post-test). Have some ideas but unsure. Cliche question but:What stats test to use? I'm working on a proposal and trying to get my stats tests right. Been doing some reading and while I'm beginning to get a better grasp of things, I'm still a little puzzled as to what stats test to use.
Here is my situation:
I am doing a study in which I want to study the effect of a game on students performance and motivation:
IV: Two levels; Treatment and Control.
DV: Performance will be measured using a pre-test post-test maths quiz.
For motivation however, I'm only doing a post-test. (If anyone is curious, I'm using Keller's Instructional Material Motivation Survery (IMMS)). The reason being is that it measures motivation in relation to the game (which is what I want). Hence, a pre test would not be possible as it contains items such as "The game is attractive to me" something that can only be measured after treatment.
Hence, one DV will have pre-test & post-test scores while the other will only have post-test scores
The possible ways of designing my study that I have seen so far are:

*

*MANCOVA on the post-treatment scores (motivation and performance), with pre-treatment score (performance) as a covariate and treatment as an independent variable. [I don't even know if this makes sense. The fact that I don't have a pre-test for motivation is kinda throwing me off]

*Mixed MANOVA - Two within-subject factor (pre vs. post-test) and one between-subject factor (treatment vs. control). [Again, thrown off because I don't have a pre-test for motivation. Should I put my pre-test for motivation as 0 then? I thinking that way because their motivation WOULD technically be zero as they have never played the game before]

*MANOVA - 1 IV (treatment and control), 2 DV (post-pre performance & motivation)
That's what I have so far. What do you think of the above and ss there a (hopefully) simpler design I could go with?

redpajama_set_name: RedPajamaStackExchange


text:
Q: How to spatially join OSM point to road data? Using QGIS 2.16.1 , using shape layers, with the same CRS, I am having two  line and a point layer.  The point layer was added by the plugin : locate points along lines" The third layer is the downloaded layer "roads" (shape-OSM) from geofabrik. I want to add the streetnames from the roads layer to the points layer. The points are on te line.....  If possible without extra steps like buffers..

Which spatial join should I use? And, do I use intersect/touches/crosses etc?

A: What you want is transferring attributes from one geometry to another depending on how they relate so the tool to use is "Join attributes by location".
You want to transfer them if they touch in any way so just use "intersects".
As there is zero chance that your points actually lie on the infinitely thin vector lines, you should adjust the "precision" value. What kind of value makes sense depends on your data and coordinate reference system. An alternative would be buffering the points, joining the attributes to the buffers, then join them back to the points on "within".

A: Thanks for answering!  I couldn't find the "join by location"in QGIS 2.16.1 After deleting the other QGIS versions I could. But it didn't do the job for me really.
So, I chose another way: in stead of buffering the points, I buffered the network, so that the points are within it! Then I used the "spatial join" plugin. This works great for me!


text:
Q: Highlight selected row in primeng table without checking the checbox I am using primeng p-table along with p-checkbox. I want to be able to highlight the clicked row (or the row content) without checking the checkbox. The Checkbox should be checked on clicking the checkbox itself, not the row.
I tried using [pSelectableRow] but it also checks the checkbox in addition to highlighting it.

    <ng-template pTemplate="header" let-columns>

                {{col.header}}

    </ng-template>
    <ng-template pTemplate="body" let-rowData let-columns="columns">

                {{rowData[col.field]}}

    </ng-template>

What should I do to only highlight the clicked row, not check the checkbox?
I have created a Stackblitz sample.

A: Add some class on the rows

Then in css do the trick
.some-class:hover {
  background-color: some color... or put any style you need
}

A: I was able to achieve this by maintaining a variable highlight that gets the clicked row value and assigning the highlight class only to rows where this value is equal to that of the clicked row.
<ng-template pTemplate="body" let-rowData let-columns="columns">

                 {{rowData[col.field]}}

    </ng-template>

Updated Stackblitz here.


text:
Q: Apache: The given path contained wildcard characters The problem is not a persistent one; it happens sometimes and I am unable to recreate it (even using the same urls).

[Tue Dec 20 09:07:12 2011] [error] [client 66.249.66.169] (20025)The
given path contained wildcard characters: access to /?p=2463 failed
[Tue Dec 20 10:10:30 2011] [error] [client 110.0.107.198] (20025)The given path contained wildcard characters: access to /proxyimages.php?url=http%3A%2F%2Fi.imgur.com%2F2DKZ0.jpg&mimeType=image%2Fjpeg failed

I am using a Wordpress blog with some modifications, and since a while a go i have been getting a lot of those errors from apache, and google results for this problem aren't helpful...
Any ideas?
EDIT:
Some virtual hosts are only thing different from the clean httpd.conf
<VirtualHost *:80>
    DocumentRoot C:/xampp/htdocs/
    ServerName 94.102.49.102
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot C:/xampp/htdocs/site1
    ServerName www.site1.com
    ServerAlias site1.com *.site1.com
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot C:/xampp/htdocs/site2
    ServerName www.site2.info
    ServerAlias site2.info *.site2.info
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot C:/xampp/htdocs/site3
    ServerName www.site3.com
    ServerAlias site3.com *.site3.com
</VirtualHost>

And the .htaccess generated by wordpress
# BEGIN WordPress
<IfModule mod_rewrite.c>
RewriteEngine On
RewriteBase /
RewriteRule ^index\.php$ - [L]
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule . /index.php [L]
</IfModule>
# END WordPress

A: The problem is that there is a character that is being inserted into URLs that needs to be escaped or removed. Some rule somewhere in apache is placing that character. You must take into account any rewrite rule or AliasMatch rule.
Copy your existing httpd.conf file and put a vanilla conf in its place. See if the problem exists. diff the two files and start adding blocks back in one at a time and testing your server. If you use mod_alias, disable that and see if the problem persists. It's also possible that you're inheriting some troublesome regex in an .htaccess file somewhere. Check those and rule out any possibility there.
Once you've narrowed the issue down, you can report back and we can be of more help.
Edit 1
This is sounding like an application error. It could be something with one of your Wordpress plugin. The errors suggest that something is throwing unescaped characters into your URLs. Perhaps a decodeURI function. Of primary concern is any rewriting that is happening to pull in files and documents that are outside of the web server's document root.
Disable all plugins in your wordpress installation and check for errors. Add them back in one at a time and see when the errors resurface.

A: The 5th line in your .htaccess file looks funny. Also, AFAIK, it's not part of the default permalink rewrite ruleset in WordPress. Try removing (or just commenting out) the line. this is the one I'm talking about:

RewriteRule ^index\.php$ - [L]

Also, as it is a [L]ast rule, the rest is deferred after this rule is processed, so it would not make sense to have them there it that line was intended. Please remove it and let us know about the result


text:
Q: How To Simplify This Code In Wordpress Function? I'm Trying to make a function, my code works but i wonder is there any way to simplify my code? with loop maybe?
Background:
I try to show data from usermeta (the usermeta from plugin)
so these are the meta key:

*

*child_name

*child_name_1

*child_name_2

*child_name_3

and so on.. based on how much user input their children in database.
example, if user only input 2 children, meta key will be:

*

*child_name

*child_name_1

temporary, i limit only 3 children to input, because i can't simplify it.
function get_child_name(){

$user = wp_get_current_user();
$count_extra_field = $user->wppb_repeater_field_15_extra_groups_count;
$count_child = $count_extra_field + 1;

$child_name_0 = $user->child_name;
$child_name_1 = $user->child_name_1;
$child_name_2 = $user->child_name_2;

$child_names = array($child_name_0,$child_name_1,$child_name_2);

$n=0;
foreach($child_names as $child_name) {
if($n==$count_child) break;
$n++;
echo $child_name;
}
}
add_shortcode('child_names', 'get_child_name');

Above code is works, as I use it now.
but is it possible to simplify it / automate the process?
So, user can input as many children as possible.
or if I want to increase the limit (for input children names) I don't have to add the code again manually, is it possible?

A: I have tried to simplify the code. Meta fields are being created dynamically based on index. Please check code below. With this you dont have to touch this function again when you want to increase the number of fields.
function get_child_name(){

    $user = wp_get_current_user();

    $count_extra_field = $user->wppb_repeater_field_15_extra_groups_count;

    $names = array();

    for ( $i = 0; $i < $count_extra_field; $i++ ) {
        $meta_key = 'child_name';
        $key_suffix = ( 0 === $i ) ? '' : '_' . $i ;
        $meta_key .= $key_suffix;

        if ( $user->$meta_key ) {
            $names[] = $user->$meta_key;
        }
    }

    if ( ! empty( $names ) ) {
        foreach ( $names as $name ) {
            echo $name;
        }
    }
}


text:
Q: the_title() & the_content() are retrieving Post details inside a Page, after calling a shortcode I'm trying to create a custom theme, since I need to convert html pages to be used at WordPress.
In about.php page, I have this shortcode to retrieve posts of a category:
<?php echo do_shortcode('[categoryposts catname="about-section-1"]'); ?>
functions.php:
 function wpb_postsbycategory($atts='') {

    // Get parameters\attributes from shortcode
    $attributes = shortcode_atts(
        array(
            'catname' => '',//this is default value
        ),
        $atts,
        'featured'
    );

   // the query
   $the_query = new WP_Query( array(
       'category_name' => $attributes['catname'],
       'posts_per_page' => 5
   ) );

   // The Loop
   $string = "";
   if ( $the_query->have_posts() ) {
       $string .= '
';
       while ( $the_query->have_posts() ) {
           $the_query->the_post();
               if ( has_post_thumbnail() ) {
                    $string .= '
';
                    $string .= '' . get_the_post_thumbnail($post_id, array( 50, 50) ) . get_the_title() .'
';
               } else {
                    // if no featured image is found
                    $string .= '
' . get_the_title() .'
';
               }
            }
    } else {
        // no posts found
        $string .= '
No Posts Found
';
   }
   $string .= '
';

   return $string;

   /* Restore original Post Data */
   wp_reset_postdata();
 }
 // Add a shortcode
 add_shortcode('categoryposts', 'wpb_postsbycategory');

Though about.php is a PAGE (since I linked it using Template Name), if I use the_title() & the_content():

*

*before the shortcode line, they properly get current Page title & content.

*but after the shortcode line, they wrongly get some Post title & content.

Question:
How can I retrieve Page title & content (instead of Post), after having used shortcode? Do I need some reset functionality?

A:
Do I need some reset functionality?

Yes, you do — when you call $the_query->the_post(), the global $post variable will be modified so that the the_ functions like the_title(), the_content() and the_permalink() will use the current post in your custom loop, and thus after the loop ends, you should call wp_reset_postdata() in order to restore the $post global to the current post in the main query (that's referenced via the global $wp_query variable), because otherwise then the issue in question would happen.
And your code/function is actually calling wp_reset_postdata(), except that it never got called because it's called after the return line, i.e. you did return $string; wp_reset_postdata();..
So you would just need to swap their position, like so:
wp_reset_postdata(); // call this first

return $string;      // then return the output

But I would probably call the function right after the while block ends, i.e. while ( ... ) { ... } wp_reset_postdata();, because there's nothing to reset if the $the_query->the_post() didn't run.
Additionally, the $post_id as in get_the_post_thumbnail($post_id, array( 50, 50) ) is never defined in your code, so you should change that to get_the_ID(), or use null instead to use the current post in your loop.


text:
Q: Whats the best (fastest) way to scape webpages? I'm trying to scrape data from Google Patents and finding the execution time takes too long. How can I increase the speed? Running through 8000 patents took 7 hours already...
Here's an example of a patent.
I need to get data from the tables below and write them to a csv file. I think the bottle neck is at WebDriverWait(driver, 10).until(EC.presence_of_element_located((By.XPATH, "//div[@class='table style-scope patent-result']")))
Is this necessary or can I use find_elements_by_css_selector and check if that returns anything?
#...
from selenium.webdriver.support import expected_conditions as EC
#...

##  read file of patent numbers and initiate chrome

url = "https://patents.google.com/patent/US6403086B1/en?oq=US6403086B1"

for x in patent_number:

    #url = new url with new patent number similar to above

    try:
        driver.get(url)
        driver.set_page_load_timeout(20)
    except:
        #--write to csv
        continue

    if "404" in driver.title: #patent number not found
        #--write to csv
        continue

    try:
        WebDriverWait(driver, 10).until(
            EC.presence_of_element_located((By.XPATH, "//div[@class='table style-scope patent-result']"))
        )
    except:
        #--write to csv
        continue

    ##  rest of code to get data from tables and write to csv

Is there a more efficient way of finding if these tables exist on a patent page? Or would there be a difference if I used BeautifulSoup?
I'm new to webscraping, so any help would be greatly appreciated :)

A: Not sure which tables you are after but consider you may be able to use requests and pandas to grab the tables, as well as Session to re-use connection.
import requests
from bs4 import BeautifulSoup as bs
import pandas as pd

codes = ['US6403086B1','US6403086B1'] #patent numbers to come from file
with requests.Session() as s:
    for code in codes:
        url = 'https://patents.google.com/patent/{}/en?oq={}'.format(code, code)
        r = s.get(url)
        tables = pd.read_html(str(r.content))
        print(tables)  #example only. Remove later
       #here would add some tidying up to tables e.g. dropNa rows, replace NaN with '' ....
       # rather than print... whatever steps to store info you want until write out


text:
Q: CVS check out earlier date Am using WinCVS, need to check out the whole project branch as it was on an earlier date... How would i do it....
Thanks a lot,
Vinod.

A: In WinCvs you can specify the date to check out on the "Update Options" tab of the Checkout dialog (Remote|Checkout module).

A: > cvs -H co
Usage:
  cvs checkout [-ANPRcflnps] [-r rev] [-D date] [-d dir]
    [-j rev1] [-j rev2] [-k kopt] modules...
    [...]
    -P  Prune empty directories.
    [...]
    -r rev  Check out revision or tag. (implies -P) (is sticky)
    -D date Check out revisions as of date. (implies -P) (is sticky)


text:
Q: JavaScript stops working after I load another page I am new to JavaScript and trying to see why my on event listeners are not working. I have found similar posts on stackoverflow however the solutions are not working for me.
var search = function( event ) {
    alert("bobo")
   $.get("http://localhost:3000/search", {"search" : $("#Search-Bar").val()}, function(data, status){
        if(status == "success")
           $(".centering.text-center").html(data)
    })
}

var attachListeners = function(){
    $("#Search").on("click", search)
    $("#SearchIcon").click( () => search() )
    $("#Search-Bar").keypress( event => (event.KeyCode == 13 || event.which == 13) ? search() : undefined )
}

$(document).ready( function(){
    attachListeners()
})

My website is not a single page application. I have attached the listeners to my navigation search bar where I load a different view through the nav links and my server(ruby back end) uploads a new html page.
On the first load I have noticed that document ready gets called and everything else works. The on and click. After I use my navigation and load a different html page my events disappear. In my html views my searchbar, searchicon, and a search text have consistent id's through out. I have tried using window.load() and putting an onload attribute for my body <body onload=attachListeners()> but neither worked(perhaps I didn't use them properly). I also noticed that when I render the next html views my docment.ready does not get called. However, if I forcefully refresh the page with an F5 the listeners are active again for that one html page. What am I missing here that I don't understand?

A: It looks like you might be using Turbolinks, from the Readme for the project:

When you follow a link, Turbolinks automatically fetches the page, swaps in its <body>, and merges its <head>, all without incurring the cost of a full page load.

Since this library makes it so the page ever only loads once, normal javascript window.onload, DOMContentLoaded, and jQuery ready events don't function after the initial page load and you have to use
document.addEventListener("turbolinks:load", function() {

instead of those. If you're new to turbo links, I suggest reading through that README to see what it's all about.
I've never understood why the Rails team would put something like this in rails and enable it by default, and in every single project I've made since they made that change the first thing I do is uninstall it, and when I forgot to do so, I spend several hours later in the project wondering why my javascript is broken.


text:
Q: Stop border from doubling when 2 elements touch in wpf I have a text box and a listbox. both have a border brush and a thickness set
i get a thicker line where these 2 controls meet. basically the border of them both together makes a double border effect i want them to touch but i do not want them to have a thicker line between them.
is there a way to stop this from happening?
 <TextBox BorderBrush="black" BorderThickness="1"/>
 <ListBox BorderBrush="black" BorderThickness="1"/>

A: Set a negative margin in the appropriate direction:
<StackPanel>
    <TextBox BorderBrush="Black" BorderThickness="1"/>
    <ListBox BorderBrush="Black" BorderThickness="1" Margin="0,-1,0,0"/>
</StackPanel>


text:
Q: Extracting existing and non existing values from 2 columns using pandas I am new to pandas and I am trying to get a list of values that exists in both columns, values that exist in column A, values that only exist in column B.
My .csv file looks like this:
A        B
AAA      ZZZ
BBB      BBB
CCC      EEE
DDD      FFF
EEE      AAA
         DDD
GGG      HHH
JJJ

Columns have a different length and my outcome would be 3 lists or one csv that I would ouput having 3 columns, one for items existing in both columns, one for items existing in only A column and one for items existing in only B column.
IN BOTH      IN COLUMN A     IN COLUMN B
AAA          CCC             ZZZ
BBB          GGG             FFF
DDD          JJJ             HHH
EEE
(empty one)

I have tried using .isin() module but it returns true of false rather than the actual list.
existing_in_both = df_column_a.isin(df_column_b)

And I do not know how I should try to extract values that only exist in either column A or B.
Thank you for your suggestions.
My actual .csv has the following:
id clickout_id timestamp click_id click_type
1 123abc       2019-11-25 c51c56d1 1
1 123dce       2019-11-25 c51c5fs1 12

and other file is looking like this:
timestamp id gid type
2019-11-25 1 c51c56d1 2
2019-11-25 1 c51c5fs1 2

And I am trying to compare click_id from first file and gid from the second file.
When I print out using your answer I get the header names as answers rather than the values from the columns.

A: Use sets with intersection and difference, then for new DataFrame are used Series, because different lengths of outputs:
a = set(df.A)
b = set(df.B)

df = pd.DataFrame({'IN BOTH': pd.Series(list(a & b)),
                   'IN COLUMN A': pd.Series(list(a - b)),
                   'IN COLUMN B': pd.Series(list(b - a))})
print (df)
  IN BOTH IN COLUMN A IN COLUMN B
0     DDD         CCC         FFF
1     BBB         GGG         ZZZ
2     AAA         JJJ         HHH
3                 NaN         NaN
4     EEE         NaN         NaN

Or use numpy.intersect1d with numpy.setdiff1d:
df = pd.DataFrame({'IN BOTH': pd.Series(np.intersect1d(df.A, df.B)),
                   'IN COLUMN A': pd.Series(np.setdiff1d(df.A, df.B)),
                   'IN COLUMN B': pd.Series(np.setdiff1d(df.B, df.A))})
print (df)
  IN BOTH IN COLUMN A IN COLUMN B
0                 CCC         FFF
1     AAA         GGG         HHH
2     BBB         JJJ         ZZZ
3     DDD         NaN         NaN
4     EEE         NaN         NaN


text:
Q: Custom control child controls not persisted to ViewState in ASP.NET 4.0 We just switched target framework in our ASP.NET web application from 3.5 to 4.0. We ran into the following problem:
We have a couple of custom controls that worked fine in 3.5 but now with 4.0 they are not persisted in ViewState, one of them is basically a wrapper for other controls that inherits the Label class and the aspx-code looks like this:
<fsc:FormLabel ID="l_purchaserNo" runat="server" CssClass="label" Text="Purchaser">
    <asp:TextBox ID="tb_purchaserNo" runat="server" CssClass="textBox" MaxLength="50" />
</fsc:FormLabel>

and the resulting html is:

    Purchaser

        <input name="tb_purchaserNo" type="text" id="tb_purchaserNo" class="textBox" />

So the control basically just adds a few span-tags and a label that is connected to the textbox.
After postback the html-code in 4.0 was:

i.e. everything within the outer wrapper was gone and anything entered in the textbox could not be retreived from code behind.
Below you find the code for our FormLabel class.
We found that by setting ViewStateMode=Disabled on our custom control fsc:FormLabel and ViewStateMode=Enabled on the asp:TextBox the inner controls where persisted to ViewState but at the same time we lost ViewState on the wrapper and since we translate the text on the wrapper label we need viewstate for this as well (actually we tried every combination and setting ViewStateMode=Enabled on fsc:FormLabel did not help, regardless of how we set the ViewStateMode on the page). EnableViewState is true on all levels.
Could someone tell us how to get ViewState to work as before in 3.5, on ALL controls - wrapper as well as wrapped controls?
Thanks
Christian, Zeljko, Jonas
using System;
using System.Collections.Generic;
using System.Web.UI;
using System.Web.UI.WebControls;

namespace FormLabel
{
    public class FormLabel : Label
    {
        private bool HasChildren
        {
            get
            {
                return Controls.Count > 0;
            }
        }

        public override string Text
        {
            get
            {
                if (!HasChildren)
                {
                    return base.Text;
                }

                var text = ViewState[ID + "Text"] as String;

                if (text != null)
                {
                    ((LiteralControl)Controls[0]).Text = text;
                }

                return ((LiteralControl)Controls[0]).Text;
            }
            set
            {
                if (!HasChildren)
                {
                    base.Text = value;
                    return;
                }

                ((LiteralControl)Controls[0]).Text = value;
            }
        }

        public void SetText(string text)
        {
            ((LiteralControl)Controls[0]).Text = text;
            ViewState[ID + "Text"] = text;
        }

        public bool IndicateRequired
        {
            get
            {
                object state = ViewState[String.Format("{0}_IR", ID)];
                return state != null && (bool)state;
            }
            set
            {
                ViewState[String.Format("{0}_IR", ID)] = value;
            }
        }

        protected override void OnLoad(EventArgs e)
        {
            ViewState[ID + "Text"] = Text;
            base.OnLoad(e);
        }

        protected override void Render(HtmlTextWriter writer)
        {
            if (HasChildren)
            {
                List<Control> controls = Controls.GetControls();
                List<BaseValidator> validators = Controls.GetValidators();

                WriteLabelControl(writer);
                WriteRequiredIndicator(writer);
                WriteControlHeader(writer, validators, this.GetFirstControl());
                WriteInnerControls(writer, controls);
                WriteLabelEndControl(writer);

                return;
            }

            base.Render(writer);
        }

        private void WriteLabelControl(HtmlTextWriter writer)
        {
            writer.WriteBeginTag("span");
            writer.WriteAttribute("id", ClientID);
            writer.WriteAttribute("class", CssClass);

            foreach (string attributeKey in Attributes.Keys)
            {
                writer.WriteAttribute(attributeKey, Attributes[attributeKey]);
            }

            writer.Write(HtmlTextWriter.TagRightChar);
        }

        private void WriteRequiredIndicator(HtmlTextWriter writer)
        {
            if (IndicateRequired)
            {
                writer.WriteBeginTag("span");
                writer.WriteAttribute("class", "requiredIndicator");
                writer.Write(HtmlTextWriter.TagRightChar);
                writer.WriteEndTag("span");
            }
        }

        private void WriteControlHeader(HtmlTextWriter writer, IEnumerable<BaseValidator> validators, Control userControl)
        {
            writer.WriteBeginTag("label");
            writer.WriteAttribute("class", "header");

            if (userControl != null)
            {
                writer.WriteAttribute("for", userControl.ClientID);
            }

            writer.Write(HtmlTextWriter.TagRightChar);
            writer.Write(Text);

            foreach (BaseValidator validator in validators)
            {
                validator.CssClass = "Error";
                validator.RenderControl(writer);
            }

            writer.WriteEndTag("label");
        }

        private static void WriteInnerControls(HtmlTextWriter writer, IList<Control> controls)
        {
            writer.WriteBeginTag("span");
            writer.WriteAttribute("class", "valueContainer");
            writer.Write(HtmlTextWriter.TagRightChar);

            for (int i = 1; i < controls.Count; i++)
            {
                controls[i].RenderControl(writer);
            }

            writer.WriteEndTag("span");
        }

        private static void WriteLabelEndControl(HtmlTextWriter writer)
        {
            writer.WriteEndTag("span");
        }

    }

    #region Nested type: Extensions

    public static class Extensions
    {
        public static List<BaseValidator> GetValidators(this ControlCollection controls)
        {
            var validators = new List<BaseValidator>();

            foreach (Control c in controls)
            {
                if (c is BaseValidator)
                {
                    validators.Add(c as BaseValidator);
                }

            }

            return validators;
        }

        public static List<Control> GetControls(this ControlCollection controls)
        {
            var listcontrols = new List<Control>();

            foreach (Control c in controls)
            {
                if (!(c is BaseValidator))
                {
                    listcontrols.Add(c as Control);
                }

            }

            return listcontrols;
        }

        public static Control GetFirstControl(this Control container)
        {
            return (new InputControlFinder().FindFirstInputControl(container));
        }

        private class InputControlFinder
        {
            public Control FindFirstInputControl(Control control)
            {
                Control input = null;

                foreach (Control child in control.Controls)
                {
                    if (child is TextBox || child is DropDownList || child is CheckBox)
                    {
                        input = child;
                    }
                    else
                    {
                        input = FindFirstInputControl(child);
                    }

                    if (input != null)
                    {
                        return input;
                    }
                }

                return input;
            }
        }
    }
    #endregion
}


text:
Q: Proving uniform convergence of $(1+\frac{x}{n})^n$ to $e^x$ on compact intervals in the real numbers My goal is to prove that if $b> a > 0$ are real numbers, then:
$\lim_{n \rightarrow \infty} \int_a^b (1 + x/n)^n e^{-x} dx = b-a$.
I think the best way to do this is to show that $(1+x/n)^n$ tends uniformly to $e^x$ on positive compact intervals. I know that it converges pointwise but I am struggling with the uniform proof. I have tried figuring out $\sup_{x \in [a,b]} \left|(1+\frac{x}{n})^n - e^x \right|$ by differentiating $(1+\frac{x}{n})^n - e^x$, but this is getting me nowhere.
I would appreciate a nudge in the right direction about how to prove the convergence is uniform. Thank you!

A: hint: Try to show $\left(1+\frac{x}{n}\right)^n\cdot e^{-x} \leq 1$,  and use $g(x) = 1$ as a dominating function, and use the DCT to conclude. And the above inequality is true because:  $\ln\left(1+\frac{x}{n}\right) \leq \frac{x}{n} $  is a well-known inequality.

A: $$\lim_{n\to\infty}\left(1+\frac xn\right)^n$$
Substitute $n/x=m$
$$\lim_{m\to\infty}\left(1+\frac1m\right)^{mx}=\left(\lim_{m\to\infty}\left(1+\frac1m\right)^m\right)^x=e^x$$
If $x>0$, that is the limit.  If $x<0$, the limit is $\lim_{m\to\infty}$.
But you will find that when you go and prove this limit, all you get is $e^{\lim_{|m|\to\infty}1+\frac1m}$
So regardless of the direction you approach infinity, it evaluates to $e^x$

A: \begin{eqnarray}
e^x-(1+{x \over n})^n &=& \sum_{k>n} {1 \over k!} x^k  +\sum_{k=0}^n ({1 \over k!} - \binom{n}{k} {1 \over n^k}) x^k \\
&=& \sum_{k=0}^\infty a_{n,k} {1 \over k!} x^k \\
\end{eqnarray}
Where $a_{n,k} = \begin{cases} 1-(1(1-{1 \over n} ) \cdots (1 - { k-1 \over n})), & k \le n \\
1, & \text{otherwise}\end{cases}$. Note that $0 \le a_{n,k} \le 1$ for all $k, n$ and for any fixed $k$, then $\lim_n a_{n,k} = 0$.
Let $\epsilon>0$ and choose $N$ such that for $n \ge N$, $\sum_{k>n} {1 \over k!} b^k < {1 \over 2} \epsilon$.
Then
\begin{eqnarray}
|e^x-(1+{x \over n})^n| &\le& \sum_{k=0}^N a_{n,k} {1 \over k!} |x|^k + {1 \over 2} \epsilon \\
&\le& \sum_{k=0}^N a_{n,k} \max(1,b^N) + {1 \over 2} \epsilon \\
\end{eqnarray}
Now choose $N' \ge N$ such that $\sum_{k=0}^N a_{n,k} \le { 1\over 2 \max(1,b^N)} \epsilon$ for $n \ge N'$ (note the upper sum limit is fixed
at $N$) to get
$|e^x-(1+{x \over n})^n| \le \epsilon $ for all $x \in [a,b]$.

A: Let $C=\max (|a|,|b|).$ For $k\geq 2$ let $2\leq n_k\in N$ such that $\forall x\in [a,b]\;(|x/n_k|<1/k).$ Then for $x\in [a,b]$  and $n\geq n_k$ we have $$|-x+(\log (1+x/n)^{n})|=$$ $$=|-x+x\sum_{j=1}^{\infty}(x/n)^j(-1)^{j+1}/j|=$$ $$=|x \sum_{j=2}^{\infty}(x/n)^{j-1}(-1)^{j+1}/j|\leq$$ $$\leq  C\sum_{j=2}^{\infty}k^{1-j}/j<C \sum_{j=2}^{\infty}k^{1-j}/2=C /2(k-1).$$ So $-x+\log (1+x/n)^n$ converges uniformly to $0$ on $[a,b].$
Since $\exp (x)$ is continuous, it is uniformly continuous on $[a,b],$ so $-\exp (x)+ \exp (\log (1+x/n)^n))$ also converges uniformly to $0$ on $[a,b].$


text:
Q: How to set up auto deployment of a maven project on multiple machines? I have a maven project that lives in 3 servers/hosts.
I was looking at the  maven release plugin but I cant seem to find how to push to multiple servers at the same time. BTW my source control is Perforce.
I wanted to see if I can deploy the project to multiple locations(servers/hosts) during the mvn package cycle and avoid the manual transfer of the jars to these different machines.
Can somebody point me to some documentation that discusses this?

A: To achieve this, I created different profiles for each deployment in the POM similar to the following
 <profile>
    <id>deployToDev_Host</id>
        <activation>
            <property>
                <name>dev</name>
                <value>test</value>
            </property>
        </activation>

        <build>
            <plugins>
                <plugin>
                    <groupId>org.apache.maven.plugins</groupId>
                    <artifactId>maven-antrun-plugin</artifactId>
                    <executions>
                        <execution>
                            <id>restart_service</id>
                            <phase>deploy</phase>
                            <configuration>
                                <target>

                                    <scp trust="yes" file="${project.build.directory}/${project.artifactId}-${project.version}.jar" remoteToFile="location/on/remote/host/" />
            </plugin>
            </plugins>
        </build>
    </profile>

Followed this document   http://slackspace.de/articles/create-deployment-profiles-with-maven/


text:
Q: Property is not updating in textbox - WPF I have an issue with binding the property Message to the view.
Callback returns a result from a WCF Service. I'm trying to assign this result to the property Message. My text box is never updated with new value - it always displays TEST.
public class CallbackHandler : IDataExchangeCallback, INotifyPropertyChanged
{
    public CallbackHandler()
    {
        this.Message = "TEST";
    }

    public void Result(string result)
    {
        Message = result;
    }

    private string _message;
    public string Message
    {
        get { return _message; }
        set
        {
            _message = value;
            OnPropertyChanged("Message");
        }
    }

    public event PropertyChangedEventHandler PropertyChanged;
    protected void OnPropertyChanged(string propertyName)
    {
        PropertyChangedEventHandler handler = PropertyChanged;

        if (handler != null)
        {
            handler(this, new PropertyChangedEventArgs(propertyName));
        }
    }
}

<Window x:Class="guiClient.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:tb="http://www.hardcodet.net/taskbar"
        xmlns:local="clr-namespace:guiClient"
        Title="DataExchangeClient" Height="76" Width="297" WindowStyle="SingleBorderWindow" MinHeight="50" MinWidth="50" MaxWidth="300">
    <Window.DataContext>
        <local:CallbackHandler/>
    </Window.DataContext>
    <Grid>
        <TextBox HorizontalAlignment="Left" Height="45" TextWrapping="Wrap" VerticalAlignment="Top" Width="289" Text="{Binding Path=Message}"/>
    </Grid>
</Window>

HERE IS INTERFACE:
------From UserBuzzer
Callback is defined like this :

IDataExchangeCallback Callback
{
    get
    {
        return OperationContext.Current.GetCallbackChannel<IDataExchangeCallback>();
    }
}

And interface:
// The callback interface is used to send messages from service back to client.
// The Result operation will return the current result after each operation.
public interface IDataExchangeCallback
{
    [OperationContract(IsOneWay = true)]
    void Result(string result);
}

A: The reason could be that you're not raising PropertyChanged on the UI thread, since you're calling it from a callback. Try using Dispatcher to make sure the event is raised on UI thread:
protected void OnPropertyChanged(string propertyName)
{
    PropertyChangedEventHandler handler = PropertyChanged;

    if (handler != null)
    {
        Application.Current.Dispatcher.Invoke(() =>
            handler(this, new PropertyChangedEventArgs(propertyName)));
    }
}

A: I found solution. It's very bad, but atm i don't know how to raise event on UI thread.
namespace guiClient
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window, IDataExchangeCallback
    {
        public MainWindow()
        {
            InitializeComponent();
            Register();
        }

        public void Result(string result)
        {
            //this will not cause the application to hang
            Application.Current.Dispatcher.BeginInvoke(new Action(
              () => textBox.Text = result));
        }

        public void Register()
        {
            InstanceContext instanceContext = new InstanceContext(this);
            DataExchangeClient client = new DataExchangeClient(instanceContext);

            client.RegisterClient(Guid.NewGuid().ToString());
        }
    }
}

As Damir Arh mention i used dispather. In this case i named control and passed result to Text property.
Notice also MainWindow now inherits from IDataExchangeCallback.
This is also tricky: InstanceContext instanceContext = new InstanceContext(this);
If anyone know how to implement this in MVVM patern give me a call.


text:
Q: Show that $V(XZ - Y^2, YZ - X^3, Z^2 - X^2Y)$ is irreducible This is from Problem 2.8 (b) in Fulton's "Algebraic Curves". The hint given asks to show that $Y^3 - X^4, Z^3 - X^5, Z^4 - Y^5 \in I(V)$ and then find a polynomial map from $\mathbb{A}^1(\mathbb{C})$ onto $V$.
I can see how to show that the 3 polynomials are in $I(V)$. But I can't seem to find a parameterization of $V(Y^3 - X^4, Z^3 - X^5, Z^4 - Y^5)$. I assume theres a general way to find parameterizations given this but I don't know of that yet. How do I go about that? Also I can't seem to show that $V(Y^3 - X^4, Z^3 - X^5, Z^4 - Y^5) \subseteq V(XZ - Y^2, YZ - X^3, Z^2 - X^2Y)$, any suggestions about how to show that?

A: Try a parametrisation $(X,Y,Z)=(t^a,t^b,t^c)$. We must have $a+c=2b$,
$b+c=3a$ and $2c=2a+b$. Therefore $a-b=2b-3a$, so $4a=3b$. Then $(a,b,c)=(3,4,5)$ works. So try $t\mapsto(t^3,t^4,t^5)$

A: Put $t=\frac{Y}{X}$, now you can check that $X=t^3$, $Y=t^4$ and $Z=t^5$. This parametrization satisfies the relations given by the ideal.
How can you get this? I tried playing with the relations and dividing by one of the indeterminates to see if I can express all indeterminates in terms of a quotient.
What worked to me, was combining relations 1 and 2 so you get $Y\cdot Y^2 = YZX = X^4$, so $X= (Y/X)^3$. Then the rest are easy $ Z=Y^2/X = Y\cdot t$, so we only need to find $Y$ in terms of $t$, we use the third relation $Y=Z^2/X^2 = \frac{Y^2t^2}{t^6}$ so $Y= t^4$. And finally $Z=t^5$.


text:
Q: How to set BITS data type in SNMPSET command? the MIB OID object have data type 'Bits':
object_OID
Composed Type: Bits
Base Type: BITS
Access: read-write
Kind: Scalar
SMI Type: OBJECT-TYPE
Value List:
doc (0)
emta (1)
cpe (2)

From MIB description, default is DEFVAL { '00'h }.
I want set value 2 (cpe).
I tried to set the value with command
snmpset -v2c -c public 192.168.100.1  [object_OID] b 2

but got
Error in packet.
Reason: wrongValue (The set value is illegal or unsupported in some way)

tried also
snmpset -v2c -c public 192.168.100.1  [object_OID] i 2

again error
Error in packet.
Reason: wrongType (The set datatype does not match the data type the agent expects)

Snmpget against this object returns Hex-STRING: 00
What is proper format to set value 2 for BITS data type?

A: You're using the correct syntax to set a BITS value. I would hazard a guess that the agent implementation is faulty (i.e. the agent is not following the MIB definition).

A: A correct Syntax for Net-SNMP is:
snmpset -v2c -c public 192.168.100.1   $ObjectId   = 'emta cpe'

A: i
INTEGER
u
UNSIGNED
s
STRING
x
HEX STRING
d
DECIMAL STRING
n
NULLOBJ
o
OBJID
t
TIMETICKS
a
IPADDRESS
b
BITS

Change the value according to data type
Example for trap IP Change -
snmpset -v2c -c private 192.168.0.1  OID  a  '10.12.14.190'


text:
Q: Classpath Scanning in Spring Boot Jar Not Working I have a custom annotation:
@Target(value=ElementType.TYPE)
@Retention(RetentionPolicy.RUNTIME)
public @interface Pipeline  {
  String id ();
  String name ();
  boolean visible () default true;
  String role () default "USER";
}

Which I use on interfaces within a Spring Boot App with nested jars:
@Pipeline(id="my-pipeline", name="My Pipeline")
public interface Echo {
  ...
}

My project structure:
parent-boot-project
   |
   --- plugin1.jar
   --- plugin2.jar <--- interfaces are here
   --- ...

Next, I use lukehutch's fast-classpath-scanner to scan for them:
new FastClasspathScanner(BASE_PACKAGE)
    .matchClassesWithAnnotation(PIPELINE_ANNOTATION, aProcessor)
    .verbose()
    .scan();

Works great on my IDE (eclipse) but not when I build the jar. Tried messing around with the classpath but to no avail. Anyone ran into something like that?

A: FastClasspathScanner has been renamed ClassGraph, and now has full Spring Boot scanning support.


text:
Q: Jest - enzyme testing warning: Failed prop type Doing testing with jest and enzyme and I think I am doing everything right but somehow getting the warning:

Warning: Failed prop type: The prop project is marked as required in ProjectPageUI, but its value is undefined.
            in ProjectPageUI

Here is how the test looks like:
test('shallow-render without crashing', () => {
  /*
    project: PropTypes.object.isRequired,
   */

  const props = {
    match: { params: {} },
  }
  const store = configureStore()(STATE_WITH_2_FAMILIES)
  shallow(<ProjectPageUIComponent store={store} {...props} />)
})

Inside ProjectPageUI.jsx I get project property using the selector:
const mapStateToProps = (state, ownProps) => ({
  project: getCurrentProject(state),
})

Where getCurrentProject is the following:
export const getProjectsByGuid = state => state.projectsByGuid
export const getProjectGuid = state => state.currentProjectGuid

export const getCurrentProject = createSelector(
  getProjectsByGuid, getProjectGuid, (projectsByGuid, currentProjectGuid) => projectsByGuid[currentProjectGuid],
)

In the STATE_WITH_2_FAMILIES I have both projectsByGuid and currentProjectGuid defined and projectsByGuid has the respective key for currentProjectGuid and the object defined. So, now I am wondering why is this warning happenning and how I should change my test, since I would expect it to have no issues at all: the selector gets project from the state and it should be defined.

Clarification

Thats how the ProjectPageUI looks like:
const ProjectPageUI = (props) => {
    ...
    ...
    return ( ... )
}

ProjectPageUI.propTypes = {
  project: PropTypes.object.isRequired,
  ...
  ...
}

const mapStateToProps = (state, ownProps) => ({
  project: getCurrentProject(state),
  ...
  ...
})

export { ProjectPageUI as ProjectPageUIComponent }

export default connect(mapStateToProps)(ProjectPageUI)

A: Try to wrap you component with redux Provider component
The  makes the Redux store available to any nested components that have been wrapped in the connect() function.
shallow(
  <Provider store={store}>
    <ProjectPageUIComponent {...props} />
  </Provider>)

A: Pretty stupid, but it was an issue of wrong importing of the ProjectPageUI. I imported it as:
import { ProjectPageUIComponent } from './ProjectPageUI'

which imports the unconnected component, but should have imported the defaults' way:
import ProjectPageUI from './ProjectPageUI'

Which worked out

A: Since you export your raw component
export { ProjectPageUI as ProjectPageUIComponent }

You can test it directly without the need to mock up a redux provider and store
import { ProjectPageUIComponent } from '.'; // import raw component

...

test('shallow-render without crashing', () => {

  const props = {
    match: { params: {} },
    project: { /* now mock up a project object for testing */ }
    // mock/supply any other required props
  }

  shallow(<ProjectPageUIComponent {...props} />)
});

Have you considered react-testing-library? IMO it is a much cleaner way to test UI components. For a simple "renders without crashing" test it is very similar to the above.


text:
Q: Associate an image with Radio button in Android I want to fetch Images from my URL and add it to the radio button that is further added to a radio group. However, i could not find metod such as setText to set text for radio button. I wish to add image to my radio button in similar fashion. Is there any hint/method that can do the same for me? Any hint/code example would be really helpful for me,
        RadioGroup rg = new RadioGroup (this);
            rg = (RadioGroup) findViewById(R.id.radioGroup1);
            RadioButton rb[]= new RadioButton[children.size()];

            for (int i = 0; i < var.size(); i++)
                {
                Element movieAtt = (Element)doc.getRootElement().getChild("movies").getChildren("movie").get(i);
                MovieName[i]=movieAtt.getAttributeValue( "Title" );
                MovieCover[i]=movieAtt.getAttributeValue( "cover" );
                ShowTime[i]=movieAtt.getAttributeValue( "showtime" );

                rb[i] = new RadioButton(this);
                rb[i].setText(movieAtt.getAttributeValue("Title"));
                rg.addView(rb[i]);

                //Calling this func to get Images
                //LoadImageFromWebOperations(movieAtt.getAttributeValue( "cover" ));
                //rb[i].buildDrawingCache(LoadImageFromWebOperations(movieAtt.getAttributeValue( "cover" )));

public static Drawable LoadImageFromWebOperations(String url)
{
        try
        {
            InputStream is = (InputStream) new URL(url).getContent();
            Drawable d = Drawable.createFromStream(is, "src name");
            return d;
        }
        catch (Exception e)
        {
            return null;
        }
}

A: Is the problem with the image or the text? As for the image, I believe this should work:
Drawable d = LoadImageFromWebOperations(movieAtt.getAttributeValue("cover"));
rb[i].setButtonDrawable(d);

Make sure to set gravity to Gravity.CENTER or your image won't be centered around the radio button.
You should find information about the text in the RadioButton reference.


text:
Q: Different Types of Full Stack Architectures I have built a few stacks in my time as a self-taught full-stack developer, but I think there may be a hole in my knowledge that you can hopefully fill in for me. I have built a few stacks that all have a core architecture like this:

*

*Backend in Go, interfacing with a Postgres database or doing some core logic

*RESTful API server (also written in Go) serving over HTTPS that triggers database methods/backend logic

*Frontend in JavaScript using ReactJS or some other framework. The front end makes calls to the API server (using fetch()) whenever data is needed/logic should be executed (on the backend).

I find that this is a pretty good, common architecture that can work in many different use cases. However, I am wondering if there is any other type of core architecture that differs from this. I have heard of GraphQL and I see how that is different than this traditional REST-like architecture, but I am wondering if there is some other type of architecture used to build web apps that does not revolve around a REST/SOAP/GraphQL API. I've heard of WebSockets, and I think that they fit into what I am asking about here, so how are they different from just calling JavaScript's fetch() to make calls to my REST API (or using a third-party library like axios.)?

A: The architecture of your application is whatever you decide it is.  The alphabet soup you've mentioned in your question is just the ones that are more well-known.  Each approach has its own features and advantages.
How websockets is different is that it's more "real-time."  It's not uncommon to have a REST architecture that is supplemented by websockets to provide things like real-time dashboards, or the "this post has been edited, click here to reload" banner you sometimes see on Stack Exchange sites.
When you create a websocket, you open a two-way communication channel.  This clearly differs from the other architectures you've mentioned, as those architectures are based on querying the endpoint to obtain some data.  It's the difference between making a telephone call each time, and leaving the line open while you talk.

A: You're asking broadly about web app architecture, but focusing solely on client-server communication, i.e. the application layer. The style of communication doesn't really change the overall architecture pattern; these are just different data types or protocols. That's an implementation detail of an architecture, not the architectural pattern itself.
You can find some useful primers for web app architecture patterns, but here's a quick list (and a super elementary description) of some of the most common:

*

*Client-server, which is what you have described

*Microservices, wherein the UI interacts with several backend servers with specialized domains

*Layered, wherein concerns in the backend (and sometimes the frontend, as with a robust Redux service, for example) are broken into different concerns-- good for testability

*Peer-to-peer, wherein clients serve as both consumers and suppliers of resources

These aren't necessarily mutually exclusive. These can all be combined in different ways based on the needs of the application.


text:
Q: ZF2 module config service_manager add constructor param I've been searching and trying for a while now and I can't find out what I'm doing wrong...
I've been reading quite some documentation now and have tried a lot of different approaches.
I hope one of you guys can help me out..
My idea:
I have a module called Application. In this module there is an \Application\Controller\IndexController which is used to show the homepage of my application.
The IndexController needs an object with \Zend\http\Client, so I though I should use the factories key in the configuration that is returned by \Application\Module->getServiceConfig() and add a constructor with required param \Zend\Http\Client $client.
Unfortunatly this is not working..
My code:
<?php
// module/Application/Module.php

namespace Application;

use Zend\Mvc\ModuleRouteListener;
use Zend\Mvc\MvcEvent;

class Module
{
    public function getConfig()
    {
        return include __DIR__ . '/config/module.config.php';
    }

    public function getServiceConfig()
    {
        return array(
            'factories' => array(
                'IndexController' => function($serviceManager) {
                    $httpClient = \Zend\Http\Client;

                    return new IndexController($httpClient);
                },
            ),
        );
    }

    public function getAutoloaderConfig()
    {
        return array(
            'Zend\Loader\StandardAutoloader' => array(
                'namespaces' => array(
                    __NAMESPACE__ => __DIR__ . '/src/' . __NAMESPACE__,
                ),
            ),
        );
    }
}

<?php
// module/Application/config/module.config.php

return array(
    'router' => array(
        'routes' => array(
            'home' => array(
                'type' => 'Zend\Mvc\Router\Http\Literal',
                'options' => array(
                    'route' => '/',
                    'defaults' => array(
                        'controller' => 'Application\Controller\Index',
                        'action' => 'index',
                    ),
                ),
            )
        ),
    ),
    'service_manager' => array(
        'factories' => array(
            'translator' => 'Zend\I18n\Translator\TranslatorServiceFactory',
        ),
    ),
    'translator' => array(
        'locale' => 'en_US',
        'translation_file_patterns' => array(
            array(
                'type' => 'gettext',
                'base_dir' => __DIR__ . '/../language',
                'pattern' => '%s.mo',
            ),
        ),
    ),
    'controllers' => array(
        'invokables' => array(
            'Application\Controller\Index' => 'Application\Controller\IndexController'
        ),
    ),
    'view_manager' => array(
        'display_not_found_reason' => true,
        'display_exceptions' => true,
        'doctype' => 'HTML5',
        'not_found_template' => 'error/404',
        'exception_template' => 'error/index',
        'template_map' => array(
            'layout/layout' => __DIR__ . '/../view/layout/layout.phtml',
            'application/index/index' => __DIR__ . '/../view/index/index.phtml',
            'error/404' => __DIR__ . '/../view/error/404.phtml',
            'error/index' => __DIR__ . '/../view/error/index.phtml',
        ),
        'template_path_stack' => array(
            __DIR__ . '/../view',
        ),
    ),
);

<?php
// module/Application/src/Application/Controller/IndexController.php

namespace Application\Controller;

use Zend\Mvc\Controller\AbstractActionController;
use Zend\View\Model\ViewModel;

class IndexController extends AbstractActionController
{
    protected $httpClient;

    public function __construct(\Zend\Http\Client $client)
    {
        $this->httpClient = $client;
    }

    public function getHttpClient()
    {
        return $this->httpClient;
    }

    public function indexAction()
    {
        $httpClient = $this->getHttpClient();

        return new ViewModel();
    }
}

The error:

Catchable fatal error: Argument 1 passed to Application\Controller\IndexController::__construct() must be an instance of Zend\Http\Client, none given, called in /var/www/library/Zend/ServiceManager/AbstractPluginManager.php on line 170 and defined in /var/www/module/Application/src/Application/Controller/IndexController.php on line 13

A: You need to implement the getControllerConfig method in Module.php to do what you're asking, controllers have their own manager, remove what you have from getServiceConfig, and use the following instead
public function getControllerConfig()
{
    return array(
        'factories' => array(
            'Application\Controller\Index' => function($serviceManager) {
                $httpClient = new \Zend\Http\Client;
                return new \Application\Controller\IndexController($httpClient);
            },
        ),
    );
}

You'll also need to remove the line from controller invokables in module.config.php since it'll conflict with your factory
'controllers' => array(
    'invokables' => array(
        // this line's no longer needed
        //'Application\Controller\Index'      => 'Application\Controller\IndexController',
    ),
),


text:
Q: How take html dash-case input tag name in js Case to naming all HTML parameters and now I have some troubles. I want take value from form input but JS don't taking dash-case. There is any way to take form input without changing input name?
HTML and JavaScript:

const form = document.querySelector('#message-form');
console.log(form.user-message.value); //Here rise error
<form id="message-form">
    <input type="text" name="user-message">
</form>

A: You can access it like this:
form['user-message'].value

A: Change name to usermessage and it will work
<form id="message-form">
    <input type="text" name="usermessage">
</form>

const form = document.querySelector('#message-form');
console.log(form.usermessage.value)

Or add querySelector for message
var message = form.querySelector('input[name="user-message"]').value;


text:
Q: Symfony2 and MVC - Is extend controller a good practice? I have a simple and perhaps stupid question.
Using Symfony2 PHP framework i often work extending controllers like below (of course it depends from the kind of work):
    class MainController extends Controller{
        private $locale = array();

        protected function Locale() {
        $em = $this->getDoctrine()
            ->getManager();

                $this->locale = $em->getRepository('CommonLanguageBundle:Language')
            ->findBy(
                array('code' => $this->getRequest()
                    ->getLocale()
                )
            );
//      \Doctrine\Common\Util\Debug::dump($this->locale);
        return $this->locale[0];
    }
     //..
    }
    class StoreController extends MainController{
     function a_method() {
       $data = $this->Locale()->getId();
       //...
      }
    }
    class DefaultController extends StoreController {
     $data = $this->Locale()->getId();
     //...
    }

Is this a good practice?
Surfing on the web i found many articles but it isn't still so clear for me.
In the end, if it worked fine in Symfony2, would it be good in general for MVC pattern?

A: Symfony is not MVC framework. Symfony is Service-oriented architecture framework. Generally cascading extending controllers doesn't make a sens.
Rather you should create services and use it in whe you need it.
Moreover, good practice is define Controller as service.


text:
Q: Setting 404 response while still displaying page I have a details page for products. The product is fetched by id in a query string, if a product with the id is found in the database we display the details, otherwise we show a "this item can not be found" message. Pretty standard stuff. What I would like to do is show the details page with the "this item can not be found' message but send a 404 response. This is so that Google will un-index items that have been removed.
So I have something like this(simplified):
<asp:Panel ID="pnlDetails" runat="server" Visible="false">
    item details go here
</asp:Panel>

<asp:Panel ID="pnlError" runat="server" Visible="false">

The specified  item could not be found.

</asp:Panel>

And in the code behind:

if(itemFound)
{
   showDetails();
}
else
{
   showError();
}

private void showDetails()
{
   pnlDetails.Visible = true;
   //fill in details
}

private void showError()
{
    //set response
    Response.StatusCode = 404;
    pnlError.Visible = true;
}

What is happening now is I see the error panel but I still get a 200 response. Could anyone tell me what I am doing wrong? Any advice would be appreciated, thanks much!
Edit: This I am calling these methods in the Page_Load event handler.

A: I see... since your code won't throw a 404, you infact want it too so google will clean up your dead links naturally.... try this: stackoverflow.throwing404errorsForMissingParameters
also, this is helpful (near the bottom) forums.asp.net/throwing404InHTTPResponse. For example HttpContext.Current.Respone.StatusCode = 404;
protected void Page_Load(object sender, EventArgs e)
{
    Response.StatusCode = 404;
    Response.End();
}

A: Google says that..

If outdated pages from your site appear in the search results, ensure
  that the pages return a status of either 404 (not found) or 410 (gone)
  in the header.

Here is the source
So what you can do..

*

*Incase the item is not found - Redirect to your custom 404 page.

*In the Page_Load event of your 404 page add this..
Response.StatusCode = 404;
But just by doing this it return HTTP 302 Redirect code and then HTTP 200 - ok code. So the page will not be removed from Google's indexes.
3. Open the Global.asax file (if not present, add it). Add the following code to handle 404 (Page not found) errors
     protected void Application_Error(object sender, EventArgs e)
{
    Exception ex = Server.GetLastError();
    if (ex is HttpException)
    {
        if (((HttpException)(ex)).GetHttpCode() == 404)
            Server.Transfer("~/404.aspx");
    }
    Server.Transfer("~/AnyOtherError.aspx");
}

However in this case make sure you have no customErrors configuration in web.config for 404. Hope it helps.

A: Set the status code in the Render method, so it might look something like this:
protected override void Render(HtmlTextWriter writer)
{
    base.Render(writer);
    Response.StatusCode = 404;
    pnlError.Visible = true;
}


text:
Q: Upload a HttpPostedFileBase for image but always null I am new to MVC and web programming.
My uploading image is working fine, but when I use almost the exact same code to allow user to modify its upload, it HttpPostedFileBase is always null. Driving me crazy...
here is the model
     public class ModifyGenreViewModel
        {
            public int Id { get; set; }
        [Display(Name = "Nom du style")]
        public string Name { get; set; }

        [Display(Name = "Image")]
        public HttpPostedFileBase Image { get; set; }
    }

and the view
@using (Html.BeginForm("ModifyGenre", "Upload", null, FormMethod.Post, new { enctype = "multipart/form-data" }))
        {
            @Html.AntiForgeryToken()

@Resource.StyleCreationHeader

                @Html.ValidationMessageFor(model=>Model)

                    @Html.LabelFor(model => model.Id, htmlAttributes: new { @class = "control-label col-md-2" })

                        @Html.EditorFor(model => model.Id, new { htmlAttributes = new { @class = "form-control" } })

                    @Html.LabelFor(model => model.Name, htmlAttributes: new { @class = "control-label col-md-2" })

                        @Html.EditorFor(model => model.Name, new { htmlAttributes = new { @class = "form-control" } })
                        @Html.ValidationMessageFor(model => model.Name, "", new { @class = "text-danger" })

                    @Html.LabelFor(model => model.Image, new { @class = "control-label col-md-2" })

                        <input type="file" data-val="true" id="ModifyGenreViewModel_Image" name="ModifyGenreViewModel.Image" />
                        @Html.ValidationMessageFor(model => model.Image, "", new { @class = "text-danger" })

                        <input type="submit" value="@Resource.Modify" class="btn btn-primary" />

        }

When I set the breakpoint in my controller, I see the Id and the name, but Image is always null.
Thank's for your help!

A: The name property value of your file input should match with the view model property name for model binding to work properly.
Change the input field name to "Image"
<input type="file" data-val="true" id="ModifyGenreViewModel_Image" name="Image" />

Assuming your HttpPost action method accepts the ModifyGenreViewModel object as parameter.
[HttpPost]
public ActionResult ModifyGenre(ModifyGenreViewModel  model)
{
  // to do : return something
}

A: *

*In model class change it to public String Image { get; set; }

*In .cshtml page change it to @Html.TextBoxFor(m => m.Image, new {
type = "file", name="Image" })

*In Controller you should use the name what you have decleared in html    helper HttpPostedFileBase Image