Programs & Examples On #Pascalcasing

Pascal case is a language-independent naming convention in which each word of an identifier name begins with a capital letter, such as CustomerName, CustomerId, etc.

JSON Naming Convention (snake_case, camelCase or PascalCase)

As others have stated there is no standard so you should choose one yourself. Here are a couple of things to consider when doing so:

  1. If you are using JavaScript to consume JSON then using the same naming convention for properties in both will provide visual consistency and possibly some opportunities for cleaner code re-use.

  2. A small reason to avoid kebab-case is that the hyphens may clash visually with - characters that appear in values.

    {
      "bank-balance": -10
    }
    

How to completely remove Python from a Windows machine?

Uninstall the python program using the windows GUI. Delete the containing folder e.g if it was stored in C:\python36\ make sure to delete that folder

Has anyone ever got a remote JMX JConsole to work?

You are probably experiencing an issue with a firewall. The 'problem' is that the port you specify is not the only port used, it uses 1 or maybe even 2 more ports for RMI, and those are probably blocked by a firewall.

One of the extra ports will not be know up front if you use the default RMI configuration, so you have to open up a big range of ports - which might not amuse the server administrator.

There is a solution that does not require opening up a lot of ports however, I've gotten it to work using the combined source snippets and tips from

http://forums.sun.com/thread.jspa?threadID=5267091 - link doesn't work anymore

http://blogs.oracle.com/jmxetc/entry/connecting_through_firewall_using_jmx

http://java.sun.com/javase/6/docs/technotes/guides/management/agent.html

It's even possible to setup an ssh tunnel and still get it to work :-)

How to increase Heap size of JVM

Following are few options available to change Heap Size.

-Xms<size>        set initial Java heap size
-Xmx<size>        set maximum Java heap size
-Xss<size>        set java thread stack size


java -Xmx256m TestData.java

Fatal error: Allowed memory size of 134217728 bytes exhausted (tried to allocate 32 bytes)

Well try ini_set('memory_limit', '256M');

134217728 bytes = 128 MB

Or rewrite the code to consume less memory.

Change DIV content using ajax, php and jQuery

<script>

function getSummary(id)
{
   $.ajax({

     type: "GET",
     url: 'Your URL',
     data: "id=" + id, // appears as $_GET['id'] @ your backend side
     success: function(data) {
           // data is ur summary
          $('#summary').html(data);
     }

   });

}
</script>

And add onclick event in your lists

<a onclick="getSummary('1')">View Text</a>
<div id="#summary">This text will be replaced when the onclick event (link is clicked) is triggered.</div>

Visual Studio C# IntelliSense not automatically displaying

A new cause for this in the .net core era is having a project loaded for an unsupported .net core version. For instance if you loaded a project from GitHub that was set to use:

  <PropertyGroup>
    <TargetFramework>netcoreapp2.2</TargetFramework>
    <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
  </PropertyGroup>

But you only have 2.1 installed or find yourself using Visual Studio 2017 then the compiler wont be able to find the SDK code and thus provide intellisense.

The solution in that case might be to right click on your project and select Edit MyProject.csproj from the context menu and change the target framework as necessary:

  <PropertyGroup>
    <TargetFramework>netcoreapp2.1</TargetFramework>
    <AspNetCoreHostingModel>InProcess</AspNetCoreHostingModel>
  </PropertyGroup>

This assumes whatever project you loaded can actually be run under a lesser target framework.

Why am I getting "Unable to find manifest signing certificate in the certificate store" in my Excel Addin?

Make sure you commit .pfx files to repository.

I just found *.pfx in my default .gitignore. Comment it (by #) and commit changes. Then pull repository and rebuild.

C# - What does the Assert() method do? Is it still useful?

Assert also gives you another opportunity to chuckle at Microsoft's UI design skills. I mean: a dialog with three buttons Abort, Retry, Ignore, and an explanation of how to interpret them in the title bar!

Convert date to datetime in Python

You can use the date.timetuple() method and unpack operator *.

args = d.timetuple()[:6]
datetime.datetime(*args)

android studio 0.4.2: Gradle project sync failed error

I have Android Studio 0.8.9 and after hours on forums the thing that finally worked for me was to manually download Gradle (latest version) then go to: C:\Users\.gradle\wrapper\dists\gradle-1.12-all\\ and replace the local archive with the recently downloaded archive and also replace the extracted data; after restarting Android Studio... he did some downloadings and builds and all sorts of stuff, but it finally worked.. Good Luck people!

what does numpy ndarray shape do?

array([[1, 2, 3],
[4, 5, 6],
[7, 8, 9]])

enter image description here

How do I see what character set a MySQL database / table / column is?

For databases:

SELECT SCHEMA_NAME 'database', default_character_set_name 'charset', DEFAULT_COLLATION_NAME 'collation' FROM information_schema.SCHEMATA;

Example output:

mysql> SELECT SCHEMA_NAME 'database', default_character_set_name 'charset', DEFAULT_COLLATION_NAME 'collation' FROM information_schema.SCHEMATA;
+----------------------------+---------+--------------------+
| database                   | charset | collation          |
+----------------------------+---------+--------------------+
| information_schema         | utf8    | utf8_general_ci    |
| drupal_demo1               | utf8    | utf8_general_ci    |
| drupal_demo2               | utf8    | utf8_general_ci    |
| drupal_demo3               | utf8    | utf8_general_ci    |
| drupal_demo4               | utf8    | utf8_general_ci    |
| drupal_demo5               | latin1  | latin1_swedish_ci  |

...

+----------------------------+---------+--------------------+
55 rows in set (0.00 sec)

mysql> 

How to find the nearest parent of a Git branch?

vbc=$(git rev-parse --abbrev-ref HEAD)
vbc_col=$(( $(git show-branch | grep '^[^\[]*\*' | head -1 | cut -d* -f1 | wc -c) - 1 )) 
swimming_lane_start_row=$(( $(git show-branch | grep -n "^[\-]*$" | cut -d: -f1) + 1 )) 
git show-branch | tail -n +$swimming_lane_start_row | grep -v "^[^\[]*\[$vbc" | grep "^.\{$vbc_col\}[^ ]" | head -n1 | sed 's/.*\[\(.*\)\].*/\1/' | sed 's/[\^~].*//'

Achieves the same ends as Mark Reed's answer, but uses a much safer approach that doesn't misbehave in a number of scenarios:

  1. Parent branch's last commit is a merge, making the column show - not *
  2. Commit message contains branch name
  3. Commit message contains *

Identifying country by IP address

Yes, you can download the IP address ranges by country from https://lite.ip2location.com/ip-address-ranges-by-country

You can see that each country has multiple ranges and changes frequently.

How to put/get multiple JSONObjects to JSONArray?

Once you have put the values into the JSONObject then put the JSONObject into the JSONArray staright after.

Something like this maybe:

jsonObj.put("value1", 1);
jsonObj.put("value2", 900);
jsonObj.put("value3", 1368349);
jsonArray.put(jsonObj);

Then create new JSONObject, put the other values into it and add it to the JSONArray:

jsonObj.put("value1", 2);
jsonObj.put("value2", 1900);
jsonObj.put("value3", 136856);
jsonArray.put(jsonObj);

How do I delete multiple rows in Entity Framework (without foreach)

using (var context = new DatabaseEntities())
{
    context.ExecuteStoreCommand("DELETE FROM YOURTABLE WHERE CustomerID = {0}", customerId);
}

Regex matching in a Bash if statement

There are a couple of important things to know about bash's [[ ]] construction. The first:

Word splitting and pathname expansion are not performed on the words between the [[ and ]]; tilde expansion, parameter and variable expansion, arithmetic expansion, command substitution, process substitution, and quote removal are performed.

The second thing:

An additional binary operator, ‘=~’, is available,... the string to the right of the operator is considered an extended regular expression and matched accordingly... Any part of the pattern may be quoted to force it to be matched as a string.

Consequently, $v on either side of the =~ will be expanded to the value of that variable, but the result will not be word-split or pathname-expanded. In other words, it's perfectly safe to leave variable expansions unquoted on the left-hand side, but you need to know that variable expansions will happen on the right-hand side.

So if you write: [[ $x =~ [$0-9a-zA-Z] ]], the $0 inside the regex on the right will be expanded before the regex is interpreted, which will probably cause the regex to fail to compile (unless the expansion of $0 ends with a digit or punctuation symbol whose ascii value is less than a digit). If you quote the right-hand side like-so [[ $x =~ "[$0-9a-zA-Z]" ]], then the right-hand side will be treated as an ordinary string, not a regex (and $0 will still be expanded). What you really want in this case is [[ $x =~ [\$0-9a-zA-Z] ]]

Similarly, the expression between the [[ and ]] is split into words before the regex is interpreted. So spaces in the regex need to be escaped or quoted. If you wanted to match letters, digits or spaces you could use: [[ $x =~ [0-9a-zA-Z\ ] ]]. Other characters similarly need to be escaped, like #, which would start a comment if not quoted. Of course, you can put the pattern into a variable:

pat="[0-9a-zA-Z ]"
if [[ $x =~ $pat ]]; then ...

For regexes which contain lots of characters which would need to be escaped or quoted to pass through bash's lexer, many people prefer this style. But beware: In this case, you cannot quote the variable expansion:

# This doesn't work:
if [[ $x =~ "$pat" ]]; then ...

Finally, I think what you are trying to do is to verify that the variable only contains valid characters. The easiest way to do this check is to make sure that it does not contain an invalid character. In other words, an expression like this:

valid='0-9a-zA-Z $%&#' # add almost whatever else you want to allow to the list
if [[ ! $x =~ [^$valid] ]]; then ...

! negates the test, turning it into a "does not match" operator, and a [^...] regex character class means "any character other than ...".

The combination of parameter expansion and regex operators can make bash regular expression syntax "almost readable", but there are still some gotchas. (Aren't there always?) One is that you could not put ] into $valid, even if $valid were quoted, except at the very beginning. (That's a Posix regex rule: if you want to include ] in a character class, it needs to go at the beginning. - can go at the beginning or the end, so if you need both ] and -, you need to start with ] and end with -, leading to the regex "I know what I'm doing" emoticon: [][-])

SyntaxError: expected expression, got '<'

The main idea is that somehow HTML has been returned instead of Javascript.

The reason may be:

  • wrong paths
  • assets itself

It may be caused by wrong assets precompilation. In my case, I caught this error because of wrong encoding.

When I opened my application.js I saw application error Encoding::UndefinedConversionError at /assets/application.js

There was full backtrace of error formatted as HTML instead of Javasript.

Make sure that assets had been successfully precompiled.

Run function from the command line

I had a requirement of using various python utilities (range, string, etc.) on the command line and had written the tool pyfunc specifically for that. You can use it to enrich you command line usage experience:

 $ pyfunc -m range -a 1 7 2
 1
 3
 5

 $ pyfunc -m string.upper -a test
 TEST

 $ pyfunc -m string.replace -a 'analyze what' 'what' 'this'
 analyze this

Rendering an array.map() in React

You are implicitly returning undefined. You need to return the element.

this.state.data.map(function(item, i){
  console.log('test');
  return <li>Test</li>
})

Remove char at specific index - python

Try this code:

s = input() 
a = int(input()) 
b = s.replace(s[a],'')
print(b)

Arrays.fill with multidimensional array in Java

how can I fill a multidimensional array in Java without using a loop?

Multidimensional arrays are just arrays of arrays and fill(...) doesn't check the type of the array and the value you pass in (this responsibility is upon the developer).

Thus you can't fill a multidimensional array reasonably well without using a loop.

Be aware of the fact that, unlike languages like C or C++, Java arrays are objects and in multidimensional arrays all but the last level contain references to other Array objects. I'm not 100% sure about this, but most likely they are distributed in memory, thus you can't just fill a contiguous block without a loop, like C/C++ would allow you to do.

Sending Multipart File as POST parameters with RestTemplate requests

If you have to send a multipart file that is composed, among other things, by an Object that needs to be converted with a specific HttpMessageConverter and you get the "no suitable HttpMessageConverter" error no matter what you try, you may want to try with this:

RestTemplate restTemplate = new RestTemplate();
FormHttpMessageConverter converter = new FormHttpMessageConverter();

converter.addPartConverter(new TheRequiredHttpMessageConverter());
//for example, in my case it was "new MappingJackson2HttpMessageConverter()"

restTemplate.getMessageConverters().add(converter);

This solved the problem for me with a custom Object that, together with a file (instanceof FileSystemResource, in my case), was part of the multipart file I needed to send. I tried with TrueGuidance's solution (and many others found around the web) to no avail, then I looked at FormHttpMessageConverter's source code and tried this.

Accessing Google Spreadsheets with C# using Google Data API

This Twilio blog page made on March 24, 2017 by Marcos Placona may be helpful.

Google Spreadsheets and .NET Core

It references Google.Api.Sheets.v4 and OAuth2.

Crop image in android

I found a really cool library, try this out. this is really smooth and easy to use.

https://github.com/TakuSemba/CropMe

Angularjs: Error: [ng:areq] Argument 'HomeController' is not a function, got undefined

Try this

    <title>My First Angular App</title>

</head>

<body>

     <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.8/angular.min.js"></script>

    <h3>Adding Simple Controller<h3>        

    <div ng-controller="SimpleController">
        Name:

        <br/>

        <input type = "text" data-ng-model = "name"/> {{name}}

        <br/>

        <ul>    
            <li data-ng-repeat = "cust in customers | filter:name | orderBy:'city'">
                {{cust.name}} - {{cust.city}}
            </li>
        </ul>

    </div>


    <script>

        var angularApp = angular.module('angularApp',[]);

        angularApp.controller('SimpleController', [ '$scope', SimpleController]);

        function SimpleController($scope)
        {

            $scope.customers = [
                                    {name:'Nikhil Mahirrao', city:'Pune'},
                                    {name:'Kapil Mahire', city:'Pune'},
                                    {name:'Narendra Mahirrao', city:'Phophare'},
                                    {name:'Mithun More', city:'Shahada'}

                                ]; 
        }

    </script>

</body>

Converting Pandas dataframe into Spark dataframe error

Type related errors can be avoided by imposing a schema as follows:

note: a text file was created (test.csv) with the original data (as above) and hypothetical column names were inserted ("col1","col2",...,"col25").

import pyspark
from pyspark.sql import SparkSession
import pandas as pd

spark = SparkSession.builder.appName('pandasToSparkDF').getOrCreate()

pdDF = pd.read_csv("test.csv")

contents of the pandas data frame:

       col1     col2    col3    col4    col5    col6    col7    col8   ... 
0      10000001 1       0       1       12:35   OK      10002   1      ...
1      10000001 2       0       1       12:36   OK      10002   1      ...
2      10000002 1       0       4       12:19   PA      10003   1      ...

Next, create the schema:

from pyspark.sql.types import *

mySchema = StructType([ StructField("col1", LongType(), True)\
                       ,StructField("col2", IntegerType(), True)\
                       ,StructField("col3", IntegerType(), True)\
                       ,StructField("col4", IntegerType(), True)\
                       ,StructField("col5", StringType(), True)\
                       ,StructField("col6", StringType(), True)\
                       ,StructField("col7", IntegerType(), True)\
                       ,StructField("col8", IntegerType(), True)\
                       ,StructField("col9", IntegerType(), True)\
                       ,StructField("col10", IntegerType(), True)\
                       ,StructField("col11", StringType(), True)\
                       ,StructField("col12", StringType(), True)\
                       ,StructField("col13", IntegerType(), True)\
                       ,StructField("col14", IntegerType(), True)\
                       ,StructField("col15", IntegerType(), True)\
                       ,StructField("col16", IntegerType(), True)\
                       ,StructField("col17", IntegerType(), True)\
                       ,StructField("col18", IntegerType(), True)\
                       ,StructField("col19", IntegerType(), True)\
                       ,StructField("col20", IntegerType(), True)\
                       ,StructField("col21", IntegerType(), True)\
                       ,StructField("col22", IntegerType(), True)\
                       ,StructField("col23", IntegerType(), True)\
                       ,StructField("col24", IntegerType(), True)\
                       ,StructField("col25", IntegerType(), True)])

Note: True (implies nullable allowed)

create the pyspark dataframe:

df = spark.createDataFrame(pdDF,schema=mySchema)

confirm the pandas data frame is now a pyspark data frame:

type(df)

output:

pyspark.sql.dataframe.DataFrame

Aside:

To address Kate's comment below - to impose a general (String) schema you can do the following:

df=spark.createDataFrame(pdDF.astype(str)) 

Sprintf equivalent in Java

Since Java 13 you have formatted 1 method on String, which was added along with text blocks as a preview feature 2. You can use it instead of String.format()

Assertions.assertEquals(
   "%s %d %.3f".formatted("foo", 123, 7.89),
   "foo 123 7.890"
);

$_POST not working. "Notice: Undefined index: username..."

first of all,

be sure that there is a post

if(isset($_POST['username'])) { 
    // check if the username has been set
}

second, and most importantly, sanitize the data, meaning that

$query = "SELECT password FROM users WHERE username='".$_POST['username']."'";

is deadly dangerous, instead use

$query = "SELECT password FROM users WHERE username='".mysql_real_escape_string($_POST['username'])."'";

and please research the subject sql injection

C: How to free nodes in the linked list?

An iterative function to free your list:

void freeList(struct node* head)
{
   struct node* tmp;

   while (head != NULL)
    {
       tmp = head;
       head = head->next;
       free(tmp);
    }

}

What the function is doing is the follow:

  1. check if head is NULL, if yes the list is empty and we just return

  2. Save the head in a tmp variable, and make head point to the next node on your list (this is done in head = head->next

  3. Now we can safely free(tmp) variable, and head just points to the rest of the list, go back to step 1

What is the difference between match_parent and fill_parent?

Both have similar functionality only difference is that fill_parent is used up to API level 8 and match_parent is used after API level 8 or higher level.

What is the difference between #include <filename> and #include "filename"?

When you use #include <filename>, the pre-processor looking for the file in directory of C\C++ header files (stdio.h\cstdio, string, vector, etc.). But, when you use #include "filename": first, the pre-processor looking for the file in the current directory, and if it doesn't here - he looking for it in the directory of C\C++ header files.

How to open a txt file and read numbers in Java

A much shorter alternative is below:

Path filePath = Paths.get("file.txt");
Scanner scanner = new Scanner(filePath);
List<Integer> integers = new ArrayList<>();
while (scanner.hasNext()) {
    if (scanner.hasNextInt()) {
        integers.add(scanner.nextInt());
    } else {
        scanner.next();
    }
}

A Scanner breaks its input into tokens using a delimiter pattern, which by default matches whitespace. Although default delimiter is whitespace, it successfully found all integers separated by new line character.

How do I get the path of the Python script I am running in?

7.2 of Dive Into Python: Finding the Path.

import sys, os

print('sys.argv[0] =', sys.argv[0])             
pathname = os.path.dirname(sys.argv[0])        
print('path =', pathname)
print('full path =', os.path.abspath(pathname)) 

Proper indentation for Python multiline strings

If you want a quick&easy solution and save yourself from typing newlines, you could opt for a list instead, e.g.:

def func(*args, **kwargs):
    string = '\n'.join([
        'first line of very long string and',
        'second line of the same long thing and',
        'third line of ...',
        'and so on...',
        ])
    print(string)
    return

Fatal error: Uncaught Error: Call to undefined function mysql_connect()

For mysqli you can use :

$db = ADONewConnection('mysqli');

... ...

$db->execute("set names 'utf8'");

POST string to ASP.NET Web Api application - returns null

You seem to have used some [Authorize] attribute on your Web API controller action and I don't see how this is relevant to your question.

So, let's get into practice. Here's a how a trivial Web API controller might look like:

public class TestController : ApiController
{
    public string Post([FromBody] string value)
    {
        return value;
    }
}

and a consumer for that matter:

class Program
{
    static void Main()
    {
        using (var client = new WebClient())
        {
            client.Headers[HttpRequestHeader.ContentType] = "application/x-www-form-urlencoded";
            var data = "=Short test...";
            var result = client.UploadString("http://localhost:52996/api/test", "POST", data);
            Console.WriteLine(result);
        }
    }
}

You will undoubtedly notice the [FromBody] decoration of the Web API controller attribute as well as the = prefix of the POST data om the client side. I would recommend you reading about how does the Web API does parameter binding to better understand the concepts.

As far as the [Authorize] attribute is concerned, this could be used to protect some actions on your server from being accessible only to authenticated users. Actually it is pretty unclear what you are trying to achieve here.You should have made this more clear in your question by the way. Are you are trying to understand how parameter bind works in ASP.NET Web API (please read the article I've linked to if this is your goal) or are attempting to do some authentication and/or authorization? If the second is your case you might find the following post that I wrote on this topic interesting to get you started.

And if after reading the materials I've linked to, you are like me and say to yourself, WTF man, all I need to do is POST a string to a server side endpoint and I need to do all of this? No way. Then checkout ServiceStack. You will have a good base for comparison with Web API. I don't know what the dudes at Microsoft were thinking about when designing the Web API, but come on, seriously, we should have separate base controllers for our HTML (think Razor) and REST stuff? This cannot be serious.

Apache: client denied by server configuration

This code worked for me..

 <Location />
Allow from all
Order Deny,Allow
</Location> 

Hope this helps others

Get and set position with jQuery .offset()

I recommend another option. jQuery UI has a new position feature that allows you to position elements relative to each other. For complete documentation and demo see: http://jqueryui.com/demos/position/#option-offset.

Here's one way to position your elements using the position feature:

var options = {
    "my": "top left",
    "at": "top left",
    "of": ".layer1"
};
$(".layer2").position(options);

Foreign key referring to primary keys across multiple tables?

Assuming you must have two tables for the two employee types for some reason, I'll extend on vmarquez's answer:

Schema:

employees_ce (id, name)
employees_sn (id, name)
deductions (id, parentId, parentType, name)

Data in deductions:

deductions table
id      parentId      parentType      name
1       1             ce              gold
2       1             sn              silver
3       2             sn              wood
...

This would allow you to have deductions point to any other table in your schema. This kind of relation isn't supported by database-level constraints, IIRC so you'll have to make sure your App manages the constraint properly (which makes it more cumbersome if you have several different Apps/services hitting the same database).

Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

In my case I was trying to run on an watchOS 7 simulator in Relese mode but the iOS 14 simulator was in Debug mode.

So simply putting both sims in Debug/Release mode solved the problem for me!

JPanel setBackground(Color.BLACK) does nothing

If your panel is 'not opaque' (transparent) you wont see your background color.

I want to use CASE statement to update some records in sql server 2005

Add a WHERE clause

UPDATE dbo.TestStudents  
SET     LASTNAME =  CASE  
                        WHEN LASTNAME = 'AAA' THEN 'BBB' 
                        WHEN LASTNAME = 'CCC' THEN 'DDD' 
                        WHEN LASTNAME = 'EEE' THEN 'FFF' 
                        ELSE LASTNAME
                    END 
WHERE   LASTNAME IN ('AAA', 'CCC', 'EEE')

How to convert a PNG image to a SVG?

potrace does not support PNG as input file, but PNM.
Therefore, first convert from PNG to PNM:

convert file.png file.pnm        # PNG to PNM
potrace file.pnm -s -o file.svg  # PNM to SVG

Explain options

  • potrace -s => Output file is SVG
  • potrace -o file.svg => Write output to file.svg

Example

Input file = 2017.png Input file

convert 2017.png 2017.pnm

Temporary file = 2017.pnm

potrace 2017.pnm -s -o 2017.svg

Output file = 2017.svg Output file

Script

ykarikos proposes a script png2svg.sh that I have improved:

#!/bin/bash

File_png="${1?:Usage: $0 file.png}"

if [[ ! -s "$File_png" ]]; then
  echo >&2 "The first argument ($File_png)"
  echo >&2 "must be a file having a size greater than zero"
  ( set -x ; ls -s "$File_png" )
  exit 1
fi

File="${File_png%.*}"

convert "$File_png" "$File.pnm"        # PNG to PNM
potrace "$File.pnm" -s -o "$File.svg"  # PNM to SVG
rm "$File.pnm"                         # Remove PNM

One-line command

If you want to convert many files, you can also use the following one-line command:

( set -x ; for f_png in *.png ; do f="${f_png%.png}" ; convert "$f_png" "$f.pnm" && potrace "$f.pnm" -s -o "$f.svg" ; done )

See also

See also this good comparison of raster to vector converters on Wikipedia.

Difference between an API and SDK

How about... It's like if you wanted to install a home theatre system in your house. Using an API is like getting all the wires, screws, bits, and pieces. The possibilities are endless (constrained only by the pieces you receive), but sometimes overwhelming. An SDK is like getting a kit. You still have to put it together, but it's more like getting pre-cut pieces and instructions for an IKEA bookshelf than a box of screws.

How to name an object within a PowerPoint slide?

Yes. Click on the object (textbox, shape, etc.) to select the object and in the Drawing Tools | Format tab, click on Selection Pane in the Arrange group. From there, you'll see names of objects - you can double click (or press F2) on any name and rename it. By deselecting it, it becomes renamed. You can also get to this from the Home tab -> Drawing group -> Arrange drop-down -> Selection pane or by pressing ALT + F10.

What does "to stub" mean in programming?

Layman's terms, it's dummy data (or fake data, test data...etc.) that you can use to test or develop your code against until you (or the other party) is ready to present/receive real data. It's a programmer's "Lorem Ipsum".

Employee database not ready? Make up a simple one with Jane Doe, John Doe...etc. API not ready? Make up a fake one by creating a static .json file containing fake data.

Regular expression for extracting tag attributes

I suggest that you use HTML Tidy to convert the HTML to XHTML, and then use a suitable XPath expression to extract the attributes.

OSError: [Errno 2] No such file or directory while using python subprocess in Django

No such file or directory can be also raised if you are trying to put a file argument to Popen with double-quotes.

For example:

call_args = ['mv', '"path/to/file with spaces.txt"', 'somewhere']

In this case, you need to remove double-quotes.

call_args = ['mv', 'path/to/file with spaces.txt', 'somewhere']

How can I switch to another branch in git?

I am using this to switch one branch to another anyone you can use it works for me like charm.

git switch [branchName] OR git checkout [branchName]

ex: git switch develop OR
git checkout develop

How can I access a hover state in reactjs?

For having hover effect you can simply try this code

import React from "react";
  import "./styles.css";

    export default function App() {

      function MouseOver(event) {
        event.target.style.background = 'red';
      }
      function MouseOut(event){
        event.target.style.background="";
      }
      return (
        <div className="App">
          <button onMouseOver={MouseOver} onMouseOut={MouseOut}>Hover over me!</button>
        </div>
      );
    }

Or if you want to handle this situation using useState() hook then you can try this piece of code

import React from "react";
import "./styles.css";


export default function App() {
   let [over,setOver]=React.useState(false);

   let buttonstyle={
    backgroundColor:''
  }

  if(over){
    buttonstyle.backgroundColor="green";
  }
  else{
    buttonstyle.backgroundColor='';
  }

  return (
    <div className="App">
      <button style={buttonstyle}
      onMouseOver={()=>setOver(true)} 
      onMouseOut={()=>setOver(false)}
      >Hover over me!</button>
    </div>
  );
}

Both of the above code will work for hover effect but first procedure is easier to write and understand

How to create <input type=“text”/> dynamically

You could do something like this in a loop based on the number of text fields they enter.

$('<input/>').attr({type:'text',name:'text'+i}).appendTo('#myform');

But for better performance I'd create all the html first and inject it into the DOM only once.

var count = 20;
var html = [];
while(count--) {
  html.push("<input type='text' name='name", count, "'>");
}
$('#myform').append(html.join(''));

Edit this example uses jQuery to append the html, but you could easily modify it to use innerHTML as well.

Is it possible to iterate through JSONArray?

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

Remove element of a regular array

If you don't want to use List:

var foos = new List<Foo>(array);
foos.RemoveAt(index);
return foos.ToArray();

You could try this extension method that I haven't actually tested:

public static T[] RemoveAt<T>(this T[] source, int index)
{
    T[] dest = new T[source.Length - 1];
    if( index > 0 )
        Array.Copy(source, 0, dest, 0, index);

    if( index < source.Length - 1 )
        Array.Copy(source, index + 1, dest, index, source.Length - index - 1);

    return dest;
}

And use it like:

Foo[] bar = GetFoos();
bar = bar.RemoveAt(2);

How do I get the HTTP status code with jQuery?

$.ajax({
    url: "http://my-ip/test/test.php",
    data: {},
    error: function(xhr, statusText, errorThrown){alert(xhr.status);}
});

How do I return the SQL data types from my query?

This easy query return a data type bit. You can use this thecnic for other data types:

select CAST(0 AS BIT) AS OK

Passing variables through handlebars partial

Not sure if this is helpful but here's an example of Handlebars template with dynamic parameters passed to an inline RadioButtons partial and the client(browser) rendering the radio buttons in the container.

For my use it's rendered with Handlebars on the server and lets the client finish it up. With it a forms tool can provide inline data within Handlebars without helpers.

Note : This example requires jQuery

{{#*inline "RadioButtons"}}
{{name}} Buttons<hr>
<div id="key-{{{name}}}"></div>
<script>
  {{{buttons}}}.map((o)=>{
    $("#key-{{name}}").append($(''
      +'<button class="checkbox">'
      +'<input name="{{{name}}}" type="radio" value="'+o.value+'" />'+o.text
      +'</button>'
    ));
  });
  // A little test script
  $("#key-{{{name}}} .checkbox").on("click",function(){
      alert($("input",this).val());
  });
</script>
{{/inline}}
{{>RadioButtons name="Radio" buttons='[
 {value:1,text:"One"},
 {value:2,text:"Two"}, 
 {value:3,text:"Three"}]' 
}}

Nginx: Job for nginx.service failed because the control process exited

change the port may help as 80 port is already using somewhere

vi /etc/nginx/sites-available/default

Change the port:

listen 8080 default_server;
listen [::]:8080 default_server;

And then restart the nginx server

nginx -t
service nginx restart

Coarse-grained vs fine-grained

In the terms of POS (Part of Speech) Tag,

Parse string to DateTime in C#

Put the value of a human-readable string into a .NET DateTime with code like this:

DateTime.ParseExact("April 16, 2011 4:27 pm", "MMMM d, yyyy h:mm tt", null);

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 \;

how to insert datetime into the SQL Database table?

You will need to have a datetime column in a table. Then you can do an insert like the following to insert the current date:

INSERT INTO MyTable (MyDate) Values (GetDate())

If it is not today's date then you should be able to use a string and specify the date format:

INSERT INTO MyTable (MyDate) Values (Convert(DateTime,'19820626',112)) --6/26/1982

You do not always need to convert the string either, often you can just do something like:

INSERT INTO MyTable (MyDate) Values ('06/26/1982') 

And SQL Server will figure it out for you.

Access Control Origin Header error using Axios in React Web throwing error in Chrome

I'll have a go at this complicated subject.

What is origin?

The origin itself is the name of a host (scheme, hostname, and port) i.g. https://www.google.com or could be a locally opened file file:// etc.. It is where something (i.g. a web page) originated from. When you open your web browser and go to https://www.google.com, the origin of the web page that is displayed to you is https://www.google.com. You can see this in Chrome Dev Tools under Security:

enter image description here

The same applies for if you open a local HTML file via your file explorer (which is not served via a server):

enter image description here

What has this got to do with CORS issues?

When you open your browser and go to https://website.com, that website will have the origin of https://website.com. This website will most likely only fetch images, icons, js files and do API calls towards https://website.com, basically it is calling the same server as it was served from. It is doing calls to the same origin.

If you open your web browser and open a local HTML file and in that html file there is javascript which wants to do a request to google for example, you get the following error:

enter image description here

The same-origin policy tells the browser to block cross-origin requests. In this instance origin null is trying to do a request to https://www.google.com (a cross-origin request). The browser will not allow this because of the CORS Policy which is set and that policy is that cross-origin requests is not allowed.

Same applies for if my page was served from a server on localhost:

enter image description here

Localhost server example

If we host our own localhost API server running on localhost:3000 with the following code:

const express = require('express')
const app = express()
 
app.use(express.static('public'))

app.get('/hello', function (req, res) {
    // res.header("Access-Control-Allow-Origin", "*");
    res.send('Hello World');
})
 
app.listen(3000, () => {
    console.log('alive');
})

And open a HTML file (that does a request to the localhost:3000 server) directory from the file explorer the following error will happen:

enter image description here

Since the web page was not served from the localhost server on localhost:3000 and via the file explorer the origin is not the same as the server API origin, hence a cross-origin request is being attempted. The browser is stopping this attempt due to CORS Policy.

But if we uncomment the commented line:

const express = require('express')
const app = express()
 
app.use(express.static('public'))

app.get('/hello', function (req, res) {
    res.header("Access-Control-Allow-Origin", "*");
    res.send('Hello World');
})
 
app.listen(3000, () => {
    console.log('alive');
})

And now try again:

enter image description here

It works, because the server which sends the HTTP response included now a header stating that it is ok for cross-origin requests to happen to the server, this means the browser will let it happen, hence no error.

How to fix things

  1. Serve the page from the same origin as where the requests you are making reside (same host).
  2. Allow the server to receive cross-origin requests by explicitly stating it in the response headers.
  3. Don't use a browser. Use cURL for example, it doesn't care about CORS Policies like browsers do and will get you what you want.

Example flow

Following is taken from: https://web.dev/cross-origin-resource-sharing/#how-does-cors-work

Remember, the same-origin policy tells the browser to block cross-origin requests. When you want to get a public resource from a different origin, the resource-providing server needs to tell the browser "This origin where the request is coming from can access my resource". The browser remembers that and allows cross-origin resource sharing.

  • Step 1: client (browser) request When the browser is making a cross-origin request, the browser adds an Origin header with the current origin (scheme, host, and port).

  • Step 2: server response On the server side, when a server sees this header, and wants to allow access, it needs to add an Access-Control-Allow-Origin header to the response specifying the requesting origin (or * to allow any origin.)

  • Step 3: browser receives response When the browser sees this response with an appropriate Access-Control-Allow-Origin header, the browser allows the response data to be shared with the client site.

More links

Here is another good answer, more detailed as to what is happening: https://stackoverflow.com/a/10636765/1137669

Adding an external directory to Tomcat classpath

Just specify it in shared.loader or common.loader property of /conf/catalina.properties.

How to install pip with Python 3?

Please follow below steps to install python 3 with pip:

Step 1 : Install Python from download here

Step 2 : you’ll need to download get-pip.py

Step 3 : After download get-pip.py , open your commant prompt and go to directory where your get-pip.py file saved .

Step 4 : Enter command python get-pip.py in cmd.

Step 5 : Pip installed successfully , Verify pip installation by type command in cmd pip --version

An object reference is required to access a non-static member

You should make your audioSounds and minTime members static:

public static List<AudioSource> audioSounds = new List<AudioSource>();
public static double minTime = 0.5;

But I would consider using singleton objects instead of static members instead:

public class SoundManager : MonoBehaviour
{

    public List<AudioSource> audioSounds = new List<AudioSource>();
    public double minTime = 0.5;

    public static SoundManager Instance { get; private set; }

    void Awake()
    {
        Instance = this;
    }

    public void playSound(AudioClip sourceSound, Vector3 objectPosition, int volume, float audioPitch, int dopplerLevel)
    {    
        bool playsound = false;
        foreach (AudioSource sound in audioSounds) // Loop through List with foreach
        {  
            if (sourceSound.name != sound.name && sound.time <= minTime)
            {
                playsound = true;
            }
        }

        if(playsound) {
            AudioSource.PlayClipAtPoint(sourceSound, objectPosition);
        }

    }
}

Update from September 2020:

Six years later, it is still one of my most upvoted answers on StackOverflow, so I feel obligated to add: singleton is a pattern that creates a lot of problems down the road, and personally, I consider it to be an anti-pattern. It can be accessed from anywhere, and using singletons for different game systems creates a spaghetti of invisible dependencies between different parts of your project.

If you're just learning to program, using singletons is OK for now. But please, consider reading about Dependency Injection, Inversion of Control and other architectural patterns. At least file it under "stuff I will learn later". This may sound as an overkill when you first learn about them, but a proper architecture can become a life-saver on middle and big projects.

How to use <DllImport> in VB.NET?

I saw in getwindowtext (user32) on pinvoke.net that you can place a MarshalAs statement to state that the StringBuffer is equivalent to LPSTR.

<DllImport("user32.dll", SetLastError:=True, CharSet:=CharSet.Ansi)> _
Public Function GetWindowText(hwnd As IntPtr, <MarshalAs(UnManagedType.LPStr)>lpString As System.Text.StringBuilder, cch As Integer) As Integer
End Function

Regex pattern for checking if a string starts with a certain substring?

The StartsWith method will be faster, as there is no overhead of interpreting a regular expression, but here is how you do it:

if (Regex.IsMatch(theString, "^(mailto|ftp|joe):")) ...

The ^ mathes the start of the string. You can put any protocols between the parentheses separated by | characters.

edit:

Another approach that is much faster, is to get the start of the string and use in a switch. The switch sets up a hash table with the strings, so it's faster than comparing all the strings:

int index = theString.IndexOf(':');
if (index != -1) {
  switch (theString.Substring(0, index)) {
    case "mailto":
    case "ftp":
    case "joe":
      // do something
      break;
  }
}

double free or corruption (!prev) error in c program

double *ptr = malloc(sizeof(double *) * TIME);
/* ... */
for(tcount = 0; tcount <= TIME; tcount++)
                         ^^
  • You're overstepping the array. Either change <= to < or alloc SIZE + 1 elements
  • Your malloc is wrong, you'll want sizeof(double) instead of sizeof(double *)
  • As ouah comments, although not directly linked to your corruption problem, you're using *(ptr+tcount) without initializing it

  • Just as a style note, you might want to use ptr[tcount] instead of *(ptr + tcount)
  • You don't really need to malloc + free since you already know SIZE

How to do a SQL NOT NULL with a DateTime?

Just to rule out a possibility - it doesn't appear to have anything to do with the ANSI_NULLS option, because that controls comparing to NULL with the = and <> operators. IS [NOT] NULL works whether ANSI_NULLS is ON or OFF.

I've also tried this against SQL Server 2005 with isql, because ANSI_NULLS defaults to OFF when using DB-Library.

Is it possible to interactively delete matching search pattern in Vim?

There are 3 ways I can think of:

The way that is easiest to explain is

:%s/phrase to delete//gc

but you can also (personally I use this second one more often) do a regular search for the phrase to delete

/phrase to delete

Vim will take you to the beginning of the next occurrence of the phrase.

Go into insert mode (hit i) and use the Delete key to remove the phrase.

Hit escape when you have deleted all of the phrase.

Now that you have done this one time, you can hit n to go to the next occurrence of the phrase and then hit the dot/period "." key to perform the delete action you just performed

Continue hitting n and dot until you are done.

Lastly you can do a search for the phrase to delete (like in second method) but this time, instead of going into insert mode, you

Count the number of characters you want to delete

Type that number in (with number keys)

Hit the x key - characters should get deleted

Continue through with n and dot like in the second method.

PS - And if you didn't know already you can do a capital n to move backwards through the search matches.

Using sed, Insert a line above or below the pattern?

More portable to use ed; some systems don't support \n in sed

printf "/^lorem ipsum dolor sit amet/a\nconsectetur adipiscing elit\n.\nw\nq\n" |\
    /bin/ed $filename

How does one use the onerror attribute of an img element

very simple

  <img onload="loaded(this, 'success')" onerror="error(this, 
 'error')"  src="someurl"  alt="" />

 function loaded(_this, status){
   console.log(_this, status)
  // do your work in load
 }
 function error(_this, status){
  console.log(_this, status)
  // do your work in error
  }

How do I obtain crash-data from my Android application?

You can do this directly in Android Studio. Just connect your phone, run the app, let it crash and you can view the stacktrace directly in Android Studio.

Regular expression search replace in Sublime Text 2

Note that if you use more than 9 capture groups you have to use the syntax ${10}.

$10 or \10 or \{10} will not work.

MySQL Select Query - Get only first 10 characters of a value

SELECT SUBSTRING(subject, 1, 10) FROM tbl

Should I use typescript? or I can just use ES6?

Decision tree between ES5, ES6 and TypeScript

Do you mind having a build step?

  • Yes - Use ES5
  • No - keep going

Do you want to use types?

  • Yes - Use TypeScript
  • No - Use ES6

More Details

ES5 is the JavaScript you know and use in the browser today it is what it is and does not require a build step to transform it into something that will run in today's browsers

ES6 (also called ES2015) is the next iteration of JavaScript, but it does not run in today's browsers. There are quite a few transpilers that will export ES5 for running in browsers. It is still a dynamic (read: untyped) language.

TypeScript provides an optional typing system while pulling in features from future versions of JavaScript (ES6 and ES7).

Note: a lot of the transpilers out there (i.e. babel, TypeScript) will allow you to use features from future versions of JavaScript today and exporting code that will still run in today's browsers.

Google maps API V3 - multiple markers on exact same spot

Adding to above answers but offering an alternative quick solution in php and wordpress. For this example I am storing the location field via ACF and looping through the posts to grab that data.

I found that storing the lat / lng in an array and check the value of that array to see if the loop matches, we can then update the value within that array with the amount we want to shift our pips by.

//This is the value to shift the pips by. I found this worked best with markerClusterer
$add_to_latlng = 0.00003;

while ($query->have_posts()) {
    $query->the_post();
    $meta = get_post_meta(get_the_ID(), "postcode", true); //uses an acf field to store location
    $lat = $meta["lat"];
    $lng = $meta["lng"];

    if(in_array($meta["lat"],$lat_checker)){ //check if this meta matches
        
        //if matches then update the array to a new value (current value + shift value)
        // This is using the lng value for a horizontal line of pips, use lat for vertical, or both for a diagonal
        if(isset($latlng_storer[$meta["lng"]])){
            $latlng_storer[$meta["lng"]] = $latlng_storer[$meta["lng"]] + $add_to_latlng;
            $lng = $latlng_storer[$meta["lng"]];
        } else {
            $latlng_storer[$meta["lng"]] = $meta["lng"];
            $lng = $latlng_storer[$meta["lng"]];
        }

    } else {
        $lat_checker[] = $meta["lat"]; //just for simple checking of data
        $latlng_storer[$meta["lat"]] = floatval($meta["lat"]);
        $latlng_storer[$meta["lng"]] =  floatval($meta["lng"]);
    }

    $entry[] = [
        "lat" => $lat,
        "lng" => $lng,
    //...Add all the other post data here and use this array for the pips
    ];
} // end query

Once I've grabbed these locations I json encode the $entry variable and use that within my JS.

let locations = <?=json_encode($entry)?>;

I know this is a rather specific situation but I hope this helps someone along the line!

regex string replace

Just change + to -:

str = str.replace(/[^a-z0-9-]/g, "");

You can read it as:

  1. [^ ]: match NOT from the set
  2. [^a-z0-9-]: match if not a-z, 0-9 or -
  3. / /g: do global match

More information:

Configure hibernate (using JPA) to store Y/N for type Boolean instead of 0/1

This is pure JPA without using getters/setters. As of 2013/2014 it is the best answer without using any Hibernate specific annotations, but please note this solution is JPA 2.1, and was not available when the question was first asked:

@Entity
public class Person {    

    @Convert(converter=BooleanToStringConverter.class)
    private Boolean isAlive;    
    ...
}

And then:

@Converter
public class BooleanToStringConverter implements AttributeConverter<Boolean, String> {

    @Override
    public String convertToDatabaseColumn(Boolean value) {        
        return (value != null && value) ? "Y" : "N";            
        }    

    @Override
    public Boolean convertToEntityAttribute(String value) {
        return "Y".equals(value);
        }
    }

Edit:

The implementation above considers anything different from character "Y", including null, as false. Is that correct? Some people here consider this incorrect, and believe that null in the database should be null in Java.

But if you return null in Java, it will give you a NullPointerException if your field is a primitive boolean. In other words, unless some of your fields actually use the class Boolean it's best to consider null as false, and use the above implementation. Then Hibernate will not to emit any exceptions regardless of the contents of the database.

And if you do want to accept null and emit exceptions if the contents of the database are not strictly correct, then I guess you should not accept any characters apart from "Y", "N" and null. Make it consistent, and don't accept any variations like "y", "n", "0" and "1", which will only make your life harder later. This is a more strict implementation:

@Override
public String convertToDatabaseColumn(Boolean value) {
    if (value == null) return null;
    else return value ? "Y" : "N";
    }

@Override
public Boolean convertToEntityAttribute(String value) {
    if (value == null) return null;
    else if (value.equals("Y")) return true;
    else if (value.equals("N")) return false;
    else throw new IllegalStateException("Invalid boolean character: " + value);
    }

And yet another option, if you want to allow for null in Java but not in the database:

@Override
public String convertToDatabaseColumn(Boolean value) {
    if (value == null) return "-";
    else return value ? "Y" : "N";
    }

@Override
public Boolean convertToEntityAttribute(String value) {
    if (value.equals("-") return null;
    else if (value.equals("Y")) return true;
    else if (value.equals("N")) return false;
    else throw new IllegalStateException("Invalid boolean character: " + value);
    }

Is there a “not in” operator in JavaScript for checking object properties?

It seems wrong to me to set up an if/else statement just to use the else portion...

Just negate your condition, and you'll get the else logic inside the if:

if (!(id in tutorTimes)) { ... }

Uninstall all installed gems, in OSX?

If you like doing it using ruby:

ruby -e "`gem list`.split(/$/).each { |line| puts `gem uninstall -Iax #{line.split(' ')[0]}` unless line.strip.empty? }"

Cheers

How does the SQL injection from the "Bobby Tables" XKCD comic work?

In this case, ' is not a comment character. It's used to delimit string literals. The comic artist is banking on the idea that the school in question has dynamic sql somewhere that looks something like this:

$sql = "INSERT INTO `Students` (FirstName, LastName) VALUES ('" . $fname . "', '" . $lname . "')";

So now the ' character ends the string literal before the programmer was expecting it. Combined with the ; character to end the statement, an attacker can now add whatever sql they want. The -- comment at the end is to make sure any remaining sql in the original statement does not prevent the query from compiling on the server.

FWIW, I also think the comic in question has an important detail wrong: if you're thinking about sanitizing your database inputs, as the comic suggests, you're still doing it wrong. Instead, you should think in terms of quarantining your database inputs, and the correct way to do this is via parameterized queries.

How to bring a window to the front?

I had the same problem with bringing a JFrame to the front under Ubuntu (Java 1.6.0_10). And the only way I could resolve it is by providing a WindowListener. Specifically, I had to set my JFrame to always stay on top whenever toFront() is invoked, and provide windowDeactivated event handler to setAlwaysOnTop(false).


So, here is the code that could be placed into a base JFrame, which is used to derive all application frames.

@Override
public void setVisible(final boolean visible) {
  // make sure that frame is marked as not disposed if it is asked to be visible
  if (visible) {
      setDisposed(false);
  }
  // let's handle visibility...
  if (!visible || !isVisible()) { // have to check this condition simply because super.setVisible(true) invokes toFront if frame was already visible
      super.setVisible(visible);
  }
  // ...and bring frame to the front.. in a strange and weird way
  if (visible) {
      toFront();
  }
}

@Override
public void toFront() {
  super.setVisible(true);
  int state = super.getExtendedState();
  state &= ~JFrame.ICONIFIED;
  super.setExtendedState(state);
  super.setAlwaysOnTop(true);
  super.toFront();
  super.requestFocus();
  super.setAlwaysOnTop(false);
}

Whenever your frame should be displayed or brought to front call frame.setVisible(true).

Since I moved to Ubuntu 9.04 there seems to be no need in having a WindowListener for invoking super.setAlwaysOnTop(false) -- as can be observed; this code was moved to the methods toFront() and setVisible().

Please note that method setVisible() should always be invoked on EDT.

How to remove an unpushed outgoing commit in Visual Studio?

Open the history tab in Team Explorer from the Branches tile (right-click your branch). Then in the history right-click the commit before the one you don't want to push, choose Reset. That will move the branch back to that commit and should get rid of the extra commit you made. In order to reset before a given commit you thus have to select its parent.

Depending on what you want to do with the changes choose hard, which will get rid of them locally. Or choose soft which will undo the commit but will leave your working directory with the changes in your discarded commit.

how to increase the limit for max.print in R

set the function options(max.print=10000) in top of your program. since you want intialize this before it works. It is working for me.

Stop form from submitting , Using Jquery

A different approach could be

    <script type="text/javascript">
    function CheckData() {
    //you may want to check something here and based on that wanna return true and false from the         function.
    if(MyStuffIsokay)
     return true;//will cause form to postback to server.
    else
      return false;//will cause form Not to postback to server
    }
    </script>
    @using (Html.BeginForm("SaveEmployee", "Employees", FormMethod.Post, new { id = "EmployeeDetailsForm" }))
    {
    .........
    .........
    .........
    .........
    <input type="submit" value= "Save Employee" onclick="return CheckData();"/>
    }

How to perform OR condition in django queryset?

from django.db.models import Q
User.objects.filter(Q(income__gte=5000) | Q(income__isnull=True))

via Documentation

Getting a list of associative array keys

for (var key in dictionary) {
  // Do something with key
}

It's the for..in statement.

The real difference between "int" and "unsigned int"

the type just tells you what the bit pattern is supposed to represent. the bits are only what you make of them. the same sequences can be interpreted in different ways.

In Python, what does dict.pop(a,b) mean?

The pop method of dicts (like self.data, i.e. {'a':'aaa','b':'bbb','c':'ccc'}, here) takes two arguments -- see the docs

The second argument, default, is what pop returns if the first argument, key, is absent. (If you call pop with just one argument, key, it raises an exception if that key's absent).

In your example, print b.pop('a',{'b':'bbb'}), this is irrelevant because 'a' is a key in b.data. But if you repeat that line...:

b=a()
print b.pop('a',{'b':'bbb'})
print b.pop('a',{'b':'bbb'})
print b.data

you'll see it makes a difference: the first pop removes the 'a' key, so in the second pop the default argument is actually returned (since 'a' is now absent from b.data).

How to get thread id of a pthread in linux c program?

This single line gives you pid , each threadid and spid.

 printf("before calling pthread_create getpid: %d getpthread_self: %lu tid:%lu\n",getpid(), pthread_self(), syscall(SYS_gettid));

React Native TextInput that only accepts numeric characters

This not work on IOS, setState -> render -> not change the text, but can change other. The textinput can't change itself value when textOnChange.

by the way, This work well on Android.

C# Creating and using Functions

You should either make your Add function static like so:

static public int Add(int x, int y)
{ 
    int result = x + y;
    return result;
 } //END   Add

static means that the function is not class instance dependent. So you can call it without needing to create a class instance of Program class.

or you should create in instance of your Program class, and then call Add on this instance. Like so:

Program prog = new Program();
prog.Add(5,10);

Can't drop table: A foreign key constraint fails

This probably has the same table to other schema the reason why you're getting that error.

You need to drop first the child row then the parent row.

Easiest way to detect Internet connection on iOS?

Checking the Internet connection availability in (iOS) Xcode 8.2 , Swift 3.0

This is simple method for checking the network availability. I managed to translate it to Swift 2.0 and here the final code. The existing Apple Reachability class and other third party libraries seemed to be too complicated to translate to Swift.

This works for both 3G and WiFi connections.

Don’t forget to add “SystemConfiguration.framework” to your project builder.

//Create new swift class file Reachability in your project.

import SystemConfiguration

public class Reachability {
class func isConnectedToNetwork() -> Bool {
    var zeroAddress = sockaddr_in()
    zeroAddress.sin_len = UInt8(MemoryLayout.size(ofValue: zeroAddress))
    zeroAddress.sin_family = sa_family_t(AF_INET)
    let defaultRouteReachability = withUnsafePointer(to: &zeroAddress) {
        $0.withMemoryRebound(to: sockaddr.self, capacity: 1) {zeroSockAddress in
            SCNetworkReachabilityCreateWithAddress(nil, zeroSockAddress)
        }
    }
    var flags = SCNetworkReachabilityFlags()
    if !SCNetworkReachabilityGetFlags(defaultRouteReachability! , &flags) {
        return false
    }
    let isReachable = (flags.rawValue & UInt32(kSCNetworkFlagsReachable)) != 0
    let needsConnection = (flags.rawValue & UInt32(kSCNetworkFlagsConnectionRequired)) != 0
    return (isReachable && !needsConnection)
   }
}

// Check network connectivity from anywhere in project by using this code.

if Reachability.isConnectedToNetwork() == true {
     print("Internet connection OK")
} else {
 print("Internet connection FAILED")
}

Print raw string from variable? (not getting the answers)

I have my variable assigned to big complex pattern string for using with re module and it is concatenated with few other strings and in the end I want to print it then copy and check on regex101.com. But when I print it in the interactive mode I get double slash - '\\w' as @Jimmynoarms said:

The Solution for python 3x:

print(r'%s' % your_variable_pattern_str)

How to sort an STL vector?

A pointer-to-member allows you to write a single comparator, which can work with any data member of your class:

#include <algorithm>
#include <vector>
#include <string>
#include <iostream>

template <typename T, typename U>
struct CompareByMember {
    // This is a pointer-to-member, it represents a member of class T
    // The data member has type U
    U T::*field;
    CompareByMember(U T::*f) : field(f) {}
    bool operator()(const T &lhs, const T &rhs) {
        return lhs.*field < rhs.*field;
    }
};

struct Test {
    int a;
    int b;
    std::string c;
    Test(int a, int b, std::string c) : a(a), b(b), c(c) {}
};

// for convenience, this just lets us print out a Test object
std::ostream &operator<<(std::ostream &o, const Test &t) {
    return o << t.c;
}

int main() {
    std::vector<Test> vec;
    vec.push_back(Test(1, 10, "y"));
    vec.push_back(Test(2, 9, "x"));

    // sort on the string field
    std::sort(vec.begin(), vec.end(), 
        CompareByMember<Test,std::string>(&Test::c));
    std::cout << "sorted by string field, c: ";
    std::cout << vec[0] << " " << vec[1] << "\n";

    // sort on the first integer field
    std::sort(vec.begin(), vec.end(), 
        CompareByMember<Test,int>(&Test::a));
    std::cout << "sorted by integer field, a: ";
    std::cout << vec[0] << " " << vec[1] << "\n";

    // sort on the second integer field
    std::sort(vec.begin(), vec.end(), 
        CompareByMember<Test,int>(&Test::b));
    std::cout << "sorted by integer field, b: ";
    std::cout << vec[0] << " " << vec[1] << "\n";
}

Output:

sorted by string field, c: x y
sorted by integer field, a: y x
sorted by integer field, b: x y

Convert UNIX epoch to Date object

With library(lubridate), numeric representations of date and time saved as the number of seconds since 1970-01-01 00:00:00 UTC, can be coerced into dates with as_datetime():

lubridate::as_datetime(1352068320)

[1] "2012-11-04 22:32:00 UTC"

Conditional Replace Pandas

np.where function works as follows:

df['X'] = np.where(df['Y']>=50, 'yes', 'no')

In your case you would want:

import numpy as np
df['my_channel'] = np.where(df.my_channel > 20000, 0, df.my_channel)

await vs Task.Wait - Deadlock?

Wait and await - while similar conceptually - are actually completely different.

Wait will synchronously block until the task completes. So the current thread is literally blocked waiting for the task to complete. As a general rule, you should use "async all the way down"; that is, don't block on async code. On my blog, I go into the details of how blocking in asynchronous code causes deadlock.

await will asynchronously wait until the task completes. This means the current method is "paused" (its state is captured) and the method returns an incomplete task to its caller. Later, when the await expression completes, the remainder of the method is scheduled as a continuation.

You also mentioned a "cooperative block", by which I assume you mean a task that you're Waiting on may execute on the waiting thread. There are situations where this can happen, but it's an optimization. There are many situations where it can't happen, like if the task is for another scheduler, or if it's already started or if it's a non-code task (such as in your code example: Wait cannot execute the Delay task inline because there's no code for it).

You may find my async / await intro helpful.

Format numbers to strings in Python

You can use the str.format() to make Python recognize any objects to strings.

Is it possible to ping a server from Javascript?

you can try this:

put ping.html on the server with or without any content, on the javascript do same as below:

<script>
    function ping(){
       $.ajax({
          url: 'ping.html',
          success: function(result){
             alert('reply');
          },     
          error: function(result){
              alert('timeout/error');
          }
       });
    }
</script>

How to open a new tab using Selenium WebDriver

Check this complete example to understand how to open multiple tabs and switch between the tabs and at the end close all tabs.

public class Tabs {

    WebDriver driver;

    Robot rb;

    @BeforeTest
    public void setup() throws Exception {
        System.setProperty("webdriver.chrome.driver", "C:\\Users\\Anuja.AnujaPC\\Downloads\\chromedriver_win32\\chromedriver.exe");
        WebDriver driver=new ChromeDriver();
        driver.manage().window().maximize();
        driver.manage().timeouts().implicitlyWait(5, TimeUnit.SECONDS);
        driver.get("http://qaautomated.com");
    }

    @Test
    public void openTab() {
        // Open tab 2 using CTRL + T keys.
        driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"t");

        // Open URL In 2nd tab.
        driver.get("http://www.qaautomated.com/p/contact.html");

        // Call switchToTab() method to switch to the first tab
        switchToTab();

        // Call switchToTab() method to switch to the second tab.
        switchToTab();
    }

    public void switchToTab() {
        // Switching between tabs using CTRL + tab keys.
        driver.findElement(By.cssSelector("body")).sendKeys(Keys.CONTROL +"\t");

        // Switch to current selected tab's content.
        driver.switchTo().defaultContent();
    }

    @AfterTest
    public void closeTabs() throws AWTException {
        // Used Robot class to perform ALT + SPACE + 'c' keypress event.
        rb = new Robot();
        rb.keyPress(KeyEvent.VK_ALT);
        rb.keyPress(KeyEvent.VK_SPACE);
        rb.keyPress(KeyEvent.VK_C);
    }

}

This example is given by this web page.

How do I use the CONCAT function in SQL Server 2008 R2?

NULL safe drop in replacement approximations for SQL Server 2012 CONCAT function

SQL Server 2012:

SELECT CONCAT(data1, data2)

PRE SQL 2012 (Two Solutions):

SELECT {fn CONCAT(ISNULL(data1, ''), ISNULL(data2, ''))}

SELECT ISNULL(CAST(data1 AS varchar(MAX)), '') + ISNULL(CAST(data2 AS varchar(MAX)), '')

These two solutions collate several excellent answers and caveats raised by other posters including @Martin Smith, @Svish and @vasin1987.

These options add NULL to '' (empty string) casting for safe NULL handling while accounting for the varying behaviour of the + operator pertaining to specific operands.

Note the ODBC Scaler Function solution is limited to 2 arguments whereas the + operator approach is scalable to many arguments as needed.

Note also the potential issue identified by @Swifty regarding the default varchar size here remedied by varchar(MAX).

Hexadecimal to Integer in Java

SHA-1 produces a 160-bit message (20 bytes), too large to be stored in an int or long value. As Ralph suggests, you could use BigInteger.

To get a (less-secure) int hash, you could return the hash code of the returned byte array.

Alternatively, if you don't really need SHA at all, you could just use the UUID's String hash code.

Bootstrap 3 truncate long text inside rows of a table in a responsive way

You need to use table-layout:fixed in order for CSS ellipsis to work on the table cells.

.table {
  table-layout:fixed;
}

.table td {
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
}

demo: http://bootply.com/9njmoY2CmS

How to delete a file via PHP?

Check your permissions first of all on the file, to make sure you can a) see it from your script, and b) are able to delete it.

You can also use a path calculated from the directory you're currently running the script in, eg:

unlink(dirname(__FILE__) . "/../../public_files/" . $filename);

(in PHP 5.3 I believe you can use the __DIR__ constant instead of dirname() but I've not used it myself yet)

How do you debug PHP scripts?

1) I use print_r(). In TextMate, I have a snippet for 'pre' which expands to this:

echo "<pre>";
print_r();
echo "</pre>";

2) I use Xdebug, but haven't been able to get the GUI to work right on my Mac. It at least prints out a readable version of the stack trace.

How to create a Restful web service with input parameters?

You can try this... put parameters as :
http://localhost:8080/WebApplication11/webresources/generic/getText?arg1=hello in your browser...

package newpackage;

import javax.ws.rs.core.Context;
import javax.ws.rs.core.UriInfo;
import javax.ws.rs.PathParam;
import javax.ws.rs.Produces;
import javax.ws.rs.Consumes;
import javax.ws.rs.DefaultValue;


import javax.ws.rs.GET;
import javax.ws.rs.Path;
import javax.ws.rs.PUT;
import javax.ws.rs.QueryParam;

@Path("generic")
public class GenericResource {

    @Context
    private UriInfo context;

    /**
     * Creates a new instance of GenericResource
     */
    public GenericResource() {
    }

    /**
     * Retrieves representation of an instance of newpackage.GenericResource

     * @return an instance of java.lang.String
     */
    @GET
    @Produces("text/plain")
    @Consumes("text/plain")
    @Path("getText/")
    public String getText(@QueryParam("arg1")
            @DefaultValue("") String arg1) {

       return  arg1 ;  }

    @PUT
    @Consumes("text/plain")
    public void putText(String content) {





    }
}

How do you determine what technology a website is built on?

You could use http://builtbased.com/ to figure out which server, framework and programming language was used.

any tool for java object to object mapping?

There is one more Java mapping engine/framework Nomin: http://nomin.sourceforge.net.

Find the closest ancestor element that has a specific class

Use element.closest()

https://developer.mozilla.org/en-US/docs/Web/API/Element/closest

See this example DOM:

<article>
  <div id="div-01">Here is div-01
    <div id="div-02">Here is div-02
      <div id="div-03">Here is div-03</div>
    </div>
  </div>
</article>

This is how you would use element.closest:

var el = document.getElementById('div-03');

var r1 = el.closest("#div-02");  
// returns the element with the id=div-02

var r2 = el.closest("div div");  
// returns the closest ancestor which is a div in div, here is div-03 itself

var r3 = el.closest("article > div");  
// returns the closest ancestor which is a div and has a parent article, here is div-01

var r4 = el.closest(":not(div)");
// returns the closest ancestor which is not a div, here is the outmost article

On select change, get data attribute value

Vanilla Javascript:

this.querySelector(':checked').getAttribute('data-id')

VB.NET - Click Submit Button on Webbrowser page

This seems to work easily.


Public Function LoginAsTech(ByVal UserID As String, ByVal Pass As String) As Boolean
        Dim MyDoc As New mshtml.HTMLDocument
        Dim DocElements As mshtml.IHTMLElementCollection = Nothing
        Dim LoginForm As mshtml.HTMLFormElement = Nothing

        ASPComplete = 0
        WB.Navigate(VitecLoginURI)
        BrowserLoop()

        MyDoc = WB.Document.DomDocument
        DocElements = MyDoc.getElementsByTagName("input")
        For Each i As mshtml.IHTMLElement In DocElements

            Select Case i.name
                Case "seLogin$UserName"
                    i.value = UserID
                Case "seLogin$Password"
                    i.value = Pass
                Case Else
                    Exit Select
            End Select

            frmServiceCalls.txtOut.Text &= i.name & " : " & i.value & " : " & i.type & vbCrLf
        Next i

        'Old Method for Clicking submit
        'WB.Document.Forms("form1").InvokeMember("submit")


        'Better Method to click submit
        LoginForm = MyDoc.forms.item("form1")
        LoginForm.item("seLogin$LoginButton").click()
        ASPComplete = 0
        BrowserLoop()



        MyDoc= WB.Document.DomDocument
        DocElements = MyDoc.getElementsByTagName("input")
        For Each j As mshtml.IHTMLElement In DocElements
            frmServiceCalls.txtOut.Text &= j.name & " : " & j.value & " : " & j.type & vbCrLf

        Next j

        frmServiceCalls.txtOut.Text &= vbCrLf & vbCrLf & WB.Url.AbsoluteUri & vbCrLf
        Return 1
End Function

How do I remove/delete a folder that is not empty?

From docs.python.org:

This example shows how to remove a directory tree on Windows where some of the files have their read-only bit set. It uses the onerror callback to clear the readonly bit and reattempt the remove. Any subsequent failure will propagate.

import os, stat
import shutil

def remove_readonly(func, path, _):
    "Clear the readonly bit and reattempt the removal"
    os.chmod(path, stat.S_IWRITE)
    func(path)

shutil.rmtree(directory, onerror=remove_readonly)

Label word wrapping

If you want some dynamic sizing in conjunction with a word-wrapping label you can do the following:

  1. Put the label inside a panel
  2. Handle the ClientSizeChanged event for the panel, making the label fill the space:

    private void Panel2_ClientSizeChanged(object sender, EventArgs e)
    {
        label1.MaximumSize = new Size((sender as Control).ClientSize.Width - label1.Left, 10000);
    }
    
  3. Set Auto-Size for the label to true

  4. Set Dock for the label to Fill

Kill process by name?

If you have killall:

os.system("killall -9 iChat");

Or:

os.system("ps -C iChat -o pid=|xargs kill -9")

Interface or an Abstract Class: which one to use?

The main difference is an abstract class can contain default implementation whereas an interface cannot.

An interface is a contract of behaviour without any implementation.

How do I get the current Date/time in DD/MM/YYYY HH:MM format?

time = Time.now.to_s

time = DateTime.parse(time).strftime("%d/%m/%Y %H:%M")

for increment decrement month use << >> operators

examples

datetime_month_before = DateTime.parse(time) << 1



datetime_month_before = DateTime.now << 1

Installing a pip package from within a Jupyter Notebook not working

This worked for me in Jupyter nOtebook /Mac Platform /Python 3 :

import sys
!{sys.executable} -m pip install -r requirements.txt

jQuery class within class selector

For this html:

<div class="outer">
     <div class="inner"></div>
</div>

This selector should work:

$('.outer > .inner')

MySQL select query with multiple conditions

Lets suppose there is a table with following describe command for table (hello)- name char(100), id integer, count integer, city char(100).

we have following basic commands for MySQL -

select * from hello;
select name, city from hello;
etc 

select name from hello where id = 8;
select id from hello where name = 'GAURAV';

now lets see multiple where condition -

select name from hello where id = 3 or id = 4 or id = 8 or id = 22;

select name from hello where id =3 and count = 3 city = 'Delhi';

This is how we can use multiple where commands in MySQL.

Different ways of adding to Dictionary

One is assigning a value while the other is adding to the Dictionary a new Key and Value.

XML Error: Extra content at the end of the document

You need a root node

<?xml version="1.0" encoding="ISO-8859-1"?>    
<documents>
    <document>
        <name>Sample Document</name>
        <type>document</type>
        <url>http://nsc-component.webs.com/Office/Editor/new-doc.html?docname=New+Document&amp;titletype=Title&amp;fontsize=9&amp;fontface=Arial&amp;spacing=1.0&amp;text=&amp;wordcount3=0</url>
    </document>

    <document>
        <name>Sample</name>
        <type>document</type>
        <url>http://nsc-component.webs.com/Office/Editor/new-doc.html?docname=New+Document&amp;titletype=Title&amp;fontsize=9&amp;fontface=Arial&amp;spacing=1.0&amp;text=&amp;</url>
    </document>
</documents>

PHP Include for HTML?

I figured out a simple solution to the PHP include stuff. Simply rename all your .html files to .php and your're good to go.

Resizing Images in VB.NET

This will re-size any image using the best quality with support for 32bpp with alpha. The new image will have the original image centered inside the new one at the original aspect ratio.

#Region " ResizeImage "
    Public Overloads Shared Function ResizeImage(SourceImage As Drawing.Image, TargetWidth As Int32, TargetHeight As Int32) As Drawing.Bitmap
        Dim bmSource = New Drawing.Bitmap(SourceImage)

        Return ResizeImage(bmSource, TargetWidth, TargetHeight)
    End Function

    Public Overloads Shared Function ResizeImage(bmSource As Drawing.Bitmap, TargetWidth As Int32, TargetHeight As Int32) As Drawing.Bitmap
        Dim bmDest As New Drawing.Bitmap(TargetWidth, TargetHeight, Drawing.Imaging.PixelFormat.Format32bppArgb)

        Dim nSourceAspectRatio = bmSource.Width / bmSource.Height
        Dim nDestAspectRatio = bmDest.Width / bmDest.Height

        Dim NewX = 0
        Dim NewY = 0
        Dim NewWidth = bmDest.Width
        Dim NewHeight = bmDest.Height

        If nDestAspectRatio = nSourceAspectRatio Then
            'same ratio
        ElseIf nDestAspectRatio > nSourceAspectRatio Then
            'Source is taller
            NewWidth = Convert.ToInt32(Math.Floor(nSourceAspectRatio * NewHeight))
            NewX = Convert.ToInt32(Math.Floor((bmDest.Width - NewWidth) / 2))
        Else
            'Source is wider
            NewHeight = Convert.ToInt32(Math.Floor((1 / nSourceAspectRatio) * NewWidth))
            NewY = Convert.ToInt32(Math.Floor((bmDest.Height - NewHeight) / 2))
        End If

        Using grDest = Drawing.Graphics.FromImage(bmDest)
            With grDest
                .CompositingQuality = Drawing.Drawing2D.CompositingQuality.HighQuality
                .InterpolationMode = Drawing.Drawing2D.InterpolationMode.HighQualityBicubic
                .PixelOffsetMode = Drawing.Drawing2D.PixelOffsetMode.HighQuality
                .SmoothingMode = Drawing.Drawing2D.SmoothingMode.AntiAlias
                .CompositingMode = Drawing.Drawing2D.CompositingMode.SourceOver

                .DrawImage(bmSource, NewX, NewY, NewWidth, NewHeight)
            End With
        End Using

        Return bmDest
    End Function
#End Region

Java enum - why use toString instead of name

It really depends on what you want to do with the returned value:

  • If you need to get the exact name used to declare the enum constant, you should use name() as toString may have been overriden
  • If you want to print the enum constant in a user friendly way, you should use toString which may have been overriden (or not!).

When I feel that it might be confusing, I provide a more specific getXXX method, for example:

public enum Fields {
    LAST_NAME("Last Name"), FIRST_NAME("First Name");

    private final String fieldDescription;

    private Fields(String value) {
        fieldDescription = value;
    }

    public String getFieldDescription() {
        return fieldDescription;
    }
}

Use tnsnames.ora in Oracle SQL Developer

  • In SQLDeveloper browse Tools --> Preferences, as shown in below image.

    SQLDeveloper access preferences

  • In the Preferences options expand Database --> select Advanced --> under "Tnsnames Directory" --> Browse the directory where tnsnames.ora present.
  • Then click on Ok, as shown in below diagram.
    tnsnames.ora available at Drive:\oracle\product\10x.x.x\client_x\NETWORK\ADMIN

    SQLDeveloper update tnsnames directory

Now you can connect via the TNSnames options.

How to get the HTML for a DOM element in javascript

First, put on element that wraps the div in question, put an id attribute on the element and then use getElementById on it: once you've got the lement, just do 'e.innerHTML` to retrieve the HTML.

<div><span><b>This is in bold</b></span></div>

=> <div id="wrap"><div><span><b>This is in bold</b></span></div></div>

and then:

var e=document.getElementById("wrap");
var content=e.innerHTML;

Note that outerHTML is not cross-browser compatible.

Convert RGB values to Integer

I think the code is something like:

int rgb = red;
rgb = (rgb << 8) + green;
rgb = (rgb << 8) + blue;

Also, I believe you can get the individual values using:

int red = (rgb >> 16) & 0xFF;
int green = (rgb >> 8) & 0xFF;
int blue = rgb & 0xFF;

is not JSON serializable

class CountryListView(ListView):
     model = Country

    def render_to_response(self, context, **response_kwargs):

         return HttpResponse(json.dumps(list(self.get_queryset().values_list('code', flat=True))),mimetype="application/json") 

fixed the problem

also mimetype is important.

Replacing a 32-bit loop counter with 64-bit introduces crazy performance deviations with _mm_popcnt_u64 on Intel CPUs

I can't give an authoritative answer, but provide an overview of a likely cause. This reference shows pretty clearly that for the instructions in the body of your loop there is a 3:1 ratio between latency and throughput. It also shows the effects of multiple dispatch. Since there are (give-or-take) three integer units in modern x86 processors, it's generally possible to dispatch three instructions per cycle.

So between peak pipeline and multiple dispatch performance and failure of these mechanisms, we have a factor of six in performance. It's pretty well known that the complexity of the x86 instruction set makes it quite easy for quirky breakage to occur. The document above has a great example:

The Pentium 4 performance for 64-bit right shifts is really poor. 64-bit left shift as well as all 32-bit shifts have acceptable performance. It appears that the data path from the upper 32 bits to the lower 32 bit of the ALU is not well designed.

I personally ran into a strange case where a hot loop ran considerably slower on a specific core of a four-core chip (AMD if I recall). We actually got better performance on a map-reduce calculation by turning that core off.

Here my guess is contention for integer units: that the popcnt, loop counter, and address calculations can all just barely run at full speed with the 32-bit wide counter, but the 64-bit counter causes contention and pipeline stalls. Since there are only about 12 cycles total, potentially 4 cycles with multiple dispatch, per loop body execution, a single stall could reasonably affect run time by a factor of 2.

The change induced by using a static variable, which I'm guessing just causes a minor reordering of instructions, is another clue that the 32-bit code is at some tipping point for contention.

I know this is not a rigorous analysis, but it is a plausible explanation.

Format specifier %02x

Your string is wider than your format width of 2. So there's no padding to be done.

How to fix Hibernate LazyInitializationException: failed to lazily initialize a collection of roles, could not initialize proxy - no Session

The best way to handle the LazyInitializationException is to use the JOIN FETCH directive for all the entities that you need to fetch along.

Anyway, DO NOT use the following Anti-Patterns as suggested by some of the answers:

Sometimes, a DTO projection is a better choice than fetching entities, and this way, you won't get any LazyInitializationException.

Remove leading comma from a string

remove leading or trailing characters:

function trimLeadingTrailing(inputStr, toRemove) {
    // use a regex to match toRemove at the start (^)
    // and at the end ($) of inputStr
    const re = new Regex(`/^${toRemove}|{toRemove}$/`);
    return inputStr.replace(re, '');
}

How to set delay in android?

Using the Thread.sleep(millis) method.

Turn off warnings and errors on PHP and MySQL

You can set the type of error reporting you need in php.ini or by using the error_reporting() function on top of your script.

In Visual Basic how do you create a block comment

Not in VB.NET, you have to select all lines at then Edit, Advanced, Comment Selection menu, or a keyboard shortcut for that menu.

http://bytes.com/topic/visual-basic-net/answers/376760-how-block-comment

http://forums.asp.net/t/1011404.aspx/1

Writing html form data to a txt file without the use of a webserver

I know this is old, but it's the first example of saving form data to a txt file I found in a quick search. So I've made a couple edits to the above code that makes it work more smoothly. It's now easier to add more fields, including the radio button as @user6573234 requested.

https://jsfiddle.net/cgeiser/m0j7Lwyt/1/

<!DOCTYPE html>
<html>
<head>
<style>
form * {
  display: block;
  margin: 10px;
}
</style>
<script language="Javascript" >
function download() {
  var filename = window.document.myform.docname.value;
  var name =  window.document.myform.name.value;
  var text =  window.document.myform.text.value;
  var problem =  window.document.myform.problem.value;
  
  var pom = document.createElement('a');
  pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + 
    "Your Name: " + encodeURIComponent(name) + "\n\n" +
    "Problem: " + encodeURIComponent(problem) + "\n\n" +
    encodeURIComponent(text)); 

  pom.setAttribute('download', filename);

  pom.style.display = 'none';
  document.body.appendChild(pom);

  pom.click();

  document.body.removeChild(pom);
}
</script>
</head>
<body>
<form name="myform" method="post" >
  <input type="text" id="docname" value="test.txt" />
  <input type="text" id="name" placeholder="Your Name" />
  <div style="display:unblock">
    Option 1 <input type="radio" value="Option 1" onclick="getElementById('problem').value=this.value; getElementById('problem').show()" style="display:inline" />
    Option 2 <input type="radio" value="Option 2" onclick="getElementById('problem').value=this.value;" style="display:inline" />
    <input type="text" id="problem" />
  </div>
  <textarea rows=3 cols=50 id="text" />Please type in this box. 
When you click the Download button, the contents of this box will be downloaded to your machine at the location you specify. Pretty nifty. </textarea>
  
  <input id="download_btn" type="submit" class="btn" style="width: 125px" onClick="download();" />
  
</form>
</body>
</html>

How do I get the current timezone name in Postgres 9.3?

It seems to work fine in Postgresql 9.5:

SELECT current_setting('TIMEZONE');

Set margins in a LinearLayout programmatically

/*
 * invalid margin
 */
private void invalidMarginBottom() {
    RelativeLayout.LayoutParams lp = (RelativeLayout.LayoutParams) frameLayoutContent.getLayoutParams();
    lp.setMargins(0, 0, 0, 0);
    frameLayoutContent.setLayoutParams(lp);
}

you should be ware of the type of the view's viewGroup.In the code above, for example,I want to change the frameLayout's margin,and the frameLayout's view group is a RelativeLayout,so you need to covert to (RelativeLayout.LayoutParams)

Selenium using Python - Geckodriver executable needs to be in PATH

I am using Windows 10 and Anaconda 2. I tried setting the system path variable, but it didn't work out. Then I simply added geckodriver.exe file to the Anaconda 2/Scripts folder and everything works great now.

For me the path was:

C:\Users\Bhavya\Anaconda2\Scripts

Javascript : get <img> src and set as variable?

How about this for instance :

var youtubeimgsrc = document.getElementById("youtubeimg").getAttribute('src');

Spring AMQP + RabbitMQ 3.3.5 ACCESS_REFUSED - Login was refused using authentication mechanism PLAIN

just add login password to connect to RabbitMq

 CachingConnectionFactory connectionFactory = 
         new CachingConnectionFactory("rabbit_host");

 connectionFactory.setUsername("login");
 connectionFactory.setPassword("password");

Add an index (numeric ID) column to large data frame

If your data.frame is a data.table, you can use special symbol .I:

data[, ID := .I]

How to close Browser Tab After Submitting a Form?

Remove onsubmit from the form tag. Change this:

<input type="submit" value="submit" />

To:

<input type="submit" value="submit" name='btnSub' />

And write this:

if(isset($_POST['btnSub']))
    echo "<script>window.close();</script>";

How to get the last element of an array in Ruby?

One other way, using the splat operator:

*a, last = [1, 3, 4, 5]

STDOUT:
a: [1, 3, 4]
last: 5

Basic text editor in command prompt?

You can install vim/vi for windows and set windows PATH variable and open it in command line.

How to combine two byte arrays

I think it is best approach,

public static byte[] addAll(final byte[] array1, byte[] array2) {
    byte[] joinedArray = Arrays.copyOf(array1, array1.length + array2.length);
    System.arraycopy(array2, 0, joinedArray, array1.length, array2.length);
    return joinedArray;
}

Fetch the row which has the Max value for a column

I don't have Oracle to test it, but the most efficient solution is to use analytic queries. It should look something like this:

SELECT DISTINCT
    UserId
  , MaxValue
FROM (
    SELECT UserId
      , FIRST (Value) Over (
          PARTITION BY UserId
          ORDER BY Date DESC
        ) MaxValue
    FROM SomeTable
  )

I suspect that you can get rid of the outer query and put distinct on the inner, but I'm not sure. In the meantime I know this one works.

If you want to learn about analytic queries, I'd suggest reading http://www.orafaq.com/node/55 and http://www.akadia.com/services/ora_analytic_functions.html. Here is the short summary.

Under the hood analytic queries sort the whole dataset, then process it sequentially. As you process it you partition the dataset according to certain criteria, and then for each row looks at some window (defaults to the first value in the partition to the current row - that default is also the most efficient) and can compute values using a number of analytic functions (the list of which is very similar to the aggregate functions).

In this case here is what the inner query does. The whole dataset is sorted by UserId then Date DESC. Then it processes it in one pass. For each row you return the UserId and the first Date seen for that UserId (since dates are sorted DESC, that's the max date). This gives you your answer with duplicated rows. Then the outer DISTINCT squashes duplicates.

This is not a particularly spectacular example of analytic queries. For a much bigger win consider taking a table of financial receipts and calculating for each user and receipt, a running total of what they paid. Analytic queries solve that efficiently. Other solutions are less efficient. Which is why they are part of the 2003 SQL standard. (Unfortunately Postgres doesn't have them yet. Grrr...)

gcc error: wrong ELF class: ELFCLASS64

It turns out the compiler version I was using did not match the compiled version done with the coreset.o.

One was 32bit the other was 64bit. I'll leave this up in case anyone else runs into a similar problem.

MySQL - ERROR 1045 - Access denied

If you actually have set a root password and you've just lost/forgotten it:

  1. Stop MySQL
  2. Restart it manually with the skip-grant-tables option: mysqld_safe --skip-grant-tables

  3. Now, open a new terminal window and run the MySQL client: mysql -u root

  4. Reset the root password manually with this MySQL command: UPDATE mysql.user SET Password=PASSWORD('password') WHERE User='root'; If you are using MySQL 5.7 (check using mysql --version in the Terminal) then the command is:

    UPDATE mysql.user SET authentication_string=PASSWORD('password')  WHERE  User='root';
    
  5. Flush the privileges with this MySQL command: FLUSH PRIVILEGES;

From http://www.tech-faq.com/reset-mysql-password.shtml

(Maybe this isn't what you need, Abs, but I figure it could be useful for people stumbling across this question in the future)

Subset data to contain only columns whose names match a condition

This worked for me:

df[,names(df) %in% colnames(df)[grepl(str,colnames(df))]]

How do I force make/GCC to show me the commands?

Depending on your automake version, you can also use this:

make AM_DEFAULT_VERBOSITY=1

Reference: AM_DEFAULT_VERBOSITY

Note: I added this answer since V=1 did not work for me.

java.lang.ClassNotFoundException: com.fasterxml.jackson.annotation.JsonInclude$Value

Jackson marshalling/unmarshalling requires following jar files of same version.

  1. jackson-core

  2. jackson-databind

  3. jackson-annotations

    Make sure that you have added all these with same version in your classpath. In your case jackson-annotations is missing in classpath.

What is an example of the Liskov Substitution Principle?

The Liskov Substitution Principle

  • The overridden method shouldn’t remain empty
  • The overridden method shouldn’t throw an error
  • Base class or interface behavior should not go for modification (rework) as because of derived class behaviors.

Insert default value when parameter is null

You can use default values for the parameters of stored procedures:

CREATE PROCEDURE MyTestProcedure ( @MyParam1 INT,
@MyParam2 VARCHAR(20) = ‘ABC’,
@MyParam3 INT = NULL)
AS
BEGIN
    -- Procedure body here

END

If @MyParam2 is not supplied, it will have the 'ABC' value...

Fill Combobox from database

string query = "SELECT column_name FROM table_name";      //query the database
SqlCommand queryStatus = new SqlCommand(query, myConnection);
sqlDataReader reader = queryStatus.ExecuteReader();                               
            
while (reader.Read())   //loop reader and fill the combobox
{
ComboBox1.Items.Add(reader["column_name"].ToString());
}

Convert a positive number to negative in C#

To switch the sign of an integer, you just use the sign operator:

myInt = -myInt;

To make it negative regardless if the original value is negative or not, you first use the Abs method:

myInt = -Math.Abs(myInt);

How to compare strings in Bash

Using variables in if statements

if [ "$x" = "valid" ]; then
  echo "x has the value 'valid'"
fi

If you want to do something when they don't match, replace = with !=. You can read more about string operations and arithmetic operations in their respective documentation.

Why do we use quotes around $x?

You want the quotes around $x, because if it is empty, your Bash script encounters a syntax error as seen below:

if [ = "valid" ]; then

Non-standard use of == operator

Note that Bash allows == to be used for equality with [, but this is not standard.

Use either the first case wherein the quotes around $x are optional:

if [[ "$x" == "valid" ]]; then

or use the second case:

if [ "$x" = "valid" ]; then

How do I compare two columns for equality in SQL Server?

I'd go with the CASE WHEN also.

Depending on what you actually want to do, there may be other options though, like using an outer join or whatever, but that doesn't seem to be what you need in this case.

Is there a format code shortcut for Visual Studio?

Right click on the code, and you have "Format Document". In my case it is Ctrl+Shift+I

enter image description here

Using malloc for allocation of multi-dimensional arrays with different row lengths

If every element in b has different lengths, then you need to do something like:

int totalLength = 0;
for_every_element_in_b {
    totalLength += length_of_this_b_in_bytes;
}
return (char **)malloc(totalLength);

Opening a new tab to read a PDF file

Just use target on your tag <a>

<a href="newsletter_01.pdf" target="_blank">Read more</a>

The target attribute specifies where to open the link. Using "_blank" will make your browser to open a new window/tab.

You could also use target in many ways. See http://www.w3schools.com/tags/att_a_target.asp

Unable to compile simple Java 10 / Java 11 project with Maven

Alright so for me nothing worked.
I was using spring boot with hibernate. The spring boot version was ~2.0.1 and I would keep get this error and null pointer exception upon compilation. The issue was with hibernate that needed a version bump. But after that I had some other issues that seemed like the annotation processor was not recognised so I decided to just bump spring from 2.0.1 to 2.1.7-release and everything worked as expected.

You still need to add the above plugin tough
Hope it helps!

How to call a function after delay in Kotlin?

If you're using more recent Android APIs the Handler empty constructor has been deprecated and you should include a Looper. You can easily get one through Looper.getMainLooper().

    Handler(Looper.getMainLooper()).postDelayed({
        //Your code
    }, 2000) //millis

Python Accessing Nested JSON Data

I'm using this lib to access nested dict keys

https://github.com/mewwts/addict

 import requests
 from addict import Dict
 r = requests.get('http://api.zippopotam.us/us/ma/belmont')
 j = Dict(r.json())

 print j.state
 print j.places[1]['post code']  # only work with keys without '-', space, or starting with number 

Paste Excel range in Outlook

First off, RangeToHTML. The script calls it like a method, but it isn't. It's a popular function by MVP Ron de Bruin. Coincidentally, that links points to the exact source of the script you posted, before those few lines got b?u?t?c?h?e?r?e?d? modified.

On with Range.SpecialCells. This method operates on a range and returns only those cells that match the given criteria. In your case, you seem to be only interested in the visible text cells. Importantly, it operates on a Range, not on HTML text.

For completeness sake, I'll post a working version of the script below. I'd certainly advise to disregard it and revisit the excellent original by Ron the Bruin.

Sub Mail_Selection_Range_Outlook_Body()

Dim rng As Range
Dim OutApp As Object
Dim OutMail As Object

Set rng = Nothing
' Only send the visible cells in the selection.

Set rng = Sheets("Sheet1").Range("D4:D12").SpecialCells(xlCellTypeVisible)

If rng Is Nothing Then
    MsgBox "The selection is not a range or the sheet is protected. " & _
           vbNewLine & "Please correct and try again.", vbOKOnly
    Exit Sub
End If

With Application
    .EnableEvents = False
    .ScreenUpdating = False
End With

Set OutApp = CreateObject("Outlook.Application")
Set OutMail = OutApp.CreateItem(0)


With OutMail
    .To = ThisWorkbook.Sheets("Sheet2").Range("C1").Value
    .CC = ""
    .BCC = ""
    .Subject = "This is the Subject line"
    .HTMLBody = RangetoHTML(rng)
    ' In place of the following statement, you can use ".Display" to
    ' display the e-mail message.
    .Display
End With
On Error GoTo 0

With Application
    .EnableEvents = True
    .ScreenUpdating = True
End With

Set OutMail = Nothing
Set OutApp = Nothing
End Sub


Function RangetoHTML(rng As Range)
' By Ron de Bruin.
    Dim fso As Object
    Dim ts As Object
    Dim TempFile As String
    Dim TempWB As Workbook

    TempFile = Environ$("temp") & "/" & Format(Now, "dd-mm-yy h-mm-ss") & ".htm"

    'Copy the range and create a new workbook to past the data in
    rng.Copy
    Set TempWB = Workbooks.Add(1)
    With TempWB.Sheets(1)
        .Cells(1).PasteSpecial Paste:=8
        .Cells(1).PasteSpecial xlPasteValues, , False, False
        .Cells(1).PasteSpecial xlPasteFormats, , False, False
        .Cells(1).Select
        Application.CutCopyMode = False
        On Error Resume Next
        .DrawingObjects.Visible = True
        .DrawingObjects.Delete
        On Error GoTo 0
    End With

    'Publish the sheet to a htm file
    With TempWB.PublishObjects.Add( _
         SourceType:=xlSourceRange, _
         Filename:=TempFile, _
         Sheet:=TempWB.Sheets(1).Name, _
         Source:=TempWB.Sheets(1).UsedRange.Address, _
         HtmlType:=xlHtmlStatic)
        .Publish (True)
    End With

    'Read all data from the htm file into RangetoHTML
    Set fso = CreateObject("Scripting.FileSystemObject")
    Set ts = fso.GetFile(TempFile).OpenAsTextStream(1, -2)
    RangetoHTML = ts.ReadAll
    ts.Close
    RangetoHTML = Replace(RangetoHTML, "align=center x:publishsource=", _
                          "align=left x:publishsource=")

    'Close TempWB
    TempWB.Close savechanges:=False

    'Delete the htm file we used in this function
    Kill TempFile

    Set ts = Nothing
    Set fso = Nothing
    Set TempWB = Nothing
End Function

github: server certificate verification failed

Make sure first that you have certificates installed on your Debian in /etc/ssl/certs.

If not, reinstall them:

sudo apt-get install --reinstall ca-certificates

Since that package does not include root certificates, add:

sudo mkdir /usr/local/share/ca-certificates/cacert.org
sudo wget -P /usr/local/share/ca-certificates/cacert.org http://www.cacert.org/certs/root.crt http://www.cacert.org/certs/class3.crt
sudo update-ca-certificates

Make sure your git does reference those CA:

git config --global http.sslCAinfo /etc/ssl/certs/ca-certificates.crt

Jason C mentions another potential cause (in the comments):

It was the clock. The NTP server was down, the system clock wasn't set properly, I didn't notice or think to check initially, and the incorrect time was causing verification to fail.

Certificates are time sensitive.

How to retrieve data from a SQL Server database in C#?

    DataTable formerSlidesData = new DataTable();
    DformerSlidesData = searchAndFilterService.SearchSlideById(ids[i]);
                if (formerSlidesData.Rows.Count > 0)
                {
                    DataRow rowa = formerSlidesData.Rows[0];

                    cabinet = Convert.ToInt32(rowa["cabinet"]);
                    box = Convert.ToInt32(rowa["box"]);
                    drawer = Convert.ToInt32(rowa["drawer"]);
                }

How to avoid scientific notation for large numbers in JavaScript?

If you are just doing it for display, you can build an array from the digits before they're rounded.

var num = Math.pow(2, 100);
var reconstruct = [];
while(num > 0) {
    reconstruct.unshift(num % 10);
    num = Math.floor(num / 10);
}
console.log(reconstruct.join(''));

JavaScript: client-side vs. server-side validation

Well, I still find some room to answer.

In addition to answers from Rob and Nathan, I would add that having client-side validations matters. When you are applying validations on your webforms you must follow these guidelines:

Client-Side

  1. Must use client-side validations in order to filter genuine requests coming from genuine users at your website.
  2. The client-side validation should be used to reduce the errors that might occure during server side processing.
  3. Client-side validation should be used to minimize the server-side round-trips so that you save bandwidth and the requests per user.

Server-Side

  1. You SHOULD NOT assume the validation successfully done at client side is 100% perfect. No matter even if it serves less than 50 users. You never know which of your user/emplyee turn into an "evil" and do some harmful activity knowing you dont have proper validations in place.
  2. Even if its perfect in terms of validating email address, phone numbers or checking some valid inputs it might contain very harmful data. Which needs to be filtered at server-side no matter if its correct or incorrect.
  3. If client-side validation is bypassed, your server-side validations comes to rescue you from any potential damage to your server-side processing. In recent times, we have already heard lot of stories of SQL Injections and other sort of techniques that might be applied in order to gain some evil benefits.

Both types of validations play important roles in their respective scope but the most strongest is the server-side. If you receive 10k users at a single point of time then you would definitely end up filtering the number of requests coming to your webserver. If you find there was a single mistake like invalid email address then they post back the form again and ask your user to correct it which will definitely eat your server resources and bandwidth. So better you apply javascript validation. If javascript is disabled then your server side validation will come to rescue and i bet only a few users might have accidentlly disable it since 99.99% of websites use javascript and its already enabled by default in all modern browsers.

What are the recommendations for html <base> tag?

Breakdown of the effects of the base tag:

The base tag appears to have some non-intuitive effects, and I recommend being aware of the outcomes and testing them for yourself before relying on <base>! Since I've discovered them after trying to use the base tag to handle local sites with differing urls and only found out the problematic effects after, to my dismay, I feel compelled to create this summary of these potential pitfalls for others.

I'll use a base tag of: <base href="http://www.example.com/other-subdirectory/"> as my example in the cases below, and will pretend that the page that the code is on is http://localsite.com/original-subdirectory

Major:

No links or named anchors or blank hrefs will point to the original subdirectory, unless that is made explicit: The base tag makes everything link differently, including same-page anchor links to the base tag's url instead, e.g:

  • <a href='#top-of-page' title='Some title'>A link to the top of the page via a named anchor</a>
    becomes
    <a href='http://www.example.com/other-subdirectory/#top-of-page' title='Some title'>A link to an #named-anchor on the completely different base page</a>

  • <a href='?update=1' title='Some title'>A link to this page</a>
    becomes
    <a href='http://www.example.com/other-subdirectory/?update=1' title='Some title'>A link to the base tag's page instead</a>

With some work, you can fix these problems on links that you have control over, by explicitly specifying that these links link to the page that they are on, but when you add third-party libraries to the mix that rely on the standard behavior, it can easily cause a big mess.

Minor:

IE6 fix that requires conditional comments: Requires conditional comments for ie6 to avoid screwing up the dom hierarchy, i.e. <base href="http://www.example.com/"><!--[if lte IE 6]></base><![endif]--> as BalusC mentions in his answer above.

So overall, the major problem makes use tricky unless you have full editing control over every link, and as I originally feared, that makes it more trouble than it's worth. Now I have to go off and rewrite all my uses of it! :p

Related links of testing for issues when using "fragments"/hashes:

http://www.w3.org/People/mimasa/test/base/

http://www.w3.org/People/mimasa/test/base/results


Edit by Izzy: For all of you running into the same confusion as me concerning the comments:

I've just tested it out myself, with the following results:

  • trailing slash or not, makes no difference to the examples given here (#anchor and ?query would simply be appended to the specified <BASE>).
  • It however makes a difference for relative links: omitting the trailing slash, other.html and dir/other.html would start at the DOCUMENT_ROOT with the given example, /other-subdirectory being (correctly) treated as file and thus omitted.

So for relative links, BASE works fine with the moved page – while anchors and ?queries would need the file name be specified explicitly (with BASE having a trailing slash, or the last element not corresponding to the name of the file it's used in).

Think of it as <BASE> replacing the full URL to the file itself (and not the directory it resides in), and you'll get things right. Assuming the file used in this example was other-subdirectory/test.html (after it moved to the new location), the correct specification should have been:

<base href="http://www.example.com/other-subdirectory/test.html">

– et voila, everything works as expected: #anchor, ?query, other.html, very/other.html, /completely/other.html.

Angular IE Caching issue for $http

You can either append a unique querystring (I believe this is what jQuery does with the cache: false option) to the request.

$http({
    url: '...',
    params: { 'foobar': new Date().getTime() }
})

A perhaps better solution is if you have access to the server, then you can make sure that necessary headers are set to prevent caching. If you're using ASP.NET MVC this answer might help.

Can't perform a React state update on an unmounted component

Inspired by the accepted answer by @ford04 I had even better approach dealing with it, instead of using useEffect inside useAsync create a new function that returns a callback for componentWillUnmount :

function asyncRequest(asyncRequest, onSuccess, onError, onComplete) {
  let isMounted=true
  asyncRequest().then((data => isMounted ? onSuccess(data):null)).catch(onError).finally(onComplete)
  return () => {isMounted=false}
}

...

useEffect(()=>{
        return asyncRequest(()=>someAsyncTask(arg), response=> {
            setSomeState(response)
        },onError, onComplete)
    },[])

What is the difference between URI, URL and URN?

Uniform Resource Identifier (URI) is a string of characters used to identify a name or a resource on the Internet

A URI identifies a resource either by location, or a name, or both. A URI has two specializations known as URL and URN.

A Uniform Resource Locator (URL) is a subset of the Uniform Resource Identifier (URI) that specifies where an identified resource is available and the mechanism for retrieving it. A URL defines how the resource can be obtained. It does not have to be HTTP URL (http://), a URL can also be (ftp://) or (smb://).

A Uniform Resource Name (URN) is a Uniform Resource Identifier (URI) that uses the URN scheme, and does not imply availability of the identified resource. Both URNs (names) and URLs (locators) are URIs, and a particular URI may be both a name and a locator at the same time.

The URNs are part of a larger Internet information architecture which is composed of URNs, URCs and URLs.

bar.html is not a URN. A URN is similar to a person's name, while a URL is like a street address. The URN defines something's identity, while the URL provides a location. Essentially, "what" vs. "where". A URN has to be of this form <URN> ::= "urn:" <NID> ":" <NSS> where <NID> is the Namespace Identifier, and <NSS> is the Namespace Specific String.

To put it differently:

  • A URL is a URI that identifies a resource and also provides the means of locating the resource by describing the way to access it
  • A URL is a URI
  • A URI is not necessarily a URL

I'd say the only thing left to make it 100% clear would be to have an example of an URI that is not an URL. We can use the examples in the RFC3986:

URL: ftp://ftp.is.co.za/rfc/rfc1808.txt
URL: http://www.ietf.org/rfc/rfc2396.txt
URL: ldap://[2001:db8::7]/c=GB?objectClass?one
URL: mailto:[email protected]
URL: news:comp.infosystems.www.servers.unix
URL: telnet://192.0.2.16:80/
URN (not URL): urn:oasis:names:specification:docbook:dtd:xml:4.1.2
URN (not URL): tel:+1-816-555-1212 (?)

Also check this out - https://quintupledev.wordpress.com/2016/02/29/difference-between-uri-url-and-urn/

What are your favorite extension methods for C#? (codeplex.com/extensionoverflow)

String.As<T>, which can be used to convert a string value as some type (intended to be used primarily with primitives and types that support IConvertable. Works great with Nullable types and even Enums!

public static partial class StringExtensions
{
    /// <summary>
    /// Converts the string to the specified type, using the default value configured for the type.
    /// </summary>
    /// <typeparam name="T">Type the string will be converted to. The type must implement IConvertable.</typeparam>
    /// <param name="original">The original string.</param>
    /// <returns>The converted value.</returns>
    public static T As<T>(this String original)
    {
        return As(original, CultureInfo.CurrentCulture,
                  default(T));
    }

    /// <summary>
    /// Converts the string to the specified type, using the default value configured for the type.
    /// </summary>
    /// <typeparam name="T">Type the string will be converted to.</typeparam>
    /// <param name="original">The original string.</param>
    /// <param name="defaultValue">The default value to use in case the original string is null or empty, or can't be converted.</param>
    /// <returns>The converted value.</returns>
    public static T As<T>(this String original, T defaultValue)
    {
        return As(original, CultureInfo.CurrentCulture, defaultValue);
    }

    /// <summary>
    /// Converts the string to the specified type, using the default value configured for the type.
    /// </summary>
    /// <typeparam name="T">Type the string will be converted to.</typeparam>
    /// <param name="original">The original string.</param>
    /// <param name="provider">Format provider used during the type conversion.</param>
    /// <returns>The converted value.</returns>
    public static T As<T>(this String original, IFormatProvider provider)
    {
        return As(original, provider, default(T));
    }

    /// <summary>
    /// Converts the string to the specified type.
    /// </summary>
    /// <typeparam name="T">Type the string will be converted to.</typeparam>
    /// <param name="original">The original string.</param>
    /// <param name="provider">Format provider used during the type conversion.</param>
    /// <param name="defaultValue">The default value to use in case the original string is null or empty, or can't be converted.</param>
    /// <returns>The converted value.</returns>
    /// <remarks>
    /// If an error occurs while converting the specified value to the requested type, the exception is caught and the default is returned. It is strongly recommended you
    /// do NOT use this method if it is important that conversion failures are not swallowed up.
    ///
    /// This method is intended to be used to convert string values to primatives, not for parsing, converting, or deserializing complex types.
    /// </remarks>
    public static T As<T>(this String original, IFormatProvider provider,
                          T defaultValue)
    {
        T result;
        Type type = typeof (T);

        if (String.IsNullOrEmpty(original)) result = defaultValue;
        else
        {
            // need to get the underlying type if T is Nullable<>.

            if (type.IsNullableType())
            {
                type = Nullable.GetUnderlyingType(type);
            }

            try
            {
                // ChangeType doesn't work properly on Enums
                result = type.IsEnum
                             ? (T) Enum.Parse(type, original, true)
                             : (T) Convert.ChangeType(original, type, provider);
            }
            catch // HACK: what can we do to minimize or avoid raising exceptions as part of normal operation? custom string parsing (regex?) for well-known types? it would be best to know if you can convert to the desired type before you attempt to do so.
            {
                result = defaultValue;
            }
        }

        return result;
    }
}

This relies on another simple extension for Type:

/// <summary>
/// Extension methods for <see cref="Type"/>.
/// </summary>
public static class TypeExtensions
{
    /// <summary>
    /// Returns whether or not the specified type is <see cref="Nullable{T}"/>.
    /// </summary>
    /// <param name="type">A <see cref="Type"/>.</param>
    /// <returns>True if the specified type is <see cref="Nullable{T}"/>; otherwise, false.</returns>
    /// <remarks>Use <see cref="Nullable.GetUnderlyingType"/> to access the underlying type.</remarks>
    public static bool IsNullableType(this Type type)
    {
        if (type == null) throw new ArgumentNullException("type");

        return type.IsGenericType && type.GetGenericTypeDefinition().Equals(typeof (Nullable<>));
    }
}

Usage:

var someInt = "1".As<int>();
var someIntDefault = "bad value".As(1); // "bad value" won't convert, so the default value 1 is returned.
var someEnum = "Sunday".As<DayOfWeek>();
someEnum = "0".As<DayOfWeek>(); // returns Sunday
var someNullableEnum = "".As<DayOfWeek?>(null); // returns a null value since "" can't be converted

printf \t option

A tab is a tab. How many spaces it consumes is a display issue, and depends on the settings of your shell.

If you want to control the width of your data, then you could use the width sub-specifiers in the printf format string. Eg. :

printf("%5d", 2);

It's not a complete solution (if the value is longer than 5 characters, it will not be truncated), but might be ok for your needs.

If you want complete control, you'll probably have to implement it yourself.

How to solve munmap_chunk(): invalid pointer error in C++

The hint is, the output file is created even if you get this error. The automatic deconstruction of vector starts after your code executed. Elements in the vector are deconstructed as well. This is most probably where the error occurs. The way you access the vector is through vector::operator[] with an index read from stream. Try vector::at() instead of vector::operator[]. This won't solve your problem, but will show which assignment to the vector causes error.

Git error when trying to push -- pre-receive hook declined

In my case, it's because I accidentally added a giant file to my uncommitted push and I could not get rid of it no matter whatever pull or reset or rm I did after.

my dirty solution but workable solution is to rename the current directory, re-clone the directory to local and reflect the changes manually to the recloned local directory...

It does not sound good but works...

Getting value from a cell from a gridview on RowDataBound event

Label lblSecret = ((Label)e.Row.FindControl("lblSecret"));

How to make a form close when pressing the escape key?

If you have a cancel button on your form, you can set the Form.CancelButton property to that button and then pressing escape will effectively 'click the button'.

If you don't have such a button, check out the Form.KeyPreview property.

Wait .5 seconds before continuing code VB.net

Static tStart As Single, tEnd As Single, myInterval As Integer
myInterval = 5 ' seconds
tStart = VB.Timer()
tEnd = myInterval + VB.Timer()
Do While tEnd > tStart
    Application.DoEvents()
    tStart = VB.Timer()
Loop

What are the rules about using an underscore in a C++ identifier?

The rules to avoid collision of names are both in the C++ standard (see Stroustrup book) and mentioned by C++ gurus (Sutter, etc.).

Personal rule

Because I did not want to deal with cases, and wanted a simple rule, I have designed a personal one that is both simple and correct:

When naming a symbol, you will avoid collision with compiler/OS/standard libraries if you:

  • never start a symbol with an underscore
  • never name a symbol with two consecutive underscores inside.

Of course, putting your code in an unique namespace helps to avoid collision, too (but won't protect against evil macros)

Some examples

(I use macros because they are the more code-polluting of C/C++ symbols, but it could be anything from variable name to class name)

#define _WRONG
#define __WRONG_AGAIN
#define RIGHT_
#define WRONG__WRONG
#define RIGHT_RIGHT
#define RIGHT_x_RIGHT

Extracts from C++0x draft

From the n3242.pdf file (I expect the final standard text to be similar):

17.6.3.3.2 Global names [global.names]

Certain sets of names and function signatures are always reserved to the implementation:

— Each name that contains a double underscore _ _ or begins with an underscore followed by an uppercase letter (2.12) is reserved to the implementation for any use.

— Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.

But also:

17.6.3.3.5 User-defined literal suffixes [usrlit.suffix]

Literal suffix identifiers that do not start with an underscore are reserved for future standardization.

This last clause is confusing, unless you consider that a name starting with one underscore and followed by a lowercase letter would be Ok if not defined in the global namespace...

Spring MVC - Why not able to use @RequestBody and @RequestParam together

It's too late to answer this question, but it could help for new readers, It seems version issues. I ran all these tests with spring 4.1.4 and found that the order of @RequestBody and @RequestParam doesn't matter.

  1. same as your result
  2. same as your result
  3. gave body= "name=abc", and name = "abc"
  4. Same as 3.
  5. body ="name=abc", name = "xyz,abc"
  6. same as 5.

Check if a Postgres JSON array contains a string

A small variation but nothing new infact. It's really missing a feature...

select info->>'name' from rabbits 
where '"carrots"' = ANY (ARRAY(
    select * from json_array_elements(info->'food'))::text[]);

What is the HTML unicode character for a "tall" right chevron?

I use ? (0x25B8) for the right arrow, often to show a collapsed list; and I pair it with ? (0x25BE) to show the list opened up. Both are unobtrusive.

Could not obtain information about Windows NT group user

Active Directory is refusing access to your SQL Agent. The Agent should be running under an account that is recognized by STAR domain controller.

Node.js client for a socket.io server

After installing socket.io-client:

npm install socket.io-client

This is how the client code looks like:

var io = require('socket.io-client'),
socket = io.connect('localhost', {
    port: 1337
});
socket.on('connect', function () { console.log("socket connected"); });
socket.emit('private message', { user: 'me', msg: 'whazzzup?' });

Thanks alessioalex.

Right align and left align text in same HTML table cell

Tor Valamo's answer with a little contribution form my side: use the attribute "nowrap" in the "td" element, and you can remove the "width" specification. Hope it helps.

<td nowrap>
  <div style="float:left;">this is left</div>
  <div style="float:right;">this is right</div>
</td>

Could not connect to SMTP host: localhost, port: 25; nested exception is: java.net.ConnectException: Connection refused: connect

First you have to ensure that there is a SMTP server listening on port 25.

To look whether you have the service, you can try using TELNET client, such as:

C:\> telnet localhost 25

(telnet client by default is disabled on most recent versions of Windows, you have to add/enable the Windows component from Control Panel. In Linux/UNIX usually telnet client is there by default.

$ telnet localhost 25

If it waits for long then time out, that means you don't have the required SMTP service. If successfully connected you enter something and able to type something, the service is there.

If you don't have the service, you can use these:

  • A mock SMTP server that will mimic the behavior of actual SMTP server, as you are using Java, it is natural to suggest Dumbster fake SMTP server. This even can be made to work within JUnit tests (with setup/tear down/validation), or independently run as separate process for integration test.
  • If your host is Windows, you can try installing Mercury email server (also comes with WAMPP package from Apache Friends) on your local before running above code.
  • If your host is Linux or UNIX, try to enable the mail service such as Postfix,
  • Another full blown SMTP server in Java, such as Apache James mail server.

If you are sure that you already have the service, may be the SMTP requires additional security credentials. If you can tell me what SMTP server listening on port 25 I may be able to tell you more.

How to display an unordered list in two columns?

more one answer after a few years!

in this article: http://csswizardry.com/2010/02/mutiple-column-lists-using-one-ul/

HTML:

<ul id="double"> <!-- Alter ID accordingly -->
  <li>CSS</li>
  <li>XHTML</li>
  <li>Semantics</li>
  <li>Accessibility</li>
  <li>Usability</li>
  <li>Web Standards</li>
  <li>PHP</li>
  <li>Typography</li>
  <li>Grids</li>
  <li>CSS3</li>
  <li>HTML5</li>
  <li>UI</li>
</ul>

CSS:

ul{
  width:760px;
  margin-bottom:20px;
  overflow:hidden;
  border-top:1px solid #ccc;
}
li{
  line-height:1.5em;
  border-bottom:1px solid #ccc;
  float:left;
  display:inline;
}
#double li  { width:50%;}
#triple li  { width:33.333%; }
#quad li    { width:25%; }
#six li     { width:16.666%; }

Why do multiple-table joins produce duplicate rows?

If one of the tables M, S, D, or H has more than one row for a given Id (if just the Id column is not the Primary Key), then the query would result in "duplicate" rows. If you have more than one row for an Id in a table, then the other columns, which would uniquely identify a row, also must be included in the JOIN condition(s).

References:

Related Question on MSDN Forum

How to open a new form from another form

For example, you have a Button named as Button1. First click on it it will open the EventHandler of that Button2 to call another Form you should write the following code to your Button.

your name example=form2.

form2 obj=new form2();

obj.show();

To close form1, write the following code:

form1.visible=false; or form1.Hide();

How do I recursively delete a directory and its entire contents (files + sub dirs) in PHP?

<?php

/**
 * code by Nk ([email protected])
 */

class filesystem
{
    public static function remove($path)
    {
        return is_dir($path) ? rmdir($path) : unlink($path);
    }

    public static function normalizePath($path)
    {
        return $path.(is_dir($path) && !preg_match('@/$@', $path) ? '/' : '');      
    }

    public static function rscandir($dir, $sort = SCANDIR_SORT_ASCENDING)
    {
        $results = array();

        if(!is_dir($dir))
        return $results;

        $dir = self::normalizePath($dir);

        $objects = scandir($dir, $sort);

        foreach($objects as $object)
        if($object != '.' && $object != '..')
        {
            if(is_dir($dir.$object))
            $results = array_merge($results, self::rscandir($dir.$object, $sort));
            else
            array_push($results, $dir.$object);
        }

        array_push($results, $dir);

        return $results;
    }

    public static function rrmdir($dir)
    {
        $files = self::rscandir($dir);

        foreach($files as $file)
        self::remove($file);

        return !file_exists($dir);
    }
}

?>

cleanup.php :

<?php

/* include.. */

filesystem::rrmdir('/var/log');
filesystem::rrmdir('./cache');

?>