Programs & Examples On #Hash collision

How can I make a DateTimePicker display an empty string?

In case anybody has an issue with setting datetimepicker control to blank during the form load event, and then show the current date as needed, here is an example:

MAKE SURE THAT CustomFormat = " " has same number of spaces (at least one space) in both methods

Private Sub setDateTimePickerBlank(ByVal dateTimePicker As DateTimePicker)    

    dateTimePicker.Visible = True
    dateTimePicker.Format = DateTimePickerFormat.Custom
    dateTimePicker.CustomFormat = "    " 
End Sub


Private Sub dateTimePicker_MouseHover(ByVal sender As Object, ByVal e As 
                    System.EventArgs) Handles dateTimePicker.MouseHover

    Dim dateTimePicker As DateTimePicker = CType(sender, DateTimePicker)
    If dateTimePicker.Text = "    " Then
        dateTimePicker.Text = Format(DateTime.Now, "MM/dd/yyyy")
    End If
End Sub

Printing Exception Message in java

try {
} catch (javax.script.ScriptException ex) {
// System.out.println(ex.getMessage());
}

Getting String Value from Json Object Android

This might help you.

Java:

JSONArray arr = new JSONArray(result);
JSONObject jObj = arr.getJSONObject(0);
String date = jObj.getString("NeededString");

Kotlin:

val jsonArray = JSONArray(result)
val jsonObject: JSONObject = jsonArray.getJSONObject(0)
val date= jsonObject.get("NeededString")
  • getJSONObject(index). In above example 0 represents index.

How can I download a specific Maven artifact in one command line?

LATEST is deprecated, try with range [,)

./mvnw org.apache.maven.plugins:maven-dependency-plugin:3.1.1:get \  
-DremoteRepositories=repoId::default::https://nexus/repository/maven-releases/ \
"-Dartifact=com.acme:foo:[,)"

Should we pass a shared_ptr by reference or by value?

There was a recent blog post: https://medium.com/@vgasparyan1995/pass-by-value-vs-pass-by-reference-to-const-c-f8944171e3ce

So the answer to this is: Do (almost) never pass by const shared_ptr<T>&.
Simply pass the underlying class instead.

Basically the only reasonable parameters types are:

  • shared_ptr<T> - Modify and take ownership
  • shared_ptr<const T> - Don't modify, take ownership
  • T& - Modify, no ownership
  • const T& - Don't modify, no ownership
  • T - Don't modify, no ownership, Cheap to copy

As @accel pointed out in https://stackoverflow.com/a/26197326/1930508 the advice from Herb Sutter is:

Use a const shared_ptr& as a parameter only if you’re not sure whether or not you’ll take a copy and share ownership

But in how many cases are you not sure? So this is a rare situation

How to use ArrayAdapter<myClass>

Subclass the ArrayAdapter and override the method getView() to return your own view that contains the contents that you want to display.

NodeJS / Express: what is "app.use"?

Each app.use(middleware) is called every time a request is sent to the server.

The result of a query cannot be enumerated more than once

Try explicitly enumerating the results by calling ToList().

Change

foreach (var item in query)

to

foreach (var item in query.ToList())

Applying Comic Sans Ms font style

The httpd dæmon on OpenBSD uses the following stylesheet for all of its error messages, which presumably covers all the Comic Sans variations on non-Windows systems:

http://openbsd.su/src/usr.sbin/httpd/server_http.c#server_abort_http

810    style = "body { background-color: white; color: black; font-family: "
811        "'Comic Sans MS', 'Chalkboard SE', 'Comic Neue', sans-serif; }\n"
812        "hr { border: 0; border-bottom: 1px dashed; }\n";

E.g., try this:

font-family: 'Comic Sans MS', 'Chalkboard SE', 'Comic Neue', sans-serif;

How to delete row based on cell value

if you want to delete rows based on some specific cell value. let suppose we have a file containing 10000 rows, and a fields having value of NULL. and based on that null value want to delete all those rows and records.

here are some simple tip. First open up Find Replace dialog, and on Replace tab, make all those cell containing NULL values with Blank. then press F5 and select the Blank option, now right click on the active sheet, and select delete, then option for Entire row.

it will delete all those rows based on cell value of containing word NULL.

How can I check if PostgreSQL is installed or not via Linux script?

If it is debian based.

aptitude show postgresql | grep State

But I guess you can just try to launch it with some flag like --version, that simply prints some info and exits.

Updated using "service postgres status". Try:

service postgres status
if [ "$?" -gt "0" ]; then
  echo "Not installed".
else
  echo "Intalled"
fi

How to remove decimal part from a number in C#

Use Decimal.Truncate

It removes the fractional part from the decimal.

int i = (int)Decimal.Truncate(12.66m)

what is the difference between ajax and jquery and which one is better?

They aren't comparable.

Ajax (Asynchronous Javascript and XML) is a subset of javascript. Ajax is way for the client-side browser to communicate with the server (for example: retrieve data from a database) without having to perform a page refresh.

jQuery is a javascript library that standardizes the javascript differences cross-browser. jQuery includes some ajax functions.

Entity Framework The underlying provider failed on Open

I get this exception often while running on my development machine, especially after I make a code change, rebuild the code, then execute an associated web page(s). However, the problem goes away for me if I bump up the CommandTimeout parameter to 120 seconds or more (e.g., set context.Database.CommandTimeout = 120 before the LINQ statement). While this was originally asked 3 years ago, it may help someone looking for an answer. My theory is VisualStudio takes time to convert the built binary libraries to machine code, and times out when attempting to connect to SQL Server following that just-in-time compile.

how to customize `show processlist` in mysql?

If you use old version of MySQL you can always use \P combined with some nice piece of awk code. Interesting example here

http://www.dbasquare.com/2012/03/28/how-to-work-with-a-long-process-list-in-mysql/

Isn't it exactly what you need?

How to send password using sftp batch file

If you are generating a heap of commands to be run, then call that script from a terminal, you can try the following.

sftp login@host < /path/to/command/list

You will then be asked to enter your password (as per normal) however all the commands in the script run after that.

This is clearly not a completely automated option that can be used in a cron job, but it can be used from a terminal.

Storing JSON in database vs. having a new column for each key

Updated 4 June 2017

Given that this question/answer have gained some popularity, I figured it was worth an update.

When this question was originally posted, MySQL had no support for JSON data types and the support in PostgreSQL was in its infancy. Since 5.7, MySQL now supports a JSON data type (in a binary storage format), and PostgreSQL JSONB has matured significantly. Both products provide performant JSON types that can store arbitrary documents, including support for indexing specific keys of the JSON object.

However, I still stand by my original statement that your default preference, when using a relational database, should still be column-per-value. Relational databases are still built on the assumption of that the data within them will be fairly well normalized. The query planner has better optimization information when looking at columns than when looking at keys in a JSON document. Foreign keys can be created between columns (but not between keys in JSON documents). Importantly: if the majority of your schema is volatile enough to justify using JSON, you might want to at least consider if a relational database is the right choice.

That said, few applications are perfectly relational or document-oriented. Most applications have some mix of both. Here are some examples where I personally have found JSON useful in a relational database:

  • When storing email addresses and phone numbers for a contact, where storing them as values in a JSON array is much easier to manage than multiple separate tables

  • Saving arbitrary key/value user preferences (where the value can be boolean, textual, or numeric, and you don't want to have separate columns for different data types)

  • Storing configuration data that has no defined schema (if you're building Zapier, or IFTTT and need to store configuration data for each integration)

I'm sure there are others as well, but these are just a few quick examples.

Original Answer

If you really want to be able to add as many fields as you want with no limitation (other than an arbitrary document size limit), consider a NoSQL solution such as MongoDB.

For relational databases: use one column per value. Putting a JSON blob in a column makes it virtually impossible to query (and painfully slow when you actually find a query that works).

Relational databases take advantage of data types when indexing, and are intended to be implemented with a normalized structure.

As a side note: this isn't to say you should never store JSON in a relational database. If you're adding true metadata, or if your JSON is describing information that does not need to be queried and is only used for display, it may be overkill to create a separate column for all of the data points.

How can I record a Video in my Android App.?

For the benefit of searchers, this example will give you an active preview, with a start/stop button for recording. It was modified from this android blog and seems fairly reliable.

java class (VideoWithSurfaceVw)

package <<your packagename here>>;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;

import android.app.Activity;
import android.content.Context;
import android.hardware.Camera;
import android.media.CamcorderProfile;
import android.media.MediaRecorder;
import android.os.Bundle;
import android.view.SurfaceHolder;
import android.view.SurfaceView;
import android.view.View;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.Toast;

public class VideoWithSurfaceVw extends Activity{

    // Adapted from http://sandyandroidtutorials.blogspot.co.uk/2013/05/android-video-capture-tutorial.html


    private Camera myCamera;
    private MyCameraSurfaceView myCameraSurfaceView;
    private MediaRecorder mediaRecorder;

    Button myButton;
    SurfaceHolder surfaceHolder;
    boolean recording;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        recording = false;

        setContentView(R.layout.activity_video_with_surface_vw);

        //Get Camera for preview
        myCamera = getCameraInstance();
        if(myCamera == null){
            Toast.makeText(VideoWithSurfaceVw.this,
                    "Fail to get Camera",
                    Toast.LENGTH_LONG).show();
        }

        myCameraSurfaceView = new MyCameraSurfaceView(this, myCamera);
        FrameLayout myCameraPreview = (FrameLayout)findViewById(R.id.videoview);
        myCameraPreview.addView(myCameraSurfaceView);

        myButton = (Button)findViewById(R.id.mybutton);
        myButton.setOnClickListener(myButtonOnClickListener);
    }

    Button.OnClickListener myButtonOnClickListener
            = new Button.OnClickListener(){

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub

            try{
                if(recording){
                    // stop recording and release camera
                    mediaRecorder.stop();  // stop the recording
                    releaseMediaRecorder(); // release the MediaRecorder object

                    //Exit after saved
                    //finish();
                    myButton.setText("REC");
                    recording = false;
                }else{

                    //Release Camera before MediaRecorder start
                    releaseCamera();

                    if(!prepareMediaRecorder()){
                        Toast.makeText(VideoWithSurfaceVw.this,
                                "Fail in prepareMediaRecorder()!\n - Ended -",
                                Toast.LENGTH_LONG).show();
                        finish();
                    }

                    mediaRecorder.start();
                    recording = true;
                    myButton.setText("STOP");
                }
            }catch (Exception ex){
                ex.printStackTrace();
            }
        }};

    private Camera getCameraInstance(){
        // TODO Auto-generated method stub
        Camera c = null;
        try {
            c = Camera.open(); // attempt to get a Camera instance
        }
        catch (Exception e){
            // Camera is not available (in use or does not exist)
        }
        return c; // returns null if camera is unavailable
    }

    private String getFileName_CustomFormat() {
        SimpleDateFormat sdfDate = new SimpleDateFormat("yyyy-MM-dd HH_mm_ss");
        Date now = new Date();
        String strDate = sdfDate.format(now);
        return strDate;
    }


    private boolean prepareMediaRecorder(){
        myCamera = getCameraInstance();
        mediaRecorder = new MediaRecorder();

        myCamera.unlock();
        mediaRecorder.setCamera(myCamera);

        mediaRecorder.setAudioSource(MediaRecorder.AudioSource.CAMCORDER);
        mediaRecorder.setVideoSource(MediaRecorder.VideoSource.CAMERA);

        mediaRecorder.setProfile(CamcorderProfile.get(CamcorderProfile.QUALITY_HIGH));



        mediaRecorder.setOutputFile("/sdcard/" + getFileName_CustomFormat() + ".mp4");
        //mediaRecorder.setOutputFile("/sdcard/myvideo1.mp4");
        mediaRecorder.setMaxDuration(60000); // Set max duration 60 sec.
        mediaRecorder.setMaxFileSize(50000000); // Set max file size 50M

        mediaRecorder.setPreviewDisplay(myCameraSurfaceView.getHolder().getSurface());

        try {
            mediaRecorder.prepare();
        } catch (IllegalStateException e) {
            releaseMediaRecorder();
            return false;
        } catch (IOException e) {
            releaseMediaRecorder();
            return false;
        }
        return true;

    }

    @Override
    protected void onPause() {
        super.onPause();
        releaseMediaRecorder();       // if you are using MediaRecorder, release it first
        releaseCamera();              // release the camera immediately on pause event
    }

    private void releaseMediaRecorder(){
        if (mediaRecorder != null) {
            mediaRecorder.reset();   // clear recorder configuration
            mediaRecorder.release(); // release the recorder object
            mediaRecorder = new MediaRecorder();
            myCamera.lock();           // lock camera for later use
        }
    }

    private void releaseCamera(){
        if (myCamera != null){
            myCamera.release();        // release the camera for other applications
            myCamera = null;
        }
    }

    public class MyCameraSurfaceView extends SurfaceView implements SurfaceHolder.Callback{

        private SurfaceHolder mHolder;
        private Camera mCamera;

        public MyCameraSurfaceView(Context context, Camera camera) {
            super(context);
            mCamera = camera;

            // Install a SurfaceHolder.Callback so we get notified when the
            // underlying surface is created and destroyed.
            mHolder = getHolder();
            mHolder.addCallback(this);
            // deprecated setting, but required on Android versions prior to 3.0
            mHolder.setType(SurfaceHolder.SURFACE_TYPE_PUSH_BUFFERS);
        }

        @Override
        public void surfaceChanged(SurfaceHolder holder, int format, int weight,
                                   int height) {
            // If your preview can change or rotate, take care of those events here.
            // Make sure to stop the preview before resizing or reformatting it.

            if (mHolder.getSurface() == null){
                // preview surface does not exist
                return;
            }

            // stop preview before making changes
            try {
                mCamera.stopPreview();
            } catch (Exception e){
                // ignore: tried to stop a non-existent preview
            }

            // make any resize, rotate or reformatting changes here

            // start preview with new settings
            try {
                mCamera.setPreviewDisplay(mHolder);
                mCamera.startPreview();

            } catch (Exception e){
            }
        }

        @Override
        public void surfaceCreated(SurfaceHolder holder) {
            // TODO Auto-generated method stub
            // The Surface has been created, now tell the camera where to draw the preview.
            try {
                mCamera.setPreviewDisplay(holder);
                mCamera.startPreview();
            } catch (IOException e) {
            }
        }

        @Override
        public void surfaceDestroyed(SurfaceHolder holder) {
            // TODO Auto-generated method stub

        }
    }
}

activity (activity_video_with_surface_vw)

<RelativeLayout android:id="@+id/surface_camera"     
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:layout_centerInParent="true"
android:layout_weight="1"
>

<RelativeLayout
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    >
    <FrameLayout
        android:id="@+id/videoview"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"/>
    <Button
        android:id="@+id/mybutton"
        android:layout_width="100dp"
        android:layout_height="50dp"
        android:layout_centerHorizontal="true"
        android:layout_alignParentBottom="true"
        android:text="REC"
        android:textSize="12dp"/>
</RelativeLayout>

</RelativeLayout>

First char to upper case

Regular Expressions (abbreviated "regex" or "reg-ex") is a string that defines a search pattern.

What replaceFirst() does is it uses the regular expression provided in the parameters and replaces the first result from the search with whatever you pass in as the other parameter.

What you want to do is convert the string to an array using the String class' charAt() method, and then use Character.toUpperCase() to change the character to upper case (obviously). Your code would look like this:

char first = Character.toUpperCase(userIdea.charAt(0));
betterIdea = first + userIdea.substring(1);

Or, if you feel comfortable with more complex, one-lined java code:

betterIdea = Character.toUpperCase(userIdea.charAt(0)) + userIdea.substring(1);

Both of these do the same thing, which is converting the first character of userIdea to an upper case character.

How to get 0-padded binary representation of an integer in java?

This is an old trick, create a string with 16 0's then append the trimmed binary string you got from String.format("%s", Integer.toBinaryString(1)) and use the right-most 16 characters, lopping off any leading 0's. Better yet, make a function that lets you specify how long of a binary string you want. Of course there are probably a bazillion other ways to accomplish this including libraries, but I'm adding this post to help out a friend :)

public class BinaryPrinter {

    public static void main(String[] args) {
        System.out.format("%d in binary is %s\n", 1, binaryString(1, 4));
        System.out.format("%d in binary is %s\n", 128, binaryString(128, 8));
        System.out.format("%d in binary is %s\n", 256, binaryString(256, 16));
    }

    public static String binaryString( final int number, final int binaryDigits ) {
        final String pattern = String.format( "%%0%dd", binaryDigits );
        final String padding = String.format( pattern, 0 );
        final String response = String.format( "%s%s", padding, Integer.toBinaryString(number) );

        System.out.format( "\npattern = '%s'\npadding = '%s'\nresponse = '%s'\n\n", pattern, padding, response );

        return response.substring( response.length() - binaryDigits );
    }
}

How to set time to midnight for current day?

Try this:

DateTime Date = DateTime.Now.AddHours(-DateTime.Now.Hour).AddMinutes(-DateTime.Now.Minute)
   .AddSeconds(-DateTime.Now.Second);

Output will be like:

07/29/2015 00:00:00

Tried to Load Angular More Than Once

The problem could occur when $templateCacheProvider is trying to resolve a template in the templateCache or through your project directory that does not exist

Example:

templateUrl: 'views/wrongPathToTemplate'

Should be:

templateUrl: 'views/home.html'

How do I add comments to package.json for npm install?

DISCLAIMER: you probably should not use this hack. See comments below.


Here is another hack for adding comments in JSON. Since:

{"a": 1, "a": 2}

Is equivalent to

{"a": 2}

You can do something like:

{
  "devDependencies": "'mocha' not needed as should be globally installed",
  "devDependencies" :  {
    "should": "*"
  }
}

how to download image from any web page in java

You are looking for a web crawler. You can use JSoup to do this, here is basic example

What's the PowerShell syntax for multiple values in a switch statement?

A slight modification to derekerdmann's post to meet the original request using regex's alternation operator "|"(pipe).

It's also slightly easier for regex newbies to understand and read.

Note that while using regex, if you don't put the start of string character "^"(caret/circumflex) and/or end of string character "$"(dollar) then you may get unexpected/unintuitive behavior (like matching "yesterday" or "why").

Putting grouping characters "()"(parentheses) around the options reduces the need to put start and end of string characters for each option. Without them, you'll get possibly unexpected behavior if you're not savvy with regex. Of course, if you're not processing user input, but rather some set of known strings, it will be more readable without grouping and start and end of string characters.

switch -regex ($someString) #many have noted ToLower() here is redundant
{
        #processing user input
    "^(y|yes|indubitably)$" { "You entered Yes." }

        # not processing user input
    "y|yes|indubitably" { "Yes was the selected string" } 
    default { "You entered No." } 
}

C# ASP.NET Single Sign-On Implementation

UltimateSAML SSO is an OASIS SAML v1.x and v2.0 specifications compliant .NET toolkit. It offers an elegant and easy way to add support for Single Sign-On and Single-Logout SAML to your ASP.NET, ASP.NET MVC, ASP.NET Core, Desktop, and Service applications. The lightweight library helps you provide SSO access to cloud and intranet websites using a single credentials entry.

Detailed UltimateSAML SSO review can be found here

Apache POI error loading XSSFWorkbook class

If you have downloaded pio-3.17 On eclipse: right click on the project folder -> build path -> configure build path -> libraries -> add external jars -> add all the commons jar file from the "lib". It's worked for me.

How do I access store state in React Redux?

Import connect from react-redux and use it to connect the component with the state connect(mapStates,mapDispatch)(component)

import React from "react";
import { connect } from "react-redux";


const MyComponent = (props) => {
    return (
      <div>
        <h1>{props.title}</h1>
      </div>
    );
  }
}

Finally you need to map the states to the props to access them with this.props

const mapStateToProps = state => {
  return {
    title: state.title
  };
};
export default connect(mapStateToProps)(MyComponent);

Only the states that you map will be accessible via props

Check out this answer: https://stackoverflow.com/a/36214059/4040563

For further reading : https://medium.com/@atomarranger/redux-mapstatetoprops-and-mapdispatchtoprops-shorthand-67d6cd78f132

ECONNREFUSED error when connecting to mongodb from node.js

OK, this was another case of not being truly forthcoming in the info I posted above. My node.js app was very simple, but I was including another couple lines in my node.js code that apparently caused this issue.

Specifically, I had another variable declared which was calling some other code that made a separate database call using incorrect db info. This is why, when using Xinzz's code, the console log error seemed not to change. It wasn't actually the mongoose.connect command that was throwing the error!

Lesson learned, localize the problem and comment out unrelated code! Sorry guys, I knew this was me being dumb.

/etc/apt/sources.list" E212: Can't open file for writing

It might be possible that the file you are accessing has a swap copy (or swap version) already there in the same directory

Hence first see whether a hidden file exists or not.

For example, see for the following type of files

.system.conf.swp

By using the command

ls -a

And then, delete it using ...

rm .system.conf.swp

Usually, I recommend to start using super user privileges using ...

sudo su

Shell script to capture Process ID and kill it if exist

This works good for me.

PID=`ps -eaf | grep syncapp | grep -v grep | awk '{print $2}'`
if [[ "" !=  "$PID" ]]; then
  echo "killing $PID"
  kill -9 $PID
fi

How to make UIButton's text alignment center? Using IB

For Swift 3.0

btn.titleLabel?.textAlignment = .center

Pure CSS to make font-size responsive based on dynamic amount of characters

You might be interested in the calc approach:

font-size: calc(4vw + 4vh + 2vmin);

done. Tweak values till matches your taste.

Source: https://codepen.io/CrocoDillon/pen/fBJxu

How to animate button in android?

import android.view.View;
import android.view.animation.Animation;
import android.view.animation.Transformation;

public class HeightAnimation extends Animation {
    protected final int originalHeight;
    protected final View view;
    protected float perValue;

    public HeightAnimation(View view, int fromHeight, int toHeight) {
        this.view = view;
        this.originalHeight = fromHeight;
        this.perValue = (toHeight - fromHeight);
    }

    @Override
    protected void applyTransformation(float interpolatedTime, Transformation t) {
        view.getLayoutParams().height = (int) (originalHeight + perValue * interpolatedTime);
        view.requestLayout();
    }

    @Override
    public boolean willChangeBounds() {
        return true;
    }
}

uss to:

HeightAnimation heightAnim = new HeightAnimation(view, view.getHeight(), viewPager.getHeight() - otherView.getHeight());
heightAnim.setDuration(1000);
view.startAnimation(heightAnim);

PHP prepend leading zero before single digit number, on-the-fly

You can use sprintf: http://php.net/manual/en/function.sprintf.php

<?php
$num = 4;
$num_padded = sprintf("%02d", $num);
echo $num_padded; // returns 04
?>

It will only add the zero if it's less than the required number of characters.

Edit: As pointed out by @FelipeAls:

When working with numbers, you should use %d (rather than %s), especially when there is the potential for negative numbers. If you're only using positive numbers, either option works fine.

For example:

sprintf("%04s", 10); returns 0010
sprintf("%04s", -10); returns 0-10

Where as:

sprintf("%04d", 10); returns 0010
sprintf("%04d", -10); returns -010

Javascript receipt printing using POS Printer

EDIT: NOV 27th, 2017 - BROKEN LINKS

Links below about the posts written by David Kelley are broken.

There are cached versions of the repository, just add cache: before the URL in the Chrome Browser and hit enter.


This solution is only for Google Chrome and Chromium-based browsers.

EDIT:

(*)The links are broken. Fortunately I found this repository that contains the source of the post in the following markdown files: A | B

This link* explains how to make a Javascript Interface for ESC/POS printers using Chrome/Chromium USB API (1)(2). This link* explains how to Connect to USB devices using the chrome.usb.* API.

Add Auto-Increment ID to existing table?

Try this

ALTER TABLE `users` ADD `id` INT NOT NULL AUTO_INCREMENT;

for an existing primary key

Cancel a vanilla ECMAScript 6 Promise chain

@Michael Yagudaev 's answer works for me.

But the original answer did not chain the wrapped promise with .catch() to handle reject handling, here is my improvement on top of @Michael Yagudaev's answer:

const makeCancelablePromise = promise => {
  let hasCanceled = false;
  const wrappedPromise = new Promise((resolve, reject) => {
    promise
      .then(val => (hasCanceled ? reject({ isCanceled: true }) : resolve(val)))
      .catch(
        error => (hasCanceled ? reject({ isCanceled: true }) : reject(error))
      );
  });

  return {
    promise: wrappedPromise,
    cancel() {
      hasCanceled = true;
    }
  };
};

// Example Usage:
const cancelablePromise = makeCancelable(
  new Promise((rs, rj) => {
    /*do something*/
  })
);
cancelablePromise.promise.then(() => console.log('resolved')).catch(err => {
  if (err.isCanceled) {
    console.log('Wrapped promise canceled');
    return;
  }
  console.log('Promise was not canceled but rejected due to errors: ', err);
});
cancelablePromise.cancel();

Just disable scroll not hide it?

You can do it with Javascript:

// Classic JS
window.onscroll = function(ev) {
  ev.preventDefault();
}

// jQuery
$(window).scroll(function(ev) {
  ev.preventDefault();
}

And then disable it when your lightbox is closed.

But if your lightbox contains a scroll bar, you won't be able to scroll while it's open. This is because window contains both body and #lightbox. So you have to use an architecture like the following one:

<body>
  <div id="global"></div>
  <div id="lightbox"></div>
</body>

And then apply the onscroll event only on #global.

NodeJS - Error installing with NPM

I encountered the issue with the error:

gyp ERR! configure error

gyp ERR! stack Error: Can't find Python executable "python", you can set the PYTHON env variable.

Here is what I was doing and what finally worked.

Disclaimer: I am just getting my hands into Node, Angular after many years in the Java, Linux world among others...

Environment Description: Windows 8.1 64-bit; Cygwin; cygwin bash shell

Command used that led to error: npm install -g karma

Error: gyp ERR! configure error gyp ERR! stack Error: Can't find Python executable "python", you can set the PYT HON env variable.

Discovery: 'which python' on bash shell clearly shows '/usr/bin/python'. Now that is annoying!

Solution: This is only applicable to those using the environment similar to what I have, i.e. using cygwin and bash shell. Hope it helps in other environments as well but keep in mind that your kettle of tea may look a little different than mine.

  1. Firstly, need to set the $PYTHON shell env variable in .bashrc using the explicit windows path to the python executable and not the unix like root path (/usr/bin) used by cygwin.
  2. Secondly, and this one took a lot of trial/error and here's the gotcha! Cygwin installs python under /usr/bin (which is really a mirror of /bin on windows) with the version, i.e. (in my system) /usr/bin/python2.7.exe and then adds a link /usr/bin/python --> python2.7.exe. The problem is that gyp cannot follow this link and keeps giving the annoying error that it cannot find python even though you can find it just fine from the shell command line.
  3. With the above background now add the following line to your .bashrc

export PYTHON="C:/cygwin64/bin/python2.7.exe (or whatever is the version on your system)"

  1. Now source your .bashrc from your home directory (on cygwin)--> 'source .bashrc'

You should be fine now and gyp will find the python executable.

I hope this helps someone stumbling on the same or similar issue.

Security of REST authentication schemes

REST means working with the standards of the web, and the standard for "secure" transfer on the web is SSL. Anything else is going to be kind of funky and require extra deployment effort for clients, which will have to have encryption libraries available.

Once you commit to SSL, there's really nothing fancy required for authentication in principle. You can again go with web standards and use HTTP Basic auth (username and secret token sent along with each request) as it's much simpler than an elaborate signing protocol, and still effective in the context of a secure connection. You just need to be sure the password never goes over plain text; so if the password is ever received over a plain text connection, you might even disable the password and mail the developer. You should also ensure the credentials aren't logged anywhere upon receipt, just as you wouldn't log a regular password.

HTTP Digest is a safer approach as it prevents the secret token being passed along; instead, it's a hash the server can verify on the other end. Though it may be overkill for less sensitive applications if you've taken the precautions mentioned above. After all, the user's password is already transmitted in plain-text when they log in (unless you're doing some fancy JavaScript encryption in the browser), and likewise their cookies on each request.

Note that with APIs, it's better for the client to be passing tokens - randomly generated strings - instead of the password the developer logs into the website with. So the developer should be able to log into your site and generate new tokens that can be used for API verification.

The main reason to use a token is that it can be replaced if it's compromised, whereas if the password is compromised, the owner could log into the developer's account and do anything they want with it. A further advantage of tokens is you can issue multiple tokens to the same developers. Perhaps because they have multiple apps or because they want tokens with different access levels.

(Updated to cover implications of making the connection SSL-only.)

How to scroll to top of page with JavaScript/jQuery?

First add a blank anchor tag to the place where you want to go

<a href="#topAnchor"></a> 

Now add a function in header section

 function GoToTop() {
            var urllocation = location.href;
            if (urllocation.indexOf("#topAnchor") > -1) {
                window.location.hash = "topAnchor";
            } else {
                return false;
            }
        }

finally add an onload event to the body tag

<body onload="GoToTop()">

Setting public class variables

If you are going to follow the examples given (using getter/setter or setting it in the constructor) change it to private since those are ways to control what is set in the variable.

It doesn't make sense to keep the property public with all those things added to the class.

How do I use a regex in a shell script?

I think this is what you want:

REGEX_DATE='^\d{2}[/-]\d{2}[/-]\d{4}$'

echo "$1" | grep -P -q $REGEX_DATE
echo $?

I've used the -P switch to get perl regex.

Is there a simple way that I can sort characters in a string in alphabetical order

You can use this

string x = "ABCGH"

char[] charX = x.ToCharArray();

Array.Sort(charX);

This will sort your string.

How do I bind a List<CustomObject> to a WPF DataGrid?

You should do it in the xaml code:

<DataGrid ItemsSource="{Binding list}" [...]>
  [...]
</DataGrid>

I would advise you to use an ObservableCollection as your backing collection, as that would propagate changes to the datagrid, as it implements INotifyCollectionChanged.

Auto start print html page using javascript

For me, adding <script>window.print();</script> to the end of the page worked.


I didn't need the type="text/javascript" attribute, or even for the page to be wrapped in a <body> tag. However, all of my previous attempts to intuitively use the answers suggested here, of just writing window.onload=window.print or longer versions such as window.onload=()=>window.print(); did not work, and of course calling print on the newly created window does not wait for the contents to load.

How to build a 'release' APK in Android Studio?

Follow this steps:

-Build
-Generate Signed Apk
-Create new

Then fill up "New Key Store" form. If you wand to change .jnk file destination then chick on destination and give a name to get Ok button. After finishing it you will get "Key store password", "Key alias", "Key password" Press next and change your the destination folder. Then press finish, thats all. :)

enter image description here

enter image description here enter image description here

enter image description here enter image description here

Hot to get all form elements values using jQuery?

The answer already been accepted, I just write a short technique for the same purpose.

var fieldPair = '';
$(":input").each(function(){
fieldPair += $(this).attr("name") + ':' + $(this).val() + ';';
});

console.log(fieldPair);

Commit only part of a file in Git

You can use git add --interactive or git add -p <file>, and then git commit (not git commit -a); see Interactive mode in git-add manpage, or simply follow instructions.

Modern Git has also git commit --interactive (and git commit --patch, which is shortcut to patch option in interactive commit).

If you prefer doing it from GUI, you can use git-gui. You can simply mark chunks which you want to have included in commit. I personally find it easier than using git add -i. Other git GUIs, like QGit or GitX, might also have this functionality as well.

How to get parameters from a URL string?

A much more secure answer that I'm surprised is not mentioned here yet:

filter_input

So in the case of the question you can use this to get an email value from the URL get parameters:

$email = filter_input( INPUT_GET, 'email', FILTER_SANITIZE_EMAIL );

For other types of variables, you would want to choose a different/appropriate filter such as FILTER_SANITIZE_STRING.

I suppose this answer does more than exactly what the question asks for - getting the raw data from the URL parameter. But this is a one-line shortcut that is the same result as this:

$email = $_GET['email'];
$email = filter_var( $email, FILTER_SANITIZE_EMAIL );

Might as well get into the habit of grabbing variables this way.

Bootstrap fixed header and footer with scrolling body-content area in fluid-container

Add the following css to disable the default scroll:

body {
    overflow: hidden;
}

And change the #content css to this to make the scroll only on content body:

#content {
    max-height: calc(100% - 120px);
    overflow-y: scroll;
    padding: 0px 10%;
    margin-top: 60px;
}

See fiddle here.


Edit:

Actually, I'm not sure what was the issue you were facing, since it seems that your css is working. I have only added the HTML and the header css statement:

_x000D_
_x000D_
html {_x000D_
  height: 100%;_x000D_
}_x000D_
html body {_x000D_
  height: 100%;_x000D_
  overflow: hidden;_x000D_
}_x000D_
html body .container-fluid.body-content {_x000D_
  position: absolute;_x000D_
  top: 50px;_x000D_
  bottom: 30px;_x000D_
  right: 0;_x000D_
  left: 0;_x000D_
  overflow-y: auto;_x000D_
}_x000D_
header {_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    right: 0;_x000D_
    top: 0;_x000D_
    background-color: #4C4;_x000D_
    height: 50px;_x000D_
}_x000D_
footer {_x000D_
    position: absolute;_x000D_
    left: 0;_x000D_
    right: 0;_x000D_
    bottom: 0;_x000D_
    background-color: #4C4;_x000D_
    height: 30px;_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.2/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<header></header>_x000D_
<div class="container-fluid body-content">_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
  Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>Lorem Ipsum<br/>_x000D_
</div>_x000D_
<footer></footer>
_x000D_
_x000D_
_x000D_

ImportError: cannot import name main when running pip --version command in windows7 32 bit

Even though the original question seems to be from 2015, this 'bug' seems to affect users installing pip-10.0.0 as well.

The workaround is not to modify pip, however to change the way pip is called. Instead of calling /usr/bin/pip call pip via Python itself. For example, instead of the below:

pip install <package>

If from Python version 2 (or default Python binary is called python) do :

python -m pip install <package>

or if from Python version 3:

python3 -m pip install <package> 

Tomcat started in Eclipse but unable to connect to http://localhost:8085/

You need to start the Apache Tomcat services.

Win+R --> sevices.msc

Then, search for Apache Tomcat and right click on it and click on Start. This will start the service and then you'll be able to see Apache Tomcat homepage on the localhost .

Return Max Value of range that is determined by an Index & Match lookup

You don't need an index match formula. You can use this array formula. You have to press CTL + SHIFT + ENTER after you enter the formula.

=MAX(IF((A1:A6=A10)*(B1:B6=B10),C1:F6))

SNAPSHOT

enter image description here

Adobe Reader Command Line Reference

I found this:

http://www.robvanderwoude.com/commandlineswitches.php#Acrobat

Open a PDF file with navigation pane active, zoom out to 50%, and search for and highlight the word "batch":

AcroRd32.exe /A "zoom=50&navpanes=1=OpenActions&search=batch" PdfFile

How do I center text vertically and horizontally in Flutter?

Text alignment center property setting only horizontal alignment.

enter image description here

I used below code to set text vertically and horizontally center.

enter image description here

Code:

      child: Center(
        child: Text(
          "Hello World",
          textAlign: TextAlign.center,
        ),
      ),

How to determine whether a Pandas Column contains a particular value

Or use Series.tolist or Series.any:

>>> s = pd.Series(list('abc'))
>>> s
0    a
1    b
2    c
dtype: object
>>> 'a' in s.tolist()
True
>>> (s=='a').any()
True

Series.tolist makes a list about of a Series, and the other one i am just getting a boolean Series from a regular Series, then checking if there are any Trues in the boolean Series.

The APR based Apache Tomcat Native library was not found on the java.library.path

Regarding the original question asked in the title ...

  • sudo apt-get install libtcnative-1

  • or if you are on RHEL Linux yum install tomcat-native

The documentation states you need http://tomcat.apache.org/native-doc/

  • sudo apt-get install libapr1.0-dev libssl-dev
  • or RHEL yum install apr-devel openssl-devel

how to draw smooth curve through N points using javascript HTML5 canvas?

I decide to add on, rather than posting my solution to another post. Below are the solution that I build, may not be perfect, but so far the output are good.

Important: it will pass through all the points!

If you have any idea, to make it better, please share to me. Thanks.

Here are the comparison of before after:

enter image description here

Save this code to HTML to test it out.

_x000D_
_x000D_
    <!DOCTYPE html>_x000D_
    <html>_x000D_
    <body>_x000D_
     <canvas id="myCanvas" width="1200" height="700" style="border:1px solid #d3d3d3;">Your browser does not support the HTML5 canvas tag.</canvas>_x000D_
     <script>_x000D_
      var cv = document.getElementById("myCanvas");_x000D_
      var ctx = cv.getContext("2d");_x000D_
    _x000D_
      function gradient(a, b) {_x000D_
       return (b.y-a.y)/(b.x-a.x);_x000D_
      }_x000D_
    _x000D_
      function bzCurve(points, f, t) {_x000D_
       //f = 0, will be straight line_x000D_
       //t suppose to be 1, but changing the value can control the smoothness too_x000D_
       if (typeof(f) == 'undefined') f = 0.3;_x000D_
       if (typeof(t) == 'undefined') t = 0.6;_x000D_
    _x000D_
       ctx.beginPath();_x000D_
       ctx.moveTo(points[0].x, points[0].y);_x000D_
    _x000D_
       var m = 0;_x000D_
       var dx1 = 0;_x000D_
       var dy1 = 0;_x000D_
    _x000D_
       var preP = points[0];_x000D_
       for (var i = 1; i < points.length; i++) {_x000D_
        var curP = points[i];_x000D_
        nexP = points[i + 1];_x000D_
        if (nexP) {_x000D_
         m = gradient(preP, nexP);_x000D_
         dx2 = (nexP.x - curP.x) * -f;_x000D_
         dy2 = dx2 * m * t;_x000D_
        } else {_x000D_
         dx2 = 0;_x000D_
         dy2 = 0;_x000D_
        }_x000D_
        ctx.bezierCurveTo(preP.x - dx1, preP.y - dy1, curP.x + dx2, curP.y + dy2, curP.x, curP.y);_x000D_
        dx1 = dx2;_x000D_
        dy1 = dy2;_x000D_
        preP = curP;_x000D_
       }_x000D_
       ctx.stroke();_x000D_
      }_x000D_
    _x000D_
      // Generate random data_x000D_
      var lines = [];_x000D_
      var X = 10;_x000D_
      var t = 40; //to control width of X_x000D_
      for (var i = 0; i < 100; i++ ) {_x000D_
       Y = Math.floor((Math.random() * 300) + 50);_x000D_
       p = { x: X, y: Y };_x000D_
       lines.push(p);_x000D_
       X = X + t;_x000D_
      }_x000D_
    _x000D_
      //draw straight line_x000D_
      ctx.beginPath();_x000D_
      ctx.setLineDash([5]);_x000D_
      ctx.lineWidth = 1;_x000D_
      bzCurve(lines, 0, 1);_x000D_
    _x000D_
      //draw smooth line_x000D_
      ctx.setLineDash([0]);_x000D_
      ctx.lineWidth = 2;_x000D_
      ctx.strokeStyle = "blue";_x000D_
      bzCurve(lines, 0.3, 1);_x000D_
     </script>_x000D_
    </body>_x000D_
    </html>
_x000D_
_x000D_
_x000D_

Groovy - How to compare the string?

In Groovy, null == null gets a true. At runtime, you won't know what happened. In Java, == is comparing two references.

This is a cause of big confusion in basic programming, Whether it is safe to use equals. At runtime, a null.equals will give an exception. You've got a chance to know what went wrong.

Especially, you get two values from keys not exist in map(s), == makes them equal.

SQL Update Multiple Fields FROM via a SELECT Statement

You can use:

UPDATE s SET
  s.Field1 = q.Field1,
  s.Field2 = q.Field2,
  (list of fields...)
FROM (
  SELECT Field1, Field2, (list of fields...)
  FROM ProfilerTest.dbo.BookingDetails 
  WHERE MyID=@MyID
) q
WHERE s.MyID2=@ MyID2

How to remove a character at the end of each line in unix

This Perl code removes commas at the end of the line:

perl -pe 's/,$//' file > file.nocomma

This variation still works if there is whitespace after the comma:

perl -lpe 's/,\s*$//' file > file.nocomma

This variation edits the file in-place:

perl -i -lpe 's/,\s*$//' file

This variation edits the file in-place, and makes a backup file.bak:

perl -i.bak -lpe 's/,\s*$//' file

Open soft keyboard programmatically

Please follow the below code. I am sure your problem will be solved.

if (imm != null){
        imm.toggleSoftInput(InputMethodManager.SHOW_FORCED,0);
   } 

Javascript - get array of dates between 2 dates

  1. Generate an array of years:

    const DAYS = () => {
     const days = []
     const dateStart = moment()
     const dateEnd = moment().add(30, ‘days')
     while (dateEnd.diff(dateStart, ‘days') >= 0) {
      days.push(dateStart.format(‘D'))
      dateStart.add(1, ‘days')
     }
     return days
    }
    console.log(DAYS())
    
  2. Generate an arrays for month:

            const MONTHS = () => {
             const months = []
             const dateStart = moment()
             const dateEnd = moment().add(12, ‘month')
             while (dateEnd.diff(dateStart, ‘months') >= 0) {
              months.push(dateStart.format(‘M'))
              dateStart.add(1, ‘month')
             }
             return months
            }
            console.log(MONTHS())
    
  3. Generate an arrays for days:

            const DAYS = () => {
             const days = []
             const dateStart = moment()
             const dateEnd = moment().add(30, ‘days')
             while (dateEnd.diff(dateStart, ‘days') >= 0) {
              days.push(dateStart.format(‘D'))
              dateStart.add(1, ‘days')
             }
             return days
            }
            console.log(DAYS())
    

jQuery posting JSON

You post JSON like this

$.ajax(url, {
    data : JSON.stringify(myJSObject),
    contentType : 'application/json',
    type : 'POST',
    ...

if you pass an object as settings.data jQuery will convert it to query parameters and by default send with the data type application/x-www-form-urlencoded; charset=UTF-8, probably not what you want

WELD-001408: Unsatisfied dependencies for type Customer with qualifiers @Default

You need to annotate your Customer class with @Named or @Model annotation:

package de.java2enterprise.onlineshop.model;
@Model
public class Customer {
    private String email;
    private String password;
}

or create/modify beans.xml:

<?xml version="1.0" encoding="UTF-8"?>
<beans xmlns="http://xmlns.jcp.org/xml/ns/javaee"
   xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
   xsi:schemaLocation="http://xmlns.jcp.org/xml/ns/javaee http://xmlns.jcp.org/xml/ns/javaee/beans_1_1.xsd"
   bean-discovery-mode="all">
</beans>

How can you get the Manifest Version number from the App's (Layout) XML variables?

Easiest solution is to use BuildConfig.

I use BuildConfig.VERSION_NAME in my application.

You can also use BuildConfig.VERSION_CODE to get version code.

How do I assert equality on two classes without an equals method?

I stumbled on a very similar case.

I wanted to compare on a test that an object had the same attribute values as another one, but methods like is(), refEq(), etc wouldn't work for reasons like my object having a null value in its id attribute.

So this was the solution I found (well, a coworker found):

import static org.apache.commons.lang.builder.CompareToBuilder.reflectionCompare;

assertThat(reflectionCompare(expectedObject, actualObject, new String[]{"fields","to","be","excluded"}), is(0));

If the value obtained from reflectionCompare is 0, it means they are equal. If it is -1 or 1, they differ on some attribute.

AttributeError: Can only use .dt accessor with datetimelike values

Your problem here is that to_datetime silently failed so the dtype remained as str/object, if you set param errors='coerce' then if the conversion fails for any particular string then those rows are set to NaT.

df['Date'] = pd.to_datetime(df['Date'], errors='coerce')

So you need to find out what is wrong with those specific row values.

See the docs

Powershell import-module doesn't find modules

I think that the Import-Module is trying to find the module in the default directory C:\Windows\System32\WindowsPowerShell\v1.0\Modules.

Try to put the full path, or copy it to C:\Windows\System32\WindowsPowerShell\v1.0\Modules

Styling a input type=number

For Mozilla

input[type=number] { 
    -moz-appearance: textfield;
    appearance: textfield;
    margin: 0; 
}

For Chrome

input[type=number]::-webkit-inner-spin-button, 
input[type=number]::-webkit-outer-spin-button { 
      -webkit-appearance: none; 
      margin: 0; 
}

iTunes Connect Screenshots Sizes for all iOS (iPhone/iPad/Apple Watch) devices

This answer is updated for Xcode 11.

App Store Connect currently asks for images in the following categories:

enter image description here

iPhone 6.5" Display

This is 1242 x 2688 pixels. You can create this size image using the iPhone 11 Pro Max simulator.

iPhone 5.5" Display

This is 1242 x 2208 pixels. You can create this size image using the iPhone 8 Plus simulator.

iPad Pro (3rd gen) 12.9" Display

That is 2048 x 2732 pixels. You can create this size image using the iPad Pro (12.9-inch) (3rd generation) simulator.

iPad Pro (2nd gen) 12.9" Display

That is 2048 x 2732 pixels. This is the exact same size as the iPad Pro (12.9-inch) (3rd generation), so most people can use the same screenshots here. But see this.

Notes

  • Use File > New Screen Shot (Command+S) in the simulator to save a screenshot to the desktop. On a real device press Sleep/Wake+Home on the iPhone/iPad (images available in Photo app)
  • The pixel dimensions above are the full screen portrait orientation sizes. You shouldn't include the status bar, so you can either paste background color over the status bar text and icons or crop them out and scale the image back up.
  • See this link for more details.

500.21 Bad module "ManagedPipelineHandler" in its module list

if it is IIS 8 go to control panel, turn windows features on/off and enable Bad "Named pipe activation" then restart IIS. Hope the same works with IIS 7

How to test an Oracle Stored Procedure with RefCursor return type?

I think this link will be enough for you. I found it when I was searching for the way to execute oracle procedures.

The link to the page

Short Description:

--cursor variable declaration 
variable Out_Ref_Cursor refcursor;
--execute procedure 
execute get_employees_name(IN_Variable,:Out_Ref_Cursor);
--display result referenced by ref cursor.
print Out_Ref_Cursor;

Automatically open default email client and pre-populate content

As described by RFC 6068, mailto allows you to specify subject and body, as well as cc fields. For example:

mailto:[email protected]?subject=Subject&body=message%20goes%20here

User doesn't need to click a link if you force it to be opened with JavaScript

window.location.href = "mailto:[email protected]?subject=Subject&body=message%20goes%20here";

Be aware that there is no single, standard way in which browsers/email clients handle mailto links (e.g. subject and body fields may be discarded without a warning). Also there is a risk that popup and ad blockers, anti-virus software etc. may silently block forced opening of mailto links.

How to cin Space in c++?

I thought I'd share the answer that worked for me. The previous line ended in a newline, so most of these answers by themselves didn't work. This did:

string title;
do {
  getline(cin, title);
} while (title.length() < 2);

That was assuming the input is always at least 2 characters long, which worked for my situation. You could also try simply comparing it to the string "\n".

_csv.Error: field larger than field limit (131072)

You can use read_csv from pandas to skip these lines.

import pandas as pd

data_df = pd.read_csv('data.csv', error_bad_lines=False)

Change the color of glyphicons to blue in some- but not at all places using Bootstrap 2

If it is only a bootstrap icon. Note that icons are under text or rather typography. Just add the text color class like this. E.g text-primary, text-info and so on and so forth to the icon class:

<i class="icon features-icon icons8-collaboration-2 text-primary"></i>
<i class="icon features-icon icons8-collaboration-2 text-secondary"></i>

Why do symbols like apostrophes and hyphens get replaced with black diamonds on my website?

Look at your actual html code and check that the weird symbols are not originating there. This issue came up when I started coding in Notepad++ halfway after coding in Notepad. It seems to me that the older version of Notepad I was using may have used different encoding to Notepad's++ UTF-8 encoding. After I transferred my code from Notepad to Notepad++, the apostrophes got replaced with weird symbols, so I simply had to remove the symbols from my Notepad++ code.

android: data binding error: cannot find symbol class

You must change your activity_contact_list to be binded - add layout tag as you did in content_contact_list. Don't forget, The root layout inside activity_contact_list must have an id for the Binding class to be generated and will be named ActivityContactListBinding (i.e. the name of the layout with camel casting instead of underscores).

Next, inside activity_contact_list, give <include layout="@layout/content_contact_list" /> an id, then you will have access for its binding instance through your ActivityContactListBinding instance.

Somthing like:

binding.contentContactList.setContact(user);

Let me know if it works.

Laravel: Get Object From Collection By Attribute

Laravel provides a method called keyBy which allows to set keys by given key in model.

$collection = $collection->keyBy('id');

will return the collection but with keys being the values of id attribute from any model.

Then you can say:

$desired_food = $foods->get(21); // Grab the food with an ID of 21

and it will grab the correct item without the mess of using a filter function.

Html.Partial vs Html.RenderPartial & Html.Action vs Html.RenderAction

Here is what I have found:

Use RenderAction when you do not have a model to send to the view and have a lot of html to bring back that doesn't need to be stored in a variable.

Use Action when you do not have a model to send to the view and have a little bit of text to bring back that needs to be stored in a variable.

Use RenderPartial when you have a model to send to the view and there will be a lot of html that doesn't need to be stored in a variable.

Use Partial when you have a model to send to the view and there will be a little bit of text that needs to be stored in a variable.

RenderAction and RenderPartial are faster.

How to call a method after bean initialization is complete?

You can use something like:

<beans>
    <bean id="myBean" class="..." init-method="init"/>
</beans>

This will call the "init" method when the bean is instantiated.

What is AF_INET, and why do I need it?

AF_INET is an address family that is used to designate the type of addresses that your socket can communicate with (in this case, Internet Protocol v4 addresses). When you create a socket, you have to specify its address family, and then you can only use addresses of that type with the socket. The Linux kernel, for example, supports 29 other address families such as UNIX (AF_UNIX) sockets and IPX (AF_IPX), and also communications with IRDA and Bluetooth (AF_IRDA and AF_BLUETOOTH, but it is doubtful you'll use these at such a low level).

For the most part, sticking with AF_INET for socket programming over a network is the safest option. There is also AF_INET6 for Internet Protocol v6 addresses.

Hope this helps,

Get values from a listbox on a sheet

The accepted answer doesn't cut it because if a user de-selects a row the list is not updated accordingly.

Here is what I suggest instead:

Private Sub CommandButton2_Click()
    Dim lItem As Long

    For lItem = 0 To ListBox1.ListCount - 1
        If ListBox1.Selected(lItem) = True Then
            MsgBox(ListBox1.List(lItem))
        End If
    Next
End Sub

Courtesy of http://www.ozgrid.com/VBA/multi-select-listbox.htm

How does one convert a grayscale image to RGB in OpenCV (Python)?

I am promoting my comment to an answer:

The easy way is:

You could draw in the original 'frame' itself instead of using gray image.

The hard way (method you were trying to implement):

backtorgb = cv2.cvtColor(gray,cv2.COLOR_GRAY2RGB) is the correct syntax.

App.Config file in console application C#

For .NET Core, add System.Configuration.ConfigurationManager from NuGet manager.
And read appSetting from App.config

<appSettings>
  <add key="appSetting1" value="1000" />
</appSettings>

Add System.Configuration.ConfigurationManager from NuGet Manager

enter image description here

ConfigurationManager.AppSettings.Get("appSetting1")

Attaching a Sass/SCSS to HTML docs

You can not "attach" a SASS/SCSS file to an HTML document.

SASS/SCSS is a CSS preprocessor that runs on the server and compiles to CSS code that your browser understands.

There are client-side alternatives to SASS that can be compiled in the browser using javascript such as LESS CSS, though I advise you compile to CSS for production use.

It's as simple as adding 2 lines of code to your HTML file.

<link rel="stylesheet/less" type="text/css" href="styles.less" />
<script src="less.js" type="text/javascript"></script>

JetBrains / IntelliJ keyboard shortcut to collapse all methods

You Can Go To setting > editor > general > code folding and check "show code folding outline" .

How can I add a custom HTTP header to ajax request with js or jQuery?

You can also do this without using jQuery. Override XMLHttpRequest's send method and add the header there:

XMLHttpRequest.prototype.realSend = XMLHttpRequest.prototype.send;
var newSend = function(vData) {
    this.setRequestHeader('x-my-custom-header', 'some value');
    this.realSend(vData);
};
XMLHttpRequest.prototype.send = newSend;

MongoDB - admin user not authorized

I had this problem because of the hostname in my MongoDB Compass was pointing to admin instead for my project. Fixed by adding the /projectname after the hostname :) Try this:

  1. Choose your project in the MongoDB atlas website
  2. Connect/Connect with MongoDB Compass
  3. Download Compass/Choose your OS
  4. I used Compass 1.12 or later
  5. Copy the connection string under the Compass 1.12 or later.
  6. Open MongoDB Compass/Connect(top left)/Connect To
  7. Connection String detected/Yes/
  8. Append your project name after the hostname: cluster9-foodie.mongodb.net/projectname
  9. Connect & Tested the API with POSTMAN.
  10. Succeed.

Use the same connection string in your code too:

  1. Before:
    • mongodb+srv://projectname:password@cluster9-foodie.mongodb.net/admin
  2. After:
    • mongodb+srv://projectname:password@cluster9-foodie.mongodb.net/projectname

Good luck.

How to decrypt a password from SQL server?

A quick google indicates that pwdencrypt() is not deterministic, and your statement select pwdencrypt('AAAA') returns a different value on my installation!

See also this article http://www.theregister.co.uk/2002/07/08/cracking_ms_sql_server_passwords/

Font from origin has been blocked from loading by Cross-Origin Resource Sharing policy

Just add use of origin in your if you use node.js as server...

like this

  app.use((req, res, next) => {
  res.header('Access-Control-Allow-Origin', '*');
  next();
});

We Need response for origin

Creating a "logical exclusive or" operator in Java

This is an example of using XOR(^), from this answer

byte[] array_1 = new byte[] { 1, 0, 1, 0, 1, 1 };
byte[] array_2 = new byte[] { 1, 0, 0, 1, 0, 1 };

byte[] array_3 = new byte[6];

int i = 0;
for (byte b : array_1)
    array_3[i] = b ^ array_2[i++];

Output

0 0 1 1 1 0

argparse module How to add option without any argument?

To create an option that needs no value, set the action [docs] of it to 'store_const', 'store_true' or 'store_false'.

Example:

parser.add_argument('-s', '--simulate', action='store_true')

What causes the error "undefined reference to (some function)"?

It's a linker error. ld is the linker, so if you get an error message ending with "ld returned 1 exit status", that tells you that it's a linker error.

The error message tells you that none of the object files you're linking against contains a definition for avergecolumns. The reason for that is that the function you've defined is called averagecolumns (in other words: you misspelled the function name when calling the function (and presumably in the header file as well - otherwise you'd have gotten a different error at compile time)).

phpMyAdmin - can't connect - invalid setings - ever since I added a root password - locked out

This works for me:

C:\xampp\phpMyAdmin\config.inc.php

$cfg['Servers'][$i]['password'] = 'secret';

Edit: Before you got this error it is most likely that from phpmyadmin->Users you have added password for the root user. In my case that was "secret" so the above primer works for me BUT for you will work this:

$cfg['Servers'][$i]['password'] = 'Enter the password for root you have added before you got this error';

T-SQL to list all the user mappings with database roles/permissions for a Login

CREATE TABLE #tempww (

    LoginName nvarchar(max),
    DBname nvarchar(max),
    Username nvarchar(max), 
    AliasName nvarchar(max)
)

INSERT INTO #tempww 

EXEC master..sp_msloginmappings 

-- display results

declare @col varchar(1000)

declare @sql varchar(2000)

select @col = COALESCE(@col + ', ','') + QUOTENAME(DBname)

from #tempww Group by DBname

Set @sql='select * from (select LoginName,Username,AliasName,DBname,row_number() over(order by (select 0)) rn from #tempww) src

PIVOT (Max(rn) FOR DBname

IN ('+@col+')) pvt'

EXEC(@sql)



-- cleanup
DROP TABLE #tempww

Asp.NET Web API - 405 - HTTP verb used to access this page is not allowed - how to set handler mappings

This error is coming from the staticfile handler -- which by default doesn't filter any verbs, but probably can only deal with HEAD and GET.

And this is because no other handler stepped up to the plate and said they could handle DELETE.

Since you are using the WEBAPI, which because of routing doesn't have files and therefore extensions, the following additions need to be added to your web.config file:

<system.webserver>
    <httpProtocol>
        <handlers>
          ...
            <remove name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" />
            <remove name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" />
            <remove name="ExtensionlessUrlHandler-Integrated-4.0" />

            <add name="ExtensionlessUrlHandler-ISAPI-4.0_32bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="C:\windows\Microsoft.NET\Framework\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness32" responseBufferLimit="0" />
            <add name="ExtensionlessUrlHandler-ISAPI-4.0_64bit" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" modules="IsapiModule" scriptProcessor="C:\windows\Microsoft.NET\Framework64\v4.0.30319\aspnet_isapi.dll" preCondition="classicMode,runtimeVersionv4.0,bitness64" responseBufferLimit="0" />
            <add name="ExtensionlessUrlHandler-Integrated-4.0" path="*." verb="GET,HEAD,POST,DEBUG,PUT,DELETE,PATCH,OPTIONS" type="System.Web.Handlers.TransferRequestHandler" preCondition="integratedMode,runtimeVersionv4.0" />

Obviously what is needed depends on classicmode vs integratedmode, and classicmode depends on bitness. In addition, the OPTIONS header has been added for CORS processing, but if you don't do CORS you don't need that.

FYI, your web.config is the local to the application (or application directory) version whose top level is applicationHost.config.

How to find out if a Python object is a string?

Its simple, use the following code (we assume the object mentioned to be obj)-

if type(obj) == str:
    print('It is a string')
else:
    print('It is not a string.')

How to replace deprecated android.support.v4.app.ActionBarDrawerToggle

Adding only android-support-v7-appcompat.jar to library dependencies is not enough, you have also to import in your project the module that you can find in your SDK at the path \android-sdk\extras\android\support\v7\appcompatand after that add module dependencies configuring the project structure in this way

enter image description here

otherwise are included only the class files of support library and the app is not able to load the other resources causing the error.

In addition as reVerse suggested replace this

public CustomActionBarDrawerToggle(Activity mActivity,
                                           DrawerLayout mDrawerLayout) {
            super(mActivity, mDrawerLayout,new Toolbar(MyActivity.this) ,
                    R.string.ns_menu_open, R.string.ns_menu_close);
        }

with

public CustomActionBarDrawerToggle(Activity mActivity,
                                           DrawerLayout mDrawerLayout) {
            super(mActivity, mDrawerLayout, R.string.ns_menu_open, R.string.ns_menu_close);
        }

Using sed, how do you print the first 'N' characters of a line?

To print the N first characters you can remove the N+1 characters up to the end of line:

$ sed 's/.//5g' <<< "defn-test"
defn

How to search a string in a single column (A) in excel using VBA

Below are two methods that are superior to looping. Both handle a "no-find" case.

  1. The VBA equivalent of a normal function VLOOKUP with error-handling if the variable doesn't exist (INDEX/MATCH may be a better route than VLOOKUP, ie if your two columns A and B were in reverse order, or were far apart)
  2. VBAs FIND method (matching a whole string in column A given I use the xlWhole argument)

    Sub Method1()
    Dim strSearch As String
    Dim strOut As String
    Dim bFailed As Boolean
    
    strSearch = "trees"
    
    On Error Resume Next
    strOut = Application.WorksheetFunction.VLookup(strSearch, Range("A:B"), 2, False)
    If Err.Number <> 0 Then bFailed = True
    On Error GoTo 0
    
    If Not bFailed Then
    MsgBox "corresponding value is " & vbNewLine & strOut
    Else
    MsgBox strSearch & " not found"
    End If
    End Sub
    
    Sub Method2()
        Dim rng1 As Range
        Dim strSearch As String
        strSearch = "trees"
        Set rng1 = Range("A:A").Find(strSearch, , xlValues, xlWhole)
        If Not rng1 Is Nothing Then
            MsgBox "Find has matched " & strSearch & vbNewLine & "corresponding cell is " & rng1.Offset(0, 1)
        Else
            MsgBox strSearch & " not found"
        End If
    End Sub
    

How to start mongodb shell?

Both the mongod (database server) and mongo (database client shell) programs are command line programs and each expects to be run in its own command line session. So, after starting the server (as you did with "./mongod") you should open a second command line session and run "./mongo" in it to give you a command line shell for talking to the server.

Authentication plugin 'caching_sha2_password' cannot be loaded

Downloading a development release of 8.0.11-rc worked for me on a mac. with the following docker commands:

docker run --name mysql -p 3406:3306 -e MYSQL_ROOT_PASSWORD=mypassword -d mysql

SMTP server response: 530 5.7.0 Must issue a STARTTLS command first

First, make sure you PHP installation has SSL support (look for an "openssl" section in the output from phpinfo()).

You can set the following settings in your PHP.ini:

ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");

Vim 80 column layout concerns

I'm afraid that you've put constraints on the set of solutions that, well, leave you with the null set.

Using :set textwidth=80 will fix all of the problems you mentioned except that you can't easily see the line limit coming up. If you :set ruler, you'll enable the x,y position display on the status bar, which you can use to see which column you're in.

Aside from that, I'm not sure what to tell you. It's a shame to lose the number column, fold column and splits just because you have to :set columns=80.

Changing password with Oracle SQL Developer

I realise that there are many answers, but I found a solution that may be helpful to some. I ran into the same problem, I am running oracle sql develop on my local computer and I have a bunch of users. I happen to remember the password for one of my users and I used it to reset the password of other users.

Steps:

  1. connect to a database using a valid user and password, in my case all my users expired except "system" and I remember that password

  2. find the "Other_users" node within the tree as the image below displays

enter image description here

3.within the "Other_users" tree find your users that you would like to reset password of and right click the note and select "Edit Users"

enter image description here

4.fill out the new password in edit user dialog and click "Apply". Make sure that you have unchecked "Password expired (user must change next login)".

enter image description here

And that worked for me, It is not as good as other solution because you need to be able to login to at least one account but it does work.

How do you add a scroll bar to a div?

to add scroll u need to define max-height of your div and then add overflow-y

so do something like this

.my_scroll_div{
    overflow-y: auto;
    max-height: 100px;
}

Change app language programmatically in Android

I know it's late to answer but i found this article here . Which explains the whole process very well and provides you a well structured code.

Locale Helper class:

import android.annotation.TargetApi;
import android.content.Context;
import android.content.SharedPreferences;
import android.content.res.Configuration;
import android.content.res.Resources;
import android.os.Build;
import android.preference.PreferenceManager;

import java.util.Locale;

/**
 * This class is used to change your application locale and persist this change for the next time
 * that your app is going to be used.
 * <p/>
 * You can also change the locale of your application on the fly by using the setLocale method.
 * <p/>
 * Created by gunhansancar on 07/10/15.
 */
public class LocaleHelper {

    private static final String SELECTED_LANGUAGE = "Locale.Helper.Selected.Language";

    public static Context onAttach(Context context) {
        String lang = getPersistedData(context, Locale.getDefault().getLanguage());
        return setLocale(context, lang);
    }

    public static Context onAttach(Context context, String defaultLanguage) {
        String lang = getPersistedData(context, defaultLanguage);
        return setLocale(context, lang);
    }

    public static String getLanguage(Context context) {
        return getPersistedData(context, Locale.getDefault().getLanguage());
    }

    public static Context setLocale(Context context, String language) {
        persist(context, language);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            return updateResources(context, language);
        }

        return updateResourcesLegacy(context, language);
    }

    private static String getPersistedData(Context context, String defaultLanguage) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        return preferences.getString(SELECTED_LANGUAGE, defaultLanguage);
    }

    private static void persist(Context context, String language) {
        SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(context);
        SharedPreferences.Editor editor = preferences.edit();

        editor.putString(SELECTED_LANGUAGE, language);
        editor.apply();
    }

    @TargetApi(Build.VERSION_CODES.N)
    private static Context updateResources(Context context, String language) {
        Locale locale = new Locale(language);
        Locale.setDefault(locale);

        Configuration configuration = context.getResources().getConfiguration();
        configuration.setLocale(locale);
        configuration.setLayoutDirection(locale);

        return context.createConfigurationContext(configuration);
    }

    @SuppressWarnings("deprecation")
    private static Context updateResourcesLegacy(Context context, String language) {
        Locale locale = new Locale(language);
        Locale.setDefault(locale);

        Resources resources = context.getResources();

        Configuration configuration = resources.getConfiguration();
        configuration.locale = locale;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
            configuration.setLayoutDirection(locale);
        }

        resources.updateConfiguration(configuration, resources.getDisplayMetrics());

        return context;
    }
}

You need to override attachBaseContext and call LocaleHelper.onAttach() to initialize the locale settings in your application.

import android.app.Application;
import android.content.Context;

import com.gunhansancar.changelanguageexample.helper.LocaleHelper;

public class MainApplication extends Application {
    @Override
    protected void attachBaseContext(Context base) {
        super.attachBaseContext(LocaleHelper.onAttach(base, "en"));
    }
}

All you have to do is to add

LocaleHelper.onCreate(this, "en");

wherever you want to change the locale.

pandas: multiple conditions while indexing data frame - unexpected behavior

You can also use query(), i.e.:

df_filtered = df.query('a == 4 & b != 2')

How to simulate a real mouse click using java?

You could create a simple AutoIt Script that does the job for you, compile it as an executable and perform a system call there.

in au3 Script:

; how to use: MouseClick ( "button" [, x, y [, clicks = 1 [, speed = 10]]] )
MouseClick ( "left" , $CmdLine[1], $CmdLine[1] )

Now find aut2exe in your au3 Folder or find 'Compile Script to .exe' in your Start Menu and create an executable.

in your Java class call:

Runtime.getRuntime().exec(
    new String[]{
        "yourscript.exe", 
        String.valueOf(mypoint.x),
        String.valueOf(mypoint.y)}
);

AutoIt will behave as if it was a human and won't be detected as a machine.

Find AutoIt here: https://www.autoitscript.com/

Remove icon/logo from action bar on android

Go in your manifest and find the your activity then add this code:

android:theme="@android:style/Theme.NoTitleBar"

above line hide your Actionbar .

If you need to other feature you can see other options with (CLR + SPC).

What is Android's file system?

It depends on what filesystem, for example /system and /data are yaffs2 while /sdcard is vfat. This is the output of mount:

rootfs / rootfs ro 0 0
tmpfs /dev tmpfs rw,mode=755 0 0
devpts /dev/pts devpts rw,mode=600 0 0
proc /proc proc rw 0 0
sysfs /sys sysfs rw 0 0
tmpfs /sqlite_stmt_journals tmpfs rw,size=4096k 0 0
none /dev/cpuctl cgroup rw,cpu 0 0
/dev/block/mtdblock0 /system yaffs2 ro 0 0
/dev/block/mtdblock1 /data yaffs2 rw,nosuid,nodev 0 0
/dev/block/mtdblock2 /cache yaffs2 rw,nosuid,nodev 0 0
/dev/block//vold/179:0 /sdcard vfat rw,dirsync,nosuid,nodev,noexec,uid=1000,gid=1015,fmask=0702,dmask=0702,allow_utime=0020,codepage=cp437,iocharset=iso8859-1,shortname=mixed,utf8,errors=remount-ro 0 0

and with respect to other filesystems supported, this is the list

nodev   sysfs
nodev   rootfs
nodev   bdev
nodev   proc
nodev   cgroup
nodev   binfmt_misc
nodev   sockfs
nodev   pipefs
nodev   anon_inodefs
nodev   tmpfs
nodev   inotifyfs
nodev   devpts
nodev   ramfs
         vfat
         msdos
nodev   nfsd
nodev   smbfs
         yaffs
         yaffs2
nodev   rpc_pipefs

Normalize data in pandas

This is how you do it column-wise:

[df[col].update((df[col] - df[col].min()) / (df[col].max() - df[col].min())) for col in df.columns]

How to select all rows which have same value in some column

You can do this without a JOIN:

SELECT *
FROM (SELECT *,COUNT(*) OVER(PARTITION BY phone_number) as Phone_CT
      FROM YourTable
      )sub
WHERE Phone_CT > 1
ORDER BY phone_number, employee_ids

Demo: SQL Fiddle

Loop structure inside gnuplot?

There sure is (in gnuplot 4.4+):

plot for [i=1:1000] 'data'.i.'.txt' using 1:2 title 'Flow '.i

The variable i can be interpreted as a variable or a string, so you could do something like

plot for [i=1:1000] 'data'.i.'.txt' using 1:($2+i) title 'Flow '.i

if you want to have lines offset from each other.

Type help iteration at the gnuplot command line for more info.

Also be sure to see @DarioP's answer about the do for syntax; that gives you something closer to a traditional for loop.

How to Extract Year from DATE in POSTGRESQL

answer is;

select date_part('year', timestamp '2001-02-16 20:38:40') as year,
       date_part('month', timestamp '2001-02-16 20:38:40') as month,
       date_part('day', timestamp '2001-02-16 20:38:40') as day,
       date_part('hour', timestamp '2001-02-16 20:38:40') as hour,
       date_part('minute', timestamp '2001-02-16 20:38:40') as minute

Detect if user is scrolling

window.addEventListener("scroll",function(){
    window.lastScrollTime = new Date().getTime()
});
function is_scrolling() {
    return window.lastScrollTime && new Date().getTime() < window.lastScrollTime + 500
}

Change the 500 to the number of milliseconds after the last scroll event at which you consider the user to be "no longer scrolling".

(addEventListener is better than onScroll because the former can coexist nicely with any other code that uses onScroll.)

Error - trustAnchors parameter must be non-empty

I encountered this problem with the Android SDK sdkmanager. For me this solution worked:

  1. Go to /usr/lib/jvm/java-8-oracle/jre/lib/security/
  2. Replace cacert with cacert.original

The cacert file was a tiny one (22B). I have installed oracle-java8-installer from ppa:webupd8team/java (according to this manual: https://docs.nativescript.org/start/ns-setup-linux).

How to specify the JDK version in android studio?

In Android Studio 4.0.1, Help -> About shows the details of the Java version used by the studio, in my case:

Android Studio 4.0.1
Build #AI-193.6911.18.40.6626763, built on June 25, 2020
Runtime version: 1.8.0_242-release-1644-b01 amd64
VM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
Windows 10 10.0
GC: ParNew, ConcurrentMarkSweep
Memory: 1237M
Cores: 8
Registry: ide.new.welcome.screen.force=true
Non-Bundled Plugins: com.google.services.firebase

add image to uitableview cell

Swift 5 solution

cell.imageView?.image = UIImage.init(named: "yourImageName")

How to get a function name as a string?

my_function.func_name

There are also other fun properties of functions. Type dir(func_name) to list them. func_name.func_code.co_code is the compiled function, stored as a string.

import dis
dis.dis(my_function)

will display the code in almost human readable format. :)

What's the CMake syntax to set and use variables?

Here are a couple basic examples to get started quick and dirty.

One item variable

Set variable:

SET(INSTALL_ETC_DIR "etc")

Use variable:

SET(INSTALL_ETC_CROND_DIR "${INSTALL_ETC_DIR}/cron.d")

Multi-item variable (ie. list)

Set variable:

SET(PROGRAM_SRCS
        program.c
        program_utils.c
        a_lib.c
        b_lib.c
        config.c
        )

Use variable:

add_executable(program "${PROGRAM_SRCS}")

CMake docs on variables

Can an AJAX response set a cookie?

According to the w3 spec section 4.6.3 for XMLHttpRequest a user agent should honor the Set-Cookie header. So the answer is yes you should be able to.

Quotation:

If the user agent supports HTTP State Management it should persist, discard and send cookies (as received in the Set-Cookie response header, and sent in the Cookie header) as applicable.

Java JRE 64-bit download for Windows?

The trick is to visit the original page using the 64-bit version of Internet Explorer. The site will then offer you the appropriate download options.

Thread pooling in C++11

You can use thread_pool from boost library:

void my_task(){...}

int main(){
    int threadNumbers = thread::hardware_concurrency();
    boost::asio::thread_pool pool(threadNumbers);

    // Submit a function to the pool.
    boost::asio::post(pool, my_task);

    // Submit a lambda object to the pool.
    boost::asio::post(pool, []() {
      ...
    });
}

You also can use threadpool from open source community:

void first_task() {...}    
void second_task() {...}

int main(){
    int threadNumbers = thread::hardware_concurrency();
    pool tp(threadNumbers);

    // Add some tasks to the pool.
    tp.schedule(&first_task);
    tp.schedule(&second_task);
}

jQuery Validation plugin: validate check box

You had several issues with your code.

1) Missing a closing brace, }, within your rules.

2) In this case, there is no reason to use a function for the required rule. By default, the plugin can handle checkbox and radio inputs just fine, so using true is enough. However, this will simply do the same logic as in your original function and verify that at least one is checked.

3) If you also want only a maximum of two to be checked, then you'll need to apply the maxlength rule.

4) The messages option was missing the rule specification. It will work, but the one custom message would apply to all rules on the same field.

5) If a name attribute contains brackets, you must enclose it within quotes.

DEMO: http://jsfiddle.net/K6Wvk/

$(document).ready(function () {

    $('#formid').validate({ // initialize the plugin
        rules: {
            'test[]': {
                required: true,
                maxlength: 2
            }
        },
        messages: {
            'test[]': {
                required: "You must check at least 1 box",
                maxlength: "Check no more than {0} boxes"
            }
        }
    });

});

How to convert JSON to string?

Try to Use JSON.stringify

Regards

Multiple arguments to function called by pthread_create()?

struct arg_struct *args = (struct arg_struct *)args;

--> this assignment is wrong, I mean the variable argument should be used in this context. Cheers!!!

How to declare Global Variables in Excel VBA to be visible across the Workbook

You can do the following to learn/test the concept:

  1. Open new Excel Workbook and in Excel VBA editor right-click on Modules->Insert->Module

  2. In newly added Module1 add the declaration; Public Global1 As String

  3. in Worksheet VBA Module Sheet1(Sheet1) put the code snippet:

Sub setMe()
      Global1 = "Hello"
End Sub
  1. in Worksheet VBA Module Sheet2(Sheet2) put the code snippet:
Sub showMe()
    Debug.Print (Global1)
End Sub
  1. Run in sequence Sub setMe() and then Sub showMe() to test the global visibility/accessibility of the var Global1

Hope this will help.

Difference between array_map, array_walk and array_filter

The other answers demonstrate the difference between array_walk (in-place modification) and array_map (return modified copy) quite well. However, they don't really mention array_reduce, which is an illuminating way to understand array_map and array_filter.

The array_reduce function takes an array, a two-argument function and an 'accumulator', like this:

array_reduce(array('a', 'b', 'c', 'd'),
             'my_function',
             $accumulator)

The array's elements are combined with the accumulator one at a time, using the given function. The result of the above call is the same as doing this:

my_function(
  my_function(
    my_function(
      my_function(
        $accumulator,
        'a'),
      'b'),
    'c'),
  'd')

If you prefer to think in terms of loops, it's like doing the following (I've actually used this as a fallback when array_reduce wasn't available):

function array_reduce($array, $function, $accumulator) {
  foreach ($array as $element) {
    $accumulator = $function($accumulator, $element);
  }
  return $accumulator;
}

This looping version makes it clear why I've called the third argument an 'accumulator': we can use it to accumulate results through each iteration.

So what does this have to do with array_map and array_filter? It turns out that they're both a particular kind of array_reduce. We can implement them like this:

array_map($function, $array)    === array_reduce($array, $MAP,    array())
array_filter($array, $function) === array_reduce($array, $FILTER, array())

Ignore the fact that array_map and array_filter take their arguments in a different order; that's just another quirk of PHP. The important point is that the right-hand-side is identical except for the functions I've called $MAP and $FILTER. So, what do they look like?

$MAP = function($accumulator, $element) {
  $accumulator[] = $function($element);
  return $accumulator;
};

$FILTER = function($accumulator, $element) {
  if ($function($element)) $accumulator[] = $element;
  return $accumulator;
};

As you can see, both functions take in the $accumulator and return it again. There are two differences in these functions:

  • $MAP will always append to $accumulator, but $FILTER will only do so if $function($element) is TRUE.
  • $FILTER appends the original element, but $MAP appends $function($element).

Note that this is far from useless trivia; we can use it to make our algorithms more efficient!

We can often see code like these two examples:

// Transform the valid inputs
array_map('transform', array_filter($inputs, 'valid'))

// Get all numeric IDs
array_filter(array_map('get_id', $inputs), 'is_numeric')

Using array_map and array_filter instead of loops makes these examples look quite nice. However, it can be very inefficient if $inputs is large, since the first call (map or filter) will traverse $inputs and build an intermediate array. This intermediate array is passed straight into the second call, which will traverse the whole thing again, then the intermediate array will need to be garbage collected.

We can get rid of this intermediate array by exploiting the fact that array_map and array_filter are both examples of array_reduce. By combining them, we only have to traverse $inputs once in each example:

// Transform valid inputs
array_reduce($inputs,
             function($accumulator, $element) {
               if (valid($element)) $accumulator[] = transform($element);
               return $accumulator;
             },
             array())

// Get all numeric IDs
array_reduce($inputs,
             function($accumulator, $element) {
               $id = get_id($element);
               if (is_numeric($id)) $accumulator[] = $id;
               return $accumulator;
             },
             array())

NOTE: My implementations of array_map and array_filter above won't behave exactly like PHP's, since my array_map can only handle one array at a time and my array_filter won't use "empty" as its default $function. Also, neither will preserve keys.

It's not difficult to make them behave like PHP's, but I felt that these complications would make the core idea harder to spot.

Remove an item from an IEnumerable<T> collection

Not removing but creating a new List without that element with LINQ:

// remove
users = users.Where(u => u.userId != 123).ToList();

// new list
var modified = users.Where(u => u.userId == 123).ToList();

Efficiently counting the number of lines of a text file. (200mb+)

This will use less memory, since it doesn't load the whole file into memory:

$file="largefile.txt";
$linecount = 0;
$handle = fopen($file, "r");
while(!feof($handle)){
  $line = fgets($handle);
  $linecount++;
}

fclose($handle);

echo $linecount;

fgets loads a single line into memory (if the second argument $length is omitted it will keep reading from the stream until it reaches the end of the line, which is what we want). This is still unlikely to be as quick as using something other than PHP, if you care about wall time as well as memory usage.

The only danger with this is if any lines are particularly long (what if you encounter a 2GB file without line breaks?). In which case you're better off doing slurping it in in chunks, and counting end-of-line characters:

$file="largefile.txt";
$linecount = 0;
$handle = fopen($file, "r");
while(!feof($handle)){
  $line = fgets($handle, 4096);
  $linecount = $linecount + substr_count($line, PHP_EOL);
}

fclose($handle);

echo $linecount;

MySQL: ALTER TABLE if column not exists

Here is a solution that does not involve querying INFORMATION_SCHEMA, it simply ignores the error if the column does exist.

DROP PROCEDURE IF EXISTS `?`;
DELIMITER //
CREATE PROCEDURE `?`()
BEGIN
  DECLARE CONTINUE HANDLER FOR SQLEXCEPTION BEGIN END;
  ALTER TABLE `table_name` ADD COLUMN `column_name` INTEGER;
END //
DELIMITER ;
CALL `?`();
DROP PROCEDURE `?`;

P.S. Feel free to give it other name rather than ?

Static methods - How to call a method from another method?

OK the main difference between class methods and static methods is:

  • class method has its own identity, that's why they have to be called from within an INSTANCE.
  • on the other hand static method can be shared between multiple instances so that it must be called from within THE CLASS

Install Qt on Ubuntu

The ubuntu package name is qt5-default, not qt.

CMD what does /im (taskkill)?

See the doc : it will close all running tasks using the executable file something.exe, more or less like linux' killall

Twitter Bootstrap and ASP.NET GridView

There are 2 steps to resolve this:

  1. Add UseAccessibleHeader="true" to Gridview tag:

    <asp:GridView ID="MyGridView" runat="server" UseAccessibleHeader="true">
    
  2. Add the following Code to the PreRender event:


Protected Sub MyGridView_PreRender(sender As Object, e As EventArgs) Handles MyGridView.PreRender
    Try
        MyGridView.HeaderRow.TableSection = TableRowSection.TableHeader
    Catch ex As Exception
    End Try
End Sub

Note setting Header Row in DataBound() works only when the object is databound, any other postback that doesn't databind the gridview will result in the gridview header row style reverting to a standard row again. PreRender works everytime, just make sure you have an error catch for when the gridview is empty.

Base64 Java encode and decode a string

The accepted answer uses the Apache Commons package but this is how I did it using Java's native libraries

Java 11 and up

import java.util.Base64;

public class Base64Encoding {

    public static void main(String[] args) {
        Base64.Encoder enc = Base64.getEncoder();
        Base64.Decoder dec = Base64.getDecoder();
        String str = "77+9x6s=";

        // encode data using BASE64
        String encoded = enc.encodeToString(str.getBytes());
        System.out.println("encoded value is \t" + encoded);

        // Decode data
        String decoded = new String(dec.decode(encoded));
        System.out.println("decoded value is \t" + decoded);
        System.out.println("original value is \t" + str);
    }
}

Java 6 - 10

import java.io.UnsupportedEncodingException;    
import javax.xml.bind.DatatypeConverter;

public class EncodeString64 {
    public static void main(String[] args) throws UnsupportedEncodingException {

        String str = "77+9x6s=";
        // encode data using BASE64
        String encoded = DatatypeConverter.printBase64Binary(str.getBytes());
        System.out.println("encoded value is \t" + encoded);

        // Decode data 
        String decoded = new String(DatatypeConverter.parseBase64Binary(encoded));
        System.out.println("decoded value is \t" + decoded);

        System.out.println("original value is \t" + str);
    }
}

The better way would be to try/catch the encoding/decoding steps but hopefully you get the idea.

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

git rm --cached file

should do what you want.

You can read more details at git help rm

How to add ID property to Html.BeginForm() in asp.net mvc?

In System.Web.Mvc.Html ( in System.Web.Mvc.dll ) the begin form is defined like:- Details

BeginForm ( this HtmlHelper htmlHelper, string actionName, string
controllerName, object routeValues, FormMethod method, object htmlAttributes)

Means you should use like this :

Html.BeginForm( string actionName, string controllerName,object routeValues, FormMethod method, object htmlAttributes)

So, it worked in MVC 4

@using (Html.BeginForm(null, null, new { @id = string.Empty }, FormMethod.Post,
    new { @id = "signupform" }))
{
    <input id="TRAINER_LIST" name="TRAINER_LIST" type="hidden" value="">
    <input type="submit" value="Create" id="btnSubmit" />
}

Find all files in a folder

First off; best practice would be to get the users Desktop folder with

string path = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);

Then you can find all the files with something like

string[] files = Directory.GetFiles(path, "*.txt", SearchOption.AllDirectories);

Note that with the above line you will find all files with a .txt extension in the Desktop folder of the logged in user AND all subfolders.

Then you could copy or move the files by enumerating the above collection like

// For copying...
foreach (string s in files)
{
   File.Copy(s, "C:\newFolder\newFilename.txt");
}

// ... Or for moving
foreach (string s in files)
{
   File.Move(s, "C:\newFolder\newFilename.txt");
}

Please note that you will have to include the filename in your Copy() (or Move()) operation. So you would have to find a way to determine the filename of at least the extension you are dealing with and not name all the files the same like what would happen in the above example.

With that in mind you could also check out the DirectoryInfo and FileInfo classes. These work in similair ways, but you can get information about your path-/filenames, extensions, etc. more easily

Check out these for more info:

http://msdn.microsoft.com/en-us/library/system.io.directory.aspx

http://msdn.microsoft.com/en-us/library/ms143316.aspx

http://msdn.microsoft.com/en-us/library/system.io.file.aspx

How to draw a rectangle around a region of interest in python

As the other answers said, the function you need is cv2.rectangle(), but keep in mind that the coordinates for the bounding box vertices need to be integers if they are in a tuple, and they need to be in the order of (left, top) and (right, bottom). Or, equivalently, (xmin, ymin) and (xmax, ymax).

How to read a local text file?

You need to check for status 0 (as when loading files locally with XMLHttpRequest, you don't get a status returned because it's not from a Webserver)

function readTextFile(file)
{
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                alert(allText);
            }
        }
    }
    rawFile.send(null);
}

And specify file:// in your filename:

readTextFile("file:///C:/your/path/to/file.txt");

List of special characters for SQL LIKE clause

Potential answer for SQL Server

Interesting I just ran a test using LinqPad with SQL Server which should be just running Linq to SQL underneath and it generates the following SQL statement.

Records .Where(r => r.Name.Contains("lkjwer--_~[]"))

-- Region Parameters
DECLARE @p0 VarChar(1000) = '%lkjwer--~_~~~[]%'
-- EndRegion
SELECT [t0].[ID], [t0].[Name]
FROM [RECORDS] AS [t0]
WHERE [t0].[Name] LIKE @p0 ESCAPE '~'

So I haven't tested it yet but it looks like potentially the ESCAPE '~' keyword may allow for automatic escaping of a string for use within a like expression.

Warning: mysql_connect(): Access denied for user 'root'@'localhost' (using password: YES)

try $conn = mysql_connect("localhost", "root") or $conn = mysql_connect("localhost", "root", "")

Child inside parent with min-height: 100% not inheriting height

The best way to achieve this nowadays is to use display: flex;. However you might run into an issue when trying to support IE11. According to https://caniuse.com using flexbox :

IE 11 does not vertically align items correctly when min-height is used

Internet Explorer compatible solution

The solution is to use display: table; on the parent and display: table-row; on the child both with height: 100%; as a replacement for min-height: 100%;.

Most of the solutions listed here use display: table, table-row and/or table-cell, but they don't replicate the same behaviour as min-height: 100%;, which is:

  • Inherit the computed height of the parent (as opposed to inheriting its height property);
  • Allow the parent's height to exceed its min-height;

While using this solution, the behaviour is the same and the property min-height is not needed which allows to get around the bug.

Explanation

The reason why it works is because, unlike most elements, elements using display: table and table-row will always be as tall as their content. This makes their height property behave similarly to min-height.

Solution in action

_x000D_
_x000D_
html, body {_x000D_
  height: 100px;_x000D_
  margin: 0;_x000D_
}_x000D_
_x000D_
#containment {_x000D_
  display: table;_x000D_
  height: 100%;_x000D_
  background: pink;_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
#containment-shadow-left {_x000D_
  display: table-row;_x000D_
  height: 100%;_x000D_
  background: aqua;_x000D_
}_x000D_
_x000D_
#content {_x000D_
  padding: 15px;_x000D_
}_x000D_
_x000D_
#demo {_x000D_
  display: none;_x000D_
  background-color: red;_x000D_
  height: 200px;_x000D_
}_x000D_
_x000D_
#demo-checkbox:checked ~ #demo {_x000D_
  display: block;_x000D_
}
_x000D_
<div id="containment">_x000D_
  <div id="containment-shadow-left">_x000D_
    <div id="content">_x000D_
      <input id="demo-checkbox" type="checkbox">_x000D_
      <label for="demo-checkbox">Click here for overflow demo</label>_x000D_
      <div id="demo">This is taller than #containment</div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

error code 1292 incorrect date value mysql

Insert date in the following format yyyy-MM-dd example,

INSERT INTO `PROGETTO`.`ALBERGO`(`ID`, `nome`, `viale`, `num_civico`, `data_apertura`, `data_chiusura`, `orario_apertura`, `orario_chiusura`, `posti_liberi`, `costo_intero`, `costo_ridotto`, `stelle`, `telefono`, `mail`, `web`, `Nome-paese`, `Comune`) 
VALUES(0, 'Hotel Centrale', 'Via Passo Rolle', '74', '2012-05-01', '2012-09-31', '06:30', '24:00', 80, 50, 25, 3, '43968083', '[email protected]', 'http://www.hcentrale.it/', 'Trento', 'TN')

java.io.InvalidClassException: local class incompatible:

One thing that could have happened:

  • 1: you create your serialized data with a given library A (version X)
  • 2: you then try to read this data with the same library A (but version Y)

Hence, at compile time for the version X, the JVM will generate a first Serial ID (for version X) and it will do the same with the other version Y (another Serial ID).

When your program tries to de-serialize the data, it can't because the two classes do not have the same Serial ID and your program have no guarantee that the two Serialized objects correspond to the same class format.

Assuming you changed your constructor in the mean time and this should make sense to you.

Change an image with onclick()

If you don't want use js, I think, you can use <a href="javascript:void(0);"></a> instead of img and then use css like

a {
  background: url('oldImage.png');
}
a:visited {
  background: url('newImage.png');
}

EDIT: Nope. Sorry it works only for :hover

What is the best method to merge two PHP objects?

Let's keep it simple!

function copy_properties($from, $to, $fields = null) {
    // copies properties/elements (overwrites duplicates)
    // can take arrays or objects 
    // if fields is set (an array), will only copy keys listed in that array
    // returns $to with the added/replaced properties/keys
    $from_array = is_array($from) ? $from : get_object_vars($from);
    foreach($from_array as $key => $val) {
        if(!is_array($fields) or in_array($key, $fields)) {
            if(is_object($to)) {
                $to->$key = $val;
            } else {
                $to[$key] = $val;
            }
        }
    }
    return($to);
}

If that doesn't answer your question, it will surely help towards the answer. Credit for the code above goes to myself :)

Eclipse won't compile/run java file

right click somewhere on the file or in project explorer and choose 'run as'->'java application'

Remove duplicate values from JS array

var lines = ["Mike", "Matt", "Nancy", "Adam", "Jenny", "Nancy", "Carl"];
var uniqueNames = [];

for(var i=0;i<lines.length;i++)
{
    if(uniqueNames.indexOf(lines[i]) == -1)
        uniqueNames.push(lines[i]);
}
if(uniqueNames.indexOf(uniqueNames[uniqueNames.length-1])!= -1)
    uniqueNames.pop();
for(var i=0;i<uniqueNames.length;i++)
{
    document.write(uniqueNames[i]);
      document.write("<br/>");
}

Efficiently checking if arbitrary object is NaN in Python / numpy / pandas?

pandas.isnull() (also pd.isna(), in newer versions) checks for missing values in both numeric and string/object arrays. From the documentation, it checks for:

NaN in numeric arrays, None/NaN in object arrays

Quick example:

import pandas as pd
import numpy as np
s = pd.Series(['apple', np.nan, 'banana'])
pd.isnull(s)
Out[9]: 
0    False
1     True
2    False
dtype: bool

The idea of using numpy.nan to represent missing values is something that pandas introduced, which is why pandas has the tools to deal with it.

Datetimes too (if you use pd.NaT you won't need to specify the dtype)

In [24]: s = Series([Timestamp('20130101'),np.nan,Timestamp('20130102 9:30')],dtype='M8[ns]')

In [25]: s
Out[25]: 
0   2013-01-01 00:00:00
1                   NaT
2   2013-01-02 09:30:00
dtype: datetime64[ns]``

In [26]: pd.isnull(s)
Out[26]: 
0    False
1     True
2    False
dtype: bool

Delete file from internal storage

String dir = getFilesDir().getAbsolutePath();
File f0 = new File(dir, "myFile");
boolean d0 = f0.delete(); 
Log.w("Delete Check", "File deleted: " + dir + "/myFile " + d0);

The code File dir = getFilesDir(); doesn't work because this is a request for a File object. You're trying to retrieve the String that declares the path to your directory, so you need to declare 'dir' as a String, and then request that the directory's absolute path in String form be returned by the constructor that has access to that information.

Video auto play is not working in Safari and Chrome desktop browser

After using jQuery play() or DOM maniupulation as suggested by the other answers, it was not still working (Video wasn't autoplaying) in the Chrome for Android (Version 56.0).

As per this post in developers.google.com, From Chrome 53, the autoplay option is respected by the browser, if the video is muted.

So using autoplay muted attributes in video tag enables the video to be autoplayed in Chrome browsers from version 53.

Excerpt from the above link:

Muted autoplay for video is supported by Chrome for Android as of version 53. Playback will start automatically for a video element once it comes into view if both autoplay and muted are set[...]

<video autoplay muted>
    <source src="video.webm" type="video/webm" />
    <source src="video.mp4" type="video/mp4" />
</video>
  • Muted autoplay is supported by Safari on iOS 10 and later.
  • Autoplay, whether muted or not, is already supported on Android by Firefox and UC Browser: they do not block any kind of autoplay.

How to Use Content-disposition for force a file to download to the hard drive?

On the HTTP Response where you are returning the PDF file, ensure the content disposition header looks like:

Content-Disposition: attachment; filename=quot.pdf;

See content-disposition on the wikipedia MIME page.

Function to calculate R2 (R-squared) in R

It is not something obvious, but the caret package has a function postResample() that will calculate "A vector of performance estimates" according to the documentation. The "performance estimates" are

  • RMSE
  • Rsquared
  • mean absolute error (MAE)

and have to be accessed from the vector like this

library(caret)
vect1 <- c(1, 2, 3)
vect2 <- c(3, 2, 2)
res <- caret::postResample(vect1, vect2)
rsq <- res[2]

However, this is using the correlation squared approximation for r-squared as mentioned in another answer. I'm not sure why Max Kuhn didn't just use the conventional 1-SSE/SST.

caret also has an R2() method, although it's hard to find in the documentation.

The way to implement the normal coefficient of determination equation is:

preds <- c(1, 2, 3)
actual <- c(2, 2, 4)
rss <- sum((preds - actual) ^ 2)
tss <- sum((actual - mean(actual)) ^ 2)
rsq <- 1 - rss/tss

Not too bad to code by hand of course, but why isn't there a function for it in a language primarily made for statistics? I'm thinking I must be missing the implementation of R^2 somewhere, or no one cares enough about it to implement it. Most of the implementations, like this one, seem to be for generalized linear models.

Javascript String to int conversion

JS will think that the 0 is a string, which it actually is, to convert it to a int, use the: parseInt() function, like:

var numberAsInt = parseInt(number, 10);  
// Second arg is radix, 10 is decimal.

If the number is not possible to convert to a int, it will return NaN, so I would recommend a check for that too in code used in production or at least if you are not 100% sure of the input.

What is the best way to filter a Java Collection?

With the ForEach DSL you may write

import static ch.akuhn.util.query.Query.select;
import static ch.akuhn.util.query.Query.$result;
import ch.akuhn.util.query.Select;

Collection<String> collection = ...

for (Select<String> each : select(collection)) {
    each.yield = each.value.length() > 3;
}

Collection<String> result = $result();

Given a collection of [The, quick, brown, fox, jumps, over, the, lazy, dog] this results in [quick, brown, jumps, over, lazy], ie all strings longer than three characters.

All iteration styles supported by the ForEach DSL are

  • AllSatisfy
  • AnySatisfy
  • Collect
  • Counnt
  • CutPieces
  • Detect
  • GroupedBy
  • IndexOf
  • InjectInto
  • Reject
  • Select

For more details, please refer to https://www.iam.unibe.ch/scg/svn_repos/Sources/ForEach

change pgsql port

There should be a line in your postgresql.conf file that says:

port = 1486

Change that.

The location of the file can vary depending on your install options. On Debian-based distros it is /etc/postgresql/8.3/main/

On Windows it is C:\Program Files\PostgreSQL\9.3\data

Don't forget to sudo service postgresql restart for changes to take effect.

Configuring Hibernate logging using Log4j XML config file?

In response to homaxto's comment, this is what I have right now.

<?xml version="1.0" encoding="UTF-8" ?>
<!DOCTYPE log4j:configuration SYSTEM "log4j.dtd">

<log4j:configuration xmlns:log4j="http://jakarta.apache.org/log4j/">
    <appender name="console" class="org.apache.log4j.ConsoleAppender">
        <param name="Threshold" value="debug"/>
        <param name="Target" value="System.out"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d{ABSOLUTE} [%t] %-5p %c{1} - %m%n"/>
        </layout>
    </appender>
    <appender name="rolling-file" class="org.apache.log4j.RollingFileAppender">
        <param name="file" value="Program-Name.log"/>
        <param name="MaxFileSize" value="500KB"/>
        <param name="MaxBackupIndex" value="4"/>
        <layout class="org.apache.log4j.PatternLayout">
            <param name="ConversionPattern" value="%d [%t] %-5p %l - %m%n"/>
        </layout>
    </appender>

    <logger name="org.hibernate">
        <level value="info" />
    </logger>

    <root>
        <priority value ="debug" />
        <appender-ref ref="console" />
        <appender-ref ref="rolling-file" />
    </root>
</log4j:configuration>

The key part being

<logger name="org.hibernate">
    <level value="info" />
</logger>

Hope this helps.

How to append to the end of an empty list?

use my_list.append(...) and do not use and other list to append as list are mutable.

How to disable a input in angular2

If you want input to disable on some statement. use [readonly]=true or false instead of disabled.

<input [readonly]="this.isEditable" 
    type="text" 
    formControlName="reporteeName" 
    class="form-control" 
    placeholder="Enter Name" required>

Cell color changing in Excel using C#

For text:

[RangeObject].Font.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

For cell background

[RangeObject].Interior.Color = System.Drawing.ColorTranslator.ToOle(System.Drawing.Color.Red);

for or while loop to do something n times

but on the other hand it creates a completely useless list of integers just to loop over them. Isn't it a waste of memory, especially as far as big numbers of iterations are concerned?

That is what xrange(n) is for. It avoids creating a list of numbers, and instead just provides an iterator object.

In Python 3, xrange() was renamed to range() - if you want a list, you have to specifically request it via list(range(n)).

Cheap way to search a large text file for a string

I'm surprised no one mentioned mapping the file into memory: mmap

With this you can access the file as if it were already loaded into memory and the OS will take care of mapping it in and out as possible. Also, if you do this from 2 independent processes and they map the file "shared", they will share the underlying memory.

Once mapped, it will behave like a bytearray. You can use regular expressions, find or any of the other common methods.

Beware that this approach is a little OS specific. It will not be automatically portable.

Error occurred during initialization of boot layer FindException: Module not found

check your project build in jdk 9 or not above that eclipse is having some issues with the modules. Change it to jdk 9 then it will run fine

How to Turn Off Showing Whitespace Characters in Visual Studio IDE

If the Toggle Visual Space icon shall be added to a Visual Studio toolbar of your choice, because it shall be turned on and off via mouse click, then follow this instruction:

  1. Customize the desired toolbar

  2. Click on Customize...

  3. Click on Add Command...

  4. Go to Edit and chose Toggle Visual Space

  5. Click on OK

Tested with Visual Studio 2019.

Prevent cell numbers from incrementing in a formula in Excel

Highlight "B1" and press F4. This will lock the cell.

Now you can drag it around and it will not change. The principle is simple. It adds a dollar sign before both coordinates. A dollar sign in front of a coordinate will lock it when you copy the formula around. You can have partially locked coordinates and fully locked coordinates.

Disable scrolling in all mobile devices

This prevents scrolling on mobile devices but not the single click/tap.

document.body.addEventListener('touchstart', function(e){ e.preventDefault(); });

Best way to remove from NSMutableArray while iterating?

Nowadays you can use reversed block-based enumeration. A simple example code:

NSMutableArray *array = [@[@{@"name": @"a", @"shouldDelete": @(YES)},
                           @{@"name": @"b", @"shouldDelete": @(NO)},
                           @{@"name": @"c", @"shouldDelete": @(YES)},
                           @{@"name": @"d", @"shouldDelete": @(NO)}] mutableCopy];

[array enumerateObjectsWithOptions:NSEnumerationReverse usingBlock:^(id obj, NSUInteger idx, BOOL *stop) {
    if([obj[@"shouldDelete"] boolValue])
        [array removeObjectAtIndex:idx];
}];

Result:

(
    {
        name = b;
        shouldDelete = 0;
    },
    {
        name = d;
        shouldDelete = 0;
    }
)

another option with just one line of code:

[array filterUsingPredicate:[NSPredicate predicateWithFormat:@"shouldDelete == NO"]];

How to find out if you're using HTTPS without $_SERVER['HTTPS']

The only reliable method is the one described by Igor M.

$pv_URIprotocol = isset($_SERVER["HTTPS"]) ? (($_SERVER["HTTPS"]==="on" || $_SERVER["HTTPS"]===1 || $_SERVER["SERVER_PORT"]===$pv_sslport) ? "https://" : "http://") :  (($_SERVER["SERVER_PORT"]===$pv_sslport) ? "https://" : "http://");

Consider following: You are using nginx with fastcgi, by default(debian, ubuntu) fastgi_params contain directive:

fastcgi_param HTTPS $https;

if you are NOT using SSL, it gets translated as empty value, not 'off', not 0 and you are doomed.

http://unpec.blogspot.cz/2013/01/nette-nginx-php-fpm-redirect.html

What is the equivalent of ngShow and ngHide in Angular 2+?

for me, [hidden]=!var has never worked.

So, <div *ngIf="expression" style="display:none;">

And, <div *ngIf="expression"> Always give correct results.

How to set image for bar button with swift?

Just choose Original image option when adding an image to assets in Xcode

enter image description here

How to convert string to Title Case in Python?

just use .title(), and it will convert first letter of every word in capital, rest in small:

>>> a='mohs shahid ss'
>>> a.title()
'Mohs Shahid Ss'
>>> a='TRUE'
>>> b=a.title()
>>> b
'True'
>>> eval(b)
True

Android Fragment onClick button Method

The others have already said that methods in onClick are searched in activities, not fragments. Nevertheless, if you really want it, it is possible.

Basically, each view has a tag (probably null). We set the root view's tag to the fragment that inflated that view. Then, it is easy to search the view parents and retrieve the fragment containing the clicked button. Now, we find out the method name and use reflection to call the same method from the retrieved fragment. Easy!

in a class that extends Fragment:

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

    OnClickFragments.registerTagFragment(rootView, this); // <========== !!!!!

    return rootView;
}

public void onButtonSomething(View v) {
    Log.d("~~~","~~~ MyFragment.onButtonSomething");
    // whatever
}

all activities are derived from the same ButtonHandlingActivity:

public class PageListActivity extends ButtonHandlingActivity

ButtonHandlingActivity.java:

public class ButtonHandlingActivity extends Activity {

    public void onButtonSomething(View v) {
        OnClickFragments.invokeFragmentButtonHandlerNoExc(v);
//or, if you want to handle exceptions:
//      try {
//          OnClickFragments.invokeFragmentButtonHandler(v);
//      } catch ...
    }

}

It has to define methods for all xml onClick handlers.

com/example/customandroid/OnClickFragments.java:

package com.example.customandroid;

import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import android.app.Fragment;
import android.view.View;

public abstract class OnClickFragments {
    public static class FragmentHolder {
        Fragment fragment;
        public FragmentHolder(Fragment fragment) {
            this.fragment = fragment;
        }
    }
    public static Fragment getTagFragment(View view) {
        for (View v = view; v != null; v = (v.getParent() instanceof View) ? (View)v.getParent() : null) {
            Object tag = v.getTag();
            if (tag != null && tag instanceof FragmentHolder) {
                return ((FragmentHolder)tag).fragment;
            }
        }
        return null;
    }
    public static String getCallingMethodName(int callsAbove) {
        Exception e = new Exception();
        e.fillInStackTrace();
        String methodName = e.getStackTrace()[callsAbove+1].getMethodName();
        return methodName;
    }
    public static void invokeFragmentButtonHandler(View v, int callsAbove) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException {
        String methodName = getCallingMethodName(callsAbove+1);
        Fragment f = OnClickFragments.getTagFragment(v);
        Method m = f.getClass().getMethod(methodName, new Class[] { View.class });
        m.invoke(f, v);
    }
    public static void invokeFragmentButtonHandler(View v) throws IllegalAccessException, IllegalArgumentException, InvocationTargetException, NoSuchMethodException {
        invokeFragmentButtonHandler(v,1);
    }
    public static void invokeFragmentButtonHandlerNoExc(View v) {
        try {
            invokeFragmentButtonHandler(v,1);
        } catch (NoSuchMethodException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
        } catch (IllegalArgumentException e) {
            e.printStackTrace();
        } catch (InvocationTargetException e) {
            e.printStackTrace();
        }
    }
    public static void registerTagFragment(View rootView, Fragment fragment) {
        rootView.setTag(new FragmentHolder(fragment));
    }
}

And the next adventure will be proguard obfuscation...

PS

It is of course up to you to design your application so that the data live in the Model rather than in Activities or Fragments (which are Controllers from the MVC, Model-View-Controller point of view). The View is what you define via xml, plus the custom view classes (if you define them, most people just reuse what already is). A rule of thumb: if some data definitely must survive the screen turn, they belong to Model.

Define an alias in fish shell

For posterity, fish aliases are just functions:

$ alias foo="echo bar"
$ type foo
foo is a function with definition
function foo
    echo bar $argv; 
end

To remove it

$ unalias foo
/usr/bin/unalias: line 2: unalias: foo: not found
$ functions -e foo
$ type foo
type: Could not find “foo”

Counting number of lines, words, and characters in a text file

import java.io.*;
class wordcount
{
    public static int words=0;
    public static int lines=0;
    public static int chars=0;
    public static void wc(InputStreamReader isr)throws IOException
    {
        int c=0;
        boolean lastwhite=true;
        while((c=isr.read())!=-1)
        {
            chars++;
            if(c=='\n')
                lines++;
            if(c=='\t' || c==' ' || c=='\n')
                ++words;
            if(chars!=0)
                ++chars;
        }   
       }
    public static void main(String[] args)
    {
        FileReader fr;
        try
        {
            if(args.length==0)
            {
                wc(new InputStreamReader(System.in));
            }
            else
            {
                for(int i=0;i<args.length;i++)
                {
                    fr=new FileReader(args[i]);
                    wc(fr);
                }
            }

        }
        catch(IOException ie)
        {
            return;
        }
        System.out.println(lines+" "+words+" "+chars);
    }
}

Loop Through Each HTML Table Column and Get the Data using jQuery

You can try with textContent.

var productId = val[key].textContent;

How to send data in request body with a GET when using jQuery $.ajax()

You can send your data like the "POST" request through the "HEADERS".

Something like this:

$.ajax({
   url: "htttp://api.com/entity/list($body)",
   type: "GET",
   headers: ['id1':1, 'id2':2, 'id3':3],
   data: "",
   contentType: "text/plain",
   dataType: "json",
   success: onSuccess,
   error: onError
});

How to manage startActivityForResult on Android?

First you use startActivityForResult() with parameters in first Activity and if you want to send data from second Activity to first Activity then pass value using Intent with setResult() method and get that data inside onActivityResult() method in first Activity.

Why do people use Heroku when AWS is present? What distinguishes Heroku from AWS?

Well! I observer Heroku is famous in budding and newly born developers while AWS has advanced developer persona. DigitalOcean is also a major player in this ground. Cloudways has made it much easy to create Lamp stack in a click on DigitalOcean and AWS. Having all services and packages updates in a click is far better than doing all thing manually.

You can check out completely here: https://www.cloudways.com/blog/host-php-on-aws-cloud/

Sql connection-string for localhost server

You can also use Dot(.) for local key i.e;

Data Source=.\SQLEXPRESS;Initial Catalog=master;Integrated Security=True

If you have the default server instance i.e. MSSQLSERVER, then just use dot for Data Source.

Data Source=.;Initial Catalog=master;Integrated Security=True

What is the difference between a URI, a URL and a URN?

In order to answer this I'll lean on an answer I modified to another question. A good example of a URI is how you identify an Amazon S3 resource. Let's take:

s3://www-example-com/index.html [fig. 1]

which I created as a cached copy of

http://www.example.com/index.html [fig. 2]

in Amazon's S3-US-West-2 datacenter.

Even if StackOverflow would allow me to hyperlink to the s3:// protocol scheme, it wouldn't do you any good in locating the resource. Because it Identifies a Resource, fig. 1 is a valid URI. It is also a valid URN, because Amazon requires that the bucket (their term for the authority portion of the URI) be unique across datacenters. It is helpful in locating it, but it does not indicate the datacenter. Therefore it does not work as a URL.

So, how do URI, URL, and URN differ in this case?

NOTE: RFC 3986 defines URIs as scheme://authority/path?query#fragment

TypeError: string indices must be integers, not str // working with dict

time1 is the key of the most outer dictionary, eg, feb2012. So then you're trying to index the string, but you can only do this with integers. I think what you wanted was:

for info in courses[time1][course]:

As you're going through each dictionary, you must add another nest.

IOError: [Errno 2] No such file or directory trying to open a file

Um...

with open(os.path.join(src_dir, f)) as fin:
    for line in fin:

Also, you never output to a new file.

using batch echo with special characters

The answer from Joey was not working for me. After executing

  echo ^<?xml version="1.0" encoding="utf-8" ?^> > myfile.xml

I got this error bash: syntax error near unexpected token `>'

This solution worked for me:

 echo "<?xml version=\"1.0\" encoding=\"utf-8\">" > myfile.txt

See also http://www.robvanderwoude.com/escapechars.php

How to mount a single file in a volume

You can mount files or directories/folders it all depends on Source file or directory. And also you need to provide full path or if you are not sure you can use PWD. Here is a simple working example.

In this example, I am mounting env-commands file which already exists in my working directory

$ docker run  --rm -it -v ${PWD}/env-commands:/env-commands aravindgv/eosdt:1.0.5 /bin/bash -c "cat /env-commands"

Python wildcard search in string

Use fnmatch:

import fnmatch
lst = ['this','is','just','a','test']
filtered = fnmatch.filter(lst, 'th?s')

If you want to allow _ as a wildcard, just replace all underscores with '?' (for one character) or * (for multiple characters).

If you want your users to use even more powerful filtering options, consider allowing them to use regular expressions.

Git push error: Unable to unlink old (Permission denied)

Some files are write-protected that even git cannot over write it. Change the folder permission to allow writing e.g. sudo chmod 775 foldername

And then execute

git pull 

again

Getting 400 bad request error in Jquery Ajax POST

In case anyone else runs into this. I have a web site that was working fine on the desktop browser but I was getting 400 errors with Android devices.

It turned out to be the anti forgery token.

$.ajax({
        url: "/Cart/AddProduct/",
        data: {
            __RequestVerificationToken: $("[name='__RequestVerificationToken']").val(),
            productId: $(this).data("productcode")
        },

The problem was that the .Net controller wasn't set up correctly.

I needed to add the attributes to the controller:

    [AllowAnonymous]
    [IgnoreAntiforgeryToken]
    [DisableCors]
    [HttpPost]
    public async Task<JsonResult> AddProduct(int productId)
    {

The code needs review but for now at least I know what was causing it. 400 error not helpful at all.