Programs & Examples On #Tabbed browsing

How to click a browser button with JavaScript automatically?

This will give you some control over the clicking, and looks tidy

<script>
var timeOut = 0;
function onClick(but)
{
    //code
    clearTimeout(timeOut);
    timeOut = setTimeout(function (){onClick(but)},1000);
}
</script>
<button onclick="onClick(this)">Start clicking</button>

Update Tkinter Label from variable

This is the easiest one , Just define a Function and then a Tkinter Label & Button . Pressing the Button changes the text in the label. The difference that you would when defining the Label is that use the text variable instead of text. Code is tested and working.

    from tkinter import *
    master = Tk()
    
    def change_text():
        my_var.set("Second click")
    
    my_var = StringVar()
    my_var.set("First click")
    label = Label(mas,textvariable=my_var,fg="red")
    button = Button(mas,text="Submit",command = change_text)
    button.pack()
    label.pack()
    
    master.mainloop()

Tar a directory, but don't store full absolute paths in the archive

The option -C works; just for clarification I'll post 2 examples:

  1. creation of a tarball without the full path: full path /home/testuser/workspace/project/application.war and what we want is just project/application.war so:

    tar -cvf output_filename.tar  -C /home/testuser/workspace project
    

    Note: there is a space between workspace and project; tar will replace full path with just project .

  2. extraction of tarball with changing the target path (default to ., i.e current directory)

    tar -xvf output_filename.tar -C /home/deploy/
    

    tar will extract tarball based on given path and preserving the creation path; in our example the file application.war will be extracted to /home/deploy/project/application.war.

    /home/deploy: given on extract
    project: given on creation of tarball

Note : if you want to place the created tarball in a target directory, you just add the target path before tarball name. e.g.:

tar -cvf /path/to/place/output_filename.tar  -C /home/testuser/workspace project

Can dplyr package be used for conditional mutating?

case_when is now a pretty clean implementation of the SQL-style case when:

structure(list(a = c(1, 3, 4, 6, 3, 2, 5, 1), b = c(1, 3, 4, 
2, 6, 7, 2, 6), c = c(6, 3, 6, 5, 3, 6, 5, 3), d = c(6, 2, 4, 
5, 3, 7, 2, 6), e = c(1, 2, 4, 5, 6, 7, 6, 3), f = c(2, 3, 4, 
2, 2, 7, 5, 2)), .Names = c("a", "b", "c", "d", "e", "f"), row.names = c(NA, 
8L), class = "data.frame") -> df


df %>% 
    mutate( g = case_when(
                a == 2 | a == 5 | a == 7 | (a == 1 & b == 4 )     ~   2,
                a == 0 | a == 1 | a == 4 |  a == 3 | c == 4       ~   3
))

Using dplyr 0.7.4

The manual: http://dplyr.tidyverse.org/reference/case_when.html

Searching for file in directories recursively

I tried some of the other solutions listed here, but during unit testing the code would throw exceptions I wanted to ignore. I ended up creating the following recursive search method that will ignore certain exceptions like PathTooLongException and UnauthorizedAccessException.

    private IEnumerable<string> RecursiveFileSearch(string path, string pattern, ICollection<string> filePathCollector = null)
    {
        try
        {
            filePathCollector = filePathCollector ?? new LinkedList<string>();

            var matchingFilePaths = Directory.GetFiles(path, pattern);

            foreach(var matchingFile in matchingFilePaths)
            {
                filePathCollector.Add(matchingFile);
            }

            var subDirectories = Directory.EnumerateDirectories(path);

            foreach (var subDirectory in subDirectories)
            {
                RecursiveFileSearch(subDirectory, pattern, filePathCollector);
            }

            return filePathCollector;
        }
        catch (Exception error)
        {
            bool isIgnorableError = error is PathTooLongException ||
                error is UnauthorizedAccessException;

            if (isIgnorableError)
            {
                return Enumerable.Empty<string>();
            }

            throw error;
        }
    }

Execute a command in command prompt using excel VBA

The S parameter does not do anything on its own.

/S      Modifies the treatment of string after /C or /K (see below) 
/C      Carries out the command specified by string and then terminates  
/K      Carries out the command specified by string but remains  

Try something like this instead

Call Shell("cmd.exe /S /K" & "perl a.pl c:\temp", vbNormalFocus)

You may not even need to add "cmd.exe" to this command unless you want a command window to open up when this is run. Shell should execute the command on its own.

Shell("perl a.pl c:\temp")



-Edit-
To wait for the command to finish you will have to do something like @Nate Hekman shows in his answer here

Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1

wsh.Run "cmd.exe /S /C perl a.pl c:\temp", windowStyle, waitOnReturn

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

The way I would go about this issue is:

If you need to write/replace the file:

echo "some text" | sudo tee /path/to/file

If you need to append to the file:

echo "some text" | sudo tee -a /path/to/file

How can I parse a YAML file in Python

The easiest and purest method without relying on C headers is PyYaml (documentation), which can be installed via pip install pyyaml:

#!/usr/bin/env python

import yaml

with open("example.yaml", 'r') as stream:
    try:
        print(yaml.safe_load(stream))
    except yaml.YAMLError as exc:
        print(exc)

And that's it. A plain yaml.load() function also exists, but yaml.safe_load() should always be preferred unless you explicitly need the arbitrary object serialization/deserialization provided in order to avoid introducing the possibility for arbitrary code execution.

Note the PyYaml project supports versions up through the YAML 1.1 specification. If YAML 1.2 specification support is needed, see ruamel.yaml as noted in this answer.

C# Linq Where Date Between 2 Dates

If you have date interval filter condition and you need to select all records which falls partly into this filter range. Assumption: records has ValidFrom and ValidTo property.

DateTime intervalDateFrom = new DateTime(1990, 01, 01);
DateTime intervalDateTo = new DateTime(2000, 01, 01);

var itemsFiltered = allItems.Where(x=> 
    (x.ValidFrom >= intervalDateFrom && x.ValidFrom <= intervalDateTo) ||
    (x.ValidTo >= intervalDateFrom && x.ValidTo <= intervalDateTo) ||
    (intervalDateFrom >= x.ValidFrom && intervalDateFrom <= x.ValidTo) ||
    (intervalDateTo >= x.ValidFrom && intervalDateTo <= x.ValidTo)
);

How to create a showdown.js markdown extension

In your last block you have a comma after 'lang', followed immediately with a function. This is not valid json.

EDIT

It appears that the readme was incorrect. I had to to pass an array with the string 'twitter'.

var converter = new Showdown.converter({extensions: ['twitter']}); converter.makeHtml('whatever @meandave2020'); // output "<p>whatever <a href="http://twitter.com/meandave2020">@meandave2020</a></p>" 

I submitted a pull request to update this.

How do you convert between 12 hour time and 24 hour time in PHP?

// 24-hour time to 12-hour time 
$time_in_12_hour_format  = date("g:i a", strtotime("13:30"));

// 12-hour time to 24-hour time 
$time_in_24_hour_format  = date("H:i", strtotime("1:30 PM"));

Forcing anti-aliasing using css: Is this a myth?

I think you got it a bit wrong. Someone in the thread you pasted says that you can stop anti-aliasing by using px instead of pt, not that you can force it by using the latter. I'm a bit sceptical to both of the claims though...

How do I install g++ on MacOS X?

Installing XCode requires:

  • Enrolling on the Apple website (not fun)
  • Downloading a 4.7G installer

To install g++ *WITHOUT* having to download the MASSIVE 4.7G xCode install, try this package:

https://github.com/kennethreitz/osx-gcc-installer

The DMG files linked on that page are ~270M and much quicker to install. This was perfect for me, getting homebrew up and running with a minimum of hassle.

The github project itself is basically a script that repackages just the critical chunks of xCode for distribution. In order to run that script and build the DMG files, you'd need to already have an XCode install, which would kind of defeat the point, so the pre-built DMG files are hosted on the project page.

Equivalent of *Nix 'which' command in PowerShell?

Check this PowerShell Which.

The code provided there suggests this:

($Env:Path).Split(";") | Get-ChildItem -filter notepad.exe

How set background drawable programmatically in Android

try this.

 int res = getResources().getIdentifier("you_image", "drawable", "com.my.package");
 preview = (ImageView) findViewById(R.id.preview);
 preview.setBackgroundResource(res);

Binding value to input in Angular JS

You don't need to set the value at all. ng-model takes care of it all:

  • set the input value from the model
  • update the model value when you change the input
  • update the input value when you change the model from js

Here's the fiddle for this: http://jsfiddle.net/terebentina/9mFpp/

Objective-C: Extract filename from path string

At the risk of being years late and off topic - and notwithstanding @Marc's excellent insight, in Swift it looks like:

let basename = NSURL(string: "path/to/file.ext")?.URLByDeletingPathExtension?.lastPathComponent

How to style components using makeStyles and still have lifecycle methods in Material UI?

What we ended up doing is stopped using the class components and created Functional Components, using useEffect() from the Hooks API for lifecycle methods. This allows you to still use makeStyles() with Lifecycle Methods without adding the complication of making Higher-Order Components. Which is much simpler.

Example:

import React, { useEffect, useState } from 'react';
import axios from 'axios';
import { Redirect } from 'react-router-dom';

import { Container, makeStyles } from '@material-ui/core';

import LogoButtonCard from '../molecules/Cards/LogoButtonCard';

const useStyles = makeStyles(theme => ({
  root: {
    display: 'flex',
    alignItems: 'center',
    justifyContent: 'center',
    margin: theme.spacing(1)
  },
  highlight: {
    backgroundColor: 'red',
  }
}));

// Highlight is a bool
const Welcome = ({highlight}) => { 
  const [userName, setUserName] = useState('');
  const [isAuthenticated, setIsAuthenticated] = useState(true);
  const classes = useStyles();

  useEffect(() => {
    axios.get('example.com/api/username/12')
         .then(res => setUserName(res.userName));
  }, []);

  if (!isAuthenticated()) {
    return <Redirect to="/" />;
  }
  return (
    <Container maxWidth={false} className={highlight ? classes.highlight : classes.root}>
      <LogoButtonCard
        buttonText="Enter"
        headerText={isAuthenticated && `Welcome, ${userName}`}
        buttonAction={login}
      />
   </Container>
   );
  }
}

export default Welcome;

What programming language does facebook use?

Since nobody has mentioned it, I'd like to add that Facebook chat is written in Erlang.

Finding the type of an object in C++

You are looking for dynamic_cast<B*>(pointer)

Group array items using object

Another option is using reduce() and new Map() to group the array. Use Spread syntax to convert set object into an array.

_x000D_
_x000D_
var myArray = [{"group":"one","color":"red"},{"group":"two","color":"blue"},{"group":"one","color":"green"},{"group":"one","color":"black"}]_x000D_
_x000D_
var result = [...myArray.reduce((c, {group,color}) => {_x000D_
  if (!c.has(group)) c.set(group, {group,color: []});_x000D_
  c.get(group).color.push(color);_x000D_
  return c;_x000D_
}, new Map()).values()];_x000D_
_x000D_
console.log(result);
_x000D_
_x000D_
_x000D_

How can I toggle word wrap in Visual Studio?

In Visual Studio 2008, CTRL+E+W.

IntelliJ and Tomcat.. Howto..?

You can also debug tomcat using the community edition (Unlike what is said above).

Start tomcat in debug mode, for example like this: .\catalina.bat jpda run

In intellij: Run > Edit Configurations > +

Select "Remote" Name the connection: "somename" Set "Port:" 8000 (default 5005)

Select Run > Debug "somename"

How to set Google Chrome in WebDriver

It was giving Illegal Exception.

My workaround with code:

public void dofirst(){
    System.setProperty("webdriver.chrome.driver","D:\\Softwares\\selenium\\chromedriver_win32\\chromedriver.exe");
    WebDriver driver = new ChromeDriver();
    driver.get("http://www.facebook.com");
}

Replacing .NET WebBrowser control with a better browser, like Chrome?

Chrome uses (a fork of) Webkit if you didn't know, which is also used by Safari. Here's a few questions that are of the same vein:

The webkit one isn't great as the other answer states, one version no longer works (the google code one) and the Mono one is experimental. It'd be nice if someone made the effort to make a decent .NET wrapper for it but it's not something anyone seems to want to do - which is surprising given it now has support for HTML5 and so many other features that the IE(8) engine lacks.

Update (2014)

There's new dual-licensed project that allows you embed Chrome into your .NET applications called Awesomium. It comes with a .NET api but requires quite a few hacks for rendering (the examples draw the browser window to a buffer, paint the buffer as an image and refresh on a timer).

I think this is the browser used by Origin in Battlefield 3.

Update (2016)

There is now DotnetBrowser, a commercial alternative to Awesomium. It's based off Chromium.

Responsive bootstrap 3 timepicker?

As an update to the OP's question, I can confirm that the timepicker found at http://jdewit.github.io/bootstrap-timepicker/ does in fact work with Bootstrap 3 now with no problems at all.

Java generics - get class?

I like the solution from

http://www.nautsch.net/2008/10/28/class-von-type-parameter-java-generics/

public class Dada<T> {

    private Class<T> typeOfT;

    @SuppressWarnings("unchecked")
    public Dada() {
        this.typeOfT = (Class<T>)
                ((ParameterizedType)getClass()
                .getGenericSuperclass())
                .getActualTypeArguments()[0];
    }
...

How to align a div inside td element using CSS class

I cannot help you much without a small (possibly reduced) snippit of the problem. If the problem is what I think it is then it's because a div by default takes up 100% width, and as such cannot be aligned.

What you may be after is to align the inline elements inside the div (such as text) with text-align:center; otherwise you may consider setting the div to display:inline-block;

If you do go down the inline-block route then you may have to consider my favorite IE hack.

width:100px;
display:inline-block;
zoom:1; //IE only
*display:inline; //IE only

Happy Coding :)

How can I check whether a option already exist in select by JQuery

I had a similar issue. Rather than run the search through the dom every time though the loop for the select control I saved the jquery select element in a variable and did this:

function isValueInSelect($select, data_value){
    return $($select).children('option').map(function(index, opt){
        return opt.value;
    }).get().includes(data_value);
}

No Main class found in NetBeans

When creating a new project - Maven - Java application in Netbeans the IDE is not recognizing the Main class on 1st class entry. (in Step 8 below we see no classes).

When first a generic class is created and then the Main class is created Netbeans is registering the Main class and the app could be run and debugged.

Steps that worked for me:

  1. Create new project - Maven - Java application (project created: mytest; package created: com.me.test)
  2. Right-click package: com.me.test
  3. New > Java Class > Named it 'Whatever' you want
  4. Right-click package: com.me.test
  5. New > Java Main Class > named it: 'Main' (must be 'Main')
  6. Right click on Project mytest
  7. Click on Properties
  8. Click on Run > next to 'Main Class' text box: > Browse
  9. You should see: com.me.test.Main
  10. Select it and click "Select Main Class"

Hope this works for others as well.

The preferred way of creating a new element with jQuery

I would recommend the first option, where you actually build elements using jQuery. the second approach simply sets the innerHTML property of the element to a string, which happens to be HTML, and is more error prone and less flexible.

SignalR - Sending a message to a specific user using (IUserIdProvider) *NEW 2.0.0*

This is how use SignarR in order to target a specific user (without using any provider):

 private static ConcurrentDictionary<string, string> clients = new ConcurrentDictionary<string, string>();

 public string Login(string username)
 {
     clients.TryAdd(Context.ConnectionId, username);            
     return username;
 }

// The variable 'contextIdClient' is equal to Context.ConnectionId of the user, 
// once logged in. You have to store that 'id' inside a dictionaty for example.  
Clients.Client(contextIdClient).send("Hello!");

Converting int to string in C

If you really want to use itoa, you need to include the standard library header.

#include <stdlib.h>

I also believe that if you're on Windows (using MSVC), then itoa is actually _itoa.

See http://msdn.microsoft.com/en-us/library/yakksftt(v=VS.100).aspx

Then again, since you're getting a message from collect2, you're likely running GCC on *nix.

SQL query to get most recent row for each instance of a given key

Can't post comments yet, but @Cristi S's answer works a treat for me.

In my scenario, I needed to keep only the most recent 3 records in Lowest_Offers for all product_ids.

Need to rework his SQL to delete - thought that this would be ok, but syntax is wrong.

DELETE from (
SELECT product_id, id, date_checked,
  ROW_NUMBER() OVER (PARTITION BY product_id ORDER BY date_checked DESC) rn
FROM lowest_offers
) tmp WHERE > 3;

How do I check to see if a value is an integer in MySQL?

Match it against a regular expression.

c.f. http://forums.mysql.com/read.php?60,1907,38488#msg-38488 as quoted below:

Re: IsNumeric() clause in MySQL??
Posted by: kevinclark ()
Date: August 08, 2005 01:01PM


I agree. Here is a function I created for MySQL 5:

CREATE FUNCTION IsNumeric (sIn varchar(1024)) RETURNS tinyint
RETURN sIn REGEXP '^(-|\\+){0,1}([0-9]+\\.[0-9]*|[0-9]*\\.[0-9]+|[0-9]+)$';


This allows for an optional plus/minus sign at the beginning, one optional decimal point, and the rest numeric digits.

DELETE_FAILED_INTERNAL_ERROR Error while Installing APK

For Android Studio on Mac :

Navigation Bar :

Android Studio > Preferences > Build, Execution, Deployment > Instant Run > Uncheck : Enable Instant Run

For Android Studio on Windows :

File > Settings > Build, Execution, Deployment > Instant Run > Uncheck : Enable Instant Run

How do you share code between projects/solutions in Visual Studio?

You can include a project in more than one solution. I don't think a project has a concept of which solution it's part of. However, another alternative is to make the first solution build to some well-known place, and reference the compiled binaries. This has the disadvantage that you'll need to do a bit of work if you want to reference different versions based on whether you're building in release or debug configurations.

I don't believe you can make one solution actually depend on another, but you can perform your automated builds in an appropriate order via custom scripts. Basically treat your common library as if it were another third party dependency like NUnit etc.

Nested Git repositories?

git-subtree will help you work with multiple projects in a single tree and keep separable history for them.

How to Call VBA Function from Excel Cells?

The issue you have encountered is that UDFs cannot modify the Excel environment, they can only return a value to the calling cell.

There are several alternatives

  1. For the sample given you don't actually need VBA. This formula will work
    ='C:\Users\UserName\Desktop\[TestSample.xlsx]Sheet1'!$B$2

  2. Use a rather messy work around: See this answer

  3. You can use ExecuteExcel4Macro or OLEDB

What is correct media query for IPad Pro?

/* ----------- iPad Pro ----------- */
/* Portrait and Landscape */
@media only screen 
  and (min-width: 1024px) 
  and (max-height: 1366px) 
  and (-webkit-min-device-pixel-ratio: 1.5) {
}

/* Portrait */
@media only screen 
  and (min-width: 1024px) 
  and (max-height: 1366px) 
  and (orientation: portrait) 
  and (-webkit-min-device-pixel-ratio: 1.5) {
}

/* Landscape */
@media only screen 
  and (min-width: 1024px) 
  and (max-height: 1366px) 
  and (orientation: landscape) 
  and (-webkit-min-device-pixel-ratio: 1.5) {

}

I don't have an iPad Pro but this works for me in the Chrome simulator.

JavaScript - Hide a Div at startup (load)

I've had the same problem.

Use CSS to hide is not the best solution, because sometimes you want users without JS can see the div.. The cleanest solution is to hide the div with JQuery. But the div is visible about 0.5 seconde, which is problematic if the div is on the top of the page.

In these cases, I use an intermediate solution, without JQuery. This one works and is immediate :

<script>document.write('<style>.js_hidden { display: none; }</style>');</script>

<div class="js_hidden">This div will be hidden for JS users, and visible for non JS users.</div>

Of course, you can still add all the effects you want on the div, JQuery toggle() for example. And you will get the best behaviour possible (imho) :

  • for non JS users, the div is visible directly
  • for JS users, the div is hidden and has toggle effect.

Execute another jar in a Java program

If the jar's in your classpath, and you know its Main class, you can just invoke the main class. Using DITA-OT as an example:

import org.dita.dost.invoker.CommandLineInvoker;
....
CommandLineInvoker.main('-f', 'html5', '-i', 'samples/sequence.ditamap', '-o', 'test')

Note this will make the subordinate jar share memory space and a classpath with your jar, with all the potential for interference that can cause. If you don't want that stuff polluted, you have other options, as mentioned above - namely:

  • create a new ClassLoader with the jar in it. This is more safe; you can at least isolate the new jar's knowledge to a core classloader if you architect things with the knowledge that you'll be making use of alien jars. It's what we do in my shop for our plugins system; the main application is a tiny shell with a ClassLoader factory, a copy of the API, and knowledge that the real application is the first plugin for which it should build a ClassLoader. Plugins are a pair of jars - interface and implementation - that are zipped up together. The ClassLoaders all share all the interfaces, while each ClassLoader only has knowledge of its own implementation. The stack's a little complex, but it passes all tests and works beautifully.
  • use Runtime.getRuntime.exec(...) (which wholly isolates the jar, but has the normal "find the application", "escape your strings right", "platform-specific WTF", and "OMG System Threads" pitfalls of running system commands.

Catch a thread's exception in the caller thread in Python

The problem is that thread_obj.start() returns immediately. The child thread that you spawned executes in its own context, with its own stack. Any exception that occurs there is in the context of the child thread, and it is in its own stack. One way I can think of right now to communicate this information to the parent thread is by using some sort of message passing, so you might look into that.

Try this on for size:

import sys
import threading
import Queue


class ExcThread(threading.Thread):

    def __init__(self, bucket):
        threading.Thread.__init__(self)
        self.bucket = bucket

    def run(self):
        try:
            raise Exception('An error occured here.')
        except Exception:
            self.bucket.put(sys.exc_info())


def main():
    bucket = Queue.Queue()
    thread_obj = ExcThread(bucket)
    thread_obj.start()

    while True:
        try:
            exc = bucket.get(block=False)
        except Queue.Empty:
            pass
        else:
            exc_type, exc_obj, exc_trace = exc
            # deal with the exception
            print exc_type, exc_obj
            print exc_trace

        thread_obj.join(0.1)
        if thread_obj.isAlive():
            continue
        else:
            break


if __name__ == '__main__':
    main()

How much data can a List can hold at the maximum?

How much data can be added in java.util.List in Java at the maximum?

This is very similar to Theoretical limit for number of keys (objects) that can be stored in a HashMap?

The documentation of java.util.List does not explicitly documented any limit on the maximum number of elements. The documentation of List.toArray however, states that ...

Return an array containing all of the elements in this list in proper sequence (from first to last element); would have trouble implementing certain methods faithfully, such as

... so strictly speaking it would not be possible to faithfully implement this method if the list had more than 231-1 = 2147483647 elements since that is the largest possible array.

Some will argue that the documentation of size()...

Returns the number of elements in this list. If this list contains more than Integer.MAX_VALUE elements, returns Integer.MAX_VALUE.

...indicates that there is no upper limit, but this view leads to numerous inconsistencies. See this bug report.

Is there any default size an array list?

If you're referring to ArrayList then I'd say that the default size is 0. The default capacity however (the number of elements you can insert, without forcing the list to reallocate memory) is 10. See the documentation of the default constructor.

The size limit of ArrayList is Integer.MAX_VALUE since it's backed by an ordinary array.

When to use CouchDB over MongoDB and vice versa

I'm sure you can with Mongo (more familiar with it), and pretty sure you can with couch too.

Both are documented oriented (JSON-based) so there would be no "columns" but rather fields in documents -- but they can be fully dynamic.

They both do it you may want to look at other factors on which to use: other features you care about, popularity, etc. Google insights, indeed.com job posts would be ways to look at popularity.

You could just try it i think you should be able to have mongo running in 5 minutes.

What's is the difference between train, validation and test set, in neural networks?

Training set: A set of examples used for learning, that is to fit the parameters [i.e., weights] of the classifier.

Validation set: A set of examples used to tune the parameters [i.e., architecture, not weights] of a classifier, for example to choose the number of hidden units in a neural network.

Test set: A set of examples used only to assess the performance [generalization] of a fully specified classifier.

From ftp://ftp.sas.com/pub/neural/FAQ1.txt section "What are the population, sample, training set, design set, validation"

The error surface will be different for different sets of data from your data set (batch learning). Therefore if you find a very good local minima for your test set data, that may not be a very good point, and may be a very bad point in the surface generated by some other set of data for the same problem. Therefore you need to compute such a model which not only finds a good weight configuration for the training set but also should be able to predict new data (which is not in the training set) with good error. In other words the network should be able to generalize the examples so that it learns the data and does not simply remembers or loads the training set by overfitting the training data.

The validation data set is a set of data for the function you want to learn, which you are not directly using to train the network. You are training the network with a set of data which you call the training data set. If you are using gradient based algorithm to train the network then the error surface and the gradient at some point will completely depend on the training data set thus the training data set is being directly used to adjust the weights. To make sure you don't overfit the network you need to input the validation dataset to the network and check if the error is within some range. Because the validation set is not being using directly to adjust the weights of the netowork, therefore a good error for the validation and also the test set indicates that the network predicts well for the train set examples, also it is expected to perform well when new example are presented to the network which was not used in the training process.

Early stopping is a way to stop training. There are different variations available, the main outline is, both the train and the validation set errors are monitored, the train error decreases at each iteration (backprop and brothers) and at first the validation error decreases. The training is stopped at the moment the validation error starts to rise. The weight configuration at this point indicates a model, which predicts the training data well, as well as the data which is not seen by the network . But because the validation data actually affects the weight configuration indirectly to select the weight configuration. This is where the Test set comes in. This set of data is never used in the training process. Once a model is selected based on the validation set, the test set data is applied on the network model and the error for this set is found. This error is a representative of the error which we can expect from absolutely new data for the same problem.

EDIT:

Also, in the case you do not have enough data for a validation set, you can use crossvalidation to tune the parameters as well as estimate the test error.

Add Facebook Share button to static HTML page

 <div class="fb_share">
     <a name="fb_share" type="box_count" share_url="<?php the_permalink() ?>"
       href="http://www.facebook.com/sharer.php">Partilhar</a>
     <script src="http://static.ak.fbcdn.net/connect.php/js/FB.Share" type="text/javascript"></script> </div> <?php }  }

 add_action('thesis_hook_byline_item','fb_share');

Object Library Not Registered When Adding Windows Common Controls 6.0

You Just execute the following commands in your command prompt,

For 32 bit machine,

cd C:\Windows\System32
regsvr32 mscomctl.ocx
regtlib msdatsrc.tlb

For 64 bit machine,

cd C:\Windows\SysWOW64
regsvr32 mscomctl.ocx
regtlib msdatsrc.tlb

Check if AJAX response data is empty/blank/null/undefined/0

This worked form me.. PHP Code on page.php

 $query_de="sql statements here";
 $sql_de = sqlsrv_query($conn,$query_de);
      if ($sql_de)
      {
        echo "SQLSuccess";
       }
         exit();

and then AJAX Code has bellow

jQuery.ajax({
                    url  : "page.php",
                    type : "POST",
                    data : {
                            buttonsave   : 1,
                            var1         : val1,
                            var2         : val2,
                              },
                  success:function(data)
                           {
                     if(jQuery.trim(data) === "SQLSuccess")
                                   {
                           alert("Se agrego correctamente");
                          // alert(data);
                                      } else { alert(data);}
                              },
                   error: function(error)
                           {
                    alert("Error AJAX not working: "+ error );
                              } 
               }); 

NOTE: the word 'SQLSuccess' must be received from PHP

How to get full path of selected file on change of <input type=‘file’> using javascript, jquery-ajax?

You can, if uploading an entire folder is an option for you

<input type="file" webkitdirectory directory multiple/>

change event will contain:

.target.files[...].webkitRelativePath: "FOLDER/FILE.ext"

Detect the Internet connection is offline?

You can determine that the connection is lost by making failed XHR requests.

The standard approach is to retry the request a few times. If it doesn't go through, alert the user to check the connection, and fail gracefully.

Sidenote: To put the entire application in an "offline" state may lead to a lot of error-prone work of handling state.. wireless connections may come and go, etc. So your best bet may be to just fail gracefully, preserve the data, and alert the user.. allowing them to eventually fix the connection problem if there is one, and to continue using your app with a fair amount of forgiveness.

Sidenote: You could check a reliable site like google for connectivity, but this may not be entirely useful as just trying to make your own request, because while Google may be available, your own application may not be, and you're still going to have to handle your own connection problem. Trying to send a ping to google would be a good way to confirm that the internet connection itself is down, so if that information is useful to you, then it might be worth the trouble.

Sidenote: Sending a Ping could be achieved in the same way that you would make any kind of two-way ajax request, but sending a ping to google, in this case, would pose some challenges. First, we'd have the same cross-domain issues that are typically encountered in making Ajax communications. One option is to set up a server-side proxy, wherein we actually ping google (or whatever site), and return the results of the ping to the app. This is a catch-22 because if the internet connection is actually the problem, we won't be able to get to the server, and if the connection problem is only on our own domain, we won't be able to tell the difference. Other cross-domain techniques could be tried, for example, embedding an iframe in your page which points to google.com, and then polling the iframe for success/failure (examine the contents, etc). Embedding an image may not really tell us anything, because we need a useful response from the communication mechanism in order to draw a good conclusion about what's going on. So again, determining the state of the internet connection as a whole may be more trouble than it's worth. You'll have to weight these options out for your specific app.

Remove files from Git commit

Now that Apple has non-cosensually updated all MacOS users to zsh, the correct answer doesn't work anymore.

git reset --soft HEAD^
zsh: no matches found: HEAD^

You can prevent the shell from treating the ^ as a special character by single quoting it.

git reset --soft 'HEAD^'

Alternatively you can disable this behavior in your shell. by updating your ~/.zshrc with

unsetopt nomatch

How to resolve "gpg: command not found" error during RVM installation?

On my clean macOS 10.15.7, I needed to brew link gnupg && brew unlink gnupg first and then used Ashish's answer to use gpg instead of gpg2. I also had to chown a few directories. before the un/link.

How do you execute an arbitrary native command from a string?

If you want to use the call operator, the arguments can be an array stored in a variable:

$prog = 'c:\windows\system32\cmd.exe'
$myargs = '/c','dir','/x'
& $prog $myargs

The call operator works with ApplicationInfo objects too.

$prog = get-command cmd
$myargs = -split '/c dir /x'
& $prog $myargs

How to run a program in Atom Editor?

You can go settings, select packages and type atom-runner there if your browser can't open this link.

To run your code do Alt+R if you're using Windows in Atom.

Show hide fragment in android

the answers here are correct and i liked @Jyo the Whiff idea of a show and hide fragment implementation except the way he has it currently would hide the fragment on the first run so i added a slight change in that i added the isAdded check and show the fragment if its not already

public void showHideCardPreview(int id) {
    FragmentManager fm = getSupportFragmentManager();
    Bundle b = new Bundle();
    b.putInt(Constants.CARD, id);
    cardPreviewFragment.setArguments(b);
    FragmentTransaction ft = fm.beginTransaction()
        .setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out);
    if (!cardPreviewFragment.isAdded()){
        ft.add(R.id.full_screen_container, cardPreviewFragment);
        ft.show(cardPreviewFragment);
    } else {
        if (cardPreviewFragment.isHidden()) {
            Log.d(TAG,"++++++++++++++++++++ show");
            ft.show(cardPreviewFragment);
        } else {
            Log.d(TAG,"++++++++++++++++++++ hide");
            ft.hide(cardPreviewFragment);
        }
    }

    ft.commit();
} 

Elastic Search: how to see the indexed data

A tool that helps me a lot to debug ElasticSearch is ElasticHQ. Basically, it is an HTML file with some JavaScript. No need to install anywhere, let alone in ES itself: just download it, unzip int and open the HTML file with a browser.

Not sure it is the best tool for ES heavy users. Yet, it is really practical to whoever is in a hurry to see the entries.

subquery in FROM must have an alias

In the case of nested tables, some DBMS require to use an alias like MySQL and Oracle but others do not have such a strict requirement, but still allow to add them to substitute the result of the inner query.

How to use Greek symbols in ggplot2?

You do not need the latex2exp package to do what you wanted to do. The following code would do the trick.

ggplot(smr, aes(Fuel.Rate, Eng.Speed.Ave., color=Eng.Speed.Max.)) + 
  geom_point() + 
  labs(title=expression("Fuel Efficiency"~(alpha*Omega)), 
color=expression(alpha*Omega), x=expression(Delta~price))

enter image description here

Also, some comments (unanswered as of this point) asked about putting an asterisk (*) after a Greek letter. expression(alpha~"*") works, so I suggest giving it a try.

More comments asked about getting ? Price and I find the most straightforward way to achieve that is expression(Delta~price)). If you need to add something before the Greek letter, you can also do this: expression(Indicative~Delta~price) which gets you:

enter image description here

Database development mistakes made by application developers

For SQL-based databases:

  1. Not taking advantage of CLUSTERED INDEXES or choosing the wrong column(s) to CLUSTER.
  2. Not using a SERIAL (autonumber) datatype as a PRIMARY KEY to join to a FOREIGN KEY (INT) in a parent/child table relationship.
  3. Not UPDATING STATISTICS on a table when many records have been INSERTED or DELETED.
  4. Not reorganizing (i.e. unloading, droping, re-creating, loading and re-indexing) tables when many rows have been inserted or deleted (some engines physically keep deleted rows in a table with a delete flag.)
  5. Not taking advantage of FRAGMENT ON EXPRESSION (if supported) on large tables which have high transaction rates.
  6. Choosing the wrong datatype for a column!
  7. Not choosing a proper column name.
  8. Not adding new columns at the end of the table.
  9. Not creating proper indexes to support frequently used queries.
  10. creating indexes on columns with few possible values and creating unnecessary indexes.
    ...more to be added.

Convert a number into a Roman Numeral in javaScript

I know this is an old question but I'm pretty proud of this solution :) It only handles numbers less than 1000 but could easily be expanded to include however large you'd need by adding on to the 'numeralCodes' 2D array.

_x000D_
_x000D_
var numeralCodes = [["","I","II","III","IV","V","VI","VII","VIII","IX"],         // Ones_x000D_
                    ["","X","XX","XXX", "XL", "L", "LX", "LXX", "LXXX", "XC"],   // Tens_x000D_
                    ["","C","CC","CCC","CD","D","DC","DCC","DCCC","CM"]];        // Hundreds_x000D_
_x000D_
function convert(num) {_x000D_
  var numeral = "";_x000D_
  var digits = num.toString().split('').reverse();_x000D_
  for (var i=0; i < digits.length; i++){_x000D_
    numeral = numeralCodes[i][parseInt(digits[i])] + numeral;_x000D_
  }_x000D_
  return numeral;  _x000D_
}
_x000D_
<input id="text-input" type="text">_x000D_
<button id="convert-button" onClick="var n = parseInt(document.getElementById('text-input').value);document.getElementById('text-output').value = convert(n);">Convert!</button>_x000D_
<input id="text-output" style="display:block" type="text">
_x000D_
_x000D_
_x000D_

Cannot open output file, permission denied

I tried what @willll said, and it worked. I didint find exactly the .exe named after my project, but I did kill some weird looking tasks (after checking on the internet they were not critical), and it worked.

Calculate age given the birth date in the format YYYYMMDD

Adopting from naveen's and original OP's posts I ended up with a reusable method stub that accepts both strings and / or JS Date objects.

I named it gregorianAge() because this calculation gives exactly how we denote age using Gregorian calendar. i.e. Not counting the end year if month and day is before the month and day of the birth year.

_x000D_
_x000D_
/**_x000D_
 * Calculates human age in years given a birth day. Optionally ageAtDate_x000D_
 * can be provided to calculate age at a specific date_x000D_
 *_x000D_
 * @param string|Date Object birthDate_x000D_
 * @param string|Date Object ageAtDate optional_x000D_
 * @returns integer Age between birthday and a given date or today_x000D_
 */_x000D_
function gregorianAge(birthDate, ageAtDate) {_x000D_
  // convert birthDate to date object if already not_x000D_
  if (Object.prototype.toString.call(birthDate) !== '[object Date]')_x000D_
    birthDate = new Date(birthDate);_x000D_
_x000D_
  // use today's date if ageAtDate is not provided_x000D_
  if (typeof ageAtDate == "undefined")_x000D_
    ageAtDate = new Date();_x000D_
_x000D_
  // convert ageAtDate to date object if already not_x000D_
  else if (Object.prototype.toString.call(ageAtDate) !== '[object Date]')_x000D_
    ageAtDate = new Date(ageAtDate);_x000D_
_x000D_
  // if conversion to date object fails return null_x000D_
  if (ageAtDate == null || birthDate == null)_x000D_
    return null;_x000D_
_x000D_
_x000D_
  var _m = ageAtDate.getMonth() - birthDate.getMonth();_x000D_
_x000D_
  // answer: ageAt year minus birth year less one (1) if month and day of_x000D_
  // ageAt year is before month and day of birth year_x000D_
  return (ageAtDate.getFullYear()) - birthDate.getFullYear() _x000D_
  - ((_m < 0 || (_m === 0 && ageAtDate.getDate() < birthDate.getDate())) ? 1 : 0)_x000D_
}_x000D_
_x000D_
// Below is for the attached snippet_x000D_
_x000D_
function showAge() {_x000D_
  $('#age').text(gregorianAge($('#dob').val()))_x000D_
}_x000D_
_x000D_
$(function() {_x000D_
  $(".datepicker").datepicker();_x000D_
  showAge();_x000D_
});
_x000D_
<link rel="stylesheet" href="//code.jquery.com/ui/1.11.4/themes/smoothness/jquery-ui.css">_x000D_
<script src="//code.jquery.com/jquery-1.10.2.js"></script>_x000D_
<script src="//code.jquery.com/ui/1.11.4/jquery-ui.js"></script>_x000D_
_x000D_
DOB:_x000D_
<input name="dob" value="12/31/1970" id="dob" class="datepicker" onChange="showAge()" /> AGE: <span id="age"><span>
_x000D_
_x000D_
_x000D_

How to reformat JSON in Notepad++?

Download and install this plugin JSToolNpp ,Then perform operations like this Plugins | JSTool | JSFormat. If you don’t want to install plugins, you can perform JSON beautification operations on JSON Formatter

php: loop through json array

Set the second function parameter to true if you require an associative array

Some versions of php require a 2nd paramter of true if you require an associative array

$json  = '[{"var1":"9","var2":"16","var3":"16"},{"var1":"8","var2":"15","var3":"15"}]';
$array = json_decode( $json, true );

Angular 2 Date Input not binding to date value

Angular 2 completely ignores type=date. If you change type to text you'll see that your input has two-way binding.

<input type='text' #myDate [(ngModel)]='demoUser.date'/><br>

Here is pretty bad advise with better one to follow:

My project originally used jQuery. So, I'm using jQuery datepicker for now, hoping that angular team will fix the original issue. Also it's a better replacement because it has cross-browser support. FYI, input=date doesn't work in Firefox.

Good advise: There are few pretty good Angular2 datepickers:

How do I check if there are duplicates in a flat list?

If the list contains unhashable items, you can use Alex Martelli's solution but with a list instead of a set, though it's slower for larger inputs: O(N^2).

def has_duplicates(iterable):
    seen = []
    for x in iterable:
        if x in seen:
            return True
        seen.append(x)
    return False

Generate a random date between two other dates

Use ApacheCommonUtils to generate a random long within a given range, and then create Date out of that long.

Example:

import org.apache.commons.math.random.RandomData;

import org.apache.commons.math.random.RandomDataImpl;

public Date nextDate(Date min, Date max) {

RandomData randomData = new RandomDataImpl();

return new Date(randomData.nextLong(min.getTime(), max.getTime()));

}

String contains another string

You can use .indexOf():

if(str.indexOf(substr) > -1) {

}

How can I create Min stl priority_queue?

You can do it in multiple ways:
1. Using greater as comparison function :

 #include <bits/stdc++.h>

using namespace std;

int main()
{
    priority_queue<int,vector<int>,greater<int> >pq;
    pq.push(1);
    pq.push(2);
    pq.push(3);

    while(!pq.empty())
    {
        int r = pq.top();
        pq.pop();
        cout<<r<< " ";
    }
    return 0;
}

2. Inserting values by changing their sign (using minus (-) for positive number and using plus (+) for negative number :

int main()
{
    priority_queue<int>pq2;
    pq2.push(-1); //for +1
    pq2.push(-2); //for +2
    pq2.push(-3); //for +3
    pq2.push(4);  //for -4

    while(!pq2.empty())
    {
        int r = pq2.top();
        pq2.pop();
        cout<<-r<<" ";
    }

    return 0;
}

3. Using custom structure or class :

struct compare
{
    bool operator()(const int & a, const int & b)
    {
        return a>b;
    }
};

int main()
{

    priority_queue<int,vector<int>,compare> pq;
    pq.push(1);
    pq.push(2);
    pq.push(3);

    while(!pq.empty())
    {
        int r = pq.top();
        pq.pop();
        cout<<r<<" ";
    }

    return 0;
}

4. Using custom structure or class you can use priority_queue in any order. Suppose, we want to sort people in descending order according to their salary and if tie then according to their age.

    struct people
    {
        int age,salary;

    };
    struct compare{
    bool operator()(const people & a, const people & b)
        {
            if(a.salary==b.salary)
            {
                return a.age>b.age;
            }
            else
            {
                return a.salary>b.salary;
            }

    }
    };
    int main()
    {

        priority_queue<people,vector<people>,compare> pq;
        people person1,person2,person3;
        person1.salary=100;
        person1.age = 50;
        person2.salary=80;
        person2.age = 40;
        person3.salary = 100;
        person3.age=40;


        pq.push(person1);
        pq.push(person2);
        pq.push(person3);

        while(!pq.empty())
        {
            people r = pq.top();
            pq.pop();
            cout<<r.salary<<" "<<r.age<<endl;
    }
  1. Same result can be obtained by operator overloading :

    struct people
    {
    int age,salary;
    
    bool operator< (const people & p)const
    {
        if(salary==p.salary)
        {
            return age>p.age;
        }
        else
        {
            return salary>p.salary;
        }
    }};
    

    In main function :

    priority_queue<people> pq;
    people person1,person2,person3;
    person1.salary=100;
    person1.age = 50;
    person2.salary=80;
    person2.age = 40;
    person3.salary = 100;
    person3.age=40;
    
    
    pq.push(person1);
    pq.push(person2);
    pq.push(person3);
    
    while(!pq.empty())
    {
        people r = pq.top();
        pq.pop();
        cout<<r.salary<<" "<<r.age<<endl;
    }
    

How to speed up insertion performance in PostgreSQL

If you happend to insert colums with UUIDs (which is not exactly your case) and to add to @Dennis answer (I can't comment yet), be advise than using gen_random_uuid() (requires PG 9.4 and pgcrypto module) is (a lot) faster than uuid_generate_v4()

=# explain analyze select uuid_generate_v4(),* from generate_series(1,10000);
                                                        QUERY PLAN
---------------------------------------------------------------------------------------------------------------------------
 Function Scan on generate_series  (cost=0.00..12.50 rows=1000 width=4) (actual time=11.674..10304.959 rows=10000 loops=1)
 Planning time: 0.157 ms
 Execution time: 13353.098 ms
(3 filas)

vs


=# explain analyze select gen_random_uuid(),* from generate_series(1,10000);
                                                        QUERY PLAN
--------------------------------------------------------------------------------------------------------------------------
 Function Scan on generate_series  (cost=0.00..12.50 rows=1000 width=4) (actual time=252.274..418.137 rows=10000 loops=1)
 Planning time: 0.064 ms
 Execution time: 503.818 ms
(3 filas)

Also, it's the suggested official way to do it

Note

If you only need randomly-generated (version 4) UUIDs, consider using the gen_random_uuid() function from the pgcrypto module instead.

This droped insert time from ~2 hours to ~10 minutes for 3.7M of rows.

IE9 JavaScript error: SCRIPT5007: Unable to get value of the property 'ui': object is null or undefined

check whether there is a comma at the end.

                            },
                            {
                                name: '???. ??????? ?? ?????. ?3/?',
                                data: graph_high3,
                                dataGrouping: {
                                    units: groupingUnits,
                                    groupPixelWidth: 40,
                                    approximation: "average",
                                    enabled: true,
                                    units: [[
                                            'minute',
                                            [1]
                                        ]]
                                }
                            }   // if , - SCRIPT5007

How do you get the Git repository's name in some Git repository?

I think this is a better way to unambiguously identify a clone of a repository.

git config --get remote.origin.url and checking to make sure that the origin matches ssh://your/repo.

Vim delete blank lines

This function only remove two or more blank lines, put the lines below in your vimrc, then use \d to call function

fun! DelBlank()
   let _s=@/
   let l = line(".")
   let c = col(".")
   :g/^\n\{2,}/d
   let @/=_s
   call cursor(l, c)
endfun
map <special> <leader>d :keepjumps call DelBlank()<cr>

Any way (or shortcut) to auto import the classes in IntelliJ IDEA like in Eclipse?

IntelliJ IDEA does not have an action to add imports. Rather it has the ability to do such as you type. If you enable the "Add unambiguous imports on the fly" in Settings > Editor > General > Auto Import, IntelliJ IDEA will add them as you type without the need for any shortcuts. You can also add classes and packages to exclude from auto importing to make a class you use heavily, that clashes with other classes of the same name, unambiguous.

For classes that are ambiguous (or is you prefer to have the "Add unambiguous imports on the fly" option turned off), just type the name of the class (just the name is OK, no need to fully qualify). Use code completion and select the particular class you want:

enter image description here

Notice the fully qualified names to the right. When I select the one I want and hit enter, IDEA will automatically add the import statement. This works the same if I was typing the name of a constructor. For static methods, you can even just keep typing the method you want. In the following screenshot, no "StringUtils" class is imported yet.

enter image description here

Alternatively, type the class name and then hit Alt+Enter or ?+Enter to "Show intention actions and quick-fixes" and then select the import option.

Although I've never used it, I think the Eclipse Code Formatter third party plug-in will do what you want. It lists "emulates Eclipse's imports optimizing" as a feature. See its instructions for more information. But in the end, I suspect you'll find the built in IDEA features work fine once you get use to their paradigm. In general, IDEA uses a "develop by intentions" concept. So rather than interrupting my development work to add an import statement, I just type the class I want (my intention) and IDEA automatically adds the import statement for the class for me.

How can I pass arguments to anonymous functions in JavaScript?

What you've done doesn't work because you're binding an event to a function. As such, it's the event which defines the parameters that will be called when the event is raised (i.e. JavaScript doesn't know about your parameter in the function you've bound to onclick so can't pass anything into it).

You could do this however:

<input type="button" value="Click me" id="myButton"/>

<script type="text/javascript">

    var myButton = document.getElementById("myButton");

    var myMessage = "it's working";

    var myDelegate = function(message) {
        alert(message);
    }

    myButton.onclick = function() { 
        myDelegate(myMessage);
    };

</script>

Inline elements shifting when made bold on hover

I use text-shadow solution as some others mentioned here:

text-shadow: 0 0 0.01px;

the difference is that I do not specify shadow color, so this solution is universal for all font colors.

Linq Query Group By and Selecting First Items

First of all, I wouldn't use a multi-dimensional array. Only ever seen bad things come of it.

Set up your variable like this:

IEnumerable<IEnumerable<string>> data = new[] {
    new[]{"...", "...", "..."},
    ... etc ...
};

Then you'd simply go:

var firsts = data.Select(x => x.FirstOrDefault()).Where(x => x != null); 

The Where makes sure it prunes any nulls if you have an empty list as an item inside.

Alternatively you can implement it as:

string[][] = new[] {
    new[]{"...","...","..."},
    new[]{"...","...","..."},
    ... etc ...
};

This could be used similarly to a [x,y] array but it's used like this: [x][y]

How do I create sql query for searching partial matches?

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

If your data is not large, you can do

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

using OR if you have multiple keywords.

Most efficient way to check for DBNull and then assign to a variable?

I always use :

if (row["value"] != DBNull.Value)
  someObject.Member = row["value"];

Found it short and comprehensive.

How to configure encoding in Maven?

OK, I have found the problem.

I use some reporting plugins. In the documentation of the failsafe-maven-plugin I found, that the <encoding> configuration - of course - uses ${project.reporting.outputEncoding} by default.

So I added the property as a child element of the project element and everything is fine now:

<properties>
    <project.build.sourceEncoding>UTF-8</project.build.sourceEncoding>
    <project.reporting.outputEncoding>UTF-8</project.reporting.outputEncoding>
</properties>

See also http://maven.apache.org/general.html#encoding-warning

How can I do an UPDATE statement with JOIN in SQL Server?

Simplified update query using JOIN-ing multiple tables.

   UPDATE
        first_table ft
        JOIN second_table st ON st.some_id = ft.some_id
        JOIN third_table tt  ON tt.some_id = st.some_id
        .....
    SET
        ft.some_column = some_value
    WHERE ft.some_column = 123456 AND st.some_column = 123456

Note - first_table, second_table, third_table and some_column like 123456 are demo table names, column names and ids. Replace them with the valid names.

Getting request doesn't pass access control check: No 'Access-Control-Allow-Origin' header is present on the requested resource

Basically, to make a cross domain AJAX requests, the requested server should allow the cross origin sharing of resources (CORS). You can read more about that from here: http://www.html5rocks.com/en/tutorials/cors/

In your scenario, you are setting the headers in the client which in fact needs to be set into http://localhost:8080/app server side code.

If you are using PHP Apache server, then you will need to add following in your .htaccess file:

Header set Access-Control-Allow-Origin "*"

java.net.SocketException: Connection reset

Whenever I have had odd issues like this, I usually sit down with a tool like WireShark and look at the raw data being passed back and forth. You might be surprised where things are being disconnected, and you are only being notified when you try and read.

Bad Request, Your browser sent a request that this server could not understand

If you are getting this error on the WordPress website, check the below solution.

  1. Corrupted Browser Cache & Cookies: Delete your Cookies and clear your cache
  2. Restart your server

forcing web-site to show in landscape mode only

Try this It may be more appropriate for you

_x000D_
_x000D_
#container { display:block; }_x000D_
@media only screen and (orientation:portrait){_x000D_
  #container {  _x000D_
    height: 100vw;_x000D_
    -webkit-transform: rotate(90deg);_x000D_
    -moz-transform: rotate(90deg);_x000D_
    -o-transform: rotate(90deg);_x000D_
    -ms-transform: rotate(90deg);_x000D_
    transform: rotate(90deg);_x000D_
  }_x000D_
}_x000D_
@media only screen and (orientation:landscape){_x000D_
  #container {  _x000D_
     -webkit-transform: rotate(0deg);_x000D_
     -moz-transform: rotate(0deg);_x000D_
     -o-transform: rotate(0deg);_x000D_
     -ms-transform: rotate(0deg);_x000D_
     transform: rotate(0deg);_x000D_
  }_x000D_
}
_x000D_
<div id="container">_x000D_
    <!-- your html for your website -->_x000D_
    <H1>This text is always in Landscape Mode</H1>_x000D_
</div>
_x000D_
_x000D_
_x000D_

This will automatically manage even rotation.

MYSQL query between two timestamps

You just need to convert your dates to UNIX_TIMESTAMP. You can write your query like this:

SELECT *
FROM eventList
WHERE
  date BETWEEN
      UNIX_TIMESTAMP('2013/03/26')
      AND
      UNIX_TIMESTAMP('2013/03/27 23:59:59');

When you don't specify the time, MySQL will assume 00:00:00 as the time for the given date.

Binding objects defined in code-behind

In your code behind, set the window's DataContext to the dictionary. In your XAML, you can write:

<ListView ItemsSource="{Binding}" />

This will bind the ListView to the dictionary.

For more complex scenarios, this would be a subset of techniques behind the MVVM pattern.

How to import JsonConvert in C# application?

Or if you're using dotnet Core,

add to your .csproj file

  <ItemGroup>
    <PackageReference Include="Newtonsoft.Json" Version="9.0.1" />
  </ItemGroup>

And

dotnet restore

Command-line Tool to find Java Heap Size and Memory Used (Linux)?

Using top command is the simplest way to check memory usage of the program. RES column shows the real physical memory that is occupied by a process.

For my case, I had a 10g file read in java and each time I got outOfMemory exception. This happened when the value in the RES column reached to the value set in -Xmx option. Then by increasing the memory using -Xmx option everything went fine.

.htaccess File Options -Indexes on Subdirectories

The correct answer is

Options -Indexes

You must have been thinking of

AllowOverride All

https://httpd.apache.org/docs/2.2/howto/htaccess.html

.htaccess files (or "distributed configuration files") provide a way to make configuration changes on a per-directory basis. A file, containing one or more configuration directives, is placed in a particular document directory, and the directives apply to that directory, and all subdirectories thereof.

Plot width settings in ipython notebook

If you use %pylab inline you can (on a new line) insert the following command:

%pylab inline
pylab.rcParams['figure.figsize'] = (10, 6)

This will set all figures in your document (unless otherwise specified) to be of the size (10, 6), where the first entry is the width and the second is the height.

See this SO post for more details. https://stackoverflow.com/a/17231361/1419668

Count number of lines in a git repository

I did this:

git ls-files | xargs file | grep "ASCII" | cut -d : -f 1 | xargs wc -l

this works if you count all text files in the repository as the files of interest. If some are considered documentation, etc, an exclusion filter can be added.

CSS Image size, how to fill, but not stretch?

If you want to use the image as a CSS background, there is an elegant solution. Simply use cover or contain in the background-size CSS3 property.

_x000D_
_x000D_
.container {_x000D_
  width: 150px;_x000D_
  height: 100px;_x000D_
  background-image: url("http://i.stack.imgur.com/2OrtT.jpg");_x000D_
  background-size: cover;_x000D_
  background-repeat: no-repeat;_x000D_
  background-position: 50% 50%;_x000D_
}
_x000D_
<div class="container"></div>?
_x000D_
_x000D_
_x000D_

While cover will give you a scaled up image, contain will give you a scaled down image. Both will preserve the pixel aspect ratio.

http://jsfiddle.net/uTHqs/ (using cover)

http://jsfiddle.net/HZ2FT/ (using contain)

This approach has the advantage of being friendly to Retina displays as per Thomas Fuchs' quick guide.

It's worth mentioning that browser support for both attributes excludes IE6-8.

What does upstream mean in nginx?

If we have a single server we can directly include it in the proxy_pass. But in case if we have many servers we use upstream to maintain the servers. Nginx will load-balance based on the incoming traffic.

Best practice when adding whitespace in JSX

If the goal is to seperate two elements, you can use CSS like below:

A<span style={{paddingLeft: '20px'}}>B</span>

scrollbars in JTextArea

As Fredrik mentions in his answer, the simple way to achieve this is to place the JTextArea in a JScrollPane. This will allow scrolling of the view area of the JTextArea.

Just for the sake of completeness, the following is how it could be achieved:

JTextArea ta = new JTextArea();
JScrollPane sp = new JScrollPane(ta);   // JTextArea is placed in a JScrollPane.

Once the JTextArea is included in the JScrollPane, the JScrollPane should be added to where the text area should be. In the following example, the text area with the scroll bars is added to a JFrame:

JFrame f = new JFrame();
f.getContentPane().add(sp);

Thank you kd304 for mentioning in the comments that one should add the JScrollPane to the container rather than the JTextArea -- I feel it's a common error to add the text area itself to the destination container rather than the scroll pane with text area.

The following articles from The Java Tutorials has more details:

C++ array initialization

You can declare the array in C++ in these type of ways. If you know the array size then you should declare the array for: integer: int myArray[array_size]; Double: double myArray[array_size]; Char and string : char myStringArray[array_size]; The difference between char and string is as follows

char myCharArray[6]={'a','b','c','d','e','f'};
char myStringArray[6]="abcdef";

If you don't know the size of array then you should leave the array blank like following.

integer: int myArray[array_size];

Double: double myArray[array_size];

Using Bootstrap Tooltip with AngularJS

Simple Answer - using UI Bootstrap (ui.bootstrap.tooltip)

There seem to be a bunch of very complex answers to this question. Here's what worked for me.

  1. Install UI Bootstrap - $ bower install angular-bootstrap

  2. Inject UI Bootstrap as a dependency - angular.module('myModule', ['ui.bootstrap']);

  3. Use the uib-tooltip directive in your html.


<button class="btn btn-default"
        type="button"
        uib-tooltip="I'm a tooltip!">
     I'm a button!
</button>

Checking to see if one array's elements are in another array in PHP

That code is invalid as you can only pass variables into language constructs. empty() is a language construct.

You have to do this in two lines:

$result = array_intersect($people, $criminals);
$result = !empty($result);

Count the number of times a string appears within a string

Here, I'll over-architect the answer using LINQ. Just shows that there's more than 'n' ways to cook an egg:

public int countTrue(string data)
{
    string[] splitdata = data.Split(',');

    var results = from p in splitdata
            where p.Contains("true")
            select p;

    return results.Count();
}

apc vs eaccelerator vs xcache

Check out benchmarks and comparisons:

here and here and there

How can I get device ID for Admob

Something similar to Google Ads, from the documentation:

public AdRequest.Builder addTestDevice (String deviceId)

Causes a device to receive test ads. The deviceId can be obtained by viewing the logcat output after creating a new ad. For emulators, use DEVICE_ID_EMULATOR.

for example my Test Device id displayed in LogCat is "B86BC9402A69B031A516BC57F7D3063F":

AdRequest adRequest = new AdRequest.Builder() 
        .addTestDevice(AdRequest.DEVICE_ID_EMULATOR)
        .addTestDevice("B86BC9402A69B031A516BC57F7D3063F")
        .build();

set column width of a gridview in asp.net

There are two steps:

  1. You must set an appropriate width for GridView like this: Width="2000px".
  2. You can set width of Colum by setting [ItemStyle-Width] Like this: ItemStyle-Width="300px".

** You can set width by setting fixed Pixels like "150 px" or by percentage like"10%".

Docker can't connect to docker daemon

If all the other solutions above don't work you can try checking the ownership of /var/run/docker.sock:

ls -l /var/run/docker.sock

If you're not the owner then change ownership with the command:

sudo chown *your-username* /var/run/docker.sock

Then you can go ahead and try executing the Docker commands hassle-free :D

jQuery UI dialog box not positioned center screen

Add this to your dialog declaration

my: "center",
at: "center",
of: window

Example :

$("#dialog").dialog({
       autoOpen: false,
        height: "auto",
        width: "auto",
        modal: true,
        position: {
            my: "center",
            at: "center",
            of: window
        }
})

The type List is not generic; it cannot be parameterized with arguments [HTTPClient]

Try to import

java.util.List;

instead of

java.awt.List;

cor shows only NA or 1 for correlations - Why?

The 1s are because everything is perfectly correlated with itself, and the NAs are because there are NAs in your variables.

You will have to specify how you want R to compute the correlation when there are missing values, because the default is to only compute a coefficient with complete information.

You can change this behavior with the use argument to cor, see ?cor for details.

Shortcut to exit scale mode in VirtualBox

as @MikeMiller pointed out, To exit scale mode: Right Ctrl (Host Key) + C
but for users who DON'T have a Right Ctrl (Host Key)
(such as MS Surface Pro users: we only have a Left Ctrl key), u need to go into Virtualbox>>File>>Preferences>>Input>>VirtualMachine tab>>change Host key Combination to one that works for ya(I used Ctrl+Shift+Alt which doesn't seem to be in use already)

set option "selected" attribute from dynamic created option

This should work.

$("#country [value='ID']").attr("selected","selected");

If you have function calls bound to the element just follow it with something like

$("#country").change();

How to make links in a TextView clickable?

Autolink phone does not worked for me. The following worked like a charm,

TextView tv = (TextView) findViewById(R.id.emergencynos);
String html2="<br><br>Fire - <b><a href=tel:997>997</a> </b></br></br>";        
tv.append(Html.fromHtml(html2));
tv.setMovementMethod(LinkMovementMethod.getInstance());

unary operator expected in shell script when comparing null value with string

Since the value of $var is the empty string, this:

if [ $var == $var1 ]; then

expands to this:

if [ == abcd ]; then

which is a syntax error.

You need to quote the arguments:

if [ "$var" == "$var1" ]; then

You can also use = rather than ==; that's the original syntax, and it's a bit more portable.

If you're using bash, you can use the [[ syntax, which doesn't require the quotes:

if [[ $var = $var1 ]]; then

Even then, it doesn't hurt to quote the variable reference, and adding quotes:

if [[ "$var" = "$var1" ]]; then

might save a future reader a moment trying to remember whether [[ ... ]] requires them.

Call to getLayoutInflater() in places not in activity

LayoutInflater.from(context).inflate(R.layout.row_payment_gateway_item, null);

SVN undo delete before commit

svn revert deletedDirectory

Here's the documentation for the svn revert command.


EDIT

If deletedDirectory was deleted using rmdir and not svn rm, you'll need to do

svn update deletedDirectory

instead.

Link to "pin it" on pinterest without generating a button

You can create a custom link as described here using a small jQuery script

$('.linkPinIt').click(function(){
    var url = $(this).attr('href');
    var media = $(this).attr('data-image');
    var desc = $(this).attr('data-desc');
    window.open("//www.pinterest.com/pin/create/button/"+
    "?url="+url+
    "&media="+media+
    "&description="+desc,"_blank","top=0,right=0,width=750,height=320");
    return false; 
});

this will work for all links with class linkPinItwhich have the image and the description stored in the HTML 5 data attributes data-image and data-desc

<a href="https%3A%2F%2Fwww.flickr.com%2Fphotos%2Fkentbrew%2F6851755809%2F" 
   data-image="https%3A%2F%2Fc4.staticflickr.com%2F8%2F7027%2F6851755809_df5b2051c9_b.jpg" 
   data-desc="Title for Pinterest Photo" class="linkPinIt">
    Pin it!
</a> 

see this jfiddle example

What is a semaphore?

Semaphores are act like thread limiters.

Example: If you have a pool of 100 threads and you want to perform some DB operation. If 100 threads access the DB at a given time, then there may be locking issue in DB so we can use semaphore which allow only limited thread at a time.Below Example allow only one thread at a time. When a thread call the acquire() method, it will then get the access and after calling the release() method, it will release the acccess so that next thread will get the access.

    package practice;
    import java.util.concurrent.Semaphore;

    public class SemaphoreExample {
        public static void main(String[] args) {
            Semaphore s = new Semaphore(1);
            semaphoreTask s1 = new semaphoreTask(s);
            semaphoreTask s2 = new semaphoreTask(s);
            semaphoreTask s3 = new semaphoreTask(s);
            semaphoreTask s4 = new semaphoreTask(s);
            semaphoreTask s5 = new semaphoreTask(s);
            s1.start();
            s2.start();
            s3.start();
            s4.start();
            s5.start();
        }
    }

    class semaphoreTask extends Thread {
        Semaphore s;
        public semaphoreTask(Semaphore s) {
            this.s = s;
        }
        @Override
        public void run() {
            try {
                s.acquire();
                Thread.sleep(1000);
                System.out.println(Thread.currentThread().getName()+" Going to perform some operation");
                s.release();
            } catch (InterruptedException e) {
                e.printStackTrace();
            }
        } 
    }

Practical uses of different data structures

Found the list in a similar question, previously on StackOverflow:

Hash Table - used for fast data lookup - symbol table for compilers, database indexing, caches,Unique data representation.

Trie - dictionary, such as one found on a mobile telephone for autocompletion and spell-checking.

Suffix tree - fast full text searches used in most word processors.

Stack - undo\redo operation in word processors, Expression evaluation and syntax parsing, many virtual machines like JVM are stack oriented.

Queues - Transport and operations research where various entities are stored and held to be processed later ie the queue performs the function of a buffer.

Priority queues - process scheduling in the kernel

Trees - Parsers, Filesystem

Radix tree - IP routing table

BSP tree - 3D computer graphics

Graphs - Connections/relations in social networking sites, Routing ,networks of communication, data organization etc.

Heap - Dynamic memory allocation in lisp

This is the answer originally posted by RV Pradeep

Some other, less useful links:

Applications are only listed for some data structures

Not application focused, by good summary and relevant

Laravel - htmlspecialchars() expects parameter 1 to be string, object given

if your intention is send the full array from the html to the controller, can use this:

from the blade.php:

 <input type="hidden" name="quotation" value="{{ json_encode($quotation,TRUE)}}"> 

in controller

    public function Get(Request $req) {

    $quotation = array('quotation' => json_decode($req->quotation));

    //or

    return view('quotation')->with('quotation',json_decode($req->quotation))


}

How to use log4net in Asp.net core 2.0

I've figured out what the issue is the namespace is ambigious in the loggerFactory.AddLog4Net(). Here is a brief summary of how I added log4Net to my Asp.Net Core project.

  1. Add the nugget package Microsoft.Extensions.Logging.Log4Net.AspNetCore
  2. Add the log4net.config file in your root application folder

  3. Open the Startup.cs file and change the Configure method to add log4net support with this line loggerFactory.AddLog4Net

First you have to import the package using Microsoft.Extensions.Logging; using the using statement

Here is the entire method, you have to prefix the ILoggerFactory interface with the namespace

 public void Configure(IApplicationBuilder app, IHostingEnvironment env, NorthwindContext context, Microsoft.Extensions.Logging.ILoggerFactory loggerFactory)
        {
            loggerFactory.AddLog4Net();
            ....
        }

In Android, how do I set margins in dp programmatically?

Use this method to set margin in dp

private void setMargins (View view, int left, int top, int right, int bottom) {
    if (view.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
        ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) view.getLayoutParams();

        final float scale = getBaseContext().getResources().getDisplayMetrics().density;
        // convert the DP into pixel
        int l =  (int)(left * scale + 0.5f);
        int r =  (int)(right * scale + 0.5f);
        int t =  (int)(top * scale + 0.5f);
        int b =  (int)(bottom * scale + 0.5f);

        p.setMargins(l, t, r, b);
        view.requestLayout();
    }
}

call the method :

setMargins(linearLayout,5,0,5,0);

Cannot install packages using node package manager in Ubuntu

This is the your node is not properly install, first you need to uninstall the node then install again. To install the node this may help you http://array151.com/blog/nodejs-tutorial-and-set-up/

after that you can install the packages easily. To install the packages this may help you

http://array151.com/blog/npm-node-package-manager/

Alternative to mysql_real_escape_string without connecting to DB

Well, according to the mysql_real_escape_string function reference page: "mysql_real_escape_string() calls MySQL's library function mysql_real_escape_string, which escapes the following characters: \x00, \n, \r, \, ', " and \x1a."

With that in mind, then the function given in the second link you posted should do exactly what you need:

function mres($value)
{
    $search = array("\\",  "\x00", "\n",  "\r",  "'",  '"', "\x1a");
    $replace = array("\\\\","\\0","\\n", "\\r", "\'", '\"', "\\Z");

    return str_replace($search, $replace, $value);
}

Accessing a resource via codebehind in WPF

I got the resources on C# (Desktop WPF W/ .NET Framework 4.8) using the code below

{DefaultNamespace}.Properties.Resources.{ResourceName}

ProgressDialog in AsyncTask

Fixed by moving the view modifiers to onPostExecute so the fixed code is :

public class Soirees extends ListActivity {
    private List<Message> messages;
    private TextView tvSorties;

    //private MyProgressDialog dialog;
    @Override
    public void onCreate(Bundle icicle) {

        super.onCreate(icicle);

        setContentView(R.layout.sorties);

        tvSorties=(TextView)findViewById(R.id.TVTitle);
        tvSorties.setText("Programme des soirées");

        new ProgressTask(Soirees.this).execute();


   }


    private class ProgressTask extends AsyncTask<String, Void, Boolean> {
        private ProgressDialog dialog;
        List<Message> titles;
        private ListActivity activity;
        //private List<Message> messages;
        public ProgressTask(ListActivity activity) {
            this.activity = activity;
            context = activity;
            dialog = new ProgressDialog(context);
        }



        /** progress dialog to show user that the backup is processing. */

        /** application context. */
        private Context context;

        protected void onPreExecute() {
            this.dialog.setMessage("Progress start");
            this.dialog.show();
        }

            @Override
        protected void onPostExecute(final Boolean success) {
                List<Message> titles = new ArrayList<Message>(messages.size());
                for (Message msg : messages){
                    titles.add(msg);
                }
                MessageListAdapter adapter = new MessageListAdapter(activity, titles);
                activity.setListAdapter(adapter);
                adapter.notifyDataSetChanged();

                if (dialog.isShowing()) {
                dialog.dismiss();
            }

            if (success) {
                Toast.makeText(context, "OK", Toast.LENGTH_LONG).show();
            } else {
                Toast.makeText(context, "Error", Toast.LENGTH_LONG).show();
            }
        }

        protected Boolean doInBackground(final String... args) {
            try{    
                BaseFeedParser parser = new BaseFeedParser();
                messages = parser.parse();


                return true;
             } catch (Exception e){
                Log.e("tag", "error", e);
                return false;
             }
          }


    }

}

@Vladimir, thx your code was very helpful.

Using PowerShell to remove lines from a text file if it contains a string

Suppose you want to write that in the same file, you can do as follows:

Set-Content -Path "C:\temp\Newtext.txt" -Value (get-content -Path "c:\Temp\Newtext.txt" | Select-String -Pattern 'H\|159' -NotMatch)

How to add element in List while iterating in java?

Just iterate the old-fashion way, because you need explicit index handling:

List myList = ...
...
int length = myList.size();
for(int i = 0; i < length; i++) {
   String s = myList.get(i);
   // add items here, if you want to
}

How can I change IIS Express port for a site

If you just want to change the port because it is already in use. Follow the following steps.

In Visual studio

  1. Right-click on Project Node and Unload Project
  2. Right-click on Project Node and Edit .csproj file.
  3. Search for the following tags and remove them
<DevelopmentServerPort>62140</DevelopmentServerPort>
<DevelopmentServerVPath></DevelopmentServerVPath>
<IISUrl>http://localhost:62116/</IISUrl>
  1. press Ctrl + S to save the document
  2. Right-click on Project Node and load Project

It will work by selecting another port randomly.

For further information. please click

Can't connect to MySQL server on '127.0.0.1' (10061) (2003)

Looks like the mysql server is not started.

Look to the official documentation of MySQL how you can start a service under windows.

Install the server as a service using this command: C:> "C:\Program Files\MySQL\MySQL Server 5.5\bin\mysqld" --install

fileReader.readAsBinaryString to upload files

(Following is a late but complete answer)

FileReader methods support


FileReader.readAsBinaryString() is deprecated. Don't use it! It's no longer in the W3C File API working draft:

void abort();
void readAsArrayBuffer(Blob blob);
void readAsText(Blob blob, optional DOMString encoding);
void readAsDataURL(Blob blob);

NB: Note that File is a kind of extended Blob structure.

Mozilla still implements readAsBinaryString() and describes it in MDN FileApi documentation:

void abort();
void readAsArrayBuffer(in Blob blob); Requires Gecko 7.0
void readAsBinaryString(in Blob blob);
void readAsDataURL(in Blob file);
void readAsText(in Blob blob, [optional] in DOMString encoding);

The reason behind readAsBinaryString() deprecation is in my opinion the following: the standard for JavaScript strings are DOMString which only accept UTF-8 characters, NOT random binary data. So don't use readAsBinaryString(), that's not safe and ECMAScript-compliant at all.

We know that JavaScript strings are not supposed to store binary data but Mozilla in some sort can. That's dangerous in my opinion. Blob and typed arrays (ArrayBuffer and the not-yet-implemented but not necessary StringView) were invented for one purpose: allow the use of pure binary data, without UTF-8 strings restrictions.

XMLHttpRequest upload support


XMLHttpRequest.send() has the following invocations options:

void send();
void send(ArrayBuffer data);
void send(Blob data);
void send(Document data);
void send(DOMString? data);
void send(FormData data);

XMLHttpRequest.sendAsBinary() has the following invocations options:

void sendAsBinary(   in DOMString body );

sendAsBinary() is NOT a standard and may not be supported in Chrome.

Solutions


So you have several options:

  1. send() the FileReader.result of FileReader.readAsArrayBuffer ( fileObject ). It is more complicated to manipulate (you'll have to make a separate send() for it) but it's the RECOMMENDED APPROACH.
  2. send() the FileReader.result of FileReader.readAsDataURL( fileObject ). It generates useless overhead and compression latency, requires a decompression step on the server-side BUT it's easy to manipulate as a string in Javascript.
  3. Being non-standard and sendAsBinary() the FileReader.result of FileReader.readAsBinaryString( fileObject )

MDN states that:

The best way to send binary content (like in files upload) is using ArrayBuffers or Blobs in conjuncton with the send() method. However, if you want to send a stringifiable raw data, use the sendAsBinary() method instead, or the StringView (Non native) typed arrays superclass.

Java Error opening registry key

Make sure you remove any java.exe, javaw.exe and javaws.exe from your system.

  • if you have an x32 system (Win XP 32 bits) Windows\System32 folder

  • if you have an x64 system (Win 7 64 bits) also do the same under Windows\SysWOW64 folder

How to check if a MySQL query using the legacy API was successful?

This is the first example in the manual page for mysql_query:

$result = mysql_query('SELECT * WHERE 1=1');
if (!$result) {
    die('Invalid query: ' . mysql_error());
}

If you wish to use something other than die, then I'd suggest trigger_error.

Why do people write #!/usr/bin/env python on the first line of a Python script?

If you have several versions of Python installed, /usr/bin/env will ensure the interpreter used is the first one on your environment's $PATH. The alternative would be to hardcode something like #!/usr/bin/python; that's ok, but less flexible.

In Unix, an executable file that's meant to be interpreted can indicate what interpreter to use by having a #! at the start of the first line, followed by the interpreter (and any flags it may need).

If you're talking about other platforms, of course, this rule does not apply (but that "shebang line" does no harm, and will help if you ever copy that script to a platform with a Unix base, such as Linux, Mac, etc).

How to permanently remove few commits from remote branch

Sometimes the easiest way to fix this issue is to make a new branch from the place where you know the code is good. Then you can leave the errant branch history alone in case you need to cherry-pick other commits from it later. This also ensures you did not lose any commit history.

From your local errant branch:

git log

copy the commit hash that you wanted the branch to be at and exit the git log

git checkout theHashYouJustCopied
git checkout -b your_new_awesome_branch

Now you have a new branch just the way you want it.

If you also needed to keep a specific commit from the errant branch that is not on your new branch, you can just cherry-pick that specific commit you need:

git checkout the_errant_branch
git log

Copy the commit hash of the one commit you need to pull into the good branch and exit the git log.

git checkout your_new_awesome_branch
git cherry-pick theHashYouJustCopied

Pat yourself on the back.

What techniques can be used to define a class in JavaScript, and what are their trade-offs?

The simple way is:

function Foo(a) {
  var that=this;

  function privateMethod() { .. }

  // public methods
  that.add = function(b) {
    return a + b;
  };
  that.avg = function(b) {
    return that.add(b) / 2; // calling another public method
  };
}

var x = new Foo(10);
alert(x.add(2)); // 12
alert(x.avg(20)); // 15

The reason for that is that this can be bound to something else if you give a method as an event handler, so you save the value during instantiation and use it later.

Edit: it's definitely not the best way, just a simple way. I'm waiting for good answers too!

Why doesn't java.util.Set have get(int index)?

That's true, element in Set are not ordered, by definition of the Set Collection. So they can't be access by an index.

But why don't we have a get(object) method, not by providing the index as parameter, but an object that is equal to the one we are looking for? By this way, we can access the data of the element inside the Set, just by knowing its attributes used by the equal method.

How to use HTTP_X_FORWARDED_FOR properly?

HTTP_CLIENT_IP is the most reliable way of getting the user's IP address. Next is HTTP_X_FORWARDED_FOR, followed by REMOTE_ADDR. Check all three, in that order, assuming that the first one that is set (isset($_SERVER['HTTP_CLIENT_IP']) returns true if that variable is set) is correct. You can independently check if the user is using a proxy using various methods. Check this out.

Switching between GCC and Clang/LLVM using CMake

System wide C++ change on Ubuntu:

sudo apt-get install clang
sudo update-alternatives --config c++

Will print something like this:

  Selection    Path              Priority   Status
------------------------------------------------------------
* 0            /usr/bin/g++       20        auto mode
  1            /usr/bin/clang++   10        manual mode
  2            /usr/bin/g++       20        manual mode

Then just select clang++.

Seeing if data is normally distributed in R

In addition to qqplots and the Shapiro-Wilk test, the following methods may be useful.

Qualitative:

  • histogram compared to the normal
  • cdf compared to the normal
  • ggdensity plot
  • ggqqplot

Quantitative:

The qualitive methods can be produced using the following in R:

library("ggpubr")
library("car")

h <- hist(data, breaks = 10, density = 10, col = "darkgray") 
xfit <- seq(min(data), max(data), length = 40) 
yfit <- dnorm(xfit, mean = mean(data), sd = sd(data)) 
yfit <- yfit * diff(h$mids[1:2]) * length(data) 
lines(xfit, yfit, col = "black", lwd = 2)

plot(ecdf(data), main="CDF")
lines(ecdf(rnorm(10000)),col="red")

ggdensity(data)

ggqqplot(data)

A word of caution - don't blindly apply tests. Having a solid understanding of stats will help you understand when to use which tests and the importance of assumptions in hypothesis testing.

Posting parameters to a url using the POST method without using a form

Using jQuery.post

$.post(
  "http://theurl.com",
  { key1: "value1", key2: "value2" },
  function(data) {
    alert("Response: " + data);
  }
);

no match for ‘operator<<’ in ‘std::operator

Obviously, the standard library provided operator does not know what to do with your user defined type mystruct. It only works for predefined data types. To be able to use it for your own data type, You need to overload operator << to take your user defined data type.

How to convert the background to transparent?

I would recommend this (just found via search):

  1. http://lunapic.com/editor/?action=load
  2. Browse for image to upload OR enter URL of the file (below the image)
    http://i.stack.imgur.com/2gQWg.png
  3. Edit menu/Transparent (last one)
  4. Click on the red area
  5. Behold :) below is your image, it's just white triangle with transparency...
    [dragging the image around in your browser for visibility,
    the gray background and the border is not part of the image]
    your image made transparent
  6. File menu/Save Image
    GIF/PNG/ICO image file formats support transparency, JPG doesn't!

Dynamically create checkbox with JQuery from text input

One of the elements to consider as you design your interface is on what event (when A takes place, B happens...) does the new checkbox end up being added?

Let's say there is a button next to the text box. When the button is clicked the value of the textbox is turned into a new checkbox. Our markup could resemble the following...

<div id="checkboxes">
    <input type="checkbox" /> Some label<br />
    <input type="checkbox" /> Some other label<br />
</div>

<input type="text" id="newCheckText" /> <button id="addCheckbox">Add Checkbox</button>

Based on this markup your jquery could bind to the click event of the button and manipulate the DOM.

$('#addCheckbox').click(function() {
    var text = $('#newCheckText').val();
    $('#checkboxes').append('<input type="checkbox" /> ' + text + '<br />');
});

Add carriage return to a string

string s2 = s1.Replace(",", ",\r\n");

Remove CSS class from element with JavaScript (no jQuery)

I use this JS snippet code :

First of all, I reach all the classes then according to index of my target class, I set className = "".

Target = document.getElementsByClassName("yourClass")[1];
Target.className="";

Disable mouse scroll wheel zoom on embedded Google Maps

Add style pointer-events:none; this working fine

<iframe style="pointer-events:none;" src=""></iframe>

Apache and Node.js on the Same Server

You can use a different approach such as writing a reverse proxy server with nodejs to proxy both apache and all other nodejs apps.

First you need to make apache run on a different port other than port 80. ex: port 8080

Then you can write a reverse proxy script with nodejs as:

var proxy = require('redbird')({port: 80, xfwd: false);

proxy.register("mydomain.me/blog", "http://mydomain.me:8080/blog");
proxy.register("mydomain.me", "http://mydomain.me:3000");

Following article describes the whole process of making this.

RUN APACHE WITH NODE JS REVERSE PROXY – USING REDBIRD

How can I echo a newline in a batch file?

echo. Enough said.

If you need it in a single line, use the &. For example,

echo Line 1 & echo. & echo line 3

would output as:

Line 1

line 3

Now, say you want something a bit fancier, ...

set n=^&echo.
echo hello %n% world

Outputs

hello
world

Then just throw in a %n% whenever you want a new line in an echo statement. This is more close to your \n used in various languages.

Breakdown

set n= sets the variable n equal to:

^ Nulls out the next symbol to follow:

& Means to do another command on the same line. We don't care about errorlevel(its an echo statement for crying out loud), so no && is needed.

echo. Continues the echo statement.

All of this works because you can actually create variables that are code, and use them inside of other commands. It is sort of like a ghetto function, since batch is not exactly the most advanced of shell scripting languages. This only works because batch's poor usage of variables, not designating between ints, chars, floats, strings, etc naturally.

If you are crafty, you could get this to work with other things. For example, using it to echo a tab

set t=^&echo.     ::there are spaces up to the double colon

CSS: Position loading indicator in the center of the screen

use position:fixed instead of position:absolute

The first one is relative to your screen window. (not affected by scrolling)

The second one is relative to the page. (affected by scrolling)

Note : IE6 doesn't support position:fixed.

Sum up a column from a specific row down

Something like this worked for me (references columns C and D from the row 8 till the end of the columns, in Excel 2013 if relevant):

=SUMIFS(INDIRECT(ADDRESS(ROW(D$8), COLUMN())&":"&ADDRESS(ROWS($C:$C), COLUMN())),INDIRECT("C$8:C"&ROWS($C:$C)),$C$2)

Using iText to convert HTML to PDF

I have ended up using ABCPdf from webSupergoo. It works really well and for about $350 it has saved me hours and hours based on your comments above. Thanks again Daniel and Bratch for your comments.

Display an array in a readable/hierarchical format

print_r() is mostly for debugging. If you want to print it in that format, loop through the array, and print the elements out.

foreach($data as $d){
  foreach($d as $v){
    echo $v."\n";
  }
}

What is the preferred syntax for defining enums in JavaScript?

This answer is an alternative approach for specific circumstances. I needed a set of bitmask constants based on attribute sub-values (cases where an attribute value is an array or list of values). It encompasses the equivalent of several overlapping enums.

I created a class to both store and generate the bitmask values. I can then use the pseudo-constant bitmask values this way to test, for example, if green is present in an RGB value:

if (value & Ez.G) {...}

In my code I create only one instance of this class. There doesn't seem to be a clean way to do this without instantiating at least one instance of the class. Here is the class declaration and bitmask value generation code:

class Ez {
constructor() {
    let rgba = ["R", "G", "B", "A"];
    let rgbm = rgba.slice();
    rgbm.push("M");              // for feColorMatrix values attribute
    this.createValues(rgba);
    this.createValues(["H", "S", "L"]);
    this.createValues([rgba, rgbm]);
    this.createValues([attX, attY, attW, attH]);
}
createValues(a) {                // a for array
    let i, j;
    if (isA(a[0])) {             // max 2 dimensions
        let k = 1;
        for (i of a[0]) {
            for (j of a[1]) {
                this[i + j] = k;
                k *= 2;
            }
        }
    }
    else {                       // 1D array is simple loop
        for (i = 0, j = 1; i < a.length; i++, j *= 2)
            this[a[i]] = j;
   }
}

The 2D array is for the SVG feColorMatrix values attribute, which is a 4x5 matrix of RGBA by RGBAM, where M is a multiplier. The resulting Ez properties are Ez.RR, Ez.RG, etc.

Difference between "as $key => $value" and "as $value" in PHP foreach

A very important place where it is REQUIRED to use the key => value pair in foreach loop is to be mentioned. Suppose you would want to add a new/sub-element to an existing item (in another key) in the $features array. You should do the following:

foreach($features as $key => $feature) {
    $features[$key]['new_key'] = 'new value';  
} 


Instead of this:

foreach($features as $feature) {
    $feature['new_key'] = 'new value';  
} 

The big difference here is that, in the first case you are accessing the array's sub-value via the main array itself with a key to the element which is currently being pointed to by the array pointer.

While in the second (which doesn't work for this purpose) you are assigning the sub-value in the array to a temporary variable $feature which is unset after each loop iteration.

Clear input fields on form submit

Use the reset function, which is available on the form element.

var form = document.getElementById("myForm");
form.reset();

Steps to upload an iPhone application to the AppStore

This arstechnica article describes the basic steps:

Start by visiting the program portal and make sure that your developer certificate is up to date. It expires every six months and, if you haven't requested that a new one be issued, you cannot submit software to App Store. For most people experiencing the "pink upload of doom," though, their certificates are already valid. What next?

Open your Xcode project and check that you've set the active SDK to one of the device choices, like Device - 2.2. Accidentally leaving the build settings to Simulator can be a big reason for the pink rejection. And that happens more often than many developers would care to admit.

Next, make sure that you've chosen a build configuration that uses your distribution (not your developer) certificate. Check this by double-clicking on your target in the Groups & Files column on the left of the project window. The Target Info window will open. Click the Build tab and review your Code Signing Identity. It should be iPhone Distribution: followed by your name or company name.

You may also want to confirm your application identifier in the Properties tab. Most likely, you'll have set the identifier properly when debugging with your developer certificate, but it never hurts to check.

The top-left of your project window also confirms your settings and configuration. It should read something like "Device - 2.2 | Distribution". This shows you the active SDK and configuration.

If your settings are correct but you still aren't getting that upload finished properly, clean your builds. Choose Build > Clean (Command-Shift-K) and click Clean. Alternatively, you can manually trash the build folder in your Project from Finder. Once you've cleaned, build again fresh.

If this does not produce an app that when zipped properly loads to iTunes Connect, quit and relaunch Xcode. I'm not kidding. This one simple trick solves more signing problems and "pink rejections of doom" than any other solution already mentioned.

Can I delete a git commit but keep the changes?

Using git 2.9 (precisely 2.9.2.windows.1) git reset HEAD^ prompts for more; not sure what is expected input here. Please refer below screenshot

enter image description here

Found other solution git reset HEAD~#numberOfCommits using which we can choose to select number of local commits you want to reset by keeping your changes intact. Hence, we get an opportunity to throw away all local commits as well as limited number of local commits.

Refer below screenshots showing git reset HEAD~1 in action: enter image description here

enter image description here

C#: How to make pressing enter in a text box trigger a button, yet still allow shortcuts such as "Ctrl+A" to get through?

You do not need any client side code if doing this is ASP.NET. The example below is a boostrap input box with a search button with an fontawesome icon.

You will see that in place of using a regular < div > tag with a class of "input-group" I have used a asp:Panel. The DefaultButton property set to the id of my button, does the trick.

In example below, after typing something in the input textbox, you just hit enter and that will result in a submit.

<asp:Panel DefaultButton="btnblogsearch" runat="server" CssClass="input-group blogsearch">
<asp:TextBox ID="txtSearchWords" CssClass="form-control" runat="server" Width="100%" Placeholder="Search for..."></asp:TextBox>
<span class="input-group-btn">
    <asp:LinkButton ID="btnblogsearch" runat="server" CssClass="btn btn-default"><i class="fa fa-search"></i></asp:LinkButton>
</span></asp:Panel>

How to remove duplicates from a list?

The correct answer for Java is use a Set. If you already have a List<Customer> and want to de duplicate it

Set<Customer> s = new HashSet<Customer>(listCustomer);

Otherise just use a Set implemenation HashSet, TreeSet directly and skip the List construction phase.

You will need to override hashCode() and equals() on your domain classes that are put in the Set as well to make sure that the behavior you want actually what you get. equals() can be as simple as comparing unique ids of the objects to as complex as comparing every field. hashCode() can be as simple as returning the hashCode() of the unique id' String representation or the hashCode().

Is there a Python equivalent to Ruby's string interpolation?

I've developed the interpy package, that enables string interpolation in Python.

Just install it via pip install interpy. And then, add the line # coding: interpy at the beginning of your files!

Example:

#!/usr/bin/env python
# coding: interpy

name = "Spongebob Squarepants"
print "Who lives in a Pineapple under the sea? \n#{name}."

React onClick and preventDefault() link refresh/redirect?

A nice and simple option that worked for me was:

<a href="javascript: false" onClick={this.handlerName}>Click Me</a>

Creating a pandas DataFrame from columns of other DataFrames with similar indexes

What you ask for is the join operation. With the how argument, you can define how unique indices are handled. Here, some article, which looks helpful concerning this point. In the example below, I left out cosmetics (like renaming columns) for simplicity.

Code

import numpy as np
import pandas as pd
df1 = pd.DataFrame(np.random.randn(5,3), index=pd.date_range('01/02/2014',periods=5,freq='D'), columns=['a','b','c'] )
df2 = pd.DataFrame(np.random.randn(8,3), index=pd.date_range('01/01/2014',periods=8,freq='D'), columns=['a','b','c'] )

df3 = df1.join(df2, how='outer', lsuffix='_df1', rsuffix='_df2')
print(df3)

Output

               a_df1     b_df1     c_df1     a_df2     b_df2     c_df2
2014-01-01       NaN       NaN       NaN  0.109898  1.107033 -1.045376
2014-01-02  0.573754  0.169476 -0.580504 -0.664921 -0.364891 -1.215334
2014-01-03 -0.766361 -0.739894 -1.096252  0.962381 -0.860382 -0.703269
2014-01-04  0.083959 -0.123795 -1.405974  1.825832 -0.580343  0.923202
2014-01-05  1.019080 -0.086650  0.126950 -0.021402 -1.686640  0.870779
2014-01-06 -1.036227 -1.103963 -0.821523 -0.943848 -0.905348  0.430739
2014-01-07       NaN       NaN       NaN  0.312005  0.586585  1.531492
2014-01-08       NaN       NaN       NaN -0.077951 -1.189960  0.995123

What does the JSLint error 'body of a for in should be wrapped in an if statement' mean?

First of all, never use a for in loop to enumerate over an array. Never. Use good old for(var i = 0; i<arr.length; i++).

The reason behind this is the following: each object in JavaScript has a special field called prototype. Everything you add to that field is going to be accessible on every object of that type. Suppose you want all arrays to have a cool new function called filter_0 that will filter zeroes out.

Array.prototype.filter_0 = function() {
    var res = [];
    for (var i = 0; i < this.length; i++) {
        if (this[i] != 0) {
            res.push(this[i]);
        }
    }
    return res;
};

console.log([0, 5, 0, 3, 0, 1, 0].filter_0());
//prints [5,3,1]

This is a standard way to extend objects and add new methods. Lots of libraries do this. However, let's look at how for in works now:

var listeners = ["a", "b", "c"];
for (o in listeners) {
    console.log(o);
}
//prints:
//  0
//  1
//  2
//  filter_0

Do you see? It suddenly thinks filter_0 is another array index. Of course, it is not really a numeric index, but for in enumerates through object fields, not just numeric indexes. So we're now enumerating through every numeric index and filter_0. But filter_0 is not a field of any particular array object, every array object has this property now.

Luckily, all objects have a hasOwnProperty method, which checks if this field really belongs to the object itself or if it is simply inherited from the prototype chain and thus belongs to all the objects of that type.

for (o in listeners) {
    if (listeners.hasOwnProperty(o)) {
       console.log(o);
    }
}
 //prints:
 //  0
 //  1
 //  2

Note, that although this code works as expected for arrays, you should never, never, use for in and for each in for arrays. Remember that for in enumerates the fields of an object, not array indexes or values.

var listeners = ["a", "b", "c"];
listeners.happy = "Happy debugging";

for (o in listeners) {
    if (listeners.hasOwnProperty(o)) {
       console.log(o);
    }
}

 //prints:
 //  0
 //  1
 //  2
 //  happy

how to convert current date to YYYY-MM-DD format with angular 2

Solution in ES6/TypeScript:

let d = new Date;
console.log(d, [`${d.getFullYear()}`, `0${d.getMonth()}`.substr(-2), `0${d.getDate()}`.substr(-2)].join("-"));

What is the &#xA; character?

It is the equivalent to \n -> LF (Line Feed).

Sometimes it is used in HTML and JavaScript. Otherwise in .NET environments, use Environment.NewLine.

Access 2013 - Cannot open a database created with a previous version of your application

Best solution would be to convert existing databases BEFORE upgrading to newer version/s of Access. Surely Microsoft should be warning users about this problem when upgrades are about to be installed.

About catching ANY exception

You can but you probably shouldn't:

try:
    do_something()
except:
    print "Caught it!"

However, this will also catch exceptions like KeyboardInterrupt and you usually don't want that, do you? Unless you re-raise the exception right away - see the following example from the docs:

try:
    f = open('myfile.txt')
    s = f.readline()
    i = int(s.strip())
except IOError as (errno, strerror):
    print "I/O error({0}): {1}".format(errno, strerror)
except ValueError:
    print "Could not convert data to an integer."
except:
    print "Unexpected error:", sys.exc_info()[0]
    raise

matching query does not exist Error in Django

You may try this way. just use a function to get your object

def get_object(self, id):
    try:
        return UniversityDetails.objects.get(email__exact=email)
    except UniversityDetails.DoesNotExist:
        return False

Float to String format specifier

Firstly, as Etienne says, float in C# is Single. It is just the C# keyword for that data type.

So you can definitely do this:

float f = 13.5f;
string s = f.ToString("R");

Secondly, you have referred a couple of times to the number's "format"; numbers don't have formats, they only have values. Strings have formats. Which makes me wonder: what is this thing you have that has a format but is not a string? The closest thing I can think of would be decimal, which does maintain its own precision; however, calling simply decimal.ToString should have the effect you want in that case.

How about including some example code so we can see exactly what you're doing, and why it isn't achieving what you want?

Xpath for href element

Best way to locate anchor elements is to use link=Re-Call:

selenium.click("link=Re-Call");

It will work..

Error loading the SDK when Eclipse starts

I had the same problem and it appears when I updated my sdk packages and added sdk 22 I removed all wear packages from sdk 22 as well as other sdks but problem wasn't resolved I Updated all of my sdk packages again from sdk manager then problem solved and error gone.

I think there's been few bugs with eclipse and android wear packages which are fixed in new updates available in sdk manager

Installing lxml module in python

Just do:

sudo apt-get install python-lxml

For Python 2 (e.g., required by Inkscape):

sudo apt-get install python2-lxml

If you are planning to install from source, then albertov's answer will help. But unless there is a reason, don't, just install it from the repository.

custom facebook share button

Include the facebook button on the page which you want to share

<a target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=http://trial.com/news.php?newsid=<?php echo $content; ?>"> 

                    <img src="http://trial/new_img/facebook_link.png" style=" border: 1px solid #d9d9d9; box-shadow: 0 4px 7px 0 #a5a5a5; padding: 5px;" title="facebook_link" alt="facebook_link" />

                    </a>

Java Replacing multiple different substring in a string at once (or in the most efficient way)

The below is based on Todd Owen's answer. That solution has the problem that if the replacements contain characters that have special meaning in regular expressions, you can get unexpected results. I also wanted to be able to optionally do a case-insensitive search. Here is what I came up with:

/**
 * Performs simultaneous search/replace of multiple strings. Case Sensitive!
 */
public String replaceMultiple(String target, Map<String, String> replacements) {
  return replaceMultiple(target, replacements, true);
}

/**
 * Performs simultaneous search/replace of multiple strings.
 * 
 * @param target        string to perform replacements on.
 * @param replacements  map where key represents value to search for, and value represents replacem
 * @param caseSensitive whether or not the search is case-sensitive.
 * @return replaced string
 */
public String replaceMultiple(String target, Map<String, String> replacements, boolean caseSensitive) {
  if(target == null || "".equals(target) || replacements == null || replacements.size() == 0)
    return target;

  //if we are doing case-insensitive replacements, we need to make the map case-insensitive--make a new map with all-lower-case keys
  if(!caseSensitive) {
    Map<String, String> altReplacements = new HashMap<String, String>(replacements.size());
    for(String key : replacements.keySet())
      altReplacements.put(key.toLowerCase(), replacements.get(key));

    replacements = altReplacements;
  }

  StringBuilder patternString = new StringBuilder();
  if(!caseSensitive)
    patternString.append("(?i)");

  patternString.append('(');
  boolean first = true;
  for(String key : replacements.keySet()) {
    if(first)
      first = false;
    else
      patternString.append('|');

    patternString.append(Pattern.quote(key));
  }
  patternString.append(')');

  Pattern pattern = Pattern.compile(patternString.toString());
  Matcher matcher = pattern.matcher(target);

  StringBuffer res = new StringBuffer();
  while(matcher.find()) {
    String match = matcher.group(1);
    if(!caseSensitive)
      match = match.toLowerCase();
    matcher.appendReplacement(res, replacements.get(match));
  }
  matcher.appendTail(res);

  return res.toString();
}

Here are my unit test cases:

@Test
public void replaceMultipleTest() {
  assertNull(ExtStringUtils.replaceMultiple(null, null));
  assertNull(ExtStringUtils.replaceMultiple(null, Collections.<String, String>emptyMap()));
  assertEquals("", ExtStringUtils.replaceMultiple("", null));
  assertEquals("", ExtStringUtils.replaceMultiple("", Collections.<String, String>emptyMap()));

  assertEquals("folks, we are not sane anymore. with me, i promise you, we will burn in flames", ExtStringUtils.replaceMultiple("folks, we are not winning anymore. with me, i promise you, we will win big league", makeMap("win big league", "burn in flames", "winning", "sane")));

  assertEquals("bcaacbbcaacb", ExtStringUtils.replaceMultiple("abccbaabccba", makeMap("a", "b", "b", "c", "c", "a")));
  assertEquals("bcaCBAbcCCBb", ExtStringUtils.replaceMultiple("abcCBAabCCBa", makeMap("a", "b", "b", "c", "c", "a")));
  assertEquals("bcaacbbcaacb", ExtStringUtils.replaceMultiple("abcCBAabCCBa", makeMap("a", "b", "b", "c", "c", "a"), false));

  assertEquals("c colon  backslash temp backslash  star  dot  star ", ExtStringUtils.replaceMultiple("c:\\temp\\*.*", makeMap(".", " dot ", ":", " colon ", "\\", " backslash ", "*", " star "), false));
}

private Map<String, String> makeMap(String ... vals) {
  Map<String, String> map = new HashMap<String, String>(vals.length / 2);
  for(int i = 1; i < vals.length; i+= 2)
    map.put(vals[i-1], vals[i]);
  return map;
}

How to pass parameters to a Script tag?

JQuery has a way to pass parameters from HTML to javascript:

Put this in the myhtml.html file:

<!-- Import javascript -->
<script src="//code.jquery.com/jquery-1.11.2.min.js"></script>
<!-- Invoke a different javascript file called subscript.js -->
<script id="myscript" src="subscript.js" video_filename="foobar.mp4">/script>

In the same directory make a subscript.js file and put this in there:

//Use jquery to look up the tag with the id of 'myscript' above.  Get 
//the attribute called video_filename, stuff it into variable filename.
var filename = $('#myscript').attr("video_filename");

//print filename out to screen.
document.write(filename);

Analyze Result:

Loading the myhtml.html page has 'foobar.mp4' print to screen. The variable called video_filename was passed from html to javascript. Javascript printed it to screen, and it appeared as embedded into the html in the parent.

jsfiddle proof that the above works:

http://jsfiddle.net/xqr77dLt/

How to compare two dates?

Use time

Let's say you have the initial dates as strings like these:
date1 = "31/12/2015"
date2 = "01/01/2016"

You can do the following:
newdate1 = time.strptime(date1, "%d/%m/%Y") and newdate2 = time.strptime(date2, "%d/%m/%Y") to convert them to python's date format. Then, the comparison is obvious:

newdate1 > newdate2 will return False
newdate1 < newdate2 will return True

Replacing a character from a certain index

# Use slicing to extract those parts of the original string to be kept
s = s[:position] + replacement + s[position+length_of_replaced:]

# Example: replace 'sat' with 'slept'
text = "The cat sat on the mat"
text = text[:8] + "slept" + text[11:]

I/P : The cat sat on the mat

O/P : The cat slept on the mat

C++ initial value of reference to non-const must be an lvalue

The &nKByte creates a temporary value, which cannot be bound to a reference to non-const.

You could change void test(float *&x) to void test(float * const &x) or you could just drop the pointer altogether and use void test(float &x); /*...*/ test(nKByte);.

How do you round UP a number in Python?

If working with integers, one way of rounding up is to take advantage of the fact that // rounds down: Just do the division on the negative number, then negate the answer. No import, floating point, or conditional needed.

rounded_up = -(-numerator // denominator)

For example:

>>> print(-(-101 // 5))
21

npm global path prefix

Any one got the same issue it's related to a conflict between brew and npm Please check this solution https://gist.github.com/DanHerbert/9520689

Android Stop Emulator from Command Line

To automate this, you can use any script or app that can send a string to a socket. I personally like nc (netcat) under cygwin. As I said before, I use it like this:

$ echo kill | nc -w 2 localhost 5554

(that means to send "kill" string to the port 5554 on localhost, and terminate netcat after 2 seconds.)

Defining an abstract class without any abstract methods

Yes you can. The abstract class used in java signifies that you can't create an object of the class. And an abstract method the subclasses have to provide an implementation for that method.

So you can easily define an abstract class without any abstract method.

As for Example :

public abstract class AbstractClass{

    public String nonAbstractMethodOne(String param1,String param2){
        String param = param1 + param2;
        return param;
    }

    public static void nonAbstractMethodTwo(String param){
        System.out.println("Value of param is "+param);
    }
}

This is fine.

Using media breakpoints in Bootstrap 4-alpha

Use breakpoint mixins like this:

.something {
    padding: 5px;
    @include media-breakpoint-up(sm) { 
        padding: 20px;
    }
    @include media-breakpoint-up(md) { 
        padding: 40px;
    }
}

v4 breakpoints reference

v4 alpha6 breakpoints reference


Below full options and values.

Breakpoint & up (toggle on value and above):

@include media-breakpoint-up(xs) { ... }
@include media-breakpoint-up(sm) { ... }
@include media-breakpoint-up(md) { ... }
@include media-breakpoint-up(lg) { ... }
@include media-breakpoint-up(xl) { ... }

breakpoint & up values:

// Extra small devices (portrait phones, less than 576px)
// No media query since this is the default in Bootstrap

// Small devices (landscape phones, 576px and up)
@media (min-width: 576px) { ... }

// Medium devices (tablets, 768px and up)
@media (min-width: 768px) { ... }

// Large devices (desktops, 992px and up)
@media (min-width: 992px) { ... }

// Extra large devices (large desktops, 1200px and up)
@media (min-width: 1200px) { ... }

breakpoint & down (toggle on value and down):

@include media-breakpoint-down(xs) { ... }
@include media-breakpoint-down(sm) { ... }
@include media-breakpoint-down(md) { ... }
@include media-breakpoint-down(lg) { ... }

breakpoint & down values:

// Extra small devices (portrait phones, less than 576px)
@media (max-width: 575px) { ... }

// Small devices (landscape phones, less than 768px)
@media (max-width: 767px) { ... }

// Medium devices (tablets, less than 992px)
@media (max-width: 991px) { ... }

// Large devices (desktops, less than 1200px)
@media (max-width: 1199px) { ... }

// Extra large devices (large desktops)
// No media query since the extra-large breakpoint has no upper bound on its width

breakpoint only:

@include media-breakpoint-only(xs) { ... }
@include media-breakpoint-only(sm) { ... }
@include media-breakpoint-only(md) { ... }
@include media-breakpoint-only(lg) { ... }
@include media-breakpoint-only(xl) { ... }

breakpoint only values (toggle in between values only):

// Extra small devices (portrait phones, less than 576px)
@media (max-width: 575px) { ... }

// Small devices (landscape phones, 576px and up)
@media (min-width: 576px) and (max-width: 767px) { ... }

// Medium devices (tablets, 768px and up)
@media (min-width: 768px) and (max-width: 991px) { ... }

// Large devices (desktops, 992px and up)
@media (min-width: 992px) and (max-width: 1199px) { ... }

// Extra large devices (large desktops, 1200px and up)
@media (min-width: 1200px) { ... }

Java client certificates over HTTPS/SSL

If you are dealing with a web service call using the Axis framework, there is a much simpler answer. If all want is for your client to be able to call the SSL web service and ignore SSL certificate errors, just put this statement before you invoke any web services:

System.setProperty("axis.socketSecureFactory", "org.apache.axis.components.net.SunFakeTrustSocketFactory");

The usual disclaimers about this being a Very Bad Thing to do in a production environment apply.

I found this at the Axis wiki.

Shortcut for echo "<pre>";print_r($myarray);echo "</pre>";

Both old and accepted, however, I'll just leave this here:

function dump(){
    echo (php_sapi_name() !== 'cli') ? '<pre>' : '';
    foreach(func_get_args() as $arg){
        echo preg_replace('#\n{2,}#', "\n", print_r($arg, true));
    }
    echo (php_sapi_name() !== 'cli') ? '</pre>' : '';
}

Takes an arbitrary number of arguments, and wraps each in <pre> for CGI requests. In CLI requests it skips the <pre> tag generation for clean output.

dump(array('foo'), array('bar', 'zip'));
/*
CGI request                          CLI request

<pre>                                Array
Array                                (
(                                        [0] => foo
    [0] => foo                       )
)                                    Array
</pre>                               (
<pre>                                    [0] => bar
Array                                    [1] => zip
(                                    )
    [0] => bar
    [0] => zip
)
</pre>

How to use environment variables in docker compose

You cannot ... yet. But this is an alternative, think like a docker-composer.yml generator:

https://gist.github.com/Vad1mo/9ab63f28239515d4dafd

Basically a shell script that will replace your variables. Also you can use Grunt task to build your docker compose file at the end of your CI process.

Dockerfile if else condition with external arguments

It might not look that clean but you can have your Dockerfile (conditional) as follow:

FROM centos:7
ARG arg
RUN if [[ -z "$arg" ]] ; then echo Argument not provided ; else echo Argument is $arg ; fi

and then build the image as:

docker build -t my_docker . --build-arg arg=45

or

docker build -t my_docker .

Checking on a thread / remove from list

As TokenMacGuy says, you should use thread.is_alive() to check if a thread is still running. To remove no longer running threads from your list you can use a list comprehension:

for t in my_threads:
    if not t.is_alive():
        # get results from thread
        t.handled = True
my_threads = [t for t in my_threads if not t.handled]

This avoids the problem of removing items from a list while iterating over it.

Styling Form with Label above Inputs

I'd make both the input and label elements display: block , and then split the name label & input, and the email label & input into div's and float them next to each other.

_x000D_
_x000D_
input, label {_x000D_
    display:block;_x000D_
}
_x000D_
<form name="message" method="post">_x000D_
    <section>_x000D_
_x000D_
  <div style="float:left;margin-right:20px;">_x000D_
    <label for="name">Name</label>_x000D_
    <input id="name" type="text" value="" name="name">_x000D_
  </div>_x000D_
_x000D_
  <div style="float:left;">_x000D_
    <label for="email">Email</label>_x000D_
    <input id="email" type="text" value="" name="email">_x000D_
  </div>_x000D_
_x000D_
  <br style="clear:both;" />_x000D_
_x000D_
    </section>_x000D_
_x000D_
    <section>_x000D_
_x000D_
    <label for="subject">Subject</label>_x000D_
    <input id="subject" type="text" value="" name="subject">_x000D_
    <label for="message">Message</label>_x000D_
    <input id="message" type="text" value="" name="message">_x000D_
_x000D_
    </section>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Python xml ElementTree from a string source?

You can parse the text as a string, which creates an Element, and create an ElementTree using that Element.

import xml.etree.ElementTree as ET
tree = ET.ElementTree(ET.fromstring(xmlstring))

I just came across this issue and the documentation, while complete, is not very straightforward on the difference in usage between the parse() and fromstring() methods.

Difference between dates in JavaScript

If you are looking for a difference expressed as a combination of years, months, and days, I would suggest this function:

_x000D_
_x000D_
function interval(date1, date2) {_x000D_
    if (date1 > date2) { // swap_x000D_
        var result = interval(date2, date1);_x000D_
        result.years  = -result.years;_x000D_
        result.months = -result.months;_x000D_
        result.days   = -result.days;_x000D_
        result.hours  = -result.hours;_x000D_
        return result;_x000D_
    }_x000D_
    result = {_x000D_
        years:  date2.getYear()  - date1.getYear(),_x000D_
        months: date2.getMonth() - date1.getMonth(),_x000D_
        days:   date2.getDate()  - date1.getDate(),_x000D_
        hours:  date2.getHours() - date1.getHours()_x000D_
    };_x000D_
    if (result.hours < 0) {_x000D_
        result.days--;_x000D_
        result.hours += 24;_x000D_
    }_x000D_
    if (result.days < 0) {_x000D_
        result.months--;_x000D_
        // days = days left in date1's month, _x000D_
        //   plus days that have passed in date2's month_x000D_
        var copy1 = new Date(date1.getTime());_x000D_
        copy1.setDate(32);_x000D_
        result.days = 32-date1.getDate()-copy1.getDate()+date2.getDate();_x000D_
    }_x000D_
    if (result.months < 0) {_x000D_
        result.years--;_x000D_
        result.months+=12;_x000D_
    }_x000D_
    return result;_x000D_
}_x000D_
_x000D_
// Be aware that the month argument is zero-based (January = 0)_x000D_
var date1 = new Date(2015, 4-1, 6);_x000D_
var date2 = new Date(2015, 5-1, 9);_x000D_
_x000D_
document.write(JSON.stringify(interval(date1, date2)));
_x000D_
_x000D_
_x000D_

This solution will treat leap years (29 February) and month length differences in a way we would naturally do (I think).

So for example, the interval between 28 February 2015 and 28 March 2015 will be considered exactly one month, not 28 days. If both those days are in 2016, the difference will still be exactly one month, not 29 days.

Dates with exactly the same month and day, but different year, will always have a difference of an exact number of years. So the difference between 2015-03-01 and 2016-03-01 will be exactly 1 year, not 1 year and 1 day (because of counting 365 days as 1 year).

Fragment transaction animation: slide in and slide out

UPDATE For Android v19+ see this link via @Sandra

You can create your own animations. Place animation XML files in res > anim

enter_from_left.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false">
  <translate 
      android:fromXDelta="-100%p" android:toXDelta="0%"
      android:fromYDelta="0%" android:toYDelta="0%"
      android:duration="@android:integer/config_mediumAnimTime"/>
</set>

enter_from_right.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false">
  <translate
     android:fromXDelta="100%p" android:toXDelta="0%"
     android:fromYDelta="0%" android:toYDelta="0%"
     android:duration="@android:integer/config_mediumAnimTime" />
</set>

exit_to_left.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false">
  <translate 
      android:fromXDelta="0%" android:toXDelta="-100%p"
      android:fromYDelta="0%" android:toYDelta="0%"
      android:duration="@android:integer/config_mediumAnimTime"/>
</set>

exit_to_right.xml

<?xml version="1.0" encoding="utf-8"?>
<set xmlns:android="http://schemas.android.com/apk/res/android"
     android:shareInterpolator="false">
  <translate
     android:fromXDelta="0%" android:toXDelta="100%p"
     android:fromYDelta="0%" android:toYDelta="0%"
     android:duration="@android:integer/config_mediumAnimTime" />
</set>

you can change the duration to short animation time

android:duration="@android:integer/config_shortAnimTime"

or long animation time

android:duration="@android:integer/config_longAnimTime" 

USAGE (note that the order in which you call methods on the transaction matters. Add the animation before you call .replace, .commit):

FragmentTransaction transaction = supportFragmentManager.beginTransaction();
transaction.setCustomAnimations(R.anim.enter_from_right, R.anim.exit_to_left, R.anim.enter_from_left, R.anim.exit_to_right);
transaction.replace(R.id.content_frame, fragment);
transaction.addToBackStack(null);
transaction.commit();

How do I parse JSON with Ruby on Rails?

These answers are a bit dated. Therefore I give you:

hash = JSON.parse string

Rails should automagically load the json module for you, so you don't need to add require 'json'.

gitx How do I get my 'Detached HEAD' commits back into master

If checkout master was the last thing you did, then the reflog entry HEAD@{1} will contain your commits (otherwise use git reflog or git log -p to find them). Use git merge HEAD@{1} to fast forward them into master.

EDIT:

As noted in the comments, Git Ready has a great article on this.

git reflog and git reflog --all will give you the commit hashes of the mis-placed commits.

Git Ready: Reflog, Your Safety Net

Source: http://gitready.com/intermediate/2009/02/09/reflog-your-safety-net.html

Autowiring fails: Not an managed Type

Just in case some other poor sod ends up here because they are having the same issue I was: if you have multiple data sources and this is happening with the non-primary data source, then the problem might be with that config. The data source, entity manager factory, and transaction factory all need to be correctly configured, but also -- and this is what tripped me up -- MAKE SURE TO TIE THEM ALL TOGETHER! @EnableJpaRepositories (configuration class annotation) must include entityManagerFactoryRef and transactionManagerRef to pick up all the configuration!

The example in this blog finally helped me see what I was missing, which (for quick reference) were the refs here:

@EnableJpaRepositories(
    entityManagerFactoryRef = "barEntityManagerFactory",
    transactionManagerRef = "barTransactionManager",
    basePackages = "com.foobar.bar")

Hope this helps save someone else from the struggle I've endured!

How to construct a relative path in Java from two absolute paths (or URLs)?

Here is a solution other library free:

Path sourceFile = Paths.get("some/common/path/example/a/b/c/f1.txt");
Path targetFile = Paths.get("some/common/path/example/d/e/f2.txt"); 
Path relativePath = sourceFile.relativize(targetFile);
System.out.println(relativePath);

Outputs

..\..\..\..\d\e\f2.txt

[EDIT] actually it outputs on more ..\ because of the source is file not a directory. Correct solution for my case is:

Path sourceFile = Paths.get(new File("some/common/path/example/a/b/c/f1.txt").parent());
Path targetFile = Paths.get("some/common/path/example/d/e/f2.txt"); 
Path relativePath = sourceFile.relativize(targetFile);
System.out.println(relativePath);