Programs & Examples On #Bson

BSON stands for "Binary JSON". It is a computer data interchange format used mainly as a data storage and network transfer format in the MongoDB database.

How to query nested objects?

db.messages.find( { headers : { From: "[email protected]" } } )

This queries for documents where headers equals { From: ... }, i.e. contains no other fields.


db.messages.find( { 'headers.From': "[email protected]" } )

This only looks at the headers.From field, not affected by other fields contained in, or missing from, headers.


Dot-notation docs

Understanding MongoDB BSON Document size limit

Many in the community would prefer no limit with warnings about performance, see this comment for a well reasoned argument: https://jira.mongodb.org/browse/SERVER-431?focusedCommentId=22283&page=com.atlassian.jira.plugin.system.issuetabpanels:comment-tabpanel#comment-22283

My take, the lead developers are stubborn about this issue because they decided it was an important "feature" early on. They're not going to change it anytime soon because their feelings are hurt that anyone questioned it. Another example of personality and politics detracting from a product in open source communities but this is not really a crippling issue.

Date query with ISODate in mongodb doesn't seem to work

In the MongoDB shell:

db.getCollection('sensorevents').find({from:{$gt: new ISODate('2015-08-30 16:50:24.481Z')}})

In my nodeJS code ( using Mongoose )

    SensorEvent.Model.find( {
        from: { $gt: new Date( SensorEventListener.lastSeenSensorFrom ) }
    } )

I am querying my sensor events collection to return values where the 'from' field is greater than the given date

PHP multiline string with PHP

The internal set of single quotes in your code is killing the string. Whenever you hit a single quote it ends the string and continues processing. You'll want something like:

$thisstring = 'this string is long \' in needs escaped single quotes or nothing will run';

How to print out the method name and line number and conditionally disable NSLog?

It is simple,for Example

-(void)applicationWillEnterForeground:(UIApplication *)application {

    NSLog(@"%s", __PRETTY_FUNCTION__);

}

Output: -[AppDelegate applicationWillEnterForeground:]

MySQL foreign key constraints, cascade delete

If your cascading deletes nuke a product because it was a member of a category that was killed, then you've set up your foreign keys improperly. Given your example tables, you should have the following table setup:

CREATE TABLE categories (
    id int unsigned not null primary key,
    name VARCHAR(255) default null
)Engine=InnoDB;

CREATE TABLE products (
    id int unsigned not null primary key,
    name VARCHAR(255) default null
)Engine=InnoDB;

CREATE TABLE categories_products (
    category_id int unsigned not null,
    product_id int unsigned not null,
    PRIMARY KEY (category_id, product_id),
    KEY pkey (product_id),
    FOREIGN KEY (category_id) REFERENCES categories (id)
       ON DELETE CASCADE
       ON UPDATE CASCADE,
    FOREIGN KEY (product_id) REFERENCES products (id)
       ON DELETE CASCADE
       ON UPDATE CASCADE
)Engine=InnoDB;

This way, you can delete a product OR a category, and only the associated records in categories_products will die alongside. The cascade won't travel farther up the tree and delete the parent product/category table.

e.g.

products: boots, mittens, hats, coats
categories: red, green, blue, white, black

prod/cats: red boots, green mittens, red coats, black hats

If you delete the 'red' category, then only the 'red' entry in the categories table dies, as well as the two entries prod/cats: 'red boots' and 'red coats'.

The delete will not cascade any farther and will not take out the 'boots' and 'coats' categories.

comment followup:

you're still misunderstanding how cascaded deletes work. They only affect the tables in which the "on delete cascade" is defined. In this case, the cascade is set in the "categories_products" table. If you delete the 'red' category, the only records that will cascade delete in categories_products are those where category_id = red. It won't touch any records where 'category_id = blue', and it would not travel onwards to the "products" table, because there's no foreign key defined in that table.

Here's a more concrete example:

categories:     products:
+----+------+   +----+---------+
| id | name |   | id | name    |
+----+------+   +----+---------+
| 1  | red  |   | 1  | mittens |
| 2  | blue |   | 2  | boots   |
+---++------+   +----+---------+

products_categories:
+------------+-------------+
| product_id | category_id |
+------------+-------------+
| 1          | 1           | // red mittens
| 1          | 2           | // blue mittens
| 2          | 1           | // red boots
| 2          | 2           | // blue boots
+------------+-------------+

Let's say you delete category #2 (blue):

DELETE FROM categories WHERE (id = 2);

the DBMS will look at all the tables which have a foreign key pointing at the 'categories' table, and delete the records where the matching id is 2. Since we only defined the foreign key relationship in products_categories, you end up with this table once the delete completes:

+------------+-------------+
| product_id | category_id |
+------------+-------------+
| 1          | 1           | // red mittens
| 2          | 1           | // red boots
+------------+-------------+

There's no foreign key defined in the products table, so the cascade will not work there, so you've still got boots and mittens listed. There's just no 'blue boots' and no 'blue mittens' anymore.

Flutter: Run method on Widget build complete

You could use

https://github.com/slightfoot/flutter_after_layout

which executes a function only one time after the layout is completed. Or just look at its implementation and add it to your code :-)

Which is basically

  void initState() {
    super.initState();
    WidgetsBinding.instance
        .addPostFrameCallback((_) => yourFunction(context));
  }

Array.Add vs +=

If you want a dynamically sized array, then you should make a list. Not only will you get the .Add() functionality, but as @frode-f explains, dynamic arrays are more memory efficient and a better practice anyway.

And it's so easy to use.

Instead of your array declaration, try this:

$outItems = New-Object System.Collections.Generic.List[System.Object]

Adding items is simple.

$outItems.Add(1)
$outItems.Add("hi")

And if you really want an array when you're done, there's a function for that too.

$outItems.ToArray()

adding child nodes in treeview

void treeView(string [] LineString)
    {
        int line = LineString.Length;
        string AssmMark = "";
        string PartMark = "";
        TreeNode aNode;
        TreeNode pNode;
        for ( int i=0 ; i<line ; i++){
            string sLine = LineString[i];
            if ( sLine.StartsWith("ASSEMBLY:") ){
                sLine  = sLine.Replace("ASSEMBLY:","");
                string[] aData = sLine.Split(new char[] {','});
                AssmMark  = aData[0].Trim();
                //TreeNode aNode;
                //aNode = new TreeNode(AssmMark);
                treeView1.Nodes.Add(AssmMark,AssmMark);
            }
            if( sLine.Trim().StartsWith("PART:") ){
                sLine  = sLine.Replace("PART:","");
                string[] pData = sLine.Split(new char[] {','});
                PartMark = pData[0].Trim();
                pNode = new TreeNode(PartMark);
                treeView1.Nodes[AssmMark].Nodes.Add(pNode);
            }
        }

python: SyntaxError: EOL while scanning string literal

Your variable(s1) spans multiple lines. In order to do this (i.e you want your string to span multiple lines), you have to use triple quotes(""").

s1="""some very long 
string............"""

Backup/Restore a dockerized PostgreSQL database

dksnap (https://github.com/kelda/dksnap) automates the process of running pg_dumpall and loading the dump via /docker-entrypoint-initdb.d.

It shows you a list of running containers, and you pick which one you want to backup. The resulting artifact is a regular Docker image, so you can then docker run it, or share it by pushing it to a Docker registry.

(disclaimer: I'm a maintainer on the project)

Converting list to numpy array

If you have a list of lists, you only needed to use ...

import numpy as np
...
npa = np.asarray(someListOfLists, dtype=np.float32)

per this LINK in the scipy / numpy documentation. You just needed to define dtype inside the call to asarray.

How to make an array of arrays in Java

try

String[][] arrays = new String[5][];

What is the advantage of using REST instead of non-REST HTTP?

Discovery is far easier in REST. We have WADL documents (similar to WSDL in traditional webservices) that will help you to advertise your service to the world. You can use UDDI discoveries as well. With traditional HTTP POST and GET people may not know your message request and response schemas to call you.

I need to convert an int variable to double

You have to cast one (or both) of the arguments to the division operator to double:

double firstSolution = (b1 * a22 - b2 * a12) / (double)(a11 * a22 - a12 * a21);

Since you are performing the same calculation twice I'd recommend refactoring your code:

double determinant = a11 * a22 - a12 * a21;
double firstSolution = (b1 * a22 - b2 * a12) / determinant;
double secondSolution = (b2 * a11 - b1 * a21) / determinant;

This works in the same way, but now there is an implicit cast to double. This conversion from int to double is an example of a widening primitive conversion.

How do I set a fixed background image for a PHP file?

You should consider have other php files included if you're going to derive a website from it. Instead of doing all the css/etc in that file, you can do

<head>
    <?php include_once('C:\Users\George\Documents\HTML\style.css'); ?>
    <title>Title</title>
</hea>

Then you can have a separate CSS file that is just being pulled into your php file. It provides some "neater" coding.

Query based on multiple where clauses in Firebase

Using Firebase's Query API, you might be tempted to try this:

// !!! THIS WILL NOT WORK !!!
ref
  .orderBy('genre')
  .startAt('comedy').endAt('comedy')
  .orderBy('lead')                  // !!! THIS LINE WILL RAISE AN ERROR !!!
  .startAt('Jack Nicholson').endAt('Jack Nicholson')
  .on('value', function(snapshot) { 
      console.log(snapshot.val()); 
  });

But as @RobDiMarco from Firebase says in the comments:

multiple orderBy() calls will throw an error

So my code above will not work.

I know of three approaches that will work.

1. filter most on the server, do the rest on the client

What you can do is execute one orderBy().startAt()./endAt() on the server, pull down the remaining data and filter that in JavaScript code on your client.

ref
  .orderBy('genre')
  .equalTo('comedy')
  .on('child_added', function(snapshot) { 
      var movie = snapshot.val();
      if (movie.lead == 'Jack Nicholson') {
          console.log(movie);
      }
  });

2. add a property that combines the values that you want to filter on

If that isn't good enough, you should consider modifying/expanding your data to allow your use-case. For example: you could stuff genre+lead into a single property that you just use for this filter.

"movie1": {
    "genre": "comedy",
    "name": "As good as it gets",
    "lead": "Jack Nicholson",
    "genre_lead": "comedy_Jack Nicholson"
}, //...

You're essentially building your own multi-column index that way and can query it with:

ref
  .orderBy('genre_lead')
  .equalTo('comedy_Jack Nicholson')
  .on('child_added', function(snapshot) { 
      var movie = snapshot.val();
      console.log(movie);
  });

David East has written a library called QueryBase that helps with generating such properties.

You could even do relative/range queries, let's say that you want to allow querying movies by category and year. You'd use this data structure:

"movie1": {
    "genre": "comedy",
    "name": "As good as it gets",
    "lead": "Jack Nicholson",
    "genre_year": "comedy_1997"
}, //...

And then query for comedies of the 90s with:

ref
  .orderBy('genre_year')
  .startAt('comedy_1990')
  .endAt('comedy_2000')
  .on('child_added', function(snapshot) { 
      var movie = snapshot.val();
      console.log(movie);
  });

If you need to filter on more than just the year, make sure to add the other date parts in descending order, e.g. "comedy_1997-12-25". This way the lexicographical ordering that Firebase does on string values will be the same as the chronological ordering.

This combining of values in a property can work with more than two values, but you can only do a range filter on the last value in the composite property.

A very special variant of this is implemented by the GeoFire library for Firebase. This library combines the latitude and longitude of a location into a so-called Geohash, which can then be used to do realtime range queries on Firebase.

3. create a custom index programmatically

Yet another alternative is to do what we've all done before this new Query API was added: create an index in a different node:

  "movies"
      // the same structure you have today
  "by_genre"
      "comedy"
          "by_lead"
              "Jack Nicholson"
                  "movie1"
              "Jim Carrey"
                  "movie3"
      "Horror"
          "by_lead"
              "Jack Nicholson"
                  "movie2"
      

There are probably more approaches. For example, this answer highlights an alternative tree-shaped custom index: https://stackoverflow.com/a/34105063


If none of these options work for you, but you still want to store your data in Firebase, you can also consider using its Cloud Firestore database.

Cloud Firestore can handle multiple equality filters in a single query, but only one range filter. Under the hood it essentially uses the same query model, but it's like it auto-generates the composite properties for you. See Firestore's documentation on compound queries.

What does "<>" mean in Oracle

It means not equal to

Should I use != or <> for not equal in TSQL?

Have a look at the link. It has detailed explanation of what to use for what.

How to prevent Browser cache for php site

You can try this:

    header("Expires: Tue, 03 Jul 2001 06:00:00 GMT");
    header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
    header("Cache-Control: no-store, no-cache, must-revalidate, max-age=0");
    header("Cache-Control: post-check=0, pre-check=0", false);
    header("Pragma: no-cache");
    header("Connection: close");

Hopefully it will help prevent Cache, if any!

Copy or rsync command

Especially if you use a copy-on-write filesystem like BTRFS or ZFS, rsync is much better.

I use BTRFS, and I have this in my ~/.bashrc:

alias cp="rsync -ah --inplace --no-whole-file --info=progress2"

The important flag here for CoW FSs like BTRFS is --inplace because it only copies the changed part of the files, doesn't create new for small changes between files inodes, etc. See this.

Get DataKey values in GridView RowCommand

foreach (GridViewRow gvr in gvMyGridView.Rows)
{
    string PrimaryKey = gvMyGridView.DataKeys[gvr.RowIndex].Values[0].ToString();
}

You can use this code while doing an iteration with foreach or for any GridView event like OnRowDataBound.

Here you can input multiple values for DataKeyNames by separating with comma ,. For example, DataKeyNames="ProductID,ItemID,OrderID".

You can now access each of DataKeys by providing its index like below:

string ProductID = gvMyGridView.DataKeys[gvr.RowIndex].Values[0].ToString();
string ItemID = gvMyGridView.DataKeys[gvr.RowIndex].Values[1].ToString();
string OrderID = gvMyGridView.DataKeys[gvr.RowIndex].Values[2].ToString();

You can also use Key Name instead of its index to get the values from DataKeyNames collection like below:

string ProductID = gvMyGridView.DataKeys[gvr.RowIndex].Values["ProductID"].ToString();
string ItemID = gvMyGridView.DataKeys[gvr.RowIndex].Values["ItemID"].ToString();
string OrderID = gvMyGridView.DataKeys[gvr.RowIndex].Values["OrderID"].ToString();

Difference between matches() and find() in Java Regex

matches return true if the whole string matches the given pattern. find tries to find a substring that matches the pattern.

gitx How do I get my 'Detached HEAD' commits back into master

If your detached HEAD is a fast forward of master and you just want the commits upstream, you can

git push origin HEAD:master

to push directly, or

git checkout master && git merge [ref of HEAD]

will merge it back into your local master.

Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST

and if you don't have the option to go on java8 better use 'yyyy-MM-dd'T'HH:mm:ssXXX' as this gets correctly parsed again (while with only one X this may not be the case... depending on your parsing function)

X generates: +01

XXX generates: +01:00

What is the correct JSON content type?

If you're calling ASP.NET Web Services from the client-side you have to use application/json for it to work. I believe this is the same for the jQuery and Ext frameworks.

How do you dynamically add elements to a ListView on Android?

Create an XML layout first in your project's res/layout/main.xml folder:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    <Button
        android:id="@+id/addBtn"
        android:text="Add New Item"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:onClick="addItems"/>
    <ListView
        android:id="@android:id/list"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:drawSelectorOnTop="false"
    />
</LinearLayout>

This is a simple layout with a button on the top and a list view on the bottom. Note that the ListView has the id @android:id/list which defines the default ListView a ListActivity can use.

public class ListViewDemo extends ListActivity {
    //LIST OF ARRAY STRINGS WHICH WILL SERVE AS LIST ITEMS
    ArrayList<String> listItems=new ArrayList<String>();

    //DEFINING A STRING ADAPTER WHICH WILL HANDLE THE DATA OF THE LISTVIEW
    ArrayAdapter<String> adapter;

    //RECORDING HOW MANY TIMES THE BUTTON HAS BEEN CLICKED
    int clickCounter=0;

    @Override
    public void onCreate(Bundle icicle) {
        super.onCreate(icicle);
        setContentView(R.layout.main);
        adapter=new ArrayAdapter<String>(this,
            android.R.layout.simple_list_item_1,
            listItems);
        setListAdapter(adapter);
    }

    //METHOD WHICH WILL HANDLE DYNAMIC INSERTION
    public void addItems(View v) {
        listItems.add("Clicked : "+clickCounter++);
        adapter.notifyDataSetChanged();
    }
}

android.R.layout.simple_list_item_1 is the default list item layout supplied by Android, and you can use this stock layout for non-complex things.

listItems is a List which holds the data shown in the ListView. All the insertion and removal should be done on listItems; the changes in listItems should be reflected in the view. That's handled by ArrayAdapter<String> adapter, which should be notified using:

adapter.notifyDataSetChanged();

An Adapter is instantiated with 3 parameters: the context, which could be your activity/listactivity; the layout of your individual list item; and lastly, the list, which is the actual data to be displayed in the list.

How to convert string to datetime format in pandas python?

Use to_datetime, there is no need for a format string the parser is man/woman enough to handle it:

In [51]:
pd.to_datetime(df['I_DATE'])

Out[51]:
0   2012-03-28 14:15:00
1   2012-03-28 14:17:28
2   2012-03-28 14:50:50
Name: I_DATE, dtype: datetime64[ns]

To access the date/day/time component use the dt accessor:

In [54]:
df['I_DATE'].dt.date

Out[54]:
0    2012-03-28
1    2012-03-28
2    2012-03-28
dtype: object

In [56]:    
df['I_DATE'].dt.time

Out[56]:
0    14:15:00
1    14:17:28
2    14:50:50
dtype: object

You can use strings to filter as an example:

In [59]:
df = pd.DataFrame({'date':pd.date_range(start = dt.datetime(2015,1,1), end = dt.datetime.now())})
df[(df['date'] > '2015-02-04') & (df['date'] < '2015-02-10')]

Out[59]:
         date
35 2015-02-05
36 2015-02-06
37 2015-02-07
38 2015-02-08
39 2015-02-09

Extract csv file specific columns to list in Python

import csv
from sys import argv

d = open("mydata.csv", "r")

db = []

for line in csv.reader(d):
    db.append(line)

# the rest of your code with 'db' filled with your list of lists as rows and columbs of your csv file.

Angular 2 Scroll to top on Route Change

You can add the AfterViewInit lifecycle hook to your component.

ngAfterViewInit() {
   window.scrollTo(0, 0);
}

Oracle query to fetch column names

You can use the below query to get a list of table names which uses the specific column in DB2:

SELECT TBNAME                
FROM SYSIBM.SYSCOLUMNS       
WHERE NAME LIKE '%COLUMN_NAME'; 

Note : Here replace the COLUMN_NAME with the column name that you are searching for.

Make a link in the Android browser start up my app?

You may want to consider a library to handle the deep link to your app:

https://github.com/airbnb/DeepLinkDispatch

You can add the intent filter on an annotated Activity like people suggested above. It will handle the routing and parsing of parameters for all of your deep links. For example, your MainActivity might have something like this:

@DeepLink("somePath/{useful_info_for_anton_app}")
public class MainActivity extends Activity {
   ...
}

It can also handle query parameters as well.

Hibernate: How to set NULL query-parameter value with HQL?

this seems to work as wel ->

@Override
public List<SomeObject> findAllForThisSpecificThing(String thing) {
    final Query query = entityManager.createQuery(
            "from " + getDomain().getSimpleName() + " t  where t.thing = " + ((thing == null) ? " null" : " :thing"));
    if (thing != null) {
        query.setParameter("thing", thing);
    }
    return query.getResultList();
}

Btw, I'm pretty new at this, so if for any reason this isn't a good idea, let me know. Thanks.

Python copy files to a new directory and rename if file name already exists

I always use the time-stamp - so its not possible, that the file exists already:

import os
import shutil
import datetime

now = str(datetime.datetime.now())[:19]
now = now.replace(":","_")

src_dir="C:\\Users\\Asus\\Desktop\\Versand Verwaltung\\Versand.xlsx"
dst_dir="C:\\Users\\Asus\\Desktop\\Versand Verwaltung\\Versand_"+str(now)+".xlsx"
shutil.copy(src_dir,dst_dir)

How to read input from console in a batch file?

If you're just quickly looking to keep a cmd instance open instead of exiting immediately, simply doing the following is enough

set /p asd="Hit enter to continue"

at the end of your script and it'll keep the window open.

Note that this'll set asd as an environment variable, and can be replaced with anything else.

Which type of folder structure should be used with Angular 2?

If project is small and will remain small, I would recommend to structure by type (Method 2: ng-book2)

app
|- components
|  |- hero
|  |- hero-list
|  |- villain
|  |- ...
|- services
|  |- hero.service.ts
|  |- ...
|- utils
|- shared

If project will grow you should structure your folders by domain (Method 3: mgechev/angular2-seed)

app
|- heroes
|  |- hero
|  |- hero-list
|  |- hero.service.ts
|- villains
|  |- villain
|  |- ...
|- utils
|- shared

Better to Follow official docs.
https://angular.io/guide/styleguide#application-structure-and-ngmodules

Enable ASP.NET ASMX web service for HTTP POST / GET requests

Try to declare UseHttpGet over your method.

[ScriptMethod(UseHttpGet = true)]
public string HelloWorld()
{
    return "Hello World";
}

Laravel 4 with Sentry 2 add user to a group on Registration

Somehow, where you are using Sentry, you're not using its Facade, but the class itself. When you call a class through a Facade you're not really using statics, it's just looks like you are.

Do you have this:

use Cartalyst\Sentry\Sentry; 

In your code?

Ok, but if this line is working for you:

$user = $this->sentry->register(array(     'username' => e($data['username']),     'email' => e($data['email']),      'password' => e($data['password'])     )); 

So you already have it instantiated and you can surely do:

$adminGroup = $this->sentry->findGroupById(5); 

What is the difference between char s[] and char *s?

This declaration:

char s[] = "hello";

Creates one object - a char array of size 6, called s, initialised with the values 'h', 'e', 'l', 'l', 'o', '\0'. Where this array is allocated in memory, and how long it lives for, depends on where the declaration appears. If the declaration is within a function, it will live until the end of the block that it is declared in, and almost certainly be allocated on the stack; if it's outside a function, it will probably be stored within an "initialised data segment" that is loaded from the executable file into writeable memory when the program is run.

On the other hand, this declaration:

char *s ="hello";

Creates two objects:

  • a read-only array of 6 chars containing the values 'h', 'e', 'l', 'l', 'o', '\0', which has no name and has static storage duration (meaning that it lives for the entire life of the program); and
  • a variable of type pointer-to-char, called s, which is initialised with the location of the first character in that unnamed, read-only array.

The unnamed read-only array is typically located in the "text" segment of the program, which means it is loaded from disk into read-only memory, along with the code itself. The location of the s pointer variable in memory depends on where the declaration appears (just like in the first example).

Check an integer value is Null in c#

Simply you can do this:

    public void CheckNull(int? item)
    {
        if (item != null)
        {
            //Do Something
        }

    }

Error "library not found for" after putting application in AdMob

I was getting similar bugs on library not found. Ultimately this is how I was able to resolve it

  1. Before starting with Xcode Archive, used flutter build iOS
  2. Changed the IOS Deployment Target to a higher target iOS 11.2 . Earlier I had something like 8.0 which was giving all the above errors.
  3. Made sure that the IOS deployment targets in Xcode are same in the Project, Target and Pods

remove kernel on jupyter notebook

Just for completeness, you can get a list of kernels with jupyter kernelspec list, but I ran into a case where one of the kernels did not show up in this list. You can find all kernel names by opening a Jupyter notebook and selecting Kernel -> Change kernel. If you do not see everything in this list when you run jupyter kernelspec list, try looking in common Jupyter folders:

ls ~/.local/share/jupyter/kernels  # usually where local kernels go
ls /usr/local/share/jupyter/kernels  # usually where system-wide kernels go
ls /usr/share/jupyter/kernels  # also where system-wide kernels can go

Also, you can delete a kernel with jupyter kernelspec remove or jupyter kernelspec uninstall. The latter is an alias for remove. From the in-line help text for the command:

uninstall
    Alias for remove
remove
    Remove one or more Jupyter kernelspecs by name.

How to get logged-in user's name in Access vba?

Try this:

Function UserNameWindows() As String
     UserName = Environ("USERNAME")
End Function

How to create a folder with name as current date in batch (.bat) files

for /F “tokens=1-4 delims=/ ” %%A in (‘date /t’) do (
    set DateDay=%%A
    set DateMonth=%%B
    set DateYear=%%C
)
set CurrentDate=%DateDay%-%DateMonth%-%DateYear%
md %CurrentDate%

This will give you a newly created folder with today’s date, in the format of DD-MM-YY

Sourced from: Ali's Knowledge Base

Closing JFrame with button click

You can use super.dispose() method which is more similar to close operation.

Youtube iframe wmode issue

&wmode=opaque didn't work for me (chrome 10) but &amp;wmode=transparent cleared the issue right up.

How can I recursively find all files in current and subfolders based on wildcard matching?

Use

find path/to/dir -name "*.ext1" -o -name "*.ext2"

Explanation

  1. The first parameter is the directory you want to search.
  2. By default find does recursion.
  3. The -o stands for -or. So above means search for this wildcard OR this one. If you have only one pattern then no need for -o.
  4. The quotes around the wildcard pattern are required.

Pandas unstack problems: ValueError: Index contains duplicate entries, cannot reshape

I had such problem. In my case problem was in data - my column 'information' contained 1 unique value and it caused error

UPDATE: to correct work 'pivot' pairs (id_user,information) cannot have duplicates

It works:

df2 = pd.DataFrame({'id_user':[1,2,3,4,4,5,5], 
'information':['phon','phon','phone','phone1','phone','phone1','phone'], 
'value': [1, '01.01.00', '01.02.00', 2, '01.03.00', 3, '01.04.00']})
df2.pivot(index='id_user', columns='information', values='value')

it doesn't work:

df2 = pd.DataFrame({'id_user':[1,2,3,4,4,5,5], 
'information':['phone','phone','phone','phone','phone','phone','phone'], 
'value': [1, '01.01.00', '01.02.00', 2, '01.03.00', 3, '01.04.00']})
df2.pivot(index='id_user', columns='information', values='value')

source: https://stackoverflow.com/a/37021196/6088984

Difference Between $.getJSON() and $.ajax() in jQuery

with $.getJSON()) there is no any error callback only you can track succeed callback and there no standard setting supported like beforeSend, statusCode, mimeType etc, if you want it use $.ajax().

Link vs compile vs controller

Compile :

This is the phase where Angular actually compiles your directive. This compile function is called just once for each references to the given directive. For example, say you are using the ng-repeat directive. ng-repeat will have to look up the element it is attached to, extract the html fragment that it is attached to and create a template function.

If you have used HandleBars, underscore templates or equivalent, its like compiling their templates to extract out a template function. To this template function you pass data and the return value of that function is the html with the data in the right places.

The compilation phase is that step in Angular which returns the template function. This template function in angular is called the linking function.

Linking phase :

The linking phase is where you attach the data ( $scope ) to the linking function and it should return you the linked html. Since the directive also specifies where this html goes or what it changes, it is already good to go. This is the function where you want to make changes to the linked html, i.e the html that already has the data attached to it. In angular if you write code in the linking function its generally the post-link function (by default). It is kind of a callback that gets called after the linking function has linked the data with the template.

Controller :

The controller is a place where you put in some directive specific logic. This logic can go into the linking function as well, but then you would have to put that logic on the scope to make it "shareable". The problem with that is that you would then be corrupting the scope with your directives stuff which is not really something that is expected. So what is the alternative if two Directives want to talk to each other / co-operate with each other? Ofcourse you could put all that logic into a service and then make both these directives depend on that service but that just brings in one more dependency. The alternative is to provide a Controller for this scope ( usually isolate scope ? ) and then this controller is injected into another directive when that directive "requires" the other one. See tabs and panes on the first page of angularjs.org for an example.

How to change the port of Tomcat from 8080 to 80?

As previous answers didn't work well (it was good, but not enough) for me on a 14.04 Ubuntu Server, I mention these recommendations (this is a quote).

Edit: note that as @jason-faust mentioned it in the comments, on 14.04, the authbind package that ships with it does support IPv6 now, so the prefer IPv4 thing isn't needed any longer.

1) Install authbind
2) Make port 80 available to authbind (you need to be root):

  touch /etc/authbind/byport/80
  chmod 500 /etc/authbind/byport/80
  chown tomcat7 /etc/authbind/byport/80

3) Make IPv4 the default (authbind does not currently support IPv6).
   To do so, create the file TOMCAT/bin/setenv.sh with the following content: 

   CATALINA_OPTS="-Djava.net.preferIPv4Stack=true"

4) Change /usr/share/tomcat7/bin/startup.sh

  exec authbind --deep "$PRGDIR"/"$EXECUTABLE" start "$@"
  # OLD: exec "$PRGDIR"/"$EXECUTABLE" start "$@"

If you already got a setenv.sh file in /usr/share/tomcat7/bin with CATALINA_OPTS, you have to use :

export CATALINA_OPTS="$CATALINA_OPTS -Djava.net.preferIPv4Stack=true"

Now you can change the port to 80 as told in other answers.

Find the closest ancestor element that has a specific class

@rvighne solution works well, but as identified in the comments ParentElement and ClassList both have compatibility issues. To make it more compatible, I have used:

function findAncestor (el, cls) {
    while ((el = el.parentNode) && el.className.indexOf(cls) < 0);
    return el;
}
  • parentNode property instead of the parentElement property
  • indexOf method on the className property instead of the contains method on the classList property.

Of course, indexOf is simply looking for the presence of that string, it does not care if it is the whole string or not. So if you had another element with class 'ancestor-type' it would still return as having found 'ancestor', if this is a problem for you, perhaps you can use regexp to find an exact match.

Array of an unknown length in C#

You can create an array with the size set to a variable, i.e.

int size = 50;
string[] words = new string[size]; // contains 50 strings

However, that size can't change later on, if you decide you need 100 words. If you need the size to be really dynamic, you'll need to use a different sort of data structure. Try List.

Visual C++ executable and missing MSVCR100d.dll

For me the problem appeared in this situation:

I installed VS2012 and did not need VS2010 anymore. I wanted to get my computer clean and also removed the VS2010 runtime executables, thinking that no other program would use it. Then I wanted to test my DLL by attaching it to a program (let's call it program X). I got the same error message. I thought that I did something wrong when compiling the DLL. However, the real problem was that I attached the DLL to program X, and program X was compiled in VS2010 with debug info. That is why the error was thrown. I recompiled program X in VS2012, and the error was gone.

How to properly export an ES6 class in Node 4?

I had the same problem. What i found was i called my recieving object the same name as the class name. example:

const AspectType = new AspectType();

this screwed things up that way... hope this helps

Getting Cannot read property 'offsetWidth' of undefined with bootstrap carousel script

I got same error. Because i used v4 alpha class names like carousel-control-next When i changed with v3, problem solved.

Git push/clone to new server

remote server> cd /home/ec2-user
remote server> git init --bare --shared  test
add ssh pub key to remote server
local> git remote add aws ssh://ec2-user@<hostorip>:/home/ec2-user/dev/test
local> git push aws master

Paused in debugger in chrome?

One possible cause, it that you've enabled the "pause on exceptions" (the little stop-sign shaped icon with the pause (||) symbol with in in the lower left of the window). Try clicking that back to the off/grey state (not red nor blue states) and reload the page.

UPDATE: Adding a screenshot for reference:

enter image description here

casting Object array to Integer array error

java.lang.ClassCastException: [Ljava.lang.Object; cannot be cast to [Ljava.lang.Integer;

you try to cast an Array of Object to cast into Array of Integer. You cant do it. This type of downcast is not permitted.

You can make an array of Integer, and after that copy every value of the first array into second array.

Adding a new entry to the PATH variable in ZSH

You can append to your PATH in a minimal fashion. No need for parentheses unless you're appending more than one element. It also usually doesn't need quotes. So the simple, short way to append is:

path+=/some/new/bin/dir

This lower-case syntax is using path as an array, yet also affects its upper-case partner equivalent, PATH (to which it is "bound" via typeset).

(Notice that no : is needed/wanted as a separator.)

Common interactive usage

Then the common pattern for testing a new script/executable becomes:

path+=$PWD/.
# or
path+=$PWD/bin

Common config usage

You can sprinkle path settings around your .zshrc (as above) and it will naturally lead to the earlier listed settings taking precedence (though you may occasionally still want to use the "prepend" form path=(/some/new/bin/dir $path)).

Related tidbits

Treating path this way (as an array) also means: no need to do a rehash to get the newly pathed commands to be found.

Also take a look at vared path as a dynamic way to edit path (and other things).

You may only be interested in path for this question, but since we're talking about exports and arrays, note that arrays generally cannot be exported.

You can even prevent PATH from taking on duplicate entries (refer to this and this):

typeset -U path

How do I remove a CLOSE_WAIT socket connection

CLOSE_WAIT means your program is still running, and hasn't closed the socket (and the kernel is waiting for it to do so). Add -p to netstat to get the pid, and then kill it more forcefully (with SIGKILL if needed). That should get rid of your CLOSE_WAIT sockets. You can also use ps to find the pid.

SO_REUSEADDR is for servers and TIME_WAIT sockets, so doesn't apply here.

How do I scroll the UIScrollView when the keyboard appears?

I used this answer supplied by Sudheer Palchuri https://stackoverflow.com/users/2873919/sudheer-palchuri https://stackoverflow.com/a/32583809/6193496

In ViewDidLoad, register the notifications:

NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(DetailsViewController.keyboardWillShow(_:)), name:UIKeyboardWillShowNotification, object: nil)
NSNotificationCenter.defaultCenter().addObserver(self, selector: #selector(DetailsViewController.keyboardWillHide(_:)), name:UIKeyboardWillHideNotification, object: nil)

Add below observer methods which does the automatic scrolling when keyboard appears.

func textFieldShouldReturn(textField: UITextField) -> Bool {
textField.resignFirstResponder()
return true
}

func keyboardWillShow(notification:NSNotification){

var userInfo = notification.userInfo!
var keyboardFrame:CGRect = (userInfo[UIKeyboardFrameBeginUserInfoKey] as! NSValue).CGRectValue()
keyboardFrame = self.view.convertRect(keyboardFrame, fromView: nil)

var contentInset:UIEdgeInsets = self.scrollView.contentInset
contentInset.bottom = keyboardFrame.size.height
self.scrollView.contentInset = contentInset
}

func keyboardWillHide(notification:NSNotification){

var contentInset:UIEdgeInsets = UIEdgeInsetsZero
self.scrollView.contentInset = contentInset
}

C++ String array sorting

As many here have stated, you could use std::sort to sort, but what is going to happen when you, for instance, want to sort from z-a? This code may be useful

bool cmp(string a, string b)
{
if(a.compare(b) > 0)
    return true;
else
    return false;
}

int main()
{
string words[] = {"this", "a", "test", "is"};
int length = sizeof(words) / sizeof(string);
sort(words, words + length, cmp);

for(int i = 0; i < length; i++)
    cout << words[i] << " ";
cout << endl;
    // output will be: this test is a 

}

If you want to reverse the order of sorting just modify the sign in the cmp function.

Hope this is helpful :)

Cheers!!!

Get integer value of the current year in Java

If your application is making heavy use of Date and Calendar objects, you really should use Joda Time, because java.util.Date is mutable. java.util.Calendar has performance problems when its fields get updated, and is clunky for datetime arithmetic.

java.time.format.DateTimeParseException: Text could not be parsed at index 21

Your original problem was wrong pattern symbol "h" which stands for the clock hour (range 1-12). In this case, the am-pm-information is missing. Better, use the pattern symbol "H" instead (hour of day in range 0-23). So the pattern should rather have been like:

uuuu-MM-dd'T'HH:mm:ss.SSSX (best pattern also suitable for strict mode)

How to pass multiple parameters in json format to a web service using jquery?

This is a stab in the dark, but maybe do you need to wrap your JSON arguments; like say something like this:

data: "{'Ids':[{'Id1':'2'},{'Id2':'2'}]}"

Make sure your JSON is properly formed?

Understanding Bootstrap's clearfix class

The :before pseudo element isn't needed for the clearfix hack itself.

It's just an additional nice feature helping to prevent margin-collapsing of the first child element. Thus the top margin of an child block element of the "clearfixed" element is guaranteed to be positioned below the top border of the clearfixed element.

display:table is being used because display:block doesn't do the trick. Using display:block margins will collapse even with a :before element.

There is one caveat: if vertical-align:baseline is used in table cells with clearfixed <div> elements, Firefox won't align well. Then you might prefer using display:block despite loosing the anti-collapsing feature. In case of further interest read this article: Clearfix interfering with vertical-align.

How can I list all tags for a Docker image on a remote registry?

To view all available tags in a browser:

https://registry.hub.docker.com/v1/repositories/<username>/<image_name>/tags

i.e. https://hub.docker.com/r/localstack/localstack/tags

Or, you can get a json response using this endpoint:

https://registry.hub.docker.com/v1/repositories/localstack/localstack/tags

Java. Implicit super constructor Employee() is undefined. Must explicitly invoke another constructor

This problem can also come up when you don't have your constructor immediately call super.

So this will work:

  public Employee(String name, String number, Date date)
  {
    super(....)
  }

But this won't:

  public Employee(String name, String number, Date date)
  {
    // an example of *any* code running before you call super.
    if (number < 5)
    {
       number++;
    }

    super(....)
  }

The reason the 2nd example fails is because java is trying to implicitely call

super(name,number,date)

as the first line in your constructor.... So java doesn't see that you've got a call to super going on later in the constructor. It essentially tries to do this:

  public Employee(String name, String number, Date date)
  {
    super(name, number, date);

    if (number < 5)
    {
       number++;
    }

    super(....)
  }

So the solution is pretty easy... Just don't put code before your super call ;-) If you need to initialize something before the call to super, do it in another constructor, and then call the old constructor... Like in this example pulled from this StackOverflow post:

public class Foo
{
    private int x;

    public Foo()
    {
        this(1);
    }

    public Foo(int x)
    {
        this.x = x;
    }
}

How to get URL parameter using jQuery or plain JavaScript?

Yet another alternative function...

function param(name) {
    return (location.search.split(name + '=')[1] || '').split('&')[0];
}

Import CSV to mysql table

Here's how I did it in Python using csv and the MySQL Connector:

import csv
import mysql.connector

credentials = dict(user='...', password='...', database='...', host='...')
connection = mysql.connector.connect(**credentials)
cursor = connection.cursor(prepared=True)
stream = open('filename.csv', 'rb')
csv_file = csv.DictReader(stream, skipinitialspace=True)

query = 'CREATE TABLE t ('
query += ','.join('`{}` VARCHAR(255)'.format(column) for column in csv_file.fieldnames)
query += ')'
cursor.execute(query)
for row in csv_file:
    query = 'INSERT INTO t SET '
    query += ','.join('`{}` = ?'.format(column) for column in row.keys())
    cursor.execute(query, row.values())

stream.close()
cursor.close()
connection.close()

Key points

  • Use prepared statements for the INSERT
  • Open the file.csv in 'rb' binary
  • Some CSV files may need tweaking, such as the skipinitialspace option.
  • If 255 isn't wide enough you'll get errors on INSERT and have to start over.
  • Adjust column types, e.g. ALTER TABLE t MODIFY `Amount` DECIMAL(11,2);
  • Add a primary key, e.g. ALTER TABLE t ADD `id` INT PRIMARY KEY AUTO_INCREMENT;

How do you install an APK file in the Android emulator?

06-11-2020

Drag and Drop didn't work for me on Windows 10 Pro.

  1. Put the APK on Google Drive

  2. Access that Google drive using Chrome browser on the Android Emulator

  3. Then install it from there.

Note: You need to enable unknown sources within the Emulator.

Laravel Eloquent Join vs Inner Join?

I'm sure there are other ways to accomplish this, but one solution would be to use join through the Query Builder.

If you have tables set up something like this:

users
    id
    ...

friends
    id
    user_id
    friend_id
    ...

votes, comments and status_updates (3 tables)
    id
    user_id
    ....

In your User model:

class User extends Eloquent {
    public function friends()
    {
        return $this->hasMany('Friend');
    }
}

In your Friend model:

class Friend extends Eloquent {
    public function user()
    {
        return $this->belongsTo('User');
    }
}

Then, to gather all the votes for the friends of the user with the id of 1, you could run this query:

$user = User::find(1);
$friends_votes = $user->friends()
    ->with('user') // bring along details of the friend
    ->join('votes', 'votes.user_id', '=', 'friends.friend_id')
    ->get(['votes.*']); // exclude extra details from friends table

Run the same join for the comments and status_updates tables. If you would like votes, comments, and status_updates to be in one chronological list, you can merge the resulting three collections into one and then sort the merged collection.


Edit

To get votes, comments, and status updates in one query, you could build up each query and then union the results. Unfortunately, this doesn't seem to work if we use the Eloquent hasMany relationship (see comments for this question for a discussion of that problem) so we have to modify to queries to use where instead:

$friends_votes = 
    DB::table('friends')->where('friends.user_id','1')
    ->join('votes', 'votes.user_id', '=', 'friends.friend_id');

$friends_comments = 
    DB::table('friends')->where('friends.user_id','1')
    ->join('comments', 'comments.user_id', '=', 'friends.friend_id');

$friends_status_updates = 
    DB::table('status_updates')->where('status_updates.user_id','1')
    ->join('friends', 'status_updates.user_id', '=', 'friends.friend_id');

$friends_events = 
    $friends_votes
    ->union($friends_comments)
    ->union($friends_status_updates)
    ->get();

At this point, though, our query is getting a bit hairy, so a polymorphic relationship with and an extra table (like DefiniteIntegral suggests below) might be a better idea.

What are the use cases for selecting CHAR over VARCHAR in SQL?

CHAR takes up less storage space than VARCHAR if all your data values in that field are the same length. Now perhaps in 2009 a 800GB database is the same for all intents and purposes as a 810GB if you converted the VARCHARs to CHARs, but for short strings (1 or 2 characters), CHAR is still a industry "best practice" I would say.

Now if you look at the wide variety of data types most databases provide even for integers alone (bit, tiny, int, bigint), there ARE reasons to choose one over the other. Simply choosing bigint every time is actually being a bit ignorant of the purposes and uses of the field. If a field simply represents a persons age in years, a bigint is overkill. Now it's not necessarily "wrong", but it's not efficient.

But its an interesting argument, and as databases improve over time, it could be argued CHAR vs VARCHAR does get less relevant.

How to sort by column in descending order in Spark SQL?

PySpark only

I came across this post when looking to do the same in PySpark. The easiest way is to just add the parameter ascending=False:

df.orderBy("col1", ascending=False).show(10)

Reference: http://spark.apache.org/docs/2.1.0/api/python/pyspark.sql.html#pyspark.sql.DataFrame.orderBy

Readably print out a python dict() sorted by key

I wrote the following function to print dicts, lists, and tuples in a more readable format:

def printplus(obj):
    """
    Pretty-prints the object passed in.

    """
    # Dict
    if isinstance(obj, dict):
        for k, v in sorted(obj.items()):
            print u'{0}: {1}'.format(k, v)

    # List or tuple            
    elif isinstance(obj, list) or isinstance(obj, tuple):
        for x in obj:
            print x

    # Other
    else:
        print obj

Example usage in iPython:

>>> dict_example = {'c': 1, 'b': 2, 'a': 3}
>>> printplus(dict_example)
a: 3
b: 2
c: 1

>>> tuple_example = ((1, 2), (3, 4), (5, 6), (7, 8))
>>> printplus(tuple_example)
(1, 2)
(3, 4)
(5, 6)
(7, 8)

How to automatically select all text on focus in WPF TextBox?

I solved this problem using an Attached Behavior rather than an Expression Behavior as in Sergey's answer. This means I don't need a dependency on System.Windows.Interactivity in the Blend SDK:

public class TextBoxBehavior
{
    public static bool GetSelectAllTextOnFocus(TextBox textBox)
    {
        return (bool)textBox.GetValue(SelectAllTextOnFocusProperty);
    }

    public static void SetSelectAllTextOnFocus(TextBox textBox, bool value)
    {
        textBox.SetValue(SelectAllTextOnFocusProperty, value);
    }

    public static readonly DependencyProperty SelectAllTextOnFocusProperty =
        DependencyProperty.RegisterAttached(
            "SelectAllTextOnFocus",
            typeof (bool),
            typeof (TextBoxBehavior),
            new UIPropertyMetadata(false, OnSelectAllTextOnFocusChanged));

    private static void OnSelectAllTextOnFocusChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
    {
        var textBox = d as TextBox;
        if (textBox == null) return;

        if (e.NewValue is bool == false) return;

        if ((bool) e.NewValue)
        {
            textBox.GotFocus += SelectAll;
            textBox.PreviewMouseDown += IgnoreMouseButton;
        }
        else
        {
            textBox.GotFocus -= SelectAll;
            textBox.PreviewMouseDown -= IgnoreMouseButton;
        }
    }

    private static void SelectAll(object sender, RoutedEventArgs e)
    {
        var textBox = e.OriginalSource as TextBox;
        if (textBox == null) return;
        textBox.SelectAll();
    }

    private static void IgnoreMouseButton(object sender, System.Windows.Input.MouseButtonEventArgs e)
    {
        var textBox = sender as TextBox;
        if (textBox == null || (!textBox.IsReadOnly && textBox.IsKeyboardFocusWithin)) return;

        e.Handled = true;
        textBox.Focus();
    }
}

You can then use it in your XAML like this:

<TextBox Text="Some Text" behaviors:TextBoxBehavior.SelectAllTextOnFocus="True"/>

I blogged about it here.

How do I get the browser scroll position in jQuery?

It's better to use $(window).scroll() rather than $('#Eframe').on("mousewheel")

$('#Eframe').on("mousewheel") will not trigger if people manually scroll using up and down arrows on the scroll bar or grabbing and dragging the scroll bar itself.

$(window).scroll(function(){
    var scrollPos = $(document).scrollTop();
    console.log(scrollPos);
});

If #Eframe is an element with overflow:scroll on it and you want it's scroll position. I think this should work (I haven't tested it though).

$('#Eframe').scroll(function(){
    var scrollPos = $('#Eframe').scrollTop();
    console.log(scrollPos);
});

Printing 2D array in matrix format

Here is how to do it in Unity:

(Modified answer from @markmuetz so be sure to upvote his answer)

int[,] rawNodes = new int[,]
{
    { 0, 0, 0, 0, 0, 0 },
    { 0, 0, 0, 0, 0, 0 },
    { 0, 0, 0, 0, 0, 0 },
    { 0, 0, 0, 0, 0, 0 },
    { 0, 0, 0, 0, 0, 0 }
};

private void Start()
{
    int rowLength = rawNodes.GetLength(0);
    int colLength = rawNodes.GetLength(1);
    string arrayString = "";
    for (int i = 0; i < rowLength; i++)
    {
        for (int j = 0; j < colLength; j++)
        {
            arrayString += string.Format("{0} ", rawNodes[i, j]);
        }
        arrayString += System.Environment.NewLine + System.Environment.NewLine;
    }

    Debug.Log(arrayString);
}

How to target only IE (any version) within a stylesheet?

When using SASS I use the following 2 @media queries to target IE 6-10 & EDGE.

@media screen\9
    @import ie_styles
@media screen\0
    @import ie_styles

http://keithclark.co.uk/articles/moving-ie-specific-css-into-media-blocks/

Edit

I also target later versions of EDGE using @support queries (add as many as you need)

@supports (-ms-ime-align:auto)
    @import ie_styles
@supports (-ms-accelerator:auto)
    @import ie_styles

https://jeffclayton.wordpress.com/2015/04/07/css-hacks-for-windows-10-and-spartan-browser-preview/

Disable SSL fallback and use only TLS for outbound connections in .NET? (Poodle mitigation)

@Eddie Loeffen's answer seems to be the most popular answer to this question, but it has some bad long term effects. If you review the documentation page for System.Net.ServicePointManager.SecurityProtocol here the remarks section implies that the negotiation phase should just address this (and forcing the protocol is bad practice because in the future, TLS 1.2 will be compromised as well). However, we wouldn't be looking for this answer if it did.

Researching, it appears that the ALPN negotiation protocol is required to get to TLS1.2 in the negotiation phase. We took that as our starting point and tried newer versions of the .Net framework to see where support starts. We found that .Net 4.5.2 does not support negotiation to TLS 1.2, but .Net 4.6 does.

So, even though forcing TLS1.2 will get the job done now, I recommend that you upgrade to .Net 4.6 instead. Since this is a PCI DSS issue for June 2016, the window is short, but the new framework is a better answer.

UPDATE: Working from the comments, I built this:

ServicePointManager.SecurityProtocol = 0;    
foreach (SecurityProtocolType protocol in SecurityProtocolType.GetValues(typeof(SecurityProtocolType)))
    {
        switch (protocol)
        {
            case SecurityProtocolType.Ssl3:
            case SecurityProtocolType.Tls:
            case SecurityProtocolType.Tls11:
                break;
            default:
                ServicePointManager.SecurityProtocol |= protocol;
            break;
        }
    }

In order to validate the concept, I or'd together SSL3 and TLS1.2 and ran the code targeting a server that supports only TLS 1.0 and TLS 1.2 (1.1 is disabled). With the or'd protocols, it seems to connect fine. If I change to SSL3 and TLS 1.1, that failed to connect. My validation uses HttpWebRequest from System.Net and just calls GetResponse(). For instance, I tried this and failed:

        HttpWebRequest request = WebRequest.Create("https://www.contoso.com/my/web/resource") as HttpWebRequest;
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls11;
        request.GetResponse();

while this worked:

        HttpWebRequest request = WebRequest.Create("https://www.contoso.com/my/web/resource") as HttpWebRequest;
        ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3 | SecurityProtocolType.Tls12;
        request.GetResponse();

This has an advantage over forcing TLS 1.2 in that, if the .Net framework is upgraded so that there are more entries in the Enum, they will be supported by the code as is. It has a disadvantage over just using .Net 4.6 in that 4.6 uses ALPN and should support new protocols if no restriction is specified.

Edit 4/29/2019 - Microsoft published this article last October. It has a pretty good synopsis of their recommendation of how this should be done in the various versions of .net framework.

How to set custom location for local installation of npm package?

After searching for this myself wanting several projects with shared dependencies to be DRYer, I’ve found:

  • Installing locally is the Node way for anything you want to use via require()
  • Installing globally is for binaries you want in your path, but is not intended for anything via require()
  • Using a prefix means you need to add appropriate bin and man paths to $PATH
  • npm link (info) lets you use a local install as a source for globals

? stick to the Node way and install locally

ref:

How can I set response header on express.js assets

@klode's answer is right.

However, you are supposed to set another response header to make your header accessible to others.


Example:

First, you add 'page-size' in response header

response.set('page-size', 20);

Then, all you need to do is expose your header

response.set('Access-Control-Expose-Headers', 'page-size')

Using getopts to process long and short command line options

Maybe it's simpler to use ksh, just for the getopts part, if need long command line options, as it can be easier done there.

# Working Getopts Long => KSH

#! /bin/ksh
# Getopts Long
USAGE="s(showconfig)"
USAGE+="c:(createdb)"
USAGE+="l:(createlistener)"
USAGE+="g:(generatescripts)"
USAGE+="r:(removedb)"
USAGE+="x:(removelistener)"
USAGE+="t:(createtemplate)"
USAGE+="h(help)"

while getopts "$USAGE" optchar ; do
    case $optchar in
    s)  echo "Displaying Configuration" ;;
        c)  echo "Creating Database $OPTARG" ;;
    l)  echo "Creating Listener LISTENER_$OPTARG" ;;
    g)  echo "Generating Scripts for Database $OPTARG" ;;
    r)  echo "Removing Database $OPTARG" ;;
    x)  echo "Removing Listener LISTENER_$OPTARG" ;;
    t)  echo "Creating Database Template" ;;
    h)  echo "Help" ;;
    esac
done

Mockito : how to verify method was called on an object created within a method?

Solution for your example code using PowerMockito.whenNew

  • mockito-all 1.10.8
  • powermock-core 1.6.1
  • powermock-module-junit4 1.6.1
  • powermock-api-mockito 1.6.1
  • junit 4.12

FooTest.java

package foo;

import org.junit.After;
import org.junit.Before;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.mockito.Mock;
import org.mockito.Mockito;
import org.powermock.api.mockito.PowerMockito;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;

//Both @PrepareForTest and @RunWith are needed for `whenNew` to work 
@RunWith(PowerMockRunner.class)
@PrepareForTest({ Foo.class })
public class FooTest {

    // Class Under Test
    Foo cut;

    @Mock
    Bar barMock;

    @Before
    public void setUp() throws Exception {
        cut = new Foo();

    }

    @After
    public void tearDown() {
        cut = null;

    }

    @Test
    public void testFoo() throws Exception {

        // Setup
        PowerMockito.whenNew(Bar.class).withNoArguments()
                .thenReturn(this.barMock);

        // Test
        cut.foo();

        // Validations
        Mockito.verify(this.barMock, Mockito.times(1)).someMethod();

    }

}

JUnit Output JUnit Output

IllegalArgumentException or NullPointerException for a null parameter?

If it's a "setter", or somewhere I'm getting a member to use later, I tend to use IllegalArgumentException.

If it's something I'm going to use (dereference) right now in the method, I throw a NullPointerException proactively. I like this better than letting the runtime do it, because I can provide a helpful message (seems like the runtime could do this too, but that's a rant for another day).

If I'm overriding a method, I use whatever the overridden method uses.

Mongoose query where value is not null

$ne

selects the documents where the value of the field is not equal to the specified value. This includes documents that do not contain the field.

User.find({ "username": { "$ne": 'admin' } })

$nin

$nin selects the documents where: the field value is not in the specified array or the field does not exist.

User.find({ "groups": { "$nin": ['admin', 'user'] } })

What does 'synchronized' mean?

synchronized means that in a multi threaded environment, an object having synchronized method(s)/block(s) does not let two threads to access the synchronized method(s)/block(s) of code at the same time. This means that one thread can't read while another thread updates it.

The second thread will instead wait until the first thread completes its execution. The overhead is speed, but the advantage is guaranteed consistency of data.

If your application is single threaded though, synchronized blocks does not provide benefits.

How to rsync only a specific list of files?

For the record, none of the answers above helped except for one. To summarize, you can do the backup operation using --files-from= by using either:

 rsync -aSvuc `cat rsync-src-files` /mnt/d/rsync_test/

OR

 rsync -aSvuc --recursive --files-from=rsync-src-files . /mnt/d/rsync_test/

The former command is self explanatory, beside the content of the file rsync-src-files which I will elaborate down below. Now, if you want to use the latter version, you need to keep in mind the following four remarks:

  1. Notice one needs to specify both --files-from and the source directory
  2. One needs to explicitely specify --recursive.
  3. The file rsync-src-files is a user created file and it was placed within the src directory for this test
  4. The rsyn-src-files contain the files and folders to copy and they are taken relative to the source directory. IMPORTANT: Make sure there is not trailing spaces or blank lines in the file. In the example below, there are only two lines, not three (Figure it out by chance). Content of rsynch-src-files is:

folderName1
folderName2

How can I inject a property value into a Spring Bean which was configured using annotations?

Before we get Spring 3 - which allows you to inject property constants directly into your beans using annotations - I wrote a sub-class of the PropertyPlaceholderConfigurer bean that does the same thing. So, you can mark up your property setters and Spring will autowire your properties into your beans like so:

@Property(key="property.key", defaultValue="default")
public void setProperty(String property) {
    this.property = property;
}

The Annotation is as follows:

@Retention(RetentionPolicy.RUNTIME) 
@Target({ElementType.METHOD, ElementType.FIELD})
public @interface Property {
    String key();
    String defaultValue() default "";
}

The PropertyAnnotationAndPlaceholderConfigurer is as follows:

public class PropertyAnnotationAndPlaceholderConfigurer extends PropertyPlaceholderConfigurer {

    private static Logger log = Logger.getLogger(PropertyAnnotationAndPlaceholderConfigurer.class);

    @Override
    protected void processProperties(ConfigurableListableBeanFactory beanFactory, Properties properties) throws BeansException {
        super.processProperties(beanFactory, properties);

        for (String name : beanFactory.getBeanDefinitionNames()) {
            MutablePropertyValues mpv = beanFactory.getBeanDefinition(name).getPropertyValues();
            Class clazz = beanFactory.getType(name);

            if(log.isDebugEnabled()) log.debug("Configuring properties for bean="+name+"["+clazz+"]");

            if(clazz != null) {
                for (PropertyDescriptor property : BeanUtils.getPropertyDescriptors(clazz)) {
                    Method setter = property.getWriteMethod();
                    Method getter = property.getReadMethod();
                    Property annotation = null;
                    if(setter != null && setter.isAnnotationPresent(Property.class)) {
                        annotation = setter.getAnnotation(Property.class);
                    } else if(setter != null && getter != null && getter.isAnnotationPresent(Property.class)) {
                        annotation = getter.getAnnotation(Property.class);
                    }
                    if(annotation != null) {
                        String value = resolvePlaceholder(annotation.key(), properties, SYSTEM_PROPERTIES_MODE_FALLBACK);
                        if(StringUtils.isEmpty(value)) {
                            value = annotation.defaultValue();
                        }
                        if(StringUtils.isEmpty(value)) {
                            throw new BeanConfigurationException("No such property=["+annotation.key()+"] found in properties.");
                        }
                        if(log.isDebugEnabled()) log.debug("setting property=["+clazz.getName()+"."+property.getName()+"] value=["+annotation.key()+"="+value+"]");
                        mpv.addPropertyValue(property.getName(), value);
                    }
                }

                for(Field field : clazz.getDeclaredFields()) {
                    if(log.isDebugEnabled()) log.debug("examining field=["+clazz.getName()+"."+field.getName()+"]");
                    if(field.isAnnotationPresent(Property.class)) {
                        Property annotation = field.getAnnotation(Property.class);
                        PropertyDescriptor property = BeanUtils.getPropertyDescriptor(clazz, field.getName());

                        if(property.getWriteMethod() == null) {
                            throw new BeanConfigurationException("setter for property=["+clazz.getName()+"."+field.getName()+"] not available.");
                        }

                        Object value = resolvePlaceholder(annotation.key(), properties, SYSTEM_PROPERTIES_MODE_FALLBACK);
                        if(value == null) {
                            value = annotation.defaultValue();
                        }
                        if(value == null) {
                            throw new BeanConfigurationException("No such property=["+annotation.key()+"] found in properties.");
                        }
                        if(log.isDebugEnabled()) log.debug("setting property=["+clazz.getName()+"."+field.getName()+"] value=["+annotation.key()+"="+value+"]");
                        mpv.addPropertyValue(property.getName(), value);
                    }
                }
            }
        }
    }

}

Feel free to modify to taste

The parameters dictionary contains a null entry for parameter 'id' of non-nullable type 'System.Int32'

I also had same issue. I investigated and found missing {action} attribute from route template.

Before code (Having Issue):

config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

After Fix(Working code):

config.Routes.MapHttpRoute(
            name: "DefaultApi",
            routeTemplate: "api/{controller}/{action}/{id}",
            defaults: new { id = RouteParameter.Optional }
        );

How do I use the JAVA_OPTS environment variable?

JAVA_OPTS is environment variable used by tomcat in its startup/shutdown script to configure params.

You can set it in linux by

export JAVA_OPTS="-Djava.awt.headless=true" 

check null,empty or undefined angularjs

You can also do a simple check using function,

$scope.isNullOrEmptyOrUndefined = function (value) {
    return !value;
}

Placeholder in UITextView

Simple Swift 3 solution

Add UITextViewDelegate to your class

Set yourTextView.delegate = self

Create placeholderLabel and position it inside yourTextView

Now just animate placeholderLabel.alpha on textViewDidChange:

  func textViewDidChange(_ textView: UITextView) {
    let newAlpha: CGFloat = textView.text.isEmpty ? 1 : 0
    if placeholderLabel.alpha != newAlpha {
      UIView.animate(withDuration: 0.3) {
        self.placeholderLabel.alpha = newAlpha
      }
    }
  }

you might have to play with placeholderLabel position to set it up right, but that shouldn't be too hard

The type WebMvcConfigurerAdapter is deprecated

In Spring every request will go through the DispatcherServlet. To avoid Static file request through DispatcherServlet(Front contoller) we configure MVC Static content.

Spring 3.1. introduced the ResourceHandlerRegistry to configure ResourceHttpRequestHandlers for serving static resources from the classpath, the WAR, or the file system. We can configure the ResourceHandlerRegistry programmatically inside our web context configuration class.

  • we have added the /js/** pattern to the ResourceHandler, lets include the foo.js resource located in the webapp/js/ directory
  • we have added the /resources/static/** pattern to the ResourceHandler, lets include the foo.html resource located in the webapp/resources/ directory
@Configuration
@EnableWebMvc
public class StaticResourceConfiguration implements WebMvcConfigurer {

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        System.out.println("WebMvcConfigurer - addResourceHandlers() function get loaded...");
        registry.addResourceHandler("/resources/static/**")
                .addResourceLocations("/resources/");

        registry
            .addResourceHandler("/js/**")
            .addResourceLocations("/js/")
            .setCachePeriod(3600)
            .resourceChain(true)
            .addResolver(new GzipResourceResolver())
            .addResolver(new PathResourceResolver());
    }
}

XML Configuration

<mvc:annotation-driven />
  <mvc:resources mapping="/staticFiles/path/**" location="/staticFilesFolder/js/"
                 cache-period="60"/>

Spring Boot MVC Static Content if the file is located in the WAR’s webapp/resources folder.

spring.mvc.static-path-pattern=/resources/static/**

ps command doesn't work in docker container

If you're running a CentOS container, you can install ps using this command:

yum install -y procps

Running this command on Dockerfile:

RUN yum install -y procps

Uncaught SyntaxError: Unexpected token u in JSON at position 0

I had this issue for 2 days, let me show you how I fixed it.

This was how the code looked when I was getting the error:

request.onload = function() {
    // This is where we begin accessing the Json
    let data = JSON.parse(this.response);
    console.log(data)
}

This is what I changed to get the result I wanted:

request.onload = function() {
    // This is where we begin accessing the Json
    let data = JSON.parse(this.responseText);
    console.log(data)
}

So all I really did was change this.response to this.responseText.

IsNothing versus Is Nothing

Is Nothing requires an object that has been assigned to the value Nothing. IsNothing() can take any variable that has not been initialized, including of numeric type. This is useful for example when testing if an optional parameter has been passed.

Button background as transparent

You may also use: in your xml:

android:background="@null"

or in code:

buttonVariable.setBackgroundColor(Color.TRANSPARENT);

Entity framework self referencing loop detected

Well the correct answer for the default Json formater based on Json.net is to set ReferenceLoopHandling to Ignore.

Just add this to the Application_Start in Global.asax:

HttpConfiguration config = GlobalConfiguration.Configuration;

config.Formatters.JsonFormatter
            .SerializerSettings
            .ReferenceLoopHandling = Newtonsoft.Json.ReferenceLoopHandling.Ignore;

This is the correct way. It will ignore the reference pointing back to the object.

Other responses focused in changing the list being returned by excluding data or by making a facade object and sometimes that is not an option.

Using the JsonIgnore attribute to restrict the references can be time consuming and if you want to serialize the tree starting from another point that will be a problem.

List all devices, partitions and volumes in Powershell

You can also do it on the CLI with

net use

Could not establish secure channel for SSL/TLS with authority '*'

Had same error with code:

X509Certificate2 mycert = new X509Certificate2(@"C:\certificate.crt");

Solved by adding password:

X509Certificate2 mycert = new X509Certificate2(@"C:\certificate.crt", "password");

How to make git mark a deleted and a new file as a file move?

Do the move and the modify in separate commits.

Access iframe elements in JavaScript

If your iframe is in the same domain as your parent page you can access the elements using document.frames collection.

// replace myIFrame with your iFrame id
// replace myIFrameElemId with your iFrame's element id
// you can work on document.frames['myIFrame'].document like you are working on
// normal document object in JS
window.frames['myIFrame'].document.getElementById('myIFrameElemId')

If your iframe is not in the same domain the browser should prevent such access for security reasons.

Is there a way to continue broken scp (secure copy) command process in Linux?

If you need to resume an scp transfer from local to remote, try with rsync:

rsync --partial --progress --rsh=ssh local_file user@host:remote_file

Short version, as pointed out by @aurelijus-rozenas:

rsync -P -e ssh local_file user@host:remote_file

In general the order of args for rsync is

rsync [options] SRC DEST

Disable all table constraints in Oracle

with cursor for loop (user = 'TRANEE', table = 'D')

declare
    constr all_constraints.constraint_name%TYPE;
begin
    for constr in
        (select constraint_name from all_constraints
        where table_name = 'D'
        and owner = 'TRANEE')
    loop
        execute immediate 'alter table D disable constraint '||constr.constraint_name;
    end loop;
end;
/

(If you change disable to enable, you can make all constraints enable)

Go to next item in ForEach-Object

You just have to replace the break with a return statement.

Think of the code inside the Foreach-Object as an anonymous function. If you have loops inside the function, just use the control keywords applying to the construction (continue, break, ...).

Byte Array and Int conversion in Java

/*sorry this is the correct */

     public byte[] IntArrayToByteArray(int[] iarray , int sizeofintarray)
     {
       final ByteBuffer bb ;
       bb = ByteBuffer.allocate( sizeofintarray * 4);
       for(int k = 0; k < sizeofintarray ; k++)
       bb.putInt(k * 4, iar[k]);
       return bb.array();
     }

Checking if a key exists in a JavaScript object?

Answer:

if ("key" in myObj)
{
    console.log("key exists!");
}
else
{
    console.log("key doesn't exist!");
}

Explanation:

The in operator will check if the key exists in the object. If you checked if the value was undefined: if (myObj["key"] === 'undefined'), you could run into problems because a key could possibly exist in your object with the undefined value.

For that reason, it is much better practice to first use the in operator and then compare the value that is inside the key once you already know it exists.

How to fix Error: "Could not find schema information for the attribute/element" by creating schema

Quickest, easiest laziest way to solve the problem:

  1. Right-click on the project icon in Solution Explorer and choose "Properties".
  2. Go to the "Application" tab and choose an earlier .NET target framework.
  3. Save changes.
  4. Go to the "Application" tab and choose the initial .NET target framework.
  5. Save changes => problem solved!

How to host material icons offline?

Install npm package

npm install material-design-icons --save

Put css file path to styles.css file

@import "../node_modules/material-design-icons-iconfont/dist/material-design-icons.css";

ClientAbortException: java.net.SocketException: Connection reset by peer: socket write error

Windows Firewall could cause this exception, try to disable it or add a rule for port or even program (java)

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

You could choose to rank your data and add a ROW_NUMBER and count down to zero while iterate your dataset.

-- Get your dataset and rank your dataset by adding a new row_number
SELECT  TOP 1000 A.*, ROW_NUMBER() OVER(ORDER BY A.ID DESC) AS ROW
INTO #TEMPTABLE 
FROM DBO.TABLE AS A
WHERE STATUSID = 7;

--Find the highest number to start with
DECLARE @COUNTER INT = (SELECT MAX(ROW) FROM #TEMPTABLE);
DECLARE @ROW INT;

-- Loop true your data until you hit 0
WHILE (@COUNTER != 0)
BEGIN

    SELECT @ROW = ROW
    FROM #TEMPTABLE
    WHERE ROW = @COUNTER
    ORDER BY ROW DESC

    --DO SOMTHING COOL  

    -- SET your counter to -1
    SET @COUNTER = @ROW -1
END

DROP TABLE #TEMPTABLE

jQuery vs document.querySelectorAll

Just a comment on this, when using material design lite, jquery selector does not return the property for material design for some reason.

For:

<div class="logonfield mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
        <input class="mdl-textfield__input" type="text" id="myinputfield" required>
        <label class="mdl-textfield__label" for="myinputfield">Enter something..</label>
      </div>

This works:

document.querySelector('#myinputfield').parentNode.MaterialTextfield.change();

This does not:

$('#myinputfield').parentNode.MaterialTextfield.change();

getApplication() vs. getApplicationContext()

Compare getApplication() and getApplicationContext().

getApplication returns an Application object which will allow you to manage your global application state and respond to some device situations such as onLowMemory() and onConfigurationChanged().

getApplicationContext returns the global application context - the difference from other contexts is that for example, an activity context may be destroyed (or otherwise made unavailable) by Android when your activity ends. The Application context remains available all the while your Application object exists (which is not tied to a specific Activity) so you can use this for things like Notifications that require a context that will be available for longer periods and independent of transient UI objects.

I guess it depends on what your code is doing whether these may or may not be the same - though in normal use, I'd expect them to be different.

How do I use valgrind to find memory leaks?

You can create an alias in .bashrc file as follows

alias vg='valgrind --leak-check=full -v --track-origins=yes --log-file=vg_logfile.out'

So whenever you want to check memory leaks, just do simply

vg ./<name of your executable> <command line parameters to your executable>

This will generate a Valgrind log file in the current directory.

How can I expand and collapse a <div> using javascript?

Check out Jed Foster's Readmore.js library.

It's usage is as simple as:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $('article').readmore({collapsedHeight: 100});_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"></script>_x000D_
<script src="https://fastcdn.org/Readmore.js/2.1.0/readmore.min.js" type="text/javascript"></script>_x000D_
_x000D_
<article>_x000D_
  <p>From this distant vantage point, the Earth might not seem of any particular interest. But for us, it's different. Consider again that dot. That's here. That's home. That's us. On it everyone you love, everyone you know, everyone you ever heard of, every human being who ever was, lived out their lives. The aggregate of our joy and suffering, thousands of confident religions, ideologies, and economic doctrines, every hunter and forager, every hero and coward, every creator and destroyer of civilization, every king and peasant, every young couple in love, every mother and father, hopeful child, inventor and explorer, every teacher of morals, every corrupt politician, every "superstar," every "supreme leader," every saint and sinner in the history of our species lived there – on a mote of dust suspended in a sunbeam.</p>_x000D_
_x000D_
  <p>Space, the final frontier. These are the voyages of the starship Enterprise. Its five year mission: to explore strange new worlds, to seek out new life and new civilizations, to boldly go where no man has gone before!</p>_x000D_
_x000D_
  <p>Here's how it is: Earth got used up, so we terraformed a whole new galaxy of Earths, some rich and flush with the new technologies, some not so much. Central Planets, them was formed the Alliance, waged war to bring everyone under their rule; a few idiots tried to fight it, among them myself. I'm Malcolm Reynolds, captain of Serenity. Got a good crew: fighters, pilot, mechanic. We even picked up a preacher, and a bona fide companion. There's a doctor, too, took his genius sister out of some Alliance camp, so they're keeping a low profile. You got a job, we can do it, don't much care what it is.</p>_x000D_
_x000D_
  <p>Space, the final frontier. These are the voyages of the starship Enterprise. Its five year mission: to explore strange new worlds, to seek out new life and new civilizations, to boldly go where no man has gone before!</p>_x000D_
</article>
_x000D_
_x000D_
_x000D_

Here are the available options to configure your widget:

_x000D_
_x000D_
{_x000D_
  speed: 100,_x000D_
  collapsedHeight: 200,_x000D_
  heightMargin: 16,_x000D_
  moreLink: '<a href="#">Read More</a>',_x000D_
  lessLink: '<a href="#">Close</a>',_x000D_
  embedCSS: true,_x000D_
  blockCSS: 'display: block; width: 100%;',_x000D_
  startOpen: false,_x000D_
_x000D_
  // callbacks_x000D_
  blockProcessed: function() {},_x000D_
  beforeToggle: function() {},_x000D_
  afterToggle: function() {}_x000D_
},
_x000D_
_x000D_
_x000D_

Use can use it like:

_x000D_
_x000D_
$('article').readmore({_x000D_
  collapsedHeight: 100,_x000D_
  moreLink: '<a href="#" class="you-can-also-add-classes-here">Continue reading...</a>',_x000D_
});
_x000D_
_x000D_
_x000D_

I hope it helps.

scrollIntoView Scrolls just too far

Found a workaround solution. Say that you want to scroll to an div, Element here for example, and you want to have a spacing of 20px above it. Set the ref to a created div above it:

<div ref={yourRef} style={{position: 'relative', bottom: 20}}/> <Element />

Doing so will create this spacing that you want.

If you have a header, create an empty div as well behind the header and assign to it a height equal to the height of the header and reference it.

How can I start PostgreSQL server on Mac OS X?

For Mac OS X, I really like LaunchRocket for this and other background services I used in development.

This site has nice instructions on installation.

This gives you a nice screen in your System Preferences that allows you to launch, reboot, root, and launch at login.

Split string into individual words Java

StringTokenizer separate = new StringTokenizer(s, " ");
String word = separate.nextToken();
System.out.println(word);

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

If you get errors trying to install mysqlclient with pip, you may lack the mysql dev library. Install it by running:

apt-get install libmysqlclient-dev

and try again to install mysqlclient:

pip install mysqlclient

How to change port for jenkins window service when 8080 is being used

Restart Jenkins service

Just restart the Jenkins service after you changed the port in jenkins.xml.

  1. Press Win + R
  2. Type "services.msc"
  3. Right click on the "Jenkins" line > Restart

    Restart Jenkins

  4. Type http://localhost:8081/ in your browser to test the change.

Convert a row of a data frame to vector

If you don't want to change to numeric you can try this.

> as.vector(t(df)[,1])
[1] 1.0 2.0 2.6

git add only modified changes and ignore untracked files

To stage modified and deleted files

git add -u

SQL Server: Get data for only the past year

The following adds -1 years to the current date:

SELECT ... From ... WHERE date > DATEADD(year,-1,GETDATE())

Count occurrences of a char in a string using Bash

awk is very cool, but why not keep it simple?

num=$(echo $var | grep -o "," | wc -l)

CSS: auto height on containing div, 100% height on background div inside containing div

You shouldn't have to set height: 100% at any point if you want your container to fill the page. Chances are, your problem is rooted in the fact that you haven't cleared the floats in the container's children. There are quite a few ways to solve this problem, mainly adding overflow: hidden to the container.

#container { overflow: hidden; }

Should be enough to solve whatever height problem you're having.

Convert DataTable to IEnumerable<T>

Nothing wrong with that implementation. You might give the yield keyword a shot, see how you like it:

private IEnumerable<TankReading> ConvertToTankReadings(DataTable dataTable)
    {
        foreach (DataRow row in dataTable.Rows)
        {
            yield return new TankReading
                                  {
                                      TankReadingsID = Convert.ToInt32(row["TRReadingsID"]),
                                      TankID = Convert.ToInt32(row["TankID"]),
                                      ReadingDateTime = Convert.ToDateTime(row["ReadingDateTime"]),
                                      ReadingFeet = Convert.ToInt32(row["ReadingFeet"]),
                                      ReadingInches = Convert.ToInt32(row["ReadingInches"]),
                                      MaterialNumber = row["MaterialNumber"].ToString(),
                                      EnteredBy = row["EnteredBy"].ToString(),
                                      ReadingPounds = Convert.ToDecimal(row["ReadingPounds"]),
                                      MaterialID = Convert.ToInt32(row["MaterialID"]),
                                      Submitted = Convert.ToBoolean(row["Submitted"]),
                                  };
        }

    }

Also the AsEnumerable isn't necessary, as List<T> is already an IEnumerable<T>

Landscape printing from HTML

<style type="text/css" media="print">
.landscape { 
    width: 100%; 
    height: 100%; 
    margin: 0% 0% 0% 0%; filter: progid:DXImageTransform.Microsoft.BasicImage(Rotation=1); 
} 
</style>

If you want this style to be applied to a table then create one div tag with this style class and add the table tag within this div tag and close the div tag at the end.

This table will only print in landscape and all other pages will print in portrait mode only. But the problem is if the table size is more than the page width then we may loose some of the rows and sometimes headers also are missed. Be careful.

Have a good day.

Thank you, Naveen Mettapally.

How to return a list of keys from a Hash Map?

Since Java 8:

List<String> myList = map.keySet().stream().collect(Collectors.toList());

getch and arrow codes

I have written a function using getch to get arrow code. it's a quick'n'dirty solution but the function will return an ASCII code depending on arrow key : UP : -10 DOWN : -11 RIGHT : -12 LEFT : -13

Moreover,with this function, you will be able to differenciate the ESCAPE touch and the arrow keys. But you have to press ESC 2 time to activate the ESC key.

here the code :

char getch_hotkey_upgrade(void)
{
  char ch = 0,ch_test[3] = {0,0,0};

    ch_test[0]=getch();

    if(ch_test[0] == 27)
    {
        ch_test[1]=getch();

        if (ch_test[1]== 91)
        {
            ch_test[2]=getch();

            switch(ch_test[2])
            {
            case 'A':
                //printf("You pressed the up arrow key !!\n");
                //ch = -10;
                ch = -10;
                break;
            case 'B':
                //printf("You pressed the down arrow key !!\n");
                ch = -11;
                break;
            case 'C':
                //printf("You pressed the right arrow key !!\n");
                ch = -12;
                break;
            case 'D':
                //printf("You pressed the left arrow key !!\n");
                ch = -13;
                break;
            }
        }
        else
         ch = ch_test [1];
    }
    else
        ch = ch_test [0];
  return ch;
}

How can I convert an Int to a CString?

If you want something more similar to your example try _itot_s. On Microsoft compilers _itot_s points to _itoa_s or _itow_s depending on your Unicode setting:

CString str;
_itot_s( 15, str.GetBufferSetLength( 40 ), 40, 10 );
str.ReleaseBuffer();

it should be slightly faster since it doesn't need to parse an input format.

How to merge 2 JSON objects from 2 files using jq?

Who knows if you still need it, but here is the solution.

Once you get to the --slurp option, it's easy!

--slurp/-s:
    Instead of running the filter for each JSON object in the input,
    read the entire input stream into a large array and run the filter just once.

Then the + operator will do what you want:

jq -s '.[0] + .[1]' config.json config-user.json

(Note: if you want to merge inner objects instead of just overwriting the left file ones with the right file ones, you will need to do it manually)

How to determine the encoding of text?

If you know the some content of the file you can try to decode it with several encoding and see which is missing. In general there is no way since a text file is a text file and those are stupid ;)

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

Hmm, there are a few things going wrong here.

for f in os.listdir(src_dir):
    os.path.join(src_dir, f)

You're not storing the result of join. This should be something like:

for f in os.listdir(src_dir):
    f = os.path.join(src_dir, f)

This open call is is the cause of your IOError. (Because without storing the result of the join above, f was still just 'file.csv', not 'src_dir/file.csv'.)

Also, the syntax:

with open(f): 

is close, but the syntax isn't quite right. It should be with open(file_name) as file_object:. Then, you use to the file_object to perform read or write operations.

And finally:

write(line)

You told python what you wanted to write, but not where to write it. Write is a method on the file object. Try file_object.write(line).

Edit: You're also clobbering your input file. You probably want to open the output file and write lines to it as you're reading them in from the input file.

See: input / output in python.

PHP: Split string into array, like explode with no delimiter

What are you trying to accomplish? You can access characters in a string just like an array:

$s = 'abcd';
echo $s[0];

prints 'a'

jQuery $.ajax(), pass success data into separate function

In the first code block, you're never using the str parameter. Did you mean to say the following?

testFunc = function(str, callback) {
    $.ajax({
        type: 'POST',
        url: 'http://www.myurl.com',
        data: str,
        success: callback
    });
}

Angular - "has no exported member 'Observable'"

The angular-split component is not supported in Angular 6, so to make it compatible with Angular 6 install following dependency in your application

To get this working until it's updated use:

"dependencies": {
"angular-split": "1.0.0-rc.3",
"rxjs": "^6.2.2",
    "rxjs-compat": "^6.2.2",
}

How to cin Space in c++?

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

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

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

Detect if user is scrolling

You just said javascript in your tags, so @Wampie Driessen post could helps you.

I want also to contribute, so you can use the following when using jQuery if you need it.

 //Firefox
 $('#elem').bind('DOMMouseScroll', function(e){
     if(e.detail > 0) {
         //scroll down
         console.log('Down');
     }else {
         //scroll up
         console.log('Up');
     }

     //prevent page fom scrolling
     return false;
 });

 //IE, Opera, Safari
 $('#elem').bind('mousewheel', function(e){
     if(e.wheelDelta< 0) {
         //scroll down
         console.log('Down');
     }else {
         //scroll up
         console.log('Up');
     }

     //prevent page fom scrolling
     return false;
 });

Another example:

$(function(){
    var _top = $(window).scrollTop();
    var _direction;
    $(window).scroll(function(){
        var _cur_top = $(window).scrollTop();
        if(_top < _cur_top)
        {
            _direction = 'down';
        }
        else
        {
            _direction = 'up';
        }
        _top = _cur_top;
        console.log(_direction);
    });
});?

Responsive Images with CSS

.erb-image-wrapper img{
    max-width:100% !important;
    height:auto;
    display:block;
}

Worked for me.
Thanks for MrMisterMan for his assistance.

How do I format date value as yyyy-mm-dd using SSIS expression builder?

Looks like you created a separate question. I was answering your other question How to change flat file source using foreach loop container in an SSIS package? with the same answer. Anyway, here it is again.

Create two string data type variables namely DirPath and FilePath. Set the value C:\backup\ to the variable DirPath. Do not set any value to the variable FilePath.

Variables

Select the variable FilePath and select F4 to view the properties. Set the EvaluateAsExpression property to True and set the Expression property as @[User::DirPath] + "Source" + (DT_STR, 4, 1252) DATEPART("yy" , GETDATE()) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("mm" , GETDATE()), 2) + "-" + RIGHT("0" + (DT_STR, 2, 1252) DATEPART("dd" , GETDATE()), 2)

Expression

Div Background Image Z-Index Issue

For z-index to work, you also need to give it a position:

header {
    width: 100%;
    height: 100px;
    background: url(../img/top.png) repeat-x;
    z-index: 110;
    position: relative;
}

IE Enable/Disable Proxy Settings via Registry

The problem is that IE won't reset the proxy settings until it either

  1. closes, or
  2. has its configuration refreshed.

Below is the code that I've used to get this working:

function Refresh-System
{
  $signature = @'
[DllImport("wininet.dll", SetLastError = true, CharSet=CharSet.Auto)]
public static extern bool InternetSetOption(IntPtr hInternet, int dwOption, IntPtr lpBuffer, int dwBufferLength);
'@

$INTERNET_OPTION_SETTINGS_CHANGED   = 39
$INTERNET_OPTION_REFRESH            = 37
$type = Add-Type -MemberDefinition $signature -Name wininet -Namespace pinvoke -PassThru
$a = $type::InternetSetOption(0, $INTERNET_OPTION_SETTINGS_CHANGED, 0, 0)
$b = $type::InternetSetOption(0, $INTERNET_OPTION_REFRESH, 0, 0)
return $a -and $b
}

C++11 thread-safe queue

According to the standard condition_variables are allowed to wakeup spuriously, even if the event hasn't occured. In case of a spurious wakeup it will return cv_status::no_timeout (since it woke up instead of timing out), even though it hasn't been notified. The correct solution for this is of course to check if the wakeup was actually legit before proceding.

The details are specified in the standard §30.5.1 [thread.condition.condvar]:

—The function will unblock when signaled by a call to notify_one(), a call to notify_all(), expiration of the absolute timeout (30.2.4) speci?ed by abs_time, or spuriously.

...

Returns: cv_status::timeout if the absolute timeout (30.2.4) speci?edby abs_time expired, other-ise cv_status::no_timeout.

How does one use the onerror attribute of an img element

This is actually tricky, especially if you plan on returning an image url for use cases where you need to concatenate strings with the onerror condition image URL, e.g. you might want to programatically set the url parameter in CSS.

The trick is that image loading is asynchronous by nature so the onerror doesn't happen sunchronously, i.e. if you call returnPhotoURL it immediately returns undefined bcs the asynchronous method of loading/handling the image load just began.

So, you really need to wrap your script in a Promise then call it like below. NOTE: my sample script does some other things but shows the general concept:

returnPhotoURL().then(function(value){
    doc.getElementById("account-section-image").style.backgroundImage = "url('" + value + "')";
}); 


function returnPhotoURL(){
    return new Promise(function(resolve, reject){
        var img = new Image();
        //if the user does not have a photoURL let's try and get one from gravatar
        if (!firebase.auth().currentUser.photoURL) {
            //first we have to see if user han an email
            if(firebase.auth().currentUser.email){
                //set sign-in-button background image to gravatar url
                img.addEventListener('load', function() {
                    resolve (getGravatar(firebase.auth().currentUser.email, 48));
                }, false);
                img.addEventListener('error', function() {
                    resolve ('//rack.pub/media/fallbackImage.png');
                }, false);            
                img.src = getGravatar(firebase.auth().currentUser.email, 48);
            } else {
                resolve ('//rack.pub/media/fallbackImage.png');
            }
        } else {
            img.addEventListener('load', function() {
                resolve (firebase.auth().currentUser.photoURL);
            }, false);
            img.addEventListener('error', function() {
                resolve ('https://rack.pub/media/fallbackImage.png');
            }, false);      
            img.src = firebase.auth().currentUser.photoURL;
        }
    });
}

Calculate the date yesterday in JavaScript

Try this

var d = new Date();
d.setDate(d.getDate() - 1);

How to store a byte array in Javascript

You could store the data in an array of strings of some large fixed size. It should be efficient to access any particular character in that array of strings, and to treat that character as a byte.

It would be interesting to see the operations you want to support, perhaps expressed as an interface, to make the question more concrete.

Left/Right float button inside div

You can use justify-content: space-between in .test like so:

_x000D_
_x000D_
.test {_x000D_
  display: flex;_x000D_
  justify-content: space-between;_x000D_
  width: 20rem;_x000D_
  border: .1rem red solid;_x000D_
}
_x000D_
<div class="test">_x000D_
  <button>test</button>_x000D_
  <button>test</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_


For those who want to use Bootstrap 4 can use justify-content-between:

_x000D_
_x000D_
div {_x000D_
  width: 20rem;_x000D_
  border: .1rem red solid;_x000D_
}
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet" />_x000D_
<div class="d-flex justify-content-between">_x000D_
  <button>test</button>_x000D_
  <button>test</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to get attribute of element from Selenium?

Python

element.get_attribute("attribute name")

Java

element.getAttribute("attribute name")

Ruby

element.attribute("attribute name")

C#

element.GetAttribute("attribute name");

Convert Newtonsoft.Json.Linq.JArray to a list of specific object type

The API return value in my case as shown here:

{
  "pageIndex": 1,
  "pageSize": 10,
  "totalCount": 1,
  "totalPageCount": 1,
  "items": [
    {
      "firstName": "Stephen",
      "otherNames": "Ebichondo",
      "phoneNumber": "+254721250736",
      "gender": 0,
      "clientStatus": 0,
      "dateOfBirth": "1979-08-16T00:00:00",
      "nationalID": "21734397",
      "emailAddress": "[email protected]",
      "id": 1,
      "addedDate": "2018-02-02T00:00:00",
      "modifiedDate": "2018-02-02T00:00:00"
    }
  ],
  "hasPreviousPage": false,
  "hasNextPage": false
}

The conversion of the items array to list of clients was handled as shown here:

 if (responseMessage.IsSuccessStatusCode)
        {
            var responseData = responseMessage.Content.ReadAsStringAsync().Result;
            JObject result = JObject.Parse(responseData);

            var clientarray = result["items"].Value<JArray>();
            List<Client> clients = clientarray.ToObject<List<Client>>();
            return View(clients);
        }

Correlation between two vectors?

For correlations you can just use the corr function (statistics toolbox)

corr(A_1(:), A_2(:))

Note that you can also just use

corr(A_1, A_2)

But the linear indexing guarantees that your vectors don't need to be transposed.

Android Layout Animations from bottom to top and top to bottom on ImageView click

Try this :

Create anim folder inside your res folder and copy this four files :

slide_in_bottom.xml :

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromYDelta="100%p"
android:duration="@android:integer/config_longAnimTime"/>  

slide_out_bottom.xml :

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:fromYDelta="0" 
android:duration="@android:integer/config_longAnimTime" /> 

slide_in_top.xml :

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
 android:toYDelta="0%p"
android:duration="@android:integer/config_longAnimTime" />

slide_out_top.xml :

<?xml version="1.0" encoding="utf-8"?>
<translate xmlns:android="http://schemas.android.com/apk/res/android"
android:toYDelta="100%p"
android:duration="@android:integer/config_longAnimTime" />

When you click on image view call:

overridePendingTransition(R.anim.slide_in_bottom, R.anim.slide_out_bottom);

When you click on original place call:

overridePendingTransition(R.anim.slide_in_top, R.anim.slide_out_top);

Main Activity :

package com.example.animationtest;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.Menu;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class MainActivity extends Activity {

Button btn1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    btn1 = (Button) findViewById(R.id.btn1);


    btn1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
            startActivity(new Intent(MainActivity.this, test.class));

        }
    });


}
    }

activity_main.xml :

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  tools:context=".MainActivity" >

<Button
    android:id="@+id/btn1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button1" />

 </LinearLayout>

test.java :

package com.example.animationtest;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;

public class test extends Activity {

Button btn1;

@Override
protected void onCreate(Bundle savedInstanceState) {
    // TODO Auto-generated method stub
    super.onCreate(savedInstanceState);
    setContentView(R.layout.test);
    btn1 = (Button) findViewById(R.id.btn1);

    overridePendingTransition(R.anim.slide_in_left, R.anim.slide_out_left);

    btn1.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {
         finish();
            overridePendingTransition(R.anim.slide_in_right,
                    R.anim.slide_out_right);
            startActivity(new Intent(test.this, MainActivity.class));


        }
    });
}

    }

test.xml :

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >

<Button
    android:id="@+id/btn1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Button1" />

 </LinearLayout>

Hope this helps.

How to style input and submit button with CSS?

Very simple:

<html>
<head>
<head>
<style type="text/css">
.buttonstyle 
{ 
background: black; 
background-position: 0px -401px; 
border: solid 1px #000000; 
color: #ffffff;
height: 21px;
margin-top: -1px;
padding-bottom: 2px;
}
.buttonstyle:hover {background: white;background-position: 0px -501px;color: #000000; }
</style>
</head>
<body>
<form>
<input class="buttonstyle" type="submit" name="submit" Value="Add Items"/>
</form>
</body>
</html>

This is working I have tested.

How can I count all the lines of code in a directory recursively?

You didn't specify how many files are there or what is the desired output.

This may be what you are looking for:

find . -name '*.php' | xargs wc -l

How does BitLocker affect performance?

Some practical tests...

  • Dell Latitude E7440
  • Intel Core i7-4600U
  • 16.0 GB
  • Windows 8.1 Professional
  • LiteOn IT LMT-256M6M MSATA 256GB

This test is using a system partition. Results for a non-system partition are a bit better.

Score decrease:
Read: 5%
Write: 16%

Without BitLocker:

Without BitLocker

With BitLocker:

With BitLocker

So you can see that with a very strong configuration and a modern SSD disk you can see a small performance degradation with tests. I don't know what about a typical work, especially with the Visual Studio.

MySQL: Cloning a MySQL database on the same MySql instance

You could use (in pseudocode):

FOREACH tbl IN db_a:
    CREATE TABLE db_b.tbl LIKE db_a.tbl;
    INSERT INTO db_b.tbl SELECT * FROM db_a.tbl;

The reason I'm not using the CREATE TABLE ... SELECT ... syntax is to preserve indices. Of course this only copies tables. Views and procedures are not copied, although it can be done in the same manner.

See CREATE TABLE.

how to move elasticsearch data from one server to another

If you simply need to transfer data from one elasticsearch server to another, you could also use elasticsearch-document-transfer.

Steps:

  1. Open a directory in your terminal and run
    $ npm install elasticsearch-document-transfer.
  2. Create a file config.js
  3. Add the connection details of both elasticsearch servers in config.js
  4. Set appropriate values in options.js
  5. Run in the terminal
    $ node index.js

Browser back button handling

You can also add hash when page is loading:

location.hash = "noBack";

Then just handle location hash change to add another hash:

$(window).on('hashchange', function() {
    location.hash = "noBack";
});

That makes hash always present and back button tries to remove hash at first. Hash is then added again by "hashchange" handler - so page would never actually can be changed to previous one.

How do I capture the output into a variable from an external process in PowerShell?

I tried the answers, but in my case I did not get the raw output. Instead it was converted to a PowerShell exception.

The raw result I got with:

$rawOutput = (cmd /c <command> 2`>`&1)

Are (non-void) self-closing tags valid in HTML5?

As Nikita Skvortsov pointed out, a self-closing div will not validate. This is because a div is a normal element, not a void element.

According to the HTML5 spec, tags that cannot have any contents (known as void elements) can be self-closing*. This includes the following tags:

area, base, br, col, embed, hr, img, input, 
keygen, link, meta, param, source, track, wbr

The "/" is completely optional on the above tags, however, so <img/> is not different from <img>, but <img></img> is invalid.

*Note: foreign elements can also be self-closing, but I don't think that's in scope for this answer.

Run Python script at startup in Ubuntu

If you are on Ubuntu you don't need to write any other code except your Python file's code , Here are the Steps :-

  • Open Dash (The First Icon In Sidebar).
  • Then type Startup Applications and open that app.
  • Here Click the Add Button on the right.
  • There fill in the details and in the command area browse for your Python File and click Ok.
  • Test it by Restarting System . Done . Enjoy !!

What is the function of the push / pop instructions used on registers in x86 assembly?

Here is how you push a register. I assume we are talking about x86.

push ebx
push eax

It is pushed on stack. The value of ESP register is decremented to size of pushed value as stack grows downwards in x86 systems.

It is needed to preserve the values. The general usage is

push eax           ;   preserve the value of eax
call some_method   ;   some method is called which will put return value in eax
mov  edx, eax      ;    move the return value to edx
pop  eax           ;    restore original eax

A push is a single instruction in x86, which does two things internally.

  1. Decrement the ESP register by the size of pushed value.
  2. Store the pushed value at current address of ESP register.

How do I link object files in C? Fails with "Undefined symbols for architecture x86_64"

The existing answers already cover the "how", but I just wanted to elaborate on the "what" and "why" for others who might be wondering.

What a compiler (gcc) does: The term "compile" is a bit of an overloaded term because it is used at a high-level to mean "convert source code to a program", but more technically means to "convert source code to object code". A compiler like gcc actually performs two related, but arguably distinct functions to turn your source code into a program: compiling (as in the latter definition of turning source to object code) and linking (the process of combining the necessary object code files together into one complete executable).

The original error that you saw is technically a "linking error", and is thrown by "ld", the linker. Unlike (strict) compile-time errors, there is no reference to source code lines, as the linker is already in object space.

By default, when gcc is given source code as input, it attempts to compile each and then link them all together. As noted in the other responses, it's possible to use flags to instruct gcc to just compile first, then use the object files later to link in a separate step. This two-step process may seem unnecessary (and probably is for very small programs) but it is very important when managing a very large program, where compiling the entire project each time you make a small change would waste a considerable amount of time.

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

If u r using SQLite3 beware:

It takes only 't' or 'f'. Not 1 or 0. Not TRUE OR FALSE.

Just learned the hard way.

Ansible: Store command's stdout in new variable?

In case than you want to store a complex command to compare text result, for example to compare the version of OS, maybe this can help you:

tasks:
       - shell: echo $(cat /etc/issue | awk {'print $7'})
         register: echo_content

       - shell: echo "It works"
         when: echo_content.stdout == "12"
         register: out
       - debug: var=out.stdout_lines

.htaccess redirect http to https

Insert this code in your .htaccess file. And it should work

RewriteCond %{HTTP_HOST} yourDomainName\.com [NC]
RewriteCond %{SERVER_PORT} 80
RewriteRule ^(.*)$ https://yourDomainName.com/$1 [R,L]

How can I count the numbers of rows that a MySQL query returned?

If you want the result plus the number of rows returned do something like this. Using PHP.

$query = "SELECT * FROM Employee";
$result = mysql_query($query);
echo "There are ".mysql_num_rows($result)." Employee(s).";

Change Color of Fonts in DIV (CSS)

To do links, you can do

.social h2 a:link {
  color: pink;
  font-size: 14px;   
}

You can change the hover, visited, and active link styling too. Just replace "link" with what you want to style. You can learn more at the w3schools page CSS Links.

Sending intent to BroadcastReceiver from adb

Noting down my situation here may be useful to somebody,

I have to send a custom intent with multiple intent extras to a broadcast receiver in Android P,

The details are,

Receiver name: com.hardian.testservice.TestBroadcastReceiver

Intent action = "com.hardian.testservice.ADD_DATA"

intent extras are,

  1. "text"="test msg",
  2. "source"= 1,

Run the following in command line.

adb shell "am broadcast -a com.hardian.testservice.ADD_DATA --es text 'test msg' --es source 1 -n com.hardian.testservice/.TestBroadcastReceiver"

Hope this helps.

How do I drag and drop files into an application?

You need to be aware of a gotcha. Any class that you pass around as the DataObject in the drag/drop operation has to be Serializable. So if you try and pass an object, and it is not working, ensure it can be serialized as that is almost certainly the problem. This has caught me out a couple of times!

How can I determine whether a 2D Point is within a Polygon?

C# version of nirg's answer is here: I'll just share the code. It may save someone some time.

public static bool IsPointInPolygon(IList<Point> polygon, Point testPoint) {
            bool result = false;
            int j = polygon.Count() - 1;
            for (int i = 0; i < polygon.Count(); i++) {
                if (polygon[i].Y < testPoint.Y && polygon[j].Y >= testPoint.Y || polygon[j].Y < testPoint.Y && polygon[i].Y >= testPoint.Y) {
                    if (polygon[i].X + (testPoint.Y - polygon[i].Y) / (polygon[j].Y - polygon[i].Y) * (polygon[j].X - polygon[i].X) < testPoint.X) {
                        result = !result;
                    }
                }
                j = i;
            }
            return result;
        }

How to declare a global variable in php?

$GLOBALS[] is the right solution, but since we're talking about alternatives, a function can also do this job easily:

function capital() {
    return my_var() . ' is the capital of Italy';
}

function my_var() {
    return 'Rome';
}

Is there a way of setting culture for a whole application? All current threads and new threads?

For ASP.NET5, i.e. ASPNETCORE, you can do the following in configure:

app.UseRequestLocalization(new RequestLocalizationOptions
{
    DefaultRequestCulture = new RequestCulture(new CultureInfo("en-gb")),
    SupportedCultures = new List<CultureInfo>
    {
        new CultureInfo("en-gb")
    },
            SupportedUICultures = new List<CultureInfo>
    {
        new CultureInfo("en-gb")
    }
});

Here's a series of blog posts that gives more information.

How to handle :java.util.concurrent.TimeoutException: android.os.BinderProxy.finalize() timed out after 10 seconds errors?

We solved the problem by stopping the FinalizerWatchdogDaemon.

public static void fix() {
    try {
        Class clazz = Class.forName("java.lang.Daemons$FinalizerWatchdogDaemon");

        Method method = clazz.getSuperclass().getDeclaredMethod("stop");
        method.setAccessible(true);

        Field field = clazz.getDeclaredField("INSTANCE");
        field.setAccessible(true);

        method.invoke(field.get(null));

    }
    catch (Throwable e) {
        e.printStackTrace();
    }
}

You can call the method in Application's lifecycle, like attachBaseContext(). For the same reason, you also can specific the phone's manufacture to fix the problem, it's up to you.

How do I use DateTime.TryParse with a Nullable<DateTime>?

As Jason says, you can create a variable of the right type and pass that. You might want to encapsulate it in your own method:

public static DateTime? TryParse(string text)
{
    DateTime date;
    if (DateTime.TryParse(text, out date))
    {
        return date;
    }
    else
    {
        return null;
    }
}

... or if you like the conditional operator:

public static DateTime? TryParse(string text)
{
    DateTime date;
    return DateTime.TryParse(text, out date) ? date : (DateTime?) null;
}

Or in C# 7:

public static DateTime? TryParse(string text) =>
    DateTime.TryParse(text, out var date) ? date : (DateTime?) null;

Passing references to pointers in C++

Welcome to C++11 and rvalue references:

#include <cassert>
#include <string>

using std::string;

void myfunc(string*&& val)
{
    assert(&val);
    assert(val);
    assert(val->c_str());
    // Do stuff to the string pointer
}

// sometime later 
int main () {
    // ...
    string s;
    myfunc(&s);
    // ...
}

Now you have access to the value of the pointer (referred to by val), which is the address of the string.

You can modify the pointer, and no one will care. That is one aspect of what an rvalue is in the first place.

Be careful: The value of the pointer is only valid until myfunc() returns. At last, its a temporary.

Postgresql -bash: psql: command not found

If you are using the Postgres Mac app (by Heroku) and Bundler, you can add the pg_config directly inside the app, to your bundle.

bundle config build.pg --with-pg-config=/Applications/Postgres.app/Contents/Versions/9.4/bin/pg_config

...then run bundle again.

Note: check the version first using the following.

ls /Applications/Postgres.app/Contents/Versions/

How to check the installed version of React-Native

To see the local packages installed in your project including their versions and without their dependencies, run the below command from the project's root directory. In a React native app this would include the react-native package.

npm list --depth 0

Or if you installed them with yarn:

yarn list --depth=0

And to get just a specific package:

npm list react-native --depth 0
yarn list --pattern react-native --depth=0

Apply CSS rules if browser is IE

In browsers up to and including IE9, this is done through conditional comments.

<!--[if IE]>
<style type="text/css">
  IE specific CSS rules go here
</style>
<![endif]-->

How to pattern match using regular expression in Scala?

To expand a little on Andrew's answer: The fact that regular expressions define extractors can be used to decompose the substrings matched by the regex very nicely using Scala's pattern matching, e.g.:

val Process = """([a-cA-C])([^\s]+)""".r // define first, rest is non-space
for (p <- Process findAllIn "aha bah Cah dah") p match {
  case Process("b", _) => println("first: 'a', some rest")
  case Process(_, rest) => println("some first, rest: " + rest)
  // etc.
}

Bootstrap 4, how to make a col have a height of 100%?

I solved this like this:

    <section className="container-fluid">
            <div className="row justify-content-center">

                <article className="d-flex flex-column justify-content-center align-items-center vh-100">
                        <!-- content -->
                </article>

            </div>
    </section>

Is it possible to use Visual Studio on macOS?

I recently purchased a MacBook Air (mid-2011 model) and was really happy to find that Apple officially supports Windows 7. If you purchase Windows 7 (I got DSP), you can use the Boot Camp assistant in OSX to designate part of your hard drive to Windows. Then you can install and run Windows 7 natively as if it were as Windows notebook.

I use Visual Studio 2010 on Windows 7 on my MacBook Air (I kept OSX as well) and I could not be happier. Heck, the initial start-up of the program only takes 3 seconds thanks to the SSD.

As others have mentions, you can run it on OSX using Parallels, etc. but I prefer to run it natively.

How to get IP address of running docker container

You can start your container with the flag -P. This "assigns" a random port to the exposed port of your image.

With docker port <container id> you can see the randomly choosen port. Access is then possible via localhost:port.

What's the difference between git reset --mixed, --soft, and --hard?

Please be aware, this is a simplified explanation intended as a first step in seeking to understand this complex functionality.

May be helpful for visual learners who want to visualise what their project state looks like after each of these commands:

Given: - A - B - C (master)


For those who use Terminal with colour turned on (git config --global color.ui auto):

git reset --soft A and you will see B and C's stuff in green (staged and ready to commit)

git reset --mixed A (or git reset A) and you will see B and C's stuff in red (unstaged and ready to be staged (green) and then committed)

git reset --hard A and you will no longer see B and C's changes anywhere (will be as if they never existed)


Or for those who use a GUI program like 'Tower' or 'SourceTree'

git reset --soft A and you will see B and C's stuff in the 'staged files' area ready to commit

git reset --mixed A (or git reset A) and you will see B and C's stuff in the 'unstaged files' area ready to be moved to staged and then committed

git reset --hard A and you will no longer see B and C's changes anywhere (will be as if they never existed)

Can I update a JSF component from a JSF backing bean method?

The RequestContext is deprecated from Primefaces 6.2. From this version use the following:

if (componentID != null && PrimeFaces.current().isAjaxRequest()) {
    PrimeFaces.current().ajax().update(componentID);
}

And to execute javascript from the backbean use this way:

PrimeFaces.current().executeScript(jsCommand);

Reference:

apache ProxyPass: how to preserve original IP address

If you have the capability to do so, I would recommend using either mod-jk or mod-proxy-ajp to pass requests from Apache to JBoss. The AJP protocol is much more efficient compared to using HTTP proxy requests and as a benefit, JBoss will see the request as coming from the original client and not Apache.

How to wait for the 'end' of 'resize' event and only then perform an action?

Here is VERY simple script to trigger both a 'resizestart' and 'resizeend' event on the window object.

There is no need to muck around with dates and times.

The d variable represents the number of milliseconds between resize events before triggering the resize end event, you can play with this to change how sensitive the end event is.

To listen to these events all you need to do is:

resizestart: $(window).on('resizestart', function(event){console.log('Resize Start!');});

resizeend: $(window).on('resizeend', function(event){console.log('Resize End!');});

(function ($) {
    var d = 250, t = null, e = null, h, r = false;

    h = function () {
        r = false;
        $(window).trigger('resizeend', e);
    };

    $(window).on('resize', function (event) {
        e = event || e;
        clearTimeout(t);

        if (!r) {
            $(window).trigger('resizestart', e);
            r = true;
        }

        t = setTimeout(h, d);
    });
}(jQuery));

Deleting an object in java?

Yea, java is Garbage collected, it will delete the memory for you.

Laravel: Get Object From Collection By Attribute

Since I don't need to loop entire collection, I think it is better to have helper function like this

/**
 * Check if there is a item in a collection by given key and value
 * @param Illuminate\Support\Collection $collection collection in which search is to be made
 * @param string $key name of key to be checked
 * @param string $value value of key to be checkied
 * @return boolean|object false if not found, object if it is found
 */
function findInCollection(Illuminate\Support\Collection $collection, $key, $value) {
    foreach ($collection as $item) {
        if (isset($item->$key) && $item->$key == $value) {
            return $item;
        }
    }
    return FALSE;
}

There is no ViewData item of type 'IEnumerable<SelectListItem>' that has the key 'xxx'

The cause isn't contrary to syntax rather than inappropriate usage of objects. Life Cycle of objects in ViewData, ViewBag, & View Life Cycle is shorter than in the session. Data defined in the formers will be lost after a request-response(if try to access after a request-response, you will get exceptions). So the formers are appropriate for passing data between View & Controller while the latter for storing temporary data. The temporary data should store in the session so that can be accessed many times.

How to insert text in a td with id, using JavaScript

append a text node as follows

var td1 = document.getElementById('td1');
var text = document.createTextNode("some text");
td1.appendChild(text);

How to efficiently concatenate strings in go

If you know the total length of the string that you're going to preallocate then the most efficient way to concatenate strings may be using the builtin function copy. If you don't know the total length before hand, do not use copy, and read the other answers instead.

In my tests, that approach is ~3x faster than using bytes.Buffer and much much faster (~12,000x) than using the operator +. Also, it uses less memory.

I've created a test case to prove this and here are the results:

BenchmarkConcat  1000000    64497 ns/op   502018 B/op   0 allocs/op
BenchmarkBuffer  100000000  15.5  ns/op   2 B/op        0 allocs/op
BenchmarkCopy    500000000  5.39  ns/op   0 B/op        0 allocs/op

Below is code for testing:

package main

import (
    "bytes"
    "strings"
    "testing"
)

func BenchmarkConcat(b *testing.B) {
    var str string
    for n := 0; n < b.N; n++ {
        str += "x"
    }
    b.StopTimer()

    if s := strings.Repeat("x", b.N); str != s {
        b.Errorf("unexpected result; got=%s, want=%s", str, s)
    }
}

func BenchmarkBuffer(b *testing.B) {
    var buffer bytes.Buffer
    for n := 0; n < b.N; n++ {
        buffer.WriteString("x")
    }
    b.StopTimer()

    if s := strings.Repeat("x", b.N); buffer.String() != s {
        b.Errorf("unexpected result; got=%s, want=%s", buffer.String(), s)
    }
}

func BenchmarkCopy(b *testing.B) {
    bs := make([]byte, b.N)
    bl := 0

    b.ResetTimer()
    for n := 0; n < b.N; n++ {
        bl += copy(bs[bl:], "x")
    }
    b.StopTimer()

    if s := strings.Repeat("x", b.N); string(bs) != s {
        b.Errorf("unexpected result; got=%s, want=%s", string(bs), s)
    }
}

// Go 1.10
func BenchmarkStringBuilder(b *testing.B) {
    var strBuilder strings.Builder

    b.ResetTimer()
    for n := 0; n < b.N; n++ {
        strBuilder.WriteString("x")
    }
    b.StopTimer()

    if s := strings.Repeat("x", b.N); strBuilder.String() != s {
        b.Errorf("unexpected result; got=%s, want=%s", strBuilder.String(), s)
    }
}

How do I change UIView Size?

Hi create this extends if you want. Update 2021 Swift 5

Create File Extends.Swift and add this code (add import foundation where you want change height)

extension UIView {
    /**
    Get Set x Position
    
    - parameter x: CGFloat
    */
    var x:CGFloat {
        get {
            return self.frame.origin.x
        }
        set {
            self.frame.origin.x = newValue
        }
    }
    /**
    Get Set y Position
    
    - parameter y: CGFloat
    */
    var y:CGFloat {
        get {
            return self.frame.origin.y
        }
        set {
            self.frame.origin.y = newValue
        }
    }
    /**
    Get Set Height
    
    - parameter height: CGFloat
    */
    var height:CGFloat {
        get {
            return self.frame.size.height
        }
        set {
            self.frame.size.height = newValue
        }
    }
    /**
    Get Set Width
    
    - parameter width: CGFloat
    */
    var width:CGFloat {
        get {
            return self.frame.size.width
        }
        set {
            self.frame.size.width = newValue
        }
    }
}

For Use (inherits Of UIView)

inheritsOfUIView.height = 100
button.height = 100
print(view.height)

Get the closest number out of an array

Another variant here we have circular range connecting head to toe and accepts only min value to given input. This had helped me get char code values for one of the encryption algorithm.

function closestNumberInCircularRange(codes, charCode) {
  return codes.reduce((p_code, c_code)=>{
    if(((Math.abs(p_code-charCode) > Math.abs(c_code-charCode)) || p_code > charCode) && c_code < charCode){
      return c_code;
    }else if(p_code < charCode){
      return p_code;
    }else if(p_code > charCode && c_code > charCode){
      return Math.max.apply(Math, [p_code, c_code]);
    }
    return p_code;
  });
}

Does return stop a loop?

This code will exit the loop after the first iteration in a for of loop:

const objc = [{ name: 1 }, { name: 2 }, { name: 3 }];
for (const iterator of objc) {
  if (iterator.name == 2) {
    return;
  }
  console.log(iterator.name);// 1
}

the below code will jump on the condition and continue on a for of loop:

const objc = [{ name: 1 }, { name: 2 }, { name: 3 }];

for (const iterator of objc) {
  if (iterator.name == 2) {
    continue;
  }
  console.log(iterator.name); // 1  , 3
}

How to run a cronjob every X minutes?

Your CRON should look like this:

*/5 * * * *

CronWTF is really usefull when you need to test out your CRON settings.

Might be a good idea to pipe the output into a log file so you can see if your script is throwing any errors too - since you wont see them in your terminal.

Also try using a shebang at the top of your PHP file, so the system knows where to find PHP. Such as:

#!/usr/bin/php

that way you can call the whole thing like this

*/5 * * * * php /path/to/script.php > /path/to/logfile.log

VBA Print to PDF and Save with Automatic File Name

Hopefully this is self explanatory enough. Use the comments in the code to help understand what is happening. Pass a single cell to this function. The value of that cell will be the base file name. If the cell contains "AwesomeData" then we will try and create a file in the current users desktop called AwesomeData.pdf. If that already exists then try AwesomeData2.pdf and so on. In your code you could just replace the lines filename = Application..... with filename = GetFileName(Range("A1"))

Function GetFileName(rngNamedCell As Range) As String
    Dim strSaveDirectory As String: strSaveDirectory = ""
    Dim strFileName As String: strFileName = ""
    Dim strTestPath As String: strTestPath = ""
    Dim strFileBaseName As String: strFileBaseName = ""
    Dim strFilePath As String: strFilePath = ""
    Dim intFileCounterIndex As Integer: intFileCounterIndex = 1

    ' Get the users desktop directory.
    strSaveDirectory = Environ("USERPROFILE") & "\Desktop\"
    Debug.Print "Saving to: " & strSaveDirectory

    ' Base file name
    strFileBaseName = Trim(rngNamedCell.Value)
    Debug.Print "File Name will contain: " & strFileBaseName

    ' Loop until we find a free file number
    Do
        If intFileCounterIndex > 1 Then
            ' Build test path base on current counter exists.
            strTestPath = strSaveDirectory & strFileBaseName & Trim(Str(intFileCounterIndex)) & ".pdf"
        Else
            ' Build test path base just on base name to see if it exists.
            strTestPath = strSaveDirectory & strFileBaseName & ".pdf"
        End If

        If (Dir(strTestPath) = "") Then
            ' This file path does not currently exist. Use that.
            strFileName = strTestPath
        Else
            ' Increase the counter as we have not found a free file yet.
            intFileCounterIndex = intFileCounterIndex + 1
        End If

    Loop Until strFileName <> ""

    ' Found useable filename
    Debug.Print "Free file name: " & strFileName
    GetFileName = strFileName

End Function

The debug lines will help you figure out what is happening if you need to step through the code. Remove them as you see fit. I went a little crazy with the variables but it was to make this as clear as possible.

In Action

My cell O1 contained the string "FileName" without the quotes. Used this sub to call my function and it saved a file.

Sub Testing()
    Dim filename As String: filename = GetFileName(Range("o1"))

    ActiveWorkbook.Worksheets("Sheet1").Range("A1:N24").ExportAsFixedFormat Type:=xlTypePDF, _
                                              filename:=filename, _
                                              Quality:=xlQualityStandard, _
                                              IncludeDocProperties:=True, _
                                              IgnorePrintAreas:=False, _
                                              OpenAfterPublish:=False
End Sub

Where is your code located in reference to everything else? Perhaps you need to make a module if you have not already and move your existing code into there.

how can I connect to a remote mongo server from Mac OS terminal

You are probably connecting fine but don't have sufficient privileges to run show dbs.

You don't need to run the db.auth if you pass the auth in the command line:

mongo somewhere.mongolayer.com:10011/my_database -u username -p password

Once you connect are you able to see collections?

> show collections

If so all is well and you just don't have admin privileges to the database and can't run the show dbs

Is there a command line utility for rendering GitHub flavored Markdown?

Use marked. It supports GitHub Flavored Markdown, can be used as a Node.js module and from the command line.

An example would be:

$ marked -o hello.html
hello world
^D
$ cat hello.html
<p>hello world</p>

Can I set subject/content of email using mailto:?

Yes, you can like this:

mailto: [email protected]?subject=something

Which Java library provides base64 encoding/decoding?

Java 9

Use the Java 8 solution. Note DatatypeConverter can still be used, but it is now within the java.xml.bind module which will need to be included.

module org.example.foo {
    requires java.xml.bind;
}

Java 8

Java 8 now provides java.util.Base64 for encoding and decoding base64.

Encoding

byte[] message = "hello world".getBytes(StandardCharsets.UTF_8);
String encoded = Base64.getEncoder().encodeToString(message);
System.out.println(encoded);
// => aGVsbG8gd29ybGQ=

Decoding

byte[] decoded = Base64.getDecoder().decode("aGVsbG8gd29ybGQ=");
System.out.println(new String(decoded, StandardCharsets.UTF_8));
// => hello world

Java 6 and 7

Since Java 6 the lesser known class javax.xml.bind.DatatypeConverter can be used. This is part of the JRE, no extra libraries required.

Encoding

byte[] message = "hello world".getBytes("UTF-8");
String encoded = DatatypeConverter.printBase64Binary(message);
System.out.println(encoded);
// => aGVsbG8gd29ybGQ=  

Decoding

byte[] decoded = DatatypeConverter.parseBase64Binary("aGVsbG8gd29ybGQ=");
System.out.println(new String(decoded, "UTF-8"));
// => hello world