Programs & Examples On #Phplist

Phplist is the world's most popular open source email campaign manager. Featuring an easy to use web app to send emails to the recipients, and written in PHP, it is very easy to install and use.

Apache redirect to another port

You have to make sure that the proxy is enabled on the server. You can do so by using the following commands:

  a2enmod proxy
  a2enmod proxy_http

  service apache2 restart

Close Form Button Event

If am not wrong

private void Form1_FormClosing(object sender, FormClosingEventArgs e)
{
   //You may decide to prompt to user
   //else just kill
   Process.GetCurrentProcess().Kill();
} 

regex with space and letters only?

use this expression

var RegExpression = /^[a-zA-Z\s]*$/;  

for more refer this http://tools.netshiftmedia.com

Javascript - How to extract filename from a file input control

Very simple

let file = $("#fileupload")[0].files[0]; 
file.name

How to center align the ActionBar title in Android?

Here is a complete Kotlin + androidx solution, building upon the answer from @Stanislas Heili. I hope it may be useful to others. It's for the case when you have an activity that hosts multiple fragments, with only one fragment active at the same time.

In your activity:

private lateinit var customTitle: AppCompatTextView

override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    // stuff here
    customTitle = createCustomTitleTextView()
    // other stuff here
}

private fun createCustomTitleTextView(): AppCompatTextView {
    val mTitleTextView = AppCompatTextView(this)
    TextViewCompat.setTextAppearance(mTitleTextView, R.style.your_style_or_null);

    val layoutParams = ActionBar.LayoutParams(
        ActionBar.LayoutParams.WRAP_CONTENT,
        ActionBar.LayoutParams.WRAP_CONTENT
    )
    layoutParams.gravity = Gravity.CENTER
    supportActionBar?.setCustomView(mTitleTextView, layoutParams)
    supportActionBar?.displayOptions = ActionBar.DISPLAY_SHOW_CUSTOM

    return mTitleTextView
}

override fun setTitle(title: CharSequence?) {
    customTitle.text = title
}

override fun setTitle(titleId: Int) {
    customTitle.text = getString(titleId)
}

In your fragments:

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)

    activity?.title = "some title for fragment"
}

Cannot resolve symbol 'AppCompatActivity'

A little addition to other answers here, for anyone having the same error while using the right lib version and the right class.

When I upgraded to

appcompat-v7:22.1.0

In which ActionBarActivity is deprecated and empty and AppCompatActivty is the way to go, due to some glitch in Android Studio, It didn't quite pick up on version change.

i.e. Even though Gradle ran without errors, the IDE itself kept saying Cannot resolve symbol 'AppCompatActivity' (and it also wasn't available through the Ctrl+N search)

I looked into the .idea/libraries folder and noticed there's no appropriate metafile for the new version of the lib.

So, using the old-reliable File->Invalidate Caches/Restart did the trick. Always try this when you feel something is magically wrong with Android Studio. And then Disable offline mode and sync.

center a row using Bootstrap 3

Instead of

<div class="col-md-4"></div>
<div class="col-md-4"></div>
<div class="col-md-4"></div>

You could just use

<div class="col-md-4 col-md-offset-4"></div>

As long as you don't want anything in columns 1 & 3 this is a more elegant solution. The offset "adds" 4 columns in front, leaving you with 4 "spare" after.

PS I realise that the initial question specifies no offsets but at least one previous answer uses a CSS hack that is unnecessary if you use offsets. So for completeness' sake I think this is valid.

What is the best way to iterate over multiple lists at once?

The usual way is to use zip():

for x, y in zip(a, b):
    # x is from a, y is from b

This will stop when the shorter of the two iterables a and b is exhausted. Also worth noting: itertools.izip() (Python 2 only) and itertools.izip_longest() (itertools.zip_longest() in Python 3).

"The system cannot find the file specified"

The most common reason could be the database connection string. You have to change the connection string attachDBFile=|DataDirectory|file_name.mdf. there might be problem in host name which would be (local),localhost or .\sqlexpress.

milliseconds to days

In case you solve a more complex task of logging execution statistics in your code:

public void logExecutionMillis(LocalDateTime start, String callerMethodName) {

  LocalDateTime end = getNow();
  long difference = Duration.between(start, end).toMillis();

  Logger logger = LoggerFactory.getLogger(ProfilerInterceptor.class);

  long millisInDay = 1000 * 60 * 60 * 24;
  long millisInHour = 1000 * 60 * 60;
  long millisInMinute = 1000 * 60;
  long millisInSecond = 1000;

  long days = difference / millisInDay;
  long daysDivisionResidueMillis = difference - days * millisInDay;

  long hours = daysDivisionResidueMillis / millisInHour;
  long hoursDivisionResidueMillis = daysDivisionResidueMillis - hours * millisInHour;

  long minutes = hoursDivisionResidueMillis / millisInMinute;
  long minutesDivisionResidueMillis = hoursDivisionResidueMillis - minutes * millisInMinute;

  long seconds = minutesDivisionResidueMillis / millisInSecond;
  long secondsDivisionResidueMillis = minutesDivisionResidueMillis - seconds * millisInSecond;

  logger.info(
      "\n************************************************************************\n"
          + callerMethodName
          + "() - "
          + difference
          + " millis ("
          + days
          + " d. "
          + hours
          + " h. "
          + minutes
          + " min. "
          + seconds
          + " sec."
          + secondsDivisionResidueMillis
          + " millis).");
}

P.S. Logger can be replaced with simple System.out.println() if you like.

What is the purpose of Looper and how to use it?

Simplest Definition of Looper & Handler:

Looper is a class that turns a thread into a Pipeline Thread and Handler gives you a mechanism to push tasks into it from any other threads.

Details in general wording:

So a PipeLine Thread is a thread which can accept more tasks from other threads through a Handler.

The Looper is named so because it implements the loop – takes the next task, executes it, then takes the next one and so on. The Handler is called a handler because it is used to handle or accept that next task each time from any other thread and pass to Looper (Thread or PipeLine Thread).

Example:

A Looper and Handler or PipeLine Thread's very perfect example is to download more than one images or upload them to a server (Http) one by one in a single thread instead of starting a new Thread for each network call in the background.

Read more here about Looper and Handler and the definition of Pipeline Thread:

Android Guts: Intro to Loopers and Handlers

How to recursively download a folder via FTP on Linux

You could rely on wget which usually handles ftp get properly (at least in my own experience). For example:

wget -r ftp://user:[email protected]/

You can also use -m which is suitable for mirroring. It is currently equivalent to -r -N -l inf.

If you've some special characters in the credential details, you can specify the --user and --password arguments to get it to work. Example with custom login with specific characters:

wget -r --user="user@login" --password="Pa$$wo|^D" ftp://server.com/

As pointed out by @asmaier, watch out that even if -r is for recursion, it has a default max level of 5:

-r
--recursive
    Turn on recursive retrieving.

-l depth
--level=depth
    Specify recursion maximum depth level depth.  The default maximum depth is 5.

If you don't want to miss out subdirs, better use the mirroring option, -m:

-m
--mirror
    Turn on options suitable for mirroring.  This option turns on recursion and time-stamping, sets infinite
    recursion depth and keeps FTP directory listings.  It is currently equivalent to -r -N -l inf
    --no-remove-listing.

Use LIKE %..% with field values in MySQL

Use:

SELECT t1.Notes, 
       t2.Name
  FROM Table1 t1
  JOIN Table2 t2 ON t1.Notes LIKE CONCAT('%', t2.Name ,'%')

What is the SSIS package and what does it do?

For Latest Info About SSIS > https://docs.microsoft.com/en-us/sql/integration-services/sql-server-integration-services

From the above referenced site:

Microsoft Integration Services is a platform for building enterprise-level data integration and data transformations solutions. Use Integration Services to solve complex business problems by copying or downloading files, loading data warehouses, cleansing and mining data, and managing SQL Server objects and data.

Integration Services can extract and transform data from a wide variety of sources such as XML data files, flat files, and relational data sources, and then load the data into one or more destinations.

Integration Services includes a rich set of built-in tasks and transformations, graphical tools for building packages, and the Integration Services Catalog database, where you store, run, and manage packages.

You can use the graphical Integration Services tools to create solutions without writing a single line of code. You can also program the extensive Integration Services object model to create packages programmatically and code custom tasks and other package objects.

Getting Started with SSIS - http://msdn.microsoft.com/en-us/sqlserver/bb671393.aspx

If you are Integration Services Information Worker - http://msdn.microsoft.com/en-us/library/ms141667.aspx

If you are Integration Services Administrator - http://msdn.microsoft.com/en-us/library/ms137815.aspx

If you are Integration Services Developer - http://msdn.microsoft.com/en-us/library/ms137709.aspx

If you are Integration Services Architect - http://msdn.microsoft.com/en-us/library/ms142161.aspx

Overview of SSIS - http://msdn.microsoft.com/en-us/library/ms141263.aspx

Integration Services How-to Topics - http://msdn.microsoft.com/en-us/library/ms141767.aspx

Convert JSON array to an HTML table in jQuery

For very advanced JSON objects to HTML tables you can try My jQuery Solution that is based on this closed thread.

var myList=[{"name": "abc","age": 50},{"name": {"1": "piet","2": "jan","3": "klaas"},"age": "25","hobby": "watching tv"},{"name": "xyz","hobby": "programming","subtable": [{"a": "a","b": "b"},{"a": "a","b": "b"}]}];

// Builds the HTML Table out of myList json data from Ivy restful service.
 function buildHtmlTable() {
      addTable(myList, $("#excelDataTable"));
 }

function addTable(list, appendObj) {
    var columns = addAllColumnHeaders(list, appendObj);

    for (var i = 0; i < list.length; i++) {
        var row$ = $('<tr/>');
        for (var colIndex = 0; colIndex < columns.length; colIndex++) {
            var cellValue = list[i][columns[colIndex]];

            if (cellValue == null) {
                cellValue = "";
            }

            if (cellValue.constructor === Array)
            {
                $a = $('<td/>');
                row$.append($a);
                addTable(cellValue, $a);

            } else if (cellValue.constructor === Object)
            {

                var array = $.map(cellValue, function (value, index) {
                    return [value];
                });

                $a = $('<td/>');
                row$.append($a);
                addObject(array, $a);

            } else {
                row$.append($('<td/>').html(cellValue));
            }
        }
        appendObj.append(row$);
    }
}


function addObject(list, appendObj) {
    for (var i = 0; i < list.length; i++) {
        var row$ = $('<tr/>');

        var cellValue = list[i];

        if (cellValue == null) {
            cellValue = "";
        }

        if (cellValue.constructor === Array)
        {
            $a = $('<td/>');
            row$.append($a);
            addTable(cellValue, $a);

        } else if (cellValue.constructor === Object)
        {

            var array = $.map(cellValue, function (value, index) {
                return [value];
            });

            $a = $('<td/>');
            row$.append($a);
            addObject(array, $a);

        } else {
            row$.append($('<td/>').html(cellValue));
        }
        appendObj.append(row$);
    }
}

// Adds a header row to the table and returns the set of columns.
// Need to do union of keys from all records as some records may not contain
// all records
function addAllColumnHeaders(list, appendObj)
{
    var columnSet = [];
    var headerTr$ = $('<tr/>');

    for (var i = 0; i < list.length; i++) {
        var rowHash = list[i];
        for (var key in rowHash) {
            if ($.inArray(key, columnSet) == -1) {
                columnSet.push(key);
                headerTr$.append($('<th/>').html(key));
            }
        }
    }
    appendObj.append(headerTr$);

    return columnSet;
}

What's the difference between "Layers" and "Tiers"?

Why always trying to use complex words?

A layer = a part of your code, if your application is a cake, this is a slice.

A tier = a physical machine, a server.

A tier hosts one or more layers.


Example of layers:

  • Presentation layer = usually all the code related to the User Interface
  • Data Access layer = all the code related to your database access

Tier:

Your code is hosted on a server = Your code is hosted on a tier.

Your code is hosted on 2 servers = Your code is hosted on 2 tiers.

For example, one machine hosting the Web Site itself (the Presentation layer), another machine more secured hosting all the more security sensitive code (real business code - business layer, database access layer, etc.).


There are so many benefits to implement a layered architecture. This is tricky and properly implementing a layered application takes time. If you have some, have a look at this post from Microsoft: http://msdn.microsoft.com/en-gb/library/ee658109.aspx

Undefined variable: $_SESSION

Another possibility for this warning (and, most likely, problems with app behavior) is that the original author of the app relied on session.auto_start being on (defaults to off)

If you don't want to mess with the code and just need it to work, you can always change php configuration and restart php-fpm (if this is a web app):

/etc/php.d/my-new-file.ini :

session.auto_start = 1

(This is correct for CentOS 8, adjust for your OS/packaging)

What does -Xmn jvm option stands for

From GC Performance Tuning training documents of Oracle:

-Xmn[size]: Size of young generation heap space.

Applications with emphasis on performance tend to use -Xmn to size the young generation, because it combines the use of -XX:MaxNewSize and -XX:NewSize and almost always explicitly sets -XX:PermSize and -XX:MaxPermSize to the same value.

In short, it sets the NewSize and MaxNewSize values of New generation to the same value.

Git merge develop into feature branch outputs "Already up-to-date" while it's not

You should first pull the changes from the develop branch and only then merge them to your branch:

git checkout develop 
git pull 
git checkout branch-x
git rebase develop

Or, when on branch-x:

git fetch && git rebase origin/develop

I have an alias that saves me a lot of time. Add to your ~/.gitconfig:

[alias]
    fr = "!f() { git fetch && git rebase origin/"$1"; }; f"

Now, all that you have to do is:

git fr develop

CodeIgniter removing index.php from url

Try the following

Open config.php and do following replaces

$config['index_page'] = "index.php"

to

$config['index_page'] = ""

In some cases the default setting for uri_protocol does not work properly. Just replace

$config['uri_protocol'] ="AUTO"

by

$config['uri_protocol'] = "REQUEST_URI"

.htaccess

RewriteEngine on
RewriteCond $1 !^(index\.php|resources|robots\.txt)
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ index.php/$1 [L,QSA] 

Note: .htaccess code vary depending on hosting server. In some hosting server (e.g.: Godaddy) need to use an extra ? in the last line of above code. The following line will be replaced with last line in applicable case:

// Replace last .htaccess line with this line
RewriteRule ^(.*)$ index.php?/$1 [L,QSA] 

How to filter Android logcat by application?

Generally, I do this command "adb shell ps" in prompt (allows to see processes running) and it's possible to discover aplication's pid. With this pid in hands, go to Eclipse and write pid:XXXX (XXXX is the application pid) then logs output is filtered by this application.

Or, in a easier way... in logcat view on Eclipse, search for any word related with your desired application, discover the pid, and then do a filter by pid "pid:XXXX".

How to put Google Maps V2 on a Fragment using ViewPager

For the issue of getting a NullPointerException when we change the Tabs in a FragmentTabHost you just need to add this code to your class which has the TabHost. I mean the class where you initialize the tabs. This is the code :

/**** Fix for error : Activity has been destroyed, when using Nested tabs 
 * We are actually detaching this tab fragment from the `ChildFragmentManager`
 * so that when this inner tab is viewed back then the fragment is attached again****/

import java.lang.reflect.Field;

@Override
public void onDetach() {
    super.onDetach();
    try {
        Field childFragmentManager = Fragment.class.getDeclaredField("mChildFragmentManager");
        childFragmentManager.setAccessible(true);
        childFragmentManager.set(this, null);
    } catch (NoSuchFieldException e) {
        throw new RuntimeException(e);
    } catch (IllegalAccessException e) {
        throw new RuntimeException(e);
    }
}

Converting a view to Bitmap without displaying it in Android?

I used this just a few days ago:

fun generateBitmapFromView(view: View): Bitmap {
    val specWidth = View.MeasureSpec.makeMeasureSpec(1324, View.MeasureSpec.AT_MOST)
    val specHeight = View.MeasureSpec.makeMeasureSpec(521, View.MeasureSpec.AT_MOST)
    view.measure(specWidth, specHeight)
    val width = view.measuredWidth
    val height = view.measuredHeight
    val bitmap = Bitmap.createBitmap(width, height, Bitmap.Config.ARGB_8888)
    val canvas = Canvas(bitmap)
    view.layout(view.left, view.top, view.right, view.bottom)
    view.draw(canvas)
    return bitmap
}

This code is based in this gist

Implicit type conversion rules in C++ operators

Whole chapter 4 talks about conversions, but I think you should be mostly interested in these :

4.5 Integral promotions [conv.prom]
An rvalue of type char, signed char, unsigned char, short int, or unsigned short int can be converted to an rvalue of type int if int can represent all the values of the source type; other-
wise, the source rvalue can be converted to an rvalue of type unsigned int.
An rvalue of type wchar_t (3.9.1) or an enumeration type (7.2) can be converted to an rvalue of the first
of the following types that can represent all the values of its underlying type: int, unsigned int,
long, or unsigned long.
An rvalue for an integral bit-field (9.6) can be converted to an rvalue of type int if int can represent all
the values of the bit-field; otherwise, it can be converted to unsigned int if unsigned int can rep-
resent all the values of the bit-field. If the bit-field is larger yet, no integral promotion applies to it. If the
bit-field has an enumerated type, it is treated as any other value of that type for promotion purposes.
An rvalue of type bool can be converted to an rvalue of type int, with false becoming zero and true
becoming one.
These conversions are called integral promotions.

4.6 Floating point promotion [conv.fpprom]
An rvalue of type float can be converted to an rvalue of type double. The value is unchanged.
This conversion is called floating point promotion.

Therefore, all conversions involving float - the result is float.

Only the one involving both int - the result is int : int / int = int

Git submodule update

To address the --rebase vs. --merge option:

Let's say you have super repository A and submodule B and want to do some work in submodule B. You've done your homework and know that after calling

git submodule update

you are in a HEAD-less state, so any commits you do at this point are hard to get back to. So, you've started work on a new branch in submodule B

cd B
git checkout -b bestIdeaForBEver
<do work>

Meanwhile, someone else in project A has decided that the latest and greatest version of B is really what A deserves. You, out of habit, merge the most recent changes down and update your submodules.

<in A>
git merge develop
git submodule update

Oh noes! You're back in a headless state again, probably because B is now pointing to the SHA associated with B's new tip, or some other commit. If only you had:

git merge develop
git submodule update --rebase

Fast-forwarded bestIdeaForBEver to b798edfdsf1191f8b140ea325685c4da19a9d437.
Submodule path 'B': rebased into 'b798ecsdf71191f8b140ea325685c4da19a9d437'

Now that best idea ever for B has been rebased onto the new commit, and more importantly, you are still on your development branch for B, not in a headless state!

(The --merge will merge changes from beforeUpdateSHA to afterUpdateSHA into your working branch, as opposed to rebasing your changes onto afterUpdateSHA.)

Split string into list in jinja?

If there are up to 10 strings then you should use a list in order to iterate through all values.

{% set list1 = variable1.split(';') %}
{% for list in list1 %}
<p>{{ list }}</p>
{% endfor %}

How to delete columns that contain ONLY NAs?

One way of doing it:

df[, colSums(is.na(df)) != nrow(df)]

If the count of NAs in a column is equal to the number of rows, it must be entirely NA.

Or similarly

df[colSums(!is.na(df)) > 0]

Css pseudo classes input:not(disabled)not:[type="submit"]:focus

You have a few typos in your select. It should be: input:not([disabled]):not([type="submit"]):focus

See this jsFiddle for a proof of concept. On a sidenote, if I removed the "background-color" property, then the box shadow no longer works. Not sure why.

Typescript export vs. default export

I was trying to solve the same problem, but found an interesting advice by Basarat Ali Syed, of TypeScript Deep Dive fame, that we should avoid the generic export default declaration for a class, and instead append the export tag to the class declaration. The imported class should be instead listed in the import command of the module.

That is: instead of

class Foo {
    // ...
}
export default Foo;

and the simple import Foo from './foo'; in the module that will import, one should use

export class Foo {
    // ...
}

and import {Foo} from './foo' in the importer.

The reason for that is difficulties in the refactoring of classes, and the added work for exportation. The original post by Basarat is in export default can lead to problems

How do I import global modules in Node? I get "Error: Cannot find module <module>"?

If you're using npm >=1.0, you can use npm link <global-package> to create a local link to a package already installed globally. (Caveat: The OS must support symlinks.)

However, this doesn't come without its problems.

npm link is a development tool. It's awesome for managing packages on your local development box. But deploying with npm link is basically asking for problems, since it makes it super easy to update things without realizing it.

As an alternative, you can install the packages locally as well as globally.

For additional information, see

How do you pull first 100 characters of a string in PHP

$small = substr($big, 0, 100);

For String Manipulation here is a page with a lot of function that might help you in your future work.

Formatting floats in a numpy array

[ round(x,2) for x in [2.15295647e+01, 8.12531501e+00, 3.97113829e+00, 1.00777250e+01]]

Using NOT operator in IF conditions

try like this

if (!(a | b)) {
    //blahblah
}

It's same with

if (a | b) {}
else {
    // blahblah
}

Input size vs width

You'll get more consistency if you use width (your second example).

TypeError: tuple indices must be integers, not str

I think you should do

for index, row in result: 

If you wanna access by name.

How to return a string value from a Bash function

You could use a global variable:

declare globalvar='some string'

string ()
{
  eval  "$1='some other string'"
} # ----------  end of function string  ----------

string globalvar

echo "'${globalvar}'"

This gives

'some other string'

Linux command to translate DomainName to IP

Use this

$ dig +short stackoverflow.com

69.59.196.211

or this

$ host stackoverflow.com

stackoverflow.com has address 69.59.196.211
stackoverflow.com mail is handled by 30 alt2.aspmx.l.google.com.
stackoverflow.com mail is handled by 40 aspmx2.googlemail.com.
stackoverflow.com mail is handled by 50 aspmx3.googlemail.com.
stackoverflow.com mail is handled by 10 aspmx.l.google.com.
stackoverflow.com mail is handled by 20 alt1.aspmx.l.google.com.

How to see the proxy settings on windows?

You can figure out which proxy server you're using by accessing some websites with a browser and then running the DOS command:

netstat

and you'll see some connections in the Foreign Address column on port 80 or 8080 (common proxy server ports). Ideally you will be able to identify the proxy server by its naming convention.

[see also https://stackoverflow.com/a/8161865/3195477]

css3 text-shadow in IE9

Try CSS Generator.

You can choose values and see the results online. Then you get the code in the clipboard.
This is one example of generated code:

text-shadow: 1px 1px 2px #a8aaad;
filter: dropshadow(color=#a8aaad, offx=1, offy=1);

How to specify a local file within html using the file: scheme?

The 'file' protocol is not a network protocol. Therefore file://192.168.1.57/~User/2ndFile.html simply does not make much sense.

Question is how you load the first file. Is that really done using a web server? Does not really sound like. If it is, then why not use the same protocol, most likely http? You cannot expect to simply switch the protocol and use two different protocols the same way...

I suspect the first file is really loaded using the apache server at all, but simply by opening the file? href="2ndFile.html" simply works because it uses a "relative url". This makes the browser use the same protocol and path as where he got the first (current) file from.

The program can't start because cygwin1.dll is missing... in Eclipse CDT

You can compile with either Cygwin's g++ or MinGW (via stand-alone or using Cygwin package). However, in order to run it, you need to add the Cygwin1.dll (and others) PATH to the system Windows PATH, before any cygwin style paths.

Thus add: ;C:\cygwin64\bin to the end of your Windows system PATH variable.

Also, to compile for use in CMD or PowerShell, you may need to use:

x86_64-w64-mingw32-g++.exe -static -std=c++11 prog_name.cc -o prog_name.exe

(This invokes the cross-compiler, if installed.)

Moving up one directory in Python

>>> import os
>>> print os.path.abspath(os.curdir)
C:\Python27
>>> os.chdir("..")
>>> print os.path.abspath(os.curdir)
C:\

Generating matplotlib graphs without a running X server

You need to use the matplotlib API directly rather than going through the pylab interface. There's a good example here:

http://www.dalkescientific.com/writings/diary/archive/2005/04/23/matplotlib_without_gui.html

How to get the Enum Index value in C#

One reason that the designers c# might have chosen to NOT have enums auto convert was to prevent accidentally mixing different enum types...

e.g. this is bad code followed by a good version
enum ParkingLevel { GroundLevel, FirstFloor};
enum ParkingFacing { North, East, South, West }
void Test()
{
    var parking = ParkingFacing.North; // NOT A LEVEL
    // WHOOPS at least warning in editor/compile on calls
    WhichLevel(parking); 

    // BAD  wrong type of index, no warning
    var info = ParkinglevelArray[ (int)parking ];
}


// however you can write this, looks complicated 
// but avoids using casts every time AND stops miss-use
void Test()
{
  ParkingLevelManager levels = new ParkingLevelManager();
  // assign info to each level
  var parking = ParkingFacing.North;

  // Next line wrong mixing type 
  // but great you get warning in editor or at compile time      
  var info=levels[parking];

  // and.... no cast needed for correct use
  var pl = ParkingLevel.GroundLevel;
  var infoCorrect=levels[pl];

}
class ParkingLevelInfo { /*...*/ }
class ParkingLevelManager
{
    List<ParkingLevelInfo> m_list;
    public ParkingLevelInfo this[ParkingLevel x] 
 { get{ return m_list[(int)x]; } }}

How to access cookies in AngularJS?

The original accepted answer mentions jquery.cookie plugin. A few months ago though, it was renamed to js-cookie and the jQuery dependency removed. One of the reasons was just to make it easy to integrate with other frameworks, like Angular.

Now, if you want to integrate js-cookie with angular, it is as easy as something like:

module.factory( "cookies", function() {
  return Cookies.noConflict();
});

And that's it. No jQuery. No ngCookies.


You can also create custom instances to handle specific server-side cookies that are written differently. Take for example PHP, that convert the spaces in the server-side to a plus sign + instead of also percent-encode it:

module.factory( "phpCookies", function() {
  return Cookies
    .noConflict()
    .withConverter(function( value, name ) {
      return value
            // Decode all characters according to the "encodeURIComponent" spec
            .replace(/(%[0-9A-Z]{2})+/g, decodeURIComponent)
            // Decode the plus sign to spaces
            .replace(/\+/g, ' ')
    });
});

The usage for a custom Provider would be something like this:

module.service( "customDataStore", [ "phpCookies", function( phpCookies ) {
  this.storeData = function( data ) {
    phpCookies.set( "data", data );
  };
  this.containsStoredData = function() {
    return phpCookies.get( "data" );
  }
}]);

I hope this helps anyone.

See detailed info in this issue: https://github.com/js-cookie/js-cookie/issues/103

For detailed docs on how to integrate with server-side, see here: https://github.com/js-cookie/js-cookie/blob/master/SERVER_SIDE.md

Is there any way to delete local commits in Mercurial?

[Hg Tortoise 4.6.1] If it's recent action, you can use "Rollback/Undo" action (Ctrl+U).

HG Tortoise Image

What is the syntax to insert one list into another list in python?

If we just do x.append(y), y gets referenced into x such that any changes made to y will affect appended x as well. So if we need to insert only elements, we should do following:

x = [1,2,3] y = [4,5,6] x.append(y[:])

Using Mockito, how do I verify a method was a called with a certain argument?

This is the better solution:

verify(mock_contractsDao, times(1)).save(Mockito.eq("Parameter I'm expecting"));

Present and dismiss modal view controller

presentModalViewController:

MainViewController *mainViewController=[[MainViewController alloc]init];
[self.navigationController presentModalViewController:mainViewController animated:YES];

dismissModalViewController:

[self dismissModalViewControllerAnimated:YES];

Dynamically add event listener

I will add a StackBlitz example and a comment to the answer from @tahiche.

The return value is a function to remove the event listener after you have added it. It is considered good practice to remove event listeners when you don't need them anymore. So you can store this return value and call it inside your ngOnDestroy method.

I admit that it might seem confusing at first, but it is actually a very useful feature. How else can you clean up after yourself?

export class MyComponent implements OnInit, OnDestroy {

  public removeEventListener: () => void;

  constructor(
    private renderer: Renderer2, 
    private elementRef: ElementRef
  ) {
  }

  public ngOnInit() {
    this.removeEventListener = this.renderer.listen(this.elementRef.nativeElement, 'click', (event) => {
      if (event.target instanceof HTMLAnchorElement) {
        // Prevent opening anchors the default way
        event.preventDefault();
        // Your custom anchor click event handler
        this.handleAnchorClick(event);
      }
    });
  }

  public ngOnDestroy() {
    this.removeEventListener();
  }
}

You can find a StackBlitz here to show how this could work for catching clicking on anchor elements.

I added a body with an image as follows:
<img src="x" onerror="alert(1)"></div>
to show that the sanitizer is doing its job.

Here in this fiddle you find the same body attached to an innerHTML without sanitizing it and it will demonstrate the issue.

Hide html horizontal but not vertical scrollbar

Use CSS. It's easier and faster than javascript.

overflow-x: hidden;
overflow-y: scroll;

Daylight saving time and time zone best practices

PHP's DateTimeZone::listAbbreviations() output

This PHP method returns an associative array containing some 'major' timezones (like CEST), which on their own contain more specific 'geographic' timezones (like Europe/Amsterdam).

If you're using these timezones and their offset/DST information, it's extremely important to realize the following:

It seems like all different offset/DST configurations (including historical configurations) of each timezone are included!

For example, Europe/Amsterdam can be found six times in the output of this function. Two occurrences (offset 1172/4772) are for the Amsterdam time used until 1937; two (1200/4800) are for the time that was used between 1937 and 1940; and two (3600/4800) are for the time used since 1940.

Therefore, you cannot rely on the offset/DST information returned by this function as being currently correct/in use!

If you want to know the current offset/DST of a certain timezone, you'll have to do something like this:

<?php
$now = new DateTime(null, new DateTimeZone('Europe/Amsterdam'));
echo $now->getOffset();
?>

Running Git through Cygwin from Windows

call your (windows-)git with cygpath as parameter, in order to convert the "calling path". I m confused why that should be a problem.

Raise an error manually in T-SQL to jump to BEGIN CATCH block

You could use THROW (available in SQL Server 2012+):

THROW 50000, 'Your custom error message', 1
THROW <error_number>, <message>, <state>

MSDN THROW (Transact-SQL)

Differences Between RAISERROR and THROW in Sql Server

How to create a link for all mobile devices that opens google maps with a route starting at the current location, destinating a given place?

The URL syntax is the same regardless of the platform in use

String url = "https://www.google.com/maps/search/?api=1&query=" + latitude + ","+ 
longitude;

In Android or iOS the URL launches Google Maps in the Maps app, If the Google Maps app is not installed, the URL launches Google Maps in a browser and performs the requested action.

On any other device, the URL launches Google Maps in a browser and performs the requested action.

here's the link for official documentation https://developers.google.com/maps/documentation/urls/guide

Solutions for INSERT OR UPDATE on SQL Server

IF EXISTS (SELECT * FROM [Table] WHERE ID = rowID)
UPDATE [Table] SET propertyOne = propOne, property2 . . .
ELSE
INSERT INTO [Table] (propOne, propTwo . . .)

Edit:

Alas, even to my own detriment, I must admit the solutions that do this without a select seem to be better since they accomplish the task with one less step.

What does $@ mean in a shell script?

The usage of a pure $@ means in most cases "hurt the programmer as hard as you can", because in most cases it leads to problems with word separation and with spaces and other characters in arguments.

In (guessed) 99% of all cases, it is required to enclose it in ": "$@" is what can be used to reliably iterate over the arguments.

for a in "$@"; do something_with "$a"; done

Select unique or distinct values from a list in UNIX shell script

You might want to look at the uniq and sort applications.

./yourscript.ksh | sort | uniq

(FYI, yes, the sort is necessary in this command line, uniq only strips duplicate lines that are immediately after each other)

EDIT:

Contrary to what has been posted by Aaron Digulla in relation to uniq's commandline options:

Given the following input:

class
jar
jar
jar
bin
bin
java

uniq will output all lines exactly once:

class
jar
bin
java

uniq -d will output all lines that appear more than once, and it will print them once:

jar
bin

uniq -u will output all lines that appear exactly once, and it will print them once:

class
java

Add / Change parameter of URL and redirect to the new URL

Here's a way of accomplishing this. It takes the param name and param value, and an optional 'clear'. If you supply clear=true, it will remove all other params and just leave the newly added one - in other cases, it will either replace the original with the new, or add it if it's not present in the querystring.

This is modified from the original top answer as that one broke if it replaced anything but the last value. This will work for any value, and preserve the existing order.

function setGetParameter(paramName, paramValue, clear)
{
clear = typeof clear !== 'undefined' ? clear : false;
var url = window.location.href;
var queryString = location.search.substring(1); 
var newQueryString = "";
if (clear)
{
    newQueryString = paramName + "=" + paramValue;
}
else if (url.indexOf(paramName + "=") >= 0)
{
    var decode = function (s) { return decodeURIComponent(s.replace(/\+/g, " ")); };
    var keyValues = queryString.split('&'); 
    for(var i in keyValues) { 
        var key = keyValues[i].split('=');
        if (key.length > 1) {
            if(newQueryString.length > 0) {newQueryString += "&";}
            if(decode(key[0]) == paramName)
            {
                newQueryString += key[0] + "=" + encodeURIComponent(paramValue);;
            }
            else
            {
                newQueryString += key[0] + "=" + key[1];
            }
        }
    } 
}
else
{
    if (url.indexOf("?") < 0)
        newQueryString = "?" + paramName + "=" + paramValue;
    else
        newQueryString = queryString + "&" + paramName + "=" + paramValue;
}
window.location.href = window.location.href.split('?')[0] + "?" + newQueryString;
}

Bootstrap table without stripe / borders

The border styling is set on the td elements.

html:

<table class='table borderless'>

css:

.borderless td, .borderless th {
    border: none;
}

Update: Since Bootstrap 4.1 you can use .table-borderless to remove the border.

https://getbootstrap.com/docs/4.1/content/tables/#borderless-table

Escape string for use in Javascript regex

Short 'n Sweet

function escapeRegExp(string) {
  return string.replace(/[.*+?^${}()|[\]\\]/g, '\\$&'); // $& means the whole matched string
}

Example

escapeRegExp("All of these should be escaped: \ ^ $ * + ? . ( ) | { } [ ]");

>>> "All of these should be escaped: \\ \^ \$ \* \+ \? \. \( \) \| \{ \} \[ \] "

(NOTE: the above is not the original answer; it was edited to show the one from MDN. This means it does not match what you will find in the code in the below npm, and does not match what is shown in the below long answer. The comments are also now confusing. My recommendation: use the above, or get it from MDN, and ignore the rest of this answer. -Darren,Nov 2019)

Install

Available on npm as escape-string-regexp

npm install --save escape-string-regexp

Note

See MDN: Javascript Guide: Regular Expressions

Other symbols (~`!@# ...) MAY be escaped without consequence, but are not required to be.

.

.

.

.

Test Case: A typical url

escapeRegExp("/path/to/resource.html?search=query");

>>> "\/path\/to\/resource\.html\?search=query"

The Long Answer

If you're going to use the function above at least link to this stack overflow post in your code's documentation so that it doesn't look like crazy hard-to-test voodoo.

var escapeRegExp;

(function () {
  // Referring to the table here:
  // https://developer.mozilla.org/en/JavaScript/Reference/Global_Objects/regexp
  // these characters should be escaped
  // \ ^ $ * + ? . ( ) | { } [ ]
  // These characters only have special meaning inside of brackets
  // they do not need to be escaped, but they MAY be escaped
  // without any adverse effects (to the best of my knowledge and casual testing)
  // : ! , = 
  // my test "~!@#$%^&*(){}[]`/=?+\|-_;:'\",<.>".match(/[\#]/g)

  var specials = [
        // order matters for these
          "-"
        , "["
        , "]"
        // order doesn't matter for any of these
        , "/"
        , "{"
        , "}"
        , "("
        , ")"
        , "*"
        , "+"
        , "?"
        , "."
        , "\\"
        , "^"
        , "$"
        , "|"
      ]

      // I choose to escape every character with '\'
      // even though only some strictly require it when inside of []
    , regex = RegExp('[' + specials.join('\\') + ']', 'g')
    ;

  escapeRegExp = function (str) {
    return str.replace(regex, "\\$&");
  };

  // test escapeRegExp("/path/to/res?search=this.that")
}());

Copy/Paste/Calculate Visible Cells from One Column of a Filtered Table

Just to add to Jon's coding if you needed to take it a step further, and do more than just one column you can add something like

Dim copyRange2 As Range
Dim copyRange3 As Range

Set copyRange2 =src.Range("B2:B" & lastRow)
Set copyRange3 =src.Range("C2:C" & lastRow)

copyRange2.SpecialCells(xlCellTypeVisible).Copy tgt.Range("B12")
copyRange3.SpecialCells(xlCellTypeVisible).Copy tgt.Range("C12")

put these near the other codings that are the same you can easily change the Ranges as you need.

I only add this because it was helpful for me. I'd assume Jon already knows this but for those that are less experienced sometimes it's helpful to see how to change/add/modify these codings. I figured since Ruya didn't know how to manipulate the original coding it could be helpful if one ever needed to copy over only 2 visibile columns, or only 3, etc. You can use this same coding, add in extra lines that are almost the same and then the coding is copying over whatever you need.

I don't have enough reputation to reply to Jon's comment directly so I have to post as a new comment, sorry.

How to git-svn clone the last n revisions from a Subversion repository?

You've already discovered the simplest way to specify a shallow clone in Git-SVN, by specifying the SVN revision number that you want to start your clone at ( -r$REV:HEAD).

For example: git svn clone -s -r1450:HEAD some/svn/repo

Git's data structure is based on pointers in a directed acyclic graph (DAG), which makes it trivial to walk back n commits. But in SVN ( and therefore in Git-SVN) you will have to find the revision number yourself.

Flatten nested dictionaries, compressing keys

The answers above work really well. Just thought I'd add the unflatten function that I wrote:

def unflatten(d):
    ud = {}
    for k, v in d.items():
        context = ud
        for sub_key in k.split('_')[:-1]:
            if sub_key not in context:
                context[sub_key] = {}
            context = context[sub_key]
        context[k.split('_')[-1]] = v
    return ud

Note: This doesn't account for '_' already present in keys, much like the flatten counterparts.

How do I create sql query for searching partial matches?

First of all, this approach won't scale in the large, you'll need a separate index from words to item (like an inverted index).

If your data is not large, you can do

SELECT DISTINCT(name) FROM mytable WHERE name LIKE '%mall%' OR description LIKE '%mall%'

using OR if you have multiple keywords.

Jackson and generic type reference

This is a well-known problem with Java type erasure: T is just a type variable, and you must indicate actual class, usually as Class argument. Without such information, best that can be done is to use bounds; and plain T is roughly same as 'T extends Object'. And Jackson will then bind JSON Objects as Maps.

In this case, tester method needs to have access to Class, and you can construct

JavaType type = mapper.getTypeFactory().
  constructCollectionType(List.class, Foo.class)

and then

List<Foo> list = mapper.readValue(new File("input.json"), type);

Calculate logarithm in python

If you use log without base it uses e.

From the comment

Return the logarithm of x to the given base.
If the base not specified, returns the natural logarithm (base e) of x.

Therefor you have to use:

import math
print( math.log(1.5, 10))

Android: keep Service running when app is killed

In your service, add the following code.

@Override
public void onTaskRemoved(Intent rootIntent){
    Intent restartServiceIntent = new Intent(getApplicationContext(), this.getClass());
    restartServiceIntent.setPackage(getPackageName());

    PendingIntent restartServicePendingIntent = PendingIntent.getService(getApplicationContext(), 1, restartServiceIntent, PendingIntent.FLAG_ONE_SHOT);
    AlarmManager alarmService = (AlarmManager) getApplicationContext().getSystemService(Context.ALARM_SERVICE);
    alarmService.set(
    AlarmManager.ELAPSED_REALTIME,
    SystemClock.elapsedRealtime() + 1000,
    restartServicePendingIntent);

    super.onTaskRemoved(rootIntent);
 }

Where does Vagrant download its .box files to?

As mentioned in the docs, boxes are stored at:

  • Mac OS X and Linux: ~/.vagrant.d/boxes
  • Windows: C:/Users/USERNAME/.vagrant.d/boxes

Replace an element into a specific position of a vector

See an example here: http://www.cplusplus.com/reference/stl/vector/insert/ eg.:



...
vector::iterator iterator1;

  iterator1= vec1.begin();
  vec1.insert ( iterator1+i , vec2[i] );

// This means that at position "i" from the beginning it will insert the value from vec2 from position i

Your first approach was replacing the values from vec1[i] with the values from vec2[i]

Still getting warning : Configuration 'compile' is obsolete and has been replaced with 'implementation'

Hope that you're affected with build.gradle(app) If do so , follow this step

Replace compile with androidTestImplementation in build.gradle

androidTestImplementation 'com.android.support:appcompat-v7:27.1.1'
androidTestImplementation 'com.android.support:design:27.1.1'

so simple ! hope this will solve

MVC 4 Razor adding input type date

If you want to use @Html.EditorFor() you have to use jQuery ui and update your Asp.net Mvc to 5.2.6.0 with NuGet Package Manager.

@Html.EditorFor(m => m.EntryDate, new { htmlAttributes = new { @class = "datepicker" } })

@section Scripts {

@Scripts.Render("~/bundles/jqueryval")

<script>

    $(document).ready(function(){

      $('.datepicker').datepicker();

     });

</script>

}

How to determine if a type implements an interface with C# reflection

You have a few choices:

  1. typeof(IMyInterface).IsAssignableFrom(typeof(MyType))

  2. typeof(MyType).GetInterfaces().Contains(typeof(IMyInterface))

For a generic interface, it’s a bit different.

typeof(MyType).GetInterfaces().Any(i => i.IsGenericType && i.GetGenericTypeDefinition() == typeof(IMyInterface<>))

Query comparing dates in SQL

If You are comparing only with the date vale, then converting it to date (not datetime) will work

select id,numbers_from,created_date,amount_numbers,SMS_text 
 from Test_Table
 where 
 created_date <= convert(date,'2013-04-12',102)

This conversion is also applicable during using GetDate() function

How to replace a character with a newline in Emacs?

There are four ways I've found to put a newline into the minibuffer.

  1. C-o

  2. C-q C-j

  3. C-q 12 (12 is the octal value of newline)

  4. C-x o to the main window, kill a newline with C-k, then C-x o back to the minibuffer, yank it with C-y

TypeError: $(...).on is not a function

I tried the solution of Oskar (and many others) but for me it finaly only worked with:

jQuery(function($){
   // Your jQuery code here, using the $
});

See: https://learn.jquery.com/using-jquery-core/avoid-conflicts-other-libraries/

Plotting a python dict in order of key values

Python dictionaries are unordered. If you want an ordered dictionary, use collections.OrderedDict

In your case, sort the dict by key before plotting,

import matplotlib.pylab as plt

lists = sorted(d.items()) # sorted by key, return a list of tuples

x, y = zip(*lists) # unpack a list of pairs into two tuples

plt.plot(x, y)
plt.show()

Here is the result. enter image description here

Are HTTPS URLs encrypted?

Entire request and response is encrypted, including URL.

Note that when you use a HTTP Proxy, it knows the address (domain) of the target server, but doesn't know the requested path on this server (i.e. request and response are always encrypted).

How to uninstall Ruby from /usr/local?

If ruby was installed in the following way:

./configure --prefix=/usr/local
make
sudo make install

You can uninstall it in the following way:

Check installed ruby version; lets assume 2.1.2

wget http://cache.ruby-lang.org/pub/ruby/2.1/ruby-2.1.2.tar.bz2
bunzip ...
tar xfv ...
cd ruby-2.1.2
./configure --prefix=/usr/local
make
sudo checkinstall
  # will build deb or rpm package and try to install it

After installation, you can now remove the package and it will remove the directories/files/etc.

sudo rpm -e ruby # or dpkg -P ruby (for Debian-like systems)

There might be some artifacts left:

Removing ruby ...
  warning: while removing ruby, directory '/usr/local/lib/ruby/gems/2.1.0/gems' not empty so not removed.
  ...

Remove them manually.

"call to undefined function" error when calling class method

Another silly mistake you can do is copy recursive function from non class environment to class and don`t change inner self calls to $this->method_name()

i`m writing this because couldn`t understand why i got this error and this thread is first in google when you search for this error.

CSV new-line character seen in unquoted field error

Try to run dos2unix on your windows imported files first

Checking for #N/A in Excel cell from VBA code

First check for an error (N/A value) and then try the comparisation against cvErr(). You are comparing two different things, a value and an error. This may work, but not always. Simply casting the expression to an error may result in similar problems because it is not a real error only the value of an error which depends on the expression.

If IsError(ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value) Then
  If (ActiveWorkbook.Sheets("Publish").Range("G4").offset(offsetCount, 0).Value <> CVErr(xlErrNA)) Then
    'do something
  End If
End If

nginx error connect to php5-fpm.sock failed (13: Permission denied)

Consideration must also be given to your individual FPM pools, if any.

I couldn't figure out why none of these answers was working for me today. This had been a set-and-forget scenario for me, where I had forgotten that listen.user and listen.group were duplicated on a per-pool basis.

If you used pools for different user accounts like I did, where each user account owns their FPM processes and sockets, setting only the default listen.owner and listen.group configuration options to 'nginx' will simply not work. And obviously, letting 'nginx' own them all is not acceptable either.

For each pool, make sure that

listen.group = nginx

Otherwise, you can leave the pool's ownership and such alone.

OpenCV & Python - Image too big to display

Use this for example:

cv2.namedWindow('finalImg', cv2.WINDOW_NORMAL)
cv2.imshow("finalImg",finalImg)

FORCE INDEX in MySQL - where do I put it?

FORCE_INDEX is going to be deprecated after MySQL 8:

Thus, you should expect USE INDEX, FORCE INDEX, and IGNORE INDEX to be deprecated in 
a future release of MySQL, and at some time thereafter to be removed altogether.

https://dev.mysql.com/doc/refman/8.0/en/index-hints.html

You should be using JOIN_INDEX, GROUP_INDEX, ORDER_INDEX, and INDEX instead, for v8.

LD_LIBRARY_PATH vs LIBRARY_PATH

Since I link with gcc why ld is being called, as the error message suggests?

gcc calls ld internally when it is in linking mode.

Java.lang.NoClassDefFoundError: com/fasterxml/jackson/databind/exc/InvalidDefinitionException

Replace the dependency in the POM.xml file

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-core</artifactId>
  <version>2.2.3</version>
</dependency>

By the dependency

    <dependency>
        <groupId>com.fasterxml.jackson.core</groupId>
        <artifactId>jackson-databind</artifactId>
        <version>2.9.4</version>
    </dependency>

How to find server name of SQL Server Management Studio

Run this Query to get the name

SELECT @@SERVERNAME

Python 3.6 install win32api?

Take a look at this answer: ImportError: no module named win32api

You can use

pip install pypiwin32

How to create a sticky left sidebar menu using bootstrap 3?

I used this way in my code

$(function(){
    $('.block').affix();
})

MYSQL: How to copy an entire row from one table to another in mysql with the second table having one extra column?

INSERT INTO dues_storage
SELECT field1, field2, ..., fieldN, CURRENT_DATE()
FROM dues
WHERE id = 5;

How to set menu to Toolbar in Android

You need to override this code in your Activity:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu, this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.main2, menu);
    return true;
}

and set your toolbar like this:

Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);

Selenium using Java - The path to the driver executable must be set by the webdriver.gecko.driver system property

in my case, I must to set path in properties file, in many hours I find the way:

application.properties file:

webdriver.gecko.driver="/lib/geckodriver-v0.26.0-win64/geckodriver.exe"

in java code:

private static final Logger log = Logger.getLogger(Login.class.getName());
private FirefoxDriver driver;
private FirefoxProfile firefoxProfile;
private final String BASE_URL = "https://www.myweb.com/";
private static final String RESOURCE_NAME = "main/resources/application.properties"; // could also be a constant
private Properties properties;

public Login() {
    init();
}

private void init() {
    properties = new Properties();
    try(InputStream resourceStream = getClass().getClassLoader().getResourceAsStream(RESOURCE_NAME)) {
        properties.load(resourceStream);
    } catch (IOException e) {
        System.err.println("Could not open Config file");
        log.log(Level.SEVERE, "Could not open Config file", e);
    }
    // open incognito tab by default
    firefoxProfile = new FirefoxProfile();
    firefoxProfile.setPreference("browser.privatebrowsing.autostart", true);
    // geckodriver driver path to run
    String gekoDriverPath = properties.getProperty("webdriver.gecko.driver");
    log.log(Level.INFO, gekoDriverPath);
    System.setProperty("webdriver.gecko.driver", System.getProperty("user.dir") + gekoDriverPath);
    log.log(Level.INFO, System.getProperty("webdriver.gecko.driver"));
    System.setProperty("webdriver.gecko.driver", System.getProperty("webdriver.gecko.driver").replace("\"", ""));
    if (driver == null) {
        driver = new FirefoxDriver();
    }

}

What is the purpose of the : (colon) GNU Bash builtin?

If you'd like to truncate a file to zero bytes, useful for clearing logs, try this:

:> file.log

How to parse a string in JavaScript?

Use the Javascript string split() function.

var coolVar = '123-abc-itchy-knee';
var partsArray = coolVar.split('-');

// Will result in partsArray[0] == '123', partsArray[1] == 'abc', etc

Java Enum Methods - return opposite direction enum

For those lured here by title: yes, you can define your own methods in your enum. If you are wondering how to invoke such non-static method, you do it same way as with any other non-static method - you invoke it on instance of type which defines or inherits that method. In case of enums such instances are simply ENUM_CONSTANTs.

So all you need is EnumType.ENUM_CONSTANT.methodName(arguments).


Now lets go back to problem from question. One of solutions could be

public enum Direction {

    NORTH, SOUTH, EAST, WEST;

    private Direction opposite;

    static {
        NORTH.opposite = SOUTH;
        SOUTH.opposite = NORTH;
        EAST.opposite = WEST;
        WEST.opposite = EAST;
    }

    public Direction getOppositeDirection() {
        return opposite;
    }

}

Now Direction.NORTH.getOppositeDirection() will return Direction.SOUTH.


Here is little more "hacky" way to illustrate @jedwards comment but it doesn't feel as flexible as first approach since adding more fields or changing their order will break our code.

public enum Direction {
    NORTH, EAST, SOUTH, WEST;

    // cached values to avoid recreating such array each time method is called
    private static final Direction[] VALUES = values();

    public Direction getOppositeDirection() {
        return VALUES[(ordinal() + 2) % 4]; 
    }
}

Read file line by line in PowerShell

The almighty switch works well here:

'one
two
three' > file

$regex = '^t'

switch -regex -file file { 
  $regex { "line is $_" } 
}

Output:

line is two
line is three

Adding a user on .htpasswd

Exact same thing, just omit the -c option. Apache's docs on it here.

htpasswd /etc/apache2/.htpasswd newuser

Also, htpasswd typically isn't run as root. It's typically owned by either the web server, or the owner of the files being served. If you're using root to edit it instead of logging in as one of those users, that's acceptable (I suppose), but you'll want to be careful to make sure you don't accidentally create a file as root (and thus have root own it and no one else be able to edit it).

CMake complains "The CXX compiler identification is unknown"

Run apt-get install build-essential on your system.

This package depends on other packages considered to be essential for builds and will install them. If you find you have to build packages, this can be helpful to avoid piecemeal resolution of dependencies.

See this page for more info.

How to add url parameter to the current url?

In case you want to add the URL parameter in JavaScript, see this answer. As suggested there, you can use the URLSeachParams API in modern browsers as follows:

<script>
function addUrlParameter(name, value) {
  var searchParams = new URLSearchParams(window.location.search)
  searchParams.set(name, value)
  window.location.search = searchParams.toString()
}
</script>

<body>
...
  <a onclick="addUrlParameter('like', 'like')">Like this page</a>
...
</body>

Find the most frequent number in a NumPy array

You can use the following approach:

x = np.array([[2, 5, 5, 2], [2, 7, 8, 5], [2, 5, 7, 9]])
u, c = np.unique(x, return_counts=True)
print(u[c == np.amax(c)])

This will give the answer: array([2, 5])

How to implement infinity in Java?

A generic solution is to introduce a new type. It may be more involved, but it has the advantage of working for any type that doesn't define its own infinity.

If T is a type for which lteq is defined, you can define InfiniteOr<T> with lteq something like this:

class InfiniteOr with type parameter T:
    field the_T of type null-or-an-actual-T
    isInfinite()
        return this.the_T == null
    getFinite():
        assert(!isInfinite());
        return this.the_T
    lteq(that)
        if that.isInfinite()
            return true
        if this.isInfinite()
            return false
        return this.getFinite().lteq(that.getFinite())

I'll leave it to you to translate this to exact Java syntax. I hope the ideas are clear; but let me spell them out anyways.

The idea is to create a new type which has all the same values as some already existing type, plus one special value which—as far as you can tell through public methods—acts exactly the way you want infinity to act, e.g. it's greater than anything else. I'm using null to represent infinity here, since that seems the most straightforward in Java.

If you want to add arithmetic operations, decide what they should do, then implement that. It's probably simplest if you handle the infinite cases first, then reuse the existing operations on finite values of the original type.

There might or might not be a general pattern to whether or not it's beneficial to adopt a convention of handling left-hand-side infinities before right-hand-side infinities or vice versa; I can't tell without trying it out, but for less-than-or-equal (lteq) I think it's simpler to look at right-hand-side infinity first. I note that lteq is not commutative, but add and mul are; maybe that is relevant.

Note: coming up with a good definition of what should happen on infinite values is not always easy. It is for comparison, addition and multiplication, but maybe not subtraction. Also, there is a distinction between infinite cardinal and ordinal numbers which you may want to pay attention to.

Match multiline text using regular expression

The multiline flag tells regex to match the pattern to each line as opposed to the entire string for your purposes a wild card will suffice.

How to use format() on a moment.js duration?

convert duration to ms and then to moment:

moment.utc(duration.as('milliseconds')).format('HH:mm:ss')

Making a POST call instead of GET using urllib2

it should be sending a POST if you provide a data parameter (like you are doing):

from the docs: "the HTTP request will be a POST instead of a GET when the data parameter is provided"

so.. add some debug output to see what's up from the client side.

you can modify your code to this and try again:

import urllib
import urllib2

url = 'http://myserver/post_service'
opener = urllib2.build_opener(urllib2.HTTPHandler(debuglevel=1))
data = urllib.urlencode({'name' : 'joe',
                         'age'  : '10'})
content = opener.open(url, data=data).read()

Uninstall old versions of Ruby gems

For removing older versions of all installed gems, following 2 commands are useful:

 gem cleanup --dryrun

Above command will preview what gems are going to be removed.

 gem cleanup

Above command will actually remove them.

what does it mean "(include_path='.:/usr/share/pear:/usr/share/php')"?

I had the same error while including file from root of my project in codeigniter.I was using this in common.php of my project.

<?php include_once base_url().'csrf-magic-master/csrf-magic.php';  ?>

i changed it to

<?php include_once ('csrf-magic-master/csrf-magic.php');  ?>

Working fine now.

Error 80040154 (Class not registered exception) when initializing VCProjectEngineObject (Microsoft.VisualStudio.VCProjectEngine.dll)

There are not many good reasons this would fail, especially the regsvr32 step. Run dumpbin /exports on that dll. If you don't see DllRegisterServer then you've got a corrupt install. It should have more side-effects, you wouldn't be able to build C/C++ projects anymore.

One standard failure mode is running this on a 64-bit operating system. This is 32-bit unmanaged code, you would indeed get the 'class not registered' exception. Project + Properties, Build tab, change Platform Target to x86.

How can I send an email through the UNIX mailx command?

If you want to send more than two person or DL :

echo "Message Body" | mailx -s "Message Title" -r [email protected] [email protected],[email protected]

here:

  • -s = subject or mail title
  • -r = sender mail or DL

How do I get the parent directory in Python?

The Pathlib method (Python 3.4+)

from pathlib import Path
Path('C:\Program Files').parent
# Returns a Pathlib object

The traditional method

import os.path
os.path.dirname('C:\Program Files')
# Returns a string


Which method should I use?

Use the traditional method if:

  • You are worried about existing code generating errors if it were to use a Pathlib object. (Since Pathlib objects cannot be concatenated with strings.)

  • Your Python version is less than 3.4.

  • You need a string, and you received a string. Say for example you have a string representing a filepath, and you want to get the parent directory so you can put it in a JSON string. It would be kind of silly to convert to a Pathlib object and back again for that.

If none of the above apply, use Pathlib.



What is Pathlib?

If you don't know what Pathlib is, the Pathlib module is a terrific module that makes working with files even easier for you. Most if not all of the built in Python modules that work with files will accept both Pathlib objects and strings. I've highlighted below a couple of examples from the Pathlib documentation that showcase some of the neat things you can do with Pathlib.

Navigating inside a directory tree:

>>> p = Path('/etc')
>>> q = p / 'init.d' / 'reboot'
>>> q
PosixPath('/etc/init.d/reboot')
>>> q.resolve()
PosixPath('/etc/rc.d/init.d/halt')

Querying path properties:

>>> q.exists()
True
>>> q.is_dir()
False

Get the difference between dates in terms of weeks, months, quarters, and years

try this for a months solution

StartDate <- strptime("14 January 2013", "%d %B %Y") 
EventDates <- strptime(c("26 March 2014"), "%d %B %Y") 
difftime(EventDates, StartDate) 

How to round up value C# to the nearest integer?

It is also possible to round negative integers

// performing d = c * 3/4 where d can be pos or neg
d = ((c * a) + ((c>0? (b>>1):-(b>>1)))) / b;
// explanation:
// 1.) multiply:          c * a  
// 2.) if c is negative:  (c>0? subtract half of the dividend 
//                              (b>>1) is bit shift right = (b/2)
//     if c is positive:  else  add half of the dividend 
// 3.) do the division
// on a C51/52 (8bit embedded) or similar like ATmega the below code may execute in approx 12cpu cycles (not tested)

Extended from a tip somewhere else in here. Sorry, missed from where.

/* Example test: integer rounding example including negative*/
#include <stdio.h>
#include <string.h>

int main () {
   //rounding negative int
   // doing something like d = c * 3/4
   int a=3;
   int b=4;
   int c=-5;
   int d;
   int s=c;
   int e=c+10;


   for(int f=s; f<=e; f++) {
      printf("%d\t",f);

      double cd=f, ad=a, bd=b , dd;

      // d = c * 3/4  with double
      dd = cd * ad / bd;

      printf("%.2f\t",dd);
      printf("%.1f\t",dd);        
      printf("%.0f\t",dd);

      // try again with typecast have used that a lot in Borland C++ 35 years ago....... maybe evolution has overtaken it ;) ***
      // doing div before mul on purpose
      dd =(double)c * ((double)a / (double)b);
      printf("%.2f\t",dd);

      c=f;
      // d = c * 3/4  with integer rounding
      d = ((c * a) + ((c>0? (b>>1):-(b>>1)))) / b;
      printf("%d\t",d);
      puts("");
  }
 return 0;
}

/* test output
in  2f     1f   0f cast int   
-5  -3.75   -3.8    -4  -3.75   -4  
-4  -3.00   -3.0    -3  -3.75   -3  
-3  -2.25   -2.2    -2  -3.00   -2  
-2  -1.50   -1.5    -2  -2.25   -2  
-1  -0.75   -0.8    -1  -1.50   -1  
 0   0.00    0.0     0  -0.75    0  
 1   0.75    0.8     1   0.00    1  
 2   1.50    1.5     2   0.75    2  
 3   2.25    2.2     2   1.50    2  
 4   3.00    3.0     3   2.25  3    
 5   3.75    3.8     4   3.00   

// by the way evolution: 
// Is there any decent small integer library out there for that by now?

FileSystemWatcher Changed event is raised twice

Been searching for answer but I came up with a dirty solution. Since my event fires twice, second action does nothing.

       $count = 1
       $action = { 
            if($count -eq 1){                  
                #DO SOMETHING
                $count = 2 
            }else{
                $count = 1
            }
        }  

Public free web services for testing soap client

There is a bunch on here:

http://www.webservicex.net/WS/wscatlist.aspx

Just google for "Free WebService" or "Open WebService" and you'll find tons of open SOAP endpoints.

Remember, you can get a WSDL from any ASMX endpoint by adding ?WSDL to the url.

How can I stop .gitignore from appearing in the list of untracked files?

Navigate to the base directory of your git repo and execute the following command:

echo '\\.*' >> .gitignore

All dot files will be ignored, including that pesky .DS_Store if you're on a mac.

Android getActivity() is undefined

You want getActivity() inside your class. It's better to use

yourclassname.this.getActivity()

Try this. It's helpful for you.

Nested ng-repeat

If you have a big nested JSON object and using it across several screens, you might face performance issues in page loading. I always go for small individual JSON objects and query the related objects as lazy load only where they are required.

you can achieve it using ng-init

<td class="lectureClass" ng-repeat="s in sessions" ng-init='presenters=getPresenters(s.id)'>
      {{s.name}}
      <div class="presenterClass" ng-repeat="p in presenters">
          {{p.name}}
      </div>
</td> 

The code on the controller side should look like below

$scope.getPresenters = function(id) {
    return SessionPresenters.get({id: id});
};

While the API factory is as follows:

angular.module('tryme3App').factory('SessionPresenters', function ($resource, DateUtils) {

        return $resource('api/session.Presenters/:id', {}, {
            'query': { method: 'GET', isArray: true},
            'get': {
                method: 'GET', isArray: true
            },
            'update': { method:'PUT' }
        });
    });

How can I remove the first line of a text file using bash/sed script?

No, that's about as efficient as you're going to get. You could write a C program which could do the job a little faster (less startup time and processing arguments) but it will probably tend towards the same speed as sed as files get large (and I assume they're large if it's taking a minute).

But your question suffers from the same problem as so many others in that it pre-supposes the solution. If you were to tell us in detail what you're trying to do rather then how, we may be able to suggest a better option.

For example, if this is a file A that some other program B processes, one solution would be to not strip off the first line, but modify program B to process it differently.

Let's say all your programs append to this file A and program B currently reads and processes the first line before deleting it.

You could re-engineer program B so that it didn't try to delete the first line but maintains a persistent (probably file-based) offset into the file A so that, next time it runs, it could seek to that offset, process the line there, and update the offset.

Then, at a quiet time (midnight?), it could do special processing of file A to delete all lines currently processed and set the offset back to 0.

It will certainly be faster for a program to open and seek a file rather than open and rewrite. This discussion assumes you have control over program B, of course. I don't know if that's the case but there may be other possible solutions if you provide further information.

Understanding Chrome network log "Stalled" state

https://developers.google.com/web/tools/chrome-devtools/network-performance/understanding-resource-timing

This comes from the official site of Chome-devtools and it helps. Here i quote:

  • Queuing If a request is queued it indicated that:
    • The request was postponed by the rendering engine because it's considered lower priority than critical resources (such as scripts/styles). This often happens with images.
    • The request was put on hold to wait for an unavailable TCP socket that's about to free up.
    • The request was put on hold because the browser only allows six TCP connections per origin on HTTP 1. Time spent making disk cache entries (typically very quick.)
  • Stalled/Blocking Time the request spent waiting before it could be sent. It can be waiting for any of the reasons described for Queueing. Additionally, this time is inclusive of any time spent in proxy negotiation.

Convert json to a C# array?

just take the string and use the JavaScriptSerializer to deserialize it into a native object. For example, having this json:

string json = "[{Name:'John Simith',Age:35},{Name:'Pablo Perez',Age:34}]"; 

You'd need to create a C# class called, for example, Person defined as so:

public class Person
{
 public int Age {get;set;}
 public string Name {get;set;}
}

You can now deserialize the JSON string into an array of Person by doing:

JavaScriptSerializer js = new JavaScriptSerializer();
Person [] persons =  js.Deserialize<Person[]>(json);

Here's a link to JavaScriptSerializer documentation.

Note: my code above was not tested but that's the idea Tested it. Unless you are doing something "exotic", you should be fine using the JavascriptSerializer.

Pass variables by reference in JavaScript

Actually it is really easy. The problem is understanding that once passing classic arguments, you are scoped into another, read-only zone.

The solution is to pass the arguments using JavaScript's object-oriented design. It is the same as putting the arguments in a global/scoped variable, but better...

function action(){
  /* Process this.arg, modification allowed */
}

action.arg = [["empty-array"], "some string", 0x100, "last argument"];
action();

You can also promise stuff up to enjoy the well-known chain: Here is the whole thing, with promise-like structure

function action(){
  /* Process this.arg, modification allowed */
  this.arg = ["a", "b"];
}

action.setArg = function(){this.arg = arguments; return this;}

action.setArg(["empty-array"], "some string", 0x100, "last argument")()

Or better yet...

action.setArg(["empty-array"],"some string",0x100,"last argument").call()

Establish a VPN connection in cmd

Have you looked into rasdial?

Just incase anyone wanted to do this and finds this in the future, you can use rasdial.exe from command prompt to connect to a VPN network

ie rasdial "VPN NETWORK NAME" "Username" *

it will then prompt for a password, else you can use "username" "password", this is however less secure

http://www.msfn.org/board/topic/113128-connect-to-vpn-from-cmdexe-vista/?p=747265

jQuery javascript regex Replace <br> with \n

a cheap and nasty would be:

jQuery("#myDiv").html().replace("<br>", "\n").replace("<br />", "\n")

EDIT

jQuery("#myTextArea").val(
    jQuery("#myDiv").html()
        .replace(/\<br\>/g, "\n")
        .replace(/\<br \/\>/g, "\n")
);

Also created a jsfiddle if needed: http://jsfiddle.net/2D3xx/

Python: How to create a unique file name?

Maybe you need unique temporary file?

import tempfile

f = tempfile.NamedTemporaryFile(mode='w+b', delete=False)

print f.name
f.close()

f is opened file. delete=False means do not delete file after closing.

If you need control over the name of the file, there are optional prefix=... and suffix=... arguments that take strings. See https://docs.python.org/3/library/tempfile.html.

Python wildcard search in string

Easy method is try os.system:

import os
text = 'this is text'
os.system("echo %s | grep 't*'" % text)

Jquery selector input[type=text]')

If you have multiple inputs as text in a form or a table that you need to iterate through, I did this:

var $list = $("#tableOrForm :input[type='text']");

$list.each(function(){
    // Go on with your code.
});

What I did was I checked each input to see if the type is set to "text", then it'll grab that element and store it in the jQuery list. Then, it would iterate through that list. You can set a temp variable for the current iteration like this:

var $currentItem = $(this);

This will set the current item to the current iteration of your for each loop. Then you can do whatever you want with the temp variable.

Hope this helps anyone!

dropzone.js - how to do something after ALL files are uploaded

this.on("totaluploadprogress", function(totalBytes, totalBytesSent){


                    if(totalBytes == 100) {

                        //all done! call func here
                    }
                });

Android studio, gradle and NDK

As of now (Android Studio v0.8.6) it's quite simple. Here are the steps to create a "Hello world" type app:

  1. Download the Android NDK and put the root folder somewhere sane -- in the same location as the SDK folder, perhaps.

  2. Add the following to your local.properties file: ndk.dir=<path-to-ndk>

  3. Add the following to your build.gradle file inside of the defaultConfig closure, right after the versionName line: ndk { moduleName="hello-world" }

  4. In your app module's main directory, create a new folder called jni.

  5. In that folder, create a file called hello-world.c, which you'll see below.

  6. See the example Activity code below for an example of how to call a method (or is it a function?) in hello-world.c.


hello-world.c

#include <string.h>
#include <jni.h>

jstring
Java_me_mattlogan_ndktest_MainActivity_stringFromJNI(JNIEnv* env, jobject thiz)
{
    return (*env)->NewStringUTF(env, "Hello world!");
}

MainActivity.java

public class MainActivity extends Activity {

    static {
        System.loadLibrary("hello-world");
    }

    public native String stringFromJNI();

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

        String testString = stringFromJNI();

        TextView mainText = (TextView) findViewById(R.id.main_text);
        mainText.setText(testString);
    }
}

build.gradle

apply plugin: 'com.android.application'

android {
    compileSdkVersion 20
    buildToolsVersion "20.0.0"

    defaultConfig {
        applicationId "me.mattlogan.ndktest"
        minSdkVersion 15
        targetSdkVersion 20
        versionCode 1
        versionName "1.0"

        ndk {
            moduleName "hello-world"
        }
    }
    buildTypes {
        release {
            runProguard false
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    compile fileTree(dir: 'libs', include: ['*.jar'])
}

Find the full source code of a very similar app here (minus the NDK).

Difference of two date time in sql server

Ok we all know the answer involves DATEDIFF(). But that gives you only half the result you may be after. What if you want to get the results in human-readable format, in terms of Minutes and Seconds between two DATETIME values?

The CONVERT(), DATEADD() and of course DATEDIFF() functions are perfect for a more easily readable result that your clients can use, instead of a number.

i.e.

CONVERT(varchar(5), DATEADD(minute, DATEDIFF(MINUTE, date1, date2), 0), 114) 

This will give you something like:

HH:MM

If you want more precision, just increase the VARCHAR().

CONVERT(varchar(12), DATEADD(minute, DATEDIFF(MINUTE, date1, date2), 0), 114) 

HH:MM.SS.MS

jQuery count number of divs with a certain class?

<!DOCTYPE html>
    <html>
    <head>
        <title></title>
        <style type="text/css">
            .test {
                background: #ff4040;
                color: #fff;
                display: block;
                font-size: 15px;
            }
        </style>
    </head>
    <body>
        <div class="test"> one </div>
        <div class="test"> two </div>
        <div class="test"> three </div>
        <div class="test"> four </div>
        <div class="test"> five </div>
        <div class="test"> six </div>
        <div class="test"> seven </div>
        <div class="test"> eight </div>
        <div class="test"> nine </div>
        <div class="test"> ten </div>
        <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
        <script type="text/javascript">
        $(document).ready(function () {
            //get total length by class
            var numItems = $('.test').length;
            //get last three count
            var numItems3=numItems-3;         


            var i = 0;
            $('.test').each(function(){
                i++;
                if(i>numItems3)
                {

                    $(this).attr("class","");
                }
            })
        });
    </script>
    </body>
    </html>

JavaScript inside an <img title="<a href='#' onClick='alert('Hello World!')>The Link</a>" /> possible?

No, this is, as you say "rubbish code". If it works as should, it is because browsers try to "read the writer's mind" - in other words, they have algorithms to try to make sense of "rubbish code", guess at the probable intent and internally change it into something that actually makes sense.

In other words, your code only works by accident, and probably not in all browsers.

Is this what you're trying to do?

<a href="#" onClick="alert('Hello World!')"><img title="The Link" /></a>

Why use Gradle instead of Ant or Maven?

I don't use Gradle in anger myself (just a toy project so far) [author means they have used Gradle on only a toy project so far, not that Gradle is a toy project - see comments], but I'd say that the reasons one would consider using it would be because of the frustrations of Ant and Maven.

In my experience Ant is often write-only (yes I know it is possible to write beautifully modular, elegant builds, but the fact is most people don't). For any non-trivial projects it becomes mind-bending, and takes great care to ensure that complex builds are truly portable. Its imperative nature can lead to replication of configuration between builds (though macros can help here).

Maven takes the opposite approach and expects you to completely integrate with the Maven lifecycle. Experienced Ant users find this particularly jarring as Maven removes many of the freedoms you have in Ant. For example there's a Sonatype blog that enumerates many of the Maven criticisms and their responses.

The Maven plugin mechanism allows for very powerful build configurations, and the inheritance model means you can define a small set of parent POMs encapsulating your build configurations for the whole enterprise and individual projects can inherit those configurations, leaving them lightweight. Maven configuration is very verbose (though Maven 3 promises to address this), and if you want to do anything that is "not the Maven way" you have to write a plugin or use the hacky Ant integration. Note I happen to like writing Maven plugins but appreciate that many will object to the effort involved.

Gradle promises to hit the sweet spot between Ant and Maven. It uses Ivy's approach for dependency resolution. It allows for convention over configuration but also includes Ant tasks as first class citizens. It also wisely allows you to use existing Maven/Ivy repositories.

So if you've hit and got stuck with any of the Ant/Maven pain points, it is probably worth trying Gradle out, though in my opinion it remains to be seen if you wouldn't just be trading known problems for unknown ones. The proof of the pudding is in the eating though so I would reserve judgment until the product is a little more mature and others have ironed out any kinks (they call it bleeding edge for a reason). I'll still be using it in my toy projects though, It's always good to be aware of the options.

What's the difference between the atomic and nonatomic attributes?

The syntax and semantics are already well-defined by other excellent answers to this question. Because execution and performance are not detailed well, I will add my answer.

What is the functional difference between these 3?

I'd always considered atomic as a default quite curious. At the abstraction level we work at, using atomic properties for a class as a vehicle to achieve 100% thread-safety is a corner case. For truly correct multithreaded programs, intervention by the programmer is almost certainly a requirement. Meanwhile, performance characteristics and execution have not yet been detailed in depth. Having written some heavily multithreaded programs over the years, I had been declaring my properties as nonatomic the entire time because atomic was not sensible for any purpose. During discussion of the details of atomic and nonatomic properties this question, I did some profiling encountered some curious results.

Execution

Ok. The first thing I would like to clear up is that the locking implementation is implementation-defined and abstracted. Louis uses @synchronized(self) in his example -- I have seen this as a common source of confusion. The implementation does not actually use @synchronized(self); it uses object level spin locks. Louis's illustration is good for a high-level illustration using constructs we are all familiar with, but it's important to know it does not use @synchronized(self).

Another difference is that atomic properties will retain/release cycle your objects within the getter.

Performance

Here's the interesting part: Performance using atomic property accesses in uncontested (e.g. single-threaded) cases can be really very fast in some cases. In less than ideal cases, use of atomic accesses can cost more than 20 times the overhead of nonatomic. While the Contested case using 7 threads was 44 times slower for the three-byte struct (2.2 GHz Core i7 Quad Core, x86_64). The three-byte struct is an example of a very slow property.

Interesting side note: User-defined accessors of the three-byte struct were 52 times faster than the synthesized atomic accessors; or 84% the speed of synthesized nonatomic accessors.

Objects in contested cases can also exceed 50 times.

Due to the number of optimizations and variations in implementations, it's quite difficult to measure real-world impacts in these contexts. You might often hear something like "Trust it, unless you profile and find it is a problem". Due to the abstraction level, it's actually quite difficult to measure actual impact. Gleaning actual costs from profiles can be very time consuming, and due to abstractions, quite inaccurate. As well, ARC vs MRC can make a big difference.

So let's step back, not focussing on the implementation of property accesses, we'll include the usual suspects like objc_msgSend, and examine some real-world high-level results for many calls to a NSString getter in uncontested cases (values in seconds):

  • MRC | nonatomic | manually implemented getters: 2
  • MRC | nonatomic | synthesized getter: 7
  • MRC | atomic | synthesized getter: 47
  • ARC | nonatomic | synthesized getter: 38 (note: ARC's adding ref count cycling here)
  • ARC | atomic | synthesized getter: 47

As you have probably guessed, reference count activity/cycling is a significant contributor with atomics and under ARC. You would also see greater differences in contested cases.

Although I pay close attention to performance, I still say Semantics First!. Meanwhile, performance is a low priority for many projects. However, knowing execution details and costs of technologies you use certainly doesn't hurt. You should use the right technology for your needs, purposes, and abilities. Hopefully this will save you a few hours of comparisons, and help you make a better informed decision when designing your programs.

How can I replace the deprecated set_magic_quotes_runtime in php?

In PHP 7 we can use:

ini_set('magic_quotes_runtime', 0);

instead of set_magic_quotes_runtime(0);

Change bootstrap datepicker date format on select

As of 2016 I used datetimepicker like this:

$(function () {
    $('#date_box').datetimepicker({
        format: 'YYYY-MM-DD hh:mm'
    });
});

How to get JavaScript variable value in PHP

Add a cookie with the javascript variable you want to access.

document.cookie="profile_viewer_uid=1";

Then acces it in php via

$profile_viewer_uid = $_COOKIE['profile_viewer_uid'];

Query error with ambiguous column name in SQL

One of your tables has the same column name's which brings a confusion in the query as to which columns of the tables are you referring to. Copy this code and run it.

SELECT 
    v.VendorName, i.InvoiceID, iL.InvoiceSequence, iL.InvoiceLineItemAmount
FROM Vendors AS v
JOIN Invoices AS i ON (v.VendorID = .VendorID)
JOIN InvoiceLineItems AS iL ON (i.InvoiceID = iL.InvoiceID)
WHERE  
    I.InvoiceID IN
        (SELECT iL.InvoiceSequence 
         FROM InvoiceLineItems
         WHERE iL.InvoiceSequence > 1)
ORDER BY 
    V.VendorName, i.InvoiceID, iL.InvoiceSequence, iL.InvoiceLineItemAmount

How to use HttpWebRequest (.NET) asynchronously?

.NET has changed since many of these answers were posted, and I'd like to provide a more up-to-date answer. Use an async method to start a Task that will run on a background thread:

private async Task<String> MakeRequestAsync(String url)
{    
    String responseText = await Task.Run(() =>
    {
        try
        {
            HttpWebRequest request = WebRequest.Create(url) as HttpWebRequest;
            WebResponse response = request.GetResponse();            
            Stream responseStream = response.GetResponseStream();
            return new StreamReader(responseStream).ReadToEnd();            
        }
        catch (Exception e)
        {
            Console.WriteLine("Error: " + e.Message);
        }
        return null;
    });

    return responseText;
}

To use the async method:

String response = await MakeRequestAsync("http://example.com/");

Update:

This solution does not work for UWP apps which use WebRequest.GetResponseAsync() instead of WebRequest.GetResponse(), and it does not call the Dispose() methods where appropriate. @dragansr has a good alternative solution that addresses these issues.

jQuery UI Dialog window loaded within AJAX style jQuery UI Tabs

//Properly Formatted

<script type="text/Javascript">
  $(function ()    
{
    $('<div>').dialog({
        modal: true,
        open: function ()
        {
            $(this).load('mypage.html');
        },         
        height: 400,
        width: 600,
        title: 'Ajax Page'
    });
});

Changing background color of text box input not working when empty

You can style it using javascript and css. Add the style to css and using javascript add/remove style using classlist property. Here is a JSFiddle for it.

  <div class="div-image-text">
    <input class="input-image-url" type="text" placeholder="Add text" name="input-image">
    <input type="button" onclick="addRemoteImage(event);" value="Submit">
  </div>
  <div class="no-image-url-error" name="input-image-error">Textbox empty</div>

addRemoteImage = function(event) {
  var textbox = document.querySelector("input[name='input-image']"),
    imageUrl = textbox.value,
    errorDiv = document.querySelector("div[name='input-image-error']");
  if (imageUrl == "") {
    errorDiv.style.display = "block";
    textbox.classList.add('text-error');
    setTimeout(function() {
      errorDiv.style.removeProperty('display');
      textbox.classList.remove('text-error');
    }, 3000);
  } else {
    textbox.classList.remove('text-error');
  }
}

Searching for file in directories recursively

Try the following method:

public static IEnumerable<string> GetXMLFiles(string directory)
{
    List<string> files = new List<string>();

    try
    {
        files.AddRange(Directory.GetFiles(directory, "*.xml", SearchOption.AllDirectories));
    }
    catch (Exception ex)
    {
        Console.WriteLine(ex.Message);
    }

    return files;
}

How to pass multiple parameters in a querystring

~mypage.aspx?strID=x&strName=y&strDate=z

How to disable registration new users in Laravel

In routes.php, just add the following:

if (!env('ALLOW_REGISTRATION', false)) {
    Route::any('/register', function() {
        abort(403);
    });
}

Then you can selectively control whether registration is allowed or not in you .env file.

GitHub - List commits by author

Just add ?author=<emailaddress> or ?author=<githubUserName> to the url when viewing the "commits" section of a repo.

Get file name from URL

If you don't need to get rid of the file extension, here's a way to do it without resorting to error-prone String manipulation and without using external libraries. Works with Java 1.7+:

import java.net.URI
import java.nio.file.Paths

String url = "http://example.org/file?p=foo&q=bar"
String filename = Paths.get(new URI(url).getPath()).getFileName().toString()

SQL query: Delete all records from the table except latest N?

This should work as well:

DELETE FROM [table] 
INNER JOIN (
    SELECT [id] 
    FROM (
        SELECT [id] 
        FROM [table] 
        ORDER BY [id] DESC
        LIMIT N
    ) AS Temp
) AS Temp2 ON [table].[id] = [Temp2].[id]

Is there a CSS selector for elements containing certain text?

Doing small Filter Widgets like this:

    var searchField = document.querySelector('HOWEVER_YOU_MAY_FIND_IT')
    var faqEntries = document.querySelectorAll('WRAPPING_ELEMENT .entry')

    searchField.addEventListener('keyup', function (evt) {
        var testValue = evt.target.value.toLocaleLowerCase();
        var regExp = RegExp(testValue);

        faqEntries.forEach(function (entry) {
            var text = entry.textContent.toLocaleLowerCase();

            entry.classList.remove('show', 'hide');

            if (regExp.test(text)) {
                entry.classList.add('show')
            } else {
                entry.classList.add('hide')
            }
        })
    })

Dynamically create an array of strings with malloc

char **orderIds;

orderIds = malloc(variableNumberOfElements * sizeof(char*));

for(int i = 0; i < variableNumberOfElements; i++) {
  orderIds[i] = malloc((ID_LEN + 1) * sizeof(char));
  strcpy(orderIds[i], your_string[i]);
}

How to properly and completely close/reset a TcpClient connection?

Use word: using. A good habit of programming.

using (TcpClient tcpClient = new TcpClient())
{
     //operations
     tcpClient.Close();
}

Getting path of captured image in Android using camera intent

Try this method to get path of original image captured by camera.

public String getOriginalImagePath() {
        String[] projection = { MediaStore.Images.Media.DATA };
        Cursor cursor = getActivity().managedQuery(
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI,
                projection, null, null, null);
        int column_index_data = cursor
                .getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToLast();

        return cursor.getString(column_index_data);
    }

This method will return path of the last image captured by camera. So this path would be of original image not of thumbnail bitmap.

MongoDB Show all contents from all collections

step 1: Enter into the MongoDB shell.

mongo

step 2: for the display all the databases.

show dbs;

step 3: for a select database :

use 'databases_name'

step 4: for statistics of your database.

db.stats()

step 5: listing out all the collections(tables).

show collections

step 6:print the data from a particular collection.

db.'collection_name'.find().pretty()

Grab a segment of an array in Java without creating a new array on heap

One way is to wrap the array in java.nio.ByteBuffer, use the absolute put/get functions, and slice the buffer to work on a subarray.

For instance:

doSomething(ByteBuffer twoBytes) {
    byte b1 = twoBytes.get(0);
    byte b2 = twoBytes.get(1);
    ...
}

void someMethod(byte[] bigArray) {
      int offset = 4;
      int length = 2;
      doSomething(ByteBuffer.wrap(bigArray, offset, length).slice());
}

Note that you have to call both wrap() and slice(), since wrap() by itself only affects the relative put/get functions, not the absolute ones.

ByteBuffer can be a bit tricky to understand, but is most likely efficiently implemented, and well worth learning.

Check number of arguments passed to a Bash script

You should add spaces between test condition:

if [ $# -ne 1 ]; 
    then echo "illegal number of parameters"
fi

I hope this helps.

How to remove a directory from git repository?

I already had committed the folder before and want to remove the directory in the history as well.

I did the following:

Add folder to .gitignore:

echo Folder_Name/ >> .gitignore

Remove from all commits:

git filter-branch --index-filter 'git rm -rf --cached --ignore-unmatch Folder_Name/' --prune-empty --tag-name-filter cat -- --all

remove the refs from the old commits:

git for-each-ref --format="%(refname)" refs/original/ | xargs -n 1 git update-ref -d

Ensure all old refs are fully removed

rm -Rf .git/logs .git/refs/original

Perform a garbage collection

git gc --prune=all --aggressive

push you changes to the online repository:

git push

You are done here.

But you can to the following to push all the changes to all branches with: But be careful with this command!

git push origin --all --force
git push origin --tags --force

After that the folder was removed from git, but was not deleted from local disk.

Extract parameter value from url using regular expressions

You almost had it, just need to escape special regex chars:

regex = /http\:\/\/www\.youtube\.com\/watch\?v=([\w-]{11})/;

url = 'http://www.youtube.com/watch?v=Ahg6qcgoay4';
id = url.match(regex)[1]; // id = 'Ahg6qcgoay4'

Edit: Fix for regex by soupagain.

Tomcat 8 Maven Plugin for Java 8

Plugin run Tomcat 7.0.47:

mvn org.apache.tomcat.maven:tomcat7-maven-plugin:2.2:run

 ...
 INFO: Starting Servlet Engine: Apache Tomcat/7.0.47

This is sample to run plugin with Tomcat 8 and Java 8: Cargo embedded tomcat: custom context.xml

MongoDb query condition on comparing 2 fields

You can use $expr ( 3.6 mongo version operator ) to use aggregation functions in regular query.

Compare query operators vs aggregation comparison operators.

Regular Query:

db.T.find({$expr:{$gt:["$Grade1", "$Grade2"]}})

Aggregation Query:

db.T.aggregate({$match:{$expr:{$gt:["$Grade1", "$Grade2"]}}})

remove duplicates from sql union

If you are using T-SQL you could use a temporary table in a stored procedure and update or insert the records of your query accordingly.

Convert row to column header for Pandas DataFrame,

You can specify the row index in the read_csv or read_html constructors via the header parameter which represents Row number(s) to use as the column names, and the start of the data. This has the advantage of automatically dropping all the preceding rows which supposedly are junk.

import pandas as pd
from io import StringIO

In[1]
    csv = '''junk1, junk2, junk3, junk4, junk5
    junk1, junk2, junk3, junk4, junk5
    pears, apples, lemons, plums, other
    40, 50, 61, 72, 85
    '''

    df = pd.read_csv(StringIO(csv), header=2)
    print(df)

Out[1]
       pears   apples   lemons   plums   other
    0     40       50       61      72      85

How do I perform a Perl substitution on a string while keeping the original?

The one-liner solution is more useful as a shibboleth than good code; good Perl coders will know it and understand it, but it's much less transparent and readable than the two-line copy-and-modify couplet you're starting with.

In other words, a good way to do this is the way you're already doing it. Unnecessary concision at the cost of readability isn't a win.

Java: get greatest common divisor

I used this method that I created when I was 14 years old.

    public static int gcd (int a, int b) {
        int s = 1;
        int ia = Math.abs(a);//<-- turns to absolute value
        int ib = Math.abs(b);
        if (a == b) {
            s = a;
        }else {
            while (ib != ia) {
                if (ib > ia) {
                    s = ib - ia;
                    ib = s;
                }else { 
                    s = ia - ib;
                    ia = s;
                }
            }
        }
        return s;
    }

How do I turn a String into a InputStreamReader in java?

ByteArrayInputStream also does the trick:

InputStream is = new ByteArrayInputStream( myString.getBytes( charset ) );

Then convert to reader:

InputStreamReader reader = new InputStreamReader(is);

CSS Font "Helvetica Neue"

You can use http://www.fontsquirrel.com/fontface/generator to encode any font for websites. It'll generate the code to include the font.

I don't really use it for fonts over 30px. They look much better as an image (because images are anti-aliased, and some browsers don't anti-alias fonts in the browser).

See: http://www.truetype-typography.com/ttalias.htm

Hope that helps...

The ResourceConfig instance does not contain any root resource classes

I had to add a trailing forward slash to the end of @path

@Path ("/admin/") 

The requested resource does not support HTTP method 'GET'

I was experiencing the same issue.. I already had 4 controllers going and working just fine but when I added this one it returned "The requested resource does not support HTTP method 'GET'". I tried everything here and in a couple other relevant articles but was indifferent to the solution since, as Dan B. mentioned in response to the answer, I already had others working fine.

I walked away for a while, came back, and immediately realized that when I added the Controller it was nested under the "Controller" class and not "ApiController" class that my other Controllers were under. I'm assuming I chose the wrong scaffolding option to build the .cs file in Visual Studio. So I included the System.Web.Http namespace, changed the parent class, and everything works without the additional attributes or routing.

How to convert List<Integer> to int[] in Java?

Java 8 has given us an easy way to do this via streams...

Using the collections stream() function and then mapping to ints, you'll get an IntStream. With the IntStream we can call toArray() which gives us int []

int [] ints = list.stream().mapToInt(Integer::intValue).toArray();

to int []

to IntStream

Can you delete data from influxdb?

You can only delete with your time field, which is a number.

Delete from <measurement> where time=123456

will work. Remember not to give single quotes or double quotes. Its a number.

How to install ADB driver for any android device?

If no other driver package worked for your obscure device go read how to make a truly universal abd and fastboot driver out of Google's USB driver. The trick is to use CompatibleID instead of HardwareID in the driver's INF Models section

How do I use sudo to redirect output to a location I don't have permission to write to?

How about writing a script?

Filename: myscript

#!/bin/sh

/bin/ls -lah /root > /root/test.out

# end script

Then use sudo to run the script:

sudo ./myscript

Cannot read property 'map' of undefined

in my case it happens when I try add types to Promise.all handler:

Promise.all([1,2]).then(([num1, num2]: [number, number])=> console.log('res', num1));

If remove : [number, number], the error is gone.

How can I change the text color with jQuery?

Or you may do the following

$(this).animate({color:'black'},1000);

But you need to download the color plugin from here.

File upload from <input type="file">

@Component({
  selector: 'my-app',
  template: `
    <div>
      <input name="file" type="file" (change)="onChange($event)"/>
    </div>
  `,
  providers: [ UploadService ]
})
export class AppComponent {
  file: File;
  onChange(event: EventTarget) {
        let eventObj: MSInputMethodContext = <MSInputMethodContext> event;
        let target: HTMLInputElement = <HTMLInputElement> eventObj.target;
        let files: FileList = target.files;
        this.file = files[0];
        console.log(this.file);
    }

   doAnythingWithFile() {
   }

}

How Big can a Python List Get?

I got this from here on a x64 bit system: Python 3.7.0b5 (v3.7.0b5:abb8802389, May 31 2018, 01:54:01) [MSC v.1913 64 bit (AMD64)] on win32

enter image description here

Count number of times value appears in particular column in MySQL

Take a look at the Group by function.

What the group by function does is pretuty much grouping the similar value for a given field. You can then show the number of number of time that this value was groupped using the COUNT function.

MySQL Documentation

You can also use the group by function with a good number of other function define by MySQL (see the above link).

mysql> SELECT student_name, AVG(test_score)
    ->        FROM student
    ->        GROUP BY student_name;

Variable name as a string in Javascript

Probably pop would be better than indexing with [0], for safety (variable might be null).

const myFirstName = 'John'
const variableName = Object.keys({myFirstName}).pop();
console.log(`Variable ${variableName} with value '${variable}'`);

// returns "Variable myFirstName with value 'John'"

How do I iterate through table rows and cells in JavaScript?

_x000D_
_x000D_
var table=document.getElementById("mytab1");_x000D_
var r=0; //start counting rows in table_x000D_
while(row=table.rows[r++])_x000D_
{_x000D_
  var c=0; //start counting columns in row_x000D_
  while(cell=row.cells[c++])_x000D_
  {_x000D_
    cell.innerHTML='[R'+r+'C'+c+']'; // do sth with cell_x000D_
  }_x000D_
}
_x000D_
<table id="mytab1">_x000D_
  <tr>_x000D_
    <td>A1</td><td>A2</td><td>A3</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>B1</td><td>B2</td><td>B3</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>C1</td><td>C2</td><td>C3</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

In each pass through while loop r/c iterator increases and new row/cell object from collection is assigned to row/cell variables. When there's no more rows/cells in collection, false is assigned to row/cell variable and iteration through while loop stops (exits).

What is the difference between Visual Studio Express 2013 for Windows and Visual Studio Express 2013 for Windows Desktop?

Visual Studio for Windows Apps is meant to be used to build Windows Store Apps using HTML & Javascript or WinRT and XAML. These can also run on the Windows tablet that run Windows RT.

Visual Studio for Windows Desktop is meant to build applications using Windows Forms or Windows Presentation Foundation, these can run on Windows 8.1 on a normal desktop or on a tablet device like the Surface Pro in desktop mode (like a classic windows application).

My kubernetes pods keep crashing with "CrashLoopBackOff" but I can't find any log

In my case, the issue was a misconstrued list of command-line arguments. I was doing this in my deployment file:

...
args:
  - "--foo 10"
  - "--bar 100"

Instead of the correct approach:

...
args:
  - "--foo"
  - "10"
  - "--bar"
  - "100"

How can I count the number of elements of a given value in a matrix?

Here's a list of all the ways I could think of to counting unique elements:

M = randi([1 7], [1500 1]);

Option 1: tabulate

t = tabulate(M);
counts1 = t(t(:,2)~=0, 2);

Option 2: hist/histc

counts2_1 = hist( M, numel(unique(M)) );
counts2_2 = histc( M, unique(M) );

Option 3: accumarray

counts3 = accumarray(M, ones(size(M)), [], @sum);
%# or simply: accumarray(M, 1);

Option 4: sort/diff

[MM idx] = unique( sort(M) );
counts4 = diff([0;idx]);

Option 5: arrayfun

counts5 = arrayfun( @(x)sum(M==x), unique(M) );

Option 6: bsxfun

counts6 = sum( bsxfun(@eq, M, unique(M)') )';

Option 7: sparse

counts7 = full(sparse(M,1,1));

How to sum a list of integers with java streams?

May this help those who have objects on the list.

If you have a list of objects and wanted to sum specific fields of this object use the below.

List<ResultSom> somList = MyUtil.getResultSom();
BigDecimal result= somList.stream().map(ResultSom::getNetto).reduce(
                                             BigDecimal.ZERO, BigDecimal::add);

Creating Dynamic button with click event in JavaScript

Wow you're close. Edits in comments:

_x000D_
_x000D_
function add(type) {_x000D_
  //Create an input type dynamically.   _x000D_
  var element = document.createElement("input");_x000D_
  //Assign different attributes to the element. _x000D_
  element.type = type;_x000D_
  element.value = type; // Really? You want the default value to be the type string?_x000D_
  element.name = type; // And the name too?_x000D_
  element.onclick = function() { // Note this is a function_x000D_
    alert("blabla");_x000D_
  };_x000D_
_x000D_
  var foo = document.getElementById("fooBar");_x000D_
  //Append the element in page (in span).  _x000D_
  foo.appendChild(element);_x000D_
}_x000D_
document.getElementById("btnAdd").onclick = function() {_x000D_
  add("text");_x000D_
};
_x000D_
<input type="button" id="btnAdd" value="Add Text Field">_x000D_
<p id="fooBar">Fields:</p>
_x000D_
_x000D_
_x000D_

Now, instead of setting the onclick property of the element, which is called "DOM0 event handling," you might consider using addEventListener (on most browsers) or attachEvent (on all but very recent Microsoft browsers) — you'll have to detect and handle both cases — as that form, called "DOM2 event handling," has more flexibility. But if you don't need multiple handlers and such, the old DOM0 way works fine.


Separately from the above: You might consider using a good JavaScript library like jQuery, Prototype, YUI, Closure, or any of several others. They smooth over browsers differences like the addEventListener / attachEvent thing, provide useful utility features, and various other things. Obviously there's nothing a library can do that you can't do without one, as the libraries are just JavaScript code. But when you use a good library with a broad user base, you get the benefit of a huge amount of work already done by other people dealing with those browsers differences, etc.

How do android screen coordinates work?

enter image description here

This image presents both orientation(Landscape/Portrait)

To get MaxX and MaxY, read on.

For Android device screen coordinates, below concept will work.

Display mdisp = getWindowManager().getDefaultDisplay();
Point mdispSize = new Point();
mdisp.getSize(mdispSize);
int maxX = mdispSize.x; 
int maxY = mdispSize.y;

EDIT:- ** **for devices supporting android api level older than 13. Can use below code.

    Display mdisp = getWindowManager().getDefaultDisplay();
    int maxX= mdisp.getWidth();
    int maxY= mdisp.getHeight();

(x,y) :-

1) (0,0) is top left corner.

2) (maxX,0) is top right corner

3) (0,maxY) is bottom left corner

4) (maxX,maxY) is bottom right corner

here maxX and maxY are screen maximum height and width in pixels, which we have retrieved in above given code.

How to get all selected values from <select multiple=multiple>?

If you have multiple select boxes with multiple='multiple' and you want to select all selected options from every dropdown then use this HTML:

<select id='Alphabets'>
    <option value="1">A</option>
    <option value="2">B</option>
    <option value="3">C</option>
</select>

<select id='Alphabets' multiple='multiple'>
    <option value="4">D</option>
    <option value="5">E</option>
    <option value="6">F</option>
</select>
<select id='Alphabets'>
    <option value="7">G</option>
    <option value="8">H</option>
    <option value="9">I</option>
</select>
<select id='Alphabets' multiple='multiple'>
    <option value="10">J</option>
    <option value="11">K</option>
    <option value="12">L</option>
</select>

JavaScript for above UI:

function show_Alphebets()
{
        var tag =document.querySelectorAll("select");        
        var values="";
        for(var i=1; i<4; i++) {
            if(tag[i].options.length>0)
            for (var option of tag[i].selectedOptions) {                  
                  values+= i+"(multiple)="+option.value+",";
            }
            else values+= i+"="+tag[i].value+",";
        }
        alert(values);
}

how to query for a list<String> in jdbctemplate

You can't use placeholders for column names, table names, data type names, or basically anything that isn't data.

How many characters in varchar(max)

See the MSDN reference table for maximum numbers/sizes.

Bytes per varchar(max), varbinary(max), xml, text, or image column: 2^31-1

There's a two-byte overhead for the column, so the actual data is 2^31-3 max bytes in length. Assuming you're using a single-byte character encoding, that's 2^31-3 characters total. (If you're using a character encoding that uses more than one byte per character, divide by the total number of bytes per character. If you're using a variable-length character encoding, all bets are off.)

SpringApplication.run main method

One more way is to extend the application (as my application was to inherit and customize the parent). It invokes the parent and its commandlinerunner automatically.

@SpringBootApplication
public class ChildApplication extends ParentApplication{
    public static void main(String[] args) {
        SpringApplication.run(ChildApplication.class, args);
    }
}

How to use the toString method in Java?

The main purpose of toString is to generate a String representation of an object, means the return value is always a String. In most cases this simply is the object's class and package name, but on some cases like StringBuilder you will got actually a String-text.

Read .csv file in C

The following code is in plain c language and handles blank spaces. It only allocates memory once, so one free() is needed, for each processed line.

http://ideone.com/mSCgPM

/* Tiny CSV Reader */
/* Copyright (C) 2015, Deligiannidis Konstantinos

This program is free software: you can redistribute it and/or modify
it under the terms of the GNU General Public License as published by
the Free Software Foundation, either version 3 of the License, or
(at your option) any later version.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program.  If not, see <http://w...content-available-to-author-only...u.org/licenses/>.  */


#include <stdio.h>
#include <string.h>
#include <stdlib.h>


/* For more that 100 columns or lines (when delimiter = \n), minor modifications are needed. */
int getcols( const char * const line, const char * const delim, char ***out_storage )

{
const char *start_ptr, *end_ptr, *iter;
char **out;
int i;                                          //For "for" loops in the old c style.
int tokens_found = 1, delim_size, line_size;    //Calculate "line_size" indirectly, without strlen() call.
int start_idx[100], end_idx[100];   //Store the indexes of tokens. Example "Power;": loc('P')=1, loc(';')=6
//Change 100 with MAX_TOKENS or use malloc() for more than 100 tokens. Example: "b1;b2;b3;...;b200"

if ( *out_storage != NULL )                 return -4;  //This SHOULD be NULL: Not Already Allocated
if ( !line || !delim )                      return -1;  //NULL pointers Rejected Here
if ( (delim_size = strlen( delim )) == 0 )  return -2;  //Delimiter not provided

start_ptr = line;   //Start visiting input. We will distinguish tokens in a single pass, for good performance.
                    //Then we are allocating one unified memory region & doing one memory copy.
while ( ( end_ptr = strstr( start_ptr, delim ) ) ) {

    start_idx[ tokens_found -1 ] = start_ptr - line;    //Store the Index of current token
    end_idx[ tokens_found - 1 ] = end_ptr - line;       //Store Index of first character that will be replaced with
                                                        //'\0'. Example: "arg1||arg2||end" -> "arg1\0|arg2\0|end"
    tokens_found++;                                     //Accumulate the count of tokens.
    start_ptr = end_ptr + delim_size;                   //Set pointer to the next c-string within the line
}

for ( iter = start_ptr; (*iter!='\0') ; iter++ );

start_idx[ tokens_found -1 ] = start_ptr - line;    //Store the Index of current token: of last token here.
end_idx[ tokens_found -1 ] = iter - line;           //and the last element that will be replaced with \0

line_size = iter - line;    //Saving CPU cycles: Indirectly Count the size of *line without using strlen();

int size_ptr_region = (1 + tokens_found)*sizeof( char* );   //The size to store pointers to c-strings + 1 (*NULL).
out = (char**) malloc( size_ptr_region + ( line_size + 1 ) + 5 );   //Fit everything there...it is all memory.
//It reserves a contiguous space for both (char**) pointers AND string region. 5 Bytes for "Out of Range" tests.
*out_storage = out;     //Update the char** pointer of the caller function.

//"Out of Range" TEST. Verify that the extra reserved characters will not be changed. Assign Some Values.
//char *extra_chars = (char*) out + size_ptr_region + ( line_size + 1 );
//extra_chars[0] = 1; extra_chars[1] = 2; extra_chars[2] = 3; extra_chars[3] = 4; extra_chars[4] = 5;

for ( i = 0; i < tokens_found; i++ )    //Assign adresses first part of the allocated memory pointers that point to
    out[ i ] = (char*) out + size_ptr_region + start_idx[ i ];  //the second part of the memory, reserved for Data.
out[ tokens_found ] = (char*) NULL; //[ ptr1, ptr2, ... , ptrN, (char*) NULL, ... ]: We just added the (char*) NULL.
                                                    //Now assign the Data: c-strings. (\0 terminated strings):
char *str_region = (char*) out + size_ptr_region;   //Region inside allocated memory which contains the String Data.
memcpy( str_region, line, line_size );   //Copy input with delimiter characters: They will be replaced with \0.

//Now we should replace: "arg1||arg2||arg3" with "arg1\0|arg2\0|arg3". Don't worry for characters after '\0'
//They are not used in standard c lbraries.
for( i = 0; i < tokens_found; i++) str_region[ end_idx[ i ] ] = '\0';

//"Out of Range" TEST. Wait until Assigned Values are Printed back.
//for ( int i=0; i < 5; i++ ) printf("c=%x ", extra_chars[i] ); printf("\n");

// *out memory should now contain (example data):
//[ ptr1, ptr2,...,ptrN, (char*) NULL, "token1\0", "token2\0",...,"tokenN\0", 5 bytes for tests ]
//   |__________________________________^           ^              ^             ^
//          |_______________________________________|              |             |
//                   |_____________________________________________|      These 5 Bytes should be intact.

return tokens_found;
}


int main()

{

char in_line[] = "Arg1;;Th;s is not Del;m;ter;;Arg3;;;;Final";
char delim[] = ";;";
char **columns;
int i;

printf("Example1:\n");
columns = NULL; //Should be NULL to indicate that it is not assigned to allocated memory. Otherwise return -4;

int cols_found = getcols( in_line, delim, &columns);
for ( i = 0; i < cols_found; i++ ) printf("Column[ %d ] = %s\n", i, columns[ i ] );  //<- (1st way).
// (2nd way) // for ( i = 0; columns[ i ]; i++) printf("start_idx[ %d ] = %s\n", i, columns[ i ] );

free( columns );    //Release the Single Contiguous Memory Space.
columns = NULL;     //Pointer = NULL to indicate it does not reserve space and that is ready for the next malloc().

printf("\n\nExample2, Nested:\n\n");

char example_file[] = "ID;Day;Month;Year;Telephone;email;Date of registration\n"
        "1;Sunday;january;2009;123-124-456;[email protected];2015-05-13\n"
        "2;Monday;March;2011;(+30)333-22-55;[email protected];2009-05-23";

char **rows;
int j;

rows = NULL; //getcols() requires it to be NULL. (Avoid dangling pointers, leaks e.t.c).

getcols( example_file, "\n", &rows);
for ( i = 0; rows[ i ]; i++) {
    {
        printf("Line[ %d ] = %s\n", i, rows[ i ] );
        char **columnX = NULL;
        getcols( rows[ i ], ";", &columnX);
        for ( j = 0; columnX[ j ]; j++) printf("  Col[ %d ] = %s\n", j, columnX[ j ] );
        free( columnX );
    }
}

free( rows );
rows = NULL;

return 0;
}

Can I recover a branch after its deletion in Git?

If you like to use a GUI, you can perform the entire operation with gitk.

gitk --reflog

This will allow you to see the branch's commit history as if the branch hadn't been deleted. Now simply right click on the most recent commit to the branch and select the menu option Create new branch.

Download a working local copy of a webpage

wget is capable of doing what you are asking. Just try the following:

wget -p -k http://www.example.com/

The -p will get you all the required elements to view the site correctly (css, images, etc). The -k will change all links (to include those for CSS & images) to allow you to view the page offline as it appeared online.

From the Wget docs:

‘-k’
‘--convert-links’
After the download is complete, convert the links in the document to make them
suitable for local viewing. This affects not only the visible hyperlinks, but
any part of the document that links to external content, such as embedded images,
links to style sheets, hyperlinks to non-html content, etc.

Each link will be changed in one of the two ways:

    The links to files that have been downloaded by Wget will be changed to refer
    to the file they point to as a relative link.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif, also
    downloaded, then the link in doc.html will be modified to point to
    ‘../bar/img.gif’. This kind of transformation works reliably for arbitrary
    combinations of directories.

    The links to files that have not been downloaded by Wget will be changed to
    include host name and absolute path of the location they point to.

    Example: if the downloaded file /foo/doc.html links to /bar/img.gif (or to
    ../bar/img.gif), then the link in doc.html will be modified to point to
    http://hostname/bar/img.gif. 

Because of this, local browsing works reliably: if a linked file was downloaded,
the link will refer to its local name; if it was not downloaded, the link will
refer to its full Internet address rather than presenting a broken link. The fact
that the former links are converted to relative links ensures that you can move
the downloaded hierarchy to another directory.

Note that only at the end of the download can Wget know which links have been
downloaded. Because of that, the work done by ‘-k’ will be performed at the end
of all the downloads. 

How to disable Compatibility View in IE

Another way to achieve this in Apache is by putting the following lines in .htaccess in the root folder of your website (or in Apache's config files).

BrowserMatch "MSIE" isIE
BrowserMatch "Trident" isIE
Header set X-UA-Compatible "IE=edge" env=isIE

This requires that you have the mod_headers and mod_setenvif modules enabled.

The extra HTTP header only gets sent to IE browsers, and none of the others.

Calling Javascript from a html form

Remove javascript: from onclick=".., onsubmit=".. declarations

javascript: prefix is used only in href="" or similar attributes (not events related)

How to select the first row of each group?

This is a exact same of zero323's answer but in SQL query way.

Assuming that dataframe is created and registered as

df.createOrReplaceTempView("table")
//+----+--------+----------+
//|Hour|Category|TotalValue|
//+----+--------+----------+
//|0   |cat26   |30.9      |
//|0   |cat13   |22.1      |
//|0   |cat95   |19.6      |
//|0   |cat105  |1.3       |
//|1   |cat67   |28.5      |
//|1   |cat4    |26.8      |
//|1   |cat13   |12.6      |
//|1   |cat23   |5.3       |
//|2   |cat56   |39.6      |
//|2   |cat40   |29.7      |
//|2   |cat187  |27.9      |
//|2   |cat68   |9.8       |
//|3   |cat8    |35.6      |
//+----+--------+----------+

Window function :

sqlContext.sql("select Hour, Category, TotalValue from (select *, row_number() OVER (PARTITION BY Hour ORDER BY TotalValue DESC) as rn  FROM table) tmp where rn = 1").show(false)
//+----+--------+----------+
//|Hour|Category|TotalValue|
//+----+--------+----------+
//|1   |cat67   |28.5      |
//|3   |cat8    |35.6      |
//|2   |cat56   |39.6      |
//|0   |cat26   |30.9      |
//+----+--------+----------+

Plain SQL aggregation followed by join:

sqlContext.sql("select Hour, first(Category) as Category, first(TotalValue) as TotalValue from " +
  "(select Hour, Category, TotalValue from table tmp1 " +
  "join " +
  "(select Hour as max_hour, max(TotalValue) as max_value from table group by Hour) tmp2 " +
  "on " +
  "tmp1.Hour = tmp2.max_hour and tmp1.TotalValue = tmp2.max_value) tmp3 " +
  "group by tmp3.Hour")
  .show(false)
//+----+--------+----------+
//|Hour|Category|TotalValue|
//+----+--------+----------+
//|1   |cat67   |28.5      |
//|3   |cat8    |35.6      |
//|2   |cat56   |39.6      |
//|0   |cat26   |30.9      |
//+----+--------+----------+

Using ordering over structs:

sqlContext.sql("select Hour, vs.Category, vs.TotalValue from (select Hour, max(struct(TotalValue, Category)) as vs from table group by Hour)").show(false)
//+----+--------+----------+
//|Hour|Category|TotalValue|
//+----+--------+----------+
//|1   |cat67   |28.5      |
//|3   |cat8    |35.6      |
//|2   |cat56   |39.6      |
//|0   |cat26   |30.9      |
//+----+--------+----------+

DataSets way and don't dos are same as in original answer

How to save a spark DataFrame as csv on disk?

Apache Spark does not support native CSV output on disk.

You have four available solutions though:

  1. You can convert your Dataframe into an RDD :

    def convertToReadableString(r : Row) = ???
    df.rdd.map{ convertToReadableString }.saveAsTextFile(filepath)
    

    This will create a folder filepath. Under the file path, you'll find partitions files (e.g part-000*)

    What I usually do if I want to append all the partitions into a big CSV is

    cat filePath/part* > mycsvfile.csv
    

    Some will use coalesce(1,false) to create one partition from the RDD. It's usually a bad practice, since it may overwhelm the driver by pulling all the data you are collecting to it.

    Note that df.rdd will return an RDD[Row].

  2. With Spark <2, you can use databricks spark-csv library:

    • Spark 1.4+:

      df.write.format("com.databricks.spark.csv").save(filepath)
      
    • Spark 1.3:

      df.save(filepath,"com.databricks.spark.csv")
      
  3. With Spark 2.x the spark-csv package is not needed as it's included in Spark.

    df.write.format("csv").save(filepath)
    
  4. You can convert to local Pandas data frame and use to_csv method (PySpark only).

Note: Solutions 1, 2 and 3 will result in CSV format files (part-*) generated by the underlying Hadoop API that Spark calls when you invoke save. You will have one part- file per partition.

Converting string format to datetime in mm/dd/yyyy

Solution

DateTime.Now.ToString("MM/dd/yyyy", CultureInfo.InvariantCulture)

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

don't give this in file input value="123".

  $(document).ready(function(){  

      var img = $('#uploadPicture').val();

  });

git diff between two different files

If you are using tortoise git you can right-click on a file and git a diff by: Right-clicking on the first file and through the tortoisegit submenu select "Diff later" Then on the second file you can also right-click on this, go to the tortoisegit submenu and then select "Diff with yourfilenamehere.txt"

SQL Server 2008 can't login with newly created user

Login to Server as Admin

Go To Security > Logins > New Login

Step 1:

Login Name : SomeName

Step 2:

Select  SQL Server / Windows Authentication.

More Info on, what is the differences between sql server authentication and windows authentication..?

Choose Default DB and Language of your choice

Click OK

Try to connect with the New User Credentials, It will prompt you to change the password. Change and login

OR

Try with query :

USE [master] -- Default DB
GO

CREATE LOGIN [Username] WITH PASSWORD=N'123456', DEFAULT_DATABASE=[master], DEFAULT_LANGUAGE=[us_english], CHECK_EXPIRATION=ON, CHECK_POLICY=ON
GO

--123456 is the Password And Username is Login User 
ALTER LOGIN [Username] enable -- Enable or to Disable User
GO