Programs & Examples On #Editline

Elevating process privilege programmatically?

[PrincipalPermission(SecurityAction.Demand, Role = @"BUILTIN\Administrators")]

This will do it without UAC - no need to start a new process. If the running user is member of Admin group as for my case.

React-router: How to manually invoke Link?

React Router v5 - React 16.8+ with Hooks (updated 09/23/2020)

If you're leveraging React Hooks, you can take advantage of the useHistory API that comes from React Router v5.

import React, {useCallback} from 'react';
import {useHistory} from 'react-router-dom';

export default function StackOverflowExample() {
  const history = useHistory();
  const handleOnClick = useCallback(() => history.push('/sample'), [history]);

  return (
    <button type="button" onClick={handleOnClick}>
      Go home
    </button>
  );
}

Another way to write the click handler if you don't want to use useCallback

const handleOnClick = () => history.push('/sample');

React Router v4 - Redirect Component

The v4 recommended way is to allow your render method to catch a redirect. Use state or props to determine if the redirect component needs to be shown (which then trigger's a redirect).

import { Redirect } from 'react-router';

// ... your class implementation

handleOnClick = () => {
  // some action...
  // then redirect
  this.setState({redirect: true});
}

render() {
  if (this.state.redirect) {
    return <Redirect push to="/sample" />;
  }

  return <button onClick={this.handleOnClick} type="button">Button</button>;
}

Reference: https://reacttraining.com/react-router/web/api/Redirect

React Router v4 - Reference Router Context

You can also take advantage of Router's context that's exposed to the React component.

static contextTypes = {
  router: PropTypes.shape({
    history: PropTypes.shape({
      push: PropTypes.func.isRequired,
      replace: PropTypes.func.isRequired
    }).isRequired,
    staticContext: PropTypes.object
  }).isRequired
};

handleOnClick = () => {
  this.context.router.push('/sample');
}

This is how <Redirect /> works under the hood.

Reference: https://github.com/ReactTraining/react-router/blob/master/packages/react-router/modules/Redirect.js#L46,L60

React Router v4 - Externally Mutate History Object

If you still need to do something similar to v2's implementation, you can create a copy of BrowserRouter then expose the history as an exportable constant. Below is a basic example but you can compose it to inject it with customizable props if needed. There are noted caveats with lifecycles, but it should always rerender the Router, just like in v2. This can be useful for redirects after an API request from an action function.

// browser router file...
import createHistory from 'history/createBrowserHistory';
import { Router } from 'react-router';

export const history = createHistory();

export default class BrowserRouter extends Component {
  render() {
    return <Router history={history} children={this.props.children} />
  }
}

// your main file...
import BrowserRouter from './relative/path/to/BrowserRouter';
import { render } from 'react-dom';

render(
  <BrowserRouter>
    <App/>
  </BrowserRouter>
);

// some file... where you don't have React instance references
import { history } from './relative/path/to/BrowserRouter';

history.push('/sample');

Latest BrowserRouter to extend: https://github.com/ReactTraining/react-router/blob/master/packages/react-router-dom/modules/BrowserRouter.js

React Router v2

Push a new state to the browserHistory instance:

import {browserHistory} from 'react-router';
// ...
browserHistory.push('/sample');

Reference: https://github.com/reactjs/react-router/blob/master/docs/guides/NavigatingOutsideOfComponents.md

Why do you create a View in a database?

The one major advantage of a view over a stored procedure is that you can use a view just like you use a table. Namely, a view can be referred to directly in the FROM clause of a query. E.g., SELECT * FROM dbo.name_of_view.

In just about every other way, stored procedures are more powerful. You can pass in parameters, including out parameters that allow you effectively to return several values at once, you can do SELECT, INSERT, UPDATE, and DELETE operations, etc. etc.

If you want a View's ability to query from within the FROM clause, but you also want to be able to pass in parameters, there's a way to do that too. It's called a table-valued function.

Here's a pretty useful article on the topic:

http://databases.aspfaq.com/database/should-i-use-a-view-a-stored-procedure-or-a-user-defined-function.html

EDIT: By the way, this sort of raises the question, what advantage does a view have over a table-valued function? I don't have a really good answer to that, but I will note that the T-SQL syntax for creating a view is simpler than for a table-valued function, and users of your database may be more familiar with views.

How can I view a git log of just one user's commits?

Show n number of logs for x user in colour by adding this little snippet in your .bashrc file.

gitlog() {
    if [ "$1" ] && [ "$2" ]; then
       git log --pretty=format:"%h%x09 %C(cyan)%an%x09 %Creset%ad%x09 %Cgreen%s" --date-order -n "$1" --author="$2"
    elif [ "$1" ]; then
       git log --pretty=format:"%h%x09 %C(cyan)%an%x09 %Creset%ad%x09 %Cgreen%s" --date-order -n "$1"
    else
        git log --pretty=format:"%h%x09 %C(cyan)%an%x09 %Creset%ad%x09 %Cgreen%s" --date-order
    fi
}

alias l=gitlog

To show the last 10 commits by Frank:

l 10 frank

To show the last 20 commits by anyone:

l 20

On Duplicate Key Update same as insert

The UPDATE statement is given so that older fields can be updated to new value. If your older values are the same as your new ones, why would you need to update it in any case?

For eg. if your columns a to g are already set as 2 to 8; there would be no need to re-update it.

Alternatively, you can use:

INSERT INTO table (id,a,b,c,d,e,f,g)
VALUES (1,2,3,4,5,6,7,8) 
ON DUPLICATE KEY
    UPDATE a=a, b=b, c=c, d=d, e=e, f=f, g=g;

To get the id from LAST_INSERT_ID; you need to specify the backend app you're using for the same.

For LuaSQL, a conn:getlastautoid() fetches the value.

What is the difference between single and double quotes in SQL?

In ANSI SQL, double quotes quote object names (e.g. tables) which allows them to contain characters not otherwise permitted, or be the same as reserved words (Avoid this, really).

Single quotes are for strings.

However, MySQL is oblivious to the standard (unless its SQL_MODE is changed) and allows them to be used interchangably for strings.

Moreover, Sybase and Microsoft also use square brackets for identifier quoting.

So it's a bit vendor specific.

Other databases such as Postgres and IBM actually adhere to the ansi standard :)

git add, commit and push commands in one?

I did this .sh script for command

#!/bin/sh
cd LOCALDIRECTORYNAME/  
git config --global user.email "YOURMAILADDRESS"
git config --global user.name "YOURUSERNAME"
git init
git status
git add -A && git commit -m "MASSAGEFORCOMMITS"
git push origin master

Declare and initialize a Dictionary in Typescript

Typescript fails in your case because it expects all the fields to be present. Use Record and Partial utility types to solve it.

Record<string, Partial<IPerson>>

interface IPerson {
   firstName: string;
   lastName: string;
}

var persons: Record<string, Partial<IPerson>> = {
   "p1": { firstName: "F1", lastName: "L1" },
   "p2": { firstName: "F2" }
};

Explanation.

  1. Record type creates a dictionary/hashmap.
  2. Partial type says some of the fields may be missing.

Alternate.

If you wish to make last name optional you can append a ? Typescript will know that it's optional.

lastName?: string;

https://www.typescriptlang.org/docs/handbook/utility-types.html

Iterating Through a Dictionary in Swift

Here is an alternative for that experiment (Swift 3.0). This tells you exactly which kind of number was the largest.

let interestingNumbers = [
"Prime": [2, 3, 5, 7, 11, 13],
"Fibonacci": [1, 1, 2, 3, 5, 8],
"Square": [1, 4, 9, 16, 25],
]

var largest = 0
var whichKind: String? = nil

for (kind, numbers) in interestingNumbers {
    for number in numbers {
    if number > largest {
        whichKind = kind
        largest = number
    }
  }
}

print(whichKind)
print(largest)

OUTPUT:
Optional("Square")
25

ImportError: No module named site on Windows

I had the same problem. My solution was to repair the Python installation. (It was a new installation so I did not expect a problem but now it is solved.)

To repair (Windows 7):

  1. go to Control Panel -> Programs -> Programs and Features
  2. click on the Python version installed and then press Uninstall/Change.
  3. follow the instructions to repair the installation.

MAX(DATE) - SQL ORACLE

select * from 
  (SELECT MEMBSHIP_ID
   FROM user_payment WHERE user_id=1
   order by paym_date desc) 
where rownum=1;

excel - if cell is not blank, then do IF statement

Your formula is wrong. You probably meant something like:

=IF(AND(NOT(ISBLANK(Q2));NOT(ISBLANK(R2)));IF(Q2<=R2;"1";"0");"")

Another equivalent:

=IF(NOT(OR(ISBLANK(Q2);ISBLANK(R2)));IF(Q2<=R2;"1";"0");"")

Or even shorter:

=IF(OR(ISBLANK(Q2);ISBLANK(R2));"";IF(Q2<=R2;"1";"0"))

OR EVEN SHORTER:

=IF(OR(ISBLANK(Q2);ISBLANK(R2));"";--(Q2<=R2))

Import error: No module name urllib2

Some tab completions to show the contents of the packages in Python 2 vs Python 3.

In Python 2:

In [1]: import urllib

In [2]: urllib.
urllib.ContentTooShortError      urllib.ftpwrapper                urllib.socket                    urllib.test1
urllib.FancyURLopener            urllib.getproxies                urllib.splitattr                 urllib.thishost
urllib.MAXFTPCACHE               urllib.getproxies_environment    urllib.splithost                 urllib.time
urllib.URLopener                 urllib.i                         urllib.splitnport                urllib.toBytes
urllib.addbase                   urllib.localhost                 urllib.splitpasswd               urllib.unquote
urllib.addclosehook              urllib.noheaders                 urllib.splitport                 urllib.unquote_plus
urllib.addinfo                   urllib.os                        urllib.splitquery                urllib.unwrap
urllib.addinfourl                urllib.pathname2url              urllib.splittag                  urllib.url2pathname
urllib.always_safe               urllib.proxy_bypass              urllib.splittype                 urllib.urlcleanup
urllib.base64                    urllib.proxy_bypass_environment  urllib.splituser                 urllib.urlencode
urllib.basejoin                  urllib.quote                     urllib.splitvalue                urllib.urlopen
urllib.c                         urllib.quote_plus                urllib.ssl                       urllib.urlretrieve
urllib.ftpcache                  urllib.re                        urllib.string                    
urllib.ftperrors                 urllib.reporthook                urllib.sys  

In Python 3:

In [2]: import urllib.
urllib.error        urllib.parse        urllib.request      urllib.response     urllib.robotparser

In [2]: import urllib.error.
urllib.error.ContentTooShortError  urllib.error.HTTPError             urllib.error.URLError

In [2]: import urllib.parse.
urllib.parse.parse_qs          urllib.parse.quote_plus        urllib.parse.urldefrag         urllib.parse.urlsplit
urllib.parse.parse_qsl         urllib.parse.unquote           urllib.parse.urlencode         urllib.parse.urlunparse
urllib.parse.quote             urllib.parse.unquote_plus      urllib.parse.urljoin           urllib.parse.urlunsplit
urllib.parse.quote_from_bytes  urllib.parse.unquote_to_bytes  urllib.parse.urlparse

In [2]: import urllib.request.
urllib.request.AbstractBasicAuthHandler         urllib.request.HTTPSHandler
urllib.request.AbstractDigestAuthHandler        urllib.request.OpenerDirector
urllib.request.BaseHandler                      urllib.request.ProxyBasicAuthHandler
urllib.request.CacheFTPHandler                  urllib.request.ProxyDigestAuthHandler
urllib.request.DataHandler                      urllib.request.ProxyHandler
urllib.request.FTPHandler                       urllib.request.Request
urllib.request.FancyURLopener                   urllib.request.URLopener
urllib.request.FileHandler                      urllib.request.UnknownHandler
urllib.request.HTTPBasicAuthHandler             urllib.request.build_opener
urllib.request.HTTPCookieProcessor              urllib.request.getproxies
urllib.request.HTTPDefaultErrorHandler          urllib.request.install_opener
urllib.request.HTTPDigestAuthHandler            urllib.request.pathname2url
urllib.request.HTTPErrorProcessor               urllib.request.url2pathname
urllib.request.HTTPHandler                      urllib.request.urlcleanup
urllib.request.HTTPPasswordMgr                  urllib.request.urlopen
urllib.request.HTTPPasswordMgrWithDefaultRealm  urllib.request.urlretrieve
urllib.request.HTTPRedirectHandler     


In [2]: import urllib.response.
urllib.response.addbase       urllib.response.addclosehook  urllib.response.addinfo       urllib.response.addinfourl

Github: Can I see the number of downloads for a repo?

I have written a small web application in javascript for showing count of the number of downloads of all the assets in the available releases of any project on Github. You can try out the application over here: http://somsubhra.github.io/github-release-stats/

Using Jquery AJAX function with datatype HTML

Here is a version that uses dataType html, but this is far less explicit, because i am returning an empty string to indicate an error.

Ajax call:

$.ajax({
  type : 'POST',
  url : 'post.php',
  dataType : 'html',
  data: {
      email : $('#email').val()
  },
  success : function(data){
      $('#waiting').hide(500);
      $('#message').removeClass().addClass((data == '') ? 'error' : 'success')
     .html(data).show(500);
      if (data == '') {
          $('#message').html("Format your email correcly");
          $('#demoForm').show(500);
      }
  },
  error : function(XMLHttpRequest, textStatus, errorThrown) {
      $('#waiting').hide(500);
      $('#message').removeClass().addClass('error')
      .text('There was an error.').show(500);
      $('#demoForm').show(500);
  }

});

post.php

<?php
sleep(1);

function processEmail($email) {
    if (preg_match("#^[a-zA-Z0-9_.-]+@[a-zA-Z0-9-]+.[a-zA-Z0-9-.]+$#", $email)) {
        // your logic here (ex: add into database)
        return true;
    }
    return false;
}

if (processEmail($_POST['email'])) {
    echo "<span>Your email is <strong>{$_POST['email']}</strong></span>";
}

Pass variables from servlet to jsp

If you are using Action, Actionforward way to process business logic and next page to show, check out if redirect is called. As many others pointed out, redirecting doesn't keep your original request since it is basically forcing you to make a new request to designated path. So the value set in original request will be vanished if you use redirection instead of requestdispatch.

How to sort a collection by date in MongoDB?

if your date format is like this : 14/02/1989 ----> you may find some problems

you need to use ISOdate like this :

var start_date = new Date(2012, 07, x, x, x); 

-----> the result ------>ISODate("2012-07-14T08:14:00.201Z")

now just use the query like this :

 collection.find( { query : query ,$orderby :{start_date : -1}} ,function (err, cursor) {...}

that's it :)

AltGr key not working, instead I have to use Ctrl+AltGr

I found a solution for my problem while writing my question !

Going into my remote session i tried two key combinations, and it solved the problem on my Desktop : Alt+Enter and Ctrl+Enter (i don't know which one solved the problem though)

I tried to reproduce the problem, but i couldn't... but i'm almost sure it's one of the key combinations described in the question above (since i experienced this problem several times)

So it seems the problem comes from the use of RDP (windows7 and 8)

Update 2017: Problem occurs on Windows 10 aswell.

Best way to import Observable from rxjs

One thing I've learnt the hard way is being consistent

Watch out for mixing:

 import { BehaviorSubject } from "rxjs";

with

 import { BehaviorSubject } from "rxjs/BehaviorSubject";

This will probably work just fine UNTIL you try to pass the object to another class (where you did it the other way) and then this can fail

 (myBehaviorSubject instanceof Observable)

It fails because the prototype chain will be different and it will be false.

I can't pretend to understand exactly what is happening but sometimes I run into this and need to change to the longer format.

Read Post Data submitted to ASP.Net Form

Read the Request.Form NameValueCollection and process your logic accordingly:

NameValueCollection nvc = Request.Form;
string userName, password;
if (!string.IsNullOrEmpty(nvc["txtUserName"]))
{
  userName = nvc["txtUserName"];
}

if (!string.IsNullOrEmpty(nvc["txtPassword"]))
{
  password = nvc["txtPassword"];
}

//Process login
CheckLogin(userName, password);

... where "txtUserName" and "txtPassword" are the Names of the controls on the posting page.

Extracting jar to specified directory

Current working version as of Oct 2020, updated to use maven-antrun-plugin 3.0.0.

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-antrun-plugin</artifactId>
            <version>3.0.0</version>
            <executions>
                <execution>
                    <id>prepare</id>
                    <phase>package</phase>
                    <configuration>
                        <target>
                            <unzip src="target/shaded-jar/shade-test.jar"
                                   dest="target/unpacked-shade/"/>
                        </target>
                    </configuration>
                    <goals>
                        <goal>run</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>

Making text background transparent but not text itself

box-shadow: inset 1px 2000px rgba(208, 208, 208, 0.54);

jquery Ajax call - data parameters are not being passed to MVC Controller action

I tried:

<input id="btnTest" type="button" value="button" />

<script type="text/javascript">
    $(document).ready( function() {
      $('#btnTest').click( function() {
        $.ajax({
          type: "POST", 
          url: "/Login/Test",
          data: { ListID: '1', ItemName: 'test' },
          dataType: "json",
          success: function(response) { alert(response); },
          error: function(xhr, ajaxOptions, thrownError) { alert(xhr.responseText); }
        });
      });
    });
</script>

and C#:

[HttpPost]
public ActionResult Test(string ListID, string ItemName)
{
    return Content(ListID + " " + ItemName);
}

It worked. Remove contentType and set data without double quotes.

How can I iterate over files in a given directory?

I really like using the scandir directive that is built into the os library. Here is a working example:

import os

i = 0
with os.scandir('/usr/local/bin') as root_dir:
    for path in root_dir:
        if path.is_file():
            i += 1
            print(f"Full path is: {path} and just the name is: {path.name}")
print(f"{i} files scanned successfully.")

add a temporary column with a value

select field1, field2, '' as newfield from table1

This Will Do you Job

Change status bar text color to light in iOS 9 with Objective-C

If you want to change Status Bar Style from the launch screen, You should take this way.

  1. Go to Project -> Target,

  2. Set Status Bar Style to Light Project Setting

  3. Set View controller-based status bar appearance to NO in Info.plist.

Cannot push to GitHub - keeps saying need merge

Have you updated your code before pushing?

Use git pull origin master before you push anything.

I assume that you are using origin as a name for your remote.

You need to pull before push, to make your local repository up-to-date before you push something (just in case someone else has already updated code on github.com). This helps in resolving conflicts locally.

.NET HashTable Vs Dictionary - Can the Dictionary be as fast?

I guess it doesn't mean anything to you now. But just for reference for people stopping by

Performance Test - SortedList vs. SortedDictionary vs. Dictionary vs. Hashtable

Memory allocation:

Memory usage performance test

Time used for inserting:

Time used for inserting

Time for searching an item:

Time for searching an item

How can I install packages using pip according to the requirements.txt file from a local directory?

Use:

pip install -r requirements.txt

For further details, please check the help option:

pip install --help

We can find the option '-r' -

-r, --requirement Install from the given requirements file. This option can be used multiple times.

Further information on some commonly used pip install options (this is the help option on the pip install command):

Enter image description here

Also the above is the complete set of options. Please use pip install --help for the complete list of options.

How to display svg icons(.svg files) in UI using React Component?

If your SVG includes sprites, here's a component you can use. We have three or four groups of sprites... obviously you can pull that bit out if you only have one sprite file.

The Sprite component:

import React from 'react'
import PropTypes from 'prop-types';

export default class Sprite extends React.Component {
  static propTypes = {
    label: PropTypes.string,
    group: PropTypes.string,
    sprite: PropTypes.string.isRequired
  }

  filepath(spriteGroup)
  {
    if(spriteGroup == undefined) {  spriteGroup = 'base' }
    return "/asset_path/sprite_" + spriteGroup + ".svg";
  }

  render()
  {
    return(
      <svg aria-hidden="true" title={this.props.label}>
        <use xlinkHref={`${this.filepath(this.props.group)}#${this.props.sprite}`}></use>
      </svg>
    )
  }
}

And elsewhere in React you would:

import Sprite from './Sprite';

render()
{
   ...
   <Sprite label="No Current Value" group='base' sprite='clock' />
}

Example from our 'base' sprite file, sprite_base.svg:

<svg xmlns="http://www.w3.org/2000/svg">
  <defs>
    <symbol id="clock" viewBox="0 0 512 512">
      <path fill="currentColor" d="M256 8C119 8 8 119 8 256s111 248 248 248 248-111 248-248S393 8 256 8zm216 248c0 118.7-96.1 216-216 216-118.7 0-216-96.1-216-216 0-118.7 96.1-216 216-216 118.7 0 216 96.1 216 216zm-148.9 88.3l-81.2-59c-3.1-2.3-4.9-5.9-4.9-9.7V116c0-6.6 5.4-12 12-12h14c6.6 0 12 5.4 12 12v146.3l70.5 51.3c5.4 3.9 6.5 11.4 2.6 16.8l-8.2 11.3c-3.9 5.3-11.4 6.5-16.8 2.6z" class="">
      </path>
    </symbol>
    <symbol id="arrow-up" viewBox="0 0 16 16">
      <polygon points="1.3,6.7 2.7,8.1 7,3.8 7,16 9,16 9,3.8 13.3,8.1 14.7,6.7 8,0 "> </polygon>
    </symbol>
    <symbol id="arrow-down" viewBox="0 0 16 16">
      <polygon points="14.7,9.3 13.3,7.9 9,12.2 9,0 7,0 7,12.2 2.7,7.9 1.3,9.3 8,16 "> </polygon>
    </symbol>
    <symbol id="download" viewBox="0 0 48 48">
      <line data-cap="butt" fill="none" stroke-width="3" stroke-miterlimit="10" x1="24" y1="3" x2="24" y2="36" stroke-linejoin="miter" stroke-linecap="butt"></line>
      <polyline fill="none" stroke-width="3" stroke-linecap="square" stroke-miterlimit="10" points="11,23 24,36 37,23 " stroke-linejoin="miter"></polyline>
      <line data-color="color-2" fill="none" stroke-width="3" stroke-linecap="square" stroke-miterlimit="10" x1="2" y1="45" x2="46" y2="45" stroke-linejoin="miter"></line>
    </symbol>
  </devs>
</svg>

Convert columns to string in Pandas

Here's the other one, particularly useful to convert the multiple columns to string instead of just single column:

In [76]: import numpy as np
In [77]: import pandas as pd
In [78]: df = pd.DataFrame({
    ...:     'A': [20, 30.0, np.nan],
    ...:     'B': ["a45a", "a3", "b1"],
    ...:     'C': [10, 5, np.nan]})
    ...: 

In [79]: df.dtypes ## Current datatype
Out[79]: 
A    float64
B     object
C    float64
dtype: object

## Multiple columns string conversion
In [80]: df[["A", "C"]] = df[["A", "C"]].astype(str) 

In [81]: df.dtypes ## Updated datatype after string conversion
Out[81]: 
A    object
B    object
C    object
dtype: object

Abstract methods in Python

You can use six and abc to construct a class for both python2 and python3 efficiently as follows:

import six
import abc

@six.add_metaclass(abc.ABCMeta)
class MyClass(object):
    """
    documentation
    """

    @abc.abstractmethod
    def initialize(self, para=None):
        """
        documentation
        """
        raise NotImplementedError

This is an awesome document of it.

Validate IPv4 address in Java

Please see https://stackoverflow.com/a/5668971/1586965 which uses an apache commons library InetAddressValidator

Or you can use this function -

public static boolean validate(final String ip) {
    String PATTERN = "^((0|1\\d?\\d?|2[0-4]?\\d?|25[0-5]?|[3-9]\\d?)\\.){3}(0|1\\d?\\d?|2[0-4]?\\d?|25[0-5]?|[3-9]\\d?)$";

    return ip.matches(PATTERN);
}

Express.js: how to get remote client address

If you are fine using 3rd-party library. You can check request-ip.

You can use it is by

import requestIp from 'request-ip';

app.use(requestIp.mw())

app.use((req, res) => {
  const ip = req.clientIp;
});

The source code is quite long, so I won't copy here, you can check at https://github.com/pbojinov/request-ip/blob/master/src/index.js

Basically,

It looks for specific headers in the request and falls back to some defaults if they do not exist.

The user ip is determined by the following order:

  1. X-Client-IP
  2. X-Forwarded-For (Header may return multiple IP addresses in the format: "client IP, proxy 1 IP, proxy 2 IP", so we take the the first one.)
  3. CF-Connecting-IP (Cloudflare)
  4. Fastly-Client-Ip (Fastly CDN and Firebase hosting header when forwared to a cloud function)
  5. True-Client-Ip (Akamai and Cloudflare)
  6. X-Real-IP (Nginx proxy/FastCGI)
  7. X-Cluster-Client-IP (Rackspace LB, Riverbed Stingray)
  8. X-Forwarded, Forwarded-For and Forwarded (Variations of #2)
  9. req.connection.remoteAddress
  10. req.socket.remoteAddress
  11. req.connection.socket.remoteAddress
  12. req.info.remoteAddress

If an IP address cannot be found, it will return null.

Disclose: I am not associated with the library.

Capitalize words in string

Using JavaScript and html

_x000D_
_x000D_
String.prototype.capitalize = function() {_x000D_
  return this.replace(/(^|\s)([a-z])/g, function(m, p1, p2) {_x000D_
    return p1 + p2.toUpperCase();_x000D_
  });_x000D_
};
_x000D_
<form name="form1" method="post">_x000D_
  <input name="instring" type="text" value="this is the text string" size="30">_x000D_
  <input type="button" name="Capitalize" value="Capitalize >>" onclick="form1.outstring.value=form1.instring.value.capitalize();">_x000D_
  <input name="outstring" type="text" value="" size="30">_x000D_
</form>
_x000D_
_x000D_
_x000D_

Basically, you can do string.capitalize() and it'll capitalize every 1st letter of each word.

Source: http://www.mediacollege.com/internet/javascript/text/case-capitalize.html

Download file through an ajax call php

@joe : Many thanks, this was a good heads up!

I had a slightly harder problem: 1. sending an AJAX request with POST data, for the server to produce a ZIP file 2. getting a response back 3. download the ZIP file

So that's how I did it (using JQuery to handle the AJAX request):

  1. Initial post request:

    var parameters = {
         pid     : "mypid",
       "files[]": ["file1.jpg","file2.jpg","file3.jpg"]
    }

    var options = { url: "request/url",//replace with your request url type: "POST",//replace with your request type data: parameters,//see above context: document.body,//replace with your contex success: function(data){ if (data) { if (data.path) { //Create an hidden iframe, with the 'src' attribute set to the created ZIP file. var dlif = $('<iframe/>',{'src':data.path}).hide(); //Append the iFrame to the context this.append(dlif); } else if (data.error) { alert(data.error); } else { alert('Something went wrong'); } } } }; $.ajax(options);

The "request/url" handles the zip creation (off topic, so I wont post the full code) and returns the following JSON object. Something like:

 //Code to create the zip file
 //......
 //Id of the file
 $zipid = "myzipfile.zip"
 //Download Link - it can be prettier
 $dlink = 'http://'.$_SERVER["SERVER_NAME"].'/request/download&file='.$zipid;
 //JSON response to be handled on the client side
 $result = '{"success":1,"path":"'.$dlink.'","error":null}';
 header('Content-type: application/json;');
 echo $result;

The "request/download" can perform some security checks, if needed, and generate the file transfer:

$fn = $_GET['file'];
if ($fn) {
  //Perform security checks
  //.....check user session/role/whatever
  $result = $_SERVER['DOCUMENT_ROOT'].'/path/to/file/'.$fn;
  if (file_exists($result)) {
    header('Content-Description: File Transfer');
    header('Content-Type: application/force-download');
    header('Content-Disposition: attachment; filename='.basename($result));
    header('Content-Transfer-Encoding: binary');
    header('Expires: 0');
    header('Cache-Control: must-revalidate, post-check=0, pre-check=0');
    header('Pragma: public');
    header('Content-Length: ' . filesize($result));
    ob_clean();
    flush();
    readfile($result);
    @unlink($result);
  }

}

How to run multiple sites on one apache instance

Your question is mixing a few different concepts. You started out saying you wanted to run sites on the same server using the same domain, but in different folders. That doesn't require any special setup. Once you get the single domain running, you just create folders under that docroot.

Based on the rest of your question, what you really want to do is run various sites on the same server with their own domain names.

The best documentation you'll find on the topic is the virtual host documentation in the apache manual.

There are two types of virtual hosts: name-based and IP-based. Name-based allows you to use a single IP address, while IP-based requires a different IP for each site. Based on your description above, you want to use name-based virtual hosts.

The initial error you were getting was due to the fact that you were using different ports than the NameVirtualHost line. If you really want to have sites served from ports other than 80, you'll need to have a NameVirtualHost entry for each port.

Assuming you're starting from scratch, this is much simpler than it may seem.

If you are using 2.3 or earlier, the first thing you need to do is tell Apache that you're going to use name-based virtual hosts.

NameVirtualHost *:80

If you are using 2.4 or later do not add a NameVirtualHost line. Version 2.4 of Apache deprecated the NameVirtualHost directive, and it will be removed in a future version.

Now your vhost definitions:

<VirtualHost *:80>
    DocumentRoot "/home/user/site1/"
    ServerName site1
</VirtualHost>

<VirtualHost *:80>
    DocumentRoot "/home/user/site2/"
    ServerName site2
</VirtualHost>

You can run as many sites as you want on the same port. The ServerName being different is enough to tell Apache which vhost to use. Also, the ServerName directive is always the domain/hostname and should never include a path.

If you decide to run sites on a port other than 80, you'll always have to include the port number in the URL when accessing the site. So instead of going to http://example.com you would have to go to http://example.com:81

YouTube iframe API: how do I control an iframe player that's already in the HTML?

Looks like YouTube has updated their JS API so this is available by default! You can use an existing YouTube iframe's ID...

<iframe id="player" src="http://www.youtube.com/embed/M7lc1UVf-VE?enablejsapi=1&origin=http://example.com" frameborder="0"></iframe>

...in your JS...

var player;
function onYouTubeIframeAPIReady() {
  player = new YT.Player('player', {
    events: {
      'onStateChange': onPlayerStateChange
    }
  });
}

function onPlayerStateChange() {
  //...
}

...and the constructor will use your existing iframe instead of replacing it with a new one. This also means you don't have to specify the videoId to the constructor.

See Loading a video player

How to remove all white spaces in java

boolean flag = true;
while(flag) {
    s = s.replaceAll(" ", "");
    if (!s.contains(" "))
        flag = false;
}
return s;

how to bind img src in angular 2 in ngFor?

Angular 2 and Angular 4 

In a ngFor loop it must be look like this:

<div class="column" *ngFor="let u of events ">
                <div class="thumb">
                    <img src="assets/uploads/{{u.image}}">
                    <h4>{{u.name}}</h4>
                </div>
                <div class="info">
                    <img src="assets/uploads/{{u.image}}">
                    <h4>{{u.name}}</h4>
                    <p>{{u.text}}</p>
                </div>
            </div>

Table 'performance_schema.session_variables' doesn't exist

If, while using the mysql_upgrade -u root -p --force command You get this error:

Could not create the upgrade info file '/var/lib/mysql/mysql_upgrade_info' in the MySQL Servers datadir, errno: 13

just add the sudo before the command. That worked for me, and I solved my problem. So, it's: sudo mysql_upgrade -u root -p --force :)

How to pass parameter to click event in Jquery

 $('elements-to-match').click(function(){
        alert("The id is "+ this.id );
    });

no need to wrap it in a jquery object

Access denied for user 'root'@'localhost' (using password: YES) after new installation on Ubuntu

The new command to flush the privileges is:

FLUSH PRIVILEGES

The old command FLUSH ALL PRIVILEGES does not work any more.

You will get an error that looks like that:

MariaDB [(none)]> FLUSH ALL PRIVILEGES; ERROR 1064 (42000): You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'ALL PRIVILEGES' at line 1

Hope this helps :)

Adding an onclick event to a table row

Simple way is generating code as bellow:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
_x000D_
<style>_x000D_
  table, td {_x000D_
      border:1px solid black;_x000D_
  }_x000D_
</style>_x000D_
_x000D_
</head>_x000D_
<body>_x000D_
<p>Click on each tr element to alert its index position in the table:</p>_x000D_
<table>_x000D_
  <tr onclick="myFunction(this)">_x000D_
    <td>Click to show rowIndex</td>_x000D_
  </tr>_x000D_
  <tr onclick="myFunction(this)">_x000D_
    <td>Click to show rowIndex</td>_x000D_
  </tr>_x000D_
  <tr onclick="myFunction(this)">_x000D_
    <td>Click to show rowIndex</td>_x000D_
  </tr>_x000D_
</table>_x000D_
_x000D_
<script>_x000D_
  function myFunction(x) {_x000D_
      alert("Row index is: " + x.rowIndex);_x000D_
  }_x000D_
</script>_x000D_
_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How to implement band-pass Butterworth filter with Scipy.signal.butter

The filter design method in accepted answer is correct, but it has a flaw. SciPy bandpass filters designed with b, a are unstable and may result in erroneous filters at higher filter orders.

Instead, use sos (second-order sections) output of filter design.

from scipy.signal import butter, sosfilt, sosfreqz

def butter_bandpass(lowcut, highcut, fs, order=5):
        nyq = 0.5 * fs
        low = lowcut / nyq
        high = highcut / nyq
        sos = butter(order, [low, high], analog=False, btype='band', output='sos')
        return sos

def butter_bandpass_filter(data, lowcut, highcut, fs, order=5):
        sos = butter_bandpass(lowcut, highcut, fs, order=order)
        y = sosfilt(sos, data)
        return y

Also, you can plot frequency response by changing

b, a = butter_bandpass(lowcut, highcut, fs, order=order)
w, h = freqz(b, a, worN=2000)

to

sos = butter_bandpass(lowcut, highcut, fs, order=order)
w, h = sosfreqz(sos, worN=2000)

iterate through a map in javascript

The callback to $.each() is passed the property name and the value, in that order. You're therefore trying to iterate over the property names in the inner call to $.each(). I think you want:

$.each(myMap, function (i, val) {
  $.each(val, function(innerKey, innerValue) {
    // ...
  });
});

In the inner loop, given an object like your map, the values are arrays. That's OK, but note that the "innerKey" values will all be numbers.

edit — Now once that's straightened out, here's the next problem:

    setTimeout(function () {

      // ...

    }, i * 6000);

The first time through that loop, "i" will be the string "partnr1". Thus, that multiplication attempt will result in a NaN. You can keep an external counter to keep track of the property count of the outer map:

var pcount = 1;
$.each(myMap, function(i, val) {
  $.each(val, function(innerKey, innerValue) {
    setTimeout(function() {
      // ...
    }, pcount++ * 6000);
  });
});

What's the difference between implementation and compile in Gradle?

Gradle 3.0 introduced next changes:

  • compile -> api

    api keyword is the same as deprecated compile which expose this dependency for all levels

  • compile -> implementation

    Is preferable way because has some advantages. implementation expose dependency only for one level up at build time (the dependency is available at runtime). As a result you have a faster build(no need to recompile consumers which are higher then 1 level up)

  • provided -> compileOnly

    This dependency is available only in compile time(the dependency is not available at runtime). This dependency can not be transitive and be .aar. It can be used with compile time annotation processor and allows you to reduce a final output file

  • compile -> annotationProcessor

    Very similar to compileOnly but also guarantees that transitive dependency are not visible for consumer

  • apk -> runtimeOnly

    Dependency is not available in compile time but available at runtime.

[POM dependency type]

How to set java_home on Windows 7?

One Image can fix this issue. enter image description here

For More

Turn off constraints temporarily (MS SQL)

You can disable FK and CHECK constraints only in SQL 2005+. See ALTER TABLE

ALTER TABLE foo NOCHECK CONSTRAINT ALL

or

ALTER TABLE foo NOCHECK CONSTRAINT CK_foo_column

Primary keys and unique constraints can not be disabled, but this should be OK if I've understood you correctly.

CSS Pseudo-classes with inline styles

Not CSS, but inline:

<a href="#" 
   onmouseover = "this.style.textDecoration = 'none'"
   onmouseout  = "this.style.textDecoration = 'underline'">Hello</a>

See example →

How to set my default shell on Mac?

This work for me on fresh install of mac osx (sierra):

  1. Define current user as owner of shells
sudo chown $(whoami) /etc/shells
  1. Add Fish to /etc/shells
sudo echo /usr/local/bin/fish >> /etc/shells
  1. Make Fish your default shell with chsh
chsh -s /usr/local/bin/fish
  1. Redefine root as owner of shells
sudo chown root /etc/shells

iPhone - Grand Central Dispatch main thread

One place where it's useful is for UI activities, like setting a spinner before a lengthy operation:

- (void) handleDoSomethingButton{

    [mySpinner startAnimating];

    (do something lengthy)
    [mySpinner stopAnimating];
}

will not work, because you are blocking the main thread during your lengthy thing and not letting UIKit actually start the spinner.

- (void) handleDoSomethingButton{
     [mySpinner startAnimating];

     dispatch_async (dispatch_get_main_queue(), ^{
          (do something lengthy)
          [mySpinner stopAnimating];
    });
}

will return control to the run loop, which will schedule UI updating, starting the spinner, then will get the next thing off the dispatch queue, which is your actual processing. When your processing is done, the animation stop is called, and you return to the run loop, where the UI then gets updated with the stop.

HTML5 Canvas Resize (Downscale) Image High Quality?

If you wish to use canvas only, the best result will be with multiple downsteps. But that's not good enougth yet. For better quality you need pure js implementation. We just released pica - high speed downscaler with variable quality/speed. In short, it resizes 1280*1024px in ~0.1s, and 5000*3000px image in 1s, with highest quality (lanczos filter with 3 lobes). Pica has demo, where you can play with your images, quality levels, and even try it on mobile devices.

Pica does not have unsharp mask yet, but that will be added very soon. That's much more easy than implement high speed convolution filter for resize.

issue ORA-00001: unique constraint violated coming in INSERT/UPDATE

select the index then select the ones needed then select sql and click action then click rebuild

enter image description here

Disabling user input for UITextfield in swift

Another solution, declare your controller as UITextFieldDelegate, implement this call-back:

@IBOutlet weak var myTextField: UITextField!

override func viewDidLoad() {
    super.viewDidLoad()

    myTextField.delegate = self
}

func textFieldShouldBeginEditing(textField: UITextField) -> Bool {
    if textField == myTextField {
        return false; //do not show keyboard nor cursor
    }
    return true
}

How to use bluetooth to connect two iPhone?

Check out the BeamIt open source project. It will connect via bluetooth and WIFI (although it claims it does not do WIFI) and I have verified that it works well in my projects. It will allow peer to peer contact easily.

As for multiple connections, it is possible, but you will have to edit the BeamIt source code to make it possible. I suggest reading the GameKit programming guide

Convert hex string to int in Python

with '0x' prefix, you might also use eval function

For example

>>a='0xff'
>>eval(a)
255

LaTeX: remove blank page after a \part or \chapter

Although I guess you do not need an answer any longer, I am giving the solution for those who will come to see this post.

Derived from book.cls

\def\@endpart{\vfil\newpage
              \if@twoside
                \null
                \thispagestyle{empty}%
                \newpage
              \fi
              \if@tempswa
                \twocolumn
              \fi}

It is "\newpage" at the first line of this fragment that adds a redundant blank page after the part header page. So you must redefine the command \@endpart. Add the following snippet to the beggining of your tex file.

\makeatletter
\renewcommand\@endpart{\vfil
              \if@twoside
                \null
                \thispagestyle{empty}%
                \newpage
              \fi
              \if@tempswa
                \twocolumn
              \fi}
\makeatother

Javascript use variable as object name

Is it a global variable? If so, these are actually part of the window object, so you can do window[objname].value.

If it's local to a function, I don't think there's a good way to do what you want.

How do I debug Windows services in Visual Studio?

You should separate out all the code that will do stuff from the service project into a separate project, and then make a test application that you can run and debug normally.

The service project would be just the shell needed to implement the service part of it.

Full-screen responsive background image

By useing this code below :

.classname{
    background-image: url(images/paper.jpg);
    background-position: center;
    background-size: cover;
    background-repeat: no-repeat;
}

Hope it works. Thanks

ArrayList of String Arrays

private List<String[]> addresses = new ArrayList<String[]>();

this will work defenitely...

How to tell if a connection is dead in python

It depends on what you mean by "dropped". For TCP sockets, if the other end closes the connection either through close() or the process terminating, you'll find out by reading an end of file, or getting a read error, usually the errno being set to whatever 'connection reset by peer' is by your operating system. For python, you'll read a zero length string, or a socket.error will be thrown when you try to read or write from the socket.

Get the real width and height of an image with JavaScript? (in Safari/Chrome)

Another suggestion is to use imagesLoaded plugin.

$("img").imagesLoaded(function(){
alert( $(this).width() );
alert( $(this).height() );
});

Split String into an array of String

String[] result = "hi i'm paul".split("\\s+"); to split across one or more cases.

Or you could take a look at Apache Common StringUtils. It has StringUtils.split(String str) method that splits string using white space as delimiter. It also has other useful utility methods

Postman: How to make multiple requests at the same time

Not sure if people are still looking for simple solutions to this, but you are able to run multiple instances of the "Collection Runner" in Postman. Just create a runner with some requests and click the "Run" button multiple times to bring up multiple instances.

How to download image from url

Simply You can use following methods.

using (WebClient client = new WebClient()) 
{
    client.DownloadFile(new Uri(url), @"c:\temp\image35.png");
    // OR 
    client.DownloadFileAsync(new Uri(url), @"c:\temp\image35.png");
}

These methods are almost same as DownloadString(..) and DownloadStringAsync(...). They store the file in Directory rather than in C# string and no need of Format extension in URi

If You don't know the Format(.png, .jpeg etc) of Image

public void SaveImage(string filename, ImageFormat format)
{    
    WebClient client = new WebClient();
    Stream stream = client.OpenRead(imageUrl);
    Bitmap bitmap;  bitmap = new Bitmap(stream);

    if (bitmap != null)
    {
        bitmap.Save(filename, format);
    }

    stream.Flush();
    stream.Close();
    client.Dispose();
}

Using it

try
{
    SaveImage("--- Any Image Path ---", ImageFormat.Png)
}
catch(ExternalException)
{
    // Something is wrong with Format -- Maybe required Format is not 
    // applicable here
}
catch(ArgumentNullException)
{   
    // Something wrong with Stream
}

Under what conditions is a JSESSIONID created?

For links generated in a JSP with custom tags, I had to use

<%@ page session="false" %>

in the JSP

AND

request.getSession().invalidate();

in the Struts action

Reading file contents on the client-side in javascript in various browsers

In order to read a file chosen by the user, using a file open dialog, you can use the <input type="file"> tag. You can find information on it from MSDN. When the file is chosen you can use the FileReader API to read the contents.

_x000D_
_x000D_
function onFileLoad(elementId, event) {_x000D_
    document.getElementById(elementId).innerText = event.target.result;_x000D_
}_x000D_
_x000D_
function onChooseFile(event, onLoadFileHandler) {_x000D_
    if (typeof window.FileReader !== 'function')_x000D_
        throw ("The file API isn't supported on this browser.");_x000D_
    let input = event.target;_x000D_
    if (!input)_x000D_
        throw ("The browser does not properly implement the event object");_x000D_
    if (!input.files)_x000D_
        throw ("This browser does not support the `files` property of the file input.");_x000D_
    if (!input.files[0])_x000D_
        return undefined;_x000D_
    let file = input.files[0];_x000D_
    let fr = new FileReader();_x000D_
    fr.onload = onLoadFileHandler;_x000D_
    fr.readAsText(file);_x000D_
}
_x000D_
<input type='file' onchange='onChooseFile(event, onFileLoad.bind(this, "contents"))' />_x000D_
<p id="contents"></p>
_x000D_
_x000D_
_x000D_

The specified type member is not supported in LINQ to Entities. Only initializers, entity members, and entity navigation properties are supported

A lot of people are going to say this is a bad answer because it is not best practice but you can also convert it to a List before your where.

result = result.ToList().Where(p => date >= p.DOB);

Slauma's answer is better, but this would work as well. This cost more because ToList() will execute the Query against the database and move the results into memory.

Script @php artisan package:discover handling the post-autoload-dump event returned with error code 1

In case the error appears when upgrading from Laravel 6 to Laravel 7, the command composer require laravel/ui "^2.0" solves the problem (see https://laravel.com/docs/7.x/upgrade#authentication -scaffolding)

Using Tkinter in python to edit the title bar

I found this works:

window = Tk()
window.title('Window')

Maybe this helps?

POST JSON fails with 415 Unsupported media type, Spring 3 mvc

I had a similar problem but found the issue was that I had neglected to provide a default constructor for the DTO that was annotated with @RequestBody.

Compare two date formats in javascript/jquery

Try it the other way:

var start_date  = $("#fit_start_time").val(); //05-09-2013
var end_date    = $("#fit_end_time").val(); //10-09-2013
var format='dd-MM-y';
    var result= compareDates(start_date,format,end_date,format);
    if(result==1)/// end date is less than start date
    {
            alert('End date should be greater than Start date');
    }



OR:
if(new Date(start_date) >= new Date(end_date))
{
    alert('End date should be greater than Start date');
}

WPF - add static items to a combo box

Here is the code from MSDN and the link - Article Link, which you should check out for more detail.

<ComboBox Text="Is not open">
    <ComboBoxItem Name="cbi1">Item1</ComboBoxItem>
    <ComboBoxItem Name="cbi2">Item2</ComboBoxItem>
    <ComboBoxItem Name="cbi3">Item3</ComboBoxItem>
</ComboBox>

How to do fade-in and fade-out with JavaScript and CSS

why do that to yourself?

jQuery:

$("#element").fadeOut();
$("#element").fadeIn();

I think that's easier.

www.jquery.com

How to execute only one test spec with angular-cli

Each of your .spec.ts file have all its tests grouped in describe block like this:

describe('SomeComponent', () => {...}

You can easily run just this single block, by prefixing the describe function name with f:

fdescribe('SomeComponent', () => {...}

If you have such function, no other describe blocks will run. Btw. you can do similar thing with it => fit and there is also a "blacklist" version - x. So:

  • fdescribe and fit causes only functions marked this way to run
  • xdescribe and xit causes all but functions marked this way to run

How to show all privileges from a user in oracle?

Another useful resource:

http://psoug.org/reference/roles.html

  • DBA_SYS_PRIVS
  • DBA_TAB_PRIVS
  • DBA_ROLE_PRIVS

Redirect within component Angular 2

callLog(){
    this.http.get('http://localhost:3000/getstudent/'+this.login.email+'/'+this.login.password)
    .subscribe(data => {
        this.getstud=data as string[];
        if(this.getstud.length!==0) {
            console.log(data)
            this.route.navigate(['home']);// used for routing after importing Router    
        }
    });
}

rbind error: "names do not match previous names"

check all the variables names in both of the combined files. Name of variables of both files to be combines should be exact same or else it will produce the above mentioned errors. I was facing the same problem as well, and after making all names same in both the file, rbind works accurately.

Thanks

"echo -n" prints "-n"

Just for the most popular linux Ubuntu & it's bash:

  1. Check which shell are you using? Mostly below works, else see this:

    echo $0

  2. If above prints bash, then below will work:

    printf "hello with no new line printed at end"
    OR
    echo -n "hello with no new line printed at end"

Difference between "while" loop and "do while" loop

The difference between do while (exit check) and while (entry check) is that while entering in do while it will not check but in while it will first check

The example is as such:

Program 1:

int a=10;
do{
System.out.println(a);
}
while(a<10);

//here the a is not less than 10 then also it will execute once as it will execute do while exiting it checks that a is not less than 10 so it will exit the loop

Program 2:

int b=0;
while(b<10)
{
System.out.println(b);
}
//here nothing will be printed as the value of b is not less than 10 and it will not let enter the loop and will exit

output Program 1:

10

output Program 2:

[nothing is printed]

note:

output of the program 1 and program 2 will be same if we assign a=0 and b=0 and also put a++; and b++; in the respective body of the program.

What is the correct Performance Counter to get CPU and Memory Usage of a Process?

Pelo Hyper-V:

private PerformanceCounter theMemCounter = new PerformanceCounter(
    "Hyper-v Dynamic Memory VM",
    "Physical Memory",
    Process.GetCurrentProcess().ProcessName); 

How to import JSON File into a TypeScript file?

I couldn't import a different file.json too. But I resolved it like this

const swaggerDoc = require('../swagger.json')

Zip lists in Python

In Python 2.7 this might have worked fine:

>>> a = b = c = range(20)
>>> zip(a, b, c)

But in Python 3.4 it should be (otherwise, the result will be something like <zip object at 0x00000256124E7DC8>):

>>> a = b = c = range(20)
>>> list(zip(a, b, c))

Connect with SSH through a proxy

$ which nc
/bin/nc

$ rpm -qf /bin/nc
nmap-ncat-7.40-7.fc26.x86_64

$ ssh -o "ProxyCommand nc --proxy <addr[:port]> %h %p" USER@HOST

$ ssh -o "ProxyCommand nc --proxy <addr[:port]> --proxy-type <type> --proxy-auth <auth> %h %p" USER@HOST

Using 'starts with' selector on individual class names

While the top answer here is a workaround for the asker's particular case, if you're looking for a solution to actually using 'starts with' on individual class names:

You can use this custom jQuery selector, which I call :acp() for "A Class Prefix." Code is at the bottom of this post.

var test = $('div:acp("starting_text")');

This will select any and all <div> elements that have at least one class name beginning with the given string ("starting_text" in this example), regardless of whether that class is at the beginning or elsewhere in the class attribute strings.

<div id="1" class="apple orange lemon" />
<div id="2" class="orange applelemon banana" />
<div id="3" class="orange lemon apple" />
<div id="4" class="lemon orangeapple" />
<div id="5" class="lemon orange" />

var startsWithapp = $('div:acp("app")');

This will return elements 1, 2, and 3, but not 4 or 5.

Here's the declaration for the :acp custom selector, which you can put anywhere:

$(function(){
    $.expr[":"].acp = function(elem, index, m){
          var regString = '\\b' + m[3];
          var reg = new RegExp(regString, "g");
          return elem.className.match(reg);
    }
});

I made this because I do a lot of GreaseMonkey hacking of websites on which I have no backend control, so I often need to find elements with class names that have dynamic suffixes. It's been very useful.

Install .ipa to iPad with or without iTunes

If your using the latest version of Itunes and there is no APP section Click on summary while the device is connected to you PC . Then Drag and drop the file onto the "on my device" section.

-see picture for illustrationIllustration

MySQL Query - Records between Today and Last 30 Days

Here's a solution without using curdate() function, this is a solution for those who use TSQL I guess

SELECT myDate
FROM myTable
WHERE myDate BETWEEN DATEADD(DAY, -30, GETDATE()) AND GETDATE()

Check if Internet Connection Exists with jQuery?

5 years later-version:

Today, there are JS libraries for you, if you don't want to get into the nitty gritty of the different methods described on this page.

On of these is https://github.com/hubspot/offline. It checks for the connectivity of a pre-defined URI, by default your favicon. It automatically detects when the user's connectivity has been reestablished and provides neat events like up and down, which you can bind to in order to update your UI.

What is mod_php?

mod_php is a PHP interpreter.

From docs, one important catch of mod_php is,

"mod_php is not thread safe and forces you to stick with the prefork mpm (multi process, no threads), which is the slowest possible configuration"

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

Besides the session cookie (which is kind of standard), I don't want to use extra cookies.

I found a solution which works for me when building a Single Page Web Application (SPA), with many AJAX requests. Note: I am using server side Java and client side JQuery, but no magic things so I think this principle can be implemented in all popular programming languages.

My solution without extra cookies is simple:

Client Side

Store the CSRF token which is returned by the server after a succesful login in a global variable (if you want to use web storage instead of a global thats fine of course). Instruct JQuery to supply a X-CSRF-TOKEN header in each AJAX call.

The main "index" page contains this JavaScript snippet:

// Intialize global variable CSRF_TOKEN to empty sting. 
// This variable is set after a succesful login
window.CSRF_TOKEN = '';

// the supplied callback to .ajaxSend() is called before an Ajax request is sent
$( document ).ajaxSend( function( event, jqXHR ) {
    jqXHR.setRequestHeader('X-CSRF-TOKEN', window.CSRF_TOKEN);
}); 

Server Side

On successul login, create a random (and long enough) CSRF token, store this in the server side session and return it to the client. Filter certain (sensitive) incoming requests by comparing the X-CSRF-TOKEN header value to the value stored in the session: these should match.

Sensitive AJAX calls (POST form-data and GET JSON-data), and the server side filter catching them, are under a /dataservice/* path. Login requests must not hit the filter, so these are on another path. Requests for HTML, CSS, JS and image resources are also not on the /dataservice/* path, thus not filtered. These contain nothing secret and can do no harm, so this is fine.

@WebFilter(urlPatterns = {"/dataservice/*"})
...
String sessionCSRFToken = req.getSession().getAttribute("CSRFToken") != null ? (String) req.getSession().getAttribute("CSRFToken") : null;
if (sessionCSRFToken == null || req.getHeader("X-CSRF-TOKEN") == null || !req.getHeader("X-CSRF-TOKEN").equals(sessionCSRFToken)) {
    resp.sendError(401);
} else
    chain.doFilter(request, response);
}   

getting only name of the class Class.getName()

You can use following simple technique for print log with class name.

private String TAG = MainActivity.class.getSimpleName();

Suppose we have to check coming variable value in method then we can use log like bellow :

private void printVariable(){
Log.e(TAG, "printVariable: ");
}

Importance of this line is that, we can check method name along with class name. To write this type of log.

write :- loge and Enter.

will print on console

E/MainActivity: printVariable:

What is the size of column of int(11) in mysql in bytes?

An INT will always be 4 bytes no matter what length is specified.

  • TINYINT = 1 byte (8 bit)
  • SMALLINT = 2 bytes (16 bit)
  • MEDIUMINT = 3 bytes (24 bit)
  • INT = 4 bytes (32 bit)
  • BIGINT = 8 bytes (64 bit).

The length just specifies how many characters to pad when selecting data with the mysql command line client. 12345 stored as int(3) will still show as 12345, but if it was stored as int(10) it would still display as 12345, but you would have the option to pad the first five digits. For example, if you added ZEROFILL it would display as 0000012345.

... and the maximum value will be 2147483647 (Signed) or 4294967295 (Unsigned)

Should methods in a Java interface be declared with or without a public access modifier?

I used declare methods with the public modifier, because it makes the code more readable, especially with syntax highlighting. In our latest project though, we used Checkstyle which shows a warning with the default configuration for public modifiers on interface methods, so I switched to ommitting them.

So I'm not really sure what's best, but one thing I really don't like is using public abstract on interface methods. Eclipse does this sometimes when refactoring with "Extract Interface".

Add image to left of text via css

Try something like:

.create
 { 
  margin: 0px;
  padding-left: 20px;
  background-image: url('yourpic.gif');
    background-repeat: no-repeat;

}

display HTML page after loading complete

try using javascript for this! Seems like its the best and easiest way to do this. You'll get inbuilt funcn to execute a html code only after HTML page loads completely.

or else you may use state based programming where an event occurs at a particular state of the browser..

ASP.NET postback with JavaScript

First, don't use update panels. They are the second most evil thing that Microsoft has ever created for the web developer.

Second, if you must use update panels, try setting the UpdateMode property to Conditional. Then add a trigger to an Asp:Hidden control that you add to the page. Assign the change event as the trigger. In your dragstop event, change the value of the hidden control.

This is untested, but the theory seems sound... If this does not work, you could try the same thing with an asp:button, just set the display:none style on it and use the click event instead of the change event.

git - remote add origin vs remote set-url origin

git remote add => ADDS a new remote.

git remote set-url => UPDATES existing remote.


  1. The remote name that comes after add is a new remote name that did not exist prior to that command.
  2. The remote name that comes after set-url should already exist as a remote name to your repository.

git remote add myupstream someurl => myupstream remote name did not exist now creating it with this command.

git remote set-url upstream someurl => upstream remote name already exist i'm just changing it's url.


git remote add myupstream https://github.com/nodejs/node => **ADD** If you don't already have upstream
git remote set-url upstream https://github.com/nodejs/node # => **UPDATE** url for upstream

Closing a file after File.Create

The reason is because a FileStream is returned from your method to create a file. You should return the FileStream into a variable or call the close method directly from it after the File.Create.

It is a best practice to let the using block help you implement the IDispose pattern for a task like this. Perhaps what might work better would be:

if(!File.Exists(myPath)){
   using(FileStream fs = File.Create(myPath))
   using(StreamWriter writer = new StreamWriter(fs)){
      // do your work here
   }
}

How to turn a string formula into a "real" formula

Evaluate might suit:

http://www.mrexcel.com/forum/showthread.php?t=62067

Function Eval(Ref As String)
    Application.Volatile
    Eval = Evaluate(Ref)
End Function

What values for checked and selected are false?

No value is considered false, only the absence of the attribute. There are plenty of invalid values though, and some implementations might consider certain invalid values as false.

HTML5 spec

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

The disabled content 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="checkbox" checked />
<input type="checkbox" checked="" />
<input type="checkbox" checked="checked" />
<input type="checkbox" checked="ChEcKeD" />

The following are invalid:

<input type="checkbox" checked="0" />
<input type="checkbox" checked="1" />
<input type="checkbox" checked="false" />
<input type="checkbox" checked="true" />

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

<input type="checkbox" />

Recommendation

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

Check if input is number or letter javascript

Just find the remainder by dividing by 1, that is x%1. If the remainder is 0, it means that x is a whole number. Otherwise, you have to display the message "Must input numbers". This will work even in the case of strings, decimal numbers etc.

function checkInp()
{
    var x = document.forms["myForm"]["age"].value;
    if ((x%1) != 0) 
    {
        alert("Must input numbers");
        return false;
    }
}

How to change a particular element of a C++ STL vector

I prefer

l.at(4)= -1;

while [4] is your index

IIS: Idle Timeout vs Recycle

IIS now has

Idle Time-out Action : Suspend setting

Suspending is just freezes the process and it is much more efficient than the destroying the process.

UITableView, Separator color where to set?

If you just want to set the same color to every separator and it is opaque you can use:

 self.tableView.separatorColor = UIColor.redColor()

If you want to use different colors for the separators or clear the separator color or use a color with alpha.

BE CAREFUL: You have to know that there is a backgroundView in the separator that has a default color.

To change it you can use this functions:

    func tableView(tableView: UITableView, willDisplayHeaderView view: UIView, forSection section: Int) {
        if(view.isKindOfClass(UITableViewHeaderFooterView)){
            var headerView = view as! UITableViewHeaderFooterView;
            headerView.backgroundView?.backgroundColor = myColor

           //Other colors you can change here
           // headerView.backgroundColor = myColor
           // headerView.contentView.backgroundColor = myColor
        }
    }

    func tableView(tableView: UITableView, willDisplayFooterView view: UIView, forSection section: Int) {
        if(view.isKindOfClass(UITableViewHeaderFooterView)){
            var footerView = view as! UITableViewHeaderFooterView;
            footerView.backgroundView?.backgroundColor = myColor
           //Other colors you can change here
           //footerView.backgroundColor = myColor
           //footerView.contentView.backgroundColor = myColor
        }
    }

Hope it helps!

HTML button calling an MVC Controller and Action method

Try this:

@Html.ActionLink("DisplayText", "Action", "Controller", route, attribute)

This should work for you.

What's HTML character code 8203?

I landed here with the same issue, then figured it out on my own. This weird character was appearing with my HTML.

The issue is most likely your code editor. I use Espresso and sometimes run into issues like this.

To fix it, simply highlight the affected code, then go to the menu and click "convert to numeric entities". You'll see the numeric value of this character appear; simply delete it and it's gone forever.

CentOS 7 and Puppet unable to install nc

yum install nmap-ncat.x86_64

resolved my problem

Bootstrap Carousel : Remove auto slide

You can do this 2 ways, via js or html (easist)

  1. Via js
$('.carousel').carousel({
  interval: false,
});

That will make the auto sliding stop because there no Milliseconds added and will never slider next.

  1. Via Html By adding data-interval="false" and removing data-ride="carousel"
<div id="carouselExampleCaptions" class="carousel slide" data-ride="carousel">

becomes:

<div id="carouselExampleCaptions" class="carousel slide" data-interval="false">

updated based on @webMan's comment

Is there a way to select sibling nodes?

Quick:

var siblings = n => [...n.parentElement.children].filter(c=>c!=n)

https://codepen.io/anon/pen/LLoyrP?editors=1011

Get the parent's children as an array, filter out this element.

Edit:

And to filter out text nodes (Thanks pmrotule):

var siblings = n => [...n.parentElement.children].filter(c=>c.nodeType == 1 && c!=n)

how to insert datetime into the SQL Database table?

DateTime values should be inserted as if they are strings surrounded by single quotes '20201231' but in many cases they need to be casted explicitly to datetime CAST(N'20201231' AS DATETIME) to avoid bad execution plans with CONVERSION_IMPLICIT warnings that affect negatively the performance. Hier is an example:

CREATE TABLE dbo.T(D DATETIME)

--wrong way
INSERT INTO dbo.T (D) VALUES ('20201231'), ('20201231')

Warnings in the execution plan

--better way
INSERT INTO dbo.T (D) VALUES (CAST(N'20201231' AS DATETIME)), (CAST(N'20201231' AS DATETIME))

No warnings

Laravel 5.4 ‘cross-env’ Is Not Recognized as an Internal or External Command

First run:

rm -rf node_modules
rm package-lock.json yarn.lock
npm cache clear --force

Then run the command

npm install cross-env

npm install 

and then you can also run

npm run dev

What is the difference between Amazon SNS and Amazon SQS?

In simple terms,

  • SNS - sends messages to the subscriber using push mechanism and no need of pull.

  • SQS - it is a message queue service used by distributed applications to exchange messages through a polling model, and can be used to decouple sending and receiving components.

A common pattern is to use SNS to publish messages to Amazon SQS queues to reliably send messages to one or many system components asynchronously.

Reference from Amazon SNS FAQs.

How to get row data by clicking a button in a row in an ASP.NET gridview

<asp:TemplateField>
   <ItemTemplate>
  <asp:LinkButton runat="server" ID="LnKB" Text='edit' OnClick="LnKB_Click"   > 
 </asp:LinkButton>
 </ItemTemplate>
</asp:TemplateField>

  protected void LnKB_Click(object sender, System.EventArgs e)
  {
        LinkButton lb = sender as LinkButton;

        GridViewRow clickedRow = ((LinkButton)sender).NamingContainer as GridViewRow;
        int x = clickedRow.RowIndex;
        int id = Convert.ToInt32(yourgridviewname.Rows[x].Cells[0].Text);
        lbl.Text = yourgridviewname.Rows[x].Cells[2].Text; 
   }

How to get page content using cURL?

For a realistic approach that emulates the most human behavior, you may want to add a referer in your curl options. You may also want to add a follow_location to your curl options. Trust me, whoever said that cURLING Google results is impossible, is a complete dolt and should throw his/her computer against the wall in hopes of never returning to the internetz again. Everything that you can do "IRL" with your own browser can all be emulated using PHP cURL or libCURL in Python. You just need to do more cURLS to get buff. Then you will see what I mean. :)

  $url = "http://www.google.com/search?q=".$strSearch."&hl=en&start=0&sa=N";
  $ch = curl_init();
  curl_setopt($ch, CURLOPT_REFERER, 'http://www.example.com/1');
  curl_setopt($ch, CURLOPT_HEADER, 0);
  curl_setopt($ch, CURLOPT_VERBOSE, 0);
  curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
  curl_setopt($ch, CURLOPT_USERAGENT, "Mozilla/4.0 (compatible;)");
  curl_setopt($ch, CURLOPT_URL, urlencode($url));
  $response = curl_exec($ch);
  curl_close($ch);

How to access the SMS storage on Android?

Do the following, download SQLLite Database Browser from here:

Locate your db. file in your phone.

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

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

VirtualBox Cannot register the hard disk already exists

I found a solution

File -> Virtual Media Manager -> Removed existing images (note, I removed them only from the registry).

I followed these steps.

http://www.webdesignblog.asia/software/virtualbox-moving-vdi-file-re-linking-guest/#sthash.1QOHeiw5.dpbs

After that I could update the path in the VM settings.

Downloading all maven dependencies to a directory NOT in repository?

The maven dependency plugin can potentially solve your problem.

If you have a pom with all your project dependencies specified, all you would need to do is run

mvn dependency:copy-dependencies

and you will find the target/dependencies folder filled with all the dependencies, including transitive.

Adding Gustavo's answer from below: To download the dependency sources, you can use

mvn dependency:copy-dependencies -Dclassifier=sources

(via Apache Maven Dependency Plugin doc).

How to set an image as a background for Frame in Swing GUI of java?

The Background Panel entry shows a couple of different ways depending on your requirements.

JWT authentication for ASP.NET Web API

I think you should use some 3d party server to support the JWT token and there is no out of the box JWT support in WEB API 2.

However there is an OWIN project for supporting some format of signed token (not JWT). It works as a reduced OAuth protocol to provide just a simple form of authentication for a web site.

You can read more about it e.g. here.

It's rather long, but most parts are details with controllers and ASP.NET Identity that you might not need at all. Most important are

Step 9: Add support for OAuth Bearer Tokens Generation

Step 12: Testing the Back-end API

There you can read how to set up endpoint (e.g. "/token") that you can access from frontend (and details on the format of the request).

Other steps provide details on how to connect that endpoint to the database, etc. and you can chose the parts that you require.

<SELECT multiple> - how to allow only one item selected?

Late to answer but might help someone else, here is how to do it without removing the 'multiple' attribute.

$('.myDropdown').chosen({
    //Here you can change the value of the maximum allowed options
    max_selected_options: 1
});

Has Facebook sharer.php changed to no longer accept detailed parameters?

If you encode the & in your URL to %26 it works correctly. Just tested and verified.

How to show an alert box in PHP?

When I just run this as a page

<?php
echo '<script language="javascript">';
echo 'alert("message successfully sent")';
echo '</script>';
exit;

it works fine.

What version of PHP are you running?

Could you try echoing something else after: $testObject->split_for_sms($Chat);

Maybe it doesn't get to that part of the code? You could also try these with the other function calls to check where your program stops/is getting to.

Hope you get a bit further with this.

Set Date in a single line

This is yet another reason to use Joda Time

new DateMidnight(2010, 3, 5)

DateMidnight is now deprecated but the same effect can be achieved with Joda Time DateTime

DateTime dt = new DateTime(2010, 3, 5, 0, 0);

Converting VS2012 Solution to VS2010

Solution of VS2010 is supported by VS2012. Solution of VS2012 isn't supported by VS2010 --> one-way upgrade only. VS2012 doesn't support setup projects. Find here more about VS2010/VS2012 compatibility: http://msdn.microsoft.com/en-us/library/hh266747(v=vs.110).aspx

On Selenium WebDriver how to get Text from Span Tag

Maybe the span element is hidden. If that's the case then use the innerHtml property:

By.css:

String kk = wd.findElement(By.cssSelector("#customSelect_3 span.selectLabel"))
              .getAttribute("innerHTML");

By.xpath:

String kk = wd.findElement(By.xpath(
                   "//*[@id='customSelect_3']/.//span[contains(@class,'selectLabel')]"))
              .getAttribute("innerHTML");

"/.//" means "look under the selected element".

ViewPager and fragments — what's the right way to store fragment's state?

If anyone is having issues with their FragmentStatePagerAdapter not properly restoring the state of its fragments...ie...new Fragments are being created by the FragmentStatePagerAdapter instead of it restoring them from state...

Make sure you call ViewPager.setOffscreenPageLimit() BEFORE you call ViewPager.setAdapter(fragmentStatePagerAdapter)

Upon calling ViewPager.setOffscreenPageLimit()...the ViewPager will immediately look to its adapter and try to get its fragments. This could happen before the ViewPager has a chance to restore the Fragments from savedInstanceState(thus creating new Fragments that can't be re-initialized from SavedInstanceState because they're new).

IIS7 - The request filtering module is configured to deny a request that exceeds the request content length

<configuration>
    <system.web>
        <httpRuntime maxRequestLength="1048576" />
    </system.web>
</configuration>

From here.

For IIS7 and above, you also need to add the lines below:

 <system.webServer>
   <security>
      <requestFiltering>
         <requestLimits maxAllowedContentLength="1073741824" />
      </requestFiltering>
   </security>
 </system.webServer>

mysql alphabetical order

You do not need to user where clause while ordering the data alphabetically. here is my code

SELECT * FROM tbl_name ORDER BY field_name

that's it. It return the data in alphabetical order ie; From A to Z. :)

Wamp Server not goes to green color

Open cmd and type the command below.

netstat -o -n -a | findstr 0.0:80

Last column of each row is the process identifier (PID)

You can find the application that reserves port 80, using taskmanager services tab or just type tasklist in cmd.

Then follow this link: http://www.ttkalec.com/blog/resolving-yellow-wamp-server-status-freeing-up-port-80-for-apache/

java.lang.ClassNotFoundException: Didn't find class on path: dexpathlist

If the project was compiling just before, you can try to clear the cache using :

./gradlew clean

or

./gradlew cleanBuildCache

or for windows

gradlew cleanBuildCache

https://developer.android.com/studio/build/build-cache.html

What is a predicate in c#?

The following code can help you to understand some real world use of predicates (Combined with named iterators).

namespace Predicate
{
    class Person
    {
        public int Age { get; set; }
    }
    class Program
    {
        static void Main(string[] args)
        {
            foreach (Person person in OlderThan(18))
            {
                Console.WriteLine(person.Age);
            }
        }

        static IEnumerable<Person> OlderThan(int age)
        {
            Predicate<Person> isOld = x => x.Age > age;
            Person[] persons = { new Person { Age = 10 }, new Person { Age = 20 }, new Person { Age = 19 } };

            foreach (Person person in persons)
                if (isOld(person)) yield return person;
        }
    }
}

jQuery check if Cookie exists, if not create it

Try this very simple:

            var cookieExist = $.cookie("status");
            if(cookieExist == "null" ){
                alert("Cookie Is Null");

            }

Detecting touch screen devices with Javascript

I use:

if(jQuery.support.touch){
    alert('Touch enabled');
}

in jQuery mobile 1.0.1

Import existing source code to GitHub

From Bitbucket:

Push up an existing repository. You already have a Git repository on your computer. Let's push it up to Bitbucket:

cd /path/to/my/repo
git remote add origin ssh://[email protected]/javacat/geo.git
git push -u origin --all   # To push up the repo for the first time

How can I pass a parameter to a setTimeout() callback?

How i resolved this stage ?

just like that :

setTimeout((function(_deepFunction ,_deepData){
    var _deepResultFunction = function _deepResultFunction(){
          _deepFunction(_deepData);
    };
    return _deepResultFunction;
})(fromOuterFunction, fromOuterData ) , 1000  );

setTimeout wait a reference to a function, so i created it in a closure, which interprete my data and return a function with a good instance of my data !

Maybe you can improve this part :

_deepFunction(_deepData);

// change to something like :
_deepFunction.apply(contextFromParams , args); 

I tested it on chrome, firefox and IE and it execute well, i don't know about performance but i needed it to be working.

a sample test :

myDelay_function = function(fn , params , ctxt , _time){
setTimeout((function(_deepFunction ,_deepData, _deepCtxt){
            var _deepResultFunction = function _deepResultFunction(){
                //_deepFunction(_deepData);
                _deepFunction.call(  _deepCtxt , _deepData);
            };
        return _deepResultFunction;
    })(fn , params , ctxt)
, _time) 
};

// the function to be used :
myFunc = function(param){ console.log(param + this.name) }
// note that we call this.name

// a context object :
myObjet = {
    id : "myId" , 
    name : "myName"
}

// setting a parmeter
myParamter = "I am the outer parameter : ";

//and now let's make the call :
myDelay_function(myFunc , myParamter  , myObjet , 1000)

// this will produce this result on the console line :
// I am the outer parameter : myName

Maybe you can change the signature to make it more complient :

myNass_setTimeOut = function (fn , _time , params , ctxt ){
return setTimeout((function(_deepFunction ,_deepData, _deepCtxt){
            var _deepResultFunction = function _deepResultFunction(){
                //_deepFunction(_deepData);
                _deepFunction.apply(  _deepCtxt , _deepData);
            };
        return _deepResultFunction;
    })(fn , params , ctxt)
, _time) 
};

// and try again :
for(var i=0; i<10; i++){
   myNass_setTimeOut(console.log ,1000 , [i] , console)
}

And finaly to answer the original question :

 myNass_setTimeOut( postinsql, 4000, topicId );

Hope it can help !

ps : sorry but english it's not my mother tongue !

How to connect to LocalDb

Use (localdb)\MSSQLLocalDBwith Windows Auth

Laravel 5 PDOException Could Not Find Driver

I'm using Ubuntu 16.04 and PHP 5.6.20

After too many problems, the below steps solved this for me:

  1. find php.ini path via phpinfo()

  2. uncomment

    extension=php_pdo_mysql.dll
    
  3. add this line

    extension=pdo_mysql.so
    
  4. then run

    sudo apt-get install php-mysql
    

Curl : connection refused

Try curl -v http://localhost:8080/ instead of 127.0.0.1

How to declare a constant in Java

Anything that is static is in the class level. You don't have to create instance to access static fields/method. Static variable will be created once when class is loaded.

Instance variables are the variable associated with the object which means that instance variables are created for each object you create. All objects will have separate copy of instance variable for themselves.

In your case, when you declared it as static final, that is only one copy of variable. If you change it from multiple instance, the same variable would be updated (however, you have final variable so it cannot be updated).

In second case, the final int a is also constant , however it is created every time you create an instance of the class where that variable is declared.

Have a look on this Java tutorial for better understanding ,

Matplotlib tight_layout() doesn't take into account figure suptitle

I had a similar issue that cropped up when using tight_layout for a very large grid of plots (more than 200 subplots) and rendering in a jupyter notebook. I made a quick solution that always places your suptitle at a certain distance above your top subplot:

import matplotlib.pyplot as plt

n_rows = 50
n_col = 4
fig, axs = plt.subplots(n_rows, n_cols)

#make plots ...

# define y position of suptitle to be ~20% of a row above the top row
y_title_pos = axs[0][0].get_position().get_points()[1][1]+(1/n_rows)*0.2
fig.suptitle('My Sup Title', y=y_title_pos)

For variably-sized subplots, you can still use this method to get the top of the topmost subplot, then manually define an additional amount to add to the suptitle.

What is correct media query for IPad Pro?

Note that there are multiple iPad Pros, each with a different Viewports: When emulating an iPad Pro via the Chrome developer tools, the iPad Pro (12.9") is the default option. If you want to emulate one of the other iPad Pros (10.5" or 9.7") with a different viewport, you'll need to add a custom emulated device with the correct specs.

You can search devices, viewports, and their respective CSS media queries at: http://vizdevices.yesviz.com/devices.php.

For instance, the iPad Pro (12.9") would have the following media queries:

/* Landscape */ 
@media only screen and (min-width: 1366px) and (orientation: landscape) { /* Your Styles... */ }

/*Portrait*/ 
@media only screen and (min-width: 1024px) and (orientation: portrait) { /* Your Styles... */ }

Whereas the iPad Pro (10.5") will have:

/* Landscape */ 
@media only screen and (min-device-width: 1112px) and (orientation: landscape) { /* Your Styles... */ }

/*Portrait*/ 
@media only screen and (min-device-width: 834px) and (orientation: portrait) { /* Your Styles... */ }

how to automatically scroll down a html page?

here is the example using Pure JavaScript

_x000D_
_x000D_
function scrollpage() {  _x000D_
 function f() _x000D_
 {_x000D_
  window.scrollTo(0,i);_x000D_
  if(status==0) {_x000D_
      i=i+40;_x000D_
   if(i>=Height){ status=1; } _x000D_
  } else {_x000D_
   i=i-40;_x000D_
   if(i<=1){ status=0; }  // if you don't want continue scroll then remove this line_x000D_
  }_x000D_
 setTimeout( f, 0.01 );_x000D_
 }f();_x000D_
}_x000D_
var Height=document.documentElement.scrollHeight;_x000D_
var i=1,j=Height,status=0;_x000D_
scrollpage();_x000D_
</script>
_x000D_
<style type="text/css">_x000D_
_x000D_
 #top { border: 1px solid black;  height: 20000px; }_x000D_
 #bottom { border: 1px solid red; }_x000D_
_x000D_
</style>
_x000D_
<div id="top">top</div>_x000D_
<div id="bottom">bottom</div>
_x000D_
_x000D_
_x000D_

How to increase executionTimeout for a long-running query?

RE. "Can we set this value for individual page" – MonsterMMORPG.

Yes, you can (& normally should) enclose the previous answer using the location-tag.

e.g.

  ...
  <location path="YourWebpage.aspx">
    <system.web>
      <httpRuntime executionTimeout="300" maxRequestLength="29296" />
    </system.web>
  </location>
</configuration>

The above snippet is taken from the end of my own working web.config, which I tested yesterday - it works for me.

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

I had to write this in the Immediate window :3

(((exception as System.Data.Entity.Validation.DbEntityValidationException).EntityValidationErrors as System.Collections.Generic.List<System.Data.Entity.Validation.DbEntityValidationResult>)[0].ValidationErrors as System.Collections.Generic.List<System.Data.Entity.Validation.DbValidationError>)[0]

in order to get deep into the exact error !

Detect if device is iOS

In my case the user agent was not good enought since in the Ipad the user agent was the same as in Mac OS, therefore I had to do a nasty trick:

var mql = window.matchMedia("(orientation: landscape)");

/**
 * If we are in landscape but the height is bigger than width
 */
if(mql.matches && window.screen.height > window.screen.width) {
    // IOS
} else {
    // Mac OS
}

Decoding a Base64 string in Java

Modify the package you're using:

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

And then use it like this:

byte[] decoded = Base64.decodeBase64("YWJjZGVmZw==");
System.out.println(new String(decoded, "UTF-8") + "\n");

What is difference between cacerts and keystore?

cacerts is where Java stores public certificates of root CAs. Java uses cacerts to authenticate the servers.

Keystore is where Java stores the private keys of the clients so that it can share it to the server when the server requests client authentication.

Is it possible to install iOS 6 SDK on Xcode 5?

My app was transitioned to Xcode 5 seamlessly because it can still build with the original iOS Deployment Target that you set in the project (5.1 in my case). If the new SDK doesn't cause some insurmountable problem, then why not build using it? Surely there are many improvements under the hood.

For example, I will much prefer to use Xcode 5 instead of Xcode 4.6.3. Why? I'll get a lot more battery life because the UI scrolling of text/code areas in Xcode 5 no longer chews up an entire CPU thread.

Best practice for storing and protecting private API keys in applications

Old unsecured way:

Follow 3 simple steps to secure API/Secret key (Old answer)

We can use Gradle to secure the API key or Secret key.

1. gradle.properties (Project properties) : Create variable with key.

GoolgeAPIKey = "Your API/Secret Key"

2. build.gradle (Module: app) : Set variable in build.gradle to access it in activity or fragment. Add below code to buildTypes {}.

buildTypes.each {
    it.buildConfigField 'String', 'GoogleSecAPIKEY', GoolgeAPIKey
}

3. Access it in Activity/Fragment by app's BuildConfig :

BuildConfig.GoogleSecAPIKEY

Update :

The above solution is helpful in the open source project to commit over Git. (Thanks to David Rawson and riyaz-ali for your comment).

As per the Matthew and Pablo Cegarra comments the above way is not secure and Decompiler will allow someone to view the BuildConfig with our secret keys.

Solution :

We can use NDK to Secure API Keys. We can store keys in the native C/C++ class and access them in our Java classes.

Please follow this blog to secure API keys using NDK.

A follow-up on how to store tokens securely in Android

Securely storing passwords for use in python script

Know the master key yourself. Don't hard code it.

Use py-bcrypt (bcrypt), powerful hashing technique to generate a password yourself.

Basically you can do this (an idea...)

import bcrypt
from getpass import getpass
master_secret_key = getpass('tell me the master secret key you are going to use')
salt = bcrypt.gensalt()
combo_password = raw_password + salt + master_secret_key
hashed_password = bcrypt.hashpw(combo_password, salt)

save salt and hashed password somewhere so whenever you need to use the password, you are reading the encrypted password, and test against the raw password you are entering again.

This is basically how login should work these days.

How do I parse a string into a number with Dart?

In Dart 2 int.tryParse is available.

It returns null for invalid inputs instead of throwing. You can use it like this:

int val = int.tryParse(text) ?? defaultValue;

www-data permissions?

As stated in an article by Slicehost:

User setup

So let's start by adding the main user to the Apache user group:

sudo usermod -a -G www-data demo

That adds the user 'demo' to the 'www-data' group. Do ensure you use both the -a and the -G options with the usermod command shown above.

You will need to log out and log back in again to enable the group change.

Check the groups now:

groups
...
# demo www-data

So now I am a member of two groups: My own (demo) and the Apache group (www-data).

Folder setup

Now we need to ensure the public_html folder is owned by the main user (demo) and is part of the Apache group (www-data).

Let's set that up:

sudo chgrp -R www-data /home/demo/public_html

As we are talking about permissions I'll add a quick note regarding the sudo command: It's a good habit to use absolute paths (/home/demo/public_html) as shown above rather than relative paths (~/public_html). It ensures sudo is being used in the correct location.

If you have a public_html folder with symlinks in place then be careful with that command as it will follow the symlinks. In those cases of a working public_html folder, change each folder by hand.

Setgid

Good so far, but remember the command we just gave only affects existing folders. What about anything new?

We can set the ownership so anything new is also in the 'www-data' group.

The first command will change the permissions for the public_html directory to include the "setgid" bit:

sudo chmod 2750 /home/demo/public_html

That will ensure that any new files are given the group 'www-data'. If you have subdirectories, you'll want to run that command for each subdirectory (this type of permission doesn't work with '-R'). Fortunately new subdirectories will be created with the 'setgid' bit set automatically.

If we need to allow write access to Apache, to an uploads directory for example, then set the permissions for that directory like so:

sudo chmod 2770 /home/demo/public_html/domain1.com/public/uploads

The permissions only need to be set once as new files will automatically be assigned the correct ownership.

Groovy Shell warning "Could not open/create prefs root node ..."

Dennis answer is correct. However I would like to explain the solution in a bit more detailed way (for Windows User):

  1. Go into your Start Menu and type regedit into the search field.
  2. Navigate to path HKEY_LOCAL_MACHINE\Software\JavaSoft (Windows 10 seems to now have this here: HKEY_LOCAL_MACHINE\Software\WOW6432Node\JavaSoft)
  3. Right click on the JavaSoft folder and click on New -> Key
  4. Name the new Key Prefs and everything should work.

Alternatively, save and execute a *.reg file with the following content:

Windows Registry Editor Version 5.00
[HKEY_LOCAL_MACHINE\Software\JavaSoft\Prefs]

INSERT INTO TABLE from comma separated varchar-list

Since there's no way to just pass this "comma-separated list of varchars", I assume some other system is generating them. If you can modify your generator slightly, it should be workable. Rather than separating by commas, you separate by union all select, and need to prepend a select also to the list. Finally, you need to provide aliases for the table and column in you subselect:

Create Table #IMEIS(
    imei varchar(15)
)
INSERT INTO #IMEIS(imei)
    SELECT * FROM (select '012251000362843' union all select '012251001084784' union all select '012251001168744' union all
                   select '012273007269862' union all select '012291000080227' union all select '012291000383084' union all
                   select '012291000448515') t(Col)
SELECT * from #IMEIS
DROP TABLE #IMEIS;

But noting your comment to another answer, about having 5000 entries to add. I believe the 256 tables per select limitation may kick in with the above "union all" pattern, so you'll still need to do some splitting of these values into separate statements.

how to convert a string to an array in php

Take a look at the explode function.

<?php
// Example 1
$pizza  = "piece1 piece2 piece3 piece4 piece5 piece6";
$pieces = explode(" ", $pizza);
echo $pieces[0]; // piece1
echo $pieces[1]; // piece2
?>

Using pickle.dump - TypeError: must be str, not bytes

The output file needs to be opened in binary mode:

f = open('varstor.txt','w')

needs to be:

f = open('varstor.txt','wb')

How do I check if a number is positive or negative in C#?

if (num < 0) {
  //negative
}
if (num > 0) {
  //positive
}
if (num == 0) {
  //neither positive or negative,
}

or use "else ifs"

Git branching: master vs. origin/master vs. remotes/origin/master

One clarification (and a point that confused me):

"remotes/origin/HEAD is the default branch" is not really correct.

remotes/origin/master was the default branch in the remote repository (last time you checked). HEAD is not a branch, it just points to a branch.

Think of HEAD as your working area. When you think of it this way then 'git checkout branchname' makes sense with respect to changing your working area files to be that of a particular branch. You "checkout" branch files into your working area. HEAD for all practical purposes is what is visible to you in your working area.

Richtextbox wpf binding

I can give you an ok solution and you can go with it, but before I do I'm going to try to explain why Document is not a DependencyProperty to begin with.

During the lifetime of a RichTextBox control, the Document property generally doesn't change. The RichTextBox is initialized with a FlowDocument. That document is displayed, can be edited and mangled in many ways, but the underlying value of the Document property remains that one instance of the FlowDocument. Therefore, there is really no reason it should be a DependencyProperty, ie, Bindable. If you have multiple locations that reference this FlowDocument, you only need the reference once. Since it is the same instance everywhere, the changes will be accessible to everyone.

I don't think FlowDocument supports document change notifications, though I am not sure.

That being said, here's a solution. Before you start, since RichTextBox doesn't implement INotifyPropertyChanged and Document is not a DependencyProperty, we have no notifications when the RichTextBox's Document property changes, so the binding can only be OneWay.

Create a class that will provide the FlowDocument. Binding requires the existence of a DependencyProperty, so this class inherits from DependencyObject.

class HasDocument : DependencyObject
{
    public static readonly DependencyProperty DocumentProperty =
        DependencyProperty.Register("Document", 
                                    typeof(FlowDocument), 
                                    typeof(HasDocument), 
                                    new PropertyMetadata(new PropertyChangedCallback(DocumentChanged)));

    private static void DocumentChanged(DependencyObject obj, DependencyPropertyChangedEventArgs e)
    {
        Debug.WriteLine("Document has changed");
    }

    public FlowDocument Document
    {
        get { return GetValue(DocumentProperty) as FlowDocument; }
        set { SetValue(DocumentProperty, value); }
    }
}

Create a Window with a rich text box in XAML.

<Window x:Class="samples.Window1"
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Title="Flow Document Binding" Height="300" Width="300"
    >
    <Grid>
      <RichTextBox Name="richTextBox" />
    </Grid>
</Window>

Give the Window a field of type HasDocument.

HasDocument hasDocument;

Window constructor should create the binding.

hasDocument = new HasDocument();

InitializeComponent();

Binding b = new Binding("Document");
b.Source = richTextBox;
b.Mode = BindingMode.OneWay;
BindingOperations.SetBinding(hasDocument, HasDocument.DocumentProperty, b);

If you want to be able to declare the binding in XAML, you would have to make your HasDocument class derive from FrameworkElement so that it can be inserted into the logical tree.

Now, if you were to change the Document property on HasDocument, the rich text box's Document will also change.

FlowDocument d = new FlowDocument();
Paragraph g = new Paragraph();
Run a = new Run();
a.Text = "I showed this using a binding";
g.Inlines.Add(a);
d.Blocks.Add(g);

hasDocument.Document = d;

Hibernate error: ids for this class must be manually assigned before calling save():

Here is what I did to solve just by 2 ways:

  1. make ID column as int type

  2. if you are using autogenerate in ID dont assing value in the setter of ID. If your mapping the some then sometimes autogenetated ID is not concedered. (I dont know why)

  3. try using @GeneratedValue(strategy=GenerationType.SEQUENCE) if possible

fork() child and parent processes

Start by reading the fork man page as well as the getppid / getpid man pages.

From fork's

On success, the PID of the child process is returned in the parent's thread of execution, and a 0 is returned in the child's thread of execution. On failure, a -1 will be returned in the parent's context, no child process will be created, and errno will be set appropriately.

So this should be something down the lines of

if ((pid=fork())==0){
    printf("yada yada %u and yada yada %u",getpid(),getppid());
}
else{ /* avoids error checking*/
    printf("Dont yada yada me, im your parent with pid %u ", getpid());
}

As to your question:

This is the child process. My pid is 22163 and my parent's id is 0.

This is the child process. My pid is 22162 and my parent's id is 22163.

fork() executes before the printf. So when its done, you have two processes with the same instructions to execute. Therefore, printf will execute twice. The call to fork() will return 0 to the child process, and the pid of the child process to the parent process.

You get two running processes, each one will execute this instruction statement:

printf ("... My pid is %d and my parent's id is %d",getpid(),0); 

and

printf ("... My pid is %d and my parent's id is %d",getpid(),22163);  

~

To wrap it up, the above line is the child, specifying its pid. The second line is the parent process, specifying its id (22162) and its child's (22163).

MATLAB, Filling in the area between two sets of data, lines in one figure

Personally, I find it both elegant and convenient to wrap the fill function. To fill between two equally sized row vectors Y1 and Y2 that share the support X (and color C):

fill_between_lines = @(X,Y1,Y2,C) fill( [X fliplr(X)],  [Y1 fliplr(Y2)], C );

Convert RGBA PNG to RGB with PIL

Here's a version that's much simpler - not sure how performant it is. Heavily based on some django snippet I found while building RGBA -> JPG + BG support for sorl thumbnails.

from PIL import Image

png = Image.open(object.logo.path)
png.load() # required for png.split()

background = Image.new("RGB", png.size, (255, 255, 255))
background.paste(png, mask=png.split()[3]) # 3 is the alpha channel

background.save('foo.jpg', 'JPEG', quality=80)

Result @80%

enter image description here

Result @ 50%
enter image description here

Android webview & localStorage

if you have multiple webview, localstorage does not work correctly.
two suggestion:

  1. using java database instead webview localstorage that " @Guillaume Gendre " explained.(of course it does not work for me)
  2. local storage work like json,so values store as "key:value" .you can add your browser unique id to it's key and using normal android localstorage

Sending XML data using HTTP POST with PHP

Another option would be file_get_contents():

// $xml_str = your xml
// $url = target url

$post_data = array('xml' => $xml_str);
$stream_options = array(
    'http' => array(
        'method'  => 'POST',
        'header'  => 'Content-type: application/x-www-form-urlencoded' . "\r\n",
        'content' =>  http_build_query($post_data)));

$context  = stream_context_create($stream_options);
$response = file_get_contents($url, null, $context);

Adding additional data to select options using jQuery

HTML

<Select id="SDistrict" class="form-control">
    <option value="1" data-color="yellow" > Mango </option>
</select>

JS when initialized

   $('#SDistrict').selectize({
        create: false,
        sortField: 'text',
        onInitialize: function() {
            var s = this;
            this.revertSettings.$children.each(function() {
                $.extend(s.options[this.value], $(this).data());
            });
        },
        onChange: function(value) {
            var option = this.options[value];
            alert(option.text + ' color is ' + option.color);
        }
    });

You can access data attribute of option tag with option.[data-attribute]

JS Fiddle : https://jsfiddle.net/shashank_p/9cqoaeyt/3/

Functional style of Java 8's Optional.ifPresent and if-not-Present?

In case you want store the value:

Pair.of<List<>, List<>> output = opt.map(details -> Pair.of(details.a, details.b))).orElseGet(() -> Pair.of(Collections.emptyList(), Collections.emptyList()));

Sql server - log is full due to ACTIVE_TRANSACTION

Restarting the SQL Server will clear up the log space used by your database. If this however is not an option, you can try the following:

* Issue a CHECKPOINT command to free up log space in the log file.

* Check the available log space with DBCC SQLPERF('logspace'). If only a small 
  percentage of your log file is actually been used, you can try a DBCC SHRINKFILE 
  command. This can however possibly introduce corruption in your database. 

* If you have another drive with space available you can try to add a file there in 
  order to get enough space to attempt to resolve the issue.

Hope this will help you in finding your solution.

Log4j, configuring a Web App to use a relative path

As a further comment on https://stackoverflow.com/a/218037/2279200 - this may break, if the web app implicitely starts other ServletContextListener's, which may get called earlier and which already try to use log4j - in this case, the log4j configuration will be read and parsed already before the property determining the log root directory is set => the log files will appear somewhere below the current directory (the current directory when starting tomcat).

I could only think of following solution to this problem: - rename your log4j.properties (or logj4.xml) file to something which log4j will not automatically read. - In your context filter, after setting the property, call the DOM/PropertyConfigurator helper class to ensure that your log4j-.{xml,properties} is read - Reset the log4j configuration (IIRC there is a method to do that)

This is a bit brute force, but methinks it is the only way to make it watertight.

JavaScript alert not working in Android WebView

The following code will work:

private WebView mWebView;
final Activity activity = this;

// private Button b;
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    mWebView = (WebView) findViewById(R.id.webview);
    mWebView.getSettings().setJavaScriptEnabled(true);
    mWebView.getSettings().setDomStorageEnabled(true);
    mWebView.setWebChromeClient(new WebChromeClient() {
        public void onProgressChanged(WebView view, int progress) {
            activity.setProgress(progress * 1000);
        }
    });

    mWebView.loadUrl("file:///android_asset/raw/NewFile1.html");
}

How to hide Android soft keyboard on EditText

Three ways based on the same simple instruction:

a). Results as easy as locate (1):

android:focusableInTouchMode="true"

among the configuration of any precedent element in the layout, example:

if your whole layout is composed of:

<ImageView>

<EditTextView>

<EditTextView>

<EditTextView>

then you can write the (1) among ImageView parameters and this will grab android's attention to the ImageView instead of the EditText.

b). In case you have another precedent element than an ImageView you may need to add (2) to (1) as:

android:focusable="true"

c). you can also simply create an empty element at the top of your view elements:

<LinearLayout
  android:focusable="true"
  android:focusableInTouchMode="true"
  android:layout_width="0px"
  android:layout_height="0px" />

This alternative until this point results as the simplest of all I've seen. Hope it helps...

How to cherry pick from 1 branch to another

When you cherry-pick, it creates a new commit with a new SHA. If you do:

git cherry-pick -x <sha>

then at least you'll get the commit message from the original commit appended to your new commit, along with the original SHA, which is very useful for tracking cherry-picks.

How can I throw a general exception in Java?

It depends. You can throw a more general exception, or a more specific exception. For simpler methods, more general exceptions are enough. If the method is complex, then, throwing a more specific exception will be reliable.

How to do SQL Like % in Linq?

System.Data.Linq.SqlClient.SqlMethods.Like("mystring", "%string")

Using SQL LOADER in Oracle to import CSV file

You need to designate the logfile name when calling the sql loader.

sqlldr myusername/mypassword control=Billing.ctl log=Billing.log

I was running into this problem when I was calling sql loader from inside python. The following article captures all the parameters you can designate when calling sql loader http://docs.oracle.com/cd/A97630_01/server.920/a96652/ch04.htm

JNI converting jstring to char *

Here's a a couple of useful link that I found when I started with JNI

http://en.wikipedia.org/wiki/Java_Native_Interface
http://download.oracle.com/javase/1.5.0/docs/guide/jni/spec/functions.html

concerning your problem you can use this

JNIEXPORT void JNICALL Java_ClassName_MethodName(JNIEnv *env, jobject obj, jstring javaString)   
{
   const char *nativeString = env->GetStringUTFChars(javaString, 0);

   // use your string

   env->ReleaseStringUTFChars(javaString, nativeString);
}

Making RGB color in Xcode

You already got the right answer, but if you dislike the UIColor interface like me, you can do this:

#import "UIColor+Helper.h"
// ...
myLabel.textColor = [UIColor colorWithRGBA:0xA06105FF];

UIColor+Helper.h:

#import <UIKit/UIKit.h>

@interface UIColor (Helper)
+ (UIColor *)colorWithRGBA:(NSUInteger)color;
@end

UIColor+Helper.m:

#import "UIColor+Helper.h"

@implementation UIColor (Helper)

+ (UIColor *)colorWithRGBA:(NSUInteger)color
{
    return [UIColor colorWithRed:((color >> 24) & 0xFF) / 255.0f
                           green:((color >> 16) & 0xFF) / 255.0f
                            blue:((color >> 8) & 0xFF) / 255.0f
                           alpha:((color) & 0xFF) / 255.0f];
}

@end

Android Button setOnClickListener Design

Implement Activity with View.OnClickListener like below.

public class MyActivity extends AppCompatActivity implements View.OnClickListener {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_scan_options);

        Button button = findViewById(R.id.button);
        Button button2 = findViewById(R.id.button2);

        button.setOnClickListener(this);
        button2.setOnClickListener(this);
    }

    @Override
    public void onClick(View view) {

        int id = view.getId();

        switch (id) {

            case R.id.button:

                  // Write your code here first button

                break;

             case R.id.button2:

                  // Write your code here for second button

                break;

        }

    }

}

Adding images to an HTML document with javascript

Get rid of the this statements too

var img = document.createElement("img");
img.src = "img/eqp/"+this.apparel+"/"+this.facing+"_idle.png";
src = document.getElementById("gamediv");
src.appendChild(this.img)

How to hide element label by element id in CSS?

You have to give a separate id to the label too.

<label for="foo" id="foo_label">text</label>

#foo_label {display: none;}

Or hide the whole row

<tr id="foo_row">/***/</tr>

#foo_row {display: none;}

remove first element from array and return the array minus the first element

Try this

    var myarray = ["item 1", "item 2", "item 3", "item 4"];

    //removes the first element of the array, and returns that element apart from item 1.
    myarray.shift(); 
    console.log(myarray); 

Redefine tab as 4 spaces

or shorthand for vim modeline:

vim :set ts=4 sw=4 sts=4 et :

How do I make a checkbox required on an ASP.NET form?

Scott's answer will work for classes of checkboxes. If you want individual checkboxes, you have to be a little sneakier. If you're just doing one box, it's better to do it with IDs. This example does it by specific check boxes and doesn't require jQuery. It's also a nice little example of how you can get those pesky control IDs into your Javascript.

The .ascx:

<script type="text/javascript">

    function checkAgreement(source, args)
    {                
        var elem = document.getElementById('<%= chkAgree.ClientID %>');
        if (elem.checked)
        {
            args.IsValid = true;
        }
        else
        {        
            args.IsValid = false;
        }
    }

    function checkAge(source, args)
    {
        var elem = document.getElementById('<%= chkAge.ClientID %>');
        if (elem.checked)
        {
            args.IsValid = true;
        }
        else
        {
            args.IsValid = false;
        }    
    }

</script>

<asp:CheckBox ID="chkAgree" runat="server" />
<asp:Label AssociatedControlID="chkAgree" runat="server">I agree to the</asp:Label>
<asp:HyperLink ID="lnkTerms" runat="server">Terms & Conditions</asp:HyperLink>
<asp:Label AssociatedControlID="chkAgree" runat="server">.</asp:Label>
<br />

<asp:CustomValidator ID="chkAgreeValidator" runat="server" Display="Dynamic"
    ClientValidationFunction="checkAgreement">
    You must agree to the terms and conditions.
    </asp:CustomValidator>

<asp:CheckBox ID="chkAge" runat="server" />
<asp:Label AssociatedControlID="chkAge" runat="server">I certify that I am at least 18 years of age.</asp:Label>        
<asp:CustomValidator ID="chkAgeValidator" runat="server" Display="Dynamic"
    ClientValidationFunction="checkAge">
    You must be 18 years or older to continue.
    </asp:CustomValidator>

And the codebehind:

Protected Sub chkAgreeValidator_ServerValidate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ServerValidateEventArgs) _
Handles chkAgreeValidator.ServerValidate
    e.IsValid = chkAgree.Checked
End Sub

Protected Sub chkAgeValidator_ServerValidate(ByVal sender As Object, ByVal e As System.Web.UI.WebControls.ServerValidateEventArgs) _
Handles chkAgeValidator.ServerValidate
    e.IsValid = chkAge.Checked
End Sub

Sql Server equivalent of a COUNTIF aggregate function

I would use this syntax. It achives the same as Josh and Chris's suggestions, but with the advantage it is ANSI complient and not tied to a particular database vendor.

select count(case when myColumn = 1 then 1 else null end)
from   AD_CurrentView

Angular JS: Full example of GET/POST/DELETE/PUT client for a REST/CRUD backend?

Because your update uses PUT method, {entryId: $scope.entryId} is considered as data, to tell angular generate from the PUT data, you need to add params: {entryId: '@entryId'} when you define your update, which means

return $resource('http://localhost\\:3000/realmen/:entryId', {}, {
  query: {method:'GET', params:{entryId:''}, isArray:true},
  post: {method:'POST'},
  update: {method:'PUT', params: {entryId: '@entryId'}},
  remove: {method:'DELETE'}
});

Fix: Was missing a closing curly brace on the update line.

numpy.where() detailed, step-by-step explanation / examples

After fiddling around for a while, I figured things out, and am posting them here hoping it will help others.

Intuitively, np.where is like asking "tell me where in this array, entries satisfy a given condition".

>>> a = np.arange(5,10)
>>> np.where(a < 8)       # tell me where in a, entries are < 8
(array([0, 1, 2]),)       # answer: entries indexed by 0, 1, 2

It can also be used to get entries in array that satisfy the condition:

>>> a[np.where(a < 8)] 
array([5, 6, 7])          # selects from a entries 0, 1, 2

When a is a 2d array, np.where() returns an array of row idx's, and an array of col idx's:

>>> a = np.arange(4,10).reshape(2,3)
array([[4, 5, 6],
       [7, 8, 9]])
>>> np.where(a > 8)
(array(1), array(2))

As in the 1d case, we can use np.where() to get entries in the 2d array that satisfy the condition:

>>> a[np.where(a > 8)] # selects from a entries 0, 1, 2

array([9])


Note, when a is 1d, np.where() still returns an array of row idx's and an array of col idx's, but columns are of length 1, so latter is empty array.

How to fit Windows Form to any screen resolution?

Set the form property to open in maximized state.

this.WindowState = FormWindowState.Maximized;

Jenkins pipeline if else not working

your first try is using declarative pipelines, and the second working one is using scripted pipelines. you need to enclose steps in a steps declaration, and you can't use if as a top-level step in declarative, so you need to wrap it in a script step. here's a working declarative version:

pipeline {
    agent any

    stages {
        stage('test') {
            steps {
                sh 'echo hello'
            }
        }
        stage('test1') {
            steps {
                sh 'echo $TEST'
            }
        }
        stage('test3') {
            steps {
                script {
                    if (env.BRANCH_NAME == 'master') {
                        echo 'I only execute on the master branch'
                    } else {
                        echo 'I execute elsewhere'
                    }
                }
            }
        }
    }
}

you can simplify this and potentially avoid the if statement (as long as you don't need the else) by using "when". See "when directive" at https://jenkins.io/doc/book/pipeline/syntax/. you can also validate jenkinsfiles using the jenkins rest api. it's super sweet. have fun with declarative pipelines in jenkins!

If...Then...Else with multiple statements after Then

Multiple statements are to be separated by a new line:

If SkyIsBlue Then
  StartEngines
  Pollute
ElseIf SkyIsRed Then
  StopAttack
  Vent
ElseIf SkyIsYellow Then
  If Sunset Then
    Sleep
  ElseIf Sunrise or IsMorning Then
    Smoke
    GetCoffee
  Else
    Error
  End If
Else
  Joke
  Laugh
End If

Differences between MySQL and SQL Server

Frankly, I can't find a single reason to use MySQL rather than MSSQL. The issue before used to be cost but SQL Server 2005 Express is free and there are lots of web hosting companies which offer full hosting with sql server for less than $5.00 a month.

MSSQL is easier to use and has many features which do not exist in MySQL.

How do I get the type of a variable?

If you have a variable

int k;

You can get its type using

cout << typeid(k).name() << endl;

See the following thread on SO: Similar question

PostgreSQL: export resulting data from SQL query to Excel/CSV

Several GUI tools like Squirrel, SQL Workbench/J, AnySQL, ExecuteQuery can export to Excel files.

Most of those tools are listed in the PostgreSQL wiki:

http://wiki.postgresql.org/wiki/Community_Guide_to_PostgreSQL_GUI_Tools

How to position two elements side by side using CSS

Like this

.block {
    display: inline-block;
    vertical-align:top;
}

JSFiddle Demo

Android dependency has different version for the compile and runtime

Switching my conflicting dependencies from implementation to api does the trick. Here's a good article by mindorks explaining the difference.

https://medium.com/mindorks/implementation-vs-api-in-gradle-3-0-494c817a6fa

Edit:

Here's my dependency resolutions as well

 subprojects {
        project.configurations.all {
            resolutionStrategy.eachDependency { details ->
                if (details.requested.group == 'com.android.support'
                        && !details.requested.name.contains('multidex')) {
                    details.useVersion "28.0.0"
                }
                if (details.requested.group == 'com.google.android.gms'
                        && details.requested.name.contains('play-services-base')) {
                    details.useVersion "15.0.1"
                }
                if (details.requested.group == 'com.google.android.gms'
                        && details.requested.name.contains('play-services-tasks')) {
                    details.useVersion "15.0.1"
                }
            }
        }
    }

How to use 'git pull' from the command line?

Open up your git bash and type

echo $HOME

This shall be the same folder as you get when you open your command window (cmd) and type

echo %USERPROFILE%

And – of course – the .ssh folder shall be present on THAT directory.