Programs & Examples On #Throwable

The `Throwable` class is the superclass of all errors and exceptions in the Java programming language. Only objects that are instances of this class (or one of its subclasses) are thrown by the Java VM or could be thrown by the Java `throw` statement.

Difference between using Throwable and Exception in a try catch

The first one catches all subclasses of Throwable (this includes Exception and Error), the second one catches all subclasses of Exception.

Error is programmatically unrecoverable in any way and is usually not to be caught, except for logging purposes (which passes it through again). Exception is programmatically recoverable. Its subclass RuntimeException indicates a programming error and is usually not to be caught as well.

Regex to match any character including new lines

If you don't want add the /s regex modifier (perhaps you still want . to retain its original meaning elsewhere in the regex), you may also use a character class. One possibility:

[\S\s]

a character which is not a space or is a space. In other words, any character.

You can also change modifiers locally in a small part of the regex, like so:

(?s:.)

did you register the component correctly? For recursive components, make sure to provide the "name" option

Adding my scenario. Just in case someone has similar problem and not able to identify ACTUAL issue.

I was using vue splitpanes.

Previously it required only "Splitpanes", in latest version, they made another "Pane" component (as children of splitpanes).

Now thing is, if you don't register "Pane" component in latest version of splitpanes, it was showing error for "Splitpanes". as below.

[Vue warn]: Unknown custom element: <splitpanes> - did you register the component correctly? For recursive components, make sure to provide the "name" option.

Converting string to double in C#

In your string I see: 15.5859949000000662452.23862099999999 which is not a double (it has two decimal points). Perhaps it's just a legitimate input error?

You may also want to figure out if your last String will be empty, and account for that situation.

How to check if image exists with given url?

$.ajax({
    url:'http://www.example.com/somefile.ext',
    type:'HEAD',
    error: function(){
            //do something depressing
    },
    success: function(){
            //do something cheerful :)
    }
});

from: http://www.ambitionlab.com/how-to-check-if-a-file-exists-using-jquery-2010-01-06

In Perl, how can I concisely check if a $variable is defined and contains a non zero length string?

You often see the check for definedness so you don't have to deal with the warning for using an undef value (and in Perl 5.10 it tells you the offending variable):

 Use of uninitialized value $name in ...

So, to get around this warning, people come up with all sorts of code, and that code starts to look like an important part of the solution rather than the bubble gum and duct tape that it is. Sometimes, it's better to show what you are doing by explicitly turning off the warning that you are trying to avoid:

 {
 no warnings 'uninitialized';

 if( length $name ) {
      ...
      }
 }

In other cases, use some sort of null value instead of the data. With Perl 5.10's defined-or operator, you can give length an explicit empty string (defined, and give back zero length) instead of the variable that will trigger the warning:

 use 5.010;

 if( length( $name // '' ) ) {
      ...
      }

In Perl 5.12, it's a bit easier because length on an undefined value also returns undefined. That might seem like a bit of silliness, but that pleases the mathematician I might have wanted to be. That doesn't issue a warning, which is the reason this question exists.

use 5.012;
use warnings;

my $name;

if( length $name ) { # no warning
    ...
    }

Generate a random number in a certain range in MATLAB

Generate values from the uniform distribution on the interval [a, b].

      r = a + (b-a).*rand(100,1);

SQL Server: convert ((int)year,(int)month,(int)day) to Datetime

In order to be independent of the language and locale settings, you should use the ISO 8601 YYYYMMDD format - this will work on any SQL Server system with any language and regional setting in effect:

SELECT
   CAST(
      CAST(year AS VARCHAR(4)) +
      RIGHT('0' + CAST(month AS VARCHAR(2)), 2) +
      RIGHT('0' + CAST(day AS VARCHAR(2)), 2) 
   AS DATETIME)

How can I check if a string represents an int, without using try/except?

I guess the question is related with speed since the try/except has a time penalty:

 test data

First, I created a list of 200 strings, 100 failing strings and 100 numeric strings.

from random import shuffle
numbers = [u'+1'] * 100
nonumbers = [u'1abc'] * 100
testlist = numbers + nonumbers
shuffle(testlist)
testlist = np.array(testlist)

 numpy solution (only works with arrays and unicode)

np.core.defchararray.isnumeric can also work with unicode strings np.core.defchararray.isnumeric(u'+12') but it returns and array. So, it's a good solution if you have to do thousands of conversions and have missing data or non numeric data.

import numpy as np
%timeit np.core.defchararray.isnumeric(testlist)
10000 loops, best of 3: 27.9 µs per loop # 200 numbers per loop

try/except

def check_num(s):
  try:
    int(s)
    return True
  except:
    return False

def check_list(l):
  return [check_num(e) for e in l]

%timeit check_list(testlist)
1000 loops, best of 3: 217 µs per loop # 200 numbers per loop

Seems that numpy solution is much faster.

Understanding passport serialize deserialize

For anyone using Koa and koa-passport:

Know that the key for the user set in the serializeUser method (often a unique id for that user) will be stored in:

this.session.passport.user

When you set in done(null, user) in deserializeUser where 'user' is some user object from your database:

this.req.user OR this.passport.user

for some reason this.user Koa context never gets set when you call done(null, user) in your deserializeUser method.

So you can write your own middleware after the call to app.use(passport.session()) to put it in this.user like so:

app.use(function * setUserInContext (next) {
  this.user = this.req.user
  yield next
})

If you're unclear on how serializeUser and deserializeUser work, just hit me up on twitter. @yvanscher

How to remove margin space around body or clear default css styles

try removing the padding/margins from the body tag.

body{
padding:0px;
margin:0px;
}

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding. The statement has been terminated

While all the earlier responses address the issue they did not cover all cases.

Microsoft has acknowledged the issue and fixed it in 2011 for supported operating systems, so if you get the stack trace like:

Timeout expired. The timeout period elapsed prior to completion of the operation or the server is not responding.
at System.Data.SqlClient.SqlInternalConnection.OnError(SqlException exception, Boolean breakConnection)
at System.Data.SqlClient.TdsParser.ThrowExceptionAndWarning()
at System.Data.SqlClient.TdsParserStateObject.ReadSniError(TdsParserStateObject stateObj, UInt32 error)
at System.Data.SqlClient.TdsParserStateObject.ReadSni(DbAsyncResult asyncResult, TdsParserStateObject stateObj)

you may need to update your .NET assemblies.

This issue occurs because of an error in the connection-retry algorithm for mirrored databases.

When the retry-algorithm is used, the data provider waits for the first read (SniReadSync) call to finish. The call is sent to the back-end computer that is running SQL Server, and the waiting time is calculated by multiplying the connection time-out value by 0.08. However, the data provider incorrectly sets a connection to a doomed state if a response is slow and if the first SniReadSync call is not completed before the waiting time expires.

See KB 2605597 for details

https://support.microsoft.com/kb/2605597

How do I parse command line arguments in Bash?

I have write a bash helper to write a nice bash tool

project home: https://gitlab.mbedsys.org/mbedsys/bashopts

example:

#!/bin/bash -ei

# load the library
. bashopts.sh

# Enable backtrace dusplay on error
trap 'bashopts_exit_handle' ERR

# Initialize the library
bashopts_setup -n "$0" -d "This is myapp tool description displayed on help message" -s "$HOME/.config/myapprc"

# Declare the options
bashopts_declare -n first_name -l first -o f -d "First name" -t string -i -s -r
bashopts_declare -n last_name -l last -o l -d "Last name" -t string -i -s -r
bashopts_declare -n display_name -l display-name -t string -d "Display name" -e "\$first_name \$last_name"
bashopts_declare -n age -l number -d "Age" -t number
bashopts_declare -n email_list -t string -m add -l email -d "Email adress"

# Parse arguments
bashopts_parse_args "$@"

# Process argument
bashopts_process_args

will give help:

NAME:
    ./example.sh - This is myapp tool description displayed on help message

USAGE:
    [options and commands] [-- [extra args]]

OPTIONS:
    -h,--help                          Display this help
    -n,--non-interactive true          Non interactive mode - [$bashopts_non_interactive] (type:boolean, default:false)
    -f,--first "John"                  First name - [$first_name] (type:string, default:"")
    -l,--last "Smith"                  Last name - [$last_name] (type:string, default:"")
    --display-name "John Smith"        Display name - [$display_name] (type:string, default:"$first_name $last_name")
    --number 0                         Age - [$age] (type:number, default:0)
    --email                            Email adress - [$email_list] (type:string, default:"")

enjoy :)

LEFT JOIN only first row

I want to give a more generalized answer. One that will handle any case when you want to select only the first item in a LEFT JOIN.

You can use a subquery that GROUP_CONCATS what you want (sorted, too!), then just split the GROUP_CONCAT'd result and take only its first item, like so...

LEFT JOIN Person ON Person.id = (
    SELECT SUBSTRING_INDEX(
        GROUP_CONCAT(FirstName ORDER BY FirstName DESC SEPARATOR "_" ), '_', 1)
    ) FROM Person
);

Since we have DESC as our ORDER BY option, this will return a Person id for someone like "Zack". If we wanted someone with the name like "Andy", we would change ORDER BY FirstName DESC to ORDER BY FirstName ASC.

This is nimble, as this places the power of ordering totally within your hands. But, after much testing, it will not scale well in a situation with lots of users and lots of data.

It is, however, useful in running data-intensive reports for admin.

Failed to execute goal org.apache.maven.plugins:maven-surefire-plugin:2.12:test (default-test) on project.

Here is the simplest way to resolve this error:

1) Go to your pom.xml file path

2) And edit the pom.xml like:

<plugins>
    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-surefire-plugin</artifactId>
        <version>2.12</version>
    </plugin>
</plugins>

3) Save the file That's it.

How do I sort a list of datetime or date objects?

You're getting None because list.sort() it operates in-place, meaning that it doesn't return anything, but modifies the list itself. You only need to call a.sort() without assigning it to a again.

There is a built in function sorted(), which returns a sorted version of the list - a = sorted(a) will do what you want as well.

pip is not able to install packages correctly: Permission denied error

On a Mac, you need to use this command:

STATIC_DEPS=true sudo pip install lxml

Addition for BigDecimal

The BigDecimal is immutable so you need to do this:

BigDecimal result = test.add(new BigDecimal(30));
System.out.println(result);

'int' object has no attribute '__getitem__'

you can also covert int to str first and assign index to it then again convert it to int like this:

int(str(x)[n]) //where x is an integer value

href overrides ng-click in Angular.js

Just write ng-click before href ..It worked for me

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
  <head>_x000D_
    <script data-require="[email protected]" data-semver="1.5.0" src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.0/angular.js"></script>_x000D_
    <script>_x000D_
    angular.module("module",[])_x000D_
.controller("controller",function($scope){_x000D_
  _x000D_
  $scope.func =function(){_x000D_
    console.log("d");_x000D_
  }_x000D_
  _x000D_
})</script>_x000D_
  </head>_x000D_
_x000D_
  <body ng-app="module" ng-controller="controller">_x000D_
    <h1>Hello ..</h1>_x000D_
    <a ng-click="func()" href="someplace.html">Take me there</a>_x000D_
  </body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

Do I need to compile the header files in a C program?

I think we do need preprocess(maybe NOT call the compile) the head file. Because from my understanding, during the compile stage, the head file should be included in c file. For example, in test.h we have

typedef enum{
    a,
    b,
    c
}test_t

and in test.c we have

void foo()
{
    test_t test;
    ...
}

during the compile, i think the compiler will put the code in head file and c file together and code in head file will be pre-processed and substitute the code in c file. Meanwhile, we'd better to define the include path in makefile.

How can I install a .ipa file to my iPhone simulator

For Xcode 10, here's an easy way that worked for me for a debug IPA (development profiles)

  1. Unzip the IPA to get the Payload folder.
  2. Within the Payload folder is the app executable.
  3. Drag and drop the app to an open simulator. (You might see a green add button when you drag it over the simulator)

It should install that app on that simulator.

Calculating the difference between two Java date instances

I liked the TimeUnit-based approach until I found out that it only covers the trivial cases where the number of how many units of one timeunit are in the next higher unit is fixed. This breaks apart when you want to know how many months, year, etc are in between.

here is a counting approach, not as efficient as some others, but it seems to work for me and takes into account DST, too.

public static String getOffsetAsString( Calendar cNow, Calendar cThen) {
    Calendar cBefore;
    Calendar cAfter;
    if ( cNow.getTimeInMillis() < cThen.getTimeInMillis()) {
        cBefore = ( Calendar) cNow.clone();
        cAfter = cThen;
    } else {
        cBefore = ( Calendar) cThen.clone();
        cAfter = cNow;
    }
    // compute diff
    Map<Integer, Long> diffMap = new HashMap<Integer, Long>();
    int[] calFields = { Calendar.YEAR, Calendar.MONTH, Calendar.DAY_OF_MONTH, Calendar.HOUR_OF_DAY, Calendar.MINUTE, Calendar.SECOND, Calendar.MILLISECOND};
    for ( int i = 0; i < calFields.length; i++) {
        int field = calFields[ i];
        long    d = computeDist( cAfter, cBefore, field);
        diffMap.put( field, d);
    }
    final String result = String.format( "%dY %02dM %dT %02d:%02d:%02d.%03d",
            diffMap.get( Calendar.YEAR), diffMap.get( Calendar.MONTH), diffMap.get( Calendar.DAY_OF_MONTH), diffMap.get( Calendar.HOUR_OF_DAY), diffMap.get( Calendar.MINUTE), diffMap.get( Calendar.SECOND), diffMap.get( Calendar.MILLISECOND));
    return result;
}

private static int computeDist( Calendar cAfter, Calendar cBefore, int field) {
    cBefore.setLenient( true);
    System.out.print( "D " + new Date( cBefore.getTimeInMillis()) + " --- " + new Date( cAfter.getTimeInMillis()) + ": ");
    int count = 0;
    if ( cAfter.getTimeInMillis() > cBefore.getTimeInMillis()) {
        int fVal = cBefore.get( field);
        while ( cAfter.getTimeInMillis() >= cBefore.getTimeInMillis()) {
            count++;
            fVal = cBefore.get( field);
            cBefore.set( field, fVal + 1);
            System.out.print( count + "/"  + ( fVal + 1) + ": " + new Date( cBefore.getTimeInMillis()) + " ] ");
        }
        int result = count - 1;
        cBefore.set( field, fVal);
        System.out.println( "" + result + " at: " + field + " cb = " + new Date( cBefore.getTimeInMillis()));
        return result;
    }
    return 0;
}

How to properly validate input values with React.JS?

Use onChange={this.handleChange.bind(this, "name") method and value={this.state.fields["name"]} on input text field and below that create span element to show error, see the below example.

export default class Form extends Component {

  constructor(){
    super()
    this.state ={
       fields: {
         name:'',
         email: '',
         message: ''
       },
       errors: {},
       disabled : false
    }
  }

  handleValidation(){
       let fields = this.state.fields;
       let errors = {};
       let formIsValid = true;

       if(!fields["name"]){
          formIsValid = false;
          errors["name"] = "Name field cannot be empty";
       }

       if(typeof fields["name"] !== "undefined" && !fields["name"] === false){
          if(!fields["name"].match(/^[a-zA-Z]+$/)){
             formIsValid = false;
             errors["name"] = "Only letters";
          }
       }

       if(!fields["email"]){
          formIsValid = false;
          errors["email"] = "Email field cannot be empty";
       }

       if(typeof fields["email"] !== "undefined" && !fields["email"] === false){
          let lastAtPos = fields["email"].lastIndexOf('@');
          let lastDotPos = fields["email"].lastIndexOf('.');

          if (!(lastAtPos < lastDotPos && lastAtPos > 0 && fields["email"].indexOf('@@') === -1 && lastDotPos > 2 && (fields["email"].length - lastDotPos) > 2)) {
             formIsValid = false;
             errors["email"] = "Email is not valid";
           }
      }

      if(!fields["message"]){
         formIsValid = false;
         errors["message"] = " Message field cannot be empty";
      }

      this.setState({errors: errors});
      return formIsValid;
  }

  handleChange(field, e){
      let fields = this.state.fields;
      fields[field] = e.target.value;
      this.setState({fields});
  }

  handleSubmit(e){
      e.preventDefault();
      if(this.handleValidation()){
          console.log('validation successful')
        }else{
          console.log('validation failed')
        }
  }

  render(){
    return (
      <form onSubmit={this.handleSubmit.bind(this)} method="POST">
          <div className="row">
            <div className="col-25">
                <label htmlFor="name">Name</label>
            </div>
            <div className="col-75">
                <input type="text" placeholder="Enter Name"  refs="name" onChange={this.handleChange.bind(this, "name")} value={this.state.fields["name"]}/>
                <span style={{color: "red"}}>{this.state.errors["name"]}</span>
            </div>
          </div>
          <div className="row">
            <div className="col-25">
              <label htmlFor="exampleInputEmail1">Email address</label>
            </div>
            <div className="col-75">
                <input type="email" placeholder="Enter Email" refs="email" aria-describedby="emailHelp" onChange={this.handleChange.bind(this, "email")} value={this.state.fields["email"]}/>
                <span style={{color: "red"}}>{this.state.errors["email"]}</span>
            </div>
          </div>
          <div className="row">
            <div className="col-25">
                <label htmlFor="message">Message</label>
            </div>
            <div className="col-75">
                <textarea type="text" placeholder="Enter Message" rows="5" refs="message" onChange={this.handleChange.bind(this, "message")} value={this.state.fields["message"]}></textarea>
                <span style={{color: "red"}}>{this.state.errors["message"]}</span>
            </div>
          </div>
          <div className="row">
            <button type="submit" disabled={this.state.disabled}>{this.state.disabled ? 'Sending...' : 'Send'}</button>
          </div>
      </form>
    )
  }
}

What does a bitwise shift (left or right) do and what is it used for?

Left bit shifting to multiply by any power of two. Right bit shifting to divide by any power of two.

x = x << 5; // Left shift
y = y >> 5; // Right shift

In C/C++ it can be written as,

#include <math.h>

x = x * pow(2, 5);
y = y / pow(2, 5);

Android Material: Status bar color won't change

As others have also mentioned, this can be readily solved by adding the following to the onCreate() of the Activity:

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        getWindow().addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
        getWindow().clearFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
        getWindow().setStatusBarColor(ContextCompat.getColor(this, R.color.primary_dark));
    }

However, the important point I want to add here is that in some cases, even the above does not change the status bar color. For example, when using MikePenz library for Navigation Drawer, it implicityly overrides the status bar color, so that you need to manually add the following for it to work:

.withStatusBarColorRes(R.color.status_bar_color)

count distinct values in spreadsheet

This works if you just want the count of unique values in e.g. the following range

=counta(unique(B4:B21))

Filename timestamp in Windows CMD batch script getting truncated

See Stack Overflow question How to get current datetime on Windows command line, in a suitable format for using in a filename?.

Create a file, date.bat:

@echo off
For /f "tokens=2-4 delims=/ " %%a in ('date /t') do (set mydate=%%c-%%a-%%b)
For /f "tokens=1-3 delims=/:/ " %%a in ('time /t') do (set mytime=%%a-%%b-%%c)
set mytime=%mytime: =% 
echo %mydate%_%mytime%

Run date.bat:

C:\>date.bat
2012-06-14_12-47-PM

UPDATE:

You can also do it with one line like this:

for /f "tokens=2-8 delims=.:/ " %%a in ("%date% %time%") do set DateNtime=%%c-%%a-%%b_%%d-%%e-%%f.%%g

Including external HTML file to another HTML file

You're looking for the <iframe> tag, or, better yet, a server-side templating language.

Simple check for SELECT query empty result

SELECT count(*) as count FROM service s WHERE s.service_id = ?;

test if count == 0 .

More baroquely:

select case when (SELECT count(*) as count FROM service s WHERE s.service_id = ?) = 0 then 'No rows, bro!' else 'You got data!" end as stupid_message;

MySQL timestamp select date range

This SQL query will extract the data for you. It is easy and fast.

SELECT *
  FROM table_name
  WHERE extract( YEAR_MONTH from timestamp)="201010";

When and why do I need to use cin.ignore() in C++?

It is better to use scanf(" %[^\n]",str) in c++ than cin.ignore() after cin>> statement.To do that first you have to include < cstdio > header.

Converting a double to an int in C#

In the provided example your decimal is 8.6. Had it been 8.5 or 9.5, the statement i1 == i2 might have been true. Infact it would have been true for 8.5, and false for 9.5.

Explanation:

Regardless of the decimal part, the second statement, int i2 = (int)score will discard the decimal part and simply return you the integer part. Quite dangerous thing to do, as data loss might occur.

Now, for the first statement, two things can happen. If the decimal part is 5, that is, it is half way through, a decision is to be made. Do we round up or down? In C#, the Convert class implements banker's rounding. See this answer for deeper explanation. Simply put, if the number is even, round down, if the number is odd, round up.

E.g. Consider:

        double score = 8.5;
        int i1 = Convert.ToInt32(score); // 8
        int i2 = (int)score;             // 8

        score += 1;
        i1 = Convert.ToInt32(score);     // 10
        i2 = (int)score;                 // 9

How to use a FolderBrowserDialog from a WPF application

The advantage of passing an owner handle is that the FolderBrowserDialog will not be modal to that window. This prevents the user from interacting with your main application window while the dialog is active.

Case insensitive 'Contains(string)'

You could use the String.IndexOf Method and pass StringComparison.OrdinalIgnoreCase as the type of search to use:

string title = "STRING";
bool contains = title.IndexOf("string", StringComparison.OrdinalIgnoreCase) >= 0;

Even better is defining a new extension method for string:

public static class StringExtensions
{
    public static bool Contains(this string source, string toCheck, StringComparison comp)
    {
        return source?.IndexOf(toCheck, comp) >= 0;
    }
}

Note, that null propagation ?. is available since C# 6.0 (VS 2015), for older versions use

if (source == null) return false;
return source.IndexOf(toCheck, comp) >= 0;

USAGE:

string title = "STRING";
bool contains = title.Contains("string", StringComparison.OrdinalIgnoreCase);

How to generate classes from wsdl using Maven and wsimport?

To generate classes from WSDL, all you need is build-helper-maven-plugin and jaxws-maven-plugin in your pom.xml
Make sure you have placed wsdl under folder src/main/resources/wsdl and corresponding schema in src/main/resources/schema, run command "mvn generate-sources" from Project root directory.

C:/Project root directory > mvn generate-sources

generated java classes can be located under folder

target/generated/src/main/java/com/raps/code/generate/ws.

pom.xml snippet

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>build-helper-maven-plugin</artifactId>
    <version>1.9</version>
    <executions>
        <execution>
            <id>add-source</id>
            <phase>generate-sources</phase>
            <goals><goal>add-source</goal></goals>
            <configuration>
                <sources>
                    <source>${project.build.directory}/generated/src/main/java</source>
                </sources>
            </configuration>
        </execution>
    </executions>
</plugin>

<plugin>
    <groupId>org.codehaus.mojo</groupId>
    <artifactId>jaxws-maven-plugin</artifactId>
    <version>1.12</version>
    <configuration>
        <wsdlDirectory>${project.basedir}/src/main/resources/wsdl</wsdlDirectory>
        <packageName>com.raps.code.generate.ws</packageName>
        <keep>true</keep>
        <sourceDestDir>${project.build.directory}/generated/src/main/java</sourceDestDir>
    </configuration>
    <executions>
        <execution> 
            <id>myImport</id>
            <goals><goal>wsimport</goal></goals>
        </execution>
    </executions>
</plugin>

How to add onload event to a div element

I had the same question and was trying to get a Div to load a scroll script, using onload or load. The problem I found was that it would always work before the Div could open, not during or after, so it wouldn't really work.

Then I came up with this as a work around.

<body>

<span onmouseover="window.scrollTo(0, document.body.scrollHeight);" 
onmouseout="window.scrollTo(0, document.body.scrollHeight);">

<div id="">
</div>

<a href="" onclick="window.scrollTo(0, document.body.scrollHeight);">Link to open Div</a>

</span>
</body>

I placed the Div inside a Span and gave the Span two events, a mouseover and a mouseout. Then below that Div, I placed a link to open the Div, and gave that link an event for onclick. All events the exact same, to make the page scroll down to bottom of page. Now when the button to open the Div is clicked, the page will jump down part way, and the Div will open above the button, causing the mouseover and mouseout events to help push the scroll down script. Then any movement of the mouse at that point will push the script one last time.

$(document).on("click"... not working?

if this code does not work even under document ready, most probable you assigned a return false; somewhere in your js file to that button, if it is button try to change it to a ,span, anchor or div and test if it is working.

$(document).on("click","#test-element",function() {
        alert("click bound to document listening for #test-element");
});

Format SQL in SQL Server Management Studio

There is a special trick I discovered by accident.

  1. Select the query you wish to format.
  2. Ctrl+Shift+Q (This will open your query in the query designer)
  3. Then just go OK Voila! Query designer will format your query for you. Caveat is that you can only do this for statements and not procedural code, but its better than nothing.

Check if string has space in between (or anywhere)

If indeed the goal is to see if a string contains the actual space character (as described in the title), as opposed to any other sort of whitespace characters, you can use:

string s = "Hello There";
bool fHasSpace = s.Contains(" ");

If you're looking for ways to detect whitespace, there's several great options below.

Undefined symbols for architecture armv7

I only added the libz.1.2.5.dylib to my project and it worked like a charm.

Steps -

  1. Go to Build Phases.
  2. Link Binary With library - use the '+' button to choose frameworks and libraries to add.
  3. Select libz.1.2.5.dylib from the list.
  4. Build and run.

"Fatal error: Unable to find local grunt." when running "grunt" command

You have to install grunt in your project folder

  1. create your package.json

    $ npm init
    
  2. install grunt for this project, this will be installed under node_modules/. --save-dev will add this module to devDependency in your package.json

    $ npm install grunt --save-dev
    
  3. then create gruntfile.js and run

    $ grunt 
    

How to get the jQuery $.ajax error response text?

For me, this simply works:

error: function(xhr, status, error) {
  alert(xhr.responseText);
}

Pad with leading zeros

You can do this with a string datatype. Use the PadLeft method:

var myString = "1";
myString = myString.PadLeft(myString.Length + 5, '0');

000001

Using union and order by clause in mysql

Don't forget, union all is a way to add records to a record set without sorting or merging (as opposed to union).

So for example:

select * from (
    select col1, col2
    from table a
    <....>
    order by col3
    limit by 200
) a
union all
select * from (
    select cola, colb
    from table b
    <....>
    order by colb
    limit by 300
) b

It keeps the individual queries clearer and allows you to sort by different parameters in each query. However by using the selected answer's way it might become clearer depending on complexity and how related the data is because you are conceptualizing the sort. It also allows you to return the artificial column to the querying program so it has a context it can sort by or organize.

But this way has the advantage of being fast, not introducing extra variables, and making it easy to separate out each query including the sort. The ability to add a limit is simply an extra bonus.

And of course feel free to turn the union all into a union and add a sort for the whole query. Or add an artificial id, in which case this way makes it easy to sort by different parameters in each query, but it otherwise is the same as the accepted answer.

How to instantiate a javascript class in another js file?

Possible Suggestions to make it work:

Some modifications (U forgot to include a semicolon in the statement this.getName=function(){...} it should be this.getName=function(){...};)

function Customer(){
this.name="Jhon";
this.getName=function(){
return this.name;
};
}

(This might be one of the problem.)

and

Make sure U Link the JS files in the correct order

<script src="file1.js" type="text/javascript"></script>
<script src="file2.js" type="text/javascript"></script>

java: run a function after a specific number of seconds

ScheduledThreadPoolExecutor has this ability, but it's quite heavyweight.

Timer also has this ability but opens several thread even if used only once.

Here's a simple implementation with a test (signature close to Android's Handler.postDelayed()):

public class JavaUtil {
    public static void postDelayed(final Runnable runnable, final long delayMillis) {
        final long requested = System.currentTimeMillis();
        new Thread(new Runnable() {
            @Override
            public void run() {
                // The while is just to ignore interruption.
                while (true) {
                    try {
                        long leftToSleep = requested + delayMillis - System.currentTimeMillis();
                        if (leftToSleep > 0) {
                            Thread.sleep(leftToSleep);
                        }
                        break;
                    } catch (InterruptedException ignored) {
                    }
                }
                runnable.run();
            }
        }).start();
    }
}

Test:

@Test
public void testRunsOnlyOnce() throws InterruptedException {
    long delay = 100;
    int num = 0;
    final AtomicInteger numAtomic = new AtomicInteger(num);
    JavaUtil.postDelayed(new Runnable() {
        @Override
        public void run() {
            numAtomic.incrementAndGet();
        }
    }, delay);
    Assert.assertEquals(num, numAtomic.get());
    Thread.sleep(delay + 10);
    Assert.assertEquals(num + 1, numAtomic.get());
    Thread.sleep(delay * 2);
    Assert.assertEquals(num + 1, numAtomic.get());
}

Call-time pass-by-reference has been removed

Only call time pass-by-reference is removed. So change:

call_user_func($func, &$this, &$client ...

To this:

call_user_func($func, $this, $client ...

&$this should never be needed after PHP4 anyway period.

If you absolutely need $client to be passed by reference, update the function ($func) signature instead (function func(&$client) {)

How to use wait and notify in Java without IllegalMonitorStateException?

You can only call notify on objects where you own their monitor. So you need something like

synchronized(threadObject)
{
   threadObject.notify();
}

How to set an environment variable from a Gradle build?

This looks like an old thread but there is one more variant of how we can set an environment variable in the Gradle task.

task runSomeRandomTask(type: NpmTask, dependsOn: [npmInstall]) {
    environment = [ 'NODE_ENV': 'development', BASE_URL: '3000' ]
    args = ['run']
}

The above Gradle task integrates the Gradle and npm tasks.

This way we can pass multiple environment variables. Hope this helps to broaden the understanding which the answers above have already provided. Cheers!!

How do you create a Swift Date object?

Personally I think it should be a failable initialiser:

extension Date {

    init?(dateString: String) {
        let dateStringFormatter = DateFormatter()
        dateStringFormatter.dateFormat = "yyyy-MM-dd"
        if let d = dateStringFormatter.date(from: dateString) {
            self.init(timeInterval: 0, since: d)
        } else {
            return nil
        }
    }
}

Otherwise a string with an invalid format will raise an exception.

Merging dictionaries in C#

Simplified from use compared with my earlier answer with a bool default of non-destructive merge if existing or overwrite entirely if true rather than using an enum. It still suits my own needs without any fancier code ever being required:

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

public static partial class Extensions
{
    public static void Merge<K, V>(this IDictionary<K, V> target, IDictionary<K, V> source, bool overwrite = false)
    {
        source.ToList().ForEach(_ => {
            if ((!target.ContainsKey(_.Key)) || overwrite)
                target[_.Key] = _.Value;
        });
    }
}

Is there a way to avoid null check before the for-each loop iteration starts?

It's already 2017, and you can now use Apache Commons Collections4

The usage:

for(Object obj : CollectionUtils.emptyIfNull(list1)){
    // Do your stuff
}

How to get a shell environment variable in a makefile?

If you've exported the environment variable:

export demoPath=/usr/local/demo

you can simply refer to it by name in the makefile (make imports all the environment variables you have set):

DEMOPATH = ${demoPath}    # Or $(demoPath) if you prefer.

If you've not exported the environment variable, it is not accessible until you do export it, or unless you pass it explicitly on the command line:

make DEMOPATH="${demoPath}" …

If you are using a C shell derivative, substitute setenv demoPath /usr/local/demo for the export command.

Render Partial View Using jQuery in ASP.NET MVC

I have used ajax load to do this:

$('#user_content').load('@Url.Action("UserDetails","User")');

In Swift how to call method with parameters on GCD main thread?

Swift 3+ & Swift 4 version:

DispatchQueue.main.async {
    print("Hello")
}

Swift 3 and Xcode 9.2:

dispatch_async_on_main_queue {
    print("Hello")
}

Android - Set text to TextView

In your layout. Your Texto should not contain (android:text=...). I would remove this line. Either keep the Java string OR the (android:text=...)

What is the difference between char array and char pointer in C?

You're not allowed to change the contents of a string constant, which is what the first p points to. The second p is an array initialized with a string constant, and you can change its contents.

Can we cast a generic object to a custom object type in javascript?

No.

But if you're looking to treat your person1 object as if it were a Person, you can call methods on Person's prototype on person1 with call:

Person.prototype.getFullNamePublic = function(){
    return this.lastName + ' ' + this.firstName;
}
Person.prototype.getFullNamePublic.call(person1);

Though this obviously won't work for privileged methods created inside of the Person constructor—like your getFullName method.

What's HTML character code 8203?

I have these characters show up in scripts where I do not desire them. I noticed because it ruins my HTML/CSS visual formatting : it makes a new text box.

Pretty sure a buggy editor is adding them... I suspect Komodo Edit for the Mac, in my case.

how to generate a unique token which expires after 24 hours?

Use Dictionary<string, DateTime> to store token with timestamp:

static Dictionary<string, DateTime> dic = new Dictionary<string, DateTime>();

Add token with timestamp whenever you create new token:

dic.Add("yourToken", DateTime.Now);

There is a timer running to remove any expired tokens out of dic:

 timer = new Timer(1000*60); //assume run in 1 minute
 timer.Elapsed += timer_Elapsed;

 static void timer_Elapsed(object sender, ElapsedEventArgs e)
    {
        var expiredTokens = dic.Where(p => p.Value.AddDays(1) <= DateTime.Now)
                              .Select(p => p.Key);

        foreach (var key in expiredTokens)
            dic.Remove(key);
    }

So, when you authenticate token, just check whether token exists in dic or not.

How to get the Facebook user id using the access token

The facebook acess token looks similar too "1249203702|2.h1MTNeLqcLqw__.86400.129394400-605430316|-WE1iH_CV-afTgyhDPc"

if you extract the middle part by using | to split you get

2.h1MTNeLqcLqw__.86400.129394400-605430316

then split again by -

the last part 605430316 is the user id.

Here is the C# code to extract the user id from the access token:

   public long ParseUserIdFromAccessToken(string accessToken)
   {
        Contract.Requires(!string.isNullOrEmpty(accessToken);

        /*
         * access_token:
         *   1249203702|2.h1MTNeLqcLqw__.86400.129394400-605430316|-WE1iH_CV-afTgyhDPc
         *                                               |_______|
         *                                                   |
         *                                                user id
         */

        long userId = 0;

        var accessTokenParts = accessToken.Split('|');

        if (accessTokenParts.Length == 3)
        {
            var idPart = accessTokenParts[1];
            if (!string.IsNullOrEmpty(idPart))
            {
                var index = idPart.LastIndexOf('-');
                if (index >= 0)
                {
                    string id = idPart.Substring(index + 1);
                    if (!string.IsNullOrEmpty(id))
                    {
                        return id;
                    }
                }
            }
        }

        return null;
    }

WARNING: The structure of the access token is undocumented and may not always fit the pattern above. Use it at your own risk.

Update Due to changes in Facebook. the preferred method to get userid from the encrypted access token is as follows:

try
{
    var fb = new FacebookClient(accessToken);
    var result = (IDictionary<string, object>)fb.Get("/me?fields=id");
    return (string)result["id"];
}
catch (FacebookOAuthException)
{
    return null;
}

How to call a web service from jQuery

I blogged about how to consume a WCF service using jQuery:

http://yoavniran.wordpress.com/2009/08/02/creating-a-webservice-proxy-with-jquery/

The post shows how to create a service proxy straight up in javascript.

Is multiplication and division using shift operators in C actually faster?

Short answer: Not likely.

Long answer: Your compiler has an optimizer in it that knows how to multiply as quickly as your target processor architecture is capable. Your best bet is to tell the compiler your intent clearly (i.e. i*2 rather than i << 1) and let it decide what the fastest assembly/machine code sequence is. It's even possible that the processor itself has implemented the multiply instruction as a sequence of shifts & adds in microcode.

Bottom line--don't spend a lot of time worrying about this. If you mean to shift, shift. If you mean to multiply, multiply. Do what is semantically clearest--your coworkers will thank you later. Or, more likely, curse you later if you do otherwise.

How can I do a line break (line continuation) in Python?

If you want to break your line because of a long literal string, you can break that string into pieces:

long_string = "a very long string"
print("a very long string")

will be replaced by

long_string = (
  "a "
  "very "
  "long "
  "string"
)
print(
  "a "
  "very "
  "long "
  "string"
)

Output for both print statements:

a very long string

Notice the parenthesis in the affectation.

Notice also that breaking literal strings into pieces allows to use the literal prefix only on parts of the string and mix the delimiters:

s = (
  '''2+2='''
  f"{2+2}"
)

The difference between sys.stdout.write and print?

print is just a thin wrapper that formats the inputs (modifiable, but by default with a space between args and newline at the end) and calls the write function of a given object. By default this object is sys.stdout, but you can pass a file using the "chevron" form. For example:

print >> open('file.txt', 'w'), 'Hello', 'World', 2+3

See: https://docs.python.org/2/reference/simple_stmts.html?highlight=print#the-print-statement


In Python 3.x, print becomes a function, but it is still possible to pass something other than sys.stdout thanks to the fileargument.

print('Hello', 'World', 2+3, file=open('file.txt', 'w'))

See https://docs.python.org/3/library/functions.html#print


In Python 2.6+, print is still a statement, but it can be used as a function with

from __future__ import print_function

Update: Bakuriu commented to point out that there is a small difference between the print function and the print statement (and more generally between a function and a statement).

In case of an error when evaluating arguments:

print "something", 1/0, "other" #prints only something because 1/0 raise an Exception

print("something", 1/0, "other") #doesn't print anything. The function is not called

Stopping fixed position scrolling at a certain point?

Here's a quick jQuery plugin I just wrote that can do what you require:

$.fn.followTo = function (pos) {
    var $this = this,
        $window = $(window);

    $window.scroll(function (e) {
        if ($window.scrollTop() > pos) {
            $this.css({
                position: 'absolute',
                top: pos
            });
        } else {
            $this.css({
                position: 'fixed',
                top: 0
            });
        }
    });
};

$('#yourDiv').followTo(250);

See working example →

Jenkins fails when running "service start jenkins"

Adding on to what has been already answered by Guna Sekaran. Jenkins need the user jenkins to be present in order to run the jenkins as a service.

To add user fire 'useradd jenkins' as root and fire 'passwd jenkins' as root before starting Jenkins as a service.

Eclipse: Error ".. overlaps the location of another project.." when trying to create new project

Go to the actual FILE menu and create a new general project.

If the project type isn't recognized, preventing one of these import methods from working, then try this. Once you add the generic project, you can then add support for whatever language you require.

Processing $http response in service

I really don't like the fact that, because of the "promise" way of doing things, the consumer of the service that uses $http has to "know" about how to unpack the response.

I just want to call something and get the data out, similar to the old $scope.items = Data.getData(); way, which is now deprecated.

I tried for a while and didn't come up with a perfect solution, but here's my best shot (Plunker). It may be useful to someone.

app.factory('myService', function($http) {
  var _data;  // cache data rather than promise
  var myService = {};

  myService.getData = function(obj) { 
    if(!_data) {
      $http.get('test.json').then(function(result){
        _data = result.data;
        console.log(_data);  // prove that it executes once
        angular.extend(obj, _data);
      }); 
    } else {  
      angular.extend(obj, _data);
    }
  };

  return myService;
}); 

Then controller:

app.controller('MainCtrl', function( myService,$scope) {
  $scope.clearData = function() {
    $scope.data = Object.create(null);
  };
  $scope.getData = function() {
    $scope.clearData();  // also important: need to prepare input to getData as an object
    myService.getData($scope.data); // **important bit** pass in object you want to augment
  };
});

Flaws I can already spot are

  • You have to pass in the object which you want the data added to, which isn't an intuitive or common pattern in Angular
  • getData can only accept the obj parameter in the form of an object (although it could also accept an array), which won't be a problem for many applications, but it's a sore limitation
  • You have to prepare the input object $scope.data with = {} to make it an object (essentially what $scope.clearData() does above), or = [] for an array, or it won't work (we're already having to assume something about what data is coming). I tried to do this preparation step IN getData, but no luck.

Nevertheless, it provides a pattern which removes controller "promise unwrap" boilerplate, and might be useful in cases when you want to use certain data obtained from $http in more than one place while keeping it DRY.

git ignore exception

!foo.dll in .gitignore, or (every time!) git add -f foo.dll

Error: TypeError: $(...).dialog is not a function

I had a similar problem and in my case, the issue was different (I am using Django templates).

The order of JS was incorrect (I know that's the first thing you check but I was almost sure that that was not the case, but it was). The js calling the dialog was called before jqueryUI library was called.

I am using Django, so was inheriting a template and using {{super.block}} to inherit code from the block as well to the template. I had to move {{super.block}} at the end of the block which solved the issue. The js calling the dialog was declared in the Media class in Django's admin.py. I spent more than an hour to figure it out. Hope this helps someone.

Decode UTF-8 with Javascript

This should work:

// http://www.onicos.com/staff/iz/amuse/javascript/expert/utf.txt

/* utf.js - UTF-8 <=> UTF-16 convertion
 *
 * Copyright (C) 1999 Masanao Izumo <[email protected]>
 * Version: 1.0
 * LastModified: Dec 25 1999
 * This library is free.  You can redistribute it and/or modify it.
 */

function Utf8ArrayToStr(array) {
    var out, i, len, c;
    var char2, char3;

    out = "";
    len = array.length;
    i = 0;
    while(i < len) {
    c = array[i++];
    switch(c >> 4)
    { 
      case 0: case 1: case 2: case 3: case 4: case 5: case 6: case 7:
        // 0xxxxxxx
        out += String.fromCharCode(c);
        break;
      case 12: case 13:
        // 110x xxxx   10xx xxxx
        char2 = array[i++];
        out += String.fromCharCode(((c & 0x1F) << 6) | (char2 & 0x3F));
        break;
      case 14:
        // 1110 xxxx  10xx xxxx  10xx xxxx
        char2 = array[i++];
        char3 = array[i++];
        out += String.fromCharCode(((c & 0x0F) << 12) |
                       ((char2 & 0x3F) << 6) |
                       ((char3 & 0x3F) << 0));
        break;
    }
    }

    return out;
}

Check out the JSFiddle demo.

Also see the related questions: here and here

Can a foreign key refer to a primary key in the same table?

Sure, why not? Let's say you have a Person table, with id, name, age, and parent_id, where parent_id is a foreign key to the same table. You wouldn't need to normalize the Person table to Parent and Child tables, that would be overkill.

Person
| id |  name | age | parent_id |
|----|-------|-----|-----------|
|  1 |   Tom |  50 |      null |
|  2 | Billy |  15 |         1 |

Something like this.

I suppose to maintain consistency, there would need to be at least 1 null value for parent_id, though. The one "alpha male" row.

EDIT: As the comments show, Sam found a good reason not to do this. It seems that in MySQL when you attempt to make edits to the primary key, even if you specify CASCADE ON UPDATE it won’t propagate the edit properly. Although primary keys are (usually) off-limits to editing in production, it is nevertheless a limitation not to be ignored. Thus I change my answer to:- you should probably avoid this practice unless you have pretty tight control over the production system (and can guarantee no one will implement a control that edits the PKs). I haven't tested it outside of MySQL.

How to raise a ValueError?

raise ValueError('could not find %c in %s' % (ch,str))

Comparing two columns, and returning a specific adjacent cell in Excel

Here is what needs to go in D1: =VLOOKUP(C1, $A$1:$B$4, 2, FALSE)

You should then be able to copy this down to the rest of column D.

How to get the unique ID of an object which overrides hashCode()?

Just to augment the other answers from a different angle.

If you want to reuse hashcode(s) from 'above' and derive new ones using your class' immutatable state, then a call to super will work. While this may/may not cascade all the way up to Object (i.e. some ancestor may not call super), it will allow you to derive hashcodes by reuse.

@Override
public int hashCode() {
    int ancestorHash = super.hashCode();
    // now derive new hash from ancestorHash plus immutable instance vars (id fields)
}

How to go to a URL using jQuery?

//As an HTTP redirect (back button will not work )
window.location.replace("http://www.google.com");

//like if you click on a link (it will be saved in the session history, 
//so the back button will work as expected)
window.location.href = "http://www.google.com";

Converting a string to a date in a cell

To accomodate both data scenarios you have, you will want to use this:

datevalue(text(a2,"mm/dd/yyyy"))

That will give you the date number representation for a cell that Excel has in date, or in text datatype.

javascript functions to show and hide divs

check this:

click here
<div id="benefits" style="display:none;">some input in here plus the close button
       <div id="upbutton"><a onclick="close(); return false;"></a></div>
</div>

Integration Testing POSTing an entire object to Spring MVC controller

Here is the method I made to transform recursively the fields of an object in a map ready to be used with a MockHttpServletRequestBuilder

public static void objectToPostParams(final String key, final Object value, final Map<String, String> map) throws IllegalAccessException {
    if ((value instanceof Number) || (value instanceof Enum) || (value instanceof String)) {
        map.put(key, value.toString());
    } else if (value instanceof Date) {
        map.put(key, new SimpleDateFormat("yyyy-MM-dd HH:mm").format((Date) value));
    } else if (value instanceof GenericDTO) {
        final Map<String, Object> fieldsMap = ReflectionUtils.getFieldsMap((GenericDTO) value);
        for (final Entry<String, Object> entry : fieldsMap.entrySet()) {
            final StringBuilder sb = new StringBuilder();
            if (!GenericValidator.isEmpty(key)) {
                sb.append(key).append('.');
            }
            sb.append(entry.getKey());
            objectToPostParams(sb.toString(), entry.getValue(), map);
        }
    } else if (value instanceof List) {
        for (int i = 0; i < ((List) value).size(); i++) {
            objectToPostParams(key + '[' + i + ']', ((List) value).get(i), map);
        }
    }
}

GenericDTO is a simple class extending Serializable

public interface GenericDTO extends Serializable {}

and here is the ReflectionUtils class

public final class ReflectionUtils {
    public static List<Field> getAllFields(final List<Field> fields, final Class<?> type) {
        if (type.getSuperclass() != null) {
            getAllFields(fields, type.getSuperclass());
        }
        // if a field is overwritten in the child class, the one in the parent is removed
        fields.addAll(Arrays.asList(type.getDeclaredFields()).stream().map(field -> {
            final Iterator<Field> iterator = fields.iterator();
            while(iterator.hasNext()){
                final Field fieldTmp = iterator.next();
                if (fieldTmp.getName().equals(field.getName())) {
                    iterator.remove();
                    break;
                }
            }
            return field;
        }).collect(Collectors.toList()));
        return fields;
    }

    public static Map<String, Object> getFieldsMap(final GenericDTO genericDTO) throws IllegalAccessException {
        final Map<String, Object> map = new HashMap<>();
        final List<Field> fields = new ArrayList<>();
        getAllFields(fields, genericDTO.getClass());
        for (final Field field : fields) {
            final boolean isFieldAccessible = field.isAccessible();
            field.setAccessible(true);
            map.put(field.getName(), field.get(genericDTO));
            field.setAccessible(isFieldAccessible);
        }
        return map;
    }
}

You can use it like

final MockHttpServletRequestBuilder post = post("/");
final Map<String, String> map = new TreeMap<>();
objectToPostParams("", genericDTO, map);
for (final Entry<String, String> entry : map.entrySet()) {
    post.param(entry.getKey(), entry.getValue());
}

I didn't tested it extensively, but it seems to work.

Django auto_now and auto_now_add

Is this cause for concern?

No, Django automatically adds it for you while saving the models, so, it is expected.

Side question: in my admin tool, those 2 fields aren't showing up. Is that expected?

Since these fields are auto added, they are not shown.

To add to the above, as synack said, there has been a debate on the django mailing list to remove this, because, it is "not designed well" and is "a hack"

Writing a custom save() on each of my models is much more pain than using the auto_now

Obviously you don't have to write it to every model. You can write it to one model and inherit others from it.

But, as auto_add and auto_now_add are there, I would use them rather than trying to write a method myself.

Https to http redirect using htaccess

Attempt 2 was close to perfect. Just modify it slightly:

RewriteEngine On
RewriteCond %{HTTPS} on
RewriteRule (.*) http://%{HTTP_HOST}%{REQUEST_URI} [R=301,L]

How can I set NODE_ENV=production on Windows?

Here is the non-command line method:

In Windows 7 or 10, type environment into the start menu search box, and select Edit the system environment variables.

Alternatively, navigate to Control Panel\System and Security\System, and click Advanced system settings

This should open up the System properties dialog box with the Advanced tab selected. At the bottom, you will see an Environment Variables... button. Click this.

System Dialog Box

The Environment Variables Dialog Box will open.

Environment Variable Dialog Box

At the bottom, under System variables, select New...This will open the New System Variable dialog box.

enter image description here

Enter the variable name and value, and click OK.

You will need to close all cmd prompts and restart your server for the new variable to be available to process.env. If it still doesn't show up, restart your machine.

What's the simplest way to list conflicted files in Git?

git status displays "both modified" next to files that have conflicts instead of "modified" or "new file", etc

Changing the image source using jQuery

There is no way of changing the image source with CSS.

Only possible way is using Javascript or any Javascript library like jQuery.

Logic-

The images are inside a div and there are no class or id with that image.

So logic will be select the elements inside the div where the images are located.

Then select all the images elements with loop and change the image src with Javascript / jQuery.

Example Code with demo output-

_x000D_
_x000D_
$(document).ready(function()_x000D_
{_x000D_
    $("button").click(function()_x000D_
    {_x000D_
      $("#d1 .c1 a").each(function()_x000D_
      {_x000D_
          $(this).children('img').attr('src', 'https://www.gravatar.com/avatar/e56672acdbce5d9eda58a178ade59ffe');_x000D_
      });_x000D_
    });_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.12.0/jquery.min.js"></script>_x000D_
_x000D_
<div id="d1">_x000D_
   <div class="c1">_x000D_
            <a href="#"><img src="img1_on.gif"></a>_x000D_
            <a href="#"><img src="img2_on.gif"></a>_x000D_
   </div>_x000D_
</div>_x000D_
_x000D_
<button>Change The Images</button>
_x000D_
_x000D_
_x000D_

HQL ERROR: Path expected for join

select u from UserGroup ug inner join ug.user u 
where ug.group_id = :groupId 
order by u.lastname

As a named query:

@NamedQuery(
  name = "User.findByGroupId",
  query =
    "SELECT u FROM UserGroup ug " +
    "INNER JOIN ug.user u WHERE ug.group_id = :groupId ORDER BY u.lastname"
)

Use paths in the HQL statement, from one entity to the other. See the Hibernate documentation on HQL and joins for details.

How to change CSS using jQuery?

wrong code:$("#myParagraph").css({"backgroundColor":"black","color":"white");

its missing "}" after white"

change it to this

 $("#myParagraph").css({"background-color":"black","color":"white"});

Performing a Stress Test on Web Application?

Try ZebraTester which is much easier to use than jMeter. I have used jMeter for a long time but the total setup time for a load test was always an issue. Although ZebraTester isn't open source, the time that I have saved in the last six months makes up for it. They also have a SaaS portal which can be used for quickly running tests using their load generators.

Convert python datetime to timestamp in milliseconds

For Python2.7 - modifying MYGz's answer to not strip milliseconds:

from datetime import datetime

d = datetime.strptime("20.12.2016 09:38:42,76", "%d.%m.%Y %H:%M:%S,%f").strftime('%s.%f')
d_in_ms = int(float(d)*1000)
print(d_in_ms)

print(datetime.fromtimestamp(float(d)))

Output:

1482248322760
2016-12-20 09:38:42.760000

Inline labels in Matplotlib

@Jan Kuiken's answer is certainly well-thought and thorough, but there are some caveats:

  • it does not work in all cases
  • it requires a fair amount of extra code
  • it may vary considerably from one plot to the next

A much simpler approach is to annotate the last point of each plot. The point can also be circled, for emphasis. This can be accomplished with one extra line:

from matplotlib import pyplot as plt

for i, (x, y) in enumerate(samples):
    plt.plot(x, y)
    plt.text(x[-1], y[-1], 'sample {i}'.format(i=i))

A variant would be to use ax.annotate.

ERROR 1044 (42000): Access denied for 'root' With All Privileges

The reason i could not delete some of the users via 'drop' statement was that there is a bug in Mysql http://bugs.mysql.com/bug.php?id=62255 with hostname containing upper case letters. The solution was running following query:

DELETE FROM mysql.user where host='Some_Host_With_UpperCase_Letters';

I am still trying to figure the other issue where the root user with all permissions are unable to grant privileges to new user for particular database

Jenkins: Failed to connect to repository

This is a very tricky issue - even if you're familiar with how things are working in https with certificates (OTOH if you see my workaround, it seems very logical :)

If you want to connect to a GIT repository via http(s) from shell, you would make sure to have the public certificate stored (as file) on your machine. Then you would add that certificate to your GIT configuration

git config [--global] http.sslCAInfo "certificate"

(replace "certificate" with the complete path/name of the PEM file :)

For shell usage you would as well e.g. supply a '.netrc' provding your credentials for the http-server login. Having done that, you shall be able to do a 'git clone https://...' without any interactive provisioning of credentials.

However, for the Jenkins-service it's a bit different ... Here, the jenkins process needs to be aware of the server certificate - and it doesn't use the shell settings (in the meaning of the global git configuration file '.gitconfig') :P

What I needed to do is to add another parameter to the startup options of Jenkins.

... -Djavax.net.ssl.trustStore="keystore" ...

(replace "keystore" with the complete path/name like explained below :)

Now copy the keystore file of your webserver holding the certificate to some path (I know this is a dirty hack and not exactly secure :) and refer to it with the '-Djavax.net.ssl.trustStore=' parameter.

Now the Jenkins service will accept the certificate from the webserver providing the repository via https. Configure the GIT repository URL like

https://yourserver.com/your-repositorypath

Note that you still require the '.netrc' under the jenkins-user home folder for the logon !!! Thus what I describe is to be seen as a workaround ... until a properly working credentials helper plugin is provided. IMHO this plugin (in its current version 1.9.4) is buggy.

I could never get the credentials-helper to work from Jenkins no matter what I tried :( At best I got to see some errors about the not accessible temporary credential helper file, etc. You can see lots of bugs reported about it in the Jenkins JIRA, but no fix.

So if somebody got it to work okay, please share the knowledge ...


P.S.: Using the Jenkins plugins in the following versions:

Credentials plugin 1.9.4, GIT client plugin 1.6.1, Jenkins GIT plugin 2.0.1

AccessDenied for ListObjects for S3 bucket when permissions are s3:*

I was unable to access to S3 because

  • first I configured key access on the instance (it was impossible to attach role after the launch then)
  • forgot about it for a few months
  • attached role to instance
  • tried to access. The configured key had higher priority than role, and access was denied because the user wasn't granted with necessary S3 permissions.

Solution: rm -rf .aws/credentials, then aws uses role.

Replace \n with actual new line in Sublime Text

On MAC

Step 1: Alt + Cmd + F . At the bottom, a window appears Step 2: Enable Regular Expression. Left side on the window, looks like .* Step 3: Enter text to you want to find in the Find input field Step 4: Enter replace text in the Replace input field Step 5: Click on Replace All - Right bottom.

replace field

How to determine if one array contains all elements of another array

a = [5, 1, 6, 14, 2, 8]
b = [2, 6, 15]

a - b
# => [5, 1, 14, 8]

b - a
# => [15]

(b - a).empty?
# => false

Jquery function return value

The return statement you have is stuck in the inner function, so it won't return from the outer function. You just need a little more code:

function getMachine(color, qty) {
    var returnValue = null;
    $("#getMachine li").each(function() {
        var thisArray = $(this).text().split("~");
        if(thisArray[0] == color&& qty>= parseInt(thisArray[1]) && qty<= parseInt(thisArray[2])) {
            returnValue = thisArray[3];
            return false; // this breaks out of the each
        }
    });
    return returnValue;
}

var retval = getMachine(color, qty);

Get city name using geolocation

Here's an easy function you can use to get it. I used axios to make the API request, but you can use anything else.

async function getCountry(lat, long) {
  const { data: { results } } = await axios.get(`https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${long}&key=${GOOGLE_API_KEY}`);
  const { address_components } = results[0];

  for (let i = 0; i < address_components.length; i++) {
    const { types, long_name } = address_components[i];

    if (types.indexOf("country") !== -1) return long_name;
  }
}

execute shell command from android

You should grab the standard input of the su process just launched and write down the command there, otherwise you are running the commands with the current UID.

Try something like this:

try{
    Process su = Runtime.getRuntime().exec("su");
    DataOutputStream outputStream = new DataOutputStream(su.getOutputStream());

    outputStream.writeBytes("screenrecord --time-limit 10 /sdcard/MyVideo.mp4\n");
    outputStream.flush();

    outputStream.writeBytes("exit\n");
    outputStream.flush();
    su.waitFor();
}catch(IOException e){
    throw new Exception(e);
}catch(InterruptedException e){
    throw new Exception(e);
}

How can I move all the files from one folder to another using the command line?

This command will move all the files in originalfolder to destinationfolder.

MOVE c:\originalfolder\* c:\destinationfolder

(However it wont move any sub-folders to the new location.)

To lookup the instructions for the MOVE command type this in a windows command prompt:

MOVE /?

HTML entity for check mark

HTML and XML entities are just a way of referencing a Unicode code-point in a way that reliably works regardless of the encoding of the actual page, making them useful for using esoteric Unicode characters in a page using 7-bit ASCII or some other encoding scheme, ideally on a one-off basis. They're also used to escape the <, >, " and & characters as these are reserved in SGML.

Anyway, Unicode has a number of tick/check characters, as per Wikipedia ( http://en.wikipedia.org/wiki/Tick_(check_mark) ).

Ideally you should save/store your HTML in a Unicode format like UTF-8 or 16, thus obviating the need to use HTML entities to represent a Unicode character. Nonetheless use: &#x2714; ✔.

&#x2714;

Is using hex notation and is the same as

$#10004;

(as 2714 in base 16 is the same as 10004 in base 10)

Working with a List of Lists in Java

Also this is an example of how to print List of List using advanced for loop:

public static void main(String[] args){
        int[] a={1,3, 7, 8, 3, 9, 2, 4, 10};
        List<List<Integer>> triplets;
        triplets=sumOfThreeNaive(a, 13);
        for (List<Integer> list : triplets){
            for (int triplet: list){
                System.out.print(triplet+" ");
            }
            System.out.println();
        }
    }

Oracle SqlDeveloper JDK path

The message seems to be out of date. In version 4 that setting exists in two files, and you need to change it in the other one, which is:

%APPDATA%\sqldeveloper\1.0.0.0.0\product.conf

Which you might need to expand to your actual APPDATA, which will be something like C:\Users\cprasad\AppData\Roaming. In that file you will see the SetJavaHome is currently going to be set to the path to your Java 1.8 location, so change that as you did in the sqldeveloper.conf:

SetJavaHome C:\Program Files\Java\jdk1.7.0_60\bin\

If the settig is blank (in both files, I think) then it should prompt you to pick the JDK location when you launch it, if you prefer.

Save classifier to disk in scikit-learn

In many cases, particularly with text classification it is not enough just to store the classifier but you'll need to store the vectorizer as well so that you can vectorize your input in future.

import pickle
with open('model.pkl', 'wb') as fout:
  pickle.dump((vectorizer, clf), fout)

future use case:

with open('model.pkl', 'rb') as fin:
  vectorizer, clf = pickle.load(fin)

X_new = vectorizer.transform(new_samples)
X_new_preds = clf.predict(X_new)

Before dumping the vectorizer, one can delete the stop_words_ property of vectorizer by:

vectorizer.stop_words_ = None

to make dumping more efficient. Also if your classifier parameters is sparse (as in most text classification examples) you can convert the parameters from dense to sparse which will make a huge difference in terms of memory consumption, loading and dumping. Sparsify the model by:

clf.sparsify()

Which will automatically work for SGDClassifier but in case you know your model is sparse (lots of zeros in clf.coef_) then you can manually convert clf.coef_ into a csr scipy sparse matrix by:

clf.coef_ = scipy.sparse.csr_matrix(clf.coef_)

and then you can store it more efficiently.

Check if a string is a valid Windows directory (folder) path

I actually disagree with SLaks. That solution did not work for me. Exception did not happen as expected. But this code worked for me:

if(System.IO.Directory.Exists(path))
{
    ...
}

Fill SVG path element with a background-image

You can do it by making the background into a pattern:

<defs>
  <pattern id="img1" patternUnits="userSpaceOnUse" width="100" height="100">
    <image href="wall.jpg" x="0" y="0" width="100" height="100" />
  </pattern>
</defs>

Adjust the width and height according to your image, then reference it from the path like this:

<path d="M5,50
         l0,100 l100,0 l0,-100 l-100,0
         M215,100
         a50,50 0 1 1 -100,0 50,50 0 1 1 100,0
         M265,50
         l50,100 l-100,0 l50,-100
         z"
  fill="url(#img1)" />

Working example

What's the difference between abstraction and encapsulation?

I know there are lot's of answers before me with variety of examples.
Well here is my opinion abstraction is getting interested from reality .

In abstraction we hide something to reduce the complexity of it and In encapsulation we hide something to protect the data.

So we define encapsulation as wrapping of data and methods in single entity referred as class.

In java we achieve encapsulation using getters and setters not just by wrapping data and methods in it. we also define a way to access that data. and while accessing data we protect it also.

Techinical e.g would be to define a private data variable call weight.Now we know that weight can't be zero or less than zero in real world scenario.
Imagine if there are no getters and setters someone could have easily set it to a negative value being public member of class.

Now final difference using one real world example,
Consider a circuit board consisting of switches and buttons. We wrap all the wires into a a circuit box, so that we can protect someone by not getting in contact directly(encapsulation).

We don't care how those wires are connected to each other we just want an interface to turn on and off switch. That interface is provided by buttons(abstraction)

Can inner classes access private variables?

An inner class is a friend of the class it is defined within.
So, yes; an object of type Outer::Inner can access the member variable var of an object of type Outer.

Unlike Java though, there is no correlation between an object of type Outer::Inner and an object of the parent class. You have to make the parent child relationship manually.

#include <string>
#include <iostream>

class Outer
{
    class Inner
    {
        public:
            Inner(Outer& x): parent(x) {}
            void func()
            {
                std::string a = "myconst1";
                std::cout << parent.var << std::endl;

                if (a == MYCONST)
                {   std::cout << "string same" << std::endl;
                }
                else
                {   std::cout << "string not same" << std::endl;
                }
            }
        private:
            Outer&  parent;
    };

    public:
        Outer()
            :i(*this)
            ,var(4)
        {}
        Outer(Outer& other)
            :i(other)
            ,var(22)
        {}
        void func()
        {
            i.func();
        }
    private:
        static const char* const MYCONST;
        Inner i;
        int var;
};

const char* const Outer::MYCONST = "myconst";

int main()
{

    Outer           o1;
    Outer           o2(o1);
    o1.func();
    o2.func();
}

Query to display all tablespaces in a database and datafiles

SELECT a.file_name,
       substr(A.tablespace_name,1,14) tablespace_name,
       trunc(decode(A.autoextensible,'YES',A.MAXSIZE-A.bytes+b.free,'NO',b.free)/1024/1024) free_mb,
       trunc(a.bytes/1024/1024) allocated_mb,
       trunc(A.MAXSIZE/1024/1024) capacity,
       a.autoextensible ae
FROM (
     SELECT file_id, file_name,
            tablespace_name,
            autoextensible,
            bytes,
            decode(autoextensible,'YES',maxbytes,bytes) maxsize
     FROM   dba_data_files
     GROUP BY file_id, file_name,
              tablespace_name,
              autoextensible,
              bytes,
              decode(autoextensible,'YES',maxbytes,bytes)
     ) a,
     (SELECT file_id,
             tablespace_name,
             sum(bytes) free
      FROM   dba_free_space
      GROUP BY file_id,
               tablespace_name
      ) b
WHERE a.file_id=b.file_id(+)
AND A.tablespace_name=b.tablespace_name(+)
ORDER BY A.tablespace_name ASC; 

How do I remove accents from characters in a PHP string?

When using iconv, the parameter locale must be set:

function test_enc($text = 'ešcržýáíé EŠCRŽÝÁÍÉ fóø bår FÓØ BÅR æ')
{
    echo '<tt>';
    echo iconv('utf8', 'ascii//TRANSLIT', $text);
    echo '</tt><br/>';
} 

test_enc();
setlocale(LC_ALL, 'cs_CZ.utf8');
test_enc();
setlocale(LC_ALL, 'en_US.utf8');
test_enc();

Yields into:

????????? ????????? f?? b?r F?? B?R ae
escrzyaie ESCRZYAIE fo? bar FO? BAR ae
escrzyaie ESCRZYAIE fo? bar FO? BAR ae

Another locales then cs_CZ and en_US I haven't installed and I can't test it.

In C# I see solution using translation to unicode normalized form - accents are splitted out and then filtered via nonspacing unicode category.

How to parse JSON string in Typescript

Typescript is (a superset of) javascript, so you just use JSON.parse as you would in javascript:

let obj = JSON.parse(jsonString);

Only that in typescript you can have a type to the resulting object:

interface MyObj {
    myString: string;
    myNumber: number;
}

let obj: MyObj = JSON.parse('{ "myString": "string", "myNumber": 4 }');
console.log(obj.myString);
console.log(obj.myNumber);

(code in playground)

How to split a string in Ruby and get all items except the first one?

Since you've got an array, what you really want is Array#slice, not split.

rest = ex.slice(1 .. -1)
# or
rest = ex[1 .. -1]

Calling a class function inside of __init__

How about:

class MyClass(object):
    def __init__(self, filename):
        self.filename = filename 
        self.stats = parse_file(filename)

def parse_file(filename):
    #do some parsing
    return results_from_parse

By the way, if you have variables named stat1, stat2, etc., the situation is begging for a tuple: stats = (...).

So let parse_file return a tuple, and store the tuple in self.stats.

Then, for example, you can access what used to be called stat3 with self.stats[2].

How do I delete from multiple tables using INNER JOIN in SQL server

Example for delete some records from master table and corresponding records from two detail tables:

BEGIN TRAN

  -- create temporary table for deleted IDs
  CREATE TABLE #DeleteIds (
    Id INT NOT NULL PRIMARY KEY
  )

  -- save IDs of master table records (you want to delete) to temporary table    
  INSERT INTO #DeleteIds(Id)
  SELECT DISTINCT mt.MasterTableId
  FROM MasterTable mt 
  INNER JOIN ... 
  WHERE ...  

  -- delete from first detail table using join syntax
  DELETE d
  FROM DetailTable_1 D
  INNER JOIN #DeleteIds X
    ON D.MasterTableId = X.Id


  -- delete from second detail table using IN clause  
  DELETE FROM DetailTable_2
  WHERE MasterTableId IN (
    SELECT X.Id
    FROM #DeleteIds X
  )


  -- and finally delete from master table
  DELETE d
  FROM MasterTable D
  INNER JOIN #DeleteIds X
    ON D.MasterTableId = X.Id

  -- do not forget to drop the temp table
  DROP TABLE #DeleteIds

COMMIT

jQuery multiple conditions within if statement

A more general approach:

if ( ($("body").hasClass("homepage") || $("body").hasClass("contact")) && (theLanguage == 'en-gb') )   {

       // Do something

}

Transport security has blocked a cleartext HTTP

How to fix it?

enter image description here

Below steps to fix it.

enter image description here enter image description here enter image description here enter image description here enter image description here

Call a function with argument list in python

You need to use arguments unpacking..

def wrapper(func, *args):
    func(*args)

def func1(x):
    print(x)

def func2(x, y, z):
    print x+y+z

wrapper(func1, 1)
wrapper(func2, 1, 2, 3)

How to fix/convert space indentation in Sublime Text?

The easiest thing i did was,

changed my Indentation to Tabs

and it resolved my problem.

You can do the same,

to Spaces

as well as per your need.

Mentioned the snapshot of the same.

enter image description here

Git "error: The branch 'x' is not fully merged"

Easiest Solution With Explanation (double checked solution) (faced the problem before)

Problem is:

1- I can't delete a branch

2- The terminal keep display a warning message that there are some commits that are not approved yet

3- knowing that I checked the master and branch and they are identical (up to date)

solution:

git checkout master
git merge branch_name
git checkout branch_name
git push
git checkout master
git branch -d branch_name

Explanation:

when your branch is connected to upstream remote branch (on Github, bitbucket or whatever), you need to merge (push) it into the master, and you need to push the new changes (commits) to the remote repo (Github, bitbucket or whatever) from the branch,

what I did in my code is that I switched to master, then merge the branch into it (to make sure they're identical on your local machine), then I switched to the branch again and pushed the updates or changes into the remote online repo using "git push".

after that, I switched to the master again, and tried to delete the branch, and the problem (warning message) disappeared, and the branch deleted successfully

What does "commercial use" exactly mean?

Fundamentally if you use it as part of a business then its commercial use - so its not a matter of whether the tools are directly generating income or not rather one of if they are being used in support of income generation directly or indirectly.

To take your specific example, if the purpose of the site is to sell or promote your paid services/product then its a commercial enterprise.

Override hosts variable of Ansible playbook from the command line

An other solution is to use the special variable ansible_limit which is the contents of the --limit CLI option for the current execution of Ansible.

- hosts: "{{ ansible_limit | default(omit) }}"

If the --limit option is omitted, then Ansible issues a warning, but does nothing since no host matched.

[WARNING]: Could not match supplied host pattern, ignoring: None

PLAY ****************************************************************
skipping: no hosts matched

How to create a printable Twitter-Bootstrap page

Replace every col-md- with col-xs-

eg: replace every col-md-6 to col-xs-6.

This is the thing that worked for me to get me rid of this problem you can see what you have to replace.

Android getText from EditText field

Use this:

  setContentView(R.layout.yourlayout);

  //after setting yor layout do the following
  EditText email = (EdiText) findViewById(R.id.vnosEmaila);
  String val = email.getText().toString;   // Use the toString method to convert the return value to a String.

  //Your Toast with String val; 
  Toast toast = Toast.makeText(EmailGumb.this, val, Toast.LENGTH_LONG);
  toast.setGravity(Gravity.CENTER, 0, 0);
  toast.show();

Thanks

How do I get the full url of the page I am on in C#

Try the following -

var FullUrl = Request.Url.AbsolutePath.ToString();
var ID = FullUrl.Split('/').Last();

How can I retrieve a table from stored procedure to a datatable?

Set the CommandText as well, and call Fill on the SqlAdapter to retrieve the results in a DataSet:

var con = new SqlConnection();
con.ConnectionString = "connection string";
var com = new SqlCommand();
com.Connection = con;
com.CommandType = CommandType.StoredProcedure;
com.CommandText = "sp_returnTable";
var adapt = new SqlDataAdapter();
adapt.SelectCommand = com;
var dataset = new DataSet();
adapt.Fill(dataset);

(Example is using parameterless constructors for clarity; can be shortened by using other constructors.)

Get max and min value from array in JavaScript

Instead of .each, another (perhaps more concise) approach to getting all those prices might be:

var prices = $(products).children("li").map(function() {
    return $(this).prop("data-price");
}).get();

additionally you may want to consider filtering the array to get rid of empty or non-numeric array values in case they should exist:

prices = prices.filter(function(n){ return(!isNaN(parseFloat(n))) });

then use Sergey's solution above:

var max = Math.max.apply(Math,prices);
var min = Math.min.apply(Math,prices);

How to prevent a browser from storing passwords

I would create a session variable and randomize it. Then build the id and name values based on the session variable. Then on login interrogate the session var you created.

if (!isset($_SESSION['autoMaskPassword'])) {
    $bytes = random_bytes(16);
    $_SESSION['autoMask_password'] = bin2hex($bytes);
}

<input type="password" name="<?=$_SESSION['autoMaskPassword']?>" placeholder="password">

Case insensitive comparison of strings in shell script

grep has a -i flag which means case insensitive so ask it to tell you if var2 is in var1.

var1=match 
var2=MATCH 
if echo $var1 | grep -i "^${var2}$" > /dev/null ; then
    echo "MATCH"
fi

Change a HTML5 input's placeholder color with CSS

I think this code will work because a placeholder is needed only for input type text. So this one line CSS will be enough for your need:

input[type="text"]::-webkit-input-placeholder {
    color: red;
}

How to scroll to the bottom of a UITableView on the iPhone before the view appears

I think the easiest way is this:

if (self.messages.count > 0)
{
    [self.tableView 
        scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:self.messages.count-1 
        inSection:0] 
        atScrollPosition:UITableViewScrollPositionBottom animated:YES];
}

Swift 3 Version:

if messages.count > 0 {
    userDefinedOptionsTableView.scrollToRow(at: IndexPath(item:messages.count-1, section: 0), at: .bottom, animated: true)
}

How to center Font Awesome icons horizontally?

It's a really old topic but as it still comes up top in search results:

Nowadays you can add additional class fa-fw to set it fixed width.

Example:

<i class="fa fa-pencil fa-fw" aria-hidden="true"></i>

Malformed String ValueError ast.literal_eval() with String representation of Tuple

ast.literal_eval (located in ast.py) parses the tree with ast.parse first, then it evaluates the code with quite an ugly recursive function, interpreting the parse tree elements and replacing them with their literal equivalents. Unfortunately the code is not at all expandable, so to add Decimal to the code you need to copy all the code and start over.

For a slightly easier approach, you can use ast.parse module to parse the expression, and then the ast.NodeVisitor or ast.NodeTransformer to ensure that there is no unwanted syntax or unwanted variable accesses. Then compile with compile and eval to get the result.

The code is a bit different from literal_eval in that this code actually uses eval, but in my opinion is simpler to understand and one does not need to dig too deep into AST trees. It specifically only allows some syntax, explicitly forbidding for example lambdas, attribute accesses (foo.__dict__ is very evil), or accesses to any names that are not deemed safe. It parses your expression fine, and as an extra I also added Num (float and integer), list and dictionary literals.

Also, works the same on 2.7 and 3.3

import ast
import decimal

source = "(Decimal('11.66985'), Decimal('1e-8'),"\
    "(1,), (1,2,3), 1.2, [1,2,3], {1:2})"

tree = ast.parse(source, mode='eval')

# using the NodeTransformer, you can also modify the nodes in the tree,
# however in this example NodeVisitor could do as we are raising exceptions
# only.
class Transformer(ast.NodeTransformer):
    ALLOWED_NAMES = set(['Decimal', 'None', 'False', 'True'])
    ALLOWED_NODE_TYPES = set([
        'Expression', # a top node for an expression
        'Tuple',      # makes a tuple
        'Call',       # a function call (hint, Decimal())
        'Name',       # an identifier...
        'Load',       # loads a value of a variable with given identifier
        'Str',        # a string literal

        'Num',        # allow numbers too
        'List',       # and list literals
        'Dict',       # and dicts...
    ])

    def visit_Name(self, node):
        if not node.id in self.ALLOWED_NAMES:
            raise RuntimeError("Name access to %s is not allowed" % node.id)

        # traverse to child nodes
        return self.generic_visit(node)

    def generic_visit(self, node):
        nodetype = type(node).__name__
        if nodetype not in self.ALLOWED_NODE_TYPES:
            raise RuntimeError("Invalid expression: %s not allowed" % nodetype)

        return ast.NodeTransformer.generic_visit(self, node)


transformer = Transformer()

# raises RuntimeError on invalid code
transformer.visit(tree)

# compile the ast into a code object
clause = compile(tree, '<AST>', 'eval')

# make the globals contain only the Decimal class,
# and eval the compiled object
result = eval(clause, dict(Decimal=decimal.Decimal))

print(result)

MySQL selecting yesterday's date

Last or next date, week, month & year calculation. It might be helpful for anyone.

Current Date:

select curdate();

Yesterday:

select subdate(curdate(), 1)

Tomorrow:

select adddate(curdate(), 1)

Last 1 week:

select between subdate(curdate(), 7) and subdate(curdate(), 1)

Next 1 week:

between adddate(curdate(), 7) and adddate(curdate(), 1)

Last 1 month:

between subdate(curdate(), 30) and subdate(curdate(), 1)

Next 1 month:

between adddate(curdate(), 30) and adddate(curdate(), 1)

Current month:

subdate(curdate(),day(curdate())-1) and last_day(curdate());

Last 1 year:

between subdate(curdate(), 365) and subdate(curdate(), 1)

Next 1 year:

between adddate(curdate(), 365) and adddate(curdate(), 1)

How to activate virtualenv?

1- open powershell and navigate to your application folder 2- enter your virtualenv folder ex : cd .\venv\Scripts\ 3- active virtualenv by type .\activate

iCheck check if checkbox is checked

Call

element.iCheck('update');

To get the updated markup on the element

Alternative to iFrames with HTML5

I created a node module to solve this problem node-iframe-replacement. You provide the source URL of the parent site and CSS selector to inject your content into and it merges the two together.

Changes to the parent site are picked up every 5 minutes.

var iframeReplacement = require('node-iframe-replacement');

// add iframe replacement to express as middleware (adds res.merge method) 
app.use(iframeReplacement);

// create a regular express route 
app.get('/', function(req, res){

    // respond to this request with our fake-news content embedded within the BBC News home page 
    res.merge('fake-news', {
        // external url to fetch 
       sourceUrl: 'http://www.bbc.co.uk/news',
       // css selector to inject our content into 
       sourcePlaceholder: 'div[data-entityid="container-top-stories#1"]',
       // pass a function here to intercept the source html prior to merging 
       transform: null
    });
});

The source contains a working example of injecting content into the BBC News home page.

Spring RestTemplate GET with parameters

Since at least Spring 3, instead of using UriComponentsBuilder to build the URL (which is a bit verbose), many of the RestTemplate methods accept placeholders in the path for parameters (not just exchange).

From the documentation:

Many of the RestTemplate methods accepts a URI template and URI template variables, either as a String vararg, or as Map<String,String>.

For example with a String vararg:

restTemplate.getForObject(
   "http://example.com/hotels/{hotel}/rooms/{room}", String.class, "42", "21");

Or with a Map<String, String>:

Map<String, String> vars = new HashMap<>();
vars.put("hotel", "42");
vars.put("room", "21");

restTemplate.getForObject("http://example.com/hotels/{hotel}/rooms/{room}", 
    String.class, vars);

Reference: https://docs.spring.io/spring/docs/current/spring-framework-reference/integration.html#rest-resttemplate-uri

If you look at the JavaDoc for RestTemplate and search for "URI Template", you can see which methods you can use placeholders with.

Verify a certificate chain using openssl verify

From verify documentation:

If a certificate is found which is its own issuer it is assumed to be the root CA.

In other words, root CA needs to self signed for verify to work. This is why your second command didn't work. Try this instead:

openssl verify -CAfile RootCert.pem -untrusted Intermediate.pem UserCert.pem

It will verify your entire chain in a single command.

Batch file to restart a service. Windows

net stop <your service> && net start <your service>

No net restart, unfortunately.

How do I check the operating system in Python?

If you want to know on which platform you are on out of "Linux", "Windows", or "Darwin" (Mac), without more precision, you should use:

>>> import platform
>>> platform.system()
'Linux'  # or 'Windows'/'Darwin'

The platform.system function uses uname internally.

What algorithms compute directions from point A to point B on a map?

An all-pairs shortest path algorithm will compute the shortest paths between all vertices in a graph. This will allow paths to be pre-computed instead of requiring a path to be calculated each time someone wants to find the shortest path between a source and a destination. The Floyd-Warshall algorithm is an all-pairs shortest path algorithm.

Render Content Dynamically from an array map function in React Native

lapsList() {

    return this.state.laps.map((data) => {
      return (
        <View><Text>{data.time}</Text></View>
      )
    })
}

You forgot to return the map. this code will resolve the issue.

Extend a java class from one file in another java file

Just put the two files in the same directory. Here's an example:

Person.java

public class Person {
  public String name;

  public Person(String name) {
    this.name = name;
  }

  public String toString() {
    return name;
  }
}

Student.java

public class Student extends Person {
  public String somethingnew;

  public Student(String name) {
    super(name);
    somethingnew = "surprise!";
  }

  public String toString() {
    return super.toString() + "\t" + somethingnew;
  }

  public static void main(String[] args) {
    Person you = new Person("foo");
    Student me = new Student("boo");

    System.out.println("Your name is " + you);
    System.out.println("My name is " + me);
  }
}

Running Student (since it has the main function) yields us the desired outcome:

Your name is foo
My name is boo  surprise!

Config Error: This configuration section cannot be used at this path

The best option is to Change Application Settings from the Custom Site Delegation
Open IIS and from the root select Feature Delegation and then select Application Settings and from the right sidebar select Read/Write Step #1 Step #2

What svn command would list all the files modified on a branch?

This will list only modified files:

svn status -u | grep M

In Excel how to get the left 5 characters of each cell in a specified column and put them into a new column

Have you tried using the "auto-fill" in Excel?

If you have an entire column of items you put the formula in the first cell, make sure you get the result you desire and then you can do the copy/paste, or use auto fill which is an option that sits on the bottom right corner of the cell.

You go to that corner in the cell and once your cursor changes to a "+", you can double-click on it and it should populate all the way down to the last entry (as long as there are no populated cells, that is).

Is having an 'OR' in an INNER JOIN condition a bad idea?

This kind of JOIN is not optimizable to a HASH JOIN or a MERGE JOIN.

It can be expressed as a concatenation of two resultsets:

SELECT  *
FROM    maintable m
JOIN    othertable o
ON      o.parentId = m.id
UNION
SELECT  *
FROM    maintable m
JOIN    othertable o
ON      o.id = m.parentId

, each of them being an equijoin, however, SQL Server's optimizer is not smart enough to see it in the query you wrote (though they are logically equivalent).

How to resolve TypeError: can only concatenate str (not "int") to str

Use f-strings to resolve the TypeError

# the following line causes a TypeError
# test = 'Here is a test that can be run' + 15 + 'times'

# same intent with a f-string
i = 15

test = f'Here is a test that can be run {i} times'

print(test)

# output
'Here is a test that can be run 15 times'
i = 15
# t = 'test' + i  # will cause a TypeError

# should be
t = f'test{i}'

print(t)

# output
'test15'
  • The issue may be attempting to evaluate an expression where a variable is the string of a numeric.
  • Convert the string to an int.
  • This scenario is specific to this question
  • When iterating, it's important to be aware of the dtype
i = '15'
# t = 15 + i  # will cause a TypeError

# convert the string to int
t = 15 + int(i)
print(t)

# output
30

Note

  • The preceding part of the answer addresses the TypeError shown in the question title, which is why people seem to be coming to this question.
  • However, this doesn't resolve the issue in relation to the example provided by the OP, which is addressed below.

Original Code Issues

  • TypeError is caused because message type is a str.
  • The code iterates each character and attempts to add char, a str type, to an int
  • That issue can be resolved by converting char to an int
  • As the code is presented, secret_string needs to be initialized with 0 instead of "".
  • The code also results in a ValueError: chr() arg not in range(0x110000) because 7429146 is out of range for chr().
  • Resolved by using a smaller number
  • The output is not a string, as was intended, which leads to the Updated Code in the question.
message = input("Enter a message you want to be revealed: ")

secret_string = 0

for char in message:
    char = int(char)
    value = char + 742146
    secret_string += ord(chr(value))
    
print(f'\nRevealed: {secret_string}')

# Output
Enter a message you want to be revealed:  999

Revealed: 2226465

Updated Code Issues

  • message is now an int type, so for char in message: causes TypeError: 'int' object is not iterable
  • message is converted to int to make sure the input is an int.
  • Set the type with str()
  • Only convert value to Unicode with chr
  • Don't use ord
while True:
    try:
        message = str(int(input("Enter a message you want to be decrypt: ")))
        break
    except ValueError:
        print("Error, it must be an integer")
        
secret_string = ""
for char in message:
    
    value = int(char) + 10000
    
    secret_string += chr(value)

print("Decrypted", secret_string)

# output
Enter a message you want to be decrypt:  999
Decrypted ???

Enter a message you want to be decrypt:  100
Decrypted ???

Having issues with a MySQL Join that needs to meet multiple conditions

also this should work (not tested):

SELECT u.* FROM room u JOIN facilities_r fu ON fu.id_uc = u.id_uc AND u.id_fu IN(4,3) WHERE 1 AND vizibility = 1 GROUP BY id_uc ORDER BY u_premium desc , id_uc desc

If u.id_fu is a numeric field then you can remove the ' around them. The same for vizibility. Only if the field is a text field (data type char, varchar or one of the text-datatype e.g. longtext) then the value has to be enclosed by ' or even ".

Also I and Oracle too recommend to enclose table and field names in backticks. So you won't get into trouble if a field name contains a keyword.

ES6 export default with multiple functions referring to each other

tl;dr: baz() { this.foo(); this.bar() }

In ES2015 this construct:

var obj = {
    foo() { console.log('foo') }
}

is equal to this ES5 code:

var obj = {
    foo : function foo() { console.log('foo') }
}

exports.default = {} is like creating an object, your default export translates to ES5 code like this:

exports['default'] = {
    foo: function foo() {
        console.log('foo');
    },
    bar: function bar() {
        console.log('bar');
    },
    baz: function baz() {
        foo();bar();
    }
};

now it's kind of obvious (I hope) that baz tries to call foo and bar defined somewhere in the outer scope, which are undefined. But this.foo and this.bar will resolve to the keys defined in exports['default'] object. So the default export referencing its own methods shold look like this:

export default {
    foo() { console.log('foo') }, 
    bar() { console.log('bar') },
    baz() { this.foo(); this.bar() }
}

See babel repl transpiled code.

Non-numeric Argument to Binary Operator Error in R

Because your question is phrased regarding your error message and not whatever your function is trying to accomplish, I will address the error.

- is the 'binary operator' your error is referencing, and either CurrentDay or MA (or both) are non-numeric.

A binary operation is a calculation that takes two values (operands) and produces another value (see wikipedia for more). + is one such operator: "1 + 1" takes two operands (1 and 1) and produces another value (2). Note that the produced value isn't necessarily different from the operands (e.g., 1 + 0 = 1).

R only knows how to apply + (and other binary operators, such as -) to numeric arguments:

> 1 + 1
[1] 2
> 1 + 'one'
Error in 1 + "one" : non-numeric argument to binary operator

When you see that error message, it means that you are (or the function you're calling is) trying to perform a binary operation with something that isn't a number.

EDIT:

Your error lies in the use of [ instead of [[. Because Day is a list, subsetting with [ will return a list, not a numeric vector. [[, however, returns an object of the class of the item contained in the list:

> Day <- Transaction(1, 2)["b"]
> class(Day)
[1] "list"
> Day + 1
Error in Day + 1 : non-numeric argument to binary operator

> Day2 <- Transaction(1, 2)[["b"]]
> class(Day2)
[1] "numeric"
> Day2 + 1
[1] 3

Transaction, as you've defined it, returns a list of two vectors. Above, Day is a list contain one vector. Day2, however, is simply a vector.

How can I restore the MySQL root user’s full privileges?

If the GRANT ALL doesn't work, try:

  1. Stop mysqld and restart it with the --skip-grant-tables option.
  2. Connect to the mysqld server with just: mysql (i.e. no -p option, and username may not be required).
  3. Issue the following commands in the mysql client:

    UPDATE mysql.user SET Grant_priv='Y', Super_priv='Y' WHERE User='root';

    FLUSH PRIVILEGES;

After that, you should be able to run GRANT ALL ON *.* TO 'root'@'localhost'; and have it work.

SQLite UPSERT / UPDATE OR INSERT

Option 1: Insert -> Update

If you like to avoid both changes()=0 and INSERT OR IGNORE even if you cannot afford deleting the row - You can use this logic;

First, insert (if not exists) and then update by filtering with the unique key.

Example

-- Table structure
CREATE TABLE players (
    id        INTEGER       PRIMARY KEY AUTOINCREMENT,
    user_name VARCHAR (255) NOT NULL
                            UNIQUE,
    age       INTEGER       NOT NULL
);

-- Insert if NOT exists
INSERT INTO players (user_name, age)
SELECT 'johnny', 20
WHERE NOT EXISTS (SELECT 1 FROM players WHERE user_name='johnny' AND age=20);

-- Update (will affect row, only if found)
-- no point to update user_name to 'johnny' since it's unique, and we filter by it as well
UPDATE players 
SET age=20 
WHERE user_name='johnny';

Regarding Triggers

Notice: I haven't tested it to see the which triggers are being called, but I assume the following:

if row does not exists

  • BEFORE INSERT
  • INSERT using INSTEAD OF
  • AFTER INSERT
  • BEFORE UPDATE
  • UPDATE using INSTEAD OF
  • AFTER UPDATE

if row does exists

  • BEFORE UPDATE
  • UPDATE using INSTEAD OF
  • AFTER UPDATE

Option 2: Insert or replace - keep your own ID

in this way you can have a single SQL command

-- Table structure
CREATE TABLE players (
    id        INTEGER       PRIMARY KEY AUTOINCREMENT,
    user_name VARCHAR (255) NOT NULL
                            UNIQUE,
    age       INTEGER       NOT NULL
);

-- Single command to insert or update
INSERT OR REPLACE INTO players 
(id, user_name, age) 
VALUES ((SELECT id from players WHERE user_name='johnny' AND age=20),
        'johnny',
        20);

Edit: added option 2.

Get value of div content using jquery

$('#field-function_purpose') will get you the element with ID field-function_purpose, which is your div element. text() returns you the content of the div.

var x = $('#field-function_purpose').text();

What are metaclasses in Python?

A metaclass is a class that tells how (some) other class should be created.

This is a case where I saw metaclass as a solution to my problem: I had a really complicated problem, that probably could have been solved differently, but I chose to solve it using a metaclass. Because of the complexity, it is one of the few modules I have written where the comments in the module surpass the amount of code that has been written. Here it is...

#!/usr/bin/env python

# Copyright (C) 2013-2014 Craig Phillips.  All rights reserved.

# This requires some explaining.  The point of this metaclass excercise is to
# create a static abstract class that is in one way or another, dormant until
# queried.  I experimented with creating a singlton on import, but that did
# not quite behave how I wanted it to.  See now here, we are creating a class
# called GsyncOptions, that on import, will do nothing except state that its
# class creator is GsyncOptionsType.  This means, docopt doesn't parse any
# of the help document, nor does it start processing command line options.
# So importing this module becomes really efficient.  The complicated bit
# comes from requiring the GsyncOptions class to be static.  By that, I mean
# any property on it, may or may not exist, since they are not statically
# defined; so I can't simply just define the class with a whole bunch of
# properties that are @property @staticmethods.
#
# So here's how it works:
#
# Executing 'from libgsync.options import GsyncOptions' does nothing more
# than load up this module, define the Type and the Class and import them
# into the callers namespace.  Simple.
#
# Invoking 'GsyncOptions.debug' for the first time, or any other property
# causes the __metaclass__ __getattr__ method to be called, since the class
# is not instantiated as a class instance yet.  The __getattr__ method on
# the type then initialises the class (GsyncOptions) via the __initialiseClass
# method.  This is the first and only time the class will actually have its
# dictionary statically populated.  The docopt module is invoked to parse the
# usage document and generate command line options from it.  These are then
# paired with their defaults and what's in sys.argv.  After all that, we
# setup some dynamic properties that could not be defined by their name in
# the usage, before everything is then transplanted onto the actual class
# object (or static class GsyncOptions).
#
# Another piece of magic, is to allow command line options to be set in
# in their native form and be translated into argparse style properties.
#
# Finally, the GsyncListOptions class is actually where the options are
# stored.  This only acts as a mechanism for storing options as lists, to
# allow aggregation of duplicate options or options that can be specified
# multiple times.  The __getattr__ call hides this by default, returning the
# last item in a property's list.  However, if the entire list is required,
# calling the 'list()' method on the GsyncOptions class, returns a reference
# to the GsyncListOptions class, which contains all of the same properties
# but as lists and without the duplication of having them as both lists and
# static singlton values.
#
# So this actually means that GsyncOptions is actually a static proxy class...
#
# ...And all this is neatly hidden within a closure for safe keeping.
def GetGsyncOptionsType():
    class GsyncListOptions(object):
        __initialised = False

    class GsyncOptionsType(type):
        def __initialiseClass(cls):
            if GsyncListOptions._GsyncListOptions__initialised: return

            from docopt import docopt
            from libgsync.options import doc
            from libgsync import __version__

            options = docopt(
                doc.__doc__ % __version__,
                version = __version__,
                options_first = True
            )

            paths = options.pop('<path>', None)
            setattr(cls, "destination_path", paths.pop() if paths else None)
            setattr(cls, "source_paths", paths)
            setattr(cls, "options", options)

            for k, v in options.iteritems():
                setattr(cls, k, v)

            GsyncListOptions._GsyncListOptions__initialised = True

        def list(cls):
            return GsyncListOptions

        def __getattr__(cls, name):
            cls.__initialiseClass()
            return getattr(GsyncListOptions, name)[-1]

        def __setattr__(cls, name, value):
            # Substitut option names: --an-option-name for an_option_name
            import re
            name = re.sub(r'^__', "", re.sub(r'-', "_", name))
            listvalue = []

            # Ensure value is converted to a list type for GsyncListOptions
            if isinstance(value, list):
                if value:
                    listvalue = [] + value
                else:
                    listvalue = [ None ]
            else:
                listvalue = [ value ]

            type.__setattr__(GsyncListOptions, name, listvalue)

    # Cleanup this module to prevent tinkering.
    import sys
    module = sys.modules[__name__]
    del module.__dict__['GetGsyncOptionsType']

    return GsyncOptionsType

# Our singlton abstract proxy class.
class GsyncOptions(object):
    __metaclass__ = GetGsyncOptionsType()

Get domain name from given url

If the input url is user input. this method gives the most appropriate host name. if not found gives back the input url.

private String getHostName(String urlInput) {
        urlInput = urlInput.toLowerCase();
        String hostName=urlInput;
        if(!urlInput.equals("")){
            if(urlInput.startsWith("http") || urlInput.startsWith("https")){
                try{
                    URL netUrl = new URL(urlInput);
                    String host= netUrl.getHost();
                    if(host.startsWith("www")){
                        hostName = host.substring("www".length()+1);
                    }else{
                        hostName=host;
                    }
                }catch (MalformedURLException e){
                    hostName=urlInput;
                }
            }else if(urlInput.startsWith("www")){
                hostName=urlInput.substring("www".length()+1);
            }
            return  hostName;
        }else{
            return  "";
        }
    }

Failed linking file resources

It can also occur if you leave an element with a null or empty attribute in your XML layout file else if your java file's path of objects creation such as specifying improper ID for the object

enter image description here

here frombottom= AnimationUtils.loadAnimation(this,R.anim); in which anim. the id or filename is left blank can lead to such problem.

Excel telling me my blank cells aren't blank

All, this is pretty simple. I have been trying for the same and this is what worked for me in VBA

Range("A1:R50").Select    'The range you want to remove blanks
With Selection
    Selection.NumberFormat = "General"
    .Value = .Value
End With

Regards, Anand Lanka

On Windows, running "import tensorflow" generates No module named "_pywrap_tensorflow" error

Dll not found. Install Visual C++ 2015 redistributable to fix.

How do I migrate an SVN repository with history to a new Git repository?

I suggest getting comfortable with Git before trying to use git-svn constantly, i.e. keeping SVN as the centralized repo and using Git locally.

However, for a simple migration with all the history, here are the few simple steps:

Initialize the local repo:

mkdir project
cd project
git svn init http://svn.url

Mark how far back you want to start importing revisions:

git svn fetch -r42

(or just "git svn fetch" for all revs)

Actually fetch everything since then:

git svn rebase

You can check the result of the import with Gitk. I'm not sure if this works on Windows, it works on OSX and Linux:

gitk

When you've got your SVN repo cloned locally, you may want to push it to a centralized Git repo for easier collaboration.

First create your empty remote repo (maybe on GitHub?):

git remote add origin [email protected]:user/project-name.git

Then, optionally sync your main branch so the pull operation will automatically merge the remote master with your local master, when both contain new stuff:

git config branch.master.remote origin
git config branch.master.merge refs/heads/master

After that, you may be interested in trying out my very own git_remote_branch tool, which helps dealing with remote branches:

First explanatory post: "Git remote branches"

Follow-up for the most recent version: "Time to git collaborating with git_remote_branch"

JavaScript get child element

ULs don't have a name attribute, but you can reference the ul by tag name.

Try replacing line 3 in your script with this:

var sub = cat.getElementsByTagName("UL");

PHP and MySQL Select a Single Value

  1. Don't use quotation in a field name or table name inside the query.

  2. After fetching an object you need to access object attributes/properties (in your case id) by attributes/properties name.

One note: please use mysqli_* or PDO since mysql_* deprecated. Here it is using mysqli:

session_start();
mysqli_report(MYSQLI_REPORT_ERROR | MYSQLI_REPORT_STRICT);
$link = new mysqli('localhost', 'username', 'password', 'db_name');
$link->set_charset('utf8mb4'); // always set the charset
$name = $_GET["username"];
$stmt = $link->prepare("SELECT id FROM Users WHERE username=? limit 1");
$stmt->bind_param('s', $name);
$stmt->execute();
$result = $stmt->get_result();
$value = $result->fetch_object();
$_SESSION['myid'] = $value->id;

Bonus tips: Use limit 1 for this type of scenario, it will save execution time :)

Angular 4 - get input value

I think you were planning to use Angular template reference variable based on your html template.

 // in html
 <input #nameInput type="text" class="form-control" placeholder=''/>

 // in add-player.ts file
 import { OnInit, ViewChild, ElementRef } from '@angular/core';

 export class AddPlayerComponent implements OnInit {
   @ViewChild('nameInput') nameInput: ElementRef;

   constructor() { }

   ngOnInit() { }

   addPlayer() {
     // you can access the input value via the following syntax.
     console.log('player name: ', this.nameInput.nativeElement.value);
   }
 }

Change the Textbox height?

Go into yourForm.Designer.cs Scroll down to your textbox. Example below is for textBox2 object. Add this

this.textBox2.AutoSize = false;

and set its size to whatever you want

this.textBox2.Size = new System.Drawing.Size(142, 27);

Will work like a charm - without setting multiline to true, but only until you change any option in designer itself (you will have to set these 2 lines again). I think, this method is still better than multilining. I had a textbox for nickname in my app and with multiline, people sometimes accidentially wrote their names twice, like Thomas\nThomas (you saw only one in actual textbox line). With this solution, text is simply hiding to the left after each char too long for width, so its much safer for users, to put inputs.

How can I iterate JSONObject to get individual items

You can try this it will recursively find all key values in a json object and constructs as a map . You can simply get which key you want from the Map .

public static Map<String,String> parse(JSONObject json , Map<String,String> out) throws JSONException{
    Iterator<String> keys = json.keys();
    while(keys.hasNext()){
        String key = keys.next();
        String val = null;
        try{
             JSONObject value = json.getJSONObject(key);
             parse(value,out);
        }catch(Exception e){
            val = json.getString(key);
        }

        if(val != null){
            out.put(key,val);
        }
    }
    return out;
}

 public static void main(String[] args) throws JSONException {

    String json = "{'ipinfo': {'ip_address': '131.208.128.15','ip_type': 'Mapped','Location': {'continent': 'north america','latitude': 30.1,'longitude': -81.714,'CountryData': {'country': 'united states','country_code': 'us'},'region': 'southeast','StateData': {'state': 'florida','state_code': 'fl'},'CityData': {'city': 'fleming island','postal_code': '32003','time_zone': -5}}}}";

    JSONObject object = new JSONObject(json);

    JSONObject info = object.getJSONObject("ipinfo");

    Map<String,String> out = new HashMap<String, String>();

    parse(info,out);

    String latitude = out.get("latitude");
    String longitude = out.get("longitude");
    String city = out.get("city");
    String state = out.get("state");
    String country = out.get("country");
    String postal = out.get("postal_code");

    System.out.println("Latitude : " + latitude + " LongiTude : " + longitude + " City : "+city + " State : "+ state + " Country : "+country+" postal "+postal);

    System.out.println("ALL VALUE " + out);

}

Output:

    Latitude : 30.1 LongiTude : -81.714 City : fleming island State : florida Country : united states postal 32003
ALL VALUE {region=southeast, ip_type=Mapped, state_code=fl, state=florida, country_code=us, city=fleming island, country=united states, time_zone=-5, ip_address=131.208.128.15, postal_code=32003, continent=north america, longitude=-81.714, latitude=30.1}

Setting a spinner onClickListener() in Android

Personally, I use that:

    final Spinner spinner = (Spinner) (view.findViewById(R.id.userList));
    spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
        @Override
        public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {                

            userSelectedIndex = position;
        }

        @Override
        public void onNothingSelected(AdapterView<?> parent) {
        }
    });  

Selenium WebDriver How to Resolve Stale Element Reference Exception?

Use the Expected Conditions provided by Selenium to wait for the WebElement.

While you debug, the client is not as fast as if you just run a unit test or a maven build. This means in debug mode the client has more time to prepare the element, but if the build is running the same code he is much faster and the WebElement your looking for is might not visible in the DOM of the Page.

Trust me with this, I had the same problem.

for example:

inClient.waitUntil(ExpectedConditions.visibilityOf(YourElement,2000))

This easy method calls wait after his call for 2 seconds on the visibility of your WebElement on DOM.

How to get the timezone offset in GMT(Like GMT+7:00) from android device?

Adding dst offset will solve this:

    int offsetInMillis = TimeZone.getDefault().getRawOffset()+TimeZone.getDefault().getDSTSavings();
    String offset = String.format("%02d:%02d", Math.abs(offsetInMillis / 3600000), Math.abs((offsetInMillis / 60000) % 60));
    offset = (offsetInMillis >= 0 ? "+" : "-") + offset;
    return offset;

Determine if 2 lists have the same elements, regardless of order?

This seems to work, though possibly cumbersome for large lists.

>>> A = [0, 1]
>>> B = [1, 0]
>>> C = [0, 2]
>>> not sum([not i in A for i in B])
True
>>> not sum([not i in A for i in C])
False
>>> 

However, if each list must contain all the elements of other then the above code is problematic.

>>> A = [0, 1, 2]
>>> not sum([not i in A for i in B])
True

The problem arises when len(A) != len(B) and, in this example, len(A) > len(B). To avoid this, you can add one more statement.

>>> not sum([not i in A for i in B]) if len(A) == len(B) else False
False

One more thing, I benchmarked my solution with timeit.repeat, under the same conditions used by Aaron Hall in his post. As suspected, the results are disappointing. My method is the last one. set(x) == set(y) it is.

>>> def foocomprehend(): return not sum([not i in data for i in data2])
>>> min(timeit.repeat('fooset()', 'from __main__ import fooset, foocount, foocomprehend'))
25.2893661496
>>> min(timeit.repeat('foosort()', 'from __main__ import fooset, foocount, foocomprehend'))
94.3974742993
>>> min(timeit.repeat('foocomprehend()', 'from __main__ import fooset, foocount, foocomprehend'))
187.224562545

usr/bin/ld: cannot find -l<nameOfTheLibrary>

I had this problem with compiling LXC on a fresh VM with Centos 7.8. I tried all the above and failed. Some suggested removing the -static flag from the compiler configuration but I didn't want to change anything.

The only thing that helped was to install glibc-static and retry. Hope that helps someone.

What are type hints in Python 3.5?

Type hints are for maintainability and don't get interpreted by Python. In the code below, the line def add(self, ic:int) doesn't result in an error until the next return... line:

class C1:
    def __init__(self):
        self.idn = 1
    def add(self, ic: int):
        return self.idn + ic

c1 = C1()
c1.add(2)

c1.add(c1)
Traceback (most recent call last):
  File "<input>", line 1, in <module>
  File "<input>", line 5, in add
TypeError: unsupported operand type(s) for +: 'int' and 'C1'

ASP.NET IIS Web.config [Internal Server Error]

I had the same problem.

Solution:

  1. Click the right button in your site folder in "iis"
  2. "Convert to Application".

member names cannot be the same as their enclosing type C#

A constructor should no have a return type . remove void before each constructor .

Some very basic characteristic of a constructor :

a. Same name as class b. no return type. c. will be called every time an object is made with the class. for eg- in your program if u made two objects of Flow, Flow flow1=new Flow(); Flow flow2=new Flow(); then Flow constructor will be called for 2 times.

d. If you want to call the constructor just for once then declare that as static (static constructor) and dont forget to remove any access modifier from static constructor ..

How to check if a stored procedure exists before creating it

**The simplest way to drop and recreate a stored proc in T-Sql is **

Use DatabaseName
go
If Object_Id('schema.storedprocname') is not null
begin
   drop procedure schema.storedprocname
end
go

create procedure schema.storedprocname
as

begin
end

How to find row number of a value in R code

(1:nrow(mydata_2))[mydata_2[,4] == 1578]

Of course there may be more than one row with a value of 1578.

Can I limit the length of an array in JavaScript?

You're not using splice correctly:

arr.splice(4, 1)

this will remove 1 item at index 4. see here

I think you want to use slice:

arr.slice(0,5)

this will return elements in position 0 through 4.

This assumes all the rest of your code (cookies etc) works correctly

windows batch file rename

I found this solution via PowerShell :

dir | rename-item -NewName {$_.name -replace "replaceME","MyNewTxt"}

This will rename parts of all the files in the current folder.

Concatenating Column Values into a Comma-Separated List

Another solution within a query :

select 
    Id, 
    STUFF(
        (select (', "' + od.ProductName + '"')
        from OrderDetails od (nolock)
        where od.Order_Id = o.Id
        order by od.ProductName
        FOR XML PATH('')), 1, 2, ''
    ) ProductNames
from Orders o (nolock)
where o.Customer_Id = 525188
order by o.Id desc

(EDIT: thanks @user007 for the STUFF declaration)

What does the explicit keyword mean?

The compiler is allowed to make one implicit conversion to resolve the parameters to a function. What this means is that the compiler can use constructors callable with a single parameter to convert from one type to another in order to get the right type for a parameter.

Here's an example class with a constructor that can be used for implicit conversions:

class Foo
{
public:
  // single parameter constructor, can be used as an implicit conversion
  Foo (int foo) : m_foo (foo) 
  {
  }

  int GetFoo () { return m_foo; }

private:
  int m_foo;
};

Here's a simple function that takes a Foo object:

void DoBar (Foo foo)
{
  int i = foo.GetFoo ();
}

and here's where the DoBar function is called:

int main ()
{
  DoBar (42);
}

The argument is not a Foo object, but an int. However, there exists a constructor for Foo that takes an int so this constructor can be used to convert the parameter to the correct type.

The compiler is allowed to do this once for each parameter.

Prefixing the explicit keyword to the constructor prevents the compiler from using that constructor for implicit conversions. Adding it to the above class will create a compiler error at the function call DoBar (42). It is now necessary to call for conversion explicitly with DoBar (Foo (42))

The reason you might want to do this is to avoid accidental construction that can hide bugs.
Contrived example:

  • You have a MyString(int size) class with a constructor that constructs a string of the given size. You have a function print(const MyString&), and you call print(3) (when you actually intended to call print("3")). You expect it to print "3", but it prints an empty string of length 3 instead.

Export from pandas to_excel without row names (index)?

Example: index = False

import pandas as pd

writer = pd.ExcelWriter("dataframe.xlsx", engine='xlsxwriter')
dataframe.to_excel(writer,sheet_name = dataframe, index=False)
writer.save() 

Checking if a folder exists (and creating folders) in Qt, C++

To both check if it exists and create if it doesn't, including intermediaries:

QDir dir("path/to/dir");
if (!dir.exists())
    dir.mkpath(".");

angularjs ng-style: background-image isn't working

IF you have data you're waiting for the server to return (item.id) and have a construct like this:

ng-style="{'background-image':'url(https://www.myImageplusitsid/{{item.id}})'}"

Make sure you add something like ng-if="item.id"

Otherwise you'll either have two requests or one faulty.

How to change background Opacity when bootstrap modal is open

Just in case someone is using Bootstrap 4. It seems we can no longer use .modal-backdrop.in, but must now use .modal-backdrop.show. Fade effect preserved.

.modal-backdrop.show {
    opacity: 0.7;
}

Manipulating an Access database from Java without ODBC

UCanAccess is a pure Java JDBC driver that allows us to read from and write to Access databases without using ODBC. It uses two other packages, Jackcess and HSQLDB, to perform these tasks. The following is a brief overview of how to get it set up.

 

Option 1: Using Maven

If your project uses Maven you can simply include UCanAccess via the following coordinates:

groupId: net.sf.ucanaccess
artifactId: ucanaccess

The following is an excerpt from pom.xml, you may need to update the <version> to get the most recent release:

  <dependencies>
    <dependency>
        <groupId>net.sf.ucanaccess</groupId>
        <artifactId>ucanaccess</artifactId>
        <version>4.0.4</version>
    </dependency>
  </dependencies>

 

Option 2: Manually adding the JARs to your project

As mentioned above, UCanAccess requires Jackcess and HSQLDB. Jackcess in turn has its own dependencies. So to use UCanAccess you will need to include the following components:

UCanAccess (ucanaccess-x.x.x.jar)
HSQLDB (hsqldb.jar, version 2.2.5 or newer)
Jackcess (jackcess-2.x.x.jar)
commons-lang (commons-lang-2.6.jar, or newer 2.x version)
commons-logging (commons-logging-1.1.1.jar, or newer 1.x version)

Fortunately, UCanAccess includes all of the required JAR files in its distribution file. When you unzip it you will see something like

ucanaccess-4.0.1.jar  
  /lib/
    commons-lang-2.6.jar  
    commons-logging-1.1.1.jar  
    hsqldb.jar  
    jackcess-2.1.6.jar

All you need to do is add all five (5) JARs to your project.

NOTE: Do not add loader/ucanload.jar to your build path if you are adding the other five (5) JAR files. The UcanloadDriver class is only used in special circumstances and requires a different setup. See the related answer here for details.

Eclipse: Right-click the project in Package Explorer and choose Build Path > Configure Build Path.... Click the "Add External JARs..." button to add each of the five (5) JARs. When you are finished your Java Build Path should look something like this

BuildPath.png

NetBeans: Expand the tree view for your project, right-click the "Libraries" folder and choose "Add JAR/Folder...", then browse to the JAR file.

nbAddJar.png

After adding all five (5) JAR files the "Libraries" folder should look something like this:

nbLibraries.png

IntelliJ IDEA: Choose File > Project Structure... from the main menu. In the "Libraries" pane click the "Add" (+) button and add the five (5) JAR files. Once that is done the project should look something like this:

IntelliJ.png

 

That's it!

Now "U Can Access" data in .accdb and .mdb files using code like this

// assumes...
//     import java.sql.*;
Connection conn=DriverManager.getConnection(
        "jdbc:ucanaccess://C:/__tmp/test/zzz.accdb");
Statement s = conn.createStatement();
ResultSet rs = s.executeQuery("SELECT [LastName] FROM [Clients]");
while (rs.next()) {
    System.out.println(rs.getString(1));
}

 

Disclosure

At the time of writing this Q&A I had no involvement in or affiliation with the UCanAccess project; I just used it. I have since become a contributor to the project.

Using cURL with a username and password?

In some API maybe it does not work (like rabbitmq).

there is alternative:

curl http://username:[email protected]

curl http://admin:[email protected]

Python Remove last 3 characters of a string

What's wrong with this?

foo.replace(" ", "")[:-3].upper()

What's the difference between passing by reference vs. passing by value?

Pass by value - The function copies the variable and works with a copy(so it doesn't change anything in the original variable)

Pass by reference - The function uses the original variable, if you change the variable in the other function, it changes in the original variable too.

Example(copy and use/try this yourself and see) :

#include <iostream>

using namespace std;

void funct1(int a){ //pass-by-value
    a = 6; //now "a" is 6 only in funct1, but not in main or anywhere else
}
void funct2(int &a){ //pass-by-reference
    a = 7; //now "a" is 7 both in funct2, main and everywhere else it'll be used
}

int main()
{
    int a = 5;

    funct1(a);
    cout<<endl<<"A is currently "<<a<<endl<<endl; //will output 5
    funct2(a);
    cout<<endl<<"A is currently "<<a<<endl<<endl; //will output 7

    return 0;
}

Keep it simple, peeps. Walls of text can be a bad habit.

Running bash script from within python

If sleep.sh has the shebang #!/bin/sh and it has appropriate file permissions -- run chmod u+rx sleep.sh to make sure and it is in $PATH then your code should work as is:

import subprocess

rc = subprocess.call("sleep.sh")

If the script is not in the PATH then specify the full path to it e.g., if it is in the current working directory:

from subprocess import call

rc = call("./sleep.sh")

If the script has no shebang then you need to specify shell=True:

rc = call("./sleep.sh", shell=True)

If the script has no executable permissions and you can't change it e.g., by running os.chmod('sleep.sh', 0o755) then you could read the script as a text file and pass the string to subprocess module instead:

with open('sleep.sh', 'rb') as file:
    script = file.read()
rc = call(script, shell=True)

What does the PHP error message "Notice: Use of undefined constant" mean?

Am not sure if there is any difference am using code igniter and i use "" for the names and it works great.

$department = mysql_real_escape_string($_POST["department"]);
$name = mysql_real_escape_string($_POST["name"]);
$email = mysql_real_escape_string($_POST["email"]);
$message = mysql_real_escape_string($_POST["message"]);

regards,

Jorge.

How do I dump an object's fields to the console?

You might find a use for the methods method which returns an array of methods for an object. It's not the same as print_r, but still useful at times.

>> "Hello".methods.sort
=> ["%", "*", "+", "<", "<<", "<=", "<=>", "==", "===", "=~", ">", ">=", "[]", "[]=", "__id__", "__send__", "all?", "any?", "between?", "capitalize", "capitalize!", "casecmp", "center", "chomp", "chomp!", "chop", "chop!", "class", "clone", "collect", "concat", "count", "crypt", "delete", "delete!", "detect", "display", "downcase", "downcase!", "dump", "dup", "each", "each_byte", "each_line", "each_with_index", "empty?", "entries", "eql?", "equal?", "extend", "find", "find_all", "freeze", "frozen?", "grep", "gsub", "gsub!", "hash", "hex", "id", "include?", "index", "inject", "insert", "inspect", "instance_eval", "instance_of?", "instance_variable_defined?", "instance_variable_get", "instance_variable_set", "instance_variables", "intern", "is_a?", "is_binary_data?", "is_complex_yaml?", "kind_of?", "length", "ljust", "lstrip", "lstrip!", "map", "match", "max", "member?", "method", "methods", "min", "next", "next!", "nil?", "object_id", "oct", "partition", "private_methods", "protected_methods", "public_methods", "reject", "replace", "respond_to?", "reverse", "reverse!", "rindex", "rjust", "rstrip", "rstrip!", "scan", "select", "send", "singleton_methods", "size", "slice", "slice!", "sort", "sort_by", "split", "squeeze", "squeeze!", "strip", "strip!", "sub", "sub!", "succ", "succ!", "sum", "swapcase", "swapcase!", "taguri", "taguri=", "taint", "tainted?", "to_a", "to_f", "to_i", "to_s", "to_str", "to_sym", "to_yaml", "to_yaml_properties", "to_yaml_style", "tr", "tr!", "tr_s", "tr_s!", "type", "unpack", "untaint", "upcase", "upcase!", "upto", "zip"]

Remote Linux server to remote linux server dir copy. How?

I think you can try with:

rsync -azvu -e ssh user@host1:/directory/ user@host2:/directory2/

(and I assume you are on host0 and you want to copy from host1 to host2 directly)

If the above does not work, you could try:

ssh user@host1 "/usr/bin/rsync -azvu -e ssh /directory/ user@host2:/directory2/"

in the this, it would work, if you already have setup passwordless SSH login from host1 to host2

In Excel, how do I extract last four letters of a ten letter string?

No need to use a macro. Supposing your first string is in A1.

=RIGHT(A1, 4)

Drag this down and you will get your four last characters.

Edit: To be sure, if you ever have sequences like 'ABC DEF' and want the last four LETTERS and not CHARACTERS you might want to use trimspaces()

=RIGHT(TRIMSPACES(A1), 4)

Edit: As per brettdj's suggestion, you may want to check that your string is actually 4-character long or more:

=IF(TRIMSPACES(A1)>=4, RIGHT(TRIMSPACES(A1), 4), TRIMSPACES(A1))

Creating a zero-filled pandas data frame

Assuming having a template DataFrame, which one would like to copy with zero values filled here...

If you have no NaNs in your data set, multiplying by zero can be significantly faster:

In [19]: columns = ["col{}".format(i) for i in xrange(3000)]                                                                                       

In [20]: indices = xrange(2000)

In [21]: orig_df = pd.DataFrame(42.0, index=indices, columns=columns)

In [22]: %timeit d = pd.DataFrame(np.zeros_like(orig_df), index=orig_df.index, columns=orig_df.columns)
100 loops, best of 3: 12.6 ms per loop

In [23]: %timeit d = orig_df * 0.0
100 loops, best of 3: 7.17 ms per loop

Improvement depends on DataFrame size, but never found it slower.

And just for the heck of it:

In [24]: %timeit d = orig_df * 0.0 + 1.0
100 loops, best of 3: 13.6 ms per loop

In [25]: %timeit d = pd.eval('orig_df * 0.0 + 1.0')
100 loops, best of 3: 8.36 ms per loop

But:

In [24]: %timeit d = orig_df.copy()
10 loops, best of 3: 24 ms per loop

EDIT!!!

Assuming you have a frame using float64, this will be the fastest by a huge margin! It is also able to generate any value by replacing 0.0 to the desired fill number.

In [23]: %timeit d = pd.eval('orig_df > 1.7976931348623157e+308 + 0.0')
100 loops, best of 3: 3.68 ms per loop

Depending on taste, one can externally define nan, and do a general solution, irrespective of the particular float type:

In [39]: nan = np.nan
In [40]: %timeit d = pd.eval('orig_df > nan + 0.0')
100 loops, best of 3: 4.39 ms per loop

How to reference Microsoft.Office.Interop.Excel dll?

You can also try installing it in Visual Studio via Package Manager.

Run Install-Package Microsoft.Office.Interop.Excel in the Package Console. This will automatically add it as a project reference.

Use is like this:

Using Excel=Microsoft.Office.Interop.Excel;

Conditional operator in Python?

simple is the best and works in every version.

if a>10: 
    value="b"
else: 
    value="c"

bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js

include popper.js before bootstrap.min.js

<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.0.4/popper.js"></script>

use this link to get popper

C++ unordered_map using a custom class type as the key

check the following link https://www.geeksforgeeks.org/how-to-create-an-unordered_map-of-user-defined-class-in-cpp/ for more details.

  • the custom class must implement the == operator
  • must create a hash function for the class (for primitive types like int and also types like string the hash function is predefined)

Warning :-Presenting view controllers on detached view controllers is discouraged

I think that the problem is that you do not have a proper view controller hierarchy. Set the rootviewcontroller of the app and then show new views by pushing or presenting new view controllers on them. Let each view controller manage their views. Only container view controllers, like the tabbarviewcontroller, should ever add other view controllers views to their own views. Read the view controllers programming guide to learn more on how to use view controllers properly. https://developer.apple.com/library/content/featuredarticles/ViewControllerPGforiPhoneOS/

How to run a subprocess with Python, wait for it to exit and get the full stdout as a string?

I'd try something like:

#!/usr/bin/python
from __future__ import print_function

import shlex
from subprocess import Popen, PIPE

def shlep(cmd):
    '''shlex split and popen
    '''
    parsed_cmd = shlex.split(cmd)
    ## if parsed_cmd[0] not in approved_commands:
    ##    raise ValueError, "Bad User!  No output for you!"
    proc = Popen(parsed_command, stdout=PIPE, stderr=PIPE)
    out, err = proc.communicate()
    return (proc.returncode, out, err)

... In other words let shlex.split() do most of the work. I would NOT attempt to parse the shell's command line, find pipe operators and set up your own pipeline. If you're going to do that then you'll basically have to write a complete shell syntax parser and you'll end up doing an awful lot of plumbing.

Of course this raises the question, why not just use Popen with the shell=True (keyword) option? This will let you pass a string (no splitting nor parsing) to the shell and still gather up the results to handle as you wish. My example here won't process any pipelines, backticks, file descriptor redirection, etc that might be in the command, they'll all appear as literal arguments to the command. Thus it is still safer then running with shell=True ... I've given a silly example of checking the command against some sort of "approved command" dictionary or set --- through it would make more sense to normalize that into an absolute path unless you intend to require that the arguments be normalized prior to passing the command string to this function.

How do I comment on the Windows command line?

: this is one way to comment

As a result:

:: this will also work
:; so will this
:! and this

Above styles work outside codeblocks, otherwise:

REM is another way to comment.