Programs & Examples On #Continuous integration

Continuous integration (CI) is the building and automated testing of the full software product on a frequent schedule: at least once a day, often several times a day and sometimes as often as after every check in to the version control system.

How to uninstall Jenkins?

You are right, it is simple. Run (admin password required):

'/Library/Application Support/Jenkins/Uninstall.command'

It may be necessary to do this with admin privileges using sudo.

How to connect Bitbucket to Jenkins properly

I had a similar problems, till I got it working. Below is the full listing of the integration:

  1. Generate public/private keys pair: ssh-keygen -t rsa
  2. Copy the public key (~/.ssh/id_rsa.pub) and paste it in Bitbucket SSH keys, in user’s account management console: enter image description here

  3. Copy the private key (~/.ssh/id_rsa) to new user (or even existing one) with private key credentials, in this case, username will not make a difference, so username can be anything: enter image description here

  4. run this command to test if you can get access to Bitbucket account: ssh -T [email protected]

  5. OPTIONAL: Now, you can use your git to to copy repo to your desk without passwjord git clone [email protected]:username/repo_name.git
  6. Now you can enable Bitbucket hooks for Jenkins push notifications and automatic builds, you will do that in 2 steps:

    1. Add an authentication token inside the job/project you configure, it can be anything: enter image description here

    2. In Bitbucket hooks: choose jenkins hooks, and fill the fields as below: enter image description here

Where:

**End point**: username:usertoken@jenkins_domain_or_ip
**Project name**: is the name of job you created on Jenkins
**Token**: Is the authorization token you added in the above steps in your Jenkins' job/project 

Recommendation: I usually add the usertoken as the authorization Token (in both Jenkins Auth Token job configuration and Bitbucket hooks), making them one variable to ease things on myself.

How to run jenkins as a different user

The "Issue 2" answer given by @Sagar works for the majority of git servers such as gitorious.

However, there will be a name clash in a system like gitolite where the public ssh keys are checked in as files named with the username, ie keydir/jenkins.pub. What if there are multiple jenkins servers that need to access the same gitolite server?

(Note: this is about running the Jenkins daemon not running a build job as a user (addressed by @Sagar's "Issue 1").)

So in this case you do need to run the Jenkins daemon as a different user.

There are two steps:

Step 1

The main thing is to update the JENKINS_USER environment variable. Here's a patch showing how to change the user to ptran.

BEGIN PATCH
--- etc/default/jenkins.old     2011-10-28 17:46:54.410305099 -0700
+++ etc/default/jenkins 2011-10-28 17:47:01.670369300 -0700
@@ -13,7 +13,7 @@
 PIDFILE=/var/run/jenkins/jenkins.pid

 # user id to be invoked as (otherwise will run as root; not wise!)
-JENKINS_USER=jenkins
+JENKINS_USER=ptran

 # location of the jenkins war file
 JENKINS_WAR=/usr/share/jenkins/jenkins.war
--- etc/init.d/jenkins.old      2011-10-28 17:47:20.878539172 -0700
+++ etc/init.d/jenkins  2011-10-28 17:47:47.510774714 -0700
@@ -23,7 +23,7 @@

 #DAEMON=$JENKINS_SH
 DAEMON=/usr/bin/daemon
-DAEMON_ARGS="--name=$NAME --inherit --env=JENKINS_HOME=$JENKINS_HOME --output=$JENKINS_LOG -   -pidfile=$PIDFILE" 
+DAEMON_ARGS="--name=$JENKINS_USER --inherit --env=JENKINS_HOME=$JENKINS_HOME --output=$JENKINS_LOG --pidfile=$PIDFILE" 

 SU=/bin/su
END PATCH

Step 2

Update ownership of jenkins directories:

chown -R ptran /var/log/jenkins
chown -R ptran /var/lib/jenkins
chown -R ptran /var/run/jenkins
chown -R ptran /var/cache/jenkins

Step 3

Restart jenkins

sudo service jenkins restart

Jenkins CI: How to trigger builds on SVN commit

You need to require only one plugin which is the Subversion plugin.

Then simply, go into Jenkins ? job_name ? Build Trigger section ? (i) Trigger build remotely (i.e., from scripts) Authentication token: Token_name

Go to the SVN server's hooks directory, and then after fire the below commands:

  1. cp post-commit.tmpl post-commit
  2. chmod 777 post-commit
  3. chown -R www-data:www-data post-commit
  4. vi post-commit

    Note: All lines should be commented Add the below line at last

Syntax (for Linux users):

/usr/bin/curl http://username:API_token@localhost:8081/job/job_name/build?token=Token_name

Syntax (for Windows user):

C:/curl_for_win/curl http://username:API_token@localhost:8081/job/job_name/build?token=Token_name

How to trigger Jenkins builds remotely and to pass parameters

See Jenkins documentation: Parameterized Build

Below is the line you are interested in:

http://server/job/myjob/buildWithParameters?token=TOKEN&PARAMETER=Value

Authenticate Jenkins CI for Github private repository

An alternative to the answer from sergey_mo is to create multiple ssh keys on the jenkins server.

(Though as the first commenter to sergey_mo's answer said, this may end up being more painful than managing a single key-pair.)

How to select different app.config for several build configurations

After some research on managing configs for development and builds etc, I decided to roll my own, I have made it available on bitbucket at: https://bitbucket.org/brightertools/contemplate/wiki/Home

This multiple configuration files for multiple environments, its a basic configuration entry replacement tool that will work with any text based file format.

Hope this helps.

Jenkins vs Travis-CI. Which one would you use for a Open Source project?

Travis-ci and Jenkins, while both are tools for continuous integration are very different.

Travis is a hosted service (free for open source) while you have to host, install and configure Jenkins.

Travis does not have jobs as in Jenkins. The commands to run to test the code are taken from a file named .travis.yml which sits along your project code. This makes it easy to have different test code per branch since each branch can have its own version of the .travis.yml file.

You can have a similar feature with Jenkins if you use one of the following plugins:

  • Travis YML Plugin - warning: does not seem to be popular, probably not feature complete in comparison to the real Travis.
  • Jervis - a modification of Jenkins to make it read create jobs from a .jervis.yml file found at the root of project code. If .jervis.yml does not exist, it will fall back to using .travis.yml file instead.

There are other hosted services you might also consider for continuous integration (non exhaustive list):


How to choose ?

You might want to stay with Jenkins because you are familiar with it or don't want to depend on 3rd party for your continuous integration system. Else I would drop Jenkins and go with one of the free hosted CI services as they save you a lot of trouble (host, install, configure, prepare jobs)

Depending on where your code repository is hosted I would make the following choices:

  • in-house ? Jenkins or gitlab-ci
  • Github.com ? Travis-CI

To setup Travis-CI on a github project, all you have to do is:

  • add a .travis.yml file at the root of your project
  • create an account at travis-ci.com and activate your project

The features you get are:

  • Travis will run your tests for every push made on your repo
  • Travis will run your tests on every pull request contributors will make

Jenkins CI Pipeline Scripts not permitted to use method groovy.lang.GroovyObject

I ran into this when I reduced the number of user-input parameters in userInput from 3 to 1. This changed the variable output type of userInput from an array to a primitive.

Example:

myvar1 = userInput['param1']
myvar2 = userInput['param2']

to:

myvar = userInput

Skip a submodule during a Maven build

It's possible to decide which reactor projects to build by specifying the -pl command line argument:

$ mvn --help
[...]
 -pl,--projects <arg>                   Build specified reactor projects
                                        instead of all projects
[...]

It accepts a comma separated list of parameters in one of the following forms:

  • relative path of the folder containing the POM
  • [groupId]:artifactId

Thus, given the following structure:

project-root [com.mycorp:parent]
  |
  + --- server [com.mycorp:server]
  |       |
  |       + --- orm [com.mycorp.server:orm]
  |
  + --- client [com.mycorp:client]

You can specify the following command line:

mvn -pl .,server,:client,com.mycorp.server:orm clean install

to build everything. Remove elements in the list to build only the modules you please.


EDIT: as blackbuild pointed out, as of Maven 3.2.1 you have a new -el flag that excludes projects from the reactor, similarly to what -pl does:

Jenkins/Hudson - accessing the current build number?

I've just come across this question too and found out that if anytime the build number gets corrupt because of any error-triggered hard shutdown of the jenkins instance you can set back the build number manually by just editing the file nextBuildNumber (pathToJenkins\jobs\jobxyz\nextBuildNumber) and then make a reload by using the option
Reload Configuration from Disk from the Manage Jenkins View.

How to set environment variables in Jenkins?

This is the snippet to store environment variable and access it.

node {
   withEnv(["ENABLE_TESTS=true", "DISABLE_SQL=false"]) {
      stage('Select Jenkinsfile') {
          echo "Enable test?: ${env.DEVOPS_SKIP_TESTS}
          customStep script: this
      }
   }
}

Note: The value of environment variable is coming as a String. If you want to use it as a boolean then you have to parse it using Boolean.parse(env.DISABLE_SQL).

How do I clear my Jenkins/Hudson build history?

This one is the best option available.

Jenkins.instance.getAllItems(AbstractProject.class).each {it -> Jenkins.instance.getItemByFullName(it.fullName).builds.findAll { it.number > 0 }.each { it.delete() } }

This code will delete all Jenkins Job build history.

Archive the artifacts in Jenkins

Your understanding is correct, an artifact in the Jenkins sense is the result of a build - the intended output of the build process.

A common convention is to put the result of a build into a build, target or bin directory.

The Jenkins archiver can use globs (target/*.jar) to easily pick up the right file even if you have a unique name per build.

Jenkins - passing variables between jobs?

You can use Hudson Groovy builder to do this.

First Job in pipeline

enter image description here

Second job in pipeline

enter image description here

How do I clone a job in Jenkins?

Create a new Item and go to the last you'll find option to copy from existing, just write your current job name and you will have clone of that project to work with.

How can I auto increment the C# assembly version via our CI platform (Hudson)?

This is a simpler mechanism. It simply involves the addition of a Windows Batch command task build step before the MSBuild step and the use of a simple find and replace program (FART).

The Batch Step

fart --svn -r AssemblyInfo.cs "[assembly: AssemblyVersion(\"1.0.0.0\")]" "[assembly: AssemblyVersion(\"1.0.%BUILD_NUMBER%.%SVN_REVISION%\")]"
if %ERRORLEVEL%==0 exit /b 1
fart --svn -r AssemblyInfo.cs "[assembly: AssemblyFileVersion(\"1.0.0.0\")]" "[assembly: AssemblyFileVersion(\"1.0.%BUILD_NUMBER%.%SVN_REVISION%\")]"
if %ERRORLEVEL%==0 exit /b 1
exit /b 0

If you are using source control other than svn change the --svn option for the appropriate one for your scm environment.

Download Fart

How to choose between Hudson and Jenkins?

From the Jenkins website, http://jenkins-ci.org, the following sums it up.

In a nutshell Jenkins CI is the leading open-source continuous integration server. Built with Java, it provides over 300 plugins to support building and testing virtually any project.

Oracle now owns the Hudson trademark, but has licensed it under the Eclipse EPL. Jenkins is on the MIT license. Both Hudson and Jenkins are open-source. Based on the combination of who you work for and personal preference for open-source, the decision is straightforward IMHO.

Hope this was helpful.

Continuous Integration vs. Continuous Delivery vs. Continuous Deployment

Difference between Continuous Integration, Continuous delivery and continuous deployment

enter image description here

Managing SSH keys within Jenkins for Git

Have you tried logging in as the jenkins user?

Try this:

sudo -i -u jenkins #For RedHat you might have to do 'su' instead.
git clone [email protected]:your/repo.git

Often times you see failure if the host has not been added or authorized (hence I always manually login as hudson/jenkins for the first connection to github/bitbucket) but that link you included supposedly fixes that.

If the above doesn't work try recopying the key. Make sure its the pub key (ie id_rsa.pub). Maybe you missed some characters?

mvn clean install vs. deploy vs. release

  • mvn install will put your packaged maven project into the local repository, for local application using your project as a dependency.
  • mvn release will basically put your current code in a tag on your SCM, change your version in your projects.
  • mvn deploy will put your packaged maven project into a remote repository for sharing with other developers.

Resources :

How can I merge two commits into one if I already started rebase?

you can cancel the rebase with

git rebase --abort

and when you run the interactive rebase command again the 'squash; commit must be below the pick commit in the list

C++: what regex library should I use?

Two more options:

If you can write it in c++11 - Do the tutorial: http://www.codeguru.com/cpp/cpp/cpp_mfc/stl/article.php/c15339

Note: At the time of writing the only c++11 regex library that I know works is the clang/llvm one, and only works on Mac. The GNU still doesn't implement regex yet. I don't know about Visual Studio. Most people still use the boost regex implementation.


Or you can use ragel to generate a finite state machine to do the parsing for you, and generate the C/C++ code implementation: http://www.complang.org/ragel/

I used it a little to generate code to parse json. This ragel file: https://github.com/matiu2/yajp/blob/master/parser/number.rl is used to generate this code https://github.com/matiu2/yajp/blob/master/parser/json.hpp#L254 and this finite state machine diagram:

state diagram


Update 1:

lvm's libc++ regex works on ubuntu 14.04: libc++-dev - LLVM C++ Standard library (development files). When compiling: clang++ -std=c++11 -lc++ -I/usr/include/c++/v1 ...

Update 2:

I'm currently enjoying boost spirit 3 - I like it more than regex, because it has BNF style rules and is well thought out. (Older (more documented) Spirit Qi libs found here)

How exactly does binary code get converted into letters?

Why not just do this take 010010001001001 split it into two bits 8 letter each (01001000, 01001001). Then issue the powers

01001000. 01001001.

The first 8 ignore the first three they determine if it's capital or not, the go right to left doing powers of 2 (2^1, 2^2 2^3 2^4 2^5). So then add all the ones up , there's only one, and it = 8, and te eight letter in the alphabet is h so our first bit is the letter h, try it on the other bit

Replacing characters in Ant property

Properties can't be changed but antContrib vars (http://ant-contrib.sourceforge.net/tasks/tasks/variable_task.html ) can.

Here is a macro to do a find/replace on a var:

    <macrodef name="replaceVarText">
        <attribute name="varName" />
        <attribute name="from" />
        <attribute name="to" />
        <sequential>
            <local name="replacedText"/>
            <local name="textToReplace"/>
            <local name="fromProp"/>
            <local name="toProp"/>
            <property name="textToReplace" value = "${@{varName}}"/>
            <property name="fromProp" value = "@{from}"/>
            <property name="toProp" value = "@{to}"/>

            <script language="javascript">
                project.setProperty("replacedText",project.getProperty("textToReplace").split(project.getProperty("fromProp")).join(project.getProperty("toProp")));
            </script>
            <ac:var name="@{varName}" value = "${replacedText}"/>
        </sequential>
    </macrodef>

Then call the macro like:

<ac:var name="updatedText" value="${oldText}"/>
<current:replaceVarText varName="updatedText" from="." to="_" />
<echo message="Updated Text will be ${updatedText}"/>

Code above uses javascript split then join, which is faster than regex. "local" properties are passed to JavaScript so no property leakage.

How to use log levels in java

Here is a good introduction to logging in Java: http://www.javapractices.com/topic/TopicAction.do?Id=143

Java comes with a logging API since it's 1.4.2 version: http://download.oracle.com/javase/1.4.2/docs/guide/util/logging/overview.html

You can also use other logging frameworks like Apache Log4j which is the most popular one: http://logging.apache.org/log4j

I suggest you to use a logging abstraction framework which allows you to change your logging framework without re-factoring you code. So you can starts by using Jul (Java Util Logging) then swith to Log4j without changing you code. The most popular logging facade is slf4j: http://www.slf4j.org/

Regards,

Python 3 Online Interpreter / Shell

Ideone supports Python 2.6 and Python 3

How can I make git accept a self signed certificate?

Using 64bit version of Git on Windows, just add the self signed CA certificate into these files :

  • C:\Program Files\Git\mingw64\ssl\certs\ca-bundle.crt
  • C:\Program Files\Git\mingw64\ssl\certs\ca-bundle.trust.crt

If it is just a server self signed certificate add it into

  • C:\Program Files\Git\mingw64\ssl\cert.pem

Java TreeMap Comparator

you can swipe the key and the value. For example

        String[] k = {"Elena", "Thomas", "Hamilton", "Suzie", "Phil"};
        int[] v = {341, 273, 278, 329, 445};
        TreeMap<Integer,String>a=new TreeMap();
        for (int i = 0; i < k.length; i++) 
           a.put(v[i],k[i]);            
        System.out.println(a.firstEntry().getValue()+"\t"+a.firstEntry().getKey());
        a.remove(a.firstEntry().getKey());
        System.out.println(a.firstEntry().getValue()+"\t"+a.firstEntry().getKey());

How can I convert ticks to a date format?

    private void button1_Click(object sender, EventArgs e)
    {
        long myTicks = 633896886277130000;
        DateTime dtime = new DateTime(myTicks);
        MessageBox.Show(dtime.ToString("MMMM d, yyyy"));
    }

Gives

September 27, 2009

Is that what you need?

I don't see how that format is necessarily easy to work with in SQL queries, though.

How to deal with page breaks when printing a large HTML table

The accepted answer did not work for me in all browsers, but following css did work for me:

tr    
{ 
  display: table-row-group;
  page-break-inside:avoid; 
  page-break-after:auto;
}

The html structure was:

<table>
  <thead>
    <tr></tr>
  </thead>
  <tbody>
    <tr></tr>
    <tr></tr>
    ...
  </tbody>
</table>

In my case, there were some additional issues with the thead tr, but this resolved the original issue of keeping the table rows from breaking.

Because of the header issues, I ultimately ended up with:

#theTable td *
{
  page-break-inside:avoid;
}

This didn't prevent rows from breaking; just each cell's content.

sklearn error ValueError: Input contains NaN, infinity or a value too large for dtype('float64')

try

mat.sum()

If the sum of your data is infinity (greater that the max float value which is 3.402823e+38) you will get that error.

see the _assert_all_finite function in validation.py from the scikit source code:

if is_float and np.isfinite(X.sum()):
    pass
elif is_float:
    msg_err = "Input contains {} or a value too large for {!r}."
    if (allow_nan and np.isinf(X).any() or
            not allow_nan and not np.isfinite(X).all()):
        type_err = 'infinity' if allow_nan else 'NaN, infinity'
        # print(X.sum())
        raise ValueError(msg_err.format(type_err, X.dtype))

DateTime vs DateTimeOffset

This piece of code from Microsoft explains everything:

// Find difference between Date.Now and Date.UtcNow
  date1 = DateTime.Now;
  date2 = DateTime.UtcNow;
  difference = date1 - date2;
  Console.WriteLine("{0} - {1} = {2}", date1, date2, difference);

  // Find difference between Now and UtcNow using DateTimeOffset
  dateOffset1 = DateTimeOffset.Now;
  dateOffset2 = DateTimeOffset.UtcNow;
  difference = dateOffset1 - dateOffset2;
  Console.WriteLine("{0} - {1} = {2}", 
                    dateOffset1, dateOffset2, difference);
  // If run in the Pacific Standard time zone on 4/2/2007, the example
  // displays the following output to the console:
  //    4/2/2007 7:23:57 PM - 4/3/2007 2:23:57 AM = -07:00:00
  //    4/2/2007 7:23:57 PM -07:00 - 4/3/2007 2:23:57 AM +00:00 = 00:00:00

How do you set the document title in React?

You can use ReactDOM and altering <title> tag

ReactDOM.render(
   "New Title",
   document.getElementsByTagName("title")[0]
);

Node / Express: EADDRINUSE, Address already in use - Kill server

I had the same problem and I found out that it was the nodemon problem. First I was using this script to start my process:

{"dev": "nodemon -r dotenv/config app.js"}

the app boots correctly, but as soon as any file changes, nodemon can't restart it. In the meantime, the app still continues to run in the background. If I do Ctrl+C, it quits, but there's no more process on port 3000, so killing it by port fuser -k 3000/tcp doesn't do anything.

And, I was using .env port in app.js file.

const port = process.env.PORT || 3000;

So, I changed the port value to 3000 only and it worked.

const port = 3000;

I had to find another way to load .env file, but this solved the issue for me. Hope that helps.

HTML code for an apostrophe

As far as I know it is &#39; but it seems yours works as well

See http://w3schools.com/tags/ref_ascii.asp

Formatting Numbers by padding with leading zeros in SQL Server

I am posting all at one place, all works for me to pad with 4 leading zero :)

declare @number int =  1;
print right('0000' + cast(@number as varchar(4)) , 4)
print right('0000' + convert(varchar(4), @number) , 4)
print right(replicate('0',4) + convert(varchar(4), @number) , 4)
print  cast(replace(str(@number,4),' ','0')as char(4))
print format(@number,'0000')

CSS styling in Django forms

Write your form like:

    class MyForm(forms.Form):
         name = forms.CharField(widget=forms.TextInput(attr={'class':'name'}),label="Your Name")
         message = forms.CharField(widget=forms.Textarea(attr={'class':'message'}), label="Your Message")

In your HTML field do something like:

{% for field in form %}
      <div class="row">
        <label for="{{ field.name}}">{{ field.label}}</label>{{ field }}
     </div>
{% endfor %}

Then in your CSS write something like:

.name{
      /* you already have this class so create it's style form here */
}
.message{
      /* you already have this class so create it's style form here */
}
label[for='message']{
      /* style for label */
}

Hope this answer is worth a try! Note you must have written your views to render the HTML file that contains the form.

Get div tag scroll position using JavaScript

you use the scrollTop attribute

var position = document.getElementById('id').scrollTop;

Links in <select> dropdown options

... or if you want / need to keep your option 'value' as it was, just add a new attribute:

<select id="my_selection">
<option value="x" href="/link/to/somewhere">value 1</option>
<option value="y" href="/link/to/somewhere/else">value 2</option>
</select>

<script>
document.getElementById('my_selection').onchange = function() {
    window.location.href = this.children[this.selectedIndex].getAttribute('href');
}
</script>

How do I correctly clean up a Python object?

It seems that the idiomatic way to do this is to provide a close() method (or similar), and call it explicitely.

Unable to set default python version to python3 in ubuntu

The best way in ubuntu 18.04 which will work for all users is

sudo vim /etc/bash.bashrc
add lines
alias python=python3
alias pip=pip3

Save the changes and restart .

After restart what ever version of python 3 you have in the system along with python 2.7 will be taken as default. You could be more specific by saying the following in alias if you have multiple version of python 3.

sudo vim /etc/bash.bashrc
add lines
alias python=python3.6
alias pip=pip3.6

How to get index of object by its property in JavaScript?

Only way known for me is to looping through all array:

var index=-1;
for(var i=0;i<Data.length;i++)
  if(Data[i].name==="John"){index=i;break;}

or case insensitive:

var index=-1;
for(var i=0;i<Data.length;i++)
  if(Data[i].name.toLowerCase()==="john"){index=i;break;}

On result variable index contain index of object or -1 if not found.

Convert CString to const char*

I had a similar problem. I had a char* buffer with the .so name in it.
I could not convert the char* variable to LPCTSTR. Here's how I got around it...

char *fNam;
...
LPCSTR nam = fNam;
dll = LoadLibraryA(nam);

List Highest Correlation Pairs from a Large Correlation Matrix in Pandas?

You can do graphically according to this simple code by substituting your data.

corr = df.corr()

kot = corr[corr>=.9]
plt.figure(figsize=(12,8))
sns.heatmap(kot, cmap="Greens")

enter image description here

All possible array initialization syntaxes

Trivial solution with expressions. Note that with NewArrayInit you can create just one-dimensional array.

NewArrayExpression expr = Expression.NewArrayInit(typeof(int), new[] { Expression.Constant(2), Expression.Constant(3) });
int[] array = Expression.Lambda<Func<int[]>>(expr).Compile()(); // compile and call callback

Mocking python function based on input arguments

If you "want to return a fixed value when the input parameter has a particular value", maybe you don't even need a mock and could use a dict along with its get method:

foo = {'input1': 'value1', 'input2': 'value2'}.get

foo('input1')  # value1
foo('input2')  # value2

This works well when your fake's output is a mapping of input. When it's a function of input I'd suggest using side_effect as per Amber's answer.

You can also use a combination of both if you want to preserve Mock's capabilities (assert_called_once, call_count etc):

self.mock.side_effect = {'input1': 'value1', 'input2': 'value2'}.get

node-request - Getting error "SSL23_GET_SERVER_HELLO:unknown protocol"

You will get such error message when you request HTTPS resource via wrong port, such as 80. So please make sure you specified right port, 443, in the Request options.

How do I vertically center an H1 in a div?

This is the jQuery method. Looks like overkill but it calculates the offset.

<html>
<head>
<title></title>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
    <script type="text/javascript" src="https://raw.github.com/dreamerslab/jquery.center/master/jquery.center.js"></script>
    <script type="text/javascript">
        $(function(){

            $('#jquery-center').center();

        });
    </script>

</head>
<body>
    <div id="jquery-center" style="position:absolute;">
       <h1>foo</h1>
    </div>
</body>
</html>

How to remove unused imports in Intellij IDEA on commit?

When you commit, tick the Optimize imports option on the right. This will become the default until you change it.

I prefer using the Reformat code option as well.

Convert a list of characters into a string

If your Python interpreter is old (1.5.2, for example, which is common on some older Linux distributions), you may not have join() available as a method on any old string object, and you will instead need to use the string module. Example:

a = ['a', 'b', 'c', 'd']

try:
    b = ''.join(a)

except AttributeError:
    import string
    b = string.join(a, '')

The string b will be 'abcd'.

Commenting code in Notepad++

To add a comment under any code on NOTEPAD++ first we have to save and define the programming or scripting file type. Like, save the file as xml, html etc. Once the file is saved in proper format you will be able to add a comment directly using the shortcut ctrl+Q

C++ style cast from unsigned char * to const char *

unsigned char* is basically a byte array and should be used to represent raw data rather than a string generally. A unicode string would be represented as wchar_t*

According to the C++ standard a reinterpret_cast between unsigned char* and char* is safe as they are the same size and have the same construction and constraints. I try to avoid reintrepret_cast even more so than const_cast in general.

If static cast fails with what you are doing you may want to reconsider your design because frankly if you are using C++ you may want to take advantage of what the "plus plus" part offers and use string classes and STL (aka std::basic_string might work better for you)

How do I open workbook programmatically as read-only?

Check out the language reference:

http://msdn.microsoft.com/en-us/library/aa195811(office.11).aspx

expression.Open(FileName, UpdateLinks, ReadOnly, Format, Password, WriteResPassword, IgnoreReadOnlyRecommended, Origin, Delimiter, Editable, Notify, Converter, AddToMru, Local, CorruptLoad)

Binding value to input in Angular JS

Some times there are problems with funtion/features that do not interact with the DOM

try to change the value sharply and then assign the $scope

document.getElementById ("textWidget") value = "<NewVal>";
$scope.widget.title = "<NewVal>";

Windows equivalent of 'touch' (i.e. the node.js way to create an index.html)

You can also use copy con [filename] in a Windows command window (cmd.exe):

C:\copy con yourfile.txt [enter]
C:\CTRL + Z [enter] //hold CTRL key & press "Z" then press Enter key.
^Z
    1 Files Copied.

This will create a file named yourfile.txt in the local directory.

Sorting a List<int>

Sort list of int descending you could just sort first and reverse

class Program
{
    static void Main(string[] args)
    {

        List<int> myList = new List<int>();

        myList.Add(38);
        myList.Add(34);
        myList.Add(35);
        myList.Add(36);
        myList.Add(37);


        myList.Sort();
        myList.Reverse();
        myList.ForEach(Console.WriteLine);


    }



}

How to read from stdin with fgets()?

Assuming that you only want to read a single line, then use LINE_MAX, which is defined in <limits.h>:

#include <stdio.h>
#include <limits.h>
...
char line[LINE_MAX];
...
if (fgets(line, LINE_MAX, stdin) != NULL) {
...
}
...

Change Circle color of radio button

<RadioButton
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:id="@+id/radio"
    android:buttonTint="@color/my_color"/>

All button will change color, the circle box and the central check.

Disable arrow key scrolling in users browser

For maintainability, I would attach the "blocking" handler on the element itself (in your case, the canvas).

theCanvas.onkeydown = function (e) {
    if (e.key === 'ArrowUp' || e.key === 'ArrowDown') {
        e.view.event.preventDefault();
    }
}

Why not simply do window.event.preventDefault()? MDN states:

window.event is a proprietary Microsoft Internet Explorer property which is only available while a DOM event handler is being called. Its value is the Event object currently being handled.

Further readings:

Linq to SQL .Sum() without group ... into

I know this is an old question but why can't you do it like:

db.OrderLineItems.Where(o => o.OrderId == currentOrder.OrderId).Sum(o => o.WishListItem.Price);

I am not sure how to do this using query expressions.

How to get a list of properties with a given attribute?

var props = t.GetProperties().Where(
                prop => Attribute.IsDefined(prop, typeof(MyAttribute)));

This avoids having to materialize any attribute instances (i.e. it is cheaper than GetCustomAttribute[s]().

How to install Python package from GitHub?

You need to use the proper git URL:

pip install git+https://github.com/jkbr/httpie.git#egg=httpie

Also see the VCS Support section of the pip documentation.

Don’t forget to include the egg=<projectname> part to explicitly name the project; this way pip can track metadata for it without having to have run the setup.py script.

Loading scripts after page load?

Focusing on one of the accepted answer's jQuery solutions, $.getScript() is an .ajax() request in disguise. It allows to execute other function on success by adding a second parameter:

$.getScript(url, function() {console.log('loaded script!')})

Or on the request's handlers themselves, i.e. success (.done() - script was loaded) or failure (.fail()):

_x000D_
_x000D_
$.getScript(_x000D_
    "https://code.jquery.com/color/jquery.color.js",_x000D_
    () => console.log('loaded script!')_x000D_
  ).done((script,textStatus ) => {_x000D_
    console.log( textStatus );_x000D_
    $(".block").animate({backgroundColor: "green"}, 1000);_x000D_
  }).fail(( jqxhr, settings, exception ) => {_x000D_
    console.log(exception + ': ' + jqxhr.status);_x000D_
  }_x000D_
);
_x000D_
.block {background-color: blue;width: 50vw;height: 50vh;margin: 1rem;}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div class="block"></div>
_x000D_
_x000D_
_x000D_

How to make input type= file Should accept only pdf and xls

You could use JavaScript. Take in consideration that the big problem with doing this with JavaScript is to reset the input file. Well, this restricts to only JPG (for PDF you will have to change the mime type and the magic number):

<form id="form-id">
  <input type="file" id="input-id" accept="image/jpeg"/>
</form>

<script type="text/javascript">
    $(function(){
        $("#input-id").on('change', function(event) {
            var file = event.target.files[0];
            if(file.size>=2*1024*1024) {
                alert("JPG images of maximum 2MB");
                $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                return;
            }

            if(!file.type.match('image/jp.*')) {
                alert("only JPG images");
                $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                return;
            }

            var fileReader = new FileReader();
            fileReader.onload = function(e) {
                var int32View = new Uint8Array(e.target.result);
                //verify the magic number
                // for JPG is 0xFF 0xD8 0xFF 0xE0 (see https://en.wikipedia.org/wiki/List_of_file_signatures)
                if(int32View.length>4 && int32View[0]==0xFF && int32View[1]==0xD8 && int32View[2]==0xFF && int32View[3]==0xE0) {
                    alert("ok!");
                } else {
                    alert("only valid JPG images");
                    $("#form-id").get(0).reset(); //the tricky part is to "empty" the input file here I reset the form.
                    return;
                }
            };
            fileReader.readAsArrayBuffer(file);
        });
    });
</script>

Take in consideration that this was tested on latest versions of Firefox and Chrome, and on IExplore 10.

For a complete list of mime types see Wikipedia.

For a complete list of magic number see Wikipedia.

latex large division sign in a math formula

I found the answer I was looking for. The thing to use here is the construct of

\left \middle \right

For example, in this case, two possible solutions are:

$\left( {\frac{a_1}{a_2}} \middle/ {\frac{b_1}{b_2}} \right) $

Or, in case the brackets are not necessary:

$\left. {\frac{a_1}{a_2}} \middle/ {\frac{b_1}{b_2}} \right. $

How can I use external JARs in an Android project?

If you are using gradle build system, follow these steps:

  1. put jar files inside respective libs folder of your android app. You will generally find it at Project > app > libs. If libs folder is missing, create one.

  2. add this to your build.gradle file your app. (Not to your Project's build.gradle)

    dependencies {
        compile fileTree(dir: 'libs', include: '*.jar')
        // other dependencies
    }
    

    This will include all your jar files available in libs folder.

If don't want to include all jar files, then you can add it individually.

compile fileTree(dir: 'libs', include: 'file.jar')

Check if Cookie Exists

You can do something like this to find out the cookies's value:

Request.Cookies[SESSION_COOKIE_NAME].Value

How to get current relative directory of your Makefile?

Example for your reference, as below:

The folder structure might be as:

enter image description here

Where there are two Makefiles, each as below;

sample/Makefile
test/Makefile

Now, let us see the content of the Makefiles.

sample/Makefile

export ROOT_DIR=${PWD}

all:
    echo ${ROOT_DIR}
    $(MAKE) -C test

test/Makefile

all:
    echo ${ROOT_DIR}
    echo "make test ends here !"

Now, execute the sample/Makefile, as;

cd sample
make

OUTPUT:

echo /home/symphony/sample
/home/symphony/sample
make -C test
make[1]: Entering directory `/home/symphony/sample/test'
echo /home/symphony/sample
/home/symphony/sample
echo "make test ends here !"
make test ends here !
make[1]: Leaving directory `/home/symphony/sample/test'

Explanation, would be that the parent/home directory can be stored in the environment-flag, and can be exported, so that it can be used in all the sub-directory makefiles.

How do I obtain the frequencies of each value in an FFT?

Take a look at my answer here.

Answer to comment:

The FFT actually calculates the cross-correlation of the input signal with sine and cosine functions (basis functions) at a range of equally spaced frequencies. For a given FFT output, there is a corresponding frequency (F) as given by the answer I posted. The real part of the output sample is the cross-correlation of the input signal with cos(2*pi*F*t) and the imaginary part is the cross-correlation of the input signal with sin(2*pi*F*t). The reason the input signal is correlated with sin and cos functions is to account for phase differences between the input signal and basis functions.

By taking the magnitude of the complex FFT output, you get a measure of how well the input signal correlates with sinusoids at a set of frequencies regardless of the input signal phase. If you are just analyzing frequency content of a signal, you will almost always take the magnitude or magnitude squared of the complex output of the FFT.

Set the intervals of x-axis using r

You can use axis:

> axis(side=1, at=c(0:23))

That is, something like this:

plot(0:23, d, type='b', axes=FALSE)
axis(side=1, at=c(0:23))
axis(side=2, at=seq(0, 600, by=100))
box()

Regex to test if string begins with http:// or https://

Your use of [] is incorrect -- note that [] denotes a character class and will therefore only ever match one character. The expression [(http)(https)] translates to "match a (, an h, a t, a t, a p, a ), or an s." (Duplicate characters are ignored.)

Try this:

^https?://

If you really want to use alternation, use this syntax instead:

^(http|https)://

Style input type file?

Same solution via Jquery. Works if you have more than one file input in the page.

$j(".filebutton").click(function() {
    var input = $j(this).next().find('input');
    input.click();
});

$j(".fileinput").change(function(){

    var file = $j(this).val();
    var fileName = file.split("\\");
    var pai =$j(this).parent().parent().prev();
    pai.html(fileName[fileName.length-1]);
    event.preventDefault();
});

CS0234: Mvc does not exist in the System.Web namespace

None of previous answers worked for me.

I noticed that my project was referencing another project using the System.Web.Mvc reference from the .NET Framework.

I just deleted that assembly and added the "Microsoft.AspNet.Mvc" NuGet package and that fixed my problem.

Recommended way to embed PDF in HTML?

If you don't want to host PDF.JS on your own, you could try DocDroid. It is similar to the Google Drive PDF viewer but allows custom branding.

Selecting multiple columns/fields in MySQL subquery

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

FROM TABLE A

The other way is

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

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

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

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

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

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

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

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

React - how to pass state to another component

Move all of your state and your handleClick function from Header to your MainWrapper component.

Then pass values as props to all components that need to share this functionality.

class MainWrapper extends React.Component {
    constructor() {
        super();
        this.state = {
            sidbarPushCollapsed: false,
            profileCollapsed: false
        };
        this.handleClick = this.handleClick.bind(this);
    }
    handleClick() {
        this.setState({
            sidbarPushCollapsed: !this.state.sidbarPushCollapsed,
            profileCollapsed: !this.state.profileCollapsed

        });
    }
    render() {
        return (
           //...
           <Header 
               handleClick={this.handleClick} 
               sidbarPushCollapsed={this.state.sidbarPushCollapsed}
               profileCollapsed={this.state.profileCollapsed} />
        );

Then in your Header's render() method, you'd use this.props:

<button type="button" id="sidbarPush" onClick={this.props.handleClick} profile={this.props.profileCollapsed}>

Disallow Twitter Bootstrap modal window from closing

Just set the backdrop property to 'static'.

$('#myModal').modal({
  backdrop: 'static',
  keyboard: true
})

You may also want to set the keyboard property to false because that prevents the modal from being closed by pressing the Esc key on the keyboard.

$('#myModal').modal({
  backdrop: 'static',
  keyboard: false
})

myModal is the ID of the div that contains your modal content.

Lightweight workflow engine for Java

I recently open sourced Piper (https://github.com/creactiviti/piper) a distributed and very light weight, Spring-based, workflow engine.

keytool error Keystore was tampered with, or password was incorrect

Summarizing the advices from this page, I finished up with the following:

keytool -genkeypair -keystore ~/.android/release.keystore -alias <my_alias> -storepass <my_cert_pass> -keyalg RSA

Then I got a set of questions regarding name, organization, location and password for my alias.

How to call JavaScript function instead of href in HTML

Try to make your javascript unobtrusive :

  • you should use a real link in href attribute
  • and add a listener on click event to handle ajax

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

You can use the following command:

svn status -q

According to svnbook:

With --quiet (-q), it prints only summary information about locally modified items.

WARNING: The output of this command only shows your modification. So I suggest to do a svn up to get latest version of the file and then use svn status -q to get the files you have modified.

How to create EditText with cross(x) button at end of it?

Just put close cross like drawableEnd in your EditText:

<EditText
     ...
    android:drawableEnd="@drawable/ic_close"
    android:drawablePadding="8dp"
     ... />

and use extension to handle click (or use OnTouchListener directly on your EditText):

fun EditText.onDrawableEndClick(action: () -> Unit) {
    setOnTouchListener { v, event ->
        if (event.action == MotionEvent.ACTION_UP) {
            v as EditText
            val end = if (v.resources.configuration.layoutDirection == View.LAYOUT_DIRECTION_RTL)
                v.left else v.right
            if (event.rawX >= (end - v.compoundPaddingEnd)) {
                action.invoke()
                return@setOnTouchListener true
            }
        }
        return@setOnTouchListener false
    }
}

extension usage:

editText.onDrawableEndClick {
    // TODO clear action
    etSearch.setText("")
}

How can I initialize a C# List in the same line I declare it. (IEnumerable string Collection Example)

List<string> nameslist = new List<string> {"one", "two", "three"} ?

How to escape special characters of a string with single backslashes

Just assuming this is for a regular expression, use re.escape.

Is there an equivalent of lsusb for OS X

Homebrew users: you can get lsusb by installing usbutils formula from my tap:

brew install mikhailai/misc/usbutils

It installs the REAL lsusb based on Linux sources (version 007).

Extract the filename from a path

Get-ChildItem "D:\Server\User\CUST\MEA\Data\In\Files\CORRECTED\CUST_MEAFile.csv"
|Select-Object -ExpandProperty Name

What is "stdafx.h" used for in Visual Studio?

"Stdafx.h" is a precompiled header.It include file for standard system include files and for project-specific include files that are used frequently but are changed infrequently.which reduces compile time and Unnecessary Processing.

Precompiled Header stdafx.h is basically used in Microsoft Visual Studio to let the compiler know the files that are once compiled and no need to compile it from scratch. You can read more about it

http://www.cplusplus.com/articles/1TUq5Di1/

https://docs.microsoft.com/en-us/cpp/ide/precompiled-header-files?view=vs-2017

How to change the colors of a PNG image easily?

If you are going to be programming an application to do all of this, the process will be something like this:

  1. Convert image from RGB to HSV
  2. adjust H value
  3. Convert image back to RGB
  4. Save image

Submit form using <a> tag

Here is how I would do it using vanilla JS

<form id="myform" method="POST" action="xxx">
    <!-- your stuff here -->
    <a href="javascript:void()" onclick="document.getElementById('myform').submit();>Ponies await!</a>
</form>

You can play with the return falses and href="#" vs void and whatever you need to but this method worked for me in Chrome 18, IE 9 and Firefox 14 and the rest depends on your javascript mostly.

Difference between static memory allocation and dynamic memory allocation

This is a standard interview question:

Dynamic memory allocation

Is memory allocated at runtime using calloc(), malloc() and friends. It is sometimes also referred to as 'heap' memory, although it has nothing to do with the heap data-structure ref.

int * a = malloc(sizeof(int));

Heap memory is persistent until free() is called. In other words, you control the lifetime of the variable.

Automatic memory allocation

This is what is commonly known as 'stack' memory, and is allocated when you enter a new scope (usually when a new function is pushed on the call stack). Once you move out of the scope, the values of automatic memory addresses are undefined, and it is an error to access them.

int a = 43;

Note that scope does not necessarily mean function. Scopes can nest within a function, and the variable will be in-scope only within the block in which it was declared. Note also that where this memory is allocated is not specified. (On a sane system it will be on the stack, or registers for optimisation)

Static memory allocation

Is allocated at compile time*, and the lifetime of a variable in static memory is the lifetime of the program.

In C, static memory can be allocated using the static keyword. The scope is the compilation unit only.

Things get more interesting when the extern keyword is considered. When an extern variable is defined the compiler allocates memory for it. When an extern variable is declared, the compiler requires that the variable be defined elsewhere. Failure to declare/define extern variables will cause linking problems, while failure to declare/define static variables will cause compilation problems.

in file scope, the static keyword is optional (outside of a function):

int a = 32;

But not in function scope (inside of a function):

static int a = 32;

Technically, extern and static are two separate classes of variables in C.

extern int a; /* Declaration */
int a; /* Definition */

*Notes on static memory allocation

It's somewhat confusing to say that static memory is allocated at compile time, especially if we start considering that the compilation machine and the host machine might not be the same or might not even be on the same architecture.

It may be better to think that the allocation of static memory is handled by the compiler rather than allocated at compile time.

For example the compiler may create a large data section in the compiled binary and when the program is loaded in memory, the address within the data segment of the program will be used as the location of the allocated memory. This has the marked disadvantage of making the compiled binary very large if uses a lot of static memory. It's possible to write a multi-gigabytes binary generated from less than half a dozen lines of code. Another option is for the compiler to inject initialisation code that will allocate memory in some other way before the program is executed. This code will vary according to the target platform and OS. In practice, modern compilers use heuristics to decide which of these options to use. You can try this out yourself by writing a small C program that allocates a large static array of either 10k, 1m, 10m, 100m, 1G or 10G items. For many compilers, the binary size will keep growing linearly with the size of the array, and past a certain point, it will shrink again as the compiler uses another allocation strategy.

Register Memory

The last memory class are 'register' variables. As expected, register variables should be allocated on a CPU's register, but the decision is actually left to the compiler. You may not turn a register variable into a reference by using address-of.

register int meaning = 42;
printf("%p\n",&meaning); /* this is wrong and will fail at compile time. */

Most modern compilers are smarter than you at picking which variables should be put in registers :)

References:

Select row with most recent date per user

This worked for me:

SELECT user, time FROM 
(
    SELECT user, time FROM lms_attendance --where clause
) AS T 
WHERE (SELECT COUNT(0) FROM table WHERE user = T.user AND time > T.time) = 0
ORDER BY user ASC, time DESC

Difference between UTF-8 and UTF-16?

I believe there are a lot of good articles about this around the Web, but here is a short summary.

Both UTF-8 and UTF-16 are variable length encodings. However, in UTF-8 a character may occupy a minimum of 8 bits, while in UTF-16 character length starts with 16 bits.

Main UTF-8 pros:

  • Basic ASCII characters like digits, Latin characters with no accents, etc. occupy one byte which is identical to US-ASCII representation. This way all US-ASCII strings become valid UTF-8, which provides decent backwards compatibility in many cases.
  • No null bytes, which allows to use null-terminated strings, this introduces a great deal of backwards compatibility too.
  • UTF-8 is independent of byte order, so you don't have to worry about Big Endian / Little Endian issue.

Main UTF-8 cons:

  • Many common characters have different length, which slows indexing by codepoint and calculating a codepoint count terribly.
  • Even though byte order doesn't matter, sometimes UTF-8 still has BOM (byte order mark) which serves to notify that the text is encoded in UTF-8, and also breaks compatibility with ASCII software even if the text only contains ASCII characters. Microsoft software (like Notepad) especially likes to add BOM to UTF-8.

Main UTF-16 pros:

  • BMP (basic multilingual plane) characters, including Latin, Cyrillic, most Chinese (the PRC made support for some codepoints outside BMP mandatory), most Japanese can be represented with 2 bytes. This speeds up indexing and calculating codepoint count in case the text does not contain supplementary characters.
  • Even if the text has supplementary characters, they are still represented by pairs of 16-bit values, which means that the total length is still divisible by two and allows to use 16-bit char as the primitive component of the string.

Main UTF-16 cons:

  • Lots of null bytes in US-ASCII strings, which means no null-terminated strings and a lot of wasted memory.
  • Using it as a fixed-length encoding “mostly works” in many common scenarios (especially in US / EU / countries with Cyrillic alphabets / Israel / Arab countries / Iran and many others), often leading to broken support where it doesn't. This means the programmers have to be aware of surrogate pairs and handle them properly in cases where it matters!
  • It's variable length, so counting or indexing codepoints is costly, though less than UTF-8.

In general, UTF-16 is usually better for in-memory representation because BE/LE is irrelevant there (just use native order) and indexing is faster (just don't forget to handle surrogate pairs properly). UTF-8, on the other hand, is extremely good for text files and network protocols because there is no BE/LE issue and null-termination often comes in handy, as well as ASCII-compatibility.

receiving json and deserializing as List of object at spring mvc controller

Here is the code that works for me. The key is that you need a wrapper class.

public class Person {

    private String name;
    private Integer age;

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public Integer getAge() {
        return age;
    }

    public void setAge(Integer age) {
        this.age = age;
    }

    @Override
    public String toString() {
        return "Person [name=" + name + ", age=" + age + "]";
    }

A PersonWrapper class

public class PersonWrapper {

    private List<Person> persons;

    /**
     * @return the persons
     */
    public List<Person> getPersons() {
        return persons;
    }

    /**
     * @param persons the persons to set
     */
    public void setPersons(List<Person> persons) {
        this.persons = persons;
    }
}

My Controller methods

@RequestMapping(value="person", method=RequestMethod.POST,consumes="application/json",produces="application/json")
    @ResponseBody
    public List<String> savePerson(@RequestBody PersonWrapper wrapper) {
        List<String> response = new ArrayList<String>();
        for (Person person: wrapper.getPersons()){
        personService.save(person);
         response.add("Saved person: " + person.toString());
    }
        return response;
    }

The request sent is json in POST

{"persons":[{"name":"shail1","age":"2"},{"name":"shail2","age":"3"}]}

And the response is

["Saved person: Person [name=shail1, age=2]","Saved person: Person [name=shail2, age=3]"]

Could not install Gradle distribution from 'https://services.gradle.org/distributions/gradle-2.1-all.zip'

First check your Internet conection..

or try with

Tools -> Android -> Sync

or Try

File -> Settings -> Gradle -> Check Offline Work

enter image description here

AngularJS access scope from outside js function

It's been a long time since I asked this question, but here's an answer that doesn't require jquery:

function change() {
    var scope = angular.element(document.querySelector('#outside')).scope();
    scope.$apply(function(){
        scope.msg = 'Superhero';
    })
}

How can I dynamically switch web service addresses in .NET without a recompile?

If you are fetching the URL from a database you can manually assign it to the web service proxy class URL property. This should be done before calling the web method.

If you would like to use the config file, you can set the proxy classes URL behavior to dynamic.

Items in JSON object are out of order using "json.dumps"?

As others have mentioned the underlying dict is unordered. However there are OrderedDict objects in python. ( They're built in in recent pythons, or you can use this: http://code.activestate.com/recipes/576693/ ).

I believe that newer pythons json implementations correctly handle the built in OrderedDicts, but I'm not sure (and I don't have easy access to test).

Old pythons simplejson implementations dont handle the OrderedDict objects nicely .. and convert them to regular dicts before outputting them.. but you can overcome this by doing the following:

class OrderedJsonEncoder( simplejson.JSONEncoder ):
   def encode(self,o):
      if isinstance(o,OrderedDict.OrderedDict):
         return "{" + ",".join( [ self.encode(k)+":"+self.encode(v) for (k,v) in o.iteritems() ] ) + "}"
      else:
         return simplejson.JSONEncoder.encode(self, o)

now using this we get:

>>> import OrderedDict
>>> unordered={"id":123,"name":"a_name","timezone":"tz"}
>>> ordered = OrderedDict.OrderedDict( [("id",123), ("name","a_name"), ("timezone","tz")] )
>>> e = OrderedJsonEncoder()
>>> print e.encode( unordered )
{"timezone": "tz", "id": 123, "name": "a_name"}
>>> print e.encode( ordered )
{"id":123,"name":"a_name","timezone":"tz"}

Which is pretty much as desired.

Another alternative would be to specialise the encoder to directly use your row class, and then you'd not need any intermediate dict or UnorderedDict.

How can I mock requests and the response?

If you want to mock a fake response, another way to do it is to simply instantiate an instance of the base HttpResponse class, like so:

from django.http.response import HttpResponseBase

self.fake_response = HttpResponseBase()

Change a web.config programmatically with C# (.NET)

Here it is some code:

var configuration = WebConfigurationManager.OpenWebConfiguration("~");
var section = (ConnectionStringsSection)configuration.GetSection("connectionStrings");
section.ConnectionStrings["MyConnectionString"].ConnectionString = "Data Source=...";
configuration.Save();

See more examples in this article, you may need to take a look to impersonation.

Warning: date_format() expects parameter 1 to be DateTime

try this

$start_date = date_create($_POST['start_date']);
$start_date = date_format($start_date,"Y-m-d H:i:s");

How can I send the "&" (ampersand) character via AJAX?

The preferred way is to use a JavaScript library such as jQuery and set your data option as an object, then let jQuery do the encoding, like this:

$.ajax({
  type: "POST",
  url: "/link.json",
  data: { value: poststr },
  error: function(){ alert('some error occured'); }
});

If you can't use jQuery (which is pretty much the standard these days), use encodeURIComponent.

Configuring RollingFileAppender in log4j

I had a similar problem and just found a way to solve it (by single-stepping through log4j-extras source, no less...)

The good news is that, unlike what's written everywhere, it turns out that you actually CAN configure TimeBasedRollingPolicy using log4j.properties (XML config not needed! At least in versions of log4j >1.2.16 see this bug report)

Here is an example:

log4j.appender.File = org.apache.log4j.rolling.RollingFileAppender
log4j.appender.File.rollingPolicy = org.apache.log4j.rolling.TimeBasedRollingPolicy
log4j.appender.File.rollingPolicy.FileNamePattern = logs/worker-${instanceId}.%d{yyyyMMdd-HHmm}.log

BTW the ${instanceId} bit is something I am using on Amazon's EC2 to distinguish the logs from all my workers -- I just need to set that property before calling PropertyConfigurator.configure(), as follow:

p.setProperty("instanceId", EC2Util.getMyInstanceId());
PropertyConfigurator.configure(p);

TypeError("'bool' object is not iterable",) when trying to return a Boolean

Look at the traceback:

Traceback (most recent call last):
  File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
    out = iter(out)
TypeError: 'bool' object is not iterable

Your code isn't iterating the value, but the code receiving it is.

The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)) or enclose it in a tuple ((False,)).

Always read the traceback: it's correct, and it's helpful.

Python: TypeError: object of type 'NoneType' has no len()

I was faces this issue but after change object into str, problem solved. str(fname).isalpha():

iOS - Build fails with CocoaPods cannot find header files

Update

Make sure your Podfile includes link_with on targets missing a config file. Cocoapods only sets the first target by default otherwise. e.g.

platform :osx, '10.7'
pod 'JSONKit',       '~> 1.4'

link_with 'Pomo', 'Pomo Dev', 'Pomo Tests'

------ End Update


Note: Please do note that you have to look into Project->Info->Configurations for steps below.


I had similar symptoms and found that the pods.xcconfig file was not being included in the specific target I was trying to build. Some of the other suggested solutions worked for me, but this one seemed to address part of the underlying issue.

Pods.xcconfig not working

The simple solution was to change set the configuration file for the targets that didn't have one set.

Pods.xcconfig working

mysql update multiple columns with same now()

MySQL evaluates now() once per statement when the statement commences execution. So it is safe to have multiple visible now() calls per statement.

select now(); select now(), sleep(10), now(); select now();
+---------------------+
| now()               |
+---------------------+
| 2018-11-05 16:54:00 |
+---------------------+
1 row in set (0.00 sec)

+---------------------+-----------+---------------------+
| now()               | sleep(10) | now()               |
+---------------------+-----------+---------------------+
| 2018-11-05 16:54:00 |         0 | 2018-11-05 16:54:00 |
+---------------------+-----------+---------------------+
1 row in set (10.00 sec)

+---------------------+
| now()               |
+---------------------+
| 2018-11-05 16:54:10 |
+---------------------+
1 row in set (0.00 sec)

C#: HttpClient with POST parameters

A cleaner alternative would be to use a Dictionary to handle parameters. They are key-value pairs after all.

private static readonly HttpClient httpclient;

static MyClassName()
{
    // HttpClient is intended to be instantiated once and re-used throughout the life of an application. 
    // Instantiating an HttpClient class for every request will exhaust the number of sockets available under heavy loads. 
    // This will result in SocketException errors.
    // https://docs.microsoft.com/en-us/dotnet/api/system.net.http.httpclient?view=netframework-4.7.1
    httpclient = new HttpClient();    
} 

var url = "http://myserver/method";
var parameters = new Dictionary<string, string> { { "param1", "1" }, { "param2", "2" } };
var encodedContent = new FormUrlEncodedContent (parameters);

var response = await httpclient.PostAsync (url, encodedContent).ConfigureAwait (false);
if (response.StatusCode == HttpStatusCode.OK) {
    // Do something with response. Example get content:
    // var responseContent = await response.Content.ReadAsStringAsync ().ConfigureAwait (false);
}

Also dont forget to Dispose() httpclient, if you dont use the keyword using

As stated in the Remarks section of the HttpClient class in the Microsoft docs, HttpClient should be instantiated once and re-used.

Edit:

You may want to look into response.EnsureSuccessStatusCode(); instead of if (response.StatusCode == HttpStatusCode.OK).

You may want to keep your httpclient and dont Dispose() it. See: Do HttpClient and HttpClientHandler have to be disposed?

Edit:

Do not worry about using .ConfigureAwait(false) in .NET Core. For more details look at https://blog.stephencleary.com/2017/03/aspnetcore-synchronization-context.html

How to convert from int to string in objective c: example code

== shouldn't be used to compare objects in your if. For NSString use isEqualToString: to compare them.

What is the best/simplest way to read in an XML file in Java application?

This is what I use. http://marketmovers.blogspot.com/2014/02/the-easy-way-to-read-xml-in-java.html It sits on top of the standard JDK tools, so if it's missing some feature you can always use the JDK version.

This really makes things easier for me. It's especially nice when I'm reading a config file that was saved by and older version of the software, or was manually edited by a user. It's very robust and won't throw an exception if some data is not exactly in the format you expect.

Print string to text file

With using pathlib module, indentation isn't needed.

import pathlib
pathlib.Path("output.txt").write_text("Purchase Amount: {}" .format(TotalAmount))

As of python 3.6, f-strings is available.

pathlib.Path("output.txt").write_text(f"Purchase Amount: {TotalAmount}")

How to split a string in shell and get the last field

You could try something like this if you want to use cut:

echo "1:2:3:4:5" | cut -d ":" -f5

You can also use grep try like this :

echo " 1:2:3:4:5" | grep -o '[^:]*$'

How do I include negative decimal numbers in this regular expression?

This worked for me, allowing both negative and positive numbers:

 \-*\d+

If using C#:

Regex.Match(someString, @"\-*\d+").Value;

How do I create a ListView with rounded corners in Android?

There are different ways to achieve it. The latest approach is using CardView for each ListItem component. Here are some steps.

  1. Create a layout resource file; let's name it "listitem.xml
  2. Copy and paste the under enclosed Listitem.xml layout body into it.
  3. Create RowItem class for each listitem data; later you will instantiate this to assign values for each list item. Check Code below, RowItem.class.
  4. Create a custom ListAdapter; let's name it ListAdapter.class, and inflate this (#1) list item layout for each list item (Check the second code snippet for this one)
  5. Set this adapter (#3) the way you set default adapters inside an activity the listview belongs to. maybe the only difference would be you first have to instantiate RowItem class with values and add RowItem object to your adapter then notify your adapter that the data is changed.
**listitem.xml**
<?xml version="1.0" encoding="utf-8"?>
    <LinearLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">
        <GridLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"

            android:alignmentMode="alignMargins"
            android:columnCount="1"
            android:columnOrderPreserved="false"
            android:rowCount="1">
            <androidx.cardview.widget.CardView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:layout_rowWeight="1"
                android:layout_columnWeight="1"
                android:layout_margin="6dp"
                app:cardCornerRadius="8dp"
                app:cardElevation="6dp">
                <LinearLayout
                    android:layout_width="match_parent"
                    android:layout_height="match_parent"
                    android:orientation="horizontal">
                    <ImageView
                        android:id="@+id/sampleiconimageID"
                        android:layout_width="60dp"
                        android:layout_height="60dp"
                        android:padding="5dp"/>
                    <LinearLayout android:layout_width="wrap_content"
                        android:layout_height="wrap_content"
                        android:orientation="vertical">
                        <TextView
                            android:id="@+id/titleoflistview"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="Main Heading"
                            android:textStyle="bold" />
                        <TextView
                            android:id="@+id/samplesubtitle"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="Sub Heading"
                           />
                        </LinearLayout>
                </LinearLayout>
            </androidx.cardview.widget.CardView>
        </GridLayout>
    </LinearLayout>

RowItem.Class

public class RowItem {
    private String heading;
    private String subHeading;
    private int smallImageName;
    private String datetime;
    private int count;

    public void setHeading( String theHeading ) {
        this.heading = theHeading;
    }

    public String getHeading() {
        return this.heading;
    }
    public void setSubHeading( String theSubHeading ) {

        this.subHeading = theSubHeading;

    }

    public String getSubHeading( ) {

        return this.subHeading;

    }

    public void setSmallImageName(int smallName) {

        this.smallImageName = smallName;

    }

    public int getSmallImageName() {

        return this.smallImageName;

    }

    public void setDate(String datetime) {
        this.datetime = datetime;
    }

    public String getDate() {
        return this.datetime;
    }

    public void setCount(int count) {
        this.count = count;
    }

    public int getCount() {
        return this.count;
    }

}

Sample ListAdapter

public class ListAdapter extends BaseAdapter {
    private ArrayList<RowItem> singleRow;
    private LayoutInflater thisInflater;

    public ListAdapter(Context context, ArrayList<RowItem> aRow){

        this.singleRow = aRow;
        thisInflater = ( LayoutInflater.from(context) );
    }
    @Override
    public int getCount() {
        return singleRow.size();    }

    @Override
    public Object getItem(int position) {
        return singleRow.get( position );    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    public View getView(int position, View view, ViewGroup parent) {

        if (view == null) {
            view = thisInflater.inflate( R.layout.mylist2, parent, false );
            //set listview objects here
            //example

            TextView titleText = (TextView) view.findViewById(R.id.titleoflistview);
           
            RowItem currentRow = (RowItem) getItem(position);
            
            titleText.setText( currentRow.getHeading() );
          
        }

        return view;

//        LayoutInflater inflater=.getLayoutInflater();
//        View rowView=inflater.inflate(R.layout.mylist, null,true);
//

//        titleText.setText(maintitle[position]);
//        subtitleText.setText(subtitle[position]);

//        return null;

    };
}

Difference between onStart() and onResume()

Short answer:

We can't live without onStart because that is the state when the activity becomes "visible" to the user, but the user cant "interact" with it yet may be cause it's overlapped with some other small dialog. This ability to interact with the user is the one that differentiates onStart and onResume. Think of it as a person behind a glass door. You can see the person but you can't interact (talk/listen/shake hands) with him. OnResume is like the door opener after which you can begin the interaction.

Additionally onRestart() is the least understood one. We can ask the question as to why not directly go to onStart() or onResume() after onStop() instead of onRestart(). It becomes easier to understand if we note that onRestart() is partially equivalent to onCreate() if the creation part is omitted. Basically both states lead to onStart() (i.e the Activity becomes visible). So both the states have to "prepare" the stuff to be displayed. OnCreate has the additional responsibility to "create" the stuff to be displayed

So their code structures might fit to something like:

onCreate()
{
     createNecessaryObjects();

     prepareObjectsForDisplay();
}


onRestart()
{
     prepareObjectsForDisplay();

}

The entire confusion is caused since Google chose non-intuitive names instead of something as follows:

onCreateAndPrepareToDisplay()   [instead of onCreate() ]
onPrepareToDisplay()            [instead of onRestart() ]
onVisible()                     [instead of onStart() ]
onBeginInteraction()            [instead of onResume() ]
onPauseInteraction()            [instead of onPause() ]
onInvisible()                   [instead of onStop]
onDestroy()                     [no change] 

The Activity Diagram might be interpreted as:

Android Activity Lifecycle

How do I use WPF bindings with RelativeSource?

If you want to bind to another property on the object:

{Binding Path=PathToProperty, RelativeSource={RelativeSource Self}}

If you want to get a property on an ancestor:

{Binding Path=PathToProperty,
    RelativeSource={RelativeSource AncestorType={x:Type typeOfAncestor}}}

If you want to get a property on the templated parent (so you can do 2 way bindings in a ControlTemplate)

{Binding Path=PathToProperty, RelativeSource={RelativeSource TemplatedParent}}

or, shorter (this only works for OneWay bindings):

{TemplateBinding Path=PathToProperty}

create array from mysql query php

Very often this is done in a while loop:

$types = array();

while(($row =  mysql_fetch_assoc($result))) {
    $types[] = $row['type'];
}

Have a look at the examples in the documentation.

The mysql_fetch_* methods will always get the next element of the result set:

Returns an array of strings that corresponds to the fetched row, or FALSE if there are no more rows.

That is why the while loops works. If there aren't any rows anymore $row will be false and the while loop exists.

It only seems that mysql_fetch_array gets more than one row, because by default it gets the result as normal and as associative value:

By using MYSQL_BOTH (default), you'll get an array with both associative and number indices.

Your example shows it best, you get the same value 18 and you can access it via $v[0] or $v['type'].

Determine if Android app is being used for the first time

You could simply check for the existence of an empty file, if it doesn't exist, then execute your code and create the file.

e.g.

if(File.Exists("emptyfile"){
    //Your code here
    File.Create("emptyfile");
}

How to get anchor text/href on click using jQuery?

Alternative

Using the example from Sarfraz above.

<div class="res">
    <a class="info_link" href="~/Resumes/Resumes1271354404687.docx">
        ~/Resumes/Resumes1271354404687.docx
    </a>
</div>

For href:

$(function(){
  $('.res').on('click', '.info_link', function(){
    alert($(this)[0].href);
  });
});

C# Foreach statement does not contain public definition for GetEnumerator

Your CarBootSaleList class is not a list. It is a class that contain a list.

You have three options:

Make your CarBootSaleList object implement IEnumerable

or

make your CarBootSaleList inherit from List<CarBootSale>

or

if you are lazy this could almost do the same thing without extra coding

List<List<CarBootSale>>

appcompat-v7:21.0.0': No resource found that matches the given name: attr 'android:actionModeShareDrawable'

Make sure you clean your project in android studio (or eclipse),

It should solve your issues

What is the order of precedence for CSS?

AS is state in W3: W3 Cascade CSS

the orden that different style sheet are applied is the following (quote from W3 cascading section):

  1. user agent declarations

  2. user normal declarations

  3. author normal declarations

  4. author important declarations

  5. user important declarations

More information about this in the referred W3 document

How to write inside a DIV box with javascript

_x000D_
_x000D_
document.getElementById('log').innerHTML += '<br>Some new content!';
_x000D_
<div id="log">initial content</div>
_x000D_
_x000D_
_x000D_

Reading RFID with Android phones

You can use a simple, low-cost USB port reader like this test connects directly to your Android device; it has a utility app and an SDK you can use for app development: https://www.atlasrfidstore.com/sls-rfid-smartmicro-android-micro-usb-reader/

How to put the legend out of the plot

Not exactly what you asked for, but I found it's an alternative for the same problem. Make the legend semi-transparant, like so: matplotlib plot with semi transparent legend and semitransparent text box

Do this with:

fig = pylab.figure()
ax = fig.add_subplot(111)
ax.plot(x,y,label=label,color=color)
# Make the legend transparent:
ax.legend(loc=2,fontsize=10,fancybox=True).get_frame().set_alpha(0.5)
# Make a transparent text box
ax.text(0.02,0.02,yourstring, verticalalignment='bottom',
                     horizontalalignment='left',
                     fontsize=10,
                     bbox={'facecolor':'white', 'alpha':0.6, 'pad':10},
                     transform=self.ax.transAxes)

ng serve not detecting file changes automatically

In your project dist folder is own by root

Try to use sudo ng serve instead of ng serve.

Another solution

When there is having a large number of files watch not work in linux.There is a Limit at INotify Watches on Linux. So increasing the watches limit

//When live server not work in linux

sudo sysctl fs.inotify.max_user_watches=524288
sudo sysctl -p --system

ng serve //You can also do sudo **ng serve**

What's the difference between a mock & stub?

Both Stubs and Mocks override external dependencies but the difference is

Stubs -> To Test Data

Mocks -> To Test Behavior


Fake/Dummy -> Test nothing (just override functionality with empty methods, eg replace Logger to avoid any logging noise while testing)

Fastest way to determine if an integer's square root is an integer

I'm not sure if it would be faster, or even accurate, but you could use John Carmack's Magical Square Root, algorithm to solve the square root faster. You could probably easily test this for all possible 32 bit integers, and validate that you actually got correct results, as it's only an appoximation. However, now that I think about it, using doubles is approximating also, so I'm not sure how that would come into play.

Merge a Branch into Trunk

The syntax is wrong, it should instead be

svn merge <what(the range)> <from(your dev branch)> <to(trunk/trunk local copy)>

Differences between strong and weak in Objective-C

strong is the default. An object remains “alive” as long as there is a strong pointer to it.

weak specifies a reference that does not keep the referenced object alive. A weak reference is set to nil when there are no strong references to the object.

Git - Ignore node_modules folder everywhere

Add this

node_modules/

to .gitignore file to ignore all directories called node_modules in current folder and any subfolders

Angular, Http GET with parameter?

Above solutions not helped me, but I resolve same issue by next way

private setHeaders(params) {      
        const accessToken = this.localStorageService.get('token');
        const reqData = {
            headers: {
                Authorization: `Bearer ${accessToken}`
            },
        };
        if(params) {
            let reqParams = {};        
            Object.keys(params).map(k =>{
                reqParams[k] = params[k];
            });
            reqData['params'] = reqParams;
        }
        return reqData;
    }

and send request

this.http.get(this.getUrl(url), this.setHeaders(params))

Its work with NestJS backend, with other I don't know.

How to modify list entries during for loop?

One more for loop variant, looks cleaner to me than one with enumerate():

for idx in range(len(list)):
    list[idx]=... # set a new value
    # some other code which doesn't let you use a list comprehension

symfony2 twig path with parameter url creation

In Twig:

{% for l in locations %}

<tr>
    <td>
        <input type="checkbox" class="filled-in" id="filled-in-box-{{ l.idLocation }}" />
        <label for="filled-in-box-{{ l.idLocation }}"></label>
    </td>
    <td>{{ l.loc }}</td>
    <td>{{ l.mun }}</td>
    <td>{{ l.pro }}</td>
    <td>{{ l.cou }}</td>
    {#<td>
        {% if l.active == 1  %}
            <span class="fa fa-check"></span>
        {% else %}
            <span class="fa fa-close"></span>
        {% endif %}
    </td>#}
    <td><a href="{{ url('admin_edit_location',{'id': l.idLocation}) }}" class="db-list-edit"><span class="fa fa-pencil-square-o"></span></a>
    </td>
</tr>{% endfor %}

The route admin_edit_location:

admin_edit_location:
  path: /edit_location/{id}
  defaults: { _controller: "AppBundle:Admin:editLocation" }
  methods: GET

And the controller

public function editLocationAction($id){
    // use $id 

    $em = $this->getDoctrine()->getManager();
    $location = $em->getRepository('BackendBundle:locations')->findOneBy(array(
    'id'    => $id
    ));
}

Windows batch: sleep

I just wrote my own sleep which called the Win32 Sleep API function.

How to access the GET parameters after "?" in Express?

So, after checking out the express reference, I found that req.query.color would return me the value I'm looking for.

req.params refers to items with a ':' in the URL and req.query refers to items associated with the '?'

Example:

GET /something?color1=red&color2=blue

Then in express, the handler:

app.get('/something', (req, res) => {
    req.query.color1 === 'red'  // true
    req.query.color2 === 'blue' // true
})

Convert array to JSON string in swift

Hint: To convert an NSArray containing JSON compatible objects to an NSData object containing a JSON document, use the appropriate method of NSJSONSerialization. JSONObjectWithData is not it.

Hint 2: You rarely want that data as a string; only for debugging purposes.

How to call a vue.js function on page load

You can call this function in beforeMount section of a Vue component: like following:

 ....
 methods:{
     getUnits: function() {...}
 },
 beforeMount(){
    this.getUnits()
 },
 ......

Working fiddle: https://jsfiddle.net/q83bnLrx/1/

There are different lifecycle hooks Vue provide:

I have listed few are :

  1. beforeCreate: Called synchronously after the instance has just been initialized, before data observation and event/watcher setup.
  2. created: Called synchronously after the instance is created. At this stage, the instance has finished processing the options which means the following have been set up: data observation, computed properties, methods, watch/event callbacks. However, the mounting phase has not been started, and the $el property will not be available yet.
  3. beforeMount: Called right before the mounting begins: the render function is about to be called for the first time.
  4. mounted: Called after the instance has just been mounted where el is replaced by the newly created vm.$el.
  5. beforeUpdate: Called when the data changes, before the virtual DOM is re-rendered and patched.
  6. updated: Called after a data change causes the virtual DOM to be re-rendered and patched.

You can have a look at complete list here.

You can choose which hook is most suitable to you and hook it to call you function like the sample code provided above.

How to use onClick() or onSelect() on option tag in a JSP page?

in this example de select tag is named as: aula_clase_cb

<select class="form-control" id="aula_clase_cb" >
</select>

document.getElementById("aula_clase_cb").onchange = function(e){
    id = document.getElementById('aula_clase_cb').value;
    alert("id: "+id);
};

'this' is undefined in JavaScript class methods

I just wanted to point out that sometimes this error happens because a function has been used as a high order function (passed as an argument) and then the scope of this got lost. In such cases, I would recommend passing such function bound to this. E.g.

this.myFunction.bind(this);

How to change the size of the font of a JLabel to take the maximum size

 JLabel textLabel = new JLabel("<html><span style='font-size:20px'>"+Text+"</span></html>");

How to cut a string after a specific character in unix

This should do the trick:

$ echo "$var" | awk -F':' '{print $NF}'
/home/some/directory/file

maven... Failed to clean project: Failed to delete ..\org.ow2.util.asm-asm-tree-3.1.jar

Maven complains if you do not have admin permissions on the target folder.Check if you have admin right to delete that folder.

enter image description here

What is the maximum number of edges in a directed graph with n nodes?

There can be as many as n(n-1)/2 edges in the graph if not multi-edge is allowed.

And this is achievable if we label the vertices 1,2,...,n and there's an edge from i to j iff i>j.

See here.

Read Numeric Data from a Text File in C++

Repeat >> reads in loop.

#include <iostream>
#include <fstream>
int main(int argc, char * argv[])
{
    std::fstream myfile("D:\\data.txt", std::ios_base::in);

    float a;
    while (myfile >> a)
    {
        printf("%f ", a);
    }

    getchar();

    return 0;
}

Result:

45.779999 67.900002 87.000000 34.889999 346.000000 0.980000

If you know exactly, how many elements there are in a file, you can chain >> operator:

int main(int argc, char * argv[])
{
    std::fstream myfile("D:\\data.txt", std::ios_base::in);

    float a, b, c, d, e, f;

    myfile >> a >> b >> c >> d >> e >> f;

    printf("%f\t%f\t%f\t%f\t%f\t%f\n", a, b, c, d, e, f);

    getchar();

    return 0;
}

Edit: In response to your comments in main question.

You have two options.

  • You can run previous code in a loop (or two loops) and throw away a defined number of values - for example, if you need the value at point (97, 60), you have to skip 5996 (= 60 * 100 + 96) values and use the last one. This will work if you're interested only in specified value.
  • You can load the data into an array - as Jerry Coffin sugested. He already gave you quite nice class, which will solve the problem. Alternatively, you can use simple array to store the data.

Edit: How to skip values in file

To choose the 1234th value, use the following code:

int skipped = 1233;
for (int i = 0; i < skipped; i++)
{
    float tmp;
    myfile >> tmp;
}
myfile >> value;

How do I execute multiple SQL Statements in Access' Query Editor?

Unfortunately, AFAIK you cannot run multiple SQL statements under one named query in Access in the traditional sense.

You can make several queries, then string them together with VBA (DoCmd.OpenQuery if memory serves).

You can also string a bunch of things together with UNION if you wish.

PHP function to generate v4 UUID

My answer is based on comment uniqid user comment but it uses openssl_random_pseudo_bytes function to generate random string instead of reading from /dev/urandom

function guid()
{
    $randomString = openssl_random_pseudo_bytes(16);
    $time_low = bin2hex(substr($randomString, 0, 4));
    $time_mid = bin2hex(substr($randomString, 4, 2));
    $time_hi_and_version = bin2hex(substr($randomString, 6, 2));
    $clock_seq_hi_and_reserved = bin2hex(substr($randomString, 8, 2));
    $node = bin2hex(substr($randomString, 10, 6));

    /**
     * Set the four most significant bits (bits 12 through 15) of the
     * time_hi_and_version field to the 4-bit version number from
     * Section 4.1.3.
     * @see http://tools.ietf.org/html/rfc4122#section-4.1.3
    */
    $time_hi_and_version = hexdec($time_hi_and_version);
    $time_hi_and_version = $time_hi_and_version >> 4;
    $time_hi_and_version = $time_hi_and_version | 0x4000;

    /**
     * Set the two most significant bits (bits 6 and 7) of the
     * clock_seq_hi_and_reserved to zero and one, respectively.
     */
    $clock_seq_hi_and_reserved = hexdec($clock_seq_hi_and_reserved);
    $clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved >> 2;
    $clock_seq_hi_and_reserved = $clock_seq_hi_and_reserved | 0x8000;

    return sprintf('%08s-%04s-%04x-%04x-%012s', $time_low, $time_mid, $time_hi_and_version, $clock_seq_hi_and_reserved, $node);
} // guid

HTTP 401 - what's an appropriate WWW-Authenticate header value?

When the user session times out, I send back an HTTP 204 status code. Note that the HTTP 204 status contains no content. On the client-side I do this:

xhr.send(null);
if (xhr.status == 204) 
    Reload();
else 
    dropdown.innerHTML = xhr.responseText;

Here is the Reload() function:

function Reload() {
    var oForm = document.createElement("form");
    document.body.appendChild(oForm);
    oForm.submit();
    }

How to Define Callbacks in Android?

No need to define a new interface when you can use an existing one: android.os.Handler.Callback. Pass an object of type Callback, and invoke callback's handleMessage(Message msg).

Use of document.getElementById in JavaScript

It is just a selector that helps you select specific tag <p id = 'demo'></p> elements which help you change the behavior, in any event (either mouse or keyboard).

Java ArrayList of Arrays?

  1. Create the ArrayList like ArrayList action.

    In JDK 1.5 or higher use ArrayList <string[]> reference name.

    In JDK 1.4 or lower use ArrayList reference name.

  2. Specify the access specifiers:

    • public, can be accessed anywhere
    • private, accessed within the class
    • protected, accessed within the class and different package subclasses
  3. Then specify the reference it will be assigned in

    action = new ArrayList<String[]>();
    
  4. In JVM new keyword will allocate memory in runtime for the object.

    You should not assigned the value where declared, because you are asking without fixed size.

  5. Finally you can be use the add() method in ArrayList. Use like

    action.add(new string[how much you need])
    

    It will allocate the specific memory area in heap.

Clear contents of cells in VBA using column reference

You can access entire column as a range using the Worksheet.Columns object

Something like:

Worksheets(sheetname).Columns(1).ClearContents 

should clear contents of A column

There is also the Worksheet.Rows object if you need to do something similar for rows


The error you are receiving is likely due to a missing with block.

You can read about with blocks here: Microsoft Help

'0000-00-00 00:00:00' can not be represented as java.sql.Timestamp error

You can remove the "not null" property from your column in mysql table if not necessary. when you remove "not null" property no need for "0000-00-00 00:00:00" conversion and problem is gone.

At least worked for me.

What is Robocopy's "restartable" option?

Restartable mode (/Z) has to do with a partially-copied file. With this option, should the copy be interrupted while any particular file is partially copied, the next execution of robocopy can pick up where it left off rather than re-copying the entire file.

That option could be useful when copying very large files over a potentially unstable connection.

Backup mode (/B) has to do with how robocopy reads files from the source system. It allows the copying of files on which you might otherwise get an access denied error on either the file itself or while trying to copy the file's attributes/permissions. You do need to be running in an Administrator context or otherwise have backup rights to use this flag.

How to open .SQLite files

My favorite:

https://inloop.github.io/sqlite-viewer/

No installation needed. Just drop the file.

Javascript: Easier way to format numbers?

There's the NUMBERFORMATTER jQuery plugin, details below:

https://code.google.com/p/jquery-numberformatter/

From the above link:

This plugin is a NumberFormatter plugin. Number formatting is likely familiar to anyone who's worked with server-side code like Java or PHP and who has worked with internationalization.

EDIT: Replaced the link with a more direct one.

Switching from zsh to bash on OSX, and back again?

You can just use exec to replace your current shell with a new shell:

Switch to bash:

exec bash

Switch to zsh:

exec zsh

This won't affect new terminal windows or anything, but it's convenient.

How to change python version in anaconda spyder

In Preferences, select Python Interpreter

Under Python Interpreter, change from "Default" to "Use the following Python interpreter"

The path there should be the default Python executable. Find your Python 2.7 executable and use that.

What is the difference between H.264 video and MPEG-4 video?

H.264 is a new standard for video compression which has more advanced compression methods than the basic MPEG-4 compression. One of the advantages of H.264 is the high compression rate. It is about 1.5 to 2 times more efficient than MPEG-4 encoding. This high compression rate makes it possible to record more information on the same hard disk.
The image quality is also better and playback is more fluent than with basic MPEG-4 compression. The most interesting feature however is the lower bit-rate required for network transmission.
So the 3 main advantages of H.264 over MPEG-4 compression are:
- Small file size for longer recording time and better network transmission.
- Fluent and better video quality for real time playback
- More efficient mobile surveillance application

H264 is now enshrined in MPEG4 as part 10 also known as AVC

Refer to: http://www.velleman.eu/downloads/3/h264_vs_mpeg4_en.pdf

Hope this helps.

How to reset or change the passphrase for a GitHub SSH key?

In short there's no way to recover the passphrase for a pair of SSH keys. Why? Because it was intended this way in the first place for security reasons. The answers the other people gave you are all correct ways to CHANGE the password of your keys, not to recover them. So if you've forgotten your passphrase, the best you can do is create a new pair of SSH keys. Here's how to generate SSH keys and add it to your GitHub account.

How to fetch the dropdown values from database and display in jsp

  1. Make the database connection and retrieve the query result.
  2. Traverse through the result and display the query results.

The example code below demonstrates this in detail.

<%@page import="java.sql.*, java.io.*,listresult"%> //import the required library

<%

String label = request.getParameter("label"); // retrieving a variable from a previous page

Connection dbc = null; //Make connection to the database
Class.forName("com.mysql.jdbc.Driver");
dbc = DriverManager.getConnection("jdbc:mysql://localhost:3306/works", "root", "root");
if (dbc != null) 
{
    System.out.println("Connection successful");
}

ResultSet rs = listresult.dbresult.func(dbc, label); //This function is in the end. The function is defined in another package- listresult

%>

<form name="demo form" method="post">

    <table>
        <tr>
            <td>
                Label Name:
            </td>

            <td>
                <input type="text" name="label" value="<%=rs.getString("labelname")%>">
            </td>

            <td>
                <select name="label">
                <option value="">SELECT</option>

                <% while (rs.next()) {%>

                    <option value="<%=rs.getString("lname")%>"><%=rs.getString("lname")%>
                    </option>

                <%}%>
                </select>
            </td>
        </tr>
    </table>

</form>

//The function:

public static ResultSet func(Connection dbc, String x)
{
    ResultSet rs = null;
    String sql;
    PreparedStatement pst;
    try
    {
        sql = "select lname from demo where label like '" + x + "'";
        pst = dbc.prepareStatement(sql);
        rs = pst.executeQuery();
    } 
    catch (Exception e) 
    {
        e.printStackTrace();
        String sqlMessage = e.getMessage();
    }
    return rs;
}

I have tried to make this example as detailed as possible. Do ask if you have any queries.

How to make the script wait/sleep in a simple way in unity

With .Net 4.x you can use Task-based Asynchronous Pattern (TAP) to achieve this:

// .NET 4.x async-await
using UnityEngine;
using System.Threading.Tasks;
public class AsyncAwaitExample : MonoBehaviour
{
     private async void Start()
     {
        Debug.Log("Wait.");
        await WaitOneSecondAsync();
        DoMoreStuff(); // Will not execute until WaitOneSecond has completed
     }
    private async Task WaitOneSecondAsync()
    {
        await Task.Delay(TimeSpan.FromSeconds(1));
        Debug.Log("Finished waiting.");
    }
}

this is a feature to use .Net 4.x with Unity please see this link for description about it

and this link for sample project and compare it with coroutine

But becareful as documentation says that This is not fully replacement with coroutine

Unable to install gem - Failed to build gem native extension - cannot load such file -- mkmf (LoadError)

For WSL (Windows Subsystem for Linux) you need install build-essential package:

sudo apt install build-essential

Groovy - Convert object to JSON string

You can use JsonBuilder for that.

Example Code:

import groovy.json.JsonBuilder

class Person {
    String name
    String address
}

def o = new Person( name: 'John Doe', address: 'Texas' )

println new JsonBuilder( o ).toPrettyString()

C++ callback using class member

A complete working example from the code above.... for C++11:

#include <stdlib.h>
#include <stdio.h>
#include <functional>

#if __cplusplus <= 199711L
  #error This file needs at least a C++11 compliant compiler, try using:
  #error    $ g++ -std=c++11 ..
#endif

using namespace std;

class EventHandler {
    public:
        void addHandler(std::function<void(int)> callback) {
            printf("\nHandler added...");
            // Let's pretend an event just occured
            callback(1);
        }
};


class MyClass
{
    public:
        MyClass(int);
        // Note: No longer marked `static`, and only takes the actual argument
        void Callback(int x);

    private:
        EventHandler *pHandler;
        int private_x;
};

MyClass::MyClass(int value) {
    using namespace std::placeholders; // for `_1`

    pHandler = new EventHandler();
    private_x = value;
    pHandler->addHandler(std::bind(&MyClass::Callback, this, _1));
}

void MyClass::Callback(int x) {
    // No longer needs an explicit `instance` argument,
    // as `this` is set up properly
    printf("\nResult:%d\n\n", (x+private_x));
}

// Main method
int main(int argc, char const *argv[]) {

    printf("\nCompiler:%ld\n", __cplusplus);
    new MyClass(5);
    return 0;
}


// where $1 is your .cpp file name... this is the command used:
// g++ -std=c++11 -Wall -o $1 $1.cpp
// chmod 700 $1
// ./$1

Output should be:

Compiler:201103

Handler added...
Result:6

Correct way to load a Nib for a UIView subclass

Follow the following steps

  1. Create a class named MyView .h/.m of type UIView.
  2. Create a xib of same name MyView.xib.
  3. Now change the File Owner class to UIViewController from NSObject in xib. See the image below enter image description here
  4. Connect the File Owner View to your View. See the image below enter image description here

  5. Change the class of your View to MyView. Same as 3.

  6. Place controls create IBOutlets.

Here is the code to load the View:

UIViewController *controller=[[UIViewController alloc] initWithNibName:@"MyView" bundle:nil];
MyView* view=(MyView*)controller.view;
[self.view addSubview:myview];

Hope it helps.

Clarification:

UIViewController is used to load your xib and the View which the UIViewController has is actually MyView which you have assigned in the MyView xib..

Demo I have made a demo grab here

How to properly express JPQL "join fetch" with "where" clause as JPA 2 CriteriaQuery?

I will show visually the problem, using the great example from James answer and adding the alternative solution.

When you do the follow query, without the FETCH:

Select e from Employee e 
join e.phones p 
where p.areaCode = '613'

You will have the follow results from Employee as you expected:

EmployeeId EmployeeName PhoneId PhoneAreaCode
1 James 5 613
1 James 6 416

But when you add the FETCH word on JOIN, this is what happens:

EmployeeId EmployeeName PhoneId PhoneAreaCode
1 James 5 613

The generated SQL is the same for the two queries, but the Hibernate removes on memory the 416 register when you use WHERE on the FETCH join.

So, to bring all phones and apply the WHERE correctly, you need to have two JOINs: one for the WHERE and another for the FETCH. Like:

Select e from Employee e 
join e.phones p 
join fetch e.phones      //no alias, to not commit the mistake
where p.areaCode = '613'

Using a custom (ttf) font in CSS

This is not a system font. this font is not supported in other systems. you can use font-face, convert font from this Site or from this

enter image description here

How to delete all rows from all tables in a SQL Server database?

Note that TRUNCATE won't work if you have any referential integrity set.

In that case, this will work:

EXEC sp_MSForEachTable 'DISABLE TRIGGER ALL ON ?'
GO
EXEC sp_MSForEachTable 'ALTER TABLE ? NOCHECK CONSTRAINT ALL'
GO
EXEC sp_MSForEachTable 'DELETE FROM ?'
GO
EXEC sp_MSForEachTable 'ALTER TABLE ? CHECK CONSTRAINT ALL'
GO
EXEC sp_MSForEachTable 'ENABLE TRIGGER ALL ON ?'
GO

Edit: To be clear, the ? in the statements is a ?. It's replaced with the table name by the sp_MSForEachTable procedure.

SQL MAX of multiple columns?

You could create a function where you pass the dates and then add the function to the select statement like below. select Number, dbo.fxMost_Recent_Date(Date1,Date2,Date3), Cost

create FUNCTION  fxMost_Recent_Date 

( @Date1 smalldatetime, @Date2 smalldatetime, @Date3 smalldatetime ) RETURNS smalldatetime AS BEGIN DECLARE @Result smalldatetime

declare @MostRecent smalldatetime

set @MostRecent='1/1/1900'

if @Date1>@MostRecent begin set @MostRecent=@Date1 end
if @Date2>@MostRecent begin set @MostRecent=@Date2 end
if @Date3>@MostRecent begin set @MostRecent=@Date3 end
RETURN @MostRecent

END

How to send email from localhost WAMP Server to send email Gmail Hotmail or so forth?

If you have a wamp setup that won't send emails, there is only a couple of things to do. 1. find out what the smtp server name is for your isp. The gmail thing is most likely unnecessary complication 2. create a phpsetup.php file in your 'www' folder and edit like this:

<?php
   phpinfo();
?>

this will give you a handle on what wamp is using. 3. search for the php.ini file. there may be serveral. The one you want is the one that effects the output of the file above. 4. find the smtp address in the most likely php.ini. 5. Type in your browser localhost/phpsetup.php and scroll down to smtp setting. it should say 'localhost' 6. edit the php.ini file smtp setting to the name of your ISPs smtp server. check if it changes for you phpsetup.php. if it works your done, if not you are working the wrong file.

this issue should be on the Wordpress site but they are way too up-them-selves or trying to get clients.;)

Body of Http.DELETE request in Angular2

Below is the relevant code example for Angular 2/4/5 projects:

let headers = new Headers({
  'Content-Type': 'application/json'
});

let options = new RequestOptions({
  headers: headers,
  body: {
    id: 123
  }
});

return this.http.delete("http//delete.example.com/delete", options)
  .map((response: Response) => {
    return response.json()
  })
  .catch(err => {
    return err;
  });

Notice that body is passed through RequestOptions

'True' and 'False' in Python

is compares identity. A string will never be identical to a not-string.

== is equality. But a string will never be equal to either True or False.

You want neither.

path = '/bla/bla/bla'

if path:
    print "True"
else:
    print "False"

In Flask, What is request.args and how is it used?

@martinho as a newbie using Flask and Python myself, I think the previous answers here took for granted that you had a good understanding of the fundamentals. In case you or other viewers don't know the fundamentals, I'll give more context to understand the answer...

... the request.args is bringing a "dictionary" object for you. The "dictionary" object is similar to other collection-type of objects in Python, in that it can store many elements in one single object. Therefore the answer to your question

And how many parameters request.args.get() takes.

It will take only one object, a "dictionary" type of object (as stated in the previous answers). This "dictionary" object, however, can have as many elements as needed... (dictionaries have paired elements called Key, Value).

Other collection-type of objects besides "dictionaries", would be "tuple", and "list"... you can run a google search on those and "data structures" in order to learn other Python fundamentals. This answer is based Python; I don't have an idea if the same applies to other programming languages.

Setting size for icon in CSS

None of those work for me.

.fa-volume-down {
    color: white;
    width: 50% !important;
    height: 50% !important;
    margin-top: 8%;
    margin-left: 7.5%;
    font-size: 1em;
    background-size: 120%;
}

How to reference a local XML Schema file correctly?

If you work in MS Visual Studio just do following

  1. Put WSDL file and XSD file at the same folder.
  2. Correct WSDL file like this YourSchemeFile.xsd

  3. Use visual Studio using this great example How to generate service reference with only physical wsdl file

Notice that you have to put the path to your WSDL file manually. There is no way to use Open File dialog box out there.

How do I vertically align something inside a span tag?

This is the simplest way to do it if you need multiple lines. Wrap you span'd text in another span and specify its height with line-height. The trick to multiple lines is resetting the inner span's line-height.

<span class="textvalignmiddle"><span>YOUR TEXT HERE</span></span>
.textvalignmiddle {
    line-height: /*set height*/;
}

.textvalignmiddle > span {
    display: inline-block;
    vertical-align: middle;
    line-height: 1em; /*set line height back to normal*/
}

DEMO

Of course the outer span could be a div or whathaveyou

Insert all values of a table into another table in SQL

 Dim ofd As New OpenFileDialog
                ofd.Filter = "*.mdb|*.MDB"
                ofd.FilterIndex = (2)
                ofd.FileName = "bd1.mdb"
                ofd.Title = "SELECCIONE LA BASE DE DATOS ORIGEN (bd1.mdb)"
                ofd.ShowDialog()
                Dim conexion1 = "Driver={Microsoft Access Driver (*.mdb)};DBQ=" + ofd.FileName
                Dim conn As New OdbcConnection()
                conn.ConnectionString = conexion1
                conn.Open()



            'EN ESTE CODIGO SOLO SE AGREGAN LOS DATOS'
            Dim ofd2 As New OpenFileDialog
            ofd2.Filter = "*.mdb|*.MDB"
            ofd2.FilterIndex = (2)
            ofd2.FileName = "bd1.mdb"
            ofd2.Title = "SELECCIONE LA BASE DE DATOS DESTINO (bd1.mdb)"
            ofd2.ShowDialog()
            Dim conexion2 = "Driver={Microsoft Access Driver (*.mdb)};DBQ=" + ofd2.FileName
            Dim conn2 As New OdbcConnection()
            conn2.ConnectionString = conexion2
            Dim cmd2 As New OdbcCommand
            Dim CADENA2 As String

            CADENA2 = "INSERT INTO EXISTENCIA IN '" + ofd2.FileName + "' SELECT * FROM EXISTENCIA IN '" + ofd.FileName + "'"


            cmd2.CommandText = CADENA2
            cmd2.Connection = conn2
            conn2.Open()
            Dim dA2 As New OdbcDataAdapter
            dA2.SelectCommand = cmd2
            Dim midataset2 As New DataSet
            dA2.Fill(midataset2, "EXISTENCIA")

UIButton Image + Text IOS

I think you are looking for this solution for your problem:

UIButton *_button = [UIButton buttonWithType:UIButtonTypeCustom];
[_button setFrame:CGRectMake(0.f, 0.f, 128.f, 128.f)]; // SET the values for your wishes
[_button setCenter:CGPointMake(128.f, 128.f)]; // SET the values for your wishes
[_button setClipsToBounds:false];
[_button setBackgroundImage:[UIImage imageNamed:@"jquery-mobile-icon.png"] forState:UIControlStateNormal]; // SET the image name for your wishes
[_button setTitle:@"Button" forState:UIControlStateNormal];
[_button.titleLabel setFont:[UIFont systemFontOfSize:24.f]];
[_button setTitleColor:[UIColor blackColor] forState:UIControlStateNormal]; // SET the colour for your wishes
[_button setTitleColor:[UIColor redColor] forState:UIControlStateHighlighted]; // SET the colour for your wishes
[_button setTitleEdgeInsets:UIEdgeInsetsMake(0.f, 0.f, -110.f, 0.f)]; // SET the values for your wishes
[_button addTarget:self action:@selector(buttonTouchedUpInside:) forControlEvents:UIControlEventTouchUpInside]; // you can ADD the action to the button as well like

...the rest of the customisation of the button is your duty now, and don't forget to add the button to your view.

UPDATE #1 and UPDATE #2

or, if you don't need a dynamic button you could add your button to your view in the Interface Builder and you could set the same values at there as well. it is pretty same, but here is this version as well in one simple picture.

you can also see the final result in the Interface Builder as it is on the screenshot.

enter image description here

Spring MVC Controller redirect using URL parameters instead of in response

Hey you can just do one simple thing instead of using model to send parameter use HttpServletRequest object and do this

HttpServletRequest request;
request.setAttribute("param", "value")

now your parametrs will not be shown in your url header hope it works :)

is there any alternative for ng-disabled in angular2?

For angular 4+ versions you can try

<input [readonly]="true" type="date" name="date" />

Add a column with a default value to an existing table in SQL Server

Right click on the table name and click on Design, click under the last column name and enter Column Name, Data Type, Allow Nulls.

Then in bottom of page set a default value or binding : something like '1' for string or 1 for int.

Conditional HTML Attributes using Razor MVC3

I guess a little more convenient and structured way is to use Html helper. In your view it can be look like:

@{
 var htmlAttr = new Dictionary<string, object>();
 htmlAttr.Add("id", strElementId);
 if (!CSSClass.IsEmpty())
 {
   htmlAttr.Add("class", strCSSClass);
 }
}

@* ... *@

@Html.TextBox("somename", "", htmlAttr)

If this way will be useful for you i recommend to define dictionary htmlAttr in your model so your view doesn't need any @{ } logic blocks (be more clear).

jQuery set radio button

Combining previous answers:

$('input[name="cols"]').filter("[value='Site']").click();

Add carriage return to a string

string s2 = s1.Replace(",", ",\n") + ",....";

Using CookieContainer with WebClient class

 WebClient wb = new WebClient();
 wb.Headers.Add(HttpRequestHeader.Cookie, "somecookie");

From Comments

How do you format the name and value of the cookie in place of "somecookie" ?

wb.Headers.Add(HttpRequestHeader.Cookie, "cookiename=cookievalue"); 

For multiple cookies:

wb.Headers.Add(HttpRequestHeader.Cookie, 
              "cookiename1=cookievalue1;" +
              "cookiename2=cookievalue2");

PHP append one array to another (not array_push or +)

<?php
// Example 1 [Merging associative arrays. When two or more arrays have same key
// then the last array key value overrides the others one]

$array1 = array("a" => "JAVA", "b" => "ASP");
$array2 = array("c" => "C", "b" => "PHP");
echo " <br> Example 1 Output: <br>";
print_r(array_merge($array1,$array2));

// Example 2 [When you want to merge arrays having integer keys and
//want to reset integer keys to start from 0 then use array_merge() function]

$array3 =array(5 => "CSS",6 => "CSS3");
$array4 =array(8 => "JAVASCRIPT",9 => "HTML");
echo " <br> Example 2 Output: <br>";
print_r(array_merge($array3,$array4));

// Example 3 [When you want to merge arrays having integer keys and
// want to retain integer keys as it is then use PLUS (+) operator to merge arrays]

$array5 =array(5 => "CSS",6 => "CSS3");
$array6 =array(8 => "JAVASCRIPT",9 => "HTML");
echo " <br> Example 3 Output: <br>";
print_r($array5+$array6);

// Example 4 [When single array pass to array_merge having integer keys
// then the array return by array_merge have integer keys starting from 0]

$array7 =array(3 => "CSS",4 => "CSS3");
echo " <br> Example 4 Output: <br>";
print_r(array_merge($array7));
?>

Output:

Example 1 Output:
Array
(
[a] => JAVA
[b] => PHP
[c] => C
)

Example 2 Output:
Array
(
[0] => CSS
[1] => CSS3
[2] => JAVASCRIPT
[3] => HTML
)

Example 3 Output:
Array
(
[5] => CSS
[6] => CSS3
[8] => JAVASCRIPT
[9] => HTML
)

Example 4 Output:
Array
(
[0] => CSS
[1] => CSS3
)

Reference Source Code

Form content type for a json HTTP POST?

multipart/form-data

is used when you want to upload files to the server. Please check this article for details.

Using the value in a cell as a cell reference in a formula?

Use INDIRECT()

=SUM(INDIRECT(<start cell here> & ":" & <end cell here>))

When do you use map vs flatMap in RxJava?

In your case you need map, since there is only 1 input and 1 output.

map - supplied function simply accepts an item and returns an item which will be emitted further (only once) down.

flatMap - supplied function accepts an item then returns an "Observable", meaning each item of the new "Observable" will be emitted separately further down.

May be code will clear things up for you:

Observable.just("item1").map( str -> {
    System.out.println("inside the map " + str);
    return str;
}).subscribe(System.out::println);

Observable.just("item2").flatMap( str -> {
    System.out.println("inside the flatMap " + str);
    return Observable.just(str + "+", str + "++" , str + "+++");
}).subscribe(System.out::println);

Output:

inside the map item1
item1
inside the flatMap item2
item2+
item2++
item2+++

Decimal number regular expression, where digit after decimal is optional

In Perl, use Regexp::Common which will allow you to assemble a finely-tuned regular expression for your particular number format. If you are not using Perl, the generated regular expression can still typically be used by other languages.

Printing the result of generating the example regular expressions in Regexp::Common::Number:

$ perl -MRegexp::Common=number -E 'say $RE{num}{int}'
(?:(?:[-+]?)(?:[0123456789]+))

$ perl -MRegexp::Common=number -E 'say $RE{num}{real}'
(?:(?i)(?:[-+]?)(?:(?=[.]?[0123456789])(?:[0123456789]*)(?:(?:[.])(?:[0123456789]{0,}))?)(?:(?:[E])(?:(?:[-+]?)(?:[0123456789]+))|))

$ perl -MRegexp::Common=number -E 'say $RE{num}{real}{-base=>16}'
(?:(?i)(?:[-+]?)(?:(?=[.]?[0123456789ABCDEF])(?:[0123456789ABCDEF]*)(?:(?:[.])(?:[0123456789ABCDEF]{0,}))?)(?:(?:[G])(?:(?:[-+]?)(?:[0123456789ABCDEF]+))|))

Xcode Product -> Archive disabled

Change the active scheme Device from Simulator to Generic iOS Device

Git keeps prompting me for a password

In Windows for Git 1.7.9+, run the following command on the command prompt to open the configuration file in a text editor:

    git config --global --edit

Then in the file, add the following block if not present or edit it accordingly:

    [credential "https://giturl.com"]
        username = <user id>
         helper = wincred

Save and close the file. You will need to provide the credentials only once after the above change.

Enable 'xp_cmdshell' SQL Server

For me, the only way on SQL 2008 R2 was this :

EXEC sp_configure 'Show Advanced Options', 1    
RECONFIGURE **WITH OVERRIDE**    
EXEC sp_configure 'xp_cmdshell', 1    
RECONFIGURE **WITH OVERRIDE**

android get real path by Uri.getPath()

This helped me to get uri from Gallery and convert to a file for Multipart upload

File file = FileUtils.getFile(this, fileUri);

https://github.com/iPaulPro/aFileChooser/blob/master/aFileChooser/src/com/ipaulpro/afilechooser/utils/FileUtils.java

YouTube URL in Video Tag

MediaElement YouTube API example

Wraps the YouTube API in an HTML5 Media API wrapper, so that it can be programmed against as if it was true HTML5 <video>.

<script src="jquery.js"></script>
<script src="mediaelement-and-player.min.js"></script>
<link rel="stylesheet" href="mediaelementplayer.css" />

<video width="640" height="360" id="player1" preload="none">
    <source type="video/youtube" src="http://www.youtube.com/watch?v=nOEw9iiopwI" />
</video>

<script>
    var player = new MediaElementPlayer('#player1');
</script>

Read large files in Java

Unless you accidentally read in the whole input file instead of reading it line by line, then your primary limitation will be disk speed. You may want to try starting with a file containing 100 lines and write it to 100 different files one line in each and make the triggering mechanism work on the number of lines written to the current file. That program will be easily scalable to your situation.

What is the best way to compare floats for almost-equality in Python?

Use Python's decimal module, which provides the Decimal class.

From the comments:

It is worth noting that if you're doing math-heavy work and you don't absolutely need the precision from decimal, this can really bog things down. Floats are way, way faster to deal with, but imprecise. Decimals are extremely precise but slow.

How can I disable the Maven Javadoc plugin from the command line?

You can use the maven.javadoc.skip property to skip execution of the plugin, going by the Mojo's javadoc. You can specify the value as a Maven property:

<properties>
    <maven.javadoc.skip>true</maven.javadoc.skip>
</properties>

or as a command-line argument: -Dmaven.javadoc.skip=true, to skip generation of the Javadocs.

Iterate through Nested JavaScript Objects

- , ,

function forEachNested(O, f, cur){
    O = [ O ]; // ensure that f is called with the top-level object
    while (O.length) // keep on processing the top item on the stack
        if(
           !f( cur = O.pop() ) && // do not spider down if `f` returns true
           cur instanceof Object && // ensure cur is an object, but not null 
           [Object, Array].includes(cur.constructor) //limit search to [] and {}
        ) O.push.apply(O, Object.values(cur)); //search all values deeper inside
}

To use the above function, pass the array as the first argument and the callback function as the second argument. The callback function will receive 1 argument when called: the current item being iterated.

_x000D_
_x000D_
(function(){"use strict";

var cars = {"label":"Autos","subs":[{"label":"SUVs","subs":[]},{"label":"Trucks","subs":[{"label":"2 Wheel Drive","subs":[]},{"label":"4 Wheel Drive","subs":[{"label":"Ford","subs":[]},{"label":"Chevrolet","subs":[]}]}]},{"label":"Sedan","subs":[]}]};

var lookForCar = prompt("enter the name of the car you are looking for (e.g. 'Ford')") || 'Ford';
lookForCar = lookForCar.replace(/[^ \w]/g, ""); // incaseif the user put quotes or something around their input
lookForCar = lookForCar.toLowerCase();

var foundObject = null;
forEachNested(cars, function(currentValue){
    if(currentValue.constructor === Object &&
      currentValue.label.toLowerCase() === lookForCar) {
        foundObject = currentValue;
    }
});
if (foundObject !== null) {
    console.log("Found the object: " + JSON.stringify(foundObject, null, "\t"));
} else {
    console.log('Nothing found with a label of "' + lookForCar + '" :(');
}

function forEachNested(O, f, cur){
    O = [ O ]; // ensure that f is called with the top-level object
    while (O.length) // keep on processing the top item on the stack
        if(
           !f( cur = O.pop() ) && // do not spider down if `f` returns true
           cur instanceof Object && // ensure cur is an object, but not null 
           [Object, Array].includes(cur.constructor) //limit search to [] and {}
        ) O.push.apply(O, Object.values(cur)); //search all values deeper inside
}

})();
_x000D_
_x000D_
_x000D_

A "cheat" alternative might be to use JSON.stringify to iterate. HOWEVER, JSON.stringify will call the toString method of each object it passes over, which may produce undesirable results if you have your own special uses for the toString.

function forEachNested(O, f, v){
    typeof O === "function" ? O(v) : JSON.stringify(O,forEachNested.bind(0,f));
    return v; // so that JSON.stringify keeps on recursing
}

_x000D_
_x000D_
(function(){"use strict";

var cars = {"label":"Autos","subs":[{"label":"SUVs","subs":[]},{"label":"Trucks","subs":[{"label":"2 Wheel Drive","subs":[]},{"label":"4 Wheel Drive","subs":[{"label":"Ford","subs":[]},{"label":"Chevrolet","subs":[]}]}]},{"label":"Sedan","subs":[]}]};

var lookForCar = prompt("enter the name of the car you are looking for (e.g. 'Ford')") || 'Ford';
lookForCar = lookForCar.replace(/[^ \w]/g, ""); // incaseif the user put quotes or something around their input
lookForCar = lookForCar.toLowerCase();

var foundObject = null;
forEachNested(cars, function(currentValue){
    if(currentValue.constructor === Object &&
      currentValue.label.toLowerCase() === lookForCar) {
        foundObject = currentValue;
    }
});
if (foundObject !== null)
    console.log("Found the object: " + JSON.stringify(foundObject, null, "\t"));
else
    console.log('Nothing found with a label of "' + lookForCar + '" :(');

function forEachNested(O, f, v){
    typeof O === "function" ? O(v) : JSON.stringify(O,forEachNested.bind(0,f));
    return v; // so that JSON.stringify keeps on recursing
}
})();
_x000D_
_x000D_
_x000D_

However, while the above method might be useful for demonstration purposes, Object.values is not supported by Internet Explorer and there are many terribly illperformant places in the code:

  1. the code changes the value of input parameters (arguments) [lines 2 & 5],
  2. the code calls Array.prototype.push and Array.prototype.pop on every single item [lines 5 & 8],
  3. the code only does a pointer-comparison for the constructor which does not work on out-of-window objects [line 7],
  4. the code duplicates the array returned from Object.values [line 8],
  5. the code does not localize window.Object or window.Object.values [line 9],
  6. and the code needlessly calls Object.values on arrays [line 8].

Below is a much much faster version that should be far faster than any other solution. The solution below fixes all of the performance problems listed above. However, it iterates in a much different way: it iterates all the arrays first, then iterates all the objects. It continues to iterate its present type until complete exhaustion including iteration subvalues inside the current list of the current flavor being iterated. Then, the function iterates all of the other type. By iterating until exhaustion before switching over, the iteration loop gets hotter than otherwise and iterates even faster. This method also comes with an added advantage: the callback which is called on each value gets passed a second parameter. This second parameter is the array returned from Object.values called on the parent hash Object, or the parent Array itself.

var getValues = Object.values; // localize
var type_toString = Object.prototype.toString;
function forEachNested(objectIn, functionOnEach){
    "use strict";
    functionOnEach( objectIn );
    
    // for iterating arbitrary objects:
    var allLists = [  ];
    if (type_toString.call( objectIn ) === '[object Object]')
        allLists.push( getValues(objectIn) );
    var allListsSize = allLists.length|0; // the length of allLists
    var indexLists = 0;
    
    // for iterating arrays:
    var allArray = [  ];
    if (type_toString.call( objectIn ) === '[object Array]')
        allArray.push( objectIn );
    var allArraySize = allArray.length|0; // the length of allArray
    var indexArray = 0;
    
    do {
        // keep cycling back and forth between objects and arrays
        
        for ( ; indexArray < allArraySize; indexArray=indexArray+1|0) {
            var currentArray = allArray[indexArray];
            var currentLength = currentArray.length;
            for (var curI=0; curI < currentLength; curI=curI+1|0) {
                var arrayItemInner = currentArray[curI];
                if (arrayItemInner === undefined &&
                    !currentArray.hasOwnProperty(arrayItemInner)) {
                    continue; // the value at this position doesn't exist!
                }
                functionOnEach(arrayItemInner, currentArray);
                if (typeof arrayItemInner === 'object') {
                    var typeTag = type_toString.call( arrayItemInner );
                    if (typeTag === '[object Object]') {
                        // Array.prototype.push returns the new length
                        allListsSize=allLists.push( getValues(arrayItemInner) );
                    } else if (typeTag === '[object Array]') {
                        allArraySize=allArray.push( arrayItemInner );
                    }
                }
            }
            allArray[indexArray] = null; // free up memory to reduce overhead
        }
         
        for ( ; indexLists < allListsSize; indexLists=indexLists+1|0) {
            var currentList = allLists[indexLists];
            var currentLength = currentList.length;
            for (var curI=0; curI < currentLength; curI=curI+1|0) {
                var listItemInner = currentList[curI];
                functionOnEach(listItemInner, currentList);
                if (typeof listItemInner === 'object') {
                    var typeTag = type_toString.call( listItemInner );
                    if (typeTag === '[object Object]') {
                        // Array.prototype.push returns the new length
                        allListsSize=allLists.push( getValues(listItemInner) );
                    } else if (typeTag === '[object Array]') {
                        allArraySize=allArray.push( listItemInner );
                    }
                }
            }
            allLists[indexLists] = null; // free up memory to reduce overhead
        }
    } while (indexLists < allListsSize || indexArray < allArraySize);
}

_x000D_
_x000D_
(function(){"use strict";

var cars = {"label":"Autos","subs":[{"label":"SUVs","subs":[]},{"label":"Trucks","subs":[{"label":"2 Wheel Drive","subs":[]},{"label":"4 Wheel Drive","subs":[{"label":"Ford","subs":[]},{"label":"Chevrolet","subs":[]}]}]},{"label":"Sedan","subs":[]}]};

var lookForCar = prompt("enter the name of the car you are looking for (e.g. 'Ford')") || 'Ford';
lookForCar = lookForCar.replace(/[^ \w]/g, ""); // incaseif the user put quotes or something around their input
lookForCar = lookForCar.toLowerCase();





var getValues = Object.values; // localize
var type_toString = Object.prototype.toString;
function forEachNested(objectIn, functionOnEach){
    functionOnEach( objectIn );
    
    // for iterating arbitrary objects:
    var allLists = [  ];
    if (type_toString.call( objectIn ) === '[object Object]')
        allLists.push( getValues(objectIn) );
    var allListsSize = allLists.length|0; // the length of allLists
    var indexLists = 0;
    
    // for iterating arrays:
    var allArray = [  ];
    if (type_toString.call( objectIn ) === '[object Array]')
        allArray.push( objectIn );
    var allArraySize = allArray.length|0; // the length of allArray
    var indexArray = 0;
    
    do {
        // keep cycling back and forth between objects and arrays
        
        for ( ; indexArray < allArraySize; indexArray=indexArray+1|0) {
            var currentArray = allArray[indexArray];
            var currentLength = currentArray.length;
            for (var curI=0; curI < currentLength; curI=curI+1|0) {
                var arrayItemInner = currentArray[curI];
                if (arrayItemInner === undefined &&
                    !currentArray.hasOwnProperty(arrayItemInner)) {
                    continue; // the value at this position doesn't exist!
                }
                functionOnEach(arrayItemInner, currentArray);
                if (typeof arrayItemInner === 'object') {
                    var typeTag = type_toString.call( arrayItemInner );
                    if (typeTag === '[object Object]') {
                        // Array.prototype.push returns the new length
                        allListsSize=allLists.push( getValues(arrayItemInner) );
                    } else if (typeTag === '[object Array]') {
                        allArraySize=allArray.push( arrayItemInner );
                    }
                }
            }
            allArray[indexArray] = null; // free up memory to reduce overhead
        }
         
        for ( ; indexLists < allListsSize; indexLists=indexLists+1|0) {
            var currentList = allLists[indexLists];
            var currentLength = currentList.length;
            for (var curI=0; curI < currentLength; curI=curI+1|0) {
                var listItemInner = currentList[curI];
                functionOnEach(listItemInner, currentList);
                if (typeof listItemInner === 'object') {
                    var typeTag = type_toString.call( listItemInner );
                    if (typeTag === '[object Object]') {
                        // Array.prototype.push returns the new length
                        allListsSize=allLists.push( getValues(listItemInner) );
                    } else if (typeTag === '[object Array]') {
                        allArraySize=allArray.push( listItemInner );
                    }
                }
            }
            allLists[indexLists] = null; // free up memory to reduce overhead
        }
    } while (indexLists < allListsSize || indexArray < allArraySize);
}




var foundObject = null;
forEachNested(cars, function(currentValue){
    if(currentValue.constructor === Object &&
      currentValue.label.toLowerCase() === lookForCar) {
        foundObject = currentValue;
    }
});
if (foundObject !== null) {
    console.log("Found the object: " + JSON.stringify(foundObject, null, "\t"));
} else {
    console.log('Nothing found with a label of "' + lookForCar + '" :(');
}

})();
_x000D_
_x000D_
_x000D_

If you have a problem with circular references (e.g. having object A's values being object A itself in such as that object A contains itself), or you just need the keys then the following slower solution is available.

function forEachNested(O, f){
    O = Object.entries(O);
    var cur;
    function applyToEach(x){return cur[1][x[0]] === x[1]} 
    while (O.length){
        cur = O.pop();
        f(cur[0], cur[1]);
        if (typeof cur[1] === 'object' && cur[1].constructor === Object && 
          !O.some(applyToEach))
            O.push.apply(O, Object.entries(cur[1]));
    }
}

Because these methods do not use any recursion of any sort, these functions are well suited for areas where you might have thousands of levels of depth. The stack limit varies greatly from browser to browser, so recursion to an unknown depth is not very wise in Javascript.

How to create JSON object Node.js

What I believe you're looking for is a way to work with arrays as object values:

var o = {} // empty Object
var key = 'Orientation Sensor';
o[key] = []; // empty Array, which you can push() values into


var data = {
    sampleTime: '1450632410296',
    data: '76.36731:3.4651554:0.5665419'
};
var data2 = {
    sampleTime: '1450632410296',
    data: '78.15431:0.5247617:-0.20050584'
};
o[key].push(data);
o[key].push(data2);

This is standard JavaScript and not something NodeJS specific. In order to serialize it to a JSON string you can use the native JSON.stringify:

JSON.stringify(o);
//> '{"Orientation Sensor":[{"sampleTime":"1450632410296","data":"76.36731:3.4651554:0.5665419"},{"sampleTime":"1450632410296","data":"78.15431:0.5247617:-0.20050584"}]}'

In a unix shell, how to get yesterday's date into a variable?

$var=$TZ;
TZ=$TZ+24;
date;
TZ=$var;

Will get you yesterday in AIX and set back the TZ variable back to original

JUnit 5: How to assert an exception is thrown?

Now Junit5 provides a way to assert the exceptions

You can test both general exceptions and customized exceptions

A general exception scenario:

ExpectGeneralException.java

public void validateParameters(Integer param ) {
    if (param == null) {
        throw new NullPointerException("Null parameters are not allowed");
    }
}

ExpectGeneralExceptionTest.java

@Test
@DisplayName("Test assert NullPointerException")
void testGeneralException(TestInfo testInfo) {
    final ExpectGeneralException generalEx = new ExpectGeneralException();

     NullPointerException exception = assertThrows(NullPointerException.class, () -> {
            generalEx.validateParameters(null);
        });
    assertEquals("Null parameters are not allowed", exception.getMessage());
}

You can find a sample to test CustomException here : assert exception code sample

ExpectCustomException.java

public String constructErrorMessage(String... args) throws InvalidParameterCountException {
    if(args.length!=3) {
        throw new InvalidParameterCountException("Invalid parametercount: expected=3, passed="+args.length);
    }else {
        String message = "";
        for(String arg: args) {
            message += arg;
        }
        return message;
    }
}

ExpectCustomExceptionTest.java

@Test
@DisplayName("Test assert exception")
void testCustomException(TestInfo testInfo) {
    final ExpectCustomException expectEx = new ExpectCustomException();

     InvalidParameterCountException exception = assertThrows(InvalidParameterCountException.class, () -> {
            expectEx.constructErrorMessage("sample ","error");
        });
    assertEquals("Invalid parametercount: expected=3, passed=2", exception.getMessage());
}

JSON datetime between Python and JavaScript

On python side:

import time, json
from datetime import datetime as dt
your_date = dt.now()
data = json.dumps(time.mktime(your_date.timetuple())*1000)
return data # data send to javascript

On javascript side:

var your_date = new Date(data)

where data is result from python

Render partial from different folder (not shared)

For readers using ASP.NET Core 2.1 or later and wanting to use Partial Tag Helper syntax, try this:

<partial name="~/Views/Folder/_PartialName.cshtml" />

The tilde (~) is optional.

The information at https://docs.microsoft.com/en-us/aspnet/core/mvc/views/partial?view=aspnetcore-3.1#partial-tag-helper is helpful too.

Android Studio doesn't see device

I had usb to usbc hub on my macbook pro which was blocking the device somehow, it worked when I connected it directly with the apple usbc to usb dongle.

Maven 3 and JUnit 4 compilation problem: package org.junit does not exist

My case was a simple oversight.

I put the JUnit dependency declaration inside <dependencies> under the <dependencyManagement/> node instead of <project/> in the POM file. Correct way is:

<project>
<!-- Other elements -->
    <dependencies>
    <!-- Other dependencies-->
        <dependency>
            <groupId>junit</groupId>
            <artifactId>junit</artifactId>
            <version>4.11</version>
        </dependency>
    </dependencies>
<project>

How do I seed a random class to avoid getting duplicate random values

this workes for me:

private int GetaRandom()
    {
        Thread.Sleep(1);
        return new Random(DateTime.Now.Millisecond).Next();
    }

How can I drop a "not null" constraint in Oracle when I don't know the name of the constraint?

I was facing the same problem trying to get around a custom check constraint that I needed to updated to allow different values. Problem is that ALL_CONSTRAINTS does't have a way to tell which column the constraint(s) are applied to. The way I managed to do it is by querying ALL_CONS_COLUMNS instead, then dropping each of the constraints by their name and recreate it.

select constraint_name from all_cons_columns where table_name = [TABLE_NAME] and column_name = [COLUMN_NAME];

call javascript function on hyperlink click

I would generally recommend using element.attachEvent (IE) or element.addEventListener (other browsers) over setting the onclick event directly as the latter will replace any existing event handlers for that element.

attachEvent / addEventListening allow multiple event handlers to be created.

Restoring Nuget References?

The following script can be run in the Package Manger Console window, and will remove all packages from each project in your solution before reinstalling them.

foreach ($project in Get-Project -All) { 
    $packages = Get-Package -ProjectName $project.ProjectName
    foreach ($package in $packages) {
        Uninstall-Package $package.Id -Force -ProjectName $project.ProjectName
    }
    foreach ($package in $packages) {
        Install-Package $package.Id -ProjectName $project.ProjectName -Version $package.Version
    }
}

This will run every package's install script again, which should restore the missing assembly references. Unfortunately, all the other stuff that install scripts can do -- like creating files and modifying configs -- will also happen again. You'll probably want to start with a clean working copy, and use your SCM tool to pick and choose what changes in your project to keep and which to ignore.

Remove last character from string. Swift language

let str = "abc"
let substr = str.substringToIndex(str.endIndex.predecessor())  // "ab"

Automatic login script for a website on windows machine?

I used @qwertyjones's answer to automate logging into Oracle Agile with a public password.

I saved the login page as index.html, edited all the href= and action= fields to have the full URL to the Agile server.

The key <form> line needed to change from

<form autocomplete="off" name="MainForm" method="POST"
 action="j_security_check" 
 onsubmit="return false;" target="_top">

to

<form autocomplete="off" name="MainForm" method="POST"
 action="http://my.company.com:7001/Agile/default/j_security_check"   
 onsubmit="return false;" target="_top">

I also added this snippet to the end of the <body>

<script>
function checkCookiesEnabled(){ return true; }
document.MainForm.j_username.value = "joeuser";
document.MainForm.j_password.value = "abcdef";
submitLoginForm();
</script> 

I had to disable the cookie check by redefining the function that did the check, because I was hosting this from XAMPP and I didn't want to deal with it. The submitLoginForm() call was inspired by inspecting the keyPressEvent() function.

How to write a confusion matrix in Python?

Here is a simple implementation that handles an unequal number of classes in the predicted and actual labels (see examples 3 and 4). I hope this helps!

For folks just learning this, here's a quick review. The labels for the columns indicate the predicted class, and the labels for the rows indicate the correct class. In example 1, we have [3 1] on the top row. Again, rows indicate truth, so this means that the correct label is "0" and there are 4 examples with ground truth label of "0". Columns indicate predictions, so we have 3/4 of the samples correctly labeled as "0", but 1/4 was incorrectly labeled as a "1".

def confusion_matrix(actual, predicted):
    classes       = np.unique(np.concatenate((actual,predicted)))
    confusion_mtx = np.empty((len(classes),len(classes)),dtype=np.int)
    for i,a in enumerate(classes):
        for j,p in enumerate(classes):
            confusion_mtx[i,j] = np.where((actual==a)*(predicted==p))[0].shape[0]
    return confusion_mtx

Example 1:

actual    = np.array([1,1,1,1,0,0,0,0])
predicted = np.array([1,1,1,1,0,0,0,1])
confusion_matrix(actual,predicted)

   0  1
0  3  1
1  0  4

Example 2:

actual    = np.array(["a","a","a","a","b","b","b","b"])
predicted = np.array(["a","a","a","a","b","b","b","a"])
confusion_matrix(actual,predicted)

   0  1
0  4  0
1  1  3

Example 3:

actual    = np.array(["a","a","a","a","b","b","b","b"])
predicted = np.array(["a","a","a","a","b","b","b","z"]) # <-- notice the 3rd class, "z"
confusion_matrix(actual,predicted)

   0  1  2
0  4  0  0
1  0  3  1
2  0  0  0

Example 4:

actual    = np.array(["a","a","a","x","x","b","b","b"]) # <-- notice the 4th class, "x"
predicted = np.array(["a","a","a","a","b","b","b","z"])
confusion_matrix(actual,predicted)

   0  1  2  3
0  3  0  0  0
1  0  2  0  1
2  1  1  0  0
3  0  0  0  0

Execute JavaScript code stored as a string

New Function and apply() together works also

var a=new Function('alert(1);')
a.apply(null)