Programs & Examples On #Groovy

Groovy is an object-oriented programming language for the Java platform. It is a dynamic language with features similar to those of Python, Ruby, Perl and Smalltalk. It can be used as a scripting language for the Java platform.

Try-catch block in Jenkins pipeline script

try like this (no pun intended btw)

script {
  try {
      sh 'do your stuff'
  } catch (Exception e) {
      echo 'Exception occurred: ' + e.toString()
      sh 'Handle the exception!'
  }
}

The key is to put try...catch in a script block in declarative pipeline syntax. Then it will work. This might be useful if you want to say continue pipeline execution despite failure (eg: test failed, still you need reports..)

Converting a string to int in Groovy

def str = "32"

int num = str as Integer

Gradle does not find tools.jar

In my case (Windows 10) after Java update I lost my Enviroment Variables, so I fixed added the variables again, based in the following steps https://confluence.atlassian.com/doc/setting-the-java_home-variable-in-windows-8895.html

Creating a Jenkins environment variable using Groovy

Just had the same issue. Wanted to dynamically trigger parametrized downstream jobs based on the outcome of some groovy scripting.

Unfortunately on our Jenkins it's not possible to run System Groovy scripts. Therefore I had to do a small workaround:

  1. Run groovy script which creates a properties file where the environment variable to be set is specified

    def props = new File("properties.text")
    if (props.text == 'foo=bar') {
        props.text = 'foo=baz'
    } else {
        props.text = 'foo=bar'
    }
    
  2. Use env inject plugin to inject the variable written into this script

    Inject environment variable
    Property file path: properties.text
    

After that I was able to use the variable 'foo' as parameter for the parametrized trigger plugin. Some kind of workaround. But works!

Groovy write to file (newline)

As @Steven points out, a better way would be:

public void writeToFile(def directory, def fileName, def extension, def infoList) {
  new File("$directory/$fileName$extension").withWriter { out ->
    infoList.each {
      out.println it
    }
  }
}

As this handles the line separator for you, and handles closing the writer as well

(and doesn't open and close the file each time you write a line, which could be slow in your original version)

Groovy method with optional parameters

Just a simplification of the Tim's answer. The groovy way to do it is using a map, as already suggested, but then let's put the mandatory parameters also in the map. This will look like this:

def someMethod(def args) {
    println "MANDATORY1=${args.mandatory1}"
    println "MANDATORY2=${args.mandatory2}"
    println "OPTIONAL1=${args?.optional1}"
    println "OPTIONAL2=${args?.optional2}"
}

someMethod mandatory1:1, mandatory2:2, optional1:3

with the output:

MANDATORY1=1
MANDATORY2=2
OPTIONAL1=3
OPTIONAL2=null

This looks nicer and the advantage of this is that you can change the order of the parameters as you like.

Reading file from Workspace in Jenkins with Groovy script

Although this question is only related to finding directory path ($WORKSPACE) however I had a requirement to read the file from workspace and parse it into JSON object to read sonar issues ( ignore minor/notes issues )

Might help someone, this is how I did it- from readFile

jsonParse(readFile('xyz.json')) 

and jsonParse method-

@NonCPS
def jsonParse(text) {
        return new groovy.json.JsonSlurperClassic().parseText(text);
}

This will also require script approval in ManageJenkins-> In-process script approval

Get a list of all the files in a directory (recursive)

This is what I came up with for a gradle build script:

task doLast {
    ext.FindFile = { list, curPath ->
        def files = file(curPath).listFiles().sort()

        files.each {  File file ->

            if (file.isFile()) {
                list << file
            }
            else {
                list << file  // If you want the directories in the list

                list = FindFile( list, file.path) 
            }
        }
        return list
    }

    def list = []
    def theFile = FindFile(list, "${project.projectDir}")

    list.each {
        println it.path
    }
}

Groovy Shell warning "Could not open/create prefs root node ..."

Had a similar problem when starting apache jmeter on windows 8 64 bit:

[]apache-jmeter-2.13\bin>jmeter
java.util.prefs.WindowsPreferences <init>
WARNING: Could not open/create prefs root node Software\JavaSoft\Prefs     at root 0x80000002. Windows RegCreateKeyEx(...) returned error code 5.

Successfully used Dennis Traub solution, with Mkorsch explanations. Or you can create a file with the extension "reg" and write into it the following:

Windows Registry Editor Version 5.00

[HKEY_LOCAL_MACHINE\SOFTWARE\JavaSoft\Prefs]

... then execute it.

How to retrieve Jenkins build parameters using the Groovy API?

If you are trying to get all parameters passed to Jenkins job you can use the global variable params in your groovy pipeline to fetch it.

http://jenkins_host:8080/pipeline-syntax/globals

params

Exposes all parameters defined in the build as a read-only map with variously typed values. Example:

if (params.BOOLEAN_PARAM_NAME) {doSomething()} or to supply a nontrivial default value:

if (params.get('BOOLEAN_PARAM_NAME', true)) {doSomething()} Note for multibranch (Jenkinsfile) usage: the properties step allows you to define job properties, but these take effect when the step is run, whereas build parameter definitions are generally consulted before the build begins. As a convenience, any parameters currently defined in the job which have default values will also be listed in this map. That allows you to write, for example:

properties([parameters([string(name: 'BRANCH', defaultValue: 'master')])]) git url: '…', branch: params.BRANCH and be assured that the master branch will be checked out even in the initial build of a branch project, or if the previous build did not specify parameters or used a different parameter name.

Use something like below.

def dumpParameter()
{
  params.each {
    println it.key + " = " + it.value
  }
}

how to fix groovy.lang.MissingMethodException: No signature of method:

You can also get this error if the objects you're passing to the method are out of order. In other words say your method takes, in order, a string, an integer, and a date. If you pass a date, then a string, then an integer you will get the same error message.

How to set and reference a variable in a Jenkinsfile

A complete example for scripted pipepline:

       stage('Build'){
            withEnv(["GOPATH=/ws","PATH=/ws/bin:${env.PATH}"]) {
                sh 'bash build.sh'
            }
        }

How to replace string in Groovy

You need to escape the backslash \:

println yourString.replace("\\", "/")

How to check if element in groovy array/hash/collection/list?

You can use Membership operator:

def list = ['Grace','Rob','Emmy']
assert ('Emmy' in list)  

Membership operator Groovy

How to check if a directory containing a file exist?

To check if a folder exists or not, you can simply use the exists() method:

// Create a File object representing the folder 'A/B'
def folder = new File( 'A/B' )

// If it doesn't exist
if( !folder.exists() ) {
  // Create all folders up-to and including B
  folder.mkdirs()
}

// Then, write to file.txt inside B
new File( folder, 'file.txt' ).withWriterAppend { w ->
  w << "Some text\n"
}

Jenkins: Cannot define variable in pipeline stage

In Jenkins 2.138.3 there are two different types of pipelines.

Declarative and Scripted pipelines.

"Declarative pipelines is a new extension of the pipeline DSL (it is basically a pipeline script with only one step, a pipeline step with arguments (called directives), these directives should follow a specific syntax. The point of this new format is that it is more strict and therefore should be easier for those new to pipelines, allow for graphical editing and much more. scripted pipelines is the fallback for advanced requirements."

jenkins pipeline: agent vs node?

Here is an example of using environment and global variables in a Declarative Pipeline. From what I can tell enviroment are static after they are set.

def  browser = 'Unknown'

pipeline {
    agent any
    environment {
    //Use Pipeline Utility Steps plugin to read information from pom.xml into env variables
    IMAGE = readMavenPom().getArtifactId()
    VERSION = readMavenPom().getVersion()


    }
    stages {
        stage('Example') {
            steps {
                script {
                    browser = sh(returnStdout: true, script: 'echo Chrome')
                }
            }
        }
        stage('SNAPSHOT') {
                when {
                    expression { 
                        return !env.JOB_NAME.equals("PROD") && !env.VERSION.contains("RELEASE")
                    }
                }
                steps {
                    echo "SNAPSHOT"
                    echo "${browser}"
                }
            }
            stage('RELEASE') {
                when {
                    expression { 
                        return !env.JOB_NAME.equals("TEST") && !env.VERSION.contains("RELEASE")
                    }
                }
                steps {
                    echo "RELEASE"
                    echo "${browser}"
                }
            }
    }//end of stages 
}//end of pipeline

How to pass parameters or arguments into a gradle task

I would suggest the method presented on the Gradle forum:

def createMinifyCssTask(def brand, def sourceFile, def destFile) {
    return tasks.create("minify${brand}Css", com.eriwen.gradle.css.tasks.MinifyCssTask) {
        source = sourceFile
        dest = destFile
    }
}

I have used this method myself to create custom tasks, and it works very well.

How to pass boolean parameter value in pipeline to downstream jobs?

Not sure if this answers this question. But I was looking for something else. Highly recommend see this 2 minute video. If you wanted to get into more details then see docs - Handling Parameters and this link

And then if you have something like blue ocean, the choices would look something like this:

enter image description here

You define and access your variables like this:

pipeline {
    agent any

    parameters {
    string(defaultValue: "TEST", description: 'What environment?', name: 'userFlag')
    choice(choices: ['TESTING', 'STAGING', 'PRODUCTION'], description: 'Select field for target environment', name: 'DEPLOY_ENV')
    }

    stages {
        stage("foo") {
            steps {
                echo "flag: ${params.userFlag}"
                echo "flag: ${params.DEPLOY_ENV}"
            }
        }
    }
}

Automated builds will pick up the default params. But if you do it manually then you get the option to choose.

And then assign values like this:

enter image description here

Scala vs. Groovy vs. Clojure

Scala

Scala evolved out of a pure functional language known as Funnel and represents a clean-room implementation of almost all Java's syntax, differing only where a clear improvement could be made or where it would compromise the functional nature of the language. Such differences include singleton objects instead of static methods, and type inference.

Much of this was based on Martin Odersky's prior work with the Pizza language. The OO/FP integration goes far beyond mere closures and has led to the language being described as post-functional.

Despite this, it's the closest to Java in many ways. Mainly due to a combination of OO support and static typing, but also due to a explicit goal in the language design that it should integrate very tightly with Java.

Groovy

Groovy explicitly tackles two of Java's biggest criticisms by

  • being dynamically typed, which removes a lot of boilerplate and
  • adding closures to the language.

It's perhaps syntactically closest to Java, not offering some of the richer functional constructs that Clojure and Scala provide, but still offering a definite evolutionary improvement - especially for writing script-syle programs.

Groovy has the strongest commercial backing of the three languages, mostly via springsource.

Clojure

Clojure is a functional language in the LISP family, it's also dynamically typed.

Features such as STM support give it some of the best out-of-the-box concurrency support, whereas Scala requires a 3rd-party library such as Akka to duplicate this.

Syntactically, it's also the furthest of the three languages from typical Java code.

I also have to disclose that I'm most acquainted with Scala :)

get current date and time in groovy?

Date has the time part, so we only need to extract it from Date

I personally prefer the default format parameter of the Date when date and time needs to be separated instead of using the extra SimpleDateFormat

Date date = new Date()
String datePart = date.format("dd/MM/yyyy")
String timePart = date.format("HH:mm:ss")

println "datePart : " + datePart + "\ttimePart : " + timePart

Groovy / grails how to determine a data type?

somObject instanceof Date

should be

somObject instanceOf Date

Dynamically adding elements to ArrayList in Groovy

What you actually created with:

MyType[] list = []

Was fixed size array (not list) with size of 0. You can create fixed size array of size for example 4 with:

MyType[] array = new MyType[4]

But there's no add method of course.

If you create list with def it's something like creating this instance with Object (You can read more about def here). And [] creates empty ArrayList in this case.

So using def list = [] you can then append new items with add() method of ArrayList

list.add(new MyType())

Or more groovy way with overloaded left shift operator:

list << new MyType() 

Jenkins pipeline if else not working

        if ( params.build_deploy == '1' ) {
            println "build_deploy ? ${params.build_deploy}"
              jobB = build job: 'k8s-core-user_deploy', propagate: false, wait: true, parameters: [
                         string(name:'environment', value: "${params.environment}"),
                         string(name:'branch_name', value: "${params.branch_name}"),
                         string(name:'service_name', value: "${params.service_name}"),                      
                     ]
            println jobB.getResult()
        }

How can I trigger another job from a jenkins pipeline (jenkinsfile) with GitHub Org Plugin?

You can use the build job step from Jenkins Pipeline (Minimum Jenkins requirement: 2.130).

Here's the full API for the build step: https://jenkins.io/doc/pipeline/steps/pipeline-build-step/

How to use build:

  • job: Name of a downstream job to build. May be another Pipeline job, but more commonly a freestyle or other project.
    • Use a simple name if the job is in the same folder as this upstream Pipeline job;
    • You can instead use relative paths like ../sister-folder/downstream
    • Or you can use absolute paths like /top-level-folder/nested-folder/downstream

Trigger another job using a branch as a param

At my company many of our branches include "/". You must replace any instances of "/" with "%2F" (as it appears in the URL of the job).

In this example we're using relative paths

    stage('Trigger Branch Build') {
        steps {
            script {
                    echo "Triggering job for branch ${env.BRANCH_NAME}"
                    BRANCH_TO_TAG=env.BRANCH_NAME.replace("/","%2F")
                    build job: "../my-relative-job/${BRANCH_TO_TAG}", wait: false
            }
        }
    }

Trigger another job using build number as a param

build job: 'your-job-name', 
    parameters: [
        string(name: 'passed_build_number_param', value: String.valueOf(BUILD_NUMBER)),
        string(name: 'complex_param', value: 'prefix-' + String.valueOf(BUILD_NUMBER))
    ]

Trigger many jobs in parallel

Source: https://jenkins.io/blog/2017/01/19/converting-conditional-to-pipeline/

More info on Parallel here: https://jenkins.io/doc/book/pipeline/syntax/#parallel

    stage ('Trigger Builds In Parallel') {
        steps {
            // Freestyle build trigger calls a list of jobs
            // Pipeline build() step only calls one job
            // To run all three jobs in parallel, we use "parallel" step
            // https://jenkins.io/doc/pipeline/examples/#jobs-in-parallel
            parallel (
                linux: {
                    build job: 'full-build-linux', parameters: [string(name: 'GIT_BRANCH_NAME', value: env.BRANCH_NAME)]
                },
                mac: {
                    build job: 'full-build-mac', parameters: [string(name: 'GIT_BRANCH_NAME', value: env.BRANCH_NAME)]
                },
                windows: {
                    build job: 'full-build-windows', parameters: [string(name: 'GIT_BRANCH_NAME', value: env.BRANCH_NAME)]
                },
                failFast: false)
        }
    }

Or alternatively:

    stage('Build A and B') {
            failFast true
            parallel {
                stage('Build A') {
                    steps {
                            build job: "/project/A/${env.BRANCH}", wait: true
                    }
                }
                stage('Build B') {
                    steps {
                            build job: "/project/B/${env.BRANCH}", wait: true
                    }
                }
            }
    }

for each loop in groovy

you can use below groovy code for maps with foreachloop

def map=[key1:'value1',key2:'value2']

for(item in map)
{
log.info item.value // this will print value1 value2
log.info item // this will print key1=value1 key2=value2
}

Checking if a collection is null or empty in Groovy

!members.find()

I think now the best way to solve this issue is code above. It works since Groovy 1.8.1 http://docs.groovy-lang.org/docs/next/html/groovy-jdk/java/util/Collection.html#find(). Examples:

def lst1 = []
assert !lst1.find()

def lst2 = [null]
assert !lst2.find()

def lst3 = [null,2,null]
assert lst3.find()

def lst4 = [null,null,null]
assert !lst4.find()

def lst5 = [null, 0, 0.0, false, '', [], 42, 43]
assert lst5.find() == 42

def lst6 = null; 
assert !lst6.find()

Found shared references to a collection org.hibernate.HibernateException

In a one to many and many to one relationship this error will occur. If you attempt to devote same instance from many to one entity to more than one instance from one to many entity.

For example, each person can have many books but each of these books can be owned by only one person if you consider more than one owner for a book this issue is raised.

How to print a Groovy variable in Jenkins?

The following code worked for me:

echo userInput

Copy entire directory contents to another directory?

With regard to Java, there is no such method in the standard API. In Java 7, the java.nio.file.Files class will provide a copy convenience method.

References

  1. The Java Tutorials

  2. Copying files from one directory to another in Java

How do I create and access the global variables in Groovy?

Could not figure out what you want, but you need something like this ? :

?def a = { b -> b = 1 }
?bValue = a()
println b // prints 1

Now bValue contains the value of b which is a variable in the closure a. Now you can do anything with bValue Let me know if i have misunderstood your question

How to read a file in Groovy into a string?

the easiest way would be

new File(filename).getText()

which means you could just do:

new File(filename).text

Can you break from a Groovy "each" closure?

I agree with other answers not to use an exception to break an each. I also do not prefer to create an extra closure eachWithBreak, instead of this I prefer a modern approach: let's use the each to iterate over the collection, as requested, but refine the collection to contain only those elements to be iterated, for example with findAll:

collection.findAll { !endCondition }.each { doSomething() }

For example, if we what to break when the counter == 3 we can write this code (already suggested):

(0..5)
    .findAll { it < 3  }
    .each { println it }

This will output

0
1
2

So far so good, but you will notice a small discrepancy though. Our end condition, negation of counter == 3 is not quite correct because !(counter==3) is not equivalent with it < 3. This is necessary to make the code work since findAll does not actually break the loop but continues until the end.

To emulate a real situation, let's say we have this code:

for (n in 0..5) {
    if (n == 3)
        break
    println n
}

but we want to use each, so let's rewrite it using a function to simulate a break condition:

def breakWhen(nr) { nr == 3 }
(0..5)
    .findAll { !breakWhen(it) }
    .each { println it }

with the output:

0
1
2
4
5

now you see the problem with findAll. This does not stop, but ignores that element where the condition is not met.

To solve this issues, we need an extra variable to remember when the breaking condition become true. After this moment, findAll must ignore all remaining elements.

This is how it should look like:

def breakWhen(nr) { nr == 3 }
def loop = true
(0..5)
    .findAll {
        if (breakWhen(it))
            loop = false
        !breakWhen(it) && loop
    } .each {
        println it
    }

with the output:

0
1
2

That's what we want!

Including a groovy script in another groovy

Another way to do this is to define the functions in a groovy class and parse and add the file to the classpath at runtime:

File sourceFile = new File("path_to_file.groovy");
Class groovyClass = new GroovyClassLoader(getClass().getClassLoader()).parseClass(sourceFile);
GroovyObject myObject = (GroovyObject) groovyClass.newInstance();

How do I add an element to a list in Groovy?

From the documentation:

We can add to a list in many ways:

assert [1,2] + 3 + [4,5] + 6 == [1, 2, 3, 4, 5, 6]
assert [1,2].plus(3).plus([4,5]).plus(6) == [1, 2, 3, 4, 5, 6]
    //equivalent method for +
def a= [1,2,3]; a += 4; a += [5,6]; assert a == [1,2,3,4,5,6]
assert [1, *[222, 333], 456] == [1, 222, 333, 456]
assert [ *[1,2,3] ] == [1,2,3]
assert [ 1, [2,3,[4,5],6], 7, [8,9] ].flatten() == [1, 2, 3, 4, 5, 6, 7, 8, 9]

def list= [1,2]
list.add(3) //alternative method name
list.addAll([5,4]) //alternative method name
assert list == [1,2,3,5,4]

list= [1,2]
list.add(1,3) //add 3 just before index 1
assert list == [1,3,2]
list.addAll(2,[5,4]) //add [5,4] just before index 2
assert list == [1,3,5,4,2]

list = ['a', 'b', 'z', 'e', 'u', 'v', 'g']
list[8] = 'x'
assert list == ['a', 'b', 'z', 'e', 'u', 'v', 'g', null, 'x']

You can also do:

def myNewList = myList << "fifth"

Groovy String to Date

I think the best easy way in this case is to use parseToStringDate which is part of GDK (Groovy JDK enhancements):

Parse a String matching the pattern EEE MMM dd HH:mm:ss zzz yyyy containing US-locale-constants only (e.g. Sat for Saturdays). Such a string is generated by the toString method of Date

Example:

println(Date.parseToStringDate("Tue Aug 10 16:02:43 PST 2010").format('MM-dd-yyyy'))

Using Javamail to connect to Gmail smtp server ignores specified port and tries to use 25

Maybe useful for anyone else running into this issue: When setting the port on the properties:

props.put("mail.smtp.port", smtpPort);

..make sure to use a string object. Using a numeric (ie Long) object will cause this statement to seemingly have no effect.

Could not find method compile() for arguments Gradle

Just for the record: I accidentally enabled Offline work under Preferences -> Build,Execution,Deployment -> Gradle -> uncheck Offline Work, but the error message was misleading

Access to build environment variables from a groovy script in a Jenkins build step (Windows)

The Scriptler Groovy script doesn't seem to get all the environment variables of the build. But what you can do is force them in as parameters to the script:

  1. When you add the Scriptler build step into your job, select the option "Define script parameters"

  2. Add a parameter for each environment variable you want to pass in. For example "Name: JOB_NAME", "Value: $JOB_NAME". The value will get expanded from the Jenkins build environment using '$envName' type variables, most fields in the job configuration settings support this sort of expansion from my experience.

  3. In your script, you should have a variable with the same name as the parameter, so you can access the parameters with something like:

    println "JOB_NAME = $JOB_NAME"

I haven't used Sciptler myself apart from some experimentation, but your question posed an interesting problem. I hope this helps!

How do I get the output of a shell command executed using into a variable from Jenkinsfile (groovy)?

Easiest way is use this way

my_var=`echo 2` echo $my_var output : 2

note that is not simple single quote is back quote ( ` ).

How to get just the parent directory name of a specific file

If you have just String path and don't want to create new File object you can use something like:

public static String getParentDirPath(String fileOrDirPath) {
    boolean endsWithSlash = fileOrDirPath.endsWith(File.separator);
    return fileOrDirPath.substring(0, fileOrDirPath.lastIndexOf(File.separatorChar, 
            endsWithSlash ? fileOrDirPath.length() - 2 : fileOrDirPath.length() - 1));
}

How can I use random numbers in groovy?

There is no such method as java.util.Random.getRandomDigits.

To get a random number use nextInt:

return random.nextInt(10 ** num)

Also you should create the random object once when your application starts:

Random random = new Random()

You should not create a new random object every time you want a new random number. Doing this destroys the randomness.

Groovy - How to compare the string?

This should be an answer

str2.equals( str )

If you want to ignore case

str2.equalsIgnoreCase( str )

Conditional step/stage in Jenkins pipeline

Doing the same in declarative pipeline syntax, below are few examples:

stage('master-branch-stuff') {
    when {
        branch 'master'
    }
    steps {
        echo 'run this stage - ony if the branch = master branch'
    }
}

stage('feature-branch-stuff') {
    when {
        branch 'feature/*'
    }
    steps {
        echo 'run this stage - only if the branch name started with feature/'
    }
}

stage('expression-branch') {
    when {
        expression {
            return env.BRANCH_NAME != 'master';
        }
    }
    steps {
        echo 'run this stage - when branch is not equal to master'
    }
}

stage('env-specific-stuff') {
    when { 
        environment name: 'NAME', value: 'this' 
    }
    steps {
        echo 'run this stage - only if the env name and value matches'
    }
}

More effective ways coming up - https://issues.jenkins-ci.org/browse/JENKINS-41187
Also look at - https://jenkins.io/doc/book/pipeline/syntax/#when


The directive beforeAgent true can be set to avoid spinning up an agent to run the conditional, if the conditional doesn't require git state to decide whether to run:

when { beforeAgent true; expression { return isStageConfigured(config) } }

Release post and docs


UPDATE
New WHEN Clause
REF: https://jenkins.io/blog/2018/04/09/whats-in-declarative

equals - Compares two values - strings, variables, numbers, booleans - and returns true if they’re equal. I’m honestly not sure how we missed adding this earlier! You can do "not equals" comparisons using the not { equals ... } combination too.

changeRequest - In its simplest form, this will return true if this Pipeline is building a change request, such as a GitHub pull request. You can also do more detailed checks against the change request, allowing you to ask "is this a change request against the master branch?" and much more.

buildingTag - A simple condition that just checks if the Pipeline is running against a tag in SCM, rather than a branch or a specific commit reference.

tag - A more detailed equivalent of buildingTag, allowing you to check against the tag name itself.

groovy: safely find a key in a map and return its value

The whole point of using Maps is direct access. If you know for sure that the value in a map will never be Groovy-false, then you can do this:

def mymap = [name:"Gromit", likes:"cheese", id:1234]
def key = "likes"

if(mymap[key]) {
    println mymap[key]
}

However, if the value could potentially be Groovy-false, you should use:

if(mymap.containsKey(key)) {
    println mymap[key]
}

The easiest solution, though, if you know the value isn't going to be Groovy-false (or you can ignore that), and want a default value, is like this:

def value = mymap[key] ?: "default"

All three of these solutions are significantly faster than your examples, because they don't scan the entire map for keys. They take advantage of the HashMap (or LinkedHashMap) design that makes direct key access nearly instantaneous.

Jenkins pipeline how to change to another folder

The dir wrapper can wrap, any other step, and it all works inside a steps block, for example:

steps {
    sh "pwd"
    dir('your-sub-directory') {
      sh "pwd"
    }
    sh "pwd"
} 

Running Groovy script from the command line

It will work on Linux kernel 2.6.28 (confirmed on 4.9.x). It won't work on FreeBSD and other Unix flavors.

Your /usr/local/bin/groovy is a shell script wrapping the Java runtime running Groovy.

See the Interpreter Scripts section of EXECVE(2) and EXECVE(2).

Groovy executing shell commands

I find this more idiomatic:

def proc = "ls foo.txt doesnotexist.txt".execute()
assert proc.in.text == "foo.txt\n"
assert proc.err.text == "ls: doesnotexist.txt: No such file or directory\n"

As another post mentions, these are blocking calls, but since we want to work with the output, this may be necessary.

How to access parameters in a Parameterized Build?

As per Pipeline plugin tutorial:

If you have configured your pipeline to accept parameters when it is built — Build with Parameters — they are accessible as Groovy variables of the same name.

So try to access the variable directly, e.g.:

node()
{
     print "DEBUG: parameter foo = " + foo
     print "DEBUG: parameter bar = ${bar}"
}

Groovy built-in REST/HTTP client?

If your needs are simple and you want to avoid adding additional dependencies you may be able to use the getText() methods that Groovy adds to the java.net.URL class:

new URL("http://stackoverflow.com").getText()

// or

new URL("http://stackoverflow.com")
        .getText(connectTimeout: 5000, 
                readTimeout: 10000, 
                useCaches: true, 
                allowUserInteraction: false, 
                requestProperties: ['Connection': 'close'])

If you are expecting binary data back there is also similar functionality provided by the newInputStream() methods.

how to parse json using groovy

You can map JSON to specific class in Groovy using as operator:

import groovy.json.JsonSlurper

String json = '''
{
  "name": "John",  
  "age": 20
}
'''

def person = new JsonSlurper().parseText(json) as Person 

with(person) {
    assert name == 'John'
    assert age == 20
}

Groovy - Convert object to JSON string

I couldn't get the other answers to work within the evaluate console in Intellij so...

groovy.json.JsonOutput.toJson(myObject)

This works quite well, but unfortunately

groovy.json.JsonOutput.prettyString(myObject)

didn't work for me.

To get it pretty printed I had to do this...

groovy.json.JsonOutput.prettyPrint(groovy.json.JsonOutput.toJson(myObject))

String concatenation with Groovy

def my_string = "some string"
println "here: " + my_string 

Not quite sure why the answer above needs to go into benchmarks, string buffers, tests, etc.

Java/Groovy - simple date reformatting

oldDate is not in the format of the SimpleDateFormat you are using to parse it.

Try this format: dd-MMM-yyyy - It matches what you're trying to parse.

groovy.lang.MissingPropertyException: No such property: jenkins for class: groovy.lang.Binding

Please double check that jenkins is not blocking this import. Go to script approvals and check to see if it is blocking it. If it is click allow.

https://jenkins.io/doc/book/managing/script-approval/

Converting File to MultiPartFile

File file = new File("src/test/resources/input.txt");
FileInputStream input = new FileInputStream(file);
MultipartFile multipartFile = new MockMultipartFile("file",
            file.getName(), "text/plain", IOUtils.toByteArray(input));

Map with Key as String and Value as List in Groovy

def map = [:]
map["stringKey"] = [1, 2, 3, 4]
map["anotherKey"] = [55, 66, 77]

assert map["anotherKey"] == [55, 66, 77] 

Test only if variable is not null in if statement

I don't believe the expression is sensical as it is.

Elvis means "if truthy, use the value, else use this other thing."

Your "other thing" is a closure, and the value is status != null, neither of which would seem to be what you want. If status is null, Elvis says true. If it's not, you get an extra layer of closure.

Why can't you just use:

(it.description == desc) && ((status == null) || (it.status == status))

Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find calls, just use an intermediate variable.

How to list all `env` properties within jenkins pipeline job?

Here's a quick script you can add as a pipeline job to list all environment variables:

node {
    echo(env.getEnvironment().collect({environmentVariable ->  "${environmentVariable.key} = ${environmentVariable.value}"}).join("\n"))
    echo(System.getenv().collect({environmentVariable ->  "${environmentVariable.key} = ${environmentVariable.value}"}).join("\n"))
}

This will list both system and Jenkins variables.

Jenkins: Can comments be added to a Jenkinsfile?

You can use block (/***/) or single line comment (//) for each line. You should use "#" in sh command.

Block comment

_x000D_
_x000D_
/*  _x000D_
post {_x000D_
    success {_x000D_
      mail to: "[email protected]", _x000D_
      subject:"SUCCESS: ${currentBuild.fullDisplayName}", _x000D_
      body: "Yay, we passed."_x000D_
    }_x000D_
    failure {_x000D_
      mail to: "[email protected]", _x000D_
      subject:"FAILURE: ${currentBuild.fullDisplayName}", _x000D_
      body: "Boo, we failed."_x000D_
    }_x000D_
  }_x000D_
*/
_x000D_
_x000D_
_x000D_

Single Line

_x000D_
_x000D_
// post {_x000D_
//     success {_x000D_
//       mail to: "[email protected]", _x000D_
//       subject:"SUCCESS: ${currentBuild.fullDisplayName}", _x000D_
//       body: "Yay, we passed."_x000D_
//     }_x000D_
//     failure {_x000D_
//       mail to: "[email protected]", _x000D_
//       subject:"FAILURE: ${currentBuild.fullDisplayName}", _x000D_
//       body: "Boo, we failed."_x000D_
//     }_x000D_
// }
_x000D_
_x000D_
_x000D_

Comment in 'sh' command

_x000D_
_x000D_
        stage('Unit Test') {_x000D_
            steps {_x000D_
                ansiColor('xterm'){_x000D_
                  sh '''_x000D_
                  npm test_x000D_
                  # this is a comment in sh_x000D_
                  '''_x000D_
                }_x000D_
            }_x000D_
        }
_x000D_
_x000D_
_x000D_

Run bash command on jenkins pipeline

The Groovy script you provided is formatting the first line as a blank line in the resultant script. The shebang, telling the script to run with /bin/bash instead of /bin/sh, needs to be on the first line of the file or it will be ignored.

So instead, you should format your Groovy like this:

stage('Setting the variables values') {
    steps {
         sh '''#!/bin/bash
                 echo "hello world" 
         '''
    }
}

And it will execute with /bin/bash.

Difference between Groovy Binary and Source release?

The source release is the raw, uncompiled code. You could read it yourself. To use it, it must be compiled on your machine. Binary means the code was compiled into a machine language format that the computer can read, then execute. No human can understand the binary file unless its been dissected, or opened with some program that let's you read the executable as code.

Hibernate: Automatically creating/updating the db tables based on entity classes

In applicationContext.xml file:

<bean id="entityManagerFactoryBean" class="org.springframework.orm.jpa.LocalContainerEntityManagerFactoryBean">
      <property name="dataSource" ref="dataSource" />
      <!-- This makes /META-INF/persistence.xml is no longer necessary -->
      <property name="packagesToScan" value="com.howtodoinjava.demo.model" />
      <!-- JpaVendorAdapter implementation for Hibernate EntityManager.
           Exposes Hibernate's persistence provider and EntityManager extension interface -->
      <property name="jpaVendorAdapter">
         <bean class="org.springframework.orm.jpa.vendor.HibernateJpaVendorAdapter" />
      </property>
      <property name="jpaProperties">
         <props>
            <prop key="hibernate.hbm2ddl.auto">update</prop>
            <prop key="hibernate.dialect">org.hibernate.dialect.MySQL5Dialect</prop>
         </props>
      </property>
   </bean>

How to retrieve current workspace using Jenkins Pipeline Groovy script?

I have successfully used as shown below in Jenkinsfile:

steps {
  script {
    def reportPath = "${WORKSPACE}/target/report"
    ...
  }
}

Splitting String with delimiter

split doesn't work that way in groovy. you have to use tokenize...

See the docs:

http://groovy-lang.org/gdk.html#split()

Loop through Map in Groovy?

Quite simple with a closure:

def map = [
           'iPhone':'iWebOS',
           'Android':'2.3.3',
           'Nokia':'Symbian',
           'Windows':'WM8'
           ]

map.each{ k, v -> println "${k}:${v}" }

Groovy: How to check if a string contains any element of an array?

def valid = pointAddress.findAll { a ->
    validPointTypes.any { a.contains(it) }
}

Should do it

How to define and use function inside Jenkins Pipeline config?

Solved! The call build job: project, parameters: params fails with an error java.lang.UnsupportedOperationException: must specify $class with an implementation of interface java.util.List when params = [:]. Replacing it with params = null solved the issue. Here the working code below.

def doCopyMibArtefactsHere(projectName) {
    step ([
        $class: 'CopyArtifact',
        projectName: projectName,
        filter: '**/**.mib',
        fingerprintArtifacts: true, 
        flatten: true
    ]);
}

def BuildAndCopyMibsHere(projectName, params = null) {
    build job: project, parameters: params
    doCopyMibArtefactsHere(projectName)
}
node { 
    stage('Prepare Mib'){
        BuildAndCopyMibsHere('project1')
    }
}

Array of strings in groovy

Most of the time you would create a list in groovy rather than an array. You could do it like this:

names = ["lucas", "Fred", "Mary"]

Alternately, if you did not want to quote everything like you did in the ruby example, you could do this:

names = "lucas Fred Mary".split()

Set "Homepage" in Asp.Net MVC

Look at the Default.aspx/Default.aspx.cs and the Global.asax.cs

You can set up a default route:

        routes.MapRoute(
            "Default", // Route name
            "",        // URL with parameters
            new { controller = "Home", action = "Index"}  // Parameter defaults
        );

Just change the Controller/Action names to your desired default. That should be the last route in the Routing Table.

JavaScript: Check if mouse button down?

As said @Jack, when mouseup happens outside of browser window, we are not aware of it...

This code (almost) worked for me:

window.addEventListener('mouseup', mouseUpHandler, false);
window.addEventListener('mousedown', mouseDownHandler, false);

Unfortunately, I won't get the mouseup event in one of those cases:

  • user simultaneously presses a keyboard key and a mouse button, releases mouse button outside of browser window then releases key.
  • user presses two mouse buttons simultaneously, releases one mouse button then the other one, both outside of browser window.

Replace new lines with a comma delimiter with Notepad++?

Open the find and replace dialog (press CTRL+H).

Then select Regular expression in the 'Search Mode' section at the bottom.

In the Find what field enter this: [\r\n]+

In the Replace with:

There is a space after the comma.

This will also replace lines like

Apples

Apricots
Pear

Avocados
Bananas

Where there are empty lines.

If your lines have trailing blank spaces you should remove those first. The simplest way to achieve this is

EDIT -> Blank Operations -> Trim Trailing Space

OR

TextFX -> TextFX Edit -> Trim trailing spaces

Be sure to set the Search Mode to "Regular expression".

Laravel, sync() - how to sync an array and also pass additional pivot fields?

In order to sync multiple models along with custom pivot data, you need this:

$user->roles()->sync([ 
    1 => ['expires' => true],
    2 => ['expires' => false],
    ...
]);

Ie.

sync([
    related_id => ['pivot_field' => value],
    ...
]);

edit

Answering the comment:

$speakers  = (array) Input::get('speakers'); // related ids
$pivotData = array_fill(0, count($speakers), ['is_speaker' => true]);
$syncData  = array_combine($speakers, $pivotData);

$user->roles()->sync($syncData);

Using Excel OleDb to get sheet names IN SHEET ORDER

This worked for me. Stolen from here: How do you get the name of the first page of an excel workbook?

object opt = System.Reflection.Missing.Value;
Excel.Application app = new Microsoft.Office.Interop.Excel.Application();
Excel.Workbook workbook = app.Workbooks.Open(WorkBookToOpen,
                                         opt, opt, opt, opt, opt, opt, opt,
                                         opt, opt, opt, opt, opt, opt, opt);
Excel.Worksheet worksheet = workbook.Worksheets[1] as Microsoft.Office.Interop.Excel.Worksheet;
string firstSheetName = worksheet.Name;

How do I handle a click anywhere in the page, even when a certain element stops the propagation?

Events in modern DOM implementations have two phases, capturing and bubbling. The capturing phase is the first phase, flowing from the defaultView of the document to the event target, followed by the bubbling phase, flowing from the event target back to the defaultView. For more information, see http://www.w3.org/TR/DOM-Level-3-Events/#event-flow.

To handle the capturing phase of an event, you need to set the third argument for addEventListener to true:

document.body.addEventListener('click', fn, true); 

Sadly, as Wesley mentioned, the capturing phase of an event cannot be handled reliably, or at all, in older browsers.

One possible solution is to handle the mouseup event instead, since event order for clicks is:

  1. mousedown
  2. mouseup
  3. click

If you can be sure you have no handlers cancelling the mouseup event, then this is one way (and, arguably, a better way) to go. Another thing to note is that many, if not most (if not all), UI menus disappear on mouse down.

How to bind list to dataGridView?

Instead of create the new Container class you can use a dataTable.

DataTable dt = new DataTable();
dt.Columns.Add("My first column Name");

dt.Rows.Add(new object[] { "Item 1" });
dt.Rows.Add(new object[] { "Item number 2" });
dt.Rows.Add(new object[] { "Item number three" });

myDataGridView.DataSource = dt;

More about this problem you can find here: http://psworld.pl/Programming/BindingListOfString

JQuery get data from JSON array

I think you need something like:

var text= data.response.venue.tips.groups[0].items[1].text;

C++ preprocessor __VA_ARGS__ number of arguments

There are some C++11 solutions for finding the number of arguments at compile-time, but I'm surprised to see that no one has suggested anything so simple as:

#define VA_COUNT(...) detail::va_count(__VA_ARGS__)

namespace detail
{
    template<typename ...Args>
    constexpr std::size_t va_count(Args&&...) { return sizeof...(Args); }
}

This doesn't require inclusion of the <tuple> header either.

jQuery get html of container including the container itself

I like to use this;

$('#container').prop('outerHTML');

Compile c++14-code with g++

G++ does support C++14 both via -std=c++14 and -std=c++1y. The latter was the common name for the standard before it was known in which year it would be released. In older versions (including yours) only the latter is accepted as the release year wasn't known yet when those versions were released.

I used "sudo apt-get install g++" which should automatically retrieve the latest version, is that correct?

It installs the latest version available in the Ubuntu repositories, not the latest version that exists.

The latest GCC version is 5.2.

JavaScript REST client Library

You don't really need a specific client, it's fairly simple with most libraries. For example in jQuery you can just call the generic $.ajax function with the type of request you want to make:

$.ajax({
    url: 'http://example.com/',
    type: 'PUT',
    data: 'ID=1&Name=John&Age=10', // or $('#myform').serializeArray()
    success: function() { alert('PUT completed'); }
});

You can replace PUT with GET/POST/DELETE or whatever.

com.microsoft.sqlserver.jdbc.SQLServerDriver not found error

intellij idea 2019

  1. Download Microsoft JDBC Driver for SQL Server

(https://docs.microsoft.com/en-us/sql/connect/jdbc/download-microsoft-jdbc-driver-for-sql-server?view=sql-server-2017)

  1. Unpack ("C:\opt\sqljdbc_7.2\enu\mssql-jdbc-7.2.2.jre11.jar")
  2. Add; (File->Project Structure->Global Libraries)
  3. Use; (Adding Jar files to IntellijIdea classpath (look video)) add import com.microsoft.sqlserver.jdbc.SQLServerDriver; enter image description here https://youtu.be/-2hjxoRKsyk

or ub Gradle set "compile" compile group: 'com.microsoft.sqlserver', name: 'mssql-jdbc', version: '7.2.2.jre11'

python for increment inner loop

In python, for loops iterate over iterables, instead of incrementing a counter, so you have a couple choices. Using a skip flag like Artsiom recommended is one way to do it. Another option is to make a generator from your range and manually advance it by discarding an element using next().

iGen = (i for i in range(0, 6))
for i in iGen:
    print i
    if not i % 2:
        iGen.next()

But this isn't quite complete because next() might throw a StopIteration if it reaches the end of the range, so you have to add some logic to detect that and break out of the outer loop if that happens.

In the end, I'd probably go with aw4ully's solution with the while loops.

Cannot get Kerberos service ticket: KrbException: Server not found in Kerberos database (7)

In my case, it's caused by wrong configuration of the requested server's address.

The server address should be an FQDN (fully qualified domain name).

FQDN is always required by Kerberos.

Using number as "index" (JSON)

JSON regulates key type to be string. The purpose is to support the dot notation to access the members of the object.

For example, person = {"height":170, "weight":60, "age":32}. You can access members by person.height, person.weight, etc. If JSON supports value keys, then it would look like person.0, person.1, person.2.

Disable Proximity Sensor during call

Proximity Sensor Dial

*#*#7378423#*#*

1) Service Tests - (If present)

2) Proximity Switch

3) Test on sensor (Next to logo(top) of mobile)

4) Yes if works, then u can keep on and proximity switch forever which gives beep all the time and consumes lot of battery

OR

4) No it doesn't work - Then simply clean the mobile screen or screen guard and clear the blocked screen from sensor. It works charm.

Technically, Its not any software solution, but hardware solution will work.

PermissionError: [Errno 13] Permission denied

Another option that helped me is using pathlib:

from pathlib import Path
p = Path('.') ## if you want to write to current directory
with open(p / 'test.txt', 'w') as f:
    f.write('test message')

and it works

how to add the missing RANDR extension

I am seeing this error message when I run Firefox headless through selenium using xvfb. It turns out that the message was a red herring for me. The message is only a warning, not an error. It is not why Firefox was not starting correctly.

The reason that Firefox was not starting for me was that it had been updated to a version that was no longer compatible with the Selenium drivers that I was using. I upgraded the selenium drivers to the latest and Firefox starts up fine again (even with this warning message about RANDR).

New releases of Firefox are often only compatible with one or two versions of Selenium. Occasionally Firefox is released with NO compatible version of Selenium. When that happens, it may take a week or two for a new version of Selenium to get released. Because of this, I now keep a version of Firefox that is known to work with the version of Selenium that I have installed. In addition to the version of Firefox that is kept up to date by my package manager, I have a version installed in /opt/ (eg /opt/firefox31/). The Selenium Java API takes an argument for the location of the Firefox binary to be used. The downside is that older versions of Firefox have known security vulnerabilities and shouldn't be used with untrusted content.

jQuery Refresh/Reload Page if Ajax Success after time

$.ajax("youurl", function(data){
    if (data.success == true)
    setTimeout(function(){window.location = window.location}, 5000); 
    })
)

javascript push multidimensional array

Arrays must have zero based integer indexes in JavaScript. So:

var valueToPush = new Array();
valueToPush[0] = productID;
valueToPush[1] = itemColorTitle;
valueToPush[2] = itemColorPath;
cookie_value_add.push(valueToPush);

Or maybe you want to use objects (which are associative arrays):

var valueToPush = { }; // or "var valueToPush = new Object();" which is the same
valueToPush["productID"] = productID;
valueToPush["itemColorTitle"] = itemColorTitle;
valueToPush["itemColorPath"] = itemColorPath;
cookie_value_add.push(valueToPush);

which is equivalent to:

var valueToPush = { };
valueToPush.productID = productID;
valueToPush.itemColorTitle = itemColorTitle;
valueToPush.itemColorPath = itemColorPath;
cookie_value_add.push(valueToPush);

It's a really fundamental and crucial difference between JavaScript arrays and JavaScript objects (which are associative arrays) that every JavaScript developer must understand.

Datagrid binding in WPF

Without seeing said object list, I believe you should be binding to the DataGrid's ItemsSource property, not its DataContext.

<DataGrid x:Name="Imported" VerticalAlignment="Top" ItemsSource="{Binding Source=list}"  AutoGenerateColumns="False" CanUserResizeColumns="True">
    <DataGrid.Columns>                
        <DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
        <DataGridTextColumn Header="Date" Binding="{Binding Date}"/>
   </DataGrid.Columns>
</DataGrid>

(This assumes that the element [UserControl, etc.] that contains the DataGrid has its DataContext bound to an object that contains the list collection. The DataGrid is derived from ItemsControl, which relies on its ItemsSource property to define the collection it binds its rows to. Hence, if list isn't a property of an object bound to your control's DataContext, you might need to set both DataContext={Binding list} and ItemsSource={Binding list} on the DataGrid...)

How to read appSettings section in the web.config file?

    using System.Configuration;

    /// <summary>
    /// For read one setting
    /// </summary>
    /// <param name="key">Key correspondent a your setting</param>
    /// <returns>Return the String contains the value to setting</returns>
    public string ReadSetting(string key)
    {
        var appSettings = ConfigurationManager.AppSettings;
        return appSettings[key] ?? string.Empty;
    }

    /// <summary>
    /// Read all settings for output Dictionary<string,string> 
    /// </summary>        
    /// <returns>Return the Dictionary<string,string> contains all settings</returns>
    public Dictionary<string, string> ReadAllSettings()
    {
        var result = new Dictionary<string, string>();
        foreach (var key in ConfigurationManager.AppSettings.AllKeys)
            result.Add(key, ConfigurationManager.AppSettings[key]);
        return result;
    }

How to use a servlet filter in Java to change an incoming servlet request url?

A simple JSF Url Prettyfier filter based in the steps of BalusC's answer. The filter forwards all the requests starting with the /ui path (supposing you've got all your xhtml files stored there) to the same path, but adding the xhtml suffix.

public class UrlPrettyfierFilter implements Filter {

    private static final String JSF_VIEW_ROOT_PATH = "/ui";

    private static final String JSF_VIEW_SUFFIX = ".xhtml";

    @Override
    public void destroy() {

    }

    @Override
    public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
            throws IOException, ServletException {
        HttpServletRequest httpServletRequest = ((HttpServletRequest) request);
        String requestURI = httpServletRequest.getRequestURI();
        //Only process the paths starting with /ui, so as other requests get unprocessed. 
        //You can register the filter itself for /ui/* only, too
        if (requestURI.startsWith(JSF_VIEW_ROOT_PATH) 
                && !requestURI.contains(JSF_VIEW_SUFFIX)) {
            request.getRequestDispatcher(requestURI.concat(JSF_VIEW_SUFFIX))
                .forward(request,response);
        } else {
            chain.doFilter(httpServletRequest, response);
        }
    }

    @Override
    public void init(FilterConfig arg0) throws ServletException {

    }

}

How to create duplicate table with new name in SQL Server 2008

In SSMS right click on a desired table > script as > create to > new query
-change the name of the table (ex. table2)
-change the PK key for the table (ex. PK_table2)

USE [NAMEDB]
GO
SET ANSI_NULLS ON
GO

SET QUOTED_IDENTIFIER ON
GO

CREATE TABLE [dbo].[table_2](
[id] [int] NOT NULL,
[name] [varchar](50) NULL,
CONSTRAINT [PK_table_2] PRIMARY KEY CLUSTERED 
(
[reference] ASC
)WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = 
OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, 
ALLOW_PAGE_LOCKS = ON, 
OPTIMIZE_FOR_SEQUENTIAL_KEY = OFF) ON [PRIMARY]
) ON [PRIMARY]
GO

Create a zip file and download it

// http headers for zip downloads
header("Pragma: public");
header("Expires: 0");
header("Cache-Control: must-revalidate, post-check=0, pre-check=0");
header("Cache-Control: public");
header("Content-Description: File Transfer");
header("Content-type: application/octet-stream");
header("Content-Disposition: attachment; filename=\"".$filename."\"");
header("Content-Transfer-Encoding: binary");
header("Content-Length: ".filesize($filepath.$filename));
ob_end_flush();
@readfile($filepath.$filename);

I found this soludtion here and it work for me

Concat strings by & and + in VB.Net

Try this. It almost seemed to simple to be right. Simply convert the Integer to a string. Then you can use the method below or concatenate.

Dim I, J, K, L As Integer
Dim K1, L1 As String

K1 = K
L1 = L
Cells(2, 1) = K1 & " - uploaded"
Cells(3, 1) = L1 & " - expanded"

MsgBox "records uploaded " & K & " records expanded " & L

Setting CSS pseudo-class rules from JavaScript

I threw together a small library for this since I do think there are valid use cases for manipulating stylesheets in JS. Reasons being:

  • Setting styles that must be calculated or retrieved - for example setting the user's preferred font-size from a cookie.
  • Setting behavioural (not aesthetic) styles, especially for UI widget/plugin developers. Tabs, carousels, etc, often require some basic CSS simply to function - shouldn't demand a stylesheet for the core function.
  • Better than inline styles since CSS rules apply to all current and future elements, and don't clutter the HTML when viewing in Firebug / Developer Tools.

how to get login option for phpmyadmin in xampp

Ya, it's working fine, but it can enter into localhost without entering password.

You can do it in another way by following these steps:

  1. In the browser, type: localhost/xampp/

  2. On the left side bar menu, click Security.

  3. Now you can see the subject table, and below the subject table you can see this link:
    http://localhost/security/xamppsecurity.php. Click this link.

  4. Now you can set the password as you want.

  5. Go to the xampp folder where you installed xampp. Open the xampp folder.

  6. Find and open the phpMyAdmin folder.

  7. Find and open the config.inc.php file with Notepad.

  8. Find the code below:

    $cfg['Servers'][$i]['auth_type'] = 'config';
    $cfg['Servers'][$i]['user'] = 'root';
    $cfg['Servers'][$i]['password'] = '';
    $cfg['Servers'][$i]['extension'] = 'mysqli';
    $cfg['Servers'][$i]['AllowNoPassword'] = true;
    
  9. Replace it with the code below:

    $cfg['Servers'][$i]['auth_type'] = 'cookie';
    $cfg['Servers'][$i]['user'] = 'root';
    $cfg['Servers'][$i]['password'] = '';
    $cfg['Servers'][$i]['extension'] = 'mysqli';
    $cfg['Servers'][$i]['AllowNoPassword'] = false;
    
  10. Save the file and run the localhost/phpmyadmin with the browser.

Why am I getting "(304) Not Modified" error on some links when using HttpWebRequest?

It is not an issue it is because of caching...

To overcome this add a timestamp to your endpoint call, e.g. axios.get('/api/products').

After timestamp it should be axios.get(/api/products?${Date.now()}.

It will resolve your 304 status code.

Convert hex string to int

Try with this:

long abc=convertString2Hex("1A2A3B");

private  long  convertString2Hex(String numberHexString)
{
    char[] ChaArray = numberHexString.toCharArray();
    long HexSum=0;
    long cChar =0;

    for(int i=0;i<numberHexString.length();i++ )
    {
        if( (ChaArray[i]>='0') && (ChaArray[i]<='9') )
            cChar = ChaArray[i] - '0';
        else
            cChar = ChaArray[i]-'A'+10;
        HexSum = 16 * HexSum + cChar;
    }
    return  HexSum;
}

Printing tuple with string formatting in Python

Talk is cheap, show you the code:

>>> tup = (10, 20, 30)
>>> i = 50
>>> print '%d      %s'%(i,tup)
50  (10, 20, 30)
>>> print '%s'%(tup,)
(10, 20, 30)
>>> 

Difference between "enqueue" and "dequeue"

These are terms usually used when describing a "FIFO" queue, that is "first in, first out". This works like a line. You decide to go to the movies. There is a long line to buy tickets, you decide to get into the queue to buy tickets, that is "Enqueue". at some point you are at the front of the line, and you get to buy a ticket, at which point you leave the line, that is "Dequeue".

Convert Promise to Observable

You can add a wrapper around promise functionality to return an Observable to observer.

  • Creating a Lazy Observable using defer() operator which allows you to create the Observable only when the Observer subscribes.
import { of, Observable, defer } from 'rxjs'; 
import { map } from 'rxjs/operators';


function getTodos$(): Observable<any> {
  return defer(()=>{
    return fetch('https://jsonplaceholder.typicode.com/todos/1')
      .then(response => response.json())
      .then(json => {
        return json;
      })
  });
}

getTodos$().
 subscribe(
   (next)=>{
     console.log('Data is:', next);
   }
)

Python date string to date object

There is another library called arrow really great to make manipulation on python date.

import arrow
import datetime

a = arrow.get('24052010', 'DMYYYY').date()
print(isinstance(a, datetime.date)) # True

SQL Server date format yyyymmdd

try this....

SELECT FORMAT(CAST(DOB AS DATE),'yyyyMMdd') FROM Employees;

How can I show an image using the ImageView component in javafx and fxml?

It's recommended to put the image to the resources, than you can use it like this:

imageView = new ImageView("/gui.img/img.jpg");

How to show hidden divs on mouseover?

Pass the mouse over the container and go hovering on the divs I use this for jQuery DropDown menus mainly:

Copy the whole document and create a .html file you'll be able to figure out on your own from that!

            <!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
            <html xmlns="http://www.w3.org/1999/xhtml">
            <head>
            <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
            <title>The Divs Case</title>
            <style type="text/css">
            * {margin:0px auto;
            padding:0px;}

            .container {width:800px;
            height:600px;
            background:#FFC;
            border:solid #F3F3F3 1px;}

            .div01 {float:right;
            background:#000;
            height:200px;
            width:200px;
            display:none;}

            .div02 {float:right;
            background:#FF0;
            height:150px;
            width:150px;
            display:none;}

            .div03 {float:right;
            background:#FFF;
            height:100px;
            width:100px;
            display:none;}

            div.container:hover div.div01 {display:block;}
            div.container div.div01:hover div.div02  {display:block;}
            div.container div.div01 div.div02:hover div.div03 {display:block;}

            </style>
            </head>
            <body>

            <div class="container">
              <div class="div01">
                <div class="div02">
                    <div class="div03">
                    </div>
                </div>
              </div>

            </div>
            </body>
            </html>

How do I show the changes which have been staged?

Think about the gitk tool also , provided with git and very useful to see the changes

How do I check/uncheck all checkboxes with a button using jQuery?

Try below code to check/uncheck all checkboxes

_x000D_
_x000D_
jQuery(document).ready(function() {_x000D_
    $("#check_uncheck").change(function() {_x000D_
        if ($("#check_uncheck:checked").length) {_x000D_
            $(".checkboxes input:checkbox").prop("checked", true);_x000D_
        } else {_x000D_
            $(".checkboxes input:checkbox").prop("checked", false);_x000D_
        }_x000D_
    })_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
<input type="checkbox" name="check_uncheck" id="check_uncheck" /> Check All/Uncheck All_x000D_
<br/>_x000D_
<br/>_x000D_
<div class="checkboxes">_x000D_
    <input type="checkbox" name="check" id="check" /> Check Box 1_x000D_
    <br/>_x000D_
    <input type="checkbox" name="check" id="check" /> Check Box 2_x000D_
    <br/>_x000D_
    <input type="checkbox" name="check" id="check" /> Check Box 3_x000D_
    <br/>_x000D_
    <input type="checkbox" name="check" id="check" /> Check Box 4_x000D_
</div>
_x000D_
_x000D_
_x000D_

Try this Demo Link

There is also another short way to do this, checkout below example. In this example check/uncheck all checkbox is checked or not if checked then all wiil be checked and if not all will be uncheck

_x000D_
_x000D_
$("#check_uncheck").change(function() {_x000D_
    $(".checkboxes input:checkbox").prop("checked",$(this).is(':checked'));_x000D_
})
_x000D_
    <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js"></script>_x000D_
    <input type="checkbox" name="check_uncheck" id="check_uncheck" /> Check All/Uncheck All_x000D_
    <br/>_x000D_
    <br/>_x000D_
    <div class="checkboxes">_x000D_
        <input type="checkbox" name="check" id="check" /> Check Box 1_x000D_
        <br/>_x000D_
        <input type="checkbox" name="check" id="check" /> Check Box 2_x000D_
        <br/>_x000D_
        <input type="checkbox" name="check" id="check" /> Check Box 3_x000D_
        <br/>_x000D_
        <input type="checkbox" name="check" id="check" /> Check Box 4_x000D_
    </div>
_x000D_
_x000D_
_x000D_

How to change the style of alert box?

Styling alert()-boxes ist not possible. You could use a javascript modal overlay instead.

Get Today's date in Java at midnight time

DateFormat dateFormat = new SimpleDateFormat("yyyy/MM/dd HH:mm:ss");    
Date date = new Date(); System.out.println(dateFormat.format(date));    //2014/08/06 15:59:4

Check an integer value is Null in c#

Simply you can do this:

    public void CheckNull(int? item)
    {
        if (item != null)
        {
            //Do Something
        }

    }

Uncaught ReferenceError: angular is not defined - AngularJS not working

You need to move your angular app code below the inclusion of the angular libraries. At the time your angular code runs, angular does not exist yet. This is an error (see your dev tools console).

In this line:

var app = angular.module(`

you are attempting to access a variable called angular. Consider what causes that variable to exist. That is found in the angular.js script which must then be included first.

  <h1>{{2+3}}</h1>

  <!-- In production use:
  <script src="//ajax.googleapis.com/ajax/libs/angularjs/1.0.7/angular.min.js"></script>
  -->
  <script src="lib/angular/angular.js"></script>
  <script src="lib/angular/angular-route.js"></script>
  <script src="js/app.js"></script>
  <script src="js/services.js"></script>
  <script src="js/controllers.js"></script>
  <script src="js/filters.js"></script>
  <script src="js/directives.js"></script>

      <script>
        var app = angular.module('myApp',[]);

        app.directive('myDirective',function(){

            return function(scope, element,attrs) {
                element.bind('click',function() {alert('click')});
            };

        });
    </script>

For completeness, it is true that your directive is similar to the already existing directive ng-click, but I believe the point of this exercise is just to practice writing simple directives, so that makes sense.

How to add buttons like refresh and search in ToolBar in Android?

To control the location of the title you may want to set a custom font as explained here (by twaddington): Link

Then to relocate the position of the text, in updateMeasureState() you would add p.baselineShift += (int) (p.ascent() * R); Similarly in updateDrawState() add tp.baselineShift += (int) (tp.ascent() * R); Where R is double between -1 and 1.

Javascript variable access in HTML

The info inside the <script> tag is then processed inside it to access other parts. If you want to change the text inside another paragraph, then first give the paragraph an id, then set a variable to it using getElementById([id]) to access it ([id] means the id you gave the paragraph). Next, use the innerHTML built-in variable with whatever your variable was called and a '.' (dot) to show that it is based on the paragraph. You can set it to whatever you want, but be aware that to set a paragraph to a tag (<...>), then you have to still put it in speech marks.

Example:

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
    <body>_x000D_
        <!--\|/id here-->_x000D_
        <p id="myText"></p>_x000D_
        <p id="myTextTag"></p>_x000D_
        <script>_x000D_
            <!--Here we retrieve the text and show what we want to write..._x000D_
            var text = document.getElementById("myText");_x000D_
            var tag = document.getElementById("myTextTag");_x000D_
            var toWrite = "Hello"_x000D_
            var toWriteTag = "<a href='https://stackoverflow.com'>Stack Overflow</a>"_x000D_
            <!--...and here we are actually affecting the text.-->_x000D_
            text.innerHTML = toWrite_x000D_
            tag.innerHTML = toWriteTag_x000D_
        </script>_x000D_
    <body>_x000D_
<html>
_x000D_
_x000D_
_x000D_

Can you use @Autowired with static fields?

Generally, setting static field by object instance is a bad practice.

to avoid optional issues you can add synchronized definition, and set it only if private static Logger logger;

@Autowired
public synchronized void setLogger(Logger logger)
{
    if (MyClass.logger == null)
    {
        MyClass.logger = logger;
    }
}

:

How to make custom error pages work in ASP.NET MVC 4

I had everything set up, but still couldn't see proper error pages for status code 500 on our staging server, despite the fact everything worked fine on local development servers.

I found this blog post from Rick Strahl that helped me.

I needed to add Response.TrySkipIisCustomErrors = true; to my custom error handling code.

PHP mPDF save file as PDF

This can be done like this. It worked fine for me. And also set the directory permissions to 777 or 775 if not set.

ob_clean();
$mpdf->Output('directory_name/pdf_file_name.pdf', 'F');

Why is document.body null in my javascript?

Or add this part

<script type="text/javascript">

    var mySpan = document.createElement("span");
    mySpan.innerHTML = "This is my span!";

    mySpan.style.color = "red";
    document.body.appendChild(mySpan);

    alert("Why does the span change after this alert? Not before?");

</script>

after the HTML, like:

    <html>
    <head>...</head>
    <body>...</body>
   <script type="text/javascript">
        var mySpan = document.createElement("span");
        mySpan.innerHTML = "This is my span!";

        mySpan.style.color = "red";
        document.body.appendChild(mySpan);

        alert("Why does the span change after this alert? Not before?");

    </script>

    </html>

Find all files in a folder

A lot of these answers won't actually work, having tried them myself. Give this a go:

string filepath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
DirectoryInfo d = new DirectoryInfo(filepath);

foreach (var file in d.GetFiles("*.txt"))
{
      Directory.Move(file.FullName, filepath + "\\TextFiles\\" + file.Name);
}

It will move all .txt files on the desktop to the folder TextFiles.

CodeIgniter activerecord, retrieve last insert id?

Last insert id means you can get inserted auto increment id by using this method in active record,

$this->db->insert_id() 
// it can be return insert id it is 
// similar to the mysql_insert_id in core PHP

You can refer this link you can find some more stuff.

Information from executing a query

Runtime error: Could not load file or assembly 'System.Web.WebPages.Razor, Version=3.0.0.0

I had this issue when I upgraded to v3.0.0.preview4, so a downgrade to a stable version fixed this.

Openstreetmap: embedding map in webpage (like Google Maps)

You can use OpenLayers (js API for maps).

There's an example on their page showing how to embed OSM tiles.

Edit: New Link to OpenLayers examples

Can I apply multiple background colors with CSS3?

You can only use one color but as many images as you want, here is the format:

background: [ <bg-layer> , ]* <final-bg-layer>

<bg-layer> = <bg-image> || <bg-position> [ / <bg-size> ]? || <repeat-style> || <attachment> || <box>{1,2}

<final-bg-layer> = <bg-image> || <bg-position> [ / <bg-size> ]? || <repeat-style> || <attachment> || <box>{1,2} || <background-color>

or background: url(image1.png) center bottom no-repeat, url(image2.png) left top no-repeat;

If you need more colors, make an image of a solid color and use it. I know it’s not what you want to hear, but I hope it helps.

The format is from http://www.css3.info/preview/multiple-backgrounds/

PHP remove all characters before specific string

You can use strstr to do this.

echo strstr($str, 'www/audio');

How to write both h1 and h2 in the same line?

In answer the question heading (found by a google search) and not the re-question To stop the line breaking when you have different heading tags e.g.

<h5 style="display:inline;"> What the... </h5><h1 style="display:inline;"> heck is going on? </h1>

Will give you:

What the...heck is going on?

and not

What the... 
heck is going on?

addClass and removeClass in jQuery - not removing class

I would recomend to cache the jQuery objects you use more than once. For Instance:

    $(document).on("click", ".clickable", function () {
        $(this).addClass("grown");
        $(this).removeClass("spot");
    });

would be:

    var doc = $(document);
    doc.on('click', '.clickable', function(){
       var currentClickedObject = $(this);
       currentClickedObject.addClass('grown');
       currentClickedObject.removeClass('spot');
    });

its actually more code, BUT it is muuuuuuch faster because you dont have to "walk" through the whole jQuery library in order to get the $(this) object.

PHP case-insensitive in_array function

$a = [1 => 'funny', 3 => 'meshgaat', 15 => 'obi', 2 => 'OMER'];  

$b = 'omer';

function checkArr($x,$array)
{
    $arr = array_values($array);
    $arrlength = count($arr);
    $z = strtolower($x);

    for ($i = 0; $i < $arrlength; $i++) {
        if ($z == strtolower($arr[$i])) {
            echo "yes";
        }  
    } 
};

checkArr($b, $a);

Download multiple files as a zip-file using php

You can use the ZipArchive class to create a ZIP file and stream it to the client. Something like:

$files = array('readme.txt', 'test.html', 'image.gif');
$zipname = 'file.zip';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {
  $zip->addFile($file);
}
$zip->close();

and to stream it:

header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));
readfile($zipname);

The second line forces the browser to present a download box to the user and prompts the name filename.zip. The third line is optional but certain (mainly older) browsers have issues in certain cases without the content size being specified.

Closing JFrame with button click

You will need a reference to the specific frame you want to close but assuming you have the reference dispose() should close the frame.

jButton1.addActionListener(new ActionListener() {
    public void actionPerformed(ActionEvent e)
    {
       frameToClose.dispose();
    }
});

Importing csv file into R - numeric values read as characters

In read.table (and its relatives) it is the na.strings argument which specifies which strings are to be interpreted as missing values NA. The default value is na.strings = "NA"

If missing values in an otherwise numeric variable column are coded as something else than "NA", e.g. "." or "N/A", these rows will be interpreted as character, and then the whole column is converted to character.

Thus, if your missing values are some else than "NA", you need to specify them in na.strings.

PHP string concatenation

while ($personCount < 10) {
    $result .= ($personCount++)." people ";
}

echo $result;

Creating a class object in c++

1) What is the difference between both the way of creating class objects.

a) pointer

Example* example=new Example();
// you get a pointer, and when you finish it use, you have to delete it:

delete example;

b) Simple declaration

Example example;

you get a variable, not a pointer, and it will be destroyed out of scope it was declared.

2) Singleton C++

This SO question may helps you

How to upgrade safely php version in wamp server

To add to the above answer (do steps 1-5).

  1. Click on WAMP -> Select PHP -> Versions: Select the new version installed
  2. Check that your PATH folder is updated to new path to PHP so your OS has same PHP version of WAMP.

How do I POST with multipart form data using fetch?

You're setting the Content-Type to be multipart/form-data, but then using JSON.stringify on the body data, which returns application/json. You have a content type mismatch.

You will need to encode your data as multipart/form-data instead of json. Usually multipart/form-data is used when uploading files, and is a bit more complicated than application/x-www-form-urlencoded (which is the default for HTML forms).

The specification for multipart/form-data can be found in RFC 1867.

For a guide on how to submit that kind of data via javascript, see here.

The basic idea is to use the FormData object (not supported in IE < 10):

async function sendData(url, data) {
  const formData  = new FormData();

  for(const name in data) {
    formData.append(name, data[name]);
  }

  const response = await fetch(url, {
    method: 'POST',
    body: formData
  });

  // ...
}

Per this article make sure not to set the Content-Type header. The browser will set it for you, including the boundary parameter.

Do a "git export" (like "svn export")?

As simple as clone then delete the .git folder:

git clone url_of_your_repo path_to_export && rm -rf path_to_export/.git

Understanding ASP.NET Eval() and Bind()

The question was answered perfectly by Darin Dimitrov, but since ASP.NET 4.5, there is now a better way to set up these bindings to replace* Eval() and Bind(), taking advantage of the strongly-typed bindings.

*Note: this will only work if you're not using a SqlDataSource or an anonymous object. It requires a Strongly-typed object (from an EF model or any other class).

This code snippet shows how Eval and Bind would be used for a ListView control (InsertItem needs Bind, as explained by Darin Dimitrov above, and ItemTemplate is read-only (hence they're labels), so just needs an Eval):

<asp:ListView ID="ListView1" runat="server" DataKeyNames="Id" InsertItemPosition="LastItem" SelectMethod="ListView1_GetData" InsertMethod="ListView1_InsertItem" DeleteMethod="ListView1_DeleteItem">
    <InsertItemTemplate>
        <li>
            Title: <asp:TextBox ID="Title" runat="server" Text='<%# Bind("Title") %>'/><br />         
            Description: <asp:TextBox ID="Description" runat="server" TextMode="MultiLine" Text='<%# Bind("Description") %>' /><br />        
            <asp:Button ID="InsertButton" runat="server" Text="Insert" CommandName="Insert" />        
        </li>
    </InsertItemTemplate>
    <ItemTemplate>
        <li>
            Title: <asp:Label ID="Title" runat="server" Text='<%#  Eval("Title") %>' /><br />
            Description: <asp:Label ID="Description" runat="server" Text='<%# Eval("Description") %>' /><br />        
            <asp:Button ID="DeleteButton" runat="server" Text="Delete" CommandName="Delete" CausesValidation="false"/>
        </li>
      </ItemTemplate>

From ASP.NET 4.5+, data-bound controls have been extended with a new property ItemType, which points to the type of object you're assigning to its data source.

<asp:ListView ItemType="Picture" ID="ListView1" runat="server" ...>

Picture is the strongly type object (from EF model). We then replace:

Bind(property) -> BindItem.property
Eval(property) -> Item.property

So this:

<%# Bind("Title") %>      
<%# Bind("Description") %>         
<%#  Eval("Title") %> 
<%# Eval("Description") %>

Would become this:

<%# BindItem.Title %>         
<%# BindItem.Description %>
<%# Item.Title %>
<%# Item.Description %>

Advantages over Eval & Bind:

  • IntelliSense can find the correct property of the object your're working withenter image description here
  • If property is renamed/deleted, you will get an error before page is viewed in browser
  • External tools (requires full versions of VS) will correctly rename item in markup when you rename a property on your object

Source: from this excellent book

How do I delete specific characters from a particular String in Java?

Use:

String str = "whatever";
str = str.replaceAll("[,.]", "");

replaceAll takes a regular expression. This:

[,.]

...looks for each comma and/or period.

How to Import 1GB .sql file to WAMP/phpmyadmin

Step 1: Find the config.inc.php file located in the phpmyadmin directory. In my case it is located here:

C:\wamp\apps\phpmyadmin3.4.5\config.inc.php 

Note: phymyadmin3.4.5 folder name is different in different version of wamp

Step 2: Find the line with $cfg['UploadDir'] on it and update it to:

$cfg['UploadDir'] = 'upload';

Step 3: Create a directory called ‘upload’ within the phpmyadmin directory.

C:\wamp\apps\phpmyadmin3.2.0.1\upload\

Step 4: Copy and paste the large sql file into upload directory which you want importing to phymyadmin

Step 5: Select sql file from drop down list from phymyadmin to import.

How do I zip two arrays in JavaScript?

Zip Arrays of same length:

Using Array.prototype.map()

_x000D_
_x000D_
const zip = (a, b) => a.map((k, i) => [k, b[i]]);

console.log(zip([1,2,3], ["a","b","c"]));
// [[1, "a"], [2, "b"], [3, "c"]]
_x000D_
_x000D_
_x000D_

Zip Arrays of different length:

Using Array.from()

_x000D_
_x000D_
const zip = (a, b) => Array.from(Array(Math.max(b.length, a.length)), (_, i) => [a[i], b[i]]);

console.log( zip([1,2,3], ["a","b","c","d"]) );
// [[1, "a"], [2, "b"], [3, "c"], [undefined, "d"]]
_x000D_
_x000D_
_x000D_

Using Array.prototype.fill() and Array.prototype.map()

_x000D_
_x000D_
const zip = (a, b) => Array(Math.max(b.length, a.length)).fill().map((_,i) => [a[i], b[i]]);

console.log(zip([1,2,3], ["a","b","c","d"]));
// [[1, "a"], [2, "b"], [3, "c"], [undefined, 'd']]
_x000D_
_x000D_
_x000D_

Keep CMD open after BAT file executes

start cmd /k did the magic for me. I actually used it for preparing cordova phonegap app it runs the command, shows the result and waits for the user to close it. Below is the simple example

start cmd /k echo Hello, World!

What I did use in my case

start cmd /k cordova prepare

Update

You could even have a title for this by using

start "My Title" echo Hello, World!

Find an element in a list of tuples

Read up on List Comprehensions

[ (x,y) for x, y in a if x  == 1 ]

Also read up up generator functions and the yield statement.

def filter_value( someList, value ):
    for x, y in someList:
        if x == value :
            yield x,y

result= list( filter_value( a, 1 ) )

How to decide when to use Node.js?

You did a great job of summarizing what's awesome about Node.js. My feeling is that Node.js is especially suited for applications where you'd like to maintain a persistent connection from the browser back to the server. Using a technique known as "long-polling", you can write an application that sends updates to the user in real time. Doing long polling on many of the web's giants, like Ruby on Rails or Django, would create immense load on the server, because each active client eats up one server process. This situation amounts to a tarpit attack. When you use something like Node.js, the server has no need of maintaining separate threads for each open connection.

This means you can create a browser-based chat application in Node.js that takes almost no system resources to serve a great many clients. Any time you want to do this sort of long-polling, Node.js is a great option.

It's worth mentioning that Ruby and Python both have tools to do this sort of thing (eventmachine and twisted, respectively), but that Node.js does it exceptionally well, and from the ground up. JavaScript is exceptionally well situated to a callback-based concurrency model, and it excels here. Also, being able to serialize and deserialize with JSON native to both the client and the server is pretty nifty.

I look forward to reading other answers here, this is a fantastic question.

It's worth pointing out that Node.js is also great for situations in which you'll be reusing a lot of code across the client/server gap. The Meteor framework makes this really easy, and a lot of folks are suggesting this might be the future of web development. I can say from experience that it's a whole lot of fun to write code in Meteor, and a big part of this is spending less time thinking about how you're going to restructure your data, so the code that runs in the browser can easily manipulate it and pass it back.

Here's an article on Pyramid and long-polling, which turns out to be very easy to set up with a little help from gevent: TicTacToe and Long Polling with Pyramid.

How to implement a Map with multiple keys?

Why not just drop the requirement that the key has to be a specific type, i.e. just use Map<Object,V>.

Sometimes generics just isn't worth the extra work.

Visual Studio "Could not copy" .... during build

Use

Debug.Flush();
Debug.Close();

in case exception occurs, in catch or finally block.

Edit: I personally faced this issue and I do a trick usually and it works fine. I change the type of build from 'debug' to 'release' (and 'release' to 'debug' if there is already).

Best way to randomize an array with .NET

You can also make an extention method out of Matt Howells. Example.

   namespace System
    {
        public static class MSSystemExtenstions
        {
            private static Random rng = new Random();
            public static void Shuffle<T>(this T[] array)
            {
                rng = new Random();
                int n = array.Length;
                while (n > 1)
                {
                    int k = rng.Next(n);
                    n--;
                    T temp = array[n];
                    array[n] = array[k];
                    array[k] = temp;
                }
            }
        }
    }

Then you can just use it like:

        string[] names = new string[] {
                "Aaron Moline1", 
                "Aaron Moline2", 
                "Aaron Moline3", 
                "Aaron Moline4", 
                "Aaron Moline5", 
                "Aaron Moline6", 
                "Aaron Moline7", 
                "Aaron Moline8", 
                "Aaron Moline9", 
            };
        names.Shuffle<string>();

How do I create a round cornered UILabel on the iPhone?

If you want rounded corner of UI objects like (UILabel, UIView, UIButton, UIImageView) by storyboard then set clip to bounds true and set User Defined Runtime Attributes Key path as layer.cornerRadius, type = Number and value = 9 (as your requirement)

Set clip to bounds as Set User Defined Runtime Attributes as

Send auto email programmatically

Referred link has correct answer, but there are written some libraries to make your work easy.

So don't write all code again, just use any of these library and get your work done in little time.

How do I check if an array includes a value in JavaScript?

You can also use this trick:

var arrayContains = function(object) {
  return (serverList.filter(function(currentObject) {
    if (currentObject === object) {
      return currentObject
    }
    else {
      return false;
    }
  }).length > 0) ? true : false
}

How to see the values of a table variable at debug time in T-SQL?

That's not yet implemented according this Microsoft Connect link: Microsoft Connect

Mongoose query where value is not null

You should be able to do this like (as you're using the query api):

Entrant.where("pincode").ne(null)

... which will result in a mongo query resembling:

entrants.find({ pincode: { $ne: null } })

A few links that might help:

Javascript Date - set just the date, ignoring time?

_x000D_
_x000D_
new Date((new Date("07/06/2012 13:30")).toDateString())
_x000D_
_x000D_
_x000D_

MySQL "incorrect string value" error when save unicode string in Django

You can change the collation of your text field to UTF8_general_ci and the problem will be solved.

Notice, this cannot be done in Django.

Meaning of - <?xml version="1.0" encoding="utf-8"?>

The encoding declaration identifies which encoding is used to represent the characters in the document.

More on the XML Declaration here: http://msdn.microsoft.com/en-us/library/ms256048.aspx

Simple Android RecyclerView example

Based on different sources I have created Simple Implementation of RecyclerView using a Simple Library.

Add this line in build.gradle

implementation 'com.hereshem.lib:awesomelib:2.0.1'

AddCreate a RecyclerView by adding MyRecyclerView in activity_main.xml with

<com.hereshem.lib.recycler.MyRecyclerView
        android:id="@+id/recycler"
        app:layoutManager="LinearLayoutManager"
        android:layout_width="match_parent"
        android:layout_height="match_parent"/>

Now in the MainActivity, Create a ViewHolder by passing the name of Class that needs to bind

public static class EVHolder extends MyViewHolder<Events> {
    TextView date, title, summary;
    public EVHolder(View v) {
        super(v);
        date = v.findViewById(R.id.date);
        title = v.findViewById(R.id.title);
        summary = v.findViewById(R.id.summary);
    }
    @Override
    public void bindView(Events c) {
        date.setText(c.date);
        title.setText(c.title);
        summary.setText(c.summary);
    }
}

Create Items list variable and adapters with very few lines by passing items, class and layout in the adapter

List<Events> items = new ArrayList<>();
MyRecyclerView recycler = findViewById(R.id.recycler);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(this, items, EVHolder.class, R.layout.row_event);
recycler.setAdapter(adapter);

ClickListener can be added with following lines

recycler.setOnItemClickListener(new MyRecyclerView.OnItemClickListener() {
    @Override
    public void onItemClick(int position) {
        Toast.makeText(MainActivity.this, "Recycler Item Clicked " + position, Toast.LENGTH_SHORT).show();
    }
});

Its all done.

More example and implementation can be found here . Hope this helps !!!

Make error: missing separator

In my case, I was actually missing a tab in between ifeq and the command on the next line. No spaces were there to begin with.

ifeq ($(wildcard $DIR_FILE), )
cd $FOLDER; cp -f $DIR_FILE.tpl $DIR_FILE.xs;
endif

Should have been:

ifeq ($(wildcard $DIR_FILE), )
<tab>cd $FOLDER; cp -f $DIR_FILE.tpl $DIR_FILE.xs;
endif

Note the <tab> is an actual tab character

ADB - Android - Getting the name of the current activity

You can try this command,

adb shell dumpsys activity recents

There you can find current activity name in activity stack.

To get most recent activity name:

adb shell dumpsys activity recents | find "Recent #0"

How to unescape HTML character entities in Java?

The most reliable way is with

String cleanedString = StringEscapeUtils.unescapeHtml4(originalString);

from org.apache.commons.lang3.StringEscapeUtils.

And to escape the whitespaces

cleanedString = cleanedString.trim();

This will ensure that whitespaces due to copy and paste in web forms to not get persisted in DB.

How can I format date by locale in Java?

Yes, using DateFormat.getDateInstance(int style, Locale aLocale) This displays the current date in a locale-specific way.

So, for example:

DateFormat df = DateFormat.getDateInstance(DateFormat.SHORT, yourLocale);
String formattedDate = df.format(yourDate);

See the docs for the exact meaning of the style parameter (SHORT, MEDIUM, etc)

What is the difference between an interface and abstract class?

It's pretty simple actually.

You can think of an interface as a class which is only allowed to have abstract methods and nothing else.

So an interface can only "declare" and not define the behavior you want the class to have.

An abstract class allows you to do both declare (using abstract methods) as well as define (using full method implementations) the behavior you want the class to have.

And a regular class only allows you to define, not declare, the behavior/actions you want the class to have.

One last thing,

In Java, you can implement multiple interfaces, but you can only extend one (Abstract Class or Class)...

This means inheritance of defined behavior is restricted to only allow one per class... ie if you wanted a class that encapsulated behavior from Classes A,B&C you would need to do the following: Class A extends B, Class C extends A .. its a bit of a round about way to have multiple inheritance...

Interfaces on the other hand, you could simply do: interface C implements A, B

So in effect Java supports multiple inheritance only in "declared behavior" ie interfaces, and only single inheritance with defined behavior.. unless you do the round about way I described...

Hopefully that makes sense.

How to Copy Contents of One Canvas to Another Canvas Locally

@robert-hurst has a cleaner approach.

However, this solution may also be used, in places when you actually want to have a copy of Data Url after copying. For example, when you are building a website that uses lots of image/canvas operations.

    // select canvas elements
    var sourceCanvas = document.getElementById("some-unique-id");
    var destCanvas = document.getElementsByClassName("some-class-selector")[0];

    //copy canvas by DataUrl
    var sourceImageData = sourceCanvas.toDataURL("image/png");
    var destCanvasContext = destCanvas.getContext('2d');

    var destinationImage = new Image;
    destinationImage.onload = function(){
      destCanvasContext.drawImage(destinationImage,0,0);
    };
    destinationImage.src = sourceImageData;

What is difference between Implicit wait and Explicit wait in Selenium WebDriver?

Implicit wait --

Implicit waits are basically your way of telling WebDriver the latency that you want to see if specified web element is not present that WebDriver looking for. So in this case, you are telling WebDriver that it should wait 10 seconds in cases of specified element not available on the UI (DOM).

Explicit wait--

Explicit waits are intelligent waits that are confined to a particular web element. Using explicit waits you are basically telling WebDriver at the max it is to wait for X units of time before it gives up.

sort csv by column

To sort by MULTIPLE COLUMN (Sort by column_1, and then sort by column_2)

with open('unsorted.csv',newline='') as csvfile:
    spamreader = csv.DictReader(csvfile, delimiter=";")
    sortedlist = sorted(spamreader, key=lambda row:(row['column_1'],row['column_2']), reverse=False)


with open('sorted.csv', 'w') as f:
    fieldnames = ['column_1', 'column_2', column_3]
    writer = csv.DictWriter(f, fieldnames=fieldnames)
    writer.writeheader()
    for row in sortedlist:
        writer.writerow(row)

NSCameraUsageDescription in iOS 10.0 runtime crash?

I checked the plist and found it is not working, only in the "project" info, you need to add the "Privacy - Camera ....", then it should work. Hope to help you.

How can I make a link from a <td> table cell

This might be the most simple way to make a whole <td> cell an active hyperlink just using HTML.

I never had a satisfactory answer for this question, until about 10 minutes ago, so years in the making #humor.

Tested on Firefox 70, this is a bare-bones example where one full line-width of the cell is active:

<td><a href=""><div><br /></div></a></td>

Obviously the example just links to "this document," so fill in the href="" and replace the <br /> with anything appropriate.

Previously I used a style and class pair that I cobbled together from the answers above (Thanks to you folks.)

Today, working on a different issue, I kept stripping it down until <div>&nbsp;</div> was the only thing left, remove the <div></div> and it stops linking beyond the text. I didn't like the short "_" the &nbsp; displayed and found a single <br /> works without an "extra line" penalty.

If another <td></td> in the <tr> has multiple lines, and makes the row taller with word-wrap for instance, then use multiple <br /> to bring the <td> you want to be active to the correct number of lines and active the full width of each line.

The only problem is it isn't dynamic, but usually the mouse is closer in height than width, so active everywhere on one line is better than just the width of the text.

Send HTTP POST message in ASP.NET Core using HttpClient PostAsJsonAsync

You are right that this has long since been implemented in .NET Core.

At the time of writing (September 2019), the project.json file of NuGet 3.x+ has been superseded by PackageReference (as explained at https://docs.microsoft.com/en-us/nuget/archive/project-json).

To get access to the *Async methods of the HttpClient class, your .csproj file must be correctly configured.

Open your .csproj file in a plain text editor, and make sure the first line is
<Project Sdk="Microsoft.NET.Sdk.Web">
(as pointed out at https://docs.microsoft.com/en-us/dotnet/core/tools/project-json-to-csproj#the-csproj-format).

To get access to the *Async methods of the HttpClient class, you also need to have the correct package reference in your .csproj file, like so:

<ItemGroup>
    <!-- ... -->
    <PackageReference Include="Microsoft.AspNetCore.App" />
    <!-- ... -->
</ItemGroup>

(See https://docs.microsoft.com/en-us/nuget/consume-packages/package-references-in-project-files#adding-a-packagereference. Also: We recommend applications targeting ASP.NET Core 2.1 and later use the Microsoft.AspNetCore.App metapackage, https://docs.microsoft.com/en-us/aspnet/core/fundamentals/metapackage)

Methods such as PostAsJsonAsync, ReadAsAsync, PutAsJsonAsync and DeleteAsync should now work out of the box. (No using directive needed.)

Update: The PackageReference tag is no longer needed in .NET Core 3.0.

Count specific character occurrences in a string

When I found this solution I was looking for something slightly different as the string I wanted to count was longer than one character, so I came up with this solution:

    Public Shared Function StrCounter(str As String, CountStr As String) As Integer
        Dim Ctr As Integer = 0
        Dim Ptr As Integer = 1
        While InStr(Ptr, str, CountStr) > 0
            Ptr = InStr(Ptr, str, CountStr) + Len(CountStr)
            Ctr += 1
        End While
        Return Ctr
    End Function

NPM global install "cannot find module"

I got this error Error: Cannot find module 'number-is-nan' whereas the module actually exists. It was due to a bad/incomplete Node.js installation.

For Windows , as other answers suggest it, you need a clean Node installation :

  • Uninstall Node.js
  • Delete the two folders npm and npm_cache in C:\Users\user\AppData\Roaming
  • Restart Windows and install Node.js
  • Run npm initor (npm init --yes for default config)
  • Set the Windows environment variable for NODE_PATH. This path is where your packages are installed. It's probably something likeNODE_PATH = C:\Users\user\node_modules or C:\Users\user\AppData\Roaming\npm\node_modules
  • Start a new cmd console and npm should work fine

Note :

Try the last points before reinstalling Node.js, it could save you some time and avoid to re-install all your packages.

How to add a default include path for GCC in Linux?

Try setting C_INCLUDE_PATH (for C header files) or CPLUS_INCLUDE_PATH (for C++ header files).

As Ciro mentioned, CPATH will set the path for both C and C++ (and any other language).

More details in GCC's documentation.

Javascript to Select Multiple options

You can get access to the options array of a selected object by going document.getElementById("cars").options where 'cars' is the select object.

Once you have that you can call option[i].setAttribute('selected', 'selected'); to select an option.

I agree with every one else that you are better off doing this server side though.

How do you get a query string on Flask?

from flask import request

@app.route('/data')
def data():
    # here we want to get the value of user (i.e. ?user=some-value)
    user = request.args.get('user')

What is the SQL command to return the field names of a table?

MySQL is the same:

select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = 'tablename'

Java: how to convert HashMap<String, Object> to array

If you are using Java 8+ and need a 2 dimensional Array, perhaps for TestNG data providers, you can try:

map.entrySet()
    .stream()
    .map(e -> new Object[]{e.getKey(), e.getValue()})
    .toArray(Object[][]::new);

If your Objects are Strings and you need a String[][], try:

map.entrySet()
    .stream()
    .map(e -> new String[]{e.getKey(), e.getValue().toString()})
    .toArray(String[][]::new);

How can I set a dynamic model name in AngularJS?

You can use something like this scopeValue[field], but if your field is in another object you will need another solution.

To solve all kind of situations, you can use this directive:

this.app.directive('dynamicModel', ['$compile', '$parse', function ($compile, $parse) {
    return {
        restrict: 'A',
        terminal: true,
        priority: 100000,
        link: function (scope, elem) {
            var name = $parse(elem.attr('dynamic-model'))(scope);
            elem.removeAttr('dynamic-model');
            elem.attr('ng-model', name);
            $compile(elem)(scope);
        }
    };
}]);

Html example:

<input dynamic-model="'scopeValue.' + field" type="text">

AngularJS not detecting Access-Control-Allow-Origin header?

It can also happen when your parameters are wrong in the request. In my case I was working with a API that sent me the message

"No 'Access-Control-Allow-Origin' header is present on the requested resource. Origin 'null' is therefore not allowed access. The response had HTTP status code 401."

when I send wrong username or password with the POST request to login.

View the change history of a file using Git versioning

git log --follow -p -- path-to-file

This will show the entire history of the file (including history beyond renames and with diffs for each change).

In other words, if the file named bar was once named foo, then git log -p bar (without the --follow option) will only show the file's history up to the point where it was renamed -- it won't show the file's history when it was known as foo. Using git log --follow -p bar will show the file's entire history, including any changes to the file when it was known as foo. The -p option ensures that diffs are included for each change.

Android: I lost my android key store, what should I do?

If you lost a keystore file, don't create/update the new one with another set of value. First do the thorough search. Because it will overwrite the old one, so it will not match to your previous apk.

If you use eclipse most probably it will store in default path. For MAC (eclipse) it will be in your elispse installation path something like:

/Applications/eclipse/Eclipse.app/Contents/MacOS/

then your keystore file without any extension. You need root privilege to access this path (file).

Javascript - Replace html using innerHTML

You are replacing the starting tag and then putting that back in innerHTML, so the code will be invalid. Make all the replacements before you put the code back in the element:

var html = strMessage1.innerHTML;
html = html.replace( /aaaaaa./g,'<a href=\"http://www.google.com/');
html = html.replace( /.bbbbbb/g,'/world\">Helloworld</a>');
strMessage1.innerHTML = html;

Get the string within brackets in Python

your_string = "lnfgbdgfi343456dsfidf[my data] ljfbgns47647jfbgfjbgskj"
your_string[your_string.find("[")+1 : your_string.find("]")]

courtesy: Regular expression to return text between parenthesis

Best way to check that element is not present using Selenium WebDriver with java

    WebElement element = driver.findElement(locator);

    Assert.assertFalse(element.isDisplayed());

The assertion will pass if the element is not present, otherwise it will fail.

mysql command for showing current configuration variables

What you are looking for is this:

SHOW VARIABLES;  

You can modify it further like any query:

SHOW VARIABLES LIKE '%max%';  

How to uninstall pip on OSX?

Aditionally to the answer from @srk, you should uninstall package setuptools:

python -m pip uninstall pip setuptools

If you want to uninstall all other packages first, this answer has some hints: https://stackoverflow.com/a/11250821/265954

Note: before you use the commands from that answer, please carefully read the comments about side effects and how to avoid uninstalling pip and setuptools too early. E.g. pip freeze | grep -v "^-e" | grep -v "^(setuptools|pip)" | xargs pip uninstall -y

Remove duplicated rows using dplyr

Here is a solution using dplyr >= 0.5.

library(dplyr)
set.seed(123)
df <- data.frame(
  x = sample(0:1, 10, replace = T),
  y = sample(0:1, 10, replace = T),
  z = 1:10
)

> df %>% distinct(x, y, .keep_all = TRUE)
    x y z
  1 0 1 1
  2 1 0 2
  3 1 1 4

How to use subprocess popen Python

Use sh, it'll make things a lot easier:

import sh
print sh.swfdump("/tmp/filename.swf", "-d")

Convert a string to integer with decimal in Python

"Convert" only makes sense when you change from one data type to another without loss of fidelity. The number represented by the string is a float and will lose precision upon being forced into an int.

You want to round instead, probably (I hope that the numbers don't represent currency because then rounding gets a whole lot more complicated).

round(float('23.45678'))

How to Sort a List<T> by a property in the object

Anybody working with nullable types, Value is required to use CompareTo.

objListOrder.Sort((x, y) => x.YourNullableType.Value.CompareTo(y.YourNullableType.Value));

How to pass multiple parameter to @Directives (@Components) in Angular with TypeScript?

Similar to the above solutions I used @Input() in a directive and able to pass multiple arrays of values in the directive.

selector: '[selectorHere]',

@Input() options: any = {};

Input.html

<input selectorHere [options]="selectorArray" />

Array from TS file

selectorArray= {
  align: 'left',
  prefix: '$',
  thousands: ',',
  decimal: '.',
  precision: 2
};

How to fix: fatal error: openssl/opensslv.h: No such file or directory in RedHat 7

On CYGwin, you can install this as a typical package in the first screen. Look for

libssl-devel

Parsing JSON in Spring MVC using Jackson JSON

I'm using json lib from http://json-lib.sourceforge.net/
json-lib-2.1-jdk15.jar

import net.sf.json.JSONObject;
...

public void send()
{
    //put attributes
    Map m = New HashMap();
    m.put("send_to","[email protected]");
    m.put("email_subject","this is a test email");
    m.put("email_content","test email content");

    //generate JSON Object
    JSONObject json = JSONObject.fromObject(content);
    String message = json.toString();
    ...
}

public void receive(String jsonMessage)
{
    //parse attributes
    JSONObject json = JSONObject.fromObject(jsonMessage);
    String to = (String) json.get("send_to");
    String title = (String) json.get("email_subject");
    String content = (String) json.get("email_content");
    ...
}

More samples here http://json-lib.sourceforge.net/usage.html

Copy folder recursively, excluding some folders

inspired by @SteveLazaridis's answer, which would fail, here is a POSIX shell function - just copy and paste into a file named cpx in yout $PATH and make it executible (chmod a+x cpr). [Source is now maintained in my GitLab.

#!/bin/sh

# usage: cpx [-n|--dry-run] "from_path" "to_path" "newline_separated_exclude_list"
# limitations: only excludes from "from_path", not it's subdirectories

cpx() {
# run in subshell to avoid collisions
  (_CopyWithExclude "$@")
}

_CopyWithExclude() {
  case "$1" in
    -n|--dry-run) { DryRun='echo'; shift; } ;;
  esac

  from="$1"
  to="$2"
  exclude="$3"

  $DryRun mkdir -p "$to"

  if [ -z "$exclude" ]; then
      cp "$from" "$to"
      return
  fi

  ls -A1 "$from" \
    | while IFS= read -r f; do
        unset excluded
        if [ -n "$exclude" ]; then
          for x in $(printf "$exclude"); do
          if [ "$f" = "$x" ]; then
              excluded=1
              break
          fi
          done
        fi
        f="${f#$from/}"
        if [ -z "$excluded" ]; then
          $DryRun cp -R "$f" "$to"
        else
          [ -n "$DryRun" ] && echo "skip '$f'"
        fi
      done
}

# Do not execute if being sourced
[ "${0#*cpx}" != "$0" ] && cpx "$@"

Example usage

EXCLUDE="
.git
my_secret_stuff
"
cpr "$HOME/my_stuff" "/media/usb" "$EXCLUDE"

OSError: [Errno 8] Exec format error

If you think the space before and after "=" is mandatory, try it as separate item in the list.

Out = subprocess.Popen(['/usr/local/bin/script', 'hostname', '=', 'actual server name', '-p', 'LONGLIST'],shell=True,stdout=subprocess.PIPE,stderr=subprocess.PIPE)

AppFabric installation failed because installer MSI returned with error code : 1603

I had the same problem today. I've found this link, where you can try 3 solutions. First solution helped for me.

Microsoft ANSWER for this issue

Simplest way to wait some asynchronous tasks complete, in Javascript?

I do this without external libaries:

var yourArray = ['aaa','bbb','ccc'];
var counter = [];

yourArray.forEach(function(name){
    conn.collection(name).drop(function(err) {
        counter.push(true);
        console.log('dropped');
        if(counter.length === yourArray.length){
            console.log('all dropped');
        }
    });                
});

Return True, False and None in Python

It's impossible to say without seeing your actual code. Likely the reason is a code path through your function that doesn't execute a return statement. When the code goes down that path, the function ends with no value returned, and so returns None.

Updated: It sounds like your code looks like this:

def b(self, p, data): 
    current = p 
    if current.data == data: 
        return True 
    elif current.data == 1:
        return False 
    else: 
        self.b(current.next, data)

That else clause is your None path. You need to return the value that the recursive call returns:

    else:
        return self.b(current.next, data)

BTW: using recursion for iterative programs like this is not a good idea in Python. Use iteration instead. Also, you have no clear termination condition.

Sql connection-string for localhost server

<add name="connstr" connectionString="Data Source=localhost;Initial Catalog=DBName;User Id=username;Password=password" providerName="System.Data.SqlClient"/>

The above also works. It ignores the username and password passed in in the connection string. I switched from an environment db to a local one, and it works fine even though my user in the connection string does not exist in this context.

How to get screen width without (minus) scrollbar?

Here is what I use

function windowSizes(){
    var e = window,
        a = 'inner';
    if (!('innerWidth' in window)) {
        a = 'client';
        e = document.documentElement || document.body;
    }
    return {
        width: e[a + 'Width'],
        height: e[a + 'Height']
    };  
}

$(window).on('resize', function () {
    console.log( windowSizes().width,windowSizes().height );
});

Named capturing groups in JavaScript regex?

Update: It finally made it into JavaScript (ECMAScript 2018)!


Named capturing groups could make it into JavaScript very soon.
The proposal for it is at stage 3 already.

A capture group can be given a name inside angular brackets using the (?<name>...) syntax, for any identifier name. The regular expression for a date then can be written as /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/u. Each name should be unique and follow the grammar for ECMAScript IdentifierName.

Named groups can be accessed from properties of a groups property of the regular expression result. Numbered references to the groups are also created, just as for non-named groups. For example:

let re = /(?<year>\d{4})-(?<month>\d{2})-(?<day>\d{2})/u;
let result = re.exec('2015-01-02');
// result.groups.year === '2015';
// result.groups.month === '01';
// result.groups.day === '02';

// result[0] === '2015-01-02';
// result[1] === '2015';
// result[2] === '01';
// result[3] === '02';

How do you set the EditText keyboard to only consist of numbers on Android?

Place the below lines in your <EditText>:

android:digits="0123456789"
android:inputType="phone"

Jquery to open Bootstrap v3 modal of remote url

In bootstrap-3.3.7.js you will see the following code.

if (this.options.remote) {
  this.$element
    .find('.modal-content')
    .load(this.options.remote, $.proxy(function () {
      this.$element.trigger('loaded.bs.modal')
    }, this))
}

So the bootstrap is going to replace the remote content into <div class="modal-content"> element. This is the default behavior by framework. So the problem is in your remote content itself, it should contain <div class="modal-header">, <div class="modal-body">, <div class="modal-footer"> by design.

How can I unstage my files again after making a local commit?

Lets say you want to unstage changes upto n commits,

Where commit hashes are as follows:

  • h1
  • h2 ...
  • hn
  • hn+1

Then run the following command:
git reset hn

Now the HEAD will be at hn+1. Changes from h1 to hn will be unstaged.

Axios handling errors

I tried using the try{}catch{} method but it did not work for me. However, when I switched to using .then(...).catch(...), the AxiosError is caught correctly that I can play around with. When I try the former when putting a breakpoint, it does not allow me to see the AxiosError and instead, says to me that the caught error is undefined, which is also what eventually gets displayed in the UI.

Not sure why this happens I find it very trivial. Either way due to this, I suggest using the conventional .then(...).catch(...) method mentioned above to avoid throwing undefined errors to the user.

bypass invalid SSL certificate in .net core

I solve with this:

Startup.cs

public void ConfigureServices(IServiceCollection services)
    {
        services.AddHttpClient("HttpClientWithSSLUntrusted").ConfigurePrimaryHttpMessageHandler(() => new HttpClientHandler
        {
            ClientCertificateOptions = ClientCertificateOption.Manual,
            ServerCertificateCustomValidationCallback =
            (httpRequestMessage, cert, cetChain, policyErrors) =>
            {
                return true;
            }
        });

YourService.cs

public UserService(IHttpClientFactory clientFactory, IOptions<AppSettings> appSettings)
    {
        _appSettings = appSettings.Value;
        _clientFactory = clientFactory;
    }

var request = new HttpRequestMessage(...

var client = _clientFactory.CreateClient("HttpClientWithSSLUntrusted");

HttpResponseMessage response = await client.SendAsync(request);

jQuery: load txt file and insert into div

You can use jQuery load method to get the contents and insert into an element.

Try this:

$(document).ready(function() {
        $("#lesen").click(function() {
                $(".text").load("helloworld.txt");
    }); 
}); 

You, can also add a call back to execute something once the load process is complete

e.g:

$(document).ready(function() {
    $("#lesen").click(function() {
        $(".text").load("helloworld.txt", function(){
            alert("Done Loading");
        });
   }); 
}); 

How does DateTime.Now.Ticks exactly work?

You can get the milliseconds since 1/1/1970 using such code:

private static DateTime JanFirst1970 = new DateTime(1970, 1, 1);
public static long getTime()
{
    return (long)((DateTime.Now.ToUniversalTime() - JanFirst1970).TotalMilliseconds + 0.5);
}

SSL_connect returned=1 errno=0 state=SSLv3 read server certificate B: certificate verify failed

Installing the following package on Ubuntu fixed the issue for me

sudo apt-get install libssl-dev

How do I change Bootstrap 3 column order on mobile layout?

In Bootstrap 4, if you want to do something like this:

    Mobile  |   Desktop
-----------------------------
    A       |       A
    C       |   B       C
    B       |       D
    D       |

You need to reverse the order of B then C then apply order-{breakpoint}-first to B. And apply two different settings, one that will make them share the same cols and other that will make them take the full width of the 12 cols:

  • Smaller screens: 12 cols to B and 12 cols to C

  • Larger screens: 12 cols between the sum of them (B + C = 12)

Like this

<div class='row no-gutters'>
    <div class='col-12'>
        A
    </div>
    <div class='col-12'>
        <div class='row no-gutters'>
            <div class='col-12 col-md-6'>
                C
            </div>
            <div class='col-12 col-md-6 order-md-first'>
                B
            </div>
        </div>
    </div>
    <div class='col-12'>
        D
    </div>
</div>

Demo: https://codepen.io/anon/pen/wXLGKa

Is the Javascript date object always one day off?

There are several crazy things that happen with a JS DATE object that convert strings, for example consider the following date you provided

Note: The following examples may or may not be ONE DAY OFF depending on YOUR timezone and current time.

new Date("2011-09-24"); // Year-Month-Day
// => Fri Sep 23 2011 17:00:00 GMT-0700 (MST) - ONE DAY OFF.

However, if we rearrange the string format to Month-Day-Year...

new Date("09-24-2011");
// => Sat Sep 24 2011 00:00:00 GMT-0700 (MST) - CORRECT DATE.

Another strange one

new Date("2011-09-24");
// => Fri Sep 23 2011 17:00:00 GMT-0700 (MST) - ONE DAY OFF AS BEFORE.

new Date("2011/09/24"); // change from "-" to "/".
// => Sat Sep 24 2011 00:00:00 GMT-0700 (MST) - CORRECT DATE.

We could easily change hyphens in your date "2011-09-24" when making a new date

new Date("2011-09-24".replace(/-/g, '\/')); // => "2011/09/24".
// => Sat Sep 24 2011 00:00:00 GMT-0700 (MST) - CORRECT DATE.

What if we had a date string like "2011-09-24T00:00:00"

new Date("2011-09-24T00:00:00");
// => Fri Sep 23 2011 17:00:00 GMT-0700 (MST) - ONE DAY OFF.

Now change hyphen to forward slash as before; what happens?

new Date("2011/09/24T00:00:00");
// => Invalid Date.

I typically have to manage the date format 2011-09-24T00:00:00 so this is what I do.

new Date("2011-09-24T00:00:00".replace(/-/g, '\/').replace(/T.+/, ''));
// => Sat Sep 24 2011 00:00:00 GMT-0700 (MST) - CORRECT DATE.

UPDATE

If you provide separate arguments to the Date constructor you can get other useful outputs as described below

Note: arguments can be of type Number or String. I'll show examples with mixed values.

Get the first month and day of a given year

new Date(2011, 0); // Normal behavior as months in this case are zero based.
// => Sat Jan 01 2011 00:00:00 GMT-0700 (MST)

Get the last month and day of a year

new Date((2011 + 1), 0, 0); // The second zero roles back one day into the previous month's last day.
// => Sat Dec 31 2011 00:00:00 GMT-0700 (MST)

Example of Number, String arguments. Note the month is March because zero based months again.

new Date(2011, "02"); 
// => Tue Mar 01 2011 00:00:00 GMT-0700 (MST)

If we do the same thing but with a day of zero, we get something different.

new Date(2011, "02", 0); // Again the zero roles back from March to the last day of February.
// => Mon Feb 28 2011 00:00:00 GMT-0700 (MST)

Adding a day of zero to any year and month argument will get the last day of the previous month. If you continue with negative numbers you can continue rolling back another day

new Date(2011, "02", -1);
// => Sun Feb 27 2011 00:00:00 GMT-0700 (MST)

Open soft keyboard programmatically

I used it as singleton like:

public static void showSoftKeyboard(final Context context, final EditText editText) {
        try {
            editText.requestFocus();
            editText.postDelayed(
                    new Runnable() {
                        @Override
                        public void run() {
                            InputMethodManager keyboard = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
                            keyboard.showSoftInput(editText, 0);
                        }
                    }
                    , 200);
        } catch (NullPointerException npe) {
            npe.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

Use it in your activity like:

showSoftKeyboard(this, yourEditTextToFocus);

How to run Gulp tasks sequentially one after the other

I was having this exact same problem and the solution turned out to be pretty easy for me. Basically change your code to the following and it should work. NOTE: the return before gulp.src made all the difference for me.

gulp.task "coffee", ->
    return gulp.src("src/server/**/*.coffee")
        .pipe(coffee {bare: true}).on("error",gutil.log)
        .pipe(gulp.dest "bin")

gulp.task "clean",->
    return gulp.src("bin", {read:false})
        .pipe clean
            force:true

gulp.task 'develop',['clean','coffee'], ->
    console.log "run something else"

How to convert SQL Server's timestamp column to datetime format

Some of them actually does covert to a date-time from SQL Server 2008 onwards.

Try the following SQL query and you will see for yourself:

SELECT CAST (0x00009CEF00A25634 AS datetime)

The above will result in 2009-12-30 09:51:03:000 but I have encountered ones that actually don't map to a date-time.

How can I edit a view using phpMyAdmin 3.2.4?

Just export you view and you will have all SQL need to make some change on it.

Just need to add your change in SQL query for the view and change :

CREATE for CREATE OR REPLACE

How do I get information about an index and table owner in Oracle?

The following may help give you want you need:

SELECT
    index_owner, index_name, table_name, column_name, column_position
FROM DBA_IND_COLUMNS
ORDER BY
    index_owner, 
    table_name,
    index_name,
    column_position
    ;

For my use case, I wanted the column_names and order that they are in the indices (so that I could recreate them in a different database engine after migrating to AWS). The following was what I used, in case it is of use to anyone else:

SELECT
    index_name, table_name, column_name, column_position
FROM DBA_IND_COLUMNS
WHERE
    INDEX_OWNER = 'FOO'
    AND TABLE_NAME NOT LIKE '%$%'
ORDER BY
    table_name,
    index_name,
    column_position
    ;

How to read an http input stream

It looks like the documentation is just using readStream() to mean:

Ok, we've shown you how to get the InputStream, now your code goes in readStream()

So you should either write your own readStream() method which does whatever you wanted to do with the data in the first place.

How to convert data.frame column from Factor to numeric

From ?factor:

To transform a factor f to approximately its original numeric values, as.numeric(levels(f))[f] is recommended and slightly more efficient than as.numeric(as.character(f)).

How to determine the first and last iteration in a foreach loop?

Best answer:

$arr = array(1, 2, 3, 4, 5, 6, 7, 8, 9, 10);

foreach ($arr as $a) {

// This is the line that does the checking
if (!each($arr)) echo "End!\n";

echo $a."\n";

}

how to call scalar function in sql server 2008

Your syntax is for table valued function which return a resultset and can be queried like a table. For scalar function do

 select  dbo.fun_functional_score('01091400003') as [er]

Java Program to test if a character is uppercase/lowercase/number/vowel

This may not be what you are looking for but I thought you oughta know the real way to do this. You can use the java.lang.Character class's isUpperCase() to find aout about the case of the character. You can use isDigit() to differentiate between the numbers and letters(This is just FYI :) ). You can then do a toUpperCase() and then do the switch for vowels. This will improve your code quality.

sql ORDER BY multiple values in specific order?

@bobflux's answer is great. I would like to extend it by adding a complete query that uses proposed approach.

select tt.id, tt.x_field
from target_table as tt
-- Here we join our target_table with order_table to specify custom ordering.
left join
    (values ('f', 1), ('p', 2), ('i', 3), ('a', 4)) as order_table (x_field, order_num)
    on order_table.x_field = tt.x_field
order by
    order_table.order_num, -- Here we order values by our custom order.
    tt.x_field;            -- Other values can be ordered alphabetically, for example.

Here is complete demo.

Triangle Draw Method

There is not a drawTriangle method neither in Graphics nor Graphics2D. You need to do it by yourself. You can draw three lines using the drawLine method or use one these methods:

These methods work with polygons. You may change the prefix draw to fill when you want to fill the polygon defined by the point set. I inserted the documentation links. Take a look to learn how to use them.

There is the GeneralPath class too. It can be used with Graphics2D, which is capable to draw Shapes. Take a look:

Selecting the first "n" items with jQuery

Use lt pseudo selector:

$("a:lt(n)")

This matches the elements before the nth one (the nth element excluded). Numbering starts from 0.

What are the ascii values of up down left right?

this is what i get:

Left - 19 Up - 5 Right - 4 Down - 24

Works in Visual Fox Pro

How can I set the opacity or transparency of a Panel in WinForms?

Based on information found at http://www.windows-tech.info/3/53ee08e46d9cb138.php, I was able to achieve a translucent panel control using the following code.

public class TransparentPanel : Panel
{
    protected override CreateParams CreateParams
    {
        get
        {
            var cp = base.CreateParams;
            cp.ExStyle |= 0x00000020; // WS_EX_TRANSPARENT

            return cp;
        }
    }

    protected override void OnPaint(PaintEventArgs e) =>
        e.Graphics.FillRectangle(new SolidBrush(this.BackColor), this.ClientRectangle);
}

The caveat is that any controls that are added to the panel have an opaque background. Nonetheless, the translucent panel was useful for me to block off parts of my WinForms application so that users focus was shifted to the appropriate area of the application.

How to redirect and append both stdout and stderr to a file with Bash?

This should work fine:

your_command 2>&1 | tee -a file.txt

It will store all logs in file.txt as well as dump them on terminal.

Transpose a range in VBA

You do not need to do this. Here is how to create a co-variance method:

http://www.youtube.com/watch?v=RqAfC4JXd4A

Alternatively you can use statistical analysis package that Excel has.

How can I get the name of an html page in Javascript?

This will work even if the url ends with a /:

var segments = window.location.pathname.split('/');
var toDelete = [];
for (var i = 0; i < segments.length; i++) {
    if (segments[i].length < 1) {
        toDelete.push(i);
    }
}
for (var i = 0; i < toDelete.length; i++) {
    segments.splice(i, 1);
}
var filename = segments[segments.length - 1];
console.log(filename);

Sending SMS from PHP

Clickatell is a popular SMS gateway. It works in 200+ countries.

Their API offers a choice of connection options via: HTTP/S, SMPP, SMTP, FTP, XML, SOAP. Any of these options can be used from php.

The HTTP/S method is as simple as this:

http://api.clickatell.com/http/sendmsg?to=NUMBER&msg=Message+Body+Here

The SMTP method consists of sending a plain-text e-mail to: [email protected], with the following body:

user: xxxxx
password: xxxxx
api_id: xxxxx
to: 448311234567
text: Meet me at home

You can also test the gateway (incoming and outgoing) for free from your browser

How to determine the version of Gradle?

Option 1- From Studio

In Android Studio, go to File > Project Structure. Then select the "project" tab on the left.

Your Gradle version will be displayed here.

Option 2- gradle-wrapper.properties

If you are using the Gradle wrapper, then your project will have a gradle/wrapper/gradle-wrapper.properties folder.

This file should contain a line like this:

distributionUrl=https\://services.gradle.org/distributions/gradle-2.2.1-all.zip

This determines which version of Gradle you are using. In this case, gradle-2.2.1-all.zip means I am using Gradle 2.2.1.

Option 3- Local Gradle distribution

If you are using a version of Gradle installed on your system instead of the wrapper, you can run gradle --version to check.

JPanel setBackground(Color.BLACK) does nothing

You need to create a new Jpanel object in the Board constructor. for example

public Board(){
    JPanel pane = new JPanel();
    pane.setBackground(Color.ORANGE);// sets the background to orange
} 

Android LinearLayout : Add border with shadow around a LinearLayout

I get the best looking results by using a 9 patch graphic.

You can simply create an individual 9 patch graphic by using the following editor: http://inloop.github.io/shadow4android/

Example:

The 9 patch graphic:

The 9 patch graphic:

The result:

enter image description here

The source:

<LinearLayout
android:layout_width="200dp"
android:layout_height="200dp"
android:orientation="vertical"
android:background="@drawable/my_nine_patch"

How do I convert a TimeSpan to a formatted string?

Use String.Format() with multiple parameters.

using System;

namespace TimeSpanFormat
{
    class Program
    {
        static void Main(string[] args)
        {
            TimeSpan dateDifference = new TimeSpan(0, 0, 6, 32, 445);
            string formattedTimeSpan = string.Format("{0:D2} hrs, {1:D2} mins, {2:D2} secs", dateDifference.Hours, dateDifference.Minutes, dateDifference.Seconds);
            Console.WriteLine(formattedTimeSpan);
        }
    }
}

Cannot install signed apk to device manually, got error "App not installed"

This can happen due to your choice of the signature version. On some phones, installation errors occur if the signature version was selected as V2. So if that happens, try selecting V1, it will surely work.

Read large files in Java

Yes. I also think that using read() with arguments like read(Char[], int init, int end) is a better way to read a such a large file (Eg : read(buffer,0,buffer.length))

And I also experienced the problem of missing values of using the BufferedReader instead of BufferedInputStreamReader for a binary data input stream. So, using the BufferedInputStreamReader is a much better in this like case.

How does the data-toggle attribute work? (What's its API?)

I think you are a bit confused on the purpose of custom data attributes. From the w3 spec

Custom data attributes are intended to store custom data private to the page or application, for which there are no more appropriate attributes or elements.

By itself an attribute of data-toggle=value is basically a key-value pair, in which the key is "data-toggle" and the value is "value".

In the context of Bootstrap, the custom data in the attribute is almost useless without the context that their JavaScript library includes for the data. If you look at the non-minified version of bootstrap.js then you can do a search for "data-toggle" and find how it is being used.

Here is an example of Bootstrap JavaScript code that I copied straight from the file regarding the use of "data-toggle".

  • Button Toggle

    Button.prototype.toggle = function () {
      var changed = true
      var $parent = this.$element.closest('[data-toggle="buttons"]')
    
      if ($parent.length) {
        var $input = this.$element.find('input')
        if ($input.prop('type') == 'radio') {
          if ($input.prop('checked') && this.$element.hasClass('active')) changed = false
          else $parent.find('.active').removeClass('active')
        }
        if (changed) $input.prop('checked', !this.$element.hasClass('active')).trigger('change')
      } else {
        this.$element.attr('aria-pressed', !this.$element.hasClass('active'))
      }
    
      if (changed) this.$element.toggleClass('active')
    }
    

The context that the code provides shows that Bootstrap is using the data-toggle attribute as a custom query selector to process the particular element.

From what I see these are the data-toggle options:

  • collapse
  • dropdown
  • modal
  • tab
  • pill
  • button(s)

You may want to look at the Bootstrap JavaScript documentation to get more specifics of what each do, but basically the data-toggle attribute toggles the element to active or not.

grep regex whitespace behavior

This looks like a behavior difference in the handling of \s between grep 2.5 and newer versions (a bug in old grep?). I confirm your result with grep 2.5.4, but all four of your greps do work when using grep 2.6.3 (Ubuntu 10.10).

Note:

GNU grep 2.5.4
echo "foo bar" | grep "\s"
   (doesn't match)

whereas

GNU grep 2.6.3
echo "foo bar" | grep "\s"
foo bar

Probably less trouble (as \s is not documented):

Both GNU greps
echo "foo bar" | grep "[[:space:]]"
foo bar

My advice is to avoid using \s ... use [ \t]* or [[:space:]] or something like it instead.

Assets file project.assets.json not found. Run a NuGet package restore

Seen this after adding a WinForms Core 3.1 project (from project templates) on VS-2019 vs 16.4.0 and trying to run it out of the box. Clean or Rebuild the entire solution did not work.

I just reloaded my solution.. that is File/Close Solution and then reopening it and rebuilding it solved the problem.

jQuery UI DatePicker to show year only

Try this:
add in html following

<input type="text" id="datepicker"/>

Add in js file

$(function() {
   $( "#datepicker" ).datepicker({dateFormat: 'yy',  changeYear: true,  changeMonth: false});
});

Add in css

.ui-datepicker-calendar {
       display: none;
    }
    .ui-datepicker-month {
       display: none;
    }
    .ui-datepicker-prev{
       display: none;
    }
    .ui-datepicker-next{
       display: none;
    }

Working Demo

Setting a checkbox as checked with Vue.js

In the v-model the value of the property might not be a strict boolean value and the checkbox might not 'recognise' the value as checked/unchecked. There is a neat feature in VueJS to make the conversion to true or false:

<input
  type="checkbox"
  v-model="toggle"
  true-value="yes"
  false-value="no"
>

Django URL Redirect

If you are stuck on django 1.2 like I am and RedirectView doesn't exist, another route-centric way to add the redirect mapping is using:

(r'^match_rules/$', 'django.views.generic.simple.redirect_to', {'url': '/new_url'}),  

You can also re-route everything on a match. This is useful when changing the folder of an app but wanting to preserve bookmarks:

(r'^match_folder/(?P<path>.*)', 'django.views.generic.simple.redirect_to', {'url': '/new_folder/%(path)s'}),  

This is preferable to django.shortcuts.redirect if you are only trying to modify your url routing and do not have access to .htaccess, etc (I'm on Appengine and app.yaml doesn't allow url redirection at that level like an .htaccess).

If REST applications are supposed to be stateless, how do you manage sessions?

Have a look at this presentation.

http://youtu.be/MRxTP-rQ-S8

According to this pattern - create transient restful resources to manage state if and when really needed. Avoid explicit sessions.

Command-line Git on Windows

These instructions worked for a Windows 8 with a msysgit/TortoiseGit installation, but should be applicable for other types of git installations on Windows.

  • Go to Control Panel\System and Security\System
  • Click on Advanced System Settings on the left which opens System Properties.
  • Click on the Advanced Tab
  • Click on the Environment Variables button at the bottom of the dialog box.
  • Edit the System Variable called PATH.
  • Append these two paths to the list of existing paths already present in the system variable. The tricky part was two paths were required. These paths may vary for your PC. ;C:\msysgit\bin\;C:\msysgit\mingw\bin\
  • Close the CMD prompt window if it is open already. CMD needs to restart to get the updated Path variable.
  • Try typing git in the command line, you should see a list of the git commands scroll down the screen.

TypeScript - Append HTML to container element in Angular 2

There is a better solution to this answer that is more Angular based.

  1. Save your string in a variable in the .ts file

    MyStrings = ["one","two","three"]

  2. In the html file use *ngFor.

    <div class="one" *ngFor="let string of MyStrings; let i = index"> <div class="two">{{string}}</div> </div>

  3. if you want to dynamically insert the div element, just push more strings into the MyStrings array

    myFunction(nextString){ this.MyString.push(nextString) }

this way every time you click the button containing the myFunction(nextString) you effectively add another class="two" div which acts the same way as inserting it into the DOM with pure javascript.

Maven error: Not authorized, ReasonPhrase:Unauthorized

I have recently encountered this problem. Here are the steps to resolve

  1. Check the servers section in the settings.xml file.Is username and password correct?

_x000D_
_x000D_
<servers>_x000D_
  <server>_x000D_
    <id>serverId</id>_x000D_
    <username>username</username>_x000D_
    <password>password</password>_x000D_
  </server>_x000D_
</servers>
_x000D_
_x000D_
_x000D_

  1. Check the repository section in the pom.xml file.The id of the server tag should be the same as the id of the repository tag.

_x000D_
_x000D_
<repositories>_x000D_
 <repository>_x000D_
   <id>serverId</id>  _x000D_
   <url>http://maven.aliyun.com/nexus/content/groups/public/</url>_x000D_
 </repository>_x000D_
</repositories>
_x000D_
_x000D_
_x000D_

  1. If the repository tag is not configured in the pom.xml file, look in the settings.xml file.

_x000D_
_x000D_
<profiles>_x000D_
 <profile>_x000D_
   <repositories>_x000D_
     <repository>_x000D_
      <id>serverId</id>_x000D_
      <name>aliyun</name>_x000D_
      <url>http://maven.aliyun.com/nexus/content/groups/public/</url>_x000D_
     </repository>_x000D_
   </repositories>_x000D_
 </profile>_x000D_
</profiles>
_x000D_
_x000D_
_x000D_

Note that you should ensure that the id of the server tag should be the same as the id of the repository tag.

CardView not showing Shadow in Android L

I think if you check your manifest first if you wrote android:hardwareAccelerated="false" you should make it true to having shadow for the card Like this answer here

Android open pdf file

The reason you don't have permissions to open file is because you didn't grant other apps to open or view the file on your intent. To grant other apps to open the downloaded file, include the flag(as shown below): FLAG_GRANT_READ_URI_PERMISSION

Intent browserIntent = new Intent(Intent.ACTION_VIEW);
browserIntent.setDataAndType(getUriFromFile(localFile), "application/pdf");
browserIntent.setFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION|
Intent.FLAG_ACTIVITY_NO_HISTORY);
startActivity(browserIntent);

And for function:

getUriFromFile(localFile)

private Uri getUriFromFile(File file){
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.N) {
        return Uri.fromFile(file);
    }else {
        return FileProvider.getUriForFile(itemView.getContext(), itemView.getContext().getApplicationContext().getPackageName() + ".provider", file);
    }
}

How to Use Content-disposition for force a file to download to the hard drive?

With recent browsers you can use the HTML5 download attribute as well:

<a download="quot.pdf" href="../doc/quot.pdf">Click here to Download quotation</a>

It is supported by most of the recent browsers except MSIE11. You can use a polyfill, something like this (note that this is for data uri only, but it is a good start):

(function (){

    addEvent(window, "load", function (){
        if (isInternetExplorer())
            polyfillDataUriDownload();
    });

    function polyfillDataUriDownload(){
        var links = document.querySelectorAll('a[download], area[download]');
        for (var index = 0, length = links.length; index<length; ++index) {
            (function (link){
                var dataUri = link.getAttribute("href");
                var fileName = link.getAttribute("download");
                if (dataUri.slice(0,5) != "data:")
                    throw new Error("The XHR part is not implemented here.");
                addEvent(link, "click", function (event){
                    cancelEvent(event);
                    try {
                        var dataBlob = dataUriToBlob(dataUri);
                        forceBlobDownload(dataBlob, fileName);
                    } catch (e) {
                        alert(e)
                    }
                });
            })(links[index]);
        }
    }

    function forceBlobDownload(dataBlob, fileName){
        window.navigator.msSaveBlob(dataBlob, fileName);
    }

    function dataUriToBlob(dataUri) {
        if  (!(/base64/).test(dataUri))
            throw new Error("Supports only base64 encoding.");
        var parts = dataUri.split(/[:;,]/),
            type = parts[1],
            binData = atob(parts.pop()),
            mx = binData.length,
            uiArr = new Uint8Array(mx);
        for(var i = 0; i<mx; ++i)
            uiArr[i] = binData.charCodeAt(i);
        return new Blob([uiArr], {type: type});
    }

    function addEvent(subject, type, listener){
        if (window.addEventListener)
            subject.addEventListener(type, listener, false);
        else if (window.attachEvent)
            subject.attachEvent("on" + type, listener);
    }

    function cancelEvent(event){
        if (event.preventDefault)
            event.preventDefault();
        else
            event.returnValue = false;
    }

    function isInternetExplorer(){
        return /*@cc_on!@*/false || !!document.documentMode;
    }
    
})();

Gradle: Could not determine java version from '11.0.2'

To put long answer short, upgrade your gradlew using the system gradle tool. Note that the below upgrade works even if your system gradle version is < 5.

gradle wrapper --gradle-version=5.1.1

Creating SVG elements dynamically with javascript inside HTML

To facilitate svg editing you can use an intermediate function:

function getNode(n, v) {
  n = document.createElementNS("http://www.w3.org/2000/svg", n);
  for (var p in v)
    n.setAttributeNS(null, p, v[p]);
  return n
}

Now you can write:

svg.appendChild( getNode('rect', { width:200, height:20, fill:'#ff0000' }) );

Example (with an improved getNode function allowing camelcase for property with dash, eg strokeWidth > stroke-width):

_x000D_
_x000D_
function getNode(n, v) {_x000D_
  n = document.createElementNS("http://www.w3.org/2000/svg", n);_x000D_
  for (var p in v)_x000D_
    n.setAttributeNS(null, p.replace(/[A-Z]/g, function(m, p, o, s) { return "-" + m.toLowerCase(); }), v[p]);_x000D_
  return n_x000D_
}_x000D_
_x000D_
var svg = getNode("svg");_x000D_
document.body.appendChild(svg);_x000D_
_x000D_
var r = getNode('rect', { x: 10, y: 10, width: 100, height: 20, fill:'#ff00ff' });_x000D_
svg.appendChild(r);_x000D_
_x000D_
var r = getNode('rect', { x: 20, y: 40, width: 100, height: 40, rx: 8, ry: 8, fill: 'pink', stroke:'purple', strokeWidth:7 });_x000D_
svg.appendChild(r);
_x000D_
_x000D_
_x000D_

Php $_POST method to get textarea value

Use htmlspecialchars():

echo htmlspecialchars($_POST['contact_list']);

You can even improve your form processing by stripping all tags with strip_tags() and remove all white spaces with trim():

function processText($text) {
    $text = strip_tags($text);
    $text = trim($text);
    $text = htmlspecialchars($text);
    return $text;
}

echo processText($_POST['contact_list']);

MySQL Event Scheduler on a specific time everyday

Try this

CREATE EVENT event1
ON SCHEDULE EVERY '1' DAY
STARTS '2012-04-17 13:00:00' -- should be in the future
DO
-- your statements
END

This IP, site or mobile application is not authorized to use this API key

Also the corresponding API should be enabled for the given project

https://console.developers.google.com/apis/library?project=projectnamehere

The value violated the integrity constraints for the column

It's as the error message says "The value violated the integrity constraints for the column" for column "Copy of F2"

Make it so it doesn't violate the value in the target table. What the allowable values are, data types, etc are not provided in your question so we cannot be more specific in answering.

To address the downvote, No, really it's as it says: you are putting something into a column that is not allowed. It could be Faizan points out, that you're putting a NULL into a NOT NULLable column, but it could be a whole host of other things and as the original poster never provided any update, we're left to guess. Was there a foreign key constraint that the insert violated? Maybe there's a check constraint that got blown? Maybe the source column in Excel has a valid date value for Excel that is not valid for the target column's date/time data type.

Thus, baring concrete information, the best possible answer is "don't do the thing that breaks it" In this case, something about "Copy of F2" is bad for the target column. Give us table definitions, supplied values, etc, then you can specific answers.

Telling people to make a NOT NULLable column into a NULLable one might be the right answer. It might also be the most horrific answer known to mankind. If an existing process expects there to always be a value in column "Copy of F2" changing the constraint to NULL can wreak havoc on existing queries. For example

SELECT * FROM ArbitraryTable AS T WHERE T.[Copy of F2] = '';

Currently, that query retrieves everything that was freshly imported because Copy of F2 is a poorly named status indicator. That data needs to get fed into the next system so... bills can get paid. As soon as you make it such that unprocessed rows can have a NULL value, the above query no longer satisfies that. Bills don't get paid, collections repos your building and now you're out of a job, all because you didn't do impact analysis, etc, etc.

How to delete a cookie?

would this work?

function eraseCookie(name) {
    document.cookie = name + '=; Max-Age=0'
}

I know Max-Age causes the cookie to be a session cookie in IE when creating the cookie. Not sure how it works when deleting cookies.

CLEAR SCREEN - Oracle SQL Developer shortcut?

Use cl scr on the Sql* command line tool to clear all the matter on the screen.

How can I create an utility class?

For a completely stateless utility class in Java, I suggest the class be declared public and final, and have a private constructor to prevent instantiation. The final keyword prevents sub-classing and can improve efficiency at runtime.

The class should contain all static methods and should not be declared abstract (as that would imply the class is not concrete and has to be implemented in some way).

The class should be given a name that corresponds to its set of provided utilities (or "Util" if the class is to provide a wide range of uncategorized utilities).

The class should not contain a nested class unless the nested class is to be a utility class as well (though this practice is potentially complex and hurts readability).

Methods in the class should have appropriate names.

Methods only used by the class itself should be private.

The class should not have any non-final/non-static class fields.

The class can also be statically imported by other classes to improve code readability (this depends on the complexity of the project however).

Example:

public final class ExampleUtilities {
    // Example Utility method
    public static int foo(int i, int j) {
        int val;

        //Do stuff

        return val;
    }

    // Example Utility method overloaded
    public static float foo(float i, float j) {
        float val;

        //Do stuff

        return val;
    }

    // Example Utility method calling private method
    public static long bar(int p) {
        return hid(p) * hid(p);
    }

    // Example private method
    private static long hid(int i) {
        return i * 2 + 1;
    }
}

Perhaps most importantly of all, the documentation for each method should be precise and descriptive. Chances are methods from this class will be used very often and its good to have high quality documentation to complement the code.

Datagridview full row selection but get single cell value

For those who could not fire the click event, they may use following code

public Form1()
            {
                InitializeComponent();
                this.dataGridView1.CellClick += new System.Windows.Forms.DataGridViewCellEventHandler(this.dataGridView1_CellClick);
            }

SQL Transaction Error: The current transaction cannot be committed and cannot support operations that write to the log file

There are a few misunderstandings in the discussion above.

First, you can always ROLLBACK a transaction... no matter what the state of the transaction. So you only have to check the XACT_STATE before a COMMIT, not before a rollback.

As far as the error in the code, you will want to put the transaction inside the TRY. Then in your CATCH, the first thing you should do is the following:

 IF @@TRANCOUNT > 0
      ROLLBACK TRANSACTION @transaction

Then, after the statement above, then you can send an email or whatever is needed. (FYI: If you send the email BEFORE the rollback, then you will definitely get the "cannot... write to log file" error.)

This issue was from last year, so I hope you have resolved this by now :-) Remus pointed you in the right direction.

As a rule of thumb... the TRY will immediately jump to the CATCH when there is an error. Then, when you're in the CATCH, you can use the XACT_STATE to decide whether you can commit. But if you always want to ROLLBACK in the catch, then you don't need to check the state at all.

Saving Excel workbook to constant path with filename from two fields

try

Sub save()
ActiveWorkbook.SaveAS Filename:="C:\-docs\cmat\Desktop\New folder\" & Range("C5").Text & chr(32) & Range("C8").Text &".xls", FileFormat:= _
  xlNormal, Password:="", WriteResPassword:="", ReadOnlyRecommended:=False _
 , CreateBackup:=False
End Sub

If you want to save the workbook with the macros use the below code

Sub save()
ActiveWorkbook.SaveAs Filename:="C:\Users\" & Environ$("username") & _
    "\Desktop\" & Range("C5").Text & Chr(32) & Range("C8").Text & ".xlsm", FileFormat:= _
    xlOpenXMLWorkbookMacroEnabled, Password:=vbNullString, WriteResPassword:=vbNullString, _
    ReadOnlyRecommended:=False, CreateBackup:=False
End Sub

if you want to save workbook with no macros and no pop-up use this

Sub save()
    Application.DisplayAlerts = False
    ActiveWorkbook.SaveAs Filename:="C:\Users\" & Environ$("username") & _
    "\Desktop\" & Range("C5").Text & Chr(32) & Range("C8").Text & ".xls", _
    FileFormat:=xlOpenXMLWorkbook, CreateBackup:=False
    Application.DisplayAlerts = True
End Sub

How can I add additional PHP versions to MAMP

If you need to be able to switch between more than two versions at a time, you can use the following to change the version of PHP manually.

MAMP automatically rewrites the following line in your /Applications/MAMP/conf/apache/httpd.conf file when it restarts based on the settings in preferences. You can comment out this line and add the second one to the end of your file:

# Comment this out just under all the modules loaded
# LoadModule php5_module        /Applications/MAMP/bin/php/php5.x.x/modules/libphp5.so

At the bottom of the httpd.conf file, you'll see where additional configurations are loaded from the extra folder. Add this to the bottom of the httpd.conf file

# PHP Version Change
Include /Applications/MAMP/conf/apache/extra/httpd-php.conf

Then create a new file here: /Applications/MAMP/conf/apache/extra/httpd-php.conf

# Uncomment the version of PHP you want to run with MAMP
# LoadModule php5_module /Applications/MAMP/bin/php/php5.2.17/modules/libphp5.so
# LoadModule php5_module /Applications/MAMP/bin/php/php5.3.27/modules/libphp5.so
# LoadModule php5_module /Applications/MAMP/bin/php/php5.4.19/modules/libphp5.so
LoadModule php5_module /Applications/MAMP/bin/php/php5.5.3/modules/libphp5.so

After you have this setup, just uncomment the version of PHP you want to use and restart the servers!

#pragma mark in Swift?

In Xcode 11 they added minimap which can be activated Editor -> Minimap.

Minimap will show each mark text for fast orientation in code. Each mark is written like // MARK: Variables

enter image description here

How to find the mysql data directory from command line in windows

Check if the Data directory is in "C:\ProgramData\MySQL\MySQL Server 5.7\Data". This is where it is on my computer. Someone might find this helpful.

jQuery: Selecting by class and input type

Your selector is looking for any descendants of a checkbox element that have a class of .myClass.

Try this instead:

$("input.myClass:checkbox")

Check it out in action.

I also tested this:

$("input:checkbox.myClass")

And it will also work properly. In my humble opinion this syntax really looks rather ugly, as most of the time I expect : style selectors to come last. As I said, though, either one will work.

Is there a performance difference between a for loop and a for-each loop?

It's always better to use the iterator instead of indexing. This is because iterator is most likely optimzied for the List implementation while indexed (calling get) might not be. For example LinkedList is a List but indexing through its elements will be slower than iterating using the iterator.

Single quotes vs. double quotes in C or C++

Single quotes are for a single character. Double quotes are for a string (array of characters). You can use single quotes to build up a string one character at a time, if you like.

char myChar     = 'A';
char myString[] = "Hello Mum";
char myOtherString[] = { 'H','e','l','l','o','\0' };

Passing a String by Reference in Java?

objects are passed by reference, primitives are passed by value.

String is not a primitive, it is an object, and it is a special case of object.

This is for memory-saving purpose. In JVM, there is a string pool. For every string created, JVM will try to see if the same string exist in the string pool, and point to it if there were already one.

public class TestString
{
    private static String a = "hello world";
    private static String b = "hello world";
    private static String c = "hello " + "world";
    private static String d = new String("hello world");

    private static Object o1 = new Object();
    private static Object o2 = new Object();

    public static void main(String[] args)
    {
        System.out.println("a==b:"+(a == b));
        System.out.println("a==c:"+(a == c));
        System.out.println("a==d:"+(a == d));
        System.out.println("a.equals(d):"+(a.equals(d)));
        System.out.println("o1==o2:"+(o1 == o2));

        passString(a);
        passString(d);
    }

    public static void passString(String s)
    {
        System.out.println("passString:"+(a == s));
    }
}

/* OUTPUT */

a==b:true
a==c:true
a==d:false
a.equals(d):true
o1==o2:false
passString:true
passString:false

the == is checking for memory address (reference), and the .equals is checking for contents (value)

How do you change the server header returned by nginx?

Install Nginx Extras

sudo apt-get update
sudo apt-get install nginx-extras

Server details can be removed from response by adding following two lines in the nginx.conf (under http section)

more_clear_headers Server;
server_tokens off;

Meaning of delta or epsilon argument of assertEquals for double values

Note that if you're not doing math, there's nothing wrong with asserting exact floating point values. For instance:

public interface Foo {
    double getDefaultValue();
}

public class FooImpl implements Foo {
    public double getDefaultValue() { return Double.MIN_VALUE; }
}

In this case, you want to make sure it's really MIN_VALUE, not zero or -MIN_VALUE or MIN_NORMAL or some other very small value. You can say

double defaultValue = new FooImpl().getDefaultValue();
assertEquals(Double.MIN_VALUE, defaultValue);

but this will get you a deprecation warning. To avoid that, you can call assertEquals(Object, Object) instead:

// really you just need one cast because of autoboxing, but let's be clear
assertEquals((Object)Double.MIN_VALUE, (Object)defaultValue);

And, if you really want to look clever:

assertEquals(
    Double.doubleToLongBits(Double.MIN_VALUE), 
    Double.doubleToLongBits(defaultValue)
);

Or you can just use Hamcrest fluent-style assertions:

// equivalent to assertEquals((Object)Double.MIN_VALUE, (Object)defaultValue);
assertThat(defaultValue, is(Double.MIN_VALUE));

If the value you're checking does come from doing some math, though, use the epsilon.

How to compute precision, recall, accuracy and f1-score for the multiclass case with scikit learn?

I think there is a lot of confusion about which weights are used for what. I am not sure I know precisely what bothers you so I am going to cover different topics, bear with me ;).

Class weights

The weights from the class_weight parameter are used to train the classifier. They are not used in the calculation of any of the metrics you are using: with different class weights, the numbers will be different simply because the classifier is different.

Basically in every scikit-learn classifier, the class weights are used to tell your model how important a class is. That means that during the training, the classifier will make extra efforts to classify properly the classes with high weights.
How they do that is algorithm-specific. If you want details about how it works for SVC and the doc does not make sense to you, feel free to mention it.

The metrics

Once you have a classifier, you want to know how well it is performing. Here you can use the metrics you mentioned: accuracy, recall_score, f1_score...

Usually when the class distribution is unbalanced, accuracy is considered a poor choice as it gives high scores to models which just predict the most frequent class.

I will not detail all these metrics but note that, with the exception of accuracy, they are naturally applied at the class level: as you can see in this print of a classification report they are defined for each class. They rely on concepts such as true positives or false negative that require defining which class is the positive one.

             precision    recall  f1-score   support

          0       0.65      1.00      0.79        17
          1       0.57      0.75      0.65        16
          2       0.33      0.06      0.10        17
avg / total       0.52      0.60      0.51        50

The warning

F1 score:/usr/local/lib/python2.7/site-packages/sklearn/metrics/classification.py:676: DeprecationWarning: The 
default `weighted` averaging is deprecated, and from version 0.18, 
use of precision, recall or F-score with multiclass or multilabel data  
or pos_label=None will result in an exception. Please set an explicit 
value for `average`, one of (None, 'micro', 'macro', 'weighted', 
'samples'). In cross validation use, for instance, 
scoring="f1_weighted" instead of scoring="f1".

You get this warning because you are using the f1-score, recall and precision without defining how they should be computed! The question could be rephrased: from the above classification report, how do you output one global number for the f1-score? You could:

  1. Take the average of the f1-score for each class: that's the avg / total result above. It's also called macro averaging.
  2. Compute the f1-score using the global count of true positives / false negatives, etc. (you sum the number of true positives / false negatives for each class). Aka micro averaging.
  3. Compute a weighted average of the f1-score. Using 'weighted' in scikit-learn will weigh the f1-score by the support of the class: the more elements a class has, the more important the f1-score for this class in the computation.

These are 3 of the options in scikit-learn, the warning is there to say you have to pick one. So you have to specify an average argument for the score method.

Which one you choose is up to how you want to measure the performance of the classifier: for instance macro-averaging does not take class imbalance into account and the f1-score of class 1 will be just as important as the f1-score of class 5. If you use weighted averaging however you'll get more importance for the class 5.

The whole argument specification in these metrics is not super-clear in scikit-learn right now, it will get better in version 0.18 according to the docs. They are removing some non-obvious standard behavior and they are issuing warnings so that developers notice it.

Computing scores

Last thing I want to mention (feel free to skip it if you're aware of it) is that scores are only meaningful if they are computed on data that the classifier has never seen. This is extremely important as any score you get on data that was used in fitting the classifier is completely irrelevant.

Here's a way to do it using StratifiedShuffleSplit, which gives you a random splits of your data (after shuffling) that preserve the label distribution.

from sklearn.datasets import make_classification
from sklearn.cross_validation import StratifiedShuffleSplit
from sklearn.metrics import accuracy_score, f1_score, precision_score, recall_score, classification_report, confusion_matrix

# We use a utility to generate artificial classification data.
X, y = make_classification(n_samples=100, n_informative=10, n_classes=3)
sss = StratifiedShuffleSplit(y, n_iter=1, test_size=0.5, random_state=0)
for train_idx, test_idx in sss:
    X_train, X_test, y_train, y_test = X[train_idx], X[test_idx], y[train_idx], y[test_idx]
    svc.fit(X_train, y_train)
    y_pred = svc.predict(X_test)
    print(f1_score(y_test, y_pred, average="macro"))
    print(precision_score(y_test, y_pred, average="macro"))
    print(recall_score(y_test, y_pred, average="macro"))    

Hope this helps.

How to do while loops with multiple conditions

I am not sure it would read better but you could do the following:

while any((not condition1, not condition2, val == -1)):
    val,something1,something2 = getstuff()

    if something1==10:
        condition1 = True

    if something2==20:
        condition2 = True