Programs & Examples On #Winforms to web

0

How to set fake GPS location on IOS real device

When running in debug mode you can use the little arrow button in the debug area (Shift+Cmd+Y) in Xcode to specify a location. There are some presets or you can also add a GPX file.

Specify debug location

You can generate GPX files here manually: http://www.bikehike.co.uk/mapview.php (from answer: https://stackoverflow.com/a/17478860/881197)

Array initialization in Perl

To produce the output in your comment to your post, this will do it:

use strict;
use warnings;

my @other_array = (0,0,0,1,2,2,3,3,3,4);
my @array;
my %uniqs;

$uniqs{$_}++ for @other_array;

foreach (keys %uniqs) { $array[$_]=$uniqs{$_} }

print "array[$_] = $array[$_]\n" for (0..$#array);

Output:

   array[0] = 3
   array[1] = 1
   array[2] = 2
   array[3] = 3
   array[4] = 1

This is different than your stated algorithm of producing a parallel array with zero values, but it is a more Perly way of doing it...

If you must have a parallel array that is the same size as your first array with the elements initialized to 0, this statement will dynamically do it: @array=(0) x scalar(@other_array); but really, you don't need to do that.

Cannot resolve symbol HttpGet,HttpClient,HttpResponce in Android Studio

That is just in SDK 23, Httpclient and others are deprecated. You can correct it by changing the target SDK version like below:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 22
    buildToolsVersion "22.0.1"

    defaultConfig {
        applicationId "vahid.hoseini.com.testclient"
        minSdkVersion 10
        targetSdkVersion 22
        versionCode 1
        versionName "1.0"
    }

    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android.txt'),    'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
    compile 'com.android.support:appcompat-v7:22.1.1'
}

Is it possible to ping a server from Javascript?

You can't directly "ping" in javascript. There may be a few other ways:

  • Ajax
  • Using a java applet with isReachable
  • Writing a serverside script which pings and using AJAX to communicate to your serversidescript
  • You might also be able to ping in flash (actionscript)

CSS "color" vs. "font-color"

The same way Boston came up with its street plan. They followed the cow paths already there, and built houses where the streets weren't, and after a while it was too much trouble to change.

Error:Failed to open zip file. Gradle's dependency cache may be corrupt

Android Studio 4.1.1 has this bug,

In gradle-wrapper.properties

distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-bin.zip

This won't download and always gives 'gradle cache corrupt' error, but a small change makes it work fine

distributionUrl=https\://services.gradle.org/distributions/gradle-6.5-all.zip

Now sync the gradle again and it's done.

How to access the GET parameters after "?" in Express?

The express manual says that you should use req.query to access the QueryString.

// Requesting /display/post?size=small
app.get('/display/post', function(req, res, next) {

  var isSmall = req.query.size === 'small'; // > true
  // ...

});

Why do we not have a virtual constructor in C++?

We do, it's just not a constructor :-)

struct A {
  virtual ~A() {}
  virtual A * Clone() { return new A; }
};

struct B : public A {
  virtual A * Clone() { return new B; }
};

int main() {

   A * a1 = new B;
   A * a2 = a1->Clone();    // virtual construction
   delete a2;
   delete a1;
}

Remove characters from C# string

Its a powerful method I usually use in the same case:

private string Normalize(string text)
{
        return string.Join("",
            from ch in text
            where char.IsLetterOrDigit(ch) || char.IsWhiteSpace(ch)
            select ch);
}

Enjoy...

Getting value of select (dropdown) before change

Use following code,I have tested it and its working

var prev_val;
$('.dropdown').focus(function() {
    prev_val = $(this).val();
}).change(function(){
            $(this).unbind('focus');
            var conf = confirm('Are you sure want to change status ?');

            if(conf == true){
                //your code
            }
            else{
                $(this).val(prev_val);
                $(this).bind('focus');
                return false;
            }
});

Does Java support default parameter values?

You may use Java Method Invocation Builder to automatically generate the builder with default values.

Just add @GenerateMethodInvocationBuilder to the class, or interface, and the @Default to parameters in methods where you want default values. A builder will be generated at compile time, using the default values that you specified with your annotations.

@GenerateMethodInvocationBuilder
public class CarService {
 public CarService() {
 }

 public String getCarsByFilter(//
   @Default("Color.BLUE") Color color, //
   @Default("new ProductionYear(2001)") ProductionYear productionYear,//
   @Default("Tomas") String owner//
 ) {
  return "Filtering... " + color + productionYear + owner;
 }
}

And then you can invoke the methods.

CarService instance = new CarService();
String carsByFilter = CarServiceGetCarsByFilterBuilder.getCarsByFilter()//
  .invoke(instance);

Or set any of the default values to something else.

CarService instance = new CarService();
String carsByFilter = CarServiceGetCarsByFilterBuilder.getCarsByFilter()//
  .withColor(Color.YELLOW)//
  .invoke(instance);

Android read text raw resource file

@borislemke you can do this by similar way like

TextView  tv ;
findViewById(R.id.idOfTextView);
tv.setText(readNewTxt());
private String readNewTxt(){
InputStream inputStream = getResources().openRawResource(R.raw.yourNewTextFile);
 ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();

 int i;
 try {
 i = inputStream.read();
while (i != -1)
  {
   byteArrayOutputStream.write(i);
   i = inputStream.read();
   }
    inputStream.close();
  } catch (IOException e) {
   // TODO Auto-generated catch block
 e.printStackTrace();
 }

 return byteArrayOutputStream.toString();
 }

Java using scanner enter key pressed

This works using java.util.Scanner and will take multiple "enter" keystrokes:

    Scanner scanner = new Scanner(System.in);
    String readString = scanner.nextLine();
    while(readString!=null) {
        System.out.println(readString);

        if (readString.isEmpty()) {
            System.out.println("Read Enter Key.");
        }

        if (scanner.hasNextLine()) {
            readString = scanner.nextLine();
        } else {
            readString = null;
        }
    }

To break it down:

Scanner scanner = new Scanner(System.in);
String readString = scanner.nextLine();

These lines initialize a new Scanner that is reading from the standard input stream (the keyboard) and reads a single line from it.

    while(readString!=null) {
        System.out.println(readString);

While the scanner is still returning non-null data, print each line to the screen.

        if (readString.isEmpty()) {
            System.out.println("Read Enter Key.");
        }

If the "enter" (or return, or whatever) key is supplied by the input, the nextLine() method will return an empty string; by checking to see if the string is empty, we can determine whether that key was pressed. Here the text Read Enter Key is printed, but you could perform whatever action you want here.

        if (scanner.hasNextLine()) {
            readString = scanner.nextLine();
        } else {
            readString = null;
        }

Finally, after printing the content and/or doing something when the "enter" key is pressed, we check to see if the scanner has another line; for the standard input stream, this method will "block" until either the stream is closed, the execution of the program ends, or further input is supplied.

Laravel 5 Eloquent where and or in Clauses

When we use multiple and (where) condition with last (where + or where) the where condition fails most of the time. for that we can use the nested where function with parameters passing in that.

$feedsql = DB::table('feeds as t1')
                   ->leftjoin('groups as t2', 't1.groups_id', '=', 't2.id')
                    ->where('t2.status', 1)
                    ->whereRaw("t1.published_on <= NOW()") 
                    >whereIn('t1.groupid', $group_ids)
                   ->where(function($q)use ($userid) {
                            $q->where('t2.contact_users_id', $userid)
                            ->orWhere('t1.users_id', $userid);
                     })
                  ->orderBy('t1.published_on', 'desc')->get();

The above query validate all where condition then finally checks where t2.status=1 and (where t2.contact_users_id='$userid' or where t1.users_id='$userid')

Difference between .dll and .exe?

This answer was a little more detailed than I thought but read it through.

DLL:
In most cases, a DLL file is a library. There are a couple of types of libraries, dynamic and static - read about the difference. DLL stands for dynamic link library which tells us that it's a part of the program but not the whole thing. It's made of reusable software components (library) which you could use for more than a single program. Bear in mind that it's always possible to use the library source code in many applications using copy-paste, but the idea of a DLL/Static Library is that you could update the code of a library and at the same time update all the applications using it - without compiling.

For example:
Imagine you're creating a Windows GUI component like a Button. In most cases you'd want to re-use the code you've written because it's a complex but a common component - You want many applications to use it but you don't want to give them the source code You can't copy-paste the code for the button in every program, so you decide you want to create a DL-Library (DLL).

This "button" library is required by EXEcutables to run, and without it they will not run because they don't know how to create the button, only how to talk to it.

Likewise, a DLL cannot be executed - run, because it's only a part of the program but doesn't have the information required to create a "process".

EXE:
An executable is the program. It knows how to create a process and how to talk to the DLL. It needs the DLL to create a button, and without it the application doesn't run - ERROR.

hope this helps....

Calculating distance between two points (Latitude, Longitude)

It looks like Microsoft invaded brains of all other respondents and made them write as complicated solutions as possible. Here is the simplest way without any additional functions/declare statements:

SELECT geography::Point(LATITUDE_1, LONGITUDE_1, 4326).STDistance(geography::Point(LATITUDE_2, LONGITUDE_2, 4326))

Simply substitute your data instead of LATITUDE_1, LONGITUDE_1, LATITUDE_2, LONGITUDE_2 e.g.:

SELECT geography::Point(53.429108, -2.500953, 4326).STDistance(geography::Point(c.Latitude, c.Longitude, 4326))
from coordinates c

ModuleNotFoundError: What does it mean __main__ is not a package?

The problem still not resolved after remove the '.', then it start points the error to my folder. As i added this folder first time then i restarted the PyCharm and it automatically resolved the issue

how to convert a string to a bool

I use this:

public static bool ToBoolean(this string input)
        {
            //Account for a string that does not need to be processed
            if (string.IsNullOrEmpty(input))
                return false;

            return (input.Trim().ToLower() == "true") || (input.Trim() == "1");
        }

JavaScript/jQuery - How to check if a string contain specific words

_x000D_
_x000D_
var str1 = "STACKOVERFLOW";_x000D_
var str2 = "OVER";_x000D_
if(str1.indexOf(str2) != -1){_x000D_
    console.log(str2 + " found");_x000D_
}
_x000D_
_x000D_
_x000D_

In DB2 Display a table's definition

I just came across this query to describe a table in winsql

select NAME,TBNAME,COLTYPE,LENGTH,REMARKS,SCALE from sysibm.syscolumns
where tbcreator = 'Schema_name' and tbname='Table_name' ;

How To Make Circle Custom Progress Bar in Android

I did a simple class which u can use to make custom ProgressBar dialog. Actually it has 2 default layouts: - First dialog with no panel with progress bar and animated text centered over it - Second normal dialog with panel, progress bar, title and msg

It is just a class, so not a customizable library which u can import in your project, so you need to copy it and change it how you want. It is a DialogFragment class, but you can use it inside an activity as a normal fragment just like you do with classic fragment by using FragmentManager.

Code of the dialog class:

public class ProgressBarDialog extends DialogFragment {

private static final String TAG = ProgressBarDialog.class.getSimpleName();
private static final String KEY = TAG.concat(".key");
// Argument Keys
private static final String KEY_DIALOG_TYPE = KEY.concat(".dialogType");
private static final String KEY_TITLE = KEY.concat(".title");
private static final String KEY_PROGRESS_TEXT = KEY.concat(".progressText");
private static final String KEY_CUSTOM_LAYOUT_BUILDER = KEY.concat(".customLayoutBuilder");
// Class Names
private static final String CLASS_GRADIENT_STATE = "GradientState";
// Field Names
private static final String FIELD_THICKNESS = "mThickness";
private static final String FIELD_INNER_RADIUS = "mInnerRadius";

/** Dialog Types **/
private static final int TYPE_PROGRESS_BAR_ONLY_NO_ANIM = 0x0;
private static final int TYPE_PROGRESS_BAR_ONLY_ROTATE_ANIM = 0x1;
private static final int TYPE_PROGRESS_BAR_ONLY_FADE_ANIM = 0x2;
private static final int TYPE_PROGRESS_BAR_AND_MSG = 0xF;

/** Animations Values **/
private static final long CENTER_TEXT_VIEWS_ANIMATION_DURATION = 250L;
private static final long CENTER_TEXT_VIEWS_START_OFFSET_MULTIPLIER = 250L;

private MaterialProgressBar mProgressBar;
private LinearLayout mllTextContainer;
private TextView mtvTitle;
private TextView mtvProgressText;

private List<TextView> mCenterTextViews;
private int mDialogType;
private String mTitle;
private String mProgressText;
private CustomLayoutBuilder mCustomLayoutBuilder;

/** Public Static Factory Methods **/
public static ProgressBarDialog initLayoutProgressBarOnlyNoAnim(String text, CustomLayoutBuilder builder){
    return initLayoutProgressBarOnly(TYPE_PROGRESS_BAR_ONLY_NO_ANIM, text, builder);
}

public static ProgressBarDialog initLayoutProgressBarOnlyRotateAnim(String text, CustomLayoutBuilder builder){
    return initLayoutProgressBarOnly(TYPE_PROGRESS_BAR_ONLY_ROTATE_ANIM, text, builder);
}

public static ProgressBarDialog initLayoutProgressBarOnlyFadeAnim(String text, CustomLayoutBuilder builder){
    return initLayoutProgressBarOnly(TYPE_PROGRESS_BAR_ONLY_FADE_ANIM, text, builder);
}

public static ProgressBarDialog initLayoutProgressBarAndMsg(String title, String text, CustomLayoutBuilder builder){
    ProgressBarDialog mInstance = new ProgressBarDialog();
    Bundle args = new Bundle();
    args.putInt(KEY_DIALOG_TYPE, TYPE_PROGRESS_BAR_AND_MSG);
    args.putString(KEY_TITLE, title);
    args.putString(KEY_PROGRESS_TEXT, text);
    args.putParcelable(KEY_CUSTOM_LAYOUT_BUILDER, builder);
    mInstance.setArguments(args);
    return mInstance;
}

/** Private Static Factory Methods **/
private static ProgressBarDialog initLayoutProgressBarOnly(int animation, String text, CustomLayoutBuilder builder){
    ProgressBarDialog mInstance = new ProgressBarDialog();
    Bundle args = new Bundle();
    args.putInt(KEY_DIALOG_TYPE, animation);
    args.putString(KEY_PROGRESS_TEXT, text);
    args.putParcelable(KEY_CUSTOM_LAYOUT_BUILDER, builder);
    mInstance.setArguments(args);
    return mInstance;
}

/** Override Lifecycle Methods **/
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    initData();
}

@Override @Nullable
public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
    super.onCreateView(inflater, container, savedInstanceState);
    View view = inflater.inflate(R.layout.dialog_progress_bar, container, false);
    initViews(view);
    if(getContext() != null && mCustomLayoutBuilder != null) {
        mProgressBar.setIndeterminateDrawable(getResources().getDrawable(mCustomLayoutBuilder.getLayoutResID()));
        initShapes();
    }
    return view;
}

private void initShapes(){
    if(mProgressBar.getIndeterminateDrawable() instanceof LayerDrawable) {
        LayerDrawable layerDrawable = (LayerDrawable) mProgressBar.getIndeterminateDrawable();
        for (int i = 0; i < layerDrawable.getNumberOfLayers(); i++) {
            if(layerDrawable.getDrawable(i) instanceof RotateDrawable) {
                RotateDrawable rotateDrawable = (RotateDrawable) layerDrawable.getDrawable(i);
                int[] fromToDeg = mCustomLayoutBuilder.getDegreesMatrixRow(i);
                if(fromToDeg.length > 0){
                    rotateDrawable.setFromDegrees(fromToDeg[CustomLayoutBuilder.INDEX_FROM_DEGREES]);
                    rotateDrawable.setToDegrees(fromToDeg[CustomLayoutBuilder.INDEX_TO_DEGREES]);
                }
                if(rotateDrawable.getDrawable() instanceof GradientDrawable){
                    GradientDrawable gradientDrawable = (GradientDrawable) rotateDrawable.getDrawable();
                    int innerRadius = getResources().getDimensionPixelSize(mCustomLayoutBuilder.getInnerRadius(i));
                    if(mDialogType == TYPE_PROGRESS_BAR_AND_MSG){
                        innerRadius /= 3;
                    }
                    int thickness = getResources().getDimensionPixelSize(mCustomLayoutBuilder.getThickness(i));
                    int[] colors = mCustomLayoutBuilder.getColorsMatrixRow(i);
                    if(colors.length > 0x0){
                        gradientDrawable.setColors(DataUtils.resourcesIDsToColors(this.getContext(), colors));
                    }
                    if(innerRadius != -0x1){
                        DataUtils.setSubClassFieldIntValue(gradientDrawable.getConstantState(), gradientDrawable.getClass(), CLASS_GRADIENT_STATE, FIELD_INNER_RADIUS, innerRadius);
                    }
                    if(thickness != -0x1){
                        DataUtils.setSubClassFieldIntValue(gradientDrawable.getConstantState(), gradientDrawable.getClass(), CLASS_GRADIENT_STATE, FIELD_THICKNESS, thickness);
                    }
                }
            }
        }
    }
}

@Override
public void onStart() {
    super.onStart();
    setWindowSize();
    startAnimation();
}

/** Public Methods **/
public void changeTextViews(String progressText){
    mProgressText = progressText;
    initTextViews();
    startAnimation();
}

public String getProgressText(){
    return mProgressText;
}

/** Private Methods **//** Init Methods **/
private void initData(){
    if(getArguments() != null) {
        if (getArguments().containsKey(KEY_DIALOG_TYPE)) {
            mDialogType = getArguments().getInt(KEY_DIALOG_TYPE);
        }
        if(getArguments().containsKey(KEY_TITLE)){
            mTitle = getArguments().getString(KEY_TITLE);
        }
        if (getArguments().containsKey(KEY_PROGRESS_TEXT)) {
            mProgressText = getArguments().getString(KEY_PROGRESS_TEXT);
        }
        if (getArguments().containsKey(KEY_CUSTOM_LAYOUT_BUILDER)){
            mCustomLayoutBuilder = getArguments().getParcelable(KEY_CUSTOM_LAYOUT_BUILDER);
        }
    }
    mCenterTextViews = new ArrayList<>();
}

private void initViews(View layout){
    if(layout != null){
        switch(mDialogType){
            case TYPE_PROGRESS_BAR_ONLY_NO_ANIM:
            case TYPE_PROGRESS_BAR_ONLY_ROTATE_ANIM:
            case TYPE_PROGRESS_BAR_ONLY_FADE_ANIM:
                if(getDialog() != null && getDialog().getWindow() != null) {
                    getDialog().getWindow().setBackgroundDrawableResource(android.R.color.transparent);
                }
                LinearLayout mLayoutProgressBarOnly = layout.findViewById(R.id.layout_progress_bar_only);
                mLayoutProgressBarOnly.setVisibility(LinearLayout.VISIBLE);
                mProgressBar = layout.findViewById(R.id.dpb_progress_bar);
                if(mCustomLayoutBuilder.getProgressBarWidthDimen() != -0x1){
                    ConstraintLayout.LayoutParams lp = (ConstraintLayout.LayoutParams) mProgressBar.getLayoutParams();
                    lp.width = getResources().getDimensionPixelSize(mCustomLayoutBuilder.getProgressBarWidthDimen());
                    lp.height = getResources().getDimensionPixelSize(mCustomLayoutBuilder.getProgressBarHeightDimen());
                    mProgressBar.setLayoutParams(lp);
                }
                mllTextContainer = layout.findViewById(R.id.dpb_text_container);
                initTextViews();
                break;
            case TYPE_PROGRESS_BAR_AND_MSG:
                LinearLayout mLayoutProgressBarAndMsg = layout.findViewById(R.id.layout_progress_bar_and_msg);
                mLayoutProgressBarAndMsg.setVisibility(LinearLayout.VISIBLE);
                mProgressBar = layout.findViewById(R.id.dpb_progress_bar_and_msg);
                mtvTitle = layout.findViewById(R.id.pbd_title);
                mtvProgressText = layout.findViewById(R.id.dpb_progress_msg);
                initProgressMsg();
                break;
        }
    }
}

private void initTextViews(){
    if(!TextUtils.isEmpty(mProgressText)){
        clearTextContainer();
        for(char digit : mProgressText.toCharArray()){
            TextView tv = new TextView(getContext(), null, 0x0, R.style.PBDCenterTextStyleWhite);
            if(mCustomLayoutBuilder.getProgressMsgColor() != CustomLayoutBuilder.DEFAULT_COLOR && getContext() != null){
                tv.setTextColor(ActivityCompat.getColor(getContext(), mCustomLayoutBuilder.getProgressMsgColor()));
            }
            if(mCustomLayoutBuilder.getProgressMsgDimen() != CustomLayoutBuilder.DEFAULT_DIMEN){
                tv.setTextSize(getResources().getDimension(mCustomLayoutBuilder.getProgressMsgDimen()));
            }
            tv.setText(String.valueOf(digit));
            mCenterTextViews.add(tv);
            mllTextContainer.addView(tv);
        }
    }
}

private void initProgressMsg(){
    mtvTitle.setText(mTitle);
    mtvProgressText.setText(mProgressText);
    if(mCustomLayoutBuilder.getProgressMsgColor() != CustomLayoutBuilder.DEFAULT_COLOR){
        mtvProgressText.setTextColor(mCustomLayoutBuilder.getProgressMsgColor());
    }
    if(mCustomLayoutBuilder.getProgressMsgDimen() != CustomLayoutBuilder.DEFAULT_DIMEN){
        mtvProgressText.setTextSize(getResources().getDimension(mCustomLayoutBuilder.getProgressMsgDimen()));
    }
}

private void clearTextContainer(){
    if(mllTextContainer.getChildCount() >= 0x0){
        for(int i=0; i < mllTextContainer.getChildCount(); i++){
            View v = mllTextContainer.getChildAt(i);
            if(v instanceof TextView){
                TextView tv = (TextView) v;
                if(tv.getAnimation() != null){
                    tv.clearAnimation();
                }
            }
        }
    }
    mllTextContainer.removeAllViews();
}

private void setWindowSize(){
    Dialog dialog = getDialog();
    if(dialog != null && dialog.getWindow() != null){
        int width = 0x0, height = 0x0;
        switch(mDialogType){
            case TYPE_PROGRESS_BAR_ONLY_NO_ANIM:
            case TYPE_PROGRESS_BAR_ONLY_ROTATE_ANIM:
            case TYPE_PROGRESS_BAR_ONLY_FADE_ANIM:
                width = ViewGroup.LayoutParams.WRAP_CONTENT;        //getResources().getDimensionPixelSize(R.dimen.pbd_window_width);
                height = ViewGroup.LayoutParams.WRAP_CONTENT;       //getResources().getDimensionPixelSize(R.dimen.pbd_window_height);
                break;
            case TYPE_PROGRESS_BAR_AND_MSG:
                width = ViewGroup.LayoutParams.MATCH_PARENT;
                height = ViewGroup.LayoutParams.WRAP_CONTENT;       //getResources().getDimensionPixelSize(R.dimen.pbd_textual_window_height);
                break;
        }
        dialog.getWindow().setLayout(width, height);
    }
}

/** Animation Methods **/
private void startAnimation(){
    switch(mDialogType){
        case TYPE_PROGRESS_BAR_ONLY_ROTATE_ANIM:
        startRotateAnimations();
        break;
        case TYPE_PROGRESS_BAR_ONLY_FADE_ANIM:
        startFadeInAnimations();
        break;
    }
}

private void startRotateAnimations(){
    for(TextView tv : mCenterTextViews){
        if(tv != null && tv.getText() != null && !TextUtils.isEmpty(tv.getText().toString().trim())) {
            int i = mCenterTextViews.indexOf(tv);
            RotateAnimation anim = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
            anim.setDuration(CENTER_TEXT_VIEWS_ANIMATION_DURATION);
            anim.setFillAfter(true);
            anim.setStartOffset(CENTER_TEXT_VIEWS_START_OFFSET_MULTIPLIER * i);
            if (i == (mCenterTextViews.size() - 0x1)) {
                anim.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        startRotateAnimations();
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
            }
            tv.startAnimation(anim);
        }
    }
}

private void startFadeInAnimations(){
    for(TextView tv : mCenterTextViews){
        if(tv != null && tv.getText() != null && !TextUtils.isEmpty(tv.getText().toString().trim())) {
            int i = mCenterTextViews.indexOf(tv);
            AlphaAnimation anim = new AlphaAnimation(0x1, 0x0);
            anim.setDuration(CENTER_TEXT_VIEWS_ANIMATION_DURATION);
            anim.setFillAfter(true);
            anim.setStartOffset(CENTER_TEXT_VIEWS_START_OFFSET_MULTIPLIER * i);
            if (i == (mCenterTextViews.size() - 0x1)) {
                anim.setAnimationListener(new Animation.AnimationListener() {
                    @Override
                    public void onAnimationStart(Animation animation) {

                    }

                    @Override
                    public void onAnimationEnd(Animation animation) {
                        startFadeOutAnimations();
                    }

                    @Override
                    public void onAnimationRepeat(Animation animation) {

                    }
                });
            }
            tv.startAnimation(anim);
        }
    }
}

private void startFadeOutAnimations(){
    for(TextView tv : mCenterTextViews){
        int i = mCenterTextViews.indexOf(tv);
        AlphaAnimation anim = new AlphaAnimation(0x0, 0x1);
        anim.setDuration(CENTER_TEXT_VIEWS_ANIMATION_DURATION);
        anim.setFillAfter(true);
        anim.setStartOffset(CENTER_TEXT_VIEWS_START_OFFSET_MULTIPLIER * i);
        if(i == (mCenterTextViews.size() - 0x1)){
            anim.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart(Animation animation) {

                }

                @Override
                public void onAnimationEnd(Animation animation) {
                    startFadeInAnimations();
                }

                @Override
                public void onAnimationRepeat(Animation animation) {

                }
            });
        }
        tv.startAnimation(anim);
    }
}

/** Progress Bar Custom Layout Builder Class **/
public static class CustomLayoutBuilder implements Parcelable {

    /** Shapes **/
    private static final int RING = GradientDrawable.RING;

    /** Colors **/
    private static final int[][] COLORS_MATRIX_RYGB = new int[][]{
        new int[]{ R.color.transparent, R.color.transparent, R.color.material_red_A700 },
        new int[]{ R.color.transparent, R.color.transparent, R.color.material_amber_A700 },
        new int[]{ R.color.transparent, R.color.transparent, R.color.material_light_green_A700 },
        new int[]{ R.color.transparent, R.color.transparent, R.color.material_blue_A700 }
    };
    private static final int DEFAULT_COLOR = -0x1;

    /** Dimens **/
    private static final int DEFAULT_DIMEN = -0x1;
    private static final int[] DEFAULT_PROGRESS_BAR_DIMEN = new int[]{};

    /** Indexes **/
    private static final int INDEX_PROGRESS_BAR_WIDTH = 0x0;
    private static final int INDEX_PROGRESS_BAR_HEIGHT = 0x1;
    private static final int INDEX_FROM_DEGREES = 0x0;
    private static final int INDEX_TO_DEGREES = 0x1;

    /** Arrays Sizes **/
    private static final int SIZE_PROGRESS_BAR_DIMENS_ARRAY = 0x2;

    /** Matrix Columns Number **/
    private static final int NUM_COLUMNS_DEGREES_MATRIX = 0x2;      /* Degrees Matrix Index                     ->  degrees[3]  =   { fromDegrees, toDegrees } */
    private static final int NUM_COLUMNS_COLORS_MATRIX = 0x3;       /* GradientDrawable Colors Matrix Index     ->  colors[3]   =   { startColor, centerColor, endColor } */

    /** Drawables Layout Resource IDs **/
    private static final int LAYOUT_RES_PROGRESS_BAR_RINGS = R.drawable.progress_bar_rings;

    /** Layout Data: Four Rings Overlaid **/
    private static final int RINGS_OVERLAID_LAYERS = 0x4;
    private static final int[][] RINGS_OVERLAID_DEGREES = new int[][]{ new int[]{ 300, 660 }, new int[]{ 210, 570 }, new int[]{ 120, 480 }, new int[]{ 30, 390 } };
    private static final int[] RINGS_OVERLAID_SHAPES = new int[]{ RING, RING, RING, RING };
    private static final int[] RINGS_OVERLAID_INNER_RADIUS = new int[]{ R.dimen.pbd_inner_radius_60dp, R.dimen.pbd_inner_radius_60dp, R.dimen.pbd_inner_radius_60dp, R.dimen.pbd_inner_radius_60dp};
    private static final int[] RINGS_OVERLAID_THICKNESS = new int[]{ R.dimen.pbd_thickness_40dp, R.dimen.pbd_thickness_30dp, R.dimen.pbd_thickness_20dp, R.dimen.pbd_thickness_10dp };

    /** Layout Data: Four Rings Spaced **/
    private static final int RINGS_SPACED_LAYERS = 0x4;
    private static final int[][] RINGS_SPACED_DEGREES = new int[][]{ new int[]{ 180, 540 }, new int[]{ 0, 360 }, new int[]{ 90, 450 }, new int[]{ 270, 630 } };
    private static final int[] RINGS_SPACED_SHAPES = new int[]{ RING, RING, RING, RING };
    private static final int[] RINGS_SPACED_INNER_RADIUS = new int[]{ R.dimen.pbd_inner_radius_30dp, R.dimen.pbd_inner_radius_60dp, R.dimen.pbd_inner_radius_90dp, R.dimen.pbd_inner_radius_120dp };
    private static final int[] RINGS_SPACED_THICKNESS = new int[]{ R.dimen.pbd_thickness_10dp, R.dimen.pbd_thickness_15dp, R.dimen.pbd_thickness_20dp, R.dimen.pbd_thickness_25dp };

    private int mLayoutResID;
    private int[] mProgressBarDimens;
    private int mNumLayers;
    private int[][] mRotateDegrees;
    private int[] mShapes;
    private int[] mInnerRadius;
    private int[] mThickness;
    private int[][] mColors;
    private int mProgressMsgColor;
    private int mProgressMsgDimen;

    public static Parcelable.Creator CREATOR = new CreatorCustomLayoutBuilder();

    /** Constructors **/
    private CustomLayoutBuilder(int layoutResID, int[] progressBarDimens, int numLayers, int[][] degreesMatrix, int[] shapes, int[] innerRadius, int[] thickness,
                                int[][] colorsMatrix, int msgColor, int progressMsgDimen){
        mLayoutResID = layoutResID;
        mProgressBarDimens = progressBarDimens;
        mNumLayers = numLayers;
        mRotateDegrees = degreesMatrix;
        mShapes = shapes;
        mInnerRadius = innerRadius;
        mThickness = thickness;
        mColors = colorsMatrix;
        mProgressMsgColor = msgColor;
        mProgressMsgDimen = progressMsgDimen;
    }

    private CustomLayoutBuilder(Parcel in){
        mLayoutResID = in.readInt();
        mProgressBarDimens = new int[SIZE_PROGRESS_BAR_DIMENS_ARRAY];
        in.readIntArray(mProgressBarDimens);
        mNumLayers = in.readInt();
        int[] tempArray = new int[NUM_COLUMNS_DEGREES_MATRIX * mNumLayers];
        in.readIntArray(tempArray);
        mRotateDegrees = DataUtils.arrayToMatrix(tempArray, NUM_COLUMNS_DEGREES_MATRIX);
        mShapes = new int[mNumLayers];
        in.readIntArray(mShapes);
        mInnerRadius = new int[mNumLayers];
        in.readIntArray(mInnerRadius);
        mThickness = new int[mNumLayers];
        in.readIntArray(mThickness);
        tempArray = new int[NUM_COLUMNS_COLORS_MATRIX * mNumLayers];
        in.readIntArray(tempArray);
        mColors = DataUtils.arrayToMatrix(tempArray, NUM_COLUMNS_COLORS_MATRIX);
        mProgressMsgColor = in.readInt();
        mProgressMsgDimen = in.readInt();
    }

    /** Public Static Factory Methods **/
    public static CustomLayoutBuilder initLayoutRingsOverlaid(){
        return new CustomLayoutBuilder(LAYOUT_RES_PROGRESS_BAR_RINGS, DEFAULT_PROGRESS_BAR_DIMEN, RINGS_OVERLAID_LAYERS, RINGS_OVERLAID_DEGREES, RINGS_OVERLAID_SHAPES,
                RINGS_OVERLAID_INNER_RADIUS, RINGS_OVERLAID_THICKNESS, COLORS_MATRIX_RYGB, R.color.material_white, DEFAULT_DIMEN);
    }

    public static CustomLayoutBuilder initLayoutRingsOverlaid(int[] resProgBarDimens, int resProgMsgColor, int resProgMsgDimen){
        return new CustomLayoutBuilder(LAYOUT_RES_PROGRESS_BAR_RINGS, resProgBarDimens, RINGS_OVERLAID_LAYERS, RINGS_OVERLAID_DEGREES, RINGS_OVERLAID_SHAPES,
                RINGS_OVERLAID_INNER_RADIUS, RINGS_OVERLAID_THICKNESS, COLORS_MATRIX_RYGB, resProgMsgColor, resProgMsgDimen);
    }

    public static CustomLayoutBuilder initLayoutRingsSpaced(){
        return new CustomLayoutBuilder(LAYOUT_RES_PROGRESS_BAR_RINGS, DEFAULT_PROGRESS_BAR_DIMEN, RINGS_SPACED_LAYERS, RINGS_SPACED_DEGREES, RINGS_SPACED_SHAPES,
                RINGS_SPACED_INNER_RADIUS, RINGS_SPACED_THICKNESS, COLORS_MATRIX_RYGB, DEFAULT_COLOR, DEFAULT_DIMEN);
    }

    /** Override Parcelable Methods **/
    @Override
    public int describeContents() {
        return 0;
    }

    @Override
    public void writeToParcel(Parcel out, int flags) {
        out.writeInt(mLayoutResID);
        out.writeIntArray(mProgressBarDimens);
        out.writeInt(mNumLayers);
        out.writeIntArray(DataUtils.matrixToArray(mRotateDegrees));
        out.writeIntArray(mShapes);
        out.writeIntArray(mInnerRadius);
        out.writeIntArray(mThickness);
        out.writeIntArray(DataUtils.matrixToArray(mColors));
        out.writeInt(mProgressMsgColor);
        out.writeInt(mProgressMsgDimen);
    }

    /** Getter & Setter Methods **/
    private int getLayoutResID() {
        return mLayoutResID;
    }

    private void setLayoutResID(int layoutResID) {
        this.mLayoutResID = layoutResID;
    }

    private int[] getProgressBarDimens() {
        return mProgressBarDimens;
    }

    private void setProgressBarDimens(int[] progressBarDimens) {
        this.mProgressBarDimens = progressBarDimens;
    }

    private int getProgressBarWidthDimen(){         // Used to check if 'mProgressBarDimens' array is set.
        if(mProgressBarDimens != null && mProgressBarDimens.length == SIZE_PROGRESS_BAR_DIMENS_ARRAY){
            return mProgressBarDimens[INDEX_PROGRESS_BAR_WIDTH];
        } else {
            return -0x1;
        }
    }

    private int getProgressBarHeightDimen(){
        return mProgressBarDimens[INDEX_PROGRESS_BAR_HEIGHT];
    }

    private int getNumLayers() {
        return mNumLayers;
    }

    private void setNumLayers(int numLayers) {
        this.mNumLayers = numLayers;
    }

    private int[][] getRotateDegrees() {
        return mRotateDegrees;
    }

    private void setRotateDegrees(int[][] rotateDegrees) {
        this.mRotateDegrees = rotateDegrees;
    }

    private int[] getShapes() {
        return mShapes;
    }

    private void setShapes(int[] shapes) {
        this.mShapes = shapes;
    }

    private int[] getInnerRadius() {
        return mInnerRadius;
    }

    private void setInnerRadius(int[] innerRadius) {
        this.mInnerRadius = innerRadius;
    }

    private int[] getThickness() {
        return mThickness;
    }

    private void setThickness(int[] thickness) {
        this.mThickness = thickness;
    }

    private int[][] getColorsMatrix() {
        return mColors;
    }

    private void setColorsMatrix(int[][] colorsMatrix) {
        this.mColors = colorsMatrix;
    }

    private int getProgressMsgColor() {
        return mProgressMsgColor;
    }

    private void setProgressMsgColor(int progressMsgColor) {
        this.mProgressMsgColor = progressMsgColor;
    }

    private int getProgressMsgDimen() {
        return mProgressMsgDimen;
    }

    private void setProgressMsgDimen(int progressMsgDimen) {
        this.mProgressMsgDimen = progressMsgDimen;
    }

    /** Public Methods **/
    private int[] getDegreesMatrixRow(int numRow){
        if(mRotateDegrees != null && mRotateDegrees.length > numRow) {
            return mRotateDegrees[numRow];
        } else {
            return new int[]{};
        }
    }

    private int getShape(int position){
        if(mShapes != null && mShapes.length > position){
            return mShapes[position];
        } else {
            return -0x1;
        }
    }

    private int getInnerRadius(int position){
        if(mInnerRadius != null && mInnerRadius.length > position){
            return mInnerRadius[position];
        } else {
            return -0x1;
        }
    }

    private int getThickness(int position){
        if(mThickness != null && mThickness.length > position){
            return mThickness[position];
        } else {
            return -0x1;
        }
    }

    private int[] getColorsMatrixRow(int numRow) {
        if(mColors != null && mColors.length > numRow){
            return mColors[numRow];
        } else {
            return new int[]{};
        }
    }

    /** Private Static Class Parcelable Creator **/
    private static class CreatorCustomLayoutBuilder implements Parcelable.Creator<CustomLayoutBuilder> {

        @Override
        public CustomLayoutBuilder createFromParcel(Parcel in) {
            return new CustomLayoutBuilder(in);
        }

        @Override
        public CustomLayoutBuilder[] newArray(int size) {
            return new CustomLayoutBuilder[size];
        }

    }

}
}
  • The class has a progress bar with no dialog and custom text over it. The text can have 2 animations:

  • Fade In -> Fade Out animation: digits will fade out like a sequentially from left to right. At end of text will restart from left.

  • Rotate Animation: same sequential behavior but the digits rotate on themself one by one instead of fading out.

  • Other way is a Progress Bar with a dialog (Title + Message)

Rotation Animation

Dialog Progress Bar

fatal: This operation must be run in a work tree

You repository is bare, i.e. it does not have a working tree attached to it. You can clone it locally to create a working tree for it, or you could use one of several other options to tell Git where the working tree is, e.g. the --work-tree option for single commands, or the GIT_WORK_TREE environment variable. There is also the core.worktree configuration option but it will not work in a bare repository (check the man page for what it does).

# git --work-tree=/path/to/work/tree checkout master
# GIT_WORK_TREE=/path/to/work/tree git status

How to install wget in macOS?

For macOS Sierra, to build wget 1.18 from source with Xcode 8.2.

  1. Install Xcode

  2. Build OpenSSL

    Since Xcode doesn't come with OpenSSL lib, you need build by yourself. I found this: https://github.com/sqlcipher/openssl-xcode, follow instruction and build OpenSSL lib. Then, prepare your OpenSSL directory with "include" and "lib/libcrypto.a", "lib/libssl.a" in it.

    Let's say it is: "/Users/xxx/openssl-xcode/openssl", so there should be "/Users/xxx/openssl-xcode/openssl/include" for OpenSSL include and "/Users/xxx/openssl-xcode/openssl/lib" for "libcrypto.a" and "libssl.a".

  3. Build wget

    Go to wget directory, configure:

    ./configure --with-ssl=openssl --with-libssl-prefix=/Users/xxx/openssl-xcode/openssl
    

    wget should configure and found OpenSSL, then make:

    make
    

    wget made out. Install wget:

    make install
    

    Or just copy wget to where you want.

  4. Configure cert

    You may find wget cannot verify any https connection, because there is no CA certs for the OpenSSL you built. You need to run:

    New way:

    If you machine doesn't have "/usr/local/ssl/" dir, first make it.

    ln -s /etc/ssl/cert.pem /usr/local/ssl/cert.pem
    

    Old way:

    security find-certificate -a -p /Library/Keychains/System.keychain > cert.pem
    security find-certificate -a -p /System/Library/Keychains/SystemRootCertificates.keychain >> cert.pem
    

    Then put cert.pem to: "/usr/local/ssl/cert.pem"

    DONE: It should be all right now.

"TypeError: (Integer) is not JSON serializable" when serializing JSON in Python?

This might be the late response, but recently i got the same error. After lot of surfing this solution helped me.

alerts = {'upper':[1425],'lower':[576],'level':[2],'datetime':['2012-08-08 15:30']}
def myconverter(obj):
        if isinstance(obj, np.integer):
            return int(obj)
        elif isinstance(obj, np.floating):
            return float(obj)
        elif isinstance(obj, np.ndarray):
            return obj.tolist()
        elif isinstance(obj, datetime.datetime):
            return obj.__str__()

Call myconverter in json.dumps() like below. json.dumps(alerts, default=myconverter).

Sending Windows key using SendKeys

download InputSimulator from nuget package.

then write this:

        var simu = new InputSimulator();
        simu.Keyboard.ModifiedKeyStroke(VirtualKeyCode.LWIN, VirtualKeyCode.VK_E);

in my case to create new vertial desktop, 3 keys needed and code like this(windows key + ctrl + D):

        simu.Keyboard.ModifiedKeyStroke(new[] { VirtualKeyCode.LWIN, VirtualKeyCode.CONTROL }, VirtualKeyCode.VK_D);

Redirecting from HTTP to HTTPS with PHP

Redirecting from HTTP to HTTPS with PHP on IIS

I was having trouble getting redirection to HTTPS to work on a Windows server which runs version 6 of MS Internet Information Services (IIS). I’m more used to working with Apache on a Linux host so I turned to the Internet for help and this was the highest ranking Stack Overflow question when I searched for “php redirect http to https”. However, the selected answer didn’t work for me.

After some trial and error, I discovered that with IIS, $_SERVER['HTTPS'] is set to off for non-TLS connections. I thought the following code should help any other IIS users who come to this question via search engine.

<?php
if (! isset($_SERVER['HTTPS']) or $_SERVER['HTTPS'] == 'off' ) {
    $redirect_url = "https://" . $_SERVER['HTTP_HOST'] . $_SERVER['REQUEST_URI'];
    header("Location: $redirect_url");
    exit();
}
?>

Edit: From another Stack Overflow answer, a simpler solution is to check if($_SERVER["HTTPS"] != "on").

Using if elif fi in shell scripts

sh is interpreting the && as a shell operator. Change it to -a, that’s [’s conjunction operator:

[ "$arg1" = "$arg2" -a "$arg1" != "$arg3" ]

Also, you should always quote the variables, because [ gets confused when you leave off arguments.

JPA getSingleResult() or null

I've done (in Java 8):

query.getResultList().stream().findFirst().orElse(null);

How to add multiple files to Git at the same time

step1.

git init

step2.

a) for all files

git add -a

b) only specific folder

git add <folder1> <folder2> <etc.>

step3.

git commit -m "Your message about the commit"

step4.

enter image description here

git remote add origin https://github.com/yourUsername/yourRepository.git

step5.

git push -u origin master
git push origin master

if you are face this error than

 ! [rejected]        master -> master (fetch first)
error: failed to push some refs to 'https://github.com/harishkumawat2610/Qt5-with-C-plus-plus.git'
hint: Updates were rejected because the remote contains work that you do
hint: not have locally. This is usually caused by another repository pushing
hint: to the same ref. You may want to first integrate the remote changes
hint: (e.g., 'git pull ...') before pushing again.
hint: See the 'Note about fast-forwards' in 'git push --help' for details.

Use this command

git push --force origin master

How do I truly reset every setting in Visual Studio 2012?

Executing the command: Devenv.exe /ResetSettings like :

C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE>devenv.exe /ResetSettings , resolved my issue :D

For more: https://msdn.microsoft.com/en-us/library/ms241273.aspx

ADB Install Fails With INSTALL_FAILED_TEST_ONLY

Add -t install flag, as on the screenshot below:

answer is in the red box

Why does integer division in C# return an integer and not a float?

The result will always be of type that has the greater range of the numerator and the denominator. The exceptions are byte and short, which produce int (Int32).

var a = (byte)5 / (byte)2;  // 2 (Int32)
var b = (short)5 / (byte)2; // 2 (Int32)
var c = 5 / 2;              // 2 (Int32)
var d = 5 / 2U;             // 2 (UInt32)
var e = 5L / 2U;            // 2 (Int64)
var f = 5L / 2UL;           // 2 (UInt64)
var g = 5F / 2UL;           // 2.5 (Single/float)
var h = 5F / 2D;            // 2.5 (Double)
var i = 5.0 / 2F;           // 2.5 (Double)
var j = 5M / 2;             // 2.5 (Decimal)
var k = 5M / 2F;            // Not allowed

There is no implicit conversion between floating-point types and the decimal type, so division between them is not allowed. You have to explicitly cast and decide which one you want (Decimal has more precision and a smaller range compared to floating-point types).

How to do an INNER JOIN on multiple columns

You can JOIN with the same table more than once by giving the joined tables an alias, as in the following example:

SELECT 
    airline, flt_no, fairport, tairport, depart, arrive, fare
FROM 
    flights
INNER JOIN 
    airports from_port ON (from_port.code = flights.fairport)
INNER JOIN
    airports to_port ON (to_port.code = flights.tairport)
WHERE 
    from_port.code = '?' OR to_port.code = '?' OR airports.city='?'

Note that the to_port and from_port are aliases for the first and second copies of the airports table.

Eclipse : Failed to connect to remote VM. Connection refused.

Which server are you using?

Like already said:

  1. In your debug configuration you'll have to define the right port of your server (GF:9009 / Tomcat:8000)
  2. You'll have to set the JVM property of the server to debug

For Glassfish:

    Log in to admin-console > Configurations > server-config > JVM-Settings > check DEBUG checkbox > restart server

For Tomcat:

create file debug.bat/.sh (depending on your OS) in %TOMCAT_HOME%/bin directory and write

    set JPDA_ADDRESS=8000
    set JPDA_TRANSPORT=dt_socket
    catalina.bat jpda start

in it.

After you've created this file start server by executing debug.bat/.sh.

Now you should be able to debug remotely in Eclipse after you set the necessary properties in your debug configuration.

Hope this helped! Have Fun!

EDIT

If you're running tomcat in a Win environment as a service you don't have a catalina.bat file in the bin-directory of your tomcat installation.
To set your server into debug-mode please try the following:

  1. Run the Configuration option in Windows Menu or run %catalina_home%/bin/tomcat6w.exe
  2. In Java tab, add this line to Java:

options:-Xrunjdwp:transport=dt_socket,address=8000,server=y,suspend=n

Converting from a string to boolean in Python?

The usual rule for casting to a bool is that a few special literals (False, 0, 0.0, (), [], {}) are false and then everything else is true, so I recommend the following:

def boolify(val):
    if (isinstance(val, basestring) and bool(val)):
        return not val in ('False', '0', '0.0')
    else:
        return bool(val)

How do I get the RootViewController from a pushed controller?

For all who are interested in a swift extension, this is what I'm using now:

extension UINavigationController {
    var rootViewController : UIViewController? {
        return self.viewControllers.first
    }
}

Allow all remote connections, MySQL

As pointed out by Ryan above, the command you need is

GRANT ALL ON *.* to user@'%' IDENTIFIED BY 'password'; 

However, note that the documentation indicates that in order for this to work, another user account from localhost must be created for the same user; otherwise, the anonymous account created automatically by mysql_install_db takes precedence because it has a more specific host column.

In other words; in order for user user to be able to connect from any server; 2 accounts need to be created as follows:

GRANT ALL ON *.* to user@localhost IDENTIFIED BY 'password'; 
GRANT ALL ON *.* to user@'%' IDENTIFIED BY 'password'; 

Read the full documentation here.

And here's the relevant piece for reference:

After connecting to the server as root, you can add new accounts. The following statements use GRANT to set up four new accounts:

mysql> CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost'
    ->     WITH GRANT OPTION;
mysql> CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
mysql> GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%'
    ->     WITH GRANT OPTION;
mysql> CREATE USER 'admin'@'localhost';
mysql> GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
mysql> CREATE USER 'dummy'@'localhost';

The accounts created by these statements have the following properties:

Two of the accounts have a user name of monty and a password of some_pass. Both accounts are superuser accounts with full privileges to do anything. The 'monty'@'localhost' account can be used only when connecting from the local host. The 'monty'@'%' account uses the '%' wildcard for the host part, so it can be used to connect from any host.

It is necessary to have both accounts for monty to be able to connect from anywhere as monty. Without the localhost account, the anonymous-user account for localhost that is created by mysql_install_db would take precedence when monty connects from the local host. As a result, monty would be treated as an anonymous user. The reason for this is that the anonymous-user account has a more specific Host column value than the 'monty'@'%' account and thus comes earlier in the user table sort order. (user table sorting is discussed in Section 6.2.4, “Access Control, Stage 1: Connection Verification”.)

How can I check if mysql is installed on ubuntu?

"mysql" may be found even if mysql and mariadb is uninstalled, but not "mysqld".

Faster than rpm -qa | grep mysqld is:

which mysqld

Regular expression for excluding special characters

The negated set of everything that is not alphanumeric & underscore for ASCII chars:

/[^\W]/g

For email or username validation i've used the following expression that allows 4 standard special characters - _ . @

/^[-.@_a-z0-9]+$/gi

For a strict alphanumeric only expression use:

/^[a-z0-9]+$/gi

Test @ RegExr.com

Reset the database (purge all), then seed a database

on Rails 6 you can now do something like

rake db:seed:replant This Truncates tables of each database for current environment and loads the seeds

https://blog.saeloun.com/2019/09/30/rails-6-adds-db-seed-replant-task-and-db-truncate_all.html

$ rails db:seed:replant --trace
** Invoke db:seed:replant (first_time)
** Invoke db:load_config (first_time)
** Invoke environment (first_time)
** Execute environment
** Execute db:load_config
** Invoke db:truncate_all (first_time)
** Invoke db:load_config
** Invoke db:check_protected_environments (first_time)
** Invoke db:load_config
** Execute db:check_protected_environments
** Execute db:truncate_all
** Invoke db:seed (first_time)
** Invoke db:load_config
** Execute db:seed
** Invoke db:abort_if_pending_migrations (first_time)
** Invoke db:load_config
** Execute db:abort_if_pending_migrations
** Execute db:seed:replant

ORDER BY date and time BEFORE GROUP BY name in mysql

This is not the exact answer, but this might be helpful for the people looking to solve some problem with the approach of ordering row before group by in mysql.

I came to this thread, when I wanted to find the latest row(which is order by date desc but get the only one result for a particular column type, which is group by column name).

One other approach to solve such problem is to make use of aggregation.

So, we can let the query run as usual, which sorted asc and introduce new field as max(doc) as latest_doc, which will give the latest date, with grouped by the same column.

Suppose, you want to find the data of a particular column now and max aggregation cannot be done. In general, to finding the data of a particular column, you can make use of GROUP_CONCAT aggregator, with some unique separator which can't be present in that column, like GROUP_CONCAT(string SEPARATOR ' ') as new_column, and while you're accessing it, you can split/explode the new_column field.

Again, this might not sound to everyone. I did it, and liked it as well because I had written few functions and I couldn't run subqueries. I am working on codeigniter framework for php.

Not sure of the complexity as well, may be someone can put some light on that.

Regards :)

Count characters in textarea

this worked fine for me.

$('#customText').on('keyup', function(event) {
   var len = $(this).val().length;
   if (len >= 40) {
      $(this).val($(this).val().substring(0, len-1));
   }
});

How to check if a row exists in MySQL? (i.e. check if an email exists in MySQL)

There are multiple ways to check if a value exists in the database. Let me demonstrate how this can be done properly with PDO and mysqli.

PDO

PDO is the simpler option. To find out whether a value exists in the database you can use prepared statement and fetchColumn(). There is no need to fetch any data so we will only fetch 1 if the value exists.

<?php

// Connection code. 
$options = [
    \PDO::ATTR_ERRMODE            => \PDO::ERRMODE_EXCEPTION,
    \PDO::ATTR_EMULATE_PREPARES   => false,
];
$pdo = new \PDO('mysql:host=localhost;port=3306;dbname=test;charset=utf8mb4', 'testuser', 'password', $options);

// Prepared statement
$stmt = $pdo->prepare('SELECT 1 FROM tblUser WHERE email=?');
$stmt->execute([$_POST['email']]);
$exists = $stmt->fetchColumn(); // either 1 or null

if ($exists) {
    echo 'Email exists in the database.';
} else {
    // email doesn't exist yet
}

For more examples see: How to check if email exists in the database?

MySQLi

As always mysqli is a little more cumbersome and more restricted, but we can follow a similar approach with prepared statement.

<?php

// Connection code
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$mysqli = new \mysqli('localhost', 'testuser', 'password', 'test');
$mysqli->set_charset('utf8mb4');

// Prepared statement
$stmt = $mysqli->prepare('SELECT 1 FROM tblUser WHERE email=?');
$stmt->bind_param('s', $_POST['email']);
$stmt->execute();
$exists = (bool) $stmt->get_result()->fetch_row(); // Get the first row from result and cast to boolean

if ($exists) {
    echo 'Email exists in the database.';
} else {
    // email doesn't exist yet
}

Instead of casting the result row(which might not even exist) to boolean, you can also fetch COUNT(1) and read the first item from the first row using fetch_row()[0]

For more examples see: How to check whether a value exists in a database using mysqli prepared statements

Minor remarks

  • If someone suggests you to use mysqli_num_rows(), don't listen to them. This is a very bad approach and could lead to performance issues if misused.
  • Don't use real_escape_string(). This is not meant to be used as a protection against SQL injection. If you use prepared statements correctly you don't need to worry about any escaping.
  • If you want to check if a row exists in the database before you try to insert a new one, then it is better not to use this approach. It is better to create a unique key in the database and let it throw an exception if a duplicate value exists.

Check synchronously if file/directory exists in Node.js

Another Update

Needing an answer to this question myself I looked up the node docs, seems you should not be using fs.exists, instead use fs.open and use outputted error to detect if a file does not exist:

from the docs:

fs.exists() is an anachronism and exists only for historical reasons. There should almost never be a reason to use it in your own code.

In particular, checking if a file exists before opening it is an anti-pattern that leaves you vulnerable to race conditions: another process may remove the file between the calls to fs.exists() and fs.open(). Just open the file and handle the error when it's not there.

http://nodejs.org/api/fs.html#fs_fs_exists_path_callback

How to split page into 4 equal parts?

Demo at http://jsfiddle.net/CRSVU/

_x000D_
_x000D_
html,
body {
  height: 100%;
  padding: 0;
  margin: 0;
}

div {
  width: 50%;
  height: 50%;
  float: left;
}

#div1 {
  background: #DDD;
}

#div2 {
  background: #AAA;
}

#div3 {
  background: #777;
}

#div4 {
  background: #444;
}
_x000D_
<div id="div1"></div>
<div id="div2"></div>
<div id="div3"></div>
<div id="div4"></div>
_x000D_
_x000D_
_x000D_

Parsing domain from a URL

function getTrimmedUrl($link)
{
    $str = str_replace(["www.","https://","http://"],[''],$link);
    $link = explode("/",$str);
    return strtolower($link[0]);                
}

How to set top position using jquery

You can use CSS to do the trick:

$("#yourElement").css({ top: '100px' });

How to make String.Contains case insensitive?

bool b = list.Contains("Hello", StringComparer.CurrentCultureIgnoreCase);

[EDIT] extension code:

public static bool Contains(this string source, string cont
                                                    , StringComparison compare)
{
    return source.IndexOf(cont, compare) >= 0;
}

This could work :)

Why my $.ajax showing "preflight is invalid redirect error"?

This answer goes over the exact same thing (although for angular) -- it is a CORS issue.

One quick fix is to modify each POST request by specifying one of the 'Content-Type' header values which will not trigger a "preflight". These types are:

  • application/x-www-form-urlencoded
  • multipart/form-data
  • text/plain

ANYTHING ELSE triggers a preflight.

For example:

$.ajax({
   url: 'http://api.example.com/users/get',
   type: 'POST',
   headers: {
      'name-api-key':'ewf45r4435trge',
      'Content-Type':'application/x-www-form-urlencoded'
   },
   data: {
      'uid':36,
   },
   success: function(data) {
      console.log(data);
   }
});

Authentication plugin 'caching_sha2_password' cannot be loaded

You can change the encryption of the user's password by altering the user with below Alter command :

ALTER USER 'username'@'ip_address' IDENTIFIED WITH mysql_native_password BY 'password';

OR

We can avoid this error by make it work with old password plugin:

First change the authentication plugin in my.cnf file for Linux / my.ini file in Windows:

[mysqld]

default_authentication_plugin=mysql_native_password

Restart the mysql server to take the changes in affect and try connecting via MySQL with any mysql client.

If still unable to connect and getting the below error:

Unable to load plugin 'caching_sha2_password'

It means your user needs the above plugin. So try creating new user with create user or grant command after changing default plugin. then new user need the native plugin and you will able to connect MySQL.

Thanks

How does RewriteBase work in .htaccess

RewriteBase is only useful in situations where you can only put a .htaccess at the root of your site. Otherwise, you may be better off placing your different .htaccess files in different directories of your site and completely omitting the RewriteBase directive.

Lately, for complex sites, I've been taking them out, because it makes deploying files from testing to live just one more step complicated.

How can I define an interface for an array of objects with Typescript?

In Angular use 'extends' to define the interface for an 'Array' of objects.

Using an indexer will give you an error as its not an Array interface so doesn't contain the properties and methods.

e.g

error TS2339: Property 'find' does not exist on type 'ISelectOptions2'.

// good    
export interface ISelectOptions1 extends Array<ISelectOption> {}

// bad
export interface ISelectOptions2 {
    [index: number]: ISelectOption;
}

interface ISelectOption {
    prop1: string;
    prop2?: boolean;
}

How do I list all remote branches in Git 1.7+?

Git Branching - Remote Branches

git ls-remote

Git documentation.

How can I use LTRIM/RTRIM to search and replace leading/trailing spaces?

To remove spaces from left/right, use LTRIM/RTRIM. What you had

UPDATE *tablename*
   SET *columnname* = LTRIM(RTRIM(*columnname*));

would have worked on ALL the rows. To minimize updates if you don't need to update, the update code is unchanged, but the LIKE expression in the WHERE clause would have been

UPDATE [tablename]
   SET [columnname] = LTRIM(RTRIM([columnname]))
 WHERE 32 in (ASCII([columname]), ASCII(REVERSE([columname])));

Note: 32 is the ascii code for the space character.

How do I find the time difference between two datetime objects in python?

To get the hour, minute and second, you can do this

>>> import datetime
>>> first_time = datetime.datetime.now()
>>> later_time = datetime.datetime.now()
>>> difference = later_time - first_time
>>> m,s = divmod(difference.total_seconds(), 60)
>>> print("H:M:S is {}:{}:{}".format(m//60,m%60,s)

Git submodule update

To update each submodule, you could invoke the following command (at the root of the repository):

git submodule -q foreach git pull -q origin master

You can remove the -q option to follow the whole process.

Why do I have to define LD_LIBRARY_PATH with an export every time I run my application?

Did you 'export' in your .bashrc?

export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:"/path/to/library"

Remote Procedure call failed with sql server 2008 R2

start SQL Server Agent from the command prompt using:

SQLAGENT90 -C -V>C:\SQLAGENT.OUT

What is :: (double colon) in Python when subscripting sequences?

You can also use this notation in your own custom classes to make it do whatever you want

class C(object):
    def __getitem__(self, k):
        return k

# Single argument is passed directly.
assert C()[0] == 0

# Multiple indices generate a tuple.
assert C()[0, 1] == (0, 1)

# Slice notation generates a slice object.
assert C()[1:2:3] == slice(1, 2, 3)

# If you omit any part of the slice notation, it becomes None.
assert C()[:] == slice(None, None, None)
assert C()[::] == slice(None, None, None)
assert C()[1::] == slice(1, None, None)
assert C()[:2:] == slice(None, 2, None)
assert C()[::3] == slice(None, None, 3)

# Tuple with a slice object:
assert C()[:, 1] == (slice(None, None, None), 1)

# Ellipsis class object.
assert C()[...] == Ellipsis

We can then open up slice objects as:

s = slice(1, 2, 3)
assert s.start == 1
assert s.stop == 2
assert s.step == 3

This is notably used in Numpy to slice multi-dimensional arrays in any direction.

Of course, any sane API should use ::3 with the usual "every 3" semantic.

The related Ellipsis is covered further at: What does the Ellipsis object do?

Apply style to parent if it has child with css

It's not possible with CSS3. There is a proposed CSS4 selector, $, to do just that, which could look like this (Selecting the li element):

ul $li ul.sub { ... }

See the list of CSS4 Selectors here.

As an alternative, with jQuery, a one-liner you could make use of would be this:

$('ul li:has(ul.sub)').addClass('has_sub');

You could then go ahead and style the li.has_sub in your CSS.

JQuery to load Javascript file dynamically

Yes, use getScript instead of document.write - it will even allow for a callback once the file loads.

You might want to check if TinyMCE is defined, though, before including it (for subsequent calls to 'Add Comment') so the code might look something like this:

$('#add_comment').click(function() {
    if(typeof TinyMCE == "undefined") {
        $.getScript('tinymce.js', function() {
            TinyMCE.init();
        });
    }
});

Assuming you only have to call init on it once, that is. If not, you can figure it out from here :)

HTML list-style-type dash

My solution is in adding extra span tag with mdash in it:

<ul class="mdash-list">
    <li><span class="mdash-icon">&mdash;</span>ABC</li>
    <li><span class="mdash-icon">&mdash;</span>XYZ</li>
</ul>

and adding to css:

ul.mdash-list 
{
    list-style:none;
}

ul.mdash-list  li
{
    position:relative;
}

ul.mdash-list li .mdash-icon
{
    position:absolute;
    left:-20px;
}

Count(*) vs Count(1) - SQL Server

As this question comes up again and again, here is one more answer. I hope to add something for beginners wondering about "best practice" here.

SELECT COUNT(*) FROM something counts records which is an easy task.

SELECT COUNT(1) FROM something retrieves a 1 per record and than counts the 1s that are not null, which is essentially counting records, only more complicated.

Having said this: Good dbms notice that the second statement will result in the same count as the first statement and re-interprete it accordingly, as not to do unnecessary work. So usually both statements will result in the same execution plan and take the same amount of time.

However from the point of readability you should use the first statement. You want to count records, so count records, not expressions. Use COUNT(expression) only when you want to count non-null occurences of something.

MySQL convert date string to Unix timestamp

You will certainly have to use both STR_TO_DATE to convert your date to a MySQL standard date format, and UNIX_TIMESTAMP to get the timestamp from it.

Given the format of your date, something like

UNIX_TIMESTAMP(STR_TO_DATE(Sales.SalesDate, '%M %e %Y %h:%i%p'))

Will gives you a valid timestamp. Look the STR_TO_DATE documentation to have more information on the format string.

Laravel 5.5 ajax call 419 (unknown status)

This worked for me:

$.ajaxSetup({
  headers: {
    'X-CSRF-TOKEN': "{{ csrf_token() }}"
  }
});

After this set regular AJAX call. Example:

    $.ajax({
       type:'POST',
       url:'custom_url',

       data:{name: "some name", password: "pass", email: "[email protected]"},

       success:function(response){

          // Log response
          console.log(response);

       }

    });

WordPress: get author info from post id

If you want it outside of loop then use the below code.

<?php
$author_id = get_post_field ('post_author', $cause_id);
$display_name = get_the_author_meta( 'display_name' , $author_id ); 
echo $display_name;
?>

How to fix "The ConnectionString property has not been initialized"

The connection string is not in AppSettings.

What you're looking for is in:

System.Configuration.ConfigurationManager.ConnectionStrings["MyDB"]...

How can one print a size_t variable portably using the printf family?

On some platforms and for some types there are specific printf conversion specifiers available, but sometimes one has to resort to casting to larger types.

I've documented this tricky issue here, with example code: http://www.pixelbeat.org/programming/gcc/int_types/ and update it periodically with info on new platforms and types.

Formatting code in Notepad++

NPP+ v7.9.1 with the latest version of XMLTools can't format exported VBA code from Office 2016/2019 Word. It puts all the code on the same line since it strips the CRLF out. Moreover, when you enable "auto validation" it errors out on the first VBA line that is, Attribute VB_Name = "The VBA module name". So any of the xml tool validations apparently can't be used for VBA validation.

How to assign a NULL value to a pointer in python?

Normally you can use None, but you can also use objc.NULL, e.g.

import objc
val = objc.NULL

Especially useful when working with C code in Python.

Also see: Python objc.NULL Examples

Disable Drag and Drop on HTML elements?

I will just leave it here. Helped me after I tried everything.

   $(document.body).bind("dragover", function(e) {
        e.preventDefault();
        return false;
   });

   $(document.body).bind("drop", function(e){
        e.preventDefault();
        return false;
   });

Ng-model does not update controller value

I had the same problem.
The proper way would be setting the 'searchText' to be a property inside an object.

But what if I want to leave it as it is, a string? well, I tried every single method mentioned here, nothing worked.
But then I noticed that the problem is only in the initiation, so I've just set the value attribute and it worked.

<input type="text" ng-model="searchText" value={{searchText}} />

This way the value is just set to '$scope.searchText' value and it's being updated when the input value changes.

I know it's a workaround, but it worked for me..

Style jQuery autocomplete in a Bootstrap input field

If you're using jQuery-UI, you must include the jQuery UI CSS package, otherwise the UI components don't know how to be styled.

If you don't like the jQuery UI styles, then you'll have to recreate all the styles it would have otherwise applied.

Here's an example and some possible fixes.

Minimal, Complete, and Verifiable example (i.e. broken)

Here's a demo in Stack Snippets without jquery-ui.css (doesn't work)

_x000D_
_x000D_
$(function() {_x000D_
  var availableTags = [_x000D_
    "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++",_x000D_
    "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran",_x000D_
    "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl",_x000D_
    "PHP", "Python", "Ruby", "Scala", "Scheme"_x000D_
  ];_x000D_
  _x000D_
  $(".autocomplete").autocomplete({_x000D_
    source: availableTags_x000D_
  });_x000D_
});
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
_x000D_
  <div class="form-group">_x000D_
    <label>Languages</label>_x000D_
    <input class="form-control autocomplete" placeholder="Enter A" />_x000D_
  </div>_x000D_
  _x000D_
  <div class="form-group">_x000D_
    <label >Another Field</label>_x000D_
    <input class="form-control">_x000D_
  </div>_x000D_
_x000D_
</div>
_x000D_
_x000D_
_x000D_

Fix #1 - jQuery-UI Style

Just include jquery-ui.css and everything should work just fine with the latest supported versions of jquery.

_x000D_
_x000D_
$(function() {_x000D_
  var availableTags = [_x000D_
    "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++",_x000D_
    "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran",_x000D_
    "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl",_x000D_
    "PHP", "Python", "Ruby", "Scala", "Scheme"_x000D_
  ];_x000D_
  _x000D_
  $(".autocomplete").autocomplete({_x000D_
    source: availableTags_x000D_
  });_x000D_
});
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.css" rel="stylesheet"/>_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
  <div class="form-group">_x000D_
    <label>Languages</label>_x000D_
    <input class="form-control autocomplete" placeholder="Enter A" />_x000D_
  </div>_x000D_
  _x000D_
  <div class="form-group">_x000D_
    <label >Another Field</label>_x000D_
    <input class="form-control">_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Fix #2 - Bootstrap Theme

There is a project that created a Bootstrap-esque theme for jQuery-UI components called jquery-ui-bootstrap. Just grab the stylesheet from there and you should be all set.

_x000D_
_x000D_
$(function() {_x000D_
  var availableTags = [_x000D_
    "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++",_x000D_
    "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran",_x000D_
    "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl",_x000D_
    "PHP", "Python", "Ruby", "Scala", "Scheme"_x000D_
  ];_x000D_
  _x000D_
  $(".autocomplete").autocomplete({_x000D_
    source: availableTags_x000D_
  });_x000D_
});
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/jquery-ui-bootstrap/0.5pre/css/custom-theme/jquery-ui-1.10.0.custom.css" rel="stylesheet"/>_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
  <div class="form-group">_x000D_
    <label>Languages</label>_x000D_
    <input class="form-control autocomplete" placeholder="Enter A" />_x000D_
  </div>_x000D_
  _x000D_
  <div class="form-group">_x000D_
    <label >Another Field</label>_x000D_
    <input class="form-control">_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Fix #3 - Manual CSS

If you only need the AutoComplete widget from jQuery-UI's library, you should start by doing a custom build so you don't pull in resources you're not using.

After that, you'll need to style it yourself. Just look at some of the other styles that are applied to jquery's autocomplete.css and theme.css to figure out what styles you'll need to manually replace.

You can use bootstrap's dropdowns.less for inspiration.

Here's a sample CSS that fits pretty well with Bootstrap's default theme:

.ui-autocomplete {
    position: absolute;
    z-index: 1000;
    cursor: default;
    padding: 0;
    margin-top: 2px;
    list-style: none;
    background-color: #ffffff;
    border: 1px solid #ccc;
    -webkit-border-radius: 5px;
       -moz-border-radius: 5px;
            border-radius: 5px;
    -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
       -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
            box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);
}
.ui-autocomplete > li {
  padding: 3px 20px;
}
.ui-autocomplete > li.ui-state-focus {
  background-color: #DDD;
}
.ui-helper-hidden-accessible {
  display: none;
}

_x000D_
_x000D_
$(function() {_x000D_
  var availableTags = [_x000D_
    "ActionScript", "AppleScript", "Asp", "BASIC", "C", "C++",_x000D_
    "Clojure", "COBOL", "ColdFusion", "Erlang", "Fortran",_x000D_
    "Groovy", "Haskell", "Java", "JavaScript", "Lisp", "Perl",_x000D_
    "PHP", "Python", "Ruby", "Scala", "Scheme"_x000D_
  ];_x000D_
  _x000D_
  $(".autocomplete").autocomplete({_x000D_
    source: availableTags_x000D_
  });_x000D_
});
_x000D_
.ui-autocomplete {_x000D_
    position: absolute;_x000D_
    z-index: 1000;_x000D_
    cursor: default;_x000D_
    padding: 0;_x000D_
    margin-top: 2px;_x000D_
    list-style: none;_x000D_
    background-color: #ffffff;_x000D_
    border: 1px solid #ccc_x000D_
    -webkit-border-radius: 5px;_x000D_
       -moz-border-radius: 5px;_x000D_
            border-radius: 5px;_x000D_
    -webkit-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);_x000D_
       -moz-box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);_x000D_
            box-shadow: 0 5px 10px rgba(0, 0, 0, 0.2);_x000D_
}_x000D_
.ui-autocomplete > li {_x000D_
  padding: 3px 20px;_x000D_
}_x000D_
.ui-autocomplete > li.ui-state-focus {_x000D_
  background-color: #DDD;_x000D_
}_x000D_
.ui-helper-hidden-accessible {_x000D_
  display: none;_x000D_
}
_x000D_
<link href="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/css/bootstrap.css" rel="stylesheet"/>_x000D_
_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jquery/2.1.3/jquery.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/jqueryui/1.11.2/jquery-ui.js"></script>_x000D_
<script src="//cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.2/js/bootstrap.js"></script>_x000D_
_x000D_
<div class="container">_x000D_
  <div class="form-group ui-widget">_x000D_
    <label>Languages</label>_x000D_
    <input class="form-control autocomplete" placeholder="Enter A" />_x000D_
  </div>_x000D_
  _x000D_
  <div class="form-group ui-widget">_x000D_
    <label >Another Field</label>_x000D_
    <input class="form-control" />_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Tip: Since the dropdown menu hides every time you go to inspect the element (i.e. whenever the input loses focus), for easier debugging of the style, find the control with .ui-autocomplete and remove display: none;.

Importing project into Netbeans

File >> New Project >> Java Project With Existing Source>Next >> Project Name(add a name for your project) >> Next>>Add Folder >> select your existing project source code from your Directory>>Next >> Finish

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

enter image description here

Java Project With Existing Source

Number of lines in a file in Java

A straight-forward way using Scanner

static void lineCounter (String path) throws IOException {

        int lineCount = 0, commentsCount = 0;

        Scanner input = new Scanner(new File(path));
        while (input.hasNextLine()) {
            String data = input.nextLine();

            if (data.startsWith("//")) commentsCount++;

            lineCount++;
        }

        System.out.println("Line Count: " + lineCount + "\t Comments Count: " + commentsCount);
    }

How do I import a pre-existing Java project into Eclipse and get up and running?

I think you'll have to import the project via the file->import wizard:

http://www.coderanch.com/t/419556/vc/Open-existing-project-Eclipse

It's not the last step, but it will start you on your way.

I also feel your pain - there is really no excuse for making it so difficult to do a simple thing like opening an existing project. I truly hope that the Eclipse designers focus on making the IDE simpler to use (tho I applaud their efforts at trying different approaches - but please, Eclipse designers, if you are listening, never complicate something simple).

SVN Error - Not a working copy

I tried pasting the .svn folder from the sub folder to the root folder. It works!!!

How can I create a table with borders in Android?

I used this solution: in TableRow, I created for every cell LinearLayout with vertical line and actual cell in it, and after every TableRow, I added a horizontal line.

Look at the code below:

<TableLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:shrinkColumns="1">

    <TableRow            
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" >

            <LinearLayout 
                android:orientation="horizontal"
                android:layout_height="match_parent"
                android:layout_weight="1">

                <TextView 
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:gravity="center"/>

            </LinearLayout>

            <LinearLayout 
                android:orientation="horizontal"
                android:layout_height="match_parent"
                android:layout_weight="1">

                <View
                    android:layout_height="match_parent"
                    android:layout_width="1dp"
                    android:background="#BDCAD2"/>

                <TextView 
                    android:layout_width="0dp"
                    android:layout_height="wrap_content"
                    android:gravity="center"/>

            </LinearLayout>
      </TableRow>

      <View
        android:layout_height="1dip"
        android:background="#BDCAD2" />

      <!-- More TableRows -->
</TableLayout>

Hope it will help.

Python - A keyboard command to stop infinite loop?

Ctrl+C is what you need. If it didn't work, hit it harder. :-) Of course, you can also just close the shell window.

Edit: You didn't mention the circumstances. As a last resort, you could write a batch file that contains taskkill /im python.exe, and put it on your desktop, Start menu, etc. and run it when you need to kill a runaway script. Of course, it will kill all Python processes, so be careful.

HTML meta tag for content language

You asked for differences, but you can’t quite compare those two.

Note that <meta http-equiv="content-language" content="es"> is obsolete and removed in HTML5. It was used to specify “a document-wide default language”, with its http-equiv attribute making it a pragma directive (which simulates an HTTP response header like Content-Language that hasn’t been sent from the server, since it cannot override a real one).

Regarding <meta name="language" content="Spanish">, you hardly find any reliable information. It’s non-standard and was probably invented as a SEO makeshift.

However, the HTML5 W3C Recommendation encourages authors to use the lang attribute on html root elements (attribute values must be valid BCP 47 language tags):

<!DOCTYPE html>
<html lang="es-ES">
    <head>
        …

Anyway, if you want to specify the content language to instruct search engine robots, you should consider this quote from Google Search Console Help on multilingual sites:

Google uses only the visible content of your page to determine its language. We don’t use any code-level language information such as lang attributes.

How to handle AssertionError in Python and find out which line or statement it occurred on?

The traceback module and sys.exc_info are overkill for tracking down the source of an exception. That's all in the default traceback. So instead of calling exit(1) just re-raise:

try:
    assert "birthday cake" == "ice cream cake", "Should've asked for pie"
except AssertionError:
    print 'Houston, we have a problem.'
    raise

Which gives the following output that includes the offending statement and line number:

Houston, we have a problem.
Traceback (most recent call last):
  File "/tmp/poop.py", line 2, in <module>
    assert "birthday cake" == "ice cream cake", "Should've asked for pie"
AssertionError: Should've asked for pie

Similarly the logging module makes it easy to log a traceback for any exception (including those which are caught and never re-raised):

import logging

try:
    assert False == True 
except AssertionError:
    logging.error("Nothing is real but I can't quit...", exc_info=True)

PHPExcel set border and format for all sheets in spreadsheet

You can set a default style for the entire workbook (all worksheets):

$objPHPExcel->getDefaultStyle()
    ->getBorders()
    ->getTop()
        ->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getDefaultStyle()
    ->getBorders()
    ->getBottom()
        ->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getDefaultStyle()
    ->getBorders()
    ->getLeft()
        ->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);
$objPHPExcel->getDefaultStyle()
    ->getBorders()
    ->getRight()
        ->setBorderStyle(PHPExcel_Style_Border::BORDER_THIN);

or

  $styleArray = array(
      'borders' => array(
          'allborders' => array(
              'style' => PHPExcel_Style_Border::BORDER_THIN
          )
      )
  );
$objPHPExcel->getDefaultStyle()->applyFromArray($styleArray);

And this can be used for all style properties, not just borders.

But column autosizing is structural rather than stylistic, and has to be set for each column on each worksheet individually.

EDIT

Note that default workbook style only applies to Excel5 Writer

Compression/Decompression string with C#

We can reduce code complexity by using StreamReader and StreamWriter rather than manually converting strings to byte arrays. Three streams is all you need:

    public static byte[] Zip(string uncompressed)
    {
        byte[] ret;
        using (var outputMemory = new MemoryStream())
        {
            using (var gz = new GZipStream(outputMemory, CompressionLevel.Optimal))
            {
                using (var sw = new StreamWriter(gz, Encoding.UTF8))
                {
                    sw.Write(uncompressed);
                }
            }
            ret = outputMemory.ToArray();
        }
        return ret;
    }

    public static string Unzip(byte[] compressed)
    {
        string ret = null;
        using (var inputMemory = new MemoryStream(compressed))
        {
            using (var gz = new GZipStream(inputMemory, CompressionMode.Decompress))
            {
                using (var sr = new StreamReader(gz, Encoding.UTF8))
                {
                    ret = sr.ReadToEnd();
                }
            }
        }
        return ret;
    }

Directory Chooser in HTML page

In case if you are the server and the user (e.g. you are creating an app which works via browser and you need to choose a folder) then try to call JFileChooser from the server when some button is clicked in the browser

JFileChooser chooser = new JFileChooser();
chooser.setCurrentDirectory(new java.io.File("."));
chooser.setDialogTitle("select folder");
chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
chooser.setAcceptAllFileFilterUsed(false);

This code snipped is from here

String comparison in Objective-C

Use the -isEqualToString: method to compare the value of two strings. Using the C == operator will simply compare the addresses of the objects.

if ([category isEqualToString:@"Some String"])
{
    // Do stuff...
}

SQL Server - transactions roll back on error?

You are correct in that the entire transaction will be rolled back. You should issue the command to roll it back.

You can wrap this in a TRY CATCH block as follows

BEGIN TRY
    BEGIN TRANSACTION

        INSERT INTO myTable (myColumns ...) VALUES (myValues ...);
        INSERT INTO myTable (myColumns ...) VALUES (myValues ...);
        INSERT INTO myTable (myColumns ...) VALUES (myValues ...);

    COMMIT TRAN -- Transaction Success!
END TRY
BEGIN CATCH
    IF @@TRANCOUNT > 0
        ROLLBACK TRAN --RollBack in case of Error

    -- you can Raise ERROR with RAISEERROR() Statement including the details of the exception
    RAISERROR(ERROR_MESSAGE(), ERROR_SEVERITY(), 1)
END CATCH

How to override the path of PHP to use the MAMP path?

you might still run into mysql binary not being found in that manner

open terminal, type
touch ~/.bash_profile; open ~/.bash_profile

edit as follows below, save, quite and restart terminal or alternately

source ~/.bash_profile

to execute new PATH without restarting terminal

and in the fashion of the DavidYell's post above, also add the following. You can stack various variables by exporting them followed by a single PATH export which I demonstrated below

export MAMP_PHP=/Applications/MAMP/bin/php/php5.6.2/bin
export MAMP_BINS=/Applications/MAMP/Library/bin
export USERBINS=~/bins
export PATH="$USERBINS:$MAMP_PHP:$MAMP_BINS:$PATH"

cheers

The openssl extension is required for SSL/TLS protection

I had the same problem. I tried everything listed on this page. When I re-installed Composer it worked like before. I had a PHP version mismatch that was corrected with a new install establishing the dependencies with the PHP path installed in my system environment variables.

I DO NOT RECOMMEND the composer config -g -- disable-tls true approach.

By the way the way to reverse this is composer config -g -- disable-tls false.

Returning JSON object from an ASP.NET page

With ASP.NET Web Pages you can do this on a single page as a basic GET example (the simplest possible thing that can work.

var json = Json.Encode(new {
    orientation = Cache["orientation"],
    alerted = Cache["alerted"] as bool?,
    since = Cache["since"] as DateTime?
});
Response.Write(json);

Set start value for column with autoincrement

From Resetting SQL Server Identity Columns:

Retrieving the identity for the table Employees:

DBCC checkident ('Employees')

Repairing the identity seed (if for some reason the database is inserting duplicate identities):

DBCC checkident ('Employees', reseed)

Changing the identity seed for the table Employees to 1000:

DBCC checkident ('Employees', reseed, 1000)

The next row inserted will begin at 1001.

Can I make dynamic styles in React Native?

If you are using a screen with filters for example, and you want to set the background of the filter regarding if it was selected or not, you can do:

<TouchableOpacity style={this.props.venueFilters.includes('Bar')?styles.filterBtnActive:styles.filterBtn} onPress={()=>this.setFilter('Bar')}>
<Text numberOfLines={1}>
Bar
</Text>
</TouchableOpacity>

On which set filter is:

setVenueFilter(filter){
  var filters = this.props.venueFilters;
  filters.push(filter);
  console.log(filters.includes('Bar'), "Inclui Bar");
  this.setState(previousState => {
    return { updateFilter: !previousState.updateFilter };
  });
  this.props.setVenueFilter(filters);
}

PS: the function this.props.setVenueFilter(filters) is a redux action, and this.props.venueFilters is a redux state.

Javascript Date: next month

I was looking for a simple one-line solution to get the next month via math so I wouldn't have to look up the javascript date functions (mental laziness on my part). Quite strangely, I didn't find one here.

I overcame my brief bout of laziness, wrote one, and decided to share!

Solution:

(new Date().getMonth()+1)%12 + 1

Just to be clear why this works, let me break down the magic!

It gets the current month (which is in 0..11 format), increments by 1 for the next month, and wraps it to a boundary of 12 via modulus (11%12==11; 12%12==0). This returns the next month in the same 0..11 format, so converting to a format Date() will recognize (1..12) is easy: simply add 1 again.

Proof of concept:

> for(var m=0;m<=11;m++) { console.info( "next month for %i: %i", m+1, (m+1)%12 + 1 ) }
next month for 1: 2
next month for 2: 3
next month for 3: 4
next month for 4: 5
next month for 5: 6
next month for 6: 7
next month for 7: 8
next month for 8: 9
next month for 9: 10
next month for 10: 11
next month for 11: 12
next month for 12: 1

So there you have it.

"You may need an appropriate loader to handle this file type" with Webpack and Babel

If you are using Webpack > 3 then you only need to install babel-preset-env, since this preset accounts for es2015, es2016 and es2017.

var path = require('path');
let webpack = require("webpack");

module.exports = {
    entry: {
        app: './app/App.js',
        vendor: ["react","react-dom"]
    },
    output: {
        filename: 'bundle.js',
        path: path.resolve(__dirname, '../public')
    },
    module: {
        rules: [{
            test: /\.jsx?$/,
            exclude: /node_modules/,
            use: {
                loader: 'babel-loader?cacheDirectory=true',
            }
        }]
    }
};

This picks up its configuration from my .babelrc file:

{
    "presets": [
        [
            "env",
            {
                "targets": {
                    "browsers":["last 2 versions"],
                    "node":"current"
                }
            }
        ],["react"]
    ]
}

How to set x axis values in matplotlib python?

The scaling on your example figure is a bit strange but you can force it by plotting the index of each x-value and then setting the ticks to the data points:

import matplotlib.pyplot as plt
x = [0.00001,0.001,0.01,0.1,0.5,1,5]
# create an index for each tick position
xi = list(range(len(x)))
y = [0.945,0.885,0.893,0.9,0.996,1.25,1.19]
plt.ylim(0.8,1.4)
# plot the index for the x-values
plt.plot(xi, y, marker='o', linestyle='--', color='r', label='Square') 
plt.xlabel('x')
plt.ylabel('y') 
plt.xticks(xi, x)
plt.title('compare')
plt.legend() 
plt.show()

Adb over wireless without usb cable at all for not rooted phones

type in Windows cmd.exe

    cd %userprofile%\.android
    dir
    copy adbkey.pub adb_keys
    dir

copy the file adb_keys to your phone folder /data/misc/adb. Reboot the phone. RSA Key is now authorized.

from: How to solve ADB device unauthorized in Android ADB host device?

now follow the instructions for adb connect, or use any app for preparing. i prefer ADB over WIFI Widget from Mehdy Bohlool, it works without root.

from: How can I connect to Android with ADB over TCP?

How to display list items on console window in C#

Console.WriteLine(string.Join<TYPE>("\n", someObjectList));

align images side by side in html

In your CSS:

.image123{
float:left;
}

Error when checking model input: expected convolution2d_input_1 to have 4 dimensions, but got array with shape (32, 32, 3)

Got the same problem, non of the answers worked for me. After a lot of debugging I found out that the size of one image was smaller than 32. This leads to a broken array with wrong dimensions and the above mentioned error.

To solve the problem, make sure that all images have the correct dimensions.

Binding objects defined in code-behind

You can try x:Reference trick

<Window ... x:Name="myWindow"><ListBox ItemsSource="{Binding Items, Source={x:Reference myWindow}}" /></Window>

How to deal with page breaks when printing a large HTML table

I ended up following @vicenteherrera's approach, with some tweaks (that are possibly bootstrap 3 specific).

Basically; we can't break trs, or tds because they're not block-level elements. So we embed divs into each, and apply our page-break-* rules against the div. Secondly; we add some padding to the top of each of these divs, to compensate for any styling artifacts.

<style>
    @media print {
        /* avoid cutting tr's in half */
        th div, td div {
            margin-top:-8px;
            padding-top:8px;
            page-break-inside:avoid;
        }
    }
</style>
<script>
    $(document).ready(function(){
        // Wrap each tr and td's content within a div
        // (todo: add logic so we only do this when printing)
        $("table tbody th, table tbody td").wrapInner("<div></div>");
    })
</script>

The margin and padding adjustments were necessary to offset some kind of jitter that was being introduced (by my guess - from bootstrap). I'm not sure that I'm presenting any new solution from the other answers to this question, but I figure maybe this will help someone.

what does Error "Thread 1:EXC_BAD_INSTRUCTION (code=EXC_I386_INVOP, subcode=0x0)" mean?

In my case this was caused by an integer overflow. I had a UInt16, and was doubling the value to put into an Int. The faulty code was

let result = Int(myUInt16 * 2)

However, this multiplies as a UInt16, then converts to Int. So if myUInt16 contains a value over 32767 then an overflow occurs.

All was well once I corrected the code to

let result = Int(myUint16) * 2

How to SELECT the last 10 rows of an SQL table which has no ID field?

you can with code select 10 row from end of table. select * from (SELECT * FROM table1 order by id desc LIMIT 10) as table2 order by id"

Is there any way to redraw tmux window when switching smaller monitor to bigger one?

This is still the top post when searching, but it's no longer valid. Best answer is here, but the TLDR is

<c-b>:resize-window -A

How can I select the record with the 2nd highest salary in database Oracle?

select * from emp where sal=(select max(sal) from emp where sal<(select max(sal) from emp))

so in our emp table(default provided by oracle) here is the output

EMPNO ENAME JOB MGR HIREDATE SAL COMM DEPTNO


  7698 BLAKE      MANAGER         7839 01-MAY-81       3000            30
  7788 SCOTT      ANALYST         7566 19-APR-87       3000            20
  7902 FORD       ANALYST         7566 03-DEC-81       3000            20

or just you want 2nd maximum salary to be displayed

select max(sal) from emp where sal<(select max(sal) from emp)

MAX(SAL)

  3000

How can I tell if an algorithm is efficient?

Yes you can start with the Wikipedia article explaining the Big O notation, which in a nutshell is a way of describing the "efficiency" (upper bound of complexity) of different type of algorithms. Or you can look at an earlier answer where this is explained in simple english

What does DIM stand for in Visual Basic and BASIC?

It stands for Dimension, but is generally read as "Create Variable," or "Allocate Space for This."

How to animate RecyclerView items when they appear

Just extends your Adapter like below

public class RankingAdapter extends AnimatedRecyclerView<RankingAdapter.ViewHolder> 

And add super method to onBindViewHolder

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

It's automate way to create animated adapter like "Basheer AL-MOMANI"

import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.view.ViewGroup;
import android.view.animation.Animation;
import android.view.animation.ScaleAnimation;

import java.util.Random;

/**
 * Created by eliaszkubala on 24.02.2017.
 */
public class AnimatedRecyclerView<T extends RecyclerView.ViewHolder> extends RecyclerView.Adapter<T> {


    @Override
    public T onCreateViewHolder(ViewGroup parent, int viewType) {
        return null;
    }

    @Override
    public void onBindViewHolder(T holder, int position) {
        setAnimation(holder.itemView, position);
    }

    @Override
    public int getItemCount() {
        return 0;
    }

    protected int mLastPosition = -1;

    protected void setAnimation(View viewToAnimate, int position) {
        if (position > mLastPosition) {
            ScaleAnimation anim = new ScaleAnimation(0.0f, 1.0f, 0.0f, 1.0f, Animation.RELATIVE_TO_SELF, 0.5f, Animation.RELATIVE_TO_SELF, 0.5f);
            anim.setDuration(new Random().nextInt(501));//to make duration random number between [0,501)
            viewToAnimate.startAnimation(anim);
            mLastPosition = position;
        }
    }

}

Using Gulp to Concatenate and Uglify files

My gulp file produces a final compiled-bundle-min.js, hope this helps someone.

enter image description here

//Gulpfile.js

var gulp = require("gulp");
var watch = require("gulp-watch");

var concat = require("gulp-concat");
var rename = require("gulp-rename");
var uglify = require("gulp-uglify");
var del = require("del");
var minifyCSS = require("gulp-minify-css");
var copy = require("gulp-copy");
var bower = require("gulp-bower");
var sourcemaps = require("gulp-sourcemaps");

var path = {
    src: "bower_components/",
    lib: "lib/"
}

var config = {
    jquerysrc: [
        path.src + "jquery/dist/jquery.js",
        path.src + "jquery-validation/dist/jquery.validate.js",
        path.src + "jquery-validation/dist/jquery.validate.unobtrusive.js"
    ],
    jquerybundle: path.lib + "jquery-bundle.js",
    ngsrc: [
        path.src + "angular/angular.js",
         path.src + "angular-route/angular-route.js",
         path.src + "angular-resource/angular-resource.js"
    ],
    ngbundle: path.lib + "ng-bundle.js",

    //JavaScript files that will be combined into a Bootstrap bundle
    bootstrapsrc: [
        path.src + "bootstrap/dist/js/bootstrap.js"
    ],
    bootstrapbundle: path.lib + "bootstrap-bundle.js"
}

// Synchronously delete the output script file(s)
gulp.task("clean-scripts", function (cb) {
    del(["lib","dist"], cb);
});

//Create a jquery bundled file
gulp.task("jquery-bundle", ["clean-scripts", "bower-restore"], function () {
    return gulp.src(config.jquerysrc)
     .pipe(concat("jquery-bundle.js"))
     .pipe(gulp.dest("lib"));
});

//Create a angular bundled file
gulp.task("ng-bundle", ["clean-scripts", "bower-restore"], function () {
    return gulp.src(config.ngsrc)
     .pipe(concat("ng-bundle.js"))
     .pipe(gulp.dest("lib"));
});

//Create a bootstrap bundled file
gulp.task("bootstrap-bundle", ["clean-scripts", "bower-restore"], function     () {
    return gulp.src(config.bootstrapsrc)
     .pipe(concat("bootstrap-bundle.js"))
     .pipe(gulp.dest("lib"));
});


// Combine and the vendor files from bower into bundles (output to the Scripts folder)
gulp.task("bundle-scripts", ["jquery-bundle", "ng-bundle", "bootstrap-bundle"], function () {

});

//Restore all bower packages
gulp.task("bower-restore", function () {
    return bower();
});

//build lib scripts
gulp.task("compile-lib", ["bundle-scripts"], function () {
    return gulp.src("lib/*.js")
        .pipe(sourcemaps.init())
        .pipe(concat("compiled-bundle.js"))
        .pipe(gulp.dest("dist"))
        .pipe(rename("compiled-bundle.min.js"))
        .pipe(uglify())
        .pipe(sourcemaps.write("./"))
        .pipe(gulp.dest("dist"));
});

How do I fix a "Expected Primary-expression before ')' token" error?

showInventory(player); is passing a type as parameter. That's illegal, you need to pass an object.

For example, something like:

player p;
showInventory(p);  

I'm guessing you have something like this:

int main()
{
   player player;
   toDo();
}

which is awful. First, don't name the object the same as your type. Second, in order for the object to be visible inside the function, you'll need to pass it as parameter:

int main()
{
   player p;
   toDo(p);
}

and

std::string toDo(player& p) 
{
    //....
    showInventory(p);
    //....
}

Using wget to recursively fetch a directory with arbitrary files in it

You should be able to do it simply by adding a -r

wget -r http://stackoverflow.com/

Where can I find my Facebook application id and secret key?

Peter's post is pretty much spot on, but if you want to learn how to navigate to it yourself here are the instructions:

On the left hand menu, you need to click "more", then you'll see "Developer", click on it. Afterwards you'll be presented with a page where your apps are listed under "My Applications" click on "See my applications". You can find all your API Key, secrets, and IDs there.

Send response to all clients except sender

Here is a more complete answer about what has changed from 0.9.x to 1.x.

 // send to current request socket client
 socket.emit('message', "this is a test");// Hasn't changed

 // sending to all clients, include sender
 io.sockets.emit('message', "this is a test"); // Old way, still compatible
 io.emit('message', 'this is a test');// New way, works only in 1.x

 // sending to all clients except sender
 socket.broadcast.emit('message', "this is a test");// Hasn't changed

 // sending to all clients in 'game' room(channel) except sender
 socket.broadcast.to('game').emit('message', 'nice game');// Hasn't changed

 // sending to all clients in 'game' room(channel), include sender
 io.sockets.in('game').emit('message', 'cool game');// Old way, DOES NOT WORK ANYMORE
 io.in('game').emit('message', 'cool game');// New way
 io.to('game').emit('message', 'cool game');// New way, "in" or "to" are the exact same: "And then simply use to or in (they are the same) when broadcasting or emitting:" from http://socket.io/docs/rooms-and-namespaces/

 // sending to individual socketid, socketid is like a room
 io.sockets.socket(socketid).emit('message', 'for your eyes only');// Old way, DOES NOT WORK ANYMORE
 socket.broadcast.to(socketid).emit('message', 'for your eyes only');// New way

I wanted to edit the post of @soyuka but my edit was rejected by peer-review.

How to define several include path in Makefile

Make's substitutions feature is nice and helped me to write

%.i: src/%.c $(INCLUDE)
        gcc -E $(CPPFLAGS) $(INCLUDE:%=-I %) $< > $@

You might find this useful, because it asks make to check for changes in include folders too

Decode JSON with unknown structure

package main

import "encoding/json"

func main() {
    in := []byte(`{ "votes": { "option_A": "3" } }`)
    var raw map[string]interface{}
    if err := json.Unmarshal(in, &raw); err != nil {
        panic(err)
    }
    raw["count"] = 1
    out, err := json.Marshal(raw)
    if err != nil {
        panic(err)
    }
    println(string(out))
}

https://play.golang.org/p/o8ZwvgsQmoO

android - listview get item view by position

workignHoursListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
    @Override
    public void onItemClick(AdapterView<?> parent,View view, int position, long id) {
        viewtype yourview=yourListViewId.getChildAt(position).findViewById(R.id.viewid);
    }
});

how to do bitwise exclusive or of two strings in python?

Below illustrates XORing string s with m, and then again to reverse the process:

>>> s='hello, world'
>>> m='markmarkmark'
>>> s=''.join(chr(ord(a)^ord(b)) for a,b in zip(s,m))
>>> s
'\x05\x04\x1e\x07\x02MR\x1c\x02\x13\x1e\x0f'
>>> s=''.join(chr(ord(a)^ord(b)) for a,b in zip(s,m))
>>> s
'hello, world'
>>>

Retrieving Dictionary Value Best Practices

TryGetValue is slightly faster, because FindEntry will only be called once.

How much faster? It depends on the dataset at hand. When you call the Contains method, Dictionary does an internal search to find its index. If it returns true, you need another index search to get the actual value. When you use TryGetValue, it searches only once for the index and if found, it assigns the value to your variable.

FYI: It's not actually catching an error.

It's calling:

public bool TryGetValue(TKey key, out TValue value)
{
    int index = this.FindEntry(key);
    if (index >= 0)
    {
        value = this.entries[index].value;
        return true;
    }
    value = default(TValue);
    return false;
}

ContainsKey is this:

public bool ContainsKey(TKey key)
{
    return (this.FindEntry(key) >= 0);
}

Unit testing with Spring Security

Using a static in this case is the best way to write secure code.

Yes, statics are generally bad - generally, but in this case, the static is what you want. Since the security context associates a Principal with the currently running thread, the most secure code would access the static from the thread as directly as possible. Hiding the access behind a wrapper class that is injected provides an attacker with more points to attack. They wouldn't need access to the code (which they would have a hard time changing if the jar was signed), they just need a way to override the configuration, which can be done at runtime or slipping some XML onto the classpath. Even using annotation injection would be overridable with external XML. Such XML could inject the running system with a rogue principal.

multiple packages in context:component-scan, spring config

You can add multiple base packages (see axtavt's answer), but you can also filter what's scanned inside the base package:

<context:component-scan base-package="x.y.z">
   <context:include-filter type="regex" expression="(service|controller)\..*"/>
</context:component-scan>

how to re-format datetime string in php?

For PHP 5 >= 5.3.0 http://www.php.net/manual/en/datetime.createfromformat.php

$datetime = "20130409163705"; 
$d = DateTime::createFromFormat("YmdHis", $datetime);
echo $d->format("d/m/Y H:i:s"); // or any you want

Result:

09/04/2013 16:37:05

Eclipse hangs on loading workbench

After some investigation about file dates I solved the same issue (which is a randomly recurrent trouble on my Kepler) by simply deleting the following file in my local workspace: .metadata.plugins\org.eclipse.jdt.core\variablesAndContainers.dat

with negligible impact on the workspace restoring.

I hope it can help someone else...

Postgresql : Connection refused. Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

The error you quote has nothing to do with pg_hba.conf; it's failing to connect, not failing to authorize the connection.

Do what the error message says:

Check that the hostname and port are correct and that the postmaster is accepting TCP/IP connections

You haven't shown the command that produces the error. Assuming you're connecting on localhost port 5432 (the defaults for a standard PostgreSQL install), then either:

  • PostgreSQL isn't running

  • PostgreSQL isn't listening for TCP/IP connections (listen_addresses in postgresql.conf)

  • PostgreSQL is only listening on IPv4 (0.0.0.0 or 127.0.0.1) and you're connecting on IPv6 (::1) or vice versa. This seems to be an issue on some older Mac OS X versions that have weird IPv6 socket behaviour, and on some older Windows versions.

  • PostgreSQL is listening on a different port to the one you're connecting on

  • (unlikely) there's an iptables rule blocking loopback connections

(If you are not connecting on localhost, it may also be a network firewall that's blocking TCP/IP connections, but I'm guessing you're using the defaults since you didn't say).

So ... check those:

  • ps -f -u postgres should list postgres processes

  • sudo lsof -n -u postgres |grep LISTEN or sudo netstat -ltnp | grep postgres should show the TCP/IP addresses and ports PostgreSQL is listening on

BTW, I think you must be on an old version. On my 9.3 install, the error is rather more detailed:

$ psql -h localhost -p 12345
psql: could not connect to server: Connection refused
        Is the server running on host "localhost" (::1) and accepting
        TCP/IP connections on port 12345?

Is it possible to decrypt MD5 hashes?

Not directly. Because of the pigeonhole principle, there is (likely) more than one value that hashes to any given MD5 output. As such, you can't reverse it with certainty. Moreover, MD5 is made to make it difficult to find any such reversed hash (however there have been attacks that produce collisions - that is, produce two values that hash to the same result, but you can't control what the resulting MD5 value will be).

However, if you restrict the search space to, for example, common passwords with length under N, you might no longer have the irreversibility property (because the number of MD5 outputs is much greater than the number of strings in the domain of interest). Then you can use a rainbow table or similar to reverse hashes.

How to correctly save instance state of Fragments in back stack?

This is the way I am using at this moment... it's very complicated but at least it handles all the possible situations. In case anyone is interested.

public final class MyFragment extends Fragment {
    private TextView vstup;
    private Bundle savedState = null;

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.whatever, null);
        vstup = (TextView)v.findViewById(R.id.whatever);

        /* (...) */

        /* If the Fragment was destroyed inbetween (screen rotation), we need to recover the savedState first */
        /* However, if it was not, it stays in the instance from the last onDestroyView() and we don't want to overwrite it */
        if(savedInstanceState != null && savedState == null) {
            savedState = savedInstanceState.getBundle(App.STAV);
        }
        if(savedState != null) {
            vstup.setText(savedState.getCharSequence(App.VSTUP));
        }
        savedState = null;

        return v;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        savedState = saveState(); /* vstup defined here for sure */
        vstup = null;
    }

    private Bundle saveState() { /* called either from onDestroyView() or onSaveInstanceState() */
        Bundle state = new Bundle();
        state.putCharSequence(App.VSTUP, vstup.getText());
        return state;
    }

    @Override
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        /* If onDestroyView() is called first, we can use the previously savedState but we can't call saveState() anymore */
        /* If onSaveInstanceState() is called first, we don't have savedState, so we need to call saveState() */
        /* => (?:) operator inevitable! */
        outState.putBundle(App.STAV, (savedState != null) ? savedState : saveState());
    }

    /* (...) */

}

Alternatively, it is always a possibility to keep the data displayed in passive Views in variables and using the Views only for displaying them, keeping the two things in sync. I don't consider the last part very clean, though.

How can I find out the current route in Rails?

You can do request.env['REQUEST_URI'] to see the full requested URI.. it will output something like below

http://localhost:3000/client/1/users/1?name=test

Reactjs setState() with a dynamic key name?

How I accomplished this...

inputChangeHandler: function(event) {
  var key = event.target.id
  var val = event.target.value
  var obj  = {}
  obj[key] = val
  this.setState(obj)
},

Android: making a fullscreen application

You can use the following codes to have a full page in android

Step 1 : Make theme in styles.xml section

<style name="AppTheme.Fullscreen" parent="AppTheme">
    <item name="windowActionBar">false</item>
    <item name="windowNoTitle">true</item>
</style>

Step 2 : Add theme on AndroidManifest.xml

<activity
android:name=“.Activity”
android:theme="@style/AppTheme.Fullscreen"/>

Step 3 : Java codes section

For example you can added following codes in to the onCreate() method.

getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);

Initialising an array of fixed size in python

>>> import numpy
>>> x = numpy.zeros((3,4))
>>> x
array([[ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.],
       [ 0.,  0.,  0.,  0.]])
>>> y = numpy.zeros(5)   
>>> y
array([ 0.,  0.,  0.,  0.,  0.])

x is a 2-d array, and y is a 1-d array. They are both initialized with zeros.

How to capture UIView to UIImage without loss of quality on retina display

Swift 3.0 implementation

extension UIView {
    func getSnapshotImage() -> UIImage {
        UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0)
        drawHierarchy(in: bounds, afterScreenUpdates: false)
        let snapshotImage = UIGraphicsGetImageFromCurrentImageContext()!
        UIGraphicsEndImageContext()
        return snapshotImage
    }
}

Bootstrap4 adding scrollbar to div

      <div class="overflow-auto p-3 mb-3 mb-md-0 mr-md-3 bg-light" style="max-width: 260px; max-height: 100px;">
        <strong>Column 0 </strong><br>
        <strong>Column 1</strong><br>
        <strong>Column 2</strong><br>
        <strong>Column 3</strong><br>
        <strong>Column 4</strong><br>
        <strong>Column 5</strong><br>
        <strong>Column 6</strong><br>
        <strong>Column 7</strong><br>
        <strong>Column 8</strong><br>
        <strong>Column 9</strong><br>
        <strong>Column 10</strong><br>
        <strong>Column 11</strong><br>
        <strong>Column 12</strong><br>
        <strong>Column 13</strong><br>
      </div>
    </div>

How to get everything after last slash in a URL?

urlparse is fine to use if you want to (say, to get rid of any query string parameters).

import urllib.parse

urls = [
    'http://www.test.com/TEST1',
    'http://www.test.com/page/TEST2',
    'http://www.test.com/page/page/12345',
    'http://www.test.com/page/page/12345?abc=123'
]

for i in urls:
    url_parts = urllib.parse.urlparse(i)
    path_parts = url_parts[2].rpartition('/')
    print('URL: {}\nreturns: {}\n'.format(i, path_parts[2]))

Output:

URL: http://www.test.com/TEST1
returns: TEST1

URL: http://www.test.com/page/TEST2
returns: TEST2

URL: http://www.test.com/page/page/12345
returns: 12345

URL: http://www.test.com/page/page/12345?abc=123
returns: 12345

How to Query an NTP Server using C#?

http://www.codeproject.com/Articles/237501/Windows-Phone-NTP-Client is going to work well for Windows Phone .

Adding the relevant code

/// <summary>
/// Class for acquiring time via Ntp. Useful for applications in which correct world time must be used and the 
/// clock on the device isn't "trusted."
/// </summary>
public class NtpClient
{
    /// <summary>
    /// Contains the time returned from the Ntp request
    /// </summary>
    public class TimeReceivedEventArgs : EventArgs
    {
        public DateTime CurrentTime { get; internal set; }
    }

    /// <summary>
    /// Subscribe to this event to receive the time acquired by the NTP requests
    /// </summary>
    public event EventHandler<TimeReceivedEventArgs> TimeReceived;

    protected void OnTimeReceived(DateTime time)
    {
        if (TimeReceived != null)
        {
            TimeReceived(this, new TimeReceivedEventArgs() { CurrentTime = time });
        }
    }


    /// <summary>
    /// Not reallu used. I put this here so that I had a list of other NTP servers that could be used. I'll integrate this
    /// information later and will provide method to allow some one to choose an NTP server.
    /// </summary>
    public string[] NtpServerList = new string[]
    {
        "pool.ntp.org ",
        "asia.pool.ntp.org",
        "europe.pool.ntp.org",
        "north-america.pool.ntp.org",
        "oceania.pool.ntp.org",
        "south-america.pool.ntp.org",
        "time-a.nist.gov"
    };

    string _serverName;
    private Socket _socket;

    /// <summary>
    /// Constructor allowing an NTP server to be specified
    /// </summary>
    /// <param name="serverName">the name of the NTP server to be used</param>
    public NtpClient(string serverName)
    {
        _serverName = serverName;
    }


    /// <summary>
    /// 
    /// </summary>
    public NtpClient()
        : this("time-a.nist.gov")
    { }

    /// <summary>
    /// Begins the network communication required to retrieve the time from the NTP server
    /// </summary>
    public void RequestTime()
    {
        byte[] buffer = new byte[48];
        buffer[0] = 0x1B;
        for (var i = 1; i < buffer.Length; ++i)
            buffer[i] = 0;
        DnsEndPoint _endPoint = new DnsEndPoint(_serverName, 123);

        _socket = new Socket(AddressFamily.InterNetwork, SocketType.Dgram, ProtocolType.Udp);
        SocketAsyncEventArgs sArgsConnect = new SocketAsyncEventArgs() { RemoteEndPoint = _endPoint };
        sArgsConnect.Completed += (o, e) =>
        {
            if (e.SocketError == SocketError.Success)
            {
                SocketAsyncEventArgs sArgs = new SocketAsyncEventArgs() { RemoteEndPoint = _endPoint };
                sArgs.Completed +=
                    new EventHandler<SocketAsyncEventArgs>(sArgs_Completed);
                sArgs.SetBuffer(buffer, 0, buffer.Length);
                sArgs.UserToken = buffer;
                _socket.SendAsync(sArgs);
            }
        };
        _socket.ConnectAsync(sArgsConnect);

    }

    void sArgs_Completed(object sender, SocketAsyncEventArgs e)
    {
        if (e.SocketError == SocketError.Success)
        {
            byte[] buffer = (byte[])e.Buffer;
            SocketAsyncEventArgs sArgs = new SocketAsyncEventArgs();
            sArgs.RemoteEndPoint = e.RemoteEndPoint;

            sArgs.SetBuffer(buffer, 0, buffer.Length);
            sArgs.Completed += (o, a) =>
            {
                if (a.SocketError == SocketError.Success)
                {
                    byte[] timeData = a.Buffer;

                    ulong hTime = 0;
                    ulong lTime = 0;

                    for (var i = 40; i <= 43; ++i)
                        hTime = hTime << 8 | buffer[i];
                    for (var i = 44; i <= 47; ++i)
                        lTime = lTime << 8 | buffer[i];
                    ulong milliseconds = (hTime * 1000 + (lTime * 1000) / 0x100000000L);

                    TimeSpan timeSpan =
                        TimeSpan.FromTicks((long)milliseconds * TimeSpan.TicksPerMillisecond);
                    var currentTime = new DateTime(1900, 1, 1) + timeSpan;
                    OnTimeReceived(currentTime);

                }
            };
            _socket.ReceiveAsync(sArgs);
        }
    }
}

Usage :

public partial class MainPage : PhoneApplicationPage
{
    private NtpClient _ntpClient;
    public MainPage()
    {
        InitializeComponent();
        _ntpClient = new NtpClient();
        _ntpClient.TimeReceived += new EventHandler<NtpClient.TimeReceivedEventArgs>(_ntpClient_TimeReceived);
    }

    void _ntpClient_TimeReceived(object sender, NtpClient.TimeReceivedEventArgs e)
    {
        this.Dispatcher.BeginInvoke(() =>
                                        {
                                            txtCurrentTime.Text = e.CurrentTime.ToLongTimeString();
                                            txtSystemTime.Text = DateTime.Now.ToUniversalTime().ToLongTimeString();
                                        });
    }

    private void UpdateTimeButton_Click(object sender, RoutedEventArgs e)
    {
        _ntpClient.RequestTime();
    }
}

Code for printf function in C

Here's the GNU version of printf... you can see it passing in stdout to vfprintf:

__printf (const char *format, ...)
{
   va_list arg;
   int done;

   va_start (arg, format);
   done = vfprintf (stdout, format, arg);
   va_end (arg);

   return done;
}

See here.

Here's a link to vfprintf... all the formatting 'magic' happens here.

The only thing that's truly 'different' about these functions is that they use varargs to get at arguments in a variable length argument list. Other than that, they're just traditional C. (This is in contrast to Pascal's printf equivalent, which is implemented with specific support in the compiler... at least it was back in the day.)

Html.ActionLink as a button or an image, not a link

<li><a href="@Url.Action(  "View", "Controller" )"><i class='fa fa-user'></i><span>Users View</span></a></li>

To display an icon with the link

What is the Regular Expression For "Not Whitespace and Not a hyphen"

Which programming language are you using? May be you just need to escape the backslash like "[^\\s-]"

ThreeJS: Remove object from scene

If your element is not directly on you scene go back to Parent to remove it

  function removeEntity(object) {
        var selectedObject = scene.getObjectByName(object.name);
        selectedObject.parent.remove( selectedObject );
    }

Non-resolvable parent POM for Could not find artifact and 'parent.relativePath' points at wrong local POM

In my case, the reason was a simple typo.

<parent>
    <groupId>org.sringframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>2.1.5.RELEASE</version>
</parent>

A missing character in the groupId org.s(p)ringframework lead to this error.

CSS smooth bounce animation

Here is code not using the percentage in the keyframes. Because you used percentages the animation does nothing a long time.

  • 0% translate 0px
  • 20% translate 0px
  • etc.

How does this example work:

  1. We set an animation. This is a short hand for animation properties.
  2. We immediately start the animation since we use from and to in the keyframes. from is = 0% and to is = 100%
  3. We can now control how fast it will bounce by setting the animation time: animation: bounce 1s infinite alternate; the 1s is how long the animation will last.

_x000D_
_x000D_
.ball {_x000D_
  margin-top: 50px;_x000D_
  border-radius: 50%;_x000D_
  width: 50px;_x000D_
  height: 50px;_x000D_
  background-color: cornflowerblue;_x000D_
  border: 2px solid #999;_x000D_
  animation: bounce 1s infinite alternate;_x000D_
  -webkit-animation: bounce 1s infinite alternate;_x000D_
}_x000D_
@keyframes bounce {_x000D_
  from {_x000D_
    transform: translateY(0px);_x000D_
  }_x000D_
  to {_x000D_
    transform: translateY(-15px);_x000D_
  }_x000D_
}_x000D_
@-webkit-keyframes bounce {_x000D_
  from {_x000D_
    transform: translateY(0px);_x000D_
  }_x000D_
  to {_x000D_
    transform: translateY(-15px);_x000D_
  }_x000D_
}
_x000D_
<div class="ball"></div>
_x000D_
_x000D_
_x000D_

Could not install packages due to an EnvironmentError: [Errno 13]

This also happens to me when I try to install the opencv-python package:

installation attempt

I can fix it with command line

python3 -m pip install {name of package} --user

When I try to install the said package, the command becomes:

python3 -m pip install opencv-python --user

Resulting in this:

result

Make TextBox uneditable

Using the TextBox.ReadOnly property

TextBox.ReadOnly = true;

For a Non-Grey background you can change the TextBox.BackColor property to SystemColors.Window Color

textBox.BackColor = System.Drawing.SystemColors.Window;

When this property is set to true, the contents of the control cannot be changed by the user at runtime. With this property set to true, you can still set the value of the Text property in code. You can use this feature instead of disabling the control with the Enabled property to allow the contents to be copied and ToolTips to be shown.

git - remote add origin vs remote set-url origin

  • When you run git remote add origin [email protected]:User/UserRepo.git, then a new remote created named origin.
  • When you run git remote set-url origin [email protected]:User/UserRepo.git,git searches for existing remote having name origin and change it's remote repository url. If git unable to find any remote having name origin, It raise an error fatal: No such remote 'origin'.

If you are going to create a new repository then use git remote add origin [email protected]:User/UserRepo.git to add remote.

Delete entire row if cell contains the string X

This was alluded to in another comment, but you could try something like this.

Sub FilterAndDelete()

Application.DisplayAlerts = False 

     With Sheet1 'Change this to your sheet name

         .AutoFilterMode = False   
         .Range("A3:K3").AutoFilter
         .Range("A3:K3").AutoFilter Field:=5, Criteria1:="none"
         .UsedRange.Offset(1, 0).Resize(ActiveSheet.UsedRange.Rows.Count - 1).Rows.Delete 

     End With

Application.DisplayAlerts = True

End Sub

I haven't tested this and it is from memory, so it may require some tweaking but it should get the job done without looping through thousands of rows. You'll need to remove the 11-Jul so that UsedRange is correct or change the offset to 2 rows instead of 1 in the .Offset(1,0).

Generally, before I do .Delete I will run the macro with .Select instead of the Delete that way I can be sure the correct range will be deleted, that may be worth doing to check to ensure the appropriate range is being deleted.

Round integers to the nearest 10

About the round(..) function returning a float

That float (double-precision in Python) is always a perfect representation of an integer, as long as it's in the range [-253..253]. (Pedants pay attention: it's not two's complement in doubles, so the range is symmetric about zero.)

See the discussion here for details.

iPhone 6 and 6 Plus Media Queries

You have to target screen size using media query for different screen size.

for iphone:

@media only screen 
    and (min-device-width : 375px) 
    and (max-device-width : 667px) 
    and (orientation : landscape) 
    and (-webkit-min-device-pixel-ratio : 2)
{ }

@media only screen 
    and (min-device-width : 375px) 
    and (max-device-width : 667px) 
    and (orientation : portrait) 
    and (-webkit-min-device-pixel-ratio : 2)
{ }

and for desktop version:

@media only screen (max-width: 1080){

}

What is a mutex?

Mutex: Mutex stands for Mutual Exclusion. It means only one process/thread can enter into critical section at a given time. In concurrent programming multiple threads/process updating the shared resource (any variable, shared memory etc.) may lead to some unexpected result. ( As the result depends upon the which thread/process gets the first access).

In order to avoid such an unexpected result we need some synchronization mechanism, which ensures that only one thread/process gets access to such a resource at a time.

pthread library provides support for Mutex.

typedef union
{
  struct __pthread_mutex_s
  {
    ***int __lock;***
    unsigned int __count;
    int __owner;
#ifdef __x86_64__
    unsigned int __nusers;
#endif
int __kind;
#ifdef __x86_64__
    short __spins;
    short __elision;
    __pthread_list_t __list;
# define __PTHREAD_MUTEX_HAVE_PREV      1
# define __PTHREAD_SPINS             0, 0
#else
    unsigned int __nusers;
    __extension__ union
    {
      struct
      {
        short __espins;
        short __elision;
# define __spins __elision_data.__espins
# define __elision __elision_data.__elision
# define __PTHREAD_SPINS         { 0, 0 }
      } __elision_data;
      __pthread_slist_t __list;
    };
#endif

This is the structure for mutex data type i.e pthread_mutex_t. When mutex is locked, __lock set to 1. When it is unlocked __lock set to 0.

This ensure that no two processes/threads can access the critical section at same time.

Using NotNull Annotation in method argument

@Nullable and @NotNull do nothing on their own. They are supposed to act as Documentation tools.

The @Nullable Annotation reminds you about the necessity to introduce an NPE check when:

  1. Calling methods that can return null.
  2. Dereferencing variables (fields, local variables, parameters) that can be null.

The @NotNull Annotation is, actually, an explicit contract declaring the following:

  1. A method should not return null.
  2. A variable (like fields, local variables, and parameters) cannot should not hold null value.

For example, instead of writing:

/**
 * @param aX should not be null
 */
public void setX(final Object aX ) {
    // some code
}

You can use:

public void setX(@NotNull final Object aX ) {
    // some code
}

Additionally, @NotNull is often checked by ConstraintValidators (eg. in spring and hibernate).

The @NotNull annotation doesn't do any validation on its own because the annotation definition does not provide any ConstraintValidator type reference.

For more info see:

  1. Bean validation
  2. NotNull.java
  3. Constraint.java
  4. ConstraintValidator.java

How to include files outside of Docker's build context?

I had this same issue with a project and some data files that I wasn't able to move inside the repo context for HIPAA reasons. I ended up using 2 Dockerfiles. One builds the main application without the stuff I needed outside the container and publishes that to internal repo. Then a second dockerfile pulls that image and adds the data and creates a new image which is then deployed and never stored anywhere. Not ideal, but it worked for my purposes of keeping sensitive information out of the repo.

Eclipse DDMS error "Can't bind to local 8600 for debugger"

On my mac from a terminal:

$ ./adb kill-server
$ ./adb start-server
* daemon not running. starting it now on port 5037 *
* daemon started successfully *

I opened the eclipse and set the ddms port to 5037. it works fine.

enter image description here

python: restarting a loop

You may want to consider using a different type of loop where that logic is applicable, because it is the most obvious answer.

perhaps a:

i=2
while i < n:
    if something:
       do something
       i += 1
    else: 
       do something else  
       i = 2 #restart the loop  

What does int argc, char *argv[] mean?

argc is the number of arguments being passed into your program from the command line and argv is the array of arguments.

You can loop through the arguments knowing the number of them like:

for(int i = 0; i < argc; i++)
{
    // argv[i] is the argument at index i
}

How to list all the roles existing in Oracle database?

Got the answer :

SELECT * FROM DBA_ROLES;

getString Outside of a Context or Activity

Unfortunately, the only way you can access any of the string resources is with a Context (i.e. an Activity or Service). What I've usually done in this case, is to simply require the caller to pass in the context.

How to get the html of a div on another page with jQuery ajax?

Unfortunately an ajax request gets the entire file, but you can filter the content once it's retrieved:

$.ajax({
   url:href,
   type:'GET',
   success: function(data) {
       var content = $('<div>').append(data).find('#content');
       $('#content').html( content );
   }
});

Note the use of a dummy element as find() only works with descendants, and won't find root elements.

or let jQuery filter it for you:

$('#content').load(href + ' #IDofDivToFind');

I'm assuming this isn't a cross domain request, as that won't work, only pages on the same domain.

Java using enum with switch statement

The enums should not be qualified within the case label like what you have NDroid.guideView.GUIDE_VIEW_SEVEN_DAY, instead you should remove the qualification and use GUIDE_VIEW_SEVEN_DAY

Open Jquery modal dialog on click event

$(function() {

$('#clickMe').click(function(event) {
    var mytext = $('#myText').val();

    $('<div id="dialog">'+mytext+'</div>').appendTo('body');        
    event.preventDefault();

        $("#dialog").dialog({                   
            width: 600,
            modal: true,
            close: function(event, ui) {
                $("#dialog").hide();
                }
            });
    }); //close click
});

Better to use .hide() instead of .remove(). With .remove() it returns undefined if you have pressed the link once, then close the modal and if you press the modal link again, it returns undefined with .remove.

With .hide() it doesnt and it works like a breeze. Ty for the snippet in the first hand!

How to calculate difference in hours (decimal) between two dates in SQL Server?

SELECT DATEDIFF(hh, firstDate, secondDate) FROM tableName WHERE ...

How to tell if a string contains a certain character in JavaScript?

Use a regular expression to accomplish this.

function isAlphanumeric( str ) {
 return /^[0-9a-zA-Z]+$/.test(str);
}

CSS / HTML Navigation and Logo on same line

1) you can float the image to the left:

<img style="float:left" src="http://i.imgur.com/hCrQkJi.png">

2)You can use an HTML table to place elements on one line.

Code below

  <div class="navigation-bar">
    <div id="navigation-container">
      <table>
        <tr>
          <td><img src="http://i.imgur.com/hCrQkJi.png"></td>
          <td><ul>
            <li><a href="#">Home</a></li>
            <li><a href="#">Projects</a></li>
            <li><a href="#">About</a></li>
            <li><a href="#">Services</a></li>
            <li><a href="#">Get in Touch</a></li>
        </ul>
          </td></tr></table>
    </div>

mongodb group values by multiple fields

Using aggregate function like below :

[
{$group: {_id : {book : '$book',address:'$addr'}, total:{$sum :1}}},
{$project : {book : '$_id.book', address : '$_id.address', total : '$total', _id : 0}}
]

it will give you result like following :

        {
            "total" : 1,
            "book" : "book33",
            "address" : "address90"
        }, 
        {
            "total" : 1,
            "book" : "book5",
            "address" : "address1"
        }, 
        {
            "total" : 1,
            "book" : "book99",
            "address" : "address9"
        }, 
        {
            "total" : 1,
            "book" : "book1",
            "address" : "address5"
        }, 
        {
            "total" : 1,
            "book" : "book5",
            "address" : "address2"
        }, 
        {
            "total" : 1,
            "book" : "book3",
            "address" : "address4"
        }, 
        {
            "total" : 1,
            "book" : "book11",
            "address" : "address77"
        }, 
        {
            "total" : 1,
            "book" : "book9",
            "address" : "address3"
        }, 
        {
            "total" : 1,
            "book" : "book1",
            "address" : "address15"
        }, 
        {
            "total" : 2,
            "book" : "book1",
            "address" : "address2"
        }, 
        {
            "total" : 3,
            "book" : "book1",
            "address" : "address1"
        }

I didn't quite get your expected result format, so feel free to modify this to one you need.

Recommended website resolution (width and height)?

I target the 1024 pixel monitors (but don't use 100% of that space). I've given up on those with 800x600. I'd rather punish the few with outdated hardware by making them scroll if they need to, versus punishing everyone with new equipment by wasting space.

I suppose it depends on your audience, and the nature of you app though.

UINavigationBar custom back button without title

Create a UILabel with the title you want for your root view controller and assign it to the view controller's navigationItem.titleView.

Now set the title to an empty string and the next view controller you push will have a back button without text.

self.navigationItem.titleView = titleLabel; //Assuming you've created titleLabel above
self.title = @"";

How can I convert a string with dot and comma into a float in Python

Just remove the , with replace():

float("123,456.908".replace(',',''))

How to use JavaScript variables in jQuery selectors?

  1. ES6 String Template

    Here is a simple way if you don't need IE/EDGE support

    $(`input[id=${x}]`).hide();
    

    or

    $(`input[id=${$(this).attr("name")}]`).hide();
    

    This is a es6 feature called template string

    _x000D_
    _x000D_
        (function($) {_x000D_
            $("input[type=button]").click(function() {_x000D_
                var x = $(this).attr("name");_x000D_
                $(`input[id=${x}]`).toggle(); //use hide instead of toggle_x000D_
            });_x000D_
        })(jQuery);
    _x000D_
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
        <input type="text" id="bx" />_x000D_
        <input type="button" name="bx" value="1" />_x000D_
        <input type="text" id="by" />_x000D_
        <input type="button" name="by" value="2" />_x000D_
    _x000D_
     
    _x000D_
    _x000D_
    _x000D_


  1. String Concatenation

    If you need IE/EDGE support use

    $("#" + $(this).attr("name")).hide();
    

    _x000D_
    _x000D_
        (function($) {_x000D_
            $("input[type=button]").click(function() {_x000D_
                $("#" + $(this).attr("name")).toggle(); //use hide instead of toggle_x000D_
            });_x000D_
        })(jQuery);
    _x000D_
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
        <input type="text" id="bx" />_x000D_
        <input type="button" name="bx" value="1" />_x000D_
        <input type="text" id="by" />_x000D_
        <input type="button" name="by" value="2" />_x000D_
    _x000D_
     
    _x000D_
    _x000D_
    _x000D_


  1. Selector in DOM as data attribute

    This is my preferred way as it makes you code really DRY

    // HTML
    <input type="text"   id="bx" />
    <input type="button" data-input-sel="#bx" value="1" class="js-hide-onclick"/>
    
    //JS
    $($(this).data("input-sel")).hide();
    

    _x000D_
    _x000D_
        (function($) {_x000D_
            $(".js-hide-onclick").click(function() {_x000D_
                $($(this).data("input-sel")).toggle(); //use hide instead of toggle_x000D_
            });_x000D_
        })(jQuery);
    _x000D_
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
        <input type="text" id="bx" />_x000D_
        <input type="button" data-input-sel="#bx" value="1" class="js-hide-onclick" />_x000D_
        <input type="text" id="by" />_x000D_
        <input type="button" data-input-sel="#by" value="2" class="js-hide-onclick" />_x000D_
    _x000D_
     
    _x000D_
    _x000D_
    _x000D_

How to form tuple column from two columns in Pandas

In [10]: df
Out[10]:
          A         B       lat      long
0  1.428987  0.614405  0.484370 -0.628298
1 -0.485747  0.275096  0.497116  1.047605
2  0.822527  0.340689  2.120676 -2.436831
3  0.384719 -0.042070  1.426703 -0.634355
4 -0.937442  2.520756 -1.662615 -1.377490
5 -0.154816  0.617671 -0.090484 -0.191906
6 -0.705177 -1.086138 -0.629708  1.332853
7  0.637496 -0.643773 -0.492668 -0.777344
8  1.109497 -0.610165  0.260325  2.533383
9 -1.224584  0.117668  1.304369 -0.152561

In [11]: df['lat_long'] = df[['lat', 'long']].apply(tuple, axis=1)

In [12]: df
Out[12]:
          A         B       lat      long                             lat_long
0  1.428987  0.614405  0.484370 -0.628298      (0.484370195967, -0.6282975278)
1 -0.485747  0.275096  0.497116  1.047605      (0.497115615839, 1.04760475074)
2  0.822527  0.340689  2.120676 -2.436831      (2.12067574274, -2.43683074367)
3  0.384719 -0.042070  1.426703 -0.634355      (1.42670326172, -0.63435462504)
4 -0.937442  2.520756 -1.662615 -1.377490     (-1.66261469102, -1.37749004179)
5 -0.154816  0.617671 -0.090484 -0.191906  (-0.0904840623396, -0.191905582481)
6 -0.705177 -1.086138 -0.629708  1.332853     (-0.629707821728, 1.33285348929)
7  0.637496 -0.643773 -0.492668 -0.777344   (-0.492667604075, -0.777344111021)
8  1.109497 -0.610165  0.260325  2.533383        (0.26032456699, 2.5333825651)
9 -1.224584  0.117668  1.304369 -0.152561     (1.30436900612, -0.152560909725)

Is it possible to focus on a <div> using JavaScript focus() function?

document.getElementById('tries').scrollIntoView() works. This works better than window.location.hash when you have fixed positioning.

Remove android default action bar

You can set it as a no title bar theme in the activity's xml in the AndroidManifest

    <activity 
        android:name=".AnActivity"
        android:label="@string/a_string"
        android:theme="@android:style/Theme.NoTitleBar">
    </activity>

Integer expression expected error in shell script

If you are using -o (or -a), it needs to be inside the brackets of the test command:

if [ "$age" -le "7" -o "$age" -ge " 65" ]

However, their use is deprecated, and you should use separate test commands joined by || (or &&) instead:

if [ "$age" -le "7" ] || [ "$age" -ge " 65" ]

Make sure the closing brackets are preceded with whitespace, as they are technically arguments to [, not simply syntax.

In bash and some other shells, you can use the superior [[ expression as shown in kamituel's answer. The above will work in any POSIX-compliant shell.

Sum of values in an array using jQuery

You don't need jQuery. You can do this using a for loop:

var total = 0;
for (var i = 0; i < someArray.length; i++) {
    total += someArray[i] << 0;
}

Related:

Android Studio: Drawable Folder: How to put Images for Multiple dpi?

The standard procedures are:

  1. Choose Project > app > scr > main
  2. Right click "res", choose "New" and choose "Android resource directory" Step 2
  3. In the opened dialog, at Resource Type choose "drawable" Step 3
  4. In the list Available qualifier choose Density, then click the right arrow at the middle. Step 4
  5. Choose the Density that you like then press OK Step 5

How to add an extra language input to Android?

Don't agree with post above. I have a Hero with only English available and I want Spanish.

I installed MoreLocale 2, and it has lots of different languages (Dutch among them). I choose Spanish, Sense UI restarted and EVERYTHING in my phone changed to Spanish: menus, settings, etc. The keyboard predictive text defaulted to Spanish and started suggesting words in Spanish. This means, somewhere within the OS there is a Spanish dictionary hidden and MoreLocale made it available.

The problem is that English is still the only option available in keyboard input language so I can switch to English but can't switch back to Spanish unless I restart Sense UI, which takes a couple of minutes so not a very practical solution.

Still looking for an easier way to do it so please help.

smtpclient " failure sending mail"

For us, everything was fine, emails are very small and not a lot of them are sent and sudently it gave this error. It appeared that a technicien installed ASTARO which was preventing email to be sent. and we were getting this error so yes the error is a bit cryptic but I hope this could help others.

How to insert a data table into SQL Server database table?

    //best way to deal with this is sqlbulkcopy 
    //but if you dont like it you can do it like this
    //read current sql table in an adapter
    //add rows of datatable , I have mentioned a simple way of it
    //and finally updating changes

    Dim cnn As New SqlConnection("connection string")        
    cnn.Open()
    Dim cmd As New SqlCommand("select * from  sql_server_table", cnn)
    Dim da As New SqlDataAdapter(cmd)       
    Dim ds As New DataSet()
    da.Fill(ds, "sql_server_table")
    Dim cb As New SqlCommandBuilder(da)        

    //for each datatable row
    ds.Tables("sql_server_table").Rows.Add(COl1, COl2)

    da.Update(ds, "sql_server_table")

How to get Bitmap from an Uri?

try
{
    Bitmap bitmap = MediaStore.Images.Media.getBitmap(c.getContentResolver() , Uri.parse(paths));
}
catch (Exception e) 
{
    //handle exception
}

and yes path must be in a format of like this

file:///mnt/sdcard/filename.jpg

com.jcraft.jsch.JSchException: UnknownHostKey

setting known host is better than setting fingure print value.

When you set known host, try to manually ssh (very first time, before application runs) from the box the application runs.

Execute another jar in a Java program

If the jar's in your classpath, and you know its Main class, you can just invoke the main class. Using DITA-OT as an example:

import org.dita.dost.invoker.CommandLineInvoker;
....
CommandLineInvoker.main('-f', 'html5', '-i', 'samples/sequence.ditamap', '-o', 'test')

Note this will make the subordinate jar share memory space and a classpath with your jar, with all the potential for interference that can cause. If you don't want that stuff polluted, you have other options, as mentioned above - namely:

  • create a new ClassLoader with the jar in it. This is more safe; you can at least isolate the new jar's knowledge to a core classloader if you architect things with the knowledge that you'll be making use of alien jars. It's what we do in my shop for our plugins system; the main application is a tiny shell with a ClassLoader factory, a copy of the API, and knowledge that the real application is the first plugin for which it should build a ClassLoader. Plugins are a pair of jars - interface and implementation - that are zipped up together. The ClassLoaders all share all the interfaces, while each ClassLoader only has knowledge of its own implementation. The stack's a little complex, but it passes all tests and works beautifully.
  • use Runtime.getRuntime.exec(...) (which wholly isolates the jar, but has the normal "find the application", "escape your strings right", "platform-specific WTF", and "OMG System Threads" pitfalls of running system commands.

TypeError: 'type' object is not subscriptable when indexing in to a dictionary

Normally Python throws NameError if the variable is not defined:

>>> d[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'd' is not defined

However, you've managed to stumble upon a name that already exists in Python.

Because dict is the name of a built-in type in Python you are seeing what appears to be a strange error message, but in reality it is not.

The type of dict is a type. All types are objects in Python. Thus you are actually trying to index into the type object. This is why the error message says that the "'type' object is not subscriptable."

>>> type(dict)
<type 'type'>
>>> dict[0]
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'type' object is not subscriptable

Note that you can blindly assign to the dict name, but you really don't want to do that. It's just going to cause you problems later.

>>> dict = {1:'a'}
>>> type(dict)
<class 'dict'>
>>> dict[1]
'a'

The true source of the problem is that you must assign variables prior to trying to use them. If you simply reorder the statements of your question, it will almost certainly work:

d = {1: "walk1.png", 2: "walk2.png", 3: "walk3.png"}
m1 = pygame.image.load(d[1])
m2 = pygame.image.load(d[2])
m3 = pygame.image.load(d[3])
playerxy = (375,130)
window.blit(m1, (playerxy))

How do I git rm a file without deleting it from disk?

I tried experimenting with the answers given. My personal finding came out to be:

git rm -r --cached .

And then

git add .

This seemed to make my working directory nice and clean. You can put your fileName in place of the dot.

How to paste into a terminal?

Mostly likely middle click your mouse.

Or try Shift + Insert.

It all depends on terminal used and X11-config for mouse.

Regex Explanation ^.*$

  • ^ matches position just before the first character of the string
  • $ matches position just after the last character of the string
  • . matches a single character. Does not matter what character it is, except newline
  • * matches preceding match zero or more times

So, ^.*$ means - match, from beginning to end, any character that appears zero or more times. Basically, that means - match everything from start to end of the string. This regex pattern is not very useful.

Let's take a regex pattern that may be a bit useful. Let's say I have two strings The bat of Matt Jones and Matthew's last name is Jones. The pattern ^Matt.*Jones$ will match Matthew's last name is Jones. Why? The pattern says - the string should start with Matt and end with Jones and there can be zero or more characters (any characters) in between them.

Feel free to use an online tool like https://regex101.com/ to test out regex patterns and strings.

Python Matplotlib Y-Axis ticks on Right Side of Plot

Use ax.yaxis.tick_right()

for example:

from matplotlib import pyplot as plt

f = plt.figure()
ax = f.add_subplot(111)
ax.yaxis.tick_right()
plt.plot([2,3,4,5])
plt.show()

enter image description here

sqlplus: error while loading shared libraries: libsqlplus.so: cannot open shared object file: No such file or directory

You can try usage:

# echo "/usr/lib/oracle/12.2/client64/lib" > /etc/ld.so.conf.d/oracle.conf
# ldconfig

This problem are because oracleinstant client not configure shared library.

How to print instances of a class using print()?

If you're in a situation like @Keith you could try:

print(a.__dict__)

It goes against what I would consider good style but if you're just trying to debug then it should do what you want.

Difference between | and || or & and && for comparison

& and | are binary operators while || and && are boolean.

The big difference:
(1 & 2) is 0, false
(1 && 2) is true

Transaction count after EXECUTE indicates a mismatching number of BEGIN and COMMIT statements. Previous count = 1, current count = 0

For me after extensive debugging the fix was a simple missing throw; statement in the catch after the rollback. Without it this ugly error message is what you end up with.

begin catch
    if @@trancount > 0 rollback transaction;
    throw; --allows capture of useful info when an exception happens within the transaction
end catch

Remove composer

During the installation you got a message Composer successfully installed to: ... this indicates where Composer was installed. But you might also search for the file composer.phar on your system.

Then simply:

  1. Delete the file composer.phar.
  2. Delete the Cache Folder:
    • Linux: /home/<user>/.composer
    • Windows: C:\Users\<username>\AppData\Roaming\Composer

That's it.

jQuery - Redirect with post data

There is a JQuery plug-in that accomplishes pretty much what you're trying to do: https://github.com/mgalante/jquery.redirect/blob/master/jquery.redirect.js.

After including JQuery and the jquery.redirect.min.js plug-in, you can simply do something like this:

$().redirect('demo.php', {'arg1': 'value1', 'arg2': 'value2'});

Use the following code on newer JQuery versions instead:

$.redirect('demo.php', {'arg1': 'value1', 'arg2': 'value2'});

Hope this helps!

How to define two angular apps / modules in one page?

I made a POC for an Angular application using multiple modules and router-outlets to nest sub apps in a single page app. You can get the source code at: https://github.com/AhmedBahet/ng-sub-apps

Hope this will help

How to generate a range of numbers between two numbers?

This is what I do, it's pretty fast and flexible and not a lot of code.

DECLARE @count  int =   65536;
DECLARE @start  int =   11;
DECLARE @xml    xml =   REPLICATE(CAST('<x/>' AS nvarchar(max)), @count);

; WITH GenerateNumbers(Num) AS
(
    SELECT  ROW_NUMBER() OVER (ORDER BY @count) + @start - 1
    FROM    @xml.nodes('/x') X(T)
)
SELECT  Num
FROM    GenerateNumbers;

Note that (ORDER BY @count) is a dummy. It doesn't do anything but ROW_NUMBER() requires an ORDER BY.

Edit: I realized that the original question was to get a range from x to y. My script can be modified like this to get a range:

DECLARE @start  int =   5;
DECLARE @end    int =   21;
DECLARE @xml    xml =   REPLICATE(CAST('<x/>' AS nvarchar(max)), @end - @start + 1);

; WITH GenerateNumbers(Num) AS
(
    SELECT  ROW_NUMBER() OVER (ORDER BY @end) + @start - 1
    FROM    @xml.nodes('/x') X(T)
)
SELECT  Num
FROM    GenerateNumbers;

HTML: How to make a submit button with text + image in it?

You're really close to the answer yourself

<button type="submit">
<img src="save.gif" alt="Save icon"/>
<br/>
Save
</button>

Or, you can just remove the type-attribute

<button>
<img src="save.gif" alt="Save icon"/>
<br/>
Save
</button>

Swift: Determine iOS Screen size

In Swift 3.0

let screenSize = UIScreen.main.bounds
let screenWidth = screenSize.width
let screenHeight = screenSize.height

In older swift: Do something like this:

let screenSize: CGRect = UIScreen.mainScreen().bounds

then you can access the width and height like this:

let screenWidth = screenSize.width
let screenHeight = screenSize.height

if you want 75% of your screen's width you can go:

let screenWidth = screenSize.width * 0.75

Swift 4.0

// Screen width.
public var screenWidth: CGFloat {
    return UIScreen.main.bounds.width
}

// Screen height.
public var screenHeight: CGFloat {
    return UIScreen.main.bounds.height
}

In Swift 5.0

let screenSize: CGRect = UIScreen.main.bounds

Handlebars.js Else If

in handlebars first register a function like below

Handlebars.registerHelper('ifEquals', function(arg1, arg2, options) {
    return (arg1 == arg2) ? options.fn(this) : options.inverse(this);
});

you can register more than one function . to add another function just add like below

Handlebars.registerHelper('calculate', function(operand1, operator, operand2) {
    let result;
    switch (operator) {
        case '+':
            result = operand1 + operand2;            
            break;
        case '-':
            result = operand1 - operand2;            
            break;
        case '*':
            result = operand1 * operand2;            
            break;
        case '/':
            result = operand1 / operand2;            
            break;
    }

    return Number(result);
});

and in HTML page just include the conditions like

    {{#ifEquals day "mon"}}
    <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
      //html code goes here
    </html>
   {{else ifEquals day "sun"}}
    <html>
     //html code goes here
    </html>
   {{else}}
     //html code goes here
   {{/ifEquals}}

Add a dependency in Maven

You'll have to do this in two steps:

1. Give your JAR a groupId, artifactId and version and add it to your repository.

If you don't have an internal repository, and you're just trying to add your JAR to your local repository, you can install it as follows, using any arbitrary groupId/artifactIds:

mvn install:install-file -DgroupId=com.stackoverflow... -DartifactId=yourartifactid... -Dversion=1.0 -Dpackaging=jar -Dfile=/path/to/jarfile

You can also deploy it to your internal repository if you have one, and want to make this available to other developers in your organization. I just use my repository's web based interface to add artifacts, but you should be able to accomplish the same thing using mvn deploy:deploy-file ....

2. Update dependent projects to reference this JAR.

Then update the dependency in the pom.xml of the projects that use the JAR by adding the following to the element:

<dependencies>
    ...
    <dependency>
        <groupId>com.stackoverflow...</groupId>
        <artifactId>artifactId...</artifactId>
        <version>1.0</version>
    </dependency>
    ...
</dependencies>

How to tell a Mockito mock object to return something different the next time it is called?

Or, even cleaner:

when(mockFoo.someMethod()).thenReturn(obj1, obj2);

How to find which git branch I am on when my disk is mounted on other server

.git/HEAD contains the path of the current ref, the working directory is using as HEAD.