Programs & Examples On #Hsc2hs

is there a function in lodash to replace matched item

As the time passes you should embrace a more functional approach in which you should avoid data mutations and write small, single responsibility functions. With the ECMAScript 6 standard, you can enjoy functional programming paradigm in JavaScript with the provided map, filter and reduce methods. You don't need another lodash, underscore or what else to do most basic things.

Down below I have included some proposed solutions to this problem in order to show how this problem can be solved using different language features:

Using ES6 map:

_x000D_
_x000D_
const replace = predicate => replacement => element =>_x000D_
  predicate(element) ? replacement : element_x000D_
 _x000D_
const arr = [ { id: 1, name: "Person 1" }, { id:2, name:"Person 2" } ];_x000D_
const predicate = element => element.id === 1_x000D_
const replacement = { id: 100, name: 'New object.' }_x000D_
_x000D_
const result = arr.map(replace (predicate) (replacement))_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_


Recursive version - equivalent of mapping:

Requires destructuring and array spread.

_x000D_
_x000D_
const replace = predicate => replacement =>_x000D_
{_x000D_
  const traverse = ([head, ...tail]) =>_x000D_
    head_x000D_
    ? [predicate(head) ? replacement : head, ...tail]_x000D_
    : []_x000D_
  return traverse_x000D_
}_x000D_
 _x000D_
const arr = [ { id: 1, name: "Person 1" }, { id:2, name:"Person 2" } ];_x000D_
const predicate = element => element.id === 1_x000D_
const replacement = { id: 100, name: 'New object.' }_x000D_
_x000D_
const result = replace (predicate) (replacement) (arr)_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_


When the final array's order is not important you can use an object as a HashMap data structure. Very handy if you already have keyed collection as an object - otherwise you have to change your representation first.

Requires object rest spread, computed property names and Object.entries.

_x000D_
_x000D_
const replace = key => ({id, ...values}) => hashMap =>_x000D_
({_x000D_
  ...hashMap,       //original HashMap_x000D_
  [key]: undefined, //delete the replaced value_x000D_
  [id]: values      //assign replacement_x000D_
})_x000D_
_x000D_
// HashMap <-> array conversion_x000D_
const toHashMapById = array =>_x000D_
  array.reduce(_x000D_
    (acc, { id, ...values }) => _x000D_
    ({ ...acc, [id]: values })_x000D_
  , {})_x000D_
  _x000D_
const toArrayById = hashMap =>_x000D_
  Object.entries(hashMap)_x000D_
  .filter( // filter out undefined values_x000D_
    ([_, value]) => value _x000D_
  ) _x000D_
  .map(_x000D_
    ([id, values]) => ({ id, ...values })_x000D_
  )_x000D_
_x000D_
const arr = [ { id: 1, name: "Person 1" }, { id:2, name:"Person 2" } ];_x000D_
const replaceKey = 1_x000D_
const replacement = { id: 100, name: 'New object.' }_x000D_
_x000D_
// Create a HashMap from the array, treating id properties as keys_x000D_
const hashMap = toHashMapById(arr)_x000D_
console.log(hashMap)_x000D_
_x000D_
// Result of replacement - notice an undefined value for replaced key_x000D_
const resultHashMap = replace (replaceKey) (replacement) (hashMap)_x000D_
console.log(resultHashMap)_x000D_
_x000D_
// Final result of conversion from the HashMap to an array_x000D_
const result = toArrayById (resultHashMap)_x000D_
console.log(result)
_x000D_
_x000D_
_x000D_

Image.open() cannot identify image file - Python?

In my case there was an empty picture in the folder. After deleting the empty .jpg's it worked normally.

How should I throw a divide by zero exception in Java without actually dividing by zero?

public class ZeroDivisionException extends ArithmeticException {
    // ...
}

if (denominator == 0) {
    throw new ZeroDivisionException();
}

Change Timezone in Lumen or Laravel 5

You just have to edit de app.php file in config directory Just find next lines

/*
|--------------------------------------------------------------------------
| Application Timezone
|--------------------------------------------------------------------------
|
| Here you may specify the default timezone for your application, which
| will be used by the PHP date and date-time functions. We have gone
| ahead and set this to a sensible default for you out of the box.
|
*/

'timezone' => 'UTC',

And.. chage it for:

'timezone' => 'Europe/Paris',

How can I detect the touch event of an UIImageView?

You can also add a UIGestureRecognizer. It does not require you to add an additional element in your view hierarchy, but still provides you will all the nicely written code for handling touch events with a fairly simple interface:

    UISwipeGestureRecognizer *swipeRight = [[UISwipeGestureRecognizer alloc]
                                            initWithTarget:self action:@selector(handleSwipe:)];
    swipeRight.direction = UISwipeGestureRecognizerDirectionRight;
    [imgView_ addGestureRecognizer:swipeRight];        
    [swipeRight release];
    UISwipeGestureRecognizer *swipeLeft = [[UISwipeGestureRecognizer alloc]
                                            initWithTarget:self action:@selector(handleSwipe:)];
    swipeLeft.direction = UISwipeGestureRecognizerDirectionLeft;
    [imgView_ addGestureRecognizer:swipeLeft];
    [swipeLeft release];

Flatten List in LINQ

If you have a List<List<int>> k you can do

List<int> flatList= k.SelectMany( v => v).ToList();

XML Error: There are multiple root elements

You can do it without modifying the XML stream: Tell the XmlReader to not be so picky. Setting the XmlReaderSettings.ConformanceLevel to ConformanceLevel.Fragment will let the parser ignore the fact that there is no root node.

        XmlReaderSettings settings = new XmlReaderSettings();
        settings.ConformanceLevel = ConformanceLevel.Fragment;
        using (XmlReader reader = XmlReader.Create(tr,settings))
        {
             ...
        }

Now you can parse something like this (which is an real time XML stream, where it is impossible to wrap with a node).

<event>
  <timeStamp>1354902435238</timeStamp>
  <eventId>7073822</eventId>
</event>
<data>
  <time>1354902435341</time>
  <payload type='80'>7d1300786a0000000bf9458b0518000000000000000000000000000000000c0c030306001b</payload>
</data>
<data>
  <time>1354902435345</time>
  <payload type='80'>fd1260780912ff3028fea5ffc0387d640fa550f40fbdf7afffe001fff8200fff00f0bf0e000042201421100224ff40312300111400004f000000e0c0fbd1e0000f10e0fccc2ff0000f0fe00f00f0eed00f11e10d010021420401</payload>
</data>
<data>
  <time>1354902435347</time>
  <payload type='80'>fd126078ad11fc4015fefdf5b042ff1010223500000000000000003007ff00f20e0f01000e0000dc0f01000f000000000000004f000000f104ff001000210f000013010000c6da000000680ffa807800200000000d00c0f0</payload>
</data>

What's the difference between VARCHAR and CHAR?

What's the difference between VARCHAR and CHAR in MySQL?

To already given answers I would like to add that in OLTP systems or in systems with frequent updates consider using CHAR even for variable size columns because of possible VARCHAR column fragmentation during updates.

I am trying to store MD5 hashes.

MD5 hash is not the best choice if security really matters. However, if you will use any hash function, consider BINARY type for it instead (e.g. MD5 will produce 16-byte hash, so BINARY(16) would be enough instead of CHAR(32) for 32 characters representing hex digits. This would save more space and be performance effective.

Why use Ruby's attr_accessor, attr_reader and attr_writer?

You may use the different accessors to communicate your intent to someone reading your code, and make it easier to write classes which will work correctly no matter how their public API is called.

class Person
  attr_accessor :age
  ...
end

Here, I can see that I may both read and write the age.

class Person
  attr_reader :age
  ...
end

Here, I can see that I may only read the age. Imagine that it is set by the constructor of this class and after that remains constant. If there were a mutator (writer) for age and the class were written assuming that age, once set, does not change, then a bug could result from code calling that mutator.

But what is happening behind the scenes?

If you write:

attr_writer :age

That gets translated into:

def age=(value)
  @age = value
end

If you write:

attr_reader :age

That gets translated into:

def age
  @age
end

If you write:

attr_accessor :age

That gets translated into:

def age=(value)
  @age = value
end

def age
  @age
end

Knowing that, here's another way to think about it: If you did not have the attr_... helpers, and had to write the accessors yourself, would you write any more accessors than your class needed? For example, if age only needed to be read, would you also write a method allowing it to be written?

check if command was successful in a batch file

Goodness I had a hard time finding the answer to this... Here it is:

cd thisDoesntExist
if %errorlevel% == 0 (
  echo Oh, I guess it does
  echo Huh.
)

JavaScript, get date of the next day

Using Date object guarantees that. For eg if you try to create April 31st :

new Date(2014,3,31)        // Thu May 01 2014 00:00:00

Please note that it's zero indexed, so Jan. is 0, Feb. is 1 etc.

nginx upload client_max_body_size issue

From the documentation:

It is necessary to keep in mind that the browsers do not know how to correctly show this error.

I suspect this is what's happening, if you inspect the HTTP to-and-fro using tools such as Firebug or Live HTTP Headers (both Firefox extensions) you'll be able to see what's really going on.

How to embed image or picture in jupyter notebook, either from a local machine or from a web resource?

Agreed, i had the same issues and this is what worked and what did not:

WORKED: <img src="Docs/pinoutDOIT32devkitv1.png" width="800"/>
*DOES NOT WORK: <img src="/Docs/pinoutDOIT32devkitv1.png" width="800"/>
DOES NOT WORK: <img src="./Docs/pinoutDOIT32devkitv1.png" width="800"/>*

How to select the last record of a table in SQL?

The last is just the first when you reverse your ordering.

How to add a .dll reference to a project in Visual Studio

You probably are looking for AddReference dialog accessible from Project Context Menu (right click..)

From there you can reference dll's, after which you can reference namespaces that you need in your code.

How do I create a shortcut via command-line in Windows?

To create a shortcut for warp-cli.exe, I based rojo's Powershell command and added WorkingDirectory, Arguments, IconLocation and minimized WindowStyle attribute to it.

powershell "$s=(New-Object -COM WScript.Shell).CreateShortcut('%userprofile%\Start Menu\Programs\Startup\CWarp_DoH.lnk');$s.TargetPath='E:\Program\CloudflareWARP\warp-cli.exe';$s.Arguments='connect';$s.IconLocation='E:\Program\CloudflareWARP\Cloudflare WARP.exe';$s.WorkingDirectory='E:\Program\CloudflareWARP';$s.WindowStyle=7;$s.Save()"

Other PS attributes for CreateShortcut: https://stackoverflow.com/a/57547816/4127357

Allow 2 decimal places in <input type="number">

Try this for allowing only 2 decimal in input type

<input type="number" step="0.01" class="form-control"  />

Or Use jQuery as suggested by @SamohtVII

$( "#ELEMENTID" ).blur(function() {
    this.value = parseFloat(this.value).toFixed(2);
});

How to import spring-config.xml of one project into spring-config.xml of another project?

For some reason, import as suggested by Ricardo didnt work for me. I got it working with following statement:

<import resource="classpath*:/spring-config.xml" />

How to set transparent background for Image Button in code?

This should work - imageButton.setBackgroundColor(android.R.color.transparent);

Matrix Transpose in Python

def transpose(matrix):
    listOfLists = []
    for row in range(len(matrix[0])):
        colList = []
        for col in range(len(matrix)):
            colList.append(matrix[col][row])
    listOfLists.append(colList)

    return listOfLists

Find a value in DataTable

Maybe you can filter rows by possible columns like this :

DataRow[] filteredRows = 
  datatable.Select(string.Format("{0} LIKE '%{1}%'", columnName, value));

Meaning of 'const' last in a function declaration of a class?

I would like to add the following point.

You can also make it a const & and const &&

So,

struct s{
    void val1() const {
     // *this is const here. Hence this function cannot modify any member of *this
    }
    void val2() const & {
    // *this is const& here
    }
    void val3() const && {
    // The object calling this function should be const rvalue only.
    }
    void val4() && {
    // The object calling this function should be rvalue reference only.
    }

};

int main(){
  s a;
  a.val1(); //okay
  a.val2(); //okay
  // a.val3() not okay, a is not rvalue will be okay if called like
  std::move(a).val3(); // okay, move makes it a rvalue
}

Feel free to improve the answer. I am no expert

How to remove an unpushed outgoing commit in Visual Studio?

Go to the Team Explorer tab then click Branches. In the branches select your branch from remotes/origin. For example, you want to reset your master branch. Right-click at the master branch in remotes/origin then select Reset then click Delete changes. This will reset your local branch and removes all locally committed changes.

How to convert an int to a hex string?

If you want to pack a struct with a value <255 (one byte unsigned, uint8_t) and end up with a string of one character, you're probably looking for the format B instead of c. C converts a character to a string (not too useful by itself) while B converts an integer.

struct.pack('B', 65)

(And yes, 65 is \x41, not \x65.)

The struct class will also conveniently handle endianness for communication or other uses.

Open Facebook page from Android app?

I have created a method to open facebook page into facebook app, if app is not existing then opening in chrome

    String socailLink="https://www.facebook.com/kfc";
    Intent intent = new Intent(Intent.ACTION_VIEW);
    String facebookUrl = Utils.getFacebookUrl(getActivity(), socailLink);
    if (facebookUrl == null || facebookUrl.length() == 0) {
        Log.d("facebook Url", " is coming as " + facebookUrl);
        return;
    }
    intent.setData(Uri.parse(facebookUrl));
    startActivity(intent);

Utils.class add these method

public static String getFacebookUrl(FragmentActivity activity, String facebook_url) {
    if (activity == null || activity.isFinishing()) return null;

    PackageManager packageManager = activity.getPackageManager();
    try {
        int versionCode = packageManager.getPackageInfo("com.facebook.katana", 0).versionCode;
        if (versionCode >= 3002850) { //newer versions of fb app
            Log.d("facebook api", "new");
            return "fb://facewebmodal/f?href=" + facebook_url;
        } else { //older versions of fb app
            Log.d("facebook api", "old");
            return "fb://page/" + splitUrl(activity, facebook_url);
        }
    } catch (PackageManager.NameNotFoundException e) {
        Log.d("facebook api", "exception");
        return facebook_url; //normal web url
    }
}

and this

 /***
 * this method used to get the facebook profile name only , this method split domain into two part index 0 contains https://www.facebook.com and index 1 contains after / part
 * @param context contain context
 * @param url contains facebook url like https://www.facebook.com/kfc
 * @return if it successfully split then return "kfc"
 *
 * if exception in splitting then return "https://www.facebook.com/kfc"
 *
 */
 public static String splitUrl(Context context, String url) {
    if (context == null) return null;
    Log.d("Split string: ", url + " ");
    try {
        String splittedUrl[] = url.split(".com/");
        Log.d("Split string: ", splittedUrl[1] + " ");
        return splittedUrl.length == 2 ? splittedUrl[1] : url;
    } catch (Exception ex) {
        return url;
    }
}

How to use OKHTTP to make a post request?

Here is my method to do post request first pass in method map and data like

HashMap<String, String> param = new HashMap<String, String>();

param.put("Name", name);
param.put("Email", email);
param.put("Password", password);
param.put("Img_Name", "");

final JSONObject result = doPostRequest(map,Url);

public static JSONObject doPostRequest(HashMap<String, String> data, String url) {

    try {
        RequestBody requestBody;
        MultipartBuilder mBuilder = new MultipartBuilder().type(MultipartBuilder.FORM);

        if (data != null) {


            for (String key : data.keySet()) {
                String value = data.get(key);
                Utility.printLog("Key Values", key + "-----------------" + value);

                mBuilder.addFormDataPart(key, value);

            }
        } else {
            mBuilder.addFormDataPart("temp", "temp");
        }
        requestBody = mBuilder.build();


        Request request = new Request.Builder()
                .url(url)
                .post(requestBody)
                .build();

        OkHttpClient client = new OkHttpClient();
        Response response = client.newCall(request).execute();
        String responseBody = response.body().string();
        Utility.printLog("URL", url);
        Utility.printLog("Response", responseBody);
        return new JSONObject(responseBody);

    } catch (UnknownHostException | UnsupportedEncodingException e) {

        JSONObject jsonObject=new JSONObject();

        try {
            jsonObject.put("status","false");
            jsonObject.put("message",e.getLocalizedMessage());
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
        Log.e(TAG, "Error: " + e.getLocalizedMessage());
    } catch (Exception e) {
        e.printStackTrace();
        JSONObject jsonObject=new JSONObject();

        try {
            jsonObject.put("status","false");
            jsonObject.put("message",e.getLocalizedMessage());
        } catch (JSONException e1) {
            e1.printStackTrace();
        }
        Log.e(TAG, "Other Error: " + e.getLocalizedMessage());
    }
    return null;
}

Auto-center map with multiple markers in Google Maps API v3

I think you have to calculate latitudine min and longitude min: Here is an Example with the function to use to center your point:

//Example values of min & max latlng values
var lat_min = 1.3049337;
var lat_max = 1.3053515;
var lng_min = 103.2103116;
var lng_max = 103.8400188;

map.setCenter(new google.maps.LatLng(
  ((lat_max + lat_min) / 2.0),
  ((lng_max + lng_min) / 2.0)
));
map.fitBounds(new google.maps.LatLngBounds(
  //bottom left
  new google.maps.LatLng(lat_min, lng_min),
  //top right
  new google.maps.LatLng(lat_max, lng_max)
));

Change the On/Off text of a toggle button Android

Set the XML as:

<ToggleButton
    android:id="@+id/flashlightButton"
    style="@style/Button"
    android:layout_above="@+id/buttonStrobeLight"
    android:layout_marginBottom="20dp"
    android:onClick="onToggleClicked"
    android:text="ToggleButton"
    android:textOn="Light ON"
    android:textOff="Light OFF" />

How do I compile and run a program in Java on my Mac?

Compiling and running a Java application on Mac OSX, or any major operating system, is very easy. Apple includes a fully-functional Java runtime and development environment out-of-the-box with OSX, so all you have to do is write a Java program and use the built-in tools to compile and run it.

Writing Your First Program

The first step is writing a simple Java program. Open up a text editor (the built-in TextEdit app works fine), type in the following code, and save the file as "HelloWorld.java" in your home directory.

public class HelloWorld {
    public static void main(String args[]) {
        System.out.println("Hello World!");
    }
}

For example, if your username is David, save it as "/Users/David/HelloWorld.java". This simple program declares a single class called HelloWorld, with a single method called main. The main method is special in Java, because it is the method the Java runtime will attempt to call when you tell it to execute your program. Think of it as a starting point for your program. The System.out.println() method will print a line of text to the screen, "Hello World!" in this example.

Using the Compiler

Now that you have written a simple Java program, you need to compile it. Run the Terminal app, which is located in "Applications/Utilities/Terminal.app". Type the following commands into the terminal:

cd ~
javac HelloWorld.java

You just compiled your first Java application, albeit a simple one, on OSX. The process of compiling will produce a single file, called "HelloWorld.class". This file contains Java byte codes, which are the instructions that the Java Virtual Machine understands.

Running Your Program

To run the program, type the following command in the terminal.

java HelloWorld

This command will start a Java Virtual Machine and attempt to load the class called HelloWorld. Once it loads that class, it will execute the main method I mentioned earlier. You should see "Hello World!" printed in the terminal window. That's all there is to it.

As a side note, TextWrangler is just a text editor for OSX and has no bearing on this situation. You can use it as your text editor in this example, but it is certainly not necessary.

What is the scope of variables in JavaScript?

Here's an example:

<script>

var globalVariable = 7; //==window.globalVariable

function aGlobal( param ) { //==window.aGlobal(); 
                            //param is only accessible in this function
  var scopedToFunction = {
    //can't be accessed outside of this function

    nested : 3 //accessible by: scopedToFunction.nested
  };

  anotherGlobal = {
    //global because there's no `var`
  }; 

}

</script>

You'll want to investigate closures, and how to use them to make private members.

How to set a tkinter window to a constant size

Here is the most simple way.

import tkinter as tk

root = tk.Tk()

root.geometry('200x200')
root.resizable(width=0, height=0)

root.mainloop()

I don't think there is anything to specify. It's pretty straight forward.

How to check if object has any properties in JavaScript?

If you're using underscore.js then you can use the _.isEmpty function:

var obj = {};
var emptyObject = _.isEmpty(obj);

Set environment variables from file of key/value pairs

-o allexport enables all following variable definitions to be exported. +o allexport disables this feature.

set -o allexport
source conf-file
set +o allexport

How to force R to use a specified factor level as reference in a regression?

Others have mentioned the relevel command which is the best solution if you want to change the base level for all analyses on your data (or are willing to live with changing the data).

If you don't want to change the data (this is a one time change, but in the future you want the default behavior again), then you can use a combination of the C (note uppercase) function to set contrasts and the contr.treatments function with the base argument for choosing which level you want to be the baseline.

For example:

lm( Sepal.Width ~ C(Species,contr.treatment(3, base=2)), data=iris )

How to get the parent dir location

os.path.abspath doesn't validate anything, so if we're already appending strings to __file__ there's no need to bother with dirname or joining or any of that. Just treat __file__ as a directory and start climbing:

# climb to __file__'s parent's parent:
os.path.abspath(__file__ + "/../../")

That's far less convoluted than os.path.abspath(os.path.join(os.path.dirname(__file__),"..")) and about as manageable as dirname(dirname(__file__)). Climbing more than two levels starts to get ridiculous.

But, since we know how many levels to climb, we could clean this up with a simple little function:

uppath = lambda _path, n: os.sep.join(_path.split(os.sep)[:-n])

# __file__ = "/aParent/templates/blog1/page.html"
>>> uppath(__file__, 1)
'/aParent/templates/blog1'
>>> uppath(__file__, 2)
'/aParent/templates'
>>> uppath(__file__, 3)
'/aParent'

MAMP mysql server won't start. No mysql processes are running

Most of the answers here are offering to delete random files.

Most of the time, this is the worst thing to do especially if it is important for you to keep the integrity of your development environment.

As explained in the log file, if this problem is not related to a read access permission nor to a file you deleted in your mysql then the only solution is to:

Open your my.conf file from the File menu in MAMP (File > Edit Template > MySQL)

Find and edit this line to be: innodb_force_recovery = 1

Save with ctrl+S

MAMP will offer you to restart your servers

Go back building the next unicorn :)

Passing null arguments to C# methods

The OP's question is answered well already, but the title is just broad enough that I think it benefits from the following primer:

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;

namespace consolePlay
{
    class Program
    {
        static void Main(string[] args)
        {
            Program.test(new DateTime());
            Program.test(null);
            //Program.test(); // <<< Error.  
            // "No overload for method 'test' takes 0 arguments"  
            // So don't mistake nullable to be optional.

            Console.WriteLine("Done.  Return to quit");
            Console.Read();
        }

        static public void test(DateTime? dteIn)
        {
            Console.WriteLine("#" + dteIn.ToString() + "#");
        }
    }
}

output:

#1/1/0001 12:00:00 AM#
##
Done.  Return to quit

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.

If there are test failures just skip them with

mvn install -DskipTests

but i strongly recomend fixing your test first.

Is there a JavaScript strcmp()?

What about

str1.localeCompare(str2)

How to inspect FormData?

Already answered but if you want to retrieve values in an easy way from a submitted form you can use the spread operator combined with creating a new Map iterable to get a nice structure.

new Map([...new FormData(form)])

Is there a way to specify how many characters of a string to print out using printf()?

In addition to specify a fixed amount of characters, you can also use * which means that printf takes the number of characters from an argument:

#include <stdio.h>

int main(int argc, char *argv[])
{
        const char hello[] = "Hello world";
        printf("message: '%.3s'\n", hello);
        printf("message: '%.*s'\n", 3, hello);
        printf("message: '%.*s'\n", 5, hello);
        return 0;
}

Prints:

message: 'Hel'
message: 'Hel'
message: 'Hello'

How to check if BigDecimal variable == 0 in java?

A simple and better way for your exemple is:

BigDecimal price;

if(BigDecimal.ZERO.compareTo(price) == 0){
    
   //Returns TRUE

}

IEnumerable vs List - What to Use? How do they work?

There is a very good article written by: Claudio Bernasconi's TechBlog here: When to use IEnumerable, ICollection, IList and List

Here some basics points about scenarios and functions:

enter image description here enter image description here

Javac is not found

As far as I can see you have the JRE in your PATH, but not the JDK.

From a command prompt try this:

set PATH=%PATH%;C:\Program Files (x86)\Java\jdk1.7.0_17\bin

Then try javac again - if this works you'll need to permanently modify your environment variables to have PATH include the JDK too.

Looping through JSON with node.js

If we are using nodeJS, we should definitely take advantage of different libraries it provides. Inbuilt functions like each(), map(), reduce() and many more from underscoreJS reduces our efforts. Here's a sample

    var _=require("underscore");
    var fs=require("fs");

    var jsonObject=JSON.parse(fs.readFileSync('YourJson.json', 'utf8'));


    _.map( jsonObject, function(content) {
        _.map(content,function(data){
           if(data.Timestamp)
              console.log(data.Timestamp)          
           })
      })

Length of a JavaScript object

The solution work for many cases and cross browser:

Code

var getTotal = function(collection) {

    var length = collection['length'];
    var isArrayObject =  typeof length == 'number' && length >= 0 && length <= Math.pow(2,53) - 1; // Number.MAX_SAFE_INTEGER

    if(isArrayObject) {
        return collection['length'];
    }

    i= 0;
    for(var key in collection) {
        if (collection.hasOwnProperty(key)) {
            i++;
        }
    }

    return i;
};

Data Examples:

// case 1
var a = new Object();
a["firstname"] = "Gareth";
a["lastname"] = "Simpson";
a["age"] = 21;

//case 2
var b = [1,2,3];

// case 3
var c = {};
c[0] = 1;
c.two = 2;

Usage

getLength(a); // 3
getLength(b); // 3
getLength(c); // 2

Pretty graphs and charts in Python

I'm the one supporting CairoPlot and I'm very proud it came up here. Surely matplotlib is great, but I believe CairoPlot is better looking. So, for presentations and websites, it's a very good choice.

Today I released version 1.1. If interested, check it out at CairoPlot v1.1

EDIT: After a long and cold winter, CairoPlot is being developed again. Check out the new version on GitHub.

sys.stdin.readline() reads without prompt, returning 'nothing in between'

stdin.read(1)

will not return when you press one character - it will wait for '\n'. The problem is that the second character is buffered in standard input, and the moment you call another input - it will return immediately because it gets its input from buffer.

Extract elements of list at odd positions

I like List comprehensions because of their Math (Set) syntax. So how about this:

L = [1, 2, 3, 4, 5, 6, 7]
odd_numbers = [y for x,y in enumerate(L) if x%2 != 0]
even_numbers = [y for x,y in enumerate(L) if x%2 == 0]

Basically, if you enumerate over a list, you'll get the index x and the value y. What I'm doing here is putting the value y into the output list (even or odd) and using the index x to find out if that point is odd (x%2 != 0).

Difference between "this" and"super" keywords in Java

super is used to access methods of the base class while this is used to access methods of the current class.

Extending the notion, if you write super(), it refers to constructor of the base class, and if you write this(), it refers to the constructor of the very class where you are writing this code.

How to go from one page to another page using javascript?

Verifying that a user is an admin in javascript leads to trouble because javascript code is visible to anyone. The server is the one who should tell the difference between an admin and a regular user AFTER the login process and then generate the new page accordingly.

Maybe that's not what you are trying to do so to answer your question:

window.location.href="<the page you are going to>";

How do I recursively delete a directory and its entire contents (files + sub dirs) in PHP?

For *nix you can use a shell_exec for rm -R or DEL /S folder_name for Windows.

Can't get value of input type="file"?

@BozidarS: FileAPI is supported quite well nowadays and provides a number of useful options.

var file = document.forms['formName']['inputName'].files[0];
//file.name == "photo.png"
//file.type == "image/png"
//file.size == 300821

How to convert WebResponse.GetResponseStream return into a string?

You can create a StreamReader around the stream, then call StreamReader.ReadToEnd().

StreamReader responseReader = new StreamReader(request.GetResponse().GetResponseStream());
var responseData = responseReader.ReadToEnd();

Is it possible to open a Windows Explorer window from PowerShell?

You have a few options:

Examples:

PS C:\> explorer
PS C:\> explorer .
PS C:\> explorer /n
PS C:\> Invoke-Item c:\path\
PS C:\> ii c:\path\
PS C:\> Invoke-Item c:\windows\explorer.exe
PS C:\> ii c:\windows\explorer.exe
PS C:\> [diagnostics.process]::start("explorer.exe")

Detect when a window is resized using JavaScript ?

This can be achieved with the onresize property of the GlobalEventHandlers interface in JavaScript, by assigning a function to the onresize property, like so:

window.onresize = functionRef;

The following code snippet demonstrates this, by console logging the innerWidth and innerHeight of the window whenever it's resized. (The resize event fires after the window has been resized)

_x000D_
_x000D_
function resize() {_x000D_
  console.log("height: ", window.innerHeight, "px");_x000D_
  console.log("width: ", window.innerWidth, "px");_x000D_
}_x000D_
_x000D_
window.onresize = resize;
_x000D_
<p>In order for this code snippet to work as intended, you will need to either shrink your browser window down to the size of this code snippet, or fullscreen this code snippet and resize from there.</p>
_x000D_
_x000D_
_x000D_

check the null terminating character in char*

You have used '/0' instead of '\0'. This is incorrect: the '\0' is a null character, while '/0' is a multicharacter literal.

Moreover, in C it is OK to skip a zero in your condition:

while (*(forward++)) {
    ...
}

is a valid way to check character, integer, pointer, etc. for being zero.

Remove attribute "checked" of checkbox

Try this to check

$('#captureImage').attr("checked",true).checkboxradio("refresh");

and uncheck

$('#captureImage').attr("checked",false).checkboxradio("refresh");  

Accessing a Shared File (UNC) From a Remote, Non-Trusted Domain With Credentials

Rather than WNetUseConnection, I would recommend NetUseAdd. WNetUseConnection is a legacy function that's been superceded by WNetUseConnection2 and WNetUseConnection3, but all of those functions create a network device that's visible in Windows Explorer. NetUseAdd is the equivalent of calling net use in a DOS prompt to authenticate on a remote computer.

If you call NetUseAdd then subsequent attempts to access the directory should succeed.

How to pause a vbscript execution?

With 'Enter' is better use ReadLine() or Read(2), because key 'Enter' generate 2 symbols. If user enter any text next Pause() also wil be skipped even with Read(2). So ReadLine() is better:

Sub Pause()
    WScript.Echo ("Press Enter to continue")
    z = WScript.StdIn.ReadLine()
End Sub

More examples look in http://technet.microsoft.com/en-us/library/ee156589.aspx

How to handle the `onKeyPress` event in ReactJS?

var Test = React.createClass({
     add: function(event){
         if(event.key === 'Enter'){
            alert('Adding....');
         }
     },
     render: function(){
        return(
           <div>
            <input type="text" id="one" onKeyPress={(event) => this.add(event)}/>    
          </div>
        );
     }
});

How do I sort arrays using vbscript?

You either have to write your own sort by hand, or maybe try this technique:

http://www.aspfaqs.com/aspfaqs/ShowFAQ.asp?FAQID=83

You can freely intermix server side javascript with VBScript, so wherever VBScript falls short, switch to javascript.

Using Environment Variables with Vue.js

This is how I edited my vue.config.js so that I could expose NODE_ENV to the frontend (I'm using Vue-CLI):

vue.config.js

const webpack = require('webpack');

// options: https://github.com/vuejs/vue-cli/blob/dev/docs/config.md
module.exports = {
    // default baseUrl of '/' won't resolve properly when app js is being served from non-root location
    baseUrl: './',
    outputDir: 'dist',
    configureWebpack: {
        plugins: [
            new webpack.DefinePlugin({
                // allow access to process.env from within the vue app
                'process.env': {
                    NODE_ENV: JSON.stringify(process.env.NODE_ENV)
                }
            })
        ]
    }
};

Adding items to an object through the .push() method

stuff is an object and push is a method of an array. So you cannot use stuff.push(..).

Lets say you define stuff as an array stuff = []; then you can call push method on it.

This works because the object[key/value] is well formed.

stuff.push( {'name':$(this).attr('checked')} );

Whereas this will not work because the object is not well formed.

stuff.push( {$(this).attr('value'):$(this).attr('checked')} );

This works because we are treating stuff as an associative array and added values to it

stuff[$(this).attr('value')] = $(this).attr('checked');

How to find GCD, LCM on a set of numbers

Basically to find gcd and lcm on a set of numbers you can use below formula,

LCM(a, b) X HCF(a, b) = a * b

Meanwhile in java you can use euclid's algorithm to find gcd and lcm, like this

public static int GCF(int a, int b)
{
    if (b == 0)
    {
       return a;
    }
    else
    {
       return (GCF(b, a % b));
    }
}

You can refer this resource to find examples on euclid's algorithm.

Delete column from pandas DataFrame

If your original dataframe df is not too big, you have no memory constraints, and you only need to keep a few columns, or, if you don't know beforehand the names of all the extra columns that you do not need, then you might as well create a new dataframe with only the columns you need:

new_df = df[['spam', 'sausage']]

How to stop line breaking in vim

It is correct that set nowrap will allow you to paste in a long line without vi/vim adding newlines, but then the line is not visually wrapped for easy reading. It is instead just one long line that you have to scroll through.

To have the line visually wrap but not have newline characters inserted into it, have set wrap (which is probably default so not needed to set) and set textwidth=0.

On some systems the setting of textwidth=0 is default. If you don't find that to be the case, add set textwidth=0 to your .exrc file so that it becomes your user's default for all vi/vim sessions.

TypeError: Cannot read property "0" from undefined

For me, the problem was I was using a package that isn't included in package.json nor installed.

import { ToastrService } from 'ngx-toastr';

So when the compiler tried to compile this, it threw an error.

(I installed it locally, and when running a build on an external server the error was thrown)

Do subclasses inherit private fields?

No. They don't inherit it.

The fact some other class may use it indirectly says nothing about inheritance, but about encapsulation.

For instance:

class Some { 
   private int count; 
   public void increment() { 
      count++;
   }
   public String toString() { 
       return Integer.toString( count );
   }
}

class UseIt { 
    void useIt() { 
        Some s = new Some();
        s.increment();
        s.increment();
        s.increment();
        int v = Integer.parseInt( s.toString() );
        // hey, can you say you inherit it?
     }
}

You can also get the value of count inside UseIt via reflection. It doesn't means, you inherit it.

UPDATE

Even though the value is there, it is not inherited by the subclass.

For instance a subclass defined as:

class SomeOther extends Some { 
    private int count = 1000;
    @Override
    public void increment() { 
        super.increment();
        count *= 10000;
    }
}

class UseIt { 
    public static void main( String ... args ) { 
        s = new SomeOther();
        s.increment();
        s.increment();
        s.increment();
        v = Integer.parseInt( s.toString() );
        // what is the value of v?           
     }
}

This is exactly the same situation as the first example. The attribute count is hidden and not inherited by the subclass at all. Still, as DigitalRoss points out, the value is there, but not by means on inheritance.

Put it this way. If your father is wealthy and gives you a credit card, you can still buy thing with his money, but doesn't mean you have inherited all that money, does it?

Other update

It is very interesting though, to know why the attribute is there.

I frankly don't have the exact term to describe it, but it's the JVM and the way it works that loads also the "not inherited" parent definition.

We could actually change the parent and the subclass will still work.

For instance:

//A.java
class A {
   private int i;
   public String toString() { return ""+ i; }
}
// B.java
class B extends A {}
// Main.java
class Main {
   public static void main( String [] args ) {
      System.out.println( new B().toString() );
    }
}
// Compile all the files
javac A.java B.java Main.java
// Run Main
java Main
// Outout is 0 as expected as B is using the A 'toString' definition
0

// Change A.java
class A {
   public String toString() {
      return "Nothing here";
   }
}
// Recompile ONLY A.java
javac A.java
java Main
// B wasn't modified and yet it shows a different behaviour, this is not due to 
// inheritance but the way Java loads the class
Output: Nothing here

I guess the exact term could be found here: The JavaTM Virtual Machine Specification

Visual Studio Code Search and Replace with Regular Expressions

So, your goal is to search and replace?
According to the Official Visual Studio's keyboard shotcuts pdf, you can press Ctrl + H on Windows and Linux, or ??F on Mac to enable search and replace tool:

Visual studio code's search & replace tab If you mean to disable the code, you just have to put <h1> in search, and replace to ####.

But if you want to use this regex instead, you may enable it in the icon: .* and use the regex: <h1>(.+?)<\/h1> and replace to: #### $1.

And as @tpartee suggested, here is some more information about Visual Studio's engine if you would like to learn more:

Downcasting in Java

Using your example, you could do:

public void doit(A a) {
    if(a instanceof B) {
        // needs to cast to B to access draw2 which isn't present in A
        // note that this is probably not a good OO-design, but that would
        // be out-of-scope for this discussion :)
        ((B)a).draw2();
    }
    a.draw();
}

Editing the date formatting of x-axis tick labels in matplotlib

In short:

import matplotlib.dates as mdates
myFmt = mdates.DateFormatter('%d')
ax.xaxis.set_major_formatter(myFmt)

Many examples on the matplotlib website. The one I most commonly use is here

NULL or BLANK fields (ORACLE)

One should NEVER treat "BLANK" and NULL as the same.

Back in the olden days before there was a SQL standard, Oracle made the design decision that empty strings in VARCHAR/ VARCHAR2 columns were NULL and that there was only one sense of NULL (there are relational theorists that would differentiate between data that has never been prompted for, data where the answer exists but is not known by the user, data where there is no answer, etc. all of which constitute some sense of NULL). By the time that the SQL standard came around and agreed that NULL and the empty string were distinct entities, there were already Oracle users that had code that assumed the two were equivalent. So Oracle was basically left with the options of breaking existing code, violating the SQL standard, or introducing some sort of initialization parameter that would change the functionality of potentially large number of queries. Violating the SQL standard (IMHO) was the least disruptive of these three options.

Oracle has left open the possibility that the VARCHAR data type would change in a future release to adhere to the SQL standard (which is why everyone uses VARCHAR2 in Oracle since that data type's behavior is guaranteed to remain the same going forward).

TypeError: 'dict_keys' object does not support indexing

You're passing the result of somedict.keys() to the function. In Python 3, dict.keys doesn't return a list, but a set-like object that represents a view of the dictionary's keys and (being set-like) doesn't support indexing.

To fix the problem, use list(somedict.keys()) to collect the keys, and work with that.

File input 'accept' attribute - is it useful?

Accept attribute was introduced in the RFC 1867, intending to enable file-type filtering based on MIME type for the file-select control. But as of 2008, most, if not all, browsers make no use of this attribute. Using client-side scripting, you can make a sort of extension based validation, for submit data of correct type (extension).

Other solutions for advanced file uploading require Flash movies like SWFUpload or Java Applets like JUpload.

Elegant ways to support equivalence ("equality") in Python classes

I think that the two terms you're looking for are equality (==) and identity (is). For example:

>>> a = [1,2,3]
>>> b = [1,2,3]
>>> a == b
True       <-- a and b have values which are equal
>>> a is b
False      <-- a and b are not the same list object

Warning: mysqli_error() expects exactly 1 parameter, 0 given error

At first, the problem is because you did't put any parameter for mysqli_error. I can see that it has been solved based on the post here. Most probably, the next problem is cause by wrong file path for the included file.. .

Are you sure this code

$myConnection = mysqli_connect("$db_host","$db_username","$db_pass","$db_name") or die ("could not connect to mysql");

is in the 'scripts' folder and your main code file is on the same level as the script folder?

Check if an object exists

Since filter returns a QuerySet, you can use count to check how many results were returned. This is assuming you don't actually need the results.

num_results = User.objects.filter(email = cleaned_info['username']).count()

After looking at the documentation though, it's better to just call len on your filter if you are planning on using the results later, as you'll only be making one sql query:

A count() call performs a SELECT COUNT(*) behind the scenes, so you should always use count() rather than loading all of the record into Python objects and calling len() on the result (unless you need to load the objects into memory anyway, in which case len() will be faster).

num_results = len(user_object)

What does 'useLegacyV2RuntimeActivationPolicy' do in the .NET 4 config?

After a bit of time (and more searching), I found this blog entry by Jomo Fisher.

One of the recent problems we’ve seen is that, because of the support for side-by-side runtimes, .NET 4.0 has changed the way that it binds to older mixed-mode assemblies. These assemblies are, for example, those that are compiled from C++\CLI. Currently available DirectX assemblies are mixed mode. If you see a message like this then you know you have run into the issue:

Mixed mode assembly is built against version 'v1.1.4322' of the runtime and cannot be loaded in the 4.0 runtime without additional configuration information.

[Snip]

The good news for applications is that you have the option of falling back to .NET 2.0 era binding for these assemblies by setting an app.config flag like so:

<startup useLegacyV2RuntimeActivationPolicy="true">
  <supportedRuntime version="v4.0"/>
</startup>

So it looks like the way the runtime loads mixed-mode assemblies has changed. I can't find any details about this change, or why it was done. But the useLegacyV2RuntimeActivationPolicy attribute reverts back to CLR 2.0 loading.

How to jump to top of browser page

_x000D_
_x000D_
// When the user scrolls down 20px from the top of the document, show the button_x000D_
window.onscroll = function() {scrollFunction()};_x000D_
_x000D_
function scrollFunction() {_x000D_
    if (document.body.scrollTop > 20 || document.documentElement.scrollTop > 20) {_x000D_
        document.getElementById("myBtn").style.display = "block";_x000D_
    } else {_x000D_
        document.getElementById("myBtn").style.display = "none";_x000D_
    }_x000D_
   _x000D_
}_x000D_
_x000D_
// When the user clicks on the button, scroll to the top of the document_x000D_
function topFunction() {_x000D_
 _x000D_
     $('html, body').animate({scrollTop:0}, 'slow');_x000D_
}
_x000D_
body {_x000D_
  font-family: Arial, Helvetica, sans-serif;_x000D_
  font-size: 20px;_x000D_
}_x000D_
_x000D_
#myBtn {_x000D_
  display: none;_x000D_
  position: fixed;_x000D_
  bottom: 20px;_x000D_
  right: 30px;_x000D_
  z-index: 99;_x000D_
  font-size: 18px;_x000D_
  border: none;_x000D_
  outline: none;_x000D_
  background-color: red;_x000D_
  color: white;_x000D_
  cursor: pointer;_x000D_
  padding: 15px;_x000D_
  border-radius: 4px;_x000D_
}_x000D_
_x000D_
#myBtn:hover {_x000D_
  background-color: #555;_x000D_
}
_x000D_
<script src="https://code.jquery.com/jquery-1.10.2.js"></script>_x000D_
_x000D_
<button onclick="topFunction()" id="myBtn" title="Go to top">Top</button>_x000D_
_x000D_
<div style="background-color:black;color:white;padding:30px">Scroll Down</div>_x000D_
<div style="background-color:lightgrey;padding:30px 30px 2500px">This example demonstrates how to create a "scroll to top" button that becomes visible when the user starts to scroll the page.</div>
_x000D_
_x000D_
_x000D_

org.apache.jasper.JasperException: Unable to compile class for JSP:

This line of yours:

<%@ page import="pageNumber.*, java.util.*, java.io.*" %>

Requires an @ symbol before % like this:

<%@ page import="pageNumber.*, java.util.*, java.io.*" @%>

Docker Networking - nginx: [emerg] host not found in upstream

If you are so lost for read the last comment. I have reached another solution.

The main problem is the way that you named the services names.

In this case, if in your docker-compose.yml, the service for php are called "api" or something like that, you must ensure that in the file nginx.conf the line that begins with fastcgi_pass have the same name as the php service. i.e fastcgi_pass api:9000;

Difference between setTimeout with and without quotes and parentheses

What happens in reality in case you pass string as a first parameter of function

setTimeout('string',number)

is value of first param got evaluated when it is time to run (after numberof miliseconds passed). Basically it is equal to

setTimeout(eval('string'), number)

This is

an alternative syntax that allows you to include a string instead of a function, which is compiled and executed when the timer expires. This syntax is not recommended for the same reasons that make using eval() a security risk.

So samples which you refer are not good samples, and may be given in different context or just simple typo.

If you invoke like this setTimeout(something, number), first parameter is not string, but pointer to a something called something. And again if something is string - then it will be evaluated. But if it is function, then function will be executed. jsbin sample

"replace" function examples

Here's two simple examples

> x <- letters[1:4]
> replace(x, 3, 'Z') #replacing 'c' by 'Z'
[1] "a" "b" "Z" "d"
> 
> y <- 1:10
> replace(y, c(4,5), c(20,30)) # replacing 4th and 5th elements by 20 and 30
 [1]  1  2  3 20 30  6  7  8  9 10

Is there a "goto" statement in bash?

You can use case in bash to simulate a goto:

#!/bin/bash

case bar in
  foo)
    echo foo
    ;&

  bar)
    echo bar
    ;&

  *)
    echo star
    ;;
esac

produces:

bar
star

Maven compile: package does not exist

You have to add the following dependency to your build:

<dependency>
    <groupId>org.openrdf.sesame</groupId>
    <artifactId>sesame-rio-api</artifactId>
    <version>2.7.2</version>
</dependency>

Furthermore i would suggest to take a deep look into the documentation about how to use the lib.

AttributeError: 'list' object has no attribute 'encode'

You need to do encode on tmp[0], not on tmp.

tmp is not a string. It contains a (Unicode) string.

Try running type(tmp) and print dir(tmp) to see it for yourself.

How to check if a String is numeric in Java

We can try replacing all the numbers from the given string with ("") ie blank space and if after that the length of the string is zero then we can say that given string contains only numbers. Example:

boolean isNumber(String str){
        if(str.length() == 0)
            return false; //To check if string is empty
        
        if(str.charAt(0) == '-')
            str = str.replaceFirst("-","");// for handling -ve numbers
    
        System.out.println(str);
        
        str = str.replaceFirst("\\.",""); //to check if it contains more than one decimal points
        
        if(str.length() == 0)
            return false; // to check if it is empty string after removing -ve sign and decimal point
        System.out.println(str);
        
        return str.replaceAll("[0-9]","").length() == 0;
    }

Virtualbox shared folder permissions

In my personal experience, it's difficult to enable shared folders in VirtualBox but it Is posible. I have a debian Buster guest virtual machine installed in my Windows 10 host.

I don't recognize exactly what did it, but I remember I went to Windows defender, my antivirus to see if they recognize VirtualBox as a program and not as a virus. After that, I press right click on the document file and allowed to share the folder and I gave click to some buttons there and accepted to share with groups and with muy user in Windows 10.

Also, I found a webpage of Windows about something like virtual machines that I don't remember well, but it took me to a panel and I had to change three things double clicking so when I update Windows, it recognizes my virtual machine. Also, in muy debian, in the terminal, using some command lines, muy VirtualBox recognized my user giving permissions, I based on some info in the Ubuntu forums. I put all what I remember.

Disable form autofill in Chrome without disabling autocomplete

My solution is based on dsuess user solution, which didn't work in IE for me, because I had to click one more time in the textbox to be able to type in. Therefore I adapted it only to Chrome:

$(window).on('load', function () {
    if (navigator.userAgent.indexOf("Chrome") != -1) {
        $('#myTextBox').attr('readonly', 'true');
        $('#myTextBox').addClass("forceWhiteBackground");
        $('#myTextBox').focus(function () {
            $('#myTextBox').removeAttr('readonly');
            $('#myTextBox').removeClass('forceWhiteBackground');
        });
    }
});

In your css add this:

.forceWhiteBackground {
    background-color:white !important;
}

How to get Text BOLD in Alert or Confirm box?

Maybe you coul'd use UTF8 bold chars.

For examples: https://yaytext.com/bold-italic/

It works on Chromium 80.0, I don't know on other browsers...

What is the use of GO in SQL Server Management Studio & Transact SQL?

Use herDatabase
GO ; 

Code says to execute the instructions above the GO marker. My default database is myDatabase, so instead of using myDatabase GO and makes current query to use herDatabase

How can I remove punctuation from input text in Java?

If you don't want to use RegEx (which seems highly unnecessary given your problem), perhaps you should try something like this:

public String modified(final String input){
    final StringBuilder builder = new StringBuilder();
    for(final char c : input.toCharArray())
        if(Character.isLetterOrDigit(c))
            builder.append(Character.isLowerCase(c) ? c : Character.toLowerCase(c));
    return builder.toString();
}

It loops through the underlying char[] in the String and only appends the char if it is a letter or digit (filtering out all symbols, which I am assuming is what you are trying to accomplish) and then appends the lower case version of the char.

How to add a button programmatically in VBA next to some sheet cell data?

I think this is enough to get you on a nice path:

Sub a()
  Dim btn As Button
  Application.ScreenUpdating = False
  ActiveSheet.Buttons.Delete
  Dim t As Range
  For i = 2 To 6 Step 2
    Set t = ActiveSheet.Range(Cells(i, 3), Cells(i, 3))
    Set btn = ActiveSheet.Buttons.Add(t.Left, t.Top, t.Width, t.Height)
    With btn
      .OnAction = "btnS"
      .Caption = "Btn " & i
      .Name = "Btn" & i
    End With
  Next i
  Application.ScreenUpdating = True
End Sub

Sub btnS()
 MsgBox Application.Caller
End Sub

It creates the buttons and binds them to butnS(). In the btnS() sub, you should show your dialog, etc.

Mathematica graphics

Injecting @Autowired private field during testing

I'm a new user for Spring. I found a different solution for this. Using reflection and making public necessary fields and assign mock objects.

This is my auth controller and it has some Autowired private properties.

@RestController
public class AuthController {

    @Autowired
    private UsersDAOInterface usersDao;

    @Autowired
    private TokensDAOInterface tokensDao;

    @RequestMapping(path = "/auth/getToken", method = RequestMethod.POST)
    public @ResponseBody Object getToken(@RequestParam String username,
            @RequestParam String password) {
        User user = usersDao.getLoginUser(username, password);

        if (user == null)
            return new ErrorResult("Kullaniciadi veya sifre hatali");

        Token token = new Token();
        token.setTokenId("aergaerg");
        token.setUserId(1);
        token.setInsertDatetime(new Date());
        return token;
    }
}

And this is my Junit test for AuthController. I'm making public needed private properties and assign mock objects to them and rock :)

public class AuthControllerTest {

    @Test
    public void getToken() {
        try {
            UsersDAO mockUsersDao = mock(UsersDAO.class);
            TokensDAO mockTokensDao = mock(TokensDAO.class);

            User dummyUser = new User();
            dummyUser.setId(10);
            dummyUser.setUsername("nixarsoft");
            dummyUser.setTopId(0);

            when(mockUsersDao.getLoginUser(Matchers.anyString(), Matchers.anyString())) //
                    .thenReturn(dummyUser);

            AuthController ctrl = new AuthController();

            Field usersDaoField = ctrl.getClass().getDeclaredField("usersDao");
            usersDaoField.setAccessible(true);
            usersDaoField.set(ctrl, mockUsersDao);

            Field tokensDaoField = ctrl.getClass().getDeclaredField("tokensDao");
            tokensDaoField.setAccessible(true);
            tokensDaoField.set(ctrl, mockTokensDao);

            Token t = (Token) ctrl.getToken("test", "aergaeg");

            Assert.assertNotNull(t);

        } catch (Exception ex) {
            System.out.println(ex);
        }
    }

}

I don't know advantages and disadvantages for this way but this is working. This technic has a little bit more code but these codes can be seperated by different methods etc. There are more good answers for this question but I want to point to different solution. Sorry for my bad english. Have a good java to everybody :)

How to Convert unsigned char* to std::string in C++?

BYTE is nothing but typedef unsigned char BYTE;

You can easily use any of below constructors

string ( const char * s, size_t n );
string ( const char * s );

TypeError: can't pickle _thread.lock objects

You need to change from queue import Queue to from multiprocessing import Queue.

The root reason is the former Queue is designed for threading module Queue while the latter is for multiprocessing.Process module.

For details, you can read some source code or contact me!

make *** no targets specified and no makefile found. stop

You had to have something like this:

"configure: error: "Error: libcrypto required."

after your ./configure runs. So you need to resolve noticed dependencies first and then try ./configure once more time and then run make !

How to pass anonymous types as parameters?

"dynamic" can also be used for this purpose.

var anonymousType = new { Id = 1, Name = "A" };

var anonymousTypes = new[] { new { Id = 1, Name = "A" }, new { Id = 2, Name = "B" };

private void DisplayAnonymousType(dynamic anonymousType)
{
}

private void DisplayAnonymousTypes(IEnumerable<dynamic> anonymousTypes)
{
   foreach (var info in anonymousTypes)
   {

   }
}

Prevent the keyboard from displaying on activity start

If you are using API level 21, you can use editText.setShowSoftInputOnFocus(false);

How do I conditionally apply CSS styles in AngularJS?

I have found problems when applying classes inside table elements when I had one class already applied to the whole table (for example, a color applied to the odd rows <myClass tbody tr:nth-child(even) td>). It seems that when you inspect the element with Developer Tools, the element.style has no style assigned. So instead of using ng-class, I have tried using ng-style, and in this case, the new CSS attribute does appear inside element.style. This code works great for me:

<tr ng-repeat="element in collection">

    [...amazing code...]

    <td ng-style="myvar === 0 && {'background-color': 'red'} ||
                  myvar === 1 && {'background-color': 'green'} ||
                  myvar === 2 && {'background-color': 'yellow'}">{{ myvar }}</td>

    [...more amazing code...]

</tr>

Myvar is what I am evaluating, and in each case I apply a style to each <td> depending on myvar value, that overwrites the current style applied by the CSS class for the whole table.

UPDATE

If you want to apply a class to the table for example, when visiting a page or in other cases, you can use this structure:

<li ng-class="{ active: isActive('/route_a') || isActive('/route_b')}">

Basically, what we need to activate a ng-class is the class to apply and a true or false statement. True applies the class and false doesn't. So here we have two checks of the route of the page and an OR between them, so if we are in /route_a OR we are in route_b, the active class will be applied.

This works just having a logic function on the right that returns true or false.

So in the first example, ng-style is conditioned by three statements. If all of them are false, no style is applied, but following our logic, at least one is going to be applied, so, the logic expression will check which variable comparison is true and because a non empty array is always true, that will left an array as return and with only one true, considering we are using OR for the whole response, the style remaining will be applied.

By the way, I forgot to give you the function isActive():

$rootScope.isActive = function(viewLocation) {
    return viewLocation === $location.path();
};

NEW UPDATE

Here you have something I find really useful. When you need to apply a class depending on the value of a variable, for example, an icon depending on the contents of the div, you can use the following code (very useful in ng-repeat):

<i class="fa" ng-class="{ 'fa-github'   : type === 0,
                          'fa-linkedin' : type === 1,
                          'fa-skype'    : type === 2,
                          'fa-google'   : type === 3 }"></i>

Icons from Font Awesome

How do I include the string header?

Use this:

#include < string>

How to tell PowerShell to wait for each command to end before starting the next?

If you use Start-Process <path to exe> -NoNewWindow -Wait

You can also use the -PassThru option to echo output.

How can I use interface as a C# generic type constraint?

Use an abstract class instead. So, you would have something like:

public bool Foo<T>() where T : CBase;

Nodemailer with Gmail and NodeJS

Just attend those: 1- Gmail authentication for allow low level emails does not accept before you restart your client browser 2- If you want to send email with nodemailer and you wouldnt like to use xouath2 protocol there you should write as secureconnection:false like below

const routes = require('express').Router();
var nodemailer = require('nodemailer');
var smtpTransport = require('nodemailer-smtp-transport');



routes.get('/test', (req, res) => {
  res.status(200).json({ message: 'test!' });
});

routes.post('/Email', (req, res) =>{

    var smtpTransport = nodemailer.createTransport({
        host: "smtp.gmail.com",
        secureConnection: false,
        port: 587,
        requiresAuth: true,
        domains: ["gmail.com", "googlemail.com"],
        auth: {
            user: "your gmail account", 
            pass: "your password*"
        }
});  

  var mailOptions = {
      from: '[email protected]',
      to:'[email protected]',
      subject: req.body.subject,
      //text: req.body.content,
      html: '<p>'+req.body.content+' </p>'
  };

  smtpTransport.sendMail(mailOptions, (error, info) => {
    if (error) {
        return console.log('Error while sending mail: ' + error);
    } else {
        console.log('Message sent: %s', info.messageId);
    }
    smtpTransport.close();
});  

})

module.exports = routes;

Creating a new column based on if-elif-else condition

enter image description here

Lets say above one is your original dataframe and you want to add a new column 'old'

If age greater than 50 then we consider as older=yes otherwise False

step 1: Get the indexes of rows whose age greater than 50

row_indexes=df[df['age']>=50].index

step 2: Using .loc we can assign a new value to column

df.loc[row_indexes,'elderly']="yes"

same for age below less than 50

row_indexes=df[df['age']<50].index

df[row_indexes,'elderly']="no"

How to make an executable JAR file?

It's too late to answer for this question. But if someone is searching for this answer now I've made it to run with no errors.

First of all make sure to download and add maven to path. [ mvn --version ] will give you version specifications of it if you have added to the path correctly.

Now , add following code to the maven project [ pom.xml ] , in the following code replace with your own main file entry point for eg [ com.example.test.Test ].

      <plugin>
            <!-- Build an executable JAR -->
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>2.4</version>
            <configuration>
                <archive>
                    <manifest>
                    <mainClass>
            your_package_to_class_that_contains_main_file .MainFileName</mainClass>
                    </manifest>
                </archive>
            </configuration>
        </plugin>

Now go to the command line [CMD] in your project and type mvn package and it will generate a jar file as something like ProjectName-0.0.1-SNAPSHOT.jar under target directory.

Now navigate to the target directory by cd target.

Finally type java -jar jar-file-name.jar and yes this should work successfully if you don't have any errors in your program.

Silent installation of a MSI package

The proper way to install an MSI silently is via the msiexec.exe command line as follows:

msiexec.exe /i c:\setup.msi /QN /L*V "C:\Temp\msilog.log"

Quick explanation:

 /L*V "C:\Temp\msilog.log"= verbose logging
 /QN = run completely silently
 /i = run install sequence 

There is a much more comprehensive answer here: Batch script to install MSI. This answer provides details on the msiexec.exe command line options and a description of how to find the "public properties" that you can set on the command line at install time. These properties are generally different for each MSI.

How do I set combobox read-only or user cannot write in a combo box only can select the given items?

The solution is to change the DropDownStyle property to DropDownList. It will help.

Not able to access adb in OS X through Terminal, "command not found"

For Mac, Android Studio 3.6.1, I added this to .bash_profile

export PATH="~/Library/Android/sdk/platform-tools/platform-tools":$PATH

Setting action for back button in navigation controller

This approach worked for me (but the "Back" button will not have the "<" sign):

- (void)viewDidLoad
{
    [super viewDidLoad];

    UIBarButtonItem* backNavButton = [[UIBarButtonItem alloc] initWithTitle:@"Back"
                                                                      style:UIBarButtonItemStyleBordered
                                                                     target:self
                                                                     action:@selector(backButtonClicked)];
    self.navigationItem.leftBarButtonItem = backNavButton;
}

-(void)backButtonClicked
{
    // Do something...
    AppDelegate* delegate = (AppDelegate*)[[UIApplication sharedApplication] delegate];
    [delegate.navController popViewControllerAnimated:YES];
}

telnet to port 8089 correct command

I believe telnet 74.255.12.25 8089 . Why don't u try both

Adding POST parameters before submit

Previous answer can be shortened and be more readable.

$('#commentForm').submit(function () {
    $(this).append($.map(params, function (param) {
        return   $('<input>', {
            type: 'hidden',
            name: param.name,
            value: param.value
        })
    }))
});

How to make MySQL table primary key auto increment with some prefix

I know it is late but I just want to share on what I have done for this. I'm not allowed to add another table or trigger so I need to generate it in a single query upon insert. For your case, can you try this query.

CREATE TABLE YOURTABLE(
IDNUMBER VARCHAR(7) NOT NULL PRIMARY KEY,
ENAME VARCHAR(30) not null
);

Perform a select and use this select query and save to the parameter @IDNUMBER

(SELECT IFNULL
     (CONCAT('LHPL',LPAD(
       (SUBSTRING_INDEX
        (MAX(`IDNUMBER`), 'LHPL',-1) + 1), 5, '0')), 'LHPL001')
    AS 'IDNUMBER' FROM YOURTABLE ORDER BY `IDNUMBER` ASC)

And then Insert query will be :

INSERT INTO YOURTABLE(IDNUMBER, ENAME) VALUES 
(@IDNUMBER, 'EMPLOYEE NAME');

The result will be the same as the other answer but the difference is, you will not need to create another table or trigger. I hope that I can help someone that have a same case as mine.

PHP foreach with Nested Array?

Both syntaxes are correct. But the result would be Array. You probably want to do something like this:

foreach ($tmpArray[1] as $value) {
  echo $value[0];
  foreach($value[1] as $val){
    echo $val;
  }
}

This will print out the string "two" ($value[0]) and the integers 4, 5 and 6 from the array ($value[1]).

Can I start the iPhone simulator without "Build and Run"?

Without opening Xcode:

open /Applications/Xcode.app/Contents/Developer/Applications/iOS\ Simulator.app/

How Many Seconds Between Two Dates?

You can do it simply.

var secondBetweenTwoDate = Math.abs((new Date().getTime() - oldDate.getTime()) / 1000);

How do I free my port 80 on localhost Windows?

For me, this problem began when I hosted a VPN-connection on my Windows 8 computer.

Simply deleting the connection from "Control Panel\Network and Internet\Network Connections" solved the problem.

Spring JPA and persistence.xml

Just to confirm though you probably did...

Did you include the

<!--  tell spring to use annotation based congfigurations -->
<context:annotation-config />
<!--  tell spring where to find the beans -->
<context:component-scan base-package="zz.yy.abcd" />

bits in your application context.xml?

Also I'm not so sure you'd be able to use a jta transaction type with this kind of setup? Wouldn't that require a data source managed connection pool? So try RESOURCE_LOCAL instead.

ROW_NUMBER() in MySQL

This could also be a solution:

SET @row_number = 0;

SELECT 
    (@row_number:=@row_number + 1) AS num, firstName, lastName
FROM
    employees

How do I test if a variable does not equal either of two values?

This can be done with a switch statement as well. The order of the conditional is reversed but this really doesn't make a difference (and it's slightly simpler anyways).

switch(test) {
    case A:
    case B:
        do other stuff;
        break;
    default:
        do stuff;
}

Redirect in Spring MVC

For completing the answers, Spring MVC uses viewResolver(for example, as axtavt metionned, InternalResourceViewResolver) to get the specific view. Therefore the first step is making sure that a viewResolver is configured.

Secondly, you should pay attention to the url of redirection(redirect or forward). A url starting with "/" means that it's a url absolute in the application. As Jigar says,

return "redirect:/index.html";  

should work. If your view locates in the root of the application, Spring can find it. If a url without a "/", such as that in your question, it means a url relative. It explains why it worked before and don't work now. If your page calling "redirect" locates in the root by chance, it works. If not, Spring can't find the view and it doesn't work.

Here is the source code of the method of RedirectView of Spring

protected void renderMergedOutputModel(  
Map<String, Object> model, HttpServletRequest request, HttpServletResponse response)  
throws IOException {  
  // Prepare target URL.  
  StringBuilder targetUrl = new StringBuilder();  
  if (this.contextRelative && getUrl().startsWith("/")) {  
    // Do not apply context path to relative URLs.  
    targetUrl.append(request.getContextPath());  
  }  
  targetUrl.append(getUrl());  

  // ...  

  sendRedirect(request, response, targetUrl.toString(), this.http10Compatible);  
}  

How can I remove a character from a string using JavaScript?

A simple functional javascript way would be

mystring = mystring.split('/r').join('/')

simple, fast, it replace globally and no need for functions or prototypes

Global variables in AngularJS

In the interest of adding another idea to the wiki pool, but what about AngularJS' value and constant modules? I'm only just starting to use them myself, but it sounds to me like these are probably the best options here.

Note: as of the time of writing, Angular 1.3.7 is the latest stable, I believe these were added in 1.2.0, haven't confirmed this with the changelog though.

Depending on how many you need to define, you might want to create a separate file for them. But I generally define these just before my app's .config() block for easy access. Because these are still effectively modules, you'll need to rely on dependency injection to use them, but they are considered "global" to your app module.

For example:

angular.module('myApp', [])
  .value('debug', true)
  .constant('ENVIRONMENT', 'development')
  .config({...})

Then inside any controller:

angular.module('myApp')
  .controller('MainCtrl', function(debug, ENVIRONMENT), {
    // here you can access `debug` and `ENVIRONMENT` as straight variables
  })

From the initial question is actually sounds like static properties are required here anyway, either as mutable (value) or final (constant). It's more my personal opinion than anything else, but I find placing runtime configuration items on the $rootScope gets too messy, too quickly.

Quick-and-dirty way to ensure only one instance of a shell script is running at a time

PID and lockfiles are definitely the most reliable. When you attempt to run the program, it can check for the lockfile which and if it exists, it can use ps to see if the process is still running. If it's not, the script can start, updating the PID in the lockfile to its own.

Performance of Java matrix math libraries?

We have used COLT for some pretty large serious financial calculations and have been very happy with it. In our heavily profiled code we have almost never had to replace a COLT implementation with one of our own.

In their own testing (obviously not independent) I think they claim within a factor of 2 of the Intel hand-optimised assembler routines. The trick to using it well is making sure that you understand their design philosophy, and avoid extraneous object allocation.

How to convert list of numpy arrays into single numpy array?

I checked some of the methods for speed performance and find that there is no difference! The only difference is that using some methods you must carefully check dimension.

Timing:

|------------|----------------|-------------------|
|            | shape (10000)  |  shape (1,10000)  |
|------------|----------------|-------------------|
| np.concat  |    0.18280     |      0.17960      |
|------------|----------------|-------------------|
|  np.stack  |    0.21501     |      0.16465      |
|------------|----------------|-------------------|
| np.vstack  |    0.21501     |      0.17181      |
|------------|----------------|-------------------|
|  np.array  |    0.21656     |      0.16833      |
|------------|----------------|-------------------|

As you can see I tried 2 experiments - using np.random.rand(10000) and np.random.rand(1, 10000) And if we use 2d arrays than np.stack and np.array create additional dimension - result.shape is (1,10000,10000) and (10000,1,10000) so they need additional actions to avoid this.

Code:

from time import perf_counter
from tqdm import tqdm_notebook
import numpy as np
l = []
for i in tqdm_notebook(range(10000)):
    new_np = np.random.rand(10000)
    l.append(new_np)



start = perf_counter()
stack = np.stack(l, axis=0 )
print(f'np.stack: {perf_counter() - start:.5f}')

start = perf_counter()
vstack = np.vstack(l)
print(f'np.vstack: {perf_counter() - start:.5f}')

start = perf_counter()
wrap = np.array(l)
print(f'np.array: {perf_counter() - start:.5f}')

start = perf_counter()
l = [el.reshape(1,-1) for el in l]
conc = np.concatenate(l, axis=0 )
print(f'np.concatenate: {perf_counter() - start:.5f}')

Delete all nodes and relationships in neo4j 1.8

As of 2.3.0 and up to 3.3.0

MATCH (n)
DETACH DELETE n

Docs

Pre 2.3.0

MATCH (n)
OPTIONAL MATCH (n)-[r]-()
DELETE n,r

Docs

Quickest way to clear all sheet contents VBA

You can use the .Clear method:

Sheets("Zeros").UsedRange.Clear

Using this you can remove the contents and the formatting of a cell or range without affecting the rest of the worksheet.

How to force HTTPS using a web.config file

In .Net Core, follow the instructions at https://docs.microsoft.com/en-us/aspnet/core/security/enforcing-ssl

In your startup.cs add the following:

// Requires using Microsoft.AspNetCore.Mvc;
public void ConfigureServices(IServiceCollection services)
{
    services.Configure<MvcOptions>(options =>
    {
        options.Filters.Add(new RequireHttpsAttribute());
    });`enter code here`

To redirect Http to Https, add the following in the startup.cs

// Requires using Microsoft.AspNetCore.Rewrite;
public void Configure(IApplicationBuilder app, IHostingEnvironment env, ILoggerFactory loggerFactory)
{
    loggerFactory.AddConsole(Configuration.GetSection("Logging"));
    loggerFactory.AddDebug();

    var options = new RewriteOptions()
       .AddRedirectToHttps();

    app.UseRewriter(options);

'any' vs 'Object'

Bit old, but doesn't hurt to add some notes.

When you write something like this

let a: any;
let b: Object;
let c: {};
  • a has no interface, it can be anything, the compiler knows nothing about its members so no type checking is performed when accessing/assigning both to it and its members. Basically, you're telling the compiler to "back off, I know what I'm doing, so just trust me";
  • b has the Object interface, so ONLY the members defined in that interface are available for b. It's still JavaScript, so everything extends Object;
  • c extends Object, like anything else in TypeScript, but adds no members. Since type compatibility in TypeScript is based on structural subtyping, not nominal subtyping, c ends up being the same as b because they have the same interface: the Object interface.

And that's why

a.doSomething(); // Ok: the compiler trusts you on that
b.doSomething(); // Error: Object has no doSomething member
c.doSomething(); // Error: c neither has doSomething nor inherits it from Object

and why

a.toString(); // Ok: whatever, dude, have it your way
b.toString(); // Ok: toString is defined in Object
c.toString(); // Ok: c inherits toString from Object

So Object and {} are equivalents in TypeScript.

If you declare functions like these

function fa(param: any): void {}
function fb(param: Object): void {}

with the intention of accepting anything for param (maybe you're going to check types at run-time to decide what to do with it), remember that

  • inside fa, the compiler will let you do whatever you want with param;
  • inside fb, the compiler will only let you reference Object's members.

It is worth noting, though, that if param is supposed to accept multiple known types, a better approach is to declare it using union types, as in

function fc(param: string|number): void {}

Obviously, OO inheritance rules still apply, so if you want to accept instances of derived classes and treat them based on their base type, as in

interface IPerson {
    gender: string;
}

class Person implements IPerson {
    gender: string;
}

class Teacher extends Person {}

function func(person: IPerson): void {
    console.log(person.gender);
}

func(new Person());     // Ok
func(new Teacher());    // Ok
func({gender: 'male'}); // Ok
func({name: 'male'});   // Error: no gender..

the base type is the way to do it, not any. But that's OO, out of scope, I just wanted to clarify that any should only be used when you don't know whats coming, and for anything else you should annotate the correct type.

UPDATE:

Typescript 2.2 added an object type, which specifies that a value is a non-primitive: (i.e. not a number, string, boolean, symbol, undefined, or null).

Consider functions defined as:

function b(x: Object) {}
function c(x: {}) {}
function d(x: object) {}

x will have the same available properties within all of these functions, but it's a type error to call d with a primitive:

b("foo"); //Okay
c("foo"); //Okay
d("foo"); //Error: "foo" is a primitive

Using fonts with Rails asset pipeline

I was having this problem on Rails 4.2 (with ruby 2.2.3) and had to edit the font-awesome _paths.scss partial to remove references to $fa-font-path and removing a leading forward slash. The following was broken:

@font-face {
  font-family: 'FontAwesome';
  src: font-url('#{$fa-font-path}/fontawesome-webfont.eot?v=#{$fa-version}');
  src: font-url('#{$fa-font-path}/fontawesome-webfont.eot?#iefix&v=#{$fa-version}') format('embedded-opentype'),
    font-url('#{$fa-font-path}/fontawesome-webfont.woff2?v=#{$fa-version}') format('woff2'),
    font-url('#{$fa-font-path}/fontawesome-webfont.woff?v=#{$fa-version}') format('woff'),
    font-url('#{$fa-font-path}/fontawesome-webfont.ttf?v=#{$fa-version}') format('truetype'),
    font-url('#{$fa-font-path}/fontawesome-webfont.svg?v=#{$fa-version}#fontawesomeregular') format('svg');
  font-weight: normal;
  font-style: normal;
}

And the following works:

@font-face {
  font-family: 'FontAwesome';
  src: font-url('fontawesome-webfont.eot?v=#{$fa-version}');
  src: font-url('fontawesome-webfont.eot?#iefix&v=#{$fa-version}') format('embedded-opentype'),
    font-url('fontawesome-webfont.woff2?v=#{$fa-version}') format('woff2'),
    font-url('fontawesome-webfont.woff?v=#{$fa-version}') format('woff'),
    font-url('fontawesome-webfont.ttf?v=#{$fa-version}') format('truetype'),
    font-url('fontawesome-webfont.svg?v=#{$fa-version}#fontawesomeregular') format('svg');
  font-weight: normal;
  font-style: normal;
}

An alternative would be to simply remove the forward slash following the interpolated $fa-font-path and then define $fa-font-path as an empty string or subdirectory with trailing forward slash (as needed).

Remember to recompile assets and restart your server as needed. For example, on a passenger setup:

prompt> rake assets:clean; rake assets:clobber
prompt> RAILS_ENV=production RAILS_GROUPS=assets rake assets:precompile
prompt> service passenger restart

Then reload your browser.

How to atomically delete keys matching a pattern using Redis

Please use this command and try :

redis-cli --raw keys "$PATTERN" | xargs redis-cli del

How to convert array into comma separated string in javascript

Use the join method from the Array type.

a.value = [a, b, c, d, e, f];
var stringValueYouWant = a.join();

The join method will return a string that is the concatenation of all the array elements. It will use the first parameter you pass as a separator - if you don't use one, it will use the default separator, which is the comma.

I need a Nodejs scheduler that allows for tasks at different intervals

I have written a node module that provides a wrapper around setInterval using moment durations providing a declarative interface:

npm install every-moment

var every = require('every-moment');

var timer = every(5, 'seconds', function() {
    console.log(this.duration);
});

every(2, 'weeks', function() {
    console.log(this.duration);
    timer.stop();
    this.set(1, 'week');
    this.start();
});

https://www.npmjs.com/package/every-moment

https://github.com/raygerrard/every-moment

How to check command line parameter in ".bat" file?

In addition to the other answers, which I subscribe, you may consider using the /I switch of the IF command.

... the /I switch, if specified, says to do case insensitive string compares.

it may be of help if you want to give case insensitive flexibility to your users to specify the parameters.

IF /I "%1"=="-b" GOTO SPECIFIC

Converting pfx to pem using openssl

Another perspective for doing it on Linux... here is how to do it so that the resulting single file contains the decrypted private key so that something like HAProxy can use it without prompting you for passphrase.

openssl pkcs12 -in file.pfx -out file.pem -nodes

Then you can configure HAProxy to use the file.pem file.


This is an EDIT from previous version where I had these multiple steps until I realized the -nodes option just simply bypasses the private key encryption. But I'm leaving it here as it may just help with teaching.

openssl pkcs12 -in file.pfx -out file.nokey.pem -nokeys
openssl pkcs12 -in file.pfx -out file.withkey.pem
openssl rsa -in file.withkey.pem -out file.key
cat file.nokey.pem file.key > file.combo.pem
  1. The 1st step prompts you for the password to open the PFX.
  2. The 2nd step prompts you for that plus also to make up a passphrase for the key.
  3. The 3rd step prompts you to enter the passphrase you just made up to store decrypted.
  4. The 4th puts it all together into 1 file.

Then you can configure HAProxy to use the file.combo.pem file.

The reason why you need 2 separate steps where you indicate a file with the key and another without the key, is because if you have a file which has both the encrypted and decrypted key, something like HAProxy still prompts you to type in the passphrase when it uses it.

How can I increase a scrollbar's width using CSS?

My experience with trying to use CSS to modify the scroll bars is don't. Only IE will let you do this.

How to insert a new line in Linux shell script?

Use this echo statement

 echo -e "Hai\nHello\nTesting\n"

The output is

Hai
Hello
Testing

DataFrame constructor not properly called! error

You are providing a string representation of a dict to the DataFrame constructor, and not a dict itself. So this is the reason you get that error.

So if you want to use your code, you could do:

df = DataFrame(eval(data))

But better would be to not create the string in the first place, but directly putting it in a dict. Something roughly like:

data = []
for row in result_set:
    data.append({'value': row["tag_expression"], 'key': row["tag_name"]})

But probably even this is not needed, as depending on what is exactly in your result_set you could probably:

  • provide this directly to a DataFrame: DataFrame(result_set)
  • or use the pandas read_sql_query function to do this for you (see docs on this)

IE8 css selector

In the light of the evolving thread, see below for a more complete answer:

IE 6

* html .ie6 {property:value;}

or

.ie6 { _property:value;}

IE 7

*+html .ie7 {property:value;}

or

*:first-child+html .ie7 {property:value;}

IE 6 and 7

@media screen\9 {
    .ie67 {property:value;}
}

or

.ie67 { *property:value;}

or

.ie67 { #property:value;}

IE 6, 7 and 8

@media \0screen\,screen\9 {
    .ie678 {property:value;}
}

IE 8

html>/**/body .ie8 {property:value;}

or

@media \0screen {
    .ie8 {property:value;}
}

IE 8 Standards Mode Only

.ie8 { property /*\**/: value\9 }

IE 8,9 and 10

@media screen\0 {
    .ie8910 {property:value;}
}

IE 9 only

@media screen and (min-width:0) and (min-resolution: .001dpcm) { 
 // IE9 CSS
 .ie9{property:value;}
}

IE 9 and above

@media screen and (min-width:0) and (min-resolution: +72dpi) {
  // IE9+ CSS
  .ie9up{property:value;}
}

IE 9 and 10

@media screen and (min-width:0) {
    .ie910{property:value;}
}

IE 10 only

_:-ms-lang(x), .ie10 { property:value\9; }

IE 10 and above

_:-ms-lang(x), .ie10up { property:value; }

or

@media all and (-ms-high-contrast: none), (-ms-high-contrast: active) {
   .ie10up{property:value;}
}

IE 11 (and above..)

_:-ms-fullscreen, :root .ie11up { property:value; }

Javascript alternatives

Modernizr

Modernizr runs quickly on page load to detect features; it then creates a JavaScript object with the results, and adds classes to the html element

User agent selection

The Javascript:

var b = document.documentElement;
        b.setAttribute('data-useragent',  navigator.userAgent);
        b.setAttribute('data-platform', navigator.platform );
        b.className += ((!!('ontouchstart' in window) || !!('onmsgesturechange' in window))?' touch':'');

Adds (e.g) the below to the html element:

data-useragent='Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; Trident/5.0; SLCC2; .NET CLR 2.0.50727; .NET CLR 3.5.30729; .NET CLR 3.0.30729; Media Center PC 6.0; .NET4.0C)'
data-platform='Win32'

Allowing very targetted CSS selectors, e.g.:

html[data-useragent*='Chrome/13.0'] .nav{
    background:url(img/radial_grad.png) center bottom no-repeat;
}

Footnote

If possible, avoid browser targeting. Identify and fix any issue(s) you identify. Support progressive enhancement and graceful degradation. With that in mind, this is an 'ideal world' scenario not always obtainable in a production environment, as such- the above should help provide some good options.


Attribution / Essential Reading

Max parallel http connections in a browser?

  1. Yes, wildcard domain will work for you.
  2. Not aware of any limits on connections. Limits if any will be browser specific.

ggplot2: sorting a plot

This seems to be what you're looking for:

g <- ggplot(x, aes(reorder(variable, value), value))
g + geom_bar() + scale_y_continuous(formatter="percent") + coord_flip()

The reorder() function will reorder your x axis items according to the value of variable.

What is the difference between Tomcat, JBoss and Glassfish?

jboss and glassfish include a servlet container(like tomcat), however the two application servers (jboss and glassfish) also provide a bean container (and a few other things aswell I imagine)

How to add/subtract time (hours, minutes, etc.) from a Pandas DataFrame.Index whos objects are of type datetime.time?

The Philippe solution but cleaner:

My subtraction data is: '2018-09-22T11:05:00.000Z'

import datetime
import pandas as pd

df_modified = pd.to_datetime(df_reference.index.values) - datetime.datetime(2018, 9, 22, 11, 5, 0)

Split column at delimiter in data frame

Just came across this question as it was linked in a recent question on SO.

Shameless plug of an answer: Use cSplit from my "splitstackshape" package:

df <- data.frame(ID=11:13, FOO=c('a|b','b|c','x|y'))
library(splitstackshape)
cSplit(df, "FOO", "|")
#   ID FOO_1 FOO_2
# 1 11     a     b
# 2 12     b     c
# 3 13     x     y

This particular function also handles splitting multiple columns, even if each column has a different delimiter:

df <- data.frame(ID=11:13, 
                 FOO=c('a|b','b|c','x|y'), 
                 BAR = c("A*B", "B*C", "C*D"))
cSplit(df, c("FOO", "BAR"), c("|", "*"))
#   ID FOO_1 FOO_2 BAR_1 BAR_2
# 1 11     a     b     A     B
# 2 12     b     c     B     C
# 3 13     x     y     C     D

Essentially, it's a fancy convenience wrapper for using read.table(text = some_character_vector, sep = some_sep) and binding that output to the original data.frame. In other words, another A base R approach could be:

df <- data.frame(ID=11:13, FOO=c('a|b','b|c','x|y'))
cbind(df, read.table(text = as.character(df$FOO), sep = "|"))
  ID FOO V1 V2
1 11 a|b  a  b
2 12 b|c  b  c
3 13 x|y  x  y

How do CORS and Access-Control-Allow-Headers work?

Yes, you need to have the header Access-Control-Allow-Origin: http://domain.com:3000 or Access-Control-Allow-Origin: * on both the OPTIONS response and the POST response. You should include the header Access-Control-Allow-Credentials: true on the POST response as well.

Your OPTIONS response should also include the header Access-Control-Allow-Headers: origin, content-type, accept to match the requested header.

Sending Arguments To Background Worker?

You can pass multiple arguments like this.

List<object> arguments = new List<object>();
arguments.Add("first");      //argument 1
arguments.Add(new Object()); //argument 2
// ...
arguments.Add(10);           //argument n

backgroundWorker.RunWorkerAsync(arguments);

private void worker_DoWork(object sender, DoWorkEventArgs e) 
{
  List<object> genericlist = e.Argument as List<object>;
  //extract your multiple arguments from 
  //this list and cast them and use them. 
}

How to do sed like text replace with python?

massedit.py (http://github.com/elmotec/massedit) does the scaffolding for you leaving just the regex to write. It's still in beta but we are looking for feedback.

python -m massedit -e "re.sub(r'^# deb', 'deb', line)" /etc/apt/sources.list

will show the differences (before/after) in diff format.

Add the -w option to write the changes to the original file:

python -m massedit -e "re.sub(r'^# deb', 'deb', line)" -w /etc/apt/sources.list

Alternatively, you can now use the api:

>>> import massedit
>>> filenames = ['/etc/apt/sources.list']
>>> massedit.edit_files(filenames, ["re.sub(r'^# deb', 'deb', line)"], dry_run=True)

Convert string to number field

Within Crystal, you can do it by creating a formula that uses the ToNumber function. It might be a good idea to code for the possibility that the field might include non-numeric data - like so:

If NumericText ({field}) then ToNumber ({field}) else 0

Alternatively, you might find it easier to convert the field's datatype within the query used in the report.

Border length smaller than div width?

Another way to do this (in modern browsers) is with a negative spread box-shadow. Check out this updated fiddle: http://jsfiddle.net/WuZat/290/

box-shadow: 0px 24px 3px -24px magenta;

I think the safest and most compatible way is the accepted answer above, though. Just thought I'd share another technique.

Missing visible-** and hidden-** in Bootstrap v4

http://v4-alpha.getbootstrap.com/layout/responsive-utilities/

You now have to define the size of what is being hidden as so

.hidden-xs-down

Will hide anythinging from xs and smaller, only xs

.hidden-xs-up

Will hide everything

How to prevent scrollbar from repositioning web page?

If the width of the table won't change, you can set the width of the element (such as tbody) that contains the scrollbar > 100% (allowing extra space for the scrollbar) and set overflow-y to "overlay" (so that the scrollbar stays fixed, and won't shift the table left when it appears). Also set a fixed height for the element with the scrollbar, so the scrollbar will appear once the height is exceeded. Like so:

tbody {
  height: 100px;
  overflow-y: overlay;
  width: 105%
}

Note: you will have to manually adjust the width % as the % of space the scrollbar takes up will be relative to your table width (ie: smaller width of table, more % required to fit the scrollbar, as it's size in pixels is constant)

A dynamic table example:

_x000D_
_x000D_
function addRow(tableID)_x000D_
{_x000D_
    var table = document.getElementById(tableID);_x000D_
    var rowCount = table.rows.length;_x000D_
    var row = table.insertRow(rowCount);_x000D_
    var colCount = table.rows[0].cells.length;_x000D_
  _x000D_
    for(var i=0; i<colCount; i++)_x000D_
    {_x000D_
        var newRow = row.insertCell(i);_x000D_
_x000D_
        newRow.innerHTML = table.rows[0].cells[i].innerHTML;_x000D_
        newRow.childNodes[0].value = "";_x000D_
    }_x000D_
}_x000D_
 _x000D_
function deleteRow(row)_x000D_
{_x000D_
    var table = document.getElementById("data");_x000D_
    var rowCount = table.rows.length;_x000D_
    var rowIndex = row.parentNode.parentNode.rowIndex;_x000D_
_x000D_
    document.getElementById("data").deleteRow(rowIndex);_x000D_
}
_x000D_
.scroll-table {_x000D_
  border-collapse: collapse;_x000D_
}_x000D_
_x000D_
.scroll-table tbody {_x000D_
  display:block;_x000D_
  overflow-y:overlay;_x000D_
  height:60px;_x000D_
  width: 105%_x000D_
}_x000D_
_x000D_
.scroll-table tbody td {_x000D_
  color: #333;_x000D_
  padding: 10px;_x000D_
  text-shadow: 1px 1px 1px #fff;_x000D_
}_x000D_
_x000D_
.scroll-table thead tr {_x000D_
  display:block;_x000D_
}_x000D_
_x000D_
.scroll-table td {_x000D_
    border-top: thin solid; _x000D_
    border-bottom: thin solid;_x000D_
}_x000D_
_x000D_
.scroll-table td:first-child {_x000D_
    border-left: thin solid;_x000D_
}_x000D_
_x000D_
.scroll-table td:last-child {_x000D_
    border-right: thin solid;_x000D_
}_x000D_
_x000D_
.scroll-table tr:first-child {_x000D_
    display: none;_x000D_
}_x000D_
_x000D_
.delete_button {_x000D_
    background-color: red;_x000D_
    color: white;_x000D_
}_x000D_
_x000D_
.container {_x000D_
  display: inline-block;_x000D_
}_x000D_
_x000D_
body {_x000D_
  text-align: center;_x000D_
}
_x000D_
<!DOCTYPE html>_x000D_
<html lang="en">_x000D_
<head>_x000D_
  <link rel="stylesheet" href="test_table.css">_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
<h1>Dynamic Table</h1>_x000D_
<div class="container">_x000D_
_x000D_
  <table id="data" class="scroll-table">_x000D_
    <tbody>_x000D_
      <tr>_x000D_
        <td><input type="text" /></td>_x000D_
        <td><input type="text" /></td>_x000D_
        <td><input type="button" class="delete_button" value="X" onclick="deleteRow(this)"></td>_x000D_
      </tr>_x000D_
    </tbody>_x000D_
  </table>_x000D_
_x000D_
  <input type="button" value="Add" onclick="addRow('data')" />_x000D_
_x000D_
</div>_x000D_
_x000D_
<script src="test_table.js"></script>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to deal with a slow SecureRandom generator?

It sounds like you should be clearer about your RNG requirements. The strongest cryptographic RNG requirement (as I understand it) would be that even if you know the algorithm used to generate them, and you know all previously generated random numbers, you could not get any useful information about any of the random numbers generated in the future, without spending an impractical amount of computing power.

If you don't need this full guarantee of randomness then there are probably appropriate performance tradeoffs. I would tend to agree with Dan Dyer's response about AESCounterRNG from Uncommons-Maths, or Fortuna (one of its authors is Bruce Schneier, an expert in cryptography). I've never used either but the ideas appear reputable at first glance.

I would think that if you could generate an initial random seed periodically (e.g. once per day or hour or whatever), you could use a fast stream cipher to generate random numbers from successive chunks of the stream (if the stream cipher uses XOR then just pass in a stream of nulls or grab the XOR bits directly). ECRYPT's eStream project has lots of good information including performance benchmarks. This wouldn't maintain entropy between the points in time that you replenish it, so if someone knew one of the random numbers and the algorithm you used, technically it might be possible, with a lot of computing power, to break the stream cipher and guess its internal state to be able to predict future random numbers. But you'd have to decide whether that risk and its consequences are sufficient to justify the cost of maintaining entropy.

Edit: here's some cryptographic course notes on RNG I found on the 'net that look very relevant to this topic.

Error :The remote server returned an error: (401) Unauthorized

Shouldn't you be providing the credentials for your site, instead of passing the DefaultCredentials?

Something like request.Credentials = new NetworkCredential("UserName", "PassWord");

Also, remove request.UseDefaultCredentials = true; request.PreAuthenticate = true;

What is the best way to insert source code examples into a Microsoft Word document?

I absolutely hate and despise working for free for Microsoft, given how after all those billions of dollars they STILL do not to have proper guides about stuff like this with screenshots on their damn website.

Anyways, here is a quick guide in Word 2010, using Notepad++ for syntax coloring, and a TextBox which can be captioned:

  1. Choose Insert / Text Box / Simple Text Box
    01word
  2. A default text box is inserted
    02word
  3. Switch to NPP, choose the language for syntax coloring of your code, go to Plugins / NPPExport / Copy RTF to clipboard
    03npp
  4. Switch back to word, and paste into the text box - it may be too small ...
    04word
  5. ... so you may have to change its size
    05word
  6. Having selected the text box, right-click on it, then choose Insert Caption ...
    06word
  7. In the Caption menu, if you don't have one already, click New Label, and set the new label to "Code", click OK ...
    07word
  8. ... then in the Caption dialog, switch the label to Code, and hit OK
    08word
  9. Finally, type your caption in the newly created caption box
    09word

jQuery validation: change default error message

instead of these custom error messages we can specify the type of the text field.

Ex: set type of the field in to type = 'email'

then plugin will identify the field and validate correctly.

Is this the proper way to do boolean test in SQL?

With Postgres, you may use

select * from users where active

or

select * from users where active = 't'

If you want to use integer value, you have to consider it as a string. You can't use integer value.

select * from users where active = 1   -- Does not work

select * from users where active = '1' -- Works 

Java: how do I get a class literal from a generic type?

Well as we all know that it gets erased. But it can be known under some circumstances where the type is explicitly mentioned in the class hierarchy:

import java.lang.reflect.*;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

public abstract class CaptureType<T> {
    /**
     * {@link java.lang.reflect.Type} object of the corresponding generic type. This method is useful to obtain every kind of information (including annotations) of the generic type.
     *
     * @return Type object. null if type could not be obtained (This happens in case of generic type whose information cant be obtained using Reflection). Please refer documentation of {@link com.types.CaptureType}
     */
    public Type getTypeParam() {
        Class<?> bottom = getClass();
        Map<TypeVariable<?>, Type> reifyMap = new LinkedHashMap<>();

        for (; ; ) {
            Type genericSuper = bottom.getGenericSuperclass();
            if (!(genericSuper instanceof Class)) {
                ParameterizedType generic = (ParameterizedType) genericSuper;
                Class<?> actualClaz = (Class<?>) generic.getRawType();
                TypeVariable<? extends Class<?>>[] typeParameters = actualClaz.getTypeParameters();
                Type[] reified = generic.getActualTypeArguments();
                assert (typeParameters.length != 0);
                for (int i = 0; i < typeParameters.length; i++) {
                    reifyMap.put(typeParameters[i], reified[i]);
                }
            }

            if (bottom.getSuperclass().equals(CaptureType.class)) {
                bottom = bottom.getSuperclass();
                break;
            }
            bottom = bottom.getSuperclass();
        }

        TypeVariable<?> var = bottom.getTypeParameters()[0];
        while (true) {
            Type type = reifyMap.get(var);
            if (type instanceof TypeVariable) {
                var = (TypeVariable<?>) type;
            } else {
                return type;
            }
        }
    }

    /**
     * Returns the raw type of the generic type.
     * <p>For example in case of {@code CaptureType<String>}, it would return {@code Class<String>}</p>
     * For more comprehensive examples, go through javadocs of {@link com.types.CaptureType}
     *
     * @return Class object
     * @throws java.lang.RuntimeException If the type information cant be obtained. Refer documentation of {@link com.types.CaptureType}
     * @see com.types.CaptureType
     */
    public Class<T> getRawType() {
        Type typeParam = getTypeParam();
        if (typeParam != null)
            return getClass(typeParam);
        else throw new RuntimeException("Could not obtain type information");
    }


    /**
     * Gets the {@link java.lang.Class} object of the argument type.
     * <p>If the type is an {@link java.lang.reflect.ParameterizedType}, then it returns its {@link java.lang.reflect.ParameterizedType#getRawType()}</p>
     *
     * @param type The type
     * @param <A>  type of class object expected
     * @return The Class<A> object of the type
     * @throws java.lang.RuntimeException If the type is a {@link java.lang.reflect.TypeVariable}. In such cases, it is impossible to obtain the Class object
     */
    public static <A> Class<A> getClass(Type type) {
        if (type instanceof GenericArrayType) {
            Type componentType = ((GenericArrayType) type).getGenericComponentType();
            Class<?> componentClass = getClass(componentType);
            if (componentClass != null) {
                return (Class<A>) Array.newInstance(componentClass, 0).getClass();
            } else throw new UnsupportedOperationException("Unknown class: " + type.getClass());
        } else if (type instanceof Class) {
            Class claz = (Class) type;
            return claz;
        } else if (type instanceof ParameterizedType) {
            return getClass(((ParameterizedType) type).getRawType());
        } else if (type instanceof TypeVariable) {
            throw new RuntimeException("The type signature is erased. The type class cant be known by using reflection");
        } else throw new UnsupportedOperationException("Unknown class: " + type.getClass());
    }

    /**
     * This method is the preferred method of usage in case of complex generic types.
     * <p>It returns {@link com.types.TypeADT} object which contains nested information of the type parameters</p>
     *
     * @return TypeADT object
     * @throws java.lang.RuntimeException If the type information cant be obtained. Refer documentation of {@link com.types.CaptureType}
     */
    public TypeADT getParamADT() {
        return recursiveADT(getTypeParam());
    }

    private TypeADT recursiveADT(Type type) {
        if (type instanceof Class) {
            return new TypeADT((Class<?>) type, null);
        } else if (type instanceof ParameterizedType) {
            ArrayList<TypeADT> generic = new ArrayList<>();
            ParameterizedType type1 = (ParameterizedType) type;
            return new TypeADT((Class<?>) type1.getRawType(),
                    Arrays.stream(type1.getActualTypeArguments()).map(x -> recursiveADT(x)).collect(Collectors.toList()));
        } else throw new UnsupportedOperationException();
    }

}

public class TypeADT {
    private final Class<?> reify;
    private final List<TypeADT> parametrized;

    TypeADT(Class<?> reify, List<TypeADT> parametrized) {
        this.reify = reify;
        this.parametrized = parametrized;
    }

    public Class<?> getRawType() {
        return reify;
    }

    public List<TypeADT> getParameters() {
        return parametrized;
    }
}

And now you can do things like:

static void test1() {
        CaptureType<String> t1 = new CaptureType<String>() {
        };
        equals(t1.getRawType(), String.class);
    }

    static void test2() {
        CaptureType<List<String>> t1 = new CaptureType<List<String>>() {
        };
        equals(t1.getRawType(), List.class);
        equals(t1.getParamADT().getParameters().get(0).getRawType(), String.class);
    }


    private static void test3() {
            CaptureType<List<List<String>>> t1 = new CaptureType<List<List<String>>>() {
            };
            equals(t1.getParamADT().getRawType(), List.class);
        equals(t1.getParamADT().getParameters().get(0).getRawType(), List.class);
    }

    static class Test4 extends CaptureType<List<String>> {
    }

    static void test4() {
        Test4 test4 = new Test4();
        equals(test4.getParamADT().getRawType(), List.class);
    }

    static class PreTest5<S> extends CaptureType<Integer> {
    }

    static class Test5 extends PreTest5<Integer> {
    }

    static void test5() {
        Test5 test5 = new Test5();
        equals(test5.getTypeParam(), Integer.class);
    }

    static class PreTest6<S> extends CaptureType<S> {
    }

    static class Test6 extends PreTest6<Integer> {
    }

    static void test6() {
        Test6 test6 = new Test6();
        equals(test6.getTypeParam(), Integer.class);
    }



    class X<T> extends CaptureType<T> {
    }

    class Y<A, B> extends X<B> {
    }

    class Z<Q> extends Y<Q, Map<Integer, List<List<List<Integer>>>>> {
    }

    void test7(){
        Z<String> z = new Z<>();
        TypeADT param = z.getParamADT();
        equals(param.getRawType(), Map.class);
        List<TypeADT> parameters = param.getParameters();
        equals(parameters.get(0).getRawType(), Integer.class);
        equals(parameters.get(1).getRawType(), List.class);
        equals(parameters.get(1).getParameters().get(0).getRawType(), List.class);
        equals(parameters.get(1).getParameters().get(0).getParameters().get(0).getRawType(), List.class);
        equals(parameters.get(1).getParameters().get(0).getParameters().get(0).getParameters().get(0).getRawType(), Integer.class);
    }




    static void test8() throws IllegalAccessException, InstantiationException {
        CaptureType<int[]> type = new CaptureType<int[]>() {
        };
        equals(type.getRawType(), int[].class);
    }

    static void test9(){
        CaptureType<String[]> type = new CaptureType<String[]>() {
        };
        equals(type.getRawType(), String[].class);
    }

    static class SomeClass<T> extends CaptureType<T>{}
    static void test10(){
        SomeClass<String> claz = new SomeClass<>();
        try{
            claz.getRawType();
            throw new RuntimeException("Shouldnt come here");
        }catch (RuntimeException ex){

        }
    }

    static void equals(Object a, Object b) {
        if (!a.equals(b)) {
            throw new RuntimeException("Test failed. " + a + " != " + b);
        }
    }

More info here. But again, it is almost impossible to retrieve for:

class SomeClass<T> extends CaptureType<T>{}
SomeClass<String> claz = new SomeClass<>();

where it gets erased.

How do I select and store columns greater than a number in pandas?

Sample DF:

In [79]: df = pd.DataFrame(np.random.randint(5, 15, (10, 3)), columns=list('abc'))

In [80]: df
Out[80]:
    a   b   c
0   6  11  11
1  14   7   8
2  13   5  11
3  13   7  11
4  13   5   9
5   5  11   9
6   9   8   6
7   5  11  10
8   8  10  14
9   7  14  13

present only those rows where b > 10

In [81]: df[df.b > 10]
Out[81]:
   a   b   c
0  6  11  11
5  5  11   9
7  5  11  10
9  7  14  13

Minimums (for all columns) for the rows satisfying b > 10 condition

In [82]: df[df.b > 10].min()
Out[82]:
a     5
b    11
c     9
dtype: int32

Minimum (for the b column) for the rows satisfying b > 10 condition

In [84]: df.loc[df.b > 10, 'b'].min()
Out[84]: 11

UPDATE: starting from Pandas 0.20.1 the .ix indexer is deprecated, in favor of the more strict .iloc and .loc indexers.

How do I find out what License has been applied to my SQL Server installation?

When I run:

   exec sp_readerrorlog @p1 = 0
   ,@p2 = 1
   ,@p3 = N'licensing'

I get:

SQL Server detected 2 sockets with 21 cores per socket and 21 logical processors per socket, 42 total logical processors; using 20 logical processors based on SQL Server licensing. This is an informational message; no user action is required.

also, SELECT @@VERSION shows:

Microsoft SQL Server 2014 (SP1-GDR) (KB4019091) - 12.0.4237.0 (X64) Jul 5 2017 22:03:42 Copyright (c) Microsoft Corporation Enterprise Edition (64-bit) on Windows NT 6.3 (Build 9600: ) (Hypervisor)

This is a VM

Send POST parameters with MultipartFormData using Alamofire, in iOS Swift

Alamofire 5 and above

AF.upload(multipartFormData: { multipartFormData in
    multipartFormData.append(Data("one".utf8), withName: "one")
    multipartFormData.append(Data("two".utf8), withName: "two")
}, 
to: "https://httpbin.org/post").responseDecodable(of: MultipartResponse.self) { response in
        debugPrint(response)
}

documentation link: multipart upload

jQuery using append with effects

Having effects on append won't work because the content the browser displays is updated as soon as the div is appended. So, to combine Mark B's and Steerpike's answers:

Style the div you're appending as hidden before you actually append it. You can do it with inline or external CSS script, or just create the div as

<div id="new_div" style="display: none;"> ... </div>

Then you can chain effects to your append (demo):

$('#new_div').appendTo('#original_div').show('slow');

Or (demo):

var $new = $('#new_div');
$('#original_div').append($new);
$new.show('slow');

Regex to get the words after matching string

This might work out for you depending on which language you are using:

(?<=Object Name:).*

It's a positive lookbehind assertion. More information could be found here.

It won't work with JavaScript though. In your comment I read that you're using it for logstash. If you are using GROK parsing for logstash then it would work. You can verify it yourself here:

https://grokdebug.herokuapp.com/

Enter image description here

Random Number Between 2 Double Numbers

If you need a random number in the range [double.MinValue; double.MaxValue]

// Because of:
double.MaxValue - double.MinValue == double.PositiveInfinity

// This will be equals to NaN or PositiveInfinity
random.NextDouble() * (double.MaxValue - double.MinValue)

Use instead:

public static class RandomExtensions
{
    public static double NextDoubleInMinMaxRange(this Random random)
    {
        var bytes = new byte[sizeof(double)];
        var value = default(double);
        while (true)
        {
            random.NextBytes(bytes);
            value = BitConverter.ToDouble(bytes, 0);
            if (!double.IsNaN(value) && !double.IsInfinity(value))
                return value;
        }
    }
}

Send JSON data with jQuery

It gets serialized so that the URI can read the name value pairs in the POST request by default. You could try setting processData:false to your list of params. Not sure if that would help.

How to create a dotted <hr/> tag?

You could just have <hr style="border-top: dotted 1px;" /> . That should work.

Deprecated meaning?

I think the Wikipedia-article on Deprecation answers this one pretty well:

In the process of authoring computer software, its standards or documentation, deprecation is a status applied to software features to indicate that they should be avoided, typically because they have been superseded. Although deprecated features remain in the software, their use may raise warning messages recommending alternative practices, and deprecation may indicate that the feature will be removed in the future. Features are deprecated—rather than immediately removed—in order to provide backward compatibility, and give programmers who have used the feature time to bring their code into compliance with the new standard.

Getting selected value of a combobox

Try this:

private void comboBox1_SelectedIndexChanged(object sender, EventArgs e)
{
    ComboBox cmb = (ComboBox)sender;
    int selectedIndex = cmb.SelectedIndex;
    int selectedValue = (int)cmb.SelectedValue;

    ComboboxItem selectedCar = (ComboboxItem)cmb.SelectedItem;
    MessageBox.Show(String.Format("Index: [{0}] CarName={1}; Value={2}", selectedIndex, selectedCar.Text, selecteVal));        
}

How to generate a random string in Ruby

Create an empty string or a pre-fix if require:

myStr = "OID-"

Use this code to populate the string with random numbers:

begin; n = ((rand * 43) + 47).ceil; myStr << n.chr if !(58..64).include?(n); end while(myStr.length < 12)

Notes:

(rand * 43) + 47).ceil

It will generate random numbers from 48-91 (0,1,2..Y,Z)

!(58..64).include?(n)

It is used to skip special characters (as I am not interested to include them)

while(myStr.length < 12)

It will generate total 12 characters long string including prefix.

Sample Output:

"OID-XZ2J32XM"

Replacing a fragment with another fragment inside activity group

You Can Use This code

((AppCompatActivity) getActivity()).getSupportFragmentManager().beginTransaction().replace(R.id.YourFrameLayout, new YourFragment()).commit();

or You Can This Use Code

YourFragment fragments=(YourFragment) getSupportFragmentManager().findFragmentById(R.id.FrameLayout);

        if (fragments==null) {
            getSupportFragmentManager().beginTransaction().replace(R.id.FrameLayout, new Fragment_News()).commit();
        }

Static constant string (class member)

This is just extra information, but if you really want the string in a header file, try something like:

class foo
{
public:
    static const std::string& RECTANGLE(void)
    {
        static const std::string str = "rectangle";

        return str;
    }
};

Though I doubt that's recommended.

Table row and column number in jQuery

$('td').click(function() {
    var myCol = $(this).index();
    var $tr = $(this).closest('tr');
    var myRow = $tr.index();
});

Is there any way to configure multiple registries in a single npmrc file

You can have multiple registries for scoped packages in your .npmrc file. For example:

@polymer:registry=<url register A>
registry=http://localhost:4873/

Packages under @polymer scope will be received from https://registry.npmjs.org, but the rest will be received from your local NPM.

PHP display current server path

If you call getcwd it should give you the path:

<?php
  echo getcwd();
?>

A network-related or instance-specific error occurred while establishing a connection to SQL Server

Sql Server fire this error when your application don't have enough rights to access the database. there are several reason about this error . To fix this error you should follow the following instruction.

  1. Try to connect sql server from your server using management studio . if you use windows authentication to connect sql server then set your application pool identity to server administrator .

  2. if you use sql server authentication then check you connection string in web.config of your web application and set user id and password of sql server which allows you to log in .

  3. if your database in other server(access remote database) then first of enable remote access of sql server form sql server property from sql server management studio and enable TCP/IP form sql server configuration manager .

  4. after doing all these stuff and you still can't access the database then check firewall of server form where you are trying to access the database and add one rule in firewall to enable port of sql server(by default sql server use 1433 , to check port of sql server you need to check sql server configuration manager network protocol TCP/IP port).

  5. if your sql server is running on named instance then you need to write port number with sql serer name for example 117.312.21.21/nameofsqlserver,1433.

  6. If you are using cloud hosting like amazon aws or microsoft azure then server or instance will running behind cloud firewall so you need to enable 1433 port in cloud firewall if you have default instance or specific port for sql server for named instance.

  7. If you are using amazon RDS or SQL azure then you need to enable port from security group of that instance.

  8. If you are accessing sql server through sql server authentication mode them make sure you enabled "SQL Server and Windows Authentication Mode" sql server instance property. enter image description here

    1. Restart your sql server instance after making any changes in property as some changes will require restart.

if you further face any difficulty then you need to provide more information about your web site and sql server .

Turning off hibernate logging console output

Important notice: the property (part of hibernate configuration, NOT part of logging framework config!)

hibernate.show_sql

controls the logging directly to STDOUT bypassing any logging framework (which you can recognize by the missing output formatting of the messages). If you use a logging framework like log4j, you should always set that property to false because it gives you no benefit at all.

That circumstance irritated me quite a long time because I never really cared about it until I tried to write some benchmark regarding Hibernate.

Python list directory, subdirectory, and files

You can take a look at this sample I made. It uses the os.path.walk function which is deprecated beware.Uses a list to store all the filepaths

root = "Your root directory"
ex = ".txt"
where_to = "Wherever you wanna write your file to"
def fileWalker(ext,dirname,names):
    '''
    checks files in names'''
    pat = "*" + ext[0]
    for f in names:
        if fnmatch.fnmatch(f,pat):
            ext[1].append(os.path.join(dirname,f))


def writeTo(fList):

    with open(where_to,"w") as f:
        for di_r in fList:
            f.write(di_r + "\n")






if __name__ == '__main__':
    li = []
    os.path.walk(root,fileWalker,[ex,li])

    writeTo(li)

Copying files into the application folder at compile time

You want to use a Post-Build event on your project. You can specify the output there and there are macro values for frequently used things like project path, item name, etc.

String is immutable. What exactly is the meaning?

String is immutable means that you cannot change the object itself, but you can change the reference to the object.

When you execute a = "ty", you are actually changing the reference of a to a new object created by the String literal "ty".

Changing an object means to use its methods to change one of its fields (or the fields are public and not final, so that they can be updated from outside without accessing them via methods), for example:

Foo x = new Foo("the field");
x.setField("a new field");
System.out.println(x.getField()); // prints "a new field"

While in an immutable class (declared as final, to prevent modification via inheritance)(its methods cannot modify its fields, and also the fields are always private and recommended to be final), for example String, you cannot change the current String but you can return a new String, i.e:

String s = "some text";
s.substring(0,4);
System.out.println(s); // still printing "some text"
String a = s.substring(0,4);
System.out.println(a); // prints "some"

Exploitable PHP functions

Apart from the eval language construct there is another function which allows arbitrary code execution: assert

assert('ex' . 'ec("kill --bill")');

How to write files to assets folder or raw folder in android?

Why not update the files on the local file system instead? You can read/write files into your applications sandboxed area.

http://developer.android.com/guide/topics/data/data-storage.html#filesInternal

Other alternatives you may want to look into are Shared Perferences and using Cache Files (all described at the link above)

Why am I getting an Exception with the message "Invalid setup on a non-virtual (overridable in VB) member..."?

As help to anybody that had the same problem as me, I accidentally mistyped the implementation type instead of the interface e.g.

var mockFileBrowser = new Mock<FileBrowser>();

instead of

var mockFileBrowser = new Mock<IFileBrowser>();

How to limit text width

 display: inline-block;
max-width: 80%;
height: 1.5em;
overflow: hidden;
text-overflow: ellipsis;
white-space: nowrap; 

cannot download, $GOPATH not set

(for MAC)

I tried all these answers and, for some still unknown reason, none of them worked.

I had to "force feed" the GOPATH by setting the environment variable per every command that required it. For example:

sudo env GOPATH=$HOME/goWorkDirectory go build ...

Even glide was giving me the GOPATH not set error. Resolved it, again, by "force feeding": I tried all these answers and, for some still unknown reason, none of them worked.

I had to "force feed" the GOPATH by setting the environment variable per every command that required it.

sudo env GOPATH=$HOME/goWorkDirectory glide install

Hope this helps someone.

How to declare global variables in Android?

On activity result is called before on resume. So move you login check to on resume and your second login can be blocked once the secomd activity has returned a positive result. On resume is called every time so there is not worries of it not being called the first time.

android on Text Change Listener

I have also faced the same problem and keep on getting stackOverflow exceptions, and I come with the following solution.

edt_amnt_sent.addTextChangedListener(new TextWatcher() {    
    @Override
    public void afterTextChanged(Editable s) {
        if (skipOnChange)
            return;

        skipOnChange = true;
        try {
            //method
        } catch (NumberFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            skipOnChange = false;
        }
    }
});

edt_amnt_receive.addTextChangedListener(new TextWatcher() {

    @Override
    public void afterTextChanged(Editable s) {

        if (skipOnChange)
            return;

        skipOnChange = true;
        try {
            //method
        } catch (NumberFormatException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } finally {
            skipOnChange = false;
        }
    }
});

declared initially boolean skipOnChange = false;

Visual Studio window which shows list of methods

Microsoft doesn't feel like implementing this useful tool, but if by chance you can have Visual Assist, you have it in VAssistX > Tools > VA Outline. The plugin is not free though.

How is a JavaScript hash map implemented?

every javascript object is a simple hashmap which accepts a string or a Symbol as its key, so you could write your code as:

var map = {};
// add a item
map[key1] = value1;
// or remove it
delete map[key1];
// or determine whether a key exists
key1 in map;

javascript object is a real hashmap on its implementation, so the complexity on search is O(1), but there is no dedicated hashcode() function for javascript strings, it is implemented internally by javascript engine (V8, SpiderMonkey, JScript.dll, etc...)

2020 Update:

javascript today supports other datatypes as well: Map and WeakMap. They behave more closely as hash maps than traditional objects.

Hexadecimal string to byte array in C

No. But it's relatively trivial to achieve using sscanf in a loop.

Dynamically replace img src attribute with jQuery

This is what you wanna do:

var oldSrc = 'http://example.com/smith.gif';
var newSrc = 'http://example.com/johnson.gif';
$('img[src="' + oldSrc + '"]').attr('src', newSrc);

Cannot connect to the Docker daemon at unix:/var/run/docker.sock. Is the docker daemon running?

For me the solution was to simply make sure I had installed the correct Docker package. For example, for Ubuntu the depreciated packages are:

  • docker
  • docker-engine
  • docker.io
  • containerd
  • runc

For installation check https://docs.docker.com. Instructions are provided for Ubuntu, CentOS, Debian and Fedora at the time of writing.

How to convert an integer (time) to HH:MM:SS::00 in SQL Server 2008?

You can use the following time conversion within SQL like this:

--Convert Time to Integer (Minutes)
DECLARE @timeNow datetime = '14:47'
SELECT DATEDIFF(mi,CONVERT(datetime,'00:00',108), CONVERT(datetime, RIGHT(CONVERT(varchar, @timeNow, 100),7),108))

--Convert Minutes to Time
DECLARE @intTime int = (SELECT DATEDIFF(mi,CONVERT(datetime,'00:00',108), CONVERT(datetime, RIGHT(CONVERT(varchar, @timeNow, 100),7),108)))
SELECT DATEADD(minute, @intTime, '')

Result: 887 <- Time in minutes and 1900-01-01 14:47:00.000 <-- Minutes to time

Java regex email

General Email format (RE) which include also domain like co.in, co.uk, com, outlook.com etc.

And rule says that :

  • Uppercase and lowercase English letters (a-z, A-Z)
  • Digits 0 to 9
  • Characters ! # $ % & ' * + - / = ? ^ _ ` { | } ~ Character.
  • (dot, period, full stop) provided that it is not the first or last character, and provided also that it does not appear two or more times consecutively.

    [a-zA-Z0-9]+[._a-zA-Z0-9!#$%&'*+-/=?^_`{|}~]*[a-zA-Z]*@[a-zA-Z0-9]{2,8}.[a-zA-Z.]{2,6}