Programs & Examples On #Swfupload

A JavaScript/Flash library for uploading files to a server

How to sort alphabetically while ignoring case sensitive?

I can't believe no one made a reference to the Collator. Almost all of these answers will only work for the English language.

You should almost always use a Collator for dictionary based sorting.

For case insensitive collator searching for the English language you do the following:

Collator usCollator = Collator.getInstance(Locale.US);
usCollator.setStrength(Collator.PRIMARY);
Collections.sort(listToSort, usCollator);

Why does scanf() need "%lf" for doubles, when printf() is okay with just "%f"?

Because otherwise scanf will think you are passing a pointer to a float which is a smaller size than a double, and it will return an incorrect value.

How can I get a web site's favicon?

You can get the favicon URL from the website's HTML.

Here is the favicon element:

<link rel="icon" type="image/png" href="/someimage.png" />

You should use a regular expression here. If no tag found, look for favicon.ico in the site root directory. If nothing found, the site does not have a favicon.

How to show/hide if variable is null

<div ng-hide="myvar == null"></div>

or

<div ng-show="myvar != null"></div>

Easiest way to read/write a file's content in Python

Slow, ugly, platform-specific... but one-liner ;-)

import subprocess

contents = subprocess.Popen('cat %s' % filename, shell = True, stdout = subprocess.PIPE).communicate()[0]

Check existence of directory and create if doesn't exist

I know this question was asked a while ago, but in case useful, the here package is really helpful for not having to reference specific file paths and making code more portable. It will automatically define your working directory as the one that your .Rproj file resides in, so the following will often suffice without having to define the file path to your working directory:

library(here)

if (!dir.exists(here(outputDir))) {dir.create(here(outputDir))}

Get all parameters from JSP page

localhost:8080/esccapp/tst/submit.jsp?key=datr&key2=datr2&key3=datr3

    <%@page import="java.util.Enumeration"%>

    <%
    Enumeration in = request.getParameterNames();
    while(in.hasMoreElements()) {
     String paramName = in.nextElement().toString();
     out.println(paramName + " = " + request.getParameter(paramName)+"<br>");
    }
    %>

    key = datr
    key2 = datr2
    key3 = datr3

open a url on click of ok button in android

create an intent and set an action for it while passing the url to the intent

yourbtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                String theurl = "http://google.com";
                Uri urlstr = Uri.parse(theurl);
                Intent urlintent = new Intent();
                urlintent.setData(urlstr);
                urlintent.setAction(Intent.ACTION_VIEW);
                startActivity(urlintent);

Change x axes scale in matplotlib

The scalar formatter supports collecting the exponents. The docs are as follows:

class matplotlib.ticker.ScalarFormatter(useOffset=True, useMathText=False, useLocale=None) Bases: matplotlib.ticker.Formatter

Tick location is a plain old number. If useOffset==True and the data range is much smaller than the data average, then an offset will be determined such that the tick labels are meaningful. Scientific notation is used for data < 10^-n or data >= 10^m, where n and m are the power limits set using set_powerlimits((n,m)). The defaults for these are controlled by the axes.formatter.limits rc parameter.

your technique would be:

from matplotlib.ticker import ScalarFormatter
xfmt = ScalarFormatter()
xfmt.set_powerlimits((-3,3))  # Or whatever your limits are . . .
{{ Make your plot }}
gca().xaxis.set_major_formatter(xfmt)

To get the exponent displayed in the format x10^5, instantiate the ScalarFormatter with useMathText=True.

After Image

You could also use:

xfmt.set_useOffset(10000)

To get a result like this:

enter image description here

Dealing with "Xerces hell" in Java/Maven?

Every maven project should stop depending on xerces, they probably don't really. XML APIs and an Impl has been part of Java since 1.4. There is no need to depend on xerces or XML APIs, its like saying you depend on Java or Swing. This is implicit.

If I was boss of a maven repo I'd write a script to recursively remove xerces dependencies and write a read me that says this repo requires Java 1.4.

Anything that actually breaks because it references Xerces directly via org.apache imports needs a code fix to bring it up to Java 1.4 level (and has done since 2002) or solution at JVM level via endorsed libs, not in maven.

Why does the Google Play store say my Android app is incompatible with my own device?

To give an extra solution to the above 'This app is incompatible with your...' problem, let me share my solution for a different problem cause. I tried installing an app on a low-end Samsung Galaxy Y (GT-S6350) device and got this error from the Play store. To test various AndroidManifest configurations, I created an account and followed the routine as described in https://stackoverflow.com/a/5449397/372838 until my device showed up in the supported device list.

It turned out that a lot of devices become incompatible when you use the Camera permission:

<uses-permission android:name="android.permission.CAMERA" />

When I removed that specific permission, the application was available for 1180 devices instead of 870. Hope it will help someone

How do I create dynamic variable names inside a loop?

Try this

window['marker'+i] = "some stuff"; 

Invoking a PHP script from a MySQL trigger

A cronjob could monitor this log and based on events created by your trigger it could invoke a php script. That is if you absolutely have no control over you insertion.. If you have transaction logs in you MySQL, you can create a trigger for purpose of a log instance creation.

Gridview row editing - dynamic binding to a DropDownList

The checked answer from balexandre works great. But, it will create a problem if adapted to some other situations.

I used it to change the value of two label controls - lblEditModifiedBy and lblEditModifiedOn - when I was editing a row, so that the correct ModifiedBy and ModifiedOn would be saved to the db on 'Update'.

When I clicked the 'Update' button, in the RowUpdating event it showed the new values I entered in the OldValues list. I needed the true "old values" as Original_ values when updating the database. (There's an ObjectDataSource attached to the GridView.)

The fix to this is using balexandre's code, but in a modified form in the gv_DataBound event:

protected void gv_DataBound(object sender, EventArgs e)
{
    foreach (GridViewRow gvr in gv.Rows)
    {
        if (gvr.RowType == DataControlRowType.DataRow && (gvr.RowState & DataControlRowState.Edit) == DataControlRowState.Edit)
        {
            // Here you will get the Control you need like:
            ((Label)gvr.FindControl("lblEditModifiedBy")).Text = Page.User.Identity.Name;
            ((Label)gvr.FindControl("lblEditModifiedOn")).Text = DateTime.Now.ToString();
        }
    }
}

How do you get the length of a string?

You don't need to use jquery.

var myString = 'abc';
var n = myString.length;

n will be 3.

Add leading zeroes to number in Java?

Another option is to use DecimalFormat to format your numeric String. Here is one other way to do the job without having to use String.format if you are stuck in the pre 1.5 world:

static String intToString(int num, int digits) {
    assert digits > 0 : "Invalid number of digits";

    // create variable length array of zeros
    char[] zeros = new char[digits];
    Arrays.fill(zeros, '0');
    // format number as String
    DecimalFormat df = new DecimalFormat(String.valueOf(zeros));

    return df.format(num);
}

Excel Formula: Count cells where value is date

Here's one approach. Using a combination of the answers above do the following:

  1. Convert cell to text using a predefined format
  2. Try using DATEVALUE to convert it back to a date
  3. Exclude any cells where DATEVALUE returns an error

As a formula, just use the example below with <> replaced with your range reference.

=SUM(IF(ISERROR(DATEVALUE(TEXT(<<RANGE HERE>>, "MM/dd/yyyy"))), 0, 1))

You must enter this as an array formula with CTRL + SHIFT + ENTER.

What is the difference between int, Int16, Int32 and Int64?

They tell what size can be stored in a integer variable. To remember the size you can think in terms of :-) 2 beer( 2 bytes) , 4 beer(4 bytes) or 8 beer( 8 bytes).

  • Int16 :-2 beers/bytes = 16 bit = 2^16 = 65536 = 65536/2 = -32768 to 32767

  • Int32 :- 4 beers/bytes = 32 bit = 2^32 = 4294967296 = 4294967296/2 = -2147483648 to 2147483647

  • Int64 :- 8 beer/ bytes = 64 bit = 2^64 = 18446744073709551616 = 18446744073709551616 /2 = -9223372036854775808 to 9223372036854775807

In short you can store more than 32767 value in int16 , more than 2147483647 value in int32 and more than 9223372036854775807 value in int64.

To understand above calculation you can check out this video int16 vs int32 vs int64

int16vsint32vsint64

Is Task.Result the same as .GetAwaiter.GetResult()?

As already mentioned if you can use await. If you need to run the code synchronously like you mention .GetAwaiter().GetResult(), .Result or .Wait() is a risk for deadlocks as many have said in comments/answers. Since most of us like oneliners you can use these for .Net 4.5<

Acquiring a value via an async method:

var result = Task.Run(() => asyncGetValue()).Result;

Syncronously calling an async method

Task.Run(() => asyncMethod()).Wait();

No deadlock issues will occur due to the use of Task.Run.

Source:

https://stackoverflow.com/a/32429753/3850405

Update:

Could cause a deadlock if the calling thread is from the threadpool. The following happens: A new task is queued to the end of the queue, and the threadpool thread which would eventually execute the Task is blocked until the Task is executed.

Source:

https://medium.com/rubrikkgroup/understanding-async-avoiding-deadlocks-e41f8f2c6f5d

Java Garbage Collection Log messages

  1. PSYoungGen refers to the garbage collector in use for the minor collection. PS stands for Parallel Scavenge.
  2. The first set of numbers are the before/after sizes of the young generation and the second set are for the entire heap. (Diagnosing a Garbage Collection problem details the format)
  3. The name indicates the generation and collector in question, the second set are for the entire heap.

An example of an associated full GC also shows the collectors used for the old and permanent generations:

3.757: [Full GC [PSYoungGen: 2672K->0K(35584K)] 
            [ParOldGen: 3225K->5735K(43712K)] 5898K->5735K(79296K) 
            [PSPermGen: 13533K->13516K(27584K)], 0.0860402 secs]

Finally, breaking down one line of your example log output:

8109.128: [GC [PSYoungGen: 109884K->14201K(139904K)] 691015K->595332K(1119040K), 0.0454530 secs]
  • 107Mb used before GC, 14Mb used after GC, max young generation size 137Mb
  • 675Mb heap used before GC, 581Mb heap used after GC, 1Gb max heap size
  • minor GC occurred 8109.128 seconds since the start of the JVM and took 0.04 seconds

Allow only numbers to be typed in a textbox

With HTML5 you can do

<input type="number">

You can also use a regex pattern to limit the input text.

<input type="text" pattern="^[0-9]*$" />

wordpress contactform7 textarea cols and rows change in smaller screens

In the documentaion http://contactform7.com/text-fields/#textarea

[textarea* message id:contact-message 10x2 placeholder "Your Message"]

The above will generate a textarea with cols="10" and rows="2"

<textarea name="message" cols="10" rows="2" class="wpcf7-form-control wpcf7-textarea wpcf7-validates-as-required" id="contact-message" aria-required="true" aria-invalid="false" placeholder="Your Message"></textarea>

How to build minified and uncompressed bundle with webpack?

Maybe i am late here, but i have the same issue, so i wrote a unminified-webpack-plugin for this purpose.

Installation

npm install --save-dev unminified-webpack-plugin

Usage

var path = require('path');
var webpack = require('webpack');
var UnminifiedWebpackPlugin = require('unminified-webpack-plugin');

module.exports = {
    entry: {
        index: './src/index.js'
    },
    output: {
        path: path.resolve(__dirname, 'dist'),
        filename: 'library.min.js'
    },
    plugins: [
        new webpack.optimize.UglifyJsPlugin({
            compress: {
                warnings: false
            }
        }),
        new UnminifiedWebpackPlugin()
    ]
};

By doing as above, you will get two files library.min.js and library.js. No need execute webpack twice, it just works!^^

Check if an apt-get package is installed and then install it if it's not on Linux

This feature already exists in Ubuntu and Debian, in the command-not-found package.

"Repository does not have a release file" error

I have been having this issue for a couple of weeks and finally decided to sit down and try and fix it. I have no interest in config file editing as I'm primarily a Windows user.

In a fit of "clickyness" I noticed that the ubuntu server location was set "for United kingdom". I switched this over to "Main Server" and hey presto... it all stared updating.

So, it seems like the regionalised server (for the UK at least) has a very limited support window so if you are an infrequent user it is likely it will not have a valid upgrade path from your current version to the latest.

Edit: I only just noticted the previous reply, after posting. 100% agree.

How do you concatenate Lists in C#?

It also worth noting that Concat works in constant time and in constant memory. For example, the following code

        long boundary = 60000000;
        for (long i = 0; i < boundary; i++)
        {
            list1.Add(i);
            list2.Add(i);
        }
        var listConcat = list1.Concat(list2);
        var list = listConcat.ToList();
        list1.AddRange(list2);

gives the following timing/memory metrics:

After lists filled mem used: 1048730 KB
concat two enumerables: 00:00:00.0023309 mem used: 1048730 KB
convert concat to list: 00:00:03.7430633 mem used: 2097307 KB
list1.AddRange(list2) : 00:00:00.8439870 mem used: 2621595 KB

What are Transient and Volatile Modifiers?

Transient :

First need to know where it needed how it bridge the gap.

1) An Access modifier transient is only applicable to variable component only. It will not used with method or class.

2) Transient keyword cannot be used along with static keyword.

3) What is serialization and where it is used? Serialization is the process of making the object's state persistent. That means the state of the object is converted into a stream of bytes to be used for persisting (e.g. storing bytes in a file) or transferring (e.g. sending bytes across a network). In the same way, we can use the deserialization to bring back the object's state from bytes. This is one of the important concepts in Java programming because serialization is mostly used in networking programming. The objects that need to be transmitted through the network have to be converted into bytes. Before understanding the transient keyword, one has to understand the concept of serialization. If the reader knows about serialization, please skip the first point.

Note 1) Transient is mainly use for serialzation process. For that the class must implement the java.io.Serializable interface. All of the fields in the class must be serializable. If a field is not serializable, it must be marked transient.

Note 2) When deserialized process taken place they get set to the default value - zero, false, or null as per type constraint.

Note 3) Transient keyword and its purpose? A field which is declare with transient modifier it will not take part in serialized process. When an object is serialized(saved in any state), the values of its transient fields are ignored in the serial representation, while the field other than transient fields will take part in serialization process. That is the main purpose of the transient keyword.

python : list index out of range error while iteratively popping elements

The expression len(l) is evaluated only one time, at the moment the range() builtin is evaluated. The range object constructed at that time does not change; it can't possibly know anything about the object l.

P.S. l is a lousy name for a value! It looks like the numeral 1, or the capital letter I.

Difference between "enqueue" and "dequeue"

These are terms usually used when describing a "FIFO" queue, that is "first in, first out". This works like a line. You decide to go to the movies. There is a long line to buy tickets, you decide to get into the queue to buy tickets, that is "Enqueue". at some point you are at the front of the line, and you get to buy a ticket, at which point you leave the line, that is "Dequeue".

Logical operators for boolean indexing in Pandas

Logical operators for boolean indexing in Pandas

It's important to realize that you cannot use any of the Python logical operators (and, or or not) on pandas.Series or pandas.DataFrames (similarly you cannot use them on numpy.arrays with more than one element). The reason why you cannot use those is because they implicitly call bool on their operands which throws an Exception because these data structures decided that the boolean of an array is ambiguous:

>>> import numpy as np
>>> import pandas as pd
>>> arr = np.array([1,2,3])
>>> s = pd.Series([1,2,3])
>>> df = pd.DataFrame([1,2,3])
>>> bool(arr)
ValueError: The truth value of an array with more than one element is ambiguous. Use a.any() or a.all()
>>> bool(s)
ValueError: The truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().
>>> bool(df)
ValueError: The truth value of a DataFrame is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all().

I did cover this more extensively in my answer to the "Truth value of a Series is ambiguous. Use a.empty, a.bool(), a.item(), a.any() or a.all()" Q+A.

NumPys logical functions

However NumPy provides element-wise operating equivalents to these operators as functions that can be used on numpy.array, pandas.Series, pandas.DataFrame, or any other (conforming) numpy.array subclass:

So, essentially, one should use (assuming df1 and df2 are pandas DataFrames):

np.logical_and(df1, df2)
np.logical_or(df1, df2)
np.logical_not(df1)
np.logical_xor(df1, df2)

Bitwise functions and bitwise operators for booleans

However in case you have boolean NumPy array, pandas Series, or pandas DataFrames you could also use the element-wise bitwise functions (for booleans they are - or at least should be - indistinguishable from the logical functions):

Typically the operators are used. However when combined with comparison operators one has to remember to wrap the comparison in parenthesis because the bitwise operators have a higher precedence than the comparison operators:

(df1 < 10) | (df2 > 10)  # instead of the wrong df1 < 10 | df2 > 10

This may be irritating because the Python logical operators have a lower precendence than the comparison operators so you normally write a < 10 and b > 10 (where a and b are for example simple integers) and don't need the parenthesis.

Differences between logical and bitwise operations (on non-booleans)

It is really important to stress that bit and logical operations are only equivalent for boolean NumPy arrays (and boolean Series & DataFrames). If these don't contain booleans then the operations will give different results. I'll include examples using NumPy arrays but the results will be similar for the pandas data structures:

>>> import numpy as np
>>> a1 = np.array([0, 0, 1, 1])
>>> a2 = np.array([0, 1, 0, 1])

>>> np.logical_and(a1, a2)
array([False, False, False,  True])
>>> np.bitwise_and(a1, a2)
array([0, 0, 0, 1], dtype=int32)

And since NumPy (and similarly pandas) does different things for boolean (Boolean or “mask” index arrays) and integer (Index arrays) indices the results of indexing will be also be different:

>>> a3 = np.array([1, 2, 3, 4])

>>> a3[np.logical_and(a1, a2)]
array([4])
>>> a3[np.bitwise_and(a1, a2)]
array([1, 1, 1, 2])

Summary table

Logical operator | NumPy logical function | NumPy bitwise function | Bitwise operator
-------------------------------------------------------------------------------------
       and       |  np.logical_and        | np.bitwise_and         |        &
-------------------------------------------------------------------------------------
       or        |  np.logical_or         | np.bitwise_or          |        |
-------------------------------------------------------------------------------------
                 |  np.logical_xor        | np.bitwise_xor         |        ^
-------------------------------------------------------------------------------------
       not       |  np.logical_not        | np.invert              |        ~

Where the logical operator does not work for NumPy arrays, pandas Series, and pandas DataFrames. The others work on these data structures (and plain Python objects) and work element-wise. However be careful with the bitwise invert on plain Python bools because the bool will be interpreted as integers in this context (for example ~False returns -1 and ~True returns -2).

How to justify a single flexbox item (override justify-content)

For those situations where width of the items you do want to flex-end is known, you can set their flex to "0 0 ##px" and set the item you want to flex-start with flex:1

This will cause the pseudo flex-start item to fill the container, just format it to text-align:left or whatever.

Is it possible to pull just one file in Git?

git checkout master -- myplugin.js

master = branch name

myplugin.js = file name

jQuery position DIV fixed at top on scroll

instead of doing it like that, why not just make the flyout position:fixed, top:0; left:0; once your window has scrolled pass a certain height:

jQuery

  $(window).scroll(function(){
      if ($(this).scrollTop() > 135) {
          $('#task_flyout').addClass('fixed');
      } else {
          $('#task_flyout').removeClass('fixed');
      }
  });

css

.fixed {position:fixed; top:0; left:0;}

Example

Excel VBA - How to Redim a 2D array?

You could do this array(0)= array(0,1,2,3).

Sub add_new(data_array() As Variant, new_data() As Variant)
    Dim ar2() As Variant, fl As Integer
    If Not (isEmpty(data_array)) = True Then
        fl = 0
    Else
        fl = UBound(data_array) + 1
    End If
    ReDim Preserve data_array(fl)
    data_array(fl) = new_data
End Sub

Sub demo()
    Dim dt() As Variant, nw(0, 1) As Variant
    nw(0, 0) = "Hi"
    nw(0, 1) = "Bye"
    Call add_new(dt, nw)
    nw(0, 0) = "Good"
    nw(0, 1) = "Bad"
    Call add_new(dt, nw)
End Sub

Set environment variables on Mac OS X Lion

Let me illustrate you from my personal example in a very redundant way.

  1. First after installing JDK, make sure it's installed. enter image description here
  2. Sometimes macOS or Linux automatically sets up environment variable for you unlike Windows. But that's not the case always. So let's check it. enter image description here The line immediately after echo $JAVA_HOME would be empty if the environment variable is not set. It must be empty in your case.

  3. Now we need to check if we have bash_profile file. enter image description here You saw that in my case we already have bash_profile. If not we have to create a bash_profile file.

  4. Create a bash_profile file. enter image description here

  5. Check again to make sure bash_profile file is there. enter image description here

  6. Now let's open bash_profile file. macOS opens it using it's default TextEdit program. enter image description here

  7. This is the file where environment variables are kept. If you have opened a new bash_profile file, it must be empty. In my case, it was already set for python programming language and Anaconda distribution. Now, i need to add environment variable for Java which is just adding the first line. YOU MUST TYPE the first line VERBATIM. JUST the first line. Save and close the TextEdit. Then close the terminal. enter image description here

  8. Open the terminal again. Let's check if the environment variable is set up. enter image description here

How do I get into a Docker container's shell?

To bash into a running container, type this:

docker exec -t -i container_name /bin/bash

or

docker exec -ti container_name /bin/bash

or

docker exec -ti container_name sh

Adding gif image in an ImageView in android

Use Webview to load gif like as

webView = (WebView) findViewById(R.id.webView);
webView.setScrollBarStyle(View.SCROLLBARS_INSIDE_OVERLAY);
webView.getSettings().setLoadsImagesAutomatically(true);
webView.getSettings().setJavaScriptEnabled(true);
webView.loadUrl("file:///android_asset/1.gif");

surface plots in matplotlib

I just came across this same problem. I have evenly spaced data that is in 3 1-D arrays instead of the 2-D arrays that matplotlib's plot_surface wants. My data happened to be in a pandas.DataFrame so here is the matplotlib.plot_surface example with the modifications to plot 3 1-D arrays.

from mpl_toolkits.mplot3d import Axes3D
from matplotlib import cm
from matplotlib.ticker import LinearLocator, FormatStrFormatter
import matplotlib.pyplot as plt
import numpy as np

X = np.arange(-5, 5, 0.25)
Y = np.arange(-5, 5, 0.25)
X, Y = np.meshgrid(X, Y)
R = np.sqrt(X**2 + Y**2)
Z = np.sin(R)

fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(X, Y, Z, rstride=1, cstride=1, cmap=cm.coolwarm,
    linewidth=0, antialiased=False)
ax.set_zlim(-1.01, 1.01)

ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

fig.colorbar(surf, shrink=0.5, aspect=5)
plt.title('Original Code')

That is the original example. Adding this next bit on creates the same plot from 3 1-D arrays.

# ~~~~ MODIFICATION TO EXAMPLE BEGINS HERE ~~~~ #
import pandas as pd
from scipy.interpolate import griddata
# create 1D-arrays from the 2D-arrays
x = X.reshape(1600)
y = Y.reshape(1600)
z = Z.reshape(1600)
xyz = {'x': x, 'y': y, 'z': z}

# put the data into a pandas DataFrame (this is what my data looks like)
df = pd.DataFrame(xyz, index=range(len(xyz['x']))) 

# re-create the 2D-arrays
x1 = np.linspace(df['x'].min(), df['x'].max(), len(df['x'].unique()))
y1 = np.linspace(df['y'].min(), df['y'].max(), len(df['y'].unique()))
x2, y2 = np.meshgrid(x1, y1)
z2 = griddata((df['x'], df['y']), df['z'], (x2, y2), method='cubic')

fig = plt.figure()
ax = fig.gca(projection='3d')
surf = ax.plot_surface(x2, y2, z2, rstride=1, cstride=1, cmap=cm.coolwarm,
    linewidth=0, antialiased=False)
ax.set_zlim(-1.01, 1.01)

ax.zaxis.set_major_locator(LinearLocator(10))
ax.zaxis.set_major_formatter(FormatStrFormatter('%.02f'))

fig.colorbar(surf, shrink=0.5, aspect=5)
plt.title('Meshgrid Created from 3 1D Arrays')
# ~~~~ MODIFICATION TO EXAMPLE ENDS HERE ~~~~ #

plt.show()

Here are the resulting figures:

enter image description here enter image description here

how to toggle attr() in jquery

$('.list-toggle').click(function() {
    var $listSort = $('.list-sort');
    if ($listSort.attr('colspan')) {
        $listSort.removeAttr('colspan');
    } else {
        $listSort.attr('colspan', 6);
    }
});

Here's a working fiddle example.

See the answer by @RienNeVaPlus below for a more elegant solution.

Breaking out of nested loops

Sometimes I use a boolean variable. Naive, if you want, but I find it quite flexible and comfortable to read. Testing a variable may avoid testing again complex conditions and may also collect results from several tests in inner loops.

    x_loop_must_break = False
    for x in range(10):
        for y in range(10):
            print x*y
            if x*y > 50:
                x_loop_must_break = True
                break
        if x_loop_must_break: break

Android studio Gradle icon error, Manifest Merger

In your .gradle change MinSDK, for example:

  • build.gradle (Module: app)
    • before: minSdkVersion 9
    • after: minSdkVersion 14

etc.

Radio buttons not checked in jQuery

This works too. It seems shortest working notation: !$('#selector:checked')

SQLAlchemy insert or update example

assuming certain column names...

INSERT one

newToner = Toner(toner_id = 1,
                    toner_color = 'blue',
                    toner_hex = '#0F85FF')

dbsession.add(newToner)   
dbsession.commit()

INSERT multiple

newToner1 = Toner(toner_id = 1,
                    toner_color = 'blue',
                    toner_hex = '#0F85FF')

newToner2 = Toner(toner_id = 2,
                    toner_color = 'red',
                    toner_hex = '#F01731')

dbsession.add_all([newToner1, newToner2])   
dbsession.commit()

UPDATE

q = dbsession.query(Toner)
q = q.filter(Toner.toner_id==1)
record = q.one()
record.toner_color = 'Azure Radiance'

dbsession.commit()

or using a fancy one-liner using MERGE

record = dbsession.merge(Toner( **kwargs))

ValidateAntiForgeryToken purpose, explanation and example

MVC's anti-forgery support writes a unique value to an HTTP-only cookie and then the same value is written to the form. When the page is submitted, an error is raised if the cookie value doesn't match the form value.

It's important to note that the feature prevents cross site request forgeries. That is, a form from another site that posts to your site in an attempt to submit hidden content using an authenticated user's credentials. The attack involves tricking the logged in user into submitting a form, or by simply programmatically triggering a form when the page loads.

The feature doesn't prevent any other type of data forgery or tampering based attacks.

To use it, decorate the action method or controller with the ValidateAntiForgeryToken attribute and place a call to @Html.AntiForgeryToken() in the forms posting to the method.

OpenJDK8 for windows

Go to this link

Download version tar.gz for windows and just extract files to the folder by your needs. On the left pane, you can select which version of openjdk to download

Tutorial: unzip as expected. You need to set system variable PATH to include your directory with openjdk so you can type java -version in console.

JDK vs OpenJDK

How to move/rename a file using an Ansible task on a remote system

This is the way I got it working for me:

  Tasks:
  - name: checking if the file 1 exists
     stat:      
      path: /path/to/foo abc.xts
     register: stat_result

  - name: moving file 1
    command: mv /path/to/foo abc.xts /tmp
    when: stat_result.stat.exists == True

the playbook above, will check if file abc.xts exists before move the file to tmp folder.

Import Error: No module named numpy

I had this problem too after I installed Numpy. I solved it by just closing the Python interpreter and reopening. It may be something else to try if anyone else has this problem, perhaps it will save a few minutes!

Can a JSON value contain a multiline string

I'm not sure of your exact requirement but one possible solution to improve 'readability' is to store it as an array.

{
  "testCases" :
  {
    "case.1" :
    {
      "scenario" : "this the case 1.",
      "result" : ["this is a very long line which is not easily readble.",
                  "so i would like to write it in multiple lines.",
                  "but, i do NOT require any new lines in the output."]
    }
  }
}

}

The join in back again whenever required with

result.join(" ")

Why would I use dirname(__FILE__) in an include or include_once statement?

If you want code is running on multiple servers with different environments,then we have need to use dirname(FILE) in an include or include_once statement. reason is follows. 1. Do not give absolute path to include files on your server. 2. Dynamically calculate the full path like absolute path.

Use a combination of dirname(FILE) and subsequent calls to itself until you reach to the home of your '/myfile.php'. Then attach this variable that contains the path to your included files.

define() vs. const

No one says anything about php-doc, but for me that is also a very significant argument for the preference of const:

/**
 * My foo-bar const
 * @var string
 */
const FOO = 'BAR';

php.ini & SMTP= - how do you pass username & password

  1. Install the latest hMailServer. "Run hMailServer Administrator" in the last step.
  2. Connect to "localhost".
  3. "Add domain..."
  4. Set "127.0.0.1." as the "Domain", click "Save".
  5. "Settings" > "Protocols" > "SMTP" > "Delivery of e-mail"
  6. Set "localhost" as the "Local host name", provide your data in the "SMTP Relayer" section, click "Save".
  7. "Settings" > "Advanced" > "IP Ranges" > "My Computer"
  8. Disable the "External to external e-mail addresses" checkbox in the "Require SMTP authentication" group.
  9. If you have modified php.ini, rewrite these 3 values:

"SMTP = localhost",

"smtp_port = 25",

"; sendmail_path = ".

Credit: How to configure WAMP (localhost) to send email using Gmail?

Missing Compliance in Status when I add built for internal testing in Test Flight.How to solve?

Additionally, if you can't see the "Provide Export Compliance Information" button make sure you have the right role in your App Store Connect or talk to the right person (Account Holder, Admin, or App Manager).

Error : No resource found that matches the given name (at 'icon' with value '@drawable/icon')

This happens when you have previously changed your icon or the ic_launcher; and when that ic_launcher no longer exists in your base folder.

Try adding a png image and giving the same name and then copy it to your drawable folder.Now re build the project.

How to use subList()

You could use streams in Java 8. To always get 10 entries at the most, you could do:

dataList.stream().skip(5).limit(10).collect(Collectors.toList());
dataList.stream().skip(30).limit(10).collect(Collectors.toList());

How to upgrade OpenSSL in CentOS 6.5 / Linux / Unix from source?

You should replace the old OpenSSL binary file by the new one via a symlink:

sudo ln -sf /usr/local/ssl/bin/openssl `which openssl`

Remember that after this procedure you should reboot the server or restart all the services related to OpenSSL.

In jQuery, how do I select an element by its name attribute?

You might notice using class selector to get value of ASP.NET RadioButton controls is always empty and here is the reason.

You create RadioButton control in ASP.NET as below:

<asp:RadioButton runat="server" ID="rbSingle" GroupName="Type" CssClass="radios" Text="Single" />
<asp:RadioButton runat="server" ID="rbDouble" GroupName="Type" CssClass="radios" Text="Double" />
<asp:RadioButton runat="server" ID="rbTriple" GroupName="Type" CssClass="radios" Text="Triple" />

And ASP.NET renders following HTML for your RadioButton

<span class="radios"><input id="Content_rbSingle" type="radio" name="ctl00$Content$Type" value="rbSingle" /><label for="Content_rbSingle">Single</label></span>
<span class="radios"><input id="Content_rbDouble" type="radio" name="ctl00$Content$Type" value="rbDouble" /><label for="Content_rbDouble">Double</label></span>
<span class="radios"><input id="Content_rbTriple" type="radio" name="ctl00$Content$Type" value="rbTriple" /><label for="Content_rbTriple">Triple</label></span>

For ASP.NET we don't want to use RadioButton control name or id because they can change for any reason out of user's hand (change in container name, form name, usercontrol name, ...) as you can see in code above.

The only remaining feasible way to get the value of the RadioButton using jQuery is using css class as mentioned in this answer to a totally unrelated question as following

$('span.radios input:radio').click(function() {
    var value = $(this).val();
});

How to create a JQuery Clock / Timer

setInterval as suggested by SLaks was exactly what I needed to make my timer. (Thanks mate!)

Using setInterval and this great blog post I ended up creating the following function to display a timer inside my "box_header" div. I hope this helps anyone else with similar requirements!

 function get_elapsed_time_string(total_seconds) {
  function pretty_time_string(num) {
    return ( num < 10 ? "0" : "" ) + num;
  }

  var hours = Math.floor(total_seconds / 3600);
  total_seconds = total_seconds % 3600;

  var minutes = Math.floor(total_seconds / 60);
  total_seconds = total_seconds % 60;

  var seconds = Math.floor(total_seconds);

  // Pad the minutes and seconds with leading zeros, if required
  hours = pretty_time_string(hours);
  minutes = pretty_time_string(minutes);
  seconds = pretty_time_string(seconds);

  // Compose the string for display
  var currentTimeString = hours + ":" + minutes + ":" + seconds;

  return currentTimeString;
}

var elapsed_seconds = 0;
setInterval(function() {
  elapsed_seconds = elapsed_seconds + 1;
  $('#box_header').text(get_elapsed_time_string(elapsed_seconds));
}, 1000);

Solving "DLL load failed: %1 is not a valid Win32 application." for Pygame

Had this issue on Python 2.7.9, solved by updating to Python 2.7.10 (unreleased when this question was asked and answered).

Best way to convert text files between character sets?

Try EncodingChecker

EncodingChecker on github

File Encoding Checker is a GUI tool that allows you to validate the text encoding of one or more files. The tool can display the encoding for all selected files, or only the files that do not have the encodings you specify.

File Encoding Checker requires .NET 4 or above to run.

For encoding detection, File Encoding Checker uses the UtfUnknown Charset Detector library. UTF-16 text files without byte-order-mark (BOM) can be detected by heuristics.

enter image description here

Use Invoke-WebRequest with a username and password for basic authentication on the GitHub API

Here is another way using WebRequest, I hope it will work for you

$user = 'whatever'
$pass = 'whatever'
$secpasswd = ConvertTo-SecureString $pass -AsPlainText -Force
$credential = New-Object System.Management.Automation.PSCredential($user, $secpasswd)
$headers = @{ Authorization = "Basic Zm9vOmJhcg==" }  
Invoke-WebRequest -Credential $credential -Headers $headers -Uri "https://dc01.test.local/"

Call a stored procedure with another in Oracle

To invoke the procedure from the SQLPlus command line, try one of these:

CALL test_sp_1();
EXEC test_sp_1

ImportError: No module named requests

My answer is basically the same as @pi-k. In my case my program worked locally but failed to build on QA servers. (I suspect devops had older versions of the package blocked and my version must have been too out-of-date) I just decided to upgrade everything

$ pip install pip-review
$ pip-review --local --interactive

Can a local variable's memory be accessed outside its scope?

You never throw a C++ exception by accessing invalid memory. You are just giving an example of the general idea of referencing an arbitrary memory location. I could do the same like this:

unsigned int q = 123456;

*(double*)(q) = 1.2;

Here I am simply treating 123456 as the address of a double and write to it. Any number of things could happen:

  1. q might in fact genuinely be a valid address of a double, e.g. double p; q = &p;.
  2. q might point somewhere inside allocated memory and I just overwrite 8 bytes in there.
  3. q points outside allocated memory and the operating system's memory manager sends a segmentation fault signal to my program, causing the runtime to terminate it.
  4. You win the lottery.

The way you set it up it is a bit more reasonable that the returned address points into a valid area of memory, as it will probably just be a little further down the stack, but it is still an invalid location that you cannot access in a deterministic fashion.

Nobody will automatically check the semantic validity of memory addresses like that for you during normal program execution. However, a memory debugger such as valgrind will happily do this, so you should run your program through it and witness the errors.

Efficiently updating database using SQLAlchemy ORM

SQLAlchemy's ORM is meant to be used together with the SQL layer, not hide it. But you do have to keep one or two things in mind when using the ORM and plain SQL in the same transaction. Basically, from one side, ORM data modifications will only hit the database when you flush the changes from your session. From the other side, SQL data manipulation statements don't affect the objects that are in your session.

So if you say

for c in session.query(Stuff).all():
    c.foo = c.foo+1
session.commit()

it will do what it says, go fetch all the objects from the database, modify all the objects and then when it's time to flush the changes to the database, update the rows one by one.

Instead you should do this:

session.execute(update(stuff_table, values={stuff_table.c.foo: stuff_table.c.foo + 1}))
session.commit()

This will execute as one query as you would expect, and because at least the default session configuration expires all data in the session on commit you don't have any stale data issues.

In the almost-released 0.5 series you could also use this method for updating:

session.query(Stuff).update({Stuff.foo: Stuff.foo + 1})
session.commit()

That will basically run the same SQL statement as the previous snippet, but also select the changed rows and expire any stale data in the session. If you know you aren't using any session data after the update you could also add synchronize_session=False to the update statement and get rid of that select.

javascript code to check special characters

You can test a string using this regular expression:

function isValid(str){
 return !/[~`!#$%\^&*+=\-\[\]\\';,/{}|\\":<>\?]/g.test(str);
}

"getaddrinfo failed", what does that mean?

It most likely means the hostname can't be resolved.

import socket
socket.getaddrinfo('localhost', 8080)

If it doesn't work there, it's not going to work in the Bottle example. You can try '127.0.0.1' instead of 'localhost' in case that's the problem.

Finding rows that don't contain numeric data in Oracle

I was thinking you could use a regexp_like condition and use the regular expression to find any non-numerics. I hope this might help?!

SELECT * FROM table_with_column_to_search WHERE REGEXP_LIKE(varchar_col_with_non_numerics, '[^0-9]+');

How to get HttpRequestMessage data

I suggest that you should not do it like this. Action methods should be designed to be easily unit-tested. In this case, you should not access data directly from the request, because if you do it like this, when you want to unit test this code you have to construct a HttpRequestMessage.

You should do it like this to let MVC do all the model binding for you:

[HttpPost]
public void Confirmation(YOURDTO yourobj)//assume that you define YOURDTO elsewhere
{
        //your logic to process input parameters.

}

In case you do want to access the request. You just access the Request property of the controller (not through parameters). Like this:

[HttpPost]
public void Confirmation()
{
    var content = Request.Content.ReadAsStringAsync().Result;
}

In MVC, the Request property is actually a wrapper around .NET HttpRequest and inherit from a base class. When you need to unit test, you could also mock this object.

Ansible: Store command's stdout in new variable?

You have to store the content as a fact:

- set_fact:
    string_to_echo: "{{ command_output.stdout }}"

Vertically align an image inside a div with responsive height

Try this one

  .responsive-container{
          display:table;
  }
  .img-container{
          display:table-cell;
          vertical-align: middle;
   }

How to configure custom PYTHONPATH with VM and PyCharm?

For PyCharm 5 (or 2016.1), you can:

  1. select Preferences > Project Interpreter
  2. to the right of interpreter selector there is a "..." button, click it
  3. select "more..."
  4. pop up a new "Project Interpreters" window
  5. select the rightest button (named "show paths for the selected interpreter")
  6. pop up a "Interpreter Paths" window
  7. click the "+" buttom > select your desired PYTHONPATH directory (the folder which contains python modules) and click OK
  8. Done! Enjoy it!

enter image description here

enter image description here

enter image description here enter image description here

Fast way to get the min/max values among properties of object

var newObj = { a: 4, b: 0.5 , c: 0.35, d: 5 };
var maxValue = Math.max(...Object.values(newObj))
var minValue = Math.min(...Object.values(newObj))

How to search in a List of Java object

Using Java 8

With Java 8 you can simply convert your list to a stream allowing you to write:

import java.util.List;
import java.util.stream.Collectors;

List<Sample> list = new ArrayList<Sample>();
List<Sample> result = list.stream()
    .filter(a -> Objects.equals(a.value3, "three"))
    .collect(Collectors.toList());

Note that

  • a -> Objects.equals(a.value3, "three") is a lambda expression
  • result is a List with a Sample type
  • It's very fast, no cast at every iteration
  • If your filter logic gets heavier, you can do list.parallelStream() instead of list.stream() (read this)


Apache Commons

If you can't use Java 8, you can use Apache Commons library and write:

import org.apache.commons.collections.CollectionUtils;
import org.apache.commons.collections.Predicate;

Collection result = CollectionUtils.select(list, new Predicate() {
     public boolean evaluate(Object a) {
         return Objects.equals(((Sample) a).value3, "three");
     }
 });

// If you need the results as a typed array:
Sample[] resultTyped = (Sample[]) result.toArray(new Sample[result.size()]);

Note that:

  • There is a cast from Object to Sample at each iteration
  • If you need your results to be typed as Sample[], you need extra code (as shown in my sample)



Bonus: A nice blog article talking about how to find element in list.

How to Initialize char array from a string

Here is obscure solution: define macro function:

#define Z(x) \
        (x==0 ? 'A' : \
        (x==1 ? 'B' : \
        (x==2 ? 'C' : '\0')))

char x[] = { Z(0), Z(1), Z(2) };

Docker: Multiple Dockerfiles in project

Add an abstraction layer, for example, a YAML file like in this project https://github.com/larytet/dockerfile-generator which looks like

centos7:
    base: centos:centos7
    packager: rpm
    install:
      - $build_essential_centos 
      - rpm-build
    run:
      - $get_release
    env:
      - $environment_vars

A short Python script/make can generate all Dockerfiles from the configuration file.

Eclipse - Installing a new JRE (Java SE 8 1.8.0)

You can have many java versions in your system.

I think you should add the java 8 in yours JREs installed or edit.

Take a look my screen:

enter image description here

If you click in edit (check your java 8 path):

enter image description here

What does "Error: object '<myvariable>' not found" mean?

I had a similar problem with R-studio. When I tried to do my plots, this message was showing up.

Eventually I realised that the reason behind this was that my "window" for the plots was too small, and I had to make it bigger to "fit" all the plots inside!

Hope to help

How do I tell Python to convert integers into words

You can use the python-n2w library, Just do

pip install n2w

then simply

print(n2w.convert(your-number-here))

How to generate XML from an Excel VBA macro?

This one more version - this will help in generic

Public strSubTag As String
Public iStartCol As Integer
Public iEndCol As Integer
Public strSubTag2 As String
Public iStartCol2 As Integer
Public iEndCol2 As Integer

Sub Create()
Dim strFilePath As String
Dim strFileName As String

'ThisWorkbook.Sheets("Sheet1").Range("C3").Activate
'strTag = ActiveCell.Offset(0, 1).Value
strFilePath = ThisWorkbook.Sheets("Sheet1").Range("B4").Value
strFileName = ThisWorkbook.Sheets("Sheet1").Range("B5").Value
strSubTag = ThisWorkbook.Sheets("Sheet1").Range("F3").Value
iStartCol = ThisWorkbook.Sheets("Sheet1").Range("F4").Value
iEndCol = ThisWorkbook.Sheets("Sheet1").Range("F5").Value

strSubTag2 = ThisWorkbook.Sheets("Sheet1").Range("G3").Value
iStartCol2 = ThisWorkbook.Sheets("Sheet1").Range("G4").Value
iEndCol2 = ThisWorkbook.Sheets("Sheet1").Range("G5").Value

Dim iCaptionRow As Integer
iCaptionRow = ThisWorkbook.Sheets("Sheet1").Range("B3").Value
'strFileName = ThisWorkbook.Sheets("Sheet1").Range("B4").Value
MakeXML iCaptionRow, iCaptionRow + 1, strFilePath, strFileName

End Sub


Sub MakeXML(iCaptionRow As Integer, iDataStartRow As Integer, sOutputFilePath As String, sOutputFileName As String)
    Dim Q As String
    Dim sOutputFileNamewithPath As String
    Q = Chr$(34)

    Dim sXML As String


    'sXML = sXML & "<rows>"

'    ''--determine count of columns
    Dim iColCount As Integer
    iColCount = 1

    While Trim$(Cells(iCaptionRow, iColCount)) > ""
        iColCount = iColCount + 1
    Wend


    Dim iRow As Integer
    Dim iCount  As Integer
    iRow = iDataStartRow
    iCount = 1
    While Cells(iRow, 1) > ""
        'sXML = sXML & "<row id=" & Q & iRow & Q & ">"
        sXML = "<?xml version=" & Q & "1.0" & Q & " encoding=" & Q & "UTF-8" & Q & "?>"
        For iCOl = 1 To iColCount - 1
          If (iStartCol = iCOl) Then
               sXML = sXML & "<" & strSubTag & ">"
          End If
          If (iEndCol = iCOl) Then
               sXML = sXML & "</" & strSubTag & ">"
          End If
         If (iStartCol2 = iCOl) Then
               sXML = sXML & "<" & strSubTag2 & ">"
          End If
          If (iEndCol2 = iCOl) Then
               sXML = sXML & "</" & strSubTag2 & ">"
          End If
           sXML = sXML & "<" & Trim$(Cells(iCaptionRow, iCOl)) & ">"
           sXML = sXML & Trim$(Cells(iRow, iCOl))
           sXML = sXML & "</" & Trim$(Cells(iCaptionRow, iCOl)) & ">"
        Next

        'sXML = sXML & "</row>"
        Dim nDestFile As Integer, sText As String

    ''Close any open text files
        Close

    ''Get the number of the next free text file
        nDestFile = FreeFile
        sOutputFileNamewithPath = sOutputFilePath & sOutputFileName & iCount & ".XML"
    ''Write the entire file to sText
        Open sOutputFileNamewithPath For Output As #nDestFile
        Print #nDestFile, sXML

        iRow = iRow + 1
        sXML = ""
        iCount = iCount + 1
    Wend
    'sXML = sXML & "</rows>"

    Close
End Sub

C++ - Hold the console window open?

If your problem is retaining the Console Window within Visual Studio without modifying your application (c-code) and are running it with Ctrl+F5 (when running Ctrl+F5) but the window is still closing the principal hint is to set the /SUBSYSTEM:CONSOLE linker option in your Visual Studio project.

as explained by DJMooreTX in http://social.msdn.microsoft.com/Forums/en-US/vcprerelease/thread/21073093-516c-49d2-81c7-d960f6dc2ac6

1) Open up your project, and go to the Solution Explorer. If you're following along with me in K&R, your "Solution" will be 'hello' with 1 project under it, also 'hello' in bold.

  1. Right click on the 'hello" (or whatever your project name is.)

  2. Choose "Properties" from the context menu.

  3. Choose Configuration Properties>Linker>System.

  4. For the "Subsystem" property in the right-hand pane, click the drop-down box in the right hand column.

  5. Choose "Console (/SUBSYSTEM:CONSOLE)"

  6. Click Apply, wait for it to finish doing whatever it does, then click OK. (If "Apply" is grayed out, choose some other subsystem option, click Apply, then go back and apply the console option. My experience is that OK by itself won't work.)

Now do Boris' CTRL-F5, wait for your program to compile and link, find the console window under all the other junk on your desktop, and read your program's output, followed by the beloved "Press any key to continue...." prompt.

Again, CTRL-F5 and the subsystem hints work together; they are not separate options.

Understanding string reversal via slicing

the first two bounds default to 0 and the length of the sequence, as before, and a stride of -1 indicates that the slice should go from right to left instead of the usual left to right. The effect, therefore, is to reverse the sequence.

name="ravi"
print(name[::-1]) #ivar

Short IF - ELSE statement

You can do it as simple as this, I did it in react hooks :

 (myNumber == 12) ? "true" : "false"

it was equal to this long if function below :

if (myNumber == 12) {
  "true"
} else {
  "false"
}

Hope it helps ^_^

Loading .sql files from within PHP

Briefly, the way I have done this is:

  1. Read the file (a db dump eg $ mysqldump db > db.sql)

    $sql = file_get_contents(db.sql);
    
  2. Import it using mysqli::multi_query

    if ($mysqli->multi_query($sql)) {
        $mysqli->close();
    } else {
        throw new Exception ($mysqli->error);
    }
    

Watch out mysqli_query supports async queries. More here: http://php.net/manual/en/mysqli.multi-query.php and here https://stackoverflow.com/a/6652908/2002493

PYTHONPATH on Linux

1) PYTHONPATH is an environment variable which you can set to add additional directories where python will look for modules and packages. e.g.:

# make python look in the foo subdirectory of your home directory for
# modules and packages 
export PYTHONPATH=${PYTHONPATH}:${HOME}/foo 

Here I use the sh syntax. For other shells (e.g. csh,tcsh), the syntax would be slightly different. To make it permanent, set the variable in your shell's init file (usually ~/.bashrc).

2) Ubuntu comes with python already installed. There may be reasons for installing other (independent) python versions, but I've found that to be rarely necessary.

3) The folder where your modules live is dependent on PYTHONPATH and where the directories were set up when python was installed. For the most part, the installed stuff you shouldn't care about where it lives -- Python knows where it is and it can find the modules. Sort of like issuing the command ls -- where does ls live? /usr/bin? /bin? 99% of the time, you don't need to care -- Just use ls and be happy that it lives somewhere on your PATH so the shell can find it.

4) I'm not sure I understand the question. 3rd party modules usually come with install instructions. If you follow the instructions, python should be able to find the module and you shouldn't have to care about where it got installed.

5) Configure PYTHONPATH to include the directory where your module resides and python will be able to find your module.

CSS: how to get scrollbars for div inside container of fixed height

Code from the above answer by Dutchie432

.FixedHeightContainer {
    float:right;
    height: 250px;
    width:250px; 
    padding:3px; 
    background:#f00;
}

.Content {
    height:224px;
    overflow:auto;
    background:#fff;
}

input type=file show only button

This HTML code show up only Upload File button

<form action="/action_page.php">
    <input type="button" id="id" value="Upload File"  onclick="document.getElementById('file').click();" />
    <input type="file" style="display:none;" id="file" name="file" onchange="this.form.submit()"/>  
</form>

How to do jquery code AFTER page loading?

You can avoid get undefined in '$' this way

window.addEventListener("DOMContentLoaded", function(){
    // Your code
});

EDIT: Using 'DOMContentLoaded' is faster than just 'load' because load wait page fully loaded, imgs included... while DomContentLoaded waits just the structure

What is the difference between the GNU Makefile variable assignments =, ?=, := and +=?

Lazy Set

VARIABLE = value

Normal setting of a variable, but any other variables mentioned with the value field are recursively expanded with their value at the point at which the variable is used, not the one it had when it was declared

Immediate Set

VARIABLE := value

Setting of a variable with simple expansion of the values inside - values within it are expanded at declaration time.

Lazy Set If Absent

VARIABLE ?= value

Setting of a variable only if it doesn't have a value. value is always evaluated when VARIABLE is accessed. It is equivalent to

ifeq ($(origin FOO), undefined)
  FOO = bar
endif

See the documentation for more details.

Append

VARIABLE += value

Appending the supplied value to the existing value (or setting to that value if the variable didn't exist)

Can I set an opacity only to the background image of a div?

I implemented Marcus Ekwall's solution but was able to remove a few things to make it simpler and it still works. Maybe 2017 version of html/css?

html:

<div id="content">
  <div id='bg'></div>
  <h2>What is Lorem Ipsum?</h2>
  <p><strong>Lorem Ipsum</strong> is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen
    book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with
    desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum.</p>
</div>

css:

#content {
  text-align: left;
  width: 75%;
  margin: auto;
  position: relative;
}

#bg {
  position: absolute;
  top: 0;
  bottom: 0;
  left: 0;
  right: 0;
  background: url('https://static.pexels.com/photos/6644/sea-water-ocean-waves.jpg') center center;
  opacity: .4;
  width: 100%;
  height: 100%;
}

https://jsfiddle.net/abalter/3te9fjL5/

How to change Vagrant 'default' machine name?

Yes, for Virtualbox provider do something like this:

Vagrant.configure("2") do |config|
    # ...other options...
    config.vm.provider "virtualbox" do |p|
        p.name = "something-else"
    end
end

MySQL and PHP - insert NULL rather than empty string

To pass a NULL to MySQL, you do just that.

INSERT INTO table (field,field2) VALUES (NULL,3)

So, in your code, check if $intLat, $intLng are empty, if they are, use NULL instead of '$intLat' or '$intLng'.

$intLat = !empty($intLat) ? "'$intLat'" : "NULL";
$intLng = !empty($intLng) ? "'$intLng'" : "NULL";

$query = "INSERT INTO data (notes, id, filesUploaded, lat, lng, intLat, intLng)
          VALUES ('$notes', '$id', TRIM('$imageUploaded'), '$lat', '$long', 
                  $intLat, $intLng)";

How do I kill a VMware virtual machine that won't die?

If you're on linux then you can grab the guest processes with

ps axuw | grep vmware-vmx

As @Dubas pointed out, you should be able to pick out the errant process by the path name to the VMD

SQL command to display history of queries

You can see the history from ~/.mysql_history. However the content of the file is encoded by wctomb. To view the content:

shell> cat ~/.mysql_history | python2.7 -c "import sys; print(''.join([l.decode('unicode-escape') for l in sys.stdin]))"

Source:Check MySQL query history from command line

vim - How to delete a large block of text without counting the lines?

Alongside with other motions that are already mentioned here, there is also /{pattern}<CR> motion, so if you know that you want to delete to line that contains foo, you could do dV/foo<CR>. V is here to force motion be line-wise because by default / is characterwise.

How to uninstall a windows service and delete its files without rebooting

Should it be necessary to manually remove a service:

  1. Run Regedit or regedt32.
  2. Find the registry key entry for your service under the following key: HKEY_LOCAL_MACHINE/SYSTEM/CurrentControlSet/Services
  3. Delete the Registry Key

You will have to reboot before the list gets updated in services

Javascript find json value

Making more general the @showdev answer.

var getObjectByValue = function (array, key, value) {
    return array.filter(function (object) {
        return object[key] === value;
    });
};

Example:

getObjectByValue(data, "code", "DZ" );

jQuery get textarea text

I have figured out that I can convert the keyCode of the event to a character by using the following function:

var char = String.fromCharCode(v_code);

From there I would then append the character to a string, and when the enter key is pressed send the string to the server. I'm sorry if my question seemed somewhat cryptic, and the title meaning something almost completely off-topic, it's early in the morning and I haven't had breakfast yet ;).

Thanks for all your help guys.

OnChange event using React JS for drop down

Thank you Felix Kling, but his answer need a little change:

var MySelect = React.createClass({
 getInitialState: function() {
     return {
         value: 'select'
     }
 },
 change: function(event){
     this.setState({value: event.target.value});
 },
 render: function(){
    return(
       <div>
           <select id="lang" onChange={this.change.bind(this)} value={this.state.value}>
              <option value="select">Select</option>
              <option value="Java">Java</option>
              <option value="C++">C++</option>
           </select>
           <p></p>
           <p>{this.state.value}</p>
       </div>
    );
 }
});
React.render(<MySelect />, document.body); 

Multiple lines of text in UILabel

I found a solution.

One just has to add the following code:

// Swift
textLabel.lineBreakMode = .ByWordWrapping // or NSLineBreakMode.ByWordWrapping
textLabel.numberOfLines = 0 

// For Swift >= 3
textLabel.lineBreakMode = .byWordWrapping // notice the 'b' instead of 'B'
textLabel.numberOfLines = 0

// Objective-C
textLabel.lineBreakMode = NSLineBreakByWordWrapping;
textLabel.numberOfLines = 0;

// C# (Xamarin.iOS)
textLabel.LineBreakMode = UILineBreakMode.WordWrap;
textLabel.Lines = 0;  

Restored old answer (for reference and devs willing to support iOS below 6.0):

textLabel.lineBreakMode = UILineBreakModeWordWrap;
textLabel.numberOfLines = 0;

On the side: both enum values yield to 0 anyway.

Calculate the center point of multiple latitude/longitude coordinate pairs

If you wish to take into account the ellipsoid being used you can find the formulae here http://www.ordnancesurvey.co.uk/oswebsite/gps/docs/A_Guide_to_Coordinate_Systems_in_Great_Britain.pdf

see Annexe B

The document contains lots of other useful stuff

B

Android SDK installation doesn't find JDK

The above methods did not work for me in Windows 8 Pro.

Just set the path to

C:\Program Files\Java\jdk1.7.0_07\

Where C is your drive in which you have installed the JDK.

Don't forget the backward slash at the end.

Understanding Linux /proc/id/maps

memory mapping is not only used to map files into memory but is also a tool to request RAM from kernel. These are those inode 0 entries - your stack, heap, bss segments and more

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

For me, this was due to the fact that I was trying to debug using eclipse yet also running Android Studio. Both programs were trying to monitor android devices on the similar ports. Either quit all IDEs other than one, or modify the port number used for debugging in the IDE preferences so they are not similar.

How to wrap text of HTML button with fixed width?

I have found that a button works, but that you'll want to add style="height: 100%;" to the button so that it will show more than the first line on Safari for iPhone iOS 5.1.1

Naming Classes - How to avoid calling everything a "<WhatEver>Manager"?

You can take a look at source-code-wordle.de, I have analyzed there the most frequently used suffixes of class names of the .NET framework and some other libraries.

The top 20 are:

  • attribute
  • type
  • helper
  • collection
  • converter
  • handler
  • info
  • provider
  • exception
  • service
  • element
  • manager
  • node
  • option
  • factory
  • context
  • item
  • designer
  • base
  • editor

UITableView, Separator color where to set?

Now you should be able to do it directly in the IB.

Not sure though, if this was available when the question was posted originally.

enter image description here

How do I specify local .gem files in my Gemfile?

I would unpack your gem in the application vendor folder

gem unpack your.gem --target /path_to_app/vendor/gems/

Then add the path on the Gemfile to link unpacked gem.

gem 'your', '2.0.1', :path => 'vendor/gems/your'

How to add a new schema to sql server 2008?

You can try this:

use database
go

declare @temp as int
select @temp = count(1) from sys.schemas where name = 'newSchema'

if @temp = 0 
begin
    exec ('create SCHEMA temporal')
    print 'The schema newSchema was created in database'
end 
else 
print 'The schema newSchema already exists in database'
go

Compare two objects' properties to find differences?

Yes. Use Reflection. With Reflection, you can do things like:

//given object of some type
object myObjectFromSomewhere;
Type myObjOriginalType = myObjectFromSomewhere.GetType();
PropertyInfo[] myProps = myObjOriginalType.GetProperties();

And then you can use the resulting PropertyInfo classes to compare all manner of things.

How to get access to HTTP header information in Spring MVC REST controller?

You can use the @RequestHeader annotation with HttpHeaders method parameter to gain access to all request headers:

@RequestMapping(value = "/restURL")
public String serveRest(@RequestBody String body, @RequestHeader HttpHeaders headers) {
    // Use headers to get the information about all the request headers
    long contentLength = headers.getContentLength();
    // ...
    StreamSource source = new StreamSource(new StringReader(body));
    YourObject obj = (YourObject) jaxb2Mashaller.unmarshal(source);
    // ...
}

Is there a way to take a screenshot using Java and save it to some sort of image?

You can use java.awt.Robot to achieve this task.

below is the code of server, which saves the captured screenshot as image in your Directory.

import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.SocketTimeoutException;
import java.sql.SQLException;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;

import javax.imageio.ImageIO;

public class ServerApp extends Thread
{
       private ServerSocket serverSocket=null;
       private static Socket server = null;
       private Date date = null;
       private static final String DIR_NAME = "screenshots";

   public ServerApp() throws IOException, ClassNotFoundException, Exception{
       serverSocket = new ServerSocket(61000);
       serverSocket.setSoTimeout(180000);
   }

public void run()
   {
       while(true)
      {
           try
           {
              server = serverSocket.accept();
              date = new Date();
                  DateFormat dateFormat = new SimpleDateFormat("_yyMMdd_HHmmss");
              String fileName = server.getInetAddress().getHostName().replace(".", "-");
              System.out.println(fileName);
              BufferedImage img=ImageIO.read(ImageIO.createImageInputStream(server.getInputStream()));
              ImageIO.write(img, "png", new File("D:\\screenshots\\"+fileName+dateFormat.format(date)+".png"));
              System.out.println("Image received!!!!");
              //lblimg.setIcon(img);
          }
         catch(SocketTimeoutException st)
         {
               System.out.println("Socket timed out!"+st.toString());
 //createLogFile("[stocktimeoutexception]"+stExp.getMessage());
                  break;
             }
             catch(IOException e)
             {
                  e.printStackTrace();
                  break;
         }
         catch(Exception ex)
        {
              System.out.println(ex);
        }
      }
   }

   public static void main(String [] args) throws IOException, SQLException, ClassNotFoundException, Exception{
          ServerApp serverApp = new ServerApp();
          serverApp.createDirectory(DIR_NAME);
          Thread thread = new Thread(serverApp);
            thread.start();
   }

private void createDirectory(String dirName) {
    File newDir = new File("D:\\"+dirName);
    if(!newDir.exists()){
        boolean isCreated = newDir.mkdir();
    }
 }
} 

And this is Client code which is running on thread and after some minutes it is capturing the screenshot of user screen.

package com.viremp.client;

import java.awt.AWTException;
import java.awt.Dimension;
import java.awt.Rectangle;
import java.awt.Robot;
import java.awt.Toolkit;
import java.awt.image.BufferedImage;
import java.io.IOException;
import java.net.Socket;
import java.util.Random;

import javax.imageio.ImageIO;

public class ClientApp implements Runnable {
    private static long nextTime = 0;
    private static ClientApp clientApp = null;
    private String serverName = "192.168.100.18"; //loop back ip
    private int portNo = 61000;
    //private Socket serverSocket = null;

    /**
     * @param args
     * @throws InterruptedException 
     */
    public static void main(String[] args) throws InterruptedException {
        clientApp = new ClientApp();
        clientApp.getNextFreq();
        Thread thread = new Thread(clientApp);
        thread.start();
    }

    private void getNextFreq() {
        long currentTime = System.currentTimeMillis();
        Random random = new Random();
        long value = random.nextInt(180000); //1800000
        nextTime = currentTime + value;
        //return currentTime+value;
    }

    @Override
    public void run() {
        while(true){
            if(nextTime < System.currentTimeMillis()){
                System.out.println(" get screen shot ");
                try {
                    clientApp.sendScreen();
                    clientApp.getNextFreq();
                } catch (AWTException e) {
                    // TODO Auto-generated catch block
                    System.out.println(" err"+e);
                } catch (IOException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                } catch(Exception e){
                    e.printStackTrace();
                }

            }
            //System.out.println(" statrted ....");
        }

    }

    private void sendScreen()throws AWTException, IOException {
           Socket serverSocket = new Socket(serverName, portNo);
             Toolkit toolkit = Toolkit.getDefaultToolkit();
             Dimension dimensions = toolkit.getScreenSize();
                 Robot robot = new Robot();  // Robot class 
                 BufferedImage screenshot = robot.createScreenCapture(new Rectangle(dimensions));
                 ImageIO.write(screenshot,"png",serverSocket.getOutputStream());
                 serverSocket.close();
    }
}

Python function to convert seconds into minutes, hours, and days

Although divmod() has been mentioned, I didn't see what I considered to be a nice example. Here's mine:

q=972021.0000  # For example
days = divmod(q, 86400) 
# days[0] = whole days and
# days[1] = seconds remaining after those days
hours = divmod(days[1], 3600)
minutes = divmod(hours[1], 60)
print "%i days, %i hours, %i minutes, %i seconds" % (days[0], hours[0], minutes[0], minutes[1])

Which outputs:

11 days, 6 hours, 0 minutes, 21 seconds

Newline in string attribute

May be you can use the attribute xml:space="preserve" for preserving whitespace in the source XAML

<TextBlock xml:space="preserve">
Stuff on line 1
Stuff on line 2
</TextBlock>

How can I add items to an empty set in python

>>> d = {}
>>> D = set()
>>> type(d)
<type 'dict'>
>>> type(D)
<type 'set'>

What you've made is a dictionary and not a Set.

The update method in dictionary is used to update the new dictionary from a previous one, like so,

>>> abc = {1: 2}
>>> d.update(abc)
>>> d
{1: 2}

Whereas in sets, it is used to add elements to the set.

>>> D.update([1, 2])
>>> D
set([1, 2])

Reading Xml with XmlReader in C#

We do this kind of XML parsing all the time. The key is defining where the parsing method will leave the reader on exit. If you always leave the reader on the next element following the element that was first read then you can safely and predictably read in the XML stream. So if the reader is currently indexing the <Account> element, after parsing the reader will index the </Accounts> closing tag.

The parsing code looks something like this:

public class Account
{
    string _accountId;
    string _nameOfKin;
    Statements _statmentsAvailable;

    public void ReadFromXml( XmlReader reader )
    {
        reader.MoveToContent();

        // Read node attributes
        _accountId = reader.GetAttribute( "accountId" );
        ...

        if( reader.IsEmptyElement ) { reader.Read(); return; }

        reader.Read();
        while( ! reader.EOF )
        {
            if( reader.IsStartElement() )
            {
                switch( reader.Name )
                {
                    // Read element for a property of this class
                    case "NameOfKin":
                        _nameOfKin = reader.ReadElementContentAsString();
                        break;

                    // Starting sub-list
                case "StatementsAvailable":
                    _statementsAvailable = new Statements();
                    _statementsAvailable.Read( reader );
                    break;

                    default:
                        reader.Skip();
                }
            }
            else
            {
                reader.Read();
                break;
            }
        }       
    }
}

The Statements class just reads in the <StatementsAvailable> node

public class Statements
{
    List<Statement> _statements = new List<Statement>();

    public void ReadFromXml( XmlReader reader )
    {
        reader.MoveToContent();
        if( reader.IsEmptyElement ) { reader.Read(); return; }

        reader.Read();
        while( ! reader.EOF )
        {
            if( reader.IsStartElement() )
            {
                if( reader.Name == "Statement" )
                {
                    var statement = new Statement();
                    statement.ReadFromXml( reader );
                    _statements.Add( statement );               
                }
                else
                {
                    reader.Skip();
                }
            }
            else
            {
                reader.Read();
                break;
            }
        }
    }
}

The Statement class would look very much the same

public class Statement
{
    string _satementId;

    public void ReadFromXml( XmlReader reader )
    {
        reader.MoveToContent();

        // Read noe attributes
        _statementId = reader.GetAttribute( "statementId" );
        ...

        if( reader.IsEmptyElement ) { reader.Read(); return; }

        reader.Read();
        while( ! reader.EOF )
        {           
            ....same basic loop
        }       
    }
}

bootstrap responsive table content wrapping

I ran across the same issue you did but the above answers did not solve my issue. The only way I was able to resolve it - was to make a class and use specific widths to trigger the wrapping for my specific use case. As an example, I provided a snippet below - but I found you will need to adjust it for the table in question - since I typically use multiple colspans depending on the layout. The reasoning I believe Bootstrap is failing - is because it removes the wrapping constraints to get a full table for the scrollbars. THe colspan must be tripping it up.

<style>
@media (max-width: 768px) { /* use the max to specify at each container level */
    .specifictd {    
        width:360px;  /* adjust to desired wrapping */
        display:table;
        white-space: pre-wrap; /* css-3 */
        white-space: -moz-pre-wrap; /* Mozilla, since 1999 */
        white-space: -pre-wrap; /* Opera 4-6 */
        white-space: -o-pre-wrap; /* Opera 7 */
        word-wrap: break-word; /* Internet Explorer 5.5+ */
    }
}

I hope this helps

'Syntax Error: invalid syntax' for no apparent reason

For problems where it seems to be an error on a line you think is correct, you can often remove/comment the line where the error appears to be and, if the error moves to the next line, there are two possibilities.

Either both lines have a problem or the previous line has a problem which is being carried forward. The most likely case is the second option (even more so if you remove another line and it moves again).

For example, the following Python program twisty_passages.py:

xyzzy = (1 +
plugh = 7

generates the error:

  File "twisty_passages.py", line 2
    plugh = 7
          ^
SyntaxError: invalid syntax

despite the problem clearly being on line 1.


In your particular case, that is the problem. The parentheses in the line before your error line is unmatched, as per the following snippet:

# open parentheses: 1  2             3
#                   v  v             v
fi2=0.460*scipy.sqrt(1-(Tr-0.566)**2/(0.434**2)+0.494
#                               ^             ^
# close parentheses:            1             2

Depending on what you're trying to achieve, the solution may be as simple as just adding another closing parenthesis at the end, to close off the sqrt function.

I can't say for certain since I don't recognise the expression off the top of my head. Hardly surprising if (assuming PSAT is the enzyme, and the use of the typeMolecule identifier) it's to do with molecular biology - I seem to recall failing Biology consistently in my youth :-)

What is the difference between pip and conda?

Quoting from Conda: Myths and Misconceptions (a comprehensive description):

...

Myth #3: Conda and pip are direct competitors

Reality: Conda and pip serve different purposes, and only directly compete in a small subset of tasks: namely installing Python packages in isolated environments.

Pip, which stands for Pip Installs Packages, is Python's officially-sanctioned package manager, and is most commonly used to install packages published on the Python Package Index (PyPI). Both pip and PyPI are governed and supported by the Python Packaging Authority (PyPA).

In short, pip is a general-purpose manager for Python packages; conda is a language-agnostic cross-platform environment manager. For the user, the most salient distinction is probably this: pip installs python packages within any environment; conda installs any package within conda environments. If all you are doing is installing Python packages within an isolated environment, conda and pip+virtualenv are mostly interchangeable, modulo some difference in dependency handling and package availability. By isolated environment I mean a conda-env or virtualenv, in which you can install packages without modifying your system Python installation.

Even setting aside Myth #2, if we focus on just installation of Python packages, conda and pip serve different audiences and different purposes. If you want to, say, manage Python packages within an existing system Python installation, conda can't help you: by design, it can only install packages within conda environments. If you want to, say, work with the many Python packages which rely on external dependencies (NumPy, SciPy, and Matplotlib are common examples), while tracking those dependencies in a meaningful way, pip can't help you: by design, it manages Python packages and only Python packages.

Conda and pip are not competitors, but rather tools focused on different groups of users and patterns of use.

Pytorch tensor to numpy array

This worked for me:

np_arr = torch_tensor.cpu().detach().numpy()

What is the ellipsis (...) for in this method signature?

Those are varargs they are used to create a method that receive any number of arguments.

For instance PrintStream.printf method uses it, since you don't know how many would arguments you'll use.

They can only be used as final position of the arguments.

varargs was was added on Java 1.5

How to pass boolean parameter value in pipeline to downstream jobs?

Not sure if this answers this question. But I was looking for something else. Highly recommend see this 2 minute video. If you wanted to get into more details then see docs - Handling Parameters and this link

And then if you have something like blue ocean, the choices would look something like this:

enter image description here

You define and access your variables like this:

pipeline {
    agent any

    parameters {
    string(defaultValue: "TEST", description: 'What environment?', name: 'userFlag')
    choice(choices: ['TESTING', 'STAGING', 'PRODUCTION'], description: 'Select field for target environment', name: 'DEPLOY_ENV')
    }

    stages {
        stage("foo") {
            steps {
                echo "flag: ${params.userFlag}"
                echo "flag: ${params.DEPLOY_ENV}"
            }
        }
    }
}

Automated builds will pick up the default params. But if you do it manually then you get the option to choose.

And then assign values like this:

enter image description here

Setting the classpath in java using Eclipse IDE

Try this:

Project -> Properties -> Java Build Path -> Add Class Folder.

If it doesnt work, please be specific in what way your compilation fails, specifically post the error messages Eclipse returns, and i will know what to do about it.

How to undo local changes to a specific file

You don't want git revert. That undoes a previous commit. You want git checkout to get git's version of the file from master.

git checkout -- filename.txt

In general, when you want to perform a git operation on a single file, use -- filename.



2020 Update

Git introduced a new command git restore in version 2.23.0. Therefore, if you have git version 2.23.0+, you can simply git restore filename.txt - which does the same thing as git checkout -- filename.txt. The docs for this command do note that it is currently experimental.

How do I use the nohup command without getting nohup.out?

If you have a BASH shell on your mac/linux in-front of you, you try out the below steps to understand the redirection practically :

Create a 2 line script called zz.sh

#!/bin/bash
echo "Hello. This is a proper command"
junk_errorcommand
  • The echo command's output goes into STDOUT filestream (file descriptor 1).
  • The error command's output goes into STDERR filestream (file descriptor 2)

Currently, simply executing the script sends both STDOUT and STDERR to the screen.

./zz.sh

Now start with the standard redirection :

zz.sh > zfile.txt

In the above, "echo" (STDOUT) goes into the zfile.txt. Whereas "error" (STDERR) is displayed on the screen.

The above is the same as :

zz.sh 1> zfile.txt

Now you can try the opposite, and redirect "error" STDERR into the file. The STDOUT from "echo" command goes to the screen.

zz.sh 2> zfile.txt

Combining the above two, you get:

zz.sh 1> zfile.txt 2>&1

Explanation:

  • FIRST, send STDOUT 1 to zfile.txt
  • THEN, send STDERR 2 to STDOUT 1 itself (by using &1 pointer).
  • Therefore, both 1 and 2 goes into the same file (zfile.txt)

Eventually, you can pack the whole thing inside nohup command & to run it in the background:

nohup zz.sh 1> zfile.txt 2>&1&

How to pass parameters to a modal?

If you're not using AngularJS UI Bootstrap, here's how I did it.

I created a directive that will hold that entire element of your modal, and recompile the element to inject your scope into it.

angular.module('yourApp', []).
directive('myModal',
       ['$rootScope','$log','$compile',
function($rootScope,  $log,  $compile) {
    var _scope = null;
    var _element = null;
    var _onModalShow = function(event) {
        _element.after($compile(event.target)(_scope));
    };

    return {
        link: function(scope, element, attributes) {
            _scope = scope;
            _element = element;
            $(element).on('show.bs.modal',_onModalShow);
        }
    };
}]);

I'm assuming your modal template is inside the scope of your controller, then add directive my-modal to your template. If you saved the clicked user to $scope.aModel, the original template will now work.

Note: The entire scope is now visible to your modal so you can also access $scope.users in it.

<div my-modal id="encouragementModal" class="modal hide fade">
  <div class="modal-header">
    <button type="button" class="close" data-dismiss="modal"
      aria-hidden="true">&times;</button>
    <h3>Confirm encouragement?</h3>
  </div>
  <div class="modal-body">
      Do you really want to encourage <b>{{aModel.userName}}</b>?
  </div>
  <div class="modal-footer">
    <button class="btn btn-info"
      ng-click="encourage('${createLink(uri: '/encourage/')}',{{aModel.userName}})">
      Confirm
    </button>
    <button class="btn" data-dismiss="modal" aria-hidden="true">Never Mind</button>
  </div>
</div>

C++ Error 'nullptr was not declared in this scope' in Eclipse IDE

Trying with a different version of gcc worked for me - gcc 4.9 in my case.

Replacing few values in a pandas dataframe column with another value

The easiest way is to use the replace method on the column. The arguments are a list of the things you want to replace (here ['ABC', 'AB']) and what you want to replace them with (the string 'A' in this case):

>>> df['BrandName'].replace(['ABC', 'AB'], 'A')
0    A
1    B
2    A
3    D
4    A

This creates a new Series of values so you need to assign this new column to the correct column name:

df['BrandName'] = df['BrandName'].replace(['ABC', 'AB'], 'A')

Converting ISO 8601-compliant String to java.util.Date

The way that is blessed by Java 7 documentation:

DateFormat df1 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSZ");
String string1 = "2001-07-04T12:08:56.235-0700";
Date result1 = df1.parse(string1);

DateFormat df2 = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss.SSSXXX");
String string2 = "2001-07-04T12:08:56.235-07:00";
Date result2 = df2.parse(string2);

You can find more examples in section Examples at SimpleDateFormat javadoc.

UPD 02/13/2020: There is a completely new way to do this in Java 8

How to update the value of a key in a dictionary in Python?

Well you could directly substract from the value by just referencing the key. Which in my opinion is simpler.

>>> books = {}
>>> books['book'] = 3       
>>> books['book'] -= 1   
>>> books   
{'book': 2}   

In your case:

book_shop[ch1] -= 1

What are the differences in die() and exit() in PHP?

There's no difference - they are the same.

PHP Manual for exit:

Note: This language construct is equivalent to die().

PHP Manual for die:

This language construct is equivalent to exit().

Python and pip, list all versions of a package that's available?

You can use this small Python 3 script (using only standard library modules) to grab the list of available versions for a package from PyPI using JSON API and print them in reverse chronological order. Unlike some other Python solutions posted here, this doesn't break on loose versions like django's 2.2rc1 or uwsgi's 2.0.17.1:

#!/usr/bin/env python3

import json
import sys
from urllib import request    
from pkg_resources import parse_version    

def versions(pkg_name):
    url = f'https://pypi.python.org/pypi/{pkg_name}/json'
    releases = json.loads(request.urlopen(url).read())['releases']
    return sorted(releases, key=parse_version, reverse=True)    

if __name__ == '__main__':
    print(*versions(sys.argv[1]), sep='\n')

Save the script and run it with the package name as an argument, e.g.:

python versions.py django
3.0a1
2.2.5
2.2.4
2.2.3
2.2.2
2.2.1
2.2
2.2rc1
...

Testing if value is a function

Make sure you are calling typeof on the actual function, not a string literal:

function x() { 
    console.log("hi"); 
}

typeof "x"; // returns "string"

typeof x; // returns "function"

How to access html form input from asp.net code behind

What I'm guessing is that you need to set those input elements to runat="server".

So you won't be able to access the control

<input type="text" name="email" id="myTextBox" />

But you'll be able to work with

<input type="text" name="email" id="myTextBox" runat="server" />

And read from it by using

string myStringFromTheInput = myTextBox.Value;

Bat file to run a .exe at the command prompt

Just stick in a file and call it "ServiceModelSamples.bat" or something.

You could add "@echo off" as line one, so the command doesn't get printed to the screen:

@echo off
svcutil.exe /language:cs /out:generatedProxy.cs /config:app.config http://localhost:8000/ServiceModelSamples/service

How to pass an array to a function in VBA?

This seems unnecessary, but VBA is a strange place. If you declare an array variable, then set it using Array() then pass the variable into your function, VBA will be happy.

Sub test()
    Dim fString As String
    Dim arr() As Variant
    arr = Array("foo", "bar")
    fString = processArr(arr)
End Sub

Also your function processArr() could be written as:

Function processArr(arr() As Variant) As String
    processArr = Replace(Join(arr()), " ", "")
End Function

If you are into the whole brevity thing.

How to get a list column names and datatypes of a table in PostgreSQL?

Below will list all the distinct data types of all the table in the provided schema name.

\copy (select distinct data_type, column_name from information_schema.columns where table_name in (SELECT tablename FROM pg_catalog.pg_tables WHERE schemaname != 'pg_catalog' AND schemaname != 'information_schema' and schemaname = '<Your schema name>')) to 'datatypes.csv'  delimiter as ',' CSV header

How to get the full URL of a Drupal page?

drupal_get_destination() has some internal code that points at the correct place to getthe current internal path. To translate that path into an absolute URL, the url() function should do the trick. If the 'absolute' option is passed in it will generate the full URL, not just the internal path. It will also swap in any path aliases for the current path as well.

$path = isset($_GET['q']) ? $_GET['q'] : '<front>';
$link = url($path, array('absolute' => TRUE));

Angular.js: How does $eval work and why is it different from vanilla eval?

From the test,

it('should allow passing locals to the expression', inject(function($rootScope) {
  expect($rootScope.$eval('a+1', {a: 2})).toBe(3);

  $rootScope.$eval(function(scope, locals) {
    scope.c = locals.b + 4;
  }, {b: 3});
  expect($rootScope.c).toBe(7);
}));

We also can pass locals for evaluation expression.

How to navigate a few folders up?

You can use ..\path to go one level up, ..\..\path to go two levels up from path.

You can use Path class too.

C# Path class

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

Almost all answers assume the ID column is ordered (and perhaps auto incremented). There are situations, however, when the ID column is not ordered, hence the ORDER BY statement makes no sense.

The last inserted ID might not always be the highest ID, it is just the last (unique) entry.

One possible solution for such a situation is to create a row id on the fly:

SET @r = 0;
SELECT * FROM (SELECT *, (@r := @r + 1) AS r_id FROM uat3187) AS tmp
    ORDER BY r_id DESC LIMIT 1;

Send POST data via raw json with postman

meda's answer is completely legit, but when I copied the code I got an error!

Somewhere in the "php://input" there's an invalid character (maybe one of the quotes?).

When I typed the "php://input" code manually, it worked. Took me a while to figure out!

Using jQuery UI sortable with HTML tables

You can call sortable on a <tbody> instead of on the individual rows.

<table>
    <tbody>
        <tr> 
            <td>1</td>
            <td>2</td>
        </tr>
        <tr>
            <td>3</td>
            <td>4</td> 
        </tr>
        <tr>
            <td>5</td>
            <td>6</td>
        </tr>  
    </tbody>    
</table>?

<script>
    $('tbody').sortable();
</script> 

_x000D_
_x000D_
$(function() {_x000D_
  $( "tbody" ).sortable();_x000D_
});
_x000D_
 _x000D_
table {_x000D_
    border-spacing: collapse;_x000D_
    border-spacing: 0;_x000D_
}_x000D_
td {_x000D_
    width: 50px;_x000D_
    height: 25px;_x000D_
    border: 1px solid black;_x000D_
}
_x000D_
 _x000D_
_x000D_
<link href="//code.jquery.com/ui/1.11.1/themes/smoothness/jquery-ui.css" rel="stylesheet">_x000D_
<script src="//code.jquery.com/jquery-1.11.1.js"></script>_x000D_
<script src="//code.jquery.com/ui/1.11.1/jquery-ui.js"></script>_x000D_
_x000D_
<table>_x000D_
    <tbody>_x000D_
        <tr>_x000D_
            <td>1</td>_x000D_
            <td>2</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>3</td>_x000D_
            <td>4</td>_x000D_
        </tr>_x000D_
        <tr> _x000D_
            <td>5</td>_x000D_
            <td>6</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>7</td>_x000D_
            <td>8</td>_x000D_
        </tr>_x000D_
        <tr>_x000D_
            <td>9</td> _x000D_
            <td>10</td>_x000D_
        </tr>  _x000D_
    </tbody>    _x000D_
</table>
_x000D_
_x000D_
_x000D_

How is malloc() implemented internally?

It's also important to realize that simply moving the program break pointer around with brk and sbrk doesn't actually allocate the memory, it just sets up the address space. On Linux, for example, the memory will be "backed" by actual physical pages when that address range is accessed, which will result in a page fault, and will eventually lead to the kernel calling into the page allocator to get a backing page.

Android : Fill Spinner From Java Code Programmatically

Here is an example to fully programmatically:

  • init a Spinner.
  • fill it with data via a String List.
  • resize the Spinner and add it to my View.
  • format the Spinner font (font size, colour, padding).
  • clear the Spinner.
  • add new values to the Spinner.
  • redraw the Spinner.

I am using the following class vars:

Spinner varSpinner;
List<String> varSpinnerData;

float varScaleX;
float varScaleY;    

A - Init and render the Spinner (varRoot is a pointer to my main Activity):

public void renderSpinner() {


    List<String> myArraySpinner = new ArrayList<String>();

    myArraySpinner.add("red");
    myArraySpinner.add("green");
    myArraySpinner.add("blue");     

    varSpinnerData = myArraySpinner;

    Spinner mySpinner = new Spinner(varRoot);               

    varSpinner = mySpinner;

    ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(varRoot, android.R.layout.simple_spinner_item, myArraySpinner);
    spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); // The drop down vieww
    mySpinner.setAdapter(spinnerArrayAdapter);

B - Resize and Add the Spinner to my View:

    FrameLayout.LayoutParams myParamsLayout = new FrameLayout.LayoutParams(
            FrameLayout.LayoutParams.MATCH_PARENT, 
            FrameLayout.LayoutParams.WRAP_CONTENT);
    myParamsLayout.gravity = Gravity.NO_GRAVITY;             

    myParamsLayout.leftMargin = (int) (100 * varScaleX);
    myParamsLayout.topMargin = (int) (350 * varScaleY);             
    myParamsLayout.width = (int) (300 * varScaleX);;
    myParamsLayout.height = (int) (60 * varScaleY);;


    varLayoutECommerce_Dialogue.addView(mySpinner, myParamsLayout);

C - Make the Click handler and use this to set the font.

    mySpinner.setOnItemSelectedListener(new OnItemSelectedListener() {

        @Override
        public void onItemSelected(AdapterView<?> parentView, View selectedItemView, int myPosition, long myID) {

            Log.i("renderSpinner -> ", "onItemSelected: " + myPosition + "/" + myID);

            ((TextView) parentView.getChildAt(0)).setTextColor(Color.GREEN);
            ((TextView) parentView.getChildAt(0)).setTextSize(TypedValue.COMPLEX_UNIT_PX, (int) (varScaleY * 22.0f) );
            ((TextView) parentView.getChildAt(0)).setPadding(1,1,1,1);


        }

        @Override
        public void onNothingSelected(AdapterView<?> parentView) {
            // your code here
        }

    });

}   

D - Update the Spinner with new data:

private void updateInitSpinners(){

     String mySelected = varSpinner.getSelectedItem().toString();
     Log.i("TPRenderECommerce_Dialogue -> ", "updateInitSpinners -> mySelected: " + mySelected);


     varSpinnerData.clear();

     varSpinnerData.add("Hello World");
     varSpinnerData.add("Hello World 2");

     ((BaseAdapter) varSpinner.getAdapter()).notifyDataSetChanged();
     varSpinner.invalidate();
     varSpinner.setSelection(1);

}

}

What I have not been able to solve in the updateInitSpinners, is to do varSpinner.setSelection(0); and have the custom font settings activated automatically.

UPDATE:

This "ugly" solution solves the varSpinner.setSelection(0); issue, but I am not very happy with it:

private void updateInitSpinners(){

    String mySelected = varSpinner.getSelectedItem().toString();
    Log.i("TPRenderECommerce_Dialogue -> ", "updateInitSpinners -> mySelected: " + mySelected);


    varSpinnerData.clear();

    ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(varRoot, android.R.layout.simple_spinner_item, varSpinnerData);
    spinnerArrayAdapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item); 
    varSpinner.setAdapter(spinnerArrayAdapter);  


    varSpinnerData.add("Hello World");
    varSpinnerData.add("Hello World 2");

    ((BaseAdapter) varSpinner.getAdapter()).notifyDataSetChanged();
    varSpinner.invalidate();
    varSpinner.setSelection(0);

}

}

Hope this helps......

Switch php versions on commandline ubuntu 16.04

I made a bash script to switch between different PHP versions on Ubuntu.

Hope it helps someone.

Here's the script: (save it in /usr/local/bin/sphp.sh, don't forget to add +x flag with command: sudo chmod +x /usr/local/bin/sphp.sh)

_x000D_
_x000D_
#!/bin/bash_x000D_
_x000D_
# Usage_x000D_
if [ $# -ne 1 ]; then_x000D_
  echo "Usage: sphp [phpversion]"_x000D_
  echo "Example: sphp 7.2"_x000D_
  exit 1_x000D_
fi_x000D_
_x000D_
currentversion="`php -r \"error_reporting(0); echo str_replace('.', '', substr(phpversion(), 0, 3));\"`"_x000D_
newversion="$1"_x000D_
_x000D_
majorOld=${currentversion:0:1}_x000D_
minorOld=${currentversion:1:1}_x000D_
majorNew=${newversion:0:1}_x000D_
minorNew=${newversion:2:1}_x000D_
_x000D_
if [ $? -eq 0 ]; then_x000D_
  if [ "${newversion}" == "${currentversion}" ]; then_x000D_
    echo "PHP version [${newversion}] is already being used"_x000D_
    exit 1_x000D_
  fi_x000D_
_x000D_
  echo "PHP version [$newversion] found"_x000D_
  echo "Switching from [php${currentversion}] to [php${newversion}] ... "_x000D_
_x000D_
  printf "a2dismod php$majorOld.$minorOld ... "_x000D_
  sudo a2dismod "php${majorOld}.${minorOld}"_x000D_
  printf "[OK] and "_x000D_
_x000D_
  printf "a2enmod php${newversion} ... "_x000D_
  sudo a2enmod "php${majorNew}.${minorNew}"_x000D_
  printf "[OK]\n"_x000D_
_x000D_
  printf "update-alternatives ... "_x000D_
  sudo update-alternatives --set php "/usr/bin/php${majorNew}.${minorNew}"_x000D_
  printf "[OK]\n"_x000D_
_x000D_
  sudo service apache2 restart_x000D_
  printf "[OK] apache2 restarted\n"_x000D_
else_x000D_
  echo "PHP version $majorNew.$minorNew was not found."_x000D_
  echo "Try \`sudo apt install php@${newversion}\` first."_x000D_
  exit 1_x000D_
fi_x000D_
_x000D_
echo "DONE!"
_x000D_
_x000D_
_x000D_

Regex to check whether a string contains only numbers

\d will not match the decimal point. Use the following for the decimal.

const re = /^\d*(\.\d+)?$/
'123'.match(re)       // true
'123.3'.match(re)     // true
'123!3'.match(re)     // false

Submitting a multidimensional array via POST with php

On submitting, you would get an array as if created like this:

$_POST['topdiameter'] = array( 'first value', 'second value' );
$_POST['bottomdiameter'] = array( 'first value', 'second value' );

However, I would suggest changing your form names to this format instead:

name="diameters[0][top]"
name="diameters[0][bottom]"
name="diameters[1][top]"
name="diameters[1][bottom]"
...

Using that format, it's much easier to loop through the values.

if ( isset( $_POST['diameters'] ) )
{
    echo '<table>';
    foreach ( $_POST['diameters'] as $diam )
    {
        // here you have access to $diam['top'] and $diam['bottom']
        echo '<tr>';
        echo '  <td>', $diam['top'], '</td>';
        echo '  <td>', $diam['bottom'], '</td>';
        echo '</tr>';
    }
    echo '</table>';
}

How do I enter a multi-line comment in Perl?

I found it. Perl has multi-line comments:

#!/usr/bin/perl

use strict;

use warnings;

=for comment

Example of multiline comment.

Example of multiline comment.

=cut

print "Multi Line Comment Example \n";

iCheck check if checkbox is checked

Use this code for iCheck:

$('.i-checks').iCheck({
    checkboxClass: 'icheckbox_square-green',
    radioClass: 'iradio_square-green',
}).on('ifChanged', function(e) {
    // Get the field name
    var isChecked = e.currentTarget.checked;

    if (isChecked == true) {

    }
});

joining two select statements

Not sure what you are trying to do, but you have two select clauses. Do this instead:

SELECT * 
FROM ( SELECT * 
       FROM orders_products 
       INNER JOIN orders ON orders_products.orders_id = orders.orders_id 
       WHERE products_id = 181) AS A
JOIN ( SELECT * 
       FROM orders_products 
       INNER JOIN orders ON orders_products.orders_id = orders.orders_id
       WHERE products_id = 180) AS B

ON A.orders_id=B.orders_id

Update:

You could probably reduce it to something like this:

SELECT o.orders_id, 
       op1.products_id, 
       op1.quantity, 
       op2.products_id, 
       op2.quantity
FROM orders o
INNER JOIN orders_products op1 on o.orders_id = op1.orders_id  
INNER JOIN orders_products op2 on o.orders_id = op2.orders_id  
WHERE op1.products_id = 180
AND op2.products_id = 181

Debugging JavaScript in IE7

If you still need to Debug IE 7, the emulation mode of IE 11 is working pretty well.

Go to menu: Dev Tools, then to emulation and set it. It also gives error line information.

Using pip behind a proxy with CNTLM

Set up invironment variable in Advanced System Settings. In Command prompt it should behave like this :

C:\Windows\system32>echo %http_proxy%

http://username:passowrd@proxy:port

C:\Windows\system32>echo %https_proxy%

http://username:password@proxy:port

Later , Simply pip install whatEver should work.

How to start rails server?

For newest Rails versions

If you have trouble with rails s, sometimes terminal fails.

And you should try to use:

./bin/rails

To access command.

Working with INTERVAL and CURDATE in MySQL

I usually use

DATE_ADD(CURDATE(), INTERVAL - 1 MONTH)

Which is almost same as Pekka's but this way you can control your INTERVAL to be negative or positive...

What is a handle in C++?

A handle is whatever you want it to be.

A handle can be a unsigned integer used in some lookup table.

A handle can be a pointer to, or into, a larger set of data.

It depends on how the code that uses the handle behaves. That determines the handle type.

The reason the term 'handle' is used is what is important. That indicates them as an identification or access type of object. Meaning, to the programmer, they represent a 'key' or access to something.

How can I declare a global variable in Angular 2 / Typescript?

A shared service is the best approach

export class SharedService {
  globalVar:string;
}

But you need to be very careful when registering it to be able to share a single instance for whole your application. You need to define it when registering your application:

bootstrap(AppComponent, [SharedService]);

But not to define it again within the providers attributes of your components:

@Component({
  (...)
  providers: [ SharedService ], // No
  (...)
})

Otherwise a new instance of your service will be created for the component and its sub-components.

You can have a look at this question regarding how dependency injection and hierarchical injectors work in Angular 2:

You should notice that you can also define Observable properties in the service to notify parts of your application when your global properties change:

export class SharedService {
  globalVar:string;
  globalVarUpdate:Observable<string>;
  globalVarObserver:Observer;

  constructor() {
    this.globalVarUpdate = Observable.create((observer:Observer) => {
      this.globalVarObserver = observer;
    });
  }

  updateGlobalVar(newValue:string) {
    this.globalVar = newValue;
    this.globalVarObserver.next(this.globalVar);
  }
}

See this question for more details:

Convert a String to Modified Camel Case in Java or Title Case as is otherwise called

I used the below to solve this problem.

import org.apache.commons.lang.StringUtils;
StringUtils.capitalize(MyString);

Thanks to Ted Hopp for rightly pointing out that the question should have been TITLE CASE instead of modified CAMEL CASE.

Camel Case is usually without spaces between words.

Creating a chart in Excel that ignores #N/A or blank cells

Select the labels above the bar. Format Data Labels. Instead of selecting "VALUE" (unclick). SELECT Value from cells. Select the value. Use the following statement: if(cellvalue="","",cellvalue) where cellvalue is what ever the calculation is in the cell.

jQuery - setting the selected value of a select control via its text description

I had a problem with the examples above, and the problem was caused by the fact that my select box values are prefilled with fixed length strings of 6 characters, but the parameter being passed in wasn't fixed length.

I have an rpad function which will right pad a string, to the length specified, and with the specified character. So, after padding the parameter it works.

$('#wsWorkCenter').val(rpad(wsWorkCenter, 6, ' '));


function rpad(pStr, pLen, pPadStr) {
if (pPadStr == '') {pPadStr == ' '};
while (pStr.length < pLen)
    pStr = pStr + pPadStr;
return pStr; 
} 

Logging request/response messages when using HttpClient

See http://mikehadlow.blogspot.com/2012/07/tracing-systemnet-to-debug-http-clients.html

To configure a System.Net listener to output to both the console and a log file, add the following to your assembly configuration file:

<system.diagnostics>
  <trace autoflush="true" />
  <sources>
    <source name="System.Net">
      <listeners>
        <add name="MyTraceFile"/>
        <add name="MyConsole"/>
      </listeners>
    </source>
  </sources>
  <sharedListeners>
    <add
      name="MyTraceFile"
      type="System.Diagnostics.TextWriterTraceListener"
      initializeData="System.Net.trace.log" />
    <add name="MyConsole" type="System.Diagnostics.ConsoleTraceListener" />
  </sharedListeners>
  <switches>
    <add name="System.Net" value="Verbose" />
  </switches>
</system.diagnostics>

In the shell, what does " 2>&1 " mean?

Redirecting Input

Redirection of input causes the file whose name results from the expansion of word to be opened for reading on file descriptor n, or the standard input (file descriptor 0) if n is not specified.

The general format for redirecting input is:

[n]<word

Redirecting Output

Redirection of output causes the file whose name results from the expansion of word to be opened for writing on file descriptor n, or the standard output (file descriptor 1) if n is not specified. If the file does not exist it is created; if it does exist it is truncated to zero size.

The general format for redirecting output is:

[n]>word

Moving File Descriptors

The redirection operator,

[n]<&digit-

moves the file descriptor digit to file descriptor n, or the standard input (file descriptor 0) if n is not specified. digit is closed after being duplicated to n.

Similarly, the redirection operator

[n]>&digit-

moves the file descriptor digit to file descriptor n, or the standard output (file descriptor 1) if n is not specified.

Ref:

man bash

Type /^REDIRECT to locate to the redirection section, and learn more...

An online version is here: 3.6 Redirections

PS:

Lots of the time, man was the powerful tool to learn Linux.

makefile execute another target

If you removed the make all line from your "fresh" target:

fresh :
    rm -f *.o $(EXEC)
    clear

You could simply run the command make fresh all, which will execute as make fresh; make all.

Some might consider this as a second instance of make, but it's certainly not a sub-instance of make (a make inside of a make), which is what your attempt seemed to result in.

gcc-arm-linux-gnueabi command not found

Its a bit counter-intuitive. The toolchain is called gcc-arm-linux-gnueabi. To invoke the tools execute the following: arm-linux-gnueabi-xxx

where xxx is gcc or ar or ld, etc

php string to int

You can remove the spaces before casting to int:

(int)str_replace(' ', '', $b);

Also, if you want to strip other commonly used digit delimiters (such as ,), you can give the function an array (beware though -- in some countries, like mine for example, the comma is used for fraction notation):

(int)str_replace(array(' ', ','), '', $b);

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

I used this way in my code

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

Setting unique Constraint with fluent API?

On EF6.2, you can use HasIndex() to add indexes for migration through fluent API.

https://github.com/aspnet/EntityFramework6/issues/274

Example

modelBuilder
    .Entity<User>()
    .HasIndex(u => u.Email)
        .IsUnique();

On EF6.1 onwards, you can use IndexAnnotation() to add indexes for migration in your fluent API.

http://msdn.microsoft.com/en-us/data/jj591617.aspx#PropertyIndex

You must add reference to:

using System.Data.Entity.Infrastructure.Annotations;

Basic Example

Here is a simple usage, adding an index on the User.FirstName property

modelBuilder 
    .Entity<User>() 
    .Property(t => t.FirstName) 
    .HasColumnAnnotation(IndexAnnotation.AnnotationName, new IndexAnnotation(new IndexAttribute()));

Practical Example:

Here is a more realistic example. It adds a unique index on multiple properties: User.FirstName and User.LastName, with an index name "IX_FirstNameLastName"

modelBuilder 
    .Entity<User>() 
    .Property(t => t.FirstName) 
    .IsRequired()
    .HasMaxLength(60)
    .HasColumnAnnotation(
        IndexAnnotation.AnnotationName, 
        new IndexAnnotation(
            new IndexAttribute("IX_FirstNameLastName", 1) { IsUnique = true }));

modelBuilder 
    .Entity<User>() 
    .Property(t => t.LastName) 
    .IsRequired()
    .HasMaxLength(60)
    .HasColumnAnnotation(
        IndexAnnotation.AnnotationName, 
        new IndexAnnotation(
            new IndexAttribute("IX_FirstNameLastName", 2) { IsUnique = true }));

Eclipse, regular expression search and replace

NomeN has answered correctly, but this answer wouldn't be of much use for beginners like me because we will have another problem to solve and we wouldn't know how to use RegEx in there. So I am adding a bit of explanation to this. The answer is

search: (\w+\\.someMethod\\(\\))

replace: ((TypeName)$1)

Here:

In search:

  • First and last (, ) depicts a group in regex

  • \w depicts words (alphanumeric + underscore)

  • + depicts one or more (ie one or more of alphanumeric + underscore)

  • . is a special character which depicts any character (ie .+ means one or more of any character). Because this is a special character to depict a . we should give an escape character with it, ie \.

  • someMethod is given as it is to be searched.

  • The two parenthesis (, ) are given along with escape character because they are special character which are used to depict a group (we will discuss about group in next point)

In replace:

  • It is given ((TypeName)$1), here $1 depicts the group. That is all the characters that are enclosed within the first and last parenthesis (, ) in the search field

  • Also make sure you have checked the 'Regular expression' option in find an replace box

How can I split a JavaScript string by white space or comma?

"my, tags are, in here".split(/[ ,]+/)

the result is :

["my", "tags", "are", "in", "here"]

How to count down in for loop?

If you google. "Count down for loop python" you get these, which are pretty accurate.

how to loop down in python list (countdown)
Loop backwards using indices in Python?

I recommend doing minor searches before posting. Also "Learn Python The Hard Way" is a good place to start.

Which is the default location for keystore/truststore of Java applications?

In Java, according to the JSSE Reference Guide, there is no default for the keystore, the default for the truststore is "jssecacerts, if it exists. Otherwise, cacerts".

A few applications use ~/.keystore as a default keystore, but this is not without problems (mainly because you might not want all the application run by the user to use that trust store).

I'd suggest using application-specific values that you bundle with your application instead, it would tend to be more applicable in general.

How to do associative array/hashing in JavaScript

In C# the code looks like:

Dictionary<string,int> dictionary = new Dictionary<string,int>();
dictionary.add("sample1", 1);
dictionary.add("sample2", 2);

or

var dictionary = new Dictionary<string, int> {
    {"sample1", 1},
    {"sample2", 2}
};

In JavaScript:

var dictionary = {
    "sample1": 1,
    "sample2": 2
}

A C# dictionary object contains useful methods, like dictionary.ContainsKey()

In JavaScript, we could use the hasOwnProperty like:

if (dictionary.hasOwnProperty("sample1"))
    console.log("sample1 key found and its value is"+ dictionary["sample1"]);

Python if-else short-hand

Try this:

x = a > b and 10 or 11

This is a sample of execution:

>>> a,b=5,7
>>> x = a > b and 10 or 11
>>> print x
11

Error in eval(expr, envir, enclos) : object not found

Don't know why @Janos deleted his answer, but it's correct: your data frame Train doesn't have a column named pre. When you pass a formula and a data frame to a model-fitting function, the names in the formula have to refer to columns in the data frame. Your Train has columns called residual.sugar, total.sulfur, alcohol and quality. You need to change either your formula or your data frame so they're consistent with each other.

And just to clarify: Pre is an object containing a formula. That formula contains a reference to the variable pre. It's the latter that has to be consistent with the data frame.

How to solve “Microsoft Visual Studio (VS)” error “Unable to connect to the configured development Web server”

SOLUTION

This means that you are missing the right for using it. Create it with Netsh Commands for Hypertext Transfer Protocol > add urlacl.

1) Open "Command Line Interface (CLI)" called "Command shell" with Win+R write "cmd"

2) Open CLI windows like administrator with mouse context menu on opened windows or icon "Run as administrator"

3) Insert command to register url

netsh http add urlacl url=http://{ip_addr}:{port}/ user=everyone

NOTE:

Android Imagebutton change Image OnClick

This misled me a bit - it should be setImageResource instead of setBackgroundResource :) !!

The following works fine :

ImageButton btn = (ImageButton)findViewById(R.id.imageButton1);       
 btn.setImageResource(R.drawable.actions_record);

while when using the setBackgroundResource the actual imagebutton's image stays while the background image is changed which leads to a ugly looking imageButton object

Thanks.

How to pass credentials to the Send-MailMessage command for sending emails

PSH> $cred = Get-Credential

PSH> $cred | Export-CliXml c:\temp\cred.clixml

PSH> $cred2 = Import-CliXml c:\temp\cred.clixml

That hashes it against your SID and the machine's SID, so the file is useless on any other machine, or in anyone else's hands.

Why can't I define my workbook as an object?

You'll need to open the workbook to refer to it.

Sub Setwbk()

    Dim wbk As Workbook

    Set wbk = Workbooks.Open("F:\Quarterly Reports\2012 Reports\New Reports\ _
        Master Benchmark Data Sheet.xlsx")

End Sub

* Follow Doug's answer if the workbook is already open. For the sake of making this answer as complete as possible, I'm including my comment on his answer:

Why do I have to "set" it?

Set is how VBA assigns object variables. Since a Range and a Workbook/Worksheet are objects, you must use Set with these.

How to delete columns in a CSV file?

Off the top of my head, this will do it without any sort of error checking nor ability to configure anything. That is "left to the reader".

outFile = open( 'newFile', 'w' )
for line in open( 'oldFile' ):
   items = line.split( ',' )
   outFile.write( ','.join( items[:2] + items[ 3: ] ) )
outFile.close()

Change MySQL root password in phpMyAdmin

You can change the mysql root password by logging in to the database directly (mysql -h your_host -u root) then run

SET PASSWORD FOR root@localhost = PASSWORD('yourpassword');

How do malloc() and free() work?

OK some answers about malloc were already posted.

The more interesting part is how free works (and in this direction, malloc too can be understood better).

In many malloc/free implementations, free does normally not return the memory to the operating system (or at least only in rare cases). The reason is that you will get gaps in your heap and thus it can happen, that you just finish off your 2 or 4 GB of virtual memory with gaps. This should be avoided, since as soon as the virtual memory is finished, you will be in really big trouble. The other reason is, that the OS can only handle memory chunks that are of a specific size and alignment. To be specific: Normally the OS can only handle blocks that the virtual memory manager can handle (most often multiples of 512 bytes e.g. 4KB).

So returning 40 Bytes to the OS will just not work. So what does free do?

Free will put the memory block in its own free block list. Normally it also tries to meld together adjacent blocks in the address space. The free block list is just a circular list of memory chunks which have some administrative data in the beginning. This is also the reason why managing very small memory elements with the standard malloc/free is not efficient. Every memory chunk needs additional data and with smaller sizes more fragmentation happens.

The free-list is also the first place that malloc looks at when a new chunk of memory is needed. It is scanned before it calls for new memory from the OS. When a chunk is found that is bigger than the needed memory, it is divided into two parts. One is returned to caller, the other is put back into the free list.

There are many different optimizations to this standard behaviour (for example for small chunks of memory). But since malloc and free must be so universal, the standard behaviour is always the fallback when alternatives are not usable. There are also optimizations in handling the free-list — for example storing the chunks in lists sorted by sizes. But all optimizations also have their own limitations.

Why does your code crash:

The reason is that by writing 9 chars (don't forget the trailing null byte) into an area sized for 4 chars, you will probably overwrite the administrative-data stored for another chunk of memory that resides "behind" your chunk of data (since this data is most often stored "in front" of the memory chunks). When free then tries to put your chunk into the free list, it can touch this administrative-data and therefore stumble over an overwritten pointer. This will crash the system.

This is a rather graceful behaviour. I have also seen situations where a runaway pointer somewhere has overwritten data in the memory-free-list and the system did not immediately crash but some subroutines later. Even in a system of medium complexity such problems can be really, really hard to debug! In the one case I was involved, it took us (a larger group of developers) several days to find the reason of the crash -- since it was in a totally different location than the one indicated by the memory dump. It is like a time-bomb. You know, your next "free" or "malloc" will crash, but you don't know why!

Those are some of the worst C/C++ problems, and one reason why pointers can be so problematic.

Define static method in source-file with declaration in header-file in C++

Static member functions must refer to static variables of that class. So in your case,

static void CP_StringToPString( std::string& inString, unsigned char *outString);

Since your member function CP_StringToPstring is static, the parameters in that function, inString and outString should be declared as static too.

The static member functions does not refer to the object that it is working on but the variables your declared refers to its current object so it return error.

You could either remove the static from the member function or add static while declaring the parameters you used for the member function as static too.

How to overcome "'aclocal-1.15' is missing on your system" warning?

Before running ./configure try running autoreconf -f -i. The autoreconf program automatically runs autoheader, aclocal, automake, autopoint and libtoolize as required.

Edit to add: This is usually caused by checking out code from Git instead of extracting it from a .zip or .tar.gz archive. In order to trigger rebuilds when files change, Git does not preserve files' timestamps, so the configure script might appear to be out of date. As others have mentioned, there are ways to get around this if you don't have a sufficiently recent version of autoreconf.

Another edit: This error can also be caused by copying the source folder extracted from an archive with scp to another machine. The timestamps can be updated, suggesting that a rebuild is necessary. To avoid this, copy the archive and extract it in place.

What is an example of the simplest possible Socket.io example?

Here is my submission!

if you put this code into a file called hello.js and run it using node hello.js it should print out the message hello, it has been sent through 2 sockets.

The code shows how to handle the variables for a hello message bounced from the client to the server via the section of code labelled //Mirror.

The variable names are declared locally rather than all at the top because they are only used in each of the sections between the comments. Each of these could be in a separate file and run as its own node.

_x000D_
_x000D_
// Server_x000D_
var io1 = require('socket.io').listen(8321);_x000D_
_x000D_
io1.on('connection', function(socket1) {_x000D_
  socket1.on('bar', function(msg1) {_x000D_
    console.log(msg1);_x000D_
  });_x000D_
});_x000D_
_x000D_
// Mirror_x000D_
var ioIn = require('socket.io').listen(8123);_x000D_
var ioOut = require('socket.io-client');_x000D_
var socketOut = ioOut.connect('http://localhost:8321');_x000D_
_x000D_
_x000D_
ioIn.on('connection', function(socketIn) {_x000D_
  socketIn.on('foo', function(msg) {_x000D_
    socketOut.emit('bar', msg);_x000D_
  });_x000D_
});_x000D_
_x000D_
// Client_x000D_
var io2 = require('socket.io-client');_x000D_
var socket2 = io2.connect('http://localhost:8123');_x000D_
_x000D_
var msg2 = "hello";_x000D_
socket2.emit('foo', msg2);
_x000D_
_x000D_
_x000D_

Rotating videos with FFmpeg

Alexy's answer almost worked for me except that I was getting this error:

timebase 1/90000 not supported by MPEG 4 standard, the maximum admitted value for the timebase denominator is 65535

I just had to add a parameter (-r 65535/2733) to the command and it worked. The full command was thus:

ffmpeg -i in.mp4 -vf "transpose=1" -r 65535/2733 out.mp4

Update all objects in a collection using LINQ

I actually found an extension method that will do what I want nicely

public static IEnumerable<T> ForEach<T>(
    this IEnumerable<T> source,
    Action<T> act)
{
    foreach (T element in source) act(element);
    return source;
}

How to test enum types?

you can test if have exactly some values, by example:

for(MyBoolean b : MyBoolean.values()) {
    switch(b) {
    case TRUE:
        break;
    case FALSE:
        break;
    default:
        throw new IllegalArgumentException(b.toString());
}

for(String s : new String[]{"TRUE", "FALSE" }) {
    MyBoolean.valueOf(s);
}

If someone removes or adds a value, some of test fails.

How to trim white spaces of array values in php

array_map('trim', $data) would convert all subarrays into null. If it is needed to trim spaces only for strings and leave other types as it is, you can use:

$data = array_map(
    function ($item) {
        return is_string($item) ? trim($item) : $item;
    },
    $data
);

Protractor : How to wait for page complete after click a button?

With Protractor, you can use the following approach

var EC = protractor.ExpectedConditions;
// Wait for new page url to contain newPageName
browser.wait(EC.urlContains('newPageName'), 10000);

So your code will look something like,

emailEl.sendKeys('jack');
passwordEl.sendKeys('123pwd');

btnLoginEl.click();

var EC = protractor.ExpectedConditions;
// Wait for new page url to contain efg
ptor.wait(EC.urlContains('efg'), 10000);

expect(ptor.getCurrentUrl()).toEqual(url + 'abc#/efg');

Note: This may not mean that new page has finished loading and DOM is ready. The subsequent 'expect()' statement will ensure Protractor waits for DOM to be available for test.

Reference: Protractor ExpectedConditions

Why doesn't TFS get latest get the latest?

Most of the issues I've seen with developers complaining that Get Latest doesn't do what they expect stem from the fact that they're performing a Get Latest from Solution Explorer rather than from Source Control Explorer. Solution Explorer only gets the files that are part of the solution and ignores anything that may be required by files within the solution, and therefore part of source control, whereas Source Control explorer compares your local workspace against the repository on the server to determine which files are needed.

How do I change the title of the "back" button on a Navigation Bar

Use below line of code :

UIBarButtonItem *newBackButton =
[[UIBarButtonItem alloc] initWithTitle:@"hello"
                                 style:UIBarButtonItemStylePlain
                                target:nil
                                action:nil];

self.navigationItem.leftBarButtonItems =[[NSArray alloc] initWithObjects:newBackButton, nil];

self.navigationItem.leftItemsSupplementBackButton = YES;

shell init issue when click tab, what's wrong with getcwd?

This usually occurs when your current directory does not exist anymore. Most likely, from another terminal you remove that directory (from within a script or whatever). To get rid of this, in case your current directory was recreated in the meantime, just cd to another (existing) directory and then cd back; the simplest would be: cd; cd -.

How to inherit constructors?

As Foo is a class can you not create virtual overloaded Initialise() methods? Then they would be available to sub-classes and still extensible?

public class Foo
{
   ...
   public Foo() {...}

   public virtual void Initialise(int i) {...}
   public virtual void Initialise(int i, int i) {...}
   public virtual void Initialise(int i, int i, int i) {...}
   ... 
   public virtual void Initialise(int i, int i, ..., int i) {...}

   ...

   public virtual void SomethingElse() {...}
   ...
}

This shouldn't have a higher performance cost unless you have lots of default property values and you hit it a lot.

trying to align html button at the center of the my page

I've really taken recently to display: table to give things a fixed size such as to enable margin: 0 auto to work. Has made my life a lot easier. You just need to get past the fact that 'table' display doesn't mean table html.

It's especially useful for responsive design where things just get hairy and crazy 50% left this and -50% that just become unmanageable.

style
{
   display: table;
   margin: 0 auto
}

JsFiddle

In addition if you've got two buttons and you want them the same width you don't even need to know the size of each to get them to be the same width - because the table will magically collapse them for you.

enter image description here

JsFiddle

(this also works if they're inline and you want to center two buttons side to side - try doing that with percentages!).

Java Desktop application: SWT vs. Swing

One thing to consider: Screenreaders

For some reasons, some Swing components do not work well when using a screenreader (and the Java AccessBridge for Windows). Know that different screenreaders result in different behaviour. And in my experience the SWT-Tree performs a lot better than the Swing-Tree in combination with a screenreader. Thus our application ended up in using both SWT and Swing components.

For distributing and loading the proper SWT-library, you might find this link usefull: http://www.chrisnewland.com/select-correct-swt-jar-for-your-os-and-jvm-at-runtime-191

How to detect responsive breakpoints of Twitter Bootstrap 3 using JavaScript?

You may want to add this to your bootstrap project to check active breakpoint visually

    <script type='text/javascript'>

        $(document).ready(function () {

            var mode;

            $('<div class="mode-informer label-info" style="z-index:1000;position: fixed;bottom:10px;left:10px">%mode%</div>').appendTo('body');


            var checkMode = function () {

                if ($(window).width() < 768) {
                    return 'xs';
                }
                else if ($(window).width() >= 768 && $(window).width() < 992) {
                    return 'sm';
                }
                else if ($(window).width() >= 992 && $(window).width() < 1200) {
                    return 'md';
                }
                else {
                    return 'lg';
                }
            };

            var compareMode = function () {
                if (mode !== checkMode()) {
                    mode = checkMode();

                    $('.mode-informer').text(mode).animate({
                        bottom: '100'
                    }, 100, function () {
                        $('.mode-informer').animate({bottom: 10}, 100)
                    });
                }
            };

            $(window).on('resize', function () {
                compareMode()
            });

            compareMode();

        });

    </script>

Here is the BOOTPLY

Where does flask look for image files?

From the documentation:

Dynamic web applications also need static files. That’s usually where the CSS and JavaScript files are coming from. Ideally your web server is configured to serve them for you, but during development Flask can do that as well. Just create a folder called static in your package or next to your module and it will be available at /static on the application.

To generate URLs for static files, use the special 'static' endpoint name:

url_for('static', filename='style.css')

The file has to be stored on the filesystem as static/style.css.