Programs & Examples On #Common tasks

How do you get a directory listing in C?

I've created an open source (BSD) C header that deals with this problem. It currently supports POSIX and Windows. Please check it out:

https://github.com/cxong/tinydir

tinydir_dir dir;
tinydir_open(&dir, "/path/to/dir");

while (dir.has_next)
{
    tinydir_file file;
    tinydir_readfile(&dir, &file);

    printf("%s", file.name);
    if (file.is_dir)
    {
        printf("/");
    }
    printf("\n");

    tinydir_next(&dir);
}

tinydir_close(&dir);

Missing Microsoft RDLC Report Designer in Visual Studio

I've had the same problem as you and I installed Microsoft rdlc designer to solve my problem.

And if you already installed this but still can't found rdlc designer try open visual studio > tools > Extension and Updates > then enable Miscrosoft Rdlc designer extensions.

Pass a simple string from controller to a view MVC3

If you are trying to simply return a string to a View, try this:

public string Test()
{
     return "test";
}

This will return a view with the word test in it. You can insert some html in the string.

You can also try this:

public ActionResult Index()
{
    return Content("<html><b>test</b></html>");
}

What is Android keystore file, and what is it used for?

You can find more information about the signing process on the official Android documentation here : http://developer.android.com/guide/publishing/app-signing.html

Yes, you can sign several applications with the same keystore. But you must remember one important thing : if you publish an app on the Play Store, you have to sign it with a non debug certificate. And if one day you want to publish an update for this app, the keystore used to sign the apk must be the same. Otherwise, you will not be able to post your update.

UnsupportedClassVersionError: JVMCFRE003 bad major version in WebSphere AS 7

In this Eclipse Preferences panel you can change the compiler compatibility from 1.7 to 1.6. This solved the similar message I was getting. For Eclipse, it is under: Preferences -> Java -> Compiler: 'Compiler compliance level'

Get webpage contents with Python?

If you ask me. try this one

import urllib2
resp = urllib2.urlopen('http://hiscore.runescape.com/index_lite.ws?player=zezima')

and read the normal way ie

page = resp.read()

Good luck though

How to edit .csproj file

Here is my option to Edit the project file without the need to Unload the project:

  1. Open Solution Explorer and switch to folder view: enter image description here

  2. Navigate to the Project which you want to edit inside the Solution folders and right-click on it.

  3. Choose Open from the Context Menu. enter image description here

That is it!

You will see the *.csproj file opened inside Visual Studio Editor.
After you can switch back to a Solution/Project view (see step 1).

enter image description here

Why maven? What are the benefits?

Figuring out package dependencies is really not that hard. You rarely do it anyway. Probably once during project setup and few more during upgrades. With maven you'll end up fixing mismatched dependencies, badly written poms, and doing package exclusions anyway.

Not that hard... for toy projects. But the projects I work on have many, really many, of them, and I'm very glad to get them transitively, to have a standardized naming scheme for them. Managing all this manually by hand would be a nightmare.

And yes, sometimes you have to work on the convergence of dependencies. But think about it twice, this is not inherent to Maven, this is inherent to any system using dependencies (and I am talking about Java dependencies in general here).

So with Ant, you have to do the same work except that you have to do everything manually: grabbing some version of project A and its dependencies, grabbing some version of project B and its dependencies, figuring out yourself what exact versions they use, checking that they don't overlap, checking that they are not incompatible, etc. Welcome to hell.

On the other hand, Maven supports dependency management and will retrieve them transitively for me and gives me the tooling I need to manage the complexity inherent to dependency management: I can analyze a dependency tree, control the versions used in transitive dependencies, exclude some of them if required, control the converge across modules, etc. There is no magic. But at least you have support.

And don't forget that dependency management is only a small part of what Maven offers, there is much more (not even mentioning the other tools that integrates nicely with Maven, e.g. Sonar).

Slow FIX-COMPILE-DEPLOY-DEBUG cycle, which kills productivity. This is my main gripe. You make a change, the you have to wait for maven build to kick in and wait for it to deploy. No hot deployment whatsoever.

First, why do you use Maven like this? I don't. I use my IDE to write tests, code until they pass, refactor, deploy, hot deploy and run a local Maven build when I'm done, before to commit, to make sure I will not break the continuous build.

Second, I'm not sure using Ant would make things much better. And to my experience, modular Maven builds using binary dependencies gives me faster build time than typical monolithic Ant builds. Anyway, have a look at Maven Shell for a ready to (re)use Maven environment (which is awesome by the way).

So at end, and I'm sorry to say so, it's not really Maven that is killing your productivity, it's you misusing your tools. And if you're not happy with it, well, what can I say, don't use it. Personally, I'm using Maven since 2003 and I never looked back.

How to evaluate a math expression given in string form?

Another way is to use Spring Expression Language or SpEL which does a whole lot more along with evaluating mathematical expressions therefore maybe slightly overkill. You do not have to be using Spring framework to use this expression library as it is stand-alone. Copying examples from SpEL's documentation:

ExpressionParser parser = new SpelExpressionParser();
int two = parser.parseExpression("1 + 1").getValue(Integer.class); // 2 
double twentyFour = parser.parseExpression("2.0 * 3e0 * 4").getValue(Double.class); //24.0

Read more concise SpEL examples here and the complete docs here

Swap two items in List<T>

There is no existing Swap-method, so you have to create one yourself. Of course you can linqify it, but that has to be done with one (unwritten?) rules in mind: LINQ-operations do not change the input parameters!

In the other "linqify" answers, the (input) list is modified and returned, but this action brakes that rule. If would be weird if you have a list with unsorted items, do a LINQ "OrderBy"-operation and than discover that the input list is also sorted (just like the result). This is not allowed to happen!

So... how do we do this?

My first thought was just to restore the collection after it was finished iterating. But this is a dirty solution, so do not use it:

static public IEnumerable<T> Swap1<T>(this IList<T> source, int index1, int index2)
{
    // Parameter checking is skipped in this example.

    // Swap the items.
    T temp = source[index1];
    source[index1] = source[index2];
    source[index2] = temp;

    // Return the items in the new order.
    foreach (T item in source)
        yield return item;

    // Restore the collection.
    source[index2] = source[index1];
    source[index1] = temp;
}

This solution is dirty because it does modify the input list, even if it restores it to the original state. This could cause several problems:

  1. The list could be readonly which will throw an exception.
  2. If the list is shared by multiple threads, the list will change for the other threads during the duration of this function.
  3. If an exception occurs during the iteration, the list will not be restored. (This could be resolved to write an try-finally inside the Swap-function, and put the restore-code inside the finally-block).

There is a better (and shorter) solution: just make a copy of the original list. (This also makes it possible to use an IEnumerable as a parameter, instead of an IList):

static public IEnumerable<T> Swap2<T>(this IList<T> source, int index1, int index2)
{
    // Parameter checking is skipped in this example.

    // If nothing needs to be swapped, just return the original collection.
    if (index1 == index2)
        return source;

    // Make a copy.
    List<T> copy = source.ToList();

    // Swap the items.
    T temp = copy[index1];
    copy[index1] = copy[index2];
    copy[index2] = temp;

    // Return the copy with the swapped items.
    return copy;
}

One disadvantage of this solution is that it copies the entire list which will consume memory and that makes the solution rather slow.

You might consider the following solution:

static public IEnumerable<T> Swap3<T>(this IList<T> source, int index1, int index2)
{
    // Parameter checking is skipped in this example.
    // It is assumed that index1 < index2. Otherwise a check should be build in and both indexes should be swapped.

    using (IEnumerator<T> e = source.GetEnumerator())
    {
        // Iterate to the first index.
        for (int i = 0; i < index1; i++)
            yield return source[i];

        // Return the item at the second index.
        yield return source[index2];

        if (index1 != index2)
        {
            // Return the items between the first and second index.
            for (int i = index1 + 1; i < index2; i++)
                yield return source[i];

            // Return the item at the first index.
            yield return source[index1];
        }

        // Return the remaining items.
        for (int i = index2 + 1; i < source.Count; i++)
            yield return source[i];
    }
}

And if you want to input parameter to be IEnumerable:

static public IEnumerable<T> Swap4<T>(this IEnumerable<T> source, int index1, int index2)
{
    // Parameter checking is skipped in this example.
    // It is assumed that index1 < index2. Otherwise a check should be build in and both indexes should be swapped.

    using(IEnumerator<T> e = source.GetEnumerator())
    {
        // Iterate to the first index.
        for(int i = 0; i < index1; i++) 
        {
            if (!e.MoveNext())
                yield break;
            yield return e.Current;
        }

        if (index1 != index2)
        {
            // Remember the item at the first position.
            if (!e.MoveNext())
                yield break;
            T rememberedItem = e.Current;

            // Store the items between the first and second index in a temporary list. 
            List<T> subset = new List<T>(index2 - index1 - 1);
            for (int i = index1 + 1; i < index2; i++)
            {
                if (!e.MoveNext())
                    break;
                subset.Add(e.Current);
            }

            // Return the item at the second index.
            if (e.MoveNext())
                yield return e.Current;

            // Return the items in the subset.
            foreach (T item in subset)
                yield return item;

            // Return the first (remembered) item.
            yield return rememberedItem;
        }

        // Return the remaining items in the list.
        while (e.MoveNext())
            yield return e.Current;
    }
}

Swap4 also makes a copy of (a subset of) the source. So worst case scenario, it is as slow and memory consuming as function Swap2.

List of special characters for SQL LIKE clause

You should add that you have to add an extra ' to escape an exising ' in SQL Server:

smith's -> smith''s

How can I specify a local gem in my Gemfile?

I believe you can do this:

gem "foo", path: "/path/to/foo"

make arrayList.toArray() return more specific types

 public static <E> E[] arrayListToTypedArray(List<E> list) {

    if (list == null) {
      return null;
    }
    int noItems = list.size();
    if (noItems == 0) {
      return null;
    }

    E[] listAsTypedArray;
    E typeHelper = list.get(0);

    try {
      Object o = Array.newInstance(typeHelper.getClass(), noItems);
      listAsTypedArray = (E[]) o;
      for (int i = 0; i < noItems; i++) {
        Array.set(listAsTypedArray, i, list.get(i));
      }
    } catch (Exception e) {
      return null;
    }

    return listAsTypedArray;
  }

PHP code is not being executed, instead code shows on the page

This was in my .htaccess

DirectoryIndex index.html index.htm

index.html contained PHP code. By default, PHP won't process files with extentions like htm* as PHP code.

You can override this, by adding the following to .htaccess:

<FilesMatch ".+\.html$">
    SetHandler application/x-httpd-php
</FilesMatch>

Putting text in top left corner of matplotlib plot

You can use text.

text(x, y, s, fontsize=12)

text coordinates can be given relative to the axis, so the position of your text will be independent of the size of the plot:

The default transform specifies that text is in data coords, alternatively, you can specify text in axis coords (0,0 is lower-left and 1,1 is upper-right). The example below places text in the center of the axes::

text(0.5, 0.5,'matplotlib',
     horizontalalignment='center',
     verticalalignment='center',
     transform = ax.transAxes)

To prevent the text to interfere with any point of your scatter is more difficult afaik. The easier method is to set y_axis (ymax in ylim((ymin,ymax))) to a value a bit higher than the max y-coordinate of your points. In this way you will always have this free space for the text.

EDIT: here you have an example:

In [17]: from pylab import figure, text, scatter, show
In [18]: f = figure()
In [19]: ax = f.add_subplot(111)
In [20]: scatter([3,5,2,6,8],[5,3,2,1,5])
Out[20]: <matplotlib.collections.CircleCollection object at 0x0000000007439A90>
In [21]: text(0.1, 0.9,'matplotlib', ha='center', va='center', transform=ax.transAxes)
Out[21]: <matplotlib.text.Text object at 0x0000000007415B38>
In [22]:

enter image description here

The ha and va parameters set the alignment of your text relative to the insertion point. ie. ha='left' is a good set to prevent a long text to go out of the left axis when the frame is reduced (made narrower) manually.

Gradient of n colors ranging from color 1 and color 2

Just to expand on the previous answer colorRampPalettecan handle more than two colors.

So for a more expanded "heat map" type look you can....

colfunc<-colorRampPalette(c("red","yellow","springgreen","royalblue"))
plot(rep(1,50),col=(colfunc(50)), pch=19,cex=2)

The resulting image:

enter image description here

Matplotlib: ValueError: x and y must have same first dimension

You should make x and y numpy arrays, not lists:

x = np.array([0.46,0.59,0.68,0.99,0.39,0.31,1.09,
              0.77,0.72,0.49,0.55,0.62,0.58,0.88,0.78])
y = np.array([0.315,0.383,0.452,0.650,0.279,0.215,0.727,0.512,
              0.478,0.335,0.365,0.424,0.390,0.585,0.511])

With this change, it produces the expect plot. If they are lists, m * x will not produce the result you expect, but an empty list. Note that m is anumpy.float64 scalar, not a standard Python float.

I actually consider this a bit dubious behavior of Numpy. In normal Python, multiplying a list with an integer just repeats the list:

In [42]: 2 * [1, 2, 3]
Out[42]: [1, 2, 3, 1, 2, 3]

while multiplying a list with a float gives an error (as I think it should):

In [43]: 1.5 * [1, 2, 3]
---------------------------------------------------------------------------
TypeError                                 Traceback (most recent call last)
<ipython-input-43-d710bb467cdd> in <module>()
----> 1 1.5 * [1, 2, 3]
TypeError: can't multiply sequence by non-int of type 'float'

The weird thing is that multiplying a Python list with a Numpy scalar apparently works:

In [45]: np.float64(0.5) * [1, 2, 3]
Out[45]: []

In [46]: np.float64(1.5) * [1, 2, 3]
Out[46]: [1, 2, 3]

In [47]: np.float64(2.5) * [1, 2, 3]
Out[47]: [1, 2, 3, 1, 2, 3]

So it seems that the float gets truncated to an int, after which you get the standard Python behavior of repeating the list, which is quite unexpected behavior. The best thing would have been to raise an error (so that you would have spotted the problem yourself instead of having to ask your question on Stackoverflow) or to just show the expected element-wise multiplication (in which your code would have just worked). Interestingly, addition between a list and a Numpy scalar does work:

In [69]: np.float64(0.123) + [1, 2, 3]
Out[69]: array([ 1.123,  2.123,  3.123])

How can I apply a function to every row/column of a matrix in MATLAB?

With recent versions of Matlab, you can use the Table data structure to your advantage. There's even a 'rowfun' operation but I found it easier just to do this:

a = magic(6);
incrementRow = cell2mat(cellfun(@(x) x+1,table2cell(table(a)),'UniformOutput',0))

or here's an older one I had that doesn't require tables, for older Matlab versions.

dataBinner = cell2mat(arrayfun(@(x) Binner(a(x,:),2)',1:size(a,1),'UniformOutput',0)')

How to assign a value to a TensorFlow variable?

Also, it has to be noted that if you're using your_tensor.assign(), then the tf.global_variables_initializer need not be called explicitly since the assign operation does it for you in the background.

Example:

In [212]: w = tf.Variable(12)
In [213]: w_new = w.assign(34)

In [214]: with tf.Session() as sess:
     ...:     sess.run(w_new)
     ...:     print(w_new.eval())

# output
34 

However, this will not initialize all variables, but it will only initialize the variable on which assign was executed on.

WebSockets and Apache proxy : how to configure mod_proxy_wstunnel?

As of Socket.IO 1.0 (May 2014), all connections begin with an HTTP polling request (more info here). That means that in addition to forwarding WebSocket traffic, you need to forward any transport=polling HTTP requests.

The solution below should redirect all socket traffic correctly, without redirecting any other traffic.

  1. Enable the following Apache2 mods:

    sudo a2enmod proxy rewrite proxy_http proxy_wstunnel
    
  2. Use these settings in your *.conf file (e.g. /etc/apache2/sites-available/mysite.com.conf). I've included comments to explain each piece:

    <VirtualHost *:80>
        ServerName www.mydomain.com
    
        # Enable the rewrite engine
        # Requires: sudo a2enmod proxy rewrite proxy_http proxy_wstunnel
        # In the rules/conds, [NC] means case-insensitve, [P] means proxy
        RewriteEngine On
    
        # socket.io 1.0+ starts all connections with an HTTP polling request
        RewriteCond %{QUERY_STRING} transport=polling       [NC]
        RewriteRule /(.*)           http://localhost:3001/$1 [P]
    
        # When socket.io wants to initiate a WebSocket connection, it sends an
        # "upgrade: websocket" request that should be transferred to ws://
        RewriteCond %{HTTP:Upgrade} websocket               [NC]
        RewriteRule /(.*)           ws://localhost:3001/$1  [P]
    
        # OPTIONAL: Route all HTTP traffic at /node to port 3001
        ProxyRequests Off
        ProxyPass           /node   http://localhost:3001
        ProxyPassReverse    /node   http://localhost:3001
    </VirtualHost>
    
  3. I've included an extra section for routing /node traffic that I find handy, see here for more info.

How to quickly and conveniently disable all console.log statements in my code?

I know you asked how to disable console.log, but this might be what you're really after. This way you don't have to explicitly enable or disable the console. It simply prevents those pesky console errors for people who don't have it open or installed.

if(typeof(console) === 'undefined') {
    var console = {};
    console.log = console.error = console.info = console.debug = console.warn = console.trace = console.dir = console.dirxml = console.group = console.groupEnd = console.time = console.timeEnd = console.assert = console.profile = function() {};
}

Using PHP Replace SPACES in URLS with %20

Use urlencode() rather than trying to implement your own. Be lazy.

Conversion failed when converting the nvarchar value ... to data type int

You got this Error because you tried to convert column DataType from String to int which is

leagal if and only if

you dont have row in that table with string content inside that column

so just make sure your previously inserted Rows is compatible with the new changes

how to properly display an iFrame in mobile safari

Don't scroll the IFrame page or its content, scroll the parent page. If you control the IFrame content, you can use the iframe-resizer library to turn the iframe element itself into a proper block level element, with a natural/correct/native height. Also, don't attempt to position (fixed, absolute) your iframe in the parent page, or present an iframe in a modal window, especially if it has form elements.

I also suspect that iOS Safari has a non-standards behavior that expands your iframe's height to its natural height, much like the iframe-resizer library will do for desktop browsers, which seem to render responsive iframe content at height 0px or 150px or some other not useful default. If you need to contrain width, try a max-width style inside the iframe.

What is the difference between public, private, and protected?

When we follow object oriented php in our project , we should follow some rules to use access modifiers in php. Today we are going to learn clearly what is access modifier and how can we use it.PHP access modifiers are used to set access rights with PHP classes and their members that are the functions and variables defined within the class scope. In php there are three scopes for class members.

  1. PUBLIC
  2. PRIVATE
  3. PROTECTED

Now, let us have a look at the following image to understand access modifier access level enter image description here

Now, let us have a look at the following list to know about the possible PHP keywords used as access modifiers.

public :- class or its members defined with this access modifier will be publicly accessible from anywhere, even from outside the scope of the class.

private :- class members with this keyword will be accessed within the class itself. we can’t access private data from subclass. It protects members from outside class access.

protected :- same as private, except by allowing subclasses to access protected superclass members.

Now see the table to understand access modifier Read full article php access modifire

How can I set the current working directory to the directory of the script in Bash?

I take this and it works.

#!/bin/bash
cd "$(dirname "$0")"
CUR_DIR=$(pwd)

Excel cell value as string won't store as string

Use Range("A1").Text instead of .Value

post comment edit:
Why?
Because the .Text property of Range object returns what is literally visible in the spreadsheet, so if you cell displays for example i100l:25he*_92 then <- Text will return exactly what it in the cell including any formatting.
The .Value and .Value2 properties return what's stored in the cell under the hood excluding formatting. Specially .Value2 for date types, it will return the decimal representation.

If you want to dig deeper into the meaning and performance, I just found this article which seems like a good guide

another edit
Here you go @Santosh
type in (MANUALLY) the values from the DEFAULT (col A) to other columns
Do not format column A at all
Format column B as Text
Format column C as Date[dd/mm/yyyy]
Format column D as Percentage
Dont Format column A, Format B as TEXT, C as Date, D as Percentage
now,
paste this code in a module

Sub main()

    Dim ws As Worksheet, i&, j&
    Set ws = Sheets(1)
    For i = 3 To 7
        For j = 1 To 4
            Debug.Print _
                    "row " & i & vbTab & vbTab & _
                    Cells(i, j).Text & vbTab & _
                    Cells(i, j).Value & vbTab & _
                    Cells(i, j).Value2
        Next j
    Next i
End Sub

and Analyse the output! Its really easy and there isn't much more i can do to help :)

            .TEXT              .VALUE             .VALUE2
row 3       hello             hello               hello
row 3       hello             hello               hello
row 3       hello             hello               hello
row 3       hello             hello               hello
row 4       1                 1                   1
row 4       1                 1                   1
row 4       01/01/1900        31/12/1899          1
row 4       1.00%             0.01                0.01
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 5       helo1$$           helo1$$             helo1$$
row 6       63                63                  63
row 6       =7*9              =7*9                =7*9
row 6       03/03/1900        03/03/1900          63
row 6       6300.00%          63                  63
row 7       29/05/2013        29/05/2013          41423
row 7       29/05/2013        29/05/2013          29/05/2013
row 7       29/05/2013        29/05/2013          41423
row 7       29/05/2013%       29/05/2013%         29/05/2013%

converting CSV/XLS to JSON?

Since Powershell 3.0 (shipped with Windows 8, available for Windows 7 and windows Server 2008 but not Windows Vista ) you can use the built-in convertto-json commandlet:

PS E:> $topicsjson = import-csv .\itinerary-all.csv | ConvertTo-Json 

PS E:\> $topicsjson.Length
11909

PS E:\> $topicsjson.getType()

IsPublic IsSerial Name                                     BaseType                  
-------- -------- ----                                     --------                  
True     True     Object[]                                 System.Array              

Online Help Page on Technet

Get custom product attributes in Woocommerce

Most updated:

$product->get_attribute( 'your_attr' );

You will need to define $product if it's not on the page.

Using parameters in batch files at Windows command line

@Jon's :parse/:endparse scheme is a great start, and he has my gratitude for the initial pass, but if you think that the Windows torturous batch system would let you off that easy… well, my friend, you are in for a shock. I have spent the whole day with this devilry, and after much painful research and experimentation I finally managed something viable for a real-life utility.

Let us say that we want to implement a utility foobar. It requires an initial command. It has an optional parameter --foo which takes an optional value (which cannot be another parameter, of course); if the value is missing it defaults to default. It also has an optional parameter --bar which takes a required value. Lastly it can take a flag --baz with no value allowed. Oh, and these parameters can come in any order.

In other words, it looks like this:

foobar <command> [--foo [<fooval>]] [--bar <barval>] [--baz]

Complicated? No, that seems pretty typical of real life utilities. (git anyone?)

Without further ado, here is a solution:

@ECHO OFF
SETLOCAL
REM FooBar parameter demo
REM By Garret Wilson

SET CMD=%~1

IF "%CMD%" == "" (
  GOTO usage
)
SET FOO=
SET DEFAULT_FOO=default
SET BAR=
SET BAZ=

SHIFT
:args
SET PARAM=%~1
SET ARG=%~2
IF "%PARAM%" == "--foo" (
  SHIFT
  IF NOT "%ARG%" == "" (
    IF NOT "%ARG:~0,2%" == "--" (
      SET FOO=%ARG%
      SHIFT
    ) ELSE (
      SET FOO=%DEFAULT_FOO%
    )
  ) ELSE (
    SET FOO=%DEFAULT_FOO%
  )
) ELSE IF "%PARAM%" == "--bar" (
  SHIFT
  IF NOT "%ARG%" == "" (
    SET BAR=%ARG%
    SHIFT
  ) ELSE (
    ECHO Missing bar value. 1>&2
    ECHO:
    GOTO usage
  )
) ELSE IF "%PARAM%" == "--baz" (
  SHIFT
  SET BAZ=true
) ELSE IF "%PARAM%" == "" (
  GOTO endargs
) ELSE (
  ECHO Unrecognized option %1. 1>&2
  ECHO:
  GOTO usage
)
GOTO args
:endargs

ECHO Command: %CMD%
IF NOT "%FOO%" == "" (
  ECHO Foo: %FOO%
)
IF NOT "%BAR%" == "" (
  ECHO Bar: %BAR%
)
IF "%BAZ%" == "true" (
  ECHO Baz
)

REM TODO do something with FOO, BAR, and/or BAZ
GOTO :eof

:usage
ECHO FooBar
ECHO Usage: foobar ^<command^> [--foo [^<fooval^>]] [--bar ^<barval^>] [--baz]
EXIT /B 1

Yes, it really is that bad. See my similar post at https://stackoverflow.com/a/50653047/421049, where I provide more analysis of what is going on in the logic, and why I used certain constructs.

Hideous. Most of that I had to learn today. And it hurt.

How to restore the menu bar in Visual Studio Code

It's also possible that you have accidentally put the IDE into Full Screen Mode. On occasion, you may be inadertently pressing F11 to set FullScreen mode to On.

If this is the case, the Accepted Answer above will not work. Instead, you must disable Full Screen mode (View > Appearance > Full Screen).Click Full Screen to switch off and restore the menu bar

Please see the attached screenshot.

Mismatch Detected for 'RuntimeLibrary'

(This is already answered in comments, but since it lacks an actual answer, I'm writing this.)

This problem arises in newer versions of Visual C++ (the older versions usually just silently linked the program and it would crash and burn at run time.) It means that some of the libraries you are linking with your program (or even some of the source files inside your program itself) are using different versions of the CRT (the C RunTime library.)

To correct this error, you need to go into your Project Properties (and/or those of the libraries you are using,) then into C/C++, then Code Generation, and check the value of Runtime Library; this should be exactly the same for all the files and libraries you are linking together. (The rules are a little more relaxed for linking with DLLs, but I'm not going to go into the "why" and into more details here.)

There are currently four options for this setting:

  1. Multithreaded Debug
  2. Multithreaded Debug DLL
  3. Multithreaded Release
  4. Multithreaded Release DLL

Your particular problem seems to stem from you linking a library built with "Multithreaded Debug" (i.e. static multithreaded debug CRT) against a program that is being built using the "Multithreaded Debug DLL" setting (i.e. dynamic multithreaded debug CRT.) You should change this setting either in the library, or in your program. For now, I suggest changing this in your program.

Note that since Visual Studio projects use different sets of project settings for debug and release builds (and 32/64-bit builds) you should make sure the settings match in all of these project configurations.

For (some) more information, you can see these (linked from a comment above):

  1. Linker Tools Warning LNK4098 on MSDN
  2. /MD, /ML, /MT, /LD (Use Run-Time Library) on MSDN
  3. Build errors with VC11 Beta - mixing MTd libs with MDd exes fail to link on Bugzilla@Mozilla

UPDATE: (This is in response to a comment that asks for the reason that this much care must be taken.)

If two pieces of code that we are linking together are themselves linking against and using the standard library, then the standard library must be the same for both of them, unless great care is taken about how our two code pieces interact and pass around data. Generally, I would say that for almost all situations just use the exact same version of the standard library runtime (regarding debug/release, threads, and obviously the version of Visual C++, among other things like iterator debugging, etc.)

The most important part of the problem is this: having the same idea about the size of objects on either side of a function call.

Consider for example that the above two pieces of code are called A and B. A is compiled against one version of the standard library, and B against another. In A's view, some random object that a standard function returns to it (e.g. a block of memory or an iterator or a FILE object or whatever) has some specific size and layout (remember that structure layout is determined and fixed at compile time in C/C++.) For any of several reasons, B's idea of the size/layout of the same objects is different (it can be because of additional debug information, natural evolution of data structures over time, etc.)

Now, if A calls the standard library and gets an object back, then passes that object to B, and B touches that object in any way, chances are that B will mess that object up (e.g. write the wrong field, or past the end of it, etc.)

The above isn't the only kind of problems that can happen. Internal global or static objects in the standard library can cause problems too. And there are more obscure classes of problems as well.

All this gets weirder in some aspects when using DLLs (dynamic runtime library) instead of libs (static runtime library.)

This situation can apply to any library used by two pieces of code that work together, but the standard library gets used by most (if not almost all) programs, and that increases the chances of clash.

What I've described is obviously a watered down and simplified version of the actual mess that awaits you if you mix library versions. I hope that it gives you an idea of why you shouldn't do it!

Linker error: "linker input file unused because linking not done", undefined reference to a function in that file

I think you are confused about how the compiler puts things together. When you use -c flag, i.e. no linking is done, the input is C++ code, and the output is object code. The .o files thus don't mix with -c, and compiler warns you about that. Symbols from object file are not moved to other object files like that.

All object files should be on the final linker invocation, which is not the case here, so linker (called via g++ front-end) complains about missing symbols.

Here's a small example (calling g++ explicitly for clarity):

PROG ?= myprog
OBJS = worker.o main.o

all: $(PROG)

.cpp.o:
        g++ -Wall -pedantic -ggdb -O2 -c -o $@ $<

$(PROG): $(OBJS)
        g++ -Wall -pedantic -ggdb -O2 -o $@ $(OBJS)

There's also makedepend utility that comes with X11 - helps a lot with source code dependencies. You might also want to look at the -M gcc option for building make rules.

HTML/Javascript: how to access JSON data loaded in a script tag with src set

You can't load JSON like that, sorry.

I know you're thinking "why I can't I just use src here? I've seen stuff like this...":

<script id="myJson" type="application/json">
 { 
   name: 'Foo' 
 }
</script>

<script type="text/javascript">
    $(function() {
        var x = JSON.parse($('#myJson').html());
        alert(x.name); //Foo
     });
</script>

... well to put it simply, that was just the script tag being "abused" as a data holder. You can do that with all sorts of data. For example, a lot of templating engines leverage script tags to hold templates.

You have a short list of options to load your JSON from a remote file:

  1. Use $.get('your.json') or some other such AJAX method.
  2. Write a file that sets a global variable to your json. (seems hokey).
  3. Pull it into an invisible iframe, then scrape the contents of that after it's loaded (I call this "1997 mode")
  4. Consult a voodoo priest.

Final point:

Remote JSON Request after page loads is also not an option, in case you want to suggest that.

... that doesn't make sense. The difference between an AJAX request and a request sent by the browser while processing your <script src=""> is essentially nothing. They'll both be doing a GET on the resource. HTTP doesn't care if it's done because of a script tag or an AJAX call, and neither will your server.

How to populate options of h:selectOneMenu from database?

Call me lazy but coding a Converter seems like a lot of unnecessary work. I'm using Primefaces and, not having used a plain vanilla JSF2 listbox or dropdown menu before, I just assumed (being lazy) that the widget could handle complex objects, i.e. pass the selected object as is to its corresponding getter/setter like so many other widgets do. I was disappointed to find (after hours of head scratching) that this capability does not exist for this widget type without a Converter. In fact if you supply a setter for the complex object rather than for a String, it fails silently (simply doesn't call the setter, no Exception, no JS error), and I spent a ton of time going through BalusC's excellent troubleshooting tool to find the cause, to no avail since none of those suggestions applied. My conclusion: listbox/menu widget needs adapting that other JSF2 widgets do not. This seems misleading and prone to leading the uninformed developer like myself down a rabbit hole.

In the end I resisted coding a Converter and found through trial and error that if you set the widget value to a complex object, e.g.:

<p:selectOneListbox id="adminEvents" value="#{testBean.selectedEvent}">

... when the user selects an item, the widget can call a String setter for that object, e.g. setSelectedThing(String thingString) {...}, and the String passed is a JSON String representing the Thing object. I can parse it to determine which object was selected. This feels a little like a hack, but less of a hack than a Converter.

Way to read first few lines for pandas dataframe

I think you can use the nrows parameter. From the docs:

nrows : int, default None

    Number of rows of file to read. Useful for reading pieces of large files

which seems to work. Using one of the standard large test files (988504479 bytes, 5344499 lines):

In [1]: import pandas as pd

In [2]: time z = pd.read_csv("P00000001-ALL.csv", nrows=20)
CPU times: user 0.00 s, sys: 0.00 s, total: 0.00 s
Wall time: 0.00 s

In [3]: len(z)
Out[3]: 20

In [4]: time z = pd.read_csv("P00000001-ALL.csv")
CPU times: user 27.63 s, sys: 1.92 s, total: 29.55 s
Wall time: 30.23 s

How to convert numpy arrays to standard TensorFlow format?

You can use placeholders and feed_dict.

Suppose we have numpy arrays like these:

trX = np.linspace(-1, 1, 101) 
trY = 2 * trX + np.random.randn(*trX.shape) * 0.33 

You can declare two placeholders:

X = tf.placeholder("float") 
Y = tf.placeholder("float")

Then, use these placeholders (X, and Y) in your model, cost, etc.: model = tf.mul(X, w) ... Y ... ...

Finally, when you run the model/cost, feed the numpy arrays using feed_dict:

with tf.Session() as sess:
.... 
    sess.run(model, feed_dict={X: trY, Y: trY})

Paste text on Android Emulator

Not sure if that's useful, but, if you need a long URL from desktop browser to be opened in mobile browser, you can send SMS with that URL and open directly from message app.

enter image description here

How to display all elements in an arraylist?

Another approach is to add a toString() method to your Car class and just let the toString() method of ArrayList do all the work.

@Override
public String toString()
{
    return "Car{" +
            "make=" + make +
            ", registration='" + registration + '\'' +
            '}';
}

You don't get one car per line in the output, but it is quick and easy if you just want to see what is in the array.

List<Car> cars = c1.getAll();
System.out.println(cars);

Output would be something like this:

[Car{make=FORD, registration='ABC 123'},
Car{make=TOYOTA, registration='ZYZ 999'}]

Angular 2 Show and Hide an element

There are two options depending what you want to achieve :

  1. You can use the hidden directive to show or hide an element

    <div [hidden]="!edited" class="alert alert-success box-msg" role="alert">
      <strong>List Saved!</strong> Your changes has been saved.
    </div>
    
  2. You can use the ngIf control directive to add or remove the element. This is different of the hidden directive because it does not show / hide the element, but it add / remove from the DOM. You can loose unsaved data of the element. It can be the better choice for an edit component that is cancelled.

    <div *ngIf="edited" class="alert alert-success box-msg" role="alert"> 
      <strong>List Saved!</strong> Your changes has been saved.
    </div>
    

For you problem of change after 3 seconds, it can be due to incompatibility with setTimeout. Did you include angular2-polyfills.js library in your page ?

How to loop backwards in python?

All of these three solutions give the same results if the input is a string:

1.

def reverse(text):
    result = ""
    for i in range(len(text),0,-1):
        result += text[i-1]
    return (result)

2.

text[::-1]

3.

"".join(reversed(text))

Codeigniter unset session

$this->session->unset_userdata('session_value');

Reading rather large json files in Python

The issue here is that JSON, as a format, is generally parsed in full and then handled in-memory, which for such a large amount of data is clearly problematic.

The solution to this is to work with the data as a stream - reading part of the file, working with it, and then repeating.

The best option appears to be using something like ijson - a module that will work with JSON as a stream, rather than as a block file.

Edit: Also worth a look - kashif's comment about json-streamer and Henrik Heino's comment about bigjson.

Determine if an element has a CSS class with jQuery

Use the hasClass method:

jQueryCollection.hasClass(className);

or

$(selector).hasClass(className);

The argument is (obviously) a string representing the class you are checking, and it returns a boolean (so it doesn't support chaining like most jQuery methods).

Note: If you pass a className argument that contains whitespace, it will be matched literally against the collection's elements' className string. So if, for instance, you have an element,

<span class="foo bar" />

then this will return true:

$('span').hasClass('foo bar')

and these will return false:

$('span').hasClass('bar foo')
$('span').hasClass('foo  bar')

text-overflow: ellipsis not working

word-wrap: break-word;

this and only this did the job for me for a

<pre> </pre> 

tag

everthing else failed to do the ellipsis....

When is it acceptable to call GC.Collect?

One case is when you are trying to unit test code that uses WeakReference.

Text not wrapping in p tag

You can use word-wrap to break words or a continuous string of characters if it doesn't fit on a line in a container.

word-wrap: break-word;

this will keep breaking lines at appropriate break points unless a single string of characters doesn't fit on a line, in that case it will break.

JSFiddle

'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine

A 64-bit version of the 'Microsoft Access Database Engine 2010 Redistributable' that will allow you to use the 'Microsoft.ACE.OLEDB.12.0' provider is available here:
http://www.microsoft.com/en-us/download/details.aspx?id=13255

If you use the download from the accepted answer, you will need to build for x86, as pointed out by @backtestbroker.com.

Prepend line to beginning of a file

There's no way to do this with any built-in functions, because it would be terribly inefficient. You'd need to shift the existing contents of the file down each time you add a line at the front.

There's a Unix/Linux utility tail which can read from the end of a file. Perhaps you can find that useful in your application.

How to assert greater than using JUnit Assert?

Just how you've done it. assertTrue(boolean) also has an overload assertTrue(String, boolean) where the String is the message in case of failure; you can use that if you want to print that such-and-such wasn't greater than so-and-so.

You could also add hamcrest-all as a dependency to use matchers. See https://code.google.com/p/hamcrest/wiki/Tutorial:

import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.*;

assertThat("timestamp",
           Long.parseLong(previousTokenValues[1]),
           greaterThan(Long.parseLong(currentTokenValues[1])));

That gives an error like:

java.lang.AssertionError: timestamp
Expected: a value greater than <456L>
     but: <123L> was less than <456L>

How do I clear the previous text field value after submitting the form with out refreshing the entire page?

I had that issue and I solved by doing this:

.done(function() {
                    $(this).find("input").val("");
                    $("#feedback").trigger("reset");
                });

I added this code after my script as I used jQuery. Try same)

<script type="text/JavaScript">

        $(document).ready(function() {
            $("#feedback").submit(function(event) {
                event.preventDefault();
                $.ajax({
                    url: "feedback_lib.php",
                    type: "post",
                    data: $("#feedback").serialize()
                }).done(function() {
                    $(this).find("input").val("");
                    $("#feedback").trigger("reset");
                });
            });
        });
    </script>
    <form id="feedback" action="" name="feedback" method="post">
        <input id="name" name="name" placeholder="name" />
        <br />
        <input id="surname" name="surname" placeholder="surname" />
        <br />
        <input id="enquiry" name="enquiry" placeholder="enquiry" />
        <br />
        <input id="organisation" name="organisation" placeholder="organisation" />
        <br />
        <input id="email" name="email" placeholder="email" />
        <br />
        <textarea id="message" name="message" rows="7" cols="40" placeholder="?????????"></textarea>
        <br />
        <button id="send" name="send">send</button>
    </form>

string to string array conversion in java

Simply use the .toCharArray() method in Java:

String k = "abc";
char[] alpha = k.toCharArray();

This should work just fine in Java 8.

Duplicate AssemblyVersion Attribute

I found this answer on msdn, that explains marking the file as Content and then Copy to Output = If Newer. See article below:

https://social.msdn.microsoft.com/Forums/en-US/8671bdff-9b16-4b49-ba9e-227cc4df31b2/compile-error-cs0579-duplicate-assemblyversion-attribute?forum=vsgatk

GH

How to embed a PDF?

I recommend using PDFObject for PDF plugin detection.

This will only allow you to display alternate content if the user's browser isn't capable of displaying the PDF directly though. For example, the PDF will display fine in Chrome for most users, but they will need a plugin like Adobe Reader installed if they're using Firefox or Internet Explorer.

At least PDFObject will allow you to display a message with a link to download Adobe Reader and/or the PDF file itself if their browser doesn't already have a PDF plugin installed.

How to run a method every X seconds

Use Timer for every second...

new Timer().scheduleAtFixedRate(new TimerTask() {
    @Override
    public void run() {
        //your method
    }
}, 0, 1000);//put here time 1000 milliseconds=1 second

How do you overcome the svn 'out of date' error?

Tried all but change in .svn directly. Nothing helped so here's my solution.

In Eclipse > Window > Show View > History I've seen that file is not at the newest Revision, although I made multiple svn "Override & Update" / "Revert" / delete file and checkout.

So I went Package Explorer > Right click on file > Replace with > Latest from Repository.

Another look in the History View showed that file was now on latest Revision.

Replace multiple characters in one replace call

Here is another version using String Prototype. Enjoy!

String.prototype.replaceAll = function(obj) {
    let finalString = '';
    let word = this;
    for (let each of word){
        for (const o in obj){
            const value = obj[o];
            if (each == o){
                each = value;
            }
        }
        finalString += each;
    }

    return finalString;
};

'abc'.replaceAll({'a':'x', 'b':'y'}); //"xyc"

Selecting only first-level elements in jquery

1

 $("ul.rootlist > target-element")
2   $("ul.rootlist").find(target-element).eq(0) (only one instance)
3   $("ul.rootlist").children(target-element)

there are probably many other ways

Unable to locate tools.jar

If you are in Linux you can solve this by installing java on the system:

sudo apt-get install openjdk-7-jdk openjdk-7-jre

How to construct a WebSocket URI relative to the page URI?

Using the Window.URL API - https://developer.mozilla.org/en-US/docs/Web/API/Window/URL

Works with http(s), ports etc.

var url = new URL('/path/to/websocket', window.location.href);

url.protocol = url.protocol.replace('http', 'ws');

url.href // => ws://www.example.com:9999/path/to/websocket

How do I get the last character of a string?

The other answers contain a lot of needless text and code. Here are two ways to get the last character of a String:

char

char lastChar = myString.charAt(myString.length() - 1);

String

String lastChar = myString.substring(myString.length() - 1);

Ruby convert Object to Hash

For Active Record Objects

module  ActiveRecordExtension
  def to_hash
    hash = {}; self.attributes.each { |k,v| hash[k] = v }
    return hash
  end
end

class Gift < ActiveRecord::Base
  include ActiveRecordExtension
  ....
end

class Purchase < ActiveRecord::Base
  include ActiveRecordExtension
  ....
end

and then just call

gift.to_hash()
purch.to_hash() 

How to get the browser language using JavaScript

Try this script to get your browser language

_x000D_
_x000D_
<script type="text/javascript">_x000D_
var userLang = navigator.language || navigator.userLanguage; _x000D_
alert ("The language is: " + userLang);_x000D_
</script>
_x000D_
_x000D_
_x000D_

Cheers

Bootstrap Navbar toggle button not working

Wasted several hours only to realize that viewport meta was missing from my code. Adding here just in case some one else misses it out.

As soon as I added this, the toggle started working fine.

<meta name="viewport" content="width=device-width, initial-scale=1">

c++ exception : throwing std::string

It works, but I wouldn't do it if I were you. You don't seem to be deleting that heap data when you're done, which means that you've created a memory leak. The C++ compiler takes care of ensuring that exception data is kept alive even as the stack is popped, so don't feel that you need to use the heap.

Incidentally, throwing a std::string isn't the best approach to begin with. You'll have a lot more flexibility down the road if you use a simple wrapper object. It may just encapsulate a string for now, but maybe in future you will want to include other information, like some data which caused the exception or maybe a line number (very common, that). You don't want to change all of your exception handling in every spot in your code-base, so take the high road now and don't throw raw objects.

Stretch and scale CSS background

For modern browsers, you can accomplish this by using background-size:

body {
    background-image: url(bg.jpg);
    background-size: cover;
}

cover means stretching the image either vertically or horizontally so it never tiles/repeats.

That would work for Safari 3 (or later), Chrome, Opera 10+, Firefox 3.6+, and Internet Explorer 9 (or later).

For it to work with lower verions of Internet Explorer, try these CSS:

filter: progid:DXImageTransform.Microsoft.AlphaImageLoader(src='.myBackground.jpg', sizingMethod='scale');
-ms-filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(src='myBackground.jpg', sizingMethod='scale')";

how to do bitwise exclusive or of two strings in python?

Based on William McBrine's answer, here is a solution for fixed-length strings which is 9% faster for my use case:

import itertools
import struct
def make_strxor(size):
    def strxor(a, b, izip=itertools.izip, pack=struct.pack, unpack=struct.unpack, fmt='%dB' % size):
        return pack(fmt, *(a ^ b for a, b in izip(unpack(fmt, a), unpack(fmt, b))))
    return strxor
strxor_3 = make_strxor(3)
print repr(strxor_3('foo', 'bar'))

How do I alias commands in git?

Basically you just need to add lines to ~/.gitconfig

[alias]
    st = status
    ci = commit -v

Or you can use the git config alias command:

$ git config --global alias.st status 

On unix, use single quotes if the alias has a space:

$ git config --global alias.ci 'commit -v'

On windows, use double quotes if the alias has a space or a command line argument:

c:\dev> git config --global alias.ci "commit -v"

The alias command even accepts functions as parameters. Take a look at aliases.

Opening Chrome From Command Line

you can create batch file and insert into it the bellow line:

cmd /k start chrome "http://yourWebSite.com

after that you do just double click on this batch file.

Can I run HTML files directly from GitHub, instead of just viewing their source?

There is a new tool called GitHub HTML Preview, which does exactly what you want. Just prepend http://htmlpreview.github.com/? to the URL of any HTML file, e.g. http://htmlpreview.github.com/?https://github.com/twbs/bootstrap/blob/gh-pages/2.3.2/index.html

Note: This tool is actually a github.io page and is not affiliated with github as a company.

useState set method not reflecting change immediately

useEffect has its own state/lifecycle, it will not update until you pass a function in parameters or effect destroyed.

object and array spread or rest will not work inside useEffect.

React.useEffect(() => {
    console.log("effect");
    (async () => {
        try {
            let result = await fetch("/query/countries");
            const res = await result.json();
            let result1 = await fetch("/query/projects");
            const res1 = await result1.json();
            let result11 = await fetch("/query/regions");
            const res11 = await result11.json();
            setData({
                countries: res,
                projects: res1,
                regions: res11
            });
        } catch {}
    })(data)
}, [setData])
# or use this
useEffect(() => {
    (async () => {
        try {
            await Promise.all([
                fetch("/query/countries").then((response) => response.json()),
                fetch("/query/projects").then((response) => response.json()),
                fetch("/query/regions").then((response) => response.json())
            ]).then(([country, project, region]) => {
                // console.log(country, project, region);
                setData({
                    countries: country,
                    projects: project,
                    regions: region
                });
            })
        } catch {
            console.log("data fetch error")
        }
    })()
}, [setData]);

Retrieving the first digit of a number

    int number = 534;
    int firstDigit = Integer.parseInt(Integer.toString(number).substring(0, 1));

How to use SVG markers in Google Maps API v3

If you need a full svg not only a path and you want it to be modifiable on client side (e.g. change text, hide details, ...) you can use an alternative data 'URL' with included svg:

var svg = '<svg width="400" height="110"><rect width="300" height="100" /></svg>';
icon.url = 'data:image/svg+xml;charset=UTF-8;base64,' + btoa(svg);

JavaScript (Firefox) btoa() is used to get the base64 encoding from the SVG text. Your may also use http://dopiaza.org/tools/datauri/index.php to generate base data URLs.

Here is a full example jsfiddle:

<!DOCTYPE html>
<html>
    <head>
        <meta http-equiv="content-type" content="text/html; charset=UTF-8" />
        <script src="http://maps.google.com/maps/api/js?sensor=false" type="text/javascript"></script>
    </head>
    <body>
        <div id="map" style="width: 500px; height: 400px;"></div>
        <script type="text/javascript">
            var map = new google.maps.Map(document.getElementById('map'), {
                zoom: 10,
                center: new google.maps.LatLng(-33.92, 151.25),
                mapTypeId: google.maps.MapTypeId.ROADMAP
            });

            var template = [
                '<?xml version="1.0"?>',
                    '<svg width="26px" height="26px" viewBox="0 0 100 100" version="1.1" xmlns="http://www.w3.org/2000/svg">',
                        '<circle stroke="#222" fill="{{ color }}" cx="50" cy="50" r="35"/>',
                    '</svg>'
                ].join('\n');
            var svg = template.replace('{{ color }}', '#800');

            var docMarker = new google.maps.Marker({
                position: new google.maps.LatLng(-33.92, 151.25),
                map: map,
                title: 'Dynamic SVG Marker',
                icon: { url: 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(svg), scaledSize: new google.maps.Size(20, 20) },
optimized: false
            });

            var docMarker = new google.maps.Marker({
                position: new google.maps.LatLng(-33.95, 151.25),
                map: map,
                title: 'Dynamic SVG Marker',
                icon: { url: 'data:image/svg+xml;charset=UTF-8;base64,' + btoa(svg), scaledSize: new google.maps.Size(20, 20) },
optimized: false
            });
        </script>
    </body>
</html>

Additional Information can be found here.

Avoid base64 encoding:

In order to avoid base64 encoding you can replace 'data:image/svg+xml;charset=UTF-8;base64,' + btoa(svg) with 'data:image/svg+xml;charset=UTF-8,' + encodeURIComponent(svg)

This should work with modern browsers down to IE9. The advantage is that encodeURIComponent is a default js function and available in all modern browsers. You might also get smaller links but you need to test this and consider to use ' instead of " in your svg.

Also see Optimizing SVGs in data URIs for additional info.

IE support: In order to support SVG Markers in IE one needs two small adaptions as described here: SVG Markers in IE. I updated the example code to support IE.

How to clone object in C++ ? Or Is there another solution?

In C++ copying the object means cloning. There is no any special cloning in the language.

As the standard suggests, after copying you should have 2 identical copies of the same object.

There are 2 types of copying: copy constructor when you create object on a non initialized space and copy operator where you need to release the old state of the object (that is expected to be valid) before setting the new state.

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

This error message means that Windows isn't able to find "cygwin1.dll". The Programs that the Cygwin gcc create depend on this DLL. The file is part of cygwin , so most likely it's located in C:\cygwin\bin. To fix the problem all you have to do is add C:\cygwin\bin (or the location where cygwin1.dll can be found) to your system path. Alternatively you can copy cygwin1.dll into your Windows directory.

There is a nice tool called DependencyWalker that you can download from http://www.dependencywalker.com . You can use it to check dependencies of executables, so if you inspect your generated program it tells you which dependencies are missing and which are resolved.

Best way to clear a PHP array's values

How about $array_name = array(); ?

Dialog to pick image from gallery or from camera

You can implement this code to select image from gallery or camera :-

private ImageView imageview;
private Button btnSelectImage;
private Bitmap bitmap;
private File destination = null;
private InputStream inputStreamImg;
private String imgPath = null;
private final int PICK_IMAGE_CAMERA = 1, PICK_IMAGE_GALLERY = 2;

Now on button click event, you can able to call your method of select Image. This is inside activity's onCreate.

imageview = (ImageView) findViewById(R.id.imageview);
btnSelectImage = (Button) findViewById(R.id.btnSelectImage);

//OnbtnSelectImage click event...
btnSelectImage.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            selectImage();
        }
    });

Outside of your activity's oncreate.

// Select image from camera and gallery
private void selectImage() {
    try {
        PackageManager pm = getPackageManager();
        int hasPerm = pm.checkPermission(Manifest.permission.CAMERA, getPackageName());
        if (hasPerm == PackageManager.PERMISSION_GRANTED) {
            final CharSequence[] options = {"Take Photo", "Choose From Gallery","Cancel"};
            android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(activity);
            builder.setTitle("Select Option");
            builder.setItems(options, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int item) {
                    if (options[item].equals("Take Photo")) {
                        dialog.dismiss();
                        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                        startActivityForResult(intent, PICK_IMAGE_CAMERA);
                    } else if (options[item].equals("Choose From Gallery")) {
                        dialog.dismiss();
                        Intent pickPhoto = new Intent(Intent.ACTION_PICK, MediaStore.Images.Media.EXTERNAL_CONTENT_URI);
                        startActivityForResult(pickPhoto, PICK_IMAGE_GALLERY);
                    } else if (options[item].equals("Cancel")) {
                        dialog.dismiss();
                    }
                }
            });
            builder.show();
        } else
            Toast.makeText(this, "Camera Permission error", Toast.LENGTH_SHORT).show();
    } catch (Exception e) {
        Toast.makeText(this, "Camera Permission error", Toast.LENGTH_SHORT).show();
        e.printStackTrace();
    }
}

@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
    super.onActivityResult(requestCode, resultCode, data);
    inputStreamImg = null;
    if (requestCode == PICK_IMAGE_CAMERA) {
        try {
            Uri selectedImage = data.getData();
            bitmap = (Bitmap) data.getExtras().get("data");
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 50, bytes);

            Log.e("Activity", "Pick from Camera::>>> ");

            String timeStamp = new SimpleDateFormat("yyyyMMdd_HHmmss", Locale.getDefault()).format(new Date());
            destination = new File(Environment.getExternalStorageDirectory() + "/" +
                    getString(R.string.app_name), "IMG_" + timeStamp + ".jpg");
            FileOutputStream fo;
            try {
                destination.createNewFile();
                fo = new FileOutputStream(destination);
                fo.write(bytes.toByteArray());
                fo.close();
            } catch (FileNotFoundException e) {
                e.printStackTrace();
            } catch (IOException e) {
                e.printStackTrace();
            }

            imgPath = destination.getAbsolutePath();
            imageview.setImageBitmap(bitmap);

        } catch (Exception e) {
            e.printStackTrace();
        }
    } else if (requestCode == PICK_IMAGE_GALLERY) {
        Uri selectedImage = data.getData();
        try {
            bitmap = MediaStore.Images.Media.getBitmap(this.getContentResolver(), selectedImage);
            ByteArrayOutputStream bytes = new ByteArrayOutputStream();
            bitmap.compress(Bitmap.CompressFormat.JPEG, 50, bytes);
            Log.e("Activity", "Pick from Gallery::>>> ");

            imgPath = getRealPathFromURI(selectedImage);
            destination = new File(imgPath.toString());
            imageview.setImageBitmap(bitmap);

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

public String getRealPathFromURI(Uri contentUri) {
    String[] proj = {MediaStore.Audio.Media.DATA};
    Cursor cursor = managedQuery(contentUri, proj, null, null, null);
    int column_index = cursor.getColumnIndexOrThrow(MediaStore.Audio.Media.DATA);
    cursor.moveToFirst();
    return cursor.getString(column_index);
}

Atlast, finally add the camera and write external storage permission to AndroidManifest.xml

It works for me greatly, hope it will also works for you.

Show a PDF files in users browser via PHP/Perl

    $url ="https://yourFile.pdf";
    $content = file_get_contents($url);

    header('Content-Type: application/pdf');
    header('Content-Length: ' . strlen($content));
    header('Content-Disposition: inline; filename="YourFileName.pdf"');
    header('Cache-Control: private, max-age=0, must-revalidate');
    header('Pragma: public');
    ini_set('zlib.output_compression','0');

    die($content);

Tested and works fine. If you want the file to download instead, replace

    Content-Disposition: inline

with

    Content-Disposition: attachment

How to "git show" a merge commit with combined diff output even when every changed file agrees with one of the parents?

I built a general-purpose approach to doing various operations on a merge's commits.

Step One: Add an alias to git by editing ~/.gitconfig:

[alias]
  range = "!. ~/.githelpers && run_on_merge_range"

Step Two: In ~/.githelpers, define a bash function:

run_on_merge_range() {
  cmd=$1; shift
  commit=$1; shift
  range=$(git show $commit | grep Merge: | awk '{print $2 "..." $3}')
  echo "git $cmd $range $@"
  if [ -z $range ]; then
    echo "No merge detected"
    exit 1
  fi
  git $cmd $range $@
}

Step Three: Profit!

git range log <merge SHA> --oneline
git range diff <merge SHA> --reverse -p
git range diff <merge SHA> --name-only

There is probably a LOT of room for improvement here, I just whipped this together to get past an annoying situation. Feel free to mock my bash syntax and/or logic.

VBScript to send email without running Outlook

You can send email without Outlook in VBScript using the CDO.Message object. You will need to know the address of your SMTP server to use this:

Set MyEmail=CreateObject("CDO.Message")

MyEmail.Subject="Subject"
MyEmail.From="[email protected]"
MyEmail.To="[email protected]"
MyEmail.TextBody="Testing one two three."

MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusing")=2

'SMTP Server
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserver")="smtp.server.com"

'SMTP Port
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpserverport")=25 

MyEmail.Configuration.Fields.Update
MyEmail.Send

set MyEmail=nothing

If your SMTP server requires a username and password then paste these lines in above the MyEmail.Configuration.Fields.Update line:

'SMTP Auth (For Windows Auth set this to 2)
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate")=1
'Username
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendusername")="username" 
'Password
MyEmail.Configuration.Fields.Item ("http://schemas.microsoft.com/cdo/configuration/sendpassword")="password"

More information on using CDO to send email with VBScript can be found on the link below: http://www.paulsadowski.com/wsh/cdo.htm

Why do we need C Unions?

Unions are used when you want to model structs defined by hardware, devices or network protocols, or when you're creating a large number of objects and want to save space. You really don't need them 95% of the time though, stick with easy-to-debug code.

Moment get current date

Just call moment as a function without any arguments:

moment()

For timezone information with moment, look at the moment-timezone package: http://momentjs.com/timezone/

Xcode is not currently available from the Software Update server

I know this is an old post but I also ran into this problem today. I found out that when I executed sudo softwareupdate -l the Command Line Tools were listed as an update, so I installed them using sudo softwareupdate -i -a.

Search an array for matching attribute

you can use ES5 some. Its pretty first by using callback

function findRestaurent(foodType) {
    var restaurant;
    restaurants.some(function (r) {
        if (r.food === id) {
            restaurant = r;
            return true;
        }
   });
  return restaurant;
}

HTTP POST using JSON in Java

You can make use of Gson library to convert your java classes to JSON objects.

Create a pojo class for variables you want to send as per above Example

{"name":"myname","age":"20"}

becomes

class pojo1
{
   String name;
   String age;
   //generate setter and getters
}

once you set the variables in pojo1 class you can send that using the following code

String       postUrl       = "www.site.com";// put in your url
Gson         gson          = new Gson();
HttpClient   httpClient    = HttpClientBuilder.create().build();
HttpPost     post          = new HttpPost(postUrl);
StringEntity postingString = new StringEntity(gson.toJson(pojo1));//gson.tojson() converts your pojo to json
post.setEntity(postingString);
post.setHeader("Content-type", "application/json");
HttpResponse  response = httpClient.execute(post);

and these are the imports

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.HttpClientBuilder;

and for GSON

import com.google.gson.Gson;

How to apply a CSS class on hover to dynamically generated submit buttons?

You have two options:

  1. Extend your .paging class definition:

    .paging:hover {
        border:1px solid #999;
        color:#000;
    }
    
  2. Use the DOM hierarchy to apply the CSS style:

    div.paginate input:hover {
        border:1px solid #999;
        color:#000;
    }
    

$this->session->set_flashdata() and then $this->session->flashdata() doesn't work in codeigniter

To set flashdata you need to redirect controller function

$this->session->set_flashdata('message_name', 'This is test message');

//redirect to some function
redirect("controller/function_name");

//echo in view or controller
$this->session->flashdata('message_name');

Sass calculate percent minus px

Sass cannot perform arithmetic on values that cannot be converted from one unit to the next. Sass has no way of knowing exactly how wide "100%" is in terms of pixels or any other unit. That's something only the browser knows.

You need to use calc() instead. Check browser compatibility on Can I use...

.foo {
    height: calc(25% - 5px);
}

If your values are in variables, you may need to use interpolation turn them into strings (otherwise Sass just tries to perform arithmetic):

$a: 25%;
$b: 5px;

.foo {
  width: calc(#{$a} - #{$b});
}

How to automatically add user account AND password with a Bash script?

For RedHat / CentOS here's the code that creates a user, adds the passwords and makes the user a sudoer:

#!/bin/sh
echo -n "Enter username: "
read uname

echo -n "Enter password: "
read -s passwd

adduser "$uname"
echo $uname:$passwd | sudo chpasswd

gpasswd wheel -a $uname

Call child component method from parent class - Angular

Angular – Call Child Component’s Method in Parent Component’s Template

You have ParentComponent and ChildComponent that looks like this.

parent.component.html

enter image description here

parent.component.ts

import {Component} from '@angular/core';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent {
  constructor() {
  }
}

child.component.html

<p>
  This is child
</p>

child.component.ts

import {Component} from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent {
  constructor() {
  }

  doSomething() {
    console.log('do something');
  }
}

When serve, it looks like this:

enter image description here

When user focus on ParentComponent’s input element, you want to call ChildComponent’s doSomething() method.

Simply do this:

  1. Give app-child selector in parent.component.html a DOM variable name (prefix with # – hashtag), in this case we call it appChild.
  2. Assign expression value (of the method you want to call) to input element’s focus event.

enter image description here

The result:

enter image description here

Find which rows have different values for a given column in Teradata SQL

You can do this using a group by:

select id, addressCode
from t
group by id, addressCode
having min(address) <> max(address)

Another way of writing this may seem clearer, but does not perform as well:

select id, addressCode
from t
group by id, addressCode
having count(distinct address) > 1

Add a scrollbar to a <textarea>

like this

css

textarea {

overflow:scroll;
height:100px;
}

How to use the command update-alternatives --config java

I'm using Ubuntu 18.04 LTS. Most of the time, when I change my java version, I also want to use the same javac version.
I use update-alternatives this way, using a java_home alternative instead :

Installation

Install every java version in /opt/java/<version>, for example

~$ ll /opt/java/
total 24
drwxr-xr-x 6 root root 4096 jan. 22 21:14 ./
drwxr-xr-x 9 root root 4096 feb.  7 13:40 ../
drwxr-xr-x  8 stephanecodes stephanecodes 4096 jan.   8  2019 jdk-11.0.2/
drwxr-xr-x  7 stephanecodes stephanecodes 4096 dec.  15  2018 jdk1.8.0_201/

Configure alternatives

~$ sudo update-alternatives --install /opt/java/current java_home /opt/java/jdk-11.0.2/ 100
~$ sudo update-alternatives --install /opt/java/current java_home /opt/java/jdk1.8.0_201 200

Declare JAVA_HOME (In this case, I use a global initialization script for this)

~$ sudo sh -c 'echo export JAVA_HOME=\"/opt/java/current\" >> environment.sh'

Log Out or restart Ubuntu (this will reload /etc/profile.d/environment.sh)

Usage

Change java version

Choose the version you want to use

~$ sudo update-alternatives --config java_home

There are 2 choices for the alternative java_home (providing /opt/java/current).

  Selection    Path                    Priority   Status
------------------------------------------------------------
  0            /opt/java/jdk-11.0.2     200       auto mode
  1            /opt/java/jdk-11.0.2     200       manual mode
* 2            /opt/java/jdk1.8.0_201   100       manual mode

Press <enter> to keep the current choice[*], or type selection number: 

Check version

~$ java -version
openjdk version "11.0.2" 2019-01-15
OpenJDK Runtime Environment 18.9 (build 11.0.2+9)
OpenJDK 64-Bit Server VM 18.9 (build 11.0.2+9, mixed mode)

~$ javac -version
javac 11.0.2

Tip

Add the following line to ~/.bash_aliases file :

alias change-java-version="sudo update-alternatives --config java_home && java -version && javac -version"

Now use the change-java-version command to change java version

What is Java Servlet?

Java Servlets are server-side Java program modules that procedure and answer customer demands and actualize the servlet interface. It helps in improving Web server usefulness with negligible overhead, upkeep and support.

A servlet goes about as a mediator between the customer and the server. As servlet modules keep running on the server, they can get and react to demands made by the customer. Demand and reaction objects of the servlet offer a helpful method to deal with HTTP asks for and send content information back to the customer.

Since a servlet is coordinated with the Java dialect, it additionally has all the Java highlights, for example, high movability, stage autonomy, security and Java database availability.

Write a function that returns the longest palindrome in a given string

As far as I understood the problem, we can find palindromes around a center index and span our search both ways, to the right and left of the center. Given that and knowing there's no palindrome on the corners of the input, we can set the boundaries to 1 and length-1. While paying attention to the minimum and maximum boundaries of the String, we verify if the characters at the positions of the symmetrical indexes (right and left) are the same for each central position till we reach our max upper bound center.

The outer loop is O(n) (max n-2 iterations), and the inner while loop is O(n) (max around (n / 2) - 1 iterations)

Here's my Java implementation using the example provided by other users.

class LongestPalindrome {

    /**
     * @param input is a String input
     * @return The longest palindrome found in the given input.
     */
    public static String getLongestPalindrome(final String input) {
        int rightIndex = 0, leftIndex = 0;
        String currentPalindrome = "", longestPalindrome = "";
        for (int centerIndex = 1; centerIndex < input.length() - 1; centerIndex++) {
            leftIndex = centerIndex - 1;  rightIndex = centerIndex + 1;
            while (leftIndex >= 0 && rightIndex < input.length()) {
                if (input.charAt(leftIndex) != input.charAt(rightIndex)) {
                    break;
                }
                currentPalindrome = input.substring(leftIndex, rightIndex + 1);
                longestPalindrome = currentPalindrome.length() > longestPalindrome.length() ? currentPalindrome : longestPalindrome;
                leftIndex--;  rightIndex++;
            }
        }
        return longestPalindrome;
    }

    public static void main(String ... args) {
        String str = "HYTBCABADEFGHABCDEDCBAGHTFYW12345678987654321ZWETYGDE";
        String longestPali = getLongestPalindrome(str);
        System.out.println("String: " + str);
        System.out.println("Longest Palindrome: " + longestPali);
    }
}

The output of this is the following:

marcello:datastructures marcello$ javac LongestPalindrome
marcello:datastructures marcello$ java LongestPalindrome
String: HYTBCABADEFGHABCDEDCBAGHTFYW12345678987654321ZWETYGDE
Longest Palindrome: 12345678987654321

How do I make case-insensitive queries on Mongodb?

To find case Insensitive string use this,

var thename = "Andrew";
db.collection.find({"name":/^thename$/i})

how to make div click-able?

I suggest to use jQuery:

$('#mydiv')
  .css('cursor', 'pointer')
  .click(
    function(){
     alert('Click event is fired');
    }
  )
  .hover(
    function(){
      $(this).css('background', '#ff00ff');
    },
    function(){
      $(this).css('background', '');
    }
  );

PHP pass variable to include

You can execute all in "second.php" adding variable with jQuery

<div id="first"></div>

<script>
$("#first").load("second.php?a=<?php echo $var?>")
</scrpt>

How to merge a Series and DataFrame

If I could suggest setting up your dataframes like this (auto-indexing):

df = pd.DataFrame({'a':[np.nan, 1, 2], 'b':[4, 5, 6]})

then you can set up your s1 and s2 values thus (using shape() to return the number of rows from df):

s = pd.DataFrame({'s1':[5]*df.shape[0], 's2':[6]*df.shape[0]})

then the result you want is easy:

display (df.merge(s, left_index=True, right_index=True))

Alternatively, just add the new values to your dataframe df:

df = pd.DataFrame({'a':[nan, 1, 2], 'b':[4, 5, 6]})
df['s1']=5
df['s2']=6
display(df)

Both return:

     a  b  s1  s2
0  NaN  4   5   6
1  1.0  5   5   6
2  2.0  6   5   6

If you have another list of data (instead of just a single value to apply), and you know it is in the same sequence as df, eg:

s1=['a','b','c']

then you can attach this in the same way:

df['s1']=s1

returns:

     a  b s1
0  NaN  4  a
1  1.0  5  b
2  2.0  6  c

Android Studio shortcuts like Eclipse

If you're looking for a shortcut in Android studio and can't quite remember the command, simply click Ctrl+Shift+A to launch the command search. From here, you can search for any shortcut you want.

Merry coding!

Can't connect to HTTPS site using cURL. Returns 0 length content instead. What can I do?

I discovered this error on a recent application project. I was writing to run from the command line or the browser window, so I was using server detection to get the relative URL of the document I was asking for. The trouble was, the site is https, and each time I attempted to access http://(same server), cURL helpfully changed it to https.

This works fine from the browser, but from the command-line, I'd then get an SSL error even with both verify's set to false. What I had to do was,

1) Check $_SERVER['HTTP_HOST']. If present, use ($_SERVER['HTTPS'] ? "https://" : "http://").$_SERVER['HTTP_HOST']

2) Check $_SERVER['COMPUTERNAME'], and if it matched the production server, provide the https URL. ("https://(servername)")

3) If neither condition passed, it means I'm running command-line on a different server, and use "http://localhost".

Now, this worked, but it's a hack. Also, I never did figure out why on one server (https) cURL changed my URL, while on the other (also https) it left my URL alone.

Weird.

Java web start - Unable to load resource

changing java proxy settings to direct connection did not fix my issue.

What worked for me:

  1. Run "Configure Java" as administrator.
  2. Go to Advanced
  3. Scroll to bottom
  4. Under: "Advanced Security Settings" uncheck "Use SSL 2.0 compatible ClientHello format"
  5. Save

android - How to get view from context?

For example you can find any textView:

TextView textView = (TextView) ((Activity) context).findViewById(R.id.textView1);

How to use Boost in Visual Studio 2010

A small addition to KTC's very informative main answer:

If you are using the free Visual Studio c++ 2010 Express, and managed to get that one to compile 64-bits binaries, and now want to use that to use a 64-bits version of the Boost libaries, you may end up with 32-bits libraries (your mileage may vary of course, but on my machine this is the sad case).

I could fix this using the following: inbetween the steps described above as

  1. Start a 32-bit MSVC command prompt and change to the directory where Boost was unzipped.
  2. Run: bootstrap

I inserted a call to 'setenv' to set the environment. For a release build, the above steps become:

  1. Start a 32-bit MSVC command prompt and change to the directory where Boost was unzipped.
  2. Run: "C:\Program Files\Microsoft SDKs\Windows\v7.1\Bin\setenv.cmd" /Release /x64
  3. Run: bootstrap

I found this info here: http://boost.2283326.n4.nabble.com/64-bit-with-VS-Express-again-td3044258.html

Cannot create cache directory .. or directory is not writable. Proceeding without cache in Laravel

When you installed composer pretty sure you used $ sudo command because of that the ~/.composer folder was created by the root.

Run this to fix the issue:

$ sudo chown -R $USER $HOME/.composer

How to fix Uncaught InvalidValueError: setPosition: not a LatLng or LatLngLiteral: in property lat: not a number?

I was having the same problem, the fact is that the input of lat and long should be String. Only then did I manage.

for example:

Controller.

 ViewBag.Lat = object.Lat.ToString().Replace(",", ".");

 ViewBag.Lng = object.Lng.ToString().Replace(",", ".");

View - function javascript

<script>
    function initMap() {
        var myLatLng = { lat: @ViewBag.Lat, lng: @ViewBag.Lng};

        // Create a map object and specify the DOM element for display.
        var map = new window.google.maps.Map(document.getElementById('map'),
        {
            center: myLatLng,
            scrollwheel: false,
            zoom: 16
        });

        // Create a marker and set its position.
        var marker = new window.google.maps.Marker({
            map: map,
            position: myLatLng
            //title: "Blue"
        });
    }
</script>

I convert the double value to string and do a Replace in the ',' to '.' And so everything works normally.

Sending SOAP request using Python Requests

It is indeed possible.

Here is an example calling the Weather SOAP Service using plain requests lib:

import requests
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
#headers = {'content-type': 'application/soap+xml'}
headers = {'content-type': 'text/xml'}
body = """<?xml version="1.0" encoding="UTF-8"?>
         <SOAP-ENV:Envelope xmlns:ns0="http://ws.cdyne.com/WeatherWS/" xmlns:ns1="http://schemas.xmlsoap.org/soap/envelope/" 
            xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:SOAP-ENV="http://schemas.xmlsoap.org/soap/envelope/">
            <SOAP-ENV:Header/>
              <ns1:Body><ns0:GetWeatherInformation/></ns1:Body>
         </SOAP-ENV:Envelope>"""

response = requests.post(url,data=body,headers=headers)
print response.content

Some notes:

  • The headers are important. Most SOAP requests will not work without the correct headers. application/soap+xml is probably the more correct header to use (but the weatherservice prefers text/xml
  • This will return the response as a string of xml - you would then need to parse that xml.
  • For simplicity I have included the request as plain text. But best practise would be to store this as a template, then you can load it using jinja2 (for example) - and also pass in variables.

For example:

from jinja2 import Environment, PackageLoader
env = Environment(loader=PackageLoader('myapp', 'templates'))
template = env.get_template('soaprequests/WeatherSericeRequest.xml')
body = template.render()

Some people have mentioned the suds library. Suds is probably the more correct way to be interacting with SOAP, but I often find that it panics a little when you have WDSLs that are badly formed (which, TBH, is more likely than not when you're dealing with an institution that still uses SOAP ;) ).

You can do the above with suds like so:

from suds.client import Client
url="http://wsf.cdyne.com/WeatherWS/Weather.asmx?WSDL"
client = Client(url)
print client ## shows the details of this service

result = client.service.GetWeatherInformation() 
print result 

Note: when using suds, you will almost always end up needing to use the doctor!

Finally, a little bonus for debugging SOAP; TCPdump is your friend. On Mac, you can run TCPdump like so:

sudo tcpdump -As 0 

This can be helpful for inspecting the requests that actually go over the wire.

The above two code snippets are also available as gists:

Error 330 (net::ERR_CONTENT_DECODING_FAILED):

Do you use the ob_start(ob_gzhandler) function? If so and If you output any content above the ob_start(ob_gzhandler) function, you'll get this error. You can don't use this function or don't output content above this function. The ob_gzhandler callback function will determine what type of content encoding the browser will accept and will return its output accordingly. So if you output content above this function, the content's encoding maybe different from the output content of ob_gzhandler and that cause this error.

Convert array to string in NodeJS

toString is a function, not a property. You'll want this:

console.log(aa.toString());

Alternatively, use join to specify the separator (toString() === join(','))

console.log(aa.join(' and '));

Can't clone a github repo on Linux via HTTPS

As JERC said, make sure you have an updated version of git. If you are only using the default settings, when you try to install git you will get version 1.7.1. Other than manually downloading and installing the latest version of get, you can also accomplish this by adding a new repository to yum.

From tecadmin.net:

Download and install the rpmforge repository:

# use this for 64-bit
rpm -i 'http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.3-1.el6.rf.x86_64.rpm'
# use this for 32-bit
rpm -i 'http://pkgs.repoforge.org/rpmforge-release/rpmforge-release-0.5.3-1.el6.rf.i686.rpm'

# then run this in either case
rpm --import http://apt.sw.be/RPM-GPG-KEY.dag.txt

Then you need to enable the rpmforge-extras. Edit /etc/yum.repos.d/rpmforge.repo and change enabled = 0 to enabled = 1 under [rpmforge-extras]. The file looks like this:

### Name: RPMforge RPM Repository for RHEL 6 - dag
### URL: http://rpmforge.net/
[rpmforge]
name = RHEL $releasever - RPMforge.net - dag
baseurl = http://apt.sw.be/redhat/el6/en/$basearch/rpmforge
mirrorlist = http://mirrorlist.repoforge.org/el6/mirrors-rpmforge
#mirrorlist = file:///etc/yum.repos.d/mirrors-rpmforge
enabled = 1
protect = 0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rpmforge-dag
gpgcheck = 1

[rpmforge-extras]
name = RHEL $releasever - RPMforge.net - extras
baseurl = http://apt.sw.be/redhat/el6/en/$basearch/extras
mirrorlist = http://mirrorlist.repoforge.org/el6/mirrors-rpmforge-extras
#mirrorlist = file:///etc/yum.repos.d/mirrors-rpmforge-extras
enabled = 0 ####### CHANGE THIS LINE TO "enabled = 1" #############
protect = 0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rpmforge-dag
gpgcheck = 1

[rpmforge-testing]
name = RHEL $releasever - RPMforge.net - testing
baseurl = http://apt.sw.be/redhat/el6/en/$basearch/testing
mirrorlist = http://mirrorlist.repoforge.org/el6/mirrors-rpmforge-testing
#mirrorlist = file:///etc/yum.repos.d/mirrors-rpmforge-testing
enabled = 0
protect = 0
gpgkey = file:///etc/pki/rpm-gpg/RPM-GPG-KEY-rpmforge-dag
gpgcheck = 1

Once you've done this, then you can update git with

yum update git

I'm not sure why, but they then suggest disabling rpmforge-extras (change back to enabled = 0) and then running yum clean all.

Most likely you'll need to use sudo for these commands.

Jquery select change not firing

For me perfectly fork this code.

$('#dom_object_id').on('change paste keyup', function(){
    console.log($("#dom_object_id").val().length)
});

Key event for .on() function is "paste" to get changes dynamically

Using a PHP variable in a text input value = statement

From the HTML point of view everything's been said, but to correct the PHP-side approach a little and taking thirtydot's and icktoofay's advice into account:

<?php echo '<input type="text" name="idtest" value="' . htmlspecialchars($idtest) . '">'; ?>

SELECT * FROM multiple tables. MySQL

What you do here is called a JOIN (although you do it implicitly because you select from multiple tables). This means, if you didn't put any conditions in your WHERE clause, you had all combinations of those tables. Only with your condition you restrict your join to those rows where the drink id matches.

But there are still X multiple rows in the result for every drink, if there are X photos with this particular drinks_id. Your statement doesn't restrict which photo(s) you want to have!

If you only want one row per drink, you have to tell SQL what you want to do if there are multiple rows with a particular drinks_id. For this you need grouping and an aggregate function. You tell SQL which entries you want to group together (for example all equal drinks_ids) and in the SELECT, you have to tell which of the distinct entries for each grouped result row should be taken. For numbers, this can be average, minimum, maximum (to name some).

In your case, I can't see the sense to query the photos for drinks if you only want one row. You probably thought you could have an array of photos in your result for each drink, but SQL can't do this. If you only want any photo and you don't care which you'll get, just group by the drinks_id (in order to get only one row per drink):

SELECT name, price, photo
FROM drinks, drinks_photos
WHERE drinks.id = drinks_id 
GROUP BY drinks_id

name     price   photo
fanta    5       ./images/fanta-1.jpg
dew      4       ./images/dew-1.jpg

In MySQL, we also have GROUP_CONCAT, if you want the file names to be concatenated to one single string:

SELECT name, price, GROUP_CONCAT(photo, ',')
FROM drinks, drinks_photos
WHERE drinks.id = drinks_id 
GROUP BY drinks_id

name     price   photo
fanta    5       ./images/fanta-1.jpg,./images/fanta-2.jpg,./images/fanta-3.jpg
dew      4       ./images/dew-1.jpg,./images/dew-2.jpg

However, this can get dangerous if you have , within the field values, since most likely you want to split this again on the client side. It is also not a standard SQL aggregate function.

C# using Sendkey function to send a key to another application

If notepad is already started, you should write:

// import the function in your class
[DllImport ("User32.dll")]
static extern int SetForegroundWindow(IntPtr point);

//...

Process p = Process.GetProcessesByName("notepad").FirstOrDefault();
if (p != null)
{
    IntPtr h = p.MainWindowHandle;
    SetForegroundWindow(h);
    SendKeys.SendWait("k");
}

GetProcessesByName returns an array of processes, so you should get the first one (or find the one you want).

If you want to start notepad and send the key, you should write:

Process p = Process.Start("notepad.exe");
p.WaitForInputIdle();
IntPtr h = p.MainWindowHandle;
SetForegroundWindow(h);
SendKeys.SendWait("k");

The only situation in which the code may not work is when notepad is started as Administrator and your application is not.

Dynamic constant assignment

In Ruby, any variable whose name starts with a capital letter is a constant and you can only assign to it once. Choose one of these alternatives:

class MyClass
  MYCONSTANT = "blah"

  def mymethod
    MYCONSTANT
  end
end

class MyClass
  def mymethod
    my_constant = "blah"
  end
end

Mvn install or Mvn package

mvn install is the option that is most often used.
mvn package is seldom used, only if you're debugging some issue with the maven build process.

See: http://maven.apache.org/guides/introduction/introduction-to-the-lifecycle.html

Note that mvn package will only create a jar file.
mvn install will do that and install the jar (and class etc.) files in the proper places if other code depends on those jars.

I usually do a mvn clean install; this deletes the target directory and recreates all jars in that location.
The clean helps with unneeded or removed stuff that can sometimes get in the way.
Rather then debug (some of the time) just start fresh all of the time.

RestSharp JSON Parameter Posting

If you have a List of objects, you can serialize them to JSON as follow:

List<MyObjectClass> listOfObjects = new List<MyObjectClass>();

And then use addParameter:

requestREST.AddParameter("myAssocKey", JsonConvert.SerializeObject(listOfObjects));

And you wil need to set the request format to JSON:

requestREST.RequestFormat = DataFormat.Json;

How do write IF ELSE statement in a MySQL query

according to the mySQL reference manual this the syntax of using if and else statement :

IF search_condition THEN statement_list
[ELSEIF search_condition THEN statement_list] ...
[ELSE statement_list]
END IF

So regarding your query :

x = IF((action=2)&&(state=0),1,2);

or you can use

IF ((action=2)&&(state=0)) then 
state = 1;
ELSE 
state = 2;
END IF;

There is good example in this link : http://easysolutionweb.com/sql-pl-sql/how-to-use-if-and-else-in-mysql/

Ignoring new fields on JSON objects using Jackson

Make sure that you place the @JsonIgnoreProperties(ignoreUnknown = true) annotation to the parent POJO class which you want to populate as a result of parsing the JSON response and not the class where the conversion from JSON to Java Object is taking place.

VBScript - How to make program wait until process has finished?

This may not specifically answer your long 3 part question but this thread is old and I found this while searching today. Here is one shorter way to: "Wait until a process has finished." If you know the name of the process such as "EXCEL.EXE"

strProcess = "EXCEL.EXE"    
Set objWMIService = GetObject("winmgmts:{impersonationLevel=impersonate}!\\.\root\cimv2")
Set colProcesses = objWMIService.ExecQuery ("Select * from Win32_Process Where Name = '"& strProcess &"'")
Do While colProcesses.Count > 0
    Set colProcesses = objWMIService.ExecQuery ("Select * from Win32_Process Where Name = '"& strProcess &"'")
    Wscript.Sleep(1000) 'Sleep 1 second
   'msgbox colProcesses.count 'optional to show the loop works
Loop

Credit to: http://crimsonshift.com/scripting-check-if-process-or-program-is-running-and-start-it/

Array vs. Object efficiency in JavaScript

In NodeJS if you know the ID, the looping through the array is very slow compared to object[ID].

const uniqueString = require('unique-string');
const obj = {};
const arr = [];
var seeking;

//create data
for(var i=0;i<1000000;i++){
  var getUnique = `${uniqueString()}`;
  if(i===888555) seeking = getUnique;
  arr.push(getUnique);
  obj[getUnique] = true;
}

//retrieve item from array
console.time('arrTimer');
for(var x=0;x<arr.length;x++){
  if(arr[x]===seeking){
    console.log('Array result:');
    console.timeEnd('arrTimer');
    break;
  }
}

//retrieve item from object
console.time('objTimer');
var hasKey = !!obj[seeking];
console.log('Object result:');
console.timeEnd('objTimer');

And the results:

Array result:
arrTimer: 12.857ms
Object result:
objTimer: 0.051ms

Even if the seeking ID is the first one in the array/object:

Array result:
arrTimer: 2.975ms
Object result:
objTimer: 0.068ms

What is the meaning of "Failed building wheel for X" in pip install?

I had the same problem while installing Brotli

ERROR

Failed building wheel for Brotli

I solved it by downloading the .whl file from here and installing it using the below command

C:\Users\{user_name}\Downloads>pip install Brotli-1.0.9-cp39-cp39-win_amd64.whl

How can I see the raw SQL queries Django is running?

Just to add, in django, if you have a query like:

MyModel.objects.all()

do:

MyModel.objects.all().query.sql_with_params()

or:

str(MyModel.objects.all().query)

to get the sql string

Android Studio 3.0 Execution failed for task: unable to merge dex

Use multiDexEnabled true as below.

{
 minSdkVersion 17
    targetSdkVersion 28
    versionCode 1
    versionName "1.0"
    testInstrumentationRunner "android.support.test.runner.AndroidJUnitRunner"
    multiDexEnabled true
}

and

implementation 'com.android.support:multidex:1.0.3'

this Solution worked for me.

javascript regex for special characters

this is the actual regex only match:

/[-!$%^&*()_+|~=`{}[:;<>?,.@#\]]/g

Favicon not showing up in Google Chrome

I read a bunch of different entries till I finally found a solution that worked for my scenario (ASP.NET MVC4 project).

Instead of using the filename favicon.ico for my icon, I renamed it to something else, ie myIcon.ico. Then I just used exactly what Domi posted:

<link rel="shortcut icon" href="myIcon.ico" type="image/x-icon" />

And this worked!

It's not a caching issue because I tested this with Fiddler - a request for favicon never occurred, even if I cleared my cache "From the beginning of time". I believe it's just some odd bug with chrome?

Hashing a string with Sha256

The shortest and fastest way ever. Only 1 line!

public static string StringSha256Hash(string text) =>
    string.IsNullOrEmpty(text) ? string.Empty : BitConverter.ToString(new System.Security.Cryptography.SHA256Managed().ComputeHash(System.Text.Encoding.UTF8.GetBytes(text))).Replace("-", string.Empty);

How do I remove all .pyc files from a project?

find . -name "*.pyc"|xargs rm -rf

Git merge two local branches

If you or another dev will not work on branchB further, I think it's better to keep commits in order to make reverts without headaches. So ;

git checkout branchA
git pull --rebase branchB

It's important that branchB shouldn't be used anymore.

For more ; https://www.derekgourlay.com/blog/git-when-to-merge-vs-when-to-rebase/

Can a variable number of arguments be passed to a function?

If I may, Skurmedel's code is for python 2; to adapt it to python 3, change iteritems to items and add parenthesis to print. That could prevent beginners like me to bump into: AttributeError: 'dict' object has no attribute 'iteritems' and search elsewhere (e.g. Error “ 'dict' object has no attribute 'iteritems' ” when trying to use NetworkX's write_shp()) why this is happening.

def myfunc(**kwargs):
for k,v in kwargs.items():
   print("%s = %s" % (k, v))

myfunc(abc=123, efh=456)
# abc = 123
# efh = 456

and:

def myfunc2(*args, **kwargs):
   for a in args:
       print(a)
   for k,v in kwargs.items():
       print("%s = %s" % (k, v))

myfunc2(1, 2, 3, banan=123)
# 1
# 2
# 3
# banan = 123

How to perform runtime type checking in Dart?

There are two operators for type testing: E is T tests for E an instance of type T while E is! T tests for E not an instance of type T.

Note that E is Object is always true, and null is T is always false unless T===Object.

How to process POST data in Node.js?

Here is how you can do it if you use node-formidable:

var formidable = require("formidable");

var form = new formidable.IncomingForm();
form.parse(request, function (err, fields) {
    console.log(fields.parameter1);
    console.log(fields.parameter2);
    // ...
});

Is there a foreach in MATLAB? If so, how does it behave if the underlying data changes?

ooh! neat question.

Matlab's for loop takes a matrix as input and iterates over its columns. Matlab also handles practically everything by value (no pass-by-reference) so I would expect that it takes a snapshot of the for-loop's input so it's immutable.

here's an example which may help illustrate:

>> A = zeros(4); A(:) = 1:16

A =

     1     5     9    13
     2     6    10    14
     3     7    11    15
     4     8    12    16

>> i = 1; for col = A; disp(col'); A(:,i) = i; i = i + 1; end;
     1     2     3     4

     5     6     7     8

     9    10    11    12

    13    14    15    16

>> A

A =

     1     2     3     4
     1     2     3     4
     1     2     3     4
     1     2     3     4

Get button click inside UITableViewCell

I find it simplest to subclass the button inside your cell (Swift 3):

class MyCellInfoButton: UIButton {
    var indexPath: IndexPath?
}

In your cell class:

class MyCell: UICollectionViewCell {
    @IBOutlet weak var infoButton: MyCellInfoButton!
   ...
}

In the table view's or collection view's data source, when dequeueing the cell, give the button its index path:

cell.infoButton.indexPath = indexPath

So you can just put these code into your table view controller:

@IBAction func handleTapOnCellInfoButton(_ sender: MyCellInfoButton) {
        print(sender.indexPath!) // Do whatever you want with the index path!
}

And don't forget to set the button's class in your Interface Builder and link it to the handleTapOnCellInfoButton function!


edited:

Using dependency injection. To set up calling a closure:

class MyCell: UICollectionViewCell {
    var someFunction: (() -> Void)?
    ...
    @IBAction func didTapInfoButton() {
        someFunction?()
    }
}

and inject the closure in the willDisplay method of the collection view's delegate:

 func collectionView(_ collectionView: UICollectionView, willDisplay cell: UICollectionViewCell, forItemAt indexPath: IndexPath) {
    (cell as? MyCell)?.someFunction = {
        print(indexPath) // Do something with the indexPath.
    }
}

Linear regression with matplotlib / numpy

Another quick and dirty answer is that you can just convert your list to an array using:

import numpy as np
arr = np.asarray(listname)

How to check undefined in Typescript

Use 'this' keyword to access variable. This worked for me

var  uemail = localStorage.getItem("useremail");

if (typeof this.uemail === "undefined")
{
    alert('undefined');
}
else
{
    alert('defined');
}

Start index for iterating Python list

stdlib will hook you up son!

deque.rotate():

#!/usr/local/bin/python2.7

from collections import deque

a = deque('Monday Tuesday Wednesday Thursday Friday Saturday Sunday'.split(' '))
a.rotate(3)
deque(['Friday', 'Saturday', 'Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday'])

jQuery, get html of a whole element

Differences might not be meaningful in a typical use case, but using the standard DOM functionality

$("#el")[0].outerHTML

is about twice as fast as

$("<div />").append($("#el").clone()).html();

so I would go with:

/* 
 * Return outerHTML for the first element in a jQuery object,
 * or an empty string if the jQuery object is empty;  
 */
jQuery.fn.outerHTML = function() {
   return (this[0]) ? this[0].outerHTML : '';  
};

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

From RFC 3986:

A URI can be further classified as a locator, a name, or both. The term "Uniform Resource Locator" (URL) refers to the subset of URIs that, in addition to identifying a resource, provide a means of locating the resource by describing its primary access mechanism (e.g., its network "location"). The term "Uniform Resource Name" (URN) has been used historically to refer to both URIs under the "urn" scheme [RFC2141], which are required to remain globally unique and persistent even when the resource ceases to exist or becomes unavailable, and to any other URI with the properties of a name.

So all URLs are URIs, and all URNs are URIs - but URNs and URLs are different, so you can't say that all URIs are URLs.

If you haven't already read Roger Pate's answer, I'd advise doing so as well.

Regular Expression to get all characters before "-"

I dont think you need regex to achieve this. I would look at the SubString method along with the indexOf method. If you need more help, add a comment showing what you have attempted and I will offer more help.

What is the difference between const and readonly in C#?

One of the team members in our office provided the following guidance on when to use const, static, and readonly:

  • Use const when you have a variable of a type you can know at runtime (string literal, int, double, enums,...) that you want all instances or consumers of a class to have access to where the value should not change.
  • Use static when you have data that you want all instances or consumers of a class to have access to where the value can change.
  • Use static readonly when you have a variable of a type that you cannot know at runtime (objects) that you want all instances or consumers of a class to have access to where the value should not change.
  • Use readonly when you have an instance level variable you will know at the time of object creation that should not change.

One final note: a const field is static, but the inverse is not true.

Catching FULL exception message

I found it!

Simply print out $Error[0] for the last error message.

Convert hex string (char []) to int?

Something like this could be useful:

char str[] = "0x1800785";
int num;

sscanf(str, "%x", &num);
printf("0x%x %i\n", num, num); 

Read man sscanf

Adding a rule in iptables in debian to open a new port

(I presume that you've concluded that it's an iptables problem by dropping the firewall completely (iptables -P INPUT ACCEPT; iptables -P OUTPUT ACCEPT; iptables -F) and confirmed that you can connect to the MySQL server from your Windows box?)

Some previous rule in the INPUT table is probably rejecting or dropping the packet. You can get around that by inserting the new rule at the top, although you might want to review your existing rules to see whether that's sensible:

iptables -I INPUT 1 -p tcp --dport 3306 -j ACCEPT

Note that iptables-save won't save the new rule persistently (i.e. across reboots) - you'll need to figure out something else for that. My usual route is to store the iptables-save output in a file (/etc/network/iptables.rules or similar) and then load then with a pre-up statement in /etc/network/interfaces).

BULK INSERT with identity (auto-increment) column

  1. Create a table with Identity column + other columns;
  2. Create a view over it and expose only the columns you will bulk insert;
  3. BCP in the view

How can I preview a merge in git?

git log currentbranch..otherbranch will give you the list of commits that will go into the current branch if you do a merge. The usual arguments to log which give details on the commits will give you more information.

git diff currentbranch otherbranch will give you the diff between the two commits that will become one. This will be a diff that gives you everything that will get merged.

Would these help?

System.Data.SqlClient.SqlException: Login failed for user

Assuming you're intending to use Windows Authentication to impersonate the service account, you have to set up Windows Authentication in both IIS and ASP.NET.

In IIS, make sure that the Windows Authentication module is added and enabled. Also make sure your application pool is running under a domain account, not a local account.

In ASP.NET make sure the authentication mode attribute is set to "Windows"

<system.web>
    <authentication mode="Windows"/>
 </system.web>

Bigger Glyphicons

In my case, I had an input-group-btn with a button, and this button was a little bigger than its container. So I just gave font-size:95% for my glyphicon and it was solved.

<div class="input-group">
    <input type="text" class="form-control" id="pesquisarinbox" placeholder="Pesquisar na Caixa de Entrada">
    <div class="input-group-btn">
        <button class="btn btn-default" type="button">
            <span class="glyphicon glyphicon-search" style="font-size:95%;"></span>
        </button>
    </div>  
</div>

How to send file contents as body entity using cURL

I believe you're looking for the @filename syntax, e.g.:

strip new lines

curl --data "@/path/to/filename" http://...

keep new lines

curl --data-binary "@/path/to/filename" http://...

curl will strip all newlines from the file. If you want to send the file with newlines intact, use --data-binary in place of --data

Java Round up Any Number

10 years later but that problem still caught me.

So this is the answer to those that are too late as me.

This does not work

int b = (int) Math.ceil(a / 100);

Cause the result a / 100 turns out to be an integer and it's rounded so Math.ceil can't do anything about it.

You have to avoid the rounded operation with this

int b = (int) Math.ceil((float) a / 100);

Now it works.

Why is it common to put CSRF prevention tokens in cookies?

A good reason, which you have sort of touched on, is that once the CSRF cookie has been received, it is then available for use throughout the application in client script for use in both regular forms and AJAX POSTs. This will make sense in a JavaScript heavy application such as one employed by AngularJS (using AngularJS doesn't require that the application will be a single page app, so it would be useful where state needs to flow between different page requests where the CSRF value cannot normally persist in the browser).

Consider the following scenarios and processes in a typical application for some pros and cons of each approach you describe. These are based on the Synchronizer Token Pattern.

Request Body Approach

  1. User successfully logs in.
  2. Server issues auth cookie.
  3. User clicks to navigate to a form.
  4. If not yet generated for this session, server generates CSRF token, stores it against the user session and outputs it to a hidden field.
  5. User submits form.
  6. Server checks hidden field matches session stored token.

Advantages:

  • Simple to implement.
  • Works with AJAX.
  • Works with forms.
  • Cookie can actually be HTTP Only.

Disadvantages:

  • All forms must output the hidden field in HTML.
  • Any AJAX POSTs must also include the value.
  • The page must know in advance that it requires the CSRF token so it can include it in the page content so all pages must contain the token value somewhere, which could make it time consuming to implement for a large site.

Custom HTTP Header (downstream)

  1. User successfully logs in.
  2. Server issues auth cookie.
  3. User clicks to navigate to a form.
  4. Page loads in browser, then an AJAX request is made to retrieve the CSRF token.
  5. Server generates CSRF token (if not already generated for session), stores it against the user session and outputs it to a header.
  6. User submits form (token is sent via hidden field).
  7. Server checks hidden field matches session stored token.

Advantages:

Disadvantages:

  • Doesn't work without an AJAX request to get the header value.
  • All forms must have the value added to its HTML dynamically.
  • Any AJAX POSTs must also include the value.
  • The page must make an AJAX request first to get the CSRF token, so it will mean an extra round trip each time.
  • Might as well have simply output the token to the page which would save the extra request.

Custom HTTP Header (upstream)

  1. User successfully logs in.
  2. Server issues auth cookie.
  3. User clicks to navigate to a form.
  4. If not yet generated for this session, server generates CSRF token, stores it against the user session and outputs it in the page content somewhere.
  5. User submits form via AJAX (token is sent via header).
  6. Server checks custom header matches session stored token.

Advantages:

Disadvantages:

  • Doesn't work with forms.
  • All AJAX POSTs must include the header.

Custom HTTP Header (upstream & downstream)

  1. User successfully logs in.
  2. Server issues auth cookie.
  3. User clicks to navigate to a form.
  4. Page loads in browser, then an AJAX request is made to retrieve the CSRF token.
  5. Server generates CSRF token (if not already generated for session), stores it against the user session and outputs it to a header.
  6. User submits form via AJAX (token is sent via header) .
  7. Server checks custom header matches session stored token.

Advantages:

Disadvantages:

  • Doesn't work with forms.
  • All AJAX POSTs must also include the value.
  • The page must make an AJAX request first to get the CRSF token, so it will mean an extra round trip each time.

Set-Cookie

  1. User successfully logs in.
  2. Server issues auth cookie.
  3. User clicks to navigate to a form.
  4. Server generates CSRF token, stores it against the user session and outputs it to a cookie.
  5. User submits form via AJAX or via HTML form.
  6. Server checks custom header (or hidden form field) matches session stored token.
  7. Cookie is available in browser for use in additional AJAX and form requests without additional requests to server to retrieve the CSRF token.

Advantages:

  • Simple to implement.
  • Works with AJAX.
  • Works with forms.
  • Doesn't necessarily require an AJAX request to get the cookie value. Any HTTP request can retrieve it and it can be appended to all forms/AJAX requests via JavaScript.
  • Once the CSRF token has been retrieved, as it is stored in a cookie the value can be reused without additional requests.

Disadvantages:

  • All forms must have the value added to its HTML dynamically.
  • Any AJAX POSTs must also include the value.
  • The cookie will be submitted for every request (i.e. all GETs for images, CSS, JS, etc, that are not involved in the CSRF process) increasing request size.
  • Cookie cannot be HTTP Only.

So the cookie approach is fairly dynamic offering an easy way to retrieve the cookie value (any HTTP request) and to use it (JS can add the value to any form automatically and it can be employed in AJAX requests either as a header or as a form value). Once the CSRF token has been received for the session, there is no need to regenerate it as an attacker employing a CSRF exploit has no method of retrieving this token. If a malicious user tries to read the user's CSRF token in any of the above methods then this will be prevented by the Same Origin Policy. If a malicious user tries to retrieve the CSRF token server side (e.g. via curl) then this token will not be associated to the same user account as the victim's auth session cookie will be missing from the request (it would be the attacker's - therefore it won't be associated server side with the victim's session).

As well as the Synchronizer Token Pattern there is also the Double Submit Cookie CSRF prevention method, which of course uses cookies to store a type of CSRF token. This is easier to implement as it does not require any server side state for the CSRF token. The CSRF token in fact could be the standard authentication cookie when using this method, and this value is submitted via cookies as usual with the request, but the value is also repeated in either a hidden field or header, of which an attacker cannot replicate as they cannot read the value in the first place. It would be recommended to choose another cookie however, other than the authentication cookie so that the authentication cookie can be secured by being marked HttpOnly. So this is another common reason why you'd find CSRF prevention using a cookie based method.

C# error: "An object reference is required for the non-static field, method, or property"

The Main method is Static. You can not invoke a non-static method from a static method.

GetRandomBits()

is not a static method. Either you have to create an instance of Program

Program p = new Program();
p.GetRandomBits();

or make

GetRandomBits() static.

Uncaught TypeError: undefined is not a function on loading jquery-min.js

I've run into the very same issue, when mistakenly named variable with the very same name, as function.

So this:

isLive = isLive(data);

failed, generating OP's mentioned error message.

Fix to this was as simple as changing above line to:

isItALive = isLive(data);

I don't know, how much does it helps in this situation, but I decided to put this answer for others looking for a solution for similar problems.

Why do I get "warning longer object length is not a multiple of shorter object length"?

I had a similar problem but it had to do with the structure and class of the object. I would check how dih_y2$MemberID is formatted.

How can I run multiple curl requests processed sequentially?

Another crucial method not mentioned here is using the same TCP connection for multiple HTTP requests, and exactly one curl command for this.

This is very useful to save network bandwidth, client and server resources, and overall the need of using multiple curl commands, as curl by default closes the connection when end of command is reached.

Keeping the connection open and reusing it is very common for standard clients running a web-app.

Starting curl version 7.36.0, the --next or -: command-line option allows to chain multiple requests, and usable both in command-line and scripting.

For example:

  • Sending multiple requests on the same TCP connection:

curl http://example.com/?update_=1 -: http://example.com/foo

  • Sending multiple different HTTP requests on the same connection:

curl http://example.com/?update_=1 -: -d "I am posting this string" http://example.com/?update_=2

  • Sending multiple HTTP requests with different curl options for each request:

curl -o 'my_output_file' http://example.com/?update_=1 -: -d "my_data" -s -m 10 http://example.com/foo -: -o /dev/null http://example.com/random

From the curl manpage:

-:, --next

Tells curl to use a separate operation for the following URL and associated options. This allows you to send several URL requests, each with their own specific options, for example, such as different user names or custom requests for each.

-:, --next will reset all local options and only global ones will have their values survive over to the operation following the -:, --next instruction. Global options include -v, --verbose, --trace, --trace-ascii and --fail-early.

For example, you can do both a GET and a POST in a single command line:

curl www1.example.com --next -d postthis www2.example.com

Added in 7.36.0.

How to fix "Attempted relative import in non-package" even with __init__.py

You can use import components.core directly if you append the current directory to sys.path:

if __name__ == '__main__' and __package__ is None:
    from os import sys, path
    sys.path.append(path.dirname(path.dirname(path.abspath(__file__))))

Check if starting characters of a string are alphabetical in T-SQL

You don't need to use regex, LIKE is sufficient:

WHERE my_field LIKE '[a-zA-Z][a-zA-Z]%'

Assuming that by "alphabetical" you mean only latin characters, not anything classified as alphabetical in Unicode.

Note - if your collation is case sensitive, it's important to specify the range as [a-zA-Z]. [a-z] may exclude A or Z. [A-Z] may exclude a or z.

How to remove newlines from beginning and end of a string?

If you only want to remove line breaks (not spaces, tabs) at the beginning and end of a String (not inbetween), then you can use this approach:

Use a regular expressions to remove carriage returns (\\r) and line feeds (\\n) from the beginning (^) and ending ($) of a string:

 s = s.replaceAll("(^[\\r\\n]+|[\\r\\n]+$)", "")

Complete Example:

public class RemoveLineBreaks {
    public static void main(String[] args) {
        var s = "\nHello\nWorld\n";
        System.out.println("before: >"+s+"<");
        s = s.replaceAll("(^[\\r\\n]+|[\\r\\n]+$)", "");
        System.out.println("after: >"+s+"<");
    }
}

It outputs:

before: >
Hello
World
<
after: >Hello
World<

Is there a sleep function in JavaScript?

A naive, CPU-intensive method to block execution for a number of milliseconds:

/**
* Delay for a number of milliseconds
*/
function sleep(delay) {
    var start = new Date().getTime();
    while (new Date().getTime() < start + delay);
}

Using Excel VBA to export data to MS Access table

@Ahmed

Below is code that specifies fields from a named range for insertion into MS Access. The nice thing about this code is that you can name your fields in Excel whatever the hell you want (If you use * then the fields have to match exactly between Excel and Access) as you can see I have named an Excel column "Haha" even though the Access column is called "dte".

Sub test()
    dbWb = Application.ActiveWorkbook.FullName
    dsh = "[" & Application.ActiveSheet.Name & "$]" & "Data2"  'Data2 is a named range


sdbpath = "C:\Users\myname\Desktop\Database2.mdb"
sCommand = "INSERT INTO [main] ([dte], [test1], [values], [values2]) SELECT [haha],[test1],[values],[values2] FROM [Excel 8.0;HDR=YES;DATABASE=" & dbWb & "]." & dsh

Dim dbCon As New ADODB.Connection
Dim dbCommand As New ADODB.Command

dbCon.Open "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" & sdbpath & "; Jet OLEDB:Database Password=;"
dbCommand.ActiveConnection = dbCon

dbCommand.CommandText = sCommand
dbCommand.Execute

dbCon.Close


End Sub

How do I get a div to float to the bottom of its container?

Put the div in another div and set the parent div's style to position:relative; Then on the child div set the following CSS properties: position:absolute; bottom:0;

How to use sed to replace only the first occurrence in a file?

The use case can perhaps be that your occurences are spread throughout your file, but you know your only concern is in the first 10, 20 or 100 lines.

Then simply adressing those lines fixes the issue - even if the wording of the OP regards first only.

sed '1,10s/#include/#include "newfile.h"\n#include/'

How to initialize a vector in C++

You can also do like this:

template <typename T>
class make_vector {
public:
  typedef make_vector<T> my_type;
  my_type& operator<< (const T& val) {
    data_.push_back(val);
    return *this;
  }
  operator std::vector<T>() const {
    return data_;
  }
private:
  std::vector<T> data_;
};

And use it like this:

std::vector<int> v = make_vector<int>() << 1 << 2 << 3;

Write variable to file, including name

Is something like this what you're looking for?

def write_vars_to_file(f, **vars):
    for name, val in vars.items():
        f.write("%s = %s\n" % (name, repr(val)))

Usage:

>>> import sys
>>> write_vars_to_file(sys.stdout, dict={'one': 1, 'two': 2})
dict = {'two': 2, 'one': 1}

How to get Rails.logger printing to the console/stdout when running rspec?

For Rails 4, see this answer.

For Rails 3.x, configure a logger in config/environments/test.rb:

config.logger = Logger.new(STDOUT)
config.logger.level = Logger::ERROR

This will interleave any errors that are logged during testing to STDOUT. You may wish to route the output to STDERR or use a different log level instead.

Sending these messages to both the console and a log file requires something more robust than Ruby's built-in Logger class. The logging gem will do what you want. Add it to your Gemfile, then set up two appenders in config/environments/test.rb:

logger = Logging.logger['test']
logger.add_appenders(
    Logging.appenders.stdout,
    Logging.appenders.file('example.log')
)
logger.level = :info
config.logger = logger

Package signatures do not match the previously installed version

You need to uninstall it because you are using a different signature than the original. If it is not working it might be because it is still installed for another user on the device. To completely uninstall, go to Settings -> Apps -> HAgnostic News -> Options (the three dots on top right) -> Uninstall for all users

Apache shutdown unexpectedly

It means port 80 is already used by another one.

Simply follow these steps:

  1. Open windows -> click on Run (win + R) -> type services.msc
  2. Goto IIS Admin -> Right click on it and click on Stop Option.
  3. Open XAMPP click on Start Action of Apache Module, Apache Module is run.

OR

For find the port of Apache (80) in Command Prompt simply type netstat -aon it displays present used ports on windows, under Local Address column it shown as 0.0.0.0:80. If it displays this port another connection is already used this port number.

Active Connections in Windows XP:

Active Connections in Windows XP

I solved my problem after installing xampp-win32-1.6.5-installer previously I used xampp version xampp-win32-1.8.2-0-VC9-installer at that time I got this error. Now it resolved my problem.

Order data frame rows according to vector with specific order

I prefer to use ***_join in dplyr whenever I need to match data. One possible try for this

left_join(data.frame(name=target),df,by="name")

Note that the input for ***_join require tbls or data.frame

Initial bytes incorrect after Java AES/CBC decryption

Lot of people including myself face lot of issues in making this work due to missing some information like, forgetting to convert to Base64, initialization vectors, character set, etc. So I thought of making a fully functional code.

Hope this will be useful to you all: To compile you need additional Apache Commons Codec jar, which is available here: http://commons.apache.org/proper/commons-codec/download_codec.cgi

import javax.crypto.Cipher;
import javax.crypto.spec.IvParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import org.apache.commons.codec.binary.Base64;

public class Encryptor {
    public static String encrypt(String key, String initVector, String value) {
        try {
            IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.ENCRYPT_MODE, skeySpec, iv);

            byte[] encrypted = cipher.doFinal(value.getBytes());
            System.out.println("encrypted string: "
                    + Base64.encodeBase64String(encrypted));

            return Base64.encodeBase64String(encrypted);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return null;
    }

    public static String decrypt(String key, String initVector, String encrypted) {
        try {
            IvParameterSpec iv = new IvParameterSpec(initVector.getBytes("UTF-8"));
            SecretKeySpec skeySpec = new SecretKeySpec(key.getBytes("UTF-8"), "AES");

            Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5PADDING");
            cipher.init(Cipher.DECRYPT_MODE, skeySpec, iv);

            byte[] original = cipher.doFinal(Base64.decodeBase64(encrypted));

            return new String(original);
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        return null;
    }

    public static void main(String[] args) {
        String key = "Bar12345Bar12345"; // 128 bit key
        String initVector = "RandomInitVector"; // 16 bytes IV

        System.out.println(decrypt(key, initVector,
                encrypt(key, initVector, "Hello World")));
    }
}

Should I Dispose() DataSet and DataTable?

If your intention or the context of this question is really garbage collection, then you can set the datasets and datatables to null explicitly or use the keyword using and let them go out of scope. Dispose does not do much as Tetraneutron said it earlier. GC will collect dataset objects that are no longer referenced and also those that are out of scope.

I really wish SO forced people down voting to actually write a comment before downvoting the answer.

Send response to all clients except sender

Emit cheatsheet

io.on('connect', onConnect);

function onConnect(socket){

  // sending to the client
  socket.emit('hello', 'can you hear me?', 1, 2, 'abc');

  // sending to all clients except sender
  socket.broadcast.emit('broadcast', 'hello friends!');

  // sending to all clients in 'game' room except sender
  socket.to('game').emit('nice game', "let's play a game");

  // sending to all clients in 'game1' and/or in 'game2' room, except sender
  socket.to('game1').to('game2').emit('nice game', "let's play a game (too)");

  // sending to all clients in 'game' room, including sender
  io.in('game').emit('big-announcement', 'the game will start soon');

  // sending to all clients in namespace 'myNamespace', including sender
  io.of('myNamespace').emit('bigger-announcement', 'the tournament will start soon');

  // sending to individual socketid (private message)
  socket.to(<socketid>).emit('hey', 'I just met you');

  // sending with acknowledgement
  socket.emit('question', 'do you think so?', function (answer) {});

  // sending without compression
  socket.compress(false).emit('uncompressed', "that's rough");

  // sending a message that might be dropped if the client is not ready to receive messages
  socket.volatile.emit('maybe', 'do you really need it?');

  // sending to all clients on this node (when using multiple nodes)
  io.local.emit('hi', 'my lovely babies');

};

Request UAC elevation from within a Python script?

It seems there's no way to elevate the application privileges for a while for you to perform a particular task. Windows needs to know at the start of the program whether the application requires certain privileges, and will ask the user to confirm when the application performs any tasks that need those privileges. There are two ways to do this:

  1. Write a manifest file that tells Windows the application might require some privileges
  2. Run the application with elevated privileges from inside another program

This two articles explain in much more detail how this works.

What I'd do, if you don't want to write a nasty ctypes wrapper for the CreateElevatedProcess API, is use the ShellExecuteEx trick explained in the Code Project article (Pywin32 comes with a wrapper for ShellExecute). How? Something like this:

When your program starts, it checks if it has Administrator privileges, if it doesn't it runs itself using the ShellExecute trick and exits immediately, if it does, it performs the task at hand.

As you describe your program as a "script", I suppose that's enough for your needs.

Cheers.

ASP.NET MVC - Attaching an entity of type 'MODELNAME' failed because another entity of the same type already has the same primary key value

Problem SOLVED!

Attach method could potentially help somebody but it wouldn't help in this situation as the document was already being tracked while being loaded in Edit GET controller function. Attach would throw exactly the same error.

The issue I encounter here was caused by function canUserAccessA() which loads the A entity before updating the state of object a. This was screwing up the tracked entity and it was changing state of a object to Detached.

The solution was to amend canUserAccessA() so that the object I was loading wouldn't be tracked. Function AsNoTracking() should be called while querying the context.

// User -> Receipt validation
private bool canUserAccessA(int aID)
{
    int userID = WebSecurity.GetUserId(User.Identity.Name);
    int aFound = db.Model.AsNoTracking().Where(x => x.aID == aID && x.UserID==userID).Count();

    return (aFound > 0); //if aFound > 0, then return true, else return false.
}

For some reason I couldnt use .Find(aID) with AsNoTracking() but it doesn't really matter as I could achieve the same by changing the query.

Hope this will help anybody with similar problem!

Python: SyntaxError: non-keyword after keyword arg

It's just what it says:

inputFile = open((x), encoding = "utf8", "r")

You have specified encoding as a keyword argument, but "r" as a positional argument. You can't have positional arguments after keyword arguments. Perhaps you wanted to do:

inputFile = open((x), "r", encoding = "utf8")

How to convert a time string to seconds?

def time_to_sec(t):
   h, m, s = map(int, t.split(':'))
   return h * 3600 + m * 60 + s

t = '10:40:20'
time_to_sec(t)  # 38420

How to use boost bind with a member function

Use the following instead:

boost::function<void (int)> f2( boost::bind( &myclass::fun2, this, _1 ) );

This forwards the first parameter passed to the function object to the function using place-holders - you have to tell Boost.Bind how to handle the parameters. With your expression it would try to interpret it as a member function taking no arguments.
See e.g. here or here for common usage patterns.

Note that VC8s cl.exe regularly crashes on Boost.Bind misuses - if in doubt use a test-case with gcc and you will probably get good hints like the template parameters Bind-internals were instantiated with if you read through the output.

The specified child already has a parent. You must call removeView() on the child's parent first (Android)

if(tv!= null){
    ((ViewGroup)tv.getParent()).removeView(tv); // <- fix
}

Ant if else condition?

Since ant 1.9.1 you can use a if:set condition : https://ant.apache.org/manual/ifunless.html

How do I use popover from Twitter Bootstrap to display an image?

This is what I used.

$('#foo').popover({
    placement : 'bottom',
    title : 'Title',
    content : '<div id="popOverBox"><img src="http://i.telegraph.co.uk/multimedia/archive/01515/alGore_1515233c.jpg" /></div>'
});

and for the HTML

<b id="foo" rel="popover">text goes here</b>

iterating over and removing from a map

ConcurrentHashMap

You can use java.util.concurrent.ConcurrentHashMap.

It implements ConcurrentMap (which extends the Map interface).

E.g.:

Map<Object, Content> map = new ConcurrentHashMap<Object, Content>();

for (Object key : map.keySet()) {
    if (something) {
        map.remove(key);
    }
}

This approach leaves your code untouched. Only the map type differs.

Text that shows an underline on hover

Fairly simple process I am using SCSS obviously but you don't have to as it's just CSS in the end!

HTML

<span class="menu">Menu</span>

SCSS

.menu {
    position: relative;
    text-decoration: none;
    font-weight: 400;
    color: blue;
    transition: all .35s ease;

    &::before {
        content: "";
        position: absolute;
        width: 100%;
        height: 2px;
        bottom: 0;
        left: 0;
        background-color: yellow;
        visibility: hidden;
        -webkit-transform: scaleX(0);
        transform: scaleX(0);
        -webkit-transition: all 0.3s ease-in-out 0s;
        transition: all 0.3s ease-in-out 0s;
    }

    &:hover {
        color: yellow;

        &::before {
            visibility: visible;
            -webkit-transform: scaleX(1);
            transform: scaleX(1);
        }
    }
}

How do I vertically align something inside a span tag?

Use line-height:50px; instead of height. That should do the trick ;)

How to get the dimensions of a tensor (in TensorFlow) at graph construction time?

Just print out the embed after construction graph (ops) without running:

import tensorflow as tf

...

train_dataset = tf.placeholder(tf.int32, shape=[128, 2])
embeddings = tf.Variable(
    tf.random_uniform([50000, 64], -1.0, 1.0))
embed = tf.nn.embedding_lookup(embeddings, train_dataset)
print (embed)

This will show the shape of the embed tensor:

Tensor("embedding_lookup:0", shape=(128, 2, 64), dtype=float32)

Usually, it's good to check shapes of all tensors before training your models.

Update just one gem with bundler

I've used bundle update --source myself for a long time but there are scenarios where it doesn't work. Luckily, there's a gem called bundler-patch which has the goal of fixing this shortcoming.

I also wrote a short blog post about how to use bundler-patch and why bundle update --source doesn't work consistently. Also, be sure to check out a post by chrismo that explains in great detail what the --source option does.

VBA Subscript out of range - error 9

Subscript out of Range error occurs when you try to reference an Index for a collection that is invalid.

Most likely, the index in Windows does not actually include .xls. The index for the window should be the same as the name of the workbook displayed in the title bar of Excel.

As a guess, I would try using this:

Windows("Data Sheet - " & ComboBox_Month.Value & " " & TextBox_Year.Value).Activate

Bulk create model objects in django

for a single line implementation, you can use a lambda expression in a map

map(lambda x:MyModel.objects.get_or_create(name=x), items)

Here, lambda matches each item in items list to x and create a Database record if necessary.

Lambda Documentation

Undefined symbols for architecture i386

Add the framework required for the method used in the project target in the "Link Binaries With Libraries" list of Build Phases, it will work easily. Like I have imported to my project

QuartzCore.framework

For the bug

Undefined symbols for architecture i386:

Java multiline string

A quite efficient and platform independent solution would be using the system property for line separators and the StringBuilder class to build strings:

String separator = System.getProperty("line.separator");
String[] lines = {"Line 1", "Line 2" /*, ... */};

StringBuilder builder = new StringBuilder(lines[0]);
for (int i = 1; i < lines.length(); i++) {
    builder.append(separator).append(lines[i]);
}
String multiLine = builder.toString();

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

Try this:

import cv2
import cv

color_img = cv2.cvtColor(gray_img, cv.CV_GRAY2RGB)

I discovered, while using opencv, that some of the constants are defined in the cv2 module, and other in the cv module.

How do I set specific environment variables when debugging in Visual Studio?

If you can't use bat files to set up your environment, then your only likely option is to set up a system wide environment variable. You can find these by doing

  1. Right click "My Computer"
  2. Select properties
  3. Select the "advanced" tab
  4. Click the "environment variables" button
  5. In the "System variables" section, add the new environment variable that you desire
  6. "Ok" all the way out to accept your changes

I don't know if you'd have to restart visual studio, but seems unlikely. HTH

Convert canvas to PDF

So for today, jspdf-1.5.3. To answer the question of having the pdf file page exactly same as the canvas. After many tries of different combinations, I figured you gotta do something like this. We first need to set the height and width for the output pdf file with correct orientation, otherwise the sides might be cut off. Then we get the dimensions from the 'pdf' file itself, if you tried to use the canvas's dimensions, the sides might be cut off again. I am not sure why that happens, my best guess is the jsPDF convert the dimensions in other units in the library.

  // Download button
  $("#download-image").on('click', function () {
    let width = __CANVAS.width; 
    let height = __CANVAS.height;

    //set the orientation
    if(width > height){
      pdf = new jsPDF('l', 'px', [width, height]);
    }
    else{
      pdf = new jsPDF('p', 'px', [height, width]);
    }
    //then we get the dimensions from the 'pdf' file itself
    width = pdf.internal.pageSize.getWidth();
    height = pdf.internal.pageSize.getHeight();
    pdf.addImage(__CANVAS, 'PNG', 0, 0,width,height);
    pdf.save("download.pdf");
  });

Learnt about switching orientations from here: https://github.com/MrRio/jsPDF/issues/476

Append data to a POST NSURLRequest

The example code above was really helpful to me, however (as has been hinted at above), I think you need to use NSMutableURLRequest rather than NSURLRequest. In its current form, I couldn't get it to respond to the setHTTPMethod call. Changing the type fixed things right up.

Node.js connect only works on localhost

On your app, makes it reachable from any device in the network:

app.listen(3000, "0.0.0.0");

For NodeJS in Azure, GCP & AWS

For Azure vm deployed in resource manager, check your virtual network security group and open ports or port ranges to make it reachable, otherwise in your cloud endpoints if vm is deployed in old version of azure.

Just look for equivalent of it for GCP and AWS

Introducing FOREIGN KEY constraint may cause cycles or multiple cascade paths - why?

I had this issue also, I solved it instantly with this answer from a similar thread

In my case, I didn't want to delete the dependent record on key deletion. If this is the case in your situation just simply change the Boolean value in the migration to false:

AddForeignKey("dbo.Stories", "StatusId", "dbo.Status", "StatusID", cascadeDelete: false);

Chances are, if you are creating relationships which throw this compiler error but DO want to maintain cascade delete; you have an issue with your relationships.

How to resize an image to a specific size in OpenCV?

You can use CvInvoke.Resize for Emgu.CV 3.0

e.g

CvInvoke.Resize(inputImage, outputImage, new System.Drawing.Size(100, 100), 0, 0, Inter.Cubic);

Details are here

Linq Select Group By

var result = priceLog.GroupBy(s => s.LogDateTime.ToString("MMM yyyy")).Select(grp => new PriceLog() { LogDateTime = Convert.ToDateTime(grp.Key), Price = (int)grp.Average(p => p.Price) }).ToList();

I have converted it to int because my Price field was int and Average method return double .I hope this will help

SqlException from Entity Framework - New transaction is not allowed because there are other threads running in the session

As you've already identified, you cannot save from within a foreach that is still drawing from the database via an active reader.

Calling ToList() or ToArray() is fine for small data sets, but when you have thousands of rows, you will be consuming a large amount of memory.

It's better to load the rows in chunks.

public static class EntityFrameworkUtil
{
    public static IEnumerable<T> QueryInChunksOf<T>(this IQueryable<T> queryable, int chunkSize)
    {
        return queryable.QueryChunksOfSize(chunkSize).SelectMany(chunk => chunk);
    }

    public static IEnumerable<T[]> QueryChunksOfSize<T>(this IQueryable<T> queryable, int chunkSize)
    {
        int chunkNumber = 0;
        while (true)
        {
            var query = (chunkNumber == 0)
                ? queryable 
                : queryable.Skip(chunkNumber * chunkSize);
            var chunk = query.Take(chunkSize).ToArray();
            if (chunk.Length == 0)
                yield break;
            yield return chunk;
            chunkNumber++;
        }
    }
}

Given the above extension methods, you can write your query like this:

foreach (var client in clientList.OrderBy(c => c.Id).QueryInChunksOf(100))
{
    // do stuff
    context.SaveChanges();
}

The queryable object you call this method on must be ordered. This is because Entity Framework only supports IQueryable<T>.Skip(int) on ordered queries, which makes sense when you consider that multiple queries for different ranges require the ordering to be stable. If the ordering isn't important to you, just order by primary key as that's likely to have a clustered index.

This version will query the database in batches of 100. Note that SaveChanges() is called for each entity.

If you want to improve your throughput dramatically, you should call SaveChanges() less frequently. Use code like this instead:

foreach (var chunk in clientList.OrderBy(c => c.Id).QueryChunksOfSize(100))
{
    foreach (var client in chunk)
    {
        // do stuff
    }
    context.SaveChanges();
}

This results in 100 times fewer database update calls. Of course each of those calls takes longer to complete, but you still come out way ahead in the end. Your mileage may vary, but this was worlds faster for me.

And it gets around the exception you were seeing.

EDIT I revisited this question after running SQL Profiler and updated a few things to improve performance. For anyone who is interested, here is some sample SQL that shows what is created by the DB.

The first loop doesn't need to skip anything, so is simpler.

SELECT TOP (100)                     -- the chunk size 
[Extent1].[Id] AS [Id], 
[Extent1].[Name] AS [Name], 
FROM [dbo].[Clients] AS [Extent1]
ORDER BY [Extent1].[Id] ASC

Subsequent calls need to skip previous chunks of results, so introduces usage of row_number:

SELECT TOP (100)                     -- the chunk size
[Extent1].[Id] AS [Id], 
[Extent1].[Name] AS [Name], 
FROM (
    SELECT [Extent1].[Id] AS [Id], [Extent1].[Name] AS [Name], row_number()
    OVER (ORDER BY [Extent1].[Id] ASC) AS [row_number]
    FROM [dbo].[Clients] AS [Extent1]
) AS [Extent1]
WHERE [Extent1].[row_number] > 100   -- the number of rows to skip
ORDER BY [Extent1].[Id] ASC

Sorting multiple keys with Unix sort

Here is one to sort various columns in a csv file by numeric and dictionary order, columns 5 and after as dictionary order

~/test>sort -t, -k1,1n -k2,2n -k3,3d -k4,4n -k5d  sort.csv
1,10,b,22,Ga
2,2,b,20,F
2,2,b,22,Ga
2,2,c,19,Ga
2,2,c,19,Gb,hi
2,2,c,19,Gb,hj
2,3,a,9,C

~/test>cat sort.csv
2,3,a,9,C
2,2,b,20,F
2,2,c,19,Gb,hj
2,2,c,19,Gb,hi
2,2,c,19,Ga
2,2,b,22,Ga
1,10,b,22,Ga

Note the -k1,1n means numeric starting at column 1 and ending at column 1. If I had done below, it would have concatenated column 1 and 2 making 1,10 sorted as 110

~/test>sort -t, -k1,2n -k3,3 -k4,4n -k5d  sort.csv
2,2,b,20,F
2,2,b,22,Ga
2,2,c,19,Ga
2,2,c,19,Gb,hi
2,2,c,19,Gb,hj
2,3,a,9,C
1,10,b,22,Ga

Setting device orientation in Swift iOS

I've been struggling all morning to get ONLY landscape left/right supported properly. I discovered something really annoying; although the "General" tab allows you to deselect "Portrait" for device orientation, you have to edit the plist itself to disable Portrait and PortraitUpsideDown INTERFACE orientations - it's the last key in the plist: "Supported Interface Orientations".

The other thing is that it seems you must use the "mask" versions of the enums (e.g., UIInterfaceOrientationMask.LandscapeLeft), not just the orientation one. The code that got it working for me (in my main viewController):

override func shouldAutorotate() -> Bool {
    return true
}

override func supportedInterfaceOrientations() -> Int {
    return Int(UIInterfaceOrientationMask.LandscapeLeft.rawValue) | Int(UIInterfaceOrientationMask.LandscapeRight.rawValue)
}

Making this combination of plist changes and code is the only way I've been able to get it working properly.

Replace contents of factor column in R dataframe

You want to replace the values in a dataset column, but you're getting an error like this:

invalid factor level, NA generated

Try this instead:

levels(dataframe$column)[levels(dataframe$column)=='old_value'] <- 'new_value'

Why does Eclipse complain about @Override on interface methods?

You can also try Retroweaver to create the Java5 version from Java6 classes.