Programs & Examples On #Changelistener

A Listener object that reacts to a generic 'change' that occurs in the application

FragmentActivity to Fragment

first of all;

a Fragment must be inside a FragmentActivity, that's the first rule,

a FragmentActivity is quite similar to a standart Activity that you already know, besides having some Fragment oriented methods

second thing about Fragments, is that there is one important method you MUST call, wich is onCreateView, where you inflate your layout, think of it as the setContentLayout

here is an example:

    @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {     mView       = inflater.inflate(R.layout.fragment_layout, container, false);       return mView; } 

and continu your work based on that mView, so to find a View by id, call mView.findViewById(..);


for the FragmentActivity part:

the xml part "must" have a FrameLayout in order to inflate a fragment in it

        <FrameLayout             android:id="@+id/content_frame"             android:layout_width="match_parent"             android:layout_height="match_parent"  >         </FrameLayout> 

as for the inflation part

getSupportFragmentManager().beginTransaction().replace(R.id.content_frame, new YOUR_FRAGMENT, "TAG").commit();


begin with these, as there is tons of other stuf you must know about fragments and fragment activities, start of by reading something about it (like life cycle) at the android developer site

Angular - POST uploaded file

Looking onto this issue Github - Request/Upload progress handling via @angular/http, angular2 http does not support file upload yet.

For very basic file upload I created such service function as a workaround (using ???????'s answer):

  uploadFile(file:File):Promise<MyEntity> {
    return new Promise((resolve, reject) => {

        let xhr:XMLHttpRequest = new XMLHttpRequest();
        xhr.onreadystatechange = () => {
            if (xhr.readyState === 4) {
                if (xhr.status === 200) {
                    resolve(<MyEntity>JSON.parse(xhr.response));
                } else {
                    reject(xhr.response);
                }
            }
        };

        xhr.open('POST', this.getServiceUrl(), true);

        let formData = new FormData();
        formData.append("file", file, file.name);
        xhr.send(formData);
    });
}

Android "gps requires ACCESS_FINE_LOCATION" error, even though my manifest file contains this

CAUSE: "Beginning in Android 6.0 (API level 23), users grant permissions to apps while the app is running, not when they install the app." In this case, "ACCESS_FINE_LOCATION" is a "dangerous permission and for that reason, you get this 'java.lang.SecurityException: "gps" location provider requires ACCESS_FINE_LOCATION permission.' error (https://developer.android.com/training/permissions/requesting.html).

SOLUTION: Implementing the code provided at https://developer.android.com/training/permissions/requesting.html under the "Request the permissions you need" and "Handle the permissions request response" headings.

Android TabLayout Android Design

So easy way :

XML:

<android.support.design.widget.TabLayout
        android:id="@+id/tab_layout"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="#fff"/>
<android.support.v4.view.ViewPager
        android:id="@+id/viewpager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"/>

Java code:

private ViewPager viewPager;

private String[] PAGE_TITLES = new String[]{
        "text1",
        "text1",
        "text3"
};
private final Fragment[] PAGES = new Fragment[]{
        new fragment1(), 
        new fragment2(),
        new fragment3()

};

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

    /**TODO ***************tebLayout*************************/
    viewPager = findViewById(R.id.viewpager);
    viewPager.setAdapter(new MyPagerAdapter(getSupportFragmentManager()));
    TabLayout tabLayout = findViewById(R.id.tab_layout);
    tabLayout.setSelectedTabIndicatorColor(Color.parseColor("#1f57ff"));
    tabLayout.setSelectedTabIndicatorHeight((int) (4 * 
    getResources().getDisplayMetrics().density));
    tabLayout.setTabTextColors(Color.parseColor("#9d9d9d"), 
    Color.parseColor("#0d0e10"));
    tabLayout.setupWithViewPager(viewPager);
    /***************************************************************************/
    }

Single selection in RecyclerView

You need to clear the OnCheckedChangeListener before setting setChecked():

@Override
public void onBindViewHolder(final ViewHolder holder, int position) {

    holder.mRadioButton.setOnCheckedChangeListener(null);
    holder.mRadioButton.setChecked(position == mCheckedPosition);
    holder.mRadioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {

            mCheckedPosition = position;
            notifyDataSetChanged();
        }
    });
}

This way it won't trigger the java.lang.IllegalStateException: Cannot call this method while RecyclerView is computing a layout or scrolling error.

Custom Listview Adapter with filter Android

You can implement search filter in listview by two ways. 1. using searchview 2. using edittext.

  1. If yo want to use searchview then read here : searchview filter.

  2. If you want to use edittext, read below.

I have taken reference from : listview search filter android

Code snippets to make filter with edittext.

First create model class MovieNames.java:

public class MovieNames {
    private String movieName;

    public MovieNames(String movieName) {
        this.movieName = movieName;
    }

    public String getMovieName() {
        return this.movieName;
    }

}

Create listview_item.xml file :

     <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:padding="10dp">


    <TextView
        android:id="@+id/name"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</RelativeLayout>

Make ListViewAdapter.java class :

    import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.TextView;

import java.util.ArrayList;
import java.util.Locale;

public class ListViewAdapter extends BaseAdapter {

    // Declare Variables

    Context mContext;
    LayoutInflater inflater;
    private ArrayList<MovieNames> arraylist;

    public ListViewAdapter(Context context, ArrayList<MovieNames> arraylist) {
        mContext = context;
        inflater = LayoutInflater.from(mContext);
        this.arraylist = arraylist;

    }

    public class ViewHolder {
        TextView name;
    }

    @Override
    public int getCount() {
        return arraylist.size();
    }

    @Override
    public MovieNames getItem(int position) {
        return arraylist.get(position);
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public View getView(final int position, View view, ViewGroup parent) {
        final ViewHolder holder;
        if (view == null) {
            holder = new ViewHolder();
            view = inflater.inflate(R.layout.listview_item, null);
            // Locate the TextViews in listview_item.xml
            holder.name = (TextView) view.findViewById(R.id.name);
            view.setTag(holder);
        } else {
            holder = (ViewHolder) view.getTag();
        }
        // Set the results into TextViews
        holder.name.setText(arraylist.get(position).getMovieName());
        return view;
    }


} 

Prepare activity_main.xml file :

    <?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context="com.example.parsaniahardik.searchedit.MainActivity"
    android:orientation="vertical">


    <EditText
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/editText"
        android:layout_alignParentTop="true"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:hint="enter query"
        android:singleLine="true">


        <requestFocus/>
    </EditText>

    <ListView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:id="@+id/listView"
        android:divider="#694fea"
        android:dividerHeight="1dp" />


</LinearLayout>

Finally make MainActivity.java class :

    import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ListView;
import android.widget.SearchView;
import android.widget.Toast;

import java.util.ArrayList;

public class MainActivity extends AppCompatActivity {

    private EditText etsearch;
    private ListView list;
    private ListViewAdapter adapter;
    private String[] moviewList;
    public static ArrayList<MovieNames> movieNamesArrayList;
    public static ArrayList<MovieNames> array_sort;
    int textlength = 0;

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

        // Generate sample data

        moviewList = new String[]{"Xmen", "Titanic", "Captain America",
                "Iron man", "Rocky", "Transporter", "Lord of the rings", "The jungle book",
                "Tarzan","Cars","Shreck"};

        list = (ListView) findViewById(R.id.listView);

        movieNamesArrayList = new ArrayList<>();
        array_sort = new ArrayList<>();

        for (int i = 0; i < moviewList.length; i++) {
            MovieNames movieNames = new MovieNames(moviewList[i]);
            // Binds all strings into an array
            movieNamesArrayList.add(movieNames);
            array_sort.add(movieNames);
        }

        adapter = new ListViewAdapter(this,movieNamesArrayList);
        list.setAdapter(adapter);


        etsearch = (EditText) findViewById(R.id.editText);

        list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                Toast.makeText(MainActivity.this, array_sort.get(position).getMovieName(), Toast.LENGTH_SHORT).show();
            }
        });

        etsearch.addTextChangedListener(new TextWatcher() {


            public void afterTextChanged(Editable s) {
            }

            public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            }

            public void onTextChanged(CharSequence s, int start, int before, int count) {
                textlength = etsearch.getText().length();
                array_sort.clear();
                for (int i = 0; i < movieNamesArrayList.size(); i++) {
                    if (textlength <= movieNamesArrayList.get(i).getMovieName().length()) {
                        Log.d("ertyyy",movieNamesArrayList.get(i).getMovieName().toLowerCase().trim());
                        if (movieNamesArrayList.get(i).getMovieName().toLowerCase().trim().contains(
                                etsearch.getText().toString().toLowerCase().trim())) {
                            array_sort.add(movieNamesArrayList.get(i));
                        }
                    }
                }
                    adapter = new ListViewAdapter(MainActivity.this, array_sort);
                    list.setAdapter(adapter);

            }
        });

    }
}

How to set seekbar min and max value

Set seekbar max and min value

seekbar have method that setmax(int position) and setProgress(int position)

thanks

Add Items to ListView - Android

ListView myListView = (ListView) rootView.findViewById(R.id.myListView);
ArrayList<String> myStringArray1 = new ArrayList<String>();
myStringArray1.add("something");
adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
myListView.setAdapter(adapter);

Try it like this

public OnClickListener moreListener = new OnClickListener() {

    @Override
    public void onClick(View v) {
        adapter = null;
        myStringArray1.add("Andrea");
        adapter = new CustomAdapter(getActivity(), R.layout.row, myStringArray1);
        myListView.setAdapter(adapter);
        adapter.notifyDataSetChanged();
    }       
};

Getting the current Fragment instance in the viewpager

To get current fragment - get position in ViewPager at public void onPageSelected(final int position), and then

public PlaceholderFragment getFragmentByPosition(Integer pos){
    for(Fragment f:getChildFragmentManager().getFragments()){
        if(f.getId()==R.viewpager && f.getArguments().getInt("SECTNUM") - 1 == pos) {
            return (PlaceholderFragment) f;
        }
    }
    return null;
}

SECTNUM - position argument assigned in public static PlaceholderFragment newInstance(int sectionNumber); of Fragment

getChildFragmentManager() or getFragmentManager() - depends on how created SectionsPagerAdapter

Android getting value from selected radiobutton

For anyone who is populating programmatically and looking to get an index, you might notice that the checkedId changes as you return to the activity/fragment and you re-add those radio buttons. One way to get around that is to set a tag with the index:

    for(int i = 0; i < myNames.length; i++) {
        rB = new RadioButton(getContext());
        rB.setText(myNames[i]);
        rB.setTag(i);
        myRadioGroup.addView(rB,i);
    }

Then in your listener:

    myRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            RadioButton radioButton = (RadioButton) group.findViewById(checkedId);
            int mySelectedIndex = (int) radioButton.getTag();
        }
    });

SeekBar and media player in android

    int  pos  = 0;
    yourSeekBar.setMax(mPlayer.getDuration());

After You start Your MediaPlayer i.e mplayer.start()

Try this code

while(mPlayer!=null){
         try {
                Thread.sleep(1000);
                pos  = mPlayer.getCurrentPosition();
            }  catch (Exception e) {
                //show exception in LogCat
            }
            yourSeekBar.setProgress(pos);

   }

Before you added this code you have to create xml resource for SeekBar and use it in Your Activity class of ur onCreate() method.

Change Image of ImageView programmatically in Android

If the above solutions are not working just delete this entire line from XML

android:src="@drawable/image"

& only try

imageView.setBackgroundResource(R.drawable.image);

Permanently hide Navigation Bar in an activity

Start by hiding in OnResume() of the activity then also keep hiding as shown below:

decorView.setOnSystemUiVisibilityChangeListener
                (new View.OnSystemUiVisibilityChangeListener() {
                    @Override
                    public void onSystemUiVisibilityChange(int visibility) {
                        // Note that system bars will only be "visible" if none of the
                        // LOW_PROFILE, HIDE_NAVIGATION, or FULLSCREEN flags are set.
                        if ((visibility & View.SYSTEM_UI_FLAG_FULLSCREEN) == 0) {
                            //visible
                            hideSystemUI();
                        } 
                    }
                    }
                });`

    public void hideSystemUI() {
        // Set the IMMERSIVE flag.
        // Set the content to appear under the system bars so that the content
        // doesn't resize when the system bars hide and show.
        decorView.setSystemUiVisibility(
                View.SYSTEM_UI_FLAG_LAYOUT_STABLE
                        | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION
                        | View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
                        | View.SYSTEM_UI_FLAG_HIDE_NAVIGATION // hide nav bar
                        | View.SYSTEM_UI_FLAG_FULLSCREEN // hide status bar
                        | View.SYSTEM_UI_FLAG_IMMERSIVE);
    }

runOnUiThread in fragment

In Xamarin.Android

For Fragment:

this.Activity.RunOnUiThread(() => { yourtextbox.Text="Hello"; });

For Activity:

RunOnUiThread(() => { yourtextbox.Text="Hello"; });

Happy coding :-)

How to detect incoming calls, in an Android device?

@Gabe Sechan, thanks for your code. It works fine except the onOutgoingCallEnded(). It is never executed. Testing phones are Samsung S5 & Trendy. There are 2 bugs I think.

1: a pair of brackets is missing.

case TelephonyManager.CALL_STATE_IDLE: 
    // Went to idle-  this is the end of a call.  What type depends on previous state(s)
    if (lastState == TelephonyManager.CALL_STATE_RINGING) {
        // Ring but no pickup-  a miss
        onMissedCall(context, savedNumber, callStartTime);
    } else {
        // this one is missing
        if(isIncoming){
            onIncomingCallEnded(context, savedNumber, callStartTime, new Date());                       
        } else {
            onOutgoingCallEnded(context, savedNumber, callStartTime, new Date());                                               
        }
    }
    // this one is missing
    break;

2: lastState is not updated by the state if it is at the end of the function. It should be replaced to the first line of this function by

public void onCallStateChanged(Context context, int state, String number) {
    int lastStateTemp = lastState;
    lastState = state;
    // todo replace all the "lastState" by lastStateTemp from here.
    if (lastStateTemp  == state) {
        //No change, debounce extras
        return;
    }
    //....
}

Additional I've put lastState and savedNumber into shared preference as you suggested.

Just tested it with above changes. Bug fixed at least on my phones.

Primefaces valueChangeListener or <p:ajax listener not firing for p:selectOneMenu

My problem were that we were using spring securyty, and the previous page doesn't call the page using faces-redirect=true, then the page show a java warning, and the control doesn't fire the change event.

Solution: The previous page must call the page using, faces-redirect=true

Android getActivity() is undefined

This is because you're using getActivity() inside an inner class. Try using:

SherlockFragmentActivity.this.getActivity()

instead, though there's really no need for the getActivity() part. In your case, SherlockFragmentActivity .this should suffice.

Set Focus on EditText

This changes the focus of the EditText when the button is clicked:

public class MainActivity extends Activity {
    private EditText e1,e2;
    private Button b1,b2;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        e1=(EditText) findViewById(R.id.editText1);
        e2=(EditText) findViewById(R.id.editText2);
        e1.requestFocus();
        b1=(Button) findViewById(R.id.one);
        b2=(Button) findViewById(R.id.two);
        b1.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                e1.requestFocus();

            }
        });
        b2.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                e2.requestFocus();
            }
        });
    }
}

Android. Fragment getActivity() sometimes returns null

Don't call methods within the Fragment that require getActivity() until onStart in the parent Activity.

private MyFragment myFragment;


public void onCreate(Bundle savedInstanceState)
{
    super.onCreate(savedInstanceState);

    FragmentTransaction ft = getSupportFragmentManager().beginTransaction();
    myFragment = new MyFragment();

    ft.add(android.R.id.content, youtubeListFragment).commit();

    //Other init calls
    //...
}


@Override
public void onStart()
{
    super.onStart();

    //Call your Fragment functions that uses getActivity()
    myFragment.onPageSelected();
}

How can I know when an EditText loses focus?

Have your Activity implement OnFocusChangeListener() if you want a factorized use of this interface, example:

public class Shops extends AppCompatActivity implements View.OnFocusChangeListener{

In your OnCreate you can add a listener for example:

editTextResearch.setOnFocusChangeListener(this);
editTextMyWords.setOnFocusChangeListener(this);
editTextPhone.setOnFocusChangeListener(this);

then android studio will prompt you to add the method from the interface, accept it... it will be like:

@Override
public void onFocusChange(View v, boolean hasFocus) {
// todo your code here...
}

and as you've got a factorized code, you'll just have to do that:

@Override
public void onFocusChange(View v, boolean hasFocus) {
   if (hasFocus) {
        editTextResearch.setText("");
        editTextMyWords.setText("");
        editTextPhone.setText("");
    }
    if (!hasFocus){
        editTextResearch.setText("BlaBlaBla");
        editTextMyWords.setText(" One Two Tree!");
        editTextPhone.setText("\"your phone here:\"");
    }
}

anything you code in the !hasFocus is for the behavior of the item that loses focus, that should do the trick! But beware that in such state, the change of focus might overwrite the user's entries!

How to disable keypad popup when on edittext?

Use following code in your onCreate() method-

    editText = (EditText) findViewById(R.id.editText);
    editText.requestFocus();
    editText.postDelayed(new Runnable() {
        public void run() {
            InputMethodManager keyboard = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            keyboard.hideSoftInputFromWindow(
                    editText.getWindowToken(), 0);
        }
    }, 200);

Android SeekBar setOnSeekBarChangeListener

Seekbar called onProgressChanged method when we initialize first time. We can skip by using below code We need to check boolean it return false when initialize automatically

volumeManager.setOnSeekBarChangeListener(new SeekBar.OnSeekBarChangeListener() {
            @Override
            public void onProgressChanged(SeekBar seekBar, int i, boolean b) {
                if(b){
                    mAudioManager.setStreamVolume(AudioManager.STREAM_MUSIC, i, 0);
                }
            }

            @Override
            public void onStartTrackingTouch(SeekBar seekBar) {

            }

            @Override
            public void onStopTrackingTouch(SeekBar seekBar) {

            }
        });

Android: I am unable to have ViewPager WRAP_CONTENT

If the ViewPager you're using is a child of a ScrollView AND has a PagerTitleStrip child you'll need to use a slight modification of the great answers already provided. For reference my XML looks like this:

<ScrollView
    android:id="@+id/match_scroll_view"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:background="@color/white">

    <LinearLayout
        android:id="@+id/match_and_graphs_wrapper"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <view
            android:id="@+id/pager"
            class="com.printandpixel.lolhistory.util.WrapContentHeightViewPager"
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.v4.view.PagerTitleStrip
                android:id="@+id/pager_title_strip"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_gravity="top"
                android:background="#33b5e5"
                android:paddingBottom="4dp"
                android:paddingTop="4dp"
                android:textColor="#fff" />
        </view>
    </LinearLayout>
</ScrollView>

In your onMeasure you have to ADD the measuredHeight of the PagerTitleStrip if one is found. Otherwise its height won't be considered into the largest height of all the children even though it takes up additional space.

Hope this helps someone else. Sorry that it's a bit of a hack...

public class WrapContentHeightViewPager extends ViewPager {

    public WrapContentHeightViewPager(Context context) {
        super(context);
    }

    public WrapContentHeightViewPager(Context context, AttributeSet attrs) {
        super(context, attrs);
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        int pagerTitleStripHeight = 0;
        int height = 0;
        for(int i = 0; i < getChildCount(); i++) {
            View child = getChildAt(i);
            child.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
            int h = child.getMeasuredHeight();
            if (h > height) {
                // get the measuredHeight of the tallest fragment
                height = h;
            }
            if (child.getClass() == PagerTitleStrip.class) {
                // store the measured height of the pagerTitleStrip if one is found. This will only
                // happen if you have a android.support.v4.view.PagerTitleStrip as a direct child
                // of this class in your XML.
                pagerTitleStripHeight = h;
            }
        }

        heightMeasureSpec = MeasureSpec.makeMeasureSpec(height+pagerTitleStripHeight, MeasureSpec.EXACTLY);

        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    }
}

Android: checkbox listener

try this

satView.setOnCheckedChangeListener(new android.widget.CompoundButton.OnCheckedChangeListener.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(RadioGroup group, int checkedId) {
            if (isChecked){
                // perform logic
            }
        }

    });

How to get the selected index of a RadioGroup in Android

You can use:

RadioButton rb = (RadioButton) findViewById(rg.getCheckedRadioButtonId());

Receiver not registered exception error?

Unregister broadcast receiver in Try Catch

    try {
        unregisterReceiver(receiver);
    } catch (IllegalArgumentException e) {
        System.out.printf(e.getMessage());
    }

How to call stopservice() method of Service class from the calling activity class

In fact to stopping the service we must use the method stopService() and you are doing in right way:

Start service:

  Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
  startService(myService);

Stop service:

  Intent myService = new Intent(MainActivity.this, BackgroundSoundService.class);
  stopService(myService);

if you call stopService(), then the method onDestroy() in the service is called (NOT the stopService() method):

  @Override
    public void onDestroy() {
      timer.cancel();
      task.cancel();    
        Log.i(TAG, "onCreate() , service stopped...");
    }

you must implement the onDestroy() method!.

Here is a complete example including how to start/stop the service.

Android: How can I validate EditText input?

This looks really promising and just what the doc ordered for me:

EditText Validator

    public void onClickNext(View v) {
    FormEditText[] allFields    = { etFirstname, etLastname, etAddress, etZipcode, etCity };
    
    
    boolean allValid = true;
    for (FormEditText field: allFields) {
        allValid = field.testValidity() && allValid;
    }
    
    if (allValid) {
        // YAY
    } else {
        // EditText are going to appear with an exclamation mark and an explicative message.
    }
}

custom validators plus these built in:

  • regexp: for custom regexp
  • numeric: for an only numeric field
  • alpha: for an alpha only field
  • alphaNumeric: guess what?
  • personName: checks if the entered text is a person first or last name.
  • personFullName: checks if the entered value is a complete full name.
  • email: checks that the field is a valid email
  • creditCard: checks that the field contains a valid credit card using Luhn Algorithm
  • phone: checks that the field contains a valid phone number
  • domainName: checks that field contains a valid domain name ( always passes the test in API Level < 8 )
  • ipAddress: checks that the field contains a valid ip address
  • webUrl: checks that the field contains a valid url ( always passes the test in API Level < 8 )
  • date: checks that the field is a valid date/datetime format ( if customFormat is set, checks with customFormat )
  • nocheck: It does not check anything except the emptyness of the field.

How do I round a double to two decimal places in Java?

Presuming the amount could be positive as well as negative, rounding to two decimal places may use the following piece of code snippet.

amount = roundTwoDecimals(amount);

public double roundTwoDecimals(double d) {
    if (d < 0)
       d -= 0.005;
    else if (d > 0)
       d += 0.005;
    return (double)((long)(d * 100.0))/100);
}

ModuleNotFoundError: No module named 'sklearn'

I had the same issue as the author, and ran into the issue with and without Anaconda and regardless of Python version. Everyone's environment is different, but after resolving it for myself I think that in some cases it may be due to having multiple version of Python installed. Each installed Python version has its own \Lib\site-packages\ folder which can contain a unique set of modules for that Python version, and where the IDE looks into folder path that doesn't have scikit-learn in it.

One way to try solve the issue: you might clear your system of all other Python versions and their cached/temp files/system variables, and then only have one version of Python installed anywhere. Then install the dependencies Numpy and Scipy, and finally Scikit-learn.

More detailed steps:

  1. Uninstall all Python versions and their launchers (e.g. from Control Panel in Windows) except the one version you want to keep. Delete any old Python version folders in the Python directory --uninstalling doesn't remove all files.
  2. Remove other Python versions from your OS' Environment Variables (both under the system and user variables sections)
  3. Clear temporary files. For example, for Windows, delete all AppData Temp cache files (in C:\Users\YourUserName\AppData\Local\Temp). In addition, you could also do a Windows disk cleanup for other temporary files, and then reboot.
  4. If your IDE supports it, create a new virtual environment in Settings, then set your only installed Python version as the interpreter.
  5. In your IDE, install the dependencies Scipy and Numpy from the module list first, then install Scikit-Learn.

As some others have suggested, the key is making sure your environment is set up correctly where everything points to the correct library folder on your computer where the Sklearn package is located. There are a few ways this can be resolved. My approach was more drastic, but it turns out that I had a very messy Python setup on my system so I had to start fresh.

Set field value with reflection

You can try this:

//Your class instance
Publication publication = new Publication();

//Get class with full path(with package name)
Class<?> c = Class.forName("com.example.publication.models.Publication");

//Get method
Method  method = c.getDeclaredMethod ("setTitle", String.class);

//set value
method.invoke (publication,  "Value to want to set here...");

What is the use of adding a null key or value to a HashMap in Java?

The answers so far only consider the worth of have a null key, but the question also asks about any number of null values.

The benefit of storing the value null against a key in a HashMap is the same as in databases, etc - you can record a distinction between having a value that is empty (e.g. string ""), and not having a value at all (null).

how to return a char array from a function in C

#include<stdio.h>
#include<string.h>
#include<stdlib.h>
char *substring(int i,int j,char *ch)
{
    int n,k=0;
    char *ch1;
    ch1=(char*)malloc((j-i+1)*1);
    n=j-i+1;

    while(k<n)
    {
        ch1[k]=ch[i];
        i++;k++;
    }

    return (char *)ch1;
}

int main()
{
    int i=0,j=2;
    char s[]="String";
    char *test;

    test=substring(i,j,s);
    printf("%s",test);
    free(test); //free the test 
    return 0;
}

This will compile fine without any warning

  1. #include stdlib.h
  2. pass test=substring(i,j,s);
  3. remove m as it is unused
  4. either declare char substring(int i,int j,char *ch) or define it before main

Map enum in JPA with fixed values?

I would do the folowing:

Declare separetly the enum, in it´s own file:

public enum RightEnum {
      READ(100), WRITE(200), EDITOR (300);

      private int value;

      private RightEnum (int value) { this.value = value; }


      @Override
      public static Etapa valueOf(Integer value){
           for( RightEnum r : RightEnum .values() ){
              if ( r.getValue().equals(value))
                 return r;
           }
           return null;//or throw exception
     }

      public int getValue() { return value; }


}

Declare a new JPA entity named Right

@Entity
public class Right{
    @Id
    private Integer id;
    //FIElDS

    // constructor
    public Right(RightEnum rightEnum){
          this.id = rightEnum.getValue();
    }

    public Right getInstance(RightEnum rightEnum){
          return new Right(rightEnum);
    }


}

You will also need a converter for receiving this values (JPA 2.1 only and there´s a problem I´ll not discuss here with these enum´s to be directly persisted using the converter, so it will be a one way road only)

import mypackage.RightEnum;
import javax.persistence.AttributeConverter;
import javax.persistence.Converter;

/**
 * 
 * 
 */
@Converter(autoApply = true)
public class RightEnumConverter implements AttributeConverter<RightEnum, Integer>{

    @Override //this method shoudn´t be used, but I implemented anyway, just in case
    public Integer convertToDatabaseColumn(RightEnum attribute) {
        return attribute.getValue();
    }

    @Override
    public RightEnum convertToEntityAttribute(Integer dbData) {
        return RightEnum.valueOf(dbData);
    }

}

The Authority entity:

@Entity
@Table(name = "AUTHORITY_")
public class Authority implements Serializable {


  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Column(name = "AUTHORITY_ID")
  private Long id;

  // the **Entity** to map : 
  private Right right;

  // the **Enum** to map (not to be persisted or updated) : 
  @Column(name="COLUMN1", insertable = false, updatable = false)
  @Convert(converter = RightEnumConverter.class)
  private RightEnum rightEnum;

}

By doing this way, you can´t set directly to the enum field. However, you can set the Right field in Authority using

autorithy.setRight( Right.getInstance( RightEnum.READ ) );//for example

And if you need to compare, you can use:

authority.getRight().equals( RightEnum.READ ); //for example

Which is pretty cool, I think. It´s not totally correct, since the converter it´s not intended to be use with enum´s. Actually, the documentation says to never use it for this purpose, you should use the @Enumerated annotation instead. The problem is that there are only two enum types: ORDINAL or STRING, but the ORDINAL is tricky and not safe.


However, if it doesn´t satisfy you, you can do something a little more hacky and simpler (or not).

Let´s see.

The RightEnum:

public enum RightEnum {
      READ(100), WRITE(200), EDITOR (300);

      private int value;

      private RightEnum (int value) { 
            try {
                  this.value= value;
                  final Field field = this.getClass().getSuperclass().getDeclaredField("ordinal");
                  field.setAccessible(true);
                  field.set(this, value);
             } catch (Exception e) {//or use more multicatch if you use JDK 1.7+
                  throw new RuntimeException(e);
            }
      }


      @Override
      public static Etapa valueOf(Integer value){
           for( RightEnum r : RightEnum .values() ){
              if ( r.getValue().equals(value))
                 return r;
           }
           return null;//or throw exception
     }

      public int getValue() { return value; }


}

and the Authority entity

@Entity
@Table(name = "AUTHORITY_")
public class Authority implements Serializable {


  @Id
  @GeneratedValue(strategy = GenerationType.AUTO)
  @Column(name = "AUTHORITY_ID")
  private Long id;


  // the **Enum** to map (to be persisted or updated) : 
  @Column(name="COLUMN1")
  @Enumerated(EnumType.ORDINAL)
  private RightEnum rightEnum;

}

In this second idea, its not a perfect situation since we hack the ordinal attribute, but it´s a much smaller coding.

I think that the JPA specification should include the EnumType.ID where the enum value field should be annotated with some kind of @EnumId annotation.

Compare two List<T> objects for equality, ignoring order

As written, this question is ambigous. The statement:

... they both have the same elements, regardless of their position within the list. Each MyType object may appear multiple times on a list.

does not indicate whether you want to ensure that the two lists have the same set of objects or the same distinct set.

If you want to ensure to collections have exactly the same set of members regardless of order, you can use:

// lists should have same count of items, and set difference must be empty
var areEquivalent = (list1.Count == list2.Count) && !list1.Except(list2).Any();

If you want to ensure two collections have the same distinct set of members (where duplicates in either are ignored), you can use:

// check that [(A-B) Union (B-A)] is empty
var areEquivalent = !list1.Except(list2).Union( list2.Except(list1) ).Any();

Using the set operations (Intersect, Union, Except) is more efficient than using methods like Contains. In my opinion, it also better expresses the expectations of your query.

EDIT: Now that you've clarified your question, I can say that you want to use the first form - since duplicates matter. Here's a simple example to demonstrate that you get the result you want:

var a = new[] {1, 2, 3, 4, 4, 3, 1, 1, 2};
var b = new[] { 4, 3, 2, 3, 1, 1, 1, 4, 2 };

// result below should be true, since the two sets are equivalent...
var areEquivalent = (a.Count() == b.Count()) && !a.Except(b).Any(); 

Where can I find a list of keyboard keycodes?

I know this was asked awhile back, but I found a comprehensive list of the virtual keyboard key codes right in MSDN, for use in C/C++. This also includes the mouse events. Note it is different than the javascript key codes (I noticed it around the VK_OEM section).

Here's the link:
http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx

Python - How to cut a string in Python?

>>str = "http://www.domain.com/?s=some&two=20"
>>str.split("&")
>>["http://www.domain.com/?s=some", "two=20"]

Enabling refreshing for specific html elements only

Try this:

_x000D_
_x000D_
function reload(){_x000D_
    var container = document.getElementById("yourDiv");_x000D_
    var content = container.innerHTML;_x000D_
    container.innerHTML= content; _x000D_
    _x000D_
   //this line is to watch the result in console , you can remove it later _x000D_
    console.log("Refreshed"); _x000D_
}
_x000D_
<a href="javascript: reload()">Click to Reload</a>_x000D_
    <div id="yourDiv">The content that you want to refresh/reload</div>
_x000D_
_x000D_
_x000D_

Hope it works. Let me know

Bad Request - Invalid Hostname IIS7

You can use Visual Studio 2005/2008/2010 CMD tool. Run it as admin, and write

aspnet_regiis -i

At last I can run my app successfully.

How can I get key's value from dictionary in Swift?

Use subscripting to access the value for a dictionary key. This will return an Optional:

let apple: String? = companies["AAPL"]

or

if let apple = companies["AAPL"] {
    // ...
}

You can also enumerate over all of the keys and values:

var companies = ["AAPL" : "Apple Inc", "GOOG" : "Google Inc", "AMZN" : "Amazon.com, Inc", "FB" : "Facebook Inc"]

for (key, value) in companies {
    print("\(key) -> \(value)")
}

Or enumerate over all of the values:

for value in Array(companies.values) {
    print("\(value)")
}

How to set header and options in axios?

You can pass a config object to axios like:

axios({
  method: 'post',
  url: '....',
  params: {'HTTP_CONTENT_LANGUAGE': self.language},
  headers: {'header1': value}
})

AngularJS $http, CORS and http authentication

For making a CORS request one must add headers to the request along with the same he needs to check of mode_header is enabled in Apache.

For enabling headers in Ubuntu:

sudo a2enmod headers

For php server to accept request from different origin use:

Header set Access-Control-Allow-Origin *
Header set Access-Control-Allow-Methods "GET, POST, PUT, DELETE"
Header always set Access-Control-Allow-Headers "x-requested-with, Content-Type, origin, authorization, accept, client-security-token"

Uppercase first letter of variable

http://phpjs.org/functions/ucwords:569 has a good example

function ucwords (str) {
    return (str + '').replace(/^([a-z])|\s+([a-z])/g, function ($1) {
        return $1.toUpperCase();
    });
}

(omitted function comment from source for brevity. please see linked source for details)

EDIT: Please note that this function uppercases the first letter of each word (as your question asks) and not just the first letter of a string (as your question title asks)

Twitter Bootstrap Responsive Background-Image inside Div

Mby bootstrap img-responsive class is you looking for.

Which Android IDE is better - Android Studio or Eclipse?

My first choice is Android Studio. its has great feature to develop android application.

Eclipse is not that hard to learn also.If you're going to be learning Android development from the start, I can recommend Hello, Android, which I just finished. It shows you exactly how to use all the features of Eclipse that are useful for developing Android apps. There's also a brief section on getting set up to develop from the command line and from other IDEs.

SonarQube Exclude a directory

If you're an Azure DevOps user looking for both where and how to exclude files and folders, here ya go:

  1. Edit your pipeline
  2. Make sure you have the "Prepare analysis on SonarQube" task added. You'll need to look elsewhere if you need help configuring this. Suggestion: Use the UI pipeline editor vs the yaml editor if you are missing the manage link. At present, there is no way to convert to UI from yaml. Just recreate the pipeline. If using git, you can delete the yaml from the root of your repo.
  3. Under the 'Advanced' section of the "Prepare analysis on SonarQube" task, you can add exclusions. See advice given by others for specific exclusion formats.

Example:

# Additional properties that will be passed to the scanner, 
# Put one key=value per line, example:
# sonar.exclusions=**/*.bin
sonar.exclusions=MyProjectName/MyWebContentFolder/**

Note: If you're not sure on the path, you can go into sonarqube, view your project, look at all or new 'Code Smells' and the path you need is listed above each grouping of issues. You can grab the full path to a file or use wilds like these examples:

  • MyProjectName/MyCodeFile.cs
  • MyProjectName/**

If you don't have the 'Run Code Analysis' task added, do that and place it somewhere after the 'Build solution **/*.sln' task.

Save and Queue and then check out your sonarqube server to see if the exclusions worked.

NPM clean modules

Try https://github.com/voidcosmos/npkill

npx npkill

it will find all node_modules and let you remove them.

npkill

Whats the CSS to make something go to the next line in the page?

It depends why the something is on the same line in the first place.

clear in the case of floats, display: block in the case of inline content naturally flowing, nothing will defeat position: absolute as the previous element will be taken out of the normal flow by it.

Does bootstrap 4 have a built in horizontal divider?

in Bootstrap 5 you can do something like this:

<div class="py-2 my-1 text-center position-relative mx-2">
            <div class="position-absolute w-100 top-50 start-50 translate-middle" style="z-index: 2">
                <span class="d-inline-block bg-white px-2 text-muted">or</span>
            </div>
            <div class="position-absolute w-100 top-50 start-0 border-muted border-top"></div>
</div>

There has been an error processing your request, Error log record number

A common solution is to upgrade magento setup by running this command

php bin/magento setup:upgrade && php bin/magento setup:di:compile

Otherwise just check var/report/{error number}

Python initializing a list of lists

The problem is that they're all the same exact list in memory. When you use the [x]*n syntax, what you get is a list of n many x objects, but they're all references to the same object. They're not distinct instances, rather, just n references to the same instance.

To make a list of 3 different lists, do this:

x = [[] for i in range(3)]

This gives you 3 separate instances of [], which is what you want

[[]]*n is similar to

l = []
x = []
for i in range(n):
    x.append(l)

While [[] for i in range(3)] is similar to:

x = []
for i in range(n):
    x.append([])   # appending a new list!

In [20]: x = [[]] * 4

In [21]: [id(i) for i in x]
Out[21]: [164363948, 164363948, 164363948, 164363948] # same id()'s for each list,i.e same object


In [22]: x=[[] for i in range(4)]

In [23]: [id(i) for i in x]
Out[23]: [164382060, 164364140, 164363628, 164381292] #different id(), i.e unique objects this time

What's the difference between identifying and non-identifying relationships?

The identifing relaionship means the child entity is totally depend on the existance of the parent entity. Example account table person table and personaccount.The person account table is identified by the existance of account and person table only.

The non identifing relationship means the child table does not identified by the existance of the parent table example there is table as accounttype and account.accounttype table is not identified with the existance of account table.

How to insert multiple rows from a single query using eloquent/fluent

It is really easy to do a bulk insert in Laravel with or without the query builder. You can use the following official approach.

Entity::upsert([
    ['name' => 'Pierre Yem Mback', 'city' => 'Eseka', 'salary' => 10000000],
    ['name' => 'Dial rock 360', 'city' => 'Yaounde', 'salary' => 20000000],
    ['name' => 'Ndibou La Menace', 'city' => 'Dakar', 'salary' => 40000000]
], ['name', 'city'], ['salary']);

How do you embed binary data in XML?

I had this problem just last week. I had to serialize a PDF file and send it, inside an XML file, to a server.

If you're using .NET, you can convert a binary file directly to a base64 string and stick it inside an XML element.

string base64 = Convert.ToBase64String(File.ReadAllBytes(fileName));

Or, there is a method built right into the XmlWriter object. In my particular case, I had to include Microsoft's datatype namespace:

StringBuilder sb = new StringBuilder();
System.Xml.XmlWriter xw = XmlWriter.Create(sb);
xw.WriteStartElement("doc");
xw.WriteStartElement("serialized_binary");
xw.WriteAttributeString("types", "dt", "urn:schemas-microsoft-com:datatypes", "bin.base64");
byte[] b = File.ReadAllBytes(fileName);
xw.WriteBase64(b, 0, b.Length);
xw.WriteEndElement();
xw.WriteEndElement();
string abc = sb.ToString();

The string abc looks something that looks like this:

<?xml version="1.0" encoding="utf-16"?>
<doc>
    <serialized_binary types:dt="bin.base64" xmlns:types="urn:schemas-microsoft-com:datatypes">
        JVBERi0xLjMKJaqrrK0KNCAwIG9iago8PCAvVHlwZSAvSW5mbw...(plus lots more)
    </serialized_binary>
</doc>

Why is System.Web.Mvc not listed in Add References?

You can also add this from the Nuget Package Manager Console, something like:

Install-Package Microsoft.AspNet.Mvc -Version 4.0.20710.0 -ProjectName XXXXX

Microsoft.AspNet.Mvc has dependencies on:

  • 'Microsoft.AspNet.WebPages (= 2.0.20710.0 && < 2.1)'
  • 'Microsoft.Web.Infrastructure (= 1.0.0.0)'
  • 'Microsoft.AspNet.Razor (= 2.0.20710.0 && < 2.1)'

...which seems like no biggie to me. In our case, this is a class library that exists solely to provide support for our Mvc apps. So, we figure it's a benign dependency at worst.

I definitely prefer this to pointing to an assembly on the file system or in the GAC, since updating the package in the future will likely be a lot less painful than experiences I've had with the GAC and file system assembly references in the past.

AngularJS - difference between pristine/dirty and touched/untouched

It's worth mentioning that the validation properties are different for forms and form elements (note that touched and untouched are for fields only):

Input fields have the following states:

$untouched The field has not been touched yet
$touched The field has been touched
$pristine The field has not been modified yet
$dirty The field has been modified
$invalid The field content is not valid
$valid The field content is valid

They are all properties of the input field, and are either true or false.

Forms have the following states:

$pristine No fields have been modified yet
$dirty One or more have been modified
$invalid The form content is not valid
$valid The form content is valid
$submitted The form is submitted

They are all properties of the form, and are either true or false.

Is right click a Javascript event?

You could use the event window.oncontextmenu, for example:

_x000D_
_x000D_
window.oncontextmenu = function () {_x000D_
  alert('Right Click')_x000D_
}
_x000D_
<h1>Please Right Click here!</h1>
_x000D_
_x000D_
_x000D_

.crx file install in chrome

Opening the debug console in Chrome, or even looking at the html source file (after it is loaded in the browser), make sure that all the paths there are valid (i.e. when you follow a link you get to it's content, and not an error). When something is not valid, fix the path (e.g. get rid of the server specific part and make sure you only refer to files that are part of your extension through paths like /js/jquery-123-min.js).

Angular (4, 5, 6, 7) - Simple example of slide in out animation on ngIf

First some code, then the explanaition. The official docs describing this are here.

import { trigger, transition, animate, style } from '@angular/animations'

@Component({
  ...
  animations: [
    trigger('slideInOut', [
      transition(':enter', [
        style({transform: 'translateY(-100%)'}),
        animate('200ms ease-in', style({transform: 'translateY(0%)'}))
      ]),
      transition(':leave', [
        animate('200ms ease-in', style({transform: 'translateY(-100%)'}))
      ])
    ])
  ]
})

In your template:

<div *ngIf="visible" [@slideInOut]>This element will slide up and down when the value of 'visible' changes from true to false and vice versa.</div>

I found the angular way a bit tricky to grasp, but once you understand it, it quite easy and powerful.

The animations part in human language:

  • We're naming this animation 'slideInOut'.
  • When the element is added (:enter), we do the following:
  • ->Immediately move the element 100% up (from itself), to appear off screen.
  • ->then animate the translateY value until we are at 0%, where the element would naturally be.

  • When the element is removed, animate the translateY value (currently 0), to -100% (off screen).

The easing function we're using is ease-in, in 200 milliseconds, you can change that to your liking.

Hope this helps!

Ant build failed: "Target "build..xml" does not exist"

since your ant file's name is build.xml, you should just type ant without ant build.xml. that is: > ant [enter]

How does one convert a HashMap to a List in Java?

If you wanna maintain the same order in your list, say: your Map looks like:

map.put(1, "msg1")
map.put(2, "msg2")
map.put(3, "msg3")

and you want your list looks like

["msg1", "msg2", "msg3"]   // same order as the map

you will have to iterate through the Map:

// sort your map based on key, otherwise you will get IndexOutofBoundException
Map<String, String> treeMap = new TreeMap<String, String>(map)

List<String> list = new List<String>();
for (treeMap.Entry<Integer, String> entry : treeMap.entrySet()) {
    list.add(entry.getKey(), entry.getValue());
}  

How to insert date values into table

Since dob is DATE data type, you need to convert the literal to DATE using TO_DATE and the proper format model. The syntax is:

TO_DATE('<date_literal>', '<format_model>')

For example,

SQL> CREATE TABLE t(dob DATE);

Table created.

SQL> INSERT INTO t(dob) VALUES(TO_DATE('17/12/2015', 'DD/MM/YYYY'));

1 row created.

SQL> COMMIT;

Commit complete.

SQL> SELECT * FROM t;

DOB
----------
17/12/2015

A DATE data type contains both date and time elements. If you are not concerned about the time portion, then you could also use the ANSI Date literal which uses a fixed format 'YYYY-MM-DD' and is NLS independent.

For example,

SQL> INSERT INTO t(dob) VALUES(DATE '2015-12-17');

1 row created.

How can I get a collection of keys in a JavaScript dictionary?

Use Object.keys() or shim it in older browsers...

const keys = Object.keys(driversCounter);

If you wanted values, there is Object.values() and if you want key and value, you can use Object.entries(), often paired with Array.prototype.forEach() like this...

Object.entries(driversCounter).forEach(([key, value]) => {
   console.log(key, value);
});

Alternatively, considering your use case, maybe this will do it...

var selectBox, option, prop;

selectBox = document.getElementById("drivers");

for (prop in driversCounter) {
   option = document.createElement("option");
   option.textContent = prop;
   option.value = driversCounter[prop];
   selectBox.add(option);
}

Spring Boot Rest Controller how to return different HTTP status codes?

One of the way to do this is you can use ResponseEntity as a return object.

@RequestMapping(value="/rawdata/", method = RequestMethod.PUT)

public ResponseEntity<?> create(@RequestBody String data) {

if(everything_fine)
    return new ResponseEntity<>(RestModel, HttpStatus.OK);
else
    return new ResponseEntity<>(null, HttpStatus.INTERNAL_SERVER_ERROR);

}

Jquery Ajax Call, doesn't call Success or Error

change your code to:

function ChangePurpose(Vid, PurId) {
    var Success = false;
    $.ajax({
        type: "POST",
        url: "CHService.asmx/SavePurpose",
        dataType: "text",
        async: false,
        data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
        contentType: "application/json; charset=utf-8",
        success: function (data) {
            Success = true;
        },
        error: function (textStatus, errorThrown) {
            Success = false;
        }
    });
    //done after here
    return Success;
} 

You can only return the values from a synchronous function. Otherwise you will have to make a callback.

So I just added async:false, to your ajax call

Update:

jquery ajax calls are asynchronous by default. So success & error functions will be called when the ajax load is complete. But your return statement will be executed just after the ajax call is started.

A better approach will be:

     // callbackfn is the pointer to any function that needs to be called
     function ChangePurpose(Vid, PurId, callbackfn) {
        var Success = false;
        $.ajax({
            type: "POST",
            url: "CHService.asmx/SavePurpose",
            dataType: "text",
            data: JSON.stringify({ Vid: Vid, PurpId: PurId }),
            contentType: "application/json; charset=utf-8",
            success: function (data) {
                callbackfn(data)
            },
            error: function (textStatus, errorThrown) {
                callbackfn("Error getting the data")
            }
        });
     } 

     function Callback(data)
     {
        alert(data);
     }

and call the ajax as:

 // Callback is the callback-function that needs to be called when asynchronous call is complete
 ChangePurpose(Vid, PurId, Callback);

SQL Server loop - how do I loop through a set of records

this way we can iterate into table data.

DECLARE @_MinJobID INT
DECLARE @_MaxJobID INT
CREATE  TABLE #Temp (JobID INT)

INSERT INTO #Temp SELECT * FROM DBO.STRINGTOTABLE(@JobID,',')
SELECT @_MinJID = MIN(JobID),@_MaxJID = MAX(JobID)  FROM #Temp

    WHILE @_MinJID <= @_MaxJID
    BEGIN

        INSERT INTO Mytable        
        (        
            JobID,        
        )        

        VALUES        
        (        
            @_MinJobID,        
        ) 

        SET @_MinJID = @_MinJID + 1;
    END

DROP TABLE #Temp

STRINGTOTABLE is user define function which will parse comma separated data and return table. thanks

Strip first and last character from C string

Further to @pmg's answer, note that you can do both operations in one statement:

char mystr[] = "Nmy stringP";
char *p = mystr;
p++[strlen(p)-1] = 0;

This will likely work as expected but behavior is undefined in C standard.

How do you detect/avoid Memory leaks in your (Unmanaged) code?

I'd like to offer something I've used at times in the past: a rudimentary leak checker which is source level and fairly automatic. I'm giving this away for three reasons:

  1. You might find it useful.

  2. Though it's a bit krufty, I don't let that embarass me.

  3. Even though it's tied to some win32 hooks, that should be easy to alleviate.

There are things of which you must be careful when using it: don't do anything that needs to lean on new in the underlying code, beware of the warnings about cases it might miss at the top of leakcheck.cpp, realize that if you turn on (and fix any issues with) the code that does image dumps, you may generate a huge file.

The design is meant to allow you to turn the checker on and off without recompiling everything that includes its header. Include leakcheck.h where you want to track checking and rebuild once. Thereafter, compile leakcheck.cpp with or without LEAKCHECK #define'd and then relink to turn it on and off. Including unleakcheck.h will turn it off locally in a file. Two macros are provided: CLEARALLOCINFO() will avoid reporting the same file and line inappropriately when you traverse allocating code that didn't include leakcheck.h. ALLOCFENCE() just drops a line in the generated report without doing any allocation.

Again, please realize that I haven't used this in a while and you may have to work with it a bit. I'm dropping it in to illustrate the idea. If there turns out to be sufficient interest, I'd be willing to work up an example, updating the code in the process, and replace the contents of the following URL with something nicer that includes a decently syntax-colored listing.

You can find it here: http://www.cse.ucsd.edu/~tkammeye/leakcheck.html

Switch php versions on commandline ubuntu 16.04

May be you might have an old PHP version like PHP 5.6 in your system and you installed PHP 7.2 too so thats multiple PHP in your machine. There are some applications which were developed when older PHP 5.6 was latest version, they are still live and you working on those applications, You might be working on Laravel simultaneously but Laravel requires PHP 7+ to get started. Getting the picture ?

In that case you can switch between the PHP versions to suit your requirements.

Switch From PHP 5.6 => PHP 7.2

Apache:-

sudo a2dismod php5.6
sudo a2enmod php7.2
sudo service apache2 restart

Command Line:-

sudo update-alternatives --set php /usr/bin/php7.2
sudo update-alternatives --set phar /usr/bin/phar7.2
sudo update-alternatives --set phar.phar /usr/bin/phar.phar7.2
sudo update-alternatives --set phpize /usr/bin/phpize7.2
sudo update-alternatives --set php-config /usr/bin/php-config7.2

And vice-versa, Switch From PHP 7.2 => PHP 5.6

Apache:-

sudo a2dismod php7.2
sudo a2enmod php5.6
sudo service apache2 restart

Command Line:-

sudo update-alternatives --set php /usr/bin/php5.6
sudo update-alternatives --set phar /usr/bin/phar5.6
sudo update-alternatives --set phar.phar /usr/bin/phar.phar5.6
sudo update-alternatives --set phpize /usr/bin/phpize5.6
sudo update-alternatives --set php-config /usr/bin/php-config5.6

Constants in Objective-C

There is also one thing to mention. If you need a non global constant, you should use static keyword.

Example

// In your *.m file
static NSString * const kNSStringConst = @"const value";

Because of the static keyword, this const is not visible outside of the file.


Minor correction by @QuinnTaylor: static variables are visible within a compilation unit. Usually, this is a single .m file (as in this example), but it can bite you if you declare it in a header which is included elsewhere, since you'll get linker errors after compilation

Is it valid to have a html form inside another html form?

HTML 4.x & HTML5 disallow nested forms, but HTML5 will allow a workaround with "form" attribute ("form owner").

As for HTML 4.x you can:

  1. Use an extra form(s) with only hidden fields & JavaScript to set its input's and submit the form.
  2. Use CSS to line up several HTML form to look like a single entity - but I think that's too hard.

How do I add multiple conditions to "ng-disabled"?

this way worked for me

ng-disabled="(user.Role.ID != 1) && (user.Role.ID != 2)"

How to count the number of true elements in a NumPy bool array

You have multiple options. Two options are the following.

numpy.sum(boolarr)
numpy.count_nonzero(boolarr)

Here's an example:

>>> import numpy as np
>>> boolarr = np.array([[0, 0, 1], [1, 0, 1], [1, 0, 1]], dtype=np.bool)
>>> boolarr
array([[False, False,  True],
       [ True, False,  True],
       [ True, False,  True]], dtype=bool)

>>> np.sum(boolarr)
5

Of course, that is a bool-specific answer. More generally, you can use numpy.count_nonzero.

>>> np.count_nonzero(boolarr)
5

How can I copy a Python string?

Copying a string can be done two ways either copy the location a = "a" b = a or you can clone which means b wont get affected when a is changed which is done by a = 'a' b = a[:]

"query function not defined for Select2 undefined error"

This issue boiled down to how I was building my select2 select box. In one javascript file I had...

$(function(){
  $(".select2").select2();
});

And in another js file an override...

$(function(){
    var employerStateSelector = 
                $("#registration_employer_state").select2("destroy");
    employerStateSelector.select2({
    placeholder: 'Select a State...'
    });
});

Moving the second override into a window load event resolved the issue.

$( window ).load(function() {
  var employerStateSelector = 
              $("#registration_employer_state").select2("destroy");
  employerStateSelector.select2({
    placeholder: 'Select a State...'
  });
});

This issue blossomed inside a Rails application

How do I clone a specific Git branch?

git clone --single-branch --branch <branchname> <remote-repo>

The --single-branch option is valid from version 1.7.10 and later.

Please see also the other answer which many people prefer.

You may also want to make sure you understand the difference. And the difference is: by invoking git clone --branch <branchname> url you're fetching all the branches and checking out one. That may, for instance, mean that your repository has a 5kB documentation or wiki branch and 5GB data branch. And whenever you want to edit your frontpage, you may end up cloning 5GB of data.

Again, that is not to say git clone --branch is not the way to accomplish that, it's just that it's not always what you want to accomplish, when you're asking about cloning a specific branch.

How to configure WAMP (localhost) to send email using Gmail?

As an alternative to PHPMailer, Pear's Mail and others you could use the Zend's library

  $config = array('auth' => 'login',
                   'ssl' => 'ssl',
                   'port'=> 465,
                   'username' => '[email protected]',
                   'password' => 'XXXXXXX');

 $transport = new Zend_Mail_Transport_Smtp('smtp.gmail.com', $config);
 $mail = new Zend_Mail();
 $mail->setBodyText('This is the text of the mail.');
 $mail->setFrom('[email protected]', 'Some Sender');
 $mail->addTo('[email protected]', 'Some Recipient');
 $mail->setSubject('TestSubj');
 $mail->send($transport); 

That is my set up in localhost server and I can able to see incoming mail to my mail box.

How to rename uploaded file before saving it into a directory?

You can Try this,

$newfilename= date('dmYHis').str_replace(" ", "", basename($_FILES["file"]["name"]));

move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);

C# using streams

To expand a little on other answers here, and help explain a lot of the example code you'll see dotted about, most of the time you don't read and write to a stream directly. Streams are a low-level means to transfer data.

You'll notice that the functions for reading and writing are all byte orientated, e.g. WriteByte(). There are no functions for dealing with integers, strings etc. This makes the stream very general-purpose, but less simple to work with if, say, you just want to transfer text.

However, .NET provides classes that convert between native types and the low-level stream interface, and transfers the data to or from the stream for you. Some notable such classes are:

StreamWriter // Badly named. Should be TextWriter.
StreamReader // Badly named. Should be TextReader.
BinaryWriter
BinaryReader

To use these, first you acquire your stream, then you create one of the above classes and associate it with the stream. E.g.

MemoryStream memoryStream = new MemoryStream();
StreamWriter myStreamWriter = new StreamWriter(memoryStream);

StreamReader and StreamWriter convert between native types and their string representations then transfer the strings to and from the stream as bytes. So

myStreamWriter.Write(123);

will write "123" (three characters '1', '2' then '3') to the stream. If you're dealing with text files (e.g. html), StreamReader and StreamWriter are the classes you would use.

Whereas

myBinaryWriter.Write(123);

will write four bytes representing the 32-bit integer value 123 (0x7B, 0x00, 0x00, 0x00). If you're dealing with binary files or network protocols BinaryReader and BinaryWriter are what you might use. (If you're exchanging data with networks or other systems, you need to be mindful of endianness, but that's another post.)

move div with CSS transition

Something like this?

DEMO

And the code I used:

.box{
    position: relative;
    overflow: hidden;
}

.box:hover .hidden{

    left: 0px;
}

.box .hidden {    
    background: yellow;
    height: 300px;    
    position: absolute; 
    top: 0;
    left: -500px;    
    width: 500px;
    opacity: 1;    
    -webkit-transition: all 0.7s ease-out;
       -moz-transition: all 0.7s ease-out;
        -ms-transition: all 0.7s ease-out;
         -o-transition: all 0.7s ease-out;
            transition: all 0.7s ease-out;
}

I may also add that it's possible to move an elment using transform: translate(); , which in this case could work something like this - DEMO nr2

How do I close a single buffer (out of many) in Vim?

Use:

  • :ls - to list buffers
  • :bd#n - to close buffer where #n is the buffer number (use ls to get it)

Examples:

  • to delete buffer 2:

    :bd2
    

How to set delay in android?

Try this code:

import android.os.Handler;
...
final Handler handler = new Handler();
handler.postDelayed(new Runnable() {
    @Override
    public void run() {
        // Do something after 5s = 5000ms
        buttons[inew][jnew].setBackgroundColor(Color.BLACK);
    }
}, 5000);

Windows batch command(s) to read first line from text file

One liner, useful for stdout redirect with ">":

@for /f %%i in ('type yourfile.txt') do @echo %%i & exit

Convert UTC to local time in Rails 3

There is actually a nice Gem called local_time by basecamp to do all of that on client side only, I believe:

https://github.com/basecamp/local_time

Parsing CSV / tab-delimited txt file with Python

Although there is nothing wrong with the other solutions presented, you could simplify and greatly escalate your solutions by using python's excellent library pandas.

Pandas is a library for handling data in Python, preferred by many Data Scientists.

Pandas has a simplified CSV interface to read and parse files, that can be used to return a list of dictionaries, each containing a single line of the file. The keys will be the column names, and the values will be the ones in each cell.

In your case:

    import pandas

    def create_dictionary(filename):
        my_data = pandas.DataFrame.from_csv(filename, sep='\t', index_col=False)
        # Here you can delete the dataframe columns you don't want!
        del my_data['B']
        del my_data['D']
        # ...
        # Now you transform the DataFrame to a list of dictionaries
        list_of_dicts = [item for item in my_data.T.to_dict().values()]
        return list_of_dicts

# Usage:
x = create_dictionary("myfile.csv")

ESLint not working in VS Code?

Restarting VSCode worked for me.

How to set data attributes in HTML elements

You can also use the following attr thing;

HTML

<div id="mydiv" data-myval="JohnCena"></div>

Script

 $('#mydiv').attr('data-myval', 'Undertaker'); // sets 
 $('#mydiv').attr('data-myval'); // gets

OR

$('#mydiv').data('myval'); // gets value
$('#mydiv').data('myval','John Cena'); // sets value

TypeScript hashmap/dictionary interface

The most simple and the correct way is to use Record type Record<string, string>

const myVar : Record<string, string> = {
   key1: 'val1',
   key2: 'val2',
}

JavaScript/jQuery to download file via POST with JSON data

There is a simplier way, create a form and post it, this runs the risk of resetting the page if the return mime type is something that a browser would open, but for csv and such it's perfect

Example requires underscore and jquery

var postData = {
    filename:filename,
    filecontent:filecontent
};
var fakeFormHtmlFragment = "<form style='display: none;' method='POST' action='"+SAVEAS_PHP_MODE_URL+"'>";
_.each(postData, function(postValue, postKey){
    var escapedKey = postKey.replace("\\", "\\\\").replace("'", "\'");
    var escapedValue = postValue.replace("\\", "\\\\").replace("'", "\'");
    fakeFormHtmlFragment += "<input type='hidden' name='"+escapedKey+"' value='"+escapedValue+"'>";
});
fakeFormHtmlFragment += "</form>";
$fakeFormDom = $(fakeFormHtmlFragment);
$("body").append($fakeFormDom);
$fakeFormDom.submit();

For things like html, text and such, make sure the mimetype is some thing like application/octet-stream

php code

<?php
/**
 * get HTTP POST variable which is a string ?foo=bar
 * @param string $param
 * @param bool $required
 * @return string
 */
function getHTTPPostString ($param, $required = false) {
    if(!isset($_POST[$param])) {
        if($required) {
            echo "required POST param '$param' missing";
            exit 1;
        } else {
            return "";
        }
    }
    return trim($_POST[$param]);
}

$filename = getHTTPPostString("filename", true);
$filecontent = getHTTPPostString("filecontent", true);

header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"$filename\"");
echo $filecontent;

How can I stop python.exe from closing immediately after I get an output?

It looks like you are running something in Windows by double clicking on it. This will execute the program in a new window and close the window when it terminates. No wonder you cannot read the output.

A better way to do this would be to switch to the command prompt. Navigate (cd) to the directory where the program is located and then call it using python. Something like this:

C:\> cd C:\my_programs\
C:\my_programs\> python area.py

Replace my_programs with the actual location of your program and area.py with the name of your python file.

Get querystring from URL using jQuery

Have a look at this Stack Overflow answer.

 function getParameterByName(name, url) {
     if (!url) url = window.location.href;
     name = name.replace(/[\[\]]/g, "\\$&");
     var regex = new RegExp("[?&]" + name + "(=([^&#]*)|&|#|$)"),
         results = regex.exec(url);
     if (!results) return null;
     if (!results[2]) return '';
     return decodeURIComponent(results[2].replace(/\+/g, " "));
 }

You can use the method to animate:

I.e.:

var thequerystring = getParameterByName("location");
$('html,body').animate({scrollTop: $("div#" + thequerystring).offset().top}, 500);

Convert pandas dataframe to NumPy array

Just had a similar problem when exporting from dataframe to arcgis table and stumbled on a solution from usgs (https://my.usgs.gov/confluence/display/cdi/pandas.DataFrame+to+ArcGIS+Table). In short your problem has a similar solution:

df

      A    B    C
ID               
1   NaN  0.2  NaN
2   NaN  NaN  0.5
3   NaN  0.2  0.5
4   0.1  0.2  NaN
5   0.1  0.2  0.5
6   0.1  NaN  0.5
7   0.1  NaN  NaN

np_data = np.array(np.rec.fromrecords(df.values))
np_names = df.dtypes.index.tolist()
np_data.dtype.names = tuple([name.encode('UTF8') for name in np_names])

np_data

array([( nan,  0.2,  nan), ( nan,  nan,  0.5), ( nan,  0.2,  0.5),
       ( 0.1,  0.2,  nan), ( 0.1,  0.2,  0.5), ( 0.1,  nan,  0.5),
       ( 0.1,  nan,  nan)], 
      dtype=(numpy.record, [('A', '<f8'), ('B', '<f8'), ('C', '<f8')]))

Lightweight workflow engine for Java

Java based workflow engines like Activiti, Bonita or jBPM support a wide range of the BPMN 2.0 specification. Therefore, you can model processes in a graphical way. In addition, some of those engines have simulation capabilities like Activiti (with Activiti Crystalball). If you code the processes on your own, you aren´t as flexible when you need to change the process. Therefore, I would also advice to use a java based BPM engine.

I did a research concerning BPMN 2.0 based Open Source Engines. Here are the key-points which were relevant for our concrete use case:

1. Bonita:

Bonita has a zero-coding approach which means that they provide an easy to use IDE to build your processes without the need for coding. To achieve that, Bonita has the concept of connectors. For example, if you want to consume a web service, they provide you with a graphical wizzard. The downside is that you have to write the plain XML SOAP-envelope manually and copy it in a graphical textbox. The problem with this approach is that you only can realize use cases which are intended by Bonita. If you want to integrate a system which Bonita did not developed a connector for, you have to code such a connector on your own which is very painful. For example, Bonita offers a SOAP connector for consuming SOAP web services. This connector only works with SOAP 1.2, but not for SOAP 1.1 (http://community.bonitasoft.com/answers/consume-soap-11-webservices-bonita-secure-web-service-connector). If you have a legacy application with SOAP 1.1, you cannot integrate this system easily in your process. The same is true for databases. There are only a few database connectors for dedicated database versions. If you have a version not matching to a connector, you have to code this on your own.

In addition, Bonita has no support for LDAP or Active Directory Sync in the free community edition which is quite a showstopper for a production environment. Another thing to consider is that Bonita is licensed under the GPL / LGPL license which could cause problems when you want to integrate Bonita in another enterprise application. In addition, the community support is very weak. There are several posts which are more than 2 years old and those posts are still not answered.

Another important thing is Business-IT-Alignment. Modelling processes is a collaborative discipline in which IT AND the business analysts are involed. That is why you need adequate tools for both user groups (e.g. an Eclipse Plugin for the developers and an easy to use web modeler for the business people). Bonita only offers Bonita Studio, which needs to be installed on your machine. This IDE is quite technical and not suitable for business users. Therefore, it is very hard to realize Business-IT-Alignment with Bonita.

Bonita is a BPM tool for very trivial and easy processes. Because of the zero-coding approach, the lerning curve is very low and you can start modelling very fast. You need less programming skills and you are able to realize your processes without the need of coding. But as soon as your processes become very complex, Bonita might not be the best solution because of the lack of flexibility. You only can realize use cases which are intended by Bonita.

2. jBPM:

jBPM is a very powerful Open Source BPM Engine which has a lot of features. The web modeler even supports prefabricated models of some van der Aalst workflow patterns (workflowpatterns.com). Business-IT-Alignment is realizable because jBPM offers an Eclipse integration as well as a web-based modeler. A bit tricky is that you only can define forms in the web modeler, but not in the Eclipse Plugin, as far as I know. To sum up, jBPM is a good candidate for using in a company. Our showstopper was the scalability. jBPM is based on the Rules-Engine Drools. This leads to the fact that whole process instances are persisted as BLOBS in the database. This is a critial showstopper when you consider searching and scalability.

In addition, the learning curve is very high because of the complexity. jBPM does not offer a Service Task like the BPMN-Standard suggests In contrast, you have to define your own Java Service tasks and you have to register them manually in the engine, which results in quite low level programming.

3. Activiti:

In the end, we went with Activiti because this is a very easy to use framework-based engine. It offers an Eclipse Plugin as well as a modern AngularJS Web-Modeler. In this way, you can realize Business-IT-Alignment. The REST-API is secured by Spring Security which means that you can extend the Engine very easily with Single Sign-on features. Because of the Apache License 2.0, there is no copyleft which means you are completely free in terms of usage and extensibility which is very important in a productive environment.

In addition, the BPMN-coverage is very good. Not all BPMN-elements are realized, but I do not know any engine which does that.

The Activiti Explorer is a demo frontend which demonstrates the usage of the Activiti APIs. Since this frontend is based on VAADIN, it can be extended very easily. The community is very active which means that you can get help very fast if you have any problems.

Activiti offers good integration points for external form-technologies which is very important for a productive usage. The form-technologies of all candidates are very restrictive. Therefore, it makes sense to use a standard form-technology like XForms in combination with the Engine. Even such more complex things are realizable via the formKey-Attribute.

Activiti does not follow the zero-coding approach which means that you will need a bit of coding if you want to orchestrate services. But even the communication with SOAP services can be achieved by using a Java Service Task and Apache CXF. The coding effort is low.

I hope that my key points can help by taking a decision. To be clear, this is no advertisment for Activiti. The right product choice depends on the concrete use cases. I only want to point out the most important points in our project

Return JSON response from Flask view

As of version 1.1.0 Flask, if a view returns a dict it will be turned into a JSON response.

@app.route("/users", methods=['GET'])
def get_user():
    return {
        "user": "John Doe",
    }

Nested Recycler view height doesn't wrap its content

Used solution from @sinan-kozak, except fixed a few bugs. Specifically, we shouldn't use View.MeasureSpec.UNSPECIFIED for both the width and height when calling measureScrapChild as that won't properly account for wrapped text in the child. Instead, we will pass through the width and height modes from the parent which will allow things to work for both horizontal and vertical layouts.

public class MyLinearLayoutManager extends LinearLayoutManager {

public MyLinearLayoutManager(Context context, int orientation, boolean reverseLayout)    {
    super(context, orientation, reverseLayout);
}

private int[] mMeasuredDimension = new int[2];

@Override
public void onMeasure(RecyclerView.Recycler recycler, RecyclerView.State state,
                      int widthSpec, int heightSpec) {
    final int widthMode = View.MeasureSpec.getMode(widthSpec);
    final int heightMode = View.MeasureSpec.getMode(heightSpec);
    final int widthSize = View.MeasureSpec.getSize(widthSpec);
    final int heightSize = View.MeasureSpec.getSize(heightSpec);
    int width = 0;
    int height = 0;
    for (int i = 0; i < getItemCount(); i++) {    
        if (getOrientation() == HORIZONTAL) {
            measureScrapChild(recycler, i,
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                View.MeasureSpec.makeMeasureSpec(heightSize, heightMode),
                mMeasuredDimension);

            width = width + mMeasuredDimension[0];
            if (i == 0) {
                height = mMeasuredDimension[1];
            }
        } else {
            measureScrapChild(recycler, i,
                View.MeasureSpec.makeMeasureSpec(widthSize, widthMode),
                View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED),
                mMeasuredDimension);

            height = height + mMeasuredDimension[1];
            if (i == 0) {
                width = mMeasuredDimension[0];
            }
        }
    }

    // If child view is more than screen size, there is no need to make it wrap content. We can use original onMeasure() so we can scroll view.
    if (height < heightSize && width < widthSize) {

        switch (widthMode) {
            case View.MeasureSpec.EXACTLY:
                width = widthSize;
            case View.MeasureSpec.AT_MOST:
            case View.MeasureSpec.UNSPECIFIED:
        }

        switch (heightMode) {
            case View.MeasureSpec.EXACTLY:
                height = heightSize;
            case View.MeasureSpec.AT_MOST:
            case View.MeasureSpec.UNSPECIFIED:
        }

        setMeasuredDimension(width, height);
    } else {
        super.onMeasure(recycler, state, widthSpec, heightSpec);
    }
}

private void measureScrapChild(RecyclerView.Recycler recycler, int position, int widthSpec,
                               int heightSpec, int[] measuredDimension) {

   View view = recycler.getViewForPosition(position);

   // For adding Item Decor Insets to view
   super.measureChildWithMargins(view, 0, 0);
    if (view != null) {
        RecyclerView.LayoutParams p = (RecyclerView.LayoutParams) view.getLayoutParams();
        int childWidthSpec = ViewGroup.getChildMeasureSpec(widthSpec,
                    getPaddingLeft() + getPaddingRight() + getDecoratedLeft(view) + getDecoratedRight(view), p.width);
            int childHeightSpec = ViewGroup.getChildMeasureSpec(heightSpec,
                    getPaddingTop() + getPaddingBottom() + getDecoratedTop(view) + getDecoratedBottom(view) , p.height);
            view.measure(childWidthSpec, childHeightSpec);

            // Get decorated measurements
            measuredDimension[0] = getDecoratedMeasuredWidth(view) + p.leftMargin + p.rightMargin;
            measuredDimension[1] = getDecoratedMeasuredHeight(view) + p.bottomMargin + p.topMargin;
            recycler.recycleView(view);
        }
    }
}

`

HTML how to clear input using javascript?

For me this is the best way:

<form id="myForm">
  First name: <input type="text" name="fname"><br>
  Last name: <input type="text" name="lname"><br><br>
  <input type="button" onclick="myFunction()" value="Reset form">
</form>

<script>
function myFunction() {
    document.getElementById("myForm").reset();
}
</script>

Is there any difference between "!=" and "<>" in Oracle Sql?

No there is no difference at all in functionality.
(The same is true for all other DBMS - most of them support both styles):

Here is the current SQL reference: https://docs.oracle.com/database/121/SQLRF/conditions002.htm#CJAGAABC

The SQL standard only defines a single operator for "not equals" and that is <>

TypeError: a bytes-like object is required, not 'str'

Simply replace message parameter passed in clientSocket.sendto(message,(serverName, serverPort)) to clientSocket.sendto(message.encode(),(serverName, serverPort)). Then you would successfully run in in python3

javascript date to string

I like Daniel Cerecedo's answer using toJSON() and regex. An even simpler form would be:

var now = new Date();
var regex = /^(\d{4})-(\d{2})-(\d{2})T(\d{2}):(\d{2}):(\d{2}).*$/;
var token_array = regex.exec(now.toJSON());
// [ "2017-10-31T02:24:45.868Z", "2017", "10", "31", "02", "24", "45" ]
var myFormat = token_array.slice(1).join('');
// "20171031022445"

Expand and collapse with angular js

In html

button ng-click="myMethod()">Videos</button>

In angular

 $scope.myMethod = function () {
         $(".collapse").collapse('hide');    //if you want to hide
         $(".collapse").collapse('toggle');  //if you want toggle
         $(".collapse").collapse('show');    //if you want to show
}

Abort a Git Merge

as long as you did not commit you can type

git merge --abort

just as the command line suggested.

event.preventDefault() function not working in IE

To disable a keyboard key after IE9, use : e.preventDefault();

To disable a regular keyboard key under IE7/8, use : e.returnValue = false; or return false;

If you try to disable a keyboard shortcut (with Ctrl, like Ctrl+F) you need to add those lines :

try {
    e.keyCode = 0;
}catch (e) {}

Here is a full example for IE7/8 only :

document.attachEvent("onkeydown", function () {
    var e = window.event;

    //Ctrl+F or F3
    if (e.keyCode === 114 || (e.ctrlKey && e.keyCode === 70)) {
        //Prevent for Ctrl+...
        try {
            e.keyCode = 0;
        }catch (e) {}

        //prevent default (could also use e.returnValue = false;)
        return false;
    }
});

Reference : How to disable keyboard shortcuts in IE7 / IE8

Defining array with multiple types in TypeScript

You can either use a regular tuple

interface IReqularDemo: [number, string];

or if optional parameters support is needed

interface IOptionalDemo: [value1: number, value2?: string]

Using number as "index" (JSON)

When a Javascript object property's name doesn't begin with either an underscore or a letter, you cant use the dot notation (like Game.status[0].0), and you must use the alternative notation, which is Game.status[0][0].

One different note, do you really need it to be an object inside the status array? If you're using the object like an array, why not use a real array instead?

Double.TryParse or Convert.ToDouble - which is faster and safer?

Unless you are 100% certain of your inputs, which is rarely the case, you should use Double.TryParse.

Convert.ToDouble will throw an exception on non-numbers
Double.Parse will throw an exception on non-numbers or null
Double.TryParse will return false or 0 on any of the above without generating an exception.

The speed of the parse becomes secondary when you throw an exception because there is not much slower than an exception.

Laravel, sync() - how to sync an array and also pass additional pivot fields?

Simply just append your fields and their values to the elements:

$user->roles()->sync([
   1 => ['F1' => 'F1 Updated']
]);

Best way to check for "empty or null value"

Something that I saw people using is stringexpression > ''. This may be not the fastest one, but happens to be one of the shortest.

Tried it on MS SQL as well as on PostgreSQL.

What is "loose coupling?" Please provide examples

You can think of (tight or loose) coupling as being literally the amount of effort it would take you to separate a particular class from its reliance on another class. For example, if every method in your class had a little finally block at the bottom where you made a call to Log4Net to log something, then you would say your class was tightly coupled to Log4Net. If your class instead contained a private method named LogSomething which was the only place that called the Log4Net component (and the other methods all called LogSomething instead), then you would say your class was loosely coupled to Log4Net (because it wouldn't take much effort to pull Log4Net out and replace it with something else).

Allowing Untrusted SSL Certificates with HttpClient

With Windows 8.1, you can now trust invalid SSL certs. You have to either use the Windows.Web.HttpClient or if you want to use the System.Net.Http.HttpClient, you can use the message handler adapter I wrote: http://www.nuget.org/packages/WinRtHttpClientHandler

Docs are on the GitHub: https://github.com/onovotny/WinRtHttpClientHandler

How to include Authorization header in cURL POST HTTP Request in PHP?

use "Content-type: application/x-www-form-urlencoded" instead of "application/json"

Removing "bullets" from unordered list <ul>

In your css file add following.

ul{
 list-style-type: none;
}

Is there an easy way to attach source in Eclipse?

I was going to ask for an alternative to attaching sources to the same JAR being used across multiple projects. Originally, I had thought that the only alternative is to re-build the JAR with the source included but looking at the "user library" feature, you don't have to build the JAR with the source.

This is an alternative when you have multiple projects (related or not) that reference the same JAR. Create an "user library" for each JAR and attach the source to them. Next time you need a specific JAR, instead of using "Add JARs..." or "Add External JARs..." you add the "user library" that you have previously created.

You would only have to attach the source ONCE per JAR and can re-use it for any number of projects.

Environment Variable with Maven

There is a maven plugin called properties-maven-plugin this one provides a goal set-system-properties to set system variables. This is especially useful if you have a file containing all these properties. So you're able to read a property file and set them as system variable.

How to add additional fields to form before submit?

Try this:

$('#form').submit(function(eventObj) {
    $(this).append('<input type="hidden" name="field_name" value="value" /> ');
    return true;
});

Printing all variables value from a class

If you are using Eclipse, this should be easy:

1.Press Alt+Shift+S

2.Choose "Generate toString()..."

Enjoy! You can have any template of toString()s.

This also works with getter/setters.

React Native fetch() Network Request Failed

  1. Add android:usesCleartextTraffic="true" line in AndroidManifest.xml.

  2. Delete all debug folder from your android folder.

How to log request and response body with Retrofit-Android?

I hope this code will help you to logging .
you just need to add interceptor in your Build.Gradle then make RetrofitClient .

First Step

Add this line to your build.gradle

 implementation 'com.squareup.okhttp3:logging-interceptor:3.4.1' 

Second Step

Make your Retrofit Client


   public class RetrofitClient {

    private Retrofit retrofit;
    private static OkHttpClient.Builder httpClient =
            new OkHttpClient.Builder();
    private static RetrofitClient instance = null;
    private static ApiServices service = null;
    private static HttpLoggingInterceptor logging =
            new HttpLoggingInterceptor();

    private RetrofitClient(final Context context) {
        httpClient.interceptors().add(new Interceptor() {
            @Override
            public okhttp3.Response intercept(Interceptor.Chain chain) throws IOException {
                Request originalRequest = chain.request();
                Request.Builder builder = originalRequest.newBuilder().
                        method(originalRequest.method(), originalRequest.body());
                okhttp3.Response response = chain.proceed(builder.build());
                /*
                Do what you want
                 */
                return response;
            }
        });

        if (BuildConfig.DEBUG) {
            logging.setLevel(HttpLoggingInterceptor.Level.BODY);
            // add logging as last interceptor
            httpClient.addInterceptor(logging);
        }

        retrofit = new Retrofit.Builder().client(httpClient.build()).
                baseUrl(Constants.BASE_URL).
                addConverterFactory(GsonConverterFactory.create()).build();
        service = retrofit.create(ApiServices.class);
    }


    public static RetrofitClient getInstance(Context context) {
        if (instance == null) {
            instance = new RetrofitClient(context);
        }
        return instance;
    }

    public ApiServices getApiService() {
        return service;
    }
}

Calling

RetrofitClient.getInstance(context).getApiService().yourRequestCall(); 

Is there an XSLT name-of element?

This will give you the current element name (tag name)

<xsl:value-of select ="name(.)"/>

OP-Edit: This will also do the trick:

<xsl:value-of select ="local-name()"/>

Service Temporarily Unavailable Magento?

I had the same issue but have not found the maintenance.flag file in my Magento root. I simply deleted cache and sessions files and all worked again.

Is there a naming convention for git repositories?

lowercase-with-hyphens is the style I most often see on GitHub.*

lowercase_with_underscores is probably the second most popular style I see.

The former is my preference because it saves keystrokes.

* Anecdotal; I haven't collected any data.

jquery - Click event not working for dynamically created button

the simple and easy way to do that is use on event:

$('body').on('click','#element',function(){
    //somthing
});

but we can say this is not the best way to do this. I suggest a another way to do this is use clone() method instead of using dynamic html. Write some html in you file for example:

<div id='div1'></div>

Now in the script tag make a clone of this div then all the properties of this div would follow with new element too. For Example:

var dynamicDiv = jQuery('#div1').clone(true);

Now use the element dynamicDiv wherever you want to add it or change its properties as you like. Now all jQuery functions will work with this element

Difference between text and varchar (character varying)

text and varchar have different implicit type conversions. The biggest impact that I've noticed is handling of trailing spaces. For example ...

select ' '::char = ' '::varchar, ' '::char = ' '::text, ' '::varchar = ' '::text

returns true, false, true and not true, true, true as you might expect.

How do I view 'git diff' output with my preferred diff tool/ viewer?

Since Git1.6.3, you can use the git difftool script: see my answer below.


May be this article will help you. Here are the best parts:

There are two different ways to specify an external diff tool.

The first is the method you used, by setting the GIT_EXTERNAL_DIFF variable. However, the variable is supposed to point to the full path of the executable. Moreover, the executable specified by GIT_EXTERNAL_DIFF will be called with a fixed set of 7 arguments:

path old-file old-hex old-mode new-file new-hex new-mode

As most diff tools will require a different order (and only some) of the arguments, you will most likely have to specify a wrapper script instead, which in turn calls the real diff tool.

The second method, which I prefer, is to configure the external diff tool via "git config". Here is what I did:

1) Create a wrapper script "git-diff-wrapper.sh" which contains something like

-->8-(snip)--
#!/bin/sh

# diff is called by git with 7 parameters:
# path old-file old-hex old-mode new-file new-hex new-mode

"<path_to_diff_executable>" "$2" "$5" | cat
--8<-(snap)--

As you can see, only the second ("old-file") and fifth ("new-file") arguments will be passed to the diff tool.

2) Type

$ git config --global diff.external <path_to_wrapper_script>

at the command prompt, replacing with the path to "git-diff-wrapper.sh", so your ~/.gitconfig contains

-->8-(snip)--
[diff]
    external = <path_to_wrapper_script>
--8<-(snap)--

Be sure to use the correct syntax to specify the paths to the wrapper script and diff tool, i.e. use forward slashed instead of backslashes. In my case, I have

[diff]
    external = \"c:/Documents and Settings/sschuber/git-diff-wrapper.sh\"

in .gitconfig and

"d:/Program Files/Beyond Compare 3/BCompare.exe" "$2" "$5" | cat

in the wrapper script. Mind the trailing "cat"!

(I suppose the '| cat' is needed only for some programs which may not return a proper or consistent return status. You might want to try without the trailing cat if your diff tool has explicit return status)

(Diomidis Spinellis adds in the comments:

The cat command is required, because diff(1), by default exits with an error code if the files differ.
Git expects the external diff program to exit with an error code only if an actual error occurred, e.g. if it run out of memory.
By piping the output of git to cat the non-zero error code is masked.
More efficiently, the program could just run exit with and argument of 0.)


That (the article quoted above) is the theory for external tool defined through config file (not through environment variable).
In practice (still for config file definition of external tool), you can refer to:

How to call a method in another class of the same package?

By calling method

public class a 
{
    void sum(int i,int k)
    {
        System.out.println("THe sum of the number="+(i+k));
    }
}
class b
{
    public static void main(String[] args)
    {
        a vc=new a();
        vc.sum(10 , 20);
    }
}

X-Frame-Options Allow-From multiple domains

Not exactly the same, but could work for some cases: there is another option ALLOWALL which will effectively remove the restriction, which might be a nice thing for testing/pre-production environments

How to code a very simple login system with java

import java.util.Scanner;

public class LoginMain {

public static void main(String[] args) {

    String Username;
    String Password;

    Password = "123";
    Username = "wisdom";

    Scanner input1 = new Scanner(System.in);
    System.out.println("Enter Username : ");
    String username = input1.next();

    Scanner input2 = new Scanner(System.in);
    System.out.println("Enter Password : ");
    String password = input2.next();

    if (username.equals(Username) && password.equals(Password)) {

        System.out.println("Access Granted! Welcome!");
    }

    else if (username.equals(Username)) {
        System.out.println("Invalid Password!");
    } else if (password.equals(Password)) {
        System.out.println("Invalid Username!");
    } else {
        System.out.println("Invalid Username & Password!");
    }

Minimum and maximum date

From the spec, §15.9.1.1:

A Date object contains a Number indicating a particular instant in time to within a millisecond. Such a Number is called a time value. A time value may also be NaN, indicating that the Date object does not represent a specific instant of time.

Time is measured in ECMAScript in milliseconds since 01 January, 1970 UTC. In time values leap seconds are ignored. It is assumed that there are exactly 86,400,000 milliseconds per day. ECMAScript Number values can represent all integers from –9,007,199,254,740,992 to 9,007,199,254,740,992; this range suffices to measure times to millisecond precision for any instant that is within approximately 285,616 years, either forward or backward, from 01 January, 1970 UTC.

The actual range of times supported by ECMAScript Date objects is slightly smaller: exactly –100,000,000 days to 100,000,000 days measured relative to midnight at the beginning of 01 January, 1970 UTC. This gives a range of 8,640,000,000,000,000 milliseconds to either side of 01 January, 1970 UTC.

The exact moment of midnight at the beginning of 01 January, 1970 UTC is represented by the value +0.

The third paragraph being the most relevant. Based on that paragraph, we can get the precise earliest date per spec from new Date(-8640000000000000), which is Tuesday, April 20th, 271,821 BCE (BCE = Before Common Era, e.g., the year -271,821).

Unable to import path from django.urls

Create setting.json file in your project

{
       "python.pythonPath": "${workspaceFolder}/env/bin/python3",
       "editor.formatOnSave": true,
       "python.linting.pep8Enabled": true,
       "python.linting.pylintPath": "pylint",
       "python.linting.pylintArgs": ["--load-plugins", "pylint_django"],
       "python.linting.pylintEnabled": true,
       "python.venvPath": "${workspaceFolder}/env/bin/python3",
       "python.linting.pep8Args": ["--ignore=E501"],
       "files.exclude": {
           "**/*.pyc": true
       }
}

Sending POST data in Android

This is an example of how to POST multi-part data WITHOUT using external Apache libraries:

byte[] buffer = getBuffer();

if(buffer.length > 0) {
   String lineEnd = "\r\n"; 
   String twoHyphens = "--"; 
   String boundary =  "RQdzAAihJq7Xp1kjraqf"; 

   ByteArrayOutputStream baos = new ByteArrayOutputStream();
   DataOutputStream dos = new DataOutputStream(baos);

   // Send parameter #1
   dos.writeBytes(twoHyphens + boundary + lineEnd); 
   dos.writeBytes("Content-Disposition: form-data; name=\"param1\"" + lineEnd);
   dos.writeBytes("Content-Type: text/plain; charset=US-ASCII" + lineEnd);
   dos.writeBytes("Content-Transfer-Encoding: 8bit" + lineEnd);
   dos.writeBytes(lineEnd);
   dos.writeBytes(myStringData + lineEnd);

   // Send parameter #2
   //dos.writeBytes(twoHyphens + boundary + lineEnd); 
   //dos.writeBytes("Content-Disposition: form-data; name=\"param2\"" + lineEnd + lineEnd);
   //dos.writeBytes("foo2" + lineEnd);

   // Send a binary file
   dos.writeBytes(twoHyphens + boundary + lineEnd); 
   dos.writeBytes("Content-Disposition: form-data; name=\"param3\";filename=\"test_file.dat\"" + lineEnd); 
   dos.writeBytes("Content-Type: application/octet-stream" + lineEnd);
   dos.writeBytes("Content-Transfer-Encoding: binary" + lineEnd);
   dos.writeBytes(lineEnd); 
   dos.write(buffer);
   dos.writeBytes(lineEnd); 
   dos.writeBytes(twoHyphens + boundary + twoHyphens + lineEnd); 
   dos.flush(); 
   dos.close();

   ByteArrayInputStream content = new ByteArrayInputStream(baos.toByteArray());
   BasicHttpEntity entity = new BasicHttpEntity();
   entity.setContent(content);

   HttpPost httpPost = new HttpPost(myURL);
   httpPost.addHeader("Connection", "Keep-Alive");
   httpPost.addHeader("Content-Type", "multipart/form-data; boundary="+boundary);

   //MultipartEntity entity = new MultipartEntity();
   //entity.addPart("param3", new ByteArrayBody(buffer, "test_file.dat"));
   //entity.addPart("param1", new StringBody(myStringData));

   httpPost.setEntity(entity);

   /*
   String httpData = "";
   ByteArrayOutputStream baos1 = new ByteArrayOutputStream();
   entity.writeTo(baos1);
   httpData = baos1.toString("UTF-8");
   */

   /*
   Header[] hdrs = httpPost.getAllHeaders();
   for(Header hdr: hdrs) {
     httpData += hdr.getName() + " | " + hdr.getValue() + " |_| ";
   }
   */

   //Log.e(TAG, "httpPost data: " + httpData);
   response = httpClient.execute(httpPost);
}

How do I call paint event?

The Invalidate() Method will cause a repaint.

MSDN Link

Basic text editor in command prompt?

You can install vim/vi for windows and set windows PATH variable and open it in command line.

"NODE_ENV" is not recognized as an internal or external command, operable command or batch file

For those who uses Git Bash and having issues with npm run <script>,

Just set npm to use Git Bash to run scripts

npm config set script-shell "C:\\Program Files\\git\\bin\\bash.exe" (change the path according to your installation)

And then npm will run scripts with Git Bash, so such usages like NODE_ENV= will work properly.

How to deal with ModalDialog using selenium webdriver?

Nope, Model window needs to be handle by javaScriptExecutor,Because majorly model window made up of window model, This will works once model appeared then control take a place into model and click the expected element.

have to import javascriptexector

like below,

Javascriptexecutor js =(Javascriptexecutor).driver;
js.executescript(**<element to be clicked>**);

Convert string into Date type on Python

While it seems the question was answered per the OP's request, none of the answers give a good way to get a datetime.date object instead of a datetime.datetime. So for those searching and finding this thread:

datetime.date has no .strptime method; use the one on datetime.datetime instead and then call .date() on it to receive the datetime.date object.

Like so:

>>> from datetime import datetime
>>> datetime.strptime('2014-12-04', '%Y-%m-%d').date()
datetime.date(2014, 12, 4)

How to grep for contents after pattern?

Modern BASH has support for regular expressions:

while read -r line; do
  if [[ $line =~ ^potato:\ ([0-9]+) ]]; then
    echo "${BASH_REMATCH[1]}"
  fi
done

How to run Python script on terminal?

You need python installed on your system. Then you can run this in the terminal in the correct directory:

python gameover.py

Creating a custom JButton in Java

I'm probably going a million miles in the wrong direct (but i'm only young :P ). but couldn't you add the graphic to a panel and then a mouselistener to the graphic object so that when the user on the graphic your action is preformed.

How can I find an element by CSS class with XPath?

XPath has a contains-token function, specifically designed for this situation:

//div[contains-token(@class, 'Test')]

It's only supported in the latest version of XPath (3.1) so you'll need an up-to-date implementation.

What does the "@" symbol do in Powershell?

While the above responses provide most of the answer it is useful--even this late to the question--to provide the full answer, to wit:

Array sub-expression (see about_arrays)

Forces the value to be an array, even if a singleton or a null, e.g. $a = @(ps | where name -like 'foo')

Hash initializer (see about_hash_tables)

Initializes a hash table with key-value pairs, e.g. $HashArguments = @{ Path = "test.txt"; Destination = "test2.txt"; WhatIf = $true }

Splatting (see about_splatting)

Let's you invoke a cmdlet with parameters from an array or a hash-table rather than the more customary individually enumerated parameters, e.g. using the hash table just above, Copy-Item @HashArguments

Here strings (see about_quoting_rules)

Let's you create strings with easily embedded quotes, typically used for multi-line strings, e.g.:

$data = @"
line one
line two
something "quoted" here
"@

Because this type of question (what does 'x' notation mean in PowerShell?) is so common here on StackOverflow as well as in many reader comments, I put together a lexicon of PowerShell punctuation, just published on Simple-Talk.com. Read all about @ as well as % and # and $_ and ? and more at The Complete Guide to PowerShell Punctuation. Attached to the article is this wallchart that gives you everything on a single sheet: enter image description here

Django -- Template tag in {% if %} block

{% for source in sources %}
  <tr>
    <td>{{ source }}</td>
    <td>
      {% ifequal title source %}
        Just now!
      {% endifequal %}
    </td>
  </tr>
{% endfor %}

                or


{% for source in sources %}
      <tr>
        <td>{{ source }}</td>
        <td>
          {% if title == source %}
            Just now!
          {% endif %}
        </td>
      </tr>
    {% endfor %}

See Django Doc

Laravel Blade html image

as of now, you can use

<img src="{{ asset('images/foo.png') }}" alt="tag">

python numpy ValueError: operands could not be broadcast together with shapes

dot is matrix multiplication, but * does something else.

We have two arrays:

  • X, shape (97,2)
  • y, shape (2,1)

With Numpy arrays, the operation

X * y

is done element-wise, but one or both of the values can be expanded in one or more dimensions to make them compatible. This operation is called broadcasting. Dimensions, where size is 1 or which are missing, can be used in broadcasting.

In the example above the dimensions are incompatible, because:

97   2
 2   1

Here there are conflicting numbers in the first dimension (97 and 2). That is what the ValueError above is complaining about. The second dimension would be ok, as number 1 does not conflict with anything.

For more information on broadcasting rules: http://docs.scipy.org/doc/numpy/user/basics.broadcasting.html

(Please note that if X and y are of type numpy.matrix, then asterisk can be used as matrix multiplication. My recommendation is to keep away from numpy.matrix, it tends to complicate more than simplifying things.)

Your arrays should be fine with numpy.dot; if you get an error on numpy.dot, you must have some other bug. If the shapes are wrong for numpy.dot, you get a different exception:

ValueError: matrices are not aligned

If you still get this error, please post a minimal example of the problem. An example multiplication with arrays shaped like yours succeeds:

In [1]: import numpy

In [2]: numpy.dot(numpy.ones([97, 2]), numpy.ones([2, 1])).shape
Out[2]: (97, 1)

Fastest way to check a string contain another substring in JavaScript?

I've found that using a simple for loop, iterating over all elements in the string and comparing using charAt performs faster than indexOf or Regex. The code and proof is available at JSPerf.

ETA: indexOf and charAt both perform similarly terrible on Chrome Mobile according to Browser Scope data listed on jsperf.com

Use custom build output folder when using create-react-app

Based on the answers by Ben Carp and Wallace Sidhrée:

This is what I use to copy my entire build folder to my wamp public folder.

package.json

{
  "name": "[your project name]",
  "homepage": "http://localhost/[your project name]/",
  "version": "0.0.1",
  [...]
  "scripts": {
    "build": "react-scripts build",
    "postbuild": "@powershell -NoProfile -ExecutionPolicy Unrestricted -Command ./post_build.ps1",
    [...]
  },
}

post_build.ps1

Copy-Item "./build/*" -Destination "C:/wamp64/www/[your project name]" -Recurse -force

The homepage line is only needed if you are deploying to a subfolder on your server (See This answer from another question).

Asus Zenfone 5 not detected by computer

To enable USB Debugging first you need to enable Developer Options.

  1. Open Zenfone Settings and scroll down and tap About.

  2. Scroll down and select Software Information.

  3. Under Software information you will see Build Number.

  4. Tap Build Number 7 times to enable Developer Options.

  5. Come back to Settings and scroll down to find Developer Options.

  6. Tap on Developer Options and it will open upto give you option to enable USB Debugging

Difference between onCreate() and onStart()?

onCreate() method gets called when activity gets created, and its called only once in whole Activity life cycle. where as onStart() is called when activity is stopped... I mean it has gone to background and its onStop() method is called by the os. onStart() may be called multiple times in Activity life cycle.More details here

Get a resource using getResource()

TestGameTable.class.getResource("/unibo/lsb/res/dice.jpg");
  • leading slash to denote the root of the classpath
  • slashes instead of dots in the path
  • you can call getResource() directly on the class.

SSL InsecurePlatform error when using Requests package

Below is how it's working for me on Python 3.6:

import requests
import urllib3

# Suppress InsecureRequestWarning: Unverified HTTPS
urllib3.disable_warnings()

Facebook Post Link Image

Try using something like this:

<link rel="image_src" href="http://yoursite.com/graphics/yourimage.jpg" /link>`

Seems to work just fine on Firefox as long as you use a full path to your image.

Trouble is it get vertically offset downward for some reason. Image is 200 x 200 as recommended somewhere I read.

how do I initialize a float to its max/min value?

To manually find the minimum of an array you don't need to know the minimum value of float:

float myFloats[];
...
float minimum = myFloats[0];
for (int i = 0; i < myFloatsSize; ++i)
{
  if (myFloats[i] < minimum)
  {
    minimum = myFloats[i];
  }
}

And similar code for the maximum value.

.ssh directory not being created

Is there a step missing?

Yes. You need to create the directory:

mkdir ${HOME}/.ssh

Additionally, SSH requires you to set the permissions so that only you (the owner) can access anything in ~/.ssh:

% chmod 700 ~/.ssh

Should the .ssh dir be generated when I use the ssh-keygen command?

No. This command generates an SSH key pair but will fail if it cannot write to the required directory:

% ssh-keygen
Generating public/private rsa key pair.
Enter file in which to save the key (/Users/xxx/.ssh/id_rsa): /Users/tmp/does_not_exist
Enter passphrase (empty for no passphrase): 
Enter same passphrase again: 
open /Users/tmp/does_not_exist failed: No such file or directory.
Saving the key failed: /Users/tmp/does_not_exist.

Once you've created your keys, you should also restrict who can read those key files to just yourself:

% chmod -R go-wrx ~/.ssh/*

Return in Scala

Don't write if statements without a corresponding else. Once you add the else to your fragment you'll see that your true and false are in fact the last expressions of the function.

def balanceMain(elem: List[Char]): Boolean =
  {
    if (elem.isEmpty)
      if (count == 0)
        true
      else
        false
    else
      if (elem.head == '(')
        balanceMain(elem.tail, open, count + 1)
      else....

PostgreSQL delete with inner join

If you have more than one join you could use comma separated USING statements:

DELETE 
FROM 
      AAA AS a 
USING 
      BBB AS b,
      CCC AS c
WHERE 
      a.id = b.id 
  AND a.id = c.id
  AND a.uid = 12345 
  AND c.gid = 's434sd4'

Reference

Using C++ filestreams (fstream), how can you determine the size of a file?

You can seek until the end, then compute the difference:

std::streampos fileSize( const char* filePath ){

    std::streampos fsize = 0;
    std::ifstream file( filePath, std::ios::binary );

    fsize = file.tellg();
    file.seekg( 0, std::ios::end );
    fsize = file.tellg() - fsize;
    file.close();

    return fsize;
}

What is the difference between “int” and “uint” / “long” and “ulong”?

uint and ulong are the unsigned versions of int and long. That means they can't be negative. Instead they have a larger maximum value.

Type    Min                           Max                           CLS-compliant
int     -2,147,483,648                2,147,483,647                 Yes
uint    0                             4,294,967,295                 No
long    –9,223,372,036,854,775,808    9,223,372,036,854,775,807     Yes
ulong   0                             18,446,744,073,709,551,615    No

To write a literal unsigned int in your source code you can use the suffix u or U for example 123U.

You should not use uint and ulong in your public interface if you wish to be CLS-Compliant.

Read the documentation for more information:

By the way, there is also short and ushort and byte and sbyte.

What is a lambda (function)?

A lambda is a type of function, defined inline. Along with a lambda you also usually have some kind of variable type that can hold a reference to a function, lambda or otherwise.

For instance, here's a C# piece of code that doesn't use a lambda:

public Int32 Add(Int32 a, Int32 b)
{
    return a + b;
}

public Int32 Sub(Int32 a, Int32 b)
{
    return a - b;
}

public delegate Int32 Op(Int32 a, Int32 b);

public void Calculator(Int32 a, Int32 b, Op op)
{
    Console.WriteLine("Calculator: op(" + a + ", " + b + ") = " + op(a, b));
}

public void Test()
{
    Calculator(10, 23, Add);
    Calculator(10, 23, Sub);
}

This calls Calculator, passing along not just two numbers, but which method to call inside Calculator to obtain the results of the calculation.

In C# 2.0 we got anonymous methods, which shortens the above code to:

public delegate Int32 Op(Int32 a, Int32 b);

public void Calculator(Int32 a, Int32 b, Op op)
{
    Console.WriteLine("Calculator: op(" + a + ", " + b + ") = " + op(a, b));
}

public void Test()
{
    Calculator(10, 23, delegate(Int32 a, Int32 b)
    {
        return a + b;
    });
    Calculator(10, 23, delegate(Int32 a, Int32 b)
    {
        return a - b;
    });
}

And then in C# 3.0 we got lambdas which makes the code even shorter:

public delegate Int32 Op(Int32 a, Int32 b);

public void Calculator(Int32 a, Int32 b, Op op)
{
    Console.WriteLine("Calculator: op(" + a + ", " + b + ") = " + op(a, b));
}

public void Test()
{
    Calculator(10, 23, (a, b) => a + b);
    Calculator(10, 23, (a, b) => a - b);
}

Practical uses of different data structures

I am in the same boat as you do. I need to study for tech interviews, but memorizing a list is not really helpful. If you have 3-4 hours to spare, and want to do a deeper dive, I recommend checking out

mycodeschool
I’ve looked on Coursera and other resources such as blogs and textbooks, but I find them either not comprehensive enough or at the other end of the spectrum, too dense with prerequisite computer science terminologies.

The dude in the video have a bunch of lectures on data structures. Don’t mind the silly drawings, or the slight accent at all. You need to understand not just which data structure to select, but some other points to consider when people think about data structures:

  • pros and cons of the common data structures
  • why each data structure exist
  • how it actually work in the memory
  • specific questions/exercises and deciding which structure to use for maximum efficiency
  • lucid Big 0 explanation

I also posted notes on github if you are interested.

`require': no such file to load -- mkmf (LoadError)

You can use RVM(Ruby version manager) which helps in managing all versions of ruby on your machine , which is very helpful for you development (when migrating to unstable release to stable release )

or for Linux (ubuntu) go for sudo apt-get install ruby1.8-dev

then sudo gem install rails to verify it do rails -v it will show version on rails

after that you can install bundles (required gems for development)

Check variable equality against a list of values

You can write if(foo in L(10,20,30)) if you define L to be

var L = function()
{
    var obj = {};
    for(var i=0; i<arguments.length; i++)
        obj[arguments[i]] = null;

    return obj;
};

Cannot change version of project facet Dynamic Web Module to 3.0?

What worked for me:

  1. Change the Java to 1.8 (or 1.7)

In your POM - you have to set compiler plugin to version 1.8 (or 1.7) in <build> section:

  <build>
    ...
      <plugins>
        <plugin>
          <groupId>org.apache.maven.plugins</groupId>
          <artifactId>maven-compiler-plugin</artifactId>
          <version>3.6.0</version>
          <configuration>
            <source>1.8</source>
            <target>1.8</target>
          </configuration>
        </plugin>  
      </plugins>    
  </build>

Ensure that change Java Build shows 1.8. If it does not - click EDIT and select what it should be.

enter image description here

  1. Modify web.xml so 3.0 is referenced in version and in the link

enter image description here

  1. Ensure you have Java set to 1.8 in Project Facets

enter image description here

  1. At this stage I still could not change Dynamic Web Module;

Instead of changing it:

a) uncheck the Dynamic Web Module

b) apply

c) check it again. New version 3.0 should be set.**

enter image description here

After applying and checking it again:

enter image description here

Hope this helps.

How to view log output using docker-compose run?

Update July 1st 2019

docker-compose logs <name-of-service>

From the documentation:

Usage: logs [options] [SERVICE...]

Options:

--no-color Produce monochrome output.

-f, --follow Follow log output.

-t, --timestamps Show timestamps.

--tail="all" Number of lines to show from the end of the logs for each container.

See docker logs

You can start Docker compose in detached mode and attach yourself to the logs of all container later. If you're done watching logs you can detach yourself from the logs output without shutting down your services.

  1. Use docker-compose up -d to start all services in detached mode (-d) (you won't see any logs in detached mode)
  2. Use docker-compose logs -f -t to attach yourself to the logs of all running services, whereas -f means you follow the log output and the -t option gives you timestamps (See Docker reference)
  3. Use Ctrl + z or Ctrl + c to detach yourself from the log output without shutting down your running containers

If you're interested in logs of a single container you can use the docker keyword instead:

  1. Use docker logs -t -f <name-of-service>

Save the output

To save the output to a file you add the following to your logs command:

  1. docker-compose logs -f -t >> myDockerCompose.log

jquery .on() method with load event

I'm not sure what you're going for here--by the time jQuery(document).ready() has executed, it has already loaded, and thus document's load event will already have been called. Attaching the load event handler at this point will have no effect and it will never be called. If you're attempting to alert "started" once the document has loaded, just put it right in the (document).ready() call, like this:

jQuery(document).ready(function() {
    var x = $('#initial').html();
    $('#add').click(function() {
        $('body').append(x);
    });

    alert('started');

});?

If, as your code also appears to insinuate, you want to fire the alert when .abc has loaded, put it in an individual .load handler:

jQuery(document).ready(function() {
    var x = $('#initial').html();
    $('#add').click(function() {
        $('body').append(x);
    });

    $(".abc").on("load", function() {
        alert('started');
    }
});?

Finally, I see little point in using jQuery in one place and $ in another. It's generally better to keep your code consistent, and either use jQuery everywhere or $ everywhere, as the two are generally interchangeable.

For loop in Oracle SQL

You are pretty confused my friend. There are no LOOPS in SQL, only in PL/SQL. Here's a few examples based on existing Oracle table - copy/paste to see results:

-- Numeric FOR loop --
set serveroutput on -->> do not use in TOAD --
DECLARE
  k NUMBER:= 0;
BEGIN
  FOR i IN 1..10 LOOP
    k:= k+1;
    dbms_output.put_line(i||' '||k);
 END LOOP;
END;
/

-- Cursor FOR loop --
set serveroutput on
DECLARE
   CURSOR c1 IS SELECT * FROM scott.emp;
   i NUMBER:= 0;
BEGIN
  FOR e_rec IN c1 LOOP
  i:= i+1;
    dbms_output.put_line(i||chr(9)||e_rec.empno||chr(9)||e_rec.ename);
  END LOOP;
END;
/

-- SQL example to generate 10 rows --
SELECT 1 + LEVEL-1 idx
  FROM dual
CONNECT BY LEVEL <= 10
/

How do I get the current year using SQL on Oracle?

Using to_char:

select to_char(sysdate, 'YYYY') from dual;

In your example you can use something like:

BETWEEN trunc(sysdate, 'YEAR') 
    AND add_months(trunc(sysdate, 'YEAR'), 12)-1/24/60/60;

The comparison values are exactly what you request:

select trunc(sysdate, 'YEAR') begin_year
     , add_months(trunc(sysdate, 'YEAR'), 12)-1/24/60/60 last_second_year
from dual;

BEGIN_YEAR  LAST_SECOND_YEAR
----------- ----------------
01/01/2009  31/12/2009

How to get the GL library/headers?

Some of the answers above, in regards to linux, are either incomplete, or flat out wrong.

For example, /usr/include/GL/gl.h is not part of mesa-common-dev or has not been for many years.

At any rate, for a more current answer, these two packages are important:

https://mesa.freedesktop.org/archive/mesa-20.1.2.tar.xz

ftp://ftp.freedesktop.org/pub/mesa/glu/glu-9.0.1.tar.xz

The glu.h is part of glu itself:

GL/glu.h
GL/glu_mangle.h

Mesa is evidently significantly larger. Its headers are a bit variable, I suppose, depending on the flags given to meson, but should include these typically:

KHR/khrplatform.h                                                                                                         
EGL/eglplatform.h                                                                                                         
EGL/eglext.h                                                                                                              
EGL/eglextchromium.h                                                                                                      
EGL/eglmesaext.h                                                                                                          
EGL/egl.h                                                                                                                 
vulkan/vulkan_intel.h
gbm.h
GLES3/gl31.h
GLES3/gl3ext.h
GLES3/gl3.h
GLES3/gl32.h
GLES3/gl3platform.h
xa_composite.h
xa_tracker.h
xa_context.h
GLES2/gl2.h
GLES2/gl2platform.h
GLES2/gl2ext.h
GLES/gl.h
GLES/glplatform.h
GLES/glext.h
GLES/egl.h
GL/gl.h
GL/glx.h
GL/osmesa.h
GL/internal
GL/internal/dri_interface.h
GL/glcorearb.h
GL/glxext.h
GL/glext.h

Hope that helps anyone finding an answer this question in the future; compiling dosbox needs this, for instance, due to SDL opengl.

Combine Points with lines with ggplot2

A small change to Paul's code so that it doesn't return the error mentioned above.

dat = melt(subset(iris, select = c("Sepal.Length","Sepal.Width", "Species")),
           id.vars = "Species")
dat$x <- c(1:150, 1:150)
ggplot(aes(x = x, y = value, color = variable), data = dat) +  
  geom_point() + geom_line()

curl: (6) Could not resolve host: google.com; Name or service not known

Try nslookup google.com to determine if there's a DNS issue. 192.168.1.254 is your local network address and it looks like your system is using it as a DNS server. Is this your gateway/modem router as well? What happens when you try ping google.com. Can you browse to it on a Internet web browser?

How to refresh datagrid in WPF

I had a lot of trouble with this and this is what helped me get the DataGrid reloaded with the new values. Make sure you use the data type that your are getting the data from to get the latest data values.

I represented that with SomeDataType below.

DataContext.Refresh(RefreshMode.OverwriteCurrentValues, DataContext.SomeDataType);

Hope this helps someone with the same issues I had.

Connect to Oracle DB using sqlplus

As David Aldridge explained, your parentheses should start right after the sqlplus command, so it should be:

sqlplus 'test/test@(DESCRIPTION=(ADDRESS_LIST=(ADDRESS=(PROTOCOL=TCP)(HOST=hostname.com )(PORT=1521)))(CONNECT_DATA=(SID=mysid))'

How to remove the default arrow icon from a dropdown list (select element)?

You cannot do this with a fully functional cross browser support.

Try taking a div of 50 pixels suppose and float a desired drop-down icon of your choice at the right of this

Now within that div, add the select tag with a width of 55 pixels maybe (something more than the container's width)

I think you'll get what you want.

In case you do not want any drop icon at the right, just do all the steps except for floating the image at the right. Set outline:0 on focus for the select tag. that's it

How to add a href link in PHP?

Just do it in HTML

<a href="https://www.google.com">Google</a>

Are parameters in strings.xml possible?

There is many ways to use it and i recomend you to see this documentation about String Format.

http://developer.android.com/intl/pt-br/reference/java/util/Formatter.html

But, if you need only one variable, you'll need to use %[type] where [type] could be any Flag (see Flag types inside site above). (i.e. "My name is %s" or to set my name UPPERCASE, use this "My name is %S")

<string name="welcome_messages">Hello, %1$S! You have %2$d new message(s) and your quote is %3$.2f%%.</string>

Hello, ANDROID! You have 1 new message(s) and your quote is 80,50%.

Show data on mouseover of circle

There is an awesome library for doing that that I recently discovered. It's simple to use and the result is quite neat: d3-tip.

You can see an example here:

enter image description here

Basically, all you have to do is to download(index.js), include the script:

<script src="index.js"></script>

and then follow the instructions from here (same link as example)

But for your code, it would be something like:

define the method:

var tip = d3.tip()
  .attr('class', 'd3-tip')
  .offset([-10, 0])
  .html(function(d) {
    return "<strong>Frequency:</strong> <span style='color:red'>" + d.frequency + "</span>";
  })

create your svg (as you already do)

var svg = ...

call the method:

svg.call(tip);

add tip to your object:

vis.selectAll("circle")
   .data(datafiltered).enter().append("svg:circle")
...
   .on('mouseover', tip.show)
   .on('mouseout', tip.hide)

Don't forget to add the CSS:

<style>
.d3-tip {
  line-height: 1;
  font-weight: bold;
  padding: 12px;
  background: rgba(0, 0, 0, 0.8);
  color: #fff;
  border-radius: 2px;
}

/* Creates a small triangle extender for the tooltip */
.d3-tip:after {
  box-sizing: border-box;
  display: inline;
  font-size: 10px;
  width: 100%;
  line-height: 1;
  color: rgba(0, 0, 0, 0.8);
  content: "\25BC";
  position: absolute;
  text-align: center;
}

/* Style northward tooltips differently */
.d3-tip.n:after {
  margin: -1px 0 0 0;
  top: 100%;
  left: 0;
}
</style>

Catching nullpointerexception in Java

I think your problem is inside CheckCircular, in the while condition:

Assume you have 2 nodes, first N1 and N2 point to the same node, then N1 points to the second node (last) and N2 points to null (because it's N2.next.next). In the next loop, you try to call the 'next' method on N2, but N2 is null. There you have it, NullPointerException

Hot to get all form elements values using jQuery?

If you want to use $(formName).serializeArray() or $(formName).serialize(), you must add name='inputName' on your input element. or will not work!

Any way to Invoke a private method?

Use getDeclaredMethod() to get a private Method object and then use method.setAccessible() to allow to actually call it.

How to center horizontal table-cell

Just add this class in your css

.column p{
   text-align:center;
}

Detect if the app was launched/opened from a push notification

For Swift Users:

If you want to launch a different page on opening from push or something like that, you need to check it in didFinishLaunchingWithOptions like:

let directVc: directVC! = directVC(nibName:"directVC", bundle: nil)
let pushVc: pushVC! = pushVC(nibName:"pushVC", bundle: nil)

if let remoteNotification = launchOptions?[UIApplicationLaunchOptionsRemoteNotificationKey] as? NSDictionary {
     self.navigationController = UINavigationController(rootViewController: pushVc!)
} else {
     self.navigationController = UINavigationController(rootViewController: directVc!)
}
self.window!.rootViewController = self.navigationController

Find duplicate entries in a column

Try this query.. It uses the Analytic function SUM:

SELECT * FROM
(  
 SELECT SUM(1) OVER(PARTITION BY ctn_no) cnt, A.*
 FROM table1 a 
 WHERE s_ind ='Y'   
)
WHERE cnt > 2

Am not sure why you are identifying a record as a duplicate if the ctn_no repeats more than 2 times. FOr me it repeats more than once it is a duplicate. In this case change the las part of the query to WHERE cnt > 1

Laravel blank white screen

This changes works for my localhost Ubuntu server 14.xx setting

# Apply all permission to the laravel 5.x site folders     
$ sudo chmod -R 777 mysite

Also made changes on site-available httpd setting Apache2 settings

Add settings:

Options +Indexes +FollowSymLinks +MultiViews
Require all granted

Regular expression to match balanced parentheses

Regular expressions are the wrong tool for the job because you are dealing with nested structures, i.e. recursion.

But there is a simple algorithm to do this, which I described in this answer to a previous question.

How do I convert from BLOB to TEXT in MySQL?

None of these answers worked for me. When converting to UTF8, when the encoder encounters a set of bytes it can't convert to UTF8 it will result in a ? substitution which results in data loss. You need to use UTF16:

SELECT
    blobfield,
    CONVERT(blobfield USING utf16),
    CONVERT(CONVERT(blobfield USING utf16), BINARY),
    CAST(blobfield  AS CHAR(10000) CHARACTER SET utf16),
    CAST(CAST(blobfield  AS CHAR(10000) CHARACTER SET utf16) AS BINARY)

You can inspect the binary values in MySQL Workbench. Right click on the field -> Open Value in Viewer-> Binary. When converted back to BINARY the binary values should be the same as the original.

Alternatively, you can just use base-64 which was made for this purpose:

SELECT
    blobfield,
    TO_BASE64(blobfield),
    FROM_BASE64(TO_BASE64(blobfield))

import module from string variable

The __import__ function can be a bit hard to understand.

If you change

i = __import__('matplotlib.text')

to

i = __import__('matplotlib.text', fromlist=[''])

then i will refer to matplotlib.text.

In Python 2.7 and Python 3.1 or later, you can use importlib:

import importlib

i = importlib.import_module("matplotlib.text")

Some notes

  • If you're trying to import something from a sub-folder e.g. ./feature/email.py, the code will look like importlib.import_module("feature.email")

  • You can't import anything if there is no __init__.py in the folder with file you are trying to import

Repeat String - Javascript

This may be the smallest recursive one:-

String.prototype.repeat = function(n,s) {
s = s || ""
if(n>0) {
   s += this
   s = this.repeat(--n,s)
}
return s}

Swift: Display HTML data in a label or textView

Swift 3.0

var attrStr = try! NSAttributedString(
        data: "<b><i>text</i></b>".data(using: String.Encoding.unicode, allowLossyConversion: true)!,
        options: [ NSDocumentTypeDocumentAttribute: NSHTMLTextDocumentType],
        documentAttributes: nil)
label.attributedText = attrStr

Sass nth-child nesting

I'd be careful about trying to get too clever here. I think it's confusing as it is and using more advanced nth-child parameters will only make it more complicated. As for the background color I'd just set that to a variable.

Here goes what I came up with before I realized trying to be too clever might be a bad thing.

#romtest {
 $bg: #e5e5e5;
 .detailed {
    th {
      &:nth-child(-2n+6) {
        background-color: $bg;
      }
    }
    td {
      &:nth-child(3n), &:nth-child(2), &:nth-child(7) {
        background-color: $bg;
      }
      &.last {
        &:nth-child(-2n+4){
          background-color: $bg;
        }
      }
    }
  }
}

and here is a quick demo: http://codepen.io/anon/pen/BEImD

----EDIT----

Here's another approach to avoid retyping background-color:

#romtest {
  %highlight {
    background-color: #e5e5e5; 
  }
  .detailed {
    th {
      &:nth-child(-2n+6) {
        @extend %highlight;
      }
    }

    td {
      &:nth-child(3n), &:nth-child(2), &:nth-child(7) {
        @extend %highlight;
      }
      &.last {
        &:nth-child(-2n+4){
          @extend %highlight;
        }
      }
    }
  }
}

How to close an iframe within iframe itself

None of this solution worked for me since I'm in a cross-domain scenario creating a bookmarklet like Pinterest's Pin It.

I've found a bookmarklet template on GitHub https://gist.github.com/kn0ll/1020251 that solved the problem of closing the Iframe sending the command from within it.

Since I can't access any element from parent window within the IFrame, this communication can only be made posting events between the two windows using window.postMessage

All these steps are on the GitHub link:

1- You have to inject a JS file on the parent page.

2- In this file injected on the parent, add a window event listner

    window.addEventListener('message', function(e) {
       var someIframe = window.parent.document.getElementById('iframeid');
       someIframe.parentNode.removeChild(window.parent.document.getElementById('iframeid'));
    });

This listener will handle the close and any other event you wish

3- Inside the Iframe page you send the close command via postMessage:

   $(this).trigger('post-message', [{
                    event: 'unload-bookmarklet'
                }]);

Follow the template on https://gist.github.com/kn0ll/1020251 and you'll be fine!

Hope it helps,

org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject

JSONObject site=jsonSites.getJSONObject(i) should work out

How can I get a favicon to show up in my django app?

Universal solution

You can get the favicon showing up in Django the same way you can do in any other framework: just use pure HTML.

Add the following code to the header of your HTML template.
Better, to your base HTML template if the favicon is the same across your application.

<link rel="shortcut icon" href="{% static 'favicon/favicon.png' %}"/>

The previous code assumes:

  1. You have a folder named 'favicon' in your static folder
  2. The favicon file has the name 'favicon.png'
  3. You have properly set the setting variable STATIC_URL

You can find useful information about file format support and how to use favicons in this article of Wikipedia https://en.wikipedia.org/wiki/Favicon.
I can recommend use .png for universal browser compatibility.

EDIT:
As posted in one comment,
"Don't forget to add {% load staticfiles %} in top of your template file!"

Do we have router.reload in vue-router?

`<router-link :to='`/products`' @click.native="$router.go()" class="sub-link"></router-link>`

I have tried this for reloading current page.

WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()'

I had same problem and it solved by defining kotlin gradle plugin version in build.gradle file.

change this

 classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlin_version"

to

 classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:1.3.50{or latest version}"

Best way to Bulk Insert from a C# DataTable

Here's how I do it using a DataTable. This is a working piece of TEST code.

using (SqlConnection con = new SqlConnection(connStr))
{
    con.Open();

    // Create a table with some rows. 
    DataTable table = MakeTable();

    // Get a reference to a single row in the table. 
    DataRow[] rowArray = table.Select();

    using (SqlBulkCopy bulkCopy = new SqlBulkCopy(con))
    {
        bulkCopy.DestinationTableName = "dbo.CarlosBulkTestTable";

        try
        {
            // Write the array of rows to the destination.
            bulkCopy.WriteToServer(rowArray);
        }
        catch (Exception ex)
        {
            Console.WriteLine(ex.Message);
        }

    }

}//using

How to run PowerShell in CMD

You need to separate the arguments from the file path:

powershell.exe -noexit "& 'D:\Work\SQLExecutor.ps1 ' -gettedServerName 'MY-PC'"

Another option that may ease the syntax using the File parameter and positional parameters:

powershell.exe -noexit -file "D:\Work\SQLExecutor.ps1" "MY-PC"

OpenCV !_src.empty() in function 'cvtColor' error

If anyone is experiencing this same problem when reading a frame from a webcam [with code similar to "frame = cv2.VideoCapture(0)"] and work in Jupyter Notebook, you may try:

  1. ensure previously tried code is not running already and restart Jupyter Notebook kernel

  2. SEPARATE code "frame = cv2.VideoCapture(0)" in separate cell on place where it is [previous code put in cell above, code under put to cell down]

  3. then run all the code above cell where is "frame = cv2.VideoCapture(0)"

  4. then try run next cell with its only code "frame = cv2.VideoCapture(0)" - AND - till you will continue in executing other cells - ENSURE - that ASTERIX on the left side of this particular cell DISAPEAR and command order number appear instead - only then continue

  5. now you can try execute the rest of your code as your camera input should not be empty anymore :-)

  6. After end, ensure you close all your program and restart kernel to prepare it for another run

How do I change the font-size of an <option> element within <select>?

Like most form controls in HTML, the results of applying CSS to <select> and <option> elements vary a lot between browsers. Chrome, as you've found, won't let you apply and font styles to an <option> element directly --- if you do Inspect Element on it, you'll see the font-size: 14px declaration is crossed through as if it's been overridden by the cascade, but it's actually because Chrome is ignoring it.

However, Chrome will let you apply font styles to the <optgroup> element, so to achieve the result you want you can wrap all the <option>s in an <optgroup> and then apply your font styles to a .styled-select optgroup selector. If you want the optgroup sans-label, you may have to do some clever CSS with positioning or something to hide the white area at the top where the label would be shown, but that should be possible.

Forked to a new JSFiddle to show you what I mean:

http://jsfiddle.net/zRtbZ/

iOS 8 removed "minimal-ui" viewport property, are there other "soft fullscreen" solutions?

The minimal-ui viewport property is no longer supported in iOS 8. However, the minimal-ui itself is not gone. User can enter the minimal-ui with a "touch-drag down" gesture.

There are several pre-conditions and obstacles to manage the view state, e.g. for minimal-ui to work, there has to be enough content to enable user to scroll; for minimal-ui to persist, window scroll must be offset on page load and after orientation change. However, there is no way of calculating the dimensions of the minimal-ui using the screen variable, and thus no way of telling when user is in the minimal-ui in advance.

These observations is a result of research as part of developing Brim – view manager for iOS 8. The end implementation works in the following way:

When page is loaded, Brim will create a treadmill element. Treadmill element is used to give user space to scroll. Presence of the treadmill element ensures that user can enter the minimal-ui view and that it continues to persist if user reloads the page or changes device orientation. It is invisible to the user the entire time. This element has ID brim-treadmill.

Upon loading the page or after changing the orientation, Brim is using Scream to detect if page is in the minimal-ui view (page that has been previously in minimal-ui and has been reloaded will remain in the minimal-ui if content height is greater than the viewport height).

When page is in the minimal-ui, Brim will disable scrolling of the document (it does this in a safe way that does not affect the contents of the main element). Disabling document scrolling prevents accidentally leaving the minimal-ui when scrolling upwards. As per the original iOS 7.1 spec, tapping the top bar brings back the rest of the chrome.

The end result looks like this:

Brim in iOS simulator.

For the sake of documentation, and in case you prefer to write your own implementation, it is worth noting that you cannot use Scream to detect if device is in minimal-ui straight after the orientationchange event because window dimensions do not reflect the new orientation until the rotation animation has ended. You have to attach a listener to the orientationchangeend event.

Scream and orientationchangeend have been developed as part of this project.

How do I add a newline to a windows-forms TextBox?

Took this from JeffK and made it a little more compact.

Private Sub Form1_Load(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles MyBase.Load

    Dim Newline As String = System.Environment.NewLine

    TextBox1.Text = "This is a test"
    TextBox1.Text += Newline + "This is another test"

End Sub

Split a string by another string in C#

This is also easy:

string data = "THExxQUICKxxBROWNxxFOX";
string[] arr = data.Split("xx".ToCharArray(), StringSplitOptions.RemoveEmptyEntries);

What do the result codes in SVN mean?

Whenever you don't have access to documentation (SVNBook), type (Linux):

svn help status | grep \'\?\'
svn help status | grep \'\!\'
svn help status | grep \'\YOUR_SYMBOL_HERE\'

or insert the following function in your ~/.bashrc file, like so:

svncode() {
  symbol=$1
  [ $symbol ] &&  svn help status | grep \'$(echo $symbol)\' || \
  echo "usage: svncode <symbol>"
}

enter image description here

Using the value in a cell as a cell reference in a formula?

Use INDIRECT()

=SUM(INDIRECT(<start cell here> & ":" & <end cell here>))

How to convert a GUID to a string in C#?

Guid guidId = Guid.Parse("xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx");
string guidValue = guidId.ToString("D"); //return with hyphens

How to access random item in list?

Why not[2]:

public static T GetRandom<T>(this List<T> list)
{
     return list[(int)(DateTime.Now.Ticks%list.Count)];
}

TypeError: 'dict_keys' object does not support indexing

Convert an iterable to a list may have a cost. Instead, to get the the first item, you can use:

next(iter(keys))

Or, if you want to iterate over all items, you can use:

items = iter(keys)
while True:
    try:
        item = next(items)
    except StopIteration as e:
        pass # finish

How can I do an OrderBy with a dynamic string parameter?

Look at this blog here. It describes a way to do this, by defining an EntitySorter<T>.

It allows you to pass in an IEntitySorter<T> into your service methods and use it like this:

public static Person[] GetAllPersons(IEntitySorter<Person> sorter)
{
    using (var db = ContextFactory.CreateContext())
    {
        IOrderedQueryable<Person> sortedList = sorter.Sort(db.Persons);

        return sortedList.ToArray();
    }
}

And you can create an EntitiySorter like this:

IEntitySorter<Person> sorter = EntitySorter<Person>
    .OrderBy(p => p.Name)
    .ThenByDescending(p => p.Id);

Or like this:

var sorter = EntitySorter<Person>
     .OrderByDescending("Address.City")
     .ThenBy("Id");

Tools to search for strings inside files without indexing

If you don't want to install Non-Microsoft tools, please download STRINGS.EXE from Microsoft Sysinternals and make a procedure like this one:

@echo off
if '%1' == '' goto NOPARAM
if '%2' == '' goto NOPARAM
if not exist %1 goto NOFOLDER

echo ------------------------------------------
echo - %1 : folder
echo - %2 : string to be searched in the folder
echo - PLEASE WAIT FOR THE RESULTS ...
strings -s %1\* | findstr /i %2 > grep.txt
notepad.exe grep.txt

goto END

:NOPARAM rem - input command not correct
echo ====================================
echo Usage of GREP.CMD:
echo   Grep "SearchFolder" SearchString
echo Please specify all parameters
echo ====================================
goto END

:NOFOLDER
echo Folder %1 does not exist
goto END

:END rem - exit

What is the difference between readonly="true" & readonly="readonly"?

readonly="readonly" is xhtml syntax. In xhtml boolean attributes are written this way. In xhtml 'attribute minimization' (<input type="checkbox" checked>) isn't allowed, so this is the valid way to include boolean attributes in xhtml. See this page for more.information.

If your document type is xhtml transitional or strict and you want to validate it, use readonly="readonly otherwise readonly is sufficient.

How can I override inline styles with external CSS?

inline-styles in a document have the highest priority, so for example say if you want to change the color of a div element to blue, but you've an inline style with a color property set to red

<div style="font-size: 18px; color: red;">
   Hello World, How Can I Change The Color To Blue?
</div>
div {
   color: blue; 
   /* This Won't Work, As Inline Styles Have Color Red And As 
      Inline Styles Have Highest Priority, We Cannot Over Ride 
      The Color Using An Element Selector */
}

So, Should I Use jQuery/Javascript? - Answer Is NO

We can use element-attr CSS Selector with !important, note, !important is important here, else it won't over ride the inline styles..

<div style="font-size: 30px; color: red;">
    This is a test to see whether the inline styles can be over ridden with CSS?
</div>
div[style] {
   font-size: 12px !important;
   color: blue !important;
}

Demo

Note: Using !important ONLY will work here, but I've used div[style] selector to specifically select div having style attribute

How schedule build in Jenkins?

H H(5-21)/2 * * 1-5

MON-FRI build every 2 hour between

Cannot kill Python script with Ctrl-C

An improved version of @Thomas K's answer:

  • Defining an assistant function is_any_thread_alive() according to this gist, which can terminates the main() automatically.

Example codes:

import threading

def job1():
    ...

def job2():
    ...

def is_any_thread_alive(threads):
    return True in [t.is_alive() for t in threads]

if __name__ == "__main__":
    ...
    t1 = threading.Thread(target=job1,daemon=True)
    t2 = threading.Thread(target=job2,daemon=True)
    t1.start()
    t2.start()

    while is_any_thread_alive([t1,t2]):
        time.sleep(0)

How to add a touch event to a UIView?

Swift 3 & Swift 4

import UIKit

extension UIView {
  func addTapGesture(tapNumber: Int, target: Any, action: Selector) {
    let tap = UITapGestureRecognizer(target: target, action: action)
    tap.numberOfTapsRequired = tapNumber
    addGestureRecognizer(tap)
    isUserInteractionEnabled = true
  }
}

Use

yourView.addTapGesture(tapNumber: 1, target: self, action: #selector(yourMethod))

Best Practice: Access form elements by HTML id or name attribute?

To access named elements placed in a form, it is a good practice to use the form object itself.

To access an arbitrary element in the DOM tree that may on occasion be found within a form, use getElementById and the element's id.

Scroll Position of div with "overflow: auto"

You need to use the scrollTop property.

document.getElementById('box').scrollTop

What is lazy loading in Hibernate?

Say you have a parent and that parent has a collection of children. Hibernate now can "lazy-load" the children, which means that it does not actually load all the children when loading the parent. Instead, it loads them when requested to do so. You can either request this explicitly or, and this is far more common, hibernate will load them automatically when you try to access a child.

Lazy-loading can help improve the performance significantly since often you won't need the children and so they will not be loaded.

Also beware of the n+1-problem. Hibernate will not actually load all children when you access the collection. Instead, it will load each child individually. When iterating over the collection, this causes a query for every child. In order to avoid this, you can trick hibernate into loading all children simultaneously, e.g. by calling parent.getChildren().size().

How to check if a column is empty or null using SQL query select statement?

An answer above got me 99% of the way there (thanks Denis Ivin!). For my PHP / MySQL implementation, I needed to change the syntax a little:

SELECT *
FROM UserProfile
WHERE PropertydefinitionID in (40, 53)
AND (LENGTH(IFNULL(PropertyValue,'')) = 0)

LEN becomes LENGTH and ISNULL becomes IFNULL.

Regex Match all characters between two strings

This worked for me (I'm using VS Code):

for: This is just\na simple sentence

Use: This .+ sentence

Merging a lot of data.frames

Put them into a list and use merge with Reduce

Reduce(function(x, y) merge(x, y, all=TRUE), list(df1, df2, df3))
#    id v1 v2 v3
# 1   1  1 NA NA
# 2  10  4 NA NA
# 3   2  3  4 NA
# 4  43  5 NA NA
# 5  73  2 NA NA
# 6  23 NA  2  1
# 7  57 NA  3 NA
# 8  62 NA  5  2
# 9   7 NA  1 NA
# 10 96 NA  6 NA

You can also use this more concise version:

Reduce(function(...) merge(..., all=TRUE), list(df1, df2, df3))

Connecting to SQL Server using windows authentication

I was facing the same issue and the reason was single backslah. I used double backslash in my "Data source" and it worked

connetionString = "Data Source=localhost\\SQLEXPRESS;Database=databasename;Integrated Security=SSPI";

How to split a number into individual digits in c#?

You can simply do:

"123456".Select(q => new string(q,1)).ToArray();

to have an enumerable of integers, as per comment request, you can:

"123456".Select(q => int.Parse(new string(q,1))).ToArray();

It is a little weak since it assumes the string actually contains numbers.

How can I determine whether a specific file is open in Windows?

Use Process Explorer from the Sysinternals Suite, the Find Handle or DLL function will let you search for the process with that file open.

Number of elements in a javascript object

AFAIK, there is no way to do this reliably, unless you switch to an array. Which honestly, doesn't seem strange - it's seems pretty straight forward to me that arrays are countable, and objects aren't.

Probably the closest you'll get is something like this

// Monkey patching on purpose to make a point
Object.prototype.length = function()
{
  var i = 0;
  for ( var p in this ) i++;
  return i;
}

alert( {foo:"bar", bar: "baz"}.length() ); // alerts 3

But this creates problems, or at least questions. All user-created properties are counted, including the _length function itself! And while in this simple example you could avoid it by just using a normal function, that doesn't mean you can stop other scripts from doing this. so what do you do? Ignore function properties?

Object.prototype.length = function()
{
  var i = 0;
  for ( var p in this )
  {
      if ( 'function' == typeof this[p] ) continue;
      i++;
  }
  return i;
}

alert( {foo:"bar", bar: "baz"}.length() ); // alerts 2

In the end, I think you should probably ditch the idea of making your objects countable and figure out another way to do whatever it is you're doing.

Convert number to month name in PHP

Am currently using the solution below to tackle the same issue:

//set locale, 
setlocale(LC_ALL,"US");

//set the date to be converted
$date = '2016-08-07';

//convert date to month name
$month_name =  ucfirst(strftime("%B", strtotime($date)));

echo $month_name;

To read more about set locale go to http://php.net/manual/en/function.setlocale.php

To learn more about strftime go to http://php.net/manual/en/function.strftime.php

Ucfirst() is used to capitalize the first letter in a string.

MS Access - execute a saved query by name in VBA

Thre are 2 ways to run Action Query in MS Access VBA:


  1. You can use DoCmd.OpenQuery statement. This allows you to control these warnings:

Action Query Warning Example

BUT! Keep in mind that DoCmd.SetWarnings will remain set even after the function completes. This means that you need to make sure that you leave it in a condition that suits your needs

Function RunActionQuery(QueryName As String)
    On Error GoTo Hell              'Set Error Hanlder
    DoCmd.SetWarnings True          'Turn On Warnings
    DoCmd.OpenQuery QueryName       'Execute Action Query
    DoCmd.SetWarnings False         'Turn On Warnings
    Exit Function
Hell:
    If Err.Number = 2501 Then       'If Query Was Canceled
        MsgBox Err.Description, vbInformation
    Else                            'Everything else
        MsgBox Err.Description, vbCritical
    End If
End Function

  1. You can use CurrentDb.Execute method. This alows you to keep Action Query failures under control. The SetWarnings flag does not affect it. Query is executed always without warnings.
Function RunActionQuery()
    'To Catch the Query Error use dbFailOnError option
    On Error GoTo Hell
    CurrentDb.Execute "Query1", dbFailOnError
    Exit Function
Hell:
    Debug.Print Err.Description
End Function

It is worth noting that the dbFailOnError option responds only to data processing failures. If the Query contains an error (such as a typo), then a runtime error is generated, even if this option is not specified


In addition, you can use DoCmd.Hourglass True and DoCmd.Hourglass False to control the mouse pointer if your Query takes longer

Access denied for user 'homestead'@'localhost' (using password: YES)

After change .env with the new configuration, you have to stop the server and run it again (php artisan serve). Cause laravel gets the environment when it's initialized the server. If you don't restart, you will change the .env asking yourself why the changes aren't taking place!!

Cloning an Object in Node.js

You can use the extend function from JQuery:

var newClone= jQuery.extend({}, oldObject);  
var deepClone = jQuery.extend(true, {}, oldObject); 

There is a Node.js Plugin too:

https://github.com/shimondoodkin/nodejs-clone-extend

To do it without JQuery or Plugin read this here:

http://my.opera.com/GreyWyvern/blog/show.dml/1725165

automatically execute an Excel macro on a cell change

Handle the Worksheet_Change event or the Workbook_SheetChange event.

The event handlers take an argument "Target As Range", so you can check if the range that's changing includes the cell you're interested in.

INSERT INTO a temp table, and have an IDENTITY field created, without first declaring the temp table?

You could do a Select Into, which would create the table structure on the fly based on the fields you select, but I don't think it will create an identity field for you.