Programs & Examples On #Flashplayer debug

Debug version of Adobe Flash Player - allows to trace and debug a Flash Player application

Converting any object to a byte array in java

What you want to do is called "serialization". There are several ways of doing it, but if you don't need anything fancy I think using the standard Java object serialization would do just fine.

Perhaps you could use something like this?

package com.example;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;

public class Serializer {

    public static byte[] serialize(Object obj) throws IOException {
        try(ByteArrayOutputStream b = new ByteArrayOutputStream()){
            try(ObjectOutputStream o = new ObjectOutputStream(b)){
                o.writeObject(obj);
            }
            return b.toByteArray();
        }
    }

    public static Object deserialize(byte[] bytes) throws IOException, ClassNotFoundException {
        try(ByteArrayInputStream b = new ByteArrayInputStream(bytes)){
            try(ObjectInputStream o = new ObjectInputStream(b)){
                return o.readObject();
            }
        }
    }

}

There are several improvements to this that can be done. Not in the least the fact that you can only read/write one object per byte array, which might or might not be what you want.

Note that "Only objects that support the java.io.Serializable interface can be written to streams" (see java.io.ObjectOutputStream).

Since you might run into it, the continuous allocation and resizing of the java.io.ByteArrayOutputStream might turn out to be quite the bottle neck. Depending on your threading model you might want to consider reusing some of the objects.

For serialization of objects that do not implement the Serializable interface you either need to write your own serializer, for example using the read*/write* methods of java.io.DataOutputStream and the get*/put* methods of java.nio.ByteBuffer perhaps together with reflection, or pull in a third party dependency.

This site has a list and performance comparison of some serialization frameworks. Looking at the APIs it seems Kryo might fit what you need.

libclntsh.so.11.1: cannot open shared object file.

probably you need to sudo into an account registered with relevant env settings :)

How do you set the width of an HTML Helper TextBox in ASP.NET MVC?

Don't use the length parameter as it will not work with all browsers. The best way is to set a style on the input tag.

<input style="width:100px" />

How to get $HOME directory of different user in bash script?

This works in Linux. Not sure how it behaves in other *nixes.

  getent passwd "${OTHER_USER}"|cut -d\: -f 6

jQuery Validate - Enable validation for hidden fields

This is working for me.

jQuery("#form_name").validate().settings.ignore = "";

How to download python from command-line?

Well if you are getting into a linux machine you can use the package manager of that linux distro.

If you are using Ubuntu just use apt-get search python, check the list and do apt-get install python2.7 (not sure if python2.7 or python-2.7, check the list)

You could use yum in fedora and do the same.

if you want to install it on your windows machine i dont know any package manager, i would download the wget for windows, donwload the package from python.org and install it

Retrieve filename from file descriptor in C

You can use readlink on /proc/self/fd/NNN where NNN is the file descriptor. This will give you the name of the file as it was when it was opened — however, if the file was moved or deleted since then, it may no longer be accurate (although Linux can track renames in some cases). To verify, stat the filename given and fstat the fd you have, and make sure st_dev and st_ino are the same.

Of course, not all file descriptors refer to files, and for those you'll see some odd text strings, such as pipe:[1538488]. Since all of the real filenames will be absolute paths, you can determine which these are easily enough. Further, as others have noted, files can have multiple hardlinks pointing to them - this will only report the one it was opened with. If you want to find all names for a given file, you'll just have to traverse the entire filesystem.

executing shell command in background from script

Building off of ngoozeff's answer, if you want to make a command run completely in the background (i.e., if you want to hide its output and prevent it from being killed when you close its Terminal window), you can do this instead:

cmd="google-chrome";
"${cmd}" &>/dev/null & disown;
  • &>/dev/null sets the command’s stdout and stderr to /dev/null instead of inheriting them from the parent process.
  • & makes the shell run the command in the background.
  • disown removes the “current” job, last one stopped or put in the background, from under the shell’s job control.

In some shells you can also use &! instead of & disown; they both have the same effect. Bash doesn’t support &!, though.

Also, when putting a command inside of a variable, it's more proper to use eval "${cmd}" rather than "${cmd}":

cmd="google-chrome";
eval "${cmd}" &>/dev/null & disown;

If you run this command directly in Terminal, it will show the PID of the process which the command starts. But inside of a shell script, no output will be shown.

Here's a function for it:

#!/bin/bash

# Run a command in the background.
_evalBg() {
    eval "$@" &>/dev/null & disown;
}

cmd="google-chrome";
_evalBg "${cmd}";

Also, see: Running bash commands in the background properly

How to move a git repository into another directory and make that directory a git repository?

It's very simple. Git doesn't care about what's the name of its directory. It only cares what's inside. So you can simply do:

# copy the directory into newrepo dir that exists already (else create it)
$ cp -r gitrepo1 newrepo

# remove .git from old repo to delete all history and anything git from it
$ rm -rf gitrepo1/.git

Note that the copy is quite expensive if the repository is large and with a long history. You can avoid it easily too:

# move the directory instead
$ mv gitrepo1 newrepo

# make a copy of the latest version
# Either:
$ mkdir gitrepo1; cp -r newrepo/* gitrepo1/  # doesn't copy .gitignore (and other hidden files)

# Or:
$ git clone --depth 1 newrepo gitrepo1; rm -rf gitrepo1/.git

# Or (look further here: http://stackoverflow.com/q/1209999/912144)
$ git archive --format=tar --remote=<repository URL> HEAD | tar xf -

Once you create newrepo, the destination to put gitrepo1 could be anywhere, even inside newrepo if you want it. It doesn't change the procedure, just the path you are writing gitrepo1 back.

"And" and "Or" troubles within an IF statement

The problem is probably somewhere else. Try this code for example:

Sub test()

  origNum = "006260006"
  creditOrDebit = "D"

  If (origNum = "006260006" Or origNum = "30062600006") And creditOrDebit = "D" Then
    MsgBox "OK"
  End If

End Sub

And you will see that your Or works as expected. Are you sure that your ElseIf statement is executed (it will not be executed if any of the if/elseif before is true)?

How do I run msbuild from the command line using Windows SDK 7.1?

Your bat file could be like:

CD C:\Windows\Microsoft.NET\Framework64\v4.0.30319

msbuild C:\Users\mmaratt\Desktop\BladeTortoise\build\ALL_BUILD.vcxproj

PAUSE

EXIT

Disable color change of anchor tag when visited

You can solve this issue by calling a:link and a:visited selectors together. And follow it with a:hover selector.

a:link, a:visited
{color: gray;}
a:hover
{color: skyblue;}

Take the content of a list and append it to another list

You can also combine two lists (say a,b) using the '+' operator. For example,

a = [1,2,3,4]
b = [4,5,6,7]
c = a + b

Output:
>>> c
[1, 2, 3, 4, 4, 5, 6, 7]

SQL query return data from multiple tables

Part 3 - Tricks and Efficient Code

MySQL in() efficiency

I thought I would add some extra bits, for tips and tricks that have come up.

One question I see come up a fair bit, is How do I get non-matching rows from two tables and I see the answer most commonly accepted as something like the following (based on our cars and brands table - which has Holden listed as a brand, but does not appear in the cars table):

select
    a.ID,
    a.brand
from
    brands a
where
    a.ID not in(select brand from cars)

And yes it will work.

+----+--------+
| ID | brand  |
+----+--------+
|  6 | Holden |
+----+--------+
1 row in set (0.00 sec)

However it is not efficient in some database. Here is a link to a Stack Overflow question asking about it, and here is an excellent in depth article if you want to get into the nitty gritty.

The short answer is, if the optimiser doesn't handle it efficiently, it may be much better to use a query like the following to get non matched rows:

select
    a.brand
from
    brands a
        left join cars b
            on a.id=b.brand
where
    b.brand is null

+--------+
| brand  |
+--------+
| Holden |
+--------+
1 row in set (0.00 sec)

Update Table with same table in subquery

Ahhh, another oldie but goodie - the old You can't specify target table 'brands' for update in FROM clause.

MySQL will not allow you to run an update... query with a subselect on the same table. Now, you might be thinking, why not just slap it into the where clause right? But what if you want to update only the row with the max() date amoung a bunch of other rows? You can't exactly do that in a where clause.

update 
    brands 
set 
    brand='Holden' 
where 
    id=
        (select 
            id 
        from 
            brands 
        where 
            id=6);
ERROR 1093 (HY000): You can't specify target table 'brands' 
for update in FROM clause

So, we can't do that eh? Well, not exactly. There is a sneaky workaround that a surprisingly large number of users don't know about - though it does include some hackery that you will need to pay attention to.

You can stick the subquery within another subquery, which puts enough of a gap between the two queries so that it will work. However, note that it might be safest to stick the query within a transaction - this will prevent any other changes being made to the tables while the query is running.

update 
    brands 
set 
    brand='Holden' 
where id=
    (select 
        id 
    from 
        (select 
            id 
        from 
            brands 
        where 
            id=6
        ) 
    as updateTable);

Query OK, 0 rows affected (0.02 sec)
Rows matched: 1  Changed: 0  Warnings: 0

How do I get the RootViewController from a pushed controller?

I encounter a strange condition.

self.viewControllers.first is not root viewController always.

Generally, self.viewControllers.first is root viewController indeed. But sometimes it's not.

class MyCustomMainNavigationController: UINavigationController {

    function configureForView(_ v: UIViewController, animated: Bool) {
        let root = self.viewControllers.first
        let isRoot = (v == root)
    
        // Update UI based on isRoot
        // ....
    }
}

extension MyCustomMainNavigationController: UINavigationControllerDelegate {
    func navigationController(_ navigationController: UINavigationController, 
        willShow viewController: UIViewController, 
        animated: Bool) {

        self.configureForView(viewController, animated: animated)
    }
}

My issue:

Generally, self.viewControllers.first is root viewController. But, when I call popToRootViewController(animated:), and then it triggers navigationController(_:willShow:animated:). At this moment, self.viewControllers.first is NOT root viewController, it's the last viewController which will disappear.

Summary

  • self.viewControllers.first is not always root viewController. Sometime, it will be the last viewController.

So, I suggest to keep rootViewController by property when self.viewControllers have ONLY one viewController. I get root viewController in viewDidLoad() of custom UINavigationController.

class MyCustomMainNavigationController: UINavigationController {
    fileprivate var myRoot: UIViewController!
    override func viewDidLoad() {

        super.viewDidLoad()

        // My UINavigationController is defined in storyboard. 
        // So at this moment, 
        // I can get root viewController by `self.topViewController!`
        let v = self.topViewController!
        self.myRoot = v
    }

}

Enviroments:

  • iPhone 7 with iOS 14.0.1
  • Xcode 12.0.1 (12A7300)

Laravel stylesheets and javascript don't load for non-base routes

Laravel 5.4 with mix helper:

<link href="{{ mix('/css/app.css') }}" rel="stylesheet">
<script src="{{ mix('/js/app.js') }}"> </script>

How does one remove a Docker image?

Here's a shell script to remove a tagged (named) image and it's containers. Save as docker-rmi and run using 'docker-rmi my-image-name'

#!/bin/bash

IMAGE=$1

if [ "$IMAGE" == "" ] ; then
  echo "Missing image argument"
  exit 2
fi

docker ps -qa -f "ancestor=$IMAGE" | xargs docker rm
docker rmi $IMAGE

Where is debug.keystore in Android Studio

The easiest thing I can think of is to grab the fingerprint from the debug.keystore (paths are mentioned in other answers) and add that to your project. No need to copy keystores or add new apps. Just append to the list of fingerprints for each machine you develop on.

FWIW, I ran into this when I switched from one laptop to another. I bounce around a lot.

https://support.google.com/firebase/answer/7000104?hl=en#sha1

Hope that helps some folks out! :)

Long press on UITableView

Here are clarified instruction combining Dawn Song's answer and Marmor's answer.

Drag a long Press Gesture Recognizer and drop it into your Table Cell. It will jump to the bottom of the list on the left.

enter image description here

Then connect the gesture recognizer the same way you would connect a button. enter image description here

Add the code from Marmor in the the action handler

- (IBAction)handleLongPress:(UILongPressGestureRecognizer *)sender {
if (sender.state == UIGestureRecognizerStateBegan) {

    CGPoint p = [sender locationInView:self.tableView];

    NSIndexPath *indexPath = [self.tableView indexPathForRowAtPoint:p];
    if (indexPath == nil) {
        NSLog(@"long press on table view but not on a row");
    } else {
        UITableViewCell *cell = [self.tableView cellForRowAtIndexPath:indexPath];
        if (cell.isHighlighted) {
            NSLog(@"long press on table view at section %d row %d", indexPath.section, indexPath.row);
        }
    }
}

}

How to convert JSON string to array

Use json_decode($json_string, TRUE) function to convert the JSON object to an array.

Example:

$json_string   = '{"a":1,"b":2,"c":3,"d":4,"e":5}';

$my_array_data = json_decode($json_string, TRUE);

NOTE: The second parameter will convert decoded JSON string into an associative array.

===========

Output:

var_dump($my_array_data);

array(5) {

    ["a"] => int(1)
    ["b"] => int(2)
    ["c"] => int(3)
    ["d"] => int(4)
    ["e"] => int(5)
}

How do I put two increment statements in a C++ 'for' loop?

Try not to do it!

From http://www.research.att.com/~bs/JSF-AV-rules.pdf:

AV Rule 199
The increment expression in a for loop will perform no action other than to change a single loop parameter to the next value for the loop.

Rationale: Readability.

How to parse XML in Bash?

Command-line tools that can be called from shell scripts include:

  • 4xpath - command-line wrapper around Python's 4Suite package

  • XMLStarlet

  • xpath - command-line wrapper around Perl's XPath library

    sudo apt-get install libxml-xpath-perl
    
  • Xidel - Works with URLs as well as files. Also works with JSON

I also use xmllint and xsltproc with little XSL transform scripts to do XML processing from the command line or in shell scripts.

What difference is there between WebClient and HTTPWebRequest classes in .NET?

WebClient is a higher-level abstraction built on top of HttpWebRequest to simplify the most common tasks. For instance, if you want to get the content out of an HttpWebResponse, you have to read from the response stream:

var http = (HttpWebRequest)WebRequest.Create("http://example.com");
var response = http.GetResponse();

var stream = response.GetResponseStream();
var sr = new StreamReader(stream);
var content = sr.ReadToEnd();

With WebClient, you just do DownloadString:

var client = new WebClient();
var content = client.DownloadString("http://example.com");

Note: I left out the using statements from both examples for brevity. You should definitely take care to dispose your web request objects properly.

In general, WebClient is good for quick and dirty simple requests and HttpWebRequest is good for when you need more control over the entire request.

How to get previous month and year relative to today, using strtotime and date?

If you want the previous year and month relative to a specific date and have DateTime available then you can do this:

$d = new DateTime('2013-01-01', new DateTimeZone('UTC')); 
$d->modify('first day of previous month');
$year = $d->format('Y'); //2012
$month = $d->format('m'); //12

Directory-tree listing in Python

Try this:

import os
for top, dirs, files in os.walk('./'):
    for nm in files:       
        print os.path.join(top, nm)

Insert images to XML file

I always convert the byte data to a Base64 encoding and then insert the image.

This is also the way that Word does it, for it's XML files (not that Word is a good example on how to work with XML :P).

Generate PDF from Swagger API documentation

You can modify your REST project, so as to produce the needed static documents (html, pdf etc) upon building the project.

If you have a Java Maven project you can use the pom snippet below. It uses a series of plugins to generate a pdf and an html documentation (of the project's REST resources).

  1. rest-api -> swagger.json : swagger-maven-plugin
  2. swagger.json -> Asciidoc : swagger2markup-maven-plugin
  3. Asciidoc -> PDF : asciidoctor-maven-plugin

Please be aware that the order of execution matters, since the output of one plugin, becomes the input to the next:

<plugin>
    <groupId>com.github.kongchen</groupId>
    <artifactId>swagger-maven-plugin</artifactId>
    <version>3.1.3</version>
    <configuration>
        <apiSources>
            <apiSource>
                <springmvc>false</springmvc>
                <locations>some.package</locations>
                <basePath>/api</basePath>
                <info>
                    <title>Put your REST service's name here</title>
                    <description>Add some description</description>
                    <version>v1</version>
                </info>
                <swaggerDirectory>${project.build.directory}/api</swaggerDirectory>
                <attachSwaggerArtifact>true</attachSwaggerArtifact>
            </apiSource>
        </apiSources>
    </configuration>
    <executions>
        <execution>
            <phase>${phase.generate-documentation}</phase>
            <!-- fx process-classes phase -->
            <goals>
                <goal>generate</goal>
            </goals>
        </execution>
    </executions>
</plugin>
<plugin>
    <groupId>io.github.robwin</groupId>
    <artifactId>swagger2markup-maven-plugin</artifactId>
    <version>0.9.3</version>
    <configuration>
        <inputDirectory>${project.build.directory}/api</inputDirectory>
        <outputDirectory>${generated.asciidoc.directory}</outputDirectory>
        <!-- specify location to place asciidoc files -->
        <markupLanguage>asciidoc</markupLanguage>
    </configuration>
    <executions>
        <execution>
            <phase>${phase.generate-documentation}</phase>
            <goals>
                <goal>process-swagger</goal>
            </goals>
        </execution>
    </executions>
</plugin>
<plugin>
    <groupId>org.asciidoctor</groupId>
    <artifactId>asciidoctor-maven-plugin</artifactId>
    <version>1.5.3</version>
    <dependencies>
        <dependency>
            <groupId>org.asciidoctor</groupId>
            <artifactId>asciidoctorj-pdf</artifactId>
            <version>1.5.0-alpha.11</version>
        </dependency>
        <dependency>
            <groupId>org.jruby</groupId>
            <artifactId>jruby-complete</artifactId>
            <version>1.7.21</version>
        </dependency>
    </dependencies>
    <configuration>
        <sourceDirectory>${asciidoctor.input.directory}</sourceDirectory>
        <!-- You will need to create an .adoc file. This is the input to this plugin -->
        <sourceDocumentName>swagger.adoc</sourceDocumentName>
        <attributes>
            <doctype>book</doctype>
            <toc>left</toc>
            <toclevels>2</toclevels>
            <generated>${generated.asciidoc.directory}</generated>
            <!-- this path is referenced in swagger.adoc file. The given file will simply 
                point to the previously create adoc files/assemble them. -->
        </attributes>
    </configuration>
    <executions>
        <execution>
            <id>asciidoc-to-html</id>
            <phase>${phase.generate-documentation}</phase>
            <goals>
                <goal>process-asciidoc</goal>
            </goals>
            <configuration>
                <backend>html5</backend>
                <outputDirectory>${generated.html.directory}</outputDirectory>
                <!-- specify location to place html file -->
            </configuration>
        </execution>
        <execution>
            <id>asciidoc-to-pdf</id>
            <phase>${phase.generate-documentation}</phase>
            <goals>
                <goal>process-asciidoc</goal>
            </goals>
            <configuration>
                <backend>pdf</backend>
                <outputDirectory>${generated.pdf.directory}</outputDirectory>
                <!-- specify location to place pdf file -->
            </configuration>
        </execution>
    </executions>
</plugin>

The asciidoctor plugin assumes the existence of an .adoc file to work on. You can create one that simply collects the ones that were created by the swagger2markup plugin:

include::{generated}/overview.adoc[]
include::{generated}/paths.adoc[]
include::{generated}/definitions.adoc[]

If you want your generated html document to become part of your war file you have to make sure that it is present on the top level - static files in the WEB-INF folder will not be served. You can do this in the maven-war-plugin:

<plugin>
    <artifactId>maven-war-plugin</artifactId>
    <configuration>
        <warSourceDirectory>WebContent</warSourceDirectory>
        <failOnMissingWebXml>false</failOnMissingWebXml>
        <webResources>
            <resource>
                <directory>${generated.html.directory}</directory>
            <!-- Add swagger.pdf to WAR file, so as to make it available as static content. -->
            </resource>
            <resource>
                <directory>${generated.pdf.directory}</directory>
            <!-- Add swagger.html to WAR file, so as to make it available as static content. -->
            </resource>
        </webResources>
    </configuration>
</plugin>

The war plugin works on the generated documentation - as such, you must make sure that those plugins have been executed in an earlier phase.

Serializing enums with Jackson

Finally I found solution myself.

I had to annotate enum with @JsonSerialize(using = OrderTypeSerializer.class) and implement custom serializer:

public class OrderTypeSerializer extends JsonSerializer<OrderType> {

  @Override
  public void serialize(OrderType value, JsonGenerator generator,
            SerializerProvider provider) throws IOException,
            JsonProcessingException {

    generator.writeStartObject();
    generator.writeFieldName("id");
    generator.writeNumber(value.getId());
    generator.writeFieldName("name");
    generator.writeString(value.getName());
    generator.writeEndObject();
  }
}

document.getElementByID is not a function

It's getElementById()

Note the lower-case d in Id.

How to find MAC address of an Android device programmatically

Recent update from Developer.Android.com

Don't work with MAC addresses MAC addresses are globally unique, not user-resettable, and survive factory resets. For these reasons, it's generally not recommended to use MAC address for any form of user identification. Devices running Android 10 (API level 29) and higher report randomized MAC addresses to all apps that aren't device owner apps.

Between Android 6.0 (API level 23) and Android 9 (API level 28), local device MAC addresses, such as Wi-Fi and Bluetooth, aren't available via third-party APIs. The WifiInfo.getMacAddress() method and the BluetoothAdapter.getDefaultAdapter().getAddress() method both return 02:00:00:00:00:00.

Additionally, between Android 6.0 and Android 9, you must hold the following permissions to access MAC addresses of nearby external devices available via Bluetooth and Wi-Fi scans:

Method/Property Permissions Required

ACCESS_FINE_LOCATION or ACCESS_COARSE_LOCATION

Source: https://developer.android.com/training/articles/user-data-ids.html#version_specific_details_identifiers_in_m

Which data type for latitude and longitude?

In PostGIS Geometry is preferred over Geography (round earth model) because the computations are much simpler therefore faster. It also has MANY more available functions but is less accurate over very long distances.

Import your CSV long and lat fields to DECIMAL(10,6) columns. 6 digits is 10cm precision, should be plenty for most use cases. Then cast your imported data to the correct SRID

The wrong way!

/* try what seems the obvious solution */
DROP TABLE IF EXISTS public.test_geom_bad;
-- Big Ben, London
SELECT ST_SetSRID(ST_MakePoint(-0.116773, 51.510357),4326) AS geom
INTO public.test_geom_bad;

The CORRECT way

/* add the necessary CAST to make it work */
DROP TABLE IF EXISTS public.test_geom_correct;
SELECT ST_SetSRID(ST_MakePoint(-0.116773, 51.510357),4326)::geometry(Geometry, 4326) AS geom
INTO public.test_geom_correct;

Verify SRID is not zero!

/* now observe the incorrect SRID 0 */
SELECT * FROM public.geometry_columns
WHERE f_table_name IN ('test_geom_bad','test_geom_correct');

Validate the order of your long lat parameter using a WKT viewer and

SELECT ST_AsEWKT(geom) FROM public.test_geom_correct

Then index it for best performance

CREATE INDEX idx_target_table_geom_gist
    ON target_table USING gist(geom);

How to clone an InputStream?

UPD. Check the comment before. It isn't exactly what was asked.

If you are using apache.commons you may copy streams using IOUtils .

You can use following code:

InputStream = IOUtils.toBufferedInputStream(toCopy);

Here is the full example suitable for your situation:

public void cloneStream() throws IOException{
    InputStream toCopy=IOUtils.toInputStream("aaa");
    InputStream dest= null;
    dest=IOUtils.toBufferedInputStream(toCopy);
    toCopy.close();
    String result = new String(IOUtils.toByteArray(dest));
    System.out.println(result);
}

This code requires some dependencies:

MAVEN

<dependency>
    <groupId>commons-io</groupId>
    <artifactId>commons-io</artifactId>
    <version>2.4</version>
</dependency>

GRADLE

'commons-io:commons-io:2.4'

Here is the DOC reference for this method:

Fetches entire contents of an InputStream and represent same data as result InputStream. This method is useful where,

Source InputStream is slow. It has network resources associated, so we cannot keep it open for long time. It has network timeout associated.

You can find more about IOUtils here: http://commons.apache.org/proper/commons-io/javadocs/api-2.4/org/apache/commons/io/IOUtils.html#toBufferedInputStream(java.io.InputStream)

Browser back button handling

Warn/confirm User if Back button is Pressed is as below.

window.onbeforeunload = function() { return "Your work will be lost."; };

You can get more information using below mentioned links.

Disable Back Button in Browser using JavaScript

I hope this will help to you.

Div Background Image Z-Index Issue

To solve the issue, you are using the z-index on the footer and header, but you forgot about the position, if a z-index is to be used, the element must have a position:

Add to your footer and header this CSS:

position: relative; 

EDITED:

Also noticed that the background image on the #backstretch has a negative z-index, don't use that, some browsers get really weird...

Remove From the #backstretch:

z-index: -999999;

Read a little bit about Z-Index here!

LaTeX table positioning

You may want to add this to your preamble, and adjust the values as necessary:

 %------------begin Float Adjustment
%two column float page must be 90% full
\renewcommand\dblfloatpagefraction{.90}
%two column top float can cover up to 80% of page
\renewcommand\dbltopfraction{.80}
%float page must be 90% full
\renewcommand\floatpagefraction{.90}
%top float can cover up to 80% of page
\renewcommand\topfraction{.80}
%bottom float can cover up to 80% of page
\renewcommand\bottomfraction{.80}
%at least 10% of a normal page must contain text
\renewcommand\textfraction{.1}
%separation between floats and text
\setlength\dbltextfloatsep{9pt plus 5pt minus 3pt }
%separation between two column floats and text
\setlength\textfloatsep{4pt plus 2pt minus 1.5pt}

Particularly, the \floatpagefraction may be of interest.

Using subprocess to run Python script on Windows

Yes subprocess.Popen(cmd, ..., shell=True) works like a charm. On Windows the .py file extension is recognized, so Python is invoked to process it (on *NIX just the usual shebang). The path environment controls whether things are seen. So the first arg to Popen is just the name of the script.

subprocess.Popen(['myscript.py', 'arg1', ...], ..., shell=True)

Hide Twitter Bootstrap nav collapse on click

I just replicate the 2 attributes of the btn-navbar (data-toggle="collapse" data-target=".nav-collapse.in") on each link like this:

<div class="nav-collapse">
  <ul class="nav" >
    <li class="active"><a href="#home" data-toggle="collapse" data-target=".nav-collapse.in">Home</a></li>
    <li><a href="#about" data-toggle="collapse" data-target=".nav-collapse.in">About</a></li>
    <li><a href="#portfolio" data-toggle="collapse" data-target=".nav-collapse.in">Portfolio</a></li>
    <li><a href="#services" data-toggle="collapse" data-target=".nav-collapse.in">Services</a></li>
    <li><a href="#contact" data-toggle="collapse" data-target=".nav-collapse.in">Contact</a></li>
  </ul>
</div>

In the Bootstrap 4 Navbar, in has changed to show so the syntax would be:

data-toggle="collapse" data-target=".navbar-collapse.show"

Can't bind to 'ngModel' since it isn't a known property of 'input'

Import the FormsModule in those modules where you want to use the [(ngModel)]

enter image description here

Android Service Stops When App Is Closed

try this, it will keep the service running in the background.

BackServices.class

public class BackServices extends Service{

    @Override
    public IBinder onBind(Intent arg0) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
   public int onStartCommand(Intent intent, int flags, int startId) {
      // Let it continue running until it is stopped.
      Toast.makeText(this, "Service Started", Toast.LENGTH_LONG).show();
      return START_STICKY;
   }
   @Override
   public void onDestroy() {
      super.onDestroy();
      Toast.makeText(this, "Service Destroyed", Toast.LENGTH_LONG).show();
   }
}

in your MainActivity onCreate drop this line of code

startService(new Intent(getBaseContext(), BackServices.class));

Now the service will stay running in background.

How to run Tensorflow on CPU

For me, only setting CUDA_VISIBLE_DEVICES to precisely -1 works:

Works:

import os
import tensorflow as tf

os.environ['CUDA_VISIBLE_DEVICES'] = '-1'

if tf.test.gpu_device_name():
    print('GPU found')
else:
    print("No GPU found")

# No GPU found

Does not work:

import os
import tensorflow as tf

os.environ['CUDA_VISIBLE_DEVICES'] = ''    

if tf.test.gpu_device_name():
    print('GPU found')
else:
    print("No GPU found")

# GPU found

When do I use path params vs. query params in a RESTful API?

The fundamental way to think about this subject is as follows:

A URI is a resource identifier that uniquely identifies a specific instance of a resource TYPE. Like everything else in life, every object (which is an instance of some type), have set of attributes that are either time-invariant or temporal.

In the example above, a car is a very tangible object that has attributes like make, model and VIN - that never changes, and color, suspension etc. that may change over time. So if we encode the URI with attributes that may change over time (temporal), we may end up with multiple URIs for the same object:

GET /cars/honda/civic/coupe/{vin}/{color=red}

And years later, if the color of this very same car is changed to black:

GET /cars/honda/civic/coupe/{vin}/{color=black}

Note that the car instance itself (the object) has not changed - it's just the color that changed. Having multiple URIs pointing to the same object instance will force you to create multiple URI handlers - this is not an efficient design, and is of course not intuitive.

Therefore, the URI should only consist of parts that will never change and will continue to uniquely identify that resource throughout its lifetime. Everything that may change should be reserved for query parameters, as such:

GET /cars/honda/civic/coupe/{vin}?color={black}

Bottom line - think polymorphism.

How to get WordPress post featured image URL

// Try it inside loop.  
<?php
$feat_image = wp_get_attachment_url( get_post_thumbnail_id($post->ID) );
echo $feat_image;
?>

How do I load a file into the python console?

For Python 2 give execfile a try. (See other answers for Python 3)

execfile('file.py')

Example usage:
Let's use "copy con" to quickly create a small script file...

C:\junk>copy con execfile_example.py
a = [9, 42, 888]
b = len(a)
^Z
        1 file(s) copied.

...and then let's load this script like so:

C:\junk>\python27\python
Python 2.7.1 (r271:86832, Nov 27 2010, 18:30:46) [MSC v.1500 32 bit (Intel)] on win32
Type "help", "copyright", "credits" or "license" for more information.
>>> execfile('execfile_example.py')
>>> a
[9, 42, 888]
>>> b
3
>>>

Does Python have “private” variables in classes?

There is a variation of private variables in the underscore convention.

In [5]: class Test(object):
   ...:     def __private_method(self):
   ...:         return "Boo"
   ...:     def public_method(self):
   ...:         return self.__private_method()
   ...:     

In [6]: x = Test()

In [7]: x.public_method()
Out[7]: 'Boo'

In [8]: x.__private_method()
---------------------------------------------------------------------------
AttributeError                            Traceback (most recent call last)
<ipython-input-8-fa17ce05d8bc> in <module>()
----> 1 x.__private_method()

AttributeError: 'Test' object has no attribute '__private_method'

There are some subtle differences, but for the sake of programming pattern ideological purity, its good enough.

There are examples out there of @private decorators that more closely implement the concept, but YMMV. Arguably one could also write a class defintion that uses meta

Invalid date in safari

I use moment to solve the problem. For example

var startDate = moment('2015-07-06 08:00', 'YYYY-MM-DD HH:mm').toDate();

How can I account for period (AM/PM) using strftime?

>>> from datetime import datetime
>>> print(datetime.today().strftime("%H:%M %p"))
15:31 AM

Try replacing %I with %H.

Display Last Saved Date on worksheet

You can also simple add the following into the Header or Footer of the Worksheet

Last Saved: &[Date] &[Time]

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

How do I declare class-level properties in Objective-C?

As of Xcode 8 Objective-C now supports class properties:

@interface MyClass : NSObject
@property (class, nonatomic, assign, readonly) NSUUID* identifier;
@end

Since class properties are never synthesised you need to write your own implementation.

@implementation MyClass
static NSUUID*_identifier = nil;

+ (NSUUID *)identifier {
  if (_identifier == nil) {
    _identifier = [[NSUUID alloc] init];
  }
  return _identifier;
}
@end

You access the class properties using normal dot syntax on the class name:

MyClass.identifier;

How to write dynamic variable in Ansible playbook

my_var: the variable declared

VAR: the variable, whose value is to be checked

param_1, param_2: values of the variable VAR

value_1, value_2, value_3: the values to be assigned to my_var according to the values of my_var

my_var: "{{ 'value_1' if VAR == 'param_1' else 'value_2' if VAR == 'param_2' else 'value_3' }}"

How to get all table names from a database?

In newer versions of MySQL connectors the default tables are also listed if catalog is not passed

        DatabaseMetaData dbMeta = con.getMetaData();
        //con.getCatalog() returns database name
        ResultSet rs = dbMeta.getTables(con.getCatalog(), "", null, new String[]{"TABLE"});
        ArrayList<String> tables = new ArrayList<String>();
        while(rs.next()){
            String tableName = rs.getString("TABLE_NAME");
            tables.add(tableName);
        }
        return tables;

Reading a huge .csv file

I do a fair amount of vibration analysis and look at large data sets (tens and hundreds of millions of points). My testing showed the pandas.read_csv() function to be 20 times faster than numpy.genfromtxt(). And the genfromtxt() function is 3 times faster than the numpy.loadtxt(). It seems that you need pandas for large data sets.

I posted the code and data sets I used in this testing on a blog discussing MATLAB vs Python for vibration analysis.

How to remove duplicate white spaces in string using Java?

Like this:

yourString = yourString.replaceAll("\\s+", " ");

For example

System.out.println("lorem  ipsum   dolor \n sit.".replaceAll("\\s+", " "));

outputs

lorem ipsum dolor sit.

What does that \s+ mean?

\s+ is a regular expression. \s matches a space, tab, new line, carriage return, form feed or vertical tab, and + says "one or more of those". Thus the above code will collapse all "whitespace substrings" longer than one character, with a single space character.


Source: Java: Removing duplicate white spaces in strings

Angular 2 change event - model changes

That's a known issue. Currently you have to use a workaround like shown in your question.

This is working as intended. When the change event is emitted ngModelChange (the (...) part of [(ngModel)] hasn't updated the bound model yet:

<input type="checkbox"  (ngModelChange)="myModel=$event" [ngModel]="mymodel">

See also

Kill Attached Screen in Linux

screen -X -S SCREENID kill

alternatively, you can use the following command

screen -S SCREENNAME -p 0 -X quit

You can view the list of the screen sessions by executing screen -ls

Remove all stylings (border, glow) from textarea

The glow effect is most-likely controlled by box-shadow. In addition to adding what Pavel said, you can add the box-shadow property for the different browser engines.

textarea {
    border: none;
    overflow: auto;
    outline: none;

    -webkit-box-shadow: none;
    -moz-box-shadow: none;
    box-shadow: none;

    resize: none; /*remove the resize handle on the bottom right*/
}

You may also try adding !important to prioritize this CSS.

Creating a div element inside a div element in javascript

Your code works well you just mistyped this line of code:

document.getElementbyId('lc').appendChild(element);

change it with this: (The "B" should be capitalized.)

document.getElementById('lc').appendChild(element);  

HERE IS MY EXAMPLE:

_x000D_
_x000D_
<html>_x000D_
<head>_x000D_
_x000D_
<script>_x000D_
_x000D_
function test() {_x000D_
_x000D_
    var element = document.createElement("div");_x000D_
    element.appendChild(document.createTextNode('The man who mistook his wife for a hat'));_x000D_
    document.getElementById('lc').appendChild(element);_x000D_
_x000D_
}_x000D_
_x000D_
</script>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<input id="filter" type="text" placeholder="Enter your filter text here.." onkeyup = "test()" />_x000D_
_x000D_
<div id="lc" style="background: blue; height: 150px; width: 150px;_x000D_
}" onclick="test();">  _x000D_
</div>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

WCF ServiceHost access rights

please open your Visual Studio in Administration Mode then try it.

What is difference between sjlj vs dwarf vs seh?

There's a short overview at MinGW-w64 Wiki:

Why doesn't mingw-w64 gcc support Dwarf-2 Exception Handling?

The Dwarf-2 EH implementation for Windows is not designed at all to work under 64-bit Windows applications. In win32 mode, the exception unwind handler cannot propagate through non-dw2 aware code, this means that any exception going through any non-dw2 aware "foreign frames" code will fail, including Windows system DLLs and DLLs built with Visual Studio. Dwarf-2 unwinding code in gcc inspects the x86 unwinding assembly and is unable to proceed without other dwarf-2 unwind information.

The SetJump LongJump method of exception handling works for most cases on both win32 and win64, except for general protection faults. Structured exception handling support in gcc is being developed to overcome the weaknesses of dw2 and sjlj. On win64, the unwind-information are placed in xdata-section and there is the .pdata (function descriptor table) instead of the stack. For win32, the chain of handlers are on stack and need to be saved/restored by real executed code.

GCC GNU about Exception Handling:

GCC supports two methods for exception handling (EH):

  • DWARF-2 (DW2) EH, which requires the use of DWARF-2 (or DWARF-3) debugging information. DW-2 EH can cause executables to be slightly bloated because large call stack unwinding tables have to be included in th executables.
  • A method based on setjmp/longjmp (SJLJ). SJLJ-based EH is much slower than DW2 EH (penalising even normal execution when no exceptions are thrown), but can work across code that has not been compiled with GCC or that does not have call-stack unwinding information.

[...]

Structured Exception Handling (SEH)

Windows uses its own exception handling mechanism known as Structured Exception Handling (SEH). [...] Unfortunately, GCC does not support SEH yet. [...]

See also:

How to add a color overlay to a background image?

Try this, it's simple and clear. I have found it from here : https://css-tricks.com/tinted-images-multiple-backgrounds/

.tinted-image {

  width: 300px;
  height: 200px;

  background: 
    /* top, transparent red */ 
    linear-gradient(
      rgba(255, 0, 0, 0.45), 
      rgba(255, 0, 0, 0.45)
    ),
    /* bottom, image */
    url(https://s3-us-west-2.amazonaws.com/s.cdpn.io/3/owl1.jpg);
}

How to properly validate input values with React.JS?

Your jsfiddle does not work anymore. I've fixed it: http://jsfiddle.net/tkrotoff/bgC6E/40/ using React 16 and ES6 classes.

class Adaptive_Input extends React.Component {
  handle_change(e) {
    var new_text = e.currentTarget.value;
    this.props.on_Input_Change(new_text);
  }

  render() {
    return (
      <div className="adaptive_placeholder_input_container">
        <input
          className="adaptive_input"
          type="text"
          required="required"
          onChange={this.handle_change.bind(this)} />
        <label
          className="adaptive_placeholder"
          alt={this.props.initial}
          placeholder={this.props.focused} />
      </div>
    );
  }
}

class Form extends React.Component {
  render() {
    return (
      <form>
        <Adaptive_Input
          initial={'Name Input'}
          focused={'Name Input'}
          on_Input_Change={this.props.handle_text_input} />

        <Adaptive_Input
          initial={'Value 1'}
          focused={'Value 1'}
          on_Input_Change={this.props.handle_value_1_input} />

        <Adaptive_Input
          initial={'Value 2'}
          focused={'Value 2'}
          on_Input_Change={this.props.handle_value_2_input} />
      </form>
    );
  }
}

class Page extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      Name: 'No Name',
      Value_1: '0',
      Value_2: '0',
      Display_Value: '0'
    };
  }

  handle_text_input(new_text) {
    this.setState({
      Name: new_text
    });
  }

  handle_value_1_input(new_value) {
    new_value = parseInt(new_value);
    var updated_display = new_value + parseInt(this.state.Value_2);
    updated_display = updated_display.toString();
    this.setState({
      Value_1: new_value,
      Display_Value: updated_display
    });
  }

  handle_value_2_input(new_value) {
    new_value = parseInt(new_value);
    var updated_display = parseInt(this.state.Value_1) + new_value;
    updated_display = updated_display.toString();
    this.setState({
      Value_2: new_value,
      Display_Value: updated_display
    });
  }

  render() {
    return(
      <div>
        <h2>{this.state.Name}</h2>
        <h2>Value 1 + Value 2 = {this.state.Display_Value}</h2>
        <Form
          handle_text_input={this.handle_text_input.bind(this)}
          handle_value_1_input={this.handle_value_1_input.bind(this)}
          handle_value_2_input={this.handle_value_2_input.bind(this)}
        />
      </div>
    );
  }
}

ReactDOM.render(<Page />, document.getElementById('app'));

And now the same code hacked with form validation thanks to this library: https://github.com/tkrotoff/react-form-with-constraints => http://jsfiddle.net/tkrotoff/k4qa4heg/

http://jsfiddle.net/tkrotoff/k4qa4heg/

const { FormWithConstraints, FieldFeedbacks, FieldFeedback } = ReactFormWithConstraints;

class Adaptive_Input extends React.Component {
  static contextTypes = {
    form: PropTypes.object.isRequired
  };

  constructor(props) {
    super(props);

    this.state = {
      field: undefined
    };

    this.fieldWillValidate = this.fieldWillValidate.bind(this);
    this.fieldDidValidate = this.fieldDidValidate.bind(this);
  }

  componentWillMount() {
    this.context.form.addFieldWillValidateEventListener(this.fieldWillValidate);
    this.context.form.addFieldDidValidateEventListener(this.fieldDidValidate);
  }

  componentWillUnmount() {
    this.context.form.removeFieldWillValidateEventListener(this.fieldWillValidate);
    this.context.form.removeFieldDidValidateEventListener(this.fieldDidValidate);
  }

  fieldWillValidate(fieldName) {
    if (fieldName === this.props.name) this.setState({field: undefined});
  }

  fieldDidValidate(field) {
    if (field.name === this.props.name) this.setState({field});
  }

  handle_change(e) {
    var new_text = e.currentTarget.value;
    this.props.on_Input_Change(e, new_text);
  }

  render() {
    const { field } = this.state;
    let className = 'adaptive_placeholder_input_container';
    if (field !== undefined) {
      if (field.hasErrors()) className += ' error';
      if (field.hasWarnings()) className += ' warning';
    }

    return (
      <div className={className}>
        <input
          type={this.props.type}
          name={this.props.name}
          className="adaptive_input"
          required
          onChange={this.handle_change.bind(this)} />
        <label
          className="adaptive_placeholder"
          alt={this.props.initial}
          placeholder={this.props.focused} />
      </div>
    );
  }
}

class Form extends React.Component {
  constructor(props) {
    super(props);

    this.state = {
      Name: 'No Name',
      Value_1: '0',
      Value_2: '0',
      Display_Value: '0'
    };
  }

  handle_text_input(e, new_text) {
    this.form.validateFields(e.currentTarget);

    this.setState({
      Name: new_text
    });
  }

  handle_value_1_input(e, new_value) {
    this.form.validateFields(e.currentTarget);

    if (this.form.isValid()) {
      new_value = parseInt(new_value);
      var updated_display = new_value + parseInt(this.state.Value_2);
      updated_display = updated_display.toString();
      this.setState({
        Value_1: new_value,
        Display_Value: updated_display
      });
    }
    else {
      this.setState({
        Display_Value: 'Error'
      });
    }
  }

  handle_value_2_input(e, new_value) {
    this.form.validateFields(e.currentTarget);

    if (this.form.isValid()) {
      new_value = parseInt(new_value);
      var updated_display = parseInt(this.state.Value_1) + new_value;
      updated_display = updated_display.toString();
      this.setState({
        Value_2: new_value,
        Display_Value: updated_display
      });
    }
    else {
      this.setState({
        Display_Value: 'Error'
      });
    }
  }

  render() {
    return(
      <div>
        <h2>Name: {this.state.Name}</h2>
        <h2>Value 1 + Value 2 = {this.state.Display_Value}</h2>

        <FormWithConstraints ref={form => this.form = form} noValidate>
          <Adaptive_Input
            type="text"
            name="name_input"
            initial={'Name Input'}
            focused={'Name Input'}
            on_Input_Change={this.handle_text_input.bind(this)} />
          <FieldFeedbacks for="name_input">
            <FieldFeedback when="*" error />
            <FieldFeedback when={value => !/^\w+$/.test(value)} warning>Should only contain alphanumeric characters</FieldFeedback>
          </FieldFeedbacks>

          <Adaptive_Input
            type="number"
            name="value_1_input"
            initial={'Value 1'}
            focused={'Value 1'}
            on_Input_Change={this.handle_value_1_input.bind(this)} />
          <FieldFeedbacks for="value_1_input">
            <FieldFeedback when="*" />
          </FieldFeedbacks>

          <Adaptive_Input
            type="number"
            name="value_2_input"
            initial={'Value 2'}
            focused={'Value 2'}
            on_Input_Change={this.handle_value_2_input.bind(this)} />
          <FieldFeedbacks for="value_2_input">
            <FieldFeedback when="*" />
          </FieldFeedbacks>
        </FormWithConstraints>
      </div>
    );
  }
}

ReactDOM.render(<Form />, document.getElementById('app'));

The proposed solution here is hackish as I've tried to keep it close to the original jsfiddle. For proper form validation with react-form-with-constraints, check https://github.com/tkrotoff/react-form-with-constraints#examples

How to Delete Session Cookie?

This needs to be done on the server-side, where the cookie was issued.

Uncaught TypeError: (intermediate value)(...) is not a function

I have faced this issue when I created a new ES2015 class where the property name was equal to the method name.

e.g.:

class Test{
  constructor () {
    this.test = 'test'
  }

  test (test) {
    this.test = test
  }
}

let t = new Test()
t.test('new Test')

Please note this implementation was in NodeJS 6.10.

As a workaround (if you do not want to use the boring 'setTest' method name), you could use a prefix for your 'private' properties (like _test).

Open your Developer Tools in jsfiddle.

Mongoose, update values in array of objects

In mongoose we can update, like simple array

user.updateInfoByIndex(0,"test")

User.methods.updateInfoByIndex = function(index, info) ={
    this.arrayField[index]=info
    this.save()
}

How do pointer-to-pointer's work in C? (and when might you use them?)

I like this "real world" code example of pointer to pointer usage, in Git 2.0, commit 7b1004b:

Linus once said:

I actually wish more people understood the really core low-level kind of coding. Not big, complex stuff like the lockless name lookup, but simply good use of pointers-to-pointers etc.
For example, I've seen too many people who delete a singly-linked list entry by keeping track of the "prev" entry, and then to delete the entry, doing something like:


   if (prev)
     prev->next = entry->next;
   else
     list_head = entry->next;

and whenever I see code like that, I just go "This person doesn't understand pointers". And it's sadly quite common.

People who understand pointers just use a "pointer to the entry pointer", and initialize that with the address of the list_head. And then as they traverse the list, they can remove the entry without using any conditionals, by just doing a

*pp =  entry->next

pointers

Applying that simplification lets us lose 7 lines from this function even while adding 2 lines of comment.

- struct combine_diff_path *p, *pprev, *ptmp;
+ struct combine_diff_path *p, **tail = &curr;

Chris points out in the comments to the 2016 video "Linus Torvalds's Double Pointer Problem".


kumar points out in the comments the blog post "Linus on Understanding Pointers", where Grisha Trubetskoy explains:

Imagine you have a linked list defined as:

   typedef struct list_entry {
       int val;
       struct list_entry *next;
   } list_entry;

You need to iterate over it from the beginning to end and remove a specific element whose value equals the value of to_remove.
The more obvious way to do this would be:

   list_entry *entry = head; /* assuming head exists and is the first entry of the list */
   list_entry *prev = NULL;
   
   while (entry) { /* line 4 */
       if (entry->val == to_remove)     /* this is the one to remove ; line 5 */
           if (prev)
              prev->next = entry->next; /* remove the entry ; line 7 */
           else
               head = entry->next;      /* special case - first entry ; line 9 */
   
       /* move on to the next entry */
       prev = entry;
       entry = entry->next;
   }

What we are doing above is:

  • iterating over the list until entry is NULL, which means we’ve reached the end of the list (line 4).
  • When we come across an entry we want removed (line 5),
  • we assign the value of current next pointer to the previous one,
  • thus eliminating the current element (line 7).

There is a special case above - at the beginning of the iteration there is no previous entry (prev is NULL), and so to remove the first entry in the list you have to modify head itself (line 9).

What Linus was saying is that the above code could be simplified by making the previous element a pointer to a pointer rather than just a pointer.
The code then looks like this:

   list_entry **pp = &head; /* pointer to a pointer */
   list_entry *entry = head;

   while (entry) {
       if (entry->val == to_remove)
           *pp = entry->next;
       else
            pp = &entry->next;
       entry = entry->next;
   }

The above code is very similar to the previous variant, but notice how we no longer need to watch for the special case of the first element of the list, since pp is not NULL at the beginning. Simple and clever.

Also, someone in that thread commented that the reason this is better is because *pp = entry->next is atomic. It is most certainly NOT atomic.
The above expression contains two dereference operators (* and ->) and one assignment, and neither of those three things is atomic.
This is a common misconception, but alas pretty much nothing in C should ever be assumed to be atomic (including the ++ and -- operators)!

Using NotNull Annotation in method argument

I do this to create my own validation annotation and validator:

ValidCardType.java(annotation to put on methods/fields)

@Constraint(validatedBy = {CardTypeValidator.class})
@Documented
@Target( { ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.FIELD })
@Retention(RetentionPolicy.RUNTIME)
public @interface ValidCardType {
    String message() default "Incorrect card type, should be among: \"MasterCard\" | \"Visa\"";
    Class<?>[] groups() default {};
    Class<? extends Payload>[] payload() default {};
}

And, the validator to trigger the check: CardTypeValidator.java:

public class CardTypeValidator implements ConstraintValidator<ValidCardType, String> {
    private static final String[] ALL_CARD_TYPES = {"MasterCard", "Visa"};

    @Override
    public void initialize(ValidCardType status) {
    }
    public boolean isValid(String value, ConstraintValidatorContext context) {
        return (Arrays.asList(ALL_CARD_TYPES).contains(value));
    }
}

You can do something very similar to check @NotNull.

What is a clean, Pythonic way to have multiple constructors in Python?

I'd use inheritance. Especially if there are going to be more differences than number of holes. Especially if Gouda will need to have different set of members then Parmesan.

class Gouda(Cheese):
    def __init__(self):
        super(Gouda).__init__(num_holes=10)


class Parmesan(Cheese):
    def __init__(self):
        super(Parmesan).__init__(num_holes=15) 

Use of #pragma in C

#pragma is used to do something implementation-specific in C, i.e. be pragmatic for the current context rather than ideologically dogmatic.

The one I regularly use is #pragma pack(1) where I'm trying to squeeze more out of my memory space on embedded solutions, with arrays of structures that would otherwise end up with 8 byte alignment.

Pity we don't have a #dogma yet. That would be fun ;)

How to add a where clause in a MySQL Insert statement?

I think you are looking for UPDATE and not insert?

UPDATE `users`
SET `username` = 'Jack', `password` = '123'
WHERE `id` = 1

Why use 'virtual' for class properties in Entity Framework model definitions?

In the context of EF, marking a property as virtual allows EF to use lazy loading to load it. For lazy loading to work EF has to create a proxy object that overrides your virtual properties with an implementation that loads the referenced entity when it is first accessed. If you don't mark the property as virtual then lazy loading won't work with it.

Create a List of primitive int?

In Java the type of any variable is either a primitive type or a reference type. Generic type arguments must be reference types. Since primitives do not extend Object they cannot be used as generic type arguments for a parametrized type.

Instead use the Integer class which is a wrapper for int:

List<Integer> list = new ArrayList<Integer>();

If your using Java 7 you can simplify this declaration using the diamond operator:

List<Integer> list = new ArrayList<>();

With autoboxing in Java the primitive type int will become an Integer when necessary.

Autoboxing is the automatic conversion that the Java compiler makes between the primitive types and their corresponding object wrapper classes.

So the following is valid:

int myInt = 1;
List<Integer> list = new ArrayList<Integer>();
list.add(myInt);

System.out.println(list.get(0)); //prints 1

How to send post request with x-www-form-urlencoded body

As you set application/x-www-form-urlencoded as content type so data sent must be like this format.

String urlParameters  = "param1=data1&param2=data2&param3=data3";

Sending part now is quite straightforward.

byte[] postData = urlParameters.getBytes( StandardCharsets.UTF_8 );
int postDataLength = postData.length;
String request = "<Url here>";
URL url = new URL( request );
HttpURLConnection conn= (HttpURLConnection) url.openConnection();           
conn.setDoOutput(true);
conn.setInstanceFollowRedirects(false);
conn.setRequestMethod("POST");
conn.setRequestProperty("Content-Type", "application/x-www-form-urlencoded"); 
conn.setRequestProperty("charset", "utf-8");
conn.setRequestProperty("Content-Length", Integer.toString(postDataLength ));
conn.setUseCaches(false);
try(DataOutputStream wr = new DataOutputStream(conn.getOutputStream())) {
   wr.write( postData );
}

Or you can create a generic method to build key value pattern which is required for application/x-www-form-urlencoded.

private String getDataString(HashMap<String, String> params) throws UnsupportedEncodingException{
    StringBuilder result = new StringBuilder();
    boolean first = true;
    for(Map.Entry<String, String> entry : params.entrySet()){
        if (first)
            first = false;
        else
            result.append("&");    
        result.append(URLEncoder.encode(entry.getKey(), "UTF-8"));
        result.append("=");
        result.append(URLEncoder.encode(entry.getValue(), "UTF-8"));
    }    
    return result.toString();
}

Starting Docker as Daemon on Ubuntu

There are multiple popular repositories offering docker packages for Ubuntu. The package docker.io is (most likely) from the Ubuntu repository. Another popular one is http://get.docker.io/ubuntu which offers a package lxc-docker (I am running the latter because it ships updates faster). Make sure only one package is installed. Not quite sure if removal of the packages cleans up properly. If sudo service docker restart still does not work, you may have to clean up manually in /etc/.

How to add meta tag in JavaScript

$('head').append('<meta http-equiv="X-UA-Compatible" content="IE=Edge" />');

or

var meta = document.createElement('meta');
meta.httpEquiv = "X-UA-Compatible";
meta.content = "IE=edge";
document.getElementsByTagName('head')[0].appendChild(meta);

Though I'm not certain it will have an affect as it will be generated after the page is loaded

If you want to add meta data tags for page description, use the SETTINGS of your DNN page to add Description and Keywords. Beyond that, the best way to go when modifying the HEAD is to dynamically inject your code into the HEAD via a third party module.

Found at http://www.dotnetnuke.com/Resources/Forums/forumid/7/threadid/298385/scope/posts.aspx

This may allow other meta tags, if you're lucky

Additional HEAD tags can be placed into Page Settings > Advanced Settings > Page Header Tags.

Found at http://www.dotnetnuke.com/Resources/Forums/forumid/-1/postid/223250/scope/posts.aspx

Store an array in HashMap

HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>();
HashMap<String, int[]> map = new HashMap<String, int[]>();

pick one, for example

HashMap<String, List<Integer>> map = new HashMap<String, List<Integer>>();
map.put("Something", new ArrayList<Integer>());
for (int i=0;i<numarulDeCopii; i++) {
    map.get("Something").add(coeficientUzura[i]); 
}

or just

HashMap<String, int[]> map = new HashMap<String, int[]>();
map.put("Something", coeficientUzura);

No Network Security Config specified, using platform default - Android Log

I have a same problem, with volley, but this is my solution:

  1. In Android Manifiest, in tag application add:

    android:usesCleartextTraffic="true"
    android:networkSecurityConfig="@xml/network_security_config"
    
  2. create in folder xml this file network_security_config.xml and write this:

    <?xml version="1.0" encoding="utf-8"?>
      <network-security-config>
        <base-config cleartextTrafficPermitted="true" />
      </network-security-config>
    
  3. inside tag application add this tag:

    <uses-library android:name="org.apache.http.legacy" android:required="false"/>
    

jQuery - prevent default, then continue default

Use jQuery.one()

Attach a handler to an event for the elements. The handler is executed at most once per element per event type

$('form').one('submit', function(e) {
    e.preventDefault();
    // do your things ...

    // and when you done:
    $(this).submit();
});

The use of one prevent also infinite loop because this custom submit event is detatched after the first submit.

PHP Warning: Invalid argument supplied for foreach()

Try this.

if(is_array($value) || is_object($value)){
    foreach($value as $item){
     //somecode
    }
}

Convert char to int in C#

This converts to an integer and handles unicode

CharUnicodeInfo.GetDecimalDigitValue('2')

You can read more here.

How to schedule a stored procedure in MySQL

I used this query and it worked for me:

CREATE EVENT `exec`
  ON SCHEDULE EVERY 5 SECOND
  STARTS '2013-02-10 00:00:00'
  ENDS '2015-02-28 00:00:00'
  ON COMPLETION NOT PRESERVE ENABLE
DO 
  call delete_rows_links();

Can't concat bytes to str

f.write(plaintext)
f.write("\n".encode("utf-8"))

UILabel Align Text to center

Label.textAlignment = NSTextAlignmentCenter;

How can I delete a file from a Git repository?

If you have the GitHub for Windows application, you can delete a file in 5 easy steps:

  • Click Sync.
  • Click on the directory where the file is located and select your latest version of the file.
  • Click on tools and select "Open a shell here."
  • In the shell, type: "rm {filename}" and hit enter.
  • Commit the change and resync.

optional parameters in SQL Server stored proc?

You can declare like this

CREATE PROCEDURE MyProcName
    @Parameter1 INT = 1,
    @Parameter2 VARCHAR (100) = 'StringValue',
    @Parameter3 VARCHAR (100) = NULL
AS

/* check for the NULL / default value (indicating nothing was passed */
if (@Parameter3 IS NULL)
BEGIN
    /* whatever code you desire for a missing parameter*/
    INSERT INTO ........
END

/* and use it in the query as so*/
SELECT *
FROM Table
WHERE Column = @Parameter

How can I order a List<string>?

Other answers are correct to suggest Sort, but they seem to have missed the fact that the storage location is typed as IList<string. Sort is not part of the interface.

If you know that ListaServizi will always contain a List<string>, you can either change its declared type, or use a cast. If you're not sure, you can test the type:

if (typeof(List<string>).IsAssignableFrom(ListaServizi.GetType()))
    ((List<string>)ListaServizi).Sort();
else
{
    //... some other solution; there are a few to choose from.
}

Perhaps more idiomatic:

List<string> typeCheck = ListaServizi as List<string>;
if (typeCheck != null)
    typeCheck.Sort();
else
{
    //... some other solution; there are a few to choose from.
}

If you know that ListaServizi will sometimes hold a different implementation of IList<string>, leave a comment, and I'll add a suggestion or two for sorting it.

Why can't I have abstract static methods in C#?

Static methods cannot be inherited or overridden, and that is why they can't be abstract. Since static methods are defined on the type, not the instance, of a class, they must be called explicitly on that type. So when you want to call a method on a child class, you need to use its name to call it. This makes inheritance irrelevant.

Assume you could, for a moment, inherit static methods. Imagine this scenario:

public static class Base
{
    public static virtual int GetNumber() { return 5; }
}

public static class Child1 : Base
{
    public static override int GetNumber() { return 1; }
}

public static class Child2 : Base
{
    public static override int GetNumber() { return 2; }
}

If you call Base.GetNumber(), which method would be called? Which value returned? It's pretty easy to see that without creating instances of objects, inheritance is rather hard. Abstract methods without inheritance are just methods that don't have a body, so can't be called.

The 'json' native gem requires installed build tools

My solution is simplier and checked on Ruby 2.0. It also enable download Json. (run CMD.exe as administrator)

    C:\RubyDev>devkitvars.bat
    Adding the DevKit to PATH...

And then write again gem command.

What is the difference between Trap and Interrupt?

A trap is a software interrupt.If you write a program in which you declare a variable having divide by zero value then it is treated as a trap.Whenever you run this program it will throw same error at the same time.System call is a special version of trap in which a program asks os for its required service. In case of interrupt(a general word for hardware interrupts)like an i/o error,the cpu is interrupted at random time and off course it is not the fault of our programmers.It is the hardware that brings them up.

jQuery select by attribute using AND and OR operators

In your special case it would be

a=$('[myc="blue"][myid="1"],[myc="blue"][myid="3"]');

How to prevent a browser from storing passwords

I tested the many solutions and finally I came with this solution.

HTML Code

<input type="text" name="UserName" id="UserName" placeholder="UserName" autocomplete="off" />
<input type="text" name="Password" id="Password" placeholder="Password" autocomplete="off"/>

CSS Code

#Password {
    text-security: disc;
    -webkit-text-security: disc;
    -moz-text-security: disc;
}

JavaScript Code

window.onload = function () {
    init();
}

function init() {
    var x = document.getElementsByTagName("input")["Password"];
    var style = window.getComputedStyle(x);
    console.log(style);

    if (style.webkitTextSecurity) {
        // Do nothing
    } else {
        x.setAttribute("type", "password");
    }
}

Bash command line and input limit

There is a buffer limit of something like 1024. The read will simply hang mid paste or input. To solve this use the -e option.

http://linuxcommand.org/lc3_man_pages/readh.html

-e use Readline to obtain the line in an interactive shell

Change your read to read -e and annoying line input hang goes away.

Boolean operators ( &&, -a, ||, -o ) in Bash

-a and -o are the older and/or operators for the test command. && and || are and/or operators for the shell. So (assuming an old shell) in your first case,

[ "$1" = 'yes' ] && [ -r $2.txt ]

The shell is evaluating the and condition. In your second case,

[ "$1" = 'yes' -a $2 -lt 3 ]

The test command (or builtin test) is evaluating the and condition.

Of course in all modern or semi-modern shells, the test command is built in to the shell, so there really isn't any or much difference. In modern shells, the if statement can be written:

[[ $1 == yes && -r $2.txt ]]

Which is more similar to modern programming languages and thus is more readable.

How do I extract specific 'n' bits of a 32-bit unsigned integer in C?

There is a single BEXTR (Bit field extract (with register)) x86 instruction on Intel and AMD CPUs and UBFX on ARM. There are intrinsic functions such as _bextr_u32() (link requires sign-in) that allow to invoke this instruction explicitly.

They implement (source >> offset) & ((1 << n) - 1) C code: get n continuous bits from source starting at the offset bit. Here's a complete function definition that handles edge cases:

#include <limits.h>

unsigned getbits(unsigned value, unsigned offset, unsigned n)
{
  const unsigned max_n = CHAR_BIT * sizeof(unsigned);
  if (offset >= max_n)
    return 0; /* value is padded with infinite zeros on the left */
  value >>= offset; /* drop offset bits */
  if (n >= max_n)
    return value; /* all  bits requested */
  const unsigned mask = (1u << n) - 1; /* n '1's */
  return value & mask;
}

For example, to get 3 bits from 2273 (0b100011100001) starting at 5-th bit, call getbits(2273, 5, 3)—it extracts 7 (0b111).

For example, say I want the first 17 bits of the 32-bit value; what is it that I should do?

unsigned first_bits = value & ((1u << 17) - 1); // & 0x1ffff

Assuming CHAR_BIT * sizeof(unsigned) is 32 on your system.

I presume I am supposed to use the modulus operator and I tried it and was able to get the last 8 bits and last 16 bits

unsigned last8bitsvalue  = value & ((1u <<  8) - 1); // & 0xff
unsigned last16bitsvalue = value & ((1u << 16) - 1); // & 0xffff

If the offset is always zero as in all your examples in the question then you don't need the more general getbits(). There is a special cpu instruction BLSMSK that helps to compute the mask ((1 << n) - 1).

How do I use Assert to verify that an exception has been thrown?

If you're using MSTest, which originally didn't have an ExpectedException attribute, you could do this:

try 
{
    SomeExceptionThrowingMethod()
    Assert.Fail("no exception thrown");
}
catch (Exception ex)
{
    Assert.IsTrue(ex is SpecificExceptionType);
}

How to run mysql command on bash?

Use double quotes while using BASH variables.

mysql --user="$user" --password="$password" --database="$database" --execute="DROP DATABASE $user; CREATE DATABASE $database;"

BASH doesn't expand variables in single quotes.

Hide/Show components in react native

I solve this problem like this:

<View style={{ display: stateLoad ? 'none' : undefined }} />

What is the best way to compare floats for almost-equality in Python?

I'm not aware of anything in the Python standard library (or elsewhere) that implements Dawson's AlmostEqual2sComplement function. If that's the sort of behaviour you want, you'll have to implement it yourself. (In which case, rather than using Dawson's clever bitwise hacks you'd probably do better to use more conventional tests of the form if abs(a-b) <= eps1*(abs(a)+abs(b)) + eps2 or similar. To get Dawson-like behaviour you might say something like if abs(a-b) <= eps*max(EPS,abs(a),abs(b)) for some small fixed EPS; this isn't exactly the same as Dawson, but it's similar in spirit.

mysql query result in php variable

There are a couple of mysql functions you need to look into.

  • mysql_query("query string here") : returns a resource
  • mysql_fetch_array(resource obtained above) : fetches a row and return as an array with numerical and associative(with column name as key) indices. Typically, you need to iterate through the results till expression evaluates to false value. Like the below:

    while ($row = mysql_fetch_array($query)){
        print_r $row;
    }

    Consult the manual, the links to which are provided below, they have more options to specify the format in which the array is requested. Like, you could use mysql_fetch_assoc(..) to get the row in an associative array.

Links:

In your case,

$query = "SELECT username,userid FROM user WHERE username = 'admin' ";
$result=mysql_query($query);
if (!$result){
    die("BAD!");
}
if (mysql_num_rows($result)==1){
    $row = mysql_fetch_array($result);
    echo "user Id: " . $row['userid'];
}
else{
    echo "not found!";
}

How can I scroll a div to be visible in ReactJS?

To build on @Michelle Tilley's answer, I sometimes want to scroll if the user's selection changes, so I trigger the scroll on componentDidUpdate. I also did some math to figure out how far to scroll and whether scrolling was needed, which for me looks like the following:

_x000D_
_x000D_
  componentDidUpdate() {_x000D_
    let panel, node;_x000D_
    if (this.refs.selectedSection && this.refs.selectedItem) {_x000D_
      // This is the container you want to scroll.          _x000D_
      panel = this.refs.listPanel;_x000D_
      // This is the element you want to make visible w/i the container_x000D_
      // Note: You can nest refs here if you want an item w/i the selected item          _x000D_
      node = ReactDOM.findDOMNode(this.refs.selectedItem);_x000D_
    }_x000D_
_x000D_
    if (panel && node &&_x000D_
      (node.offsetTop > panel.scrollTop + panel.offsetHeight || node.offsetTop < panel.scrollTop)) {_x000D_
      panel.scrollTop = node.offsetTop - panel.offsetTop;_x000D_
    }_x000D_
  }
_x000D_
_x000D_
_x000D_

how to prevent css inherit

Using the wildcard * selector in CSS to override inheritance for all attributes of an element (by setting these back to their initial state).

An example of its use:

li * {
   display: initial;
}

How do I find what Java version Tomcat6 is using?

Or you could use the Probe application and just look at its System Info page. Much easier than writing code, and once you start using it you'll never go back to Tomcat Manager.

m2e error in MavenArchiver.getManifest()

I had also faced the same issue and it got resolved by commenting the version element in POM.xml as show.

org.apache.maven.archiver.[MavenArchiver](https://maven.apache.org/shared/maven-archiver/apidocs/org/apache/maven/archiver/MavenArchiver.html).getManifest(org.apache.maven.project.MavenProject, org.apache.maven.archiver.MavenArchiveConfiguration)

<plugins>
  <plugin>
    <artifactId>maven-compiler-plugin</artifactId>
    <!-- <version>3.5.1</version> -->
    <configuration>
      <source>1.7</source>
      <target>1.7</target>
    </configuration>
  </plugin>
  <plugin>
    <artifactId>maven-war-plugin</artifactId>
    <!-- <version>3.1.0</version> -->
    <configuration>
      <warSourceDirectory>WebContent</warSourceDirectory>
      <failOnMissingWebXml>false</failOnMissingWebXml>
    </configuration>
  </plugin>
</plugins>

Working with $scope.$emit and $scope.$on

First of all, parent-child scope relation does matter. You have two possibilities to emit some event:

  • $broadcast -- dispatches the event downwards to all child scopes,
  • $emit -- dispatches the event upwards through the scope hierarchy.

I don't know anything about your controllers (scopes) relation, but there are several options:

  1. If scope of firstCtrl is parent of the secondCtrl scope, your code should work by replacing $emit by $broadcast in firstCtrl:

    function firstCtrl($scope)
    {
        $scope.$broadcast('someEvent', [1,2,3]);
    }
    
    function secondCtrl($scope)
    {
        $scope.$on('someEvent', function(event, mass) { console.log(mass); });
    }
    
  2. In case there is no parent-child relation between your scopes you can inject $rootScope into the controller and broadcast the event to all child scopes (i.e. also secondCtrl).

    function firstCtrl($rootScope)
    {
        $rootScope.$broadcast('someEvent', [1,2,3]);
    }
    
  3. Finally, when you need to dispatch the event from child controller to scopes upwards you can use $scope.$emit. If scope of firstCtrl is parent of the secondCtrl scope:

    function firstCtrl($scope)
    {
        $scope.$on('someEvent', function(event, data) { console.log(data); });
    }
    
    function secondCtrl($scope)
    {
        $scope.$emit('someEvent', [1,2,3]);
    }
    

How to use bootstrap datepicker

I believe you have to reference bootstrap.js before bootstrap-datepicker.js

Order of execution of tests in TestNG

Use this:

public class TestNG
{
        @BeforeTest
        public void setUp() 
        {
                   /*--Initialize broowsers--*/

        }

        @Test(priority=0)
        public void Login() 
        {

        }

        @Test(priority=2)
        public void Logout() 
        {

        }

        @AfterTest
        public void tearDown() 
        {
                //--Close driver--//

        }

}

Usually TestNG provides number of annotations, We can use @BeforeSuite, @BeforeTest, @BeforeClass for initializing browsers/setup.

We can assign priority if you have written number of test cases in your script and want to execute as per assigned priority then use: @Test(priority=0) starting from 0,1,2,3....

Meanwhile we can group number of test cases and execute it by grouping. for that we will use @Test(Groups='Regression')

At the end like closing the browsers we can use @AfterTest, @AfterSuite, @AfterClass annotations.

Insert at first position of a list in Python

Use insert:

In [1]: ls = [1,2,3]

In [2]: ls.insert(0, "new")

In [3]: ls
Out[3]: ['new', 1, 2, 3]

git-upload-pack: command not found, when cloning remote Git repo

Make sure git-upload-pack is on the path from a non-login shell. (On my machine it's in /usr/bin).

To see what your path looks like on the remote machine from a non-login shell, try this:

ssh you@remotemachine echo \$PATH

(That works in Bash, Zsh, and tcsh, and probably other shells too.)

If the path it gives back doesn't include the directory that has git-upload-pack, you need to fix it by setting it in .bashrc (for Bash), .zshenv (for Zsh), .cshrc (for tcsh) or equivalent for your shell.

You will need to make this change on the remote machine.

If you're not sure which path you need to add to your remote PATH, you can find it with this command (you need to run this on the remote machine):

which git-upload-pack

On my machine that prints /usr/bin/git-upload-pack. So in this case, /usr/bin is the path you need to make sure is in your remote non-login shell PATH.

Query to list all stored procedures

If you are using SQL Server 2005 the following will work:

select *
  from sys.procedures
 where is_ms_shipped = 0

how to set imageview src?

To set image cource in imageview you can use any of the following ways. First confirm your image is present in which format.

If you have image in the form of bitmap then use

imageview.setImageBitmap(bm);

If you have image in the form of drawable then use

imageview.setImageDrawable(drawable);

If you have image in your resource example if image is present in drawable folder then use

imageview.setImageResource(R.drawable.image);

If you have path of image then use

imageview.setImageURI(Uri.parse("pathofimage"));

error: (-215) !empty() in function detectMultiScale

I faced a similar issue. It seems correcting the path to XML makes this error to go away.

Connecting to Postgresql in a docker container from outside

I tried to connect from localhost (mac) to a postgres container. I changed the port in the docker-compose file from 5432 to 3306 and started the container. No idea why I did it :|

Then I tried to connect to postgres via PSequel and adminer and the connection could not be established.

After switching back to port 5432 all works fine.

  db:
    image: postgres
    ports:
      - 5432:5432
    restart: always
    volumes:
      - "db_sql:/var/lib/mysql"
    environment:
      POSTGRES_USER: root
      POSTGRES_PASSWORD: password
      POSTGRES_DB: postgres_db

This was my experience I wanted to share. Perhaps someone can make use of it.

Spring MVC Controller redirect using URL parameters instead of in response

This problem is caused (as others have stated) by model attributes being persisted into the query string - this is usually undesirable and is at risk of creating security holes as well as ridiculous query strings. My usual solution is to never use Strings for redirects in Spring MVC, instead use a RedirectView which can be configured not to expose model attributes (see: http://static.springsource.org/spring/docs/3.1.x/javadoc-api/org/springframework/web/servlet/view/RedirectView.html)

RedirectView(String url, boolean contextRelative, boolean http10Compatible, boolean exposeModelAttributes)

So I tend to have a util method which does a 'safe redirect' like:

public static RedirectView safeRedirect(String url) {
    RedirectView rv = new RedirectView(url);
    rv.setExposeModelAttributes(false);
    return rv;
}

The other option is to use bean configuration XML:

<bean id="myBean" class="org.springframework.web.servlet.view.RedirectView">
   <property name="exposeModelAttributes" value="false" />
   <property name="url" value="/myRedirect"/>
</bean>

Again, you could abstract this into its own class to avoid repetition (e.g. SafeRedirectView).


A note about 'clearing the model' - this is not the same as 'not exposing the model' in all circumstances. One site I worked on had a lot of filters which added things to the model, this meant that clearing the model before redirecting would not prevent a long query string. I would also suggest that 'not exposing model attributes' is a more semantic approach than 'clearing the model before redirecting'.

CSS background opacity with rgba not working in IE 8

This a transparency solution for most browsers including IE x

.transparent {
    /* Required for IE 5, 6, 7 */
    /* ...or something to trigger hasLayout, like zoom: 1; */
    width: 100%; 

    /* Theoretically for IE 8 & 9 (more valid) */   
    /* ...but not required as filter works too */
    /* should come BEFORE filter */
    -ms-filter:"progid:DXImageTransform.Microsoft.Alpha(Opacity=50)";

    /* This works in IE 8 & 9 too */
    /* ... but also 5, 6, 7 */
    filter: alpha(opacity=50);

    /* Older than Firefox 0.9 */
    -moz-opacity:0.5;

    /* Safari 1.x (pre WebKit!) */
    -khtml-opacity: 0.5;

    /* Modern!
    /* Firefox 0.9+, Safari 2?, Chrome any?
    /* Opera 9+, IE 9+ */
    opacity: 0.5;
}

Storing a file in a database as opposed to the file system?

Have a look at this answer:

Storing Images in DB - Yea or Nay?

Essentially, the space and performance hit can be quite big, depending on the number of users. Also, keep in mind that Web servers are cheap and you can easily add more to balance the load, whereas the database is the most expensive and hardest to scale part of a web architecture usually.

There are some opposite examples (e.g., Microsoft Sharepoint), but usually, storing files in the database is not a good idea.

Unless possibly you write desktop apps and/or know roughly how many users you will ever have, but on something as random and unexpectable like a public web site, you may pay a high price for storing files in the database.

How to easily map c++ enums to strings

I know I'm late to party, but for everyone else who comes to visit this page, u could try this, it's easier than everything there and makes more sense:

namespace texs {
    typedef std::string Type;
    Type apple = "apple";
    Type wood = "wood";
}

How to create an array for JSON using PHP?

<?php 

    $username=urldecode($_POST['log_user']);

    $user="select * from tbl_registration where member_id= '".$username."' ";
    $rsuser = $obj->select($user);
    if(count($rsuser)>0)
    {
        //   (Status if 2 then its expire)    (1= use) ( 0 = not use)

        $cheknew="select name,ldate,offer_photo  from tbl_offer where status=1 ";
        $rscheknew = $obj->selectjson($cheknew);

        if(count($rscheknew)>0)
        {

             $nik=json_encode($rscheknew);
            echo "{\"status\" : \"200\" ,\"responce\" : \"201\", \"message\" : \"Get Record\",\"feed\":".str_replace("<p>","",$nik). "}";
        }
        else
        {
            $row2="No Record Found";
            $nik1=json_encode($row2);
            echo "{\"status\" : \"202\",  \"responce\" : \"604\",\"message\" : \"No Record Found \",\"feed\":".str_replace("<p>","",$nik1). "}";
        }
    }
    else
    {
        $row2="Invlid User";
        $nik1=json_encode($row2);
        echo "{\"status\" : \"404\", \"responce\" : \"602\",\"message\" : \"Invlid User \",\"feed\":".str_replace("<p>","",$nik1). "}";
    }

 ?>

How to find whether or not a variable is empty in Bash?

[ "$variable" ] || echo empty
: ${variable="value_to_set_if_unset"}

jQuery autocomplete with callback ajax json

I hope this helps:

var token = document.getElementById('token').value;
var nombre = document.getElementById('txtNombre').value;    

$("#txtNombre").keyup(function () {
    $.ajax({
        type: "POST",
        url: host() + "Formulario/BuscarNombreAutocompletar/",
        data: JSON.stringify({ "nombre": nombre }),
        headers: {
            'Authorization': 'Bearer ' + token
        },
        contentType: "application/json; charset=utf-8",
        dataType: "json",
        success: function (data) {
            var dataArray = [];
            if (controlCarga(data)) {

                $.each(data[1], function (i, item) {
                    dataArray.push(item.frmNombre)
                });

                $('#txtNombre').autocomplete({
                    clearButton: true,
                    source: dataArray,
                    selectFirst: true,
                    minLength: 2
                });
            }
        },
        error: function (xhr, textStatus, errorThrown) {
            console.log('Error: ' + xhr.responseText);
        }
    });
});

How to update one file in a zip archive

7zip (7za) can be used for adding/updating files/directories nicely:

Example: Replacing (regardless of file date) the MANIFEST.MF file in a JAR file. The /source/META-INF directory contains the MANIFEST.MF file that you want to put into the jar (zip):

7za a /tmp/file.jar /source/META-INF/

Only update (does not replace the target if the source is older)

7za u /tmp/file.jar /source/META-INF/

Change the Theme in Jupyter Notebook?

My complete solution:

1) Get Dark Reader on chrome which will not only get you a great Dark Theme for Jupyter but also for every single website you'd like (you can play with the different filters. I use Dynamic).

2) Paste those lines of code in your notebook so the legends and axes become visible:

from jupyterthemes import jtplot
jtplot.style(theme='monokai', context='notebook', ticks=True, grid=False)

You're all set for a disco coding night !

How to check if a variable is null or empty string or all whitespace in JavaScript?

if (addr == null || addr.trim() === ''){
  //...
}

A null comparison will also catch undefined. If you want false to pass too, use !addr. For backwards browser compatibility swap addr.trim() for $.trim(addr).

Reverting to a specific commit based on commit id with Git?

I think, bwawok's answer is wrong at some point:

if you do

git reset --soft c14809fa

It will make your local files changed to be like they were then, but leave your history etc. the same.

According to manual: git-reset, "git reset --soft"...

does not touch the index file nor the working tree at all (but resets the head to <commit>, just like all modes do). This leaves all your changed files "Changes to be committed", as git status would put it.

So it will "remove" newer commits from the branch. This means, after looking at your old code, you cannot go to the newest commit in this branch again, easily. So it does the opposide as described by bwawok: Local files are not changed (they look exactly as before "git reset --soft"), but the history is modified (branch is truncated after the specified commit).

The command for bwawok's answer might be:

git checkout <commit>

You can use this to peek at old revision: How did my code look yesterday?

(I know, I should put this in comments to this answer, but stackoverflow does not allow me to do so! My reputation is too low.)

What is the difference between attribute and property?

In Java (or other languages), using Property/Attribute depends on usage:

  • Property used when value doesn't change very often (usually used at startup or for environment variable)

  • Attributes is a value (object child) of an Element (object) which can change very often/all the time and be or not persistent

ImageMagick security policy 'PDF' blocking conversion

I was experiencing this issue with nextcloud which would fail to create thumbnails for pdf files.

However, none of the suggested steps would solve the issue for me.

Eventually I found the reason: The accepted answer did work but I had to also restart php-fpm after editing the policy.xml file:

 sudo systemctl restart php7.2-fpm.service

Microsoft Advertising SDK doesn't deliverer ads

I only use MicrosoftAdvertising.Mobile and Microsoft.Advertising.Mobile.UI and I am served ads. The SDK should only add the DLLs not reference itself.

Note: You need to explicitly set width and height Make sure the phone dialer, and web browser capabilities are enabled

Followup note: Make sure that after you've removed the SDK DLL, that the xmlns references are not still pointing to it. The best route to take here is

  1. Remove the XAML for the ad
  2. Remove the xmlns declaration (usually at the top of the page, but sometimes will be declared in the ad itself)
  3. Remove the bad DLL (the one ending in .SDK )
  4. Do a Clean and then Build (clean out anything remaining from the DLL)
  5. Add the xmlns reference (actual reference is below)
  6. Add the ad to the page (example below)

Here is the xmlns reference:

xmlns:AdNamepace="clr-namespace:Microsoft.Advertising.Mobile.UI;assembly=Microsoft.Advertising.Mobile.UI" 

Then the ad itself:

<AdNamespace:AdControl x:Name="myAd" Height="80" Width="480"                    AdUnitId="yourAdUnitIdHere" ApplicationId="yourIdHere"/> 

matplotlib set yaxis label size

If you are using the 'pylab' for interactive plotting you can set the labelsize at creation time with pylab.ylabel('Example', fontsize=40).

If you use pyplot programmatically you can either set the fontsize on creation with ax.set_ylabel('Example', fontsize=40) or afterwards with ax.yaxis.label.set_size(40).

Autoplay an audio with HTML5 embed tag while the player is invisible

If you are using React, make sure autoplay is set to,

autoPlay

React wants it to be camelcase!

Why does dividing two int not yield the right value when assigned to double?

For the same reasons above, you'll have to convert one of 'a' or 'b' to a double type. Another way of doing it is to use:

double c = (a+0.0)/b;

The numerator is (implicitly) converted to a double because we have added a double to it, namely 0.0.

How to split a delimited string into an array in awk?

echo "12|23|11" | awk '{split($0,a,"|"); print a[3] a[2] a[1]}'

Why is Spring's ApplicationContext.getBean considered bad?

There is another time when using getBean makes sense. If you're reconfiguring a system that already exists, where the dependencies are not explicitly called out in spring context files. You can start the process by putting in calls to getBean, so that you don't have to wire it all up at once. This way you can slowly build up your spring configuration putting each piece in place over time and getting the bits lined up properly. The calls to getBean will eventually be replaced, but as you understand the structure of the code, or lack there of, you can start the process of wiring more and more beans and using fewer and fewer calls to getBean.

SUM of grouped COUNT in SQL Query

SELECT name, COUNT(name) AS count, SUM(COUNT(name)) OVER() AS total_count
FROM Table GROUP BY name

Get Max value from List<myType>

How about this way:

List<int> myList = new List<int>(){1, 2, 3, 4}; //or any other type
myList.Sort();
int greatestValue = myList[ myList.Count - 1 ];

You basically let the Sort() method to do the job for you instead of writing your own method. Unless you don't want to sort your collection.

Int to byte array

Most of the answers here are either 'UnSafe" or not LittleEndian safe. BitConverter is not LittleEndian safe. So building on an example in here (see the post by PZahra) I made a LittleEndian safe version simply by reading the byte array in reverse when BitConverter.IsLittleEndian == true

void Main(){    
    Console.WriteLine(BitConverter.IsLittleEndian); 
    byte[] bytes = BitConverter.GetBytes(0xdcbaabcdfffe1608);
    //Console.WriteLine(bytes); 
    string hexStr = ByteArrayToHex(bytes);
    Console.WriteLine(hexStr);
}

public static string ByteArrayToHex(byte[] data) 
{ 
   char[] c = new char[data.Length * 2]; 
   byte b; 
  if(BitConverter.IsLittleEndian)
  {
        //read the byte array in reverse
        for (int y = data.Length -1, x = 0; y >= 0; --y, ++x) 
        { 
            b = ((byte)(data[y] >> 4)); 
            c[x] = (char)(b > 9 ? b + 0x37 : b + 0x30); 
            b = ((byte)(data[y] & 0xF)); 
            c[++x] = (char)(b > 9 ? b + 0x37 : b + 0x30); 
        }               
    }
    else
    {
        for (int y = 0, x = 0; y < data.Length; ++y, ++x) 
        { 
            b = ((byte)(data[y] >> 4)); 
            c[x] = (char)(b > 9 ? b + 0x37 : b + 0x30); 
            b = ((byte)(data[y] & 0xF)); 
            c[++x] = (char)(b > 9 ? b + 0x37 : b + 0x30); 
        }
    }
    return String.Concat("0x",new string(c));
}

It returns this:

True
0xDCBAABCDFFFE1608

which is the exact hex that went into the byte array.

Gradle: Execution failed for task ':processDebugManifest'

I solved this problem in Android Studio 3.5 by cleaning and rebuilding project.

Just click to Build -> Rebuild Project.

How do I get AWS_ACCESS_KEY_ID for Amazon?

It is very dangerous to create an access_key_id in "My Account ==> Security Credentials". Because the key has all authority. Please create "IAM" user and attach only some policies you need.

pg_config executable not found

I found that this page provided the best instructions for installing PostgreSQL on my mac and that the pip install command worked perfectly afterwards:

https://www.codefellows.org/blog/three-battle-tested-ways-to-install-postgresql

What is "Connect Timeout" in sql server connection string?

By default connection timeout is 240 but if you are faceing the problem of connection time out then you can increase upto "300" "Connection Timeout=300"

How do I resolve "Run-time error '429': ActiveX component can't create object"?

This download fixed my VB6 EXE and Access 2016 (using ACEDAO.DLL) run-time error 429. Took me 2 long days to get it resolved because there are so many causes of 429.

http://www.microsoft.com/en-ca/download/details.aspx?id=13255

QUOTE from link: "This download will install a set of components that can be used to facilitate transfer of data between 2010 Microsoft Office System files and non-Microsoft Office applications"

How to select a single field for all documents in a MongoDB collection?

This works for me,

db.student.find({},{"roll":1})

no condition in where clause i.e., inside first curly braces. inside next curly braces: list of projection field names to be needed in the result and 1 indicates particular field is the part of the query result

Bootstrap 3 collapse accordion: collapse all works but then cannot expand all while maintaining data-parent

To keep the accordion nature intact when wanting to also use 'hide' and 'show' functions like .collapse( 'hide' ), you must initialize the collapsible panels with the parent property set in the object with toggle: false before making any calls to 'hide' or 'show'

// initialize collapsible panels
$('#accordion .collapse').collapse({
  toggle: false,
  parent: '#accordion'
});

// show panel one (will collapse others in accordion)
$( '#collapseOne' ).collapse( 'show' );

// show panel two (will collapse others in accordion)
$( '#collapseTwo' ).collapse( 'show' );

// hide panel two (will not collapse/expand others in accordion)
$( '#collapseTwo' ).collapse( 'hide' );

How to set the focus for a particular field in a Bootstrap modal, once it appears

I've created a dynamic way to call each event automatically. It perfect to focus a field, because it call the event just once, removing it after use.

function modalEvents() {
    var modal = $('#modal');
    var events = ['show', 'shown', 'hide', 'hidden'];

    $(events).each(function (index, event) {
        modal.on(event + '.bs.modal', function (e) {
            var callback = modal.data(event + '-callback');
            if (typeof callback != 'undefined') {
                callback.call();
                modal.removeData(event + '-callback');
            }
        });
    });
}

You just need to call modalEvents() on document ready.

Use:

$('#modal').data('show-callback', function() {
    $("input#photo_name").focus();
});

So, you can use the same modal to load what you want without worry about remove events every time.

In Git, what is the difference between origin/master vs origin master?

Given the fact that you can switch to origin/master (though in detached state) while having your network cable unplugged, it must be a local representation of the master branch at origin.

Query to list number of records in each table in a database

sp_MSForEachTable 'DECLARE @t AS VARCHAR(MAX); 
SELECT @t = CAST(COUNT(1) as VARCHAR(MAX)) 
+ CHAR(9) + CHAR(9) + ''?'' FROM ? ; PRINT @t'

Output:

enter image description here

Creating a search form in PHP to search a database?

try this out let me know what happens.

Form:

<form action="form.php" method="post"> 
Search: <input type="text" name="term" /><br /> 
<input type="submit" value="Submit" /> 
</form> 

Form.php:

$term = mysql_real_escape_string($_REQUEST['term']);    

$sql = "SELECT * FROM liam WHERE Description LIKE '%".$term."%'";
$r_query = mysql_query($sql);

while ($row = mysql_fetch_array($r_query)){ 
echo 'Primary key: ' .$row['PRIMARYKEY']; 
echo '<br /> Code: ' .$row['Code']; 
echo '<br /> Description: '.$row['Description']; 
echo '<br /> Category: '.$row['Category']; 
echo '<br /> Cut Size: '.$row['CutSize'];  
} 

Edit: Cleaned it up a little more.

Final Cut (my test file):

<?php
$db_hostname = 'localhost';
$db_username = 'demo';
$db_password = 'demo';
$db_database = 'demo';

// Database Connection String
$con = mysql_connect($db_hostname,$db_username,$db_password);
if (!$con)
  {
  die('Could not connect: ' . mysql_error());
  }

mysql_select_db($db_database, $con);
?>

<!DOCTYPE html>
<html lang="en">
    <head>
        <meta charset="utf-8" />
        <title></title>
    </head>
    <body>
<form action="" method="post">  
Search: <input type="text" name="term" /><br />  
<input type="submit" value="Submit" />  
</form>  
<?php
if (!empty($_REQUEST['term'])) {

$term = mysql_real_escape_string($_REQUEST['term']);     

$sql = "SELECT * FROM liam WHERE Description LIKE '%".$term."%'"; 
$r_query = mysql_query($sql); 

while ($row = mysql_fetch_array($r_query)){  
echo 'Primary key: ' .$row['PRIMARYKEY'];  
echo '<br /> Code: ' .$row['Code'];  
echo '<br /> Description: '.$row['Description'];  
echo '<br /> Category: '.$row['Category'];  
echo '<br /> Cut Size: '.$row['CutSize'];   
}  

}
?>
    </body>
</html>

Dynamic tabs with user-click chosen components

I'm not cool enough for comments. I fixed the plunker from the accepted answer to work for rc2. Nothing fancy, links to the CDN were just broken is all.

'@angular/core': {
  main: 'bundles/core.umd.js',
  defaultExtension: 'js'
},
'@angular/compiler': {
  main: 'bundles/compiler.umd.js',
  defaultExtension: 'js'
},
'@angular/common': {
  main: 'bundles/common.umd.js',
  defaultExtension: 'js'
},
'@angular/platform-browser-dynamic': {
  main: 'bundles/platform-browser-dynamic.umd.js',
  defaultExtension: 'js'
},
'@angular/platform-browser': {
  main: 'bundles/platform-browser.umd.js',
  defaultExtension: 'js'
},

https://plnkr.co/edit/kVJvI1vkzrLZJeRFsZuv?p=preview

Create URL from a String

URL url = new URL(yourUrl, "/api/v1/status.xml");

According to the javadocs this constructor just appends whatever resource to the end of your domain, so you would want to create 2 urls:

URL domain = new URL("http://example.com");
URL url = new URL(domain + "/files/resource.xml");

Sources: http://docs.oracle.com/javase/6/docs/api/java/net/URL.html

Get number days in a specified month using JavaScript?

The following takes any valid datetime value and returns the number of days in the associated month... it eliminates the ambiguity of both other answers...

 // pass in any date as parameter anyDateInMonth
function daysInMonth(anyDateInMonth) {
    return new Date(anyDateInMonth.getFullYear(), 
                    anyDateInMonth.getMonth()+1, 
                    0).getDate();}

How to make all controls resize accordingly proportionally when window is maximized?

Well, it's fairly simple to do.

On the window resize event handler, calculate how much the window has grown/shrunk, and use that fraction to adjust 1) Height, 2) Width, 3) Canvas.Top, 4) Canvas.Left properties of all the child controls inside the canvas.

Here's the code:

private void window1_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            myCanvas.Width = e.NewSize.Width;
            myCanvas.Height = e.NewSize.Height;

            double xChange = 1, yChange = 1;

            if (e.PreviousSize.Width != 0)
            xChange = (e.NewSize.Width/e.PreviousSize.Width);

            if (e.PreviousSize.Height != 0)
            yChange = (e.NewSize.Height / e.PreviousSize.Height);

            foreach (FrameworkElement fe in myCanvas.Children )
            {   
                /*because I didn't want to resize the grid I'm having inside the canvas in this particular instance. (doing that from xaml) */            
                if (fe is Grid == false)
                {
                    fe.Height = fe.ActualHeight * yChange;
                    fe.Width = fe.ActualWidth * xChange;

                    Canvas.SetTop(fe, Canvas.GetTop(fe) * yChange);
                    Canvas.SetLeft(fe, Canvas.GetLeft(fe) * xChange);

                }
            }
        }

Android Log.v(), Log.d(), Log.i(), Log.w(), Log.e() - When to use each one?

Let's go in reverse order:

  • Log.e: This is for when bad stuff happens. Use this tag in places like inside a catch statement. You know that an error has occurred and therefore you're logging an error.

  • Log.w: Use this when you suspect something shady is going on. You may not be completely in full on error mode, but maybe you recovered from some unexpected behavior. Basically, use this to log stuff you didn't expect to happen but isn't necessarily an error. Kind of like a "hey, this happened, and it's weird, we should look into it."

  • Log.i: Use this to post useful information to the log. For example: that you have successfully connected to a server. Basically use it to report successes.

  • Log.d: Use this for debugging purposes. If you want to print out a bunch of messages so you can log the exact flow of your program, use this. If you want to keep a log of variable values, use this.

  • Log.v: Use this when you want to go absolutely nuts with your logging. If for some reason you've decided to log every little thing in a particular part of your app, use the Log.v tag.

And as a bonus...

  • Log.wtf: Use this when stuff goes absolutely, horribly, holy-crap wrong. You know those catch blocks where you're catching errors that you never should get...yeah, if you wanna log them use Log.wtf

How to remove carriage returns and new lines in Postgresql?

select regexp_replace(field, E'[\\n\\r\\u2028]+', ' ', 'g' )

I had the same problem in my postgres d/b, but the newline in question wasn't the traditional ascii CRLF, it was a unicode line separator, character U2028. The above code snippet will capture that unicode variation as well.

Update... although I've only ever encountered the aforementioned characters "in the wild", to follow lmichelbacher's advice to translate even more unicode newline-like characters, use this:

select regexp_replace(field, E'[\\n\\r\\f\\u000B\\u0085\\u2028\\u2029]+', ' ', 'g' )

how to start stop tomcat server using CMD?

Create a .bat file and write two commands:

cd C:\ Path to your tomcat directory \ bin

startup.bat

Now on double-click, Tomcat server will start.

Opening database file from within SQLite command-line shell

I wonder why no one was able to get what the question actually asked. It stated What is the command within the SQLite shell tool to specify a database file?

A sqlite db is on my hard disk E:\ABCD\efg\mydb.db. How do I access it with sqlite3 command line interface? .open E:\ABCD\efg\mydb.db does not work. This is what question asked.

I found the best way to do the work is

  • copy-paste all your db files in 1 directory (say E:\ABCD\efg\mydbs)
  • switch to that directory in your command line
  • now open sqlite3 and then .open mydb.db

This way you can do the join operation on different tables belonging to different databases as well.

When should use Readonly and Get only properties

readonly properties are used to create a fail-safe code. i really like the Encapsulation posts series of Mark Seemann about properties and backing fields:

http://blog.ploeh.dk/2011/05/24/PokayokeDesignFromSmellToFragrance.aspx

taken from Mark's example:

public class Fragrance : IFragrance
{
    private readonly string name;

    public Fragrance(string name)
    {
        if (name == null)
        {
            throw new ArgumentNullException("name");
        }

        this.name = name;
    }

    public string Spread()
    {
        return this.name;
    }
}

in this example you use the readonly name field to make sure the class invariant is always valid. in this case the class composer wanted to make sure the name field is set only once (immutable) and is always present.

How do I execute a PowerShell script automatically using Windows task scheduler?

I also could not launch scripts, after heavy searching nothing helped. No -ExecutionPolicy, no commands, no files and no difference between "" and ''.

I simply put the command I ran in powershell in the argument tab: ./scripts.ps1 parameter1 11 parameter2 xx and so on. Now the scheduler works. Program: Powershell.exe Start in: C:/location/of/script/

Good tutorial for using HTML5 History API (Pushstate?)

You may want to take a look at this jQuery plugin. They have lots of examples on their site. http://www.asual.com/jquery/address/

Jquery .on('scroll') not firing the event while scrolling

$("body").on("custom-scroll", ".myDiv", function(){
    console.log("Scrolled :P");
})

$("#btn").on("click", function(){
    $("body").append('<div class="myDiv"><br><br><p>Content1<p><br><br><p>Content2<p><br><br></div>');
    listenForScrollEvent($(".myDiv"));
});


function listenForScrollEvent(el){
    el.on("scroll", function(){
        el.trigger("custom-scroll");
    })
}

see this post - Bind scroll Event To Dynamic DIV?

How to use cURL in Java?

You can make use of java.net.URL and/or java.net.URLConnection.

URL url = new URL("https://stackoverflow.com");

try (BufferedReader reader = new BufferedReader(new InputStreamReader(url.openStream(), "UTF-8"))) {
    for (String line; (line = reader.readLine()) != null;) {
        System.out.println(line);
    }
}

Also see the Oracle's simple tutorial on the subject. It's however a bit verbose. To end up with less verbose code, you may want to consider Apache HttpClient instead.

By the way: if your next question is "How to process HTML result?", then the answer is "Use a HTML parser. No, don't use regex for this.".

See also:

Is there a limit on number of tcp/ip connections between machines on linux?

The quick answer is 2^16 TCP ports, 64K.

The issues with system imposed limits is a configuration issue, already touched upon in previous comments.

The internal implications to TCP is not so clear (to me). Each port requires memory for it's instantiation, goes onto a list and needs network buffers for data in transit.

Given 64K TCP sessions the overhead for instances of the ports might be an issue on a 32-bit kernel, but not a 64-bit kernel (correction here gladly accepted). The lookup process with 64K sessions can slow things a bit and every packet hits the timer queues, which can also be problematic. Storage for in transit data can theoretically swell to the window size times ports (maybe 8 GByte).

The issue with connection speed (mentioned above) is probably what you are seeing. TCP generally takes time to do things. However, it is not required. A TCP connect, transact and disconnect can be done very efficiently (check to see how the TCP sessions are created and closed).

There are systems that pass tens of gigabits per second, so the packet level scaling should be OK.

There are machines with plenty of physical memory, so that looks OK.

The performance of the system, if carefully configured should be OK.

The server side of things should scale in a similar fashion.

I would be concerned about things like memory bandwidth.

Consider an experiment where you login to the local host 10,000 times. Then type a character. The entire stack through user space would be engaged on each character. The active footprint would likely exceed the data cache size. Running through lots of memory can stress the VM system. The cost of context switches could approach a second!

This is discussed in a variety of other threads: https://serverfault.com/questions/69524/im-designing-a-system-to-handle-10000-tcp-connections-per-second-what-problems

What does principal end of an association means in 1:1 relationship in Entity framework

In one-to-one relation one end must be principal and second end must be dependent. Principal end is the one which will be inserted first and which can exist without the dependent one. Dependent end is the one which must be inserted after the principal because it has foreign key to the principal.

In case of entity framework FK in dependent must also be its PK so in your case you should use:

public class Boo
{
    [Key, ForeignKey("Foo")]
    public string BooId{get;set;}
    public Foo Foo{get;set;}
}

Or fluent mapping

modelBuilder.Entity<Foo>()
            .HasOptional(f => f.Boo)
            .WithRequired(s => s.Foo);

Copy filtered data to another sheet using VBA

Best way of doing it

Below code is to copy the visible data in DBExtract sheet, and paste it into duplicateRecords sheet, with only filtered values. Range selected by me is the maximum range that can be occupied by my data. You can change it as per your need.

  Sub selectVisibleRange()

    Dim DbExtract, DuplicateRecords As Worksheet
    Set DbExtract = ThisWorkbook.Sheets("Export Worksheet")
    Set DuplicateRecords = ThisWorkbook.Sheets("DuplicateRecords")

    DbExtract.Range("A1:BF9999").SpecialCells(xlCellTypeVisible).Copy
    DuplicateRecords.Cells(1, 1).PasteSpecial


    End Sub

Regex - Does not contain certain Characters

^[^<>]+$

The caret in the character class ([^) means match anything but, so this means, beginning of string, then one or more of anything except < and >, then the end of the string.

How to remove .html from URL?

Use a hash tag.

May not be exactly what you want but it solves the problem of removing the extension.

Say you have a html page saved as about.html and you don't want that pesky extension you could use a hash tag and redirect to the correct page.

switch(window.location.hash.substring(1)){
      case 'about':
      window.location = 'about.html';
      break;
  }

Routing to yoursite.com#about will take you to yoursite.com/about.html. I used this to make my links cleaner.

Python setup.py develop vs install

From the documentation. The develop will not install the package but it will create a .egg-link in the deployment directory back to the project source code directory.

So it's like installing but instead of copying to the site-packages it adds a symbolic link (the .egg-link acts as a multiplatform symbolic link).

That way you can edit the source code and see the changes directly without having to reinstall every time that you make a little change. This is useful when you are the developer of that project hence the name develop. If you are just installing someone else's package you should use install

Break string into list of characters in Python

python >= 3.5

Version 3.5 onwards allows the use of PEP 448 - Extended Unpacking Generalizations:

>>> string = 'hello'
>>> [*string]
['h', 'e', 'l', 'l', 'o']

This is a specification of the language syntax, so it is faster than calling list:

>>> from timeit import timeit
>>> timeit("list('hello')")
0.3042821969866054
>>> timeit("[*'hello']")
0.1582647830073256

How do I draw a shadow under a UIView?

You can use my utility function created for shadow and corner radius as below:

- (void)addShadowWithRadius:(CGFloat)shadowRadius withShadowOpacity:(CGFloat)shadowOpacity withShadowOffset:(CGSize)shadowOffset withShadowColor:(UIColor *)shadowColor withCornerRadius:(CGFloat)cornerRadius withBorderColor:(UIColor *)borderColor withBorderWidth:(CGFloat)borderWidth forView:(UIView *)view{

    // drop shadow
    [view.layer setShadowRadius:shadowRadius];
    [view.layer setShadowOpacity:shadowOpacity];
    [view.layer setShadowOffset:shadowOffset];
    [view.layer setShadowColor:shadowColor.CGColor];

    // border radius
    [view.layer setCornerRadius:cornerRadius];

    // border
    [view.layer setBorderColor:borderColor.CGColor];
    [view.layer setBorderWidth:borderWidth];
}

Hope it will help you!!!

Currency Formatting in JavaScript

You can use standard JS toFixed method

var num = 5.56789;
var n=num.toFixed(2);

//5.57

In order to add commas (to separate 1000's) you can add regexp as follows (where num is a number):

num.toString().replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,")

//100000 => 100,000
//8000 => 8,000
//1000000 => 1,000,000

Complete example:

var value = 1250.223;
var num = '$' + value.toFixed(2).replace(/(\d)(?=(\d\d\d)+(?!\d))/g, "$1,");

//document.write(num) would write value as follows: $1,250.22

Separation character depends on country and locale. For some countries it may need to be .

Concatenating Column Values into a Comma-Separated List

 DECLARE @SQL AS VARCHAR(8000)
SELECT @SQL = ISNULL(@SQL+',','') + ColumnName FROM TableName
SELECT @SQL

Show space, tab, CRLF characters in editor of Visual Studio

For Visual Studio for mac, you can find it under Visual Studio -> Preferences -> Text Editor -> Markers and Rulers -> Show invisible characters

Please note you may need to restart Visual Studio for the changes to take effect

Getting attribute of element in ng-click function in angularjs

Even more simple, pass the $event object to ng-click to access the event properties. As an example:

<a ng-click="clickEvent($event)" class="exampleClass" id="exampleID" data="exampleData" href="">Click Me</a>

Within your clickEvent() = function(obj) {} function you can access the data value like this:

var dataValue = obj.target.attributes.data.value;

Which would return exampleData.

Here's a full jsFiddle.

How to view AndroidManifest.xml from APK file?

The AXMLParser and APKParser.jar can also do the job, you can see the link. AXMLParser

Create a unique number with javascript time

A better approach would be:

new Date().valueOf();

instead of

new Date().getUTCMilliseconds();

valueOf() is "most likely" a unique number. http://www.w3schools.com/jsref/jsref_valueof_date.asp.

Calculate text width with JavaScript

The better of is to detect whether text will fits right before you display the element. So you can use this function which doesn't requires the element to be on screen.

function textWidth(text, fontProp) {
    var tag = document.createElement("div");
    tag.style.position = "absolute";
    tag.style.left = "-999em";
    tag.style.whiteSpace = "nowrap";
    tag.style.font = fontProp;
    tag.innerHTML = text;

    document.body.appendChild(tag);

    var result = tag.clientWidth;

    document.body.removeChild(tag);

    return result;
}

Usage:

if ( textWidth("Text", "bold 13px Verdana") > elementWidth) {
    ...
}

Google Android USB Driver and ADB

Locate the following file

C:\Users\[your name]\.android\adb_usb.ini

And make the following changes:

# ANDROID 3RD PARTY USB VENDOR ID LIST -- DO NOT EDIT.
# USE 'android update adb' TO GENERATE.
# 1 USB VENDOR ID PER LINE.
0x2207

I added 0x2207 to the file. This number is part of the hardware id, which can be found under the device's hardware information.

Mine was:

USB\VID_2207&PID_0010&MI_01

(I tried executing android update adb, but it did nothing.)

How to form a correct MySQL connection string?

Here is an example:

MySqlConnection con = new MySqlConnection(
    "Server=ServerName;Database=DataBaseName;UID=username;Password=password");

MySqlCommand cmd = new MySqlCommand(
    " INSERT Into Test (lat, long) VALUES ('"+OSGconv.deciLat+"','"+
    OSGconv.deciLon+"')", con);

con.Open();
cmd.ExecuteNonQuery();
con.Close();

Must JDBC Resultsets and Statements be closed separately although the Connection is closed afterwards?

If you want more compact code, I suggest using Apache Commons DbUtils. In this case:

Connection conn = null;
PreparedStatement stmt = null;
ResultSet rs = null;
try {
    conn = // Retrieve connection
    stmt = conn.prepareStatement(// Some SQL);
    rs = stmt.executeQuery();
} catch(Exception e) {
    // Error Handling
} finally {
    DbUtils.closeQuietly(rs);
    DbUtils.closeQuietly(stmt);
    DbUtils.closeQuietly(conn);
}

How to remove class from all elements jquery

This just removes the highlight class from everything that has the edgetoedge class:

$(".edgetoedge").removeClass("highlight");

I think you want this:

$(".edgetoedge .highlight").removeClass("highlight");

The .edgetoedge .highlight selector will choose everything that is a child of something with the edgetoedge class and has the highlight class.

How to get all subsets of a set? (powerset)

A simple way would be to harness the internal representation of integers under 2's complement arithmetic.

Binary representation of integers is as {000, 001, 010, 011, 100, 101, 110, 111} for numbers ranging from 0 to 7. For an integer counter value, considering 1 as inclusion of corresponding element in collection and '0' as exclusion we can generate subsets based on the counting sequence. Numbers have to be generated from 0 to pow(2,n) -1 where n is the length of array i.e. number of bits in binary representation.

A simple Subset Generator Function based on it can be written as below. It basically relies

def subsets(array):
    if not array:
        return
    else:
        length = len(array)
        for max_int in range(0x1 << length):
            subset = []
            for i in range(length):
                if max_int & (0x1 << i):
                    subset.append(array[i])
            yield subset

and then it can be used as

def get_subsets(array):
    powerset = []
    for i in subsets(array):
        powerser.append(i)
    return powerset

Testing

Adding following in local file

if __name__ == '__main__':
    sample = ['b',  'd',  'f']

    for i in range(len(sample)):
        print "Subsets for " , sample[i:], " are ", get_subsets(sample[i:])

gives following output

Subsets for  ['b', 'd', 'f']  are  [[], ['b'], ['d'], ['b', 'd'], ['f'], ['b', 'f'], ['d', 'f'], ['b', 'd', 'f']]
Subsets for  ['d', 'f']  are  [[], ['d'], ['f'], ['d', 'f']]
Subsets for  ['f']  are  [[], ['f']]

Twitter Bootstrap 3: How to center a block

You can use class .center-block in combination with style="width:400px;max-width:100%;" to preserve responsiveness.

Using .col-md-* class with .center-block will not work because of the float on .col-md-*.

How to check if curl is enabled or disabled

Hope this helps.

<?php
    function _iscurl() {
        return function_exists('curl_version');
    }
?>

How to track down access violation "at address 00000000"

You start looking near that code that you know ran, and you stop looking when you reach the code you know didn't run.

What you're looking for is probably some place where your program calls a function through a function pointer, but that pointer is null.

It's also possible you have stack corruption. You might have overwritten a function's return address with zero, and the exception occurs at the end of the function. Check for possible buffer overflows, and if you are calling any DLL functions, make sure you used the right calling convention and parameter count.

This isn't an ordinary case of using a null pointer, like an unassigned object reference or PChar. In those cases, you'll have a non-zero "at address x" value. Since the instruction occurred at address zero, you know the CPU's instruction pointer was not pointing at any valid instruction. That's why the debugger can't show you which line of code caused the problem — there is no line of code. You need to find it by finding the code that lead up to the place where the CPU jumped to the invalid address.

The call stack might still be intact, which should at least get you pretty close to your goal. If you have stack corruption, though, you might not be able to trust the call stack.

Showing Thumbnail for link in WhatsApp || og:image meta-tag doesn't work

Additional useful info:

You can provide several og:images, whatsapp will use the last one. This will help with the problem that e.g. facebook want 1.91:1 ratio and whatsapp 1:1

https://stackoverflow.com/a/61078968/8486854

VMWare Player vs VMWare Workstation

re: VMware Workstation support for physical disks vs virtual disks.

I run Player with the VM Disk files on their own dedicated fast hard drive, independent from the OS hard drive. This allows both the OS and Player to simultaneously independently read/write to their own drives, the performance difference is noticeable, and a second WD Black or Raptor or SSD is cheap. Placing the VM disk file on a second drive also works with Microsoft Virtual PC.

Name node is in safe mode. Not able to leave

The Command did not work for me but the following did

hdfs dfsadmin -safemode leave

I used the hdfs command instead of the hadoop command.

Check out http://ask.gopivotal.com/hc/en-us/articles/200933026-HDFS-goes-into-readonly-mode-and-errors-out-with-Name-node-is-in-safe-mode- link too

Resize svg when window is resized in d3.js

Look for 'responsive SVG' it is pretty simple to make a SVG responsive and you don't have to worry about sizes any more.

Here is how I did it:

_x000D_
_x000D_
d3.select("div#chartId")_x000D_
   .append("div")_x000D_
   // Container class to make it responsive._x000D_
   .classed("svg-container", true) _x000D_
   .append("svg")_x000D_
   // Responsive SVG needs these 2 attributes and no width and height attr._x000D_
   .attr("preserveAspectRatio", "xMinYMin meet")_x000D_
   .attr("viewBox", "0 0 600 400")_x000D_
   // Class to make it responsive._x000D_
   .classed("svg-content-responsive", true)_x000D_
   // Fill with a rectangle for visualization._x000D_
   .append("rect")_x000D_
   .classed("rect", true)_x000D_
   .attr("width", 600)_x000D_
   .attr("height", 400);
_x000D_
.svg-container {_x000D_
  display: inline-block;_x000D_
  position: relative;_x000D_
  width: 100%;_x000D_
  padding-bottom: 100%; /* aspect ratio */_x000D_
  vertical-align: top;_x000D_
  overflow: hidden;_x000D_
}_x000D_
.svg-content-responsive {_x000D_
  display: inline-block;_x000D_
  position: absolute;_x000D_
  top: 10px;_x000D_
  left: 0;_x000D_
}_x000D_
_x000D_
svg .rect {_x000D_
  fill: gold;_x000D_
  stroke: steelblue;_x000D_
  stroke-width: 5px;_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.7.0/d3.min.js"></script>_x000D_
_x000D_
<div id="chartId"></div>
_x000D_
_x000D_
_x000D_

Note: Everything in the SVG image will scale with the window width. This includes stroke width and font sizes (even those set with CSS). If this is not desired, there are more involved alternate solutions below.

More info / tutorials:

http://thenewcode.com/744/Make-SVG-Responsive

http://soqr.fr/testsvg/embed-svg-liquid-layout-responsive-web-design.php

How do you determine the size of a file in C?

POSIX

The POSIX standard has its own method to get file size.
Include the sys/stat.h header to use the function.

Synopsis

  • Get file statistics using stat(3).
  • Obtain the st_size property.

Examples

Note: It limits the size to 4GB. If not Fat32 filesystem then use the 64bit version!

#include <stdio.h>
#include <sys/stat.h>

int main(int argc, char** argv)
{
    struct stat info;
    stat(argv[1], &info);

    // 'st' is an acronym of 'stat'
    printf("%s: size=%ld\n", argv[1], info.st_size);
}
#include <stdio.h>
#include <sys/stat.h>

int main(int argc, char** argv)
{
    struct stat64 info;
    stat64(argv[1], &info);

    // 'st' is an acronym of 'stat'
    printf("%s: size=%ld\n", argv[1], info.st_size);
}

ANSI C (standard)

The ANSI C doesn't directly provides the way to determine the length of the file.
We'll have to use our mind. For now, we'll use the seek approach!

Synopsis

  • Seek the file to the end using fseek(3).
  • Get the current position using ftell(3).

Example

#include <stdio.h>

int main(int argc, char** argv)
{
    FILE* fp = fopen(argv[1]);
    int f_size;

    fseek(fp, 0, SEEK_END);
    f_size = ftell(fp);
    rewind(fp); // to back to start again

    printf("%s: size=%ld", (unsigned long)f_size);
}

If the file is stdin or a pipe. POSIX, ANSI C won't work.
It will going return 0 if the file is a pipe or stdin.

Opinion: You should use POSIX standard instead. Because, it has 64bit support.

PHP - check if variable is undefined

You can use the PHP isset() function to test whether a variable is set or not. The isset() will return FALSE if testing a variable that has been set to NULL. Example:

<?php
    $var1 = '';
    if(isset($var1)){
        echo 'This line is printed, because the $var1 is set.';
    }
?>

This code will output "This line is printed, because the $var1 is set."

read more in https://stackhowto.com/how-to-check-if-a-variable-is-undefined-in-php/

Set the layout weight of a TextView programmatically

You can also give weight separately like this ,

LayoutParams lp1 = new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);

 lp1.weight=1;

What is the best way to measure execution time of a function?

I would definitely advise you to have a look at System.Diagnostics.Stopwatch

And when I looked around for more about Stopwatch I found this site;

Beware of the stopwatch

There mentioned another possibility

Process.TotalProcessorTime

jQuery show/hide not working

The content is not ready yet, you can move your js to the end of the file or do

<script>
$(function () { 
    $( '.expand' ).click(function() {
       $( '.img_display_content' ).show();
    });
});

So that the document waits to be loaded before running.

conditional Updating a list using LINQ

Try Parallel for longer lists:

Parallel.ForEach(li.Where(f => f.name == "di"), l => l.age = 10);

How to create a table from select query result in SQL Server 2008

Use following syntax to create new table from old table in SQL server 2008

Select * into new_table  from  old_table 

Why is "npm install" really slow?

I was able to resolve this from the comments section; outlining the process below.

From the comments

AndreFigueiredo stated :

I installed modules here in less than 1 min with your package.json with npm v3.5.2 and node v4.2.6. I suggest you update node and npm.


v1.3.0 didn't even have flattened dependencies introduced on v3 that resolved a lot of annoying issues

LINKIWI stated :

Generally speaking, don't rely on package managers like apt to maintain up-to-date software. I would strongly recommend purging the node/npm combo you installed from apt and following the instructions on nodejs.org to install the latest release.

Observations

Following their advice, I noticed that CentOS, Ubuntu, and Debian all use very outdated versions of nodejs and npm when retrieving the current version using apt or yum (depending on operating systems primary package manager).

Get rid of the outdated nodejs and npm

To resolve this with as minimal headache as possible, I ran the following command (on Ubuntu) :

apt-get purge --auto-remove nodejs npm

This purged the system of the archaic nodejs and npm as well as all dependencies which were no longer required

Install current nodejs and compatible npm

The next objective was to get a current version of both nodejs and npm which I can snag nodejs directly from here and either compile or use the binary, however this would not make it easy to swap versions as I need to (depending on age of project).

I came across a great package called nvm which (so far) seems to manage this task quite well. To install the current stable latest build of version 7 of nodejs :

Install nvm

curl -o- https://raw.githubusercontent.com/creationix/nvm/v0.33.0/install.sh | bash

Source .bashrc

source ~/.bashrc

Use nvm to install nodejs 7.x

nvm install 7

After installation I was pleasantly surprised by much faster performance of npm, that it also now showed a pretty progress bar while snagging packages.

For those curious, the current (as of this date) version of npm should look like the following (and if it doesn't, you likely need to update it):

current npm running

Summary

DO NOT USE YOUR OS PACKAGE MANAGER TO INSTALL NODE.JS OR NPM - You will get very bad results as it seems no OS is keeping these packages (not even close to) current. If you find that npm is running slow and it isn't your computer or internet, it is most likely because of a severely outdated version.

Getting list of items inside div using Selenium Webdriver

You're asking for all the elements of class facetContainerDiv, of which there is only one (your outer-most div). Why not do

List<WebElement> checks =  driver.findElements(By.class("facetCheck"));
// click the 3rd checkbox
checks.get(2).click();

How do I grant myself admin access to a local SQL Server instance?

Open a command prompt window. If you have a default instance of SQL Server already running, run the following command on the command prompt to stop the SQL Server service:

net stop mssqlserver

Now go to the directory where SQL server is installed. The directory can for instance be one of these:

C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Binn
C:\Program Files\Microsoft SQL Server\MSSQL13.MSSQLSERVER\MSSQL\Binn

Figure out your MSSQL directory and CD into it as such:

CD C:\Program Files\Microsoft SQL Server\MSSQL10_50.MSSQLSERVER\MSSQL\Binn

Now run the following command to start SQL Server in single user mode. As SQLCMD is being specified, only one SQLCMD connection can be made (from another command prompt window).

sqlservr -m"SQLCMD"

Now, open another command prompt window as the same user as the one that started SQL Server in single user mode above, and in it, run:

sqlcmd

And press enter. Now you can execute SQL statements against the SQL Server instance running in single user mode:

create login [<<DOMAIN\USERNAME>>] from windows;

-- For older versions of SQL Server:
EXEC sys.sp_addsrvrolemember @loginame = N'<<DOMAIN\USERNAME>>', @rolename = N'sysadmin';

-- For newer versions of SQL Server:
ALTER SERVER ROLE [sysadmin] ADD MEMBER [<<DOMAIN\USERNAME>>];

GO

Source.

UPDATED Do not forget a semicolon after ALTER SERVER ROLE [sysadmin] ADD MEMBER [<<DOMAIN\USERNAME>>]; and do not add extra semicolon after GO or the command never executes.