Programs & Examples On #Srand

a function which initializes the pseudo-random number generator in C/C++ or PHP

How to use function srand() with time.h?

If you chose to srand, it is a good idea to then call rand() at least once before you use it, because it is a kind of horrible primitive psuedo-random generator. See Stack Overflow question Why does rand() % 7 always return 0?.

srand(time(NULL));
rand();
//Now use rand()

If available, either random or arc4rand would be better.

Angular cookies

Use NGX Cookie Service

Inastall this package: npm install ngx-cookie-service --save

Add the cookie service to your app.module.ts as a provider:

import { CookieService } from 'ngx-cookie-service';
@NgModule({
  declarations: [ AppComponent ],
  imports: [ BrowserModule, ... ],
  providers: [ CookieService ],
  bootstrap: [ AppComponent ]
})

Then call in your component:

import { CookieService } from 'ngx-cookie-service';

constructor( private cookieService: CookieService ) { }

ngOnInit(): void {
  this.cookieService.set( 'name', 'Test Cookie' ); // To Set Cookie
  this.cookieValue = this.cookieService.get('name'); // To Get Cookie
}

That's it!

How to check if DST (Daylight Saving Time) is in effect, and if so, the offset?

Create two dates: one in June, one in January. Compare their getTimezoneOffset() values.

  • if January offset > June offset, client is in northern hemisphere
  • if January offset < June offset, client is in southern hemisphere
  • if no difference, client timezone does not observe DST

Now check getTimezoneOffset() of the current date.

  • if equal to June, northern hemisphere, then current time zone is DST (+1 hour)
  • if equal to January, southern hemisphere, then current time zone is DST (+1 hour)

Get pixel color from canvas, on mousemove

I have a very simple working example of geting pixel color from canvas.

First some basic HTML:

<canvas id="myCanvas" width="400" height="250" style="background:red;" onmouseover="echoColor(event)">
</canvas>

Then JS to draw something on the Canvas, and to get color:

var c = document.getElementById("myCanvas");
var ctx = c.getContext("2d");
ctx.fillStyle = "black";
ctx.fillRect(10, 10, 50, 50);

function echoColor(e){
    var imgData = ctx.getImageData(e.pageX, e.pageX, 1, 1);
    red = imgData.data[0];
    green = imgData.data[1];
    blue = imgData.data[2];
    alpha = imgData.data[3];
    console.log(red + " " + green + " " + blue + " " + alpha);  
}

Here is a working example, just look at the console.

Could not load file or assembly ... The parameter is incorrect

To know what to clear for sure - add the following registry key:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Fusion\EnableLog (DWord set to 1).

Then you will see output like below. This tells you where asp.net is attempting to load your DLLs. Clear this directory.

LOG: This bind starts in default load context.
LOG: Using application configuration file: c:\app\AtlasAdvisor\web\web.config
LOG: Using host configuration file: C:\Windows\Microsoft.NET\Framework\v4.0.30319\aspnet.config
LOG: Using machine configuration file from C:\Windows\Microsoft.NET\Framework\v4.0.30319\config\machine.config.
LOG: Policy not being applied to reference at this time (private, custom, partial, or location-based assembly bind).
LOG: Attempting download of new URL **file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/Temporary ASP.NET Files/root/3c8629f7/dfa387b6/Avanade.ViddlerNet.DLL.**
LOG: Attempting download of new URL **file:///C:/Windows/Microsoft.NET/Framework/v4.0.30319/Temporary ASP.NET Files/root/3c8629f7/dfa387b6/Avanade.ViddlerNet/Avanade.ViddlerNet.DLL**.

Can't subtract offset-naive and offset-aware datetimes

This is a very simple and clear solution
Two lines of code

# First we obtain de timezone info o some datatime variable    

tz_info = your_timezone_aware_variable.tzinfo

# Now we can subtract two variables using the same time zone info
# For instance
# Lets obtain the Now() datetime but for the tz_info we got before

diff = datetime.datetime.now(tz_info)-your_timezone_aware_variable

Conclusion: You must mange your datetime variables with the same time info

DateTimePicker: pick both date and time

Go to the Properties of your dateTimePickerin Visual Studio and set Format to Custom. Under CustomFormat enter your format. In my case I used MMMMdd, yyyy | hh:mm

enter image description here
dateTimePickerProperties

What does the restrict keyword mean in C++?

Nothing. It was added to the C99 standard.

Logging request/response messages when using HttpClient

Network tracing also available for next objects (see article on msdn)

  • System.Net.Sockets Some public methods of the Socket, TcpListener, TcpClient, and Dns classes
  • System.Net Some public methods of the HttpWebRequest, HttpWebResponse, FtpWebRequest, and FtpWebResponse classes, and SSL debug information (invalid certificates, missing issuers list, and client certificate errors.)
  • System.Net.HttpListener Some public methods of the HttpListener, HttpListenerRequest, and HttpListenerResponse classes.
  • System.Net.Cache Some private and internal methods in System.Net.Cache.
  • System.Net.Http Some public methods of the HttpClient, DelegatingHandler, HttpClientHandler, HttpMessageHandler, MessageProcessingHandler, and WebRequestHandler classes.
  • System.Net.WebSockets.WebSocket Some public methods of the ClientWebSocket and WebSocket classes.

Put next lines of code to the configuration file

<configuration>  
  <system.diagnostics>  
    <sources>  
      <source name="System.Net" tracemode="includehex" maxdatasize="1024">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.Cache">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.Http">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.Sockets">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
      <source name="System.Net.WebSockets">  
        <listeners>  
          <add name="System.Net"/>  
        </listeners>  
      </source>  
    </sources>  
    <switches>  
      <add name="System.Net" value="Verbose"/>  
      <add name="System.Net.Cache" value="Verbose"/>  
      <add name="System.Net.Http" value="Verbose"/>  
      <add name="System.Net.Sockets" value="Verbose"/>  
      <add name="System.Net.WebSockets" value="Verbose"/>  
    </switches>  
    <sharedListeners>  
      <add name="System.Net"  
        type="System.Diagnostics.TextWriterTraceListener"  
        initializeData="network.log"  
      />  
    </sharedListeners>  
    <trace autoflush="true"/>  
  </system.diagnostics>  
</configuration>  

View a specific Git commit

git show <revhash>

Documentation here. Or if that doesn't work, try Google Code's GIT Documentation

How to write asynchronous functions for Node.js

Just passing by callbacks is not enough. You have to use settimer for example, to make function async.

Examples: Not async functions:

function a() {
  var a = 0;    
  for(i=0; i<10000000; i++) {
    a++;
  };
  b();
};

function b() {
  var a = 0;    
  for(i=0; i<10000000; i++) {
    a++;
  };    
  c();
};

function c() {
  for(i=0; i<10000000; i++) {
  };
  console.log("async finished!");
};

a();
console.log("This should be good");

If you will run above example, This should be good, will have to wait untill those functions will finish to work.

Pseudo multithread (async) functions:

function a() {
  setTimeout ( function() {
    var a = 0;  
    for(i=0; i<10000000; i++) {
      a++;
    };
    b();
  }, 0);
};

function b() {
  setTimeout ( function() {
    var a = 0;  
    for(i=0; i<10000000; i++) {
      a++;
    };  
    c();
  }, 0);
};

function c() {
  setTimeout ( function() {
    for(i=0; i<10000000; i++) {
    };
    console.log("async finished!");
  }, 0);
};

a();
console.log("This should be good");

This one will be trully async. This should be good will be writen before async finished.

Is it possible to get an Excel document's row count without loading the entire document into memory?

Python 3

import openpyxl as xl

wb = xl.load_workbook("Sample.xlsx", enumerate)

#the 2 lines under do the same. 
sheet = wb.get_sheet_by_name('sheet') 
sheet = wb.worksheets[0]

row_count = sheet.max_row
column_count = sheet.max_column

#this works fore me.

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

Check whether you have Not Null constraint in your table columns and you are not passes the value for that column while insert/Update operations. That Causes this exception in entity framework.

Disable output buffering

You can create an unbuffered file and assign this file to sys.stdout.

import sys 
myFile= open( "a.log", "w", 0 ) 
sys.stdout= myFile

You can't magically change the system-supplied stdout; since it's supplied to your python program by the OS.

Failed to execute 'createObjectURL' on 'URL':

The problem is that the keys provided in the loop do not refer to the index of the file.

for (var i in this.files) {
    console.log(i);
}

The output of the above code is:

0
length
item

But what was expected was:

0
1
2
etc...

Then the error occurs when the browser tries to execute, for example:

window.URL.createObjectURL(this.files["length"])

I suggest implementation based on the following code:

var files = this.files;
for (var i = 0; i < files.length; i++) {
    var file = files[i],
        src = (window.URL || window.webkitURL).createObjectURL(file);
    ...
}

I hope this can help someone.

Greetings!

How to concatenate characters in java?

You need a String object of some description to hold your array of concatenated chars, since the char type will hold only a single character. e.g.,

StringBuilder sb = new StringBuilder('a').append('b').append('c');
System.out.println(sb.toString);

ASP.NET Web API - PUT & DELETE Verbs Not Allowed - IIS 8

I am not sure if you have edited right configuration file. Try following steps

  1. open %userprofile%\ducuments\iisexpress\config\applicationhost.config

  2. By default bellow given entries are commented in the applicationhost.config file. uncomment these entries.

<add name="WebDAVModule" image="%IIS_BIN%\webdav.dll" />


<add name="WebDAVModule" />
<add name="WebDAV" path="*"
 verb="PROPFIND,PROPPATCH,MKCOL,PUT,COPY,DELETE,MOVE,LOCK,UNLOCK"
 modules="WebDAVModule" resourceType="Unspecified" requireAccess="None"
 />

Differences Between vbLf, vbCrLf & vbCr Constants

The three constants have similar functions nowadays, but different historical origins, and very occasionally you may be required to use one or the other.

You need to think back to the days of old manual typewriters to get the origins of this. There are two distinct actions needed to start a new line of text:

  1. move the typing head back to the left. In practice in a typewriter this is done by moving the roll which carries the paper (the "carriage") all the way back to the right -- the typing head is fixed. This is a carriage return.
  2. move the paper up by the width of one line. This is a line feed.

In computers, these two actions are represented by two different characters - carriage return is CR, ASCII character 13, vbCr; line feed is LF, ASCII character 10, vbLf. In the old days of teletypes and line printers, the printer needed to be sent these two characters -- traditionally in the sequence CRLF -- to start a new line, and so the CRLF combination -- vbCrLf -- became a traditional line ending sequence, in some computing environments.

The problem was, of course, that it made just as much sense to only use one character to mark the line ending, and have the terminal or printer perform both the carriage return and line feed actions automatically. And so before you knew it, we had 3 different valid line endings: LF alone (used in Unix and Macintoshes), CR alone (apparently used in older Mac OSes) and the CRLF combination (used in DOS, and hence in Windows). This in turn led to the complications of DOS / Windows programs having the option of opening files in text mode, where any CRLF pair read from the file was converted to a single CR (and vice versa when writing).

So - to cut a (much too) long story short - there are historical reasons for the existence of the three separate line separators, which are now often irrelevant: and perhaps the best course of action in .NET is to use Environment.NewLine which means someone else has decided for you which to use, and future portability issues should be reduced.

Set Background color programmatically

You can use

 root.setBackgroundColor(0xFFFFFFFF);

or

 root.setBackgroundColor(Color.parseColor("#ffffff"));

How to respond with HTTP 400 error in a Spring MVC @ResponseBody method returning String?

Another approach is to use @ExceptionHandler with @ControllerAdvice to centralize all your handlers in the same class, if not you must put the handler methods in every controller you want to manage an exception.

Your handler class:

@ControllerAdvice
public class MyExceptionHandler extends ResponseEntityExceptionHandler {

  @ExceptionHandler(MyBadRequestException.class)
  public ResponseEntity<MyError> handleException(MyBadRequestException e) {
    return ResponseEntity
        .badRequest()
        .body(new MyError(HttpStatus.BAD_REQUEST, e.getDescription()));
  }
}

Your custom exception:

public class MyBadRequestException extends RuntimeException {

  private String description;

  public MyBadRequestException(String description) {
    this.description = description;
  }

  public String getDescription() {
    return this.description;
  }
}

Now you can throw exceptions from any of your controllers, and you can define other handlers inside you advice class.

How do I install Java on Mac OSX allowing version switching?

Note: These solutions work for various versions of Java including Java 8, Java 11, and the new Java 15, and for any other previous Java version covered by the listed version managers. This includes alternative JDK's from OpenJDK, Oracle, IBM, Azul, Amazon Correto, Graal and more. Easily work with Java 7, Java 8, Java 9, Java 10, Java 11, Java 12, Java 13, Java 14, and Java 15!

You have a few options for how to do the installation as well as manage JDK switching. Installation can be done by Homebrew, SDKMAN, Jabba, or a manual install. Switching can be done by JEnv, SDKMAN, Jabba, or manually by setting JAVA_HOME. All of these are described below.


Installation

First, install Java using whatever method you prefer including Homebrew, SDKMAN or a manual install of the tar.gz file. The advantage of a manual install is that the location of the JDK can be placed in a standardized location for Mac OSX. Otherwise, there are easier options such as SDKMAN that also will install other important and common tools for the JVM.

Installing and Switching versions with SDKMAN

SDKMAN is a bit different and handles both the install and the switching. SDKMAN also places the installed JDK's into its own directory tree, which is typically ~/.sdkman/candidates/java. SDKMAN allows setting a global default version, and a version specific to the current shell.

  1. Install SDKMAN from https://sdkman.io/install

  2. List the Java versions available to make sure you know the version ID

    sdk list java
    
  3. Install one of those versions, for example, Java 15:

    sdk install java 15-open 
    
  4. Make 15 the default version:

    sdk default java 15-open
    

    Or switch to 15 for the session:

    sdk use java 15-open
    

When you list available versions for installation using the list command, you will see a wide variety of distributions of Java:

sdk list java

And install additional versions, such as JDK 8:

sdk install java 8.0.181-oracle

SDKMAN can work with previously installed existing versions. Just do a local install giving your own version label and the location of the JDK:

sdk install java my-local-13 /Library/Java/JavaVirtualMachines/jdk-13.jdk/Contents/Home

And use it freely:

sdk use java my-local-13

More information is available in the SDKMAN Usage Guide along with other SDK's it can install and manage.

SDKMAN will automatically manage your PATH and JAVA_HOME for you as you change versions.


Install manually from OpenJDK download page:

  1. Download OpenJDK for Mac OSX from http://jdk.java.net/ (for example Java 15)

  2. Unarchive the OpenJDK tar, and place the resulting folder (i.e. jdk-15.jdk) into your /Library/Java/JavaVirtualMachines/ folder since this is the standard and expected location of JDK installs. You can also install anywhere you want in reality.

Install with Homebrew

The version of Java available in Homebrew Cask previous to October 3, 2018 was indeed the Oracle JVM. Now, however, it has now been updated to OpenJDK. Be sure to update Homebrew and then you will see the lastest version available for install.

  1. install Homebrew if you haven't already. Make sure it is updated:

     brew update
    
  2. Add the casks tap, if you want to use the AdoptOpenJDK versions (which tend to be more current):

     brew tap adoptopenjdk/openjdk
    

    These casks change their Java versions often, and there might be other taps out there with additional Java versions.

  3. Look for installable versions:

     brew search java   
    

    or for AdoptOpenJDK versions:

     brew search jdk     
    
  4. Check the details on the version that will be installed:

     brew info java
    

    or for the AdoptOpenJDK version:

     brew info adoptopenjdk
    
  5. Install a specific version of the JDK such as java11, adoptopenjdk8, or adoptopenjdk13, or just java or adoptopenjdk for the most current of that distribution. For example:

     brew install java
    
     brew cask install adoptopenjdk13
    

And these will be installed into /Library/Java/JavaVirtualMachines/ which is the traditional location expected on Mac OSX.

Other installation options:

Some other flavours of OpenJDK are:

Azul Systems Java Zulu certified builds of OpenJDK can be installed by following the instructions on their site.

Zulu® is a certified build of OpenJDK that is fully compliant with the Java SE standard. Zulu is 100% open source and freely downloadable. Now Java developers, system administrators, and end-users can enjoy the full benefits of open source Java with deployment flexibility and control over upgrade timing.

Amazon Correto OpenJDK builds have an easy to use an installation package for Java 8 or Java 11, and installs to the standard /Library/Java/JavaVirtualMachines/ directory on Mac OSX.

Amazon Corretto is a no-cost, multiplatform, production-ready distribution of the Open Java Development Kit (OpenJDK). Corretto comes with long-term support that will include performance enhancements and security fixes. Amazon runs Corretto internally on thousands of production services and Corretto is certified as compatible with the Java SE standard. With Corretto, you can develop and run Java applications on popular operating systems, including Linux, Windows, and macOS.


Where is my JDK?!?!

To find locations of previously installed Java JDK's installed at the default system locations, use:

/usr/libexec/java_home -V

Matching Java Virtual Machines (8):
15, x86_64: "OpenJDK 15" /Library/Java/JavaVirtualMachines/jdk-15.jdk/Contents/Home 14, x86_64: "OpenJDK 14" /Library/Java/JavaVirtualMachines/jdk-14.jdk/Contents/Home 13, x86_64: "OpenJDK 13" /Library/Java/JavaVirtualMachines/openjdk-13.jdk/Contents/Home 12, x86_64: "OpenJDK 12" /Library/Java/JavaVirtualMachines/jdk-12.jdk/Contents/Home
11, x86_64: "Java SE 11" /Library/Java/JavaVirtualMachines/jdk-11.jdk/Contents/Home
10.0.2, x86_64: "Java SE 10.0.2" /Library/Java/JavaVirtualMachines/jdk-10.0.2.jdk/Contents/Home
9, x86_64: "Java SE 9" /Library/Java/JavaVirtualMachines/jdk-9.jdk/Contents/Home
1.8.0_144, x86_64: "Java SE 8" /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home

You can also report just the location of a specific Java version using -v. For example for Java 15:

/usr/libexec/java_home -v 15

/Library/Java/JavaVirtualMachines/jdk-15.jdk/Contents/Home

Knowing the location of the installed JDK's is also useful when using tools like JEnv, or adding a local install to SDKMAN, or linking a system JDK in Jabba -- and you need to know where to find them.

If you need to find JDK's installed by other tools, check these locations:

  • SDKMAN installs to ~/.sdkman/candidates/java/
  • Jabba installs to ~/.jabba/jdk

Switching versions manually

The Java executable is a wrapper that will use whatever JDK is configured in JAVA_HOME, so you can change that to also change which JDK is in use.

For example, if you installed or untar'd JDK 15 to /Library/Java/JavaVirtualMachines/jdk-15.jdk if it is the highest version number it should already be the default, if not you could simply set:

export JAVA_HOME=/Library/Java/JavaVirtualMachines/jdk-15.jdk/Contents/Home

And now whatever Java executable is in the path will see this and use the correct JDK.

Using the /usr/libexec/java_home utility as previously described helps you to create aliases or to run commands to change Java versions by identifying the locations of different JDK installations. For example, creating shell aliases in your .profile or .bash_profile to change JAVA_HOME for you:

export JAVA_8_HOME=$(/usr/libexec/java_home -v1.8)
export JAVA_9_HOME=$(/usr/libexec/java_home -v9)
export JAVA_10_HOME=$(/usr/libexec/java_home -v10)
export JAVA_11_HOME=$(/usr/libexec/java_home -v11)
export JAVA_12_HOME=$(/usr/libexec/java_home -v12)
export JAVA_13_HOME=$(/usr/libexec/java_home -v13)
export JAVA_14_HOME=$(/usr/libexec/java_home -v14)
export JAVA_15_HOME=$(/usr/libexec/java_home -v15)

alias java8='export JAVA_HOME=$JAVA_8_HOME'
alias java9='export JAVA_HOME=$JAVA_9_HOME'
alias java10='export JAVA_HOME=$JAVA_10_HOME'
alias java11='export JAVA_HOME=$JAVA_11_HOME'
alias java12='export JAVA_HOME=$JAVA_12_HOME'
alias java13='export JAVA_HOME=$JAVA_13_HOME'
alias java14='export JAVA_HOME=$JAVA_14_HOME'
alias java15='export JAVA_HOME=$JAVA_15_HOME'

# default to Java 15
java15

Then to change versions, just use the alias.

java8
java -version

java version "1.8.0_144"

Of course, setting JAVA_HOME manually works too!


Switching versions with JEnv

JEnv expects the Java JDK's to already exist on the machine and can be in any location. Typically you will find installed Java JDK's in /Library/Java/JavaVirtualMachines/. JEnv allows setting the global version of Java, one for the current shell, and a per-directory local version which is handy when some projects require different versions than others.

  1. Install JEnv if you haven't already, instructions on the site http://www.jenv.be/ for manual install or using Homebrew.

  2. Add any Java version to JEnv (adjust the directory if you placed this elsewhere):

    jenv add /Library/Java/JavaVirtualMachines/jdk-15.jdk/Contents/Home
    
  3. Set your global version using this command:

    jenv global 15
    

You can also add other existing versions using jenv add in a similar manner, and list those that are available. For example Java 8:

jenv add /Library/Java/JavaVirtualMachines/jdk1.8.0_144.jdk/Contents/Home 
jenv versions

See the JEnv docs for more commands. You may now switch between any Java versions (Oracle, OpenJDK, other) at any time either for the whole system, for shells, or per local directory.

To help manage JAVA_HOME while using JEnv you can add the export plugin to do this for you.

$ jenv enable-plugin export
  You may restart your session to activate jenv export plugin echo export plugin activated

The export plugin may not adjust JAVA_HOME if it is already set, so you may need to clear this variable in your profile so that it can be managed by JEnv.

You can also use jenv exec <command> <parms...> to run single commands with JAVA_HOME and PATH set correctly for that one command, which could include opening another shell.


Installing and Switching versions with Jabba

Jabba also handles both the install and the switching. Jabba also places the installed JDK's into its own directory tree, which is typically ~/.jabba/jdk.

  1. Install Jabba by following the instructions on the home page.

  2. List available JDK's

    jabba ls-remote

  3. Install Java JDK 12

    jabba install [email protected]

  4. Use it:

    jabba use [email protected]

You can also alias version names, link to existing JDK's already installed, and find a mix of interesting JDK's such as GraalVM, Adopt JDK, IBM JDK, and more. The complete usage guide is available on the home page as well.

Jabba will automatically manage your PATH and JAVA_HOME for you as you change versions.

Java - Using Accessor and Mutator methods

You need to remove the static from your accessor methods - these methods need to be instance methods and access the instance variables

public class IDCard {
    public String name, fileName;
    public int id;

    public IDCard(final String name, final String fileName, final int id) {
        this.name = name;
        this.fileName = fileName
        this.id = id;
    }

    public String getName() {
        return name;
    }
}

You can the create an IDCard and use the accessor like this:

final IDCard card = new IDCard();
card.getName();

Each time you call new a new instance of the IDCard will be created and it will have it's own copies of the 3 variables.

If you use the static keyword then those variables are common across every instance of IDCard.

A couple of things to bear in mind:

  1. don't add useless comments - they add code clutter and nothing else.
  2. conform to naming conventions, use lower case of variable names - name not Name.

TypeError: ufunc 'add' did not contain a loop with signature matching types

You have a numpy array of strings, not floats. This is what is meant by dtype('<U9') -- a little endian encoded unicode string with up to 9 characters.

try:

return sum(np.asarray(listOfEmb, dtype=float)) / float(len(listOfEmb))

However, you don't need numpy here at all. You can really just do:

return sum(float(embedding) for embedding in listOfEmb) / len(listOfEmb)

Or if you're really set on using numpy.

return np.asarray(listOfEmb, dtype=float).mean()

Dockerfile if else condition with external arguments

From some reason most of the answers here didn't help me (maybe it's related to my FROM image in the Dockerfile)

So I preferred to create a bash script in my workspace combined with --build-arg in order to handle if statement while Docker build by checking if the argument is empty or not

Bash script:

#!/bin/bash -x

if test -z $1 ; then 
    echo "The arg is empty"
    ....do something....
else 
    echo "The arg is not empty: $1"
    ....do something else....
fi

Dockerfile:

FROM ...
....
ARG arg
COPY bash.sh /tmp/  
RUN chmod u+x /tmp/bash.sh && /tmp/bash.sh $arg
....

Docker Build:

docker build --pull -f "Dockerfile" -t $SERVICE_NAME --build-arg arg="yes" .

Remark: This will go to the else (false) in the bash script

docker build --pull -f "Dockerfile" -t $SERVICE_NAME .

Remark: This will go to the if (true)

Edit 1:

After several tries I have found the following article and this one which helped me to understand 2 things:

1) ARG before FROM is outside of the build

2) The default shell is /bin/sh which means that the if else is working a little bit different in the docker build. for example you need only one "=" instead of "==" to compare strings.

So you can do this inside the Dockerfile

ARG argname=false   #default argument when not provided in the --build-arg
RUN if [ "$argname" = "false" ] ; then echo 'false'; else echo 'true'; fi

and in the docker build:

docker build --pull -f "Dockerfile" --label "service_name=${SERVICE_NAME}" -t $SERVICE_NAME --build-arg argname=true .

Select all where [first letter starts with B]

SQL Statement:

 SELECT * FROM employee WHERE employeeName LIKE 'A%';

Result:

Number of Records: 4

employeeID  employeeName    employeeName    Address City    PostalCode  Country

1           Alam             Wipro          Delhi   Delhi   11005      India

2           Aditya           Wipro          Delhi   Delhi   11005      India

3           Alok             HCL            Delhi   Delhi   11005      India

4           Ashok            IBM            Delhi   Delhi   11005      India

is it possible to update UIButton title/text programmatically?

Sometimes it can get really complicated. The easy way is to "refresh" the button view!

//Do stuff to your button here.  For example:

[mybutton setEnabled:YES];

//Refresh it to new state.

[mybutton setNeedsDisplay];

Make javascript alert Yes/No Instead of Ok/Cancel

You cannot do that with the native confirm() as it is the browser’s method.

You have to create a plugin for a confirm box (or try one created by someone else). And they often look better, too.

Additional Tip: Change your English sentence to something like

Really, Delete this Thing?

How do I change the string representation of a Python class?

This is not as easy as it seems, some core library functions don't work when only str is overwritten (checked with Python 2.7), see this thread for examples How to make a class JSON serializable Also, try this

import json

class A(unicode):
    def __str__(self):
        return 'a'
    def __unicode__(self):
        return u'a'
    def __repr__(self):
        return 'a'

a = A()
json.dumps(a)

produces

'""'

and not

'"a"'

as would be expected.

EDIT: answering mchicago's comment:

unicode does not have any attributes -- it is an immutable string, the value of which is hidden and not available from high-level Python code. The json module uses re for generating the string representation which seems to have access to this internal attribute. Here's a simple example to justify this:

b = A('b') print b

produces

'a'

while

json.dumps({'b': b})

produces

{"b": "b"}

so you see that the internal representation is used by some native libraries, probably for performance reasons.

See also this for more details: http://www.laurentluce.com/posts/python-string-objects-implementation/

Is SQL syntax case sensitive?

In Sql Server it is an option. Turning it on sucks.

I'm not sure about MySql.

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

You could also have a JSON file with NODE_ENV as the top level. IMO, this is a better way to express configuration settings (as opposed to using a script that returns settings).

var config = require('./env.json')[process.env.NODE_ENV || 'development'];

Example for env.json:

{
    "development": {
        "MONGO_URI": "mongodb://localhost/test",
        "MONGO_OPTIONS": { "db": { "safe": true } }
    },
    "production": {
        "MONGO_URI": "mongodb://localhost/production",
        "MONGO_OPTIONS": { "db": { "safe": true } }
    }
}

Is there a way to delete all the data from a topic or delete the topic before every run?

As of kafka 2.3.0 version, there is an alternate way to soft deletion of Kafka (old approach are deprecated ).

Update retention.ms to 1 sec (1000ms) then set it again after a min, to default setting i.e 7 days (168 hours, 604,800,000 in ms )

Soft deletion:- (rentention.ms=1000) (using kafka-configs.sh)

bin/kafka-configs.sh --zookeeper 192.168.1.10:2181 --alter --entity-name kafka_topic3p3r --entity-type topics  --add-config retention.ms=1000
Completed Updating config for entity: topic 'kafka_topic3p3r'.

Setting to default:- 7 days (168 hours , retention.ms= 604800000)

bin/kafka-configs.sh --zookeeper 192.168.1.10:2181 --alter --entity-name kafka_topic3p3r --entity-type topics  --add-config retention.ms=604800000

jwt check if token expired

// Pass in function expiration date to check token 
function checkToken(exp) {
    if (Date.now() <= exp * 1000) {
      console.log(true, 'token is not expired')
    } else { 
      console.log(false, 'token is expired') 
    }
  }

How to refer to Excel objects in Access VBA?

I dissent from both the answers. Don't create a reference at all, but use late binding:

  Dim objExcelApp As Object
  Dim wb As Object

  Sub Initialize()
    Set objExcelApp = CreateObject("Excel.Application")
  End Sub

  Sub ProcessDataWorkbook()
     Set wb = objExcelApp.Workbooks.Open("path to my workbook")
     Dim ws As Object
     Set ws = wb.Sheets(1)

     ws.Cells(1, 1).Value = "Hello"
     ws.Cells(1, 2).Value = "World"

     'Close the workbook
     wb.Close
     Set wb = Nothing
  End Sub

You will note that the only difference in the code above is that the variables are all declared as objects and you instantiate the Excel instance with CreateObject().

This code will run no matter what version of Excel is installed, while using a reference can easily cause your code to break if there's a different version of Excel installed, or if it's installed in a different location.

Also, the error handling could be added to the code above so that if the initial instantiation of the Excel instance fails (say, because Excel is not installed or not properly registered), your code can continue. With a reference set, your whole Access application will fail if Excel is not installed.

Android - Dynamically Add Views into View

It looks like what you really want a ListView with a custom adapter to inflate the specified layout. Using an ArrayAdapter and the method notifyDataSetChanged() you have full control of the Views generation and rendering.

Take a look at these tutorials

What is the `zero` value for time.Time in Go?

Invoking an empty time.Time struct literal will return Go's zero date. Thus, for the following print statement:

fmt.Println(time.Time{})

The output is:

0001-01-01 00:00:00 +0000 UTC

For the sake of completeness, the official documentation explicitly states:

The zero value of type Time is January 1, year 1, 00:00:00.000000000 UTC.

How to extract the substring between two markers?

Using regular expressions - documentation for further reference

import re

text = 'gfgfdAAA1234ZZZuijjk'

m = re.search('AAA(.+?)ZZZ', text)
if m:
    found = m.group(1)

# found: 1234

or:

import re

text = 'gfgfdAAA1234ZZZuijjk'

try:
    found = re.search('AAA(.+?)ZZZ', text).group(1)
except AttributeError:
    # AAA, ZZZ not found in the original string
    found = '' # apply your error handling

# found: 1234

Connecting client to server using Socket.io

You need to make sure that you add forward slash before your link to socket.io:

<script src="/socket.io/socket.io.js"></script>

Then in the view/controller just do:

var socket = io.connect()

That should solve your problem.

Why does find -exec mv {} ./target/ + not work?

find . -name "*.mp3" -exec mv --target-directory=/home/d0k/??????/ {} \+

How to get the filename without the extension in Java?

Below is reference from https://android.googlesource.com/platform/tools/tradefederation/+/master/src/com/android/tradefed/util/FileUtil.java

/**
 * Gets the base name, without extension, of given file name.
 * <p/>
 * e.g. getBaseName("file.txt") will return "file"
 *
 * @param fileName
 * @return the base name
 */
public static String getBaseName(String fileName) {
    int index = fileName.lastIndexOf('.');
    if (index == -1) {
        return fileName;
    } else {
        return fileName.substring(0, index);
    }
}

How to find substring from string?

In C, use the strstr() standard library function:

const char *str = "/user/desktop/abc/post/";
const int exists = strstr(str, "/abc/") != NULL;

Take care to not accidentally find a too-short substring (this is what the starting and ending slashes are for).

Can I have multiple :before pseudo-elements for the same element?

I've resolved this using:

.element:before {
    font-family: "Font Awesome 5 Free" , "CircularStd";
    content: "\f017" " Date";
}

Using the font family "font awesome 5 free" for the icon, and after, We have to specify the font that we are using again because if we doesn't do this, navigator will use the default font (times new roman or something like this).

What algorithm for a tic-tac-toe game can I use to determine the "best move" for the AI?

An attempt without using a play field.

  1. to win(your double)
  2. if not, not to lose(opponent's double)
  3. if not, do you already have a fork(have a double double)
  4. if not, if opponent has a fork
    1. search in blocking points for possible double and fork(ultimate win)
    2. if not search forks in blocking points(which gives the opponent the most losing possibilities )
    3. if not only blocking points(not to lose)
  5. if not search for double and fork(ultimate win)
  6. if not search only for forks which gives opponent the most losing possibilities
  7. if not search only for a double
  8. if not dead end, tie, random.
  9. if not(it means your first move)
    1. if it's the first move of the game;
      1. give the opponent the most losing possibility(the algorithm results in only corners which gives 7 losing point possibility to opponent)
      2. or for breaking boredom just random.
    2. if it's second move of the game;
      1. find only the not losing points(gives a little more options)
      2. or find the points in this list which has the best winning chance(it can be boring,cause it results in only all corners or adjacent corners or center)

Note: When you have double and forks, check if your double gives the opponent a double.if it gives, check if that your new mandatory point is included in your fork list.

How to read from standard input in the console?

I'm late to the party. But how about one liner:

data, err := ioutil.ReadAll(os.Stdin)

and press ctrl+d (EOT) once input is entered on command line.

Get Android Device Name

Simply use

BluetoothAdapter.getDefaultAdapter().getName()

Extract only right most n letters from a string

Write an extension method to express the Right(n); function. The function should deal with null or empty strings returning an empty string, strings shorter than the max length returning the original string and strings longer than the max length returning the max length of rightmost characters.

public static string Right(this string sValue, int iMaxLength)
{
  //Check if the value is valid
  if (string.IsNullOrEmpty(sValue))
  {
    //Set valid empty string as string could be null
    sValue = string.Empty;
  }
  else if (sValue.Length > iMaxLength)
  {
    //Make the string no longer than the max length
    sValue = sValue.Substring(sValue.Length - iMaxLength, iMaxLength);
  }

  //Return the string
  return sValue;
}

simple vba code gives me run time error 91 object variable or with block not set

Also you are trying to set value2 using Set keyword, which is not required. You can directly use rng.value2 = 1

below test code for ref.

Sub test()
    Dim rng As Range
    Set rng = Range("A1")
    rng.Value2 = 1
End Sub

Check if a div exists with jquery

If you are simply checking for the existence of an ID, there is no need to go into jQuery, you could simply:

if(document.getElementById("yourid") !== null)
{
}

getElementById returns null if it can't be found.

Reference.

If however you plan to use the jQuery object later i'd suggest:

$(document).ready(function() {
    var $myDiv = $('#DivID');

    if ( $myDiv.length){
        //you can now reuse  $myDiv here, without having to select it again.
    }


});

A selector always returns a jQuery object, so there shouldn't be a need to check against null (I'd be interested if there is an edge case where you need to check for null - but I don't think there is).

If the selector doesn't find anything then length === 0 which is "falsy" (when converted to bool its false). So if it finds something then it should be "truthy" - so you don't need to check for > 0. Just for it's "truthyness"

XML shape drawable not rendering desired color

I had a similar problem and found that if you remove the size definition, it works for some reason.

Remove:

<size
    android:width="60dp"
    android:height="40dp" />

from the shape.

Let me know if this works!

Facebook page automatic "like" URL (for QR Code)

This has changed, it's now fb://profile/(profileID)

Putty: Getting Server refused our key Error

Steps to fix Root mount (That i followed as i changed permission with ec2-user folder and the authorization key file) This process will be similar to detach and attach a pen-drive

Below are some other scenarios you may encounter -

  1. You're using an SSH private key but the corresponding public key is not in the authorized_keys file.
  2. You don't have permissions for your authorized_keys file.
  3. You don't have permissions for the .ssh folder.
  4. Your authorized_keys file or .ssh folder isn't named correctly.
  5. Your authorized_keys file or .ssh folder was deleted.

Steps to fix them

  • Stop the problematic Ec2 instance
  • Detach the root volume (/dev/sda1)
  • Create an ec2 instance or use an running one
  • Mount the detached volume (/dev/sdvf) to new ec2 instance

Now after you login to new ec2 run below steps

  • Lsblk command - list all available mounts
  • Pick the mount value that you unmount from the problematic instance
  • As ec2-user run “sudo mount /dev/mapper/rootvg-home /mnt” sudo mount /dev/mapper/rootvg-home /mnt
  • Then change directory to /mnt
  • Make all necessary changes

Now we have fixed our volume with the issue that we faced. Mostly it could be user permission issue - Umount /mnt to unmounts it - Now go to the console and point to the volume attached to new instance and detach it - After detached, attached it to your new volume as /dev/sda1

With that said you should be able to login successfully

How to format numbers as currency string?

I suggest the NumberFormat class from Google Visualization API.

You can do something like this:

var formatter = new google.visualization.NumberFormat({
    prefix: '$',
    pattern: '#,###,###.##'
});

formatter.formatValue(1000000); // $ 1,000,000

I hope it helps.

Getting data from selected datagridview row and which event?

First take a label. set its visibility to false, then on the DataGridView_CellClick event write this

private void dataGridView1_CellClick(object sender, DataGridViewCellEventArgs e)
{
    label.Text=dataGridView1.Rows[e.RowIndex].Cells["Your Coloumn name"].Value.ToString();
    // then perform your select statement according to that label.
}
//try it it might work for you

How do I move a redis database from one server to another?

It is also possible to migrate data using the SLAVEOF command:

SLAVEOF old_instance_name old_instance_port

Check that you have receive the keys with KEYS *. You could test the new instance by any other way too, and when you are done just turn replication of:

SLAVEOF NO ONE

How to scroll the page when a modal dialog is longer than the screen?

fixed positioning alone should have fixed that problem but another good workaround to avoid this issue is to place your modal divs or elements at the bottom of the page not within your sites layout. Most modal plugins give their modal positioning absolute to allow the user keep main page scrolling.

<html>
        <body>
        <!-- Put all your page layouts and elements


        <!-- Let the last element be the modal elemment  -->
        <div id="myModals">
        ...
        </div>

        </body>
</html>

What's the difference between ISO 8601 and RFC 3339 Date Formats?

RFC 3339 is mostly a profile of ISO 8601, but is actually inconsistent with it in borrowing the "-00:00" timezone specification from RFC 2822. This is described in the Wikipedia article.

How to vertically align text with icon font?

There are already a few answers here but I found flexbox to be the cleanest and least "hacky" solution:

parent-element {
  display: flex;
  align-items: center;
}

To support Safari < 8, Firefox < 21 and Internet Explorer < 10 (Use this polyfill to support IE8+9) you'll need vendor prefixes:

parent-element {
  display: -webkit-box;
  display: -ms-flexbox;
  display: flex;
  -webkit-box-align: center;
      -ms-flex-align: center;
          align-items: center;
}

CSS Box Shadow - Top and Bottom Only

essentially the shadow is the box shape just offset behind the actual box. in order to hide portions of the shadow, you need to create additional divs and set their z-index above the shadowed box so that the shadow is not visible.

If you'd like to have extremely specific control over your shadows, build them as images and created container divs with the right amount of padding and margins.. then use the png fix to make sure the shadows render properly in all browsers

AngularJS $resource RESTful example

$resource was meant to retrieve data from an endpoint, manipulate it and send it back. You've got some of that in there, but you're not really leveraging it for what it was made to do.

It's fine to have custom methods on your resource, but you don't want to miss out on the cool features it comes with OOTB.

EDIT: I don't think I explained this well enough originally, but $resource does some funky stuff with returns. Todo.get() and Todo.query() both return the resource object, and pass it into the callback for when the get completes. It does some fancy stuff with promises behind the scenes that mean you can call $save() before the get() callback actually fires, and it will wait. It's probably best just to deal with your resource inside of a promise then() or the callback method.

Standard use

var Todo = $resource('/api/1/todo/:id');

//create a todo
var todo1 = new Todo();
todo1.foo = 'bar';
todo1.something = 123;
todo1.$save();

//get and update a todo
var todo2 = Todo.get({id: 123});
todo2.foo += '!';
todo2.$save();

//which is basically the same as...
Todo.get({id: 123}, function(todo) {
   todo.foo += '!';
   todo.$save();
});

//get a list of todos
Todo.query(function(todos) {
  //do something with todos
  angular.forEach(todos, function(todo) {
     todo.foo += ' something';
     todo.$save();
  });
});

//delete a todo
Todo.$delete({id: 123});

Likewise, in the case of what you posted in the OP, you could get a resource object and then call any of your custom functions on it (theoretically):

var something = src.GetTodo({id: 123});
something.foo = 'hi there';
something.UpdateTodo();

I'd experiment with the OOTB implementation before I went and invented my own however. And if you find you're not using any of the default features of $resource, you should probably just be using $http on it's own.

Update: Angular 1.2 and Promises

As of Angular 1.2, resources support promises. But they didn't change the rest of the behavior.

To leverage promises with $resource, you need to use the $promise property on the returned value.

Example using promises

var Todo = $resource('/api/1/todo/:id');

Todo.get({id: 123}).$promise.then(function(todo) {
   // success
   $scope.todos = todos;
}, function(errResponse) {
   // fail
});

Todo.query().$promise.then(function(todos) {
   // success
   $scope.todos = todos;
}, function(errResponse) {
   // fail
});

Just keep in mind that the $promise property is a property on the same values it was returning above. So you can get weird:

These are equivalent

var todo = Todo.get({id: 123}, function() {
   $scope.todo = todo;
});

Todo.get({id: 123}, function(todo) {
   $scope.todo = todo;
});

Todo.get({id: 123}).$promise.then(function(todo) {
   $scope.todo = todo;
});

var todo = Todo.get({id: 123});
todo.$promise.then(function() {
   $scope.todo = todo;
});

Timer Interval 1000 != 1 second?

Any other places you use TimerEventProcessor or Counter?

Anyway, you can not rely on the Event being exactly delivered one per second. The time may vary, and the system will not make sure the average time is correct.

So instead of _Counter, you should use:

 // when starting the timer:
 DateTime _started = DateTime.UtcNow;

 // in TimerEventProcessor:
 seconds = (DateTime.UtcNow-started).TotalSeconds;
 Label.Text = seconds.ToString();

Note: this does not solve the Problem of TimerEventProcessor being called to often, or _Counter incremented to often. it merely masks it, but it is also the right way to do it.

jQuery Ajax requests are getting cancelled without being sent

I had this error in a more spooky way: The network tab and the chrome://net-internals/#events did not show the request after the js was completed. When pausing the js in the error callcack the network tab did show the request as (cancelled). The was consistently called for exactly one (always the same) of several similar requests in a webpage. After restarting Chrome the error did not rise again!

How to convert uint8 Array to base64 Encoded String?

function Uint8ToBase64(u8Arr){
  var CHUNK_SIZE = 0x8000; //arbitrary number
  var index = 0;
  var length = u8Arr.length;
  var result = '';
  var slice;
  while (index < length) {
    slice = u8Arr.subarray(index, Math.min(index + CHUNK_SIZE, length)); 
    result += String.fromCharCode.apply(null, slice);
    index += CHUNK_SIZE;
  }
  return btoa(result);
}

You can use this function if you have a very large Uint8Array. This is for Javascript, can be useful in case of FileReader readAsArrayBuffer.

How can I indent multiple lines in Xcode?

In Xcode 9, you can finally use Tab and Shift+Tab to indent multiple lines of code. Yay!

Php - testing if a radio button is selected and get the value

<?php
if (isset($_POST['submit']) and ! empty($_POST['submit'])) {
    if (isset($_POST['radio'])) {
        $radio_input = $_POST['radio'];
        echo $radio_input;
    }
} else {

}
?>
<form action="radio.php" method="post">
   <input type="radio" name="radio" value="v1"/>
   <input type="radio" name="radio" value="v2"/>
   <input type="radio" name="radio" value="v3"/>
   <input type="radio" name="radio" value="v4"/>
   <input type="radio" name="radio" value="v5"/>
   <input type= "submit" name="submit"value="submit"/>
</form>

How do browser cookie domains work?

There are rules that determine whether a browser will accept the Set-header response header (server-side cookie writing), a slightly different rules/interpretations for cookie set using Javascript (I haven't tested VBScript).

Then there are rules that determine whether the browser will send a cookie along with the page request.

There are differences between the major browser engines how domain matches are handled, and how parameters in path values are interpreted. You can find some empirical evidence in the article How Different Browsers Handle Cookies Differently

How to change the integrated terminal in visual studio code or VSCode

It is possible to get this working in VS Code and have the Cmder terminal be integrated (not pop up).

To do so:

  1. Create an environment variable "CMDER_ROOT" pointing to your Cmder directory.
  2. In (Preferences > User Settings) in VS Code add the following settings:

"terminal.integrated.shell.windows": "cmd.exe"

"terminal.integrated.shellArgs.windows": ["/k", "%CMDER_ROOT%\\vendor\\init.bat"]

How to return result of a SELECT inside a function in PostgreSQL?

Use RETURN QUERY:

CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
  RETURNS TABLE (txt   text   -- also visible as OUT parameter inside function
               , cnt   bigint
               , ratio bigint) AS
$func$
BEGIN
   RETURN QUERY
   SELECT t.txt
        , count(*) AS cnt                 -- column alias only visible inside
        , (count(*) * 100) / _max_tokens  -- I added brackets
   FROM  (
      SELECT t.txt
      FROM   token t
      WHERE  t.chartype = 'ALPHABETIC'
      LIMIT  _max_tokens
      ) t
   GROUP  BY t.txt
   ORDER  BY cnt DESC;                    -- potential ambiguity 
END
$func$  LANGUAGE plpgsql;

Call:

SELECT * FROM word_frequency(123);

Explanation:

  • It is much more practical to explicitly define the return type than simply declaring it as record. This way you don't have to provide a column definition list with every function call. RETURNS TABLE is one way to do that. There are others. Data types of OUT parameters have to match exactly what is returned by the query.

  • Choose names for OUT parameters carefully. They are visible in the function body almost anywhere. Table-qualify columns of the same name to avoid conflicts or unexpected results. I did that for all columns in my example.

    But note the potential naming conflict between the OUT parameter cnt and the column alias of the same name. In this particular case (RETURN QUERY SELECT ...) Postgres uses the column alias over the OUT parameter either way. This can be ambiguous in other contexts, though. There are various ways to avoid any confusion:

    1. Use the ordinal position of the item in the SELECT list: ORDER BY 2 DESC. Example:
    2. Repeat the expression ORDER BY count(*).
    3. (Not applicable here.) Set the configuration parameter plpgsql.variable_conflict or use the special command #variable_conflict error | use_variable | use_column in the function. See:
  • Don't use "text" or "count" as column names. Both are legal to use in Postgres, but "count" is a reserved word in standard SQL and a basic function name and "text" is a basic data type. Can lead to confusing errors. I use txt and cnt in my examples.

  • Added a missing ; and corrected a syntax error in the header. (_max_tokens int), not (int maxTokens) - type after name.

  • While working with integer division, it's better to multiply first and divide later, to minimize the rounding error. Even better: work with numeric (or a floating point type). See below.

Alternative

This is what I think your query should actually look like (calculating a relative share per token):

CREATE OR REPLACE FUNCTION word_frequency(_max_tokens int)
  RETURNS TABLE (txt            text
               , abs_cnt        bigint
               , relative_share numeric) AS
$func$
BEGIN
   RETURN QUERY
   SELECT t.txt, t.cnt
        , round((t.cnt * 100) / (sum(t.cnt) OVER ()), 2)  -- AS relative_share
   FROM  (
      SELECT t.txt, count(*) AS cnt
      FROM   token t
      WHERE  t.chartype = 'ALPHABETIC'
      GROUP  BY t.txt
      ORDER  BY cnt DESC
      LIMIT  _max_tokens
      ) t
   ORDER  BY t.cnt DESC;
END
$func$  LANGUAGE plpgsql;

The expression sum(t.cnt) OVER () is a window function. You could use a CTE instead of the subquery - pretty, but a subquery is typically cheaper in simple cases like this one.

A final explicit RETURN statement is not required (but allowed) when working with OUT parameters or RETURNS TABLE (which makes implicit use of OUT parameters).

round() with two parameters only works for numeric types. count() in the subquery produces a bigint result and a sum() over this bigint produces a numeric result, thus we deal with a numeric number automatically and everything just falls into place.

Search an array for matching attribute

you can use ES5 some. Its pretty first by using callback

function findRestaurent(foodType) {
    var restaurant;
    restaurants.some(function (r) {
        if (r.food === id) {
            restaurant = r;
            return true;
        }
   });
  return restaurant;
}

Is this a good way to clone an object in ES6?

You can do it like this as well,

let copiedData = JSON.parse(JSON.stringify(data));

How can I have grep not print out 'No such file or directory' errors?

I usually don't let grep do the recursion itself. There are usually a few directories you want to skip (.git, .svn...)

You can do clever aliases with stances like that one:

find . \( -name .svn -o -name .git \) -prune -o -type f -exec grep -Hn pattern {} \;

It may seem overkill at first glance, but when you need to filter out some patterns it is quite handy.

How does the stack work in assembly language?

Regarding whether the stack is implemented in the hardware, this Wikipedia article might help.

Some processors families, such as the x86, have special instructions for manipulating the stack of the currently executing thread. Other processor families, including PowerPC and MIPS, do not have explicit stack support, but instead rely on convention and delegate stack management to the operating system's Application Binary Interface (ABI).

That article and the others it links to might be useful to get a feel for stack usage in processors.

How to fix the Hibernate "object references an unsaved transient instance - save the transient instance before flushing" error

To add my 2 cents, I got this same issue when I m accidentally sending null as the ID. Below code depicts my scenario (and OP didn't mention any specific scenario).

Employee emp = new Employee();
emp.setDept(new Dept(deptId)); // --> when deptId PKID is null, same error will be thrown
// calls to other setters...
em.persist(emp);

Here I m setting the existing department id to a new employee instance without actually getting the department entity first, as I don't want to another select query to fire.

In some scenarios, deptId PKID is coming as null from calling method and I m getting the same error.

So, watch for null values for PK ID

Can you delete data from influxdb?

I'm surprised that nobody has mentioned InfluxDB retention policies for automatic data removal. You can set a default retention policy and also set them on a per-database level.

From the docs:

CREATE RETENTION POLICY <retention_policy_name> ON <database_name> DURATION <duration> REPLICATION <n> [DEFAULT]

Making RGB color in Xcode

Color picker plugin for Interface Builder

There's a nice color picker from Panic which works well with IB: http://panic.com/~wade/picker/

Xcode plugin

This one gives you a GUI for choosing colors: http://www.youtube.com/watch?v=eblRfDQM0Go

Objective-C

UIColor *color = [UIColor colorWithRed:(160/255.0) green:(97/255.0) blue:(5/255.0) alpha:1.0];

Swift

let color = UIColor(red: 160/255, green: 97/255, blue: 5/255, alpha: 1.0)

Pods and libraries

There's a nice pod named MPColorTools: https://github.com/marzapower/MPColorTools

How to apply a function to two columns of Pandas dataframe

If you have a huge data-set, then you can use an easy but faster(execution time) way of doing this using swifter:

import pandas as pd
import swifter

def fnc(m,x,c):
    return m*x+c

df = pd.DataFrame({"m": [1,2,3,4,5,6], "c": [1,1,1,1,1,1], "x":[5,3,6,2,6,1]})
df["y"] = df.swifter.apply(lambda x: fnc(x.m, x.x, x.c), axis=1)

Android, landscape only orientation?

One thing I've not found through the answers is that there are two possible landscape orientations, and I wanted to let both be available! So android:screenOrientation="landscape" will lock your app only to one of the 2 possibilities, but if you want your app to be limited to both landscape orientations (for them whom is not clear, having device on portrait, one is rotating left and the other one rotating right) this is what is needed:

android:screenOrientation="sensorLandscape"

Rollback to an old Git commit in a public repo

You can find the commit id related to each commit in the commits section of GitHub/BitBucket/Gitlab. Its very simple, suppose your commit id is 5889575 then if you want to go back to this part in your code then you simply need to type

git checkout 5889575 .

This will take you to that point of time in your code.

SQL Server: how to create a stored procedure

CREATE PROCEDURE [dbo].[USP_StudentInformation]
@S_Name VARCHAR(50)
,@S_Address VARCHAR(500)
AS
BEGIN
SET NOCOUNT ON;

DECLARE @Date VARCHAR(50)

SET @Date = GETDATE()


IF EXISTS (
        SELECT *
        FROM TB_StdFunction
        WHERE S_Name = @S_Name
            AND S_Address = @S_Address
        )
BEGIN
    UPDATE TB_StdFunction
    SET S_Name = @S_Name
        ,S_Address = @S_Address
        ,ModifiedDate = @Date
    WHERE S_Name = @S_Name
        AND S_Address = @S_Address

    SELECT *
    FROM TB_StdFunction
END
ELSE
BEGIN
    INSERT INTO TB_StdFunction (
        S_Name
        ,S_Address
        ,CreatedDate
        )
    VALUES (
        @S_Name
        ,@S_Address
        ,@date          
        )

    SELECT *
    FROM TB_StdFunction
END
END

Table Name :   TB_StdFunction


S_No  INT PRIMARY KEY AUTO_INCREMENT
S_Name nvarchar(50)
S_Address nvarchar(500)
CreatedDate nvarchar(50)
ModifiedDate nvarchar(50)

select unique rows based on single distinct column

I'm assuming you mean that you don't care which row is used to obtain the title, id, and commentname values (you have "rob" for all of the rows, but I don't know if that is actually something that would be enforced or not in your data model). If so, then you can use windowing functions to return the first row for a given email address:

select
    id,
    title,
    email,
    commentname

from
(
select 
    *, 
    row_number() over (partition by email order by id) as RowNbr 

from YourTable
) source

where RowNbr = 1

How do I connect to an MDF database file?

Add space between Data Source

 con.ConnectionString = @"Data Source=.\SQLEXPRESS;
                          AttachDbFilename=c:\folder\SampleDatabase.mdf;
                          Integrated Security=True;
                          Connect Timeout=30;
                          User Instance=True";

Simple proof that GUID is not unique

for(begin; begin<end; begin)
    Console.WriteLine(System.Guid.NewGuid().ToString());

You aren't incrementing begin so the condition begin < end is always true.

python: how to send mail with TO, CC and BCC?

The distinction between TO, CC and BCC occurs only in the text headers. At the SMTP level, everybody is a recipient.

TO - There is a TO: header with this recipient's address

CC - There is a CC: header with this recipient's address

BCC - This recipient isn't mentioned in the headers at all, but is still a recipient.

If you have

TO: [email protected]
CC: [email protected]
BCC: [email protected]

You have three recipients. The headers in the email body will include only the TO: and CC:

How to disable right-click context-menu in JavaScript

I have used this:

document.onkeydown = keyboardDown;
document.onkeyup = keyboardUp;
document.oncontextmenu = function(e){
 var evt = new Object({keyCode:93});
 stopEvent(e);
 keyboardUp(evt);
}
function stopEvent(event){
 if(event.preventDefault != undefined)
  event.preventDefault();
 if(event.stopPropagation != undefined)
  event.stopPropagation();
}
function keyboardDown(e){
 ...
}
function keyboardUp(e){
 ...
}

Then I catch e.keyCode property in those two last functions - if e.keyCode == 93, I know that the user either released the right mouse button or pressed/released the Context Menu key.

Hope it helps.

Where does Android app package gets installed on phone

/data/data/"your app package name " 

but you wont able to read that unless you have a rooted device

Limit on the WHERE col IN (...) condition

Parameterize the query and pass the ids in using a Table Valued Parameter.

For example, define the following type:

CREATE TYPE IdTable AS TABLE (Id INT NOT NULL PRIMARY KEY)

Along with the following stored procedure:

CREATE PROCEDURE sp__Procedure_Name
    @OrderIDs IdTable READONLY,
AS

    SELECT *
    FROM table
    WHERE Col IN (SELECT Id FROM @OrderIDs)

Add key value pair to all objects in array

I would be a little cautious with some of the answers presented in here, the following examples outputs differently according with the approach:

const list = [ { a : 'a', b : 'b' } , { a : 'a2' , b : 'b2' }]

console.log(list.map(item => item.c = 'c'))
// [ 'c', 'c' ]

console.log(list.map(item => {item.c = 'c'; return item;}))
// [ { a: 'a', b: 'b', c: 'c' }, { a: 'a2', b: 'b2', c: 'c' } ]

console.log(list.map(item => Object.assign({}, item, { c : 'c'})))
// [ { a: 'a', b: 'b', c: 'c' }, { a: 'a2', b: 'b2', c: 'c' } ]

I have used node v8.10.0 to test the above pieces of code.

iPhone/iPad browser simulator?

XCode does come with a simulator for the iPad and iPhone.

You can also use Safari on OS X to debug websites on your iOS device.

What is "origin" in Git?

The best answer here:

https://www.git-tower.com/learn/git/glossary/origin

In Git, "origin" is a shorthand name for the remote repository that a project was originally cloned from. More precisely, it is used instead of that original repository's URL - and thereby makes referencing much easier.

Spring Data JPA Update @Query not updating?

The EntityManager doesn't flush change automatically by default. You should use the following option with your statement of query:

@Modifying(clearAutomatically = true)
@Query("update RssFeedEntry feedEntry set feedEntry.read =:isRead where feedEntry.id =:entryId")
void markEntryAsRead(@Param("entryId") Long rssFeedEntryId, @Param("isRead") boolean isRead);

How to build and use Google TensorFlow C++ api

If you don't mind using CMake, there is also tensorflow_cc project that builds and installs TF C++ API for you, along with convenient CMake targets you can link against. The project README contains an example and Dockerfiles you can easily follow.

Add carriage return to a string

I propose use StringBuilder

string s1 = "'99024','99050','99070','99143','99173','99191','99201','99202','99203','99204','99211','99212','99213','99214','99215','99217','99218','99219','99221','99222','99231','99232','99238','99239','99356','99357','99371','99374','99381','99382','99383','99384','99385','99386','99391','99392'";

var stringBuilder = new StringBuilder();           

foreach (var s in s1.Split(','))
{
    stringBuilder.Append(s).Append(",").AppendLine();
}
Console.WriteLine(stringBuilder);

Reverting to a previous revision using TortoiseSVN

In the TortoiseSVN context menu, select 'Update to Revision', enter the desired revision number, and voilà :)

How to compile multiple java source files in command line

or you can use the following to compile the all java source files in current directory..

javac *.java

How can I open a .tex file?

A .tex file should be a LaTeX source file.

If this is the case, that file contains the source code for a LaTeX document. You can open it with any text editor (notepad, notepad++ should work) and you can view the source code. But if you want to view the final formatted document, you need to install a LaTeX distribution and compile the .tex file.

Of course, any program can write any file with any extension, so if this is not a LaTeX document, then we can't know what software you need to install to open it. Maybe if you upload the file somewhere and link it in your question we can see the file and provide more help to you.


Yes, this is the source code of a LaTeX document. If you were able to paste it here, then you are already viewing it. If you want to view the compiled document, you need to install a LaTeX distribution. You can try to install MiKTeX then you can use that to compile the document to a .pdf file.

You can also check out this question and answer for how to do it: How to compile a LaTeX document?

Also, there's an online LaTeX editor and you can paste your code in there to preview the document: https://www.overleaf.com/.

Regular expression to extract numbers from a string

we can use \b as a word boundary and then; \b\d+\b

How to add a button dynamically using jquery

Try this

function test()
{
   $("body").append("<input type='button' id='field' />");
}

Android Studio - Importing external Library/Jar

"simple solution is here"

1 .Create a folder named libs under the app directory for that matter any directory within the project..

2 .Copy Paste your Library to libs folder

3.You simply copy the JAR to your libs/ directory and then from inside Android Studio, right click the Jar that shows up under libs/ > Add As Library..

Peace!

what is right way to do API call in react js?

It would be great to use axios for the api request which supports cancellation, interceptors etc. Along with axios, l use react-redux for state management and redux-saga/redux-thunk for the side effects.

How to display data from database into textbox, and update it

The answer is .IsPostBack as suggested by @Kundan Singh Chouhan. Just to add to it, move your code into a separate method from Page_Load

private void PopulateFields()
{
  using(SqlConnection con1 = new SqlConnection("Data Source=USER-PC;Initial Catalog=webservice_database;Integrated Security=True"))
  {
    DataTable dt = new DataTable();
    con1.Open();
    SqlDataReader myReader = null;  
    SqlCommand myCommand = new SqlCommand("select * from customer_registration where username='" + Session["username"] + "'", con1);

    myReader = myCommand.ExecuteReader();

    while (myReader.Read())
    {
        TextBoxPassword.Text = (myReader["password"].ToString());
        TextBoxRPassword.Text = (myReader["retypepassword"].ToString());
        DropDownListGender.SelectedItem.Text = (myReader["gender"].ToString());
        DropDownListMonth.Text = (myReader["birth"].ToString());
        DropDownListYear.Text = (myReader["birth"].ToString());
        TextBoxAddress.Text = (myReader["address"].ToString());
        TextBoxCity.Text = (myReader["city"].ToString());
        DropDownListCountry.SelectedItem.Text = (myReader["country"].ToString());
        TextBoxPostcode.Text = (myReader["postcode"].ToString());
        TextBoxEmail.Text = (myReader["email"].ToString());
        TextBoxCarno.Text = (myReader["carno"].ToString());
    }
    con1.Close();
  }//end using
}

Then call it in your Page_Load

protected void Page_Load(object sender, EventArgs e)
{

    if(!Page.IsPostBack)
    {
       PopulateFields();
    }
}

How can I push a specific commit to a remote, and not previous commits?

I did want to obmit a old big history and start from a fresh commit i choosed to:

rsync -a --exclude '.git' old-repo/ new-repo/
cd new-repo 
git push 

when now old-repo changes i can apply the patches to the new-repo to rebase them on the new-repo.

Open Excel file for reading with VBA without display

Open the workbook as hidden and then set it as "saved" so that users are not prompted when they close out.

Dim w As Workbooks

Private Sub Workbook_Open()
    Application.ScreenUpdating = False
    Set w = Workbooks
    w.Open Filename:="\\server\PriceList.xlsx", UpdateLinks:=False, ReadOnly:=True 'this is the data file were going to be opening
    ActiveWindow.Visible = False
    ThisWorkbook.Activate
    Application.ScreenUpdating = True
End Sub

Private Sub Workbook_BeforeClose(Cancel As Boolean)
    w.Item(2).Saved = True 'this will suppress the safe prompt for the data file only
End Sub

This is somewhat derivative of the answer posted by Ashok.

By doing it this way though you will not get prompted to save changes back to the Excel file your reading from. This is great if the Excel file your reading from is intended as a data source for validation. For example if the workbook contains product names and price data it can be hidden and you can show an Excel file that represents an invoice with drop downs for product that validates from that price list.

You can then store the price list on a shared location on a network somewhere and make it read-only.

Regular Expression: Any character that is NOT a letter or number

You are looking for:

var yourVar = '1324567890abc§$)%';
yourVar = yourVar.replace(/[^a-zA-Z0-9]/g, ' ');

This replaces all non-alphanumeric characters with a space.

The "g" on the end replaces all occurrences.

Instead of specifying a-z (lowercase) and A-Z (uppercase) you can also use the in-case-sensitive option: /[^a-z0-9]/gi.

How to change line width in ggplot?

Line width in ggplot2 can be changed with argument size= in geom_line().

#sample data
df<-data.frame(x=rnorm(100),y=rnorm(100))
ggplot(df,aes(x=x,y=y))+geom_line(size=2)

enter image description here

Limit results in jQuery UI Autocomplete

I did it in following way :

success: function (result) {
response($.map(result.d.slice(0,10), function (item) {
return {
// Mapping to Required columns (Employee Name and Employee No)
label: item.EmployeeName,
value: item.EmployeeNo
}
}
));

VS 2017 Metadata file '.dll could not be found

I had this same error. In my case I had built a library (call it commsLibrary) that referenced other libraries by including them as projects in my solution. Later, when I built a project and added my commsLibrary, whenever I would build I got the metadata file cannot be found error. So I added the libraries that my comms library referenced to the current project, then it was able to build.

CSS Div Background Image Fixed Height 100% Width

But the thing is that the .chapter class is not dynamic you're declaring a height:1200px

so it's better to use background:cover and set with media queries specific height's for popular resolutions.

form action with javascript

A form action set to a JavaScript function is not widely supported, I'm surprised it works in FireFox.

The best is to just set form action to your PHP script; if you need to do anything before submission you can just add to onsubmit

Edit turned out you didn't need any extra function, just a small change here:

function validateFormOnSubmit(theForm) {
    var reason = "";
    reason += validateName(theForm.name);
    reason += validatePhone(theForm.phone);
    reason += validateEmail(theForm.emaile);

    if (reason != "") {
        alert("Some fields need correction:\n" + reason);
    } else {
        simpleCart.checkout();
    }
    return false;
}

Then in your form:

<form action="#" onsubmit="return validateFormOnSubmit(this);">

ASP.NET Core 1.0 on IIS error 502.5

I got this issue on my production server after my VS project was automatically upgraded to .NET Core 1.1.2.

I simply installed the 1.1.2 .net core runtime from here on my production server: https://www.microsoft.com/net/download/core#/runtime

How do I pass multiple parameters into a function in PowerShell?

I don't see it mentioned here, but splatting your arguments is a useful alternative and becomes especially useful if you are building out the arguments to a command dynamically (as opposed to using Invoke-Expression). You can splat with arrays for positional arguments and hashtables for named arguments. Here are some examples:

Splat With Arrays (Positional Arguments)

Test-Connection with Positional Arguments

Test-Connection www.google.com localhost

With Array Splatting

$argumentArray = 'www.google.com', 'localhost'
Test-Connection @argumentArray

Note that when splatting, we reference the splatted variable with an @ instead of a $. It is the same when using a Hashtable to splat as well.

Splat With Hashtable (Named Arguments)

Test-Connection with Named Arguments

Test-Connection -ComputerName www.google.com -Source localhost

With Hashtable Splatting

$argumentHash = @{
  ComputerName = 'www.google.com'
  Source = 'localhost'
}
Test-Connection @argumentHash

Splat Positional and Named Arguments Simultaneously

Test-Connection With Both Positional and Named Arguments

Test-Connection www.google.com localhost -Count 1

Splatting Array and Hashtables Together

$argumentHash = @{
  Count = 1
}
$argumentArray = 'www.google.com', 'localhost'
Test-Connection @argumentHash @argumentArray

'Static readonly' vs. 'const'

Static Read Only:

The value can be changed through a static constructor at runtime. But not through a member function.

Constant:

By default static. A value cannot be changed from anywhere (constructor, function, runtime, etc. nowhere).

Read Only:

The value can be changed through a constructor at runtime. But not through a member function.

You can have a look at my repository: C# property types.

JavaScript - onClick to get the ID of the clicked button

You need to send the ID as the function parameters. Do it like this:

_x000D_
_x000D_
<button id="1" onClick="reply_click(this.id)">B1</button>_x000D_
<button id="2" onClick="reply_click(this.id)">B2</button>_x000D_
<button id="3" onClick="reply_click(this.id)">B3</button>_x000D_
    _x000D_
<script type="text/javascript">_x000D_
  function reply_click(clicked_id)_x000D_
  {_x000D_
      alert(clicked_id);_x000D_
  }_x000D_
</script>
_x000D_
_x000D_
_x000D_

This will send the ID this.id as clicked_id which you can use in your function. See it in action here.

C# "internal" access modifier when doing unit testing

Keep using private by default. If a member shouldn't be exposed beyond that type, it shouldn't be exposed beyond that type, even to within the same project. This keeps things safer and tidier - when you're using the object, it's clearer which methods you're meant to be able to use.

Having said that, I think it's reasonable to make naturally-private methods internal for test purposes sometimes. I prefer that to using reflection, which is refactoring-unfriendly.

One thing to consider might be a "ForTest" suffix:

internal void DoThisForTest(string name)
{
    DoThis(name);
}

private void DoThis(string name)
{
    // Real implementation
}

Then when you're using the class within the same project, it's obvious (now and in the future) that you shouldn't really be using this method - it's only there for test purposes. This is a bit hacky, and not something I do myself, but it's at least worth consideration.

Body of Http.DELETE request in Angular2

If you use Angular 6 we can put body in http.request method.

Reference from github

You can try this, for me it works.

import { HttpClient } from '@angular/common/http';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss'],
})
export class AppComponent {

  constructor(
    private http: HttpClient
  ) {
    http.request('delete', url, {body: body}).subscribe();
  }
}

git remote add with other SSH port

You need to edit your ~/.ssh/config file. Add something like the following:

Host example.com
    Port 1234

A quick google search shows a few different resources that explain it in more detail than me.

fastest MD5 Implementation in JavaScript

I only need to support HTML5 browsers that support typed arrays (DataView, ArrayBuffer, etc.) I think I took the Joseph Myers code and modified it to support passing in a Uint8Array. I did not catch all the improvements, and there are still probably some char() array artifacts that can be improved on. I needed this for adding to the PouchDB project.

var PouchUtils = {};
PouchUtils.Crypto = {};
(function () {
    PouchUtils.Crypto.MD5 = function (uint8Array) {
        function md5cycle(x, k) {
            var a = x[0], b = x[1], c = x[2], d = x[3];

            a = ff(a, b, c, d, k[0], 7, -680876936);
            d = ff(d, a, b, c, k[1], 12, -389564586);
            c = ff(c, d, a, b, k[2], 17, 606105819);
            b = ff(b, c, d, a, k[3], 22, -1044525330);
            a = ff(a, b, c, d, k[4], 7, -176418897);
            d = ff(d, a, b, c, k[5], 12, 1200080426);
            c = ff(c, d, a, b, k[6], 17, -1473231341);
            b = ff(b, c, d, a, k[7], 22, -45705983);
            a = ff(a, b, c, d, k[8], 7, 1770035416);
            d = ff(d, a, b, c, k[9], 12, -1958414417);
            c = ff(c, d, a, b, k[10], 17, -42063);
            b = ff(b, c, d, a, k[11], 22, -1990404162);
            a = ff(a, b, c, d, k[12], 7, 1804603682);
            d = ff(d, a, b, c, k[13], 12, -40341101);
            c = ff(c, d, a, b, k[14], 17, -1502002290);
            b = ff(b, c, d, a, k[15], 22, 1236535329);

            a = gg(a, b, c, d, k[1], 5, -165796510);
            d = gg(d, a, b, c, k[6], 9, -1069501632);
            c = gg(c, d, a, b, k[11], 14, 643717713);
            b = gg(b, c, d, a, k[0], 20, -373897302);
            a = gg(a, b, c, d, k[5], 5, -701558691);
            d = gg(d, a, b, c, k[10], 9, 38016083);
            c = gg(c, d, a, b, k[15], 14, -660478335);
            b = gg(b, c, d, a, k[4], 20, -405537848);
            a = gg(a, b, c, d, k[9], 5, 568446438);
            d = gg(d, a, b, c, k[14], 9, -1019803690);
            c = gg(c, d, a, b, k[3], 14, -187363961);
            b = gg(b, c, d, a, k[8], 20, 1163531501);
            a = gg(a, b, c, d, k[13], 5, -1444681467);
            d = gg(d, a, b, c, k[2], 9, -51403784);
            c = gg(c, d, a, b, k[7], 14, 1735328473);
            b = gg(b, c, d, a, k[12], 20, -1926607734);

            a = hh(a, b, c, d, k[5], 4, -378558);
            d = hh(d, a, b, c, k[8], 11, -2022574463);
            c = hh(c, d, a, b, k[11], 16, 1839030562);
            b = hh(b, c, d, a, k[14], 23, -35309556);
            a = hh(a, b, c, d, k[1], 4, -1530992060);
            d = hh(d, a, b, c, k[4], 11, 1272893353);
            c = hh(c, d, a, b, k[7], 16, -155497632);
            b = hh(b, c, d, a, k[10], 23, -1094730640);
            a = hh(a, b, c, d, k[13], 4, 681279174);
            d = hh(d, a, b, c, k[0], 11, -358537222);
            c = hh(c, d, a, b, k[3], 16, -722521979);
            b = hh(b, c, d, a, k[6], 23, 76029189);
            a = hh(a, b, c, d, k[9], 4, -640364487);
            d = hh(d, a, b, c, k[12], 11, -421815835);
            c = hh(c, d, a, b, k[15], 16, 530742520);
            b = hh(b, c, d, a, k[2], 23, -995338651);

            a = ii(a, b, c, d, k[0], 6, -198630844);
            d = ii(d, a, b, c, k[7], 10, 1126891415);
            c = ii(c, d, a, b, k[14], 15, -1416354905);
            b = ii(b, c, d, a, k[5], 21, -57434055);
            a = ii(a, b, c, d, k[12], 6, 1700485571);
            d = ii(d, a, b, c, k[3], 10, -1894986606);
            c = ii(c, d, a, b, k[10], 15, -1051523);
            b = ii(b, c, d, a, k[1], 21, -2054922799);
            a = ii(a, b, c, d, k[8], 6, 1873313359);
            d = ii(d, a, b, c, k[15], 10, -30611744);
            c = ii(c, d, a, b, k[6], 15, -1560198380);
            b = ii(b, c, d, a, k[13], 21, 1309151649);
            a = ii(a, b, c, d, k[4], 6, -145523070);
            d = ii(d, a, b, c, k[11], 10, -1120210379);
            c = ii(c, d, a, b, k[2], 15, 718787259);
            b = ii(b, c, d, a, k[9], 21, -343485551);

            x[0] = add32(a, x[0]);
            x[1] = add32(b, x[1]);
            x[2] = add32(c, x[2]);
            x[3] = add32(d, x[3]);

        }

        function cmn(q, a, b, x, s, t) {
            a = add32(add32(a, q), add32(x, t));
            return add32((a << s) | (a >>> (32 - s)), b);
        }

        function ff(a, b, c, d, x, s, t) {
            return cmn((b & c) | ((~b) & d), a, b, x, s, t);
        }

        function gg(a, b, c, d, x, s, t) {
            return cmn((b & d) | (c & (~d)), a, b, x, s, t);
        }

        function hh(a, b, c, d, x, s, t) {
            return cmn(b ^ c ^ d, a, b, x, s, t);
        }

        function ii(a, b, c, d, x, s, t) {
            return cmn(c ^ (b | (~d)), a, b, x, s, t);
        }

        function md51(s) {
            txt = '';
            var n = s.length,
            state = [1732584193, -271733879, -1732584194, 271733878], i;
            for (i = 64; i <= s.length; i += 64) {
                md5cycle(state, md5blk(s.subarray(i - 64, i)));
            }
            s = s.subarray(i - 64);
            var tail = [0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0, 0];
            for (i = 0; i < s.length; i++)
                tail[i >> 2] |= s[i] << ((i % 4) << 3);
            tail[i >> 2] |= 0x80 << ((i % 4) << 3);
            if (i > 55) {
                md5cycle(state, tail);
                for (i = 0; i < 16; i++) tail[i] = 0;
            }
            tail[14] = n * 8;
            md5cycle(state, tail);
            return state;
        }

        /* there needs to be support for Unicode here,
         * unless we pretend that we can redefine the MD-5
         * algorithm for multi-byte characters (perhaps
         * by adding every four 16-bit characters and
         * shortening the sum to 32 bits). Otherwise
         * I suggest performing MD-5 as if every character
         * was two bytes--e.g., 0040 0025 = @%--but then
         * how will an ordinary MD-5 sum be matched?
         * There is no way to standardize text to something
         * like UTF-8 before transformation; speed cost is
         * utterly prohibitive. The JavaScript standard
         * itself needs to look at this: it should start
         * providing access to strings as preformed UTF-8
         * 8-bit unsigned value arrays.
         */
        function md5blk(s) { /* I figured global was faster.   */
            var md5blks = [], i; /* Andy King said do it this way. */
            for (i = 0; i < 64; i += 4) {
                md5blks[i >> 2] = s[i]
                + (s[i + 1] << 8)
                + (s[i + 2] << 16)
                + (s[i + 3] << 24);
            }
            return md5blks;
        }

        var hex_chr = '0123456789abcdef'.split('');

        function rhex(n) {
            var s = '', j = 0;
            for (; j < 4; j++)
                s += hex_chr[(n >> (j * 8 + 4)) & 0x0F]
                + hex_chr[(n >> (j * 8)) & 0x0F];
            return s;
        }

        function hex(x) {
            for (var i = 0; i < x.length; i++)
                x[i] = rhex(x[i]);
            return x.join('');
        }

        function md5(s) {
            return hex(md51(s));
        }

        function add32(a, b) {
            return (a + b) & 0xFFFFFFFF;
        }

        return md5(uint8Array);
    };
})();

Commit only part of a file in Git

git-cola is a great GUI and also has this feature built-in. Just select the lines to stage and press S. If no selection is made, the complete hunk is staged.

How to create a table from select query result in SQL Server 2008

Please be careful, MSSQL: "SELECT * INTO NewTable FROM OldTable"

is not always the same as MYSQL: "create table temp AS select.."

I think that there are occasions when this (in MSSQL) does not guarantee that all the fields in the new table are of the same type as the old.

For example :

create table oldTable (field1 varchar(10), field2 integer, field3 float)
insert into oldTable (field1,field2,field3) values ('1', 1, 1)
select top 1 * into newTable from oldTable

does not always yield:

create table newTable (field1 varchar(10), field2 integer, field3 float)

but may be:

create table newTable (field1 varchar(10), field2 integer, field3 integer)

How do I assign ls to an array in Linux Bash?

It would be this

array=($(ls -d */))

EDIT: See Gordon Davisson's solution for a more general answer (i.e. if your filenames contain special characters). This answer is merely a syntax correction.

How to manually reload Google Map with JavaScript

You can refresh with this:

map.panBy(0, 0);

How can I set the Secure flag on an ASP.NET Session Cookie?

There are two ways, one httpCookies element in web.config allows you to turn on requireSSL which only transmit all cookies including session in SSL only and also inside forms authentication, but if you turn on SSL on httpcookies you must also turn it on inside forms configuration too.

Edit for clarity: Put this in <system.web>

<httpCookies requireSSL="true" />

Chaining Observables in RxJS

About promise composition vs. Rxjs, as this is a frequently asked question, you can refer to a number of previously asked questions on SO, among which :

Basically, flatMap is the equivalent of Promise.then.

For your second question, do you want to replay values already emitted, or do you want to process new values as they arrive? In the first case, check the publishReplay operator. In the second case, standard subscription is enough. However you might need to be aware of the cold. vs. hot dichotomy depending on your source (cf. Hot and Cold observables : are there 'hot' and 'cold' operators? for an illustrated explanation of the concept)

How to output a comma delimited list in jinja python template?

you could also use the builtin "join" filter (http://jinja.pocoo.org/docs/templates/#join like this:

{{ users|join(', ') }}

Find rows that have the same value on a column in MySQL

This works best

Screenshot enter image description here

SELECT RollId, count(*) AS c 
    FROM `tblstudents` 
    GROUP BY RollId 
    HAVING c > 1 
    ORDER BY c DESC

Check if a file is executable

Take a look at the various test operators (this is for the test command itself, but the built-in BASH and TCSH tests are more or less the same).

You'll notice that -x FILE says FILE exists and execute (or search) permission is granted.

BASH, Bourne, Ksh, Zsh Script

if [[ -x "$file" ]]
then
    echo "File '$file' is executable"
else
    echo "File '$file' is not executable or found"
fi

TCSH or CSH Script:

if ( -x "$file" ) then
    echo "File '$file' is executable"
else
    echo "File '$file' is not executable or found"
endif

To determine the type of file it is, try the file command. You can parse the output to see exactly what type of file it is. Word 'o Warning: Sometimes file will return more than one line. Here's what happens on my Mac:

$ file /bin/ls    
/bin/ls: Mach-O universal binary with 2 architectures
/bin/ls (for architecture x86_64):  Mach-O 64-bit executable x86_64
/bin/ls (for architecture i386):    Mach-O executable i386

The file command returns different output depending upon the OS. However, the word executable will be in executable programs, and usually the architecture will appear too.

Compare the above to what I get on my Linux box:

$ file /bin/ls
/bin/ls: ELF 64-bit LSB executable, AMD x86-64, version 1 (SYSV), for GNU/Linux 2.6.9, dynamically linked (uses shared libs), stripped

And a Solaris box:

$ file /bin/ls
/bin/ls:        ELF 32-bit MSB executable SPARC Version 1, dynamically linked, stripped

In all three, you'll see the word executable and the architecture (x86-64, i386, or SPARC with 32-bit).


Addendum

Thank you very much, that seems the way to go. Before I mark this as my answer, can you please guide me as to what kind of script shell check I would have to perform (ie, what kind of parsing) on 'file' in order to check whether I can execute a program ? If such a test is too difficult to make on a general basis, I would at least like to check whether it's a linux executable or osX (Mach-O)

Off the top of my head, you could do something like this in BASH:

if [ -x "$file" ] && file "$file" | grep -q "Mach-O"
then
    echo "This is an executable Mac file"
elif [ -x "$file" ] && file "$file" | grep -q "GNU/Linux"
then
    echo "This is an executable Linux File"
elif [ -x "$file" ] && file "$file" | grep q "shell script"
then
    echo "This is an executable Shell Script"
elif [ -x "$file" ]
then
    echo "This file is merely marked executable, but what type is a mystery"
else
    echo "This file isn't even marked as being executable"
fi

Basically, I'm running the test, then if that is successful, I do a grep on the output of the file command. The grep -q means don't print any output, but use the exit code of grep to see if I found the string. If your system doesn't take grep -q, you can try grep "regex" > /dev/null 2>&1.

Again, the output of the file command may vary from system to system, so you'll have to verify that these will work on your system. Also, I'm checking the executable bit. If a file is a binary executable, but the executable bit isn't on, I'll say it's not executable. This may not be what you want.

Writing data to a local text file with javascript

Our HTML:

<div id="addnew">
    <input type="text" id="id">
    <input type="text" id="content">
    <input type="button" value="Add" id="submit">
</div>

<div id="check">
    <input type="text" id="input">
    <input type="button" value="Search" id="search">
</div>

JS (writing to the txt file):

function writeToFile(d1, d2){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.OpenTextFile("data.txt", 8, false, 0);
    fh.WriteLine(d1 + ',' + d2);
    fh.Close();
}
var submit = document.getElementById("submit");
submit.onclick = function () {
    var id      = document.getElementById("id").value;
    var content = document.getElementById("content").value;
    writeToFile(id, content);
}

checking a particular row:

function readFile(){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.OpenTextFile("data.txt", 1, false, 0);
    var lines = "";
    while (!fh.AtEndOfStream) {
        lines += fh.ReadLine() + "\r";
    }
    fh.Close();
    return lines;
}
var search = document.getElementById("search");
search.onclick = function () {
    var input   = document.getElementById("input").value;
    if (input != "") {
        var text    = readFile();
        var lines   = text.split("\r");
        lines.pop();
        var result;
        for (var i = 0; i < lines.length; i++) {
            if (lines[i].match(new RegExp(input))) {
                result = "Found: " + lines[i].split(",")[1];
            }
        }
        if (result) { alert(result); }
        else { alert(input + " not found!"); }
    }
}

Put these inside a .hta file and run it. Tested on W7, IE11. It's working. Also if you want me to explain what's going on, say so.

How to make System.out.println() shorter

Logging libraries

You could use logging libraries instead of re-inventing the wheel. Log4j for instance will provide methods for different messages like info(), warn() and error().

Homemade methods

or simply make a println method of your own and call it:

void println(Object line) {
    System.out.println(line);
}

println("Hello World");

IDE keyboard shortcuts

IntelliJ IDEA and NetBeans:

you type sout then press TAB, and it types System.out.println() for you, with the cursor in the right place.

Eclipse:

Type syso then press CTRL + SPACE.

Other

Find a "snippets" plugin for your favorite text editor/IDE

Static Import

import static java.lang.System.out;

out.println("Hello World");

Explore JVM languages

Scala

println("Hello, World!")

Groovy

println "Hello, World!" 

Jython

print "Hello, World!" 

JRuby

puts "Hello, World!" 

Clojure

(println "Hello, World!")

Rhino

print('Hello, World!'); 

The name 'model' does not exist in current context in MVC3

I ran into this problem when I inadvertently had a copy of the view file (About.cshtml) for the route /about in the root directory. (Not the views folder) Once I moved the file out of the root, the problem went away.

IIS7 URL Redirection from root to sub directory

You need to download this from Microsoft: http://www.microsoft.com/en-us/download/details.aspx?id=7435.

The tool is called "Microsoft URL Rewrite Module 2.0 for IIS 7" and is described as follows by Microsoft: "URL Rewrite Module 2.0 provides a rule-based rewriting mechanism for changing requested URL’s before they get processed by web server and for modifying response content before it gets served to HTTP clients"

:first-child not working as expected

You could wrap your h1 tags in another div and then the first one would be the first-child. That div doesn't even need styles. It's just a way to segregate those children.

<div class="h1-holder">
    <h1>Title 1</h1>
    <h1>Title 2</h1>
</div>

Android studio: emulator is running but not showing up in Run App "choose a running device"

try to open the emulator and run it parallel with android studio/eclipse and the option will be displayed to select in the choose the device(emuator name, mine is Genymotion).

Stop node.js program from command line

if you are using VS Code and terminal select node from the right side dropdown first and then do Ctrl + C. Then It will work

enter image description here

Press y when you are prompted.

enter image description here

Thanks

How to preserve request url with nginx proxy_pass

nginx also provides the $http_host variable which will pass the port for you. its a concatenation of host and port.

So u just need to do:

proxy_set_header Host $http_host;

How to finish Activity when starting other activity in Android?

Intent i = new Intent(this,Here is your first activity.Class);
    i.setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP);
    startActivity(i);
    finish();

VERR_VMX_MSR_VMXON_DISABLED when starting an image from Oracle virtual box

There is an option in the Virtual Box itself. If you look in the Oracle VM Virtual Box Manager. Select the Virtual Box you want to start. Go to System, the second from above item in the right pane. In System go to the third tab called acceleration. In that tab the first check box is called something like: 'VT-x/AMD-V' (I have the Dutch version, so I don't know the exact string) UNCHECK And then start. That worked for me.

I also got this problem after an upgrade. And I did not have the problem before. But I fail to see the exact connection between the update and the check/unchecking of that option.

By the way, I have no idea where the hell that 'virtualization tab' should be in my 'BIOS'. Maybe I was looking in my PC's BIOS not the System page here which is the BIOS of the VM Machine maybe and that is what you meant Veer7? If it was, it was pretty unclear you meant this. Maybe it's because I have OVM in Dutch not English. But there was nothing called BIOS in the Oracle VM Virtual Box Manager I could find.

Import data into Google Colaboratory

in google colabs if this is your first time,

from google.colab import drive
drive.mount('/content/drive')

run these codes and go through the outputlink then past the pass-prase to the box

when you copy you can copy as follows, go to file right click and copy the path ***don't forget to remove " /content "

f = open("drive/My Drive/RES/dimeric_force_field/Test/python_read/cropped.pdb", "r")

What's the whole point of "localhost", hosts and ports at all?

Well, others have given a good definition of 'localhost'.

It is kind of a defacto for the text representation of the local IP 127.0.0.1.

You can have 'betterhost', 'otherhost', 'someotherhost' if you use a DNS server that can translate it to working IP addresses, OR by modifying the host file. But that's another topic for another day or better day. :P

How to see what privileges are granted to schema of another user

You can use these queries:

select * from all_tab_privs;
select * from dba_sys_privs;
select * from dba_role_privs;

Each of these tables have a grantee column, you can filter on that in the where criteria:

where grantee = 'A'

To query privileges on objects (e.g. tables) in other schema I propose first of all all_tab_privs, it also has a table_schema column.

If you are logged in with the same user whose privileges you want to query, you can use user_tab_privs, user_sys_privs, user_role_privs. They can be queried by a normal non-dba user.

How to get the insert ID in JDBC?

  1. Create Generated Column

    String generatedColumns[] = { "ID" };
    
  2. Pass this geneated Column to your statement

    PreparedStatement stmtInsert = conn.prepareStatement(insertSQL, generatedColumns);
    
  3. Use ResultSet object to fetch the GeneratedKeys on Statement

    ResultSet rs = stmtInsert.getGeneratedKeys();
    
    if (rs.next()) {
        long id = rs.getLong(1);
        System.out.println("Inserted ID -" + id); // display inserted record
    }
    

How to convert an int array to String with toString method in Java

What you want is the Arrays.toString(int[]) method:

import java.util.Arrays;

int[] array = new int[lnr.getLineNumber() + 1];
int i = 0;

..      

System.out.println(Arrays.toString(array));

There is a static Arrays.toString helper method for every different primitive java type; the one for int[] says this:

public static String toString(int[] a)

Returns a string representation of the contents of the specified array. The string representation consists of a list of the array's elements, enclosed in square brackets ("[]"). Adjacent elements are separated by the characters ", " (a comma followed by a space). Elements are converted to strings as by String.valueOf(int). Returns "null" if a is null.

How do I get the browser scroll position in jQuery?

Pure javascript can do!

var scrollTop = window.pageYOffset || document.documentElement.scrollTop;

Selecting multiple columns/fields in MySQL subquery

Yes, you can do this. The knack you need is the concept that there are two ways of getting tables out of the table server. One way is ..

FROM TABLE A

The other way is

FROM (SELECT col as name1, col2 as name2 FROM ...) B

Notice that the select clause and the parentheses around it are a table, a virtual table.

So, using your second code example (I am guessing at the columns you are hoping to retrieve here):

SELECT a.attr, b.id, b.trans, b.lang
FROM attribute a
JOIN (
 SELECT at.id AS id, at.translation AS trans, at.language AS lang, a.attribute
 FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)

Notice that your real table attribute is the first table in this join, and that this virtual table I've called b is the second table.

This technique comes in especially handy when the virtual table is a summary table of some kind. e.g.

SELECT a.attr, b.id, b.trans, b.lang, c.langcount
FROM attribute a
JOIN (
 SELECT at.id AS id, at.translation AS trans, at.language AS lang, at.attribute
 FROM attributeTranslation at
) b ON (a.id = b.attribute AND b.lang = 1)
JOIN (
 SELECT count(*) AS langcount,  at.attribute
 FROM attributeTranslation at
 GROUP BY at.attribute
) c ON (a.id = c.attribute)

See how that goes? You've generated a virtual table c containing two columns, joined it to the other two, used one of the columns for the ON clause, and returned the other as a column in your result set.

What's the difference between "super()" and "super(props)" in React when using es6 classes?

For react version 16.6.3, we use super(props) to initialize state element name : this.props.name

constructor(props){
    super(props);        
}
state = {
  name:this.props.name 
    //otherwise not defined
};

How to convert (transliterate) a string from utf8 to ASCII (single byte) in c#?

Based on Mark's answer above (and Geo's comment), I created a two liner version to remove all ASCII exception cases from a string. Provided for people searching for this answer (as I did).

using System.Text;

// Create encoder with a replacing encoder fallback
var encoder = ASCIIEncoding.GetEncoding("us-ascii", 
    new EncoderReplacementFallback(string.Empty), 
    new DecoderExceptionFallback());

string cleanString = encoder.GetString(encoder.GetBytes(dirtyString)); 

Insert NULL value into INT column

Just use the insert query and put the NULL keyword without quotes. That will work-

INSERT INTO `myDatabase`.`myTable` (`myColumn`) VALUES (NULL);

How to extract duration time from ffmpeg output?

ffmpeg has been substituted by avconv: just substitute avconb to Louis Marascio's answer.

avconv -i file.mp4 2>&1 | grep Duration | sed 's/Duration: \(.*\), start.*/\1/g'

Note: the aditional .* after start to get the time alone !!

MySQL - Make an existing Field Unique

The easiest and fastest way would be with phpmyadmin structure table.

USE PHPMYADMIN ADMIN PANEL!

There it's in Russian language but in English Version should be the same. Just click Unique button. Also from there you can make your columns PRIMARY or DELETE.

Using WGET to run a cronjob PHP

I tried following format, working fine

*/5 * * * * wget --quiet -O /dev/null http://localhost/cron.php

In Windows cmd, how do I prompt for user input and use the result in another command?

Just added the

set /p NetworkLocation= Enter name for network?

echo %NetworkLocation% >> netlist.txt

sequence to my netsh batch job. It now shows me the location I respond as the point for that sample. I continuously >> the output file so I know now "home", "work", "Starbucks", etc. Looking for clear air, I can eavulate the lowest use channels and whether there are 5 or just all 2.4 MHz WLANs around.

How to trigger a click on a link using jQuery

Since this question is ranked #1 in Google for "triggering a click on an <a> element" and no answer actually mentions how you do that, this is how you do it:

$('#titleee a')[0].click();

Explanation: you trigger a click on the underlying html-element, not the jQuery-object.

You're welcome googlers :)

Difference between jar and war in Java

A JAR file extension is .jar and is created with jar command from command prompt (like javac command is executed). Generally, a JAR file contains Java related resources like libraries, classes etc.JAR file is like winzip file except that Jar files are platform independent.

A WAR file is simply a JAR file but contains only Web related Java files like Servlets, JSP, HTML.

To execute a WAR file, a Web server or Web container is required, for example, Tomcat or Weblogic or Websphere. To execute a JAR file, simple JDK is enough.

ASP.NET MVC Bundle not rendering script files on staging server. It works on development server

I ran into the same problem, and I'm not sure why, but it turned out to be that the script link generated by Scripts.Render did not have a .js extension. Because it also does not have a Type attribute the browser was just unable to use it (chrome and firefox).

To resolve this, I changed my bundle configuration to generate compiled files with a js extension, e.g.

            var coreScripts = new ScriptBundle("~/bundles/coreAssets.js")
            .Include("~/scripts/jquery.js");

        var coreStyles = new StyleBundle("~/bundles/coreStyles.css")
            .Include("~/css/bootstrap.css");

Notice in new StyleBundle(... instead of saying ~/bundles/someBundle, I am saying ~/bundlers/someBundle.js or ~/bundles/someStyles.css..

This causes the link generated in the src attribute to have .js or .css on it when optimizations are enabled, as such the browsers know based on the file extension what mime/type to use on the get request and everything works.

If I take off the extension, everything breaks. That's because @Scripts and @Styles doesn't render all the necessary attributes to understand a src to a file with no extension.

CSS center display inline block?

Just use:

line-height:50px

Replace "50px" with the same height as your div.

How to check if a python module exists without importing it

Use one of the functions from pkgutil, for example:

from pkgutil import iter_modules

def module_exists(module_name):
    return module_name in (name for loader, name, ispkg in iter_modules())

How to draw a rounded Rectangle on HTML Canvas?

try to add this line , when you want to get rounded corners : ctx.lineCap = "round";

How to set NODE_ENV to production/development in OS X

export NODE_ENV=production is bad solution, it disappears after restart.

if you want not to worry about that variable anymore - add it to this file:

/etc/environment

don't use export syntax, just write (in new line if some content is already there):

NODE_ENV=production

it works after restart. You will not have to re-enter export NODE_ENV=production command anymore anywhere and just use node with anything you'd like - forever, pm2...

For heroku:

heroku config:set NODE_ENV="production"

which is actually default.

Why an interface can not implement another interface?

Conceptually there are the two "domains" classes and interfaces. Inside these domains you are always extending, only a class implements an interface, which is kind of "crossing the border". So basically "extends" for interfaces mirrors the behavior for classes. At least I think this is the logic behind. It seems than not everybody agrees with this kind of logic (I find it a little bit contrived myself), and in fact there is no technical reason to have two different keywords at all.

How to set enum to null

You can either use the "?" operator for a nullable type.

public Color? myColor = null;

Or use the standard practice for enums that cannot be null by having the FIRST value in the enum (aka 0) be the default value. For example in a case of color None.

public Color myColor = Color.None;

Set folder browser dialog start location

To set the directory selected path and the retrieve the new directory:

dlgBrowseForLogDirectory.SelectedPath = m_LogDirectory;
if (dlgBrowseForLogDirectory.ShowDialog() == DialogResult.OK)
{
     txtLogDirectory.Text = dlgBrowseForLogDirectory.SelectedPath;
}

Java NoSuchAlgorithmException - SunJSSE, sun.security.ssl.SSLContextImpl$DefaultSSLContext

I had the similar issue. The problem was in the passwords: the Keystore and private key used different passwords. (KeyStore explorer was used)

After creating Keystore with the same password as private key had the issue was resolved.

What is the .idea folder?

As of year 2020, JetBrains suggests to commit the .idea folder.
The JetBrains IDEs (webstorm, intellij, android studio, pycharm, clion, etc.) automatically add that folder to your git repository (if there's one).
Inside the folder .idea, has been already created a .gitignore, updated by the IDE itself to avoid to commit user related settings that may contains privacy/password data.

It is safe (and usually useful) to commit the .idea folder.

Do on-demand Mac OS X cloud services exist, comparable to Amazon's EC2 on-demand instances?

I have tried www.wheresmymac.com they are cheap and they have great bandwith so their is low latency. You need teamviewer to log into the virtual system though

How to find column names for all tables in all databases in SQL Server

SELECT * 
FROM information_schema.columns 
WHERE column_name = 'My_Column'

You must set your current database name with USE [db_name] before this query.

Display MessageBox in ASP

If you want to do it from code behind, try this:

System.Web.UI.ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "AlertBox", "alert('Message');", true);

What is the syntax meaning of RAISERROR()

The answer posted to this question as an example taken from Microsoft's MSDN is nice however it doesn't directly demonstrate where the error comes from if it doesn't come from the TRY Block. I prefer this example with a very minor update to the RAISERROR Message within the CATCH Block stating that the error is from the CATCH Block. I demonstrate this in the gif as well.

BEGIN TRY
    /* RAISERROR with severity 11-19 will cause execution
     |  to jump to the CATCH block.
    */
    RAISERROR ('Error raised in TRY block.', -- Message text.
               5, -- Severity. /* Severity Levels Less Than 11 do not jump to the CATCH block */
               1 -- State.
               );
END TRY

BEGIN CATCH
    DECLARE @ErrorMessage  NVARCHAR(4000);
    DECLARE @ErrorSeverity INT;
    DECLARE @ErrorState    INT;

    SELECT 
        @ErrorMessage  = ERROR_MESSAGE(),
        @ErrorSeverity = ERROR_SEVERITY(),
        @ErrorState    = ERROR_STATE();

    /* Use RAISERROR inside the CATCH block to return error
     | information about the original error that caused
     | execution to jump to the CATCH block
    */
    RAISERROR ('Caught Error in Catch', --@ErrorMessage, /* Message text */
               @ErrorSeverity,                           /* Severity     */
               @ErrorState                               /* State        */
               );
END CATCH;

RAISERROR Demo Gif

SVN change username

Based on Ingo Kegel's solution I created a "small" bash script to change the username in all subfolders. Remember to:

  1. Change <NEW_USERNAME> to the new username.
  2. Change <OLD_USERNAME> to the current username (if you currently have no username set, simply remove <OLD_USERNAME>@).

In the code below the svn command is only printed out (not executed). To have the svn command executed, simply remove the echo and whitespace in front of it (just above popd).

for d in */ ; \
do echo $d ; pushd $d ; \
url=$(svn info | grep "URL: svn") ; \
url=$(echo ${url#"URL: "}) ; \
newurl=$(echo $url | sed "s/svn+ssh:\/\/<OLD_USERNAME>@/svn+ssh:\/\/<NEW_USERNAME>@/") ; \
echo "Old url: "$url ; echo "New url: "$newurl ; \
echo svn relocate $url $newurl ; \
popd ; \
done

Hope you find it useful!

How do you initialise a dynamic array in C++?

The array form of new-expression accepts only one form of initializer: an empty (). This, BTW, has the same effect as the empty {} in your non-dynamic initialization.


The above applies to pre-C++11 language. Starting from C++11 one can use uniform initialization syntax with array new-expressions

char* c = new char[length]{};
char* d = new char[length]{ 'a', 'b', 'c' };

google-services.json for different productFlavors

Inspired by @ahmed_khan_89 answer above. We can directly keep like this in gradle file.

android{

// set build flavor here to get the right Google-services configuration(Google Analytics).
    def currentFlavor = "free" //This should match with Build Variant selection. free/paidFull/paidBasic

    println "--> $currentFlavor copy!"
    copy {
        from "src/$currentFlavor/"
        include 'google-services.json'
        into '.'
    }
//other stuff
}

How to input a path with a white space?

Use one of these threee variants:

SOME_PATH="/mnt/someProject/some path"
SOME_PATH='/mnt/someProject/some path'
SOME_PATH=/mnt/someProject/some\ path

GDB: Listing all mapped memory regions for a crashed process

If you have the program and the core file, you can do the following steps.

1) Run the gdb on the program along with core file

 $gdb ./test core

2) type info files and see what different segments are there in the core file.

    (gdb)info files

A sample output:

    (gdb)info files 

    Symbols from "/home/emntech/debugging/test".
    Local core dump file:
`/home/emntech/debugging/core', file type elf32-i386.
  0x0055f000 - 0x0055f000 is load1
  0x0057b000 - 0x0057c000 is load2
  0x0057c000 - 0x0057d000 is load3
  0x00746000 - 0x00747000 is load4
  0x00c86000 - 0x00c86000 is load5
  0x00de0000 - 0x00de0000 is load6
  0x00de1000 - 0x00de3000 is load7
  0x00de3000 - 0x00de4000 is load8
  0x00de4000 - 0x00de7000 is load9
  0x08048000 - 0x08048000 is load10
  0x08049000 - 0x0804a000 is load11
  0x0804a000 - 0x0804b000 is load12
  0xb77b9000 - 0xb77ba000 is load13
  0xb77cc000 - 0xb77ce000 is load14
  0xbf91d000 - 0xbf93f000 is load15

In my case I have 15 segments. Each segment has start of the address and end of the address. Choose any segment to search data for. For example lets select load11 and search for a pattern. Load11 has start address 0x08049000 and ends at 0x804a000.

3) Search for a pattern in the segment.

(gdb) find /w 0x08049000 0x0804a000 0x8048034
 0x804903c
 0x8049040
 2 patterns found

If you don't have executable file you need to use a program which prints data of all segments of a core file. Then you can search for a particular data at an address. I don't find any program as such, you can use the program at the following link which prints data of all segments of a core or an executable file.

 http://emntech.com/programs/printseg.c

How do I prompt a user for confirmation in bash script?

Here's the function I use :

function ask_yes_or_no() {
    read -p "$1 ([y]es or [N]o): "
    case $(echo $REPLY | tr '[A-Z]' '[a-z]') in
        y|yes) echo "yes" ;;
        *)     echo "no" ;;
    esac
}

And an example using it:

if [[ "no" == $(ask_yes_or_no "Are you sure?") || \
      "no" == $(ask_yes_or_no "Are you *really* sure?") ]]
then
    echo "Skipped."
    exit 0
fi

# Do something really dangerous...
  • The output is always "yes" or "no"
  • It's "no" by default
  • Everything except "y" or "yes" returns "no", so it's pretty safe for a dangerous bash script
  • And it's case insensitive, "Y", "Yes", or "YES" work as "yes".

I hope you like it,
Cheers!

How to store Node.js deployment settings/configuration files?

I am a bit late in the game, but I couldn't find what I needed here- or anywhere else - so I wrote something myself.

My requirements for a configuration mechanism are the following:

  1. Support front-end. What is the point if the front-end cannot use the configuration?
  2. Support settings-overrides.js - which looks the same but allows overrides of configuration at settings.js. The idea here is to modify configuration easily without changing the code. I find it useful for saas.

Even though I care less about supporting environments - the will explain how to add it easily to my solution

var publicConfiguration = {
    "title" : "Hello World"
    "demoAuthToken" : undefined, 
    "demoUserId" : undefined, 
    "errorEmail" : null // if null we will not send emails on errors. 

};

var privateConfiguration = {
    "port":9040,
    "adminAuthToken":undefined,
    "adminUserId":undefined
}

var meConf = null;
try{
    meConf = require("../conf/dev/meConf");
}catch( e ) { console.log("meConf does not exist. ignoring.. ")}




var publicConfigurationInitialized = false;
var privateConfigurationInitialized = false;

function getPublicConfiguration(){
    if (!publicConfigurationInitialized) {
        publicConfigurationInitialized = true;
        if (meConf != null) {
            for (var i in publicConfiguration) {
                if (meConf.hasOwnProperty(i)) {
                    publicConfiguration[i] = meConf[i];
                }
            }
        }
    }
    return publicConfiguration;
}


function getPrivateConfiguration(){
    if ( !privateConfigurationInitialized ) {
        privateConfigurationInitialized = true;

        var pubConf = getPublicConfiguration();

        if ( pubConf != null ){
            for ( var j in pubConf ){
                privateConfiguration[j] = pubConf[j];
            }
        }
        if ( meConf != null ){
              for ( var i in meConf ){
                  privateConfiguration[i] = meConf[i];
              }
        }
    }
    return privateConfiguration;

}


exports.sendPublicConfiguration = function( req, res ){
    var name = req.param("name") || "conf";

    res.send( "window." + name + " = " + JSON.stringify(getPublicConfiguration()) + ";");
};


var prConf = getPrivateConfiguration();
if ( prConf != null ){
    for ( var i in prConf ){
        if ( prConf[i] === undefined ){

            throw new Error("undefined configuration [" + i + "]");
        }
        exports[i] = prConf[i];
    }
}


return exports;

Explanation

  • undefined means this property is required
  • null means it is optional
  • meConf - currently the code is target to a file under app. meConf is the overrides files which is targeted to conf/dev - which is ignored by my vcs.
  • publicConfiguration - will be visible from front-end and back-end.
  • privateConfiguration - will be visible from back-end only.
  • sendPublicConfiguration - a route that will expose the public configuration and assign it to a global variable. For example the code below will expose the public configuration as global variable myConf in the front-end. By default it will use the global variable name conf.

    app.get("/backend/conf", require("conf").sendPublicConfiguration);

Logic of overrides

  • privateConfiguration is merged with publicConfiguration and then meConf.
  • publicConfiguration checks each key if it has an override, and uses that override. This way we are not exposing anything private.

Adding environment support

Even though I don't find an "environment support" useful, maybe someone will.

To add environment support you need to change the meConf require statement to something like this (pseudocode)

if ( environment == "production" ) { meConf = require("../conf/dev/meConf").production; }

if ( environment == "development" ) { meConf = require("../conf/dev/meConf").development; }

Similarly you can have a file per environment

 meConf.development.js
 meConf.production.js

and import the right one. The rest of the logic stays the same.

How to initialize a variable of date type in java?

Here's the Javadoc in Oracle's website for the Date class: https://docs.oracle.com/javase/8/docs/api/java/util/Date.html
If you scroll down to "Constructor Summary," you'll see the different options for how a Date object can be instantiated. Like all objects in Java, you create a new one with the following:

Date firstDate = new Date(ConstructorArgsHere);

Now you have a bit of a choice. If you don't pass in any arguments, and just do this,

Date firstDate = new Date();

it will represent the exact date and time at which you called it. Here are some other constructors you may want to make use of:

Date firstDate1 = new Date(int year, int month, int date);
Date firstDate2 = new Date(int year, int month, int date, int hrs, int min);
Date firstDate3 = new Date(int year, int month, int date, int hrs, int min, int sec);

Difference between Parameters.Add(string, object) and Parameters.AddWithValue

Without explicitly providing the type as in command.Parameters.Add("@ID", SqlDbType.Int);, it will try to implicitly convert the input to what it is expecting.

The downside of this, is that the implicit conversion may not be the most optimal of conversions and may cause a performance hit.

There is a discussion about this very topic here: http://forums.asp.net/t/1200255.aspx/1

How do I add a new column to a Spark DataFrame (using PySpark)?

To add a column using a UDF:

df = sqlContext.createDataFrame(
    [(1, "a", 23.0), (3, "B", -23.0)], ("x1", "x2", "x3"))

from pyspark.sql.functions import udf
from pyspark.sql.types import *

def valueToCategory(value):
   if   value == 1: return 'cat1'
   elif value == 2: return 'cat2'
   ...
   else: return 'n/a'

# NOTE: it seems that calls to udf() must be after SparkContext() is called
udfValueToCategory = udf(valueToCategory, StringType())
df_with_cat = df.withColumn("category", udfValueToCategory("x1"))
df_with_cat.show()

## +---+---+-----+---------+
## | x1| x2|   x3| category|
## +---+---+-----+---------+
## |  1|  a| 23.0|     cat1|
## |  3|  B|-23.0|      n/a|
## +---+---+-----+---------+

How can I parse a string with a comma thousand separator to a number?

Replace the comma with an empty string:

_x000D_
_x000D_
var x = parseFloat("2,299.00".replace(",",""))_x000D_
alert(x);
_x000D_
_x000D_
_x000D_

Assignment makes pointer from integer without cast

strToLower's return type should be char* not char (or it should return nothing at all, since it doesn't re-allocate the string)

When to favor ng-if vs. ng-show/ng-hide?

If you use ng-show or ng-hide the content (eg. thumbnails from server) will be loaded irrespective of the value of expression but will be displayed based on the value of the expression.

If you use ng-if the content will be loaded only if the expression of the ng-if evaluates to truthy.

Using ng-if is a good idea in a situation where you are going to load data or images from the server and show those only depending on users interaction. This way your page load will not be blocked by unnecessary nw intensive tasks.

How to grant permission to users for a directory using command line in Windows?

As of Vista, cacls is deprecated. Here's the first couple of help lines:

C:\>cacls
NOTE: Cacls is now deprecated, please use Icacls.

Displays or modifies access control lists (ACLs) of files

You should use icacls instead. This is how you grant John full control over D:\test folder and all its subfolders:

C:\>icacls "D:\test" /grant John:(OI)(CI)F /T

According do MS documentation:

  • F = Full Control
  • CI = Container Inherit - This flag indicates that subordinate containers will inherit this ACE.
  • OI = Object Inherit - This flag indicates that subordinate files will inherit the ACE.
  • /T = Apply recursively to existing files and sub-folders. (OI and CI only apply to new files and sub-folders). Credit: comment by @AlexSpence.

For complete documentation, you may run "icacls" with no arguments or see the Microsoft documentation here and here

More elegant "ps aux | grep -v grep"

You could use preg_split instead of explode and split on [ ]+ (one or more spaces). But I think in this case you could go with preg_match_all and capturing:

preg_match_all('/[ ]php[ ]+\S+[ ]+(\S+)/', $input, $matches);
$result = $matches[1];

The pattern matches a space, php, more spaces, a string of non-spaces (the path), more spaces, and then captures the next string of non-spaces. The first space is mostly to ensure that you don't match php as part of a user name but really only as a command.

An alternative to capturing is the "keep" feature of PCRE. If you use \K in the pattern, everything before it is discarded in the match:

preg_match_all('/[ ]php[ ]+\S+[ ]+\K\S+/', $input, $matches);
$result = $matches[0];

I would use preg_match(). I do something similar for many of my system management scripts. Here is an example:

$test = "user     12052  0.2  0.1 137184 13056 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust1 cron
user     12054  0.2  0.1 137184 13064 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust3 cron
user     12055  0.6  0.1 137844 14220 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust4 cron
user     12057  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust89 cron
user     12058  0.2  0.1 137184 13052 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust435 cron
user     12059  0.3  0.1 135112 13000 ?        Ss   10:00   0:00 php /home/user/public_html/utilities/runProcFile.php cust16 cron
root     12068  0.0  0.0 106088  1164 pts/1    S+   10:00   0:00 sh -c ps aux | grep utilities > /home/user/public_html/logs/dashboard/currentlyPosting.txt
root     12070  0.0  0.0 103240   828 pts/1    R+   10:00   0:00 grep utilities";

$lines = explode("\n", $test);

foreach($lines as $line){
        if(preg_match("/.php[\s+](cust[\d]+)[\s+]cron/i", $line, $matches)){
                print_r($matches);
        }

}

The above prints:

Array
(
    [0] => .php cust1 cron
    [1] => cust1
)
Array
(
    [0] => .php cust3 cron
    [1] => cust3
)
Array
(
    [0] => .php cust4 cron
    [1] => cust4
)
Array
(
    [0] => .php cust89 cron
    [1] => cust89
)
Array
(
    [0] => .php cust435 cron
    [1] => cust435
)
Array
(
    [0] => .php cust16 cron
    [1] => cust16
)

You can set $test to equal the output from exec. the values you are looking for would be in the if statement under the foreach. $matches[1] will have the custx value.

How to export a mysql database using Command Prompt?

First of all open command prompt then open bin directory in cmd (i hope you're aware with cmd commands) go to bin directory of your MySql folder in WAMP program files.

run command

mysqldump -u db_username -p database_name > path_where_to_save_sql_file

press enter system will export particular database and create sql file to the given location.

i hope you got it :) if you have any question please let me know.

How to find the date of a day of the week from a date using PHP?

You can use the date() function:

date('w'); // day of week

or

date('l'); // dayname

Example function to get the day nr.:

function getWeekday($date) {
    return date('w', strtotime($date));
}

echo getWeekday('2012-10-11'); // returns 4

Progress during large file copy (Copy-Item & Write-Progress?)

I haven't heard about progress with Copy-Item. If you don't want to use any external tool, you can experiment with streams. The size of buffer varies, you may try different values (from 2kb to 64kb).

function Copy-File {
    param( [string]$from, [string]$to)
    $ffile = [io.file]::OpenRead($from)
    $tofile = [io.file]::OpenWrite($to)
    Write-Progress -Activity "Copying file" -status "$from -> $to" -PercentComplete 0
    try {
        [byte[]]$buff = new-object byte[] 4096
        [long]$total = [int]$count = 0
        do {
            $count = $ffile.Read($buff, 0, $buff.Length)
            $tofile.Write($buff, 0, $count)
            $total += $count
            if ($total % 1mb -eq 0) {
                Write-Progress -Activity "Copying file" -status "$from -> $to" `
                   -PercentComplete ([long]($total * 100 / $ffile.Length))
            }
        } while ($count -gt 0)
    }
    finally {
        $ffile.Dispose()
        $tofile.Dispose()
        Write-Progress -Activity "Copying file" -Status "Ready" -Completed
    }
}

How to process POST data in Node.js?

And if you don't want to use the entire framework like Express, but you also need different kinds of forms, including uploads, then formaline may be a good choice.

It is listed in Node.js modules

Update int column in table with unique incrementing values

You can try :

DECLARE @counter int
SET @counter = 0
UPDATE [table]
SET [column] = @counter, @counter = @counter + 1```

How to allow all Network connection types HTTP and HTTPS in Android (9) Pie?

Easy Way

Add usesCleartextTraffic to AndroidManifest.xml

<application
...
android:usesCleartextTraffic="true"
...>

Indicates whether the app intends to use cleartext network traffic, such as cleartext HTTP. The default value for apps that target API level 27 or lower is "true". Apps that target API level 28 or higher default to "false".

How the single threaded non blocking IO model works in Node.js

Okay, most things should be clear so far... the tricky part is the SQL: if it is not in reality running in another thread or process in it’s entirety, the SQL-execution has to be broken down into individual steps (by an SQL processor made for asynchronous execution!), where the non-blocking ones are executed, and the blocking ones (e.g. the sleep) actually can be transferred to the kernel (as an alarm interrupt/event) and put on the event list for the main loop.

That means, e.g. the interpretation of the SQL, etc. is done immediately, but during the wait (stored as an event to come in the future by the kernel in some kqueue, epoll, ... structure; together with the other IO operations) the main loop can do other things and eventually check if something happened of those IOs and waits.

So, to rephrase it again: the program is never (allowed to get) stuck, sleeping calls are never executed. Their duty is done by the kernel (write something, wait for something to come over the network, waiting for time to elapse) or another thread or process. – The Node process checks if at least one of those duties is finished by the kernel in the only blocking call to the OS once in each event-loop-cycle. That point is reached, when everything non-blocking is done.

Clear? :-)

I don’t know Node. But where does the c.query come from?

How to check if a particular service is running on Ubuntu

Based on this answer on a similar topic https://askubuntu.com/a/58406
I prefer: /etc/init.d/postgres status

Executable directory where application is running from?

Dim P As String = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().CodeBase)
P = New Uri(P).LocalPath

Is there a way to split a widescreen monitor in to two or more virtual monitors?

What about just using virtual desktops? You can spread your windows around among multiple workspaces. Something like Virtual Dimension should give you most of that functionality. I use virtual desktops all the time on Linux, and it's the next best thing to multiple monitors.

PowerShell try/catch/finally

-ErrorAction Stop is changing things for you. Try adding this and see what you get:

Catch [System.Management.Automation.ActionPreferenceStopException] {
"caught a StopExecution Exception" 
$error[0]
}

How to move a marker in Google Maps API

You are using the correct API, but is the "marker" variable visible to the entire script. I don't see this marker variable declared globally.

Tricks to manage the available memory in an R session

Just to note that data.table package's tables() seems to be a pretty good replacement for Dirk's .ls.objects() custom function (detailed in earlier answers), although just for data.frames/tables and not e.g. matrices, arrays, lists.

How to trap the backspace key using jQuery?

The default behaviour for backspace on most browsers is to go back the the previous page. If you do not want this behaviour you need to make sure the call preventDefault(). However as the OP alluded to, if you always call it preventDefault() you will also make it impossible to delete things in text fields. The code below has a solution adapted from this answer.

Also, rather than using hard coded keyCode values (some values change depending on your browser, although I haven't found that to be true for Backspace or Delete), jQuery has keyCode constants already defined. This makes your code more readable and takes care of any keyCode inconsistencies for you.

// Bind keydown event to this function.  Replace document with jQuery selector
// to only bind to that element.
$(document).keydown(function(e){

    // Use jquery's constants rather than an unintuitive magic number.
    // $.ui.keyCode.DELETE is also available. <- See how constants are better than '46'?
    if (e.keyCode == $.ui.keyCode.BACKSPACE) {

        // Filters out events coming from any of the following tags so Backspace
        // will work when typing text, but not take the page back otherwise.
        var rx = /INPUT|SELECT|TEXTAREA/i;
        if(!rx.test(e.target.tagName) || e.target.disabled || e.target.readOnly ){
            e.preventDefault();
        }

       // Add your code here.
     }
});

How do I declare a model class in my Angular 2 component using TypeScript?

The problem lies that you haven't added Model to either the bootstrap (which will make it a singleton), or to the providers array of your component definition:

@Component({
    selector: "testWidget",
    template: "<div>This is a test and {{param1}} is my param.</div>",
    providers : [
       Model
    ]
})

export class testWidget {
    constructor(private model: Model) {}
}

And yes, you should define Model above the Component. But better would be to put it in his own file.

But if you want it to be just a class from which you can create multiple instances, you better just use new.

@Component({
    selector: "testWidget",
    template: "<div>This is a test and {{param1}} is my param.</div>"
})

export class testWidget {

    private model: Model = new Model();

    constructor() {}
}

How to convert an array of key-value tuples into an object

With Object.fromEntries, you can convert from Array to Object:

_x000D_
_x000D_
var entries = [_x000D_
  ['cardType', 'iDEBIT'],_x000D_
  ['txnAmount', '17.64'],_x000D_
  ['txnId', '20181'],_x000D_
  ['txnType', 'Purchase'],_x000D_
  ['txnDate', '2015/08/13 21:50:04'],_x000D_
  ['respCode', '0'],_x000D_
  ['isoCode', '0'],_x000D_
  ['authCode', ''],_x000D_
  ['acquirerInvoice', '0'],_x000D_
  ['message', ''],_x000D_
  ['isComplete', 'true'],_x000D_
  ['isTimeout', 'false']_x000D_
];_x000D_
var obj = Object.fromEntries(entries);_x000D_
console.log(obj);
_x000D_
_x000D_
_x000D_

Remove the last three characters from a string

   string myString = "abcdxxx";
   if (myString.Length<3)
      return;
   string newString=myString.Remove(myString.Length - 3, 3);

Flash CS4 refuses to let go

Flash still has the ASO file, which is the compiled byte code for your classes. On Windows, you can see the ASO files here:

C:\Documents and Settings\username\Local Settings\Application Data\Adobe\Flash CS4\en\Configuration\Classes\aso

On a Mac, the directory structure is similar in /Users/username/Library/Application Support/


You can remove those files by hand, or in Flash you can select Control->Delete ASO files to remove them.

How to connect to a remote Windows machine to execute commands using python?

is it too late?

I personally agree with Beatrice Len, I used paramiko maybe is an extra step for windows, but I have an example project git hub, feel free to clone or ask me.

https://github.com/davcastroruiz/django-ssh-monitor

Origin is not allowed by Access-Control-Allow-Origin

We also have same problem with phonegap application tested in chrome. One windows machine we use below batch file everyday before Opening Chrome. Remember before running this you need to clean all instance of chrome from task manager or you can select chrome to not to run in background.

BATCH: (use cmd)

cd D:\Program Files (x86)\Google\Chrome\Application\chrome.exe --disable-web-security