Programs & Examples On #Fingerprinting

ERROR in ./node_modules/css-loader?

try using

npm rebuild node-sass

Selenium WebDriver How to Resolve Stale Element Reference Exception?

With reference to the answer given by @djangofan, it looks like the viable solution is to keep your code inside try catch block where a possible Staleness occurs. When I use this below code I didn't get the problem any time.

public void inputName(String name)
{
    try {
        waitForVisibilityElement(name);//My own visibility function
        findElement(By.name("customerName")).sendKeys(name);
    }
    catch (StaleElementReferenceException e)
    {
        e.getMessage();
    }
}

I have tried using the ExpectedConditions.presenceOfElementLocated(By) but the staleness exceptions still throws intermittently.

Hope this solution helps.

Simple and fast method to compare images for similarity

If you want to compare image for similarity,I suggest you to used OpenCV. In OpenCV, there are few feature matching and template matching. For feature matching, there are SURF, SIFT, FAST and so on detector. You can use this to detect, describe and then match the image. After that, you can use the specific index to find number of match between the two images.

How do I turn a C# object into a JSON string in .NET?

I would vote for ServiceStack's JSON Serializer:

using ServiceStack;

string jsonString = new { FirstName = "James" }.ToJson();

It is also the fastest JSON serializer available for .NET: http://www.servicestack.net/benchmarks/

PivotTable to show values, not sum of values

Another easier way to do it is to upload your file to google sheets, then add a pivot, for the columns and rows select the same as you would with Excel, however, for values select Calculated Field and then in the formula type in =

In my case the column header is URL

How to run Spring Boot web application in Eclipse itself?

If you are doing code in STS you just need to add the devtools dependency in your maven file. After that it will run itself whenever you will do some change.

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-devtools</artifactId>
</dependency>

warning: Insecure world writable dir /usr/local/bin in PATH, mode 040777

Am using Mountain Lion. What I did was Look for /usr/local and Get Info. On it there is Sharing and Permissions. Make sure that its only the user and Admin are the only ones who have read and write permissions. Anyone else should have read access only. That sorted my problem.

Its normally helpful is your Run disk utilities and repair permissions too.

How to make my layout able to scroll down?

If you even did not get scroll after doing what is written above .....

Set the android:layout_height="250dp"or you can say xdp where x can be any numerical value.

Why avoid increment ("++") and decrement ("--") operators in JavaScript?

In a loop it's harmless, but in an assignment statement it can lead to unexpected results:

var x = 5;
var y = x++; // y is now 5 and x is 6
var z = ++x; // z is now 7 and x is 7

Whitespace between the variable and the operator can lead to unexpected results as well:

a = b = c = 1; a ++ ; b -- ; c; console.log('a:', a, 'b:', b, 'c:', c)

In a closure, unexpected results can be an issue as well:

var foobar = function(i){var count = count || i; return function(){return count++;}}

baz = foobar(1);
baz(); //1
baz(); //2


var alphabeta = function(i){var count = count || i; return function(){return ++count;}}

omega = alphabeta(1);
omega(); //2
omega(); //3

And it triggers automatic semicolon insertion after a newline:

var foo = 1, bar = 2, baz = 3, alpha = 4, beta = 5, delta = alpha
++beta; //delta is 4, alpha is 4, beta is 6

preincrement/postincrement confusion can produce off-by-one errors that are extremely difficult to diagnose. Fortunately, they are also complete unnecessary. There are better ways to add 1 to a variable.

References

How to convert SQL Server's timestamp column to datetime format

My coworkers helped me with this:

select CONVERT(VARCHAR(10), <tms_column>, 112), count(*)
from table where <tms_column> > '2012-09-10'
group by CONVERT(VARCHAR(10), <tms_column>, 112);

or

select CONVERT(DATE, <tms_column>, 112), count(*)
from table where <tms_column> > '2012-09-10'
group by CONVERT(DATE, <tms_column>, 112);

Get file version in PowerShell

I find this useful:

function Get-Version($filePath)
{
   $name = @{Name="Name";Expression= {split-path -leaf $_.FileName}}
   $path = @{Name="Path";Expression= {split-path $_.FileName}}
   dir -recurse -path $filePath | % { if ($_.Name -match "(.*dll|.*exe)$") {$_.VersionInfo}} | select FileVersion, $name, $path
}

Maximum Java heap size of a 32-bit JVM on a 64-bit OS

I have tried setting the heap size upto 2200M on 32bit Linux machine and JVM worked fine. The JVM didnt start when I set it to 2300M.

Android open pdf file

Kotlin version below (Updated version of @paul-burke response:

fun openPDFDocument(context: Context, filename: String) {
    //Create PDF Intent
    val pdfFile = File(Environment.getExternalStorageDirectory().absolutePath + "/" + filename)
    val pdfIntent = Intent(Intent.ACTION_VIEW)
    pdfIntent.setDataAndType(Uri.fromFile(pdfFile), "application/pdf")
    pdfIntent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY)

    //Create Viewer Intent
    val viewerIntent = Intent.createChooser(pdfIntent, "Open PDF")
    context.startActivity(viewerIntent)
}

cordova Android requirements failed: "Could not find an installed version of Gradle"

Solution for linux and specifically Ubuntu 20:04. First ensure you have Java installed before proceeding:

1. java -version
2. sudo apt-get update
3. sudo apt-get install openjdk-8-jdk

Open .bashrc

vim $HOME/.bashrc 

Set Java environment variables.

export JAVA_HOME="/usr/lib/jvm/java-1.8.0-openjdk-amd64"
export JRE_HOME="/usr/lib/jvm/java-1.8.0-openjdk-amd64/jre"

Visit Gradle's website and identify the version you would like to install. Replace version 6.5.1 with the version number you would like to install.

 1. sudo apt-get update
 2. cd /tmp && curl -L -O https://services.gradle.org/distributions/gradle-6.5.1-bin.zip
 3. sudo mkdir /opt/gradle
 4. sudo unzip -d /opt/gradle /tmp/gradle-6.5.1-bin.zip

To setup Gradle's environment variables use nano or vim or gedit editors to create a new file:

sudo vim /etc/profile.d/gradle.sh

Add the following lines to gradle.sh

export GRADLE_HOME="/opt/gradle/gradle-6.5.1/"
export PATH=${GRADLE_HOME}/bin:${PATH}

Run the following commands to make gradle.sh executable and to update your bash terminal with the environment variables you set as well as check the installed version.

1. sudo chmod +x /etc/profile.d/gradle.sh
3. source /etc/profile.d/gradle.sh
4. gradle -v

Best way to format if statement with multiple conditions

The second one is a classic example of the Arrow Anti-pattern So I'd avoid it...

If your conditions are too long extract them into methods/properties.

Using OpenGl with C#?

I think what @korona meant was since it's just a C API, you can consume it from C# directly with a heck of a lot of typing like this:

[DllImport("opengl32")]
public static extern void glVertex3f(float x, float y, float z);

You unfortunately would need to do this for every single OpenGL function you call, and is basically what Tao has done for you.

Is there an equivalent method to C's scanf in Java?

Take a look at this site, it explains two methods for reading from console in java, using Scanner or the classical InputStreamReader from System.in.

Following code is taken from cited website:

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;

public class ReadConsoleSystem {
  public static void main(String[] args) {

    System.out.println("Enter something here : ");

    try{
        BufferedReader bufferRead = new BufferedReader(new InputStreamReader(System.in));
        String s = bufferRead.readLine();

        System.out.println(s);
    }
    catch(IOException e)
    {
        e.printStackTrace();
    }

  }
}

--

import java.util.Scanner;

public class ReadConsoleScanner {
  public static void main(String[] args) {

      System.out.println("Enter something here : ");

       String sWhatever;

       Scanner scanIn = new Scanner(System.in);
       sWhatever = scanIn.nextLine();

       scanIn.close();            
       System.out.println(sWhatever);
  }
}

Regards.

The property 'value' does not exist on value of type 'HTMLElement'

There is a way to achieve this without type assertion, by using generics instead, which are generally a bit nicer and safer to use.

Unfortunately, getElementById is not generic, but querySelector is:

const inputValue = document.querySelector<HTMLInputElement>('#greet')!.value;

Similarly, you can use querySelectorAll to select multiple elements and use generics so TS can understand that all selected elements are of a particular type:

const inputs = document.querySelectorAll<HTMLInputElement>('.my-input');

This will produce a NodeListOf<HTMLInputElement>.

how to get list of port which are in use on the server

TCPView is a Windows program that will show you detailed listings of all TCP and UDP endpoints on your system, including the local and remote addresses and state of TCP connections. On Windows Server 2008, Vista, NT, 2000 and XP TCPView also reports the name of the process that owns the endpoint. TCPView provides a more informative and conveniently presented subset of the Netstat program that ships with Windows. The TCPView download includes Tcpvcon, a command-line version with the same functionality.

http://technet.microsoft.com/en-us/sysinternals/bb897437.aspx

When should I use cross apply over inner join?

It seems to me that CROSS APPLY can fill a certain gap when working with calculated fields in complex/nested queries, and make them simpler and more readable.

Simple example: you have a DoB and you want to present multiple age-related fields that will also rely on other data sources (such as employment), like Age, AgeGroup, AgeAtHiring, MinimumRetirementDate, etc. for use in your end-user application (Excel PivotTables, for example).

Options are limited and rarely elegant:

  • JOIN subqueries cannot introduce new values in the dataset based on data in the parent query (it must stand on its own).

  • UDFs are neat, but slow as they tend to prevent parallel operations. And being a separate entity can be a good (less code) or a bad (where is the code) thing.

  • Junction tables. Sometimes they can work, but soon enough you're joining subqueries with tons of UNIONs. Big mess.

  • Create yet another single-purpose view, assuming your calculations don't require data obtained mid-way through your main query.

  • Intermediary tables. Yes... that usually works, and often a good option as they can be indexed and fast, but performance can also drop due to to UPDATE statements not being parallel and not allowing to cascade formulas (reuse results) to update several fields within the same statement. And sometimes you'd just prefer to do things in one pass.

  • Nesting queries. Yes at any point you can put parenthesis on your entire query and use it as a subquery upon which you can manipulate source data and calculated fields alike. But you can only do this so much before it gets ugly. Very ugly.

  • Repeating code. What is the greatest value of 3 long (CASE...ELSE...END) statements? That's gonna be readable!

    • Tell your clients to calculate the damn things themselves.

Did I miss something? Probably, so feel free to comment. But hey, CROSS APPLY is like a godsend in such situations: you just add a simple CROSS APPLY (select tbl.value + 1 as someFormula) as crossTbl and voilà! Your new field is now ready for use practically like it had always been there in your source data.

Values introduced through CROSS APPLY can...

  • be used to create one or multiple calculated fields without adding performance, complexity or readability issues to the mix
  • like with JOINs, several subsequent CROSS APPLY statements can refer to themselves: CROSS APPLY (select crossTbl.someFormula + 1 as someMoreFormula) as crossTbl2
  • you can use values introduced by a CROSS APPLY in subsequent JOIN conditions
  • As a bonus, there's the Table-valued function aspect

Dang, there's nothing they can't do!

Generate random array of floats between a range

Alternatively you could use SciPy

from scipy import stats
stats.uniform(0.5, 13.3).rvs(50)

and for the record to sample integers it's

stats.randint(10, 20).rvs(50)

Fixed positioned div within a relative parent div

A simple thing you can do is position your fixed DIV relative to the rest of your page with % values.

Check out this jsfiddle here where the fixed DIV is a sidebar.

div#wrapper {
    margin: auto;
    width: 80%;
}

div#main {
    width: 60%;
}

div#sidebar {
    position: fixed;
    width: 30%;
    left: 60%;
}

And a brief picture below describing the layout above:

example layout

Reset Excel to default borders

If you're trying to do this from within Excel (rather than programmatically), follow these steps:

  1. From the "Orb" menu on the ribbon, click the "Excel Options" button near the bottom of the menu.

  2. In the list of choices at the left, select "Advanced".

  3. Scroll down until you see the heading "Display options for this worksheet".

  4. Select the checkbox labeled "Show guidelines".

   Show gridlines checkbox under Excel Options:Advanced

Java String array: is there a size of method?

In java there is a length field that you can use on any array to find out it's size:

    String[] s = new String[10];
    System.out.println(s.length);

Measure execution time for a Java method

You can take timestamp snapshots before and after, then repeat the experiments several times to average to results. There are also profilers that can do this for you.


From "Java Platform Performance: Strategies and Tactics" book:

With System.currentTimeMillis()

class TimeTest1 {
   public static void main(String[] args) {

      long startTime = System.currentTimeMillis();

      long total = 0;
      for (int i = 0; i < 10000000; i++) {
         total += i;
      }

      long stopTime = System.currentTimeMillis();
      long elapsedTime = stopTime - startTime;
      System.out.println(elapsedTime);
   }
}

With a StopWatch class

You can use this StopWatch class, and call start() and stop before and after the method.

class TimeTest2 {
   public static void main(String[] args) {

      Stopwatch timer = new Stopwatch().start();

      long total = 0;
      for (int i = 0; i < 10000000; i++) {
         total += i;
      }

      timer.stop();
      System.out.println(timer.getElapsedTime());
   }
}

See here (archived).


NetBeans Profiler:

Application Performance Application

Performance profiles method-level CPU performance (execution time). You can choose to profile the entire application or a part of the application.

See here.

Confusing "duplicate identifier" Typescript error message

run the following command will fix this issue.

npm install @types/node --save-dev

Shell command to tar directory excluding certain files/folders

Check it out

tar cvpzf zip_folder.tgz . --exclude=./public --exclude=./tmp --exclude=./log --exclude=fileName

Detect if string contains any spaces

What you have will find a space anywhere in the string, not just between words.

If you want to find any kind of whitespace, you can use this, which uses a regular expression:

if (/\s/.test(str)) {
    // It has any kind of whitespace
}

\s means "any whitespace character" (spaces, tabs, vertical tabs, formfeeds, line breaks, etc.), and will find that character anywhere in the string.

According to MDN, \s is equivalent to: [ \f\n\r\t\v?\u00a0\u1680?\u180e\u2000?\u2001\u2002?\u2003\u2004?\u2005\u2006?\u2007\u2008?\u2009\u200a?\u2028\u2029??\u202f\u205f?\u3000].


For some reason, I originally read your question as "How do I see if a string contains only spaces?" and so I answered with the below. But as @CrazyTrain points out, that's not what the question says. I'll leave it, though, just in case...

If you mean literally spaces, a regex can do it:

if (/^ *$/.test(str)) {
    // It has only spaces, or is empty
}

That says: Match the beginning of the string (^) followed by zero or more space characters followed by the end of the string ($). Change the * to a + if you don't want to match an empty string.

If you mean whitespace as a general concept:

if (/^\s*$/.test(str)) {
    // It has only whitespace
}

That uses \s (whitespace) rather than the space, but is otherwise the same. (And again, change * to + if you don't want to match an empty string.)

Remove header and footer from window.print()

I am sure Adding this code on your css file will solve the problem

<style type="text/css" media="print">
    @page 
    {
        size: auto;   /* auto is the initial value */
        margin: 0mm;  /* this affects the margin in the printer settings */
    }
</style>

You may visit this to know more about this

Can I use Twitter Bootstrap and jQuery UI at the same time?

just to update this, bootstrap v2 no longer conflicts with jquery ui

https://github.com/twbs/bootstrap/issues/171

Edit: as @Freshblood there are a few things that still conflict. However, as originally posted Twitter suggests that they are working on this and it largely works, specially compared to v1.

How to allow only one radio button to be checked?

All radio buttons have to have the same name:

<input type='radio' name='foo'>

Only 1 radio button of each group of buttons with the same name can be checked.

How to run a bash script from C++ program

The only standard mandated implementation dependent way is to use the system() function from stdlib.h.

Also if you know how to make user become the super-user that would be nice also.

Do you want the script to run as super-user or do you want to elevate the privileges of the C executable? The former can be done with sudo but there are a few things you need to know before you can go off using sudo.

How to scroll to top of page with JavaScript/jQuery?

Use the following function

window.scrollTo(xpos, ypos)

Here xpos is Required. The coordinate to scroll to, along the x-axis (horizontal), in pixels

ypos is also Required. The coordinate to scroll to, along the y-axis (vertical), in pixels

Error pushing to GitHub - insufficient permission for adding an object to repository database

OK - turns out it was a permissions problem on GitHub that happened during the fork of emi/bixo to bixo/bixo. Once Tekkub fixed these, it started working again.

How should I set the default proxy to use default credentials?

From .NET 2.0 you shouldn't need to do this. If you do not explicitly set the Proxy property on a web request it uses the value of the static WebRequest.DefaultWebProxy. If you wanted to change the proxy being used by all subsequent WebRequests, you can set this static DefaultWebProxy property.

The default behaviour of WebRequest.DefaultWebProxy is to use the same underlying settings as used by Internet Explorer.

If you wanted to use different proxy settings to the current user then you would need to code

WebRequest webRequest = WebRequest.Create("http://stackoverflow.com/");
webRequest.Proxy = new WebProxy("http://proxyserver:80/",true);

or

WebRequest.DefaultWebProxy = new WebProxy("http://proxyserver:80/",true);

You should also remember the object model for proxies includes the concept that the proxy can be different depending on the destination hostname. This can make things a bit confusing when debugging and checking the property of webRequest.Proxy. Call

webRequest.Proxy.GetProxy(new Uri("http://google.com.au")) to see the actual details of the proxy server that would be used.

There seems to be some debate about whether you can set webRequest.Proxy or WebRequest.DefaultWebProxy = null to prevent the use of any proxy. This seems to work OK for me but you could set it to new DefaultProxy() with no parameters to get the required behaviour. Another thing to check is that if a proxy element exists in your applications config file, the .NET Framework will NOT use the proxy settings in Internet Explorer.

The MSDN Magazine article Take the Burden Off Users with Automatic Configuration in .NET gives further details of what is happening under the hood.

_DEBUG vs NDEBUG

Unfortunately DEBUG is overloaded heavily. For instance, it's recommended to always generate and save a pdb file for RELEASE builds. Which means one of the -Zx flags, and -DEBUG linker option. While _DEBUG relates to special debug versions of runtime library such as calls to malloc and free. Then NDEBUG will disable assertions.

#1062 - Duplicate entry for key 'PRIMARY'

You need to remove shares as your PRIMARY KEY OR UNIQUE_KEY

Install python 2.6 in CentOS

rpm -Uvh http://yum.chrislea.com/centos/5/i386/chl-release-5-3.noarch.rpm
rpm --import /etc/pki/rpm-gpg/RPM-GPG-KEY-CHL
rpm -Uvh ftp://ftp.pbone.net/mirror/centos.karan.org/el5/extras/testing/i386/RPMS/libffi-3.0.5-1.el5.kb.i386.rpm
yum install python26
python26

for dos that just dont know :=)

Is it possible to iterate through JSONArray?

You can use the opt(int) method and use a classical for loop.

Alter column in SQL Server

To set a default value to a column, try this:

ALTER TABLE tb_TableName
ALTER COLUMN Record_Status SET DEFAULT 'default value'

Centering a div block without the width

An element with ‘display: block’ (as div is by default) has a width determined by the width of its container. You can't make a block's width dependent on the width of its contents (shrink-to-fit).

(Except for blocks that are ‘float: left/right’ in CSS 2.1, but that's no use for centering.)

You could set the ‘display’ property to ‘inline-block’ to turn a block into a shrink-to-fit object that can be controlled by its parent's text-align property, but browser support is spotty. You can mostly get away with it by using hacks (eg. see -moz-inline-stack) if you want to go that way.

The other way to go is tables. This can be necessary when you have columns whose width really can't be known in advance. I can't really tell what you're trying to do from the example code — there's nothing obvious in there that would need a shrink-to-fit block — but a list of products could possibly be considered tabular.

[PS. never use ‘pt’ for font sizes on the web. ‘px’ is more reliable if you really need fixed size text, otherwise relative units like ‘%’ are better. And “clear: ccc both” — a typo?]

.center{
   text-align:center; 
}

.center > div{ /* N.B. child combinators don't work in IE6 or less */
   display:inline-block;
}

JSFiddle

How do I set an absolute include path in PHP?

Another option is to create a file in the $_SERVER['DOCUMENT_ROOT'] directory with the definition of your absolute path.

For example, if your $_SERVER['DOCUMENT_ROOT'] directory is

C:\wamp\www\

create a file (i.e. my_paths.php) containing this

<?php if(!defined('MY_ABS_PATH')) define('MY_ABS_PATH',$_SERVER['DOCUMENT_ROOT'].'MyProyect/')

Now you only need to include in every file inside your MyProyect folder this file (my_paths.php), so you can user MY_ABS_PATH as an absolute path for MyProject.

How to ignore the certificate check when ssl

CA5386 : Vulnerability analysis tools will alert you to these codes.

Correct code :

ServicePointManager.ServerCertificateValidationCallback += (sender, certificate, chain, sslPolicyErrors) =>
{
   return (sslPolicyErrors & SslPolicyErrors.RemoteCertificateNotAvailable) != SslPolicyErrors.RemoteCertificateNotAvailable;
};

How to get a pixel's x,y coordinate color from an image?

Canvas would be a great way to do this, as @pst said above. Check out this answer for a good example:

getPixel from HTML Canvas?

Some code that would serve you specifically as well:

var imgd = context.getImageData(x, y, width, height);
var pix = imgd.data;

for (var i = 0, n = pix.length; i < n; i += 4) {
  console.log pix[i+3]
}

This will go row by row, so you'd need to convert that into an x,y and either convert the for loop to a direct check or run a conditional inside.

Reading your question again, it looks like you want to be able to get the point that the person clicks on. This can be done pretty easily with jquery's click event. Just run the above code inside a click handler as such:

$('el').click(function(e){
   console.log(e.clientX, e.clientY)
}

Those should grab your x and y values.

How to generate unique ID with node.js

Extending from YaroslavGaponov's answer, the simplest implementation is just using Math.random().

Math.random()

Mathematically, the chances of fractions being the same in a real space [0, 1] is theoretically 0. Probability-wise it is approximately close to 0 for a default length of 16 decimals in node.js. And this implementation should also reduce arithmetic overflows as no operations are performed. Also, it is more memory efficient compared to a string as Decimals occupy less memory than strings.

I call this the "Fractional-Unique-ID".

Wrote code to generate 1,000,000 Math.random() numbers and could not find any duplicates (at least for default decimal points of 16). See code below (please provide feedback if any):

random_numbers = [] 
for (i = 0; i < 1000000; i++) { 
   random_numbers.push(Math.random()); 
   //random_numbers.push(Math.random().toFixed(13)) //depends decimals default 16 
} 

if (i === 1000000) { 
   console.log("Before checking duplicate"); 
   console.log(random_numbers.length); 
   console.log("After checking duplicate"); 
   random_set = new Set(random_numbers); // Set removes duplicates
   console.log([...random_set].length); // length is still the same after removing
} 

how to add super privileges to mysql database?

In Sequel Pro, access the User Accounts window. Note that any MySQL administration program could be substituted in place of Sequel Pro.

Add the following accounts and privileges:

GRANT SUPER ON *.* TO 'user'@'%' IDENTIFIED BY PASSWORD

creating batch script to unzip a file without additional zip tools

If you have PowerShell 5.0 or higher (pre-installed with Windows 10 and Windows Server 2016):

powershell Expand-Archive your.zip -DestinationPath your_destination

Automapper missing type map configuration or unsupported mapping - Error

I created a new AutomapperProfile class. It extends Profile. We have over 100 projects in our solution. Many projects have an AutomapperProfile class, but this one was new to this existing project. However, I did find what I had to do to fix this issue for us. There is a Binding project. Within the Initialization there is this code:

var mappingConfig = new List<Action<IConfiguration>>();

// Initialize the Automapper Configuration for all Known Assemblies
mappingConfig.AddRange( new List<Action<IConfiguration>>
{
   ConfigureProfilesInAssemblyOfType<Application.Administration.AutomapperProfile>,
   //...

I had to add ConfigureProfilesInAssemblyOfType<MyNewNamespace.AutomapperProfile>

Note that ConfigureProfilesInAssemblyOfType looks like this:

    private static void ConfigureProfilesInAssemblyOfType<T>( IConfiguration configuration )
    {
        var log = LogProvider.Get( typeof (AutomapperConfiguration) );

        // The Automapper Profile Type
        var automapperProfileType = typeof (Profile);

        // The Assembly containing the type
        var assembly = typeof (T).Assembly;
        log.Debug( "Scanning " + assembly.FullName );

        // Configure any Profile classes found in the assembly containing the type.
        assembly.GetTypes()
            .Where( automapperProfileType.IsAssignableFrom ).ToList()
            .ForEach( x =>
            {
                log.Debug( "Adding Profile '" + x.FullName + "'" );
                configuration.AddProfile( Activator.CreateInstance( x ) as Profile );
            } );
    }

Best regards, -Jeff

"Find next" in Vim

As discussed, there are several ways to search:

/pattern
?pattern
* (and g*, which I sometimes use in macros)
# (and g#)

plus, navigating prev/next with N and n.

You can also edit/recall your search history by pulling up the search prompt with / and then cycle with C-p/C-n. Even more useful is q/, which takes you to a window where you can navigate the search history.

Also for consideration is the all-important 'hlsearch' (type :hls to enable). This makes it much easier to find multiple instances of your pattern. You might even want make your matches extra bright with something like:

hi Search ctermfg=yellow ctermbg=red guifg=...

But then you might go crazy with constant yellow matches all over your screen. So you’ll often find yourself using :noh. This is so common that a mapping is in order:

nmap <leader>z :noh<CR>

I easily remember this one as z since I used to constantly type /zz<CR> (which is a fast-to-type uncommon occurrence) to clear my highlighting. But the :noh mapping is way better.

What's the difference between HTML 'hidden' and 'aria-hidden' attributes?

A hidden attribute is a boolean attribute (True/False). When this attribute is used on an element, it removes all relevance to that element. When a user views the html page, elements with the hidden attribute should not be visible.

Example:

    <p hidden>You can't see this</p>

Aria-hidden attributes indicate that the element and ALL of its descendants are still visible in the browser, but will be invisible to accessibility tools, such as screen readers.

Example:

    <p aria-hidden="true">You can't see this</p>

Take a look at this. It should answer all your questions.

Note: ARIA stands for Accessible Rich Internet Applications

Sources: Paciello Group

What does ellipsize mean in android?

Text:

 This is my first android application and
 I am trying to make a funny game,
 It seems android is really very easy to play.

Suppose above is your text and if you are using ellipsize's start attribute it will seen like this

This is my first android application and
...t seems android is really very easy to play.

with end attribute

 This is my first android application and
 I am trying to make a funny game,...

How to empty/destroy a session in rails?

To clear the whole thing use the reset_session method in a controller.

reset_session

Here's the documentation on this method: http://api.rubyonrails.org/classes/ActionController/Base.html#M000668

Resets the session by clearing out all the objects stored within and initializing a new session object.

Good luck!

What's the difference between Instant and LocalDateTime?

You are wrong about LocalDateTime: it does not store any time-zone information and it has nanosecond precision. Quoting the Javadoc (emphasis mine):

A date-time without a time-zone in the ISO-8601 calendar system, such as 2007-12-03T10:15:30.

LocalDateTime is an immutable date-time object that represents a date-time, often viewed as year-month-day-hour-minute-second. Other date and time fields, such as day-of-year, day-of-week and week-of-year, can also be accessed. Time is represented to nanosecond precision. For example, the value "2nd October 2007 at 13:45.30.123456789" can be stored in a LocalDateTime.

The difference between the two is that Instant represents an offset from the Epoch (01-01-1970) and, as such, represents a particular instant on the time-line. Two Instant objects created at the same moment in two different places of the Earth will have exactly the same value.

Find all tables containing column with specified name - MS SQL Server

SELECT  [TABLE_NAME] ,
        [INFORMATION_SCHEMA].COLUMNS.COLUMN_NAME
FROM    INFORMATION_SCHEMA.COLUMNS
WHERE   INFORMATION_SCHEMA.COLUMNS.COLUMN_NAME LIKE '%NAME%' ;

oracle sql: update if exists else insert

HC-way :)

DECLARE
  rt_mytable mytable%ROWTYPE;
  CURSOR update_mytable_cursor(p_rt_mytable IN mytable%ROWTYPE) IS
  SELECT *
  FROM   mytable
  WHERE  ID = p_rt_mytable.ID
  FOR UPDATE;
BEGIN
  rt_mytable.ID   := 1;
  rt_mytable.NAME := 'x';
  INSERT INTO mytable VALUES (rt_mytable);
EXCEPTION WHEN DUP_VAL_ON_INDEX THEN
  <<update_mytable>>
  FOR i IN update_mytable_cursor(rt_mytable) LOOP
    UPDATE mytable SET    
      NAME = p_rt_mytable.NAME
    WHERE CURRENT OF update_mytable_cursor;
  END LOOP update_mytable;
END;

best way to create object

Really depends on your requirement, although lately I have seen a trend for classes with at least one bare constructor defined.

The upside of posting your parameters in via constructor is that you know those values can be relied on after instantiation. The downside is that you'll need to put more work in with any library that expects to be able to create objects with a bare constructor.

My personal preference is to go with a bare constructor and set any properties as part of the declaration.

Person p=new Person()
{
   Name = "Han Solo",
   Age = 39
};

This gets around the "class lacks bare constructor" problem, plus reduces maintenance ( I can set more things without changing the constructor ).

What's the HTML to have a horizontal space between two objects?

You should put a padding in each object. For example, you want a space between images, you can use the following:

img{
   padding: 5px;
}

That means 5px paddin for ALL sides. Read more at http://www.w3schools.com/css/css_padding.asp. By the way, studying a lot before attempting to program will make things easier for you (and for us).

Pick images of root folder from sub-folder

You can reference the image using relative path:

<img src="../images/logo.png">
          __ ______ ________
          |    |       |
          |    |       |___ 3. Get the file named "logo.png"
          |    |
          |    |___ 2. Go inside "images/" subdirectory
          | 
          | 
          |____ 1. Go one level up

Or you can use absolute path: / means that this is an absolute path on the server, So if your server is at https://example.org/, referencing /images/logo.png from any page would point to https://example.org/images/logo.png

<img src="/images/logo.png">
          |______ ________
          |    |       |
          |    |       |___ 3. Get the file named "logo.png"
          |    |
          |    |___ 2. Go inside "images/" subdirectory
          | 
          | 
          |____ 1. Go to the root folder

PHP - Redirect and send data via POST

Yes, you can do this in PHP e.g. in

Silex or Symfony3

using subrequest

$postParams = array(
    'email' => $request->get('email'),
    'agree_terms' => $request->get('agree_terms'),
);

$subRequest = Request::create('/register', 'POST', $postParams);
return $app->handle($subRequest, HttpKernelInterface::SUB_REQUEST, false);

Generate GUID in MySQL for existing Data?

I had a need to add a guid primary key column in an existing table and populate it with unique GUID's and this update query with inner select worked for me:

UPDATE sri_issued_quiz SET quiz_id=(SELECT uuid());

So simple :-)

Spring Boot Java Config Set Session Timeout

  • Spring Boot version 1.0: server.session.timeout=1200
  • Spring Boot version 2.0: server.servlet.session.timeout=10m
    NOTE: If a duration suffix is not specified, seconds will be used.

What is the string length of a GUID?

22 bytes, if you do it like this:

System.Guid guid = System.Guid.NewGuid();
byte[] guidbytes = guid.ToByteArray();
string uuid = Convert.ToBase64String(guidbytes).Trim('=');

Media Queries: How to target desktop, tablet, and mobile?

If you want to target a device then just write min-device-width. For example:

For iPhone

@media only screen and (min-device-width: 480px){}

For tablets

@media only screen and (min-device-width: 768px){}

Here are some good articles:

Perl: Use s/ (replace) and return new string

If you have Perl 5.14 or greater, you can use the /r option with the substitution operator to perform non-destructive substitution:

print "bla: ", $myvar =~ s/a/b/r, "\n";

In earlier versions you can achieve the same using a do() block with a temporary lexical variable, e.g.:

print "bla: ", do { (my $tmp = $myvar) =~ s/a/b/; $tmp }, "\n";

Plot logarithmic axes with matplotlib in python

You can use the Axes.set_yscale method. That allows you to change the scale after the Axes object is created. That would also allow you to build a control to let the user pick the scale if you needed to.

The relevant line to add is:

ax.set_yscale('log')

You can use 'linear' to switch back to a linear scale. Here's what your code would look like:

import pylab
import matplotlib.pyplot as plt
a = [pow(10, i) for i in range(10)]
fig = plt.figure()
ax = fig.add_subplot(2, 1, 1)

line, = ax.plot(a, color='blue', lw=2)

ax.set_yscale('log')

pylab.show()

result chart

How to call a RESTful web service from Android?

Here is my Library That I have created for simple Webservice Calling,

You can use this by adding a one line gradle dependency -

compile 'com.scantity.ScHttpLibrary:ScHttpLibrary:1.0.0'

Here is the demonstration of using.

https://github.com/vishalchhodwani1992/httpLibrary

Static Initialization Blocks

static block is used for any technology to initialize static data member in dynamic way,or we can say for the dynamic initialization of static data member static block is being used..Because for non static data member initialization we have constructor but we do not have any place where we can dynamically initialize static data member

Eg:-class Solution{
         // static int x=10;
           static int x;
       static{
        try{
          x=System.out.println();
          }
         catch(Exception e){}
        }
       }

     class Solution1{
      public static void main(String a[]){
      System.out.println(Solution.x);
        }
        }

Now my static int x will initialize dynamically ..Bcoz when compiler will go to Solution.x it will load Solution Class and static block load at class loading time..So we can able to dynamically initialize that static data member..

}

What is log4j's default log file dumping path

To redirect your logs output to a file, you need to use the FileAppender and need to define other file details in your log4j.properties/xml file. Here is a sample properties file for the same:

# Root logger option
log4j.rootLogger=INFO, file

# Direct log messages to a log file
log4j.appender.file=org.apache.log4j.RollingFileAppender
log4j.appender.file.File=C:\\loging.log
log4j.appender.file.MaxFileSize=1MB
log4j.appender.file.MaxBackupIndex=1
log4j.appender.file.layout=org.apache.log4j.PatternLayout
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

Follow this tutorial to learn more about log4j usage:

http://www.mkyong.com/logging/log4j-log4j-properties-examples/

jQuery select change event get selected option

Delegated Alternative

In case anyone is using the delegated approach for their listener, use e.target (it will refer to the select element).

$('#myform').on('change', 'select', function (e) {
    var val = $(e.target).val();
    var text = $(e.target).find("option:selected").text(); //only time the find is required
    var name = $(e.target).attr('name');
}

JSFiddle Demo

Auto populate columns in one sheet from another sheet

I have used in Google Sheets

 ={sheetname!columnnamefrom:columnnameto}

Example:

  1. ={sheet1!A:A}
  2. ={sheet2!A4:A20}

Create a txt file using batch file in a specific folder

You can also use

cd %localhost%

to set the directory to the folder the batch file was opened from. Your script would look like this:

@echo off
cd %localhost%
echo .> dblank.txt

Make sure you set the directory before you use the command to create the text file.

What is the correct XPath for choosing attributes that contain "foo"?

If you also need to match the content of the link itself, use text():

//a[contains(@href,"/some_link")][text()="Click here"]

How prevent CPU usage 100% because of worker process in iis

If it is not necessary turn off 'Enable 32-bit Applications' from your respective application pool of your website.

This worked for me on my local machine

How to get response status code from jQuery.ajax?

Came across this old thread searching for a similar solution myself and found the accepted answer to be using .complete() method of jquery ajax. I quote the notice on jquery website here:

The jqXHR.success(), jqXHR.error(), and jqXHR.complete() callbacks are deprecated as of jQuery 1.8. To prepare your code for their eventual removal, use jqXHR.done(), jqXHR.fail(), and jqXHR.always() instead.

To know the status code of a ajax response, one can use the following code:

$.ajax( url [, settings ] )
.always(function (jqXHR) {
    console.log(jqXHR.status);
});

Works similarily for .done() and .fail()

How to get values from IGrouping

From definition of IGrouping :

IGrouping<out TKey, out TElement> : IEnumerable<TElement>, IEnumerable

you can just iterate through elements like this:

IEnumerable<IGrouping<int, smth>> groups = list.GroupBy(x => x.ID)
foreach(IEnumerable<smth> element in groups)
{
//do something
}

error: package javax.servlet does not exist

In my case, migrating a Spring 3.1 app up to 3.2.7, my solution was similar to Matthias's but a bit different -- thus why I'm documenting it here:

In my POM I found this dependency and changed it from 6.0 to 7.0:

    <dependency>
        <groupId>javax</groupId>
        <artifactId>javaee-web-api</artifactId>
        <version>7.0</version>
        <scope>provided</scope>
    </dependency>

Then later in the POM I upgraded this plugin from 6.0 to 7.0:

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <version>2.1</version>
            <executions>
                <execution>
                    ...
                    <configuration>
                        ...
                        <artifactItems>
                            <artifactItem>
                                <groupId>javax</groupId>
                                <artifactId>javaee-endorsed-api</artifactId>
                                <version>7.0</version>
                                <type>jar</type>
                            </artifactItem>
                        </artifactItems>
                    </configuration>
                </execution>
            </executions>
        </plugin>

How do I write dispatch_after GCD in Swift 3, 4, and 5?

A somewhat different flavour of the Accepted Answer.

Swift 4

DispatchQueue.main.asyncAfter(deadline: .now() + 0.1 + .milliseconds(500) + 
.microseconds(500) + .nanoseconds(1000)) {
                print("Delayed by 0.1 second + 500 milliseconds + 500 microseconds + 
                      1000 nanoseconds)")
 }

How to change TextBox's Background color?

It is txtName.BackColor = System.Drawing.Color.Red;

one can also use txtName.BackColor = Color.Aqua; which is the same as txtName.BackColor = System.Color.Aqua;

Only Problem with System.color is that it does not contain a definition for some basic colors especially white, which is important cause usually textboxes are white;

Neither user 10102 nor current process has android.permission.READ_PHONE_STATE

I was experiencing this problem on Samsung devices (fine on others). like zyamys suggested in his/her comment, I added the manifest.permission line but in addition to rather than instead of the original line, so:

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

I'm targeting API 22, so don't need to explicitly ask for permissions.

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

Everything is possible only if there is enough time to research :)

What I got to do is like having people that I iterate into a ui:repeat and display names and other fields in inputs. But one of fields was singleSelect - A and depending on it value update another input - B. even ui:repeat do not have id I put and it appeared in the DOM tree

<ui:repeat id="peopleRepeat"
value="#{myBean.people}"
var="person" varStatus="status">

Than the ids in the html were something like:

myForm:peopleRepeat:0:personType
myForm:peopleRepeat:1:personType

Than in the view I got one method like:

<p:ajax event="change"
listener="#{myBean.onPersonTypeChange(person, status.index)}"/>

And its implementation was in the bean like:

String componentId = "myForm:peopleRepeat" + idx + "personType";
PrimeFaces.current().ajax().update(componentId);

So this way I updated the element from the bean with no issues. PF version 6.2

Good luck and happy coding :)

Relative div height

add this to you CSS:

html, body
{
    height: 100%;
}

working Fiddle

when you say to wrap to be 100%, 100% of what? of its parent (body), so his parent has to have some height.

and the same goes for body, his parent his html. html parent his the viewport.. so, by setting them both to 100%, wrap can also have a percentage height.

also: the elements have some default padding/margin, that causes them to span a little more then the height you applied to them. (causing a scroll bar) you can use

*
{
    padding: 0;
    margin: 0;
}

to disable that.

Look at That Fiddle

Python; urllib error: AttributeError: 'bytes' object has no attribute 'read'

Try this:

jsonResponse = json.loads(response.decode('utf-8'))

How to get access to job parameters from ItemReader, in Spring Batch?

To be able to use the jobParameters I think you need to define your reader as scope 'step', but I am not sure if you can do it using annotations.

Using xml-config it would go like this:

<bean id="foo-readers" scope="step"
  class="...MyReader">
  <property name="fileName" value="#{jobExecutionContext['fileName']}" />
</bean>

See further at the Spring Batch documentation.

Perhaps it works by using @Scope and defining the step scope in your xml-config:

<bean class="org.springframework.batch.core.scope.StepScope" />

Why is my power operator (^) not working?

You actually have to use pow(number, power);. Unfortunately, carats don't work as a power sign in C. Many times, if you find yourself not being able to do something from another language, its because there is a diffetent function that does it for you.

How to read XML using XPath in Java

Expanding on the excellent answer by @bluish and @Yishai, here is how you make the NodeLists and node attributes support iterators, i.e. the for(Node n: nodelist) interface.

Use it like:

NodeList nl = ...
for(Node n : XmlUtil.asList(nl))
{...}

and

Node n = ...
for(Node attr : XmlUtil.asList(n.getAttributes())
{...}

The code:

/**
 * Converts NodeList to an iterable construct.
 * From: https://stackoverflow.com/a/19591302/779521
 */
public final class XmlUtil {
    private XmlUtil() {}

    public static List<Node> asList(NodeList n) {
        return n.getLength() == 0 ? Collections.<Node>emptyList() : new NodeListWrapper(n);
    }

    static final class NodeListWrapper extends AbstractList<Node> implements RandomAccess {
        private final NodeList list;

        NodeListWrapper(NodeList l) {
            this.list = l;
        }

        public Node get(int index) {
            return this.list.item(index);
        }

        public int size() {
            return this.list.getLength();
        }
    }

    public static List<Node> asList(NamedNodeMap n) {
        return n.getLength() == 0 ? Collections.<Node>emptyList() : new NodeMapWrapper(n);
    }

    static final class NodeMapWrapper extends AbstractList<Node> implements RandomAccess {
        private final NamedNodeMap list;

        NodeMapWrapper(NamedNodeMap l) {
            this.list = l;
        }

        public Node get(int index) {
            return this.list.item(index);
        }

        public int size() {
            return this.list.getLength();
        }
    }
}

Find a row in dataGridView based on column and value

Or you can use like this. This may be faster.

int iFindNo = 14;
int j = dataGridView1.Rows.Count-1;
int iRowIndex = -1;
for (int i = 0; i < Convert.ToInt32(dataGridView1.Rows.Count/2) +1; i++)
{
    if (Convert.ToInt32(dataGridView1.Rows[i].Cells[0].Value) == iFindNo)
    {
        iRowIndex = i;
        break;
    }
    if (Convert.ToInt32(dataGridView1.Rows[j].Cells[0].Value) == iFindNo)
    {
        iRowIndex = j;
        break;
    }
    j--;
}
if (iRowIndex != -1)
    MessageBox.Show("Index is " + iRowIndex.ToString());
else
    MessageBox.Show("Index not found." );

Best Practices for mapping one object to another

Efran Cobisi's suggestion of using an Auto Mapper is a good one. I have used Auto Mapper for a while and it worked well, until I found the much faster alternative, Mapster.

Given a large list or IEnumerable, Mapster outperforms Auto Mapper. I found a benchmark somewhere that showed Mapster being 6 times as fast, but I could not find it again. You could look it up and then, if it is suits you, use Mapster.

Wordpress keeps redirecting to install-php after migration

I tried all of these solutions before I realized that I had enabled opcache in PHP on my live environment. Wordpress was not reading a cached version of wp-config.

Working with UTF-8 encoding in Python source

Do not forget to verify if your text editor encodes properly your code in UTF-8.

Otherwise, you may have invisible characters that are not interpreted as UTF-8.

How to set background image of a view?

self.view.backgroundColor = [UIColor colorWithPatternImage:[UIImage imageNamed:@"imageName.png"]];

more info with example project

Javascript, Change google map marker color

To expand upon the accepted answer, you can create custom MarkerImages of any color using the API at http://chart.googleapis.com

In addition to changing color, this also changes marker shape, which may be unwanted.

const marker = new window.google.maps.Marker(
        position: markerPosition,
        title: markerTitle,
        map: map)
marker.addListener('click', () => marker.setIcon(changeIcon('00ff00'));)

const changeIcon = (newIconColor) => {
    const newIcon = new window.google.maps.MarkerImage(
        `http://chart.googleapis.com/chart?                                      
        chst=d_map_spin&chld=1.0|0|${newIconColor}|60|_|%E2%80%A2`,
        new window.google.maps.Size(21, 34),
        new window.google.maps.Point(0, 0),
        new window.google.maps.Point(10, 34),
        new window.google.maps.Size(21,34)
    );
    return newIcon
}

Source: free udacity course on google maps apis

Backup a single table with its data from a database in sql server 2008

There are many ways you can take back of table.

  1. BCP (BULK COPY PROGRAM)
  2. Generate Table Script with data
  3. Make a copy of table using SELECT INTO, example here
  4. SAVE Table Data Directly in a Flat file
  5. Export Data using SSIS to any destination

How to get the fragment instance from the FragmentActivity?

To get the fragment instance in a class that extends FragmentActivity:

MyclassFragment instanceFragment=
    (MyclassFragment)getSupportFragmentManager().findFragmentById(R.id.idFragment);

To get the fragment instance in a class that extends Fragment:

MyclassFragment instanceFragment =  
    (MyclassFragment)getFragmentManager().findFragmentById(R.id.idFragment);

Fastest way to determine if record exists

EXISTS (or NOT EXISTS) is specially designed for checking if something exists and therefore should be (and is) the best option. It will halt on the first row that matches so it does not require a TOP clause and it does not actually select any data so there is no overhead in size of columns. You can safely use SELECT * here - no different than SELECT 1, SELECT NULL or SELECT AnyColumn... (you can even use an invalid expression like SELECT 1/0 and it will not break).

IF EXISTS (SELECT * FROM Products WHERE id = ?)
BEGIN
--do what you need if exists
END
ELSE
BEGIN
--do what needs to be done if not
END

Display date in dd/mm/yyyy format in vb.net

Dim formattedDate As String = Date.Today.ToString("dd/MM/yyyy")

Check link below

Spacing between elements

Use a margin to space around an element.

.box {
        margin: top right bottom left;
 }

.box {
        margin: 10px 5px 10px 5px;
}

This adds space outside of the element. So background colours, borders etc will not be included.

If you want to add spacing within an element use padding instead. It can be called in the same way as above.

Check if an element is a child of a parent

.has() seems to be designed for this purpose. Since it returns a jQuery object, you have to test for .length as well:

if ($('div#hello').has(target).length) {
   alert('Target is a child of #hello');
}

Python 3: UnboundLocalError: local variable referenced before assignment

This is because, even though Var1 exists, you're also using an assignment statement on the name Var1 inside of the function (Var1 -= 1 at the bottom line). Naturally, this creates a variable inside the function's scope called Var1 (truthfully, a -= or += will only update (reassign) an existing variable, but for reasons unknown (likely consistency in this context), Python treats it as an assignment). The Python interpreter sees this at module load time and decides (correctly so) that the global scope's Var1 should not be used inside the local scope, which leads to a problem when you try to reference the variable before it is locally assigned.

Using global variables, outside of necessity, is usually frowned upon by Python developers, because it leads to confusing and problematic code. However, if you'd like to use them to accomplish what your code is implying, you can simply add:

global Var1, Var2

inside the top of your function. This will tell Python that you don't intend to define a Var1 or Var2 variable inside the function's local scope. The Python interpreter sees this at module load time and decides (correctly so) to look up any references to the aforementioned variables in the global scope.

Some Resources

  • the Python website has a great explanation for this common issue.
  • Python 3 offers a related nonlocal statement - check that out as well.

Cross-reference (named anchor) in markdown

I will quickly complement for cases where the header contains emojis, in that case it is simpler to just remove the emoji in the link of the reference. For example

# ? Title 2
....
[Take me to title 2](#-title-2)

There are some cases where this does not work for a weird reason, for example here in setup. The solution in that case is to include the whole code for the emoji as well.

"Submit is not a function" error in JavaScript

Solution for me was to set the "form" attribute of button

<form id="form_id_name"><button name="btnSubmit" form="form_id_name" /></form>

or is js:

YOURFORMOBJ.getElementsByTagName("button")[0].setAttribute("form", "form_id_name");
YOURFORMOBJ.submit();

How can I hash a password in Java?

You could use Spring Security Crypto (has only 2 optional compile dependencies), which supports PBKDF2, BCrypt, SCrypt and Argon2 password encryption.

Argon2PasswordEncoder argon2PasswordEncoder = new Argon2PasswordEncoder();
String aCryptedPassword = argon2PasswordEncoder.encode("password");
boolean passwordIsValid = argon2PasswordEncoder.matches("password", aCryptedPassword);
SCryptPasswordEncoder sCryptPasswordEncoder = new SCryptPasswordEncoder();
String sCryptedPassword = sCryptPasswordEncoder.encode("password");
boolean passwordIsValid = sCryptPasswordEncoder.matches("password", sCryptedPassword);
BCryptPasswordEncoder bCryptPasswordEncoder = new BCryptPasswordEncoder();
String bCryptedPassword = bCryptPasswordEncoder.encode("password");
boolean passwordIsValid = bCryptPasswordEncoder.matches("password", bCryptedPassword);
Pbkdf2PasswordEncoder pbkdf2PasswordEncoder = new Pbkdf2PasswordEncoder();
String pbkdf2CryptedPassword = pbkdf2PasswordEncoder.encode("password");
boolean passwordIsValid = pbkdf2PasswordEncoder.matches("password", pbkdf2CryptedPassword);

Angular - res.json() is not a function

HttpClient.get() applies res.json() automatically and returns Observable<HttpResponse<string>>. You no longer need to call this function yourself.

See Difference between HTTP and HTTPClient in angular 4?

Issue with background color and Google Chrome

Ok guys, I found a solution, . It's not great but does the trick with no side effects.

The HTML:

<span id="chromeFix"></span> 

(put this below the body tags)

The CSS:

#chromeFix { display: block; position: absolute; width: 1px; height: 100%; top: 0px; left: 0px; }

What this does to solve the issue:

It forces Chrome to think the page's content is 100% when it's not - this stops the body 'appearing' the size of the content and resolves the missing background bug. This is basically doing what height: 100% does when applied to the body or html but you don't get the side effect of having your backgrounds cut off when scrolling (past 100% page height) like you do with a 100% height on those elements.

I can sleep now =]

Inline style to act as :hover in CSS

A simple solution:

   <a href="#" onmouseover="this.style.color='orange';" onmouseout="this.style.color='';">My Link</a>

Or

<script>
 /** Change the style **/
 function overStyle(object){
    object.style.color = 'orange';
    // Change some other properties ...
 }

 /** Restores the style **/
 function outStyle(object){
    object.style.color = 'orange';
    // Restore the rest ...
 }
</script>

<a href="#" onmouseover="overStyle(this)" onmouseout="outStyle(this)">My Link</a>

Most recent previous business day in Python

Why don't you try something like:

lastBusDay = datetime.datetime.today()
if datetime.date.weekday(lastBusDay) not in range(0,5):
    lastBusDay = 5

How to know whether refresh button or browser back button is clicked in Firefox

var keyCode = evt.keyCode;
if (keyCode==8)
alert('you pressed backspace');

if(keyCode==116)
alert('you pressed f5 to reload page')

Selecting multiple columns with linq query and lambda expression

        Object AccountObject = _dbContext.Accounts
                                   .Join(_dbContext.Users, acc => acc.AccountId, usr => usr.AccountId, (acc, usr) => new { acc, usr })
                                   .Where(x => x.usr.EmailAddress == key1)
                                   .Where(x => x.usr.Hash == key2)
                                   .Select(x => new { AccountId = x.acc.AccountId, Name = x.acc.Name })
                                   .SingleOrDefault();

What does this error mean: "error: expected specifier-qualifier-list before 'type_name'"?

this error basically comes when you use the object before using it.

Selenium WebDriver can't find element by link text

Use xpath and text()

driver.findElement(By.Xpath("//strong[contains(text(),'" + service +"')]"));

Scikit-learn: How to obtain True Positive, True Negative, False Positive and False Negative

In the scikit-learn 'metrics' library there is a confusion_matrix method which gives you the desired output.

You can use any classifier that you want. Here I used the KNeighbors as example.

from sklearn import metrics, neighbors

clf = neighbors.KNeighborsClassifier()

X_test = ...
y_test = ...

expected = y_test
predicted = clf.predict(X_test)

conf_matrix = metrics.confusion_matrix(expected, predicted)

>>> print conf_matrix
>>>  [[1403   87]
     [  56 3159]]

The docs: http://scikit-learn.org/stable/modules/generated/sklearn.metrics.confusion_matrix.html#sklearn.metrics.confusion_matrix

Android Studio - Importing external Library/Jar

"simple solution is here"

1 .Create a folder named libs under the app directory for that matter any directory within the project..

2 .Copy Paste your Library to libs folder

3.You simply copy the JAR to your libs/ directory and then from inside Android Studio, right click the Jar that shows up under libs/ > Add As Library..

Peace!

Omit rows containing specific column of NA

Try this:

cc=is.na(DF$y)
m=which(cc==c("TRUE"))
DF=DF[-m,]

OpenCV & Python - Image too big to display

Although I was expecting an automatic solution (fitting to the screen automatically), resizing solves the problem as well.

import cv2
cv2.namedWindow("output", cv2.WINDOW_NORMAL)        # Create window with freedom of dimensions
im = cv2.imread("earth.jpg")                        # Read image
imS = cv2.resize(im, (960, 540))                    # Resize image
cv2.imshow("output", imS)                            # Show image
cv2.waitKey(0)                                      # Display the image infinitely until any keypress

Place a button right aligned

If the button is the only element on the block:

_x000D_
_x000D_
.border {_x000D_
  border: 2px blue dashed;_x000D_
}_x000D_
_x000D_
.mr-0 {_x000D_
  margin-right: 0;_x000D_
}_x000D_
.ml-auto {_x000D_
  margin-left:auto;_x000D_
}_x000D_
.d-block {_x000D_
  display:block;_x000D_
}
_x000D_
<p class="border">_x000D_
  <input type="button" class="d-block mr-0 ml-auto" value="The Button">_x000D_
</p>
_x000D_
_x000D_
_x000D_

If there are other elements on the block:

_x000D_
_x000D_
.border {_x000D_
  border: 2px indigo dashed;_x000D_
}_x000D_
_x000D_
.d-table {_x000D_
  display:table;_x000D_
}_x000D_
_x000D_
.d-table-cell {_x000D_
  display:table-cell;_x000D_
}_x000D_
_x000D_
.w-100 {_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
.tar {_x000D_
  text-align: right;_x000D_
}
_x000D_
<div class="border d-table w-100">_x000D_
  <p class="d-table-cell">The paragraph.....lorem ipsum...etc.</p>_x000D_
  <div class="d-table-cell tar">_x000D_
    <button >The Button</button>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

With flex-box:

_x000D_
_x000D_
.flex-box {_x000D_
  display:flex;_x000D_
  justify-content:space-between;_x000D_
  outline: 2px dashed blue;_x000D_
}_x000D_
_x000D_
.flex-box-2 {_x000D_
  display:flex;_x000D_
  justify-content: flex-end;_x000D_
  outline: 2px deeppink dashed;_x000D_
}
_x000D_
<h1>Button with Text</h1>_x000D_
<div class="flex-box">_x000D_
<p>Once upon a time in a ...</p>_x000D_
<button>Read More...</button>_x000D_
</div>_x000D_
_x000D_
<h1>Only Button</h1>_x000D_
<div class="flex-box-2">_x000D_
  <button>The Button</button>_x000D_
</div>_x000D_
_x000D_
<h1>Multiple Buttons</h1>_x000D_
<div class="flex-box-2">_x000D_
  <button>Button 1</button>_x000D_
  <button>Button 2</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Good Luck...

Difference between Relative path and absolute path in javascript

Going Relative:

  • You could download a self-contained directory (maybe a zipped file) and open links from an html or xml locally without need to reach the server. This increases speed performance significantly, specially if you have to deal with a slow network.

Going Absolute:

  • You would have to swallow the network speed, but in terms of security you could prevent certain users to see certain files or increase network traffic if (and only if...) that is good for you.

Scripting Language vs Programming Language

All scripting languages are programming languages.

Languages are not classed as script or not - it entirely depends on the execution environment.

If the environment is one that is interpreted, this is commonly referred to as a scripting environment.

Python string class like StringBuilder in C#?

Python has several things that fulfill similar purposes:

  • One common way to build large strings from pieces is to grow a list of strings and join it when you are done. This is a frequently-used Python idiom.
    • To build strings incorporating data with formatting, you would do the formatting separately.
  • For insertion and deletion at a character level, you would keep a list of length-one strings. (To make this from a string, you'd call list(your_string). You could also use a UserString.MutableString for this.
  • (c)StringIO.StringIO is useful for things that would otherwise take a file, but less so for general string building.

How can I move all the files from one folder to another using the command line?

use move then move <file or folder> <destination directory>

Why I am getting Cannot pass parameter 2 by reference error when I am using bindParam with a constant value?

I had the same problem and I found this solution working with bindParam :

    bindParam(':param', $myvar = NULL, PDO::PARAM_INT);

"No cached version... available for offline mode."

Please follow below steps :

1.Open Your project.

2.Go to the Left side of the Gradle button.

3.Look at below image.

enter image description here

4.Click button above image show.

5.if this type of view you are not in offline mode.

6.Go to Build and rebuild the project.

All above point is work for me.

open() in Python does not create a file if it doesn't exist

'''
w  write mode
r  read mode
a  append mode

w+  create file if it doesn't exist and open it in write mode
r+  open for reading and writing. Does not create file.
a+  create file if it doesn't exist and open it in append mode
'''

example:

file_name = 'my_file.txt'
f = open(file_name, 'w+')  # open file in write mode
f.write('python rules')
f.close()

I hope this helps. [FYI am using python version 3.6.2]

Warning: mysqli_query() expects parameter 1 to be mysqli, null given in

use global scope on your $con and put it inside your getPosts() function like so.

function getPosts() {
global $con;
$query = mysqli_query($con,"SELECT * FROM Blog");
while($row = mysqli_fetch_array($query))
    {
        echo "<div class=\"blogsnippet\">";
        echo "<h4>" . $row['Title'] . "</h4>" . $row['SubHeading'];
        echo "</div>";
    }
}

No mapping found for HTTP request with URI Spring MVC

I have the same problem.... I change my project name and i have this problem...my solution was the checking project refences and use / in my web.xml (instead of /*)

How do I send a JSON string in a POST request in Go

In addition to standard net/http package, you can consider using my GoRequest which wraps around net/http and make your life easier without thinking too much about json or struct. But you can also mix and match both of them in one request! (you can see more details about it in gorequest github page)

So, in the end your code will become like follow:

func main() {
    url := "http://restapi3.apiary.io/notes"
    fmt.Println("URL:>", url)
    request := gorequest.New()
    titleList := []string{"title1", "title2", "title3"}
    for _, title := range titleList {
        resp, body, errs := request.Post(url).
            Set("X-Custom-Header", "myvalue").
            Send(`{"title":"` + title + `"}`).
            End()
        if errs != nil {
            fmt.Println(errs)
            os.Exit(1)
        }
        fmt.Println("response Status:", resp.Status)
        fmt.Println("response Headers:", resp.Header)
        fmt.Println("response Body:", body)
    }
}

This depends on how you want to achieve. I made this library because I have the same problem with you and I want code that is shorter, easy to use with json, and more maintainable in my codebase and production system.

What's the difference between a method and a function?

Historically, there may have been a subtle difference with a "method" being something which does not return a value, and a "function" one which does.Each language has its own lexicon of terms with special meaning.

In "C", the word "function" means a program routine.

In Java, the term "function" does not have any special meaning. Whereas "method" means one of the routines that forms the implementation of a class.

In C# that would translate as:

public void DoSomething() {} // method
public int DoSomethingAndReturnMeANumber(){} // function

But really, I re-iterate that there is really no difference in the 2 concepts. If you use the term "function" in informal discussions about Java, people will assume you meant "method" and carry on. Don't use it in proper documents or presentations about Java, or you will look silly.

iPhone hide Navigation Bar only on first page

I would put the code in the viewWillAppear delegate on each view being shown:

Like this where you need to hide it:

- (void)viewWillAppear:(BOOL)animated
{
        [yourObject hideBar];
}

Like this where you need to show it:

- (void)viewWillAppear:(BOOL)animated
{
        [yourObject showBar];
}

How to conditional format based on multiple specific text in Excel

You can use MATCH for instance.

  1. Select the column from the first cell, for example cell A2 to cell A100 and insert a conditional formatting, using 'New Rule...' and the option to conditional format based on a formula.

  2. In the entry box, put:

    =MATCH(A2, 'Sheet2'!A:A, 0)
    
  3. Pick the desired formatting (change the font to red or fill the cell background, etc) and click OK.

MATCH takes the value A2 from your data table, looks into 'Sheet2'!A:A and if there's an exact match (that's why there's a 0 at the end), then it'll return the row number.

Note: Conditional formatting based on conditions from other sheets is available only on Excel 2010 onwards. If you're working on an earlier version, you might want to get the list of 'Don't check' in the same sheet.

EDIT: As per new information, you will have to use some reverse matching. Instead of the above formula, try:

=SUM(IFERROR(SEARCH('Sheet2'!$A$1:$A$44, A2),0))

How can I get my Android device country code without using GPS?

You can simply use this code,

TelephonyManager tm = (TelephonyManager)this.getSystemService(Context.TELEPHONY_SERVICE);
String countryCodeValue = tm.getNetworkCountryIso();

This will return 'US' if your current connected network is in the United States. This works without a SIM card even.

Make child visible outside an overflow:hidden parent

This is an old question but encountered it myself.

I have semi-solutions that work situational for the former question("Children visible in overflow:hidden parent")

If the parent div does not need to be position:relative, simply set the children styles to visibility:visible.

If the parent div does need to be position:relative, the only way possible I found to show the children was position:fixed. This worked for me in my situation luckily enough but I would imagine it wouldn't work in others.

Here is a crappy example just post into a html file to view.

<div style="background: #ff00ff; overflow: hidden; width: 500px; height: 500px; position: relative;">
    <div style="background: #ff0000;position: fixed; top: 10px; left: 10px;">asd
        <div style="background: #00ffff; width: 200px; overflow: visible; position: absolute; visibility: visible; clear:both; height: 1000px; top: 100px; left: 10px;"> a</div>
    </div>
</div>

Invoking a PHP script from a MySQL trigger

I was thinking about this exact issue for a case with long polling where I didn't want the php script to have to continually poll the db. Polling would need to be done somewhere, memory would probably be best. So if somehow the trigger could put the info into something like memcache, then php could poll that would would be much less intensive overall. Just need a method for mysql to use memcache. Perhaps into a predefined variable with a specific user id. Once the data is retrieved php could reset the var until the db sets it again. Not sure about timing issues though. Perhaps a second variable to store the previous key selected.

How to check if a file exists in Ansible?

I find it can be annoying and error prone to do a lot of these .stat.exists type checks. For example they require extra care to get check mode (--check) working.

Many answers here suggest

  • get and register
  • apply when register expression is true

However, sometimes this is a code smell so always look for better ways to use Ansible, specifically there are many advantages to using the correct module. e.g.

- name: install ntpdate
  package:
    name: ntpdate

or

- file:
    path: /etc/file.txt
    owner: root
    group: root
    mode: 0644

But when it is not possible use one module, also investigate if you can register and check the result of a previous task. e.g.

# jmeter_version: 4.0 
- name: Download Jmeter archive
  get_url:
    url: "http://archive.apache.org/dist/jmeter/binaries/apache-jmeter-{{ jmeter_version }}.tgz"
    dest: "/opt/jmeter/apache-jmeter-{{ jmeter_version }}.tgz"
    checksum: sha512:eee7d68bd1f7e7b269fabaf8f09821697165518b112a979a25c5f128c4de8ca6ad12d3b20cd9380a2b53ca52762b4c4979e564a8c2ff37196692fbd217f1e343
  register: download_result

- name: Extract apache-jmeter
  unarchive:
    src: "/opt/jmeter/apache-jmeter-{{ jmeter_version }}.tgz"
    dest: "/opt/jmeter/"
    remote_src: yes
    creates: "/opt/jmeter/apache-jmeter-{{ jmeter_version }}"
  when: download_result.state == 'file'

Note the when: but also the creates: so --check doesn't error out

I mention this because often these less-than-ideal practices come in pairs i.e. no apt/yum package so we have to 1) download and 2) unzip

Hope this helps

Configure nginx with multiple locations with different root folders on subdomain

You need to use the alias directive for location /static:

server {

  index index.html;
  server_name test.example.com;

  root /web/test.example.com/www;

  location /static/ {
    alias /web/test.example.com/static/;
  }

}

The nginx wiki explains the difference between root and alias better than I can:

Note that it may look similar to the root directive at first sight, but the document root doesn't change, just the file system path used for the request. The location part of the request is dropped in the request Nginx issues.

Note that root and alias handle trailing slashes differently.

tell pip to install the dependencies of packages listed in a requirement file

Extending Piotr's answer, if you also need a way to figure what to put in requirements.in, you can first use pip-chill to find the minimal set of required packages you have. By combining these tools, you can show the dependency reason why each package is installed. The full cycle looks like this:

  1. Create virtual environment:
    $ python3 -m venv venv
  2. Activate it:
    $ . venv/bin/activate
  3. Install newest version of pip, pip-tools and pip-chill:
    (venv)$ pip install --upgrade pip
    (venv)$ pip install pip-tools pip-chill
  4. Build your project, install more pip packages, etc, until you want to save...
  5. Extract minimal set of packages (ie, top-level without dependencies):
    (venv)$ pip-chill --no-version > requirements.in
  6. Compile list of all required packages (showing dependency reasons):
    (venv)$ pip-compile requirements.in
  7. Make sure the current installation is synchronized with the list:
    (venv)$ pip-sync

MySQL Cannot drop index needed in a foreign key constraint

I think this is easy way to drop the index.

set FOREIGN_KEY_CHECKS=0; //disable checks

ALTER TABLE mytable DROP INDEX AID;

set FOREIGN_KEY_CHECKS=1; //enable checks

Failed to execute goal org.apache.maven.plugins:maven-compiler-plugin:2.3.2:compile (default-compile)

Actually, if you do not want to delete your local .m2/repository/... and you are have a downloaded copy of Maven from Apache, you can have Eclipse /STS use that external Maven and you can edit the {maven}\conf\settings.xml to point your localRepository to a new empty location.

<localRepository>C:\java\repository</localRepository>

Of course, you will have a new repository with all of the maven source downloads in addition to your previous .m2 location.

enter image description here

Is there a way to 'pretty' print MongoDB shell output to a file?

Just put the commands you want to run into a file, then pass it to the shell along with the database name and redirect the output to a file. So, if your find command is in find.js and your database is foo, it would look like this:

./mongo foo find.js >> out.json

Verify External Script Is Loaded

This was very simple now that I realize how to do it, thanks to all the answers for leading me to the solution. I had to abandon $.getScript() in order to specify the source of the script...sometimes doing things manually is best.

Solution

//great suggestion @Jasper
var len = $('script[src*="Javascript/MyScript.js"]').length; 

if (len === 0) {
        alert('script not loaded');

        loadScript('Javascript/MyScript.js');

        if ($('script[src*="Javascript/MyScript.js"]').length === 0) {
            alert('still not loaded');
        }
        else {
            alert('loaded now');
        }
    }
    else {
        alert('script loaded');
    }


function loadScript(scriptLocationAndName) {
    var head = document.getElementsByTagName('head')[0];
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = scriptLocationAndName;
    head.appendChild(script);
}

Can someone explain __all__ in Python?

It's a list of public objects of that module, as interpreted by import *. It overrides the default of hiding everything that begins with an underscore.

How to create streams from string in Node.Js?

There's a module for that: https://www.npmjs.com/package/string-to-stream

var str = require('string-to-stream')
str('hi there').pipe(process.stdout) // => 'hi there' 

How can I perform static code analysis in PHP?

See Semantic Designs' CloneDR, a "clone detection" tool that finds copy/paste/edited code.

It will find exact and near miss code fragments, in spite of white space, comments and even variable renamings. A sample detection report for PHP can be found at the website. (I'm the author.)

Is there a program to decompile Delphi?

Languages like Delphi, C and C++ Compile to processor-native machine code, and the output executables have little or no metadata in them. This is in contrast with Java or .Net, which compile to object-oriented platform-independent bytecode, which retains the names of methods, method parameters, classes and namespaces, and other metadata.

So there is a lot less useful decompiling that can be done on Delphi or C code. However, Delphi typically has embedded form data for any form in the project (generated by the $R *.dfm line), and it also has metadata on all published properties, so a Delphi-specific tool would be able to extract this information.

Flutter.io Android License Status Unknown

I found this solution.I download JDK 8.Then I add downloading jdk file path name of JAVA_HOME into user variables in environment variable.

How to clear/remove observable bindings in Knockout.js?

I have found that if the view model contains many div bindings the best way to clear the ko.applyBindings(new someModelView); is to use: ko.cleanNode($("body")[0]); This allows you to call a new ko.applyBindings(new someModelView2); dynamically without the worry of the previous view model still being binded.

MySQL "CREATE TABLE IF NOT EXISTS" -> Error 1050

As already stated, it's a warning not an error, but (if like me) you want things to run without warnings, you can disable that warning, then re-enable it again when you're done.

SET sql_notes = 0;      -- Temporarily disable the "Table already exists" warning
CREATE TABLE IF NOT EXISTS ...
SET sql_notes = 1;      -- And then re-enable the warning again

How can I set multiple CSS styles in JavaScript?

@Mircea: It is very much easy to set the multiple styles for an element in a single statement. It doesn't effect the existing properties and avoids the complexity of going for loops or plugins.

document.getElementById("demo").setAttribute(
   "style", "font-size: 100px; font-style: italic; color:#ff0000;");

BE CAREFUL: If, later on, you use this method to add or alter style properties, the previous properties set using 'setAttribute' will be erased.

How To Define a JPA Repository Query with a Join

You are experiencing this issue for two reasons.

  • The JPQL Query is not valid.
  • You have not created an association between your entities that the underlying JPQL query can utilize.

When performing a join in JPQL you must ensure that an underlying association between the entities attempting to be joined exists. In your example, you are missing an association between the User and Area entities. In order to create this association we must add an Area field within the User class and establish the appropriate JPA Mapping. I have attached the source for User below. (Please note I moved the mappings to the fields)

User.java

@Entity
@Table(name="user")
public class User {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="iduser")
    private Long idUser;

    @Column(name="user_name")
    private String userName;

    @OneToOne()
    @JoinColumn(name="idarea")
    private Area area;

    public Long getIdUser() {
        return idUser;
    }

    public void setIdUser(Long idUser) {
        this.idUser = idUser;
    }

    public String getUserName() {
        return userName;
    }

    public void setUserName(String userName) {
        this.userName = userName;
    }

    public Area getArea() {
        return area;
    }

    public void setArea(Area area) {
        this.area = area;
    }
}

Once this relationship is established you can reference the area object in your @Query declaration. The query specified in your @Query annotation must follow proper syntax, which means you should omit the on clause. See the following:

@Query("select u.userName from User u inner join u.area ar where ar.idArea = :idArea")

While looking over your question I also made the relationship between the User and Area entities bidirectional. Here is the source for the Area entity to establish the bidirectional relationship.

Area.java

@Entity
@Table(name = "area")
public class Area {

    @Id
    @GeneratedValue(strategy=GenerationType.AUTO)
    @Column(name="idarea")
    private Long idArea;

    @Column(name="area_name")
    private String areaName;

    @OneToOne(fetch=FetchType.LAZY, mappedBy="area")
    private User user;

    public Long getIdArea() {
        return idArea;
    }

    public void setIdArea(Long idArea) {
        this.idArea = idArea;
    }

    public String getAreaName() {
        return areaName;
    }

    public void setAreaName(String areaName) {
        this.areaName = areaName;
    }

    public User getUser() {
        return user;
    }

    public void setUser(User user) {
        this.user = user;
    }
}

Output a NULL cell value in Excel

I've been frustrated by this problem as well. Find/Replace can be helpful though, because if you don't put anything in the "replace" field it will replace with an -actual- NULL. So the steps would be something along the lines of:

1: Place some unique string in your formula in place of the NULL output (i like to use a password-like string)

2: Run your formula

3: Open Find/Replace, and fill in the unique string as the search value. Leave "replace with" blank

4: Replace All

Obviously, this has limitations. It only works when the context allows you to do a find/replace, so for more dynamic formulas this won't help much. But, I figured I'd put it up here anyway.

cursor.fetchall() vs list(cursor) in Python

A (MySQLdb/PyMySQL-specific) difference worth noting when using a DictCursor is that list(cursor) will always give you a list, while cursor.fetchall() gives you a list unless the result set is empty, in which case it gives you an empty tuple. This was the case in MySQLdb and remains the case in the newer PyMySQL, where it will not be fixed for backwards-compatibility reasons. While this isn't a violation of Python Database API Specification, it's still surprising and can easily lead to a type error caused by wrongly assuming that the result is a list, rather than just a sequence.

Given the above, I suggest always favouring list(cursor) over cursor.fetchall(), to avoid ever getting caught out by a mysterious type error in the edge case where your result set is empty.

What are the differences between NP, NP-Complete and NP-Hard?

In addition to the other great answers, here is the typical schema people use to show the difference between NP, NP-Complete, and NP-Hard:

enter image description here

How to prevent null values inside a Map and null fields inside a bean from getting serialized through Jackson

my solution, hope help
custom ObjectMapper and config to spring xml(register message conveters)

public class PyResponseConfigObjectMapper extends ObjectMapper {
public PyResponseConfigObjectMapper() {
    disable(SerializationFeature.WRITE_NULL_MAP_VALUES); //map no_null
    setSerializationInclusion(JsonInclude.Include.NON_NULL); // bean no_null
}

}

How to sum the values of a JavaScript object?

I came across this solution from @jbabey while trying to solve a similar problem. With a little modification, I got it right. In my case, the object keys are numbers (489) and strings ("489"). Hence to solve this, each key is parse. The following code works:

var array = {"nR": 22, "nH": 7, "totB": "2761", "nSR": 16, "htRb": "91981"}
var parskey = 0;
for (var key in array) {
    parskey = parseInt(array[key]);
    sum += parskey;
};
return(sum);

How do I apply a CSS class to Html.ActionLink in ASP.NET MVC?

deleted the c#... here is the vb.net

<%=Html.ActionLink("Home", "Index", "Home", New With {.class = "tab"}, Nothing)%>

How do I change the number of open files limit in Linux?

If you are using Linux and you got the permission error, you will need to raise the allowed limit in the /etc/limits.conf or /etc/security/limits.conf file (where the file is located depends on your specific Linux distribution).

For example to allow anyone on the machine to raise their number of open files up to 10000 add the line to the limits.conf file.

* hard nofile 10000

Then logout and relogin to your system and you should be able to do:

ulimit -n 10000

without a permission error.

how to convert long date value to mm/dd/yyyy format

Refer Below code which give the date in String form.

import java.text.SimpleDateFormat;
import java.util.Date;



public class Test{

    public static void main(String[] args) {
        long val = 1346524199000l;
        Date date=new Date(val);
        SimpleDateFormat df2 = new SimpleDateFormat("dd/MM/yy");
        String dateText = df2.format(date);
        System.out.println(dateText);
    }
}

Putting -moz-available and -webkit-fill-available in one width (css property)

I needed my ASP.NET drop down list to take up all available space, and this is all I put in the CSS and it is working in Firefox and IE11:

width: 100%

I had to add the CSS class into the asp:DropDownList element

Callback function for JSONP with jQuery AJAX

delete this line:

jsonp: 'jsonp_callback',

Or replace this line:

url: 'http://url.of.my.server/submit?callback=json_callback',

because currently you are asking jQuery to create a random callback function name with callback=? and then telling jQuery that you want to use jsonp_callback instead.

Accessing session from TWIG template

{{app.session}} refers to the Session object and not the $_SESSION array. I don't think the $_SESSION array is accessible unless you explicitly pass it to every Twig template or if you do an extension that makes it available.

Symfony2 is object-oriented, so you should use the Session object to set session attributes and not rely on the array. The Session object will abstract this stuff away from you so it is easier to, say, store the session in a database because storing the session variable is hidden from you.

So, set your attribute in the session and retrieve the value in your twig template by using the Session object.

// In a controller
$session = $this->get('session');
$session->set('filter', array(
    'accounts' => 'value',
));

// In Twig
{% set filter = app.session.get('filter') %}
{% set account-filter = filter['accounts'] %}

Hope this helps.

Regards,
Matt

Bootstrap: Open Another Modal in Modal

Modals in Modal:

_x000D_
_x000D_
$('.modal-child').on('show.bs.modal', function () {_x000D_
    var modalParent = $(this).attr('data-modal-parent');_x000D_
    $(modalParent).css('opacity', 0);_x000D_
});_x000D_
 _x000D_
$('.modal-child').on('hidden.bs.modal', function () {_x000D_
    var modalParent = $(this).attr('data-modal-parent');_x000D_
    $(modalParent).css('opacity', 1);_x000D_
});
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js"></script>_x000D_
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>_x000D_
_x000D_
<a href="#myModal" role="button" class="btn btn-primary" data-toggle="modal">Modals in Modal</a>_x000D_
_x000D_
_x000D_
<div id="myModal" class="modal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">_x000D_
    <div class="modal-dialog">_x000D_
        <!-- Modal content-->_x000D_
        <div class="modal-content">_x000D_
            <div class="modal-header">_x000D_
             _x000D_
                <button type="button" class="close" data-dismiss="modal">&times;</button>_x000D_
                <h4 class="modal-title">Modal Header</h4>_x000D_
            </div>_x000D_
            <div class="modal-body">_x000D_
                <a href="#myModal1" role="button" class="btn btn-primary" data-toggle="modal">Launch other modal 1</a>_x000D_
                <a href="#myModal2" role="button" class="btn btn-primary" data-toggle="modal">Launch other modal 2</a>_x000D_
            </div>_x000D_
_x000D_
        </div>_x000D_
    </div>_x000D_
</div>_x000D_
_x000D_
<div id="myModal1" class="modal modal-child" data-backdrop-limit="1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-modal-parent="#myModal">_x000D_
    <div class="modal-dialog">_x000D_
        <!-- Modal content-->_x000D_
        <div class="modal-content">_x000D_
            <div class="modal-header">_x000D_
                <button type="button" class="close" data-dismiss="modal">&times;</button>_x000D_
                <h4 class="modal-title">Modal Header 1</h4>_x000D_
            </div>_x000D_
            <div class="modal-body">_x000D_
                <p>Two modal body…1</p>_x000D_
            </div>_x000D_
            <div class="modal-footer">_x000D_
                <button class="btn btn-default" data-dismiss="modal" data-dismiss="modal" aria-hidden="true">Cancel</button>_x000D_
            </div>_x000D_
_x000D_
        </div>_x000D_
    </div>_x000D_
</div>_x000D_
_x000D_
<div id="myModal2" class="modal modal-child" data-backdrop-limit="1" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true" data-modal-parent="#myModal">_x000D_
    <div class="modal-dialog">_x000D_
        <!-- Modal content-->_x000D_
        <div class="modal-content">_x000D_
            <div class="modal-header">_x000D_
                _x000D_
                <button type="button" class="close" data-dismiss="modal">&times;</button>_x000D_
                <h4 class="modal-title">Modal Header 2</h4>_x000D_
            </div>_x000D_
            <div class="modal-body">_x000D_
                <p>Modal body…2</p>_x000D_
            </div>_x000D_
            <div class="modal-footer">_x000D_
                <button class="btn btn-default" data-dismiss="modal" data-dismiss="modal" aria-hidden="true">Cancel</button>_x000D_
            </div>_x000D_
_x000D_
        </div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to disable/enable a button with a checkbox if checked

brbcoding have been able to help me with the appropriate coding i needed, here is it

HTML

<input type="checkbox" id="checkme"/>
  <input type="submit" name="sendNewSms" class="inputButton" disabled="disabled" id="sendNewSms" value=" Send " />

Javascript

 var checker = document.getElementById('checkme');
 var sendbtn = document.getElementById('sendNewSms');
 // when unchecked or checked, run the function
 checker.onchange = function(){
if(this.checked){
    sendbtn.disabled = false;
} else {
    sendbtn.disabled = true;
}

}

What is the difference between <p> and <div>?

DIV is a generic block level container that can contain any other block or inline elements, including other DIV elements, whereas P is to wrap paragraphs (text).

Creating a random string with A-Z and 0-9 in Java

You can easily do that with a for loop,

public static void main(String[] args) {
  String aToZ="ABCD.....1234"; // 36 letter.
  String randomStr=generateRandom(aToZ);

}

private static String generateRandom(String aToZ) {
    Random rand=new Random();
    StringBuilder res=new StringBuilder();
    for (int i = 0; i < 17; i++) {
       int randIndex=rand.nextInt(aToZ.length()); 
       res.append(aToZ.charAt(randIndex));            
    }
    return res.toString();
}

Cancel a vanilla ECMAScript 6 Promise chain

@Michael Yagudaev 's answer works for me.

But the original answer did not chain the wrapped promise with .catch() to handle reject handling, here is my improvement on top of @Michael Yagudaev's answer:

const makeCancelablePromise = promise => {
  let hasCanceled = false;
  const wrappedPromise = new Promise((resolve, reject) => {
    promise
      .then(val => (hasCanceled ? reject({ isCanceled: true }) : resolve(val)))
      .catch(
        error => (hasCanceled ? reject({ isCanceled: true }) : reject(error))
      );
  });

  return {
    promise: wrappedPromise,
    cancel() {
      hasCanceled = true;
    }
  };
};

// Example Usage:
const cancelablePromise = makeCancelable(
  new Promise((rs, rj) => {
    /*do something*/
  })
);
cancelablePromise.promise.then(() => console.log('resolved')).catch(err => {
  if (err.isCanceled) {
    console.log('Wrapped promise canceled');
    return;
  }
  console.log('Promise was not canceled but rejected due to errors: ', err);
});
cancelablePromise.cancel();

How to style a checkbox using CSS

Quick fix to add icon in front of text:

< asp:CheckBox... Text="< img src='/link/to/img.png' />My Text" />

How to get the separate digits of an int number?

Try this:

int num= 4321
int first  =  num % 10;
int second =  ( num - first ) % 100 / 10;
int third  =  ( num - first - second ) % 1000 / 100;
int fourth =  ( num - first - second - third ) % 10000 / 1000;

You will get first = 1, second = 2, third = 3 and fourth = 4 ....

Python NameError: name is not defined

Define the class before you use it:

class Something:
    def out(self):
        print("it works")

s = Something()
s.out()

You need to pass self as the first argument to all instance methods.

Efficient way to return a std::vector in c++

As nice as "return by value" might be, it's the kind of code that can lead one into error. Consider the following program:

    #include <string>
    #include <vector>
    #include <iostream>
    using namespace std;
    static std::vector<std::string> strings;
    std::vector<std::string> vecFunc(void) { return strings; };
    int main(int argc, char * argv[]){
      // set up the vector of strings to hold however
      // many strings the user provides on the command line
      for(int idx=1; (idx<argc); ++idx){
         strings.push_back(argv[idx]);
      }

      // now, iterate the strings and print them using the vector function
      // as accessor
      for(std::vector<std::string>::interator idx=vecFunc().begin(); (idx!=vecFunc().end()); ++idx){
         cout << "Addr: " << idx->c_str() << std::endl;
         cout << "Val:  " << *idx << std::endl;
      }
    return 0;
    };
  • Q: What will happen when the above is executed? A: A coredump.
  • Q: Why didn't the compiler catch the mistake? A: Because the program is syntactically, although not semantically, correct.
  • Q: What happens if you modify vecFunc() to return a reference? A: The program runs to completion and produces the expected result.
  • Q: What is the difference? A: The compiler does not have to create and manage anonymous objects. The programmer has instructed the compiler to use exactly one object for the iterator and for endpoint determination, rather than two different objects as the broken example does.

The above erroneous program will indicate no errors even if one uses the GNU g++ reporting options -Wall -Wextra -Weffc++

If you must produce a value, then the following would work in place of calling vecFunc() twice:

   std::vector<std::string> lclvec(vecFunc());
   for(std::vector<std::string>::iterator idx=lclvec.begin(); (idx!=lclvec.end()); ++idx)...

The above also produces no anonymous objects during iteration of the loop, but requires a possible copy operation (which, as some note, might be optimized away under some circumstances. But the reference method guarantees that no copy will be produced. Believing the compiler will perform RVO is no substitute for trying to build the most efficient code you can. If you can moot the need for the compiler to do RVO, you are ahead of the game.

Difference between -XX:+UseParallelGC and -XX:+UseParNewGC

After a lot of searching, the best explanation I've found is from Java Performance Tuning website in Question of the month: 1.4.1 Garbage collection algorithms, January 29th, 2003

Young generation garbage collection algorithms

The (original) copying collector (Enabled by default). When this collector kicks in, all application threads are stopped, and the copying collection proceeds using one thread (which means only one CPU even if on a multi-CPU machine). This is known as a stop-the-world collection, because basically the JVM pauses everything else until the collection is completed.

The parallel copying collector (Enabled using -XX:+UseParNewGC). Like the original copying collector, this is a stop-the-world collector. However this collector parallelizes the copying collection over multiple threads, which is more efficient than the original single-thread copying collector for multi-CPU machines (though not for single-CPU machines). This algorithm potentially speeds up young generation collection by a factor equal to the number of CPUs available, when compared to the original singly-threaded copying collector.

The parallel scavenge collector (Enabled using -XX:UseParallelGC). This is like the previous parallel copying collector, but the algorithm is tuned for gigabyte heaps (over 10GB) on multi-CPU machines. This collection algorithm is designed to maximize throughput while minimizing pauses. It has an optional adaptive tuning policy which will automatically resize heap spaces. If you use this collector, you can only use the the original mark-sweep collector in the old generation (i.e. the newer old generation concurrent collector cannot work with this young generation collector).

From this information, it seems the main difference (apart from CMS cooperation) is that UseParallelGC supports ergonomics while UseParNewGC doesn't.

How to identify a strong vs weak relationship on ERD?

The relationship Room to Class is considered weak (non-identifying) because the primary key components CID and DATE of entity Class doesn't contain the primary key RID of entity Room (in this case primary key of Room entity is a single component, but even if it was a composite key, one component of it also fulfills the condition).

However, for instance, in the case of the relationship Class and Class_Ins we see that is a strong (identifying) relationship because the primary key components EmpID and CID and DATE of Class_Ins contains a component of the primary key Class (in this case it contains both components CID and DATE).

How to access the SMS storage on Android?

Do the following, download SQLLite Database Browser from here:

Locate your db. file in your phone.

Then, as soon you install the program go to: "Browse Data", you will see all the SMS there!!

You can actually export the data to an excel file or SQL.

How do you kill a Thread in Java?

Generally you don't kill, stop, or interrupt a thread (or check wheter it is interrupted()), but let it terminate naturally.

It is simple. You can use any loop together with (volatile) boolean variable inside run() method to control thread's activity. You can also return from active thread to the main thread to stop it.

This way you gracefully kill a thread :) .

When to create variables (memory management)

Well, the JVM memory model works something like this: values are stored on one pile of memory stack and objects are stored on another pile of memory called the heap. The garbage collector looks for garbage by looking at a list of objects you've made and seeing which ones aren't pointed at by anything. This is where setting an object to null comes in; all nonprimitive (think of classes) variables are really references that point to the object on the stack, so by setting the reference you have to null the garbage collector can see that there's nothing else pointing at the object and it can decide to garbage collect it. All Java objects are stored on the heap so they can be seen and collected by the garbage collector.

Nonprimitive (ints, chars, doubles, those sort of things) values, however, aren't stored on the heap. They're created and stored temporarily as they're needed and there's not much you can do there, but thankfully the compilers nowadays are really efficient and will avoid needed to store them on the JVM stack unless they absolutely need to.

On a bytecode level, that's basically how it works. The JVM is based on a stack-based machine, with a couple instructions to create allocate objects on the heap as well, and a ton of instructions to manipulate, push and pop values, off the stack. Local variables are stored on the stack, allocated variables on the heap.* These are the heap and the stack I'm referring to above. Here's a pretty good starting point if you want to get into the nitty gritty details.

In the resulting compiled code, there's a bit of leeway in terms of implementing the heap and stack. Allocation's implemented as allocation, there's really not a way around doing so. Thus the virtual machine heap becomes an actual heap, and allocations in the bytecode are allocations in actual memory. But you can get around using a stack to some extent, since instead of storing the values on a stack (and accessing a ton of memory), you can stored them on registers on the CPU which can be up to a hundred times (maybe even a thousand) faster than storing it on memory. But there's cases where this isn't possible (look up register spilling for one example of when this may happen), and using a stack to implement a stack kind of makes a lot of sense.

And quite frankly in your case a few integers probably won't matter. The compiler will probably optimize them out by itself in this case anyways. Optimization should always happen after you get it running and notice it's a tad slower than you'd prefer it to be. Worry about making simple, elegant, working code first then later make it fast (and hopefully) simple, elegant, working code.

Java's actually very nicely made so that you shouldn't have to worry about nulling variables very often. Whenever you stop needing to use something, it will usually incidentally be disappearing from the scope of your program (and thus becoming eligible for garbage collection). So I guess the real lesson here is to use local variables as often as you can.

*There's also a constant pool, a local variable pool, and a couple other things in memory but you have close to no control over the size of those things and I want to keep this fairly simple.

Is there a Newline constant defined in Java like Environment.Newline in C#?

Be aware that this property isn't as useful as many people think it is. Just because your app is running on a Windows machine, for example, doesn't mean the file it's reading will be using Windows-style line separators. Many web pages contain a mixture of "\n" and "\r\n", having been cobbled together from disparate sources. When you're reading text as a series of logical lines, you should always look for all three of the major line-separator styles: Windows ("\r\n"), Unix/Linux/OSX ("\n") and pre-OSX Mac ("\r").

When you're writing text, you should be more concerned with how the file will be used than what platform you're running on. For example, if you expect people to read the file in Windows Notepad, you should use "\r\n" because it only recognizes the one kind of separator.

How can I get date in application run by node.js?

NodeJS (and newer browsers) have a nice shortcut to get the current time in milliseconds.

var timeInMss = Date.now()

Which has a performance boost compared with

var timeInMss = new Date().getTime()

Because you do not need to create a new object.

what's the correct way to send a file from REST web service to client?

Change the machine address from localhost to IP address you want your client to connect with to call below mentioned service.

Client to call REST webservice:

package in.india.client.downloadfiledemo;

import java.io.BufferedInputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.IOException;

import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response.Status;

import com.sun.jersey.api.client.Client;
import com.sun.jersey.api.client.ClientHandlerException;
import com.sun.jersey.api.client.ClientResponse;
import com.sun.jersey.api.client.UniformInterfaceException;
import com.sun.jersey.api.client.WebResource;
import com.sun.jersey.multipart.BodyPart;
import com.sun.jersey.multipart.MultiPart;

public class DownloadFileClient {

    private static final String BASE_URI = "http://localhost:8080/DownloadFileDemo/services/downloadfile";

    public DownloadFileClient() {

        try {
            Client client = Client.create();
            WebResource objWebResource = client.resource(BASE_URI);
            ClientResponse response = objWebResource.path("/")
                    .type(MediaType.TEXT_HTML).get(ClientResponse.class);

            System.out.println("response : " + response);
            if (response.getStatus() == Status.OK.getStatusCode()
                    && response.hasEntity()) {
                MultiPart objMultiPart = response.getEntity(MultiPart.class);
                java.util.List<BodyPart> listBodyPart = objMultiPart
                        .getBodyParts();
                BodyPart filenameBodyPart = listBodyPart.get(0);
                BodyPart fileLengthBodyPart = listBodyPart.get(1);
                BodyPart fileBodyPart = listBodyPart.get(2);

                String filename = filenameBodyPart.getEntityAs(String.class);
                String fileLength = fileLengthBodyPart
                        .getEntityAs(String.class);
                File streamedFile = fileBodyPart.getEntityAs(File.class);

                BufferedInputStream objBufferedInputStream = new BufferedInputStream(
                        new FileInputStream(streamedFile));

                byte[] bytes = new byte[objBufferedInputStream.available()];

                objBufferedInputStream.read(bytes);

                String outFileName = "D:/"
                        + filename;
                System.out.println("File name is : " + filename
                        + " and length is : " + fileLength);
                FileOutputStream objFileOutputStream = new FileOutputStream(
                        outFileName);
                objFileOutputStream.write(bytes);
                objFileOutputStream.close();
                objBufferedInputStream.close();
                File receivedFile = new File(outFileName);
                System.out.print("Is the file size is same? :\t");
                System.out.println(Long.parseLong(fileLength) == receivedFile
                        .length());
            }
        } catch (UniformInterfaceException e) {
            e.printStackTrace();
        } catch (ClientHandlerException e) {
            e.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }

    public static void main(String... args) {
        new DownloadFileClient();
    }
}

Service to response client:

package in.india.service.downloadfiledemo;

import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.Produces;
import javax.ws.rs.core.MediaType;
import javax.ws.rs.core.Response;

import com.sun.jersey.multipart.MultiPart;

@Path("downloadfile")
@Produces("multipart/mixed")
public class DownloadFileResource {

    @GET
    public Response getFile() {

        java.io.File objFile = new java.io.File(
                "D:/DanGilbert_2004-480p-en.mp4");
        MultiPart objMultiPart = new MultiPart();
        objMultiPart.type(new MediaType("multipart", "mixed"));
        objMultiPart
                .bodyPart(objFile.getName(), new MediaType("text", "plain"));
        objMultiPart.bodyPart("" + objFile.length(), new MediaType("text",
                "plain"));
        objMultiPart.bodyPart(objFile, new MediaType("multipart", "mixed"));

        return Response.ok(objMultiPart).build();

    }
}

JAR needed:

jersey-bundle-1.14.jar
jersey-multipart-1.14.jar
mimepull.jar

WEB.XML:

<?xml version="1.0" encoding="UTF-8"?>
<web-app xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance"
    xmlns="http://java.sun.com/xml/ns/javaee" xmlns:web="http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    xsi:schemaLocation="http://java.sun.com/xml/ns/javaee http://java.sun.com/xml/ns/javaee/web-app_2_5.xsd"
    id="WebApp_ID" version="2.5">
    <display-name>DownloadFileDemo</display-name>
    <servlet>
        <display-name>JAX-RS REST Servlet</display-name>
        <servlet-name>JAX-RS REST Servlet</servlet-name>
        <servlet-class>com.sun.jersey.spi.container.servlet.ServletContainer</servlet-class>
        <init-param>
             <param-name>com.sun.jersey.config.property.packages</param-name> 
             <param-value>in.india.service.downloadfiledemo</param-value>
        </init-param>
        <load-on-startup>1</load-on-startup>
    </servlet>
    <servlet-mapping>
        <servlet-name>JAX-RS REST Servlet</servlet-name>
        <url-pattern>/services/*</url-pattern>
    </servlet-mapping>
    <welcome-file-list>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>
</web-app>

Django - after login, redirect user to his custom page --> mysite.com/username

If you're using Django's built-in LoginView, it takes next as context, which is "The URL to redirect to after successful login. This may contain a query string, too." (see docs)

Also from the docs:

"If login is successful, the view redirects to the URL specified in next. If next isn’t provided, it redirects to settings.LOGIN_REDIRECT_URL (which defaults to /accounts/profile/)."

Example code:

urls.py

from django.urls import path
from django.contrib.auth import views as auth_views

from account.forms import LoginForm # optional form to pass to view


urlpatterns = [
    ...

    # --------------- login url/view -------------------
    path('account/login/', auth_views.LoginView.as_view(
        template_name='login.html',  
        authentication_form=LoginForm, 
        extra_context={ 

            # option 1: provide full path
            'next': '/account/my_custom_url/', 

            # option 2: just provide the name of the url
            # 'next': 'custom_url_name',  
        },
    ), name='login'),

    ...
]

login.html

...

<form method="post" action="{% url 'login' %}">

  ...

  {# option 1 #}
  <input type="hidden" name="next" value="{{ next }}">

  {# option 2 #}
  {# <input type="hidden" name="next" value="{% url next %}"> #}

</form>

jQuery: get the file name selected from <input type="file" />

The simplest way is to simply use the following line of jquery, using this you don't get the /fakepath nonsense, you straight up get the file that was uploaded:

$('input[type=file]')[0].files[0]; // This gets the file
$('#idOfFileUpload')[0].files[0]; // This gets the file with the specified id

Some other useful commands are:

To get the name of the file:

$('input[type=file]')[0].files[0].name; // This gets the file name

To get the type of the file:

If I were to upload a PNG, it would return image/png

$("#imgUpload")[0].files[0].type

To get the size (in bytes) of the file:

$("#imgUpload")[0].files[0].size

Also you don't have to use these commands on('change', you can get the values at any time, for instance you may have a file upload and when the user clicks upload, you simply use the commands I listed.

Why do we use volatile keyword?

Consider this code,

int some_int = 100;

while(some_int == 100)
{
   //your code
}

When this program gets compiled, the compiler may optimize this code, if it finds that the program never ever makes any attempt to change the value of some_int, so it may be tempted to optimize the while loop by changing it from while(some_int == 100) to something which is equivalent to while(true) so that the execution could be fast (since the condition in while loop appears to be true always). (if the compiler doesn't optimize it, then it has to fetch the value of some_int and compare it with 100, in each iteration which obviously is a little bit slow.)

However, sometimes, optimization (of some parts of your program) may be undesirable, because it may be that someone else is changing the value of some_int from outside the program which compiler is not aware of, since it can't see it; but it's how you've designed it. In that case, compiler's optimization would not produce the desired result!

So, to ensure the desired result, you need to somehow stop the compiler from optimizing the while loop. That is where the volatile keyword plays its role. All you need to do is this,

volatile int some_int = 100; //note the 'volatile' qualifier now!

In other words, I would explain this as follows:

volatile tells the compiler that,

"Hey compiler, I'm volatile and, you know, I can be changed by some XYZ that you're not even aware of. That XYZ could be anything. Maybe some alien outside this planet called program. Maybe some lightning, some form of interrupt, volcanoes, etc can mutate me. Maybe. You never know who is going to change me! So O you ignorant, stop playing an all-knowing god, and don't dare touch the code where I'm present. Okay?"

Well, that is how volatile prevents the compiler from optimizing code. Now search the web to see some sample examples.


Quoting from the C++ Standard ($7.1.5.1/8)

[..] volatile is a hint to the implementation to avoid aggressive optimization involving the object because the value of the object might be changed by means undetectable by an implementation.[...]

Related topic:

Does making a struct volatile make all its members volatile?

Could not find main class HelloWorld

JAVA_HOME is not necessary if you start java and javac from the command line. But JAVA_HOME should point to the real jdk directory, C:\Program Files\Java\jdk1.7.0 in your case.

I'd never use the CLASSPATH environment variable outside of build scripts, especially not global defined. The -cp flag is better. But in your case, as you do not need additional libraries (rt.jardoesn't count), you won't need a classpath declaration. A missing -cp is equivalent to a -cp . and that's what you need here)

The HelloWorld class needs to be declared as public. This actually may be the cause for your problems. (I was pretty sure, that a source file needs one public class... or was it one public class at most ?)

Set default time in bootstrap-datetimepicker

i tried to set default time for a picker and it worked:

$('#date2').datetimepicker({
 format: 'DD-MM-YYYY 12:00:00'
});

this will save in database as : 2015-03-01 12:00:00

used for smalldatetime type in sql server

Rest-assured. Is it possible to extract value from request json?

There are several ways. I personally use the following ones:

extracting single value:

String user_Id =
given().
when().
then().
extract().
        path("user_id");

work with the entire response when you need more than one:

Response response =
given().
when().
then().
extract().
        response();

String userId = response.path("user_id");

extract one using the JsonPath to get the right type:

long userId =
given().
when().
then().
extract().
        jsonPath().getLong("user_id");

Last one is really useful when you want to match against the value and the type i.e.

assertThat(
    when().
    then().
    extract().
            jsonPath().getLong("user_id"), equalTo(USER_ID)
);

The rest-assured documentation is quite descriptive and full. There are many ways to achieve what you are asking: https://github.com/jayway/rest-assured/wiki/Usage

Sum one number to every element in a list (or array) in Python

if you want to operate with list of numbers it is better to use NumPy arrays:

import numpy
a = [1, 1, 1 ,1, 1]
ar = numpy.array(a)
print ar + 2

gives

[3, 3, 3, 3, 3]

Class 'DOMDocument' not found

I'm using Centos and the followings worked for me , I run this command

yum --enablerepo remi install php-xml

And restarted the Apache with this command

sudo service httpd restart

Hibernate: "Field 'id' doesn't have a default value"

Please check whether the Default value for the column id in particular table.if not make it as default

Can scrapy be used to scrape dynamic content from websites that are using AJAX?

I was using a custom downloader middleware, but wasn't very happy with it, as I didn't manage to make the cache work with it.

A better approach was to implement a custom download handler.

There is a working example here. It looks like this:

# encoding: utf-8
from __future__ import unicode_literals

from scrapy import signals
from scrapy.signalmanager import SignalManager
from scrapy.responsetypes import responsetypes
from scrapy.xlib.pydispatch import dispatcher
from selenium import webdriver
from six.moves import queue
from twisted.internet import defer, threads
from twisted.python.failure import Failure


class PhantomJSDownloadHandler(object):

    def __init__(self, settings):
        self.options = settings.get('PHANTOMJS_OPTIONS', {})

        max_run = settings.get('PHANTOMJS_MAXRUN', 10)
        self.sem = defer.DeferredSemaphore(max_run)
        self.queue = queue.LifoQueue(max_run)

        SignalManager(dispatcher.Any).connect(self._close, signal=signals.spider_closed)

    def download_request(self, request, spider):
        """use semaphore to guard a phantomjs pool"""
        return self.sem.run(self._wait_request, request, spider)

    def _wait_request(self, request, spider):
        try:
            driver = self.queue.get_nowait()
        except queue.Empty:
            driver = webdriver.PhantomJS(**self.options)

        driver.get(request.url)
        # ghostdriver won't response when switch window until page is loaded
        dfd = threads.deferToThread(lambda: driver.switch_to.window(driver.current_window_handle))
        dfd.addCallback(self._response, driver, spider)
        return dfd

    def _response(self, _, driver, spider):
        body = driver.execute_script("return document.documentElement.innerHTML")
        if body.startswith("<head></head>"):  # cannot access response header in Selenium
            body = driver.execute_script("return document.documentElement.textContent")
        url = driver.current_url
        respcls = responsetypes.from_args(url=url, body=body[:100].encode('utf8'))
        resp = respcls(url=url, body=body, encoding="utf-8")

        response_failed = getattr(spider, "response_failed", None)
        if response_failed and callable(response_failed) and response_failed(resp, driver):
            driver.close()
            return defer.fail(Failure())
        else:
            self.queue.put(driver)
            return defer.succeed(resp)

    def _close(self):
        while not self.queue.empty():
            driver = self.queue.get_nowait()
            driver.close()

Suppose your scraper is called "scraper". If you put the mentioned code inside a file called handlers.py on the root of the "scraper" folder, then you could add to your settings.py:

DOWNLOAD_HANDLERS = {
    'http': 'scraper.handlers.PhantomJSDownloadHandler',
    'https': 'scraper.handlers.PhantomJSDownloadHandler',
}

And voilà, the JS parsed DOM, with scrapy cache, retries, etc.

Java HTTPS client certificate authentication

I've connected to bank with two-way SSL (client and server certificate) with Spring Boot. So describe here all my steps, hope it helps someone (simplest working solution, I've found):

  1. Generate sertificate request:

    • Generate private key:

      openssl genrsa -des3 -passout pass:MY_PASSWORD -out user.key 2048
      
    • Generate certificate request:

      openssl req -new -key user.key -out user.csr -passin pass:MY_PASSWORD
      

    Keep user.key (and password) and send certificate request user.csr to bank for my sertificate

  2. Receive 2 certificate: my client root certificate clientId.crt and bank root certificate: bank.crt

  3. Create Java keystore (enter key password and set keystore password):

    openssl pkcs12 -export -in clientId.crt -inkey user.key -out keystore.p12 -name clientId -CAfile ca.crt -caname root
    

    Don't pay attention on output: unable to write 'random state'. Java PKCS12 keystore.p12 created.

  4. Add into keystore bank.crt (for simplicity I've used one keystore):

    keytool -import -alias banktestca -file banktestca.crt -keystore keystore.p12 -storepass javaops
    

    Check keystore certificates by:

    keytool -list -keystore keystore.p12
    
  5. Ready for Java code:) I've used Spring Boot RestTemplate with add org.apache.httpcomponents.httpcore dependency:

    @Bean("sslRestTemplate")
    public RestTemplate sslRestTemplate() throws Exception {
      char[] storePassword = appProperties.getSslStorePassword().toCharArray();
      URL keyStore = new URL(appProperties.getSslStore());
    
      SSLContext sslContext = new SSLContextBuilder()
            .loadTrustMaterial(keyStore, storePassword)
      // use storePassword twice (with key password do not work)!!
            .loadKeyMaterial(keyStore, storePassword, storePassword) 
            .build();
    
      // Solve "Certificate doesn't match any of the subject alternative names"
      SSLConnectionSocketFactory socketFactory = new SSLConnectionSocketFactory(sslContext, NoopHostnameVerifier.INSTANCE);
    
      CloseableHttpClient client = HttpClients.custom().setSSLSocketFactory(socketFactory).build();
      HttpComponentsClientHttpRequestFactory factory = new HttpComponentsClientHttpRequestFactory(client);
      RestTemplate restTemplate = new RestTemplate(factory);
      // restTemplate.setMessageConverters(List.of(new Jaxb2RootElementHttpMessageConverter()));
      return restTemplate;
    }
    

Unicode character for "X" cancel / close?

&times; and font-family: Garamond, "Apple Garamond"; make it good enough. Garamond font is thin and web safe

proper close X

Vertically centering Bootstrap modal window

This works in BS3, not tested in v2. It centers the modal vertically. Note that it will transition there - if you want it to just appear in position edit CSS transition property for .modal-dialog

centerModal = function() {
    var $dialog = $(this).find(".modal-dialog"),
        offset = ($(window).height() - $dialog.height()) / 2;

    // Center modal vertically in window
    $dialog.css({
        'transform': 'translateY(' + offset + 'px) !important',
    });
};

$('.modal').on('shown.bs.modal', centerModal);
$(window).on("resize", function() {
    $('.modal').each(centerModal);
});

Android ListView headers

What I did to make the Date (e.g December 01, 2016) as header. I used the StickyHeaderListView library

https://github.com/emilsjolander/StickyListHeaders

Convert the date to long in millis [do not include the time] and make it as the header Id.

@Override
public long getHeaderId(int position) {
    return <date in millis>;
}

Get query from java.sql.PreparedStatement

I would assume it's possible to place a proxy between the DB and your app then observe the communication. I'm not familiar with what software you would use to do this.

How to vertically align elements in a div?

My trick is to put inside the div a table with 1 row and 1 column, set 100% of width and height, and the property vertical-align:middle.

<div>

    <table style="width:100%; height:100%;">
        <tr>
            <td style="vertical-align:middle;">
                BUTTON TEXT
            </td>
        </tr>
    </table>

</div>

Fiddle: http://jsfiddle.net/joan16v/sbqjnn9q/

How do I use a C# Class Library in a project?

  1. Add a reference to your library
  2. Import the namespace
  3. Consume the types in your library

How to decode viewstate

This is somewhat "native" .NET way of converting ViewState from string into StateBag Code is below:

public static StateBag LoadViewState(string viewState)
    {
        System.Web.UI.Page converterPage = new System.Web.UI.Page();
        HiddenFieldPageStatePersister persister = new HiddenFieldPageStatePersister(new Page());
        Type utilClass = typeof(System.Web.UI.BaseParser).Assembly.GetType("System.Web.UI.Util");
        if (utilClass != null && persister != null)
        {
            MethodInfo method = utilClass.GetMethod("DeserializeWithAssert", BindingFlags.NonPublic | BindingFlags.Static);
            if (method != null)
            {
                PropertyInfo formatterProperty = persister.GetType().GetProperty("StateFormatter", BindingFlags.NonPublic | BindingFlags.Instance);
                if (formatterProperty != null)
                {
                    IStateFormatter formatter = (IStateFormatter)formatterProperty.GetValue(persister, null);
                    if (formatter != null)
                    {
                        FieldInfo pageField = formatter.GetType().GetField("_page", BindingFlags.NonPublic | BindingFlags.Instance);
                        if (pageField != null)
                        {
                            pageField.SetValue(formatter, null);
                            try
                            {
                                Pair pair = (Pair)method.Invoke(null, new object[] { formatter, viewState });
                                if (pair != null)
                                {
                                    MethodInfo loadViewState = converterPage.GetType().GetMethod("LoadViewStateRecursive", BindingFlags.Instance | BindingFlags.NonPublic);
                                    if (loadViewState != null)
                                    {
                                        FieldInfo postback = converterPage.GetType().GetField("_isCrossPagePostBack", BindingFlags.NonPublic | BindingFlags.Instance);
                                        if (postback != null)
                                        {
                                            postback.SetValue(converterPage, true);
                                        }
                                        FieldInfo namevalue = converterPage.GetType().GetField("_requestValueCollection", BindingFlags.NonPublic | BindingFlags.Instance);
                                        if (namevalue != null)
                                        {
                                            namevalue.SetValue(converterPage, new NameValueCollection());
                                        }
                                        loadViewState.Invoke(converterPage, new object[] { ((Pair)((Pair)pair.First).Second) });
                                        FieldInfo viewStateField = typeof(Control).GetField("_viewState", BindingFlags.NonPublic | BindingFlags.Instance);
                                        if (viewStateField != null)
                                        {
                                            return (StateBag)viewStateField.GetValue(converterPage);
                                        }
                                    }
                                }
                            }
                            catch (Exception ex)
                            {
                                if (ex != null)
                                {

                                }
                            }
                        }
                    }
                }
            }
        }
        return null;
    }

show all tags in git log

Note about tag of tag (tagging a tag), which is at the origin of your issue, as Charles Bailey correctly pointed out in the comment:

Make sure you study this thread, as overriding a signed tag is not as easy:

  • if you already pushed a tag, the git tag man page seriously advised against a simple git tag -f B to replace a tag name "A"
  • don't try to recreate a signed tag with git tag -f (see the thread extract below)

    (it is about a corner case, but quite instructive about tags in general, and it comes from another SO contributor Jakub Narebski):

Please note that the name of tag (heavyweight tag, i.e. tag object) is stored in two places:

  • in the tag object itself as a contents of 'tag' header (you can see it in output of "git show <tag>" and also in output of "git cat-file -p <tag>", where <tag> is heavyweight tag, e.g. v1.6.3 in git.git repository),
  • and also is default name of tag reference (reference in "refs/tags/*" namespace) pointing to a tag object.
    Note that the tag reference (appropriate reference in the "refs/tags/*" namespace) is purely local matter; what one repository has in 'refs/tags/v0.1.3', other can have in 'refs/tags/sub/v0.1.3' for example.

So when you create signed tag 'A', you have the following situation (assuming that it points at some commit)

  35805ce   <--- 5b7b4ead  <=== refs/tags/A
  (commit)       tag A
                 (tag)

Please also note that "git tag -f A A" (notice the absence of options forcing it to be an annotated tag) is a noop - it doesn't change the situation.

If you do "git tag -f -s A A": note that you force owerwriting a tag (so git assumes that you know what you are doing), and that one of -s / -a / -m options is used to force annotated tag (creation of tag object), you will get the following situation

  35805ce   <--- 5b7b4ea  <--- ada8ddc  <=== refs/tags/A
  (commit)       tag A         tag A
                 (tag)         (tag)

Note also that "git show A" would show the whole chain down to the non-tag object...

In PHP how can you clear a WSDL cache?

if you already deployed the code or can't change any configuration, you could remove all temp files from wsdl:

rm /tmp/wsdl-*

Convert Base64 string to an image file?

if($_SERVER['REQUEST_METHOD']=='POST'){
$image_no="5";//or Anything You Need
$image = $_POST['image'];
$path = "uploads/".$image_no.".png";

$status = file_put_contents($path,base64_decode($image));
if($status){
 echo "Successfully Uploaded";
}else{
 echo "Upload failed";
}
}

Creating a generic method in C#

I like to start with a class like this class settings { public int X {get;set;} public string Y { get; set; } // repeat as necessary

 public settings()
 {
    this.X = defaultForX;
    this.Y = defaultForY;
    // repeat ...
 }
 public void Parse(Uri uri)
 {
    // parse values from query string.
    // if you need to distinguish from default vs. specified, add an appropriate property

 }

This has worked well on 100's of projects. You can use one of the many other parsing solutions to parse values.

PowerShell : retrieve JSON object by field value

Hows about this:

$json=Get-Content -Raw -Path 'my.json' | Out-String | ConvertFrom-Json
$foo="TheVariableYourUsingToSelectSomething"
$json.SomePathYouKnow.psobject.properties.Where({$_.name -eq $foo}).value

which would select from json structured

{"SomePathYouKnow":{"TheVariableYourUsingToSelectSomething": "Tada!"}

This is based on this accessing values in powershell SO question . Isn't powershell fabulous!

HTML list-style-type dash

Here's a version without any position relative or absolute and without text-indent:

ul.dash {
    list-style: none;
    margin-left: 0;
    padding-left: 1em;
}
ul.dash > li:before {
    display: inline-block;
    content: "-";
    width: 1em;
    margin-left: -1em;
}

Enjoy ;)

how to add picasso library in android studio

Dependency

dependencies {

   implementation 'com.squareup.picasso:picasso:2.71828'

}

//Java Code for Image Loading into imageView

Picasso.get().load(werURL).into(imageView);