Programs & Examples On #Force based algorithm

Should I initialize variable within constructor or outside constructor

I have the practice (habit) of almost always initializing in the contructor for two reasons, one in my opinion it adds to readablitiy (cleaner), and two there is more logic control in the constructor than in one line. Even if initially the instance variable doesn't require logic, having it in the constructor gives more flexibility to add logic in the future if needed.

As to the concern mentioned above about multiple constructors, that's easily solved by having one no-arg constructor that initializes all the instance variables that are initilized the same for all constructors and then each constructor calls this() at the first line. That solves your reduncancy issues.

How to remove a package in sublime text 2

go to package control by pressing Ctrl + Shift + p

type "remove package"

and type your package/plugin to uninstall and remove it

Read XML file into XmlDocument

var doc = new XmlDocument(); 
doc.Loadxml(@"c:\abc.xml");

Simple logical operators in Bash

very close

if [[ $varA -eq 1 ]] && [[ $varB == 't1' || $varC == 't2' ]]; 
  then 
    scale=0.05
  fi

should work.

breaking it down

[[ $varA -eq 1 ]] 

is an integer comparison where as

$varB == 't1'

is a string comparison. otherwise, I am just grouping the comparisons correctly.

Double square brackets delimit a Conditional Expression. And, I find the following to be a good reading on the subject: "(IBM) Demystify test, [, [[, ((, and if-then-else"

Sum values in a column based on date

Use pivot tables, it will definitely save you time. If you are using excel 2007+ use tables (structured references) to keep your table dynamic. However if you insist on using functions, go with Smandoli's suggestion. Again, if you are on 2007+ use SUMIFS, it's faster compared to SUMIF.

Node.js: get path from the request

A more modern solution that utilises the URL WebAPI:

(req, res) => {
  const { pathname } = new URL(req.url || '', `https://${req.headers.host}`)
}

Cannot set some HTTP headers when using System.Net.WebRequest

I had the same exception when my code tried to set the "Accept" header value like this:

WebRequest request = WebRequest.Create("http://someServer:6405/biprws/logon/long");
request.Headers.Add("Accept", "application/json");

The solution was to change it to this:

HttpWebRequest request = (HttpWebRequest)WebRequest.Create("http://someServer:6405/biprws/logon/long");
request.Accept = "application/json";

How do you create a hidden div that doesn't create a line break or horizontal space?

To prevent the checkbox from taking up any space without removing it from the DOM, use hidden.

<div hidden id="divCheckbox">

To prevent the checkbox from taking up any space and also removing it from the DOM, use display: none.

<div id="divCheckbox" style="display:none">

SHA512 vs. Blowfish and Bcrypt

I agree with erickson's answer, with one caveat: for password authentication purposes, bcrypt is far better than a single iteration of SHA-512 - simply because it is far slower. If you don't get why slowness is an advantage in this particular game, read the article you linked to again (scroll down to "Speed is exactly what you don’t want in a password hash function.").

You can of course build a secure password hashing algorithm around SHA-512 by iterating it thousands of times, just like the way PHK's MD5 algorithm works. Ulrich Drepper did exactly this, for glibc's crypt(). There's no particular reason to do this, though, if you already have a tested bcrypt implementation available.

Lists: Count vs Count()

If you by any chance wants to change the type of your collection you are better served with the Count() extension. This way you don't have to refactor your code (to use Length for instance).

Input and output numpy arrays to h5py

A cleaner way to handle file open/close and avoid memory leaks:

Prep:

import numpy as np
import h5py

data_to_write = np.random.random(size=(100,20)) # or some such

Write:

with h5py.File('name-of-file.h5', 'w') as hf:
    hf.create_dataset("name-of-dataset",  data=data_to_write)

Read:

with h5py.File('name-of-file.h5', 'r') as hf:
    data = hf['name-of-dataset'][:]

How to add minutes to current time in swift

Save this little extension:

extension Int {

 var seconds: Int {
    return self
 }

 var minutes: Int {
    return self.seconds * 60
 }

 var hours: Int {
    return self.minutes * 60
 }

 var days: Int {
    return self.hours * 24
 }

 var weeks: Int {
    return self.days * 7
 }

 var months: Int {
    return self.weeks * 4
 }

 var years: Int {
    return self.months * 12
 }
}

Then use it intuitively like:

let threeDaysLater = TimeInterval(3.days)
date.addingTimeInterval(threeDaysLater)

How to run a command as a specific user in an init script?

I usually do it the way that you are doing it (i.e. sudo -u username command). But, there is also the 'djb' way to run a daemon with privileges of another user. See: http://thedjbway.b0llix.net/daemontools/uidgid.html

Does Java support structs?

Structs "really" pure aren't supported in Java. E.g., C# supports struct definitions that represent values and can be allocated anytime.

In Java, the unique way to get an approximation of C++ structs

struct Token
{
    TokenType type;
    Stringp stringValue;
    double mathValue;
}

// Instantiation

{
    Token t = new Token;
}

without using a (static buffer or list) is doing something like

var type = /* TokenType */ ;
var stringValue = /* String */ ;
var mathValue = /* double */ ;

So, simply allocate variables or statically define them into a class.

Mockito: List Matchers with generics

For Java 8 and above, it's easy:

when(mock.process(Matchers.anyList()));

For Java 7 and below, the compiler needs a bit of help. Use anyListOf(Class<T> clazz):

when(mock.process(Matchers.anyListOf(Bar.class)));

How to fix Error: laravel.log could not be opened?

It might be late but may help someone, changing directory permissions worked for me.

Assuming that your Laravel project is in /var/www/html/ directory. Goto this directory.

cd /var/www/html/

Then change permissions of storage/ and bootstrap/cache/ directories.

sudo chmod -R 777 storage/
sudo chmod -R 777 bootstrap/cache/

JavaFX How to set scene background image

You can change style directly for scene using .root class:

.root {
    -fx-background-image: url("https://www.google.com/images/srpr/logo3w.png");
}

Add this to CSS and load it as "Uluk Biy" described in his answer.

Nginx 403 forbidden for all files

One permission requirement that is often overlooked is a user needs x permissions in every parent directory of a file to access that file. Check the permissions on /, /home, /home/demo, etc. for www-data x access. My guess is that /home is probably 770 and www-data can't chdir through it to get to any subdir. If it is, try chmod o+x /home (or whatever dir is denying the request).

EDIT: To easily display all the permissions on a path, you can use namei -om /path/to/check

Get DateTime.Now with milliseconds precision

I was looking for a similar solution, base on what was suggested on this thread, I use the following DateTime.Now.ToString("MM/dd/yyyy hh:mm:ss.fff") , and it work like charm. Note: that .fff are the precision numbers that you wish to capture.

Changing Shell Text Color (Windows)

Try to look at the following link: Python | change text color in shell

Or read here: http://bytes.com/topic/python/answers/21877-coloring-print-lines

In general solution is to use ANSI codes while printing your string.

There is a solution that performs exactly what you need.

How to set JFrame to appear centered, regardless of monitor resolution?

i am using NetBeans IDE 7.2.1 as my developer environmental and there you have an option to configure the JForm properties.

in the JForm Properties go to the 'Code' tab and configure the 'Generate Center'. you will need first to set the Form Size Policy to 'Generate Resize Code'.

Difference between xcopy and robocopy

They are both rubbish! XCOPY was older and unreliable, so Microsoft replaced it with ROBOCOPY, which is still rubbish.

http://answers.microsoft.com/en-us/windows/forum/windows_8-files/robocopy-appears-to-be-broken-in-windows-8/9a7634c4-3a9d-4f2d-97ae-093002a638a9

Don't worry though, it is a long-standing tradition that was started by the original COPY command, which to this day, still needs the /B switch to get it to actually copy properly!

filename.whl is not supported wheel on this platform

I tried to install scikit-image but got the following error when I tried to install the .whl file even though my installed version of python was 2.7 32-bit. scikit_image-0.12.3-cp27-cp27m-win32.whl is not a supported wheel on this platform.

However I also got this message before the error message:

You are using pip version 7.1.0, however version 8.1.2 is available.
You should consider upgrading via the 'python -m pip install --upgrade pip' command.

I then ran the command python -m pip install --upgrade pip and then pip install scikit_image-0.12.3-cp27-cp27m-win32.whl worked fine. I hope this can help someone!

What is C# analog of C++ std::pair?

I was asking the same question just now after a quick google I found that There is a pair class in .NET except its in the System.Web.UI ^ ~ ^ (http://msdn.microsoft.com/en-us/library/system.web.ui.pair.aspx) goodness knows why they put it there instead of the collections framework

Maven package/install without test (skip tests)

Note that -Dmaven.test.skip prevents Maven building the test-jar artifact.

If you'd like to skip tests but create artifacts as per a normal build use:

-Dmaven.test.skip.exec

updating nodejs on ubuntu 16.04

Use sudo apt-get install --only-upgrade nodejs to upgrade node (and only upgrade node) using the package manager.

The package name is nodejs, see https://stackoverflow.com/a/18130296/4578017 for details.

You can also use nvm to install and update node.

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

Then restart the terminal, use nvm ls-remote to get latest version list of node, and use nvm install lts/* to install latest LTS version.

nvm is more recommended way to install or update node, even if you are not going to switch versions.

How to pass data from child component to its parent in ReactJS?

You can create the state in the ParentComponent using useState and pass down the setIsParentData function as prop into the ChildComponent.

In the ChildComponent, update the data using the received function through prop to send the data back to ParentComponent.

I use this technique especially when my code in the ParentComponent is getting too long, therefore I will create child components from the ParentComponent. Typically, it will be only 1 level down and using useContext or redux seems overkill in order to share states between components.

ParentComponent.js

import React, { useState } from 'react';
import ChildComponent from './ChildComponent';

export function ParentComponent(){
  const [isParentData, setIsParentData] = useState(True);

  return (
    <p>is this a parent data?: {isParentData}</p>
    <ChildComponent toChild={isParentData} sendToParent={setIsParentData} />
  );
}

ChildComponent.js

import React from 'react';

export function ChildComponent(props){

  return (
    <button onClick={() => {props.sendToParent(False)}}>Update</button>
    <p>The state of isParentData is {props.toChild}</p>
  );
};

Filter an array using a formula (without VBA)

Sounds like you're just trying to do a classic two-column lookup. http://www.dailydoseofexcel.com/archives/2009/04/21/vlookup-on-two-columns/

Tons of solutions for this, most simple is probably the following (which doesn't require an array formula):

=SUMPRODUCT((Lookup!A:A=Param!A1)*(Lookup!B:B=Param!B1)*(Lookup!C:C))

To translate your specific example, you would use:

=SUMPRODUCT((A1:A3=A2)*(B1:B3="B")*(C1:C3))

Convert between UIImage and Base64 string

Swift 3.0

To convert image to base64 string

Tested in playground

    var logo = UIImage(named: "image_logo")
    let imageData:Data =  UIImagePNGRepresentation(logo)
    let base64String = imageData.base64EncodedString()
    print(base64String)

How to extract numbers from string in c?

You can do it with strtol, like this:

char *str = "ab234cid*(s349*(20kd", *p = str;
while (*p) { // While there are more characters to process...
    if ( isdigit(*p) || ( (*p=='-'||*p=='+') && isdigit(*(p+1)) )) {
        // Found a number
        long val = strtol(p, &p, 10); // Read number
        printf("%ld\n", val); // and print it.
    } else {
        // Otherwise, move on to the next character.
        p++;
    }
}

Link to ideone.

How to get the parent dir location

I tried:

import os
os.path.abspath(os.path.join(os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe()))), os.pardir))

How To: Best way to draw table in console app (C#)

I wanted variable-width columns, and I didn't particularly care about the box characters. Also, I needed to print some extra information for each row.

So in case anyone else needs that, I'll save you few minutes:

public class TestTableBuilder
{

    public interface ITextRow
    {
        String Output();
        void Output(StringBuilder sb);
        Object Tag { get; set; }
    }

    public class TableBuilder : IEnumerable<ITextRow>
    {
        protected class TextRow : List<String>, ITextRow
        {
            protected TableBuilder owner = null;
            public TextRow(TableBuilder Owner)
            {
                owner = Owner;
                if (owner == null) throw new ArgumentException("Owner");
            }
            public String Output()
            {
                StringBuilder sb = new StringBuilder();
                Output(sb);
                return sb.ToString();
            }
            public void Output(StringBuilder sb)
            {
                sb.AppendFormat(owner.FormatString, this.ToArray());
            }
            public Object Tag { get; set; }
        }

        public String Separator { get; set; }

        protected List<ITextRow> rows = new List<ITextRow>();
        protected List<int> colLength = new List<int>();

        public TableBuilder()
        {
            Separator = "  ";
        }

        public TableBuilder(String separator)
            : this()
        {
            Separator = separator;
        }

        public ITextRow AddRow(params object[] cols)
        {
            TextRow row = new TextRow(this);
            foreach (object o in cols)
            {
                String str = o.ToString().Trim();
                row.Add(str);
                if (colLength.Count >= row.Count)
                {
                    int curLength = colLength[row.Count - 1];
                    if (str.Length > curLength) colLength[row.Count - 1] = str.Length;
                }
                else
                {
                    colLength.Add(str.Length);
                }
            }
            rows.Add(row);
            return row;
        }

        protected String _fmtString = null;
        public String FormatString
        {
            get
            {
                if (_fmtString == null)
                {
                    String format = "";
                    int i = 0;
                    foreach (int len in colLength)
                    {
                        format += String.Format("{{{0},-{1}}}{2}", i++, len, Separator);
                    }
                    format += "\r\n";
                    _fmtString = format;
                }
                return _fmtString;
            }
        }

        public String Output()
        {
            StringBuilder sb = new StringBuilder();
            foreach (TextRow row in rows)
            {
                row.Output(sb);
            }
            return sb.ToString();
        }

        #region IEnumerable Members

        public IEnumerator<ITextRow> GetEnumerator()
        {
            return rows.GetEnumerator();
        }

        System.Collections.IEnumerator System.Collections.IEnumerable.GetEnumerator()
        {
            return rows.GetEnumerator();
        }

        #endregion
    }



    static void Main(String[] args)
    {
        TableBuilder tb = new TableBuilder();
        tb.AddRow("When", "ID", "Name");
        tb.AddRow("----", "--", "----");

        tb.AddRow(DateTime.Now, "1", "Name1");
        tb.AddRow(DateTime.Now, "1", "Name2");

        Console.Write(tb.Output());
        Console.WriteLine();

        // or

        StringBuilder sb = new StringBuilder();
        int i = 0;
        foreach (ITextRow tr in tb)
        {
            tr.Output(sb);
            if (i++ > 1) sb.AppendLine("more stuff per line");
        }
        Console.Write(sb.ToString());
    }
}

Output:

When                 ID  Name
----                 --  ----
2/4/2013 8:37:44 PM  1   Name1
2/4/2013 8:37:44 PM  1   Name2

When                 ID  Name
----                 --  ----
2/4/2013 8:37:44 PM  1   Name1
more stuff per line
2/4/2013 8:37:44 PM  1   Name2
more stuff per line

Loading resources using getClass().getResource()

getResourceAsStream() look inside of your resource folder. So the fil shold be placed inside of the defined resource-folder i.e if the file reside in /src/main/resources/properties --> then the path should be /properties/yourFilename.

getClass.getResourceAsStream(/properties/yourFilename)

What does "yield break;" do in C#?

Here http://www.alteridem.net/2007/08/22/the-yield-statement-in-c/ is very good example:

public static IEnumerable<int> Range( int min, int max )
{
   while ( true )
   {
      if ( min >= max )
      {
         yield break;
      }
      yield return min++;
   }
}

and explanation, that if a yield break statement is hit within a method, execution of that method stops with no return. There are some time situations, when you don't want to give any result, then you can use yield break.

PHP split alternative?

You can use the easier function preg_match instead, It's better and faster than all of the other ones.

$var = "<tag>Get this var</tag>";
preg_match("/<tag>(.*)<\/tag>/", $var , $new_var);
echo $new_var['1']; 

Output: Get this var

How do you add multi-line text to a UIButton?

self.btnError.titleLabel?.lineBreakMode = NSLineBreakMode.byWordWrapping

self.btnError.titleLabel?.textAlignment = .center

self.btnError.setTitle("Title", for: .normal)

Textfield with only bottom border

See this JSFiddle

_x000D_
_x000D_
 input[type="text"]_x000D_
    {_x000D_
        border: 0;_x000D_
        border-bottom: 1px solid red;_x000D_
        outline: 0;_x000D_
    }
_x000D_
<form>_x000D_
        <input type="text" value="See! ONLY BOTTOM BORDER!" />_x000D_
    </form>
_x000D_
_x000D_
_x000D_

Display tooltip on Label's hover?

Just set a title on the label:

<label for="male" title="Hello This Will Have Some Value">Hello...</label>

Using jQuery:

<label for="male" data-title="Language" />
<input type="hidden" name="Language" value="Hello This Will Have Some Value">

$("label").prop("title", function() {
    return $("input[name='" + $(this).data("title") + "']").text();
});

If you can use CSS3, you can use the text-overflow: ellipsis; to handle the ellipsis for you so all you need to do is copy the text from the label into the title attribute using jQuery:

HTML:

<label for="male">Hello This Will Have Some Value</label>

CSS:

label {
    display: inline-block;
    width: 50px;
    text-overflow: ellipsis;
    white-space: nowrap;
    overflow: hidden;
}

jQuery:

$("label").prop("title", function() {
   return $(this).text(); 
});

Example: http://jsfiddle.net/Xm8Xe/

Finally, if you need robust and cross-browser support, you could use the DotDotDot jQuery plugin.

Simulate delayed and dropped packets on Linux

You can try http://snad.ncsl.nist.gov/nistnet/ https://www-x.antd.nist.gov/nistnet/ It's quite old NIST project (last release 2005), but it works for me.

(.text+0x20): undefined reference to `main' and undefined reference to function

This error means that, while linking, compiler is not able to find the definition of main() function anywhere.

In your makefile, the main rule will expand to something like this.

main: producer.o consumer.o AddRemove.o
   gcc -pthread -Wall -o producer.o consumer.o AddRemove.o

As per the gcc manual page, the use of -o switch is as below

-o file     Place output in file file. This applies regardless to whatever sort of output is being produced, whether it be an executable file, an object file, an assembler file or preprocessed C code. If -o is not specified, the default is to put an executable file in a.out.

It means, gcc will put the output in the filename provided immediate next to -o switch. So, here instead of linking all the .o files together and creating the binary [main, in your case], its creating the binary as producer.o, linking the other .o files. Please correct that.

Delimiter must not be alphanumeric or backslash and preg_match

You must specify a delimiter for your expression. A delimiter is a special character used at the start and end of your expression to denote which part is the expression. This allows you to use modifiers and the interpreter to know which is an expression and which are modifiers. As the error message states, the delimiter cannot be a backslash because the backslash is the escape character.

$pattern = "/My name is '(.*)' and im fine/";

and below the same example but with the i modifier to match without being case sensitive.

$pattern = "/My name is '(.*)' and im fine/i";

As you can see, the i is outside of the slashes and therefore is interpreted as a modifier.

Also bear in mind that if you use a forward slash character (/) as a delimiter you must then escape further uses of / in the regular expression, if present.

Where to place $PATH variable assertions in zsh?

tl;dr version: use ~/.zshrc

And read the man page to understand the differences between:

~/.zshrc, ~/.zshenv and ~/.zprofile.


Regarding my comment

In my comment attached to the answer kev gave, I said:

This seems to be incorrect - /etc/profile isn't listed in any zsh documentation I can find.

This turns out to be partially incorrect: /etc/profile may be sourced by zsh. However, this only occurs if zsh is "invoked as sh or ksh"; in these compatibility modes:

The usual zsh startup/shutdown scripts are not executed. Login shells source /etc/profile followed by $HOME/.profile. If the ENV environment variable is set on invocation, $ENV is sourced after the profile scripts. The value of ENV is subjected to parameter expansion, command substitution, and arithmetic expansion before being interpreted as a pathname. [man zshall, "Compatibility"].

The ArchWiki ZSH link says:

At login, Zsh sources the following files in this order:
/etc/profile
This file is sourced by all Bourne-compatible shells upon login

This implys that /etc/profile is always read by zsh at login - I haven't got any experience with the Arch Linux project; the wiki may be correct for that distribution, but it is not generally correct. The information is incorrect compared to the zsh manual pages, and doesn't seem to apply to zsh on OS X (paths in $PATH set in /etc/profile do not make it to my zsh sessions).



To address the question:

where exactly should I be placing my rvm, python, node etc additions to my $PATH?

Generally, I would export my $PATH from ~/.zshrc, but it's worth having a read of the zshall man page, specifically the "STARTUP/SHUTDOWN FILES" section - ~/.zshrc is read for interactive shells, which may or may not suit your needs - if you want the $PATH for every zsh shell invoked by you (both interactive and not, both login and not, etc), then ~/.zshenv is a better option.

Is there a specific file I should be using (i.e. .zshenv which does not currently exist in my installation), one of the ones I am currently using, or does it even matter?

There's a bunch of files read on startup (check the linked man pages), and there's a reason for that - each file has it's particular place (settings for every user, settings for user-specific, settings for login shells, settings for every shell, etc).
Don't worry about ~/.zshenv not existing - if you need it, make it, and it will be read.

.bashrc and .bash_profile are not read by zsh, unless you explicitly source them from ~/.zshrc or similar; the syntax between bash and zsh is not always compatible. Both .bashrc and .bash_profile are designed for bash settings, not zsh settings.

How to check whether Kafka Server is running?

I used the AdminClient api.

Properties properties = new Properties();
properties.put("bootstrap.servers", "localhost:9092");
properties.put("connections.max.idle.ms", 10000);
properties.put("request.timeout.ms", 5000);
try (AdminClient client = KafkaAdminClient.create(properties))
{
    ListTopicsResult topics = client.listTopics();
    Set<String> names = topics.names().get();
    if (names.isEmpty())
    {
        // case: if no topic found.
    }
    return true;
}
catch (InterruptedException | ExecutionException e)
{
    // Kafka is not available
}

preferredStatusBarStyle isn't called

Since Xcode 11.4, overriding the preferredStatusBarStyle property in a UINavigationController extension no longer works since it will not be called.

Setting the barStyle of navigationBar to .black works indeed but this will add unwanted side effects if you add subviews to the navigationBar which may have different appearances for light and dark mode. Because by setting the barStyle to black, the userInterfaceStyle of a view thats embedded in the navigationBar will then always have userInterfaceStyle.dark regardless of the userInterfaceStyle of the app.

The proper solution I come up with is by adding a subclass of UINavigationController and override preferredStatusBarStyle there. If you then use this custom UINavigationController for all your views you will be on the save side.

How to get UTF-8 working in Java webapps?

Answering myself as the FAQ of this site encourages it. This works for me:

Mostly characters äåö are not a problematic as the default character set used by browsers and tomcat/java for webapps is latin1 ie. ISO-8859-1 which "understands" those characters.

To get UTF-8 working under Java+Tomcat+Linux/Windows+Mysql requires the following:

Configuring Tomcat's server.xml

It's necessary to configure that the connector uses UTF-8 to encode url (GET request) parameters:

<Connector port="8080" maxHttpHeaderSize="8192"
 maxThreads="150" minSpareThreads="25" maxSpareThreads="75"
 enableLookups="false" redirectPort="8443" acceptCount="100"
 connectionTimeout="20000" disableUploadTimeout="true" 
 compression="on" 
 compressionMinSize="128" 
 noCompressionUserAgents="gozilla, traviata" 
 compressableMimeType="text/html,text/xml,text/plain,text/css,text/ javascript,application/x-javascript,application/javascript"
 URIEncoding="UTF-8"
/>

The key part being URIEncoding="UTF-8" in the above example. This quarantees that Tomcat handles all incoming GET parameters as UTF-8 encoded. As a result, when the user writes the following to the address bar of the browser:

 https://localhost:8443/ID/Users?action=search&name=*?*

the character ? is handled as UTF-8 and is encoded to (usually by the browser before even getting to the server) as %D0%B6.

POST request are not affected by this.

CharsetFilter

Then it's time to force the java webapp to handle all requests and responses as UTF-8 encoded. This requires that we define a character set filter like the following:

package fi.foo.filters;

import javax.servlet.*;
import java.io.IOException;

public class CharsetFilter implements Filter {

    private String encoding;

    public void init(FilterConfig config) throws ServletException {
        encoding = config.getInitParameter("requestEncoding");
        if (encoding == null) encoding = "UTF-8";
    }

    public void doFilter(ServletRequest request, ServletResponse response, FilterChain next)
            throws IOException, ServletException {
        // Respect the client-specified character encoding
        // (see HTTP specification section 3.4.1)
        if (null == request.getCharacterEncoding()) {
            request.setCharacterEncoding(encoding);
        }

        // Set the default response content type and encoding
        response.setContentType("text/html; charset=UTF-8");
        response.setCharacterEncoding("UTF-8");

        next.doFilter(request, response);
    }

    public void destroy() {
    }
}

This filter makes sure that if the browser hasn't set the encoding used in the request, that it's set to UTF-8.

The other thing done by this filter is to set the default response encoding ie. the encoding in which the returned html/whatever is. The alternative is to set the response encoding etc. in each controller of the application.

This filter has to be added to the web.xml or the deployment descriptor of the webapp:

 <!--CharsetFilter start--> 

  <filter>
    <filter-name>CharsetFilter</filter-name>
    <filter-class>fi.foo.filters.CharsetFilter</filter-class>
      <init-param>
        <param-name>requestEncoding</param-name>
        <param-value>UTF-8</param-value>
      </init-param>
  </filter>

  <filter-mapping>
    <filter-name>CharsetFilter</filter-name>
    <url-pattern>/*</url-pattern>
  </filter-mapping>

The instructions for making this filter are found at the tomcat wiki (http://wiki.apache.org/tomcat/Tomcat/UTF-8)

JSP page encoding

In your web.xml, add the following:

<jsp-config>
    <jsp-property-group>
        <url-pattern>*.jsp</url-pattern>
        <page-encoding>UTF-8</page-encoding>
    </jsp-property-group>
</jsp-config>

Alternatively, all JSP-pages of the webapp would need to have the following at the top of them:

 <%@page pageEncoding="UTF-8" contentType="text/html; charset=UTF-8"%>

If some kind of a layout with different JSP-fragments is used, then this is needed in all of them.

HTML-meta tags

JSP page encoding tells the JVM to handle the characters in the JSP page in the correct encoding. Then it's time to tell the browser in which encoding the html page is:

This is done with the following at the top of each xhtml page produced by the webapp:

   <?xml version="1.0" encoding="UTF-8"?>
   <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.1//EN" "http://www.w3.org/TR/xhtml11/DTD/xhtml11.dtd">
   <html xmlns="http://www.w3.org/1999/xhtml" xml:lang="fi">
   <head>
   <meta http-equiv='Content-Type' content='text/html; charset=UTF-8' />
   ...

JDBC-connection

When using a db, it has to be defined that the connection uses UTF-8 encoding. This is done in context.xml or wherever the JDBC connection is defiend as follows:

      <Resource name="jdbc/AppDB" 
        auth="Container"
        type="javax.sql.DataSource"
        maxActive="20" maxIdle="10" maxWait="10000"
        username="foo"
        password="bar"
        driverClassName="com.mysql.jdbc.Driver" url="jdbc:mysql://localhost:3306/      ID_development?useEncoding=true&amp;characterEncoding=UTF-8"
    />

MySQL database and tables

The used database must use UTF-8 encoding. This is achieved by creating the database with the following:

   CREATE DATABASE `ID_development` 
   /*!40100 DEFAULT CHARACTER SET utf8 COLLATE utf8_swedish_ci */;

Then, all of the tables need to be in UTF-8 also:

   CREATE TABLE  `Users` (
    `id` int(10) unsigned NOT NULL auto_increment,
    `name` varchar(30) collate utf8_swedish_ci default NULL
    PRIMARY KEY  (`id`)
   ) ENGINE=InnoDB DEFAULT CHARSET=utf8 COLLATE=utf8_swedish_ci ROW_FORMAT=DYNAMIC;

The key part being CHARSET=utf8.

MySQL server configuration

MySQL serveri has to be configured also. Typically this is done in Windows by modifying my.ini -file and in Linux by configuring my.cnf -file. In those files it should be defined that all clients connected to the server use utf8 as the default character set and that the default charset used by the server is also utf8.

   [client]
   port=3306
   default-character-set=utf8

   [mysql]
   default-character-set=utf8

Mysql procedures and functions

These also need to have the character set defined. For example:

   DELIMITER $$

   DROP FUNCTION IF EXISTS `pathToNode` $$
   CREATE FUNCTION `pathToNode` (ryhma_id INT) RETURNS TEXT CHARACTER SET utf8
   READS SQL DATA
   BEGIN

    DECLARE path VARCHAR(255) CHARACTER SET utf8;

   SET path = NULL;

   ...

   RETURN path;

   END $$

   DELIMITER ;

GET requests: latin1 and UTF-8

If and when it's defined in tomcat's server.xml that GET request parameters are encoded in UTF-8, the following GET requests are handled properly:

   https://localhost:8443/ID/Users?action=search&name=Petteri
   https://localhost:8443/ID/Users?action=search&name=?

Because ASCII-characters are encoded in the same way both with latin1 and UTF-8, the string "Petteri" is handled correctly.

The Cyrillic character ? is not understood at all in latin1. Because Tomcat is instructed to handle request parameters as UTF-8 it encodes that character correctly as %D0%B6.

If and when browsers are instructed to read the pages in UTF-8 encoding (with request headers and html meta-tag), at least Firefox 2/3 and other browsers from this period all encode the character themselves as %D0%B6.

The end result is that all users with name "Petteri" are found and also all users with the name "?" are found.

But what about äåö?

HTTP-specification defines that by default URLs are encoded as latin1. This results in firefox2, firefox3 etc. encoding the following

    https://localhost:8443/ID/Users?action=search&name=*Päivi*

in to the encoded version

    https://localhost:8443/ID/Users?action=search&name=*P%E4ivi*

In latin1 the character ä is encoded as %E4. Even though the page/request/everything is defined to use UTF-8. The UTF-8 encoded version of ä is %C3%A4

The result of this is that it's quite impossible for the webapp to correly handle the request parameters from GET requests as some characters are encoded in latin1 and others in UTF-8. Notice: POST requests do work as browsers encode all request parameters from forms completely in UTF-8 if the page is defined as being UTF-8

Stuff to read

A very big thank you for the writers of the following for giving the answers for my problem:

  • http://tagunov.tripod.com/i18n/i18n.html
  • http://wiki.apache.org/tomcat/Tomcat/UTF-8
  • http://java.sun.com/developer/technicalArticles/Intl/HTTPCharset/
  • http://dev.mysql.com/doc/refman/5.0/en/charset-syntax.html
  • http://cagan327.blogspot.com/2006/05/utf-8-encoding-fix-tomcat-jsp-etc.html
  • http://cagan327.blogspot.com/2006/05/utf-8-encoding-fix-for-mysql-tomcat.html
  • http://jeppesn.dk/utf-8.html
  • http://www.nabble.com/request-parameters-mishandle-utf-8-encoding-td18720039.html
  • http://www.utoronto.ca/webdocs/HTMLdocs/NewHTML/iso_table.html
  • http://www.utf8-chartable.de/

Important Note

supports the Basic Multilingual Plane using 3-byte UTF-8 characters. If you need to go outside of that (certain alphabets require more than 3-bytes of UTF-8), then you either need to use a flavor of VARBINARY column type or use the utf8mb4 character set (which requires MySQL 5.5.3 or later). Just be aware that using the utf8 character set in MySQL won't work 100% of the time.

Tomcat with Apache

One more thing If you are using Apache + Tomcat + mod_JK connector then you also need to do following changes:

  1. Add URIEncoding="UTF-8" into tomcat server.xml file for 8009 connector, it is used by mod_JK connector. <Connector port="8009" protocol="AJP/1.3" redirectPort="8443" URIEncoding="UTF-8"/>
  2. Goto your apache folder i.e. /etc/httpd/conf and add AddDefaultCharset utf-8 in httpd.conf file. Note: First check that it is exist or not. If exist you may update it with this line. You can add this line at bottom also.

Python: finding an element in a list

assuming you want to find a value in a numpy array, I guess something like this might work:

Numpy.where(arr=="value")[0]

how to make a new line in a jupyter markdown cell

Just add <br> where you would like to make the new line.

$S$: a set of shops
<br>
$I$: a set of items M wants to get

Because jupyter notebook markdown cell is a superset of HTML.
http://jupyter-notebook.readthedocs.io/en/latest/examples/Notebook/Working%20With%20Markdown%20Cells.html

Note that newlines using <br> does not persist when exporting or saving the notebook to a pdf (using "Download as > PDF via LaTeX"). It is probably treating each <br> as a space.

Angular2 Exception: Can't bind to 'routerLink' since it isn't a known native property

You have in your module

import {Routes, RouterModule} from '@angular/router';

you have to export the module RouteModule

example:

@NgModule({
  imports: [RouterModule.forChild(routes)],
  exports: [RouterModule]
})

to be able to access the functionalities for all who import this module.

How to resolve 'npm should be run outside of the node repl, in your normal shell'

you just open command prompt, then enter in c:/>('cd../../') then npm install -g cordova enter image description here

Writing to a TextBox from another thread?

Most simple, without caring about delegates

if(textBox1.InvokeRequired == true)
    textBox1.Invoke((MethodInvoker)delegate { textBox1.Text = "Invoke was needed";});

else
    textBox1.Text = "Invoke was NOT needed"; 

How do I add items to an array in jQuery?

Hope this will help you..

var list = [];
    $(document).ready(function () {
        $('#test').click(function () {
            var oRows = $('#MainContent_Table1 tr').length;
            $('#MainContent_Table1 tr').each(function (index) {
                list.push(this.cells[0].innerHTML);
            });
        });
    });

java.lang.UnsupportedClassVersionError: Unsupported major.minor version 51.0 (unable to load class frontend.listener.StartupListener)

What is your output when you do java -version? This will tell you what version the running JVM is.

The Unsupported major.minor version 51.0 error could mean:

  • Your server is running a lower Java version then the one used to compile your Servlet and vice versa

Either way, uninstall all JVM runtimes including JDK and download latest and re-install. That should fix any Unsupported major.minor error as you will have the lastest JRE and JDK (Maybe even newer then the one used to compile the Servlet)

See: http://www.java.com/en/download/manual.jsp (7 Update 25 )

and here: http://www.oracle.com/technetwork/java/javase/downloads/index.html (Java Platform (JDK) 7u25)

for the latest version of the JRE and JDK respectively.

EDIT:

Most likely your code was written in Java7 however maybe it was done using Java7update4 and your system is running Java7update3. Thus they both are effectively the same major version but the minor versions differ. Only the larger minor version is backward compatible with the lower minor version.

Edit 2 : If you have more than one jdk installed on your pc. you should check that Apache Tomcat is using the same one (jre) you are compiling your programs with. If you installed a new jdk after installing apache it normally won't select the new version.

How to get content body from a httpclient call?

The way you are using await/async is poor at best, and it makes it hard to follow. You are mixing await with Task'1.Result, which is just confusing. However, it looks like you are looking at a final task result, rather than the contents.

I've rewritten your function and function call, which should fix your issue:

async Task<string> GetResponseString(string text)
{
    var httpClient = new HttpClient();

    var parameters = new Dictionary<string, string>();
    parameters["text"] = text;

    var response = await httpClient.PostAsync(BaseUri, new FormUrlEncodedContent(parameters));
    var contents = await response.Content.ReadAsStringAsync();

    return contents;
}

And your final function call:

Task<string> result = GetResponseString(text);
var finalResult = result.Result;

Or even better:

var finalResult = await GetResponseString(text);

JavaScript - Hide a Div at startup (load)

Using CSS you can just set display:none for the element in a CSS file or in a style attribute

#div { display:none; }
<div id="div"></div>



<div style="display:none"></div>

or having the js just after the div might be fast enough too, but not as clean

How to manage exceptions thrown in filters in Spring?

It's strange because @ControllerAdvice should works, are you catching the correct Exception?

@ControllerAdvice
public class GlobalDefaultExceptionHandler {

    @ResponseBody
    @ExceptionHandler(value = DataAccessException.class)
    public String defaultErrorHandler(HttpServletResponse response, DataAccessException e) throws Exception {
       response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
       //Json return
    }
}

Also try to catch this exception in CorsFilter and send 500 error, something like this

@ExceptionHandler(DataAccessException.class)
@ResponseBody
public String handleDataException(DataAccessException ex, HttpServletResponse response) {
    response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
    //Json return
}

Creating a Zoom Effect on an image on hover using CSS?

.item:hover img 
{
 -moz-transform: scale(1.3);
 -webkit-transform: scale(1.3);
 transform: scale(1.3);
}

this way you can zoom any image with simple animation. If you need a complete tutorial here is a official tutorial: http://talkerscode.com/webtricks/image-zoom-in-on-hover-using-css3.php

How to generate javadoc comments in Android Studio

In Android studio we have few ways to auto-generated comments:

  • Method I:

By typing /** and Then pressing Enter you can generate next comment line and it will auto-generate the params, etc. but when you need the hotkey for this check out method II on below.

  • **Method II: **

1 - Goto topMenu

2 - File > Settings

3 - Select Keymap from settings

4 - On the top right search bar search for "Fix Doc"

5 - Select the "fix doc comment" from the results and double-click on it

6 - Select Add keyboard shortcut from the opened drop down after double-click

7 - Press the shortcut keys on the keyboard

8 - Goto your code and where you want to add some comment press the shortcut key

9 - Enjoy!

Remove last specific character in a string c#

The TrimEnd method takes an input character array and not a string. The code below from Dot Net Perls, shows a more efficient example of how to perform the same functionality as TrimEnd.

static string TrimTrailingChars(string value)
{
    int removeLength = 0;
    for (int i = value.Length - 1; i >= 0; i--)
    {
        char let = value[i];
        if (let == '?' || let == '!' || let == '.')
        {
            removeLength++;
        }
        else
        {
            break;
        }
    }
    if (removeLength > 0)
    {
        return value.Substring(0, value.Length - removeLength);
    }
    return value;
}

FontAwesome icons not showing. Why?

the CDN link that you had posted i suppose is why it wasnt showing correctly, you can use this one below, it works perfectly for me.

_x000D_
_x000D_
<link href="http://maxcdn.bootstrapcdn.com/font-awesome/4.1.0/css/font-awesome.min.css" rel="stylesheet">
_x000D_
_x000D_
_x000D_

How to advance to the next form input when the current input has a value?

If you have jQuery UI this little function allows basic tabbing

handlePseudoTab(direction) {
    if (!document.hasFocus() || !document.activeElement) {
        return;
    }
    const focusList = $(":focusable", $yourHTMLElement);
    const i = focusList.index(document.activeElement);
    if (i < 0) {
        focusList[0].focus(); // nothing is focussed so go to list item 0
    } else if (direction === 'next' && i + 1 < focusList.length) {
        focusList[i + 1].focus(); // advance one
    } else if (direction === 'prev' && i - 1 > -1) {
        focusList[i - 1].focus(); // go back one
    }
}

How do I add an element to array in reducer of React native redux?

If you need to insert into a specific position in the array, you can do this:

case ADD_ITEM :
    return { 
        ...state,
        arr: [
            ...state.arr.slice(0, action.pos),
            action.newItem,
            ...state.arr.slice(action.pos),
        ],
    }

C# catch a stack overflow exception

Starting with 2.0 a StackOverflow Exception can only be caught in the following circumstances.

  1. The CLR is being run in a hosted environment* where the host specifically allows for StackOverflow exceptions to be handled
  2. The stackoverflow exception is thrown by user code and not due to an actual stack overflow situation (Reference)

*"hosted environment" as in "my code hosts CLR and I configure CLR's options" and not "my code runs on shared hosting"

Giving height to table and row in Bootstrap

For the <tr>'s just set

tr {
   line-height: 25px;
   min-height: 25px;
   height: 25px;
}

It works with bootstrap also. For the 100% height, 100% must be 100% of something. Therefore, you must define a fixed height for one of the containers, or the body. I guess you want the entire page to be 100%, so (example) :

body {
    height: 700px;
}
.table100, .row, .container, .table-responsive, .table-bordered  {
    height: 100%;
}

A workaround not to set a static height is by forcing the height in code according to the viewport :

$('body').height(document.documentElement.clientHeight);

all the above in this fiddle -> http://jsfiddle.net/LZuJt/

Note : I do not care that you have 25% height on #description, and 100% height on table. Guess it is just an example. And notice that clientHeight is not right since the documentElement is an iframe, but you'll get the picture in your own projekt :)

How do I get the coordinates of a mouse click on a canvas element?

So this is both simple but a slightly more complicated topic than it seems.

First off there are usually to conflated questions here

  1. How to get element relative mouse coordinates

  2. How to get canvas pixel mouse coordinates for the 2D Canvas API or WebGL

so, answers

How to get element relative mouse coordinates

Whether or not the element is a canvas getting element relative mouse coordinates is the same for all elements.

There are 2 simple answers to the question "How to get canvas relative mouse coordinates"

Simple answer #1 use offsetX and offsetY

canvas.addEventListner('mousemove', (e) => {
  const x = e.offsetX;
  const y = e.offsetY;
});

This answer works in Chrome, Firefox, and Safari. Unlike all the other event values offsetX and offsetY take CSS transforms into account.

The biggest problem with offsetX and offsetY is as of 2019/05 they don't exist on touch events and so can't be used with iOS Safari. They do exist on Pointer Events which exist in Chrome and Firefox but not Safari although apparently Safari is working on it.

Another issue is the events must be on the canvas itself. If you put them on some other element or the window you can not later choose the canvas to be your point of reference.

Simple answer #2 use clientX, clientY and canvas.getBoundingClientRect

If you don't care about CSS transforms the next simplest answer is to call canvas. getBoundingClientRect() and subtract the left from clientX and top from clientY as in

canvas.addEventListener('mousemove', (e) => {
  const rect = canvas.getBoundingClientRect();
  const x = e.clientX - rect.left;
  const y = e.clientY - rect.top;
});

This will work as long as there are no CSS transforms. It also works with touch events and so will work with Safari iOS

canvas.addEventListener('touchmove', (e) => {
  const rect = canvas. getBoundingClientRect();
  const x = e.touches[0].clientX - rect.left;
  const y = e.touches[0].clientY - rect.top;
});

How to get canvas pixel mouse coordinates for the 2D Canvas API

For this we need to take the values we got above and convert from the size the canvas is displayed to the number of pixels in the canvas itself

with canvas.getBoundingClientRect and clientX and clientY

canvas.addEventListener('mousemove', (e) => {
  const rect = canvas.getBoundingClientRect();
  const elementRelativeX = e.clientX - rect.left;
  const elementRelativeY = e.clientY - rect.top;
  const canvasRelativeX = elementRelativeX * canvas.width / rect.width;
  const canvasRelativeY = elementRelativeY * canvas.height / rect.height;
});

or with offsetX and offsetY

canvas.addEventListener('mousemove', (e) => {
  const elementRelativeX = e.offsetX;
  const elementRelativeY = e.offsetY;
  const canvasRelativeX = elementRelativeX * canvas.width / canvas.clientWidth;
  const canvasRelativeY = elementRelativeY * canvas.height / canvas.clientHeight;
});

Note: In all cases do not add padding or borders to the canvas. Doing so will massively complicate the code. Instead of you want a border or padding surround the canvas in some other element and add the padding and or border to the outer element.

Working example using event.offsetX, event.offsetY

_x000D_
_x000D_
[...document.querySelectorAll('canvas')].forEach((canvas) => {
  const ctx = canvas.getContext('2d');
  ctx.canvas.width  = ctx.canvas.clientWidth;
  ctx.canvas.height = ctx.canvas.clientHeight;
  let count = 0;

  function draw(e, radius = 1) {
    const pos = {
      x: e.offsetX * canvas.width  / canvas.clientWidth,
      y: e.offsetY * canvas.height / canvas.clientHeight,
    };
    document.querySelector('#debug').textContent = count;
    ctx.beginPath();
    ctx.arc(pos.x, pos.y, radius, 0, Math.PI * 2);
    ctx.fillStyle = hsl((count++ % 100) / 100, 1, 0.5);
    ctx.fill();
  }

  function preventDefault(e) {
    e.preventDefault();
  }

  if (window.PointerEvent) {
    canvas.addEventListener('pointermove', (e) => {
      draw(e, Math.max(Math.max(e.width, e.height) / 2, 1));
    });
    canvas.addEventListener('touchstart', preventDefault, {passive: false});
    canvas.addEventListener('touchmove', preventDefault, {passive: false});
  } else {
    canvas.addEventListener('mousemove', draw);
    canvas.addEventListener('mousedown', preventDefault);
  }
});

function hsl(h, s, l) {
  return `hsl(${h * 360 | 0},${s * 100 | 0}%,${l * 100 | 0}%)`;
}
_x000D_
.scene {
  width: 200px;
  height: 200px;
  perspective: 600px;
}

.cube {
  width: 100%;
  height: 100%;
  position: relative;
  transform-style: preserve-3d;
  animation-duration: 16s;
  animation-name: rotate;
  animation-iteration-count: infinite;
  animation-timing-function: linear;
}

@keyframes rotate {
  from { transform: translateZ(-100px) rotateX(  0deg) rotateY(  0deg); }
  to   { transform: translateZ(-100px) rotateX(360deg) rotateY(720deg); }
}

.cube__face {
  position: absolute;
  width: 200px;
  height: 200px;
  display: block;
}

.cube__face--front  { background: rgba(255, 0, 0, 0.2); transform: rotateY(  0deg) translateZ(100px); }
.cube__face--right  { background: rgba(0, 255, 0, 0.2); transform: rotateY( 90deg) translateZ(100px); }
.cube__face--back   { background: rgba(0, 0, 255, 0.2); transform: rotateY(180deg) translateZ(100px); }
.cube__face--left   { background: rgba(255, 255, 0, 0.2); transform: rotateY(-90deg) translateZ(100px); }
.cube__face--top    { background: rgba(0, 255, 255, 0.2); transform: rotateX( 90deg) translateZ(100px); }
.cube__face--bottom { background: rgba(255, 0, 255, 0.2); transform: rotateX(-90deg) translateZ(100px); }
_x000D_
<div class="scene">
  <div class="cube">
    <canvas class="cube__face cube__face--front"></canvas>
    <canvas class="cube__face cube__face--back"></canvas>
    <canvas class="cube__face cube__face--right"></canvas>
    <canvas class="cube__face cube__face--left"></canvas>
    <canvas class="cube__face cube__face--top"></canvas>
    <canvas class="cube__face cube__face--bottom"></canvas>
  </div>
</div>
<pre id="debug"></pre>
_x000D_
_x000D_
_x000D_

Working example using canvas.getBoundingClientRect and event.clientX and event.clientY

_x000D_
_x000D_
const canvas = document.querySelector('canvas');
const ctx = canvas.getContext('2d');
ctx.canvas.width  = ctx.canvas.clientWidth;
ctx.canvas.height = ctx.canvas.clientHeight;
let count = 0;

function draw(e, radius = 1) {
  const rect = canvas.getBoundingClientRect();
  const pos = {
    x: (e.clientX - rect.left) * canvas.width  / canvas.clientWidth,
    y: (e.clientY - rect.top) * canvas.height / canvas.clientHeight,
  };
  ctx.beginPath();
  ctx.arc(pos.x, pos.y, radius, 0, Math.PI * 2);
  ctx.fillStyle = hsl((count++ % 100) / 100, 1, 0.5);
  ctx.fill();
}

function preventDefault(e) {
  e.preventDefault();
}

if (window.PointerEvent) {
  canvas.addEventListener('pointermove', (e) => {
    draw(e, Math.max(Math.max(e.width, e.height) / 2, 1));
  });
  canvas.addEventListener('touchstart', preventDefault, {passive: false});
  canvas.addEventListener('touchmove', preventDefault, {passive: false});
} else {
  canvas.addEventListener('mousemove', draw);
  canvas.addEventListener('mousedown', preventDefault);
}

function hsl(h, s, l) {
  return `hsl(${h * 360 | 0},${s * 100 | 0}%,${l * 100 | 0}%)`;
}
_x000D_
canvas { background: #FED; }
_x000D_
<canvas width="400" height="100" style="width: 300px; height: 200px"></canvas>
<div>canvas deliberately has differnt CSS size vs drawingbuffer size</div>
_x000D_
_x000D_
_x000D_

Check if something is (not) in a list in Python

The bug is probably somewhere else in your code, because it should work fine:

>>> 3 not in [2, 3, 4]
False
>>> 3 not in [4, 5, 6]
True

Or with tuples:

>>> (2, 3) not in [(2, 3), (5, 6), (9, 1)]
False
>>> (2, 3) not in [(2, 7), (7, 3), "hi"]
True

How to grep and replace

Be very careful when using find and sed in a git repo! If you don't exclude the binary files you can end up with this error:

error: bad index file sha1 signature 
fatal: index file corrupt

To solve this error you need to revert the sed by replacing your new_string with your old_string. This will revert your replaced strings, so you will be back to the beginning of the problem.

The correct way to search for a string and replace it is to skip find and use grep instead in order to ignore the binary files:

sed -ri -e "s/old_string/new_string/g" $(grep -Elr --binary-files=without-match "old_string" "/files_dir")

Credits for @hobs

How to use stringstream to separate comma separated strings

#include <iostream>
#include <string>
#include <sstream>
using namespace std;
int main()
{
    std::string input = "abc,def,   ghi";
    std::istringstream ss(input);
    std::string token;
    size_t pos=-1;
    while(ss>>token) {
      while ((pos=token.rfind(',')) != std::string::npos) {
        token.erase(pos, 1);
      }
      std::cout << token << '\n';
    }
}

Java Class that implements Map and keeps insertion order?

You can maintain a Map (for fast lookup) and List (for order) but a LinkedHashMap may be the simplest. You can also try a SortedMap e.g. TreeMap, which an have any order you specify.

Could not reliably determine the server's fully qualified domain name

Here's my two cents. Maybe it's useful for future readers.

I ran into this problem when using Apache within a Docker container. When I started a container from an image of the Apache webserver, this message appeared when I started it with docker run -it -p 80:80 my-apache-container.

However, after starting the container in detached mode, using docker run -d -p 80:80 my-apache-container, I was able to connect through the browser.

Get size of folder or file

  • Works for Android and Java
  • Works for both folders and files
  • Checks for null pointer everywhere where needed
  • Ignores symbolic link aka shortcuts
  • Production ready!

Source code:

   public long fileSize(File root) {
        if(root == null){
            return 0;
        }
        if(root.isFile()){
            return root.length();
        }
        try {
            if(isSymlink(root)){
                return 0;
            }
        } catch (IOException e) {
            e.printStackTrace();
            return 0;
        }

        long length = 0;
        File[] files = root.listFiles();
        if(files == null){
            return 0;
        }
        for (File file : files) {
            length += fileSize(file);
        }

        return length;
    }

    private static boolean isSymlink(File file) throws IOException {
        File canon;
        if (file.getParent() == null) {
            canon = file;
        } else {
            File canonDir = file.getParentFile().getCanonicalFile();
            canon = new File(canonDir, file.getName());
        }
        return !canon.getCanonicalFile().equals(canon.getAbsoluteFile());
    }

String parsing in Java with delimiter tab "\t" using split

String[] columnDetail = new String[11];
columnDetail = column.split("\t", -1); // unlimited
OR
columnDetail = column.split("\t", 11); // if you are sure about limit.
 * The {@code limit} parameter controls the number of times the
 * pattern is applied and therefore affects the length of the resulting
 * array.  If the limit <i>n</i> is greater than zero then the pattern
 * will be applied at most <i>n</i>&nbsp;-&nbsp;1 times, the array's
 * length will be no greater than <i>n</i>, and the array's last entry
 * will contain all input beyond the last matched delimiter.  If <i>n</i>
 * is non-positive then the pattern will be applied as many times as
 * possible and the array can have any length.  If <i>n</i> is zero then
 * the pattern will be applied as many times as possible, the array can
 * have any length, and trailing empty strings will be discarded.

How to set index.html as root file in Nginx?

in your location block you can do:

location / {
  try_files $uri $uri/index.html;
}

which will tell ngingx to look for a file with the exact name given first, and if none such file is found it will try uri/index.html. So if a request for https://www.example.com/ comes it it would look for an exact file match first, and not finding that would then check for index.html

Should you use .htm or .html file extension? What is the difference, and which file is correct?

Same thing.. makes no difference at all... htm was used in the days where only 3 letter extensions were common.

SSL Proxy/Charles and Android trouble

I figured the issue. Its because Charles 3.7 has some bugs for Android devices. I updated to Charles 3.8 Beta version and seems to working fine for me.

Bootstrap datepicker disabling past dates without current date

You can use the data attribute:

<div class="datepicker" data-date-start-date="+1d"></div>

Get scroll position using jquery

I believe the best method with jQuery is using .scrollTop():

var pos = $('body').scrollTop();

How to resize Image in Android?

BitmapFactory.Options options=new BitmapFactory.Options();
options.inSampleSize=2; //try to decrease decoded image 
Bitmap bitmap=BitmapFactory.decodeStream(is, null, options); 
bitmap.compress(Bitmap.CompressFormat.JPEG, 70, fos); //compressed bitmap to file 

Double precision floating values in Python?

Decimal datatype

  • Unlike hardware based binary floating point, the decimal module has a user alterable precision (defaulting to 28 places) which can be as large as needed for a given problem.

If you are pressed by performance issuses, have a look at GMPY

Angular exception: Can't bind to 'ngForIn' since it isn't a known native property

Since this is at least the third time I've wasted more than 5 min on this problem I figured I'd post the Q & A. I hope it helps someone else down the road... probably me!

I typed in instead of of in the ngFor expression.

Befor 2-beta.17, it should be:

<div *ngFor="#talk of talks">

As of beta.17, use the let syntax instead of #. See the UPDATE further down for more info.


Note that the ngFor syntax "desugars" into the following:

<template ngFor #talk [ngForOf]="talks">
  <div>...</div>
</template>

If we use in instead, it turns into

<template ngFor #talk [ngForIn]="talks">
  <div>...</div>
</template>

Since ngForIn isn't an attribute directive with an input property of the same name (like ngIf), Angular then tries to see if it is a (known native) property of the template element, and it isn't, hence the error.

UPDATE - as of 2-beta.17, use the let syntax instead of #. This updates to the following:

<div *ngFor="let talk of talks">

Note that the ngFor syntax "desugars" into the following:

<template ngFor let-talk [ngForOf]="talks">
  <div>...</div>
</template>

If we use in instead, it turns into

<template ngFor let-talk [ngForIn]="talks">
  <div>...</div>
</template>

JavaScript sleep/wait before continuing

JS does not have a sleep function, it has setTimeout() or setInterval() functions.

If you can move the code that you need to run after the pause into the setTimeout() callback, you can do something like this:

//code before the pause
setTimeout(function(){
    //do what you need here
}, 2000);

see example here : http://jsfiddle.net/9LZQp/

This won't halt the execution of your script, but due to the fact that setTimeout() is an asynchronous function, this code

console.log("HELLO");
setTimeout(function(){
    console.log("THIS IS");
}, 2000);
console.log("DOG");

will print this in the console:

HELLO
DOG
THIS IS

(note that DOG is printed before THIS IS)


You can use the following code to simulate a sleep for short periods of time:

function sleep(milliseconds) {
  var start = new Date().getTime();
  for (var i = 0; i < 1e7; i++) {
    if ((new Date().getTime() - start) > milliseconds){
      break;
    }
  }
}

now, if you want to sleep for 1 second, just use:

sleep(1000);

example: http://jsfiddle.net/HrJku/1/

please note that this code will keep your script busy for n milliseconds. This will not only stop execution of Javascript on your page, but depending on the browser implementation, may possibly make the page completely unresponsive, and possibly make the entire browser unresponsive. In other words this is almost always the wrong thing to do.

What does -save-dev mean in npm install grunt --save-dev

Documentation from npm for npm install <package-name> --save and npm install <package-name> --save-dev can be found here:

https://docs.npmjs.com/getting-started/using-a-package.json#the-save-and-save-dev-install-flags

A package.json file declares metadata about the module you are developing. Both aforementioned commands modify this package.json file. --save will declare the installed package (in this case, grunt) as a dependency for your module; --save-dev will declare it as a dependency for development of your module.

Ask yourself: will the installed package be required for use of my module, or will it only be required for developing it?

How might I force a floating DIV to match the height of another floating DIV?

I can't understand why this issue gets pounded into the ground when in 30 seconds you can code a two-column table and solve the problem.

This div column height problem comes up all over a typical layout. Why resort to scripting when a plain old basic HTML tag will do it? Unless there are huge and numerous tables on a layout, I don't buy the argument that tables are significantly slower.

On duplicate key ignore?

Would suggest NOT using INSERT IGNORE as it ignores ALL errors (ie its a sloppy global ignore). Instead, since in your example tag is the unique key, use:

INSERT INTO table_tags (tag) VALUES ('tag_a'),('tab_b'),('tag_c') ON DUPLICATE KEY UPDATE tag=tag;

on duplicate key produces:

Query OK, 0 rows affected (0.07 sec)

How can I reference a dll in the GAC from Visual Studio?

In VS, right click your project, select "Add Reference...", and you will see all the namespaces that exist in your GAC. Choose Microsoft.SqlServer.Management.RegisteredServers and click OK, and you should be good to go

EDIT:

That is the way you want to do this most of the time. However, after a bit of poking around I found this issue on MS Connect. MS says it is a known deployment issue, and they don't have a work around. The guy says if he copies the dll from the GAC folder and drops it in his bin, it works.

make div's height expand with its content

No need to use a lot of CSS, just use bootstrap, then use:

class="container"

for the div that needs to be filled.

You can get bootstrap from here

XPath query to get nth instance of an element

This is a FAQ:

//somexpression[$N]

means "Find every node selected by //somexpression that is the $Nth child of its parent".

What you want is:

(//input[@id="search_query"])[2]

Remember: The [] operator has higher precedence (priority) than the // abbreviation.

.jar error - could not find or load main class

I found this question when I was looking for the answer to the above question. But in my case the issue was the use of an 'en dash' rather than a 'dash'. Check which dash you are using, it might be the wrong one. I hope this answer speeds up someone else's search, a comment like this could have saved me a bit of time.

Android get image path from drawable as string

I think you cannot get it as String but you can get it as int by get resource id:

int resId = this.getResources().getIdentifier("imageNameHere", "drawable", this.getPackageName());

how to convert binary string to decimal?

Another implementation just for functional JS practicing could be

_x000D_
_x000D_
var bin2int = s => Array.prototype.reduce.call(s, (p,c) => p*2 + +c)_x000D_
console.log(bin2int("101010"));
_x000D_
_x000D_
_x000D_ where +c coerces String type c to a Number type value for proper addition.

Understanding ASP.NET Eval() and Bind()

The question was answered perfectly by Darin Dimitrov, but since ASP.NET 4.5, there is now a better way to set up these bindings to replace* Eval() and Bind(), taking advantage of the strongly-typed bindings.

*Note: this will only work if you're not using a SqlDataSource or an anonymous object. It requires a Strongly-typed object (from an EF model or any other class).

This code snippet shows how Eval and Bind would be used for a ListView control (InsertItem needs Bind, as explained by Darin Dimitrov above, and ItemTemplate is read-only (hence they're labels), so just needs an Eval):

<asp:ListView ID="ListView1" runat="server" DataKeyNames="Id" InsertItemPosition="LastItem" SelectMethod="ListView1_GetData" InsertMethod="ListView1_InsertItem" DeleteMethod="ListView1_DeleteItem">
    <InsertItemTemplate>
        <li>
            Title: <asp:TextBox ID="Title" runat="server" Text='<%# Bind("Title") %>'/><br />         
            Description: <asp:TextBox ID="Description" runat="server" TextMode="MultiLine" Text='<%# Bind("Description") %>' /><br />        
            <asp:Button ID="InsertButton" runat="server" Text="Insert" CommandName="Insert" />        
        </li>
    </InsertItemTemplate>
    <ItemTemplate>
        <li>
            Title: <asp:Label ID="Title" runat="server" Text='<%#  Eval("Title") %>' /><br />
            Description: <asp:Label ID="Description" runat="server" Text='<%# Eval("Description") %>' /><br />        
            <asp:Button ID="DeleteButton" runat="server" Text="Delete" CommandName="Delete" CausesValidation="false"/>
        </li>
      </ItemTemplate>

From ASP.NET 4.5+, data-bound controls have been extended with a new property ItemType, which points to the type of object you're assigning to its data source.

<asp:ListView ItemType="Picture" ID="ListView1" runat="server" ...>

Picture is the strongly type object (from EF model). We then replace:

Bind(property) -> BindItem.property
Eval(property) -> Item.property

So this:

<%# Bind("Title") %>      
<%# Bind("Description") %>         
<%#  Eval("Title") %> 
<%# Eval("Description") %>

Would become this:

<%# BindItem.Title %>         
<%# BindItem.Description %>
<%# Item.Title %>
<%# Item.Description %>

Advantages over Eval & Bind:

  • IntelliSense can find the correct property of the object your're working withenter image description here
  • If property is renamed/deleted, you will get an error before page is viewed in browser
  • External tools (requires full versions of VS) will correctly rename item in markup when you rename a property on your object

Source: from this excellent book

Using Cookie in Asp.Net Mvc 4

Try using Response.SetCookie(), because Response.Cookies.Add() can cause multiple cookies to be added, whereas SetCookie will update an existing cookie.

How do I show running processes in Oracle DB?

After looking at sp_who, Oracle does not have that ability per se. Oracle has at least 8 processes running which run the db. Like RMON etc.

You can ask the DB which queries are running as that just a table query. Look at the V$ tables.

Quick Example:

SELECT sid,
       opname,
       sofar,
       totalwork,
       units,
       elapsed_seconds,
       time_remaining
FROM v$session_longops
WHERE sofar != totalwork;

Counting array elements in Perl

Maybe you want a hash instead (or in addition). Arrays are an ordered set of elements; if you create $foo[23], you implicitly create $foo[0] through $foo[22].

Ruby class instance variable vs. class variable

Official Ruby FAQ: What is the difference between class variables and class instance variables?

The main difference is the behavior concerning inheritance: class variables are shared between a class and all its subclasses, while class instance variables only belong to one specific class.

Class variables in some way can be seen as global variables within the context of an inheritance hierarchy, with all the problems that come with global variables. For instance, a class variable might (accidentally) be reassigned by any of its subclasses, affecting all other classes:

class Woof

  @@sound = "woof"

  def self.sound
    @@sound
  end
end

Woof.sound  # => "woof"

class LoudWoof < Woof
  @@sound = "WOOF"
end

LoudWoof.sound  # => "WOOF"
Woof.sound      # => "WOOF" (!)

Or, an ancestor class might later be reopened and changed, with possibly surprising effects:

class Foo

  @@var = "foo"

  def self.var
    @@var
  end
end

Foo.var  # => "foo" (as expected)

class Object
  @@var = "object"
end

Foo.var  # => "object" (!)

So, unless you exactly know what you are doing and explicitly need this kind of behavior, you better should use class instance variables.

If Browser is Internet Explorer: run an alternative script instead

You can do something like this to include IE-specific javascript:

<!--[IF IE]>
    <script type="text/javascript">
        // IE stuff
    </script>
<![endif]-->

How to validate array in Laravel?

Asterisk symbol (*) is used to check values in the array, not the array itself.

$validator = Validator::make($request->all(), [
    "names"    => "required|array|min:3",
    "names.*"  => "required|string|distinct|min:3",
]);

In the example above:

  • "names" must be an array with at least 3 elements,
  • values in the "names" array must be distinct (unique) strings, at least 3 characters long.

EDIT: Since Laravel 5.5 you can call validate() method directly on Request object like so:

$data = $request->validate([
    "name"    => "required|array|min:3",
    "name.*"  => "required|string|distinct|min:3",
]);

No resource found that matches the given name '@style/Theme.AppCompat.Light'

Below are the steps you can try it out to resolve the issue: -

  1. Provide reference of AppCompat Library into your project.
  2. If option 1 doesn't solve the issue then you can try to change the style.xml file to below code.
 parent="android:Theme.Holo.Light"  

instead.

 parent="android:Theme.AppCompat.Light"  

But option 2 will require minimum sdk version 14.

Hope this will help !

Summved

Convert Pixels to Points

This works:

int pixels = (int)((dp) * Resources.System.DisplayMetrics.Density + 0.5f);

HTTP Status 405 - Request method 'POST' not supported (Spring MVC)

I am not sure if this helps but I had the same problem.

You are using springSecurityFilterChain with CSRF protection. That means you have to send a token when you send a form via POST request. Try to add the next input to your form:

<input type="hidden" name="${_csrf.parameterName}" value="${_csrf.token}"/>

Manifest Merger failed with multiple errors in Android Studio

i sloved this problem by removing below line from AndroidManifest.xml

android:allowBackup="true"

How to correctly use the extern keyword in C

In C, 'extern' is implied for function prototypes, as a prototype declares a function which is defined somewhere else. In other words, a function prototype has external linkage by default; using 'extern' is fine, but is redundant.

(If static linkage is required, the function must be declared as 'static' both in its prototype and function header, and these should normally both be in the same .c file).

How to import JSON File into a TypeScript file?

I had read some of the responses and they didn't seem to work for me. I am using Typescript 2.9.2, Angular 6 and trying to import JSON in a Jasmine Unit Test. This is what did the trick for me.

Add:

"resolveJsonModule": true,

To tsconfig.json

Import like:

import * as nameOfJson from 'path/to/file.json';

Stop ng test, start again.

Reference: https://blogs.msdn.microsoft.com/typescript/2018/05/31/announcing-typescript-2-9/#json-imports

How do I manually configure a DataSource in Java?

The javadoc for DataSource you refer to is of the wrong package. You should look at javax.sql.DataSource. As you can see this is an interface. The host and port name configuration depends on the implementation, i.e. the JDBC driver you are using.

I have not checked the Derby javadocs but I suppose the code should compile like this:

ClientDataSource ds = org.apache.derby.jdbc.ClientDataSource()
ds.setHost etc....

Overlay a background-image with an rgba background-color

Yes, there is a way to do this. You could use a pseudo-element after to position a block on top of your background image. Something like this: http://jsfiddle.net/Pevara/N2U6B/

The css for the :after looks like this:

#the-div:hover:after {
    content: ' ';
    position: absolute;
    left: 0;
    right: 0;
    top: 0;
    bottom: 0;
    background-color: rgba(0,0,0,.5);
}

edit:
When you want to apply this to a non-empty element, and just get the overlay on the background, you can do so by applying a positive z-index to the element, and a negative one to the :after. Something like this:

#the-div {
    ...
    z-index: 1;
}
#the-div:hover:after {
    ...
    z-index: -1;
}

And the updated fiddle: http://jsfiddle.net/N2U6B/255/

Pass a String from one Activity to another Activity in Android

Post Value from

Intent ii = new Intent(this, GameStartPage.class);

// ii.putExtra("pkgName", B2MAppsPKGName);

ii.putExtra("pkgName", YourValue);
ii.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
startActivity(ii);

Get Value from

pkgn = getIntent().getExtras().getString("pkgName");

pass JSON to HTTP POST Request

you can pass the json object as the body(third argument) of the fetch request.

How do I find the last column with data?

Try using the code after you active the sheet:

Dim J as integer
J = ActiveSheet.UsedRange.SpecialCells(xlCellTypeLastCell).Row

If you use Cells.SpecialCells(xlCellTypeLastCell).Row only, the problem will be that the xlCellTypeLastCell information will not be updated unless one do a "Save file" action. But use UsedRange will always update the information in realtime.

Clear the entire history stack and start a new activity on Android

Try this:

Intent logout_intent = new Intent(DashboardActivity.this, LoginActivity.class);
logout_intent.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
logout_intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
logout_intent.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(logout_intent);
finish();

How can I define a composite primary key in SQL?

CREATE TABLE `voting` (
  `QuestionID` int(10) unsigned NOT NULL,
  `MemberId` int(10) unsigned NOT NULL,
  `vote` int(10) unsigned NOT NULL,
  PRIMARY KEY  (`QuestionID`,`MemberId`)
);

difference between variables inside and outside of __init__()

I would like to add something to the responses that I read in this thread and this thread (which references this one).

Disclaimer: this remarks come from the experiments I ran

Variables outside __init__:

These are, in fact, static class variables and are, therefore, accesible to all instances of the class.

Variables inside __init__:

The value of these instance variables are only accesible to the instance at hand (through the self reference)

My contribution:

One thing that programmers must consider when using static class variables is that they can be shadowed by instance variables (if you are accessing the static class variables through the self reference).

Explanation:

Previously, I thought that both ways of declaring the variables were exactly the same (silly me), and that was partly because I could access both kind of variables through the self reference. It was now, when I ran into trouble, that I researched the topic and cleared it up.

The problem with accessing static class variables through the self reference is that it only references the static class variable if there is no instance variable with the same name, and to make things worse, trying to redefine a static class variable through the self reference does not work because an instance variable is created which then shadows the previously-accesible static class variable.

To get around this problem, you should always reference static class variables through the name of the class.

Example:

#!/usr/bin/env python

class Foo:
    static_var = 'every instance has access'

    def __init__(self,name):
        self.instance_var = 'I am %s' % name

    def printAll(self):
        print 'self.instance_var = %s' % self.instance_var
        print 'self.static_var = %s' % self.static_var
        print 'Foo.static_var = %s' % Foo.static_var

f1 = Foo('f1')

f1.printAll()

f1.static_var = 'Shadowing static_var'

f1.printAll()

f2 = Foo('f2')

f2.printAll()

Foo.static_var = 'modified class'

f1.printAll()
f2.printAll()

Output:

self.instance_var = I am f1
self.static_var = every instance has access
Foo.static_var = every instance has access
self.instance_var = I am f1
self.static_var = Shadowing static_var
Foo.static_var = every instance has access
self.instance_var = I am f2
self.static_var = every instance has access
Foo.static_var = every instance has access
self.instance_var = I am f1
self.static_var = Shadowing static_var
Foo.static_var = modified class
self.instance_var = I am f2
self.static_var = modified class
Foo.static_var = modified class

I hope this is helpful to someone

form serialize javascript (no framework)

For debugging purposes this might help you:

function print_form_data(form) {
    const form_data = new FormData(form);

    for (const item of form_data.entries()) {
        console.log(item);
    }

    return false;
}

Can I start the iPhone simulator without "Build and Run"?

Without opening Xcode:

open /Applications/Xcode.app/Contents/Developer/Applications/iOS\ Simulator.app/

What is the boundary in multipart/form-data?

The exact answer to the question is: yes, you can use an arbitrary value for the boundary parameter, given it does not exceed 70 bytes in length and consists only of 7-bit US-ASCII (printable) characters.

If you are using one of multipart/* content types, you are actually required to specify the boundary parameter in the Content-Type header, otherwise the server (in the case of an HTTP request) will not be able to parse the payload.

You probably also want to set the charset parameter to UTF-8 in your Content-Type header, unless you can be absolutely sure that only US-ASCII charset will be used in the payload data.

A few relevant excerpts from the RFC2046:

  • 4.1.2. Charset Parameter:

    Unlike some other parameter values, the values of the charset parameter are NOT case sensitive. The default character set, which must be assumed in the absence of a charset parameter, is US-ASCII.

  • 5.1. Multipart Media Type

    As stated in the definition of the Content-Transfer-Encoding field [RFC 2045], no encoding other than "7bit", "8bit", or "binary" is permitted for entities of type "multipart". The "multipart" boundary delimiters and header fields are always represented as 7bit US-ASCII in any case (though the header fields may encode non-US-ASCII header text as per RFC 2047) and data within the body parts can be encoded on a part-by-part basis, with Content-Transfer-Encoding fields for each appropriate body part.

    The Content-Type field for multipart entities requires one parameter, "boundary". The boundary delimiter line is then defined as a line consisting entirely of two hyphen characters ("-", decimal value 45) followed by the boundary parameter value from the Content-Type header field, optional linear whitespace, and a terminating CRLF.

    Boundary delimiters must not appear within the encapsulated material, and must be no longer than 70 characters, not counting the two leading hyphens.

    The boundary delimiter line following the last body part is a distinguished delimiter that indicates that no further body parts will follow. Such a delimiter line is identical to the previous delimiter lines, with the addition of two more hyphens after the boundary parameter value.

Here is an example using an arbitrary boundary:

Content-Type: multipart/form-data; charset=utf-8; boundary="another cool boundary"

--another cool boundary
Content-Disposition: form-data; name="foo"

bar
--another cool boundary
Content-Disposition: form-data; name="baz"

quux
--another cool boundary--

How to add a button programmatically in VBA next to some sheet cell data?

I think this is enough to get you on a nice path:

Sub a()
  Dim btn As Button
  Application.ScreenUpdating = False
  ActiveSheet.Buttons.Delete
  Dim t As Range
  For i = 2 To 6 Step 2
    Set t = ActiveSheet.Range(Cells(i, 3), Cells(i, 3))
    Set btn = ActiveSheet.Buttons.Add(t.Left, t.Top, t.Width, t.Height)
    With btn
      .OnAction = "btnS"
      .Caption = "Btn " & i
      .Name = "Btn" & i
    End With
  Next i
  Application.ScreenUpdating = True
End Sub

Sub btnS()
 MsgBox Application.Caller
End Sub

It creates the buttons and binds them to butnS(). In the btnS() sub, you should show your dialog, etc.

Mathematica graphics

How to create a numpy array of arbitrary length strings?

You could use the object data type:

>>> import numpy
>>> s = numpy.array(['a', 'b', 'dude'], dtype='object')
>>> s[0] += 'bcdef'
>>> s
array([abcdef, b, dude], dtype=object)

How to write :hover condition for a:before and a:after?

To change menu link's text on mouseover. (Different language text on hover) here is the

jsfiddle example

html:

<a align="center" href="#"><span>kannada</span></a>

css:

span {
    font-size:12px;
}
a {
    color:green;
}
a:hover span {
    display:none;
}
a:hover:before {
    color:red;
    font-size:24px;
    content:"?????";
}

Generate a random point within a circle (uniformly)

I am still not sure about the exact '(2/R2)×r' but what is apparent is the number of points required to be distributed in given unit 'dr' i.e. increase in r will be proportional to r2 and not r.

check this way...number of points at some angle theta and between r (0.1r to 0.2r) i.e. fraction of the r and number of points between r (0.6r to 0.7r) would be equal if you use standard generation, since the difference is only 0.1r between two intervals. but since area covered between points (0.6r to 0.7r) will be much larger than area covered between 0.1r to 0.2r, the equal number of points will be sparsely spaced in larger area, this I assume you already know, So the function to generate the random points must not be linear but quadratic, (since number of points required to be distributed in given unit 'dr' i.e. increase in r will be proportional to r2 and not r), so in this case it will be inverse of quadratic, since the delta we have (0.1r) in both intervals must be square of some function so it can act as seed value for linear generation of points (since afterwords, this seed is used linearly in sin and cos function), so we know, dr must be quadratic value and to make this seed quadratic, we need to originate this values from square root of r not r itself, I hope this makes it little more clear.

How to trigger an event in input text after I stop typing/writing?

I've been searching for a simple HTML/JS code and I did not found any. Then, I wrote the code below using onkeyup="DelayedSubmission()".

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="pt-br" lang="pt-br">
<head><title>Submit after typing finished</title>
<script language="javascript" type="text/javascript">
function DelayedSubmission() {
    var date = new Date();
    initial_time = date.getTime();
    if (typeof setInverval_Variable == 'undefined') {
            setInverval_Variable = setInterval(DelayedSubmission_Check, 50);
    } 
}
function DelayedSubmission_Check() {
    var date = new Date();
    check_time = date.getTime();
    var limit_ms=check_time-initial_time;
    if (limit_ms > 800) { //Change value in milliseconds
        alert("insert your function"); //Insert your function
        clearInterval(setInverval_Variable);
        delete setInverval_Variable;
    }
}

</script>
</head>
<body>

<input type="search" onkeyup="DelayedSubmission()" id="field_id" style="WIDTH: 100px; HEIGHT: 25px;" />

</body>
</html>

How to replace values at specific indexes of a python list?

for index in a:

This will cause index to take on the values of the elements of a, so using them as indices is not what you want. In Python, we iterate over a container by actually iterating over it.

"But wait", you say, "For each of those elements of a, I need to work with the corresponding element of m. How am I supposed to do that without indices?"

Simple. We transform a and m into a list of pairs (element from a, element from m), and iterate over the pairs. Which is easy to do - just use the built-in library function zip, as follows:

for a_element, m_element in zip(a, m):
  s[a_element] = m_element

To make it work the way you were trying to do it, you would have to get a list of indices to iterate over. This is doable: we can use range(len(a)) for example. But don't do that! That's not how we do things in Python. Actually directly iterating over what you want to iterate over is a beautiful, mind-liberating idea.

what about operator.itemgetter

Not really relevant here. The purpose of operator.itemgetter is to turn the act of indexing into something, into a function-like thing (what we call "a callable"), so that it can be used as a callback (for example, a 'key' for sorting or min/max operations). If we used it here, we'd have to re-call it every time through the loop to create a new itemgetter, just so that we could immediately use it once and throw it away. In context, that's just busy-work.

How to remove an iOS app from the App Store

Steps to Remove app from App Store

  1. Click the My Apps section.
  2. Select the app you'd like to remove.
  3. Click the Pricing tab from the app listing page.
  4. Click the "specific territories" link.
  5. In the drop-down section that appears below, click "Deselect All' at the top right. This will uncheck every territory below.
  6. A confirmation message will appear at the top of the screen.
  7. Return to the My Apps section by clicking the navigation button at the top left.
  8. The application status has changed to "Developer Removed From Sale."
  9. Within 24 hours (though usually less) your app will no longer appear in the App Store.

enter image description here

How do I use Apache tomcat 7 built in Host Manager gui?

For tomcat 8

1.Go to context.xml file located for instance../home/ubuntu/tomcat/webapps/manager/META-INF/

comment out valve tag. save and exit

2.Go to tomcat-users.xml file located in conf directory of tomcat. Add the respective roles

under the tomcat-users tag. Save and exit.

  1. Restart the tomcat.

Now, you will be able to have access to the manager app.

Adding a favicon to a static HTML page

Actually, to make your favicon work in all browsers, you must have more than 10 images in the correct sizes and formats.

I created an App (faviconit.com) so people don´t have to create all these images and the correct tags by hand.

Hope you like it.

Dropping a connected user from an Oracle 10g database schema

Just my two cents : the best way (but probably not the quickest in the short term) would probably be for each developer to work on his own database instance (see rule #1 for database work).

Installing Oracle on a developer station has become a no brainer since Oracle Database 10g Express Edition.

Error handling in getJSON calls

$.getJSON() is a kind of abstraction of a regular AJAX call where you would have to tell that you want a JSON encoded response.

$.ajax({
  url: url,
  dataType: 'json',
  data: data,
  success: callback
});

You can handle errors in two ways: generically (by configuring your AJAX calls before actually calling them) or specifically (with method chain).

'generic' would be something like:

$.ajaxSetup({
      "error":function() { alert("error");  }
});

And the 'specific' way:

$.getJSON("example.json", function() {
  alert("success");
})
.done(function() { alert("second success"); })
.fail(function() { alert("error"); })
.always(function() { alert("complete"); });

How do I write output in same place on the console?

#kinda like the one above but better :P

from __future__ import print_function
from time import sleep

for i in range(101):
  str1="Downloading File FooFile.txt [{}%]".format(i)
  back="\b"*len(str1)
  print(str1, end="")
  sleep(0.1)
  print(back, end="")

How can I store the result of a system command in a Perl variable?

Also for eg. you can use IPC::Run:

use IPC::Run qw(run);

my $pid = 5892;
run [qw(top -H -n 1 -p), $pid],
    '|', sub { print grep { /myprocess/ } <STDIN> },
    '|', [qw(wc -l)],
    '>', \my $out;

print $out;
  • processes are running without bash subprocess
  • can be piped to perl subs
  • very similar to shell

Convert from DateTime to INT

select DATEDIFF(dd, '12/30/1899', mydatefield)

Sql Server equivalent of a COUNTIF aggregate function

Why not like this?

SELECT count(1)
FROM AD_CurrentView
WHERE myColumn=1

Wheel file installation

If you already have a wheel file (.whl) on your pc, then just go with the following code:

cd ../user
pip install file.whl

If you want to download a file from web, and then install it, go with the following in command line:

pip install package_name

or, if you have the url:

pip install http//websiteurl.com/filename.whl

This will for sure install the required file.

Note: I had to type pip2 instead of pip while using Python 2.

Run bash script as daemon

To run it as a full daemon from a shell, you'll need to use setsid and redirect its output. You can redirect the output to a logfile, or to /dev/null to discard it. Assuming your script is called myscript.sh, use the following command:

setsid myscript.sh >/dev/null 2>&1 < /dev/null &

This will completely detach the process from your current shell (stdin, stdout and stderr). If you want to keep the output in a logfile, replace the first /dev/null with your /path/to/logfile.

You have to redirect the output, otherwise it will not run as a true daemon (it will depend on your shell to read and write output).

How to print third column to last column?

In Bash you can use the following syntax with positional parameters:

while read -a cols; do echo ${cols[@]:2}; done < file.txt

Learn more: Handling positional parameters at Bash Hackers Wiki

Use placeholders in yaml

Context

  • YAML version 1.2
  • user wishes to
    • include variable placeholders in YAML
    • have placeholders replaced with computed values, upon yaml.load
    • be able to use placeholders for both YAML mapping keys and values

Problem

  • YAML does not natively support variable placeholders.
  • Anchors and Aliases almost provide the desired functionality, but these do not work as variable placeholders that can be inserted into arbitrary regions throughout the YAML text. They must be placed as separate YAML nodes.
  • There are some add-on libraries that support arbitrary variable placeholders, but they are not part of the native YAML specification.

Example

Consider the following example YAML. It is well-formed YAML syntax, however it uses (non-standard) curly-brace placeholders with embedded expressions.

The embedded expressions do not produce the desired result in YAML, because they are not part of the native YAML specification. Nevertheless, they are used in this example only to help illustrate what is available with standard YAML and what is not.

part01_customer_info:
  cust_fname:   "Homer"
  cust_lname:   "Himpson"
  cust_motto:   "I love donuts!"
  cust_email:   [email protected]

part01_government_info:
  govt_sales_taxrate: 1.15

part01_purchase_info:
  prch_unit_label:    "Bacon-Wrapped Fancy Glazed Donut"
  prch_unit_price:    3.00
  prch_unit_quant:    7
  prch_product_cost:  "{{prch_unit_price * prch_unit_quant}}"
  prch_total_cost:    "{{prch_product_cost * govt_sales_taxrate}}"   

part02_shipping_info:
  cust_fname:   "{{cust_fname}}"
  cust_lname:   "{{cust_lname}}"
  ship_city:    Houston
  ship_state:   Hexas    

part03_email_info:
  cust_email:     "{{cust_email}}"
  mail_subject:   Thanks for your DoughNutz order!
  mail_notes: |
    We want the mail_greeting to have all the expected values
    with filled-in placeholders (and not curly-braces).
  mail_greeting: |
    Greetings {{cust_fname}} {{cust_lname}}!
    
    We love your motto "{{cust_motto}}" and we agree with you!
    
    Your total purchase price is {{prch_total_cost}}
    

Explanation

  • The substitutions marked in GREEN are readily available in standard YAML, using anchors, aliases, and merge keys.

  • The substitutions marked in YELLOW are technically available in standard YAML, but not without a custom type declaration, or some other binding mechanism.

  • The substitutions marked in RED are not available in standard YAML. Yet there are workarounds and alternatives; such as through string formatting or string template engines (such as python's str.format).

Image explaining the different types of variable substitution in YAML

Details

A frequently-requested feature for YAML is the ability to insert arbitrary variable placeholders that support arbitrary cross-references and expressions that relate to the other content in the same (or transcluded) YAML file(s).

YAML supports anchors and aliases, but this feature does not support arbitrary placement of placeholders and expressions anywhere in the YAML text. They only work with YAML nodes.

YAML also supports custom type declarations, however these are less common, and there are security implications if you accept YAML content from potentially untrusted sources.

YAML addon libraries

There are YAML extension libraries, but these are not part of the native YAML spec.

Workarounds

  • Use YAML in conjunction with a template system, such as Jinja2 or Twig
  • Use a YAML extension library
  • Use sprintf or str.format style functionality from the hosting language

Alternatives

  • YTT YAML Templating essentially a fork of YAML with additional features that may be closer to the goal specified in the OP.
  • Jsonnet shares some similarity with YAML, but with additional features that may be closer to the goal specified in the OP.

See also

Here at SO

Outside SO

How to center buttons in Twitter Bootstrap 3?

<div class="container-fluid">
   <div class="col-sm-12 text-center">
       <button class="btn btn-primary" title="Submit"></button>
       <button class="btn btn-warning" title="Cancel"></button>
   </div>
</div>

is there any PHP function for open page in new tab

Use the target attribute on your anchor tag with the _blank value.

Example:

<a href="http://google.com" target="_blank">Click Me!</a>

Java constructor/method with optional parameters?

You can simulate it with using varargs, however then you should check it for too many arguments.

public void foo(int param1, int ... param2)
{
   int param2_
   if(param2.length == 0)
      param2_ = 2
   else if(para2.length == 1)
      param2_ = param2[0]
   else
      throw new TooManyArgumentsException(); // user provided too many arguments,

   // rest of the code
}

However this approach is not a good way of doing this, therefore it is better to use overloading.

Rollback to last git commit

git reset --hard will force the working directory back to the last commit and delete new/changed files.

How do I create a HTTP Client Request with a cookie?

The use of http.createClient is now deprecated. You can pass Headers in options collection as below.

var options = { 
    hostname: 'example.com',
    path: '/somePath.php',
    method: 'GET',
    headers: {'Cookie': 'myCookie=myvalue'}
};
var results = ''; 
var req = http.request(options, function(res) {
    res.on('data', function (chunk) {
        results = results + chunk;
        //TODO
    }); 
    res.on('end', function () {
        //TODO
    }); 
});

req.on('error', function(e) {
        //TODO
});

req.end();

How to map calculated properties with JPA and Hibernate

Take a look at Blaze-Persistence Entity Views which works on top of JPA and provides first class DTO support. You can project anything to attributes within Entity Views and it will even reuse existing join nodes for associations if possible.

Here is an example mapping

@EntityView(Order.class)
interface OrderSummary {
  Integer getId();
  @Mapping("SUM(orderPositions.price * orderPositions.amount * orderPositions.tax)")
  BigDecimal getOrderAmount();
  @Mapping("COUNT(orderPositions)")
  Long getItemCount();
}

Fetching this will generate a JPQL/HQL query similar to this

SELECT
  o.id,
  SUM(p.price * p.amount * p.tax),
  COUNT(p.id)
FROM
  Order o
LEFT JOIN
  o.orderPositions p
GROUP BY
  o.id

Here is a blog post about custom subquery providers which might be interesting to you as well: https://blazebit.com/blog/2017/entity-view-mapping-subqueries.html

Replace a string in a file with nodejs

On Linux or Mac, keep is simple and just use sed with the shell. No external libraries required. The following code works on Linux.

const shell = require('child_process').execSync
shell(`sed -i "s!oldString!newString!g" ./yourFile.js`)

The sed syntax is a little different on Mac. I can't test it right now, but I believe you just need to add an empty string after the "-i":

const shell = require('child_process').execSync
shell(`sed -i "" "s!oldString!newString!g" ./yourFile.js`)

The "g" after the final "!" makes sed replace all instances on a line. Remove it, and only the first occurrence per line will be replaced.

Evenly distributing n points on a sphere

This is known as packing points on a sphere, and there is no (known) general, perfect solution. However, there are plenty of imperfect solutions. The three most popular seem to be:

  1. Create a simulation. Treat each point as an electron constrained to a sphere, then run a simulation for a certain number of steps. The electrons' repulsion will naturally tend the system to a more stable state, where the points are about as far away from each other as they can get.
  2. Hypercube rejection. This fancy-sounding method is actually really simple: you uniformly choose points (much more than n of them) inside of the cube surrounding the sphere, then reject the points outside of the sphere. Treat the remaining points as vectors, and normalize them. These are your "samples" - choose n of them using some method (randomly, greedy, etc).
  3. Spiral approximations. You trace a spiral around a sphere, and evenly-distribute the points around the spiral. Because of the mathematics involved, these are more complicated to understand than the simulation, but much faster (and probably involving less code). The most popular seems to be by Saff, et al.

A lot more information about this problem can be found here

Easy way to print Perl array? (with a little formatting)

I've not tried to run below, though. I think this's a tricky way.

map{print $_;} @array;

VBA, if a string contains a certain letter

Not sure if this is what you're after, but it will loop through the range that you gave it and if it finds an "A" it will remove it from the cell. I'm not sure what oldStr is used for...

Private Sub foo()
Dim myString As String
RowCount = WorksheetFunction.CountA(Range("A:A"))

For i = 2 To RowCount
    myString = Trim(Cells(i, 1).Value)
    If InStr(myString, "A") > 0 Then
        Cells(i, 1).Value = Left(myString, InStr(myString, "A"))
    End If
Next
End Sub

Re-run Spring Boot Configuration Annotation Processor to update generated metadata

None of these options worked for me. I've found that the auto detection of annotation processors to be pretty flaky. I ended up creating a plugin section in the pom.xml file that explicitly sets the annotation processors that are used for the project. The advantage of this is that you don't need to rely on any IDE settings.

<plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
        </plugin>
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-compiler-plugin</artifactId>
            <version>3.7.0</version>
            <configuration>
                <compilerVersion>1.8</compilerVersion>
                <source>1.8</source>
                <target>1.8</target>
                <annotationProcessors>
                    <annotationProcessor>org.springframework.boot.configurationprocessor.ConfigurationMetadataAnnotationProcessor</annotationProcessor>
                    <annotationProcessor>lombok.launch.AnnotationProcessorHider$AnnotationProcessor</annotationProcessor>
                    <annotationProcessor>org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor</annotationProcessor>
                </annotationProcessors>
            </configuration>
        </plugin>

wait() or sleep() function in jquery?

That'd be .delay().

http://api.jquery.com/delay/

If you are doing AJAX stuff tho, you really shouldn't just auto write "done" you should really wait for a response and see if it's actually done.

PHP __get and __set magic methods

Drop the public $bar; declaration and it should work as expected.

Get value of a specific object property in C# without knowing the class behind

Simply try this for all properties of an object,

foreach (var prop in myobject.GetType().GetProperties(BindingFlags.Public|BindingFlags.Instance))
{
   var propertyName = prop.Name;
   var propertyValue = myobject.GetType().GetProperty(propertyName).GetValue(myobject, null);

   //Debug.Print(prop.Name);
   //Debug.Print(Functions.convertNullableToString(propertyValue));

   Debug.Print(string.Format("Property Name={0} , Value={1}", prop.Name, Functions.convertNullableToString(propertyValue)));
}

NOTE: Functions.convertNullableToString() is custom function using for convert NULL value into string.empty.

Removing ul indentation with CSS

Remove this from #info:

    margin-left:auto;

Add this for your header:

#info p {
    text-align: center;
}

Do you need the fixed width etc.? I removed the in my opinion not necessary stuff and centered the header with text-align.

Sample
http://jsfiddle.net/Vc8CB/

How do I use LINQ Contains(string[]) instead of Contains(string)

I believe that what you really want to do is: let's imagine a scenario you have two database and they have a table of products in common And you want to select products from the table "A" that id has in common with the "B"

using the method contains would be too complicated to do this what we are doing is an intersection, and there is a method called intersection for that

an example from msdn: http://msdn.microsoft.com/en-us/vcsharp/aa336761.aspx#intersect1

int [] numbers = (0, 2, 4, 5, 6, 8, 9); int [] numbersB = (1, 3, 5, 7, 8); var = commonNumbers numbersA.Intersect (numbersB);

I think what you need is easily solved with intersection

How to set scope property with ng-init?

HTML:

<body ng-app="App">
    <div ng-controller="testController" >
        <input type="hidden" id="testInput" ng-model="testInput" ng-init="testInput=123" />
    </div>
    {{ testInput }}
</body>

JS:

angular.module('App', []);

testController = function ($scope) {
    console.log('test');
    $scope.$watch('testInput', testShow, true);
    function testShow() {
      console.log($scope.testInput);
    }
}

Fiddle

Return Bit Value as 1/0 and NOT True/False in SQL Server

This can be changed to 0/1 through using CASE WHEN like this example:

SELECT 
 CASE WHEN SchemaName.TableName.BitFieldName = 'true' THEN 1 ELSE 0 END AS 'bit Value' 
 FROM SchemaName.TableName

How to break out of while loop in Python?

Don't use while True and break statements. It's bad programming.

Imagine you come to debug someone else's code and you see a while True on line 1 and then have to trawl your way through another 200 lines of code with 15 break statements in it, having to read umpteen lines of code for each one to work out what actually causes it to get to the break. You'd want to kill them...a lot.

The condition that causes a while loop to stop iterating should always be clear from the while loop line of code itself without having to look elsewhere.

Phil has the "correct" solution, as it has a clear end condition right there in the while loop statement itself.

Git commit with no commit message

Git requires a commit to have a comment, otherwise it wont accept the commit.

You can configure a default template with git as your default commit message or can look up the --allow-empty-message flag in git. I think (not 100% sure) you can reconfigure git to accept empty commit messages (which isn´t such a good idea). Normally each commit should be a bit of work which is described by your message.

Define constant variables in C++ header

You could simply define a series of const ints in a header file:

// Constants.h
#if !defined(MYLIB_CONSTANTS_H)
#define MYLIB_CONSTANTS_H 1

const int a = 100;
const int b = 0x7f;

#endif

This works because in C++ a name at namespace scope (including the global namespace) that is explicitly declared const and not explicitly declared extern has internal linkage, so these variables would not cause duplicate symbols when you link together translation units. Alternatively you could explicitly declare the constants as static.

static const int a = 100;
static const int b = 0x7f;

This is more compatible with C and more readable for people that may not be familiar with C++ linkage rules.

If all the constants are ints then another method you could use is to declare the identifiers as enums.

enum mylib_constants {
    a = 100;
    b = 0x7f;
};

All of these methods use only a header and allow the declared names to be used as compile time constants. Using extern const int and a separate implementation file prevents the names from being used as compile time constants.


Note that the rule that makes certain constants implicitly internal linkage does apply to pointers, exactly like constants of other types. The tricky thing though is that marking a pointer as const requires syntax a little different that most people use to make variables of other types const. You need to do:

int * const ptr;

to make a constant pointer, so that the rule will apply to it.

Also note that this is one reason I prefer to consistently put const after the type: int const instead of const int. I also put the * next to the variable: i.e. int *ptr; instead of int* ptr; (compare also this discussion).

I like to do these sorts of things because they reflect the general case of how C++ really works. The alternatives (const int, int* p) are just special cased to make some simple things more readable. The problem is that when you step out of those simple cases, the special cased alternatives become actively misleading.

So although the earlier examples show the common usage of const, I would actually recommend people write them like this:

int const a = 100;
int const b = 0x7f;

and

static int const a = 100;
static int const b = 0x7f;

How to send multiple data fields via Ajax?

Try with quotes:

data: {"status": status, "name": name}

It must work fine.

How can I convert ticks to a date format?

    private void button1_Click(object sender, EventArgs e)
    {
        long myTicks = 633896886277130000;
        DateTime dtime = new DateTime(myTicks);
        MessageBox.Show(dtime.ToString("MMMM d, yyyy"));
    }

Gives

September 27, 2009

Is that what you need?

I don't see how that format is necessarily easy to work with in SQL queries, though.

What is the meaning of ToString("X2")?

It formats the string as two uppercase hexadecimal characters.

In more depth, the argument "X2" is a "format string" that tells the ToString() method how it should format the string. In this case, "X2" indicates the string should be formatted in Hexadecimal.

byte.ToString() without any arguments returns the number in its natural decimal representation, with no padding.

Microsoft documents the standard numeric format strings which generally work with all primitive numeric types' ToString() methods. This same pattern is used for other types as well: for example, standard date/time format strings can be used with DateTime.ToString().

Could not resolve Spring property placeholder

You may have more than one org.springframework.beans.factory.config.PropertyPlaceholderConfigurer in your application. Try setting a breakpoint on the setLocations method of the superclass and see if it's called more than once at application startup. If there is more than one org.springframework.beans.factory.config.PropertyPlaceholderConfigurer, you might need to look at configuring the ignoreUnresolvablePlaceholders property so that your application will start up cleanly.

Set UITableView content inset permanently

Probably it was some sort of my mistake because of me messing with autolayouts and storyboard but I found an answer.

You have to take care of this little guy in View Controller's Attribute Inspector asvi

It must be unchecked so the default contentInset wouldn't be set after any change. After that it is just adding one-liner to viewDidLoad:

[self.tableView setContentInset:UIEdgeInsetsMake(108, 0, 0, 0)]; // 108 is only example

iOS 11, Xcode 9 update

Looks like the previous solution is no longer a correct one if it comes to iOS 11 and Xcode 9. automaticallyAdjustsScrollViewInsets has been deprecated and right now to achieve similar effect you have to go to Size Inspector where you can find this: enter image description here
Also, you can achieve the same in code:

if #available(iOS 11.0, *) {
    scrollView.contentInsetAdjustmentBehavior = .never
} else {
    automaticallyAdjustsScrollViewInsets = false
}

java.io.InvalidClassException: local class incompatible:

If you are using the Eclipse IDE, check your Debug/Run configuration. At Classpath tab, select the runner project and click Edit button. Only include exported entries must be checked.

Jquery If radio button is checked

$('input:radio[name="postage"]').change(function(){
    if($(this).val() === 'Yes'){
       // append stuff
    }
});

This will listen for a change event on the radio buttons. At the time the user clicks Yes, the event will fire and you will be able to append anything you like to the DOM.

How do I delete a Git branch locally and remotely?

git branch -D <name-of-branch>
git branch -D -r origin/<name-of-branch>
git push origin :<name-of-branch>

Tomcat is not deploying my web project from Eclipse

I fixed this issue, this way:

  1. Stop the Server
  2. Remove the previous Deploy that You did
  3. Clean it
  4. Deploy it again

What is the difference between readonly="true" & readonly="readonly"?

readonly="true" is invalid HTML5, readonly="readonly" is valid.

HTML5 spec:

http://www.w3.org/TR/html5/forms.html#attr-input-readonly :

The readonly attribute is a boolean attribute

http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes :

The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.

If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.

Conclusion:

The following are valid, equivalent and true:

<input type="text" readonly />
<input type="text" readonly="" />
<input type="text" readonly="readonly" />
<input type="text" readonly="ReAdOnLy" />

The following are invalid:

<input type="text" readonly="0" />
<input type="text" readonly="1" />
<input type="text" readonly="false" />
<input type="text" readonly="true" />

The absence of the attribute is the only valid syntax for false:

<input type="text"/>

Recommendation

If you care about writing valid XHTML, use readonly="readonly", since <input readonly> is invalid and other alternatives are less readable. Else, just use <input readonly> as it is shorter.

node.js vs. meteor.js what's the difference?

Meteor's strength is in it's real-time updates feature which works well for some of the social applications you see nowadays where you see everyone's updates for what you're working on. These updates center around replicating subsets of a MongoDB collection underneath the covers as local mini-mongo (their client side MongoDB subset) database updates on your web browser (which causes multiple render events to be fired on your templates). The latter part about multiple render updates is also the weakness. If you want your UI to control when the UI refreshes (e.g., classic jQuery AJAX pages where you load up the HTML and you control all the AJAX calls and UI updates), you'll be fighting this mechanism.

Meteor uses a nice stack of Node.js plugins (Handlebars.js, Spark.js, Bootstrap css, etc. but using it's own packaging mechanism instead of npm) underneath along w/ MongoDB for the storage layer that you don't have to think about. But sometimes you end up fighting it as well...e.g., if you want to customize the Bootstrap theme, it messes up the loading sequence of Bootstrap's responsive.css file so it no longer is responsive (but this will probably fix itself when Bootstrap 3.0 is released soon).

So like all "full stack frameworks", things work great as long as your app fits what's intended. Once you go beyond that scope and push the edge boundaries, you might end up fighting the framework...

Resize to fit image in div, and center horizontally and vertically

This is one way to do it:

Fiddle here: http://jsfiddle.net/4Mvan/1/

HTML:

<div class='container'>
    <a href='#'>
    <img class='resize_fit_center'
      src='http://i.imgur.com/H9lpVkZ.jpg' />
    </a>
</div>

CSS:

.container {
    margin: 10px;
    width: 115px;
    height: 115px;
    line-height: 115px;
    text-align: center;
    border: 1px solid red;
}
.resize_fit_center {
    max-width:100%;
    max-height:100%;
    vertical-align: middle;
}

How to check if a string contains text from an array of substrings in JavaScript?

This is super late, but I just ran into this problem. In my own project I used the following to check if a string was in an array:

["a","b"].includes('a')     // true
["a","b"].includes('b')     // true
["a","b"].includes('c')     // false

This way you can take a predefined array and check if it contains a string:

var parameters = ['a','b']
parameters.includes('a')    // true

Update Multiple Rows in Entity Framework from a list of ids

var idList=new int[]{1, 2, 3, 4};
var friendsToUpdate = await Context.Friends.Where(f => 
    idList.Contains(f.Id).ToListAsync();

foreach(var item in previousEReceipts)
{
  item.msgSentBy = "1234";
}

You can use foreach to update each element that meets your condition.

Here is an example in a more generic way:

var itemsToUpdate = await Context.friends.Where(f => f.Id == <someCondition>).ToListAsync();

foreach(var item in itemsToUpdate)
{
   item.property = updatedValue;
}
Context.SaveChanges()

In general you will most probably use async methods with await for db queries.

Is it really impossible to make a div fit its size to its content?

CSS display setting

It is of course possible - JSFiddle proof of concept where you can see all three possible solutions:

  • display: inline-block - this is the one you're not aware of

  • position: absolute

  • float: left/right

How to read a text file in project's root directory?

In this code you access to root directory project:

 string _filePath = Path.GetDirectoryName(System.AppDomain.CurrentDomain.BaseDirectory);

then:

StreamReader r = new StreamReader(_filePath + "/cities2.json"))

How can I run NUnit tests in Visual Studio 2017?

You need to install NUnitTestAdapter. The latest version of NUnit is 3.x.y (3.6.1) and you should install NUnit3TestAdapter along with NUnit 3.x.y

To install NUnit3TestAdapter in Visual Studio 2017, follow the steps below:

  1. Right click on menu Project ? click "Manage NuGet Packages..." from the context menu
  2. Go to the Browse tab and search for NUnit
  3. Select NUnit3TestAdapter ? click Install at the right side ? click OK from the Preview pop up

Enter image description here

Multiple glibc libraries on a single host

Use LD_PRELOAD: put your library somewhere out of the man lib directories and run:

LD_PRELOAD='mylibc.so anotherlib.so' program

See: the Wikipedia article

How to change position of Toast in Android?

//A custom toast class where you can show custom or default toast as desired)

public class ToastMessage {
            private Context context;
            private static ToastMessage instance;

            /**
             * @param context
             */
            private ToastMessage(Context context) {
                this.context = context;
            }

            /**
             * @param context
             * @return
             */
            public synchronized static ToastMessage getInstance(Context context) {
                if (instance == null) {
                    instance = new ToastMessage(context);
                }
                return instance;
            }

            /**
             * @param message
             */
            public void showLongMessage(String message) {
                Toast.makeText(context, message, Toast.LENGTH_SHORT).show();
            }

            /**
             * @param message
             */
            public void showSmallMessage(String message) {
                Toast.makeText(context, message, Toast.LENGTH_LONG).show();
            }

            /**
             * The Toast displayed via this method will display it for short period of time
             *
             * @param message
             */
            public void showLongCustomToast(String message) {
                LayoutInflater inflater = ((Activity) context).getLayoutInflater();
                View layout = inflater.inflate(R.layout.layout_custom_toast, (ViewGroup) ((Activity) context).findViewById(R.id.ll_toast));
                TextView msgTv = (TextView) layout.findViewById(R.id.tv_msg);
                msgTv.setText(message);
                Toast toast = new Toast(context);
                toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.BOTTOM, 0, 0);
                toast.setDuration(Toast.LENGTH_LONG);
                toast.setView(layout);
                toast.show();


            }

            /**
             * The toast displayed by this class will display it for long period of time
             *
             * @param message
             */
            public void showSmallCustomToast(String message) {

                LayoutInflater inflater = ((Activity) context).getLayoutInflater();
                View layout = inflater.inflate(R.layout.layout_custom_toast, (ViewGroup) ((Activity) context).findViewById(R.id.ll_toast));
                TextView msgTv = (TextView) layout.findViewById(R.id.tv_msg);
                msgTv.setText(message);
                Toast toast = new Toast(context);
                toast.setGravity(Gravity.FILL_HORIZONTAL | Gravity.BOTTOM, 0, 0);
                toast.setDuration(Toast.LENGTH_SHORT);
                toast.setView(layout);
                toast.show();
            }

        }

Performing a query on a result from another query?

Note that your initial query is probably not returning what you want:

SELECT availables.bookdate AS Date, DATEDIFF(now(),availables.updated_at) as Age 
FROM availables INNER JOIN rooms ON availables.room_id=rooms.id 
WHERE availables.bookdate BETWEEN  '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094 GROUP BY availables.bookdate

You are grouping by book date, but you are not using any grouping function on the second column of your query.

The query you are probably looking for is:

SELECT availables.bookdate AS Date, count(*) as subtotal, sum(DATEDIFF(now(),availables.updated_at) as Age)
FROM availables INNER JOIN rooms ON availables.room_id=rooms.id
WHERE availables.bookdate BETWEEN '2009-06-25' AND date_add('2009-06-25', INTERVAL 4 DAY) AND rooms.hostel_id = 5094
GROUP BY availables.bookdate

How can I calculate an md5 checksum of a directory?

GNU find

find /path -type f -name "*.py" -exec md5sum "{}" +;

Why does git status show branch is up-to-date when changes exist upstream?

in this case use git add and integrate all pending files and then use git commit and then git push

git add - integrate all pedent files

git commit - save the commit

git push - save to repository

PhpMyAdmin not working on localhost

when I started xampp on my windows 10 there were many options available, unfortunately every one of them failed. I ll list them so that you don't go through all of them again.

THINGS THAT DIDN'T WORK

1) i installed xampp initially in a different drive and not c because of UAC issues so i uninstalled Xampp and installed it again in c (didn't work) 2) while reinstalling i deactivated the antivirus as setup said that some installing might not end up properly(realized it doesn't matter :) lmao) 3) i tried to change ports several times of xampp from 80 to some different number like 8080 etc. still nothing happened 4) i then tried using firefox as it is believed that internet explorer or internet edge is not a good browser for xampp 5) after that i went to config file i.e config.inc inside phpmyadmin folder and did some crap as were given in the instructions. Failure it was 6) then i closed laptop and went to sleep(XD srry leave this point) 7) then i tried searching for windows web services in the services.msc to disable it. i couldn't find it

WHAT WORKED

On eighth time i got success.This is what i did 8)In control panel, where you have actions , modules PIDs, Ports you will see Services under which you will see gray boxes which are actually checkboxes but are empty initially. i checked it so that xampp services start and apache services start. now you will see them ticked. After that just change the port of xampp and apache to 80.

I hope it helps. cheers ;)

403 Forbidden You don't have permission to access /folder-name/ on this server

Solved issue using below steps :

1) edit file "/etc/apache2/sites-enabled/000-default.conf"

    DocumentRoot "dir_name"

    ServerName <server_IP>

    <Directory "dir_name">
       Options Indexes FollowSymLinks
       AllowOverride None
       Require all granted
    </Directory>

    <Directory "dir_name">
       AllowOverride None
       # Allow open access:
       Require all granted

2) change folder permission sudo chmod -R 777 "dir_name"

Global keyboard capture in C# application

As requested by dube I'm posting my modified version of Siarhei Kuchuk's answer.
If you want to check my changes search for // EDT. I've commented most of it.

The Setup

class GlobalKeyboardHookEventArgs : HandledEventArgs
{
    public GlobalKeyboardHook.KeyboardState KeyboardState { get; private set; }
    public GlobalKeyboardHook.LowLevelKeyboardInputEvent KeyboardData { get; private set; }

    public GlobalKeyboardHookEventArgs(
        GlobalKeyboardHook.LowLevelKeyboardInputEvent keyboardData,
        GlobalKeyboardHook.KeyboardState keyboardState)
    {
        KeyboardData = keyboardData;
        KeyboardState = keyboardState;
    }
}

//Based on https://gist.github.com/Stasonix
class GlobalKeyboardHook : IDisposable
{
    public event EventHandler<GlobalKeyboardHookEventArgs> KeyboardPressed;

    // EDT: Added an optional parameter (registeredKeys) that accepts keys to restict
    // the logging mechanism.
    /// <summary>
    /// 
    /// </summary>
    /// <param name="registeredKeys">Keys that should trigger logging. Pass null for full logging.</param>
    public GlobalKeyboardHook(Keys[] registeredKeys = null)
    {
        RegisteredKeys = registeredKeys;
        _windowsHookHandle = IntPtr.Zero;
        _user32LibraryHandle = IntPtr.Zero;
        _hookProc = LowLevelKeyboardProc; // we must keep alive _hookProc, because GC is not aware about SetWindowsHookEx behaviour.

        _user32LibraryHandle = LoadLibrary("User32");
        if (_user32LibraryHandle == IntPtr.Zero)
        {
            int errorCode = Marshal.GetLastWin32Error();
            throw new Win32Exception(errorCode, $"Failed to load library 'User32.dll'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
        }



        _windowsHookHandle = SetWindowsHookEx(WH_KEYBOARD_LL, _hookProc, _user32LibraryHandle, 0);
        if (_windowsHookHandle == IntPtr.Zero)
        {
            int errorCode = Marshal.GetLastWin32Error();
            throw new Win32Exception(errorCode, $"Failed to adjust keyboard hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
        }
    }

    protected virtual void Dispose(bool disposing)
    {
        if (disposing)
        {
            // because we can unhook only in the same thread, not in garbage collector thread
            if (_windowsHookHandle != IntPtr.Zero)
            {
                if (!UnhookWindowsHookEx(_windowsHookHandle))
                {
                    int errorCode = Marshal.GetLastWin32Error();
                    throw new Win32Exception(errorCode, $"Failed to remove keyboard hooks for '{Process.GetCurrentProcess().ProcessName}'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
                }
                _windowsHookHandle = IntPtr.Zero;

                // ReSharper disable once DelegateSubtraction
                _hookProc -= LowLevelKeyboardProc;
            }
        }

        if (_user32LibraryHandle != IntPtr.Zero)
        {
            if (!FreeLibrary(_user32LibraryHandle)) // reduces reference to library by 1.
            {
                int errorCode = Marshal.GetLastWin32Error();
                throw new Win32Exception(errorCode, $"Failed to unload library 'User32.dll'. Error {errorCode}: {new Win32Exception(Marshal.GetLastWin32Error()).Message}.");
            }
            _user32LibraryHandle = IntPtr.Zero;
        }
    }

    ~GlobalKeyboardHook()
    {
        Dispose(false);
    }

    public void Dispose()
    {
        Dispose(true);
        GC.SuppressFinalize(this);
    }

    private IntPtr _windowsHookHandle;
    private IntPtr _user32LibraryHandle;
    private HookProc _hookProc;

    delegate IntPtr HookProc(int nCode, IntPtr wParam, IntPtr lParam);

    [DllImport("kernel32.dll")]
    private static extern IntPtr LoadLibrary(string lpFileName);

    [DllImport("kernel32.dll", CharSet = CharSet.Auto)]
    private static extern bool FreeLibrary(IntPtr hModule);

    /// <summary>
    /// The SetWindowsHookEx function installs an application-defined hook procedure into a hook chain.
    /// You would install a hook procedure to monitor the system for certain types of events. These events are
    /// associated either with a specific thread or with all threads in the same desktop as the calling thread.
    /// </summary>
    /// <param name="idHook">hook type</param>
    /// <param name="lpfn">hook procedure</param>
    /// <param name="hMod">handle to application instance</param>
    /// <param name="dwThreadId">thread identifier</param>
    /// <returns>If the function succeeds, the return value is the handle to the hook procedure.</returns>
    [DllImport("USER32", SetLastError = true)]
    static extern IntPtr SetWindowsHookEx(int idHook, HookProc lpfn, IntPtr hMod, int dwThreadId);

    /// <summary>
    /// The UnhookWindowsHookEx function removes a hook procedure installed in a hook chain by the SetWindowsHookEx function.
    /// </summary>
    /// <param name="hhk">handle to hook procedure</param>
    /// <returns>If the function succeeds, the return value is true.</returns>
    [DllImport("USER32", SetLastError = true)]
    public static extern bool UnhookWindowsHookEx(IntPtr hHook);

    /// <summary>
    /// The CallNextHookEx function passes the hook information to the next hook procedure in the current hook chain.
    /// A hook procedure can call this function either before or after processing the hook information.
    /// </summary>
    /// <param name="hHook">handle to current hook</param>
    /// <param name="code">hook code passed to hook procedure</param>
    /// <param name="wParam">value passed to hook procedure</param>
    /// <param name="lParam">value passed to hook procedure</param>
    /// <returns>If the function succeeds, the return value is true.</returns>
    [DllImport("USER32", SetLastError = true)]
    static extern IntPtr CallNextHookEx(IntPtr hHook, int code, IntPtr wParam, IntPtr lParam);

    [StructLayout(LayoutKind.Sequential)]
    public struct LowLevelKeyboardInputEvent
    {
        /// <summary>
        /// A virtual-key code. The code must be a value in the range 1 to 254.
        /// </summary>
        public int VirtualCode;

        // EDT: added a conversion from VirtualCode to Keys.
        /// <summary>
        /// The VirtualCode converted to typeof(Keys) for higher usability.
        /// </summary>
        public Keys Key { get { return (Keys)VirtualCode; } }

        /// <summary>
        /// A hardware scan code for the key. 
        /// </summary>
        public int HardwareScanCode;

        /// <summary>
        /// The extended-key flag, event-injected Flags, context code, and transition-state flag. This member is specified as follows. An application can use the following values to test the keystroke Flags. Testing LLKHF_INJECTED (bit 4) will tell you whether the event was injected. If it was, then testing LLKHF_LOWER_IL_INJECTED (bit 1) will tell you whether or not the event was injected from a process running at lower integrity level.
        /// </summary>
        public int Flags;

        /// <summary>
        /// The time stamp stamp for this message, equivalent to what GetMessageTime would return for this message.
        /// </summary>
        public int TimeStamp;

        /// <summary>
        /// Additional information associated with the message. 
        /// </summary>
        public IntPtr AdditionalInformation;
    }

    public const int WH_KEYBOARD_LL = 13;
    //const int HC_ACTION = 0;

    public enum KeyboardState
    {
        KeyDown = 0x0100,
        KeyUp = 0x0101,
        SysKeyDown = 0x0104,
        SysKeyUp = 0x0105
    }

    // EDT: Replaced VkSnapshot(int) with RegisteredKeys(Keys[])
    public static Keys[] RegisteredKeys;
    const int KfAltdown = 0x2000;
    public const int LlkhfAltdown = (KfAltdown >> 8);

    public IntPtr LowLevelKeyboardProc(int nCode, IntPtr wParam, IntPtr lParam)
    {
        bool fEatKeyStroke = false;

        var wparamTyped = wParam.ToInt32();
        if (Enum.IsDefined(typeof(KeyboardState), wparamTyped))
        {
            object o = Marshal.PtrToStructure(lParam, typeof(LowLevelKeyboardInputEvent));
            LowLevelKeyboardInputEvent p = (LowLevelKeyboardInputEvent)o;

            var eventArguments = new GlobalKeyboardHookEventArgs(p, (KeyboardState)wparamTyped);

            // EDT: Removed the comparison-logic from the usage-area so the user does not need to mess around with it.
            // Either the incoming key has to be part of RegisteredKeys (see constructor on top) or RegisterdKeys
            // has to be null for the event to get fired.
            var key = (Keys)p.VirtualCode;
            if (RegisteredKeys == null || RegisteredKeys.Contains(key))
            {
                EventHandler<GlobalKeyboardHookEventArgs> handler = KeyboardPressed;
                handler?.Invoke(this, eventArguments);

                fEatKeyStroke = eventArguments.Handled;
            }
        }

        return fEatKeyStroke ? (IntPtr)1 : CallNextHookEx(IntPtr.Zero, nCode, wParam, lParam);
    }
}

The Usage differences can be seen here

public partial class Form1 : Form
{
    public Form1()
    {
        InitializeComponent();
    }

    private GlobalKeyboardHook _globalKeyboardHook;

    private void buttonHook_Click(object sender, EventArgs e)
    {
        // Hooks only into specified Keys (here "A" and "B").
        _globalKeyboardHook = new GlobalKeyboardHook(new Keys[] { Keys.A, Keys.B });

        // Hooks into all keys.
        _globalKeyboardHook = new GlobalKeyboardHook();
        _globalKeyboardHook.KeyboardPressed += OnKeyPressed;
    }

    private void OnKeyPressed(object sender, GlobalKeyboardHookEventArgs e)
    {
        // EDT: No need to filter for VkSnapshot anymore. This now gets handled
        // through the constructor of GlobalKeyboardHook(...).
        if (e.KeyboardState == GlobalKeyboardHook.KeyboardState.KeyDown)
        {
            // Now you can access both, the key and virtual code
            Keys loggedKey = e.KeyboardData.Key;
            int loggedVkCode = e.KeyboardData.VirtualCode;
        }
    }
}

Thanks to Siarhei Kuchuk for his post. Even tho I've simplified the usage this initial code was very useful for me.

UIWebView open links in Safari

The accepted answer does not work.

If your page loads URLs via Javascript, the navigationType will be UIWebViewNavigationTypeOther. Which, unfortunately, also includes background page loads such as analytics.

To detect page navigation, you need to compare the [request URL] to the [request mainDocumentURL].

This solution will work in all cases:

- (BOOL)webView:(UIWebView *)view shouldStartLoadWithRequest:(NSURLRequest *)request navigationType:(UIWebViewNavigationType)type
{
    if ([[request URL] isEqual:[request mainDocumentURL]])
    {
        [[UIApplication sharedApplication] openURL:[request URL]];
        return NO;
    }
    else
    {       
        return YES;
    }
}

Writing new lines to a text file in PowerShell

It's also possible to assign newline and carriage return to variables and then append them to texts inside PowerShell scripts:

$OFS = "`r`n"
$msg = "This is First Line" + $OFS + "This is Second Line" + $OFS
Write-Host $msg

C error: undefined reference to function, but it IS defined

How are you doing the compiling and linking? You'll need to specify both files, something like:

gcc testpoint.c point.c

...so that it knows to link the functions from both together. With the code as it's written right now, however, you'll then run into the opposite problem: multiple definitions of main. You'll need/want to eliminate one (undoubtedly the one in point.c).

In a larger program, you typically compile and link separately to avoid re-compiling anything that hasn't changed. You normally specify what needs to be done via a makefile, and use make to do the work. In this case you'd have something like this:

OBJS=testpoint.o point.o

testpoint.exe: $(OBJS)
    gcc $(OJBS)

The first is just a macro for the names of the object files. You get it expanded with $(OBJS). The second is a rule to tell make 1) that the executable depends on the object files, and 2) telling it how to create the executable when/if it's out of date compared to an object file.

Most versions of make (including the one in MinGW I'm pretty sure) have a built-in "implicit rule" to tell them how to create an object file from a C source file. It normally looks roughly like this:

.c.o:
    $(CC) -c $(CFLAGS) $<

This assumes the name of the C compiler is in a macro named CC (implicitly defined like CC=gcc) and allows you to specify any flags you care about in a macro named CFLAGS (e.g., CFLAGS=-O3 to turn on optimization) and $< is a special macro that expands to the name of the source file.

You typically store this in a file named Makefile, and to build your program, you just type make at the command line. It implicitly looks for a file named Makefile, and runs whatever rules it contains.

The good point of this is that make automatically looks at the timestamps on the files, so it will only re-compile the files that have changed since the last time you compiled them (i.e., files where the ".c" file has a more recent time-stamp than the matching ".o" file).

Also note that 1) there are lots of variations in how to use make when it comes to large projects, and 2) there are also lots of alternatives to make. I've only hit on the bare minimum of high points here.

How to draw a standard normal distribution in R

By the way, instead of generating the x and y coordinates yourself, you can also use the curve() function, which is intended to draw curves corresponding to a function (such as the density of a standard normal function).

see

help(curve)

and its examples.

And if you want to add som text to properly label the mean and standard deviations, you can use the text() function (see also plotmath, for annotations with mathematical symbols) .

see

help(text)
help(plotmath)

Template not provided using create-react-app

Try running your terminal as an administrator. I was having the same issue and nothing helped apart from opening the terminal as administrator and then doing the npx create-react-app yourAppName

Reading a single char in Java

You can use a Scanner for this. It's not clear what your exact requirements are, but here's an example that should be illustrative:

    Scanner sc = new Scanner(System.in).useDelimiter("\\s*");
    while (!sc.hasNext("z")) {
        char ch = sc.next().charAt(0);
        System.out.print("[" + ch + "] ");
    }

If you give this input:

123 a b c x   y   z

The output is:

[1] [2] [3] [a] [b] [c] [x] [y] 

So what happens here is that the Scanner uses \s* as delimiter, which is the regex for "zero or more whitespace characters". This skips spaces etc in the input, so you only get non-whitespace characters, one at a time.

How to execute IN() SQL queries with Spring's JDBCTemplate effectively?

You want a parameter source:

Set<Integer> ids = ...;

MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("ids", ids);

List<Foo> foo = getJdbcTemplate().query("SELECT * FROM foo WHERE a IN (:ids)",
     parameters, getRowMapper());

This only works if getJdbcTemplate() returns an instance of type NamedParameterJdbcTemplate

Attempt to present UIViewController on UIViewController whose view is not in the window hierarchy

The message appear as warning and sometimes the code refuses to work. (!Needs Citation: Newer SDK's might have strict rules).

I have encountered it for more than one reason, mostly complicated viewcontroller scenarios. Here's an example.

Scenario: MainViewController (responsible to load: ViewControllerA & ViewControllerB)

Present ViewControllerA from MainViewController and without dismissing the ViewControllerA you try to present viewControllerB from MainViewController (using a delegate method).

In this scenario, you'd have to make sure your ViewControllerA is dismissed and then the ViewControllerB is called.

Because after presenting ViewControllerA (ViewControllerA becomes responsible for displaying views and viewcontrollers and when MainViewController attempts to load another viewcontoller, it refuses to work with throwing a warning).

Scrolling to element using webdriver?

In addition to move_to_element() and scrollIntoView() I wanted to pose the following code which attempts to center the element in the view:

desired_y = (element.size['height'] / 2) + element.location['y']
window_h = driver.execute_script('return window.innerHeight')
window_y = driver.execute_script('return window.pageYOffset')
current_y = (window_h / 2) + window_y
scroll_y_by = desired_y - current_y

driver.execute_script("window.scrollBy(0, arguments[0]);", scroll_y_by)

PHP Date Format to Month Name and Year

if you want same string output then try below else use without double quotes for proper output

$str = '20130814';
  echo date('"F Y"', strtotime($str));

//output  : "August 2013" 

How to convert an Object {} to an Array [] of key-value pairs in JavaScript

Use for in

var obj = { "10":5, "2":7, "3":0, "4":0, "5":0, "6":0, "7":0,
            "8":0, "9":0, "10":0, "11":0, "12":0 };

var objectToArray = function(obj) {
    var _arr = [];

    for (var key in obj) {
        _arr.push([key, obj[key]]);
    }
    return _arr;
}

console.log(objectToArray(obj));

How to read a file into vector in C++?

Just a piece of advice. Instead of writing

for (int i=0; i=((Main.size())-1); i++) {
   cout << Main[i] << '\n';
}

as suggested above, write a:

for (vector<double>::iterator it=Main.begin(); it!=Main.end(); it++) {
   cout << *it << '\n';
}

to use iterators. If you have C++11 support, you can declare i as auto i=Main.begin() (just a handy shortcut though)

This avoids the nasty one-position-out-of-bound error caused by leaving out a -1 unintentionally.

Angular2 Material Dialog css, dialog size

With current version of Angular Material (6.4.7) you can use a custom class:

let dialogRef = dialog.open(UserProfileComponent, {
  panelClass: 'my-class'
});

Now put your class somewhere global (haven't been able to make this work elsewhere), e.g. in styles.css:

.my-class .mat-dialog-container{
  height: 400px;
  width: 600px;
  border-radius: 10px;
  background: lightcyan;
  color: #039be5;
}

Done!

Multiline editing in Visual Studio Code

In Visual Studio Code just press Alt and place your cursor to the edit place(where you want to edit) and right click to select.

Writing List of Strings to Excel CSV File in Python

A sample - write multiple rows with boolean column (using example above by GaretJax and Eran?).

import csv
RESULT = [['IsBerry','FruitName'],
          [False,'apple'],
          [True, 'cherry'],
          [False,'orange'],
          [False,'pineapple'],
          [True, 'strawberry']]
with open("../datasets/dashdb.csv", 'wb') as resultFile:
    wr = csv.writer(resultFile, dialect='excel')
    wr.writerows(RESULT)

Result:

df_data_4 = pd.read_csv('../datasets/dashdb.csv')
df_data_4.head()

Output:

   IsBerry  FruitName
   0    False   apple
   1    True    cherry
   2    False   orange
   3    False   pineapple
   4    True    strawberry

How to find a string inside a entire database?

Here is an easy and convenient cursor based solution

DECLARE
@search_string  VARCHAR(100),
@table_name     SYSNAME,
@table_id       INT,
@column_name    SYSNAME,
@sql_string     VARCHAR(2000)

SET @search_string = 'StringtoSearch'

DECLARE tables_cur CURSOR FOR SELECT name, object_id FROM sys.objects WHERE  type = 'U'

OPEN tables_cur

FETCH NEXT FROM tables_cur INTO @table_name, @table_id

WHILE (@@FETCH_STATUS = 0)
BEGIN
    DECLARE columns_cur CURSOR FOR SELECT name FROM sys.columns WHERE object_id = @table_id 
        AND system_type_id IN (167, 175, 231, 239)

    OPEN columns_cur

    FETCH NEXT FROM columns_cur INTO @column_name
        WHILE (@@FETCH_STATUS = 0)
        BEGIN
            SET @sql_string = 'IF EXISTS (SELECT * FROM ' + @table_name + ' WHERE [' + @column_name + '] 
            LIKE ''%' + @search_string + '%'') PRINT ''' + @table_name + ', ' + @column_name + ''''

            EXECUTE(@sql_string)

        FETCH NEXT FROM columns_cur INTO @column_name
        END

    CLOSE columns_cur

DEALLOCATE columns_cur

FETCH NEXT FROM tables_cur INTO @table_name, @table_id
END

CLOSE tables_cur
DEALLOCATE tables_cur

Div with margin-left and width:100% overflowing on the right side

Add some css either in the head or in a external document. asp:TextBox are rendered as input :

input {
     width:100%;
}

Your html should look like : http://jsfiddle.net/c5WXA/

Note this will affect all your textbox : if you don't want this, give the containing div a class and specify the css.

.divClass input {
     width:100%;
}

Converting string "true" / "false" to boolean value

If you're using the variable result:

result = result == "true";

What does the exclamation mark do before the function?

JavaScript syntax 101. Here is a function declaration:

function foo() {}

Note that there's no semicolon: this is just a function declaration. You would need an invocation, foo(), to actually run the function.

Now, when we add the seemingly innocuous exclamation mark: !function foo() {} it turns it into an expression. It is now a function expression.

The ! alone doesn't invoke the function, of course, but we can now put () at the end: !function foo() {}() which has higher precedence than ! and instantly calls the function.

So what the author is doing is saving a byte per function expression; a more readable way of writing it would be this:

(function(){})();

Lastly, ! makes the expression return true. This is because by default all immediately invoked function expressions (IIFE) return undefined, which leaves us with !undefined which is true. Not particularly useful.