Programs & Examples On #Gtk textbuffer

Extracting columns from text file with different delimiters in Linux

If the command should work with both tabs and spaces as the delimiter I would use awk:

awk '{print $100,$101,$102,$103,$104,$105}' myfile > outfile

As long as you just need to specify 5 fields it is imo ok to just type them, for longer ranges you can use a for loop:

awk '{for(i=100;i<=105;i++)print $i}' myfile > outfile

If you want to use cut, you need to use the -f option:

cut -f100-105 myfile > outfile

If the field delimiter is different from TAB you need to specify it using -d:

cut -d' ' -f100-105 myfile > outfile

Check the man page for more info on the cut command.

Refused to load the script because it violates the following Content Security Policy directive

Full permission string

The previous answers did not fix my issue, because they don't include blob: data: gap: keywords at the same time; so here is a string that does:

<meta http-equiv="Content-Security-Policy" content="default-src * self blob: data: gap:; style-src * self 'unsafe-inline' blob: data: gap:; script-src * 'self' 'unsafe-eval' 'unsafe-inline' blob: data: gap:; object-src * 'self' blob: data: gap:; img-src * self 'unsafe-inline' blob: data: gap:; connect-src self * 'unsafe-inline' blob: data: gap:; frame-src * self blob: data: gap:;">

Warning: This exposes the document to many exploits. Be sure to prevent users from executing code in the console or to be in a closed environment like a Cordova application.

What does Docker add to lxc-tools (the userspace LXC tools)?

The above post & answers are rapidly becoming dated as the development of LXD continues to enhance LXC. Yes, I know Docker hasn't stood still either.

LXD now implements a repository for LXC container images which a user can push/pull from to contribute to or reuse.

LXD's REST api to LXC now enables both local & remote creation/deployment/management of LXC containers using a very simple command syntax.

Key features of LXD are:

  • Secure by design (unprivileged containers, resource restrictions and much more)
  • Scalable (from containers on your laptop to thousand of compute nodes)
  • Intuitive (simple, clear API and crisp command line experience)
  • Image based (no more distribution templates, only good, trusted images) Live migration

There is NCLXD plugin now for OpenStack allowing OpenStack to utilize LXD to deploy/manage LXC containers as VMs in OpenStack instead of using KVM, vmware etc.

However, NCLXD also enables a hybrid cloud of a mix of traditional HW VMs and LXC VMs.

The OpenStack nclxd plugin a list of features supported include:

stop/start/reboot/terminate container
Attach/detach network interface
Create container snapshot
Rescue/unrescue instance container
Pause/unpause/suspend/resume container
OVS/bridge networking
instance migration
firewall support

By the time Ubuntu 16.04 is released in Apr 2016 there will have been additional cool features such as block device support, live-migration support.

What does the "@" symbol do in Powershell?

PowerShell will actually treat any comma-separated list as an array:

"server1","server2"

So the @ is optional in those cases. However, for associative arrays, the @ is required:

@{"Key"="Value";"Key2"="Value2"}

Officially, @ is the "array operator." You can read more about it in the documentation that installed along with PowerShell, or in a book like "Windows PowerShell: TFM," which I co-authored.

How do I make a matrix from a list of vectors in R?

The built-in matrix function has the nice option to enter data byrow. Combine that with an unlist on your source list will give you a matrix. We also need to specify the number of rows so it can break up the unlisted data. That is:

> matrix(unlist(a), byrow=TRUE, nrow=length(a) )
      [,1] [,2] [,3] [,4] [,5] [,6]
 [1,]    1    1    2    3    4    5
 [2,]    2    1    2    3    4    5
 [3,]    3    1    2    3    4    5
 [4,]    4    1    2    3    4    5
 [5,]    5    1    2    3    4    5
 [6,]    6    1    2    3    4    5
 [7,]    7    1    2    3    4    5
 [8,]    8    1    2    3    4    5
 [9,]    9    1    2    3    4    5
[10,]   10    1    2    3    4    5

How to handle the modal closing event in Twitter Bootstrap?

Bootstrap Modal Events:

  1. hide.bs.modal => Occurs when the modal is about to be hidden.
  2. hidden.bs.modal => Occurs when the modal is fully hidden (after CSS transitions have completed).
<script type="text/javascript">
    $("#salesitems_modal").on('hide.bs.modal', function () {
        //actions you want to perform after modal is closed.
    });
</script>

I hope this will Help.

Catching FULL exception message

Errors and exceptions in PowerShell are structured objects. The error message you see printed on the console is actually a formatted message with information from several elements of the error/exception object. You can (re-)construct it yourself like this:

$formatstring = "{0} : {1}`n{2}`n" +
                "    + CategoryInfo          : {3}`n" +
                "    + FullyQualifiedErrorId : {4}`n"
$fields = $_.InvocationInfo.MyCommand.Name,
          $_.ErrorDetails.Message,
          $_.InvocationInfo.PositionMessage,
          $_.CategoryInfo.ToString(),
          $_.FullyQualifiedErrorId

$formatstring -f $fields

If you just want the error message displayed in your catch block you can simply echo the current object variable (which holds the error at that point):

try {
  ...
} catch {
  $_
}

If you need colored output use Write-Host with a formatted string as described above:

try {
  ...
} catch {
  ...
  Write-Host -Foreground Red -Background Black ($formatstring -f $fields)
}

With that said, usually you don't want to just display the error message as-is in an exception handler (otherwise the -ErrorAction Stop would be pointless). The structured error/exception objects provide you with additional information that you can use for better error control. For instance you have $_.Exception.HResult with the actual error number. $_.ScriptStackTrace and $_.Exception.StackTrace, so you can display stacktraces when debugging. $_.Exception.InnerException gives you access to nested exceptions that often contain additional information about the error (top level PowerShell errors can be somewhat generic). You can unroll these nested exceptions with something like this:

$e = $_.Exception
$msg = $e.Message
while ($e.InnerException) {
  $e = $e.InnerException
  $msg += "`n" + $e.Message
}
$msg

In your case the information you want to extract seems to be in $_.ErrorDetails.Message. It's not quite clear to me if you have an object or a JSON string there, but you should be able to get information about the types and values of the members of $_.ErrorDetails by running

$_.ErrorDetails | Get-Member
$_.ErrorDetails | Format-List *

If $_.ErrorDetails.Message is an object you should be able to obtain the message string like this:

$_.ErrorDetails.Message.message

otherwise you need to convert the JSON string to an object first:

$_.ErrorDetails.Message | ConvertFrom-Json | Select-Object -Expand message

Depending what kind of error you're handling, exceptions of particular types might also include more specific information about the problem at hand. In your case for instance you have a WebException which in addition to the error message ($_.Exception.Message) contains the actual response from the server:

PS C:\> $e.Exception | Get-Member

   TypeName: System.Net.WebException

Name             MemberType Definition
----             ---------- ----------
Equals           Method     bool Equals(System.Object obj), bool _Exception.E...
GetBaseException Method     System.Exception GetBaseException(), System.Excep...
GetHashCode      Method     int GetHashCode(), int _Exception.GetHashCode()
GetObjectData    Method     void GetObjectData(System.Runtime.Serialization.S...
GetType          Method     type GetType(), type _Exception.GetType()
ToString         Method     string ToString(), string _Exception.ToString()
Data             Property   System.Collections.IDictionary Data {get;}
HelpLink         Property   string HelpLink {get;set;}
HResult          Property   int HResult {get;}
InnerException   Property   System.Exception InnerException {get;}
Message          Property   string Message {get;}
Response         Property   System.Net.WebResponse Response {get;}
Source           Property   string Source {get;set;}
StackTrace       Property   string StackTrace {get;}
Status           Property   System.Net.WebExceptionStatus Status {get;}
TargetSite       Property   System.Reflection.MethodBase TargetSite {get;}

which provides you with information like this:

PS C:\> $e.Exception.Response

IsMutuallyAuthenticated : False
Cookies                 : {}
Headers                 : {Keep-Alive, Connection, Content-Length, Content-T...}
SupportsHeaders         : True
ContentLength           : 198
ContentEncoding         :
ContentType             : text/html; charset=iso-8859-1
CharacterSet            : iso-8859-1
Server                  : Apache/2.4.10
LastModified            : 17.07.2016 14:39:29
StatusCode              : NotFound
StatusDescription       : Not Found
ProtocolVersion         : 1.1
ResponseUri             : http://www.example.com/
Method                  : POST
IsFromCache             : False

Since not all exceptions have the exact same set of properties you may want to use specific handlers for particular exceptions:

try {
  ...
} catch [System.ArgumentException] {
  # handle argument exceptions
} catch [System.Net.WebException] {
  # handle web exceptions
} catch {
  # handle all other exceptions
}

If you have operations that need to be done regardless of whether an error occured or not (cleanup tasks like closing a socket or a database connection) you can put them in a finally block after the exception handling:

try {
  ...
} catch {
  ...
} finally {
  # cleanup operations go here
}

Accessing a Dictionary.Keys Key through a numeric index

Why don't you just extend the dictionary class to add in a last key inserted property. Something like the following maybe?

public class ExtendedDictionary : Dictionary<string, int>
{
    private int lastKeyInserted = -1;

    public int LastKeyInserted
    {
        get { return lastKeyInserted; }
        set { lastKeyInserted = value; }
    }

    public void AddNew(string s, int i)
    {
        lastKeyInserted = i;

        base.Add(s, i);
    }
}

How to manipulate arrays. Find the average. Beginner Java

If we want to add numbers of an Array and find the average of them follow this easy way! .....

public class Array {

    public static void main(String[] args) {

        int[]array = {1,3,5,7,9,6,3};
        int i=0;
        int sum=0;
        double average=0;
        for( i=0;i<array.length;i++){
            System.out.println(array[i]);
            sum=sum+array[i];
        }
        System.out.println("sum is:"+sum);
        System.out.println("average is: "+(double)sum/vargu.length);



    }

}

How to move a marker in Google Maps API

Just try to create the marker and set the draggable property to true. The code will be something as follows:

Marker = new google.maps.Marker({
    position: latlon,
    map: map,            
    draggable: true,
    title: "Drag me!"
});

I hope this helps!

Is there a Sleep/Pause/Wait function in JavaScript?

You need to re-factor the code into pieces. This doesn't stop execution, it just puts a delay in between the parts.

function partA() {
  ...
  window.setTimeout(partB,1000);
}

function partB() {
   ...
}

javascript how to create a validation error message without using alert

JavaScript

<script language="javascript">
        var flag=0;
        function username()
        {
            user=loginform.username.value;
            if(user=="")
            {
                document.getElementById("error0").innerHTML="Enter UserID";
                flag=1;
            }
        }   
        function password()
        {
            pass=loginform.password.value;
            if(pass=="")
            {
                document.getElementById("error1").innerHTML="Enter password";   
                flag=1;
            }
        }

        function check(form)
        {
            flag=0;
            username();
            password();
            if(flag==1)
                return false;
            else
                return true;
        }

    </script>

HTML

<form name="loginform" action="Login" method="post" class="form-signin" onSubmit="return check(this)">



                    <div id="error0"></div>
                    <input type="text" id="inputEmail" name="username" placeholder="UserID" onBlur="username()">
               controls">
                    <div id="error1"></div>
                    <input type="password" id="inputPassword" name="password" placeholder="Password" onBlur="password()" onclick="make_blank()">

                    <button type="submit" class="btn">Sign in</button>
                </div>
            </div>
        </form>

bash: npm: command not found?

in redhat base OS (tested in centos 7)

yum install nodejs npm -y

in debian base OS

apt-get install -y npm    

Regex to match any character including new lines

You want to use "multiline".

$string =~ /(START)(.+?)(END)/m;

if (boolean condition) in Java

Assuming state is having a valid boolean value set in your actual code, then the following condition will succeed

if(state)

when state is boolean value is TRUE

If condition checks for the expression whether it is evaluated to TRUE/FALSE. If the expression is simple true then the condition will succeed.

How ViewBag in ASP.NET MVC works

public dynamic ViewBag
{
    get
    {
        if (_viewBag == null)
        {
            _viewBag = new DynamicViewData(() => ViewData);
        }

        return _viewBag;
    }
}

Regular Expressions- Match Anything

/.*/ works great if there are no line breaks. If it has to match line breaks, here are some solutions:

Solution Description
/.*/s /s (dot all flag) makes . (wildcard character) match anything, including line breaks. Throw in an * (asterisk), and it will match everything. Read more.
/[\s\S]*/ \s (whitespace metacharacter) will match any whitespace character (space; tab; line break; ...), and \S (opposite of \s) will match anything that is not a whitespace character. * (asterisk) will match all occurrences of the character set (Encapsulated by []). Read more.

How can I run code on a background thread on Android?

class Background implements Runnable {
    private CountDownLatch latch = new CountDownLatch(1);
    private  Handler handler;

    Background() {
        Thread thread = new Thread(this);
        thread.start();
        try {
            latch.await();
        } catch (InterruptedException e) {
           /// e.printStackTrace();
        }
    }

    @Override
    public void run() {
        Looper.prepare();
        handler = new Handler();
        latch.countDown();
        Looper.loop();
    }

    public Handler getHandler() {
        return handler;
    }
}

Running EXE with parameters

System.Diagnostics.Process.Start("PATH to exe", "Command Line Arguments");

Is there anyway to exclude artifacts inherited from a parent POM?

Repeat the parent's dependency in child pom.xml and insert the exclusion there:

<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-test</artifactId>
    <scope>test</scope>
    <exclusions>
        <exclusion>
            <groupId>com.vaadin.external.google</groupId>
            <artifactId>android-json</artifactId>
        </exclusion>
    </exclusions>
</dependency>

How to view changes made to files on a certain revision in Subversion

Call this in the project:

svn diff -r REVNO:HEAD --summarize

REVNO is the start revision number and HEAD is the end revision number. If HEAD is equal to the last revision number, it can skip it.

The command returns a list with all files that are changed/added/deleted in this revision period.

The command can be called with the URL revision parameter to check changes like this:

svn diff -r REVNO:HEAD --summarize SVN_URL

Why is a primary-foreign key relation required when we can join without it?

A primary key is not required. A foreign key is not required either. You can construct a query joining two tables on any column you wish as long as the datatypes either match or are converted to match. No relationship needs to explicitly exist.

To do this you use an outer join:

select tablea.code, tablea.name, tableb.location from tablea left outer join 
tableb on tablea.code = tableb.code

join with out relation

SQL join

Singular matrix issue with Numpy

As it was already mentioned in previous answers, your matrix cannot be inverted, because its determinant is 0. But if you still want to get inverse matrix, you can use np.linalg.pinv, which leverages SVD to approximate initial matrix.

Batch file include external file for variables

While trying to use the method with excutable configuration I noticed that it may work or may NOT work depending on where in the script is located the call:

call config.cmd

I know it doesn't make any sens, but for me it's a fact. When "call config.cmd" is located at the top of the script, it works, but if further in the script it doesn't.

By doesn't work, I mean the variable are not set un the calling script.

Very very strange !!!!

Add Expires headers

try this solution and it is working fine for me

## EXPIRES CACHING ##
<IfModule mod_expires.c>
ExpiresActive On
ExpiresByType image/jpg "access 1 year"
ExpiresByType image/jpeg "access 1 year"
ExpiresByType image/gif "access 1 year"
ExpiresByType image/png "access 1 year"
ExpiresByType text/css "access 1 month"
ExpiresByType text/html "access 1 month"
ExpiresByType application/pdf "access 1 month"
ExpiresByType text/x-javascript "access 1 month"
ExpiresByType text/css "access plus 1 year"
ExpiresByType application/x-shockwave-flash "access 1 month"
ExpiresByType image/x-icon "access 1 year"
ExpiresDefault "access 1 month"
</IfModule>

<IfModule mod_headers.c>
  <FilesMatch "\.(js|css|xml|gz)$">
    Header append Vary: Accept-Encoding
  </FilesMatch>
</IfModule>

<ifModule mod_gzip.c>
mod_gzip_on Yes
mod_gzip_dechunk Yes
mod_gzip_item_include file .(html?|txt|css|js|php|pl)$
mod_gzip_item_include handler ^cgi-script$
mod_gzip_item_include mime ^text/.*
mod_gzip_item_include mime ^application/x-javascript.*
mod_gzip_item_exclude mime ^image/.*
mod_gzip_item_exclude rspheader ^Content-Encoding:.*gzip.*
</ifModule>

<IfModule mod_deflate.c>
SetOutputFilter DEFLATE
AddOutputFilterByType DEFLATE text/html text/css text/plain text/xml text/x-js text/js 
</IfModule>

## EXPIRES CACHING ##

How to import keras from tf.keras in Tensorflow?

I had the same problem with Tensorflow 2.0.0 in PyCharm. PyCharm did not recognize tensorflow.keras; I updated my PyCharm and the problem was resolved!

How can git be installed on CENTOS 5.5?

For installing git

  1. install last epel-release

rpm -Uvh http://dl.fedoraproject.org/pub/epel/5/i386/epel-release-5-4.noarch.rpm

  1. Install git from repository

yum install git

Remove decimal values using SQL query

Your data type is DECIMAL with decimal places, say DECIMAL(10,2). The values in your database are 12, 15, 18, and 20.

12 is the same as 12.0 and 12.00 and 12.000 . It is up to the tool you are using to select the data with, how to display the numbers. Yours either defaults to two digits for decimals or it takes the places from your data definition.

If you only want integers in your column, then change its data type to INT. It makes no sense to use DECIMAL then.

If you want integers and decimals in that column then stay with the DECIMAL type. If you don't like the way you are shown the values, then format them in your application. It's up to that client program to decide for instance if to display point or comma for the decimal separator. (The database can be used from different locations.)

Also don't rely on any database or session settings like a decimal separator being a point and not a comma and then use REPLACE on it. That can work for one person and not for the other.

OCI runtime exec failed: exec failed: (...) executable file not found in $PATH": unknown

If @papigee does solution doesn't work, maybe you don't have the permissions.

I tried @papigee solution but does't work without sudo.

I did :

sudo docker exec -it <container id or name> /bin/sh

Android - Get value from HashMap

HashMap<String, String> meMap = new HashMap<String, String>();
meMap.put("Color1", "Red");
meMap.put("Color2", "Blue");
meMap.put("Color3", "Green");
meMap.put("Color4", "White");

Iterator myVeryOwnIterator = meMap.values().iterator();
while(myVeryOwnIterator.hasNext()) {
    Toast.makeText(getBaseContext(), myVeryOwnIterator.next(), Toast.LENGTH_SHORT).show();
}

What exactly is LLVM?

LLVM is a library that is used to construct, optimize and produce intermediate and/or binary machine code.

LLVM can be used as a compiler framework, where you provide the "front end" (parser and lexer) and the "back end" (code that converts LLVM's representation to actual machine code).

LLVM can also act as a JIT compiler - it has support for x86/x86_64 and PPC/PPC64 assembly generation with fast code optimizations aimed for compilation speed.

Unfortunately disabled since 2013, there was the ability to play with LLVM's machine code generated from C or C++ code at the demo page.

How to merge two sorted arrays into a sorted array?

To marge two sorted array in O(m+n) time complexity use below approach with one loop only. m and n is length of first array and second array.

public class MargeSortedArray {
    public static void main(String[] args) {
        int[] array = new int[]{1,3,4,7};
        int[] array2 = new int[]{2,5,6,8,12,45};
        int[] newarry = margeToSortedArray(array, array2);
        //newarray is marged array
    }

    // marge two sorted array with o(a+n) time complexity
    public static int[] margeToSortedArray(int[] array, int[] array2) {
        int newarrlen = array.length+array2.length;
        int[] newarr = new int[newarrlen];

        int pos1=0,pos2=0;
        int len1=array.length, len2=array2.length;

        for(int i =0;i<newarrlen;i++) {     
            if(pos1>=len1) {
                newarr[i]=array2[pos2];
                pos2++;
                continue;
            }
            if(pos2>=len2) {
                newarr[i]=array[pos1];
                pos1++;
                continue;
            }

            if(array[pos1]>array2[pos2]) {
                newarr[i]=array2[pos2];
                pos2++;
            } else {
                newarr[i]=array[pos1];
                pos1++;
            }   
        }

        return newarr;
    }

}

Moment.js with ReactJS (ES6)

Since you are using webpack you should be able to just import or require moment and then use it:

import moment from 'moment'

...
render() {
    return (
        <div>
            { 
            this.props.data.map((post,key) => 
                <div key={key} className="post-detail">
                    <h1>{post.title}</h1>
                    <p>{moment(post.date).format()}</p>
                    <p dangerouslySetInnerHTML={{__html: post.content}}></p>
                    <hr />
                </div>
            )}
        </div>
    );
}
...

SQL Server Management Studio, how to get execution time down to milliseconds

To get the execution time as a variable in your proc:

DECLARE @EndTime datetime
DECLARE @StartTime datetime 
SELECT @StartTime=GETDATE() 

-- Write Your Query


SELECT @EndTime=GETDATE()

--This will return execution time of your query
SELECT DATEDIFF(ms,@StartTime,@EndTime) AS [Duration in millisecs] 

AND see this

Measuring Query Performance : "Execution Plan Query Cost" vs "Time Taken"

Parse rfc3339 date strings in Python?

This has already been answered here: How do I translate a ISO 8601 datetime string into a Python datetime object?

d = datetime.datetime.strptime( "2012-10-09T19:00:55Z", "%Y-%m-%dT%H:%M:%SZ" )
d.weekday()

PowerShell: Comparing dates

Late but more complete answer in point of getting the most advanced date from $Output

## Q:\test\2011\02\SO_5097125.ps1
## simulate object input with a here string 
$Output = @"
"Date"
"Monday, April 08, 2013 12:00:00 AM"
"Friday, April 08, 2011 12:00:00 AM"
"@ -split '\r?\n' | ConvertFrom-Csv

## use Get-Date and calculated property in a pipeline
$Output | Select-Object @{n='Date';e={Get-Date $_.Date}} |
    Sort-Object Date | Select-Object -Last 1 -Expand Date

## use Get-Date in a ForEach-Object
$Output.Date | ForEach-Object{Get-Date $_} |
    Sort-Object | Select-Object -Last 1

## use [datetime]::ParseExact
## the following will only work if your locale is English for day, month day abbrev.
$Output.Date | ForEach-Object{
    [datetime]::ParseExact($_,'dddd, MMMM dd, yyyy hh:mm:ss tt',$Null)
} | Sort-Object | Select-Object -Last 1

## for non English locales
$Output.Date | ForEach-Object{
    [datetime]::ParseExact($_,'dddd, MMMM dd, yyyy hh:mm:ss tt',[cultureinfo]::InvariantCulture)
} | Sort-Object | Select-Object -Last 1

## in case the day month abbreviations are in other languages, here German
## simulate object input with a here string 
$Output = @"
"Date"
"Montag, April 08, 2013 00:00:00"
"Freidag, April 08, 2011 00:00:00"
"@ -split '\r?\n' | ConvertFrom-Csv
$CIDE = New-Object System.Globalization.CultureInfo("de-DE")
$Output.Date | ForEach-Object{
    [datetime]::ParseExact($_,'dddd, MMMM dd, yyyy HH:mm:ss',$CIDE)
} | Sort-Object | Select-Object -Last 1

SQL Bulk Insert with FIRSTROW parameter skips the following line

Maybe check that the header has the same line-ending as the actual data rows (as specified in ROWTERMINATOR)?

Update: from MSDN:

The FIRSTROW attribute is not intended to skip column headers. Skipping headers is not supported by the BULK INSERT statement. When skipping rows, the SQL Server Database Engine looks only at the field terminators, and does not validate the data in the fields of skipped rows.

Running a Python script from PHP

This is so trivial, but just wanted to help anyone who already followed along Alejandro's suggestion but encountered this error:

sh: blabla.py: command not found

If anyone encountered that error, then a little change needs to be made to the php file by Alejandro:

$command = escapeshellcmd('python blabla.py');

Pandas convert string to int

You need add parameter errors='coerce' to function to_numeric:

ID = pd.to_numeric(ID, errors='coerce')

If ID is column:

df.ID = pd.to_numeric(df.ID, errors='coerce')

but non numeric are converted to NaN, so all values are float.

For int need convert NaN to some value e.g. 0 and then cast to int:

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)

Sample:

df = pd.DataFrame({'ID':['4806105017087','4806105017087','CN414149']})
print (df)
              ID
0  4806105017087
1  4806105017087
2       CN414149

print (pd.to_numeric(df.ID, errors='coerce'))
0    4.806105e+12
1    4.806105e+12
2             NaN
Name: ID, dtype: float64

df.ID = pd.to_numeric(df.ID, errors='coerce').fillna(0).astype(np.int64)
print (df)
              ID
0  4806105017087
1  4806105017087
2              0

EDIT: If use pandas 0.25+ then is possible use integer_na:

df.ID = pd.to_numeric(df.ID, errors='coerce').astype('Int64')
print (df)
              ID
0  4806105017087
1  4806105017087
2            NaN

How do you access a website running on localhost from iPhone browser

you can try ngrok.io. Works on same principle as localtunnel.
Download the application for your os. and try to run like:

for linux:

./ngrok http 8000

8000 is port number your application is running on.

for windows:

 ngrok.exe http 8000

jquery data selector

I've created a new data selector that should enable you to do nested querying and AND conditions. Usage:

$('a:data(category==music,artist.name==Madonna)');

The pattern is:

:data( {namespace} [{operator} {check}]  )

"operator" and "check" are optional. So, if you only have :data(a.b.c) it will simply check for the truthiness of a.b.c.

You can see the available operators in the code below. Amongst them is ~= which allows regex testing:

$('a:data(category~=^mus..$,artist.name~=^M.+a$)');

I've tested it with a few variations and it seems to work quite well. I'll probably add this as a Github repo soon (with a full test suite), so keep a look out!

The code:

(function(){

    var matcher = /\s*(?:((?:(?:\\\.|[^.,])+\.?)+)\s*([!~><=]=|[><])\s*("|')?((?:\\\3|.)*?)\3|(.+?))\s*(?:,|$)/g;

    function resolve(element, data) {

        data = data.match(/(?:\\\.|[^.])+(?=\.|$)/g);

        var cur = jQuery.data(element)[data.shift()];

        while (cur && data[0]) {
            cur = cur[data.shift()];
        }

        return cur || undefined;

    }

    jQuery.expr[':'].data = function(el, i, match) {

        matcher.lastIndex = 0;

        var expr = match[3],
            m,
            check, val,
            allMatch = null,
            foundMatch = false;

        while (m = matcher.exec(expr)) {

            check = m[4];
            val = resolve(el, m[1] || m[5]);

            switch (m[2]) {
                case '==': foundMatch = val == check; break;
                case '!=': foundMatch = val != check; break;
                case '<=': foundMatch = val <= check; break;
                case '>=': foundMatch = val >= check; break;
                case '~=': foundMatch = RegExp(check).test(val); break;
                case '>': foundMatch = val > check; break;
                case '<': foundMatch = val < check; break;
                default: if (m[5]) foundMatch = !!val;
            }

            allMatch = allMatch === null ? foundMatch : allMatch && foundMatch;

        }

        return allMatch;

    };

}());

How to invoke a Linux shell command from Java

exec does not execute a command in your shell

try

Process p = Runtime.getRuntime().exec(new String[]{"csh","-c","cat /home/narek/pk.txt"});

instead.

EDIT:: I don't have csh on my system so I used bash instead. The following worked for me

Process p = Runtime.getRuntime().exec(new String[]{"bash","-c","ls /home/XXX"});

How to resolve 'unrecognized selector sent to instance'?

1) Is the synthesize within @implementation block?

2) Should you refer to self.classA = [[ClassA alloc] init]; and self.classA.downloadUrl = @"..." instead of plain classA?

3) In your myApp.m file you need to import ClassA.h, when it's missing it will default to a number, or pointer? (in C variables default to int if not found by compiler):

#import "ClassA.h".

How do I limit the number of returned items?

Like this, using .limit():

var q = models.Post.find({published: true}).sort('date', -1).limit(20);
q.execFind(function(err, posts) {
  // `posts` will be of length 20
});

How to calculate the CPU usage of a process by PID in Linux from C?

This is my solution...

/*
this program is looking for CPU,Memory,Procs also u can look glibtop header there was a lot of usefull function have fun..
systeminfo.c
*/
#include <stdio.h>
#include <glibtop.h>
#include <glibtop/cpu.h>
#include <glibtop/mem.h>
#include <glibtop/proclist.h>



int main(){

glibtop_init();

glibtop_cpu cpu;
glibtop_mem memory;
glibtop_proclist proclist;

glibtop_get_cpu (&cpu);
glibtop_get_mem(&memory);


printf("CPU TYPE INFORMATIONS \n\n"
"Cpu Total : %ld \n"
"Cpu User : %ld \n"
"Cpu Nice : %ld \n"
"Cpu Sys : %ld \n"
"Cpu Idle : %ld \n"
"Cpu Frequences : %ld \n",
(unsigned long)cpu.total,
(unsigned long)cpu.user,
(unsigned long)cpu.nice,
(unsigned long)cpu.sys,
(unsigned long)cpu.idle,
(unsigned long)cpu.frequency);

printf("\nMEMORY USING\n\n"
"Memory Total : %ld MB\n"
"Memory Used : %ld MB\n"
"Memory Free : %ld MB\n"
"Memory Buffered : %ld MB\n"
"Memory Cached : %ld MB\n"
"Memory user : %ld MB\n"
"Memory Locked : %ld MB\n",
(unsigned long)memory.total/(1024*1024),
(unsigned long)memory.used/(1024*1024),
(unsigned long)memory.free/(1024*1024),
(unsigned long)memory.shared/(1024*1024),
(unsigned long)memory.buffer/(1024*1024),
(unsigned long)memory.cached/(1024*1024),
(unsigned long)memory.user/(1024*1024),
(unsigned long)memory.locked/(1024*1024));

int which,arg;
glibtop_get_proclist(&proclist,which,arg);
printf("%ld\n%ld\n%ld\n",
(unsigned long)proclist.number,
(unsigned long)proclist.total,
(unsigned long)proclist.size);
return 0;
}

makefile is
CC=gcc
CFLAGS=-Wall -g
CLIBS=-lgtop-2.0 -lgtop_sysdeps-2.0 -lgtop_common-2.0

cpuinfo:cpu.c
$(CC) $(CFLAGS) systeminfo.c -o systeminfo $(CLIBS)
clean:
rm -f systeminfo

CSS Equivalent of the "if" statement

Your stylesheet should be thought of as a static table of available variables that your html document can call on based on what you need to display. The logic should be in your javascript and html, use javascript to dynamically apply attributes based on conditions if you really need to. Stylesheets are not the place for logic.

assign value using linq

It can be done this way as well

foreach (Company company in listofCompany.Where(d => d.Id = 1)).ToList())
                {
                    //do your stuff here
                    company.Id= 2;
                    company.Name= "Sample"
                }

Do something if screen width is less than 960 px

Try this code

if ($(window).width() < 960) {
 alert('width is less than 960px');
}
else {
 alert('More than 960');
}

_x000D_
_x000D_
   if ($(window).width() < 960) {_x000D_
     alert('width is less than 960px');_x000D_
    }_x000D_
    else {_x000D_
     alert('More than 960');_x000D_
    }
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Getting rid of bullet points from <ul>

I had the same problem, and the way I ended up fixing it was like this:

ul, li{
    list-style:none;
    list-style-type:none;
}

Maybe it's a little extreme, but when I did that, it worked for me.


Hope this helped

IOPub data rate exceeded in Jupyter notebook (when viewing image)

By typing 'jupyter notebook --NotebookApp.iopub_data_rate_limit=1.0e10' in Anaconda PowerShell or prompt, the Jupyter notebook will open with the new configuration. Try now to run your query.

Youtube API Limitations

A little bit late, but you can request a higher quote here: https://support.google.com/youtube/contact/yt_api_form

How can I add an item to a SelectList in ASP.net MVC

Okay I like clean code so I made this an extension method

static public class SelectListHelper
{
    static public SelectList Add(this SelectList list, string text, string value = "", ListPosition listPosition = ListPosition.First)
    {
        if (string.IsNullOrEmpty(value))
        {
            value = text;
        }
        var listItems = list.ToList();
        var lp = (int)listPosition;
        switch (lp)
        {
            case -1:
                lp = list.Count();
                break;
            case -2:
                lp = list.Count() / 2;
                break;
            case -3:
                var random = new Random();
                lp = random.Next(0, list.Count());
                break;
        }
        listItems.Insert(lp, new SelectListItem { Value = value, Text = text });
        list = new SelectList(listItems, "Value", "Text");
        return list;
    }

    public enum ListPosition
    {
        First = 0,
        Last = -1,
        Middle = -2,
        Random = -3
    }
}

Usage (by example):

var model = new VmRoutePicker
    {
     Routes =
     new SelectList(_dataSource.Routes.Select(r => r.RouteID).Distinct())
     };                                     
  model.Routes = model.Routes.Add("All", "All", SelectListHelper.ListPosition.Random);
//or
  model.Routes = model.Routes.Add("All");

Should I use the Reply-To header when sending emails as a service to others?

Here is worked for me:

Subject: SomeSubject
From:Company B (me)
Reply-to:Company A
To:Company A's customers

How do I use floating-point division in bash?

As an alternative to bc, you can use awk within your script.

For example:

echo "$IMG_WIDTH $IMG2_WIDTH" | awk '{printf "%.2f \n", $1/$2}'

In the above, " %.2f " tells the printf function to return a floating point number with two digits after the decimal place. I used echo to pipe in the variables as fields since awk operates properly on them. " $1 " and " $2 " refer to the first and second fields input into awk.

And you can store the result as some other variable using:

RESULT = `echo ...`

Custom toast on Android: a simple example

Custom layout for toast, custom_toast.xml:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="match_parent"
    android:layout_height="match_parent">
    <TextView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="Custom Toast"
        android:gravity="center"
        android:id="@+id/custom_toast_text"
        android:typeface="serif"
        android:textStyle="bold"
        />
</LinearLayout>

And the Java method (just pass toast message to this method):

public void toast(String message)
{
    Toast toast = new Toast(context);
    View view = LayoutInflater.from(context).inflate(R.layout.image_custom, null);
    TextView textView = (TextView) view.findViewById(R.id.custom_toast_text);
    textView.setText(message);
    toast.setView(view);
    toast.setGravity(Gravity.BOTTOM|Gravity.CENTER, 0, 0);
    toast.setDuration(Toast.LENGTH_LONG);
    toast.show();
}

How to get form input array into PHP array

Nonetheless, you can use below code as,

$a = array('name1','name2','name3');
$b = array('email1','email2','email3');

function f($a,$b){
    return "The name is $a and email is $b, thank you";
}

$c = array_map('f', $a, $b);

//echoing the result

foreach ($c as $val) {
    echo $val.'<br>';
}

Difference between Eclipse Europa, Helios, Galileo

In Galileo and Helios Provisioning Platform were introduced, and non-update-site plugins now should be placed in "dropins" subfolder ("eclipse/dropins/plugin_name/features", "eclipse/dropins/plugin_name/plugins") instead of Eclipse's folder ("eclipse/features" and "eclipse/plugins").

Also for programming needs the best Eclipse is the latest Eclipse. It has too many bugs for now, and all the Eclipse team is now doing is fixing the bugs. There are very few interface enhancements since Europa. IMHO.

javascript compare strings without being case sensitive

You can also use string.match().

var string1 = "aBc";
var match = string1.match(/AbC/i);

if(match) {
}

Importing csv file into R - numeric values read as characters

version for data.table based on code from dmanuge :

convNumValues<-function(ds){
  ds<-data.table(ds)
  dsnum<-data.table(data.matrix(ds))
  num_cols <- sapply(dsnum,function(x){mean(as.numeric(is.na(x)))<0.5})
  nds <- data.table(  dsnum[, .SD, .SDcols=attributes(num_cols)$names[which(num_cols)]]
                        ,ds[, .SD, .SDcols=attributes(num_cols)$names[which(!num_cols)]] )
return(nds)
}

How can I check if a scrollbar is visible?

There's two area sizes to consider, the window and the html. If the html width, for example, is greater than window width then a scroll bar may be present on the user interface. So it's a matter of reading the window proportions and the html proportions and doing the basic math.

As for displaying an arrow overlaid atop the page, that's done with a simple classlist toggle, e.g. .hidden{display:none}

Here's a crossbrowser method for getting these proportions. (credit W3 Schools)

|| document.body.clientWidth;

var h = window.innerHeight || document.documentElement.clientHeight ||
document.body.clientHeight; ```

Best way to update data with a RecyclerView adapter

Found following solution working for my similar problem:

private ExtendedHashMap mData = new ExtendedHashMap();
private  String[] mKeys;

public void setNewData(ExtendedHashMap data) {
    mData.putAll(data);
    mKeys = data.keySet().toArray(new String[data.size()]);
    notifyDataSetChanged();
}

Using the clear-command

mData.clear()

is not nessescary

Change SVN repository URL

If you are using TortoiseSVN client then you can follow the below steps

Right-click in the source directory and then click on SVN Relocate Image#1

After that, you need to change the URL to what you want, click ok, it will be taking a few seconds.Image#2

PHP Curl And Cookies

Solutions which are described above, even with unique CookieFile names, can cause a lot of problems on scale.

We had to serve a lot of authentications with this solution and our server went down because of high file read write actions.

The solution for this was to use Apache Reverse Proxy and omit CURL requests at all.

Details how to use Proxy on Apache can be found here: https://httpd.apache.org/docs/2.4/howto/reverse_proxy.html

Pass a datetime from javascript to c# (Controller)

I found that I needed to wrap my datetime string like this:

"startdate": "\/Date(" + date() + ")\/"

Took me an hour to figure out how to enable the WCF service to give me back the error message which told me that XD

displaying a string on the textview when clicking a button in android

Try this

public void onClick(View view){
    txtView.setText("hello");

    //printmyname();
    Toast.makeText(NameonbuttonclickActivity.this, "hello", Toast.LENGTH_LONG).show();
}

Also in toast use "Hello"

Is there any native DLL export functions viewer?

DLL Export Viewer by NirSoft can be used to display exported functions in a DLL.

This utility displays the list of all exported functions and their virtual memory addresses for the specified DLL files. You can easily copy the memory address of the desired function, paste it into your debugger, and set a breakpoint for this memory address. When this function is called, the debugger will stop in the beginning of this function.

enter image description here

linking jquery in html

<script
 src="CDN">
</script>

for change the CDN check this website.

the first one is JQuery

how to check if string contains '+' character

Why not just:

int plusIndex = s.indexOf("+");
if (plusIndex != -1) {
    String before = s.substring(0, plusIndex);
    // Use before
}

It's not really clear why your original version didn't work, but then you didn't say what actually happened. If you want to split not using regular expressions, I'd personally use Guava:

Iterable<String> bits = Splitter.on('+').split(s);
String firstPart = Iterables.getFirst(bits, "");

If you're going to use split (either the built-in version or Guava) you don't need to check whether it contains + first - if it doesn't there'll only be one result anyway. Obviously there's a question of efficiency, but it's simpler code:

// Calling split unconditionally
String[] parts = s.split("\\+");
s = parts[0];

Note that writing String[] parts is preferred over String parts[] - it's much more idiomatic Java code.

How to draw rounded rectangle in Android UI?

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@android:color/white" />
    <corners android:radius="4dp" />
</shape>

Disable HttpClient logging

We use XML, rather than a properties file, to configure our logging output. The following code worked to silence this chatter.

<logger name="org.apache.commons.httpclient">
    <level value="fatal"/>
</logger>

<logger name="httpclient.wire.header">
    <level value="fatal"/>
</logger>

<logger name="httpclient.wire.content">
    <level value="fatal"/>
</logger>

Loaded nib but the 'view' outlet was not set

My problem was in wrong classes. I used custom .xib for my custom view. Correctly it has to be set like here:

  1. View shouldn't have a class
  2. Class which is used with the .xib is set in File's Owner tab
  3. Outlets are connected to File's Owner and not to the View.

    pic

jQuery ajax error function

You can use something like this:
note: responseText returns server response and statusText returns the predefined
message for status error.for e.g:
responseText returns something like "Not Found (#404)" in some frameworks like Yii2 but
statusText returns "Not Found".

$.ajax({
    cache: false,
    url: "addInterview_Code.asp",
    type: "POST",
    datatype: "text",
    data: strData,
    success: function (html) {
        alert('successful : ' + html);
        $("#result").html("Successful");
    },
    error: function (data) {
        console.log(data.status + ':' + data.statusText,data.responseText);
    }
});

Check if instance is of a type

A little more compact than the other answers if you want to use c as a TForm:

if(c is TForm form){
    form.DoStuff();
}

Injection of autowired dependencies failed; nested exception is org.springframework.beans.factory.BeanCreationException:

You need to provide a candidate for autowire. That means that an instance of PasswordHint must be known to spring in a way that it can guess that it must reference it.

Please provide the class head of PasswordHint and/or the spring bean definition of that class for further assistance.

Try changing the name of

PasswordHintAction action;

to

PasswordHintAction passwordHintAction;

so that it matches the bean definition.

Responsive web design is working on desktop but not on mobile device

Though it is answered above and it is right to use

<meta name="viewport" content="width=device-width, initial-scale=1">

but if you are using React and webpack then don't forget to close the element tag

<meta name="viewport" content="width=device-width, initial-scale=1" />

How to format current time using a yyyyMMddHHmmss format?

Use

fmt.Println(t.Format("20060102150405"))

as Go uses following constants to format date,refer here

const (
    stdLongMonth      = "January"
    stdMonth          = "Jan"
    stdNumMonth       = "1"
    stdZeroMonth      = "01"
    stdLongWeekDay    = "Monday"
    stdWeekDay        = "Mon"
    stdDay            = "2"
    stdUnderDay       = "_2"
    stdZeroDay        = "02"
    stdHour           = "15"
    stdHour12         = "3"
    stdZeroHour12     = "03"
    stdMinute         = "4"
    stdZeroMinute     = "04"
    stdSecond         = "5"
    stdZeroSecond     = "05"
    stdLongYear       = "2006"
    stdYear           = "06"
    stdPM             = "PM"
    stdpm             = "pm"
    stdTZ             = "MST"
    stdISO8601TZ      = "Z0700"  // prints Z for UTC
    stdISO8601ColonTZ = "Z07:00" // prints Z for UTC
    stdNumTZ          = "-0700"  // always numeric
    stdNumShortTZ     = "-07"    // always numeric
    stdNumColonTZ     = "-07:00" // always numeric
)

What is the C++ function to raise a number to a power?

You should be able to use normal C methods in math.

#include <cmath>

pow(2,3)

if you're on a unix-like system, man cmath

Is that what you're asking?

Sujal

How to pass ArrayList of Objects from one to another activity using Intent in android?

Your intent creation seems correct if your Question implements Parcelable.

In the next activity you can retrieve your list of questions like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if(getIntent() != null && getIntent().hasExtra("QuestionsExtra")) {
        List<Question> mQuestionsList = getIntent().getParcelableArrayListExtra("QuestionsExtra");
    }
}

How to play a sound in C#, .NET

To play an Audio file in the Windows form using C# let's check simple example as follows :

1.Go Visual Studio(VS-2008/2010/2012) --> File Menu --> click New Project.

2.In the New Project --> click Windows Forms Application --> Give Name and then click OK.

A new "Windows Forms" project will opens.

3.Drag-and-Drop a Button control from the Toolbox to the Windows Form.

4.Double-click the button to create automatically the default Click event handler, and add the following code.

This code displays the File Open dialog box and passes the results to a method named "playSound" that you will create in the next step.

 OpenFileDialog dialog = new OpenFileDialog();
 dialog.Filter = "Audio Files (.wav)|*.wav";


if(dialog.ShowDialog() == DialogResult.OK)
{
  string path = dialog.FileName;
  playSound(path);
}

5.Add the following method code under the button1_Click event hander.

 private void playSound(string path)
 {
   System.Media.SoundPlayer player = new System.Media.SoundPlayer();
   player.SoundLocation = path;
   player.Load();
   player.Play();
 }

6.Now let's run the application just by Pressing the F5 to run the code.

7.Click the button and select an audio file. After the file loads, the sound will play.

I hope this is useful example to beginners...

How to format date and time in Android?

This will do it:

Date date = new Date();
java.text.DateFormat dateFormat = android.text.format.DateFormat.getDateFormat(getApplicationContext());
mTimeText.setText("Time: " + dateFormat.format(date));

How to SFTP with PHP?

Install Flysystem:

composer require league/flysystem-sftp

Then:

use League\Flysystem\Filesystem;
use League\Flysystem\Sftp\SftpAdapter;

$filesystem = new Filesystem(new SftpAdapter([
    'host' => 'example.com',
    'port' => 22,
    'username' => 'username',
    'password' => 'password',
    'privateKey' => 'path/to/or/contents/of/privatekey',
    'root' => '/path/to/root',
    'timeout' => 10,
]));
$filesystem->listFiles($path); // get file lists
$filesystem->read($path_to_file); // grab file
$filesystem->put($path); // upload file
....

Read:

https://flysystem.thephpleague.com/v1/docs/

check if command was successful in a batch file

This likely doesn't work with start, as that starts a new window, but to answer your question:

If the command returns a error level you can check the following ways

By Specific Error Level

commandhere
if %errorlevel%==131 echo do something

By If Any Error

commandhere || echo what to do if error level ISN'T 0

By If No Error

commandhere && echo what to do if error level IS 0

If it does not return a error level but does give output, you can catch it in a variable and determine by the output, example (note the tokens and delims are just examples and would likely fail with any special characters)

By Parsing Full Output

for /f "tokens=* delims=" %%a in ('somecommand') do set output=%%a
if %output%==whateveritwouldsayinerror echo error

Or you could just look for a single phrase in the output like the word Error

By Checking For String

commandhere | find "Error" || echo There was no error!
commandhere | find "Error" && echo There was an error!

And you could even mix together (just remember to escape | with ^| if in a for statement)

Hope this helps.

How to declare a global variable in React?

Beyond React

You might not be aware that an import is global already. If you export an object (singleton) it is then globally accessible as an import statement and it can also be modified globally.

If you want to initialize something globally but ensure its only modified once, you can use this singleton approach that initially has modifiable properties but then you can use Object.freeze after its first use to ensure its immutable in your init scenario.

const myInitObject = {}
export default myInitObject

then in your init method referencing it:

import myInitObject from './myInitObject'
myInitObject.someProp = 'i am about to get cold'
Object.freeze(myInitObject)

The myInitObject will still be global as it can be referenced anywhere as an import but will remain frozen and throw if anyone attempts to modify it.

My example hack of using global state using a singleton

https://codesandbox.io/s/react-typescript-playground-forked-h8rpu

If using react-create-app

(what I was looking for actually) In this scenario you can also initialize global objects cleanly when referencing environment variables.

Creating a .env file at the root of your project with prefixed REACT_APP_ variables inside does quite nicely. You can reference within your JS and JSX process.env.REACT_APP_SOME_VAR as you need AND it's immutable by design.

This avoids having to set window.myVar = %REACT_APP_MY_VAR% in HTML.

See more useful details about this from Facebook directly:

https://facebook.github.io/create-react-app/docs/adding-custom-environment-variables

How to do one-liner if else statement?

Thanks for pointing toward the correct answer.

I have just checked the Golang FAQ (duh) and it clearly states, this is not available in the language:

Does Go have the ?: operator?

There is no ternary form in Go. You may use the following to achieve the same result:

if expr {
    n = trueVal
} else {
    n = falseVal
}

additional info found that might be of interest on the subject:

JQuery - Call the jquery button click event based on name property

$('element[name="element_name"]').click(function(){
    //do stuff
});

in your case:

$('input[name="btnName"]').click(function(){
    //do stuff
});

How can I disable editing cells in a WPF Datagrid?

I see users in comments wondering how to disable cell editing while allowing row deletion : I managed to do this by setting all columns individually to read only, instead of the DataGrid itself.

<DataGrid IsReadOnly="False">
    <DataGrid.Columns>
        <DataGridTextColumn IsReadOnly="True"/>
        <DataGridTextColumn IsReadOnly="True"/>
    </DataGrid.Columns>
</DataGrid>

How to resolve "Could not find schema information for the element/attribute <xxx>"?

Have you tried copying the schema file to the XML Schema Caching folder for VS? You can find the location of that folder by looking at VS Tools/Options/Test Editor/XML/Miscellaneous. Unfortunately, i don't know where's the schema file for the MS Enterprise Library 4.0.

Update: After installing MS Enterprise Library, it seems there's no .xsd file. However, there's a tool for editing the configuration - EntLibConfig.exe, which you can use to edit the configuration files. Also, if you add the proper config sections to your config file, VS should be able to parse the config file properly. (EntLibConfig will add these for you, or you can add them yourself). Here's an example for the loggingConfiguration section:

<configSections>
    <section name="loggingConfiguration" type="Microsoft.Practices.EnterpriseLibrary.Logging.Configuration.LoggingSettings, Microsoft.Practices.EnterpriseLibrary.Logging, Version=4.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35" />
</configSections>

You also need to add a reference to the appropriate assembly in your project.

What is the difference between Normalize.css and Reset CSS?

Normalize.css :Every browser is coming with some default css styles that will, for example, add padding around a paragraph or title.If you add the normalize style sheet all those browser default rules will be reset so for this instance 0px padding on tags.Here is a couple of links for more details: https://necolas.github.io/normalize.css/ http://nicolasgallagher.com/about-normalize-css/

Algorithm for solving Sudoku

I wrote a simple program that solved the easy ones. It took its input from a file which was just a matrix with spaces and numbers. The datastructure to solve it was just a 9 by 9 matrix of a bit mask. The bit mask would specify which numbers were still possible on a certain position. Filling in the numbers from the file would reduce the numbers in all rows/columns next to each known location. When that is done you keep iterating over the matrix and reducing possible numbers. If each location has only one option left you're done. But there are some sudokus that need more work. For these ones you can just use brute force: try all remaining possible combinations until you find one that works.

Bootstrap modal: is not a function

Changing import statement worked. From

import * as $ from 'jquery';

to:

declare var $ : any;

How to dynamically create columns in datatable and assign values to it?

If you want to create dynamically/runtime data table in VB.Net then you should follow these steps as mentioned below :

  • Create Data table object.
  • Add columns into that data table object.
  • Add Rows with values into the object.

For eg.

Dim dt As New DataTable

dt.Columns.Add("Id", GetType(Integer))
dt.Columns.Add("FirstName", GetType(String))
dt.Columns.Add("LastName", GetType(String))

dt.Rows.Add(1, "Test", "data")
dt.Rows.Add(15, "Robert", "Wich")
dt.Rows.Add(18, "Merry", "Cylon")
dt.Rows.Add(30, "Tim", "Burst")

How to use both onclick and target="_blank"

Just use window.open():

window.open('Prosjektplan.pdf')

Anyway, what guys are saying on comments is true. You better use <a target="_blank"> instead of click events.

Search an Oracle database for tables with specific column names?

Here is one that we have saved off to findcol.sql so we can run it easily from within SQLPlus

set verify off
clear break
accept colnam prompt 'Enter Column Name (or part of): '
set wrap off
select distinct table_name, 
                column_name, 
                data_type || ' (' || 
                decode(data_type,'LONG',null,'LONG RAW',null,
                       'BLOB',null,'CLOB',null,'NUMBER',
                       decode(data_precision,null,to_char(data_length),
                              data_precision||','||data_scale
                             ), data_length
                      ) || ')' data_type
  from all_tab_columns
 where column_name like ('%' || upper('&colnam') || '%');
set verify on

'if' statement in jinja2 template

We need to remember that the {% endif %} comes after the {% else %}.

So this is an example:

{% if someTest %}
     <p> Something is True </p>
{% else %}
     <p> Something is False </p>
{% endif %}

jQuery get html of container including the container itself

$.fn.outerHtml = function(){
    if (this.length) {
        var div = $('<div style="display:none"></div>');
        var clone =
        $(this[0].cloneNode(false)).html(this.html()).appendTo(div);
        var outer = div.html();
        div.remove();
        return outer;
    }
    else {
        return null;
    }
};

from http://forum.jquery.com/topic/jquery-getting-html-and-the-container-element-12-1-2010

Format price in the current locale and currency

By this code for formating price in product list

echo Mage::helper('core')->currency($_product->getPrice());

How do I do logging in C# without using 3rd party libraries?

You can write directly to an event log. Check the following links:
http://support.microsoft.com/kb/307024
http://msdn.microsoft.com/en-us/library/system.diagnostics.eventlog.aspx

And here's the sample from MSDN:

using System;
using System.Diagnostics;
using System.Threading;

class MySample{

    public static void Main(){

        // Create the source, if it does not already exist.
        if(!EventLog.SourceExists("MySource"))
        {
             //An event log source should not be created and immediately used.
             //There is a latency time to enable the source, it should be created
             //prior to executing the application that uses the source.
             //Execute this sample a second time to use the new source.
            EventLog.CreateEventSource("MySource", "MyNewLog");
            Console.WriteLine("CreatedEventSource");
            Console.WriteLine("Exiting, execute the application a second time to use the source.");
            // The source is created.  Exit the application to allow it to be registered.
            return;
        }

        // Create an EventLog instance and assign its source.
        EventLog myLog = new EventLog();
        myLog.Source = "MySource";

        // Write an informational entry to the event log.    
        myLog.WriteEntry("Writing to event log.");

    }
}

Correct way to push into state array

Using Functional Components and React Hooks

const [array,setArray] = useState([]);

Push value at the end:

setArray(oldArray => [...oldArray,newValue] );

Push value at the begging:

setArray(oldArray => [newValue,...oldArrays] );

Effects of the extern keyword on C functions

You need to distinguish between two separate concepts: function definition and symbol declaration. "extern" is a linkage modifier, a hint to the compiler about where the symbol referred to afterwards is defined (the hint is, "not here").

If I write

extern int i;

in file scope (outside a function block) in a C file, then you're saying "the variable may be defined elsewhere".

extern int f() {return 0;}

is both a declaration of the function f and a definition of the function f. The definition in this case over-rides the extern.

extern int f();
int f() {return 0;}

is first a declaration, followed by the definition.

Use of extern is wrong if you want to declare and simultaneously define a file scope variable. For example,

extern int i = 4;

will give an error or warning, depending on the compiler.

Usage of extern is useful if you explicitly want to avoid definition of a variable.

Let me explain:

Let's say the file a.c contains:

#include "a.h"

int i = 2;

int f() { i++; return i;}

The file a.h includes:

extern int i;
int f(void);

and the file b.c contains:

#include <stdio.h>
#include "a.h"

int main(void){
    printf("%d\n", f());
    return 0;
}

The extern in the header is useful, because it tells the compiler during the link phase, "this is a declaration, and not a definition". If I remove the line in a.c which defines i, allocates space for it and assigns a value to it, the program should fail to compile with an undefined reference. This tells the developer that he has referred to a variable, but hasn't yet defined it. If on the other hand, I omit the "extern" keyword, and remove the int i = 2 line, the program still compiles - i will be defined with a default value of 0.

File scope variables are implicitly defined with a default value of 0 or NULL if you do not explicitly assign a value to them - unlike block-scope variables that you declare at the top of a function. The extern keyword avoids this implicit definition, and thus helps avoid mistakes.

For functions, in function declarations, the keyword is indeed redundant. Function declarations do not have an implicit definition.

Setting the default page for ASP.NET (Visual Studio) server configuration

One way to achieve this is to add a DefaultDocument settings in the Web.config.

  <system.webServer>
   <defaultDocument>
    <files>
      <clear />
      <add value="DefaultPage.aspx" />
    </files>
   </defaultDocument>
  </system.webServer>

Adding padding to a tkinter widget only on one side

The padding options padx and pady of the grid and pack methods can take a 2-tuple that represent the left/right and top/bottom padding.

Here's an example:

import tkinter as tk

class MyApp():
    def __init__(self):
        self.root = tk.Tk()
        l1 = tk.Label(self.root, text="Hello")
        l2 = tk.Label(self.root, text="World")
        l1.grid(row=0, column=0, padx=(100, 10))
        l2.grid(row=1, column=0, padx=(10, 100)) 

app = MyApp()
app.root.mainloop()

Remove columns from dataframe where ALL values are NA

Another options with purrr package:

library(dplyr)

df <- data.frame(a = NA,
                 b = seq(1:5), 
                 c = c(rep(1, 4), NA))

df %>% purrr::discard(~all(is.na(.)))
df %>% purrr::keep(~!all(is.na(.)))

SSH Key - Still asking for password and passphrase

TL;DR
You need to use an ssh agent. So, open terminal & before pushing to git, execute

ssh-add

enter your passphrase when prompted.

Check out the original StackExchange answer here

Converting time stamps in excel to dates

This worked for me:

=(col_name]/60/60/24)+(col_name-1)

simple way to display data in a .txt file on a webpage?

How are you converting the submitted names to "a simple .txt list"? During that step, can you instead convert them into a simple HTML list or table? Then you could wrap that in a standard header which includes any styling you want.

How to clone object in C++ ? Or Is there another solution?

If your object is not polymorphic (and a stack implementation likely isn't), then as per other answers here, what you want is the copy constructor. Please note that there are differences between copy construction and assignment in C++; if you want both behaviors (and the default versions don't fit your needs), you'll have to implement both functions.

If your object is polymorphic, then slicing can be an issue and you might need to jump through some extra hoops to do proper copying. Sometimes people use as virtual method called clone() as a helper for polymorphic copying.

Finally, note that getting copying and assignment right, if you need to replace the default versions, is actually quite difficult. It is usually better to set up your objects (via RAII) in such a way that the default versions of copy/assign do what you want them to do. I highly recommend you look at Meyer's Effective C++, especially at items 10,11,12.

Is there an easy way to return a string repeated X number of times?

You can repeat your string (in case it's not a single char) and concat the result, like this:

String.Concat(Enumerable.Repeat("---", 5))

Negative matching using grep (match lines that do not contain foo)

grep -v is your friend:

grep --help | grep invert  

-v, --invert-match select non-matching lines

Also check out the related -L (the complement of -l).

-L, --files-without-match only print FILE names containing no match

Proxies with Python 'Requests' module

8 years late. But I like:

import os
import requests

os.environ['HTTP_PROXY'] = os.environ['http_proxy'] = 'http://http-connect-proxy:3128/'
os.environ['HTTPS_PROXY'] = os.environ['https_proxy'] = 'http://http-connect-proxy:3128/'
os.environ['NO_PROXY'] = os.environ['no_proxy'] = '127.0.0.1,localhost,.local'

r = requests.get('https://example.com')  # , verify=False

os.walk without digging into directories below

import os

def listFiles(self, dir_name):
    names = []
    for root, directory, files in os.walk(dir_name):
        if root == dir_name:
            for name in files:
                names.append(name)
    return names

What is an Intent in Android?

An Intent is an "intention" to perform an action; in other words,

a messaging object you can use to request an action from another app component

An Intent is basically a message to say you did or want something to happen. Depending on the intent, apps or the OS might be listening for it and will react accordingly. Think of it as a blast email to a bunch of friends, in which you tell your friend John to do something, or to friends who can do X ("intent filters"), to do X. The other folks will ignore the email, but John (or friends who can do X) will react to it.

To listen for an broadcast intent (like the phone ringing, or an SMS is received), you implement a broadcast receiver, which will be passed the intent. To declare that you can handle another's app intent like "take picture", you declare an intent filter in your app's manifest file.

If you want to fire off an intent to do something, like pop up the dialer, you fire off an intent saying you will.

jquery animate .css

You could opt for a pure CSS solution:

#hfont1 {
    transition: color 1s ease-in-out;
    -moz-transition: color 1s ease-in-out; /* FF 4 */
    -webkit-transition: color 1s ease-in-out; /* Safari & Chrome */
    -o-transition: color 1s ease-in-out; /* Opera */
}

SQL Server - Create a copy of a database table and place it in the same database?

You need to write SSIS to copy the table and its data, constraints and triggers. We have in our organization a software called Kal Admin by kalrom Systems that has a free version for downloading (I think that the copy tables feature is optional)

Driver executable must be set by the webdriver.ie.driver system property

For spring :

File inputFile = new ClassPathResource("\\chrome\\chromedriver.exe").getFile();
System.setProperty("webdriver.chrome.driver",inputFile.getCanonicalPath());

Difference between EXISTS and IN in SQL?

In certain circumstances, it is better to use IN rather than EXISTS. In general, if the selective predicate is in the subquery, then use IN. If the selective predicate is in the parent query, then use EXISTS.

https://docs.oracle.com/cd/B19306_01/server.102/b14211/sql_1016.htm#i28403

Eloquent: find() and where() usage laravel

To add to craig_h's comment above (I currently don't have enough rep to add this as a comment to his answer, sorry), if your primary key is not an integer, you'll also want to tell your model what data type it is, by setting keyType at the top of the model definition.

public $keyType = 'string'

Eloquent understands any of the types defined in the castAttribute() function, which as of Laravel 5.4 are: int, float, string, bool, object, array, collection, date and timestamp.

This will ensure that your primary key is correctly cast into the equivalent PHP data type.

C# Threading - How to start and stop a thread

Thread th = new Thread(function1);
th.Start();
th.Abort();

void function1(){
//code here
}

Java - How to create new Entry (key, value)

I defined a generic Pair class that I use all the time. It's great. As a bonus, by defining a static factory method (Pair.create) I only have to write the type arguments half as often.

public class Pair<A, B> {

    private A component1;
    private B component2;

    public Pair() {
            super();
    }

    public Pair(A component1, B component2) {
            this.component1 = component1;
            this.component2 = component2;
    }

    public A fst() {
            return component1;
    }

    public void setComponent1(A component1) {
            this.component1 = component1;
    }

    public B snd() {
            return component2;
    }

    public void setComponent2(B component2) {
            this.component2 = component2;
    }

    @Override
    public String toString() {
            return "<" + component1 + "," + component2 + ">";
    }

    @Override
    public int hashCode() {
            final int prime = 31;
            int result = 1;
            result = prime * result
                            + ((component1 == null) ? 0 : component1.hashCode());
            result = prime * result
                            + ((component2 == null) ? 0 : component2.hashCode());
            return result;
    }

    @Override
    public boolean equals(Object obj) {
            if (this == obj)
                    return true;
            if (obj == null)
                    return false;
            if (getClass() != obj.getClass())
                    return false;
            final Pair<?, ?> other = (Pair<?, ?>) obj;
            if (component1 == null) {
                    if (other.component1 != null)
                            return false;
            } else if (!component1.equals(other.component1))
                    return false;
            if (component2 == null) {
                    if (other.component2 != null)
                            return false;
            } else if (!component2.equals(other.component2))
                    return false;
            return true;
    }

    public static <A, B> Pair<A, B> create(A component1, B component2) {
            return new Pair<A, B>(component1, component2);
    }

}

Getting coordinates of marker in Google Maps API

One more alternative options

var map = new google.maps.Map(document.getElementById('map_canvas'), {
    zoom: 1,
    center: new google.maps.LatLng(35.137879, -82.836914),
    mapTypeId: google.maps.MapTypeId.ROADMAP
});

var myMarker = new google.maps.Marker({
    position: new google.maps.LatLng(47.651968, 9.478485),
    draggable: true
});

google.maps.event.addListener(myMarker, 'dragend', function (evt) {
    document.getElementById('current').innerHTML = '<p>Marker dropped: Current Lat: ' + evt.latLng.lat().toFixed(3) + ' Current Lng: ' + evt.latLng.lng().toFixed(3) + '</p>';
});

google.maps.event.addListener(myMarker, 'dragstart', function (evt) {
    document.getElementById('current').innerHTML = '<p>Currently dragging marker...</p>';
});

map.setCenter(myMarker.position);
myMarker.setMap(map);

and html file

<body>
    <section>
        <div id='map_canvas'></div>
        <div id="current">Nothing yet...</div>
    </section>
</body>

Can't Find Theme.AppCompat.Light for New Android ActionBar Support

Follow the steps of @rcdmk. Delete the android support v4.jar in YOUR project. It conflicts with the new updated version found in appcompat.

Ignore Typescript Errors "property does not exist on value of type"

The quick and dirty solution is to explicitly cast to any

(y as any).x

The "advantage" is that, the cast being explicit, this will compile even with the noImplicitAny flag set.

The proper solution is to update the typings definition file.

Please note that, when you cast a variable to any, you opt out of type checking for that variable.


Since I am in disclaimer mode, double casting via any combined with a new interface, can be useful in situations where you

  • do not want to update a broken typings file
  • are monkey patching

yet, you still want some form of typing.

Say you want to patch the definition of an instance of y of type OrginalDef with a new property x of type number:

const y: OriginalDef = ...

interface DefWithNewProperties extends OriginalDef {
    x: number
}

const patched = y as any as DefWithNewProperties

patched.x = ....   //will compile

font awesome icon in select option

Full Sample and newer version:https://codepen.io/Nagibaba/pen/bagEgx enter image description here

_x000D_
_x000D_
select {_x000D_
  font-family: 'FontAwesome', 'sans-serif';_x000D_
}
_x000D_
<link href="https://maxcdn.bootstrapcdn.com/font-awesome/4.6.1/css/font-awesome.min.css" rel="stylesheet" />_x000D_
<div>_x000D_
  <select>_x000D_
    <option value="fa-align-left">&#xf036; fa-align-left</option>_x000D_
    <option value="fa-align-right">&#xf038; fa-align-right</option>_x000D_
    <option value="fa-amazon">&#xf270; fa-amazon</option>_x000D_
    <option value="fa-ambulance">&#xf0f9; fa-ambulance</option>_x000D_
    <option value="fa-anchor">&#xf13d; fa-anchor</option>_x000D_
    <option value="fa-android">&#xf17b; fa-android</option>_x000D_
    <option value="fa-angellist">&#xf209; fa-angellist</option>_x000D_
    <option value="fa-angle-double-down">&#xf103; fa-angle-double-down</option>_x000D_
    <option value="fa-angle-double-left">&#xf100; fa-angle-double-left</option>_x000D_
    <option value="fa-angle-double-right">&#xf101; fa-angle-double-right</option>_x000D_
    <option value="fa-angle-double-up">&#xf102; fa-angle-double-up</option>_x000D_
_x000D_
    <option value="fa-angle-left">&#xf104; fa-angle-left</option>_x000D_
    <option value="fa-angle-right">&#xf105; fa-angle-right</option>_x000D_
    <option value="fa-angle-up">&#xf106; fa-angle-up</option>_x000D_
    <option value="fa-apple">&#xf179; fa-apple</option>_x000D_
    <option value="fa-archive">&#xf187; fa-archive</option>_x000D_
    <option value="fa-area-chart">&#xf1fe; fa-area-chart</option>_x000D_
    <option value="fa-arrow-circle-down">&#xf0ab; fa-arrow-circle-down</option>_x000D_
    <option value="fa-arrow-circle-left">&#xf0a8; fa-arrow-circle-left</option>_x000D_
    <option value="fa-arrow-circle-o-down">&#xf01a; fa-arrow-circle-o-down</option>_x000D_
    <option value="fa-arrow-circle-o-left">&#xf190; fa-arrow-circle-o-left</option>_x000D_
    <option value="fa-arrow-circle-o-right">&#xf18e; fa-arrow-circle-o-right</option>_x000D_
    <option value="fa-arrow-circle-o-up">&#xf01b; fa-arrow-circle-o-up</option>_x000D_
    <option value="fa-arrow-circle-right">&#xf0a9; fa-arrow-circle-right</option>_x000D_
    <option value="fa-arrow-circle-up">&#xf0aa; fa-arrow-circle-up</option>_x000D_
    <option value="fa-arrow-down">&#xf063; fa-arrow-down</option>_x000D_
    <option value="fa-arrow-left">&#xf060; fa-arrow-left</option>_x000D_
    <option value="fa-arrow-right">&#xf061; fa-arrow-right</option>_x000D_
    <option value="fa-arrow-up">&#xf062; fa-arrow-up</option>_x000D_
    <option value="fa-arrows">&#xf047; fa-arrows</option>_x000D_
    <option value="fa-arrows-alt">&#xf0b2; fa-arrows-alt</option>_x000D_
    <option value="fa-arrows-h">&#xf07e; fa-arrows-h</option>_x000D_
    <option value="fa-arrows-v">&#xf07d; fa-arrows-v</option>_x000D_
    <option value="fa-asterisk">&#xf069; fa-asterisk</option>_x000D_
    <option value="fa-at">&#xf1fa; fa-at</option>_x000D_
    <option value="fa-automobile">&#xf1b9; fa-automobile</option>_x000D_
    <option value="fa-backward">&#xf04a; fa-backward</option>_x000D_
    <option value="fa-balance-scale">&#xf24e; fa-balance-scale</option>_x000D_
    <option value="fa-ban">&#xf05e; fa-ban</option>_x000D_
    <option value="fa-bank">&#xf19c; fa-bank</option>_x000D_
    <option value="fa-bar-chart">&#xf080; fa-bar-chart</option>_x000D_
    <option value="fa-bar-chart-o">&#xf080; fa-bar-chart-o</option>_x000D_
_x000D_
    <option value="fa-battery-full">&#xf240; fa-battery-full</option>_x000D_
    n value="fa-beer">&#xf0fc; fa-beer</option>_x000D_
    <option value="fa-behance">&#xf1b4; fa-behance</option>_x000D_
    <option value="fa-behance-square">&#xf1b5; fa-behance-square</option>_x000D_
    <option value="fa-bell">&#xf0f3; fa-bell</option>_x000D_
    <option value="fa-bell-o">&#xf0a2; fa-bell-o</option>_x000D_
    <option value="fa-bell-slash">&#xf1f6; fa-bell-slash</option>_x000D_
    <option value="fa-bell-slash-o">&#xf1f7; fa-bell-slash-o</option>_x000D_
    <option value="fa-bicycle">&#xf206; fa-bicycle</option>_x000D_
    <option value="fa-binoculars">&#xf1e5; fa-binoculars</option>_x000D_
    <option value="fa-birthday-cake">&#xf1fd; fa-birthday-cake</option>_x000D_
    <option value="fa-bitbucket">&#xf171; fa-bitbucket</option>_x000D_
    <option value="fa-bitbucket-square">&#xf172; fa-bitbucket-square</option>_x000D_
    <option value="fa-bitcoin">&#xf15a; fa-bitcoin</option>_x000D_
    <option value="fa-black-tie">&#xf27e; fa-black-tie</option>_x000D_
    <option value="fa-bold">&#xf032; fa-bold</option>_x000D_
    <option value="fa-bolt">&#xf0e7; fa-bolt</option>_x000D_
    <option value="fa-bomb">&#xf1e2; fa-bomb</option>_x000D_
    <option value="fa-book">&#xf02d; fa-book</option>_x000D_
    <option value="fa-bookmark">&#xf02e; fa-bookmark</option>_x000D_
    <option value="fa-bookmark-o">&#xf097; fa-bookmark-o</option>_x000D_
    <option value="fa-briefcase">&#xf0b1; fa-briefcase</option>_x000D_
    <option value="fa-btc">&#xf15a; fa-btc</option>_x000D_
    <option value="fa-bug">&#xf188; fa-bug</option>_x000D_
    <option value="fa-building">&#xf1ad; fa-building</option>_x000D_
    <option value="fa-building-o">&#xf0f7; fa-building-o</option>_x000D_
    <option value="fa-bullhorn">&#xf0a1; fa-bullhorn</option>_x000D_
    <option value="fa-bullseye">&#xf140; fa-bullseye</option>_x000D_
    <option value="fa-bus">&#xf207; fa-bus</option>_x000D_
    <option value="fa-cab">&#xf1ba; fa-cab</option>_x000D_
    <option value="fa-calendar">&#xf073; fa-calendar</option>_x000D_
    <option value="fa-camera">&#xf030; fa-camera</option>_x000D_
    <option value="fa-car">&#xf1b9; fa-car</option>_x000D_
    <option value="fa-caret-up">&#xf0d8; fa-caret-up</option>_x000D_
    <option value="fa-cart-plus">&#xf217; fa-cart-plus</option>_x000D_
    <option value="fa-cc">&#xf20a; fa-cc</option>_x000D_
    <option value="fa-cc-amex">&#xf1f3; fa-cc-amex</option>_x000D_
    <option value="fa-cc-jcb">&#xf24b; fa-cc-jcb</option>_x000D_
    <option value="fa-cc-paypal">&#xf1f4; fa-cc-paypal</option>_x000D_
    <option value="fa-cc-stripe">&#xf1f5; fa-cc-stripe</option>_x000D_
    <option value="fa-cc-visa">&#xf1f0; fa-cc-visa</option>_x000D_
    <option value="fa-chain">&#xf0c1; fa-chain</option>_x000D_
    <option value="fa-check">&#xf00c; fa-check</option>_x000D_
    <option value="fa-chevron-left">&#xf053; fa-chevron-left</option>_x000D_
    <option value="fa-chevron-right">&#xf054; fa-chevron-right</option>_x000D_
    <option value="fa-chevron-up">&#xf077; fa-chevron-up</option>_x000D_
    <option value="fa-child">&#xf1ae; fa-child</option>_x000D_
    <option value="fa-chrome">&#xf268; fa-chrome</option>_x000D_
    <option value="fa-circle">&#xf111; fa-circle</option>_x000D_
    <option value="fa-circle-o">&#xf10c; fa-circle-o</option>_x000D_
    <option value="fa-circle-o-notch">&#xf1ce; fa-circle-o-notch</option>_x000D_
    <option value="fa-circle-thin">&#xf1db; fa-circle-thin</option>_x000D_
    <option value="fa-clipboard">&#xf0ea; fa-clipboard</option>_x000D_
    <option value="fa-clock-o">&#xf017; fa-clock-o</option>_x000D_
    <option value="fa-clone">&#xf24d; fa-clone</option>_x000D_
    <option value="fa-close">&#xf00d; fa-close</option>_x000D_
    <option value="fa-cloud">&#xf0c2; fa-cloud</option>_x000D_
    <option value="fa-cloud-download">&#xf0ed; fa-cloud-download</option>_x000D_
    <option value="fa-cloud-upload">&#xf0ee; fa-cloud-upload</option>_x000D_
    <option value="fa-cny">&#xf157; fa-cny</option>_x000D_
    <option value="fa-code">&#xf121; fa-code</option>_x000D_
    <option value="fa-code-fork">&#xf126; fa-code-fork</option>_x000D_
    <option value="fa-codepen">&#xf1cb; fa-codepen</option>_x000D_
    <option value="fa-coffee">&#xf0f4; fa-coffee</option>_x000D_
    <option value="fa-cog">&#xf013; fa-cog</option>_x000D_
    <option value="fa-cogs">&#xf085; fa-cogs</option>_x000D_
    <option value="fa-columns">&#xf0db; fa-columns</option>_x000D_
    <option value="fa-comment">&#xf075; fa-comment</option>_x000D_
    <option value="fa-comment-o">&#xf0e5; fa-comment-o</option>_x000D_
    <option value="fa-commenting">&#xf27a; fa-commenting</option>_x000D_
    <option value="fa-commenting-o">&#xf27b; fa-commenting-o</option>_x000D_
    <option value="fa-comments">&#xf086; fa-comments</option>_x000D_
    <option value="fa-comments-o">&#xf0e6; fa-comments-o</option>_x000D_
    <option value="fa-compass">&#xf14e; fa-compass</option>_x000D_
    <option value="fa-compress">&#xf066; fa-compress</option>_x000D_
    <option value="fa-connectdevelop">&#xf20e; fa-connectdevelop</option>_x000D_
    <option value="fa-contao">&#xf26d; fa-contao</option>_x000D_
    <option value="fa-copy">&#xf0c5; fa-copy</option>_x000D_
    <option value="fa-copyright">&#xf1f9; fa-copyright</option>_x000D_
    <option value="fa-creative-commons">&#xf25e; fa-creative-commons</option>_x000D_
    <option value="fa-credit-card">&#xf09d; fa-credit-card</option>_x000D_
    <option value="fa-crop">&#xf125; fa-crop</option>_x000D_
    <option value="fa-crosshairs">&#xf05b; fa-crosshairs</option>_x000D_
    <option value="fa-css3">&#xf13c; fa-css3</option>_x000D_
    <option value="fa-cube">&#xf1b2; fa-cube</option>_x000D_
    <option value="fa-cubes">&#xf1b3; fa-cubes</option>_x000D_
    <option value="fa-cut">&#xf0c4; fa-cut</option>_x000D_
    <option value="fa-cutlery">&#xf0f5; fa-cutlery</option>_x000D_
    <option value="fa-dashboard">&#xf0e4; fa-dashboard</option>_x000D_
    <option value="fa-dashcube">&#xf210; fa-dashcube</option>_x000D_
    <option value="fa-database">&#xf1c0; fa-database</option>_x000D_
    <option value="fa-dedent">&#xf03b; fa-dedent</option>_x000D_
    <option value="fa-delicious">&#xf1a5; fa-delicious</option>_x000D_
    <option value="fa-desktop">&#xf108; fa-desktop</option>_x000D_
    <option value="fa-deviantart">&#xf1bd; fa-deviantart</option>_x000D_
    <option value="fa-diamond">&#xf219; fa-diamond</option>_x000D_
    <option value="fa-digg">&#xf1a6; fa-digg</option>_x000D_
    <option value="fa-dollar">&#xf155; fa-dollar</option>_x000D_
    <option value="fa-download">&#xf019; fa-download</option>_x000D_
    <option value="fa-dribbble">&#xf17d; fa-dribbble</option>_x000D_
    <option value="fa-dropbox">&#xf16b; fa-dropbox</option>_x000D_
    <option value="fa-drupal">&#xf1a9; fa-drupal</option>_x000D_
    <option value="fa-edit">&#xf044; fa-edit</option>_x000D_
    <option value="fa-eject">&#xf052; fa-eject</option>_x000D_
    <option value="fa-ellipsis-h">&#xf141; fa-ellipsis-h</option>_x000D_
    <option value="fa-ellipsis-v">&#xf142; fa-ellipsis-v</option>_x000D_
    <option value="fa-empire">&#xf1d1; fa-empire</option>_x000D_
    <option value="fa-envelope">&#xf0e0; fa-envelope</option>_x000D_
    <option value="fa-envelope-o">&#xf003; fa-envelope-o</option>_x000D_
    <option value="fa-eur">&#xf153; fa-eur</option>_x000D_
    <option value="fa-euro">&#xf153; fa-euro</option>_x000D_
    <option value="fa-exchange">&#xf0ec; fa-exchange</option>_x000D_
    <option value="fa-exclamation">&#xf12a; fa-exclamation</option>_x000D_
    <option value="fa-exclamation-circle">&#xf06a; fa-exclamation-circle</option>_x000D_
    <option value="fa-exclamation-triangle">&#xf071; fa-exclamation-triangle</option>_x000D_
    <option value="fa-expand">&#xf065; fa-expand</option>_x000D_
    <option value="fa-expeditedssl">&#xf23e; fa-expeditedssl</option>_x000D_
    <option value="fa-external-link">&#xf08e; fa-external-link</option>_x000D_
    <option value="fa-external-link-square">&#xf14c; fa-external-link-square</option>_x000D_
    <option value="fa-eye">&#xf06e; fa-eye</option>_x000D_
    <option value="fa-eye-slash">&#xf070; fa-eye-slash</option>_x000D_
    <option value="fa-eyedropper">&#xf1fb; fa-eyedropper</option>_x000D_
    <option value="fa-facebook">&#xf09a; fa-facebook</option>_x000D_
    <option value="fa-facebook-f">&#xf09a; fa-facebook-f</option>_x000D_
    <option value="fa-facebook-official">&#xf230; fa-facebook-official</option>_x000D_
    <option value="fa-facebook-square">&#xf082; fa-facebook-square</option>_x000D_
    <option value="fa-fast-backward">&#xf049; fa-fast-backward</option>_x000D_
    <option value="fa-fast-forward">&#xf050; fa-fast-forward</option>_x000D_
    <option value="fa-fax">&#xf1ac; fa-fax</option>_x000D_
    <option value="fa-feed">&#xf09e; fa-feed</option>_x000D_
    <option value="fa-female">&#xf182; fa-female</option>_x000D_
    <option value="fa-fighter-jet">&#xf0fb; fa-fighter-jet</option>_x000D_
    <option value="fa-file">&#xf15b; fa-file</option>_x000D_
    <option value="fa-file-archive-o">&#xf1c6; fa-file-archive-o</option>_x000D_
    <option value="fa-file-audio-o">&#xf1c7; fa-file-audio-o</option>_x000D_
    <option value="fa-file-code-o">&#xf1c9; fa-file-code-o</option>_x000D_
    <option value="fa-file-excel-o">&#xf1c3; fa-file-excel-o</option>_x000D_
    <option value="fa-file-image-o">&#xf1c5; fa-file-image-o</option>_x000D_
    <option value="fa-file-movie-o">&#xf1c8; fa-file-movie-o</option>_x000D_
    <option value="fa-file-o">&#xf016; fa-file-o</option>_x000D_
    <option value="fa-file-pdf-o">&#xf1c1; fa-file-pdf-o</option>_x000D_
    <option value="fa-file-photo-o">&#xf1c5; fa-file-photo-o</option>_x000D_
    <option value="fa-file-picture-o">&#xf1c5; fa-file-picture-o</option>_x000D_
    <option value="fa-file-powerpoint-o">&#xf1c4; fa-file-powerpoint-o</option>_x000D_
    <option value="fa-file-sound-o">&#xf1c7; fa-file-sound-o</option>_x000D_
    <option value="fa-file-text">&#xf15c; fa-file-text</option>_x000D_
    <option value="fa-file-text-o">&#xf0f6; fa-file-text-o</option>_x000D_
    <option value="fa-file-video-o">&#xf1c8; fa-file-video-o</option>_x000D_
    <option value="fa-file-word-o">&#xf1c2; fa-file-word-o</option>_x000D_
    <option value="fa-file-zip-o">&#xf1c6; fa-file-zip-o</option>_x000D_
    <option value="fa-files-o">&#xf0c5; fa-files-o</option>_x000D_
    <option value="fa-film">&#xf008; fa-film</option>_x000D_
    <option value="fa-filter">&#xf0b0; fa-filter</option>_x000D_
    <option value="fa-fire">&#xf06d; fa-fire</option>_x000D_
    <option value="fa-fire-extinguisher">&#xf134; fa-fire-extinguisher</option>_x000D_
    <option value="fa-firefox">&#xf269; fa-firefox</option>_x000D_
    <option value="fa-flag">&#xf024; fa-flag</option>_x000D_
    <option value="fa-flag-checkered">&#xf11e; fa-flag-checkered</option>_x000D_
    <option value="fa-flag-o">&#xf11d; fa-flag-o</option>_x000D_
    <option value="fa-flash">&#xf0e7; fa-flash</option>_x000D_
    <option value="fa-flask">&#xf0c3; fa-flask</option>_x000D_
    <option value="fa-flickr">&#xf16e; fa-flickr</option>_x000D_
    <option value="fa-floppy-o">&#xf0c7; fa-floppy-o</option>_x000D_
    <option value="fa-folder">&#xf07b; fa-folder</option>_x000D_
    <option value="fa-folder-o">&#xf114; fa-folder-o</option>_x000D_
    <option value="fa-folder-open">&#xf07c; fa-folder-open</option>_x000D_
    <option value="fa-folder-open-o">&#xf115; fa-folder-open-o</option>_x000D_
    <option value="fa-font">&#xf031; fa-font</option>_x000D_
    <option value="fa-fonticons">&#xf280; fa-fonticons</option>_x000D_
    <option value="fa-forumbee">&#xf211; fa-forumbee</option>_x000D_
    <option value="fa-forward">&#xf04e; fa-forward</option>_x000D_
    <option value="fa-foursquare">&#xf180; fa-foursquare</option>_x000D_
    <option value="fa-frown-o">&#xf119; fa-frown-o</option>_x000D_
    <option value="fa-futbol-o">&#xf1e3; fa-futbol-o</option>_x000D_
    <option value="fa-gamepad">&#xf11b; fa-gamepad</option>_x000D_
    <option value="fa-gavel">&#xf0e3; fa-gavel</option>_x000D_
    <option value="fa-gbp">&#xf154; fa-gbp</option>_x000D_
    <option value="fa-ge">&#xf1d1; fa-ge</option>_x000D_
    <option value="fa-gear">&#xf013; fa-gear</option>_x000D_
    <option value="fa-gears">&#xf085; fa-gears</option>_x000D_
    <option value="fa-genderless">&#xf22d; fa-genderless</option>_x000D_
    <option value="fa-get-pocket">&#xf265; fa-get-pocket</option>_x000D_
    <option value="fa-gg">&#xf260; fa-gg</option>_x000D_
    <option value="fa-gg-circle">&#xf261; fa-gg-circle</option>_x000D_
    <option value="fa-gift">&#xf06b; fa-gift</option>_x000D_
    <option value="fa-git">&#xf1d3; fa-git</option>_x000D_
    <option value="fa-git-square">&#xf1d2; fa-git-square</option>_x000D_
    <option value="fa-github">&#xf09b; fa-github</option>_x000D_
    <option value="fa-github-alt">&#xf113; fa-github-alt</option>_x000D_
    <option value="fa-github-square">&#xf092; fa-github-square</option>_x000D_
    <option value="fa-gittip">&#xf184; fa-gittip</option>_x000D_
    <option value="fa-glass">&#xf000; fa-glass</option>_x000D_
    <option value="fa-globe">&#xf0ac; fa-globe</option>_x000D_
    <option value="fa-google">&#xf1a0; fa-google</option>_x000D_
    <option value="fa-google-plus">&#xf0d5; fa-google-plus</option>_x000D_
    <option value="fa-google-plus-square">&#xf0d4; fa-google-plus-square</option>_x000D_
    <option value="fa-google-wallet">&#xf1ee; fa-google-wallet</option>_x000D_
    <option value="fa-graduation-cap">&#xf19d; fa-graduation-cap</option>_x000D_
    <option value="fa-gratipay">&#xf184; fa-gratipay</option>_x000D_
    <option value="fa-group">&#xf0c0; fa-group</option>_x000D_
    <option value="fa-h-square">&#xf0fd; fa-h-square</option>_x000D_
    <option value="fa-hacker-news">&#xf1d4; fa-hacker-news</option>_x000D_
    <option value="fa-hand-grab-o">&#xf255; fa-hand-grab-o</option>_x000D_
    <option value="fa-hand-lizard-o">&#xf258; fa-hand-lizard-o</option>_x000D_
    <option value="fa-hand-o-down">&#xf0a7; fa-hand-o-down</option>_x000D_
    <option value="fa-hand-o-left">&#xf0a5; fa-hand-o-left</option>_x000D_
    <option value="fa-hand-o-right">&#xf0a4; fa-hand-o-right</option>_x000D_
    <option value="fa-hand-o-up">&#xf0a6; fa-hand-o-up</option>_x000D_
    <option value="fa-hand-paper-o">&#xf256; fa-hand-paper-o</option>_x000D_
    <option value="fa-hand-peace-o">&#xf25b; fa-hand-peace-o</option>_x000D_
    <option value="fa-hand-pointer-o">&#xf25a; fa-hand-pointer-o</option>_x000D_
    <option value="fa-hand-rock-o">&#xf255; fa-hand-rock-o</option>_x000D_
    <option value="fa-hand-scissors-o">&#xf257; fa-hand-scissors-o</option>_x000D_
    <option value="fa-hand-spock-o">&#xf259; fa-hand-spock-o</option>_x000D_
    <option value="fa-hand-stop-o">&#xf256; fa-hand-stop-o</option>_x000D_
    <option value="fa-hdd-o">&#xf0a0; fa-hdd-o</option>_x000D_
    <option value="fa-header">&#xf1dc; fa-header</option>_x000D_
    <option value="fa-headphones">&#xf025; fa-headphones</option>_x000D_
    <option value="fa-heart">&#xf004; fa-heart</option>_x000D_
    <option value="fa-heart-o">&#xf08a; fa-heart-o</option>_x000D_
    <option value="fa-heartbeat">&#xf21e; fa-heartbeat</option>_x000D_
    <option value="fa-history">&#xf1da; fa-history</option>_x000D_
    <option value="fa-home">&#xf015; fa-home</option>_x000D_
    <option value="fa-hospital-o">&#xf0f8; fa-hospital-o</option>_x000D_
    <option value="fa-hotel">&#xf236; fa-hotel</option>_x000D_
    <option value="fa-hourglass">&#xf254; fa-hourglass</option>_x000D_
    <option value="fa-hourglass-1">&#xf251; fa-hourglass-1</option>_x000D_
    <option value="fa-hourglass-2">&#xf252; fa-hourglass-2</option>_x000D_
    <option value="fa-hourglass-3">&#xf253; fa-hourglass-3</option>_x000D_
    <option value="fa-hourglass-end">&#xf253; fa-hourglass-end</option>_x000D_
    <option value="fa-hourglass-half">&#xf252; fa-hourglass-half</option>_x000D_
    <option value="fa-hourglass-o">&#xf250; fa-hourglass-o</option>_x000D_
    <option value="fa-hourglass-start">&#xf251; fa-hourglass-start</option>_x000D_
    <option value="fa-houzz">&#xf27c; fa-houzz</option>_x000D_
    <option value="fa-html5">&#xf13b; fa-html5</option>_x000D_
    <option value="fa-i-cursor">&#xf246; fa-i-cursor</option>_x000D_
    <option value="fa-ils">&#xf20b; fa-ils</option>_x000D_
    <option value="fa-image">&#xf03e; fa-image</option>_x000D_
    <option value="fa-inbox">&#xf01c; fa-inbox</option>_x000D_
    <option value="fa-indent">&#xf03c; fa-indent</option>_x000D_
    <option value="fa-industry">&#xf275; fa-industry</option>_x000D_
    <option value="fa-info">&#xf129; fa-info</option>_x000D_
    <option value="fa-info-circle">&#xf05a; fa-info-circle</option>_x000D_
    <option value="fa-inr">&#xf156; fa-inr</option>_x000D_
    <option value="fa-instagram">&#xf16d; fa-instagram</option>_x000D_
    <option value="fa-institution">&#xf19c; fa-institution</option>_x000D_
    <option value="fa-internet-explorer">&#xf26b; fa-internet-explorer</option>_x000D_
    <option value="fa-intersex">&#xf224; fa-intersex</option>_x000D_
    <option value="fa-ioxhost">&#xf208; fa-ioxhost</option>_x000D_
    <option value="fa-italic">&#xf033; fa-italic</option>_x000D_
    <option value="fa-joomla">&#xf1aa; fa-joomla</option>_x000D_
    <option value="fa-jpy">&#xf157; fa-jpy</option>_x000D_
    <option value="fa-jsfiddle">&#xf1cc; fa-jsfiddle</option>_x000D_
    <option value="fa-key">&#xf084; fa-key</option>_x000D_
    <option value="fa-keyboard-o">&#xf11c; fa-keyboard-o</option>_x000D_
    <option value="fa-krw">&#xf159; fa-krw</option>_x000D_
    <option value="fa-language">&#xf1ab; fa-language</option>_x000D_
    <option value="fa-laptop">&#xf109; fa-laptop</option>_x000D_
    <option value="fa-lastfm">&#xf202; fa-lastfm</option>_x000D_
    <option value="fa-lastfm-square">&#xf203; fa-lastfm-square</option>_x000D_
    <option value="fa-leaf">&#xf06c; fa-leaf</option>_x000D_
    <option value="fa-leanpub">&#xf212; fa-leanpub</option>_x000D_
    <option value="fa-legal">&#xf0e3; fa-legal</option>_x000D_
    <option value="fa-lemon-o">&#xf094; fa-lemon-o</option>_x000D_
    <option value="fa-level-down">&#xf149; fa-level-down</option>_x000D_
    <option value="fa-level-up">&#xf148; fa-level-up</option>_x000D_
    <option value="fa-life-bouy">&#xf1cd; fa-life-bouy</option>_x000D_
    <option value="fa-life-buoy">&#xf1cd; fa-life-buoy</option>_x000D_
    <option value="fa-life-ring">&#xf1cd; fa-life-ring</option>_x000D_
    <option value="fa-life-saver">&#xf1cd; fa-life-saver</option>_x000D_
    <option value="fa-lightbulb-o">&#xf0eb; fa-lightbulb-o</option>_x000D_
    <option value="fa-line-chart">&#xf201; fa-line-chart</option>_x000D_
    <option value="fa-link">&#xf0c1; fa-link</option>_x000D_
    <option value="fa-linkedin">&#xf0e1; fa-linkedin</option>_x000D_
    <option value="fa-linkedin-square">&#xf08c; fa-linkedin-square</option>_x000D_
    <option value="fa-linux">&#xf17c; fa-linux</option>_x000D_
    <option value="fa-list">&#xf03a; fa-list</option>_x000D_
    <option value="fa-list-alt">&#xf022; fa-list-alt</option>_x000D_
    <option value="fa-list-ol">&#xf0cb; fa-list-ol</option>_x000D_
    <option value="fa-list-ul">&#xf0ca; fa-list-ul</option>_x000D_
    <option value="fa-location-arrow">&#xf124; fa-location-arrow</option>_x000D_
    <option value="fa-lock">&#xf023; fa-lock</option>_x000D_
    <option value="fa-long-arrow-down">&#xf175; fa-long-arrow-down</option>_x000D_
    <option value="fa-long-arrow-left">&#xf177; fa-long-arrow-left</option>_x000D_
    <option value="fa-long-arrow-right">&#xf178; fa-long-arrow-right</option>_x000D_
    <option value="fa-long-arrow-up">&#xf176; fa-long-arrow-up</option>_x000D_
    <option value="fa-magic">&#xf0d0; fa-magic</option>_x000D_
    <option value="fa-magnet">&#xf076; fa-magnet</option>_x000D_
_x000D_
    <option value="fa-mars-stroke-v">&#xf22a; fa-mars-stroke-v</option>_x000D_
    <option value="fa-maxcdn">&#xf136; fa-maxcdn</option>_x000D_
    <option value="fa-meanpath">&#xf20c; fa-meanpath</option>_x000D_
    <option value="fa-medium">&#xf23a; fa-medium</option>_x000D_
    <option value="fa-medkit">&#xf0fa; fa-medkit</option>_x000D_
    <option value="fa-meh-o">&#xf11a; fa-meh-o</option>_x000D_
    <option value="fa-mercury">&#xf223; fa-mercury</option>_x000D_
    <option value="fa-microphone">&#xf130; fa-microphone</option>_x000D_
    <option value="fa-mobile">&#xf10b; fa-mobile</option>_x000D_
    <option value="fa-motorcycle">&#xf21c; fa-motorcycle</option>_x000D_
    <option value="fa-mouse-pointer">&#xf245; fa-mouse-pointer</option>_x000D_
    <option value="fa-music">&#xf001; fa-music</option>_x000D_
    <option value="fa-navicon">&#xf0c9; fa-navicon</option>_x000D_
    <option value="fa-neuter">&#xf22c; fa-neuter</option>_x000D_
    <option value="fa-newspaper-o">&#xf1ea; fa-newspaper-o</option>_x000D_
    <option value="fa-opencart">&#xf23d; fa-opencart</option>_x000D_
    <option value="fa-openid">&#xf19b; fa-openid</option>_x000D_
    <option value="fa-opera">&#xf26a; fa-opera</option>_x000D_
    <option value="fa-outdent">&#xf03b; fa-outdent</option>_x000D_
    <option value="fa-pagelines">&#xf18c; fa-pagelines</option>_x000D_
    <option value="fa-paper-plane-o">&#xf1d9; fa-paper-plane-o</option>_x000D_
    <option value="fa-paperclip">&#xf0c6; fa-paperclip</option>_x000D_
    <option value="fa-paragraph">&#xf1dd; fa-paragraph</option>_x000D_
    <option value="fa-paste">&#xf0ea; fa-paste</option>_x000D_
    <option value="fa-pause">&#xf04c; fa-pause</option>_x000D_
    <option value="fa-paw">&#xf1b0; fa-paw</option>_x000D_
    <option value="fa-paypal">&#xf1ed; fa-paypal</option>_x000D_
    <option value="fa-pencil">&#xf040; fa-pencil</option>_x000D_
    <option value="fa-pencil-square-o">&#xf044; fa-pencil-square-o</option>_x000D_
    <option value="fa-phone">&#xf095; fa-phone</option>_x000D_
    <option value="fa-photo">&#xf03e; fa-photo</option>_x000D_
    <option value="fa-picture-o">&#xf03e; fa-picture-o</option>_x000D_
    <option value="fa-pie-chart">&#xf200; fa-pie-chart</option>_x000D_
    <option value="fa-pied-piper">&#xf1a7; fa-pied-piper</option>_x000D_
    <option value="fa-pied-piper-alt">&#xf1a8; fa-pied-piper-alt</option>_x000D_
    <option value="fa-pinterest">&#xf0d2; fa-pinterest</option>_x000D_
    <option value="fa-pinterest-p">&#xf231; fa-pinterest-p</option>_x000D_
    <option value="fa-pinterest-square">&#xf0d3; fa-pinterest-square</option>_x000D_
    <option value="fa-plane">&#xf072; fa-plane</option>_x000D_
    <option value="fa-play">&#xf04b; fa-play</option>_x000D_
    <option value="fa-play-c
                  

What is the proper way to re-throw an exception in C#?

It depends. In a debug build, I want to see the original stack trace with as little effort as possible. In that case, "throw;" fits the bill. In a release build, however, (a) I want to log the error with the original stack trace included, and once that's done, (b) refashion the error handling to make more sense to the user. Here "Throw Exception" makes sense. It's true that rethrowing the error discards the original stack trace, but a non-developer gets nothing out of seeing stack trace information so it's okay to rethrow the error.

        void TrySuspectMethod()
        {
            try
            {
                SuspectMethod();
            }
#if DEBUG
            catch
            {
                //Don't log error, let developer see 
                //original stack trace easily
                throw;
#else
            catch (Exception ex)
            {
                //Log error for developers and then 
                //throw a error with a user-oriented message
                throw new Exception(String.Format
                    ("Dear user, sorry but: {0}", ex.Message));
#endif
            }
        }

The way the question is worded, pitting "Throw:" vs. "Throw ex;" makes it a bit of a red-herring. The real choice is between "Throw;" and "Throw Exception," where "Throw ex;" is an unlikely special case of "Throw Exception."

Drop columns whose name contains a specific string from pandas DataFrame

Cheaper, Faster, and Idiomatic: str.contains

In recent versions of pandas, you can use string methods on the index and columns. Here, str.startswith seems like a good fit.

To remove all columns starting with a given substring:

df.columns.str.startswith('Test')
# array([ True, False, False, False])

df.loc[:,~df.columns.str.startswith('Test')]

  toto test2 riri
0    x     x    x
1    x     x    x

For case-insensitive matching, you can use regex-based matching with str.contains with an SOL anchor:

df.columns.str.contains('^test', case=False)
# array([ True, False,  True, False])

df.loc[:,~df.columns.str.contains('^test', case=False)] 

  toto riri
0    x    x
1    x    x

if mixed-types is a possibility, specify na=False as well.

Referring to a Column Alias in a WHERE Clause

HAVING works in MySQL according to documentation:

The HAVING clause was added to SQL because the WHERE keyword could not be used with aggregate functions.

How to join multiple lines of file names into one with custom delimiter?

sed -e :a -e '/$/N; s/\n/\\n/; ta' [filename]

Explanation:

-e - denotes a command to be executed
:a - is a label
/$/N - defines the scope of the match for the current and the (N)ext line
s/\n/\\n/; - replaces all EOL with \n
ta; - goto label a if the match is successful

Taken from my blog.

Make Bootstrap's Carousel both center AND responsive?

I assume you have different sized images. I tested this myself, and it works as you describe (always centered, images widths appropriately)

/*CSS*/
div.c-wrapper{
    width: 80%; /* for example */
    margin: auto;
}

.carousel-inner > .item > img, 
.carousel-inner > .item > a > img{
width: 100%; /* use this, or not */
margin: auto;
}

<!--html-->
<div class="c-wrapper">
<div id="carousel-example-generic" class="carousel slide">
  <!-- Indicators -->
  <ol class="carousel-indicators">
    <li data-target="#carousel-example-generic" data-slide-to="0" class="active"></li>
    <li data-target="#carousel-example-generic" data-slide-to="1"></li>
    <li data-target="#carousel-example-generic" data-slide-to="2"></li>
  </ol>

  <!-- Wrapper for slides -->
  <div class="carousel-inner">
    <div class="item active">
      <img src="http://placehold.it/600x400">
      <div class="carousel-caption">
        hello
      </div>
    </div>
        <div class="item">
      <img src="http://placehold.it/500x400">
      <div class="carousel-caption">
        hello
      </div>
    </div>
    <div class="item">
      <img src="http://placehold.it/700x400">
      <div class="carousel-caption">
        hello
      </div>
    </div>
  </div>

  <!-- Controls -->
  <a class="left carousel-control" href="#carousel-example-generic" data-slide="prev">
    <span class="icon-prev"></span>
  </a>
  <a class="right carousel-control" href="#carousel-example-generic" data-slide="next">
    <span class="icon-next"></span>
  </a>
</div>
</div>

This creates a "jump" due to variable heights... to solve that, try something like this: Select the tallest image of a list

Or use media-query to set your own fixed height.

MySQL "WITH" clause

You might be interested in somethinkg like this:

select * from (
    select * from table
) as Subquery

How to pass List from Controller to View in MVC 3

I did this;

In controller:

public ActionResult Index()
{
  var invoices = db.Invoices;

  var categories = db.Categories.ToList();
  ViewData["MyData"] = categories; // Send this list to the view

  return View(invoices.ToList());
}

In view:

@model IEnumerable<abc.Models.Invoice>

@{
    ViewBag.Title = "Invoices";
}

@{
  var categories = (List<Category>) ViewData["MyData"]; // Cast the list
}

@foreach (var c in @categories) // Print the list
{
  @Html.Label(c.Name);
}

<table>
    ...
    @foreach (var item in Model) 
    {
      ...
    }
</table>

Hope it helps

How do I compare strings in GoLang?

Assuming there are no prepending/succeeding whitespace characters, there are still a few ways to assert string equality. Some of those are:

Here are some basic benchmark results (in these tests, strings.EqualFold(.., ..) seems like the most performant choice):

goos: darwin
goarch: amd64
BenchmarkStringOps/both_strings_equal::equality_op-4               10000        182944 ns/op
BenchmarkStringOps/both_strings_equal::strings_equal_fold-4        10000        114371 ns/op
BenchmarkStringOps/both_strings_equal::fold_caser-4                10000       2599013 ns/op
BenchmarkStringOps/both_strings_equal::lower_caser-4               10000       3592486 ns/op

BenchmarkStringOps/one_string_in_caps::equality_op-4               10000        417780 ns/op
BenchmarkStringOps/one_string_in_caps::strings_equal_fold-4        10000        153509 ns/op
BenchmarkStringOps/one_string_in_caps::fold_caser-4                10000       3039782 ns/op
BenchmarkStringOps/one_string_in_caps::lower_caser-4               10000       3861189 ns/op

BenchmarkStringOps/weird_casing_situation::equality_op-4           10000        619104 ns/op
BenchmarkStringOps/weird_casing_situation::strings_equal_fold-4    10000        148489 ns/op
BenchmarkStringOps/weird_casing_situation::fold_caser-4            10000       3603943 ns/op
BenchmarkStringOps/weird_casing_situation::lower_caser-4           10000       3637832 ns/op

Since there are quite a few options, so here's the code to generate benchmarks.

package main

import (
    "fmt"
    "strings"
    "testing"

    "golang.org/x/text/cases"
    "golang.org/x/text/language"
)

func BenchmarkStringOps(b *testing.B) {
    foldCaser := cases.Fold()
    lowerCaser := cases.Lower(language.English)

    tests := []struct{
        description string
        first, second string
    }{
        {
            description: "both strings equal",
            first: "aaaa",
            second: "aaaa",
        },
        {
            description: "one string in caps",
            first: "aaaa",
            second: "AAAA",
        },
        {
            description: "weird casing situation",
            first: "aAaA",
            second: "AaAa",
        },
    }

    for _, tt := range tests {
        b.Run(fmt.Sprintf("%s::equality op", tt.description), func(b *testing.B) {
            for i := 0; i < b.N; i++ {
                benchmarkStringEqualsOperation(tt.first, tt.second, b)
            }
        })

        b.Run(fmt.Sprintf("%s::strings equal fold", tt.description), func(b *testing.B) {
            for i := 0; i < b.N; i++ {
                benchmarkStringsEqualFold(tt.first, tt.second, b)
            }
        })

        b.Run(fmt.Sprintf("%s::fold caser", tt.description), func(b *testing.B) {
            for i := 0; i < b.N; i++ {
                benchmarkStringsFoldCaser(tt.first, tt.second, foldCaser, b)
            }
        })

        b.Run(fmt.Sprintf("%s::lower caser", tt.description), func(b *testing.B) {
            for i := 0; i < b.N; i++ {
                benchmarkStringsLowerCaser(tt.first, tt.second, lowerCaser, b)
            }
        })
    }
}

func benchmarkStringEqualsOperation(first, second string, b *testing.B) {
    for n := 0; n < b.N; n++ {
        _ = strings.ToLower(first) == strings.ToLower(second)
    }
}

func benchmarkStringsEqualFold(first, second string, b *testing.B) {
    for n := 0; n < b.N; n++ {
        _ = strings.EqualFold(first, second)
    }
}

func benchmarkStringsFoldCaser(first, second string, caser cases.Caser, b *testing.B) {
    for n := 0; n < b.N; n++ {
        _ = caser.String(first) == caser.String(second)
    }
}

func benchmarkStringsLowerCaser(first, second string, caser cases.Caser, b *testing.B) {
    for n := 0; n < b.N; n++ {
        _ = caser.String(first) == caser.String(second)
    }
}

How can I match on an attribute that contains a certain string?

A 2.0 XPath that works:

//*[tokenize(@class,'\s+')='atag']

or with a variable:

//*[tokenize(@class,'\s+')=$classname]

When should one use a spinlock instead of mutex?

Spinlock and Mutex synchronization mechanisms are very common today to be seen.

Let's think about Spinlock first.

Basically it is a busy waiting action, which means that we have to wait for a specified lock is released before we can proceed with the next action. Conceptually very simple, while implementing it is not on the case. For example: If the lock has not been released then the thread was swap-out and get into the sleep state, should do we deal with it? How to deal with synchronization locks when two threads simultaneously request access ?

Generally, the most intuitive idea is dealing with synchronization via a variable to protect the critical section. The concept of Mutex is similar, but they are still different. Focus on: CPU utilization. Spinlock consumes CPU time to wait for do the action, and therefore, we can sum up the difference between the two:

In homogeneous multi-core environments, if the time spend on critical section is small than use Spinlock, because we can reduce the context switch time. (Single-core comparison is not important, because some systems implementation Spinlock in the middle of the switch)

In Windows, using Spinlock will upgrade the thread to DISPATCH_LEVEL, which in some cases may be not allowed, so this time we had to use a Mutex (APC_LEVEL).

How to add an Android Studio project to GitHub

  1. Sign up and create a GitHub account in www.github.com.
  2. Download git from https://git-scm.com/downloads and install it in your system.
  3. Open the project in android studio and go to File -> Settings -> Version Control -> Git.
  4. Click on test button to test "path to Git executables". If successful message is shown everything is ok, else navigate to git.exe from where you installed git and test again.
  5. Go to File -> Settings -> Version Control -> GitHub. Enter your email and password used to create GitHub account and click on OK button.
  6. Then go to VCS -> Import into Version Control -> Share Project on GitHub. Enter Repository name, Description and click Share button.
  7. In the next window check all files inorder to add files for initial commit and click OK.
  8. Now the project will be uploaded to the GitHub repository and when uploading is finished we will get a message in android studio showing "Successfully shared project on GitHub". Click on the link provided in that message to go to GitHub repository.

equivalent of rm and mv in windows .cmd

move in windows is equivalent of mv command in Linux

del in windows is equivalent of rm command in Linux

How to resize image (Bitmap) to a given size?

 Bitmap yourBitmap;
 Bitmap resized = Bitmap.createScaledBitmap(yourBitmap, newWidth, newHeight, true);

or:

 resized = Bitmap.createScaledBitmap(yourBitmap,(int)(yourBitmap.getWidth()*0.8), (int)(yourBitmap.getHeight()*0.8), true);

Now() function with time trim

Dates in VBA are just floating point numbers, where the integer part represents the date and the fraction part represents the time. So in addition to using the Date function as tlayton says (to get the current date) you can also cast a date value to a integer to get the date-part from an arbitrary date: Int(myDateValue).

How to get calendar Quarter from a date in TSQL

nice excuse to muck around with CONVERT. Probably prettier ways of doing it:

live test on SQLfiddle here

create table the_table 
(
  [DateKey] INT,
)

insert into the_table
values
(20120101),
(20120102),
(20120201),
(20130601)


WITH myDateCTE(DateKey, Date) as
  (
    SELECT 
      DateKey
      ,[Date] = CONVERT(DATETIME, CONVERT(CHAR(8),DateKey),112) 
    FROM the_table
   )

SELECT 
  t.[DateKey]
  , m.[Date]
  , [QuarterNumber] = CONVERT(VARCHAR(20),Datepart(qq,Date))
  , [QuarterString] = 'Q' + CONVERT(VARCHAR(20),Datepart(qq,Date))
  , [Year] = Datepart(yyyy,Date) 
  , [Q-Yr] = CONVERT(VARCHAR(2),'Q' + CONVERT(VARCHAR(20),Datepart(qq,Date))) + '-' + CONVERT(VARCHAR(4),Datepart(yyyy,Date))  
FROM 
  the_table t
  inner join myDateCTE m
    on 
    t.DateKey = m.DateKey

PostgreSQL - max number of parameters in "IN" clause?

As someone more experienced with Oracle DB, I was concerned about this limit too. I carried out a performance test for a query with ~10'000 parameters in an IN-list, fetching prime numbers up to 100'000 from a table with the first 100'000 integers by actually listing all the prime numbers as query parameters.

My results indicate that you need not worry about overloading the query plan optimizer or getting plans without index usage, since it will transform the query to use = ANY({...}::integer[]) where it can leverage indices as expected:

-- prepare statement, runs instantaneous:
PREPARE hugeplan (integer, integer, integer, ...) AS
SELECT *
FROM primes
WHERE n IN ($1, $2, $3, ..., $9592);

-- fetch the prime numbers:
EXECUTE hugeplan(2, 3, 5, ..., 99991);

-- EXPLAIN ANALYZE output for the EXECUTE:
"Index Scan using n_idx on primes  (cost=0.42..9750.77 rows=9592 width=5) (actual time=0.024..15.268 rows=9592 loops=1)"
"  Index Cond: (n = ANY ('{2,3,5,7, (...)"
"Execution time: 16.063 ms"

-- setup, should you care:
CREATE TABLE public.primes
(
  n integer NOT NULL,
  prime boolean,
  CONSTRAINT n_idx PRIMARY KEY (n)
)
WITH (
  OIDS=FALSE
);
ALTER TABLE public.primes
  OWNER TO postgres;

INSERT INTO public.primes
SELECT generate_series(1,100000);

However, this (rather old) thread on the pgsql-hackers mailing list indicates that there is still a non-negligible cost in planning such queries, so take my word with a grain of salt.

Apply function to all elements of collection through LINQ

haha, man, I just asked this question a few hours ago (kind of)...try this:

example:

someIntList.ForEach(i=>i+5);

ForEach() is one of the built in .NET methods

This will modify the list, as opposed to returning a new one.

Image convert to Base64

Exactly what you need:) You can choose callback version or Promise version. Note that promises will work in IE only with Promise polyfill lib.You can put this code once on a page, and this function will appear in all your files.

The loadend event is fired when progress has stopped on the loading of a resource (e.g. after "error", "abort", or "load" have been dispatched)

Callback version

        File.prototype.convertToBase64 = function(callback){
                var reader = new FileReader();
                reader.onloadend = function (e) {
                    callback(e.target.result, e.target.error);
                };   
                reader.readAsDataURL(this);
        };

        $("#asd").on('change',function(){
          var selectedFile = this.files[0];
          selectedFile.convertToBase64(function(base64){
               alert(base64);
          }) 
        });

Promise version

    File.prototype.convertToBase64 = function(){
         return new Promise(function(resolve, reject) {
                var reader = new FileReader();
                reader.onloadend = function (e) {
                    resolve({
                      fileName: this.name,
                      result: e.target.result, 
                      error: e.target.error
                    });
                };   
                reader.readAsDataURL(this);
        }.bind(this)); 
    };

    FileList.prototype.convertAllToBase64 = function(regexp){
      // empty regexp if not set
      regexp = regexp || /.*/;
      //making array from FileList
      var filesArray = Array.prototype.slice.call(this);
      var base64PromisesArray = filesArray.
           filter(function(file){
             return (regexp).test(file.name)
           }).map(function(file){
             return file.convertToBase64();
           });
      return Promise.all(base64PromisesArray);
    };

    $("#asd").on('change',function(){
      //for one file
      var selectedFile = this.files[0];
      selectedFile.convertToBase64().
          then(function(obj){
            alert(obj.result);
          });
      });
      //for all files that have file extention png, jpeg, jpg, gif
      this.files.convertAllToBase64(/\.(png|jpeg|jpg|gif)$/i).then(function(objArray){
            objArray.forEach(function(obj, i){
                  console.log("result[" + obj.fileName + "][" + i + "] = " + obj.result);
            });
      });
    })

html

<input type="file" id="asd" multiple/>

Docker - a way to give access to a host USB or serial device?

There are a couple of options. You can use the --device flag that use can use to access USB devices without --privileged mode:

docker run -t -i --device=/dev/ttyUSB0 ubuntu bash

Alternatively, assuming your USB device is available with drivers working, etc. on the host in /dev/bus/usb, you can mount this in the container using privileged mode and the volumes option. For example:

docker run -t -i --privileged -v /dev/bus/usb:/dev/bus/usb ubuntu bash

Note that as the name implies, --privileged is insecure and should be handled with care.

Passing parameter to controller from route in laravel

You can add them like this

  Route::get('company/{name}', 'PublicareaController@companydetails');

Enter key press in C#

private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
{
    if (e.KeyChar == (char)Keys.Enter)
    {
        MessageBox.Show("Enter Key Pressed");
    }
}

This allows you to choose the specific Key you want, without finding the char value of the key.

Laravel Eloquent: Ordering results of all()

You could still use sortBy (at the collection level) instead of orderBy (at the query level) if you still want to use all() since it returns a collection of objects.

Ascending Order

$results = Project::all()->sortBy("name");

Descending Order

$results = Project::all()->sortByDesc("name");

Check out the documentation about Collections for more details.

https://laravel.com/docs/5.1/collections

How to change default language for SQL Server?

Using SQL Server Management Studio

To configure the default language option

  1. In Object Explorer, right-click a server and select Properties.
  2. Click the Misc server settings node.
  3. In the Default language for users box, choose the language in which Microsoft SQL Server should display system messages. The default language is English.

Using Transact-SQL

To configure the default language option

  1. Connect to the Database Engine.
  2. From the Standard bar, click New Query.
  3. Copy and paste the following example into the query window and click Execute.

This example shows how to use sp_configure to configure the default language option to French

USE AdventureWorks2012 ;
GO
EXEC sp_configure 'default language', 2 ;
GO
RECONFIGURE ;
GO

The 33 languages of SQL Server

| LANGID |        ALIAS        |
|--------|---------------------|
|    0   | English             |
|    1   | German              |
|    2   | French              |
|    3   | Japanese            |
|    4   | Danish              |
|    5   | Spanish             |
|    6   | Italian             |
|    7   | Dutch               |
|    8   | Norwegian           |
|    9   | Portuguese          |
|   10   | Finnish             |
|   11   | Swedish             |
|   12   | Czech               |
|   13   | Hungarian           |
|   14   | Polish              |
|   15   | Romanian            |
|   16   | Croatian            |
|   17   | Slovak              |
|   18   | Slovenian           |
|   19   | Greek               |
|   20   | Bulgarian           |
|   21   | Russian             |
|   22   | Turkish             |
|   23   | British English     |
|   24   | Estonian            |
|   25   | Latvian             |
|   26   | Lithuanian          |
|   27   | Brazilian           |
|   28   | Traditional Chinese |
|   29   | Korean              |
|   30   | Simplified Chinese  |
|   31   | Arabic              |
|   32   | Thai                |
|   33   | Bokmål              |

The request was rejected because no multipart boundary was found in springboot

I met this problem because I use request.js which writen base on axios
And I already set a defaults.headers in request.js

import axios from 'axios'
const request = axios.create({
  baseURL: '', 
  timeout: 15000 
})
service.defaults.headers.post['Content-Type'] = 'application/x-www-form-urlencoded'

here is how I solve this
instead of

request.post('/manage/product/upload.do',
      param,config
    )

I use axios directly send request,and didn't add config

axios.post('/manage/product/upload.do',
      param
    )

hope this can solve your problem

How do I handle too long index names in a Ruby on Rails ActiveRecord migration?

I'm afraid none of these solutions worked for me. Perhaps because I was using belongs_to in my create_table migration for a polymorphic association.

I'll add my code below and a link to the solution that helped me in case anyone else stumbles upon when searching for 'Index name is too long' in connection with polymorphic associations.

The following code did NOT work for me:

def change
  create_table :item_references do |t|
    t.text :item_unique_id
    t.belongs_to :referenceable, polymorphic: true
    t.timestamps
  end
  add_index :item_references, [:referenceable_id, :referenceable_type], name: 'idx_item_refs'
end

This code DID work for me:

def change
  create_table :item_references do |t|
    t.text :item_unique_id
    t.belongs_to :referenceable, polymorphic: true, index: { name: 'idx_item_refs' }

    t.timestamps
  end
end

This is the SO Q&A that helped me out: https://stackoverflow.com/a/30366460/3258059

"int cannot be dereferenced" in Java

try

id == list[pos].getItemNumber()

instead of

id.equals(list[pos].getItemNumber()

Hash String via SHA-256 in Java

I suppose you are using a relatively old Java Version without SHA-256. So you must add the BouncyCastle Provider to the already provided 'Security Providers' in your java version.

    // NEEDED if you are using a Java version without SHA-256    
    Security.addProvider(new BouncyCastleProvider());

    // then go as usual 
    MessageDigest md = MessageDigest.getInstance("SHA-256");
    String text = "my string...";
    md.update(text.getBytes("UTF-8")); // or UTF-16 if needed
    byte[] digest = md.digest();

How to add facebook share button on my website?

This Facebook page has a simple tool to create various share buttons.

For example, this is some output I got:

<div id="fb-root"></div>
<script async defer crossorigin="anonymous" src="https://connect.facebook.net/en_US/sdk.js#xfbml=1&version=v8.0" nonce="dilSYGI6"></script>
<div class="fb-share-button" data-href="https://www.mocacleveland.org/exhibitions/lee-mingwei-you-are-not-stranger" data-layout="button" data-size="small">
<a target="_blank" href="https://www.facebook.com/sharer/sharer.php?u=https%3A%2F%2Fwww.mocacleveland.org%2Fexhibitions%2Flee-mingwei-you-are-not-stranger&amp;src=sdkpreparse" class="fb-xfbml-parse-ignore">Share</a>
</div>

How do servlets work? Instantiation, sessions, shared variables and multithreading

When the servlet container (like Apache Tomcat) starts up, it will read from the web.xml file (only one per application) if anything goes wrong or shows up an error at container side console, otherwise, it will deploy and load all web applications by using web.xml (so named it as deployment descriptor).

During instantiation phase of the servlet, servlet instance is ready but it cannot serve the client request because it is missing with two pieces of information:
1: context information
2: initial configuration information

Servlet engine creates servletConfig interface object encapsulating the above missing information into it servlet engine calls init() of the servlet by supplying servletConfig object references as an argument. Once init() is completely executed servlet is ready to serve the client request.

Q) In the lifetime of servlet how many times instantiation and initialization happens ??

A)only once (for every client request a new thread is created) only one instance of the servlet serves any number of the client request ie, after serving one client request server does not die. It waits for other client requests ie what CGI (for every client request a new process is created) limitation is overcome with the servlet (internally servlet engine creates the thread).

Q)How session concept works?

A)whenever getSession() is called on HttpServletRequest object

Step 1: request object is evaluated for incoming session ID.

Step 2: if ID not available a brand new HttpSession object is created and its corresponding session ID is generated (ie of HashTable) session ID is stored into httpservlet response object and the reference of HttpSession object is returned to the servlet (doGet/doPost).

Step 3: if ID available brand new session object is not created session ID is picked up from the request object search is made in the collection of sessions by using session ID as the key.

Once the search is successful session ID is stored into HttpServletResponse and the existing session object references are returned to the doGet() or doPost() of UserDefineservlet.

Note:

1)when control leaves from servlet code to client don't forget that session object is being held by servlet container ie, the servlet engine

2)multithreading is left to servlet developers people for implementing ie., handle the multiple requests of client nothing to bother about multithread code

Inshort form:

A servlet is created when the application starts (it is deployed on the servlet container) or when it is first accessed (depending on the load-on-startup setting) when the servlet is instantiated, the init() method of the servlet is called then the servlet (its one and only instance) handles all requests (its service() method being called by multiple threads). That's why it is not advisable to have any synchronization in it, and you should avoid instance variables of the servlet when the application is undeployed (the servlet container stops), the destroy() method is called.

How to insert tab character when expandtab option is on in Vim

From the documentation on expandtab:

To insert a real tab when expandtab is on, use CTRL-V<Tab>. See also :retab and ins-expandtab.
This option is reset when the paste option is set and restored when the paste option is reset.

So if you have a mapping for toggling the paste option, e.g.

set pastetoggle=<F2>

you could also do <F2>Tab<F2>.

Apply function to pandas groupby

Regarding the issue with 'size', size is not a function on a dataframe, it is rather a property. So instead of using size(), plain size should work

Apart from that, a method like this should work

 def doCalculation(df):
    groupCount = df.size
    groupSum = df['my_labels'].notnull().sum()

    return groupCount / groupSum

dataFrame.groupby('my_labels').apply(doCalculation)

Jackson - best way writes a java list to a json array

In objectMapper we have writeValueAsString() which accepts object as parameter. We can pass object list as parameter get the string back.

List<Apartment> aptList =  new ArrayList<Apartment>();
    Apartment aptmt = null;
    for(int i=0;i<5;i++){
         aptmt= new Apartment();
         aptmt.setAptName("Apartment Name : ArrowHead Ranch");
         aptmt.setAptNum("3153"+i);
         aptmt.setPhase((i+1));
         aptmt.setFloorLevel(i+2);
         aptList.add(aptmt);
    }
mapper.writeValueAsString(aptList)

Converting string to date in mongodb

Using MongoDB 4.0 and newer

The $toDate operator will convert the value to a date. If the value cannot be converted to a date, $toDate errors. If the value is null or missing, $toDate returns null:

You can use it within an aggregate pipeline as follows:

db.collection.aggregate([
    { "$addFields": {
        "created_at": {
            "$toDate": "$created_at"
        }
    } }
])

The above is equivalent to using the $convert operator as follows:

db.collection.aggregate([
    { "$addFields": {
        "created_at": { 
            "$convert": { 
                "input": "$created_at", 
                "to": "date" 
            } 
        }
    } }
])

Using MongoDB 3.6 and newer

You cab also use the $dateFromString operator which converts the date/time string to a date object and has options for specifying the date format as well as the timezone:

db.collection.aggregate([
    { "$addFields": {
        "created_at": { 
            "$dateFromString": { 
                "dateString": "$created_at",
                "format": "%m-%d-%Y" /* <-- option available only in version 4.0. and newer */
            } 
        }
    } }
])

Using MongoDB versions >= 2.6 and < 3.2

If MongoDB version does not have the native operators that do the conversion, you would need to manually iterate the cursor returned by the find() method by either using the forEach() method or the cursor method next() to access the documents. Withing the loop, convert the field to an ISODate object and then update the field using the $set operator, as in the following example where the field is called created_at and currently holds the date in string format:

var cursor = db.collection.find({"created_at": {"$exists": true, "$type": 2 }}); 
while (cursor.hasNext()) { 
    var doc = cursor.next(); 
    db.collection.update(
        {"_id" : doc._id}, 
        {"$set" : {"created_at" : new ISODate(doc.created_at)}}
    ) 
};

For improved performance especially when dealing with large collections, take advantage of using the Bulk API for bulk updates as you will be sending the operations to the server in batches of say 1000 which gives you a better performance as you are not sending every request to the server, just once in every 1000 requests.

The following demonstrates this approach, the first example uses the Bulk API available in MongoDB versions >= 2.6 and < 3.2. It updates all the documents in the collection by changing the created_at fields to date fields:

var bulk = db.collection.initializeUnorderedBulkOp(),
    counter = 0;

db.collection.find({"created_at": {"$exists": true, "$type": 2 }}).forEach(function (doc) {
    var newDate = new ISODate(doc.created_at);
    bulk.find({ "_id": doc._id }).updateOne({ 
        "$set": { "created_at": newDate}
    });

    counter++;
    if (counter % 1000 == 0) {
        bulk.execute(); // Execute per 1000 operations and re-initialize every 1000 update statements
        bulk = db.collection.initializeUnorderedBulkOp();
    }
})
// Clean up remaining operations in queue
if (counter % 1000 != 0) { bulk.execute(); }

Using MongoDB 3.2

The next example applies to the new MongoDB version 3.2 which has since deprecated the Bulk API and provided a newer set of apis using bulkWrite():

var bulkOps = [],
    cursor = db.collection.find({"created_at": {"$exists": true, "$type": 2 }});

cursor.forEach(function (doc) { 
    var newDate = new ISODate(doc.created_at);
    bulkOps.push(         
        { 
            "updateOne": { 
                "filter": { "_id": doc._id } ,              
                "update": { "$set": { "created_at": newDate } } 
            }         
        }           
    );

    if (bulkOps.length === 500) {
        db.collection.bulkWrite(bulkOps);
        bulkOps = [];
    }     
});

if (bulkOps.length > 0) db.collection.bulkWrite(bulkOps);

Performing Inserts and Updates with Dapper

We are looking at building a few helpers, still deciding on APIs and if this goes in core or not. See: https://code.google.com/archive/p/dapper-dot-net/issues/6 for progress.

In the mean time you can do the following

val = "my value";
cnn.Execute("insert into Table(val) values (@val)", new {val});

cnn.Execute("update Table set val = @val where Id = @id", new {val, id = 1});

etcetera

See also my blog post: That annoying INSERT problem

Update

As pointed out in the comments, there are now several extensions available in the Dapper.Contrib project in the form of these IDbConnection extension methods:

T Get<T>(id);
IEnumerable<T> GetAll<T>();
int Insert<T>(T obj);
int Insert<T>(Enumerable<T> list);
bool Update<T>(T obj);
bool Update<T>(Enumerable<T> list);
bool Delete<T>(T obj);
bool Delete<T>(Enumerable<T> list);
bool DeleteAll<T>();

How do I access (read, write) Google Sheets spreadsheets with Python?

I know this thread is old now, but here is some decent documentation on Google Docs API. It was ridiculously hard to find, but useful, so maybe it will help you some. http://pythonhosted.org/gdata/docs/api.html.

I used gspread recently for a project to graph employee time data. I don't know how much it might help you, but here's a link to the code: https://github.com/lightcastle/employee-timecards

Gspread made things pretty easy for me. I was also able to add logic in to check for various conditions to create month-to-date and year-to-date results. But I just imported the whole dang spreadsheet and parsed it from there, so I'm not 100% sure that it is exactly what you're looking for. Best of luck.

Gson and deserializing an array of objects with arrays in it

The example Java data structure in the original question does not match the description of the JSON structure in the comment.

The JSON is described as

"an array of {object with an array of {object}}".

In terms of the types described in the question, the JSON translated into a Java data structure that would match the JSON structure for easy deserialization with Gson is

"an array of {TypeDTO object with an array of {ItemDTO object}}".

But the Java data structure provided in the question is not this. Instead it's

"an array of {TypeDTO object with an array of an array of {ItemDTO object}}".

A two-dimensional array != a single-dimensional array.

This first example demonstrates using Gson to simply deserialize and serialize a JSON structure that is "an array of {object with an array of {object}}".

input.json Contents:

[
  {
    "id":1,
    "name":"name1",
    "items":
    [
      {"id":2,"name":"name2","valid":true},
      {"id":3,"name":"name3","valid":false},
      {"id":4,"name":"name4","valid":true}
    ]
  },
  {
    "id":5,
    "name":"name5",
    "items":
    [
      {"id":6,"name":"name6","valid":true},
      {"id":7,"name":"name7","valid":false}
    ]
  },
  {
    "id":8,
    "name":"name8",
    "items":
    [
      {"id":9,"name":"name9","valid":true},
      {"id":10,"name":"name10","valid":false},
      {"id":11,"name":"name11","valid":false},
      {"id":12,"name":"name12","valid":true}
    ]
  }
]

Foo.java:

import java.io.FileReader;
import java.util.ArrayList;

import com.google.gson.Gson;

public class Foo
{
  public static void main(String[] args) throws Exception
  {
    Gson gson = new Gson();
    TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
    System.out.println(gson.toJson(myTypes));
  }
}

class TypeDTO
{
  int id;
  String name;
  ArrayList<ItemDTO> items;
}

class ItemDTO
{
  int id;
  String name;
  Boolean valid;
}

This second example uses instead a JSON structure that is actually "an array of {TypeDTO object with an array of an array of {ItemDTO object}}" to match the originally provided Java data structure.

input.json Contents:

[
  {
    "id":1,
    "name":"name1",
    "items":
    [
      [
        {"id":2,"name":"name2","valid":true},
        {"id":3,"name":"name3","valid":false}
      ],
      [
        {"id":4,"name":"name4","valid":true}
      ]
    ]
  },
  {
    "id":5,
    "name":"name5",
    "items":
    [
      [
        {"id":6,"name":"name6","valid":true}
      ],
      [
        {"id":7,"name":"name7","valid":false}
      ]
    ]
  },
  {
    "id":8,
    "name":"name8",
    "items":
    [
      [
        {"id":9,"name":"name9","valid":true},
        {"id":10,"name":"name10","valid":false}
      ],
      [
        {"id":11,"name":"name11","valid":false},
        {"id":12,"name":"name12","valid":true}
      ]
    ]
  }
]

Foo.java:

import java.io.FileReader;
import java.util.ArrayList;

import com.google.gson.Gson;

public class Foo
{
  public static void main(String[] args) throws Exception
  {
    Gson gson = new Gson();
    TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);
    System.out.println(gson.toJson(myTypes));
  }
}

class TypeDTO
{
  int id;
  String name;
  ArrayList<ItemDTO> items[];
}

class ItemDTO
{
  int id;
  String name;
  Boolean valid;
}

Regarding the remaining two questions:

is Gson extremely fast?

Not compared to other deserialization/serialization APIs. Gson has traditionally been amongst the slowest. The current and next releases of Gson reportedly include significant performance improvements, though I haven't looked for the latest performance test data to support those claims.

That said, if Gson is fast enough for your needs, then since it makes JSON deserialization so easy, it probably makes sense to use it. If better performance is required, then Jackson might be a better choice to use. It offers much (maybe even all) of the conveniences of Gson.

Or am I better to stick with what I've got working already?

I wouldn't. I would most always rather have one simple line of code like

TypeDTO[] myTypes = gson.fromJson(new FileReader("input.json"), TypeDTO[].class);

...to easily deserialize into a complex data structure, than the thirty lines of code that would otherwise be needed to map the pieces together one component at a time.

Send attachments with PHP Mail()?

you can send regular or attachment emails using this class that I created.

here is the link with examples of how to use it.

https://github.com/jerryurenaa/EZMAIL/blob/main/SMTP/Mail.php

WooCommerce return product object by id

Use this method:

$_product = wc_get_product( $id );

Official API-docs: wc_get_product

How do I assign a port mapping to an existing Docker container?

To change HostPort of a container on Windows 10

# list all containers
$ docker ps -a
$ docker stop docker101tutorial 
# Use grep or rg to get Id of container
$ docker inspect docker101tutorial | grep -i id
        "Id": "sha256:fff0a4b22d6f3d2eb8d2748b8a8bbc9967ea87199988acee8e86ac70bce9c3eb",
# run plain ubuntu docker image with shell and change it's namespace to docker host
# https://stackoverflow.com/questions/60408574/how-to-access-var-lib-docker-in-windows-10-docker-desktop/60411313#60411313
# https://forums.docker.com/t/the-location-of-images-in-docker-for-windows/19647/4
$ docker run -it --privileged --pid=host ubuntu nsenter -t 1 -m -u -i sh
# We want to find out the directory of docker101tutorial container. We are looking for:
# `"Image":"sha256:fff0a4b22d6f3d2eb8d2748b8a8bbc9967ea87199988acee8e86ac70bce9c3eb"`
# in /var/lib/docker/containers/*/config.v2.json
$ grep -rl --include=config.v2.json fff0a4b22d /var/lib/docker/containers/
/var/lib/docker/containers/c1eda20b30f058bce9f8ece3b47a21641df5b399770e12ab57416a954d3c8bbf/config.v2.json
# edit it
$ vi /var/lib/docker/containers/c1eda20b30f058bce9f8ece3b47a21641df5b399770e12ab57416a954d3c8bbf/hostconfig.json
  • Press i for insert mode.
  • Change "HostPort":"80" to "HostPort":"8092"
  • Press Escape and write :wq. Press Enter.
  • Do not start/stop docker101tutorial now. Otherwise changes to HostPort will be reverted.
  • Right click Docker Desktop tray icon and click Restart.
  • In Docker Desktop's list of containers, look at your container. Displayed port should change to 8092.
  • Start your container. Now it will be mapped to port 8092 on host.

Based on @holdfenytolvaj answer.

Sql server - log is full due to ACTIVE_TRANSACTION

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

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

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

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

Hope this will help you in finding your solution.

What is the fastest factorial function in JavaScript?

It would be probably very simple at first and maybe from this short code you would set it more better depend of your needs :

<body>

    <button  onclick="fact()">Open the Prompt</button>
    <h2 id="output"></h2>

    <script>

    function fact(){ 
        var enter=prompt("Enter You Factorial Number Bellow :","");
        var Num_enter=Number(enter);

        for (var i=1,FactNumber=1;i<=Num_enter;i++){

        FactNumber=FactNumber*i;
        }

        if(Num_enter){ 
           document.getElementById("output").textContent="the factorial of "+ Num_enter + " is: "+Num_enter+"!= "+ FactNumber;
        }


     }

   </script>


 </body>

Hyper-V: Create shared folder between host and guest with internal network

  • Open Hyper-V Manager
  • Create a new internal virtual switch (e.g. "Internal Network Connection")
  • Go to your Virtual Machine and create a new Network Adapter -> choose "Internal Network Connection" as virtual switch
  • Start the VM
  • Assign both your host as well as guest an IP address as well as a Subnet mask (IP4, e.g. 192.168.1.1 (host) / 192.168.1.2 (guest) and 255.255.255.0)
  • Open cmd both on host and guest and check via "ping" if host and guest can reach each other (if this does not work disable/enable the network adapter via the network settings in the control panel, restart...)
  • If successfull create a folder in the VM (e.g. "VMShare"), right-click on it -> Properties -> Sharing -> Advanced Sharing -> checkmark "Share this folder" -> Permissions -> Allow "Full Control" -> Apply
  • Now you should be able to reach the folder via the host -> to do so: open Windows Explorer -> enter the path to the guest (\192.168.1.xx...) in the address line -> enter the credentials of the guest (Choose "Other User" - it can be necessary to change the domain therefore enter ".\"[username] and [password])

There is also an easy way for copying via the clipboard:

  • If you start your VM and go to "View" you can enable "Enhanced Session". If you do it is not possible to drag and drop but to copy and paste.

Enhanced Session

How to override the properties of a CSS class using another CSS class

There are different ways in which properties can be overridden. Assuming you have

.left { background: blue }

e.g. any of the following would override it:

a.background-none { background: none; }
body .background-none { background: none; }
.background-none { background: none !important; }

The first two “win” by selector specificity; the third one wins by !important, a blunt instrument.

You could also organize your style sheets so that e.g. the rule

.background-none { background: none; }

wins simply by order, i.e. by being after an otherwise equally “powerful” rule. But this imposes restrictions and requires you to be careful in any reorganization of style sheets.

These are all examples of the CSS Cascade, a crucial but widely misunderstood concept. It defines the exact rules for resolving conflicts between style sheet rules.

P.S. I used left and background-none as they were used in the question. They are examples of class names that should not be used, since they reflect specific rendering and not structural or semantic roles.

How to find the most recent file in a directory using .NET, and without looping?

I do this is a bunch of my apps and I use a statement like this:

  var inputDirectory = new DirectoryInfo("\\Directory_Path_here");
  var myFile = inputDirectory.GetFiles().OrderByDescending(f => f.LastWriteTime).First();

From here you will have the filename for the most recently saved/added/updated file in the Directory of the "inputDirectory" variable. Now you can access it and do what you want with it.

Hope that helps.

Link and execute external JavaScript file hosted on GitHub

I had the same issue as you, what I did is change to

<script type="application/javascript" src="bootstrap-wysiwyg.js"></script>

It works for me.

JavaScript equivalent of PHP’s die

<script>
     alert("i am ajith fan");
     <?php die(); ?>
     alert("i love boxing");
     alert("i love MMA");
</script>

Image is not showing in browser?

I don't know where you're running the site from on your computer, but you have an absolute file path to your C drive: C:\Users\VIRK\Desktop\66.jpg

Try this instead:

<img  src="[PATH_RELATIVE_TO_ROOT]/66.jpg" width="400" height="400" />

UPDATE:

I don't know what your $PROJECTHOME is set to. But say for example your site files are located at C:\Users\VIRK\MyWebsite. And let's say your images are in an 'images' folder within your main site, like so: C:\Users\VIRK\MyWebsite\images.

Then in your HTML you can simply reference the image within the images folder relative to the site, like so:

<img  src="images/66.jpg" width="400" height="400" />

Or, assuming you're hosting at the root of localhost and not within another virtual directory, you can do this (note the slash in the beginning):

<img  src="/images/66.jpg" width="400" height="400" />

What is makeinfo, and how do I get it?

If it doesn't show up in your package manager (i.e. apt-cache search texinfo) and even apt-file search bin/makeinfo is no help, you may have to enable non-free/restricted packages for your package manager.

For ubuntu, sudo $EDITOR /etc/apt/sources.list and add restricted.

deb http://archive.ubuntu.com/ubuntu bionic main restricted universe multiverse
deb http://archive.ubuntu.com/ubuntu bionic-security main
deb http://archive.ubuntu.com/ubuntu bionic-updates main

For debian, sudo $EDITOR /etc/apt/sources.list and add non-free. You can even have preferences on package level if you don't want to clutter the package db with non-free stuff.

After a sudo apt-get udpate you should find the required package.

How to use foreach with a hash reference?

As others have stated, you have to dereference the reference. The keys function requires that its argument starts with a %:

My preference:

foreach my $key (keys %{$ad_grp_ref}) {

According to Conway:

foreach my $key (keys %{ $ad_grp_ref }) {

Guess who you should listen to...

You might want to read through the Perl Reference Documentation.

If you find yourself doing a lot of stuff with references to hashes and hashes of lists and lists of hashes, you might want to start thinking about using Object Oriented Perl. There's a lot of nice little tutorials in the Perl documentation.

Convert string to hex-string in C#

For Unicode support:

public class HexadecimalEncoding
{
    public static string ToHexString(string str)
    {
        var sb = new StringBuilder();

        var bytes = Encoding.Unicode.GetBytes(str);
        foreach (var t in bytes)
        {
            sb.Append(t.ToString("X2"));
        }

        return sb.ToString(); // returns: "48656C6C6F20776F726C64" for "Hello world"
    }

    public static string FromHexString(string hexString)
    {
        var bytes = new byte[hexString.Length / 2];
        for (var i = 0; i < bytes.Length; i++)
        {
            bytes[i] = Convert.ToByte(hexString.Substring(i * 2, 2), 16);
        }

        return Encoding.Unicode.GetString(bytes); // returns: "Hello world" for "48656C6C6F20776F726C64"
    }
}

Python calling method in class

Could someone explain to me, how to call the move method with the variable RIGHT

>>> myMissile = MissileDevice(myBattery)  # looks like you need a battery, don't know what that is, you figure it out.
>>> myMissile.move(MissileDevice.RIGHT)

If you have programmed in any other language with classes, besides python, this sort of thing

class Foo:
    bar = "baz"

is probably unfamiliar. In python, the class is a factory for objects, but it is itself an object; and variables defined in its scope are attached to the class, not the instances returned by the class. to refer to bar, above, you can just call it Foo.bar; you can also access class attributes through instances of the class, like Foo().bar.


Im utterly baffled about what 'self' refers too,

>>> class Foo:
...     def quux(self):
...         print self
...         print self.bar
...     bar = 'baz'
...
>>> Foo.quux
<unbound method Foo.quux>
>>> Foo.bar
'baz'
>>> f = Foo()
>>> f.bar
'baz'
>>> f
<__main__.Foo instance at 0x0286A058>
>>> f.quux
<bound method Foo.quux of <__main__.Foo instance at 0x0286A058>>
>>> f.quux()
<__main__.Foo instance at 0x0286A058>
baz
>>>

When you acecss an attribute on a python object, the interpreter will notice, when the looked up attribute was on the class, and is a function, that it should return a "bound" method instead of the function itself. All this does is arrange for the instance to be passed as the first argument.

How to make an authenticated web request in Powershell?

In some case NTLM authentication still won't work if given the correct credential.

There's a mechanism which will void NTLM auth within WebClient, see here for more information: System.Net.WebClient doesn't work with Windows Authentication

If you're trying above answer and it's still not working, follow the above link to add registry to make the domain whitelisted.

Post this here to save other's time ;)

R - Markdown avoiding package loading messages

```{r results='hide', message=FALSE, warning=FALSE}
library(RJSONIO)
library(AnotherPackage)
```

see Chunk Options in the Knitr docs

How to get package name from anywhere?

You can get your package name like so:

$ /path/to/adb shell 'pm list packages -f myapp'
package:/data/app/mycompany.myapp-2.apk=mycompany.myapp

Here are the options:

$ adb
Android Debug Bridge version 1.0.32
Revision 09a0d98bebce-android

 -a                            - directs adb to listen on all interfaces for a connection
 -d                            - directs command to the only connected USB device
                                 returns an error if more than one USB device is present.
 -e                            - directs command to the only running emulator.
                                 returns an error if more than one emulator is running.
 -s <specific device>          - directs command to the device or emulator with the given
                                 serial number or qualifier. Overrides ANDROID_SERIAL
                                 environment variable.
 -p <product name or path>     - simple product name like 'sooner', or
                                 a relative/absolute path to a product
                                 out directory like 'out/target/product/sooner'.
                                 If -p is not specified, the ANDROID_PRODUCT_OUT
                                 environment variable is used, which must
                                 be an absolute path.
 -H                            - Name of adb server host (default: localhost)
 -P                            - Port of adb server (default: 5037)
 devices [-l]                  - list all connected devices
                                 ('-l' will also list device qualifiers)
 connect <host>[:<port>]       - connect to a device via TCP/IP
                                 Port 5555 is used by default if no port number is specified.
 disconnect [<host>[:<port>]]  - disconnect from a TCP/IP device.
                                 Port 5555 is used by default if no port number is specified.
                                 Using this command with no additional arguments
                                 will disconnect from all connected TCP/IP devices.

device commands:
  adb push [-p] <local> <remote>
                               - copy file/dir to device
                                 ('-p' to display the transfer progress)
  adb pull [-p] [-a] <remote> [<local>]
                               - copy file/dir from device
                                 ('-p' to display the transfer progress)
                                 ('-a' means copy timestamp and mode)
  adb sync [ <directory> ]     - copy host->device only if changed
                                 (-l means list but don't copy)
  adb shell                    - run remote shell interactively
  adb shell <command>          - run remote shell command
  adb emu <command>            - run emulator console command
  adb logcat [ <filter-spec> ] - View device log
  adb forward --list           - list all forward socket connections.
                                 the format is a list of lines with the following format:
                                    <serial> " " <local> " " <remote> "\n"
  adb forward <local> <remote> - forward socket connections
                                 forward specs are one of:
                                   tcp:<port>
                                   localabstract:<unix domain socket name>
                                   localreserved:<unix domain socket name>
                                   localfilesystem:<unix domain socket name>
                                   dev:<character device name>
                                   jdwp:<process pid> (remote only)
  adb forward --no-rebind <local> <remote>
                               - same as 'adb forward <local> <remote>' but fails
                                 if <local> is already forwarded
  adb forward --remove <local> - remove a specific forward socket connection
  adb forward --remove-all     - remove all forward socket connections
  adb reverse --list           - list all reverse socket connections from device
  adb reverse <remote> <local> - reverse socket connections
                                 reverse specs are one of:
                                   tcp:<port>
                                   localabstract:<unix domain socket name>
                                   localreserved:<unix domain socket name>
                                   localfilesystem:<unix domain socket name>
  adb reverse --norebind <remote> <local>
                               - same as 'adb reverse <remote> <local>' but fails
                                 if <remote> is already reversed.
  adb reverse --remove <remote>
                               - remove a specific reversed socket connection
  adb reverse --remove-all     - remove all reversed socket connections from device
  adb jdwp                     - list PIDs of processes hosting a JDWP transport
  adb install [-lrtsdg] <file>
                               - push this package file to the device and install it
                                 (-l: forward lock application)
                                 (-r: replace existing application)
                                 (-t: allow test packages)
                                 (-s: install application on sdcard)
                                 (-d: allow version code downgrade)
                                 (-g: grant all runtime permissions)
  adb install-multiple [-lrtsdpg] <file...>
                               - push this package file to the device and install it
                                 (-l: forward lock application)
                                 (-r: replace existing application)
                                 (-t: allow test packages)
                                 (-s: install application on sdcard)
                                 (-d: allow version code downgrade)
                                 (-p: partial application install)
                                 (-g: grant all runtime permissions)
  adb uninstall [-k] <package> - remove this app package from the device
                                 ('-k' means keep the data and cache directories)
  adb bugreport                - return all information from the device
                                 that should be included in a bug report.

  adb backup [-f <file>] [-apk|-noapk] [-obb|-noobb] [-shared|-noshared] [-all] [-system|-nosystem] [<packages...>]
                               - write an archive of the device's data to <file>.
                                 If no -f option is supplied then the data is written
                                 to "backup.ab" in the current directory.
                                 (-apk|-noapk enable/disable backup of the .apks themselves
                                    in the archive; the default is noapk.)
                                 (-obb|-noobb enable/disable backup of any installed apk expansion
                                    (aka .obb) files associated with each application; the default
                                    is noobb.)
                                 (-shared|-noshared enable/disable backup of the device's
                                    shared storage / SD card contents; the default is noshared.)
                                 (-all means to back up all installed applications)
                                 (-system|-nosystem toggles whether -all automatically includes
                                    system applications; the default is to include system apps)
                                 (<packages...> is the list of applications to be backed up.  If
                                    the -all or -shared flags are passed, then the package
                                    list is optional.  Applications explicitly given on the
                                    command line will be included even if -nosystem would
                                    ordinarily cause them to be omitted.)

  adb restore <file>           - restore device contents from the <file> backup archive

  adb disable-verity           - disable dm-verity checking on USERDEBUG builds
  adb enable-verity            - re-enable dm-verity checking on USERDEBUG builds
  adb keygen <file>            - generate adb public/private key. The private key is stored in <file>,
                                 and the public key is stored in <file>.pub. Any existing files
                                 are overwritten.
  adb help                     - show this help message
  adb version                  - show version num

scripting:
  adb wait-for-device          - block until device is online
  adb start-server             - ensure that there is a server running
  adb kill-server              - kill the server if it is running
  adb get-state                - prints: offline | bootloader | device
  adb get-serialno             - prints: <serial-number>
  adb get-devpath              - prints: <device-path>
  adb remount                  - remounts the /system, /vendor (if present) and /oem (if present) partitions on the device read-write
  adb reboot [bootloader|recovery]
                               - reboots the device, optionally into the bootloader or recovery program.
  adb reboot sideload          - reboots the device into the sideload mode in recovery program (adb root required).
  adb reboot sideload-auto-reboot
                               - reboots into the sideload mode, then reboots automatically after the sideload regardless of the result.
  adb sideload <file>          - sideloads the given package
  adb root                     - restarts the adbd daemon with root permissions
  adb unroot                   - restarts the adbd daemon without root permissions
  adb usb                      - restarts the adbd daemon listening on USB
  adb tcpip <port>             - restarts the adbd daemon listening on TCP on the specified port

networking:
  adb ppp <tty> [parameters]   - Run PPP over USB.
 Note: you should not automatically start a PPP connection.
 <tty> refers to the tty for PPP stream. Eg. dev:/dev/omap_csmi_tty1
 [parameters] - Eg. defaultroute debug dump local notty usepeerdns

adb sync notes: adb sync [ <directory> ]
  <localdir> can be interpreted in several ways:

  - If <directory> is not specified, /system, /vendor (if present), /oem (if present) and /data partitions will be updated.

  - If it is "system", "vendor", "oem" or "data", only the corresponding partition
    is updated.

environment variables:
  ADB_TRACE                    - Print debug information. A comma separated list of the following values
                                 1 or all, adb, sockets, packets, rwx, usb, sync, sysdeps, transport, jdwp
  ANDROID_SERIAL               - The serial number to connect to. -s takes priority over this if given.
  ANDROID_LOG_TAGS             - When used with the logcat option, only these debug tags are printed.

Load json from local file with http.get() in angular 2

I you want to put the response of the request in the navItems. Because http.get() return an observable you will have to subscribe to it.

Look at this example:

_x000D_
_x000D_
// version without map_x000D_
this.http.get("../data/navItems.json")_x000D_
    .subscribe((success) => {_x000D_
      this.navItems = success.json();          _x000D_
    });_x000D_
_x000D_
// with map_x000D_
import 'rxjs/add/operator/map'_x000D_
this.http.get("../data/navItems.json")_x000D_
    .map((data) => {_x000D_
      return data.json();_x000D_
    })_x000D_
    .subscribe((success) => {_x000D_
      this.navItems = success;          _x000D_
    });
_x000D_
_x000D_
_x000D_

How to convert a String to Bytearray

You don't need underscore, just use built-in map:

_x000D_
_x000D_
var string = 'Hello World!';_x000D_
_x000D_
document.write(string.split('').map(function(c) { return c.charCodeAt(); }));
_x000D_
_x000D_
_x000D_

ASP.NET 5 MVC: unable to connect to web server 'IIS Express'

For me, IIS Express was not accessible when I added iplisten on DOS Prompt like this: netsh http add iplisten MyIPAddress. I fixed it by deleting the iplisten like this: netsh http delete iplisten MyIPAddress.

Correct format specifier for double in printf

%Lf (note the capital L) is the format specifier for long doubles.

For plain doubles, either %e, %E, %f, %g or %G will do.

How to resize datagridview control when form resizes

You have to chose 'Fill' in the Dock property.

How to find my Subversion server version number?

There really isn't an easy way to find out what version of Subversion your server is running -- except to get onto the server and see for yourself.

However, this may not be as big a problem as you may think. Subversion clients is were much of the grunt work is handled, and most versions of the Subversion clients can work with almost any version of the server.

The last release where the server version really made a difference to the client was the change from release 1.4 to release 1.5 when merge tracking was added. Merge tracking had been greatly improved in version 1.6, but that doesn't really affect the interactions between the client and server.

Let's take the latest changes in Subversion 1.8:

  • svn move is now a first class operation: Subversion finally understands the svn move is not a svn copy and svn delete. However, this is something that the client handles and doesn't really affect the server version.
  • svn merge --reintegrate deprecated: Again, as long as the server is at version 1.5 or greater this isn't an issue.
  • Property Inheritance: This is another 1.8 release update, but this will work with any Subversion server -- although Subversion servers running 1.8 will deliver better performance on inheritable properties.
  • Two new inheritable properties - svn:global-ignores and svn:auto-props: Alas! What we really wanted. A way to setup these two properties without depending upon the Subversion configuration file itself. However, this is a client-only issue, so it again doesn't matter what version of the server you're using.
  • gnu-agent memory caching: Another client-only feature.
  • fsfs performance enhancements and authz in-repository authentication. Nice features, but these work no matter what version of the client you're using.

Of all the features, only one depends upon the version of the server being 1.5 or greater (and 1.4 has been obsolete for quite a while. The newer features of 1.8 will improve performance of your working copy, but the server being at revision 1.8 isn't necessary. You're much more affected by your client version than your server version.

I know this isn't the answer you wanted (no official way to see the server version), but fortunately the server version doesn't really affect you that much.

How to detect escape key press with pure JS or jQuery?

On Firefox 78 use this ("keypress" doesn't work for Escape key):

function keyPress (e)(){
  if (e.key == "Escape"){
     //do something here      
  }
document.addEventListener("keyup", keyPress);

How do I remove objects from a JavaScript associative array?

For "Arrays":

If you know the index:

array.splice(index, 1);

If you know the value:

function removeItem(array, value) {
    var index = array.indexOf(value);
    if (index > -1) {
        array.splice(index, 1);
    }
    return array;
}

The most upvoted answer for delete works well in case of objects but not for the real arrays. If I use delete it removes elements from loops but keeps the element as empty and length of array wont change. This may be a problem in some scenarios.

For example, if I do myArray.toString() on myArray after removal via delete, it creates an empty entry, i.e. ,,.

NPM stuck giving the same error EISDIR: Illegal operation on a directory, read at error (native)

In my case, I'm using Windows 10 in Spanish and this version mixes English and Spanish directory names. My problem was that the desktop directory has this name for some commands and escritorio to others. I believe that npm cannot resolve this. My solution was to simply change to another directory starting from C:\ different to my home directory.

Know relationships between all the tables of database in SQL Server

This stored procedure will provide you with a hierarchical tree of relationship. Based on this article from Technet. It will also optionally provide you a query for reading or deleting all the related data.

IF OBJECT_ID('GetForeignKeyRelations','P') IS NOT NULL 
    DROP PROC GetForeignKeyRelations 
GO 

CREATE PROC GetForeignKeyRelations 
@Schemaname Sysname = 'dbo' 
,@Tablename Sysname 
,@WhereClause NVARCHAR(2000) = '' 
,@GenerateDeleteScripts bit  = 0  
,@GenerateSelectScripts bit  = 0 

AS 

SET NOCOUNT ON 

DECLARE @fkeytbl TABLE 
( 
ReferencingObjectid        int NULL 
,ReferencingSchemaname  Sysname NULL 
,ReferencingTablename   Sysname NULL  
,ReferencingColumnname  Sysname NULL 
,PrimarykeyObjectid     int  NULL 
,PrimarykeySchemaname   Sysname NULL 
,PrimarykeyTablename    Sysname NULL 
,PrimarykeyColumnname   Sysname NULL 
,Hierarchy              varchar(max) NULL 
,level                  int NULL 
,rnk                    varchar(max) NULL 
,Processed                bit default 0  NULL 
); 



 WITH fkey (ReferencingObjectid,ReferencingSchemaname,ReferencingTablename,ReferencingColumnname 
            ,PrimarykeyObjectid,PrimarykeySchemaname,PrimarykeyTablename,PrimarykeyColumnname,Hierarchy,level,rnk) 
    AS 
    ( 
        SELECT                   
                               soc.object_id 
                              ,scc.name 
                              ,soc.name 
                              ,convert(sysname,null) 
                              ,convert(int,null) 
                              ,convert(sysname,null) 
                              ,convert(sysname,null) 
                              ,convert(sysname,null) 
                              ,CONVERT(VARCHAR(MAX), scc.name + '.' + soc.name  ) as Hierarchy 
                              ,0 as level 
                              ,rnk=convert(varchar(max),soc.object_id) 
        FROM SYS.objects soc 
        JOIN sys.schemas scc 
          ON soc.schema_id = scc.schema_id 
       WHERE scc.name =@Schemaname 
         AND soc.name =@Tablename 
      UNION ALL 
      SELECT                   sop.object_id 
                              ,scp.name 
                              ,sop.name 
                              ,socp.name 
                              ,soc.object_id 
                              ,scc.name 
                              ,soc.name 
                              ,socc.name 
                              ,CONVERT(VARCHAR(MAX), f.Hierarchy + ' --> ' + scp.name + '.' + sop.name ) as Hierarchy 
                              ,f.level+1 as level 
                              ,rnk=f.rnk + '-' + convert(varchar(max),sop.object_id) 
        FROM SYS.foreign_key_columns sfc 
        JOIN Sys.Objects sop 
          ON sfc.parent_object_id = sop.object_id 
        JOIN SYS.columns socp 
          ON socp.object_id = sop.object_id 
         AND socp.column_id = sfc.parent_column_id 
        JOIN sys.schemas scp 
          ON sop.schema_id = scp.schema_id 
        JOIN SYS.objects soc 
          ON sfc.referenced_object_id = soc.object_id 
        JOIN SYS.columns socc 
          ON socc.object_id = soc.object_id 
         AND socc.column_id = sfc.referenced_column_id 
        JOIN sys.schemas scc 
          ON soc.schema_id = scc.schema_id 
        JOIN fkey f 
          ON f.ReferencingObjectid = sfc.referenced_object_id 
        WHERE ISNULL(f.PrimarykeyObjectid,0) <> f.ReferencingObjectid 
      ) 

     INSERT INTO @fkeytbl 
     (ReferencingObjectid,ReferencingSchemaname,ReferencingTablename,ReferencingColumnname 
            ,PrimarykeyObjectid,PrimarykeySchemaname,PrimarykeyTablename,PrimarykeyColumnname,Hierarchy,level,rnk) 
     SELECT ReferencingObjectid,ReferencingSchemaname,ReferencingTablename,ReferencingColumnname 
            ,PrimarykeyObjectid,PrimarykeySchemaname,PrimarykeyTablename,PrimarykeyColumnname,Hierarchy,level,rnk 
       FROM fkey 

        SELECT F.Relationshiptree 
         FROM 
        ( 
        SELECT DISTINCT Replicate('------',Level) + CASE LEVEL WHEN 0 THEN '' ELSE '>' END +  ReferencingSchemaname + '.' + ReferencingTablename 'Relationshiptree' 
               ,RNK 
          FROM @fkeytbl 
          ) F 
        ORDER BY F.rnk ASC 

------------------------------------------------------------------------------------------------------------------------------- 
-- Generate the Delete / Select script 
------------------------------------------------------------------------------------------------------------------------------- 

    DECLARE @Sql VARCHAR(MAX) 
    DECLARE @RnkSql VARCHAR(MAX) 

    DECLARE @Jointables TABLE 
    ( 
    ID INT IDENTITY 
    ,Object_id int 
    ) 

    DECLARE @ProcessTablename SYSNAME 
    DECLARE @ProcessSchemaName SYSNAME 

    DECLARE @JoinConditionSQL VARCHAR(MAX) 
    DECLARE @Rnk VARCHAR(MAX) 
    DECLARE @OldTablename SYSNAME 

    IF @GenerateDeleteScripts = 1 or @GenerateSelectScripts = 1  
    BEGIN 

          WHILE EXISTS ( SELECT 1 
                           FROM @fkeytbl 
                          WHERE Processed = 0 
                            AND level > 0 ) 
          BEGIN 

            SELECT @ProcessTablename = '' 
            SELECT @Sql                 = '' 
            SELECT @JoinConditionSQL = '' 
            SELECT @OldTablename     = '' 


            SELECT TOP 1 @ProcessTablename = ReferencingTablename 
                  ,@ProcessSchemaName  = ReferencingSchemaname 
                  ,@Rnk = RNK  
              FROM @fkeytbl 
             WHERE Processed = 0 
              AND level > 0  
             ORDER BY level DESC 


            SELECT @RnkSql ='SELECT ' + REPLACE (@rnk,'-',' UNION ALL SELECT ')  

            DELETE FROM @Jointables 

            INSERT INTO @Jointables 
            EXEC(@RnkSql) 

            IF @GenerateDeleteScripts = 1 
                SELECT @Sql = 'DELETE [' + @ProcessSchemaName + '].[' + @ProcessTablename + ']' + CHAR(10) + ' FROM [' + @ProcessSchemaName + '].[' + @ProcessTablename + ']' + CHAR(10) 

            IF @GenerateSelectScripts = 1 
                SELECT @Sql = 'SELECT  [' + @ProcessSchemaName + '].[' + @ProcessTablename + '].*' + CHAR(10) + ' FROM [' + @ProcessSchemaName + '].[' + @ProcessTablename + ']' + CHAR(10) 

            SELECT @JoinConditionSQL = @JoinConditionSQL  
                                           + CASE  
                                             WHEN @OldTablename <> f.PrimarykeyTablename THEN  'JOIN ['  + f.PrimarykeySchemaname  + '].[' + f.PrimarykeyTablename + '] ' + CHAR(10) + ' ON ' 
                                             ELSE ' AND '  
                                             END 
                                           + ' ['  + f.PrimarykeySchemaname  + '].[' + f.PrimarykeyTablename + '].[' + f.PrimarykeyColumnname + '] =  ['  + f.ReferencingSchemaname  + '].[' + f.ReferencingTablename + '].[' + f.ReferencingColumnname + ']' + CHAR(10)  
                     , @OldTablename = CASE  
                                         WHEN @OldTablename <> f.PrimarykeyTablename THEN  f.PrimarykeyTablename 
                                         ELSE @OldTablename 
                                         END 

                  FROM @fkeytbl f 
                  JOIN @Jointables j 
                    ON f.Referencingobjectid  = j.Object_id 
                 WHERE charindex(f.rnk + '-',@Rnk + '-') <> 0 
                   AND F.level > 0 
                 ORDER BY J.ID DESC 

            SELECT @Sql = @Sql +  @JoinConditionSQL 

            IF LTRIM(RTRIM(@WhereClause)) <> ''  
                SELECT @Sql = @Sql + ' WHERE (' + @WhereClause + ')' 

            PRINT @SQL 
            PRINT CHAR(10) 

            UPDATE @fkeytbl 
               SET Processed = 1 
             WHERE ReferencingTablename = @ProcessTablename 
               AND rnk = @Rnk 

          END 

          IF @GenerateDeleteScripts = 1 
            SELECT @Sql = 'DELETE FROM [' + @Schemaname + '].[' + @Tablename + ']' 

          IF @GenerateSelectScripts = 1 
            SELECT @Sql = 'SELECT * FROM [' + @Schemaname + '].[' + @Tablename + ']' 

          IF LTRIM(RTRIM(@WhereClause)) <> ''  
                SELECT @Sql = @Sql  + ' WHERE ' + @WhereClause 

         PRINT @SQL 
     END 

SET NOCOUNT OFF 


go 

GitHub Error Message - Permission denied (publickey)

You need to generate an SSH key (if you don't have one) and associate the public key with your Github account. See Github's own documentation.

How do I prevent and/or handle a StackOverflowException?

You can read up this property every few calls, Environment.StackTrace , and if the stacktrace exceded a specific threshold that you preset, you can return the function.

You should also try to replace some recursive functions with loops.

Using SED with wildcard

So, the concept of a "wildcard" in Regular Expressions works a bit differently. In order to match "any character" you would use "." The "*" modifier means, match any number of times.

How do I calculate square root in Python?

If you want to do it the way the calculator actually does it, use the Babylonian technique. It is explained here and here.

Suppose you want to calculate the square root of 2:

a=2

a1 = (a/2)+1
b1 = a/a1
aminus1 = a1
bminus1 = b1


while (aminus1-bminus1 > 0):
    an = 0.5 * (aminus1 + bminus1)
    bn = a / an
    aminus1 = an
    bminus1 = bn
    print(an,bn,an-bn)

SQL "select where not in subquery" returns no results

select *,
(select COUNT(ID)  from ProductMaster where ProductMaster.CatID = CategoryMaster.ID) as coun 
from CategoryMaster

How do I compile a Visual Studio project from the command-line?

I know of two ways to do it.

Method 1
The first method (which I prefer) is to use msbuild:

msbuild project.sln /Flags...

Method 2
You can also run:

vcexpress project.sln /build /Flags...

The vcexpress option returns immediately and does not print any output. I suppose that might be what you want for a script.

Note that DevEnv is not distributed with Visual Studio Express 2008 (I spent a lot of time trying to figure that out when I first had a similar issue).

So, the end result might be:

os.system("msbuild project.sln /p:Configuration=Debug")

You'll also want to make sure your environment variables are correct, as msbuild and vcexpress are not by default on the system path. Either start the Visual Studio build environment and run your script from there, or modify the paths in Python (with os.putenv).

How to call getClass() from a static method in Java?

Try something like this. It works for me. Logg (Class name)

    String level= "";

    Properties prop = new Properties();

    InputStream in =
            Logg.class.getResourceAsStream("resources\\config");

    if (in != null) {
        prop.load(in);
    } else {
        throw new FileNotFoundException("property file '" + in + "' not found in the classpath");
    }

    level = prop.getProperty("Level");

How to easily import multiple sql files into a MySQL database?

Save this file as .bat and run it , change variables inside parenthesis ...

@echo off
title Mysql Import Script
cd (Folder Name)
 for %%a in (*) do (
     echo Importing File  : %%a 
     mysql -u(username) -p(password)  %%~na < %%a
)
pause

if it's only one database modify (%%~na) with the database name .

How can I split this comma-delimited string in Python?

You don't want regular expressions here.

s = "144,1231693144,26959535291011309493156476344723991336010898738574164086137773096960,26959535291011309493156476344723991336010898738574164086137773096960,1.00,4295032833,1563,2747941 288,1231823695,26959535291011309493156476344723991336010898738574164086137773096960,26959535291011309493156476344723991336010898738574164086137773096960,1.00,4295032833,909,4725008"

print s.split(',')

Gives you:

['144', '1231693144', '26959535291011309493156476344723991336010898738574164086137773096960', '26959535291011309493156476344723991336010898738574164086137773096960', '1.00
', '4295032833', '1563', '2747941 288', '1231823695', '26959535291011309493156476344723991336010898738574164086137773096960', '26959535291011309493156476344723991336010898
738574164086137773096960', '1.00', '4295032833', '909', '4725008']

Casting string to enum

Use Enum.Parse().

var content = (ContentEnum)Enum.Parse(typeof(ContentEnum), fileContentMessage);