Programs & Examples On #Gaelyk

Gaelyk is a lightweight Groovy toolkit for Google App Engine Java.

What's the CMake syntax to set and use variables?

Here are a couple basic examples to get started quick and dirty.

One item variable

Set variable:

SET(INSTALL_ETC_DIR "etc")

Use variable:

SET(INSTALL_ETC_CROND_DIR "${INSTALL_ETC_DIR}/cron.d")

Multi-item variable (ie. list)

Set variable:

SET(PROGRAM_SRCS
        program.c
        program_utils.c
        a_lib.c
        b_lib.c
        config.c
        )

Use variable:

add_executable(program "${PROGRAM_SRCS}")

CMake docs on variables

Get IP address of visitors using Flask for Python

Proxies can make this a little tricky, make sure to check out ProxyFix (Flask docs) if you are using one. Take a look at request.environ in your particular environment. With nginx I will sometimes do something like this:

from flask import request   
request.environ.get('HTTP_X_REAL_IP', request.remote_addr)   

When proxies, such as nginx, forward addresses, they typically include the original IP somewhere in the request headers.

Update See the flask-security implementation. Again, review the documentation about ProxyFix before implementing. Your solution may vary based on your particular environment.

How to reload current page without losing any form data?

window.location.reload() // without passing true as argument

works for me.

Image style height and width not taken in outlook mails

make the image the exact size needed in the email. Windows MSO has a hard time resizing images in different scenarios.

in the case of using a 1px by 1px transparent png or gif as a spacer, defining the dimensions via width, height, or style attributes will work as expected in the majority of clients, but not windows MSO (of course).

example use case - you are using a background image and need to position a with a link inside over some part of the background image. Using a 1px by 1px spacer gif/png will only expand so wide (about 30px). You need size the spacer to the exact dimensions.

Spark difference between reduceByKey vs groupByKey vs aggregateByKey vs combineByKey

Then apart from these 4, we have

foldByKey which is same as reduceByKey but with a user defined Zero Value.

AggregateByKey takes 3 parameters as input and uses 2 functions for merging(one for merging on same partitions and another to merge values across partition. The first parameter is ZeroValue)

whereas

ReduceBykey takes 1 parameter only which is a function for merging.

CombineByKey takes 3 parameter and all 3 are functions. Similar to aggregateBykey except it can have a function for ZeroValue.

GroupByKey takes no parameter and groups everything. Also, it is an overhead for data transfer across partitions.

XMLHttpRequest cannot load an URL with jQuery

Fiddle with 3 working solutions in action.

Given an external JSON:

myurl = 'http://wikidata.org/w/api.php?action=wbgetentities&sites=frwiki&titles=France&languages=zh-hans|zh-hant|fr&props=sitelinks|labels|aliases|descriptions&format=json'

Solution 1: $.ajax() + jsonp:

$.ajax({
  dataType: "jsonp",
  url: myurl ,
  }).done(function ( data ) {
  // do my stuff
});

Solution 2: $.ajax()+json+&calback=?:

$.ajax({
  dataType: "json",
  url: myurl + '&callback=?',
  }).done(function ( data ) {
  // do my stuff
});

Solution 3: $.getJSON()+calback=?:

$.getJSON( myurl + '&callback=?', function(data) {
  // do my stuff
});

Documentations: http://api.jquery.com/jQuery.ajax/ , http://api.jquery.com/jQuery.getJSON/

Making div content responsive

Not a lot to go on there, but I think what you're looking for is to flip the width and max-width values:

#container2 {
  width: 90%;
  max-width: 960px;
  /* etc, etc... */
}

That'll give you a container that's 90% of the width of the available space, up to a maximum of 960px, but that's dependent on its container being resizable itself. Responsive design is a whole big ball of wax though, so this doesn't even scratch the surface.

How to remove \xa0 from string in Python?

try this:

string.replace('\\xa0', ' ')

Read only the first line of a file?

f1 = open("input1.txt", "r")
print(f1.readline())

redirect while passing arguments

I found that none of the answers here applied to my specific use case, so I thought I would share my solution.

I was looking to redirect an unauthentciated user to public version of an app page with any possible URL params. Example:

/app/4903294/my-great-car?email=coolguy%40gmail.com to

/public/4903294/my-great-car?email=coolguy%40gmail.com

Here's the solution that worked for me.

return redirect(url_for('app.vehicle', vid=vid, year_make_model=year_make_model, **request.args))

Hope this helps someone!

Material effect on button with background color

I used the backgroundTint and foreground:

<Button
    android:layout_width="match_parent"
    android:layout_height="40dp"
    android:backgroundTint="@color/colorAccent"
    android:foreground="?android:attr/selectableItemBackground"
    android:textColor="@android:color/white"
    android:textSize="10sp"/>

Where do alpha testers download Google Play Android apps?

Under APK/ALPHA TESTING/MANAGE TESTERS you find: enter image description here

Choose the method you want. Then you need to first upload your Apk. Before it can be published you need to go to the usual steps in publishing which means: you need icons, the FSK ratings, screenshots etc.

After you added it you click on publish.

You find the link for your testers at:

enter image description here

Node.js setting up environment specific configs to be used with everyauth

An elegant way is to use .env file to locally override production settings. No need for command line switches. No need for all those commas and brackets in a config.json file. See my answer here

Example: on my machine the .env file is this:

NODE_ENV=dev
TWITTER_AUTH_TOKEN=something-needed-for-api-calls

My local .env overrides any environment variables. But on the staging or production servers (maybe they're on heroku.com) the environment variables are pre-set to stage NODE_ENV=stage or production NODE_ENV=prod.

How to save the contents of a div as a image?

There are several of this same question (1, 2). One way of doing it is using canvas. Here's a working solution. Here you can see some working examples of using this library.

How should I log while using multiprocessing in Python?

just publish somewhere your instance of the logger. that way, the other modules and clients can use your API to get the logger without having to import multiprocessing.

jQuery set checkbox checked

"checked" attribute 'ticks' the checkbox as soon as it exists. So to check/uncheck a checkbox you have to set/unset the attribute.

For checking the box:

$('#myCheckbox').attr('checked', 'checked');

For unchecking the box:

$('#myCheckbox').removeAttr('checked');

For testing the checked status:

if ($('#myCheckbox').is(':checked'))

Hope it helps...

lambda expression join multiple tables with select and where clause

If I understand your questions correctly, all you need to do is add the .Where(m => m.r.u.UserId == 1):

    var UserInRole = db.UserProfiles.
        Join(db.UsersInRoles, u => u.UserId, uir => uir.UserId,
        (u, uir) => new { u, uir }).
        Join(db.Roles, r => r.uir.RoleId, ro => ro.RoleId, (r, ro) => new { r, ro })
        .Where(m => m.r.u.UserId == 1)
        .Select (m => new AddUserToRole
        {
            UserName = m.r.u.UserName,
            RoleName = m.ro.RoleName
        });

Hope that helps.

Writing a new line to file in PHP (line feed)

Use PHP_EOL which outputs \r\n or \n depending on the OS.

PyCharm shows unresolved references error for valid code

In PyCharm 2020.1.4 (Community Edition) on Windows 10 10.0. Under Settings in PyCharm: File > Settings > Project Structure I made two changes in Project Structure: main folder marked as source and odoo folder with all applications I excluded Screenshot shows what I did. After that I restarted PyCharm: File > Invalidate Caches / Restart...

Unresolved references error was removed project structure

Unresolved references error

Print array elements on separate lines in Bash?

Try doing this :

$ printf '%s\n' "${my_array[@]}"

The difference between $@ and $*:

  • Unquoted, the results are unspecified. In Bash, both expand to separate args and then wordsplit and globbed.

  • Quoted, "$@" expands each element as a separate argument, while "$*" expands to the args merged into one argument: "$1c$2c..." (where c is the first char of IFS).

You almost always want "$@". Same goes for "${arr[@]}".

Always quote them!

Including dependencies in a jar with Maven

        <!-- Method 1 -->
        <!-- Copy dependency libraries jar files to a separated LIB folder -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-dependency-plugin</artifactId>
            <configuration>
                <outputDirectory>${project.build.directory}/lib</outputDirectory>
                <excludeTransitive>false</excludeTransitive> 
                <stripVersion>false</stripVersion>
            </configuration>
            <executions>
                <execution>
                    <id>copy-dependencies</id>
                    <phase>package</phase>
                    <goals>
                        <goal>copy-dependencies</goal>
                    </goals>
                </execution>
            </executions>
        </plugin>
        <!-- Add LIB folder to classPath -->
        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-jar-plugin</artifactId>
            <version>2.4</version>
            <configuration>
                <archive>
                    <manifest>
                        <addClasspath>true</addClasspath>
                        <classpathPrefix>lib/</classpathPrefix>
                    </manifest>
                </archive>
            </configuration>
        </plugin>


        <!-- Method 2 -->
        <!-- Package all libraries classes into one runnable jar -->
        <plugin>
            <artifactId>maven-assembly-plugin</artifactId>
            <executions>
              <execution>
                <phase>package</phase>
                <goals>
                  <goal>single</goal>
                </goals>
              </execution>
            </executions>
            <configuration>
              <descriptorRefs>
                <descriptorRef>jar-with-dependencies</descriptorRef>
              </descriptorRefs>
            </configuration>
        </plugin>            

How to display default text "--Select Team --" in combo box on pageload in WPF?

EDIT: Per comments below, this is not a solution. Not sure how I had it working, and can't check that project.

It's time to update this answer for the latest XAML.

Finding this SO question searching for a solution to this question, I then found that the updated XAML spec has a simple solution.

An attribute called "Placeholder" is now available to accomplish this task. It is as simple as this (in Visual Studio 2015):

<ComboBox x:Name="Selection" PlaceholderText="Select...">
    <x:String>Item 1</x:String>
    <x:String>Item 2</x:String>
    <x:String>Item 3</x:String>
</ComboBox>

Replace first occurrence of string in Python

string replace() function perfectly solves this problem:

string.replace(s, old, new[, maxreplace])

Return a copy of string s with all occurrences of substring old replaced by new. If the optional argument maxreplace is given, the first maxreplace occurrences are replaced.

>>> u'longlongTESTstringTEST'.replace('TEST', '?', 1)
u'longlong?stringTEST'

How to unmount, unrender or remove a component, from itself in a React/Redux/Typescript notification message

instead of using

ReactDOM.unmountComponentAtNode(ReactDOM.findDOMNode(this).parentNode);

try using

ReactDOM.unmountComponentAtNode(document.getElementById('root'));

How to make remote REST call inside Node.js? any CURL?

var http = require('http');
var url = process.argv[2];

http.get(url, function(response) {
  var finalData = "";

  response.on("data", function (data) {
    finalData += data.toString();
  });

  response.on("end", function() {
    console.log(finalData.length);
    console.log(finalData.toString());
  });

});

What is a 'NoneType' object?

One of the variables has not been given any value, thus it is a NoneType. You'll have to look into why this is, it's probably a simple logic error on your part.

Get path from open file in Python

I had the exact same issue. If you are using a relative path os.path.dirname(path) will only return the relative path. os.path.realpath does the trick:

>>> import os
>>> f = open('file.txt')
>>> os.path.realpath(f.name)

Copy folder recursively in Node.js

This is how I did it:

let fs = require('fs');
let path = require('path');

Then:

let filePath = // Your file path

let fileList = []
    var walkSync = function(filePath, filelist)
    {
        let files = fs.readdirSync(filePath);
        filelist = filelist || [];
        files.forEach(function(file)
        {
            if (fs.statSync(path.join(filePath, file)).isDirectory())
            {
                filelist = walkSync(path.join(filePath, file), filelist);
            }
            else
            {
                filelist.push(path.join(filePath, file));
            }
        });

        // Ignore hidden files
        filelist = filelist.filter(item => !(/(^|\/)\.[^\/\.]/g).test(item));

        return filelist;
    };

Then call the method:

This.walkSync(filePath, fileList)

CSS Border Not Working

The height is a 100% unsure, try putting display: block; or display: inline-block;

How to replace multiple substrings of a string?

Note: Test your case, see comments.

Here's a sample which is more efficient on long strings with many small replacements.

source = "Here is foo, it does moo!"

replacements = {
    'is': 'was', # replace 'is' with 'was'
    'does': 'did',
    '!': '?'
}

def replace(source, replacements):
    finder = re.compile("|".join(re.escape(k) for k in replacements.keys())) # matches every string we want replaced
    result = []
    pos = 0
    while True:
        match = finder.search(source, pos)
        if match:
            # cut off the part up until match
            result.append(source[pos : match.start()])
            # cut off the matched part and replace it in place
            result.append(replacements[source[match.start() : match.end()]])
            pos = match.end()
        else:
            # the rest after the last match
            result.append(source[pos:])
            break
    return "".join(result)

print replace(source, replacements)

The point is in avoiding many concatenations of long strings. We chop the source string to fragments, replacing some of the fragments as we form the list, and then join the whole thing back into a string.

Convert seconds to Hour:Minute:Second

$given = 685;

 /*
 * In case $given == 86400, gmdate( "H" ) will convert it into '00' i.e. midnight.
 * We would need to take this into consideration, and so we will first
 * check the ratio of the seconds i.e. $given:$number_of_sec_in_a_day
 * and then after multiplying it by the number of hours in a day (24), we
 * will just use "floor" to get the number of hours as the rest would
 * be the minutes and seconds anyways.
 *
 * We can also have minutes and seconds combined in one variable,
 * e.g. $min_sec = gmdate( "i:s", $given );
 * But for versatility sake, I have taken them separately.
 */

$hours = ( $given > 86399 ) ? '0'.floor( ( $given / 86400 ) * 24 )-gmdate( "H", $given ) : gmdate("H", $given );

$min = gmdate( "i", $given );

$sec = gmdate( "s", $given );

echo $formatted_string = $hours.':'.$min.':'.$sec;

To convert it into a function:

function getHoursFormat( $given ){

 $hours = ( $given > 86399 ) ? '0'.floor( ( $given / 86400 ) * 24 )-gmdate( "H", $given ) : gmdate("H", $given );

 $min = gmdate( "i", $given );

 $sec = gmdate( "s", $given );

 $formatted_string = $hours.':'.$min.':'.$sec;

 return $formatted_string;

}

How do I trim() a string in angularjs?

use trim() method of javascript after all angularjs is also a javascript framework and it is not necessary to put $ to apply trim()

for example

var x="hello world";
x=x.trim()

Android Gradle Apache HttpClient does not exist?

if you are using target sdk as 23 add below code in your build.gradle

android{
    compileSdkVersion 23
    buildToolsVersion '23.0.1'
    useLibrary  'org.apache.http.legacy'
}

and change your buildscript to

classpath 'com.android.tools.build:gradle:1.3.0' 

for more info follow this link

Update built-in vim on Mac OS X

Like Eric, I used homebrew, but I used the default recipe. So:

brew install mercurial
brew install vim

And after restarting the terminal homebrew's vim should be the default. If not, you should update your $PATH so that /usr/local/bin is before /usr/bin. E.g. add the following to your .profile:

export PATH=/usr/local/bin:$PATH

Can I override and overload static methods in Java?

Static methods can not be overridden because there is nothing to override, as they would be two different methods. For example

static class Class1 {
    public static int Method1(){
          return 0;
    }
}
static class Class2 extends Class1 {
    public static int Method1(){
          return 1;
    }

}
public static class Main {
    public static void main(String[] args){
          //Must explicitly chose Method1 from Class1 or Class2
          Class1.Method1();
          Class2.Method1();
    }
}

And yes static methods can be overloaded just like any other method.

Set specific precision of a BigDecimal

 BigDecimal decPrec = (BigDecimal)yo.get("Avg");
 decPrec = decPrec.setScale(5, RoundingMode.CEILING);
 String value= String.valueOf(decPrec);

This way you can set specific precision of a BigDecimal.

The value of decPrec was 1.5726903423607562595809913132345426 which is rounded off to 1.57267.

No increment operator (++) in Ruby?

I don't think that notation is available because—unlike say PHP or C—everything in Ruby is an object.

Sure you could use $var=0; $var++ in PHP, but that's because it's a variable and not an object. Therefore, $var = new stdClass(); $var++ would probably throw an error.

I'm not a Ruby or RoR programmer, so I'm sure someone can verify the above or rectify it if it's inaccurate.

If table exists drop table then create it, if it does not exist just create it

Just put DROP TABLE IF EXISTS `tablename`; before your CREATE TABLE statement.

That statement drops the table if it exists but will not throw an error if it does not.

How to get method parameter names?

inspect.signature is very slow. Fastest way is

def f(a, b=1, *args, c, d=1, **kwargs):
   pass

f_code = f.__code__
f_code.co_varnames[:f_code.co_argcount + f_code.co_kwonlyargcount]  # ('a', 'b', 'c', 'd')

Does Python have a ternary conditional operator?

Does Python have a ternary conditional operator?

Yes. From the grammar file:

test: or_test ['if' or_test 'else' test] | lambdef

The part of interest is:

or_test ['if' or_test 'else' test]

So, a ternary conditional operation is of the form:

expression1 if expression2 else expression3

expression3 will be lazily evaluated (that is, evaluated only if expression2 is false in a boolean context). And because of the recursive definition, you can chain them indefinitely (though it may considered bad style.)

expression1 if expression2 else expression3 if expression4 else expression5 # and so on

A note on usage:

Note that every if must be followed with an else. People learning list comprehensions and generator expressions may find this to be a difficult lesson to learn - the following will not work, as Python expects a third expression for an else:

[expression1 if expression2 for element in iterable]
#                          ^-- need an else here

which raises a SyntaxError: invalid syntax. So the above is either an incomplete piece of logic (perhaps the user expects a no-op in the false condition) or what may be intended is to use expression2 as a filter - notes that the following is legal Python:

[expression1 for element in iterable if expression2]

expression2 works as a filter for the list comprehension, and is not a ternary conditional operator.

Alternative syntax for a more narrow case:

You may find it somewhat painful to write the following:

expression1 if expression1 else expression2

expression1 will have to be evaluated twice with the above usage. It can limit redundancy if it is simply a local variable. However, a common and performant Pythonic idiom for this use-case is to use or's shortcutting behavior:

expression1 or expression2

which is equivalent in semantics. Note that some style-guides may limit this usage on the grounds of clarity - it does pack a lot of meaning into very little syntax.

declaring a priority_queue in c++ with a custom comparator

The third template parameter must be a class who has operator()(Node,Node) overloaded. So you will have to create a class this way:

class ComparisonClass {
    bool operator() (Node, Node) {
        //comparison code here
    }
};

And then you will use this class as the third template parameter like this:

priority_queue<Node, vector<Node>, ComparisonClass> q;

Shuffling a list of objects

you can either use shuffle or sample . both of which come from random module.

import random
def shuffle(arr1):
    n=len(arr1)
    b=random.sample(arr1,n)
    return b

OR

import random
def shuffle(arr1):
    random.shuffle(arr1)
    return arr1

Could not transfer artifact org.apache.maven.plugins:maven-surefire-plugin:pom:2.7.1 from/to central (http://repo1.maven.org/maven2)

What helped me were the suggestions by @carlspring (create a settings.xml to configure your http proxy):

<?xml version="1.0" encoding="UTF-8"?>
<settings xmlns="http://maven.apache.org/SETTINGS/1.0.0" 
          xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" 
          xsi:schemaLocation="http://maven.apache.org/SETTINGS/1.0.0
                              http://maven.apache.org/xsd/settings-1.0.0.xsd">

 <proxies>
    <proxy>
      <id>myproxy</id>
      <active>true</active>
      <protocol>http</protocol>
      <username>user</username>  <!-- Put your username here -->
      <password>pass</password>  <!-- Put your password here -->
      <host>123.45.6.78</host>   <!-- Put the IP address of your proxy server here -->
      <port>80</port>            <!-- Put your proxy server's port number here -->
      <nonProxyHosts>local.net|some.host.com</nonProxyHosts> <!-- Do not use this setting unless you know what you're doing. -->
    </proxy>    
  </proxies> 
</settings>

AND then refreshing eclipse project maven as suggested by @Peter T :

"Force update of Snapshots/Releases" in Eclipse. this clears all errors. So right click on project -> Maven -> update project, then check the above option -> Ok. Hope this helps you.

What datatype to use when storing latitude and longitude data in SQL databases?

For longitudes use: Decimal(9,6), and latitudes use: Decimal(8,6)

If you're not used to precision and scale parameters, here's a format string visual:

###.###### and ##.######

How to remove all the punctuation in a string? (Python)

A really simple implementation is:

out = "".join(c for c in asking if c not in ('!','.',':'))

and keep adding any other types of punctuation.

A more efficient way would be

import string
stringIn = "string.with.punctuation!"
out = stringIn.translate(stringIn.maketrans("",""), string.punctuation)

Edit: There is some more discussion on efficiency and other implementations here: Best way to strip punctuation from a string in Python

Difference between database and schema

Schema says what tables are in database, what columns they have and how they are related. Each database has its own schema.

What values for checked and selected are false?

The checked and selected attributes are allowed only two values, which are a copy of the attribute name and (from HTML 5 onwards) an empty string. Giving any other value is an error.

If you don't want to set the attribute, then the entire attribute must be omitted.

Note that in HTML 4 you may omit everything except the value. HTML 5 changed this to omit everything except the name (which makes no practical difference).

Thus, the complete (aside from variations in cAsE) set of valid representations of the attribute are:

<input ... checked="checked"> <!-- All versions of HTML / XHTML -->
<input ...          checked > <!-- Only HTML 4.01 and earlier -->
<input ... checked          > <!-- Only HTML 5 and later -->
<input ... checked=""       > <!-- Only HTML 5 and later -->

Documents served as text/html (HTML or XHTML) will be fed through a tag soup parser, and the presence of a checked attribute (with any value) will be treated as "This element should be checked". Thus, while invalid, checked="true", checked="yes", and checked="false" will all trigger the checked state.

I've not had any inclination to find out what error recovery mechanisms are in place for XML parsing mode should a different value be given to the attribute, but I would expect that the legacy of HTML and/or simple error recovery would treat it in the same way: If the attribute is there then the element is checked.

(And all the above applies equally to selected as it does to checked.)

Difference between multitasking, multithreading and multiprocessing?

Multiprogramming: More than one task/program/job/process can reside into the main memory at one point of time. This ability of the OS is called multiprogramming.

Multitasking: More than one task/program/job/process can reside into the same CPU at one point of time. This ability of the OS is called multitasking.

Calling a JSON API with Node.js

I think that for simple HTTP requests like this it's better to use the request module. You need to install it with npm (npm install request) and then your code can look like this:

const request = require('request')
     ,url = 'http://graph.facebook.com/517267866/?fields=picture'

request(url, (error, response, body)=> {
  if (!error && response.statusCode === 200) {
    const fbResponse = JSON.parse(body)
    console.log("Got a response: ", fbResponse.picture)
  } else {
    console.log("Got an error: ", error, ", status code: ", response.statusCode)
  }
})

How to prevent auto-closing of console after the execution of batch file

besides pause.

set /p=

can be used .It will expect user input and will release the flow when enter is pressed.

or

runas /user:# "" >nul 2>&1

which will do the same except nothing from the user input will be displayed nor will remain in the command history.

How to export all data from table to an insertable sql format?

Command to get the database backup from linux machine terminal.

sqlcmd -S localhost -U SA -Q "BACKUP DATABASE [demodb] TO DISK = N'/var/opt/mssql/data/demodb.bak' WITH NOFORMAT, NOINIT, NAME = 'demodb-full', SKIP, NOREWIND, NOUNLOAD, STATS = 10"

Backup and restore SQL Server databases on Linux

open resource with relative path in Java

I made a small modification on @jonathan.cone's one liner ( by adding .getFile() ) to avoid null pointer exception, and setting the path to data directory. Here's what worked for me :

String realmID = new java.util.Scanner(new java.io.File(RandomDataGenerator.class.getClassLoader().getResource("data/aa-qa-id.csv").getFile().toString())).next();

The requested resource does not support HTTP method 'GET'

Please use the attributes from the System.Web.Http namespace on your WebAPI actions:

    [System.Web.Http.AcceptVerbs("GET", "POST")]
    [System.Web.Http.HttpGet]
    public string Auth(string username, string password)
    {...}

The reason why it doesn't work is because you were using the attributes that are from the MVC namespace System.Web.Mvc. The classes in the System.Web.Http namespace are for WebAPI.

How to connect to a remote Git repository?

Like you said remote_repo_url is indeed the IP of the server, and yes it needs to be added on each PC, but it's easier to understand if you create the server first then ask each to clone it.

There's several ways to connect to the server, you can use ssh, http, or even a network drive, each has it's pros and cons. You can refer to the documentation about protocols and how to connect to the server

You can check the rest of chapter 4 for more detailed information, as it's talking about how to set up your own server

Django Server Error: port is already in use

A more simple solution just type sudo fuser -k 8000/tcp. This should kill all the processes associated with port 8000.

EDIT:

For osx users you can use sudo lsof -t -i tcp:8000 | xargs kill -9

Maven error: Not authorized, ReasonPhrase:Unauthorized

The issue may happen while fetching dependencies from a remote repository. In my case, the repository did not need any authentication and it has been resolved by removing the servers section in the settings.xml file:

<servers>
    <server>
      <id>SomeRepo</id>
      <username>SomeUN</username>
      <password>SomePW</password>
    </server>
</servers>

ps: I guess your target is mvn clean install instead of maven install clean

What's the best practice using a settings file in Python?

The sample config you provided is actually valid YAML. In fact, YAML meets all of your demands, is implemented in a large number of languages, and is extremely human friendly. I would highly recommend you use it. The PyYAML project provides a nice python module, that implements YAML.

To use the yaml module is extremely simple:

import yaml
config = yaml.safe_load(open("path/to/config.yml"))

How do I handle Database Connections with Dapper in .NET?

It was asked about 4 years ago... but anyway, maybe the answer will be useful to someone here:

I do it like this in all the projects. First, I create a base class which contains a few helper methods like this:

public class BaseRepository
{
    protected T QueryFirstOrDefault<T>(string sql, object parameters = null)
    {
        using (var connection = CreateConnection())
        {
            return connection.QueryFirstOrDefault<T>(sql, parameters);
        }
    }

    protected List<T> Query<T>(string sql, object parameters = null)
    {
        using (var connection = CreateConnection())
        {
            return connection.Query<T>(sql, parameters).ToList();
        }
    }

    protected int Execute(string sql, object parameters = null)
    {
        using (var connection = CreateConnection())
        {
            return connection.Execute(sql, parameters);
        }
    }

    // Other Helpers...

    private IDbConnection CreateConnection()
    {
        var connection = new SqlConnection(...);
        // Properly initialize your connection here.
        return connection;
    }
}

And having such a base class I can easily create real repositories without any boilerplate code:

public class AccountsRepository : BaseRepository
{
    public Account GetById(int id)
    {
        return QueryFirstOrDefault<Account>("SELECT * FROM Accounts WHERE Id = @Id", new { id });
    }

    public List<Account> GetAll()
    {
        return Query<Account>("SELECT * FROM Accounts ORDER BY Name");
    }

    // Other methods...
}

So all the code related to Dapper, SqlConnection-s and other database access stuff is located in one place (BaseRepository). All real repositories are clean and simple 1-line methods.

I hope it will help someone.

Case-insensitive search

Suppose we want to find the string variable needle in the string variable haystack. There are three gotchas:

  1. Internationalized applications should avoid string.toUpperCase and string.toLowerCase. Use a regular expression which ignores case instead. For example, var needleRegExp = new RegExp(needle, "i"); followed by needleRegExp.test(haystack).
  2. In general, you might not know the value of needle. Be careful that needle does not contain any regular expression special characters. Escape these using needle.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&");.
  3. In other cases, if you want to precisely match needle and haystack, just ignoring case, make sure to add "^" at the start and "$" at the end of your regular expression constructor.

Taking points (1) and (2) into consideration, an example would be:

var haystack = "A. BAIL. Of. Hay.";
var needle = "bail.";
var needleRegExp = new RegExp(needle.replace(/[-[\]{}()*+?.,\\^$|#\s]/g, "\\$&"), "i");
var result = needleRegExp.test(haystack);
alert(result);

Declaring a custom android UI element using XML

It seems that Google has updated its developer page and added various trainings there.

One of them deals with the creation of custom views and can be found here

How can I get a process handle by its name in C++?

If you don't mind using system(), doing system("taskkill /f /im process.exe") would be significantly easier than these other methods.

Get the size of a 2D array

Expanding on what Mark Elliot said earlier, the easiest way to get the size of a 2D array given that each array in the array of arrays is of the same size is:

array.length * array[0].length

Setting background-image using jQuery CSS property

$('myObject').css({'background-image': 'url(imgUrl)',});

How to $http Synchronous call with AngularJS

I recently ran into a situation where I wanted to make to $http calls triggered by a page reload. The solution I went with:

  1. Encapsulate the two calls into functions
  2. Pass the second $http call as a callback into the second function
  3. Call the second function in apon .success

How to initialize List<String> object in Java?

List is an Interface, you cannot instantiate an Interface, because interface is a convention, what methods should have your classes. In order to instantiate, you need some realizations(implementations) of that interface. Try the below code with very popular implementations of List interface:

List<String> supplierNames = new ArrayList<String>(); 

or

List<String> supplierNames = new LinkedList<String>();

Change a Rails application to production

By default server runs on development environment: $ rails s

If you're running on production environment: $ rails s -e production or $ RAILS_ENV=production rails s

ASP.net page without a code behind

File: logdate.aspx

<%@ Page Language="c#" %>
<%@ Import namespace="System.IO"%>
<%

StreamWriter tsw = File.AppendText(@Server.MapPath("./test.txt"));
tsw.WriteLine("--------------------------------");
tsw.WriteLine(DateTime.Now.ToString());

tsw.Close();
%>

Done

Can I set the height of a div based on a percentage-based width?

This can be done with a CSS hack (see the other answers), but it can also be done very easily with JavaScript.

Set the div's width to (for example) 50%, use JavaScript to check its width, and then set the height accordingly. Here's a code example using jQuery:

_x000D_
_x000D_
$(function() {_x000D_
    var div = $('#dynamicheight');_x000D_
    var width = div.width();_x000D_
    _x000D_
    div.css('height', width);_x000D_
});
_x000D_
#dynamicheight_x000D_
{_x000D_
    width: 50%;_x000D_
    _x000D_
    /* Just for looks: */_x000D_
    background-color: cornflowerblue;_x000D_
    margin: 25px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="dynamicheight"></div>
_x000D_
_x000D_
_x000D_

If you want the box to scale with the browser window on resize, move the code to a function and call it on the window resize event. Here's a demonstration of that too (view example full screen and resize browser window):

_x000D_
_x000D_
$(window).ready(updateHeight);_x000D_
$(window).resize(updateHeight);_x000D_
_x000D_
function updateHeight()_x000D_
{_x000D_
    var div = $('#dynamicheight');_x000D_
    var width = div.width();_x000D_
    _x000D_
    div.css('height', width);_x000D_
}
_x000D_
#dynamicheight_x000D_
{_x000D_
    width: 50%;_x000D_
    _x000D_
    /* Just for looks: */_x000D_
    background-color: cornflowerblue;_x000D_
    margin: 25px;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.1/jquery.min.js"></script>_x000D_
_x000D_
<div id="dynamicheight"></div>
_x000D_
_x000D_
_x000D_

Qt 5.1.1: Application failed to start because platform plugin "windows" is missing

The release is likely missing a library/plugin or the library is in the wrong directory and or from the wrong directory.

Qt intended answer: Use windeployqt. see last paragraph for explanation

Manual answer:

Create a folder named "platforms" in the same directory as your application.exe file. Copy and paste the qwindows.dll, found in the /bin of whichever compiler you used to release your application, into the "platforms" folder. Like magic it works. If the .dll is not there check plugins/platforms/ ( with plugins/ being in the same directory as bin/ ) <-- PfunnyGuy's comment.

It seems like a common issue is that the .dll was taken from the wrong compiler bin. Be sure to copy your the qwindows.dll from the same compiler as the one used to release your app.

Qt comes with platform console applications that will add all dependencies (including ones like qwindows.dll and libEGL.dll) into the folder of your deployed executable. This is the intended way to deploy your application, so you do not miss any libraries (which is the main issue with all of these answers). The application for windows is called windeployqt. There is likely a deployment console app for each OS.

Get today date in google appScript

The Date object is used to work with dates and times.

Date objects are created with new Date()

var now = new Date();

now - Current date and time object.

function changeDate() {
    var sheet = SpreadsheetApp.getActiveSpreadsheet().getSheetByName(GA_CONFIG);
    var date = new Date();
    sheet.getRange(5, 2).setValue(date); 
}

Does functional programming replace GoF design patterns?

Here's another link, discussing this topic: http://blog.ezyang.com/2010/05/design-patterns-in-haskel/

In his blog post Edward describes all 23 original GoF patterns in terms of Haskell.

Oracle SQL Developer: Unable to find a JVM

If you have a 64-bit version of SQL Developer, but for some reason your default JDK is a 32-bit JDK (e.g. if you develop an Eclipse RCP application which requires a 32-bit JDK), then you have to set the value of the SetJavaHome property in the product.conf file to a 64-bit version of JDK in order to run the SQL Developer. For example:

SetJavaHome C:\Program Files\Java\jdk1.7.0_80

The product.conf file is in my case located in the following directory:

C:\Users\username\AppData\Roaming\sqldeveloper\1.0.0.0.0

The solution described above worked in my case. The solutions of @evgenyl and @FGreg did not work in my case.

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

I had problem to catch "shown.bs.modal" event.. And this is my solution which works perfect..

Instead simple on():

$('#modal').on 'shown.bs.modal', ->

Use on() with delegated element:

$('body').on 'shown.bs.modal', '#modal', ->

Get key from a HashMap using the value

if you what to obtain "ONE" by giving in 100 then

initialize hash map by

hashmap = new HashMap<Object,String>();

haspmap.put(100,"one");

and retrieve value by hashMap.get(100)

hope that helps.

Cloud Firestore collection count

There is no direct option available. You cant't do db.collection("CollectionName").count(). Below are the two ways by which you can find the count of number of documents within a collection.

1 :- Get all the documents in the collection and then get it's size.(Not the best Solution)

db.collection("CollectionName").get().subscribe(doc=>{
console.log(doc.size)
})

By using above code your document reads will be equal to the size of documents within a collection and that is the reason why one must avoid using above solution.

2:- Create a separate document with in your collection which will store the count of number of documents in the collection.(Best Solution)

db.collection("CollectionName").doc("counts")get().subscribe(doc=>{
console.log(doc.count)
})

Above we created a document with name counts to store all the count information.You can update the count document in the following way:-

  • Create a firestore triggers on the document counts
  • Increment the count property of counts document when a new document is created.
  • Decrement the count property of counts document when a document is deleted.

w.r.t price (Document Read = 1) and fast data retrieval the above solution is good.

Mysql - How to quit/exit from stored procedure

This works for me :

 CREATE DEFINER=`root`@`%` PROCEDURE `save_package_as_template`( IN package_id int , 
IN bus_fun_temp_id int  , OUT o_message VARCHAR (50) ,
            OUT o_number INT )
 BEGIN

DECLARE  v_pkg_name  varchar(50) ;

DECLARE  v_pkg_temp_id  int(10)  ; 

DECLARE  v_workflow_count INT(10);

-- checking if workflow created for package
select count(*)  INTO v_workflow_count from workflow w where w.package_id = 
package_id ;

this_proc:BEGIN   -- this_proc block start here 

 IF  v_workflow_count = 0 THEN
   select 'no work flow ' as 'workflow_status' ;
    SET o_message ='Work flow is not created for this package.';
    SET  o_number = -2 ;
      LEAVE this_proc;
 END IF;

select 'work flow  created ' as 'workflow_status' ;
-- To  send some message
SET o_message ='SUCCESSFUL';
SET  o_number = 1 ;

  END ;-- this_proc block end here 

END

Sorting hashmap based on keys

Use a TreeMap, although having a map "look like that" is a bit nebulous--you could also just sort the keys based on your criteria and iterate over the map, retrieving each object.

How to get base64 encoded data from html image

You can try following sample http://jsfiddle.net/xKJB8/3/

<img id="preview" src="http://www.gravatar.com/avatar/0e39d18b89822d1d9871e0d1bc839d06?s=128&d=identicon&r=PG">
<canvas id="myCanvas" />

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
var img = document.getElementById("preview");
ctx.drawImage(img, 10, 10);
alert(c.toDataURL());

How to generate random positive and negative numbers in Java

Random random=new Random();
int randomNumber=(random.nextInt(65536)-32768);

Show ImageView programmatically

How to undo a git merge with conflicts

Actually, it is worth noticing that git merge --abort is only equivalent to git reset --merge given that MERGE_HEAD is present. This can be read in the git help for merge command.

git merge --abort # is equivalent to git reset --merge when MERGE_HEAD is present.

After a failed merge, when there is no MERGE_HEAD, the failed merge can be undone with git reset --merge but not necessarily with git merge --abort, so they are not only old and new syntax for the same thing.

Personally I find git reset --merge much more useful in everyday work.

Styling of Select2 dropdown select boxes

Here is a working example of above. http://jsfiddle.net/z7L6m2sc/ Now select2 has been updated the classes have change may be why you cannot get it to work. Here is the css....

.select2-dropdown.select2-dropdown--below{
    width: 148px !important;
}

.select2-container--default .select2-selection--single{
    padding:6px;
    height: 37px;
    width: 148px; 
    font-size: 1.2em;  
    position: relative;
}

.select2-container--default .select2-selection--single .select2-selection__arrow {
    background-image: -khtml-gradient(linear, left top, left bottom, from(#424242), to(#030303));
    background-image: -moz-linear-gradient(top, #424242, #030303);
    background-image: -ms-linear-gradient(top, #424242, #030303);
    background-image: -webkit-gradient(linear, left top, left bottom, color-stop(0%, #424242), color-stop(100%, #030303));
    background-image: -webkit-linear-gradient(top, #424242, #030303);
    background-image: -o-linear-gradient(top, #424242, #030303);
    background-image: linear-gradient(#424242, #030303);
    width: 40px;
    color: #fff;
    font-size: 1.3em;
    padding: 4px 12px;
    height: 27px;
    position: absolute;
    top: 0px;
    right: 0px;
    width: 20px;
}

How to import a jar in Eclipse

Here are the steps:

  1. click File > Import. The Import window opens.

  2. Under Select an import source, click J2EE > App Client JAR file.

  3. Click Next.

  4. In the Application Client file field, enter the location and name of the application client JAR file that you want to import. You can click the Browse button to select the JAR file from the file system.

  5. In the Application Client project field, type a new project name or select an application client project from the drop-down list. If you type a new name in this field, the application client project will be created based on the version of the application client JAR file, and it will use the default location.

  6. In the Target runtime drop-down list, select the application server that you want to target for your development. This selection affects the run time settings by modifying the class path entries for the project.

  7. If you want to add the new module to an enterprise application project, select the Add project to an EAR check box and then select an existing enterprise application project from the list or create a new one by clicking New.

    Note: If you type a new enterprise application project name, the enterprise application project will be created in the default location with the lowest compatible J2EE version based on the version of the project being created. If you want to specify a different version or a different location for the enterprise application, you must use the New Enterprise Application Project wizard.

  8. Click Finish to import the application client JAR file.

Check if an array item is set in JS

var assoc_pagine = new Array();
assoc_pagine["home"]=0;

Don't use an Array for this. Arrays are for numerically-indexed lists. Just use a plain Object ({}).

What you are thinking of with the 'undefined' string is probably this:

if (typeof assoc_pagine[key]!=='undefined')

This is (more or less) the same as saying

if (assoc_pagine[key]!==undefined)

However, either way this is a bit ugly. You're dereferencing a key that may not exist (which would be an error in any more sensible language), and relying on JavaScript's weird hack of giving you the special undefined value for non-existent properties.

This also doesn't quite tell you if the property really wasn't there, or if it was there but explicitly set to the undefined value.

This is a more explicit, readable and IMO all-round better approach:

if (key in assoc_pagine)

Java Webservice Client (Best way)

Some ideas in the following answer:

Steps in creating a web service using Axis2 - The client code

Gives an example of a Groovy client invoking the ADB classes generated from the WSDL.

There are lots of web service frameworks out there...

Why use def main()?

Consider the second script. If you import it in another one, the instructions, as at "global level", will be executed.

Viewing full version tree in git

If you don't need branch or tag name:
git log --oneline --graph --all --no-decorate

If you don't even need color (to avoid tty color sequence):
git log --oneline --graph --all --no-decorate --no-color

And a handy alias (in .gitconfig) to make life easier:

[alias]
  tree = log --oneline --graph --all --no-decorate

Only last option takes effect, so it's even possible to override your alias:
git tree --decorate

How to update Pandas from Anaconda and is it possible to use eclipse with this last

The answer above did not work for me (python 3.6, Anaconda, pandas 0.20.3). It worked with

conda install -c anaconda pandas 

Unfortunately I do not know how to help with Eclipse.

COUNT DISTINCT with CONDITIONS

You can try this:

select
  count(distinct tag) as tag_count,
  count(distinct (case when entryId > 0 then tag end)) as positive_tag_count
from
  your_table_name;

The first count(distinct...) is easy. The second one, looks somewhat complex, is actually the same as the first one, except that you use case...when clause. In the case...when clause, you filter only positive values. Zeros or negative values would be evaluated as null and won't be included in count.

One thing to note here is that this can be done by reading the table once. When it seems that you have to read the same table twice or more, it can actually be done by reading once, in most of the time. As a result, it will finish the task a lot faster with less I/O.

How to move or copy files listed by 'find' command in unix?

find /PATH/TO/YOUR/FILES -name NAME.EXT -exec cp -rfp {} /DST_DIR \;

Java POI : How to read Excel cell value and not the formula computing it?

Previously posted solutions did not work for me. cell.getRawValue() returned the same formula as stated in the cell. The following function worked for me:

public void readFormula() throws IOException {
    FileInputStream fis = new FileInputStream("Path of your file");
    Workbook wb = new XSSFWorkbook(fis);
    Sheet sheet = wb.getSheetAt(0);
    FormulaEvaluator evaluator = wb.getCreationHelper().createFormulaEvaluator();

    CellReference cellReference = new CellReference("C2"); // pass the cell which contains the formula
    Row row = sheet.getRow(cellReference.getRow());
    Cell cell = row.getCell(cellReference.getCol());

    CellValue cellValue = evaluator.evaluate(cell);

    switch (cellValue.getCellType()) {
        case Cell.CELL_TYPE_BOOLEAN:
            System.out.println(cellValue.getBooleanValue());
            break;
        case Cell.CELL_TYPE_NUMERIC:
            System.out.println(cellValue.getNumberValue());
            break;
        case Cell.CELL_TYPE_STRING:
            System.out.println(cellValue.getStringValue());
            break;
        case Cell.CELL_TYPE_BLANK:
            break;
        case Cell.CELL_TYPE_ERROR:
            break;

        // CELL_TYPE_FORMULA will never happen
        case Cell.CELL_TYPE_FORMULA:
            break;
    }

}

LINQ: "contains" and a Lambda query

The Linq extension method Any could work for you...

buildingStatus.Any(item => item.GetCharValue() == v.Status)

No provider for Http StaticInjectorError

In ionic 4.6 I use the following technique and it works. I am adding this answer so that if anybody is facing similar issues in newer ionic version app, it may help them.

i) Open app.module.ts and add the following code block to import HttpModule and HttpClientModule

import { HttpModule } from '@angular/http';
import {   HttpClientModule } from '@angular/common/http';

ii) In @NgModule import sections add below lines:

HttpModule,
HttpClientModule,

So, in my case @NgModule, looks like this:

@NgModule({
  declarations: [AppComponent ],
  entryComponents: [ ],
  imports: [
    BrowserModule,
    HttpModule,
    HttpClientModule,
    IonicModule.forRoot(),
    AppRoutingModule, 
  ],
  providers: [
    StatusBar,
    SplashScreen,
    { provide: RouteReuseStrategy, useClass: IonicRouteStrategy }
  ],
  bootstrap: [AppComponent]
})

That's it!

Bootstrap 3 Glyphicons are not working

You must to set by this order:

<link rel="stylesheet" href="path/bootstrap.min.css">
 <style type="text/css">
      @font-face {
  font-family: 'Glyphicons Halflings';
        src: url('../fonts/glyphicons-halflings-regular.eot');
        src: url('../fonts/glyphicons-halflings-regular.eot?#iefix') format('embedded-opentype'),       url('../fonts/glyphicons-halflings-regular.woff') format('woff'),        url('../fonts/glyphicons-halflings-regular.ttf') format('truetype'),       url('../fonts/glyphicons-halflings-regular.svg#glyphicons-halflingsregular') format('svg');
}
 </style>

Select specific row from mysql table

You can add an auto generated id field in the table and select by this id

SELECT * FROM CUSTOMER WHERE CUSTOMER_ID = 3;

How to open in default browser in C#

Did you try Processas mentioned here: http://msdn.microsoft.com/de-de/library/system.diagnostics.process.aspx?

You could use

Process myProcess = new Process();

try
{
    // true is the default, but it is important not to set it to false
    myProcess.StartInfo.UseShellExecute = true; 
    myProcess.StartInfo.FileName = "http://some.domain.tld/bla";
    myProcess.Start();
}
catch (Exception e)
{
    Console.WriteLine(e.Message);
}

display:inline vs display:block

Add a background-color to the element and you will nicely see the difference of inline vs. block, as explained by the other posters.

add string to String array

As many of the answer suggesting better solution is to use ArrayList. ArrayList size is not fixed and it is easily manageable.

It is resizable-array implementation of the List interface. Implements all optional list operations, and permits all elements, including null. In addition to implementing the List interface, this class provides methods to manipulate the size of the array that is used internally to store the list.

Each ArrayList instance has a capacity. The capacity is the size of the array used to store the elements in the list. It is always at least as large as the list size. As elements are added to an ArrayList, its capacity grows automatically.

Note that this implementation is not synchronized.

ArrayList<String> scripts = new ArrayList<String>();
scripts.add("test1");
scripts.add("test2");
scripts.add("test3");

Eclipse - Installing a new JRE (Java SE 8 1.8.0)

You can have many java versions in your system.

I think you should add the java 8 in yours JREs installed or edit.

Take a look my screen:

enter image description here

If you click in edit (check your java 8 path):

enter image description here

Can (a== 1 && a ==2 && a==3) ever evaluate to true?

By overriding valueOf in a class declaration, it can be done:

class Thing {
    constructor() {
        this.value = 1;
    }

    valueOf() {
        return this.value++;
    }
}

const a = new Thing();

if(a == 1 && a == 2 && a == 3) {
    console.log(a);
}

What happens is that valueOf is called in each comparison operator. On the first one, a will equal 1, on the second, a will equal 2, and so on and so forth, because each time valueOf is called, the value of a is incremented.

Therefore the console.log will fire and output (in my terminal anyways) Thing: { value: 4}, indicating the conditional was true.

A Space between Inline-Block List Items

just remove the breaks between li's in your html code... make the li's in one line only..

Checking if a string array contains a value, and if so, getting its position

You can try this, it looks up for the index containing this element, and it sets the index number as the int, then it checks if the int is greater then -1, so if it's 0 or more, then it means it found such an index - as arrays are 0 based.

string[] Selection = {"First", "Second", "Third", "Fourth"};
string Valid = "Third";    // You can change this to a Console.ReadLine() to 
    //use user input 
int temp = Array.IndexOf(Selection, Valid); // it gets the index of 'Valid', 
                // in our case it's "Third"
            if (temp > -1)
                Console.WriteLine("Valid selection");
            }
            else
            {
                Console.WriteLine("Not a valid selection");
            }

Connecting to SQL Server using windows authentication

Just replace the first line with the below;

SqlConnection con = new SqlConnection("Server=localhost;Database=employeedetails;Trusted_Connection=True");

Regards.

How to get full path of a file?

echo $(cd $(dirname "$1") && pwd -P)/$(basename "$1")

This is explanation of what is going on at @ZeRemz's answer:

  1. This script get relative path as argument "$1"
  2. Then we get dirname part of that path (you can pass either dir or file to this script): dirname "$1"
  3. Then we cd "$(dirname "$1") into this relative dir
  4. && pwd -P and get absolute path for it. -P option will avoid all symlinks
  5. After that we append basename to absolute path: $(basename "$1")
  6. As final step we echo it

How to disable all <input > inside a form with jQuery?

The definitive answer (covering changes to jQuery api at version 1.6) has been given by Gnarf

Getting visitors country from their IP

I tried Chandra's answer but my server configuration does not allow file_get_contents()

PHP Warning: file_get_contents() URL file-access is disabled in the server configuration

I modified Chandra's code so that it also works for servers like that using cURL:

function ip_visitor_country()
{

    $client  = @$_SERVER['HTTP_CLIENT_IP'];
    $forward = @$_SERVER['HTTP_X_FORWARDED_FOR'];
    $remote  = $_SERVER['REMOTE_ADDR'];
    $country  = "Unknown";

    if(filter_var($client, FILTER_VALIDATE_IP))
    {
        $ip = $client;
    }
    elseif(filter_var($forward, FILTER_VALIDATE_IP))
    {
        $ip = $forward;
    }
    else
    {
        $ip = $remote;
    }
    $ch = curl_init();
    curl_setopt($ch, CURLOPT_URL, "http://www.geoplugin.net/json.gp?ip=".$ip);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, TRUE);
    $ip_data_in = curl_exec($ch); // string
    curl_close($ch);

    $ip_data = json_decode($ip_data_in,true);
    $ip_data = str_replace('&quot;', '"', $ip_data); // for PHP 5.2 see stackoverflow.com/questions/3110487/

    if($ip_data && $ip_data['geoplugin_countryName'] != null) {
        $country = $ip_data['geoplugin_countryName'];
    }

    return 'IP: '.$ip.' # Country: '.$country;
}

echo ip_visitor_country(); // output Coutry name

?>

Hope that helps ;-)

Floating point comparison functions for C#

From Bruce Dawson's paper on comparing floats, you can also compare floats as integers. Closeness is determined by least significant bits.

public static bool AlmostEqual2sComplement( float a, float b, int maxDeltaBits ) 
{
    int aInt = BitConverter.ToInt32( BitConverter.GetBytes( a ), 0 );
    if ( aInt <  0 )
        aInt = Int32.MinValue - aInt;  // Int32.MinValue = 0x80000000

    int bInt = BitConverter.ToInt32( BitConverter.GetBytes( b ), 0 );
    if ( bInt < 0 )
        bInt = Int32.MinValue - bInt;

    int intDiff = Math.Abs( aInt - bInt );
    return intDiff <= ( 1 << maxDeltaBits );
}

EDIT: BitConverter is relatively slow. If you're willing to use unsafe code, then here is a very fast version:

    public static unsafe int FloatToInt32Bits( float f )
    {
        return *( (int*)&f );
    }

    public static bool AlmostEqual2sComplement( float a, float b, int maxDeltaBits )
    {
        int aInt = FloatToInt32Bits( a );
        if ( aInt < 0 )
            aInt = Int32.MinValue - aInt;

        int bInt = FloatToInt32Bits( b );
        if ( bInt < 0 )
            bInt = Int32.MinValue - bInt;

        int intDiff = Math.Abs( aInt - bInt );
        return intDiff <= ( 1 << maxDeltaBits );
    }

How to Uninstall RVM?

It’s easy; just do the following:

rvm implode

or

rm -rf ~/.rvm

And don’t forget to remove the script calls in the following files:

  • ~/.bashrc
  • ~/.bash_profile
  • ~/.profile

And maybe others depending on whatever shell you’re using.

TypeError: string indices must be integers, not str // working with dict

time1 is the key of the most outer dictionary, eg, feb2012. So then you're trying to index the string, but you can only do this with integers. I think what you wanted was:

for info in courses[time1][course]:

As you're going through each dictionary, you must add another nest.

OrderBy pipe issue

Angular doesn't come with an orderBy filter out of the box, but if we decide we need one we can easily make one. There are however some caveats we need to be aware of to do with speed and minification. See below.

A simple pipe would look something like this.

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'sort'
})
export class SortPipe implements PipeTransform {
  transform(ary: any, fn: Function = (a,b) => a > b ? 1 : -1): any {
    return ary.sort(fn)
  }
}

This pipe accepts a sort function (fn), and gives it a default value that will sort an array of primitives in a sensible way. We have the option of overriding this sort function if we wish.

It does not accept an attribute name as a string, because attribute names are subject to minification. They will change when we minify our code, but minifiers are not smart enough to also minify the value in the template string.

Sorting primitives (numbers and strings)

We could use this to sort an array of numbers or strings using the default comparator:

import { Component } from '@angular/core';

@Component({
  selector: 'cat',
  template: `
    {{numbers | sort}}
    {{strings | sort}}
  `
})
export class CatComponent
  numbers:Array<number> = [1,7,5,6]
  stringsArray<string> = ['cats', 'hats', 'caveats']
}

Sorting an array of objects

If we want to sort an array of objects, we can give it a comparator function.

import { Component } from '@angular/core';

@Component({
  selector: 'cat',
  template: `
    {{cats | sort:byName}}
  `
})
export class CatComponent
  cats:Array<Cat> = [
    {name: "Missy"},
    {name: "Squoodles"},
    {name: "Madame Pompadomme"}
  ]
  byName(a,b) {
    return a.name > b.name ? 1 : -1
  }
}

Caveats - pure vs. impure pipes

Angular 2 has a concept of pure and impure pipes.

A pure pipe optimises change detection using object identity. This means that the pipe will only run if the input object changes identity, for example if we add a new item to the array. It will not descent into objects. This means that if we change a nested attribute: this.cats[2].name = "Fluffy" for example, the pipe will not rerun. This helps Angular to be fast. Angular pipes are pure by default.

An impure pipe on the other hand will check object attributes. This potentially makes it much slower. Because it can't guarantee what the pipe function will do (perhaps it sortd differently based on the time of day for example), an impure pipe will run every time an asynchronous event occurs. This will slow down your app considerably if the array is large.

The pipe above is pure. This means it will only run when the objects in the array are immutable. If you change a cat, you must replace the entire cat object with a new one.

this.cats[2] = {name:"Tomy"}

We can change the above to an impure pipe by setting the pure attribute:

import { Pipe, PipeTransform } from '@angular/core';

@Pipe({
  name: 'sort',
  pure: false
})
export class SortPipe implements PipeTransform {
  transform(ary: any, fn: Function = (a,b) => a > b ? 1 : -1): any {
    return ary.sort(fn)
  }
}

This pipe will descend into objects, but will be slower. Use with caution.

In python, what is the difference between random.uniform() and random.random()?

According to the documentation on random.uniform:

Return a random floating point number N such that a <= N <= b for a <= b and b <= N <= a for b < a.

while random.random:

Return the next random floating point number in the range [0.0, 1.0).

I.e. with random.uniform you specify a range you draw pseudo-random numbers from, e.g. between 3 and 10. With random.random you get a number between 0 and 1.

"Error 1067: The process terminated unexpectedly" when trying to start MySQL

I had the same problem. I am using mysql 5.6.11. To solve this problem I had to change my-default.ini file in mysql-5.6.11-win32 folder So I just pasted the following lines under line [mysqld]

basedir="D:\mysql-5.6.11-win32\"
datadir="D:\mysql-5.6.11-win32\data\"
port=3306
server-id=1
bind-address=127.0.0.1

Options basedir and datadir need to be modified for mysql location.

How to parse the Manifest.mbdb file in an iOS 4.0 iTunes Backup

I finished my work on this stuff - that is, iOS 4 + iTunes 9.2 update of my backup decoder library for Python - http://www.iki.fi/fingon/iphonebackupdb.py

It does what I need, little documentation, but feel free to copy ideas from there ;-)

(Seems to work fine with my backups at least.)

Java Equivalent of C# async/await?

There isn't anything native to java that lets you do this like async/await keywords, but what you can do if you really want to is use a CountDownLatch. You could then imitate async/await by passing this around (at least in Java7). This is a common practice in Android unit testing where we have to make an async call (usually a runnable posted by a handler), and then await for the result (count down).

Using this however inside your application as opposed to your test is NOT what I am recommending. That would be extremely shoddy as CountDownLatch depends on you effectively counting down the right number of times and in the right places.

How to store token in Local or Session Storage in Angular 2?

we can store session storage like that

store token should be like

 localStorage.setItem('user', JSON.stringify({ token: token, username: username }));

Store Session in to sessionStorage

You can store both string and array into session storage

String Ex.

    let key = 'title'; 
    let value = 'session';
    sessionStorage.setItem(key, value);

Array Ex.

    let key = 'user'; 
    let value = [{'name':'shail','email':'[email protected]'}];

    value = JSON.stringify(value);

    sessionStorage.setItem(key, value);

Get stored session from sessionStorage by key

const session = sessionStorage.getItem('key');

Delete saved session from sessionStorage by key

sessionStorage.removeItem('key');

Delete all saved sessions from sessionStorage

sessionStorage.clear();
  1. store Local storage should be like

Store items in to localStorage

You can store both string and array into location storage

String Ex.

 let key = 'title'; 
 let value = 'session';
 localStorage.setItem(key, value);

Array Ex.

let key = 'user'; 
let value = [{'name':'shail','email':'[email protected]'}];

value = JSON.stringify(value);

localStorage.setItem(key, value);

Get stored items from localStorage by key

const item = localStorage.getItem('key');

Delete saved session from localStorage by key

localStorage.removeItem('key');

Delete all saved items from localStorage

localStorage.clear();

what is the difference between XSD and WSDL

XSD is schema for WSDL file. XSD contain datatypes for WSDL. Element declared in XSD is valid to use in WSDL file. We can Check WSDL against XSD to check out web service WSDL is valid or not.

Error: Cannot pull with rebase: You have unstaged changes

If you want to keep your working changes while performing a rebase, you can use --autostash. From the documentation:

Before starting rebase, stash local modifications away (see git-stash[1]) if needed, and apply the stash when done.

For example:

git pull --rebase --autostash

How to call servlet through a JSP page

Why would you want to do this? You shouldn't be executing controller code in the view, and most certainly shouldn't be trying to pull code inside of another servlet into the view either.

Do all of your processing and refactoring of the application first, then just pass off the results to a view. Make the view as dumb as possible and you won't even run into these problems.

If this kind of design is hard for you, try Freemarker or even something like Velocity (although I don't recommend it) to FORCE you to do this. You never have to do this sort of thing ever.

To put it more accurately, the problem you are trying to solve is just a symptom of a greater problem - your architecture/design of your servlets.

Vue - Deep watching an array of objects and calculating the change?

I have changed the implementation of it to get your problem solved, I made an object to track the old changes and compare it with that. You can use it to solve your issue.

Here I created a method, in which the old value will be stored in a separate variable and, which then will be used in a watch.

new Vue({
  methods: {
    setValue: function() {
      this.$data.oldPeople = _.cloneDeep(this.$data.people);
    },
  },
  mounted() {
    this.setValue();
  },
  el: '#app',
  data: {
    people: [
      {id: 0, name: 'Bob', age: 27},
      {id: 1, name: 'Frank', age: 32},
      {id: 2, name: 'Joe', age: 38}
    ],
    oldPeople: []
  },
  watch: {
    people: {
      handler: function (after, before) {
        // Return the object that changed
        var vm = this;
        let changed = after.filter( function( p, idx ) {
          return Object.keys(p).some( function( prop ) {
            return p[prop] !== vm.$data.oldPeople[idx][prop];
          })
        })
        // Log it
        vm.setValue();
        console.log(changed)
      },
      deep: true,
    }
  }
})

See the updated codepen

How to fix error Base table or view not found: 1146 Table laravel relationship table?

You can add this in Post Model,

public function categories()
{
 return $this->belongsToMany('App\Category','category_post','post_id','category_id');                 
}

category_post indicate the table you want to use.
post_id indicate the column where you want to store the posts id.
category_id indicate the column where you want to store the categories id.

Locate current file in IntelliJ

I am using IntelliJ IDEA 2016.2 Ultimate.

Alt+F1, then press 1

What does <T> denote in C#

This feature is known as generics. http://msdn.microsoft.com/en-us/library/512aeb7t(v=vs.100).aspx

An example of this is to make a collection of items of a specific type.

class MyArray<T>
{
    T[] array = new T[10];

    public T GetItem(int index)
    {
        return array[index];
    }
}

In your code, you could then do something like this:

MyArray<int> = new MyArray<int>();

In this case, T[] array would work like int[] array, and public T GetItem would work like public int GetItem.

SSIS Connection Manager Not Storing SQL Password

The designed behavior in SSIS is to prevent storing passwords in a package, because it's bad practice/not safe to do so.

Instead, either use Windows auth, so you don't store secrets in packages or config files, or, if that's really impossible in your environment (maybe you have no Windows domain, for example) then you have to use a workaround as described in http://support.microsoft.com/kb/918760 (Sam's correct, just read further in that article). The simplest answer is a config file to go with the package, but then you have to worry that the config file is stored securely so someone can't just read it and take the credentials.

Using partial views in ASP.net MVC 4

Change the code where you load the partial view to:

@Html.Partial("_CreateNote", new QuickNotes.Models.Note())

This is because the partial view is expecting a Note but is getting passed the model of the parent view which is the IEnumerable

What is path of JDK on Mac ?

Which Mac version are you using? try these paths

 /System/Library/Frameworks/JavaVM.framework/ OR
 /usr/libexec/java_home

This link might help - How To Set $JAVA_HOME Environment Variable On Mac OS X

Change Tomcat Server's timeout in Eclipse

  1. Go to server View
  2. Double click the server for which you want to change the time limit
  3. On the right hand side you have timeouts dropdown tab. Select that.
  4. You then have option to change the time limits.

enter image description here

How to chain scope queries with OR instead of AND?

You can also use MetaWhere gem to not mix up your code with SQL stuff:

Person.where((:name => "John") | (:lastname => "Smith"))

Recommended way to insert elements into map

Use insert if you want to insert a new element. insert will not overwrite an existing element, and you can verify that there was no previously exising element:

if ( !myMap.insert( std::make_pair( key, value ) ).second ) {
    //  Element already present...
}

Use [] if you want to overwrite a possibly existing element:

myMap[ key ] = value;
assert( myMap.find( key )->second == value ); // post-condition

This form will overwrite any existing entry.

How to return an array from an AJAX call?

Php has a super sexy function for this, just pass the array to it:

$json = json_encode($var);

$.ajax({
url:"Example.php",
type:"POST",
dataType : "json",
success:function(msg){
    console.info(msg);
}
});

simples :)

How to push JSON object in to array using javascript

You need to have the 'data' array outside of the loop, otherwise it will get reset in every loop and also you can directly push the json. Find the solution below:-

var my_json;
$.getJSON("https://api.thingspeak.com/channels/"+did+"/feeds.json?api_key="+apikey+"&results=300", function(json1) {
console.log(json1);
var data = [];
json1.feeds.forEach(function(feed,i){
    console.log("\n The details of " + i + "th Object are :  \nCreated_at: " + feed.created_at + "\nEntry_id:" + feed.entry_id + "\nField1:" + feed.field1 + "\nField2:" + feed.field2+"\nField3:" + feed.field3);      
    my_json = feed;
    console.log(my_json); //Object {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"}
    data.push(my_json);
     //["2017-03-14T01:00:32Z", 33358, "4", "4", "0"]
}); 
console.log(data);

Login credentials not working with Gmail SMTP

I ran into a similar problem and stumbled on this question. I got an SMTP Authentication Error but my user name / pass was correct. Here is what fixed it. I read this:

https://support.google.com/accounts/answer/6010255

In a nutshell, google is not allowing you to log in via smtplib because it has flagged this sort of login as "less secure", so what you have to do is go to this link while you're logged in to your google account, and allow the access:

https://www.google.com/settings/security/lesssecureapps

Once that is set (see my screenshot below), it should work.

Less Secure Apps

Login now works:

smtpserver = smtplib.SMTP("smtp.gmail.com", 587)
smtpserver.ehlo()
smtpserver.starttls()
smtpserver.ehlo()
smtpserver.login('[email protected]', 'me_pass')

Response after change:

(235, '2.7.0 Accepted')

Response prior:

smtplib.SMTPAuthenticationError: (535, '5.7.8 Username and Password not accepted. Learn more at\n5.7.8 http://support.google.com/mail/bin/answer.py?answer=14257 g66sm2224117qgf.37 - gsmtp')

Still not working? If you still get the SMTPAuthenticationError but now the code is 534, its because the location is unknown. Follow this link:

https://accounts.google.com/DisplayUnlockCaptcha

Click continue and this should give you 10 minutes for registering your new app. So proceed to doing another login attempt now and it should work.

This doesn't seem to work right away you may be stuck for a while getting this error in smptlib:

235 == 'Authentication successful'
503 == 'Error: already authenticated'

The message says to use the browser to sign in:

SMTPAuthenticationError: (534, '5.7.9 Please log in with your web browser and then try again. Learn more at\n5.7.9 https://support.google.com/mail/bin/answer.py?answer=78754 qo11sm4014232igb.17 - gsmtp')

After enabling 'lesssecureapps', go for a coffee, come back, and try the 'DisplayUnlockCaptcha' link again. From user experience, it may take up to an hour for the change to kick in. Then try the sign-in process again.

UPDATE:: See my answer here: How to send an email with Gmail as provider using Python?

MySQL CONCAT returns NULL if any field contain NULL

Use CONCAT_WS instead:

CONCAT_WS() does not skip empty strings. However, it does skip any NULL values after the separator argument.

SELECT CONCAT_WS('-',`affiliate_name`,`model`,`ip`,`os_type`,`os_version`) AS device_name FROM devices

How to check list A contains any value from list B?

I've profiled Justins two solutions. a.Any(a => b.Contains(a)) is fastest.

using System;
using System.Collections.Generic;
using System.Linq;

namespace AnswersOnSO
{
    public class Class1
    {
        public static void Main(string []args)
        {
//            How to check if list A contains any value from list B?
//            e.g. something like A.contains(a=>a.id = B.id)?
            var a = new List<int> {1,2,3,4};
            var b = new List<int> {2,5};
            var times = 10000000;

            DateTime dtAny = DateTime.Now;
            for (var i = 0; i < times; i++)
            {
                var aContainsBElements = a.Any(b.Contains);
            }
            var timeAny = (DateTime.Now - dtAny).TotalSeconds;

            DateTime dtIntersect = DateTime.Now;
            for (var i = 0; i < times; i++)
            {
                var aContainsBElements = a.Intersect(b).Any();
            }
            var timeIntersect = (DateTime.Now - dtIntersect).TotalSeconds;

            // timeAny: 1.1470656 secs
            // timeIn.: 3.1431798 secs
        }
    }
}

How to put a div in center of browser using CSS?

<html>
<head>
<style>
*
{
    margin:0;
    padding:0;
}

html, body
{
    height:100%;
}

#distance
{
    width:1px;
    height:50%;
    margin-bottom:-300px;
    float:left;
}


#something
{
    position:relative;
    margin:0 auto;
    text-align:left;
    clear:left;
    width:800px;
    min-height:600px;
    height:auto;
    border: solid 1px #993333;
    z-index: 0;
}

/* for Internet Explorer */
* html #something{
height: 600px;
}
</style>

</head>
<body>

<div id="distance"></div>

<div id="something">
</div>
</body>

</html>

Tested in FF2-3, IE6-7, Opera and works well!

How do I set the default locale in the JVM?

You can do this:

enter image description here

enter image description here

And to capture locale. You can do this:

private static final String LOCALE = LocaleContextHolder.getLocale().getLanguage()
            + "-" + LocaleContextHolder.getLocale().getCountry();

What is the recommended way to delete a large number of items from DynamoDB?

What I ideally want to do is call LogTable.DeleteItem(user_id) - Without supplying the range, and have it delete everything for me.

An understandable request indeed; I can imagine advanced operations like these might get added over time by the AWS team (they have a history of starting with a limited feature set first and evaluate extensions based on customer feedback), but here is what you should do to avoid the cost of a full scan at least:

  1. Use Query rather than Scan to retrieve all items for user_id - this works regardless of the combined hash/range primary key in use, because HashKeyValue and RangeKeyCondition are separate parameters in this API and the former only targets the Attribute value of the hash component of the composite primary key..

    • Please note that you''ll have to deal with the query API paging here as usual, see the ExclusiveStartKey parameter:

      Primary key of the item from which to continue an earlier query. An earlier query might provide this value as the LastEvaluatedKey if that query operation was interrupted before completing the query; either because of the result set size or the Limit parameter. The LastEvaluatedKey can be passed back in a new query request to continue the operation from that point.

  2. Loop over all returned items and either facilitate DeleteItem as usual

    • Update: Most likely BatchWriteItem is more appropriate for a use case like this (see below for details).

Update

As highlighted by ivant, the BatchWriteItem operation enables you to put or delete several items across multiple tables in a single API call [emphasis mine]:

To upload one item, you can use the PutItem API and to delete one item, you can use the DeleteItem API. However, when you want to upload or delete large amounts of data, such as uploading large amounts of data from Amazon Elastic MapReduce (EMR) or migrate data from another database in to Amazon DynamoDB, this API offers an efficient alternative.

Please note that this still has some relevant limitations, most notably:

  • Maximum operations in a single request — You can specify a total of up to 25 put or delete operations; however, the total request size cannot exceed 1 MB (the HTTP payload).

  • Not an atomic operation — Individual operations specified in a BatchWriteItem are atomic; however BatchWriteItem as a whole is a "best-effort" operation and not an atomic operation. That is, in a BatchWriteItem request, some operations might succeed and others might fail. [...]

Nevertheless this obviously offers a potentially significant gain for use cases like the one at hand.

How to send push notification to web browser?

May I redefine you question as below

Can we have our own back-end to send push notification to Chrome, Firefox, Opera & Safari?

Yes. By today (2017/05), you can use same client and server side implementation to handle Chrome, Firefox and Opera (no Safari). Because they have implemented web push notifications in a same way. That is Push API protocol by W3C. But Safari have their own old architecture. So we have to maintain Safari separately.

Refer browser-push repo for guide lines to implement web push notification for your web-app with your own back-end. It explains with examples how you can add web push notification support for your web application without any third party services.

\n or \n in php echo not print

Better use PHP_EOL ("End Of Line") instead. It's cross-platform.

E.g.:

$unit1 = 'paragrahp1';
$unit2 = 'paragrahp2';
echo '<p>' . $unit1 . '</p>' . PHP_EOL;
echo '<p>' . $unit2 . '</p>';

How to create a JavaScript callback for knowing when an image is loaded?

Here is jQuery equivalent:

var $img = $('img');

if ($img.length > 0 && !$img.get(0).complete) {
   $img.on('load', triggerAction);
}

function triggerAction() {
   alert('img has been loaded');
}

Javascript change Div style

Using jQuery:

$(document).ready(function(){
    $('div').click(function(){
        $(this).toggleClass('clicked');
    });
});?

Live example

How to change the cursor into a hand when a user hovers over a list item?

I think it would be smart to only show the hand/pointer cursor when JavaScript is available. So people will not have the feeling they can click on something that is not clickable.

To achieve that you could use the JavaScript libary jQuery to add the CSS to the element like so

$("li").css({"cursor":"pointer"});

Or chain it directly to the click handler.

Or when modernizer in combination with <html class="no-js"> is used, the CSS would look like this:

.js li { cursor: pointer; }

MongoDB vs Firebase

Firebase is a suite of features .

  • Realtime Database
  • Hosting
  • Authentication
  • Storage
  • Cloud Messaging
  • Remote Config
  • Test Lab
  • Crash Reporting
  • Notifications
  • App Indexing
  • Dynamic Links
  • Invites
  • AdWords
  • AdMob

I believe you are trying to compare Firebase Realtime Database with Mongo DB . Firebase Realtime Database stores data as JSON format and syncs to all updates of the data to all clients listening to the data . It abstracts you from all complexity that is needed to setup and scale any database . I will not recommend firebase where you have lot of complex scenarios where aggregation of data is needed .(Queries that need SUM/AVERAGE kind of stuff ) . Though this is recently achievable using Firebase functions . Modeling data in Firebase is tricky . But it is the best way to get you started instantaneously . MongoDB is a database. This give you lot of powerful features. But MongoDB when installed in any platform you need to manage it by yourself .

When i try to choose between Firebase or MongoDB(or any DB ) . I try to answer the following .

  1. Are there many aggregation queries that gets executed .(Like in case of reporting tool or BI tool ) . If Yes dont go for Firebase
  2. Do i need to perform lot of transaction . (If yes then i would not like to go with firebase) (Tranactions are somewhat easy though after introduction of functions but that is also a overhead if lot of transactions needs to be maintained)
  3. What timeline do i have to get things up and running .(Firebase is very easy to setup and integrate ).
  4. Do i have expertise to scale up the DB and trouble shoot DB related stuffs . (Firebase is more like SAAS so no need to worry about scaleability)

Is it possible to include one CSS file in another?

The @import url("base.css"); works fine but bear in mind that every @import statement is a new request to the server. This might not be a problem for you, but when optimal performance is required you should avoid the @import.

React Hook "useState" is called in function "app" which is neither a React function component or a custom React Hook function

In JSX, the lower-case tag name is considered as html native component. In order to react recognise the function as React component, need to Capitalized the name.

Capitalized types indicate that the JSX tag is referring to a React component. These tags get compiled into a direct reference to the named variable, so if you use the JSX <Foo /> expression, Foo must be in scope.

https://reactjs.org/docs/jsx-in-depth.html#html-tags-vs.-react-components

How can I set multiple CSS styles in JavaScript?

A JavaScript library allows you to do these things very easily

jQuery

$('#myElement').css({
  font-size: '12px',
  left: '200px',
  top: '100px'
});

Object and a for-in-loop

Or, a much more elegant method is a basic object & for-loop

var el = document.getElementById('#myElement'),
    css = {
      font-size: '12px',
      left: '200px',
      top: '100px'
    };  

for(i in css){
   el.style[i] = css[i];
}

Python match a string with regex

You do not need regular expressions to check if a substring exists in a string.

line = 'This,is,a,sample,string'
result = bool('sample' in line) # returns True

If you want to know if a string contains a pattern then you should use re.search

line = 'This,is,a,sample,string'
result = re.search(r'sample', line) # finds 'sample'

This is best used with pattern matching, for example:

line = 'my name is bob'
result = re.search(r'my name is (\S+)', line) # finds 'bob'

convert base64 to image in javascript/jquery

You can just create an Image object and put the base64 as its src, including the data:image... part like this:

var image = new Image();
image.src = 'data:image/png;base64,iVBORw0K...';
document.body.appendChild(image);

It's what they call "Data URIs" and here's the compatibility table for inner peace.

How do I create a unique constraint that also allows nulls?

Maybe consider an "INSTEAD OF" trigger and do the check yourself? With a non-clustered (non-unique) index on the column to enable the lookup.

Does Java have a path joining method?

This concerns Java versions 7 and earlier.

To quote a good answer to the same question:

If you want it back as a string later, you can call getPath(). Indeed, if you really wanted to mimic Path.Combine, you could just write something like:

public static String combine (String path1, String path2) {
    File file1 = new File(path1);
    File file2 = new File(file1, path2);
    return file2.getPath();
}

ORA-00979 not a group by expression

In addition to the other answers, this error can result if there's an inconsistency in an order by clause. For instance:

select 
    substr(year_month, 1, 4)
    ,count(*) as tot
from
    schema.tbl
group by
    substr(year_month, 1, 4)
order by
    year_month

Center align with table-cell

This would be easier to do with flexbox. Using flexbox will let you not to specify the height of your content and can adjust automatically on the height it contains.

DEMO

here's the gist of the demo

.container{

  display: flex;
  height: 100%;
  justify-content: center;
  align-items: center;

}

html

<div class="container">
  <div class='content'> //you can size this anyway you want
    put anything you want here,
  </div>
</div>

enter image description here

How to POST using HTTPclient content type = application/x-www-form-urlencoded

The best solution for me is:

// Add key/value
var dict = new Dictionary<string, string>();
dict.Add("Content-Type", "application/x-www-form-urlencoded");

// Execute post method
using (var response = httpClient.PostAsync(path, new FormUrlEncodedContent(dict))){}

CSS selector for a checked radio button's label

try the + symbol: It is Adjacent sibling combinator. It combines two sequences of simple selectors having the same parent and the second one must come IMMEDIATELY after the first.

As such:

input[type="radio"]:checked+label{ font-weight: bold; } 
 //a label that immediately follows an input of type radio that is checked 

works very nicely for the following markup:

<input id="rad1" type="radio" name="rad"/><label for="rad1">Radio 1</label>
<input id="rad2" type="radio" name="rad"/><label for="rad2">Radio 2</label>

... and it will work for any structure, with or without divs etc as long as the label follows the radio input.

Example:

_x000D_
_x000D_
input[type="radio"]:checked+label { font-weight: bold; }
_x000D_
<input id="rad1" type="radio" name="rad"/><label for="rad1">Radio 1</label>_x000D_
<input id="rad2" type="radio" name="rad"/><label for="rad2">Radio 2</label>
_x000D_
_x000D_
_x000D_

How to update a single library with Composer?

Because you wanted to install specific package "I need to install only 1 package for my SF2 distribution (DoctrineFixtures)."

php composer.phar require package/package-name:package-version would be enough

C++ pointer to objects

if you want the object on the stack, try this:

MyClass myclass;
myclass.DoSomething();

If you need a pointer to that object:

MyClass* myclassptr = &myclass;
myclassptr->DoSomething();

Formatting doubles for output in C#

The answer is yes, double printing is broken in .NET, they are printing trailing garbage digits.

You can read how to implement it correctly here.

I have had to do the same for IronScheme.

> (* 10.0 0.69)
6.8999999999999995
> 6.89999999999999946709
6.8999999999999995
> (- 6.9 (* 10.0 0.69))
8.881784197001252e-16
> 6.9
6.9
> (- 6.9 8.881784197001252e-16)
6.8999999999999995

Note: Both C and C# has correct value, just broken printing.

Update: I am still looking for the mailing list conversation I had that lead up to this discovery.

A field initializer cannot reference the nonstatic field, method, or property

private dynamic defaultReminder = reminder.TimeSpanText[TimeSpan.FromMinutes(15)]; is a field initializer and executes first (before any field without an initializer is set to its default value and before the invoked instance constructor is executed). Instance fields that have no initializer will only have a legal (default) value after all instance field initializers are completed. Due to the initialization order, instance constructors are executed last, which is why the instance is not created yet the moment the initializers are executed. Therefore the compiler cannot allow any instance property (or field) to be referenced before the class instance is fully constructed. This is because any access to an instance variable like reminder implicitly references the instance (this) to tell the compiler the concrete memory location of the instance to use.

This is also the reason why this is not allowed in an instance field initializer.

A variable initializer for an instance field cannot reference the instance being created. Thus, it is a compile-time error to reference this in a variable initializer, as it is a compile-time error for a variable initializer to reference any instance member through a simple_name.

The only type members that are guaranteed to be initialized before instance field initializers are executed are class (static) field initializers and class (static) constructors and class methods. Since static members are instance independent, they can be referenced at any time:

class SomeOtherClass
{
  private static Reminders reminder = new Reminders();

  // This operation is allowed,
  // since the compiler can guarantee that the referenced class member is already initialized
  // when this instance field initializer executes
  private dynamic defaultReminder = reminder.TimeSpanText[TimeSpan.FromMinutes(15)];
}

That's why instance field initializers are only allowed to reference a class member (static member). This compiler initialization rules will ensure a deterministic type instantiation.

For more details I recommend this document: Microsoft Docs: Class declarations.

This means that an instance field that references another instance member to initialize its value, must be initialized from the instance constructor or the referenced member must be declared static.

How to force a component's re-rendering in Angular 2?

ChangeDetectorRef approach

import { Component, OnInit, ChangeDetectorRef } from '@angular/core';

export class MyComponent {

    constructor(private cdr: ChangeDetectorRef) { }

    selected(item: any) {
        if (item == 'Department')
            this.isDepartment = true;
        else
            this.isDepartment = false;
        this.cdr.detectChanges();
    }

}

Create <div> and append <div> dynamically

Well, I don't know how dynamic this is is, but sometimes this might save your debugging life:

var daString="<div id=\'block\' class=\'block\'><div class=\'block-2\'></div></div>";
var daParent=document.getElementById("the ID of whatever your parent is goes in here");
daParent.innerHTML=daString;

"Rat javascript" If I did it correctly. Works for me directly when the div and contents are not themselves dynamic of course, or you can even manipulate the string to change that too, though the string manipulating is complex than the "element.property=bla" approach, this gives some very welcome flexibility, and is a great debugging tool too :) Hope it helps.

Remove "Using default security password" on Spring Boot

To remove default user you need to configure authentication menager with no users for example:

@configuration
class WebSecurityConfig extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(AuthenticationManagerBuilder auth) throws Exception {
        auth.inMemoryAuthentication();
    }
}

this will remove default password message and default user because in that case you are configuring InMemoryAuthentication and you will not specify any user in next steps

How to make MySQL handle UTF-8 properly

The charset is a property of the database (default) and the table. You can have a look (MySQL commands):

show create database foo; 
> CREATE DATABASE  `foo`.`foo` /*!40100 DEFAULT CHARACTER SET latin1 */

show create table foo.bar;
> lots of stuff ending with
> ) ENGINE=InnoDB AUTO_INCREMENT=252 DEFAULT CHARSET=latin1

In other words; it's quite easy to check your database charset or change it:

ALTER TABLE `foo`.`bar` CHARACTER SET utf8;

Regex: ignore case sensitivity

The i flag is normally used for case insensitivity. You don't give a language here, but it'll probably be something like /G[ab].*/i or /(?i)G[ab].*/.

Capture Image from Camera and Display in Activity

Here is the complete code:

package com.example.cameraa;
import android.app.Activity;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;

public class MainActivity extends Activity {




        Button btnTackPic;
        Uri photoPath;
        ImageView ivThumbnailPhoto;

        static int TAKE_PICTURE = 1;

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

            // Get reference to views

            btnTackPic = (Button) findViewById(R.id.bt1);
            ivThumbnailPhoto = (ImageView) findViewById(R.id.imageView1);




     btnTackPic.setOnClickListener(new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub


                Intent cameraIntent = new Intent(android.provider.MediaStore.ACTION_IMAGE_CAPTURE); 
                startActivityForResult(cameraIntent, TAKE_PICTURE); 
            }




    });

        } 

        @Override
        protected void onActivityResult(int requestCode, int resultCode, Intent intent) {


                if (requestCode == TAKE_PICTURE && resultCode == RESULT_OK) {  
                    Bitmap photo = (Bitmap)intent.getExtras().get("data"); 
                   ivThumbnailPhoto.setImageBitmap(photo);
                ivThumbnailPhoto.setVisibility(View.VISIBLE);



            }
        }
}

Remember to add permissions for the camera too.

C char array initialization

This is not how you initialize an array, but for:

  1. The first declaration:

    char buf[10] = "";
    

    is equivalent to

    char buf[10] = {0, 0, 0, 0, 0, 0, 0, 0, 0, 0};
    
  2. The second declaration:

    char buf[10] = " ";
    

    is equivalent to

    char buf[10] = {' ', 0, 0, 0, 0, 0, 0, 0, 0, 0};
    
  3. The third declaration:

    char buf[10] = "a";
    

    is equivalent to

    char buf[10] = {'a', 0, 0, 0, 0, 0, 0, 0, 0, 0};
    

As you can see, no random content: if there are fewer initializers, the remaining of the array is initialized with 0. This the case even if the array is declared inside a function.

Get values from a listbox on a sheet

Take selected value:

worksheet name = ordls
form control list box name = DEPDB1

selectvalue = ordls.Shapes("DEPDB1").ControlFormat.List(ordls.Shapes("DEPDB1").ControlFormat.Value)

importing pyspark in python shell

I had this same problem and would add one thing to the proposed solutions above. When using Homebrew on Mac OS X to install Spark you will need to correct the py4j path address to include libexec in the path (remembering to change py4j version to the one you have);

PYTHONPATH=$SPARK_HOME/libexec/python/lib/py4j-0.9-src.zip:$PYTHONPATH

How to fill background image of an UIView

You need to process the image beforehand, to make a centered and stretched image. Try this:

UIGraphicsBeginImageContext(self.view.frame.size);
[[UIImage imageNamed:@"image.png"] drawInRect:self.view.bounds];
UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
UIGraphicsEndImageContext();

self.view.backgroundColor = [UIColor colorWithPatternImage:image];

How to undo local changes to a specific file

You don't want git revert. That undoes a previous commit. You want git checkout to get git's version of the file from master.

git checkout -- filename.txt

In general, when you want to perform a git operation on a single file, use -- filename.



2020 Update

Git introduced a new command git restore in version 2.23.0. Therefore, if you have git version 2.23.0+, you can simply git restore filename.txt - which does the same thing as git checkout -- filename.txt. The docs for this command do note that it is currently experimental.

How to create a simple checkbox in iOS?

Yeah, no checkbox for you in iOS (-:

Here, this is what I did to create a checkbox:

UIButton *checkbox;
BOOL checkBoxSelected;
checkbox = [[UIButton alloc] initWithFrame:CGRectMake(x,y,20,20)];
// 20x20 is the size of the checkbox that you want
// create 2 images sizes 20x20 , one empty square and
// another of the same square with the checkmark in it
// Create 2 UIImages with these new images, then:

[checkbox setBackgroundImage:[UIImage imageNamed:@"notselectedcheckbox.png"]
                    forState:UIControlStateNormal];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
                    forState:UIControlStateSelected];
[checkbox setBackgroundImage:[UIImage imageNamed:@"selectedcheckbox.png"]
                    forState:UIControlStateHighlighted];
checkbox.adjustsImageWhenHighlighted=YES;
[checkbox addTarget:(nullable id) action:(nonnull SEL) forControlEvents:(UIControlEvents)];
[self.view addSubview:checkbox];

Now in the target method do the following:

-(void)checkboxSelected:(id)sender
{
    checkBoxSelected = !checkBoxSelected; /* Toggle */
    [checkbox setSelected:checkBoxSelected];
}

That's it!

C compiler for Windows?

You may try Code::Blocks, which is better IDE and comes with MinGW GCC! I have used it and its just too good a freeware IDE for C/C++.

Open S3 object as a string with Boto3

read will return bytes. At least for Python 3, if you want to return a string, you have to decode using the right encoding:

import boto3

s3 = boto3.resource('s3')

obj = s3.Object(bucket, key)
obj.get()['Body'].read().decode('utf-8') 

What does the ^ (XOR) operator do?

Another application for XOR is in circuits. It is used to sum bits.

When you look at a truth table:

 x | y | x^y
---|---|-----
 0 | 0 |  0     // 0 plus 0 = 0 
 0 | 1 |  1     // 0 plus 1 = 1
 1 | 0 |  1     // 1 plus 0 = 1
 1 | 1 |  0     // 1 plus 1 = 0 ; binary math with 1 bit

You can notice that the result of XOR is x added with y, without keeping track of the carry bit, the carry bit is obtained from the AND between x and y.

x^y // is actually ~xy + ~yx
    // Which is the (negated x ANDed with y) OR ( negated y ANDed with x ).

How do I detect if a user is already logged in Firebase?

It is not possible to tell whether a user will be signed when a page starts loading, there is a work around though.

You can memorize last auth state to localStorage to persist it between sessions and between tabs.

Then, when page starts loading, you can optimistically assume the user will be re-signed in automatically and postpone the dialog until you can be sure (ie after onAuthStateChanged fires). Otherwise, if the localStorage key is empty, you can show the dialog right away.

The firebase onAuthStateChanged event will fire roughly 2 seconds after a page load.

// User signed out in previous session, show dialog immediately because there will be no auto-login
if (!localStorage.getItem('myPage.expectSignIn')) showDialog() // or redirect to sign-in page

firebase.auth().onAuthStateChanged(user => {
  if (user) {
    // User just signed in, we should not display dialog next time because of firebase auto-login
    localStorage.setItem('myPage.expectSignIn', '1')
  } else {
    // User just signed-out or auto-login failed, we will show sign-in form immediately the next time he loads the page
    localStorage.removeItem('myPage.expectSignIn')

    // Here implement logic to trigger the login dialog or redirect to sign-in page, if necessary. Don't redirect if dialog is already visible.
    // e.g. showDialog()
  }
})



I am using this with React and react-router. I put the code above into componentDidMount of my App root component. There, in the render, I have some PrivateRoutes

<Router>
  <Switch>
    <PrivateRoute
      exact path={routes.DASHBOARD}
      component={pages.Dashboard}
    />
...

And this is how my PrivateRoute is implemented:

export default function PrivateRoute(props) {
  return firebase.auth().currentUser != null
    ? <Route {...props}/>
    : localStorage.getItem('myPage.expectSignIn')
      // if user is expected to sign in automatically, display Spinner, otherwise redirect to login page.
      ? <Spinner centered size={400}/>
      : (
        <>
          Redirecting to sign in page.
          { location.replace(`/login?from=${props.path}`) }
        </>
      )
}

    // Using router Redirect instead of location.replace
    // <Redirect
    //   from={props.path}
    //   to={{pathname: routes.SIGN_IN, state: {from: props.path}}}
    // />

CSS Auto hide elements after 5 seconds

YES!

But you can't do it in the way you may immediately think, because you cant animate or create a transition around the properties you'd otherwise rely on (e.g. display, or changing dimensions and setting to overflow:hidden) in order to correctly hide the element and prevent it from taking up visible space.

Therefore, create an animation for the elements in question, and simply toggle visibility:hidden; after 5 seconds, whilst also setting height and width to zero to prevent the element from still occupying space in the DOM flow.

FIDDLE

CSS

html, body {
    height:100%;
    width:100%;
    margin:0;
    padding:0;
}
#hideMe {
    -moz-animation: cssAnimation 0s ease-in 5s forwards;
    /* Firefox */
    -webkit-animation: cssAnimation 0s ease-in 5s forwards;
    /* Safari and Chrome */
    -o-animation: cssAnimation 0s ease-in 5s forwards;
    /* Opera */
    animation: cssAnimation 0s ease-in 5s forwards;
    -webkit-animation-fill-mode: forwards;
    animation-fill-mode: forwards;
}
@keyframes cssAnimation {
    to {
        width:0;
        height:0;
        overflow:hidden;
    }
}
@-webkit-keyframes cssAnimation {
    to {
        width:0;
        height:0;
        visibility:hidden;
    }
}

HTML

<div id='hideMe'>Wait for it...</div>

How to split() a delimited string to a List<String>

string.Split() returns an array - you can convert it to a list using ToList():

listStrLineElements = line.Split(',').ToList();

Note that you need to import System.Linq to access the .ToList() function.

Regular expression to get a string between two strings in Javascript

Task

Extract substring between two string (excluding this two strings)

Solution

let allText = "Lorem Ipsum is simply dummy text of the printing and typesetting industry. Lorem Ipsum has been the industry's standard dummy text ever since the 1500s, when an unknown printer took a galley of type and scrambled it to make a type specimen book. It has survived not only five centuries, but also the leap into electronic typesetting, remaining essentially unchanged. It was popularised in the 1960s with the release of Letraset sheets containing Lorem Ipsum passages, and more recently with desktop publishing software like Aldus PageMaker including versions of Lorem Ipsum";
let textBefore = "five centuries,";
let textAfter = "electronic typesetting";
var regExp = new RegExp(`(?<=${textBefore}\\s)(.+?)(?=\\s+${textAfter})`, "g");
var results = regExp.exec(allText);
if (results && results.length > 1) {
    console.log(results[0]);
}

WorksheetFunction.CountA - not working post upgrade to Office 2010

It seems there is a change in how Application.COUNTA works in VB7 vs VB6. I tried the following in both versions of VB.

   ReDim allData(0 To 1, 0 To 15)
   Debug.Print Application.WorksheetFunction.CountA(allData)

In VB6 this returns 0.

Inn VB7 it returns 32

Looks like VB7 doesn't consider COUNTA to be COUNTA anymore.

jQuery click function doesn't work after ajax call?

$('body').delegate('.deletelanguage','click',function(){
    alert("success");
});

or

$('body').on('click','.deletelanguage',function(){
    alert("success");
});

Assembly - JG/JNLE/JL/JNGE after CMP

When you do a cmp a,b, the flags are set as if you had calculated a - b.

Then the jmp-type instructions check those flags to see if the jump should be made.

In other words, the first block of code you have (with my comments added):

cmp al,dl     ; set flags based on the comparison
jg label1     ; then jump based on the flags

would jump to label1 if and only if al was greater than dl.

You're probably better off thinking of it as al > dl but the two choices you have there are mathematically equivalent:

al > dl
al - dl > dl - dl (subtract dl from both sides)
al - dl > 0       (cancel the terms on the right hand side)

You need to be careful when using jg inasmuch as it assumes your values were signed. So, if you compare the bytes 101 (101 in two's complement) with 200 (-56 in two's complement), the former will actually be greater. If that's not what was desired, you should use the equivalent unsigned comparison.

See here for more detail on jump selection, reproduced below for completeness. First the ones where signed-ness is not appropriate:

+--------+------------------------------+-------------+--------------------+
|Instr   | Description                  | signed-ness | Flags              |
+--------+------------------------------+-------------+--------------------+
| JO     | Jump if overflow             |             | OF = 1             |
+--------+------------------------------+-------------+--------------------+
| JNO    | Jump if not overflow         |             | OF = 0             |
+--------+------------------------------+-------------+--------------------+
| JS     | Jump if sign                 |             | SF = 1             |
+--------+------------------------------+-------------+--------------------+
| JNS    | Jump if not sign             |             | SF = 0             |
+--------+------------------------------+-------------+--------------------+
| JE/    | Jump if equal                |             | ZF = 1             |
| JZ     | Jump if zero                 |             |                    |
+--------+------------------------------+-------------+--------------------+
| JNE/   | Jump if not equal            |             | ZF = 0             |
| JNZ    | Jump if not zero             |             |                    |
+--------+------------------------------+-------------+--------------------+
| JP/    | Jump if parity               |             | PF = 1             |
| JPE    | Jump if parity even          |             |                    |
+--------+------------------------------+-------------+--------------------+
| JNP/   | Jump if no parity            |             | PF = 0             |
| JPO    | Jump if parity odd           |             |                    |
+--------+------------------------------+-------------+--------------------+
| JCXZ/  | Jump if CX is zero           |             | CX = 0             |
| JECXZ  | Jump if ECX is zero          |             | ECX = 0            |
+--------+------------------------------+-------------+--------------------+

Then the unsigned ones:

+--------+------------------------------+-------------+--------------------+
|Instr   | Description                  | signed-ness | Flags              |
+--------+------------------------------+-------------+--------------------+
| JB/    | Jump if below                | unsigned    | CF = 1             |
| JNAE/  | Jump if not above or equal   |             |                    |
| JC     | Jump if carry                |             |                    |
+--------+------------------------------+-------------+--------------------+
| JNB/   | Jump if not below            | unsigned    | CF = 0             |
| JAE/   | Jump if above or equal       |             |                    |
| JNC    | Jump if not carry            |             |                    |
+--------+------------------------------+-------------+--------------------+
| JBE/   | Jump if below or equal       | unsigned    | CF = 1 or ZF = 1   |
| JNA    | Jump if not above            |             |                    |
+--------+------------------------------+-------------+--------------------+
| JA/    | Jump if above                | unsigned    | CF = 0 and ZF = 0  |
| JNBE   | Jump if not below or equal   |             |                    |
+--------+------------------------------+-------------+--------------------+

And, finally, the signed ones:

+--------+------------------------------+-------------+--------------------+
|Instr   | Description                  | signed-ness | Flags              |
+--------+------------------------------+-------------+--------------------+
| JL/    | Jump if less                 | signed      | SF <> OF           |
| JNGE   | Jump if not greater or equal |             |                    |
+--------+------------------------------+-------------+--------------------+
| JGE/   | Jump if greater or equal     | signed      | SF = OF            |
| JNL    | Jump if not less             |             |                    |
+--------+------------------------------+-------------+--------------------+
| JLE/   | Jump if less or equal        | signed      | ZF = 1 or SF <> OF |
| JNG    | Jump if not greater          |             |                    |
+--------+------------------------------+-------------+--------------------+
| JG/    | Jump if greater              | signed      | ZF = 0 and SF = OF |
| JNLE   | Jump if not less or equal    |             |                    |
+--------+------------------------------+-------------+--------------------+

Laravel 5.1 API Enable Cors

just use this as a middleware

<?php

namespace App\Http\Middleware;

use Closure;

class CorsMiddleware
{
    /**
     * Handle an incoming request.
     *
     * @param  \Illuminate\Http\Request  $request
     * @param  \Closure  $next
     * @return mixed
     */
    public function handle($request, Closure $next)
    {
        $response = $next($request);
        $response->header('Access-Control-Allow-Origin', '*');
        $response->header('Access-Control-Allow-Methods', '*');

        return $response;
    }
}

and register the middleware in your kernel file on this path app/Http/Kernel.php in which group that you prefer and everything will be fine

What is the difference between “int” and “uint” / “long” and “ulong”?

The difference is that the uint and ulong are unsigned data types, meaning the range is different: They do not accept negative values:

int range: -2,147,483,648 to 2,147,483,647
uint range: 0 to 4,294,967,295

long range: –9,223,372,036,854,775,808 to 9,223,372,036,854,775,807
ulong range: 0 to 18,446,744,073,709,551,615

Saving the PuTTY session logging

To set permanent PuTTY session parameters do:

  1. Create sessions in PuTTY. Name it as "MyskinPROD"

  2. Configure the path for this session to point to "C:\dir\&Y&M&D&T_&H_putty.log".

  3. Create a Windows "Shortcut" to C:...\Putty.exe.

  4. Open "Shortcut" Properties and append "Target" line with parameters as shown below:

    "C:\Program Files (x86)\UTL\putty.exe" -ssh -load MyskinPROD user@ServerIP -pw password
    

Now, your PuTTY shortcut will bring in the "MyskinPROD" configuration every time you open the shortcut.

Check the screenshots and details on how I did it in my environment:

http://www.evernote.com/shard/s184/sh/93ebf08f-fde2-4dad-bccf-961c98fb614b/983d2ff8f2d1e6184318825d68b0b829

Hive query output to file

The following query will insert the results directly into HDFS:

INSERT OVERWRITE DIRECTORY '/path/to/output/dir' SELECT * FROM table WHERE id > 100;

How to go back (ctrl+z) in vi/vim

You can use the u button to undo the last modification. (And Ctrl+R to redo it).

Read more about it at: http://vim.wikia.com/wiki/Undo_and_Redo

catch forEach last iteration

Updated answer for ES6+ is here.


arr = [1, 2, 3]; 

arr.forEach(function(i, idx, array){
   if (idx === array.length - 1){ 
       console.log("Last callback call at index " + idx + " with value " + i ); 
   }
});

would output:

Last callback call at index 2 with value 3

The way this works is testing arr.length against the current index of the array, passed to the callback function.

remove double quotes from Json return data using Jquery

I dont think there is a need to replace any quotes, this is a perfectly formed JSON string, you just need to convert JSON string into object.This article perfectly explains the situation : Link

Example :

success: function (data) {

        // assuming that everything is correct and there is no exception being thrown
        // output string {"d":"{"username":"hi","email":"[email protected]","password":"123"}"}
        // now we need to remove the double quotes (as it will create problem and 
        // if double quotes aren't removed then this JSON string is useless)
        // The output string : {"d":"{"username":"hi","email":"[email protected]","password":"123"}"}
        // The required string : {"d":{username:"hi",email:"[email protected]",password:"123"}"}
        // For security reasons the d is added (indicating the return "data")
        // so actually we need to convert data.d into series of objects
        // Inbuilt function "JSON.Parse" will return streams of objects
        // JSON String : "{"username":"hi","email":"[email protected]","password":"123"}"
        console.log(data);                     // output  : Object {d="{"username":"hi","email":"[email protected]","password":"123"}"}
        console.log(data.d);                   // output : {"username":"hi","email":"[email protected]","password":"123"} (accessing what's stored in "d")
        console.log(data.d[0]);                // output : {  (just accessing the first element of array of "strings")
        var content = JSON.parse(data.d);      // output : Object {username:"hi",email:"[email protected]",password:"123"}" (correct)
        console.log(content.username);         // output : hi 
        var _name = content.username;
        alert(_name);                         // hi

}

How do I restart my C# WinForm Application?

It's simple, you just need to call the Application.Restart() method, this will invoke your application to be restarted. You must also exit from the local environment with an error code:

Application.Restart();
Environment.Exit(int errorcode);
   

You can create an enumeration of error codes so that you application will exit efficeintly.
Another method is to just exit from the application and start the process using the executable path:

Application.Exit();
System.Diagnostics.Process.Start(Application.ExecutablePath);

Server.MapPath - Physical path given, virtual path expected

if you already know your folder is: E:\ftproot\sales then you do not need to use Server.MapPath, this last one is needed if you only have a relative virtual path like ~/folder/folder1 and you want to know the real path in the disk...

How to initialise memory with new operator in C++?

Yes there is:

std::vector<int> vec(SIZE, 0);

Use a vector instead of a dynamically allocated array. Benefits include not having to bother with explicitely deleting the array (it is deleted when the vector goes out of scope) and also that the memory is automatically deleted even if there is an exception thrown.

Edit: To avoid further drive-by downvotes from people that do not bother to read the comments below, I should make it more clear that this answer does not say that vector is always the right answer. But it sure is a more C++ way than "manually" making sure to delete an array.

Now with C++11, there is also std::array that models a constant size array (vs vector that is able to grow). There is also std::unique_ptr that manages a dynamically allocated array (that can be combined with initialization as answered in other answers to this question). Any of those are a more C++ way than manually handling the pointer to the array, IMHO.

"Missing return statement" within if / for / while

Any how myMethod() should return a String value .what if your condition is false is myMethod return anything? ans is no so you need to define return null or some string value in false condition

public String myMethod() {
    boolean c=true;
    if (conditions) {
        return "d";
    }
    return null;//or some other string value
}

JSTL if tag for equal strings

<c:if test="${ansokanInfo.pSystem eq 'NAT'}">

CSS body background image fixed to full screen even when zooming in/out

Use Directly like this

.bg-div{
     background: url(../img/beach.jpg) no-repeat fixed 100% 100%;
}

or call CSS separately like

.bg-div{
    background-image: url(../img/beach.jpg);
    -moz-background-size: cover;
    -webkit-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

json_encode() escaping forward slashes

On the flip side, I was having an issue with PHPUNIT asserting urls was contained in or equal to a url that was json_encoded -

my expected:

http://localhost/api/v1/admin/logs/testLog.log

would be encoded to:

http:\/\/localhost\/api\/v1\/admin\/logs\/testLog.log

If you need to do a comparison, transforming the url using:

addcslashes($url, '/')

allowed for the proper output during my comparisons.

How to get the cell value by column name not by index in GridView in asp.net

Based on something found on Code Project

Once the data table is declared based on the grid's data source, lookup the column index by column name from the columns collection. At this point, use the index as needed to obtain information from or to format the cell.

protected void gridMyGrid_RowDataBound(object sender, GridViewRowEventArgs e)
{
    if (e.Row.RowType == DataControlRowType.DataRow)
    {
        DataTable dt = (DataTable)((GridView)sender).DataSource;
        int colIndex = dt.Columns["MyColumnName"].Ordinal;

        e.Row.Cells[colIndex].BackColor = Color.FromName("#ffeb9c");
    }
}

PHP server on local machine?

If you want an all-purpose local development stack for any operating system where you can choose from different PHP, MySQL and Web server versions and are also not afraid of using Docker, you could go for the devilbox.

The devilbox is a modern and highly customisable dockerized PHP stack supporting full LAMP and MEAN and running on all major platforms. The main goal is to easily switch and combine any version required for local development. It supports an unlimited number of projects for which vhosts and DNS records are created automatically. Email catch-all and popular development tools will be at your service as well. Configuration is not necessary, as everything is pre-setup with mass virtual hosting.

Getting it up and running is pretty straight-forward:

# Get the devilbox
$ git clone https://github.com/cytopia/devilbox
$ cd devilbox

# Create docker-compose environment file
$ cp env-example .env

# Edit your configuration
$ vim .env

# Start all containers
$ docker-compose up

devilbox

Links:

What is the easiest way to remove all packages installed by pip?

I simply wanted to remove packages installed by the project, and not other packages I've installed (things like neovim, mypy and pudb which I use for local dev but are not included in the app requirements). So I did:

cat requirements.txt| sed 's/=.*//g' | xargs pip uninstall -y

which worked well for me.

Uninstall old versions of Ruby gems

You might need to set GEM_HOME for the cleanup to work. You can check what paths exist for gemfiles by running:

gem env

Take note of the GEM PATHS section.

In my case, for example, with gems installed in my user home:

export GEM_HOME="~/.gem/ruby/2.4.0"
gem cleanup

jQuery - on change input text

This worked for me

var change_temp = "";
$('#url_key').bind('keydown keyup',function(e){
    if(e.type == "keydown"){
        change_temp = $(this).val();
        return;
    }
    if($(this).val() != change_temp){
        // add the code to on change here 
    }

});

How to change target build on Android project?

Another way on the command line if you are using ant is to use the android.bat script (Windows) or android script (Mac). It's in $SDK_DIR/tools.

If you say,

android.bat update project --path .  --target "android-8"

it will regenerate your build.xml, AndroidManifest.xml, etc.

How do I find the width & height of a terminal window?

And there's stty, from coreutils

$ stty size
60 120 # <= sample output

It will print the number of rows and columns, or height and width, respectively.

Then you can use either cut or awk to extract the part you want.

That's stty size | cut -d" " -f1 for the height/lines and stty size | cut -d" " -f2 for the width/columns