Programs & Examples On #Mysql error 1452

MySql error #1452 - Cannot add or update a child row: a foreign key constraint fails

MySQL - Cannot add or update a child row: a foreign key constraint fails

I had faced same issue while creating foreign constraints on table. the simple way of coming out of this issue are first take backup of your parent and child table then truncate child table and again try to make a relation. hope this will solve the problem.

Mysql error 1452 - Cannot add or update a child row: a foreign key constraint fails

I had the same issue with my MySQL database but finally, I got a solution which worked for me.
Since in my table everything was fine from the mysql point of view(both tables should use InnoDB engine and the datatype of each column should be of the same type which takes part in foreign key constraint).
The only thing that I did was to disable the foreign key check and later on enabled it after performing the foreign key operation.
Steps that I took:

SET foreign_key_checks = 0;
alter table tblUsedDestination add constraint f_operatorId foreign key(iOperatorId) references tblOperators (iOperatorId); Query
OK, 8 rows affected (0.23 sec) Records: 8  Duplicates: 0  Warnings: 0
SET foreign_key_checks = 1;

ERROR 1452: Cannot add or update a child row: a foreign key constraint fails

This error generally occurs because we have some values in the referencing field of the child table, which do not exist in the referenced/candidate field of the parent table.

Sometimes, we may get this error when we are applying Foreign Key constraints to existing table(s), having data in them already. Some of the other answers are suggesting to delete the data completely from child table, and then apply the constraint. However, this is not an option when we already have working/production data in the child table. In most scenarios, we will need to update the data in the child table (instead of deleting them).

Now, we can utilize Left Join to find all those rows in the child table, which does not have matching values in the parent table. Following query would be helpful to fetch those non-matching rows:

SELECT child_table.* 
FROM child_table 
LEFT JOIN parent_table 
  ON parent_table.referenced_column = child_table.referencing_column 
WHERE parent_table.referenced_column IS NULL

Now, you can generally do one (or more) of the following steps to fix the data.

  1. Based on your "business logic", you will need to update/match these unmatching value(s), with the existing values in the parent table. You may sometimes need to set them null as well.
  2. Delete these rows having unmatching values.
  3. Add new rows in your parent table, corresponding to the unmatching values in the child table.

Once the data is fixed, we can apply the Foreign key constraint using ALTER TABLE syntax.

nodeJs callbacks simple example

const fs = require('fs');

fs.stat('input.txt', function (err, stats) {
    if(err){
        console.log(err);
    } else {
        console.log(stats);
        console.log('Completed Reading File');
    }
});

'fs' is a node module which helps you to read file. Callback function will make sure that your file named 'input.txt' is completely read before it gets executed. fs.stat() function is to get file information like file size, date created and date modified.

What's the "average" requests per second for a production web application?

When I go to the control panel of my webhost, open up phpMyAdmin, and click on "Show MySQL runtime information", I get:

This MySQL server has been running for 53 days, 15 hours, 28 minutes and 53 seconds. It started up on Oct 24, 2008 at 04:03 AM.

Query statistics: Since its startup, 3,444,378,344 queries have been sent to the server.

Total 3,444 M
per hour 2.68 M
per minute 44.59 k
per second 743.13

That's an average of 743 mySQL queries every single second for the past 53 days!

I don't know about you, but to me that's fast! Very fast!!

How to bind Events on Ajax loaded Content?

For those who are still looking for a solution , the best way of doing it is to bind the event on the document itself and not to bind with the event "on ready" For e.g :

$(function ajaxform_reload() {
$(document).on("submit", ".ajax_forms", function (e) {
    e.preventDefault();
    var url = $(this).attr('action');
    $.ajax({
        type: 'post',
        url: url,
        data: $(this).serialize(),
        success: function (data) {
            // DO WHAT YOU WANT WITH THE RESPONSE
        }
    });
});

});

Convert unsigned int to signed int C

I know it's an old question, but it's a good one, so how about this?

unsigned short int x = 65529U;
short int y = *(short int*)&x;

printf("%d\n", y);

Is it possible to dynamically compile and execute C# code fragments?

The best solution in C#/all static .NET languages is to use the CodeDOM for such things. (As a note, its other main purpose is for dynamically constructing bits of code, or even whole classes.)

Here's a nice short example take from LukeH's blog, which uses some LINQ too just for fun.

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CSharp;
using System.CodeDom.Compiler;

class Program
{
    static void Main(string[] args)
    {
        var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });
        var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, "foo.exe", true);
        parameters.GenerateExecutable = true;
        CompilerResults results = csc.CompileAssemblyFromSource(parameters,
        @"using System.Linq;
            class Program {
              public static void Main(string[] args) {
                var q = from i in Enumerable.Range(1,100)
                          where i % 2 == 0
                          select i;
              }
            }");
        results.Errors.Cast<CompilerError>().ToList().ForEach(error => Console.WriteLine(error.ErrorText));
    }
}

The class of primary importance here is the CSharpCodeProvider which utilises the compiler to compile code on the fly. If you want to then run the code, you just need to use a bit of reflection to dynamically load the assembly and execute it.

Here is another example in C# that (although slightly less concise) additionally shows you precisely how to run the runtime-compiled code using the System.Reflection namespace.

How to modify STYLE attribute of element with known ID using JQuery

Use the CSS function from jQuery to set styles to your items :

$('#buttonId').css({ "background-color": 'brown'});

How do I execute a bash script in Terminal?

Firstly you have to make it executable using: chmod +x name_of_your_file_script.

After you made it executable, you can run it using ./same_name_of_your_file_script

Bootstrap: align input with button

I tried all the above codes and none of them fixed my issues. Here is what worked for me. I used input-group-addon.

<div class = "input-group">
  <span class = "input-group-addon">Go</span>
  <input type = "text" class = "form-control" placeholder="you are the man!">
</div>

how to place last div into right top corner of parent div? (css)

Displaying left middle and right of there parents. If you have more then 3 elements then use nth-child() for them.

enter image description here

HTML sample:

<body>
    <ul class="nav-tabs">
        <li><a  id="btn-tab-business" class="btn-tab nav-tab-selected"  onclick="openTab('business','btn-tab-business')"><i class="fas fa-th"></i>Business</a></li>
        <li><a  id="btn-tab-expertise" class="btn-tab" onclick="openTab('expertise', 'btn-tab-expertise')"><i class="fas fa-th"></i>Expertise</a></li>
        <li><a  id="btn-tab-quality" class="btn-tab" onclick="openTab('quality', 'btn-tab-quality')"><i class="fas fa-th"></i>Quality</a></li>
    </ul>
</body>

CSS sample:

.nav-tabs{
  position: relative;
  padding-bottom: 50px;
}
.nav-tabs li {
  display: inline-block;  
  position: absolute;
  list-style: none;
}
.nav-tabs li:first-child{
  top: 0px;
  left: 0px;
}
.nav-tabs li:last-child{
  top: 0px;
  right: 0px;
}
.nav-tabs li:nth-child(2){
  top: 0px;
  left: 50%;
  transform: translate(-50%, 0%);
}

Check if program is running with bash shell script?

You can achieve almost everything in PROCESS_NUM with this one-liner:

[ `pgrep $1` ] && return 1 || return 0

if you're looking for a partial match, i.e. program is named foobar and you want your $1 to be just foo you can add the -f switch to pgrep:

[[ `pgrep -f $1` ]] && return 1 || return 0

Putting it all together your script could be reworked like this:

#!/bin/bash

check_process() {
  echo "$ts: checking $1"
  [ "$1" = "" ]  && return 0
  [ `pgrep -n $1` ] && return 1 || return 0
}

while [ 1 ]; do 
  # timestamp
  ts=`date +%T`

  echo "$ts: begin checking..."
  check_process "dropbox"
  [ $? -eq 0 ] && echo "$ts: not running, restarting..." && `dropbox start -i > /dev/null`
  sleep 5
done

Running it would look like this:

# SHELL #1
22:07:26: begin checking...
22:07:26: checking dropbox
22:07:31: begin checking...
22:07:31: checking dropbox

# SHELL #2
$ dropbox stop
Dropbox daemon stopped.

# SHELL #1
22:07:36: begin checking...
22:07:36: checking dropbox
22:07:36: not running, restarting...
22:07:42: begin checking...
22:07:42: checking dropbox

Hope this helps!

How to extract public key using OpenSSL?

For those interested in the details - you can see what's inside the public key file (generated as explained above), by doing this:-

openssl rsa -noout -text -inform PEM -in key.pub -pubin

or for the private key file, this:-

openssl rsa -noout -text -in key.private

which outputs as text on the console the actual components of the key (modulus, exponents, primes, ...)

What resources are shared between threads?

In an x86 framework, one can divide as many segments (up to 2^16-1). The ASM directives SEGMENT/ENDS allows this, and the operators SEG and OFFSET allows initialization of segment registers. CS:IP are usually initialized by the loader, but for DS, ES, SS the application is responsible with initialization. Many environments allow the so-called "simplified segment definitions" like .code, .data, .bss, .stack etc. and, depending also on the "memory model" (small, large, compact etc.) the loader initializes segment registers accordingly. Usually .data, .bss, .stack and other usual segments (I haven't done this since 20 years so I don't remember all) are grouped in one single group - that is why usually DS, ES and SS points to teh same area, but this is only to simplify things.

In general, all segment registers can have different values upon run-time. So, the interview question was right: which one of the CODE, DATA, and STACK are shared between threads. Heap management is something else - it is simply a sequence of calls to the OS. But what if you don't have an OS at all, like in an embedded system - can you still have new/delete in your code?

My advice to the young people - read some good assembly programming book. It seems that university curriculae are quite poor in this respect.

What should I do when 'svn cleanup' fails?

There are some very good suggestions in the previous answer, but if you are having an issue with TortoiseSVN on Windows (a good product, but ...) always fallback to the command line and do a simple "svn cleanup" first.

In many circumstances the Windows client will not run the cleanup command, but cleanup works fine using thing the SVN command line utility.

Multiple ping script in Python

Python actually has a really sweet method that will 'return an iterator over the usable hosts in the network'. (setting strict to false iterates over all IPs)

For example:

import subprocess
import ipaddress

subnet = ipaddress.ip_network('192.168.1.0/24', strict=False)
for i in subnet.hosts():
    i = str(i)
    subprocess.call(["ping", "-c1", "-n", "-i0.1", "-W1", i])

The wait interval (-i0.1) may be important for automations, even a one second timeout (-t1) can take forever over a .0/24

EDIT: So, in order to track ICMP (ping) requests, we can do something like this:

#!/usr/bin/env python

import subprocess
import ipaddress

alive = []
subnet = ipaddress.ip_network('192.168.1.0/23', strict=False)
for i in subnet.hosts():
    i = str(i)
    retval = subprocess.call(["ping", "-c1", "-n", "-i0.1", "-W1", i])
    if retval == 0:
        alive.append(i)
for ip in alive:
    print(ip + " is alive") 

Which will return something like:

192.168.0.1 is alive
192.168.0.2 is alive
192.168.1.1 is alive
192.168.1.246 is alive

i.e. all of the IPs responding to ICMP ranging over an entire /23-- Pretty cool!

How to run ~/.bash_profile in mac terminal

As @kojiro said, you don't want to "run" this file. Source it as he says. It should get "sourced" at startup. Sourcing just means running every line in the file, including the one you want to get run. If you want to make sure a folder is in a certain path environment variable (as it seems you want from one of your comments on another solution), execute

$ echo $PATH

At the command line. If you want to check that your ~/.bash_profile is being sourced, either at startup as it should be, or when you source it manually, enter the following line into your ~/.bash_profile file:

$ echo "Hello I'm running stuff in the ~/.bash_profile!"

Firebase FCM force onTokenRefresh() to be called

Guys it has very simple solution

https://developers.google.com/instance-id/guides/android-implementation#generate_a_token

Note: If your app used tokens that were deleted by deleteInstanceID, your app will need to generate replacement tokens.

In stead of deleting instance Id, delete only token:

String authorizedEntity = PROJECT_ID;
String scope = "GCM";
InstanceID.getInstance(context).deleteToken(authorizedEntity,scope);

Subquery returned more than 1 value.This is not permitted when the subquery follows =,!=,<,<=,>,>= or when the subquery is used as an expression

You can use IN operator as below

select * from dbo.books where isbn IN
(select isbn from dbo.lending where lended_date between @fdate and @tdate)

Django: Model Form "object has no attribute 'cleaned_data'"

I would write the code like this:

def search_book(request):
    form = SearchForm(request.POST or None)
    if request.method == "POST" and form.is_valid():
        stitle = form.cleaned_data['title']
        sauthor = form.cleaned_data['author']
        scategory = form.cleaned_data['category']
        return HttpResponseRedirect('/thanks/')
    return render_to_response("books/create.html", {
        "form": form,
    }, context_instance=RequestContext(request))

Pretty much like the documentation.

javac is not recognized as an internal or external command, operable program or batch file

TL;DR

For experienced readers:

  1. Find the Java path; it looks like this: C:\Program Files\Java\jdkxxxx\bin\
  2. Start-menu search for "environment variable" to open the options dialog.
  3. Examine PATH. Remove old Java paths.
  4. Add the new Java path to PATH.
  5. Edit JAVA_HOME.
  6. Close and re-open console/IDE.

Welcome!

You have encountered one of the most notorious technical issues facing Java beginners: the 'xyz' is not recognized as an internal or external command... error message.

In a nutshell, you have not installed Java correctly. Finalizing the installation of Java on Windows requires some manual steps. You must always perform these steps after installing Java, including after upgrading the JDK.

Environment variables and PATH

(If you already understand this, feel free to skip the next three sections.)

When you run javac HelloWorld.java, cmd must determine where javac.exe is located. This is accomplished with PATH, an environment variable.

An environment variable is a special key-value pair (e.g. windir=C:\WINDOWS). Most came with the operating system, and some are required for proper system functioning. A list of them is passed to every program (including cmd) when it starts. On Windows, there are two types: user environment variables and system environment variables.

You can see your environment variables like this:

C:\>set
ALLUSERSPROFILE=C:\ProgramData
APPDATA=C:\Users\craig\AppData\Roaming
CommonProgramFiles=C:\Program Files\Common Files
CommonProgramFiles(x86)=C:\Program Files (x86)\Common Files
CommonProgramW6432=C:\Program Files\Common Files
...

The most important variable is PATH. It is a list of paths, separated by ;. When a command is entered into cmd, each directory in the list will be scanned for a matching executable.

On my computer, PATH is:

C:\>echo %PATH%
C:\WINDOWS\system32;C:\WINDOWS;C:\WINDOWS\System32\Wbem;C:\WINDOWS\System32\WindowsPower
Shell\v1.0\;C:\ProgramData\Microsoft\Windows\Start Menu\Programs;C:\Users\craig\AppData\
Roaming\Microsoft\Windows\Start Menu\Programs;C:\msys64\usr\bin;C:\msys64\mingw64\bin;C:\
msys64\mingw32\bin;C:\Program Files\nodejs\;C:\Program Files (x86)\Yarn\bin\;C:\Users\
craig\AppData\Local\Yarn\bin;C:\Program Files\Java\jdk-10.0.2\bin;C:\ProgramFiles\Git\cmd;
C:\Program Files\Oracle\VirtualBox;C:\Program Files\7-Zip\;C:\Program Files\PuTTY\;C:\
Program Files\launch4j;C:\Program Files (x86)\NSIS\Bin;C:\Program Files (x86)\Common Files
\Adobe\AGL;C:\Program Files\Intel\Intel(R) Management Engine Components\DAL;C:\Program
Files\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files\Intel\iCLS Client\;
C:\Program Files (x86)\Intel\Intel(R) Management Engine Components\DAL;C:\Program Files
(x86)\Intel\Intel(R) Management Engine Components\IPT;C:\Program Files (x86)\Intel\iCLS
Client\;C:\Users\craig\AppData\Local\Microsoft\WindowsApps

When you run javac HelloWorld.java, cmd, upon realizing that javac is not an internal command, searches the system PATH followed by the user PATH. It mechanically enters every directory in the list, and checks if javac.com, javac.exe, javac.bat, etc. is present. When it finds javac, it runs it. When it does not, it prints 'javac' is not recognized as an internal or external command, operable program or batch file.

You must add the Java executables directory to PATH.

JDK vs. JRE

(If you already understand this, feel free to skip this section.)

When downloading Java, you are offered a choice between:

  • The Java Runtime Environment (JRE), which includes the necessary tools to run Java programs, but not to compile new ones – it contains java but not javac.
  • The Java Development Kit (JDK), which contains both java and javac, along with a host of other development tools. The JDK is a superset of the JRE.

You must make sure you have installed the JDK. If you have only installed the JRE, you cannot execute javac because you do not have an installation of the Java compiler on your hard drive. Check your Windows programs list, and make sure the Java package's name includes the words "Development Kit" in it.

Don't use set

(If you weren't planning to anyway, feel free to skip this section.)

Several other answers recommend executing some variation of:

C:\>:: DON'T DO THIS
C:\>set PATH=C:\Program Files\Java\jdk1.7.0_09\bin

Do not do that. There are several major problems with that command:

  1. This command erases everything else from PATH and replaces it with the Java path. After executing this command, you might find various other commands not working.
  2. Your Java path is probably not C:\Program Files\Java\jdk1.7.0_09\bin – you almost definitely have a newer version of the JDK, which would have a different path.
  3. The new PATH only applies to the current cmd session. You will have to reenter the set command every time you open Command Prompt.

Points #1 and #2 can be solved with this slightly better version:

C:\>:: DON'T DO THIS EITHER
C:\>set PATH=C:\Program Files\Java\<enter the correct Java folder here>\bin;%PATH%

But it is just a bad idea in general.

Find the Java path

The right way begins with finding where you have installed Java. This depends on how you have installed Java.

Exe installer

You have installed Java by running a setup program. Oracle's installer places versions of Java under C:\Program Files\Java\ (or C:\Program Files (x86)\Java\). With File Explorer or Command Prompt, navigate to that directory.

Each subfolder represents a version of Java. If there is only one, you have found it. Otherwise, choose the one that looks like the newer version. Make sure the folder name begins with jdk (as opposed to jre). Enter the directory.

Then enter the bin directory of that.

You are now in the correct directory. Copy the path. If in File Explorer, click the address bar. If in Command Prompt, copy the prompt.

The resulting Java path should be in the form of (without quotes):

C:\Program Files\Java\jdkxxxx\bin\

Zip file

You have downloaded a .zip containing the JDK. Extract it to some random place where it won't get in your way; C:\Java\ is an acceptable choice.

Then locate the bin folder somewhere within it.

You are now in the correct directory. Copy its path. This is the Java path.

Remember to never move the folder, as that would invalidate the path.

Open the settings dialog

That is the dialog to edit PATH. There are numerous ways to get to that dialog, depending on your Windows version, UI settings, and how messed up your system configuration is.

Try some of these:

  • Start Menu/taskbar search box » search for "environment variable"
  • Win + R » control sysdm.cpl,,3
  • Win + R » SystemPropertiesAdvanced.exe » Environment Variables
  • File Explorer » type into address bar Control Panel\System and Security\System » Advanced System Settings (far left, in sidebar) » Environment Variables
  • Desktop » right-click This PC » Properties » Advanced System Settings » Environment Variables
  • Start Menu » right-click Computer » Properties » Advanced System Settings » Environment Variables
  • Control Panel (icon mode) » System » Advanced System Settings » Environment Variables
  • Control Panel (category mode) » System and Security » System » Advanced System Settings » Environment Variables
  • Desktop » right-click My Computer » Advanced » Environment Variables
  • Control Panel » System » Advanced » Environment Variables

Any of these should take you to the right settings dialog.

If you are on Windows 10, Microsoft has blessed you with a fancy new UI to edit PATH. Otherwise, you will see PATH in its full semicolon-encrusted glory, squeezed into a single-line textbox. Do your best to make the necessary edits without breaking your system.

Clean PATH

Look at PATH. You almost definitely have two PATH variables (because of user vs. system environment variables). You need to look at both of them.

Check for other Java paths and remove them. Their existence can cause all sorts of conflicts. (For instance, if you have JRE 8 and JDK 11 in PATH, in that order, then javac will invoke the Java 11 compiler, which will create version 55 .class files, but java will invoke the Java 8 JVM, which only supports up to version 52, and you will experience unsupported version errors and not be able to compile and run any programs.) Sidestep these problems by making sure you only have one Java path in PATH. And while you're at it, you may as well uninstall old Java versions, too. And remember that you don't need to have both a JDK and a JRE.

If you have C:\ProgramData\Oracle\Java\javapath, remove that as well. Oracle intended to solve the problem of Java paths breaking after upgrades by creating a symbolic link that would always point to the latest Java installation. Unfortunately, it often ends up pointing to the wrong location or simply not working. It is better to remove this entry and manually manage the Java path.

Now is also a good opportunity to perform general housekeeping on PATH. If you have paths relating to software no longer installed on your PC, you can remove them. You can also shuffle the order of paths around (if you care about things like that).

Add to PATH

Now take the Java path you found three steps ago, and place it in the system PATH.

It shouldn't matter where in the list your new path goes; placing it at the end is a fine choice.

If you are using the pre-Windows 10 UI, make sure you have placed the semicolons correctly. There should be exactly one separating every path in the list.

There really isn't much else to say here. Simply add the path to PATH and click OK.

Set JAVA_HOME

While you're at it, you may as well set JAVA_HOME as well. This is another environment variable that should also contain the Java path. Many Java and non-Java programs, including the popular Java build systems Maven and Gradle, will throw errors if it is not correctly set.

If JAVA_HOME does not exist, create it as a new system environment variable. Set it to the path of the Java directory without the bin/ directory, i.e. C:\Program Files\Java\jdkxxxx\.

Remember to edit JAVA_HOME after upgrading Java, too.

Close and re-open Command Prompt

Though you have modified PATH, all running programs, including cmd, only see the old PATH. This is because the list of all environment variables is only copied into a program when it begins executing; thereafter, it only consults the cached copy.

There is no good way to refresh cmd's environment variables, so simply close Command Prompt and open it again. If you are using an IDE, close and re-open it too.

See also

Getting distance between two points based on latitude/longitude

Update: 04/2018: Note that Vincenty distance is deprecated since GeoPy version 1.13 - you should use geopy.distance.distance() instead!


The answers above are based on the Haversine formula, which assumes the earth is a sphere, which results in errors of up to about 0.5% (according to help(geopy.distance)). Vincenty distance uses more accurate ellipsoidal models such as WGS-84, and is implemented in geopy. For example,

import geopy.distance

coords_1 = (52.2296756, 21.0122287)
coords_2 = (52.406374, 16.9251681)

print geopy.distance.vincenty(coords_1, coords_2).km

will print the distance of 279.352901604 kilometers using the default ellipsoid WGS-84. (You can also choose .miles or one of several other distance units).

Package structure for a Java project?

I usually like to have the following:

  • bin (Binaries)
  • doc (Documents)
  • inf (Information)
  • lib (Libraries)
  • res (Resources)
  • src (Source)
  • tst (Test)

These may be considered unconventional, but I find it to be a very nice way to organize things.

Preventing form resubmission

The PRG pattern can only prevent the resubmission caused by page refreshing. This is not a 100% safe measure.

Usually, I will take actions below to prevent resubmission:

  1. Client Side - Use javascript to prevent duplicate clicks on a button which will trigger form submission. You can just disable the button after the first click.

  2. Server Side - I will calculate a hash on the submitted parameters and save that hash in session or database, so when the duplicated submission was received we can detect the duplication then proper response to the client. However, you can manage to generate a hash at the client side.

In most of the occasions, these measures can help to prevent resubmission.

Prevent double submission of forms in jQuery

In my case the form's onsubmit had some validation code, so I increment Nathan Long answer including an onsubmit checkpoint

$.fn.preventDoubleSubmission = function() {
      $(this).on('submit',function(e){
        var $form = $(this);
        //if the form has something in onsubmit
        var submitCode = $form.attr('onsubmit');
        if(submitCode != undefined && submitCode != ''){
            var submitFunction = new Function (submitCode);
            if(!submitFunction()){
                event.preventDefault();
                return false;
            }                   
        }

        if ($form.data('submitted') === true) {
            /*Previously submitted - don't submit again */
            e.preventDefault();
        } else {
          /*Mark it so that the next submit can be ignored*/
          $form.data('submitted', true);
        }
      });

      /*Keep chainability*/
      return this;
    };

How does EL empty operator work in JSF?

Using BalusC's suggestion of implementing Collection i can now hide my primefaces p:dataTable using not empty operator on my dataModel that extends javax.faces.model.ListDataModel

Code sample:

import java.io.Serializable;
import java.util.Collection;
import java.util.List;
import javax.faces.model.ListDataModel;
import org.primefaces.model.SelectableDataModel;

public class EntityDataModel extends ListDataModel<Entity> implements
        Collection<Entity>, SelectableDataModel<Entity>, Serializable {

    public EntityDataModel(List<Entity> data) { super(data); }

    @Override
    public Entity getRowData(String rowKey) {
        // In a real app, a more efficient way like a query by rowKey should be
        // implemented to deal with huge data
        List<Entity> entitys = (List<Entity>) getWrappedData();
        for (Entity entity : entitys) {
            if (Integer.toString(entity.getId()).equals(rowKey)) return entity;
        }
        return null;
    }

    @Override
    public Object getRowKey(Entity entity) {
        return entity.getId();
    }

    @Override
    public boolean isEmpty() {
        List<Entity> entity = (List<Entity>) getWrappedData();
        return (entity == null) || entity.isEmpty();
    }
    // ... other not implemented methods of Collection...
}

Global javascript variable inside document.ready

Use window.intro = "value"; inside the ready function. "value" could be void 0 if you want it to be undefined

Specifying a custom DateTime format when serializing with Json.Net

With below converter

public class CustomDateTimeConverter : IsoDateTimeConverter
    {
        public CustomDateTimeConverter()
        {
            DateTimeFormat = "yyyy-MM-dd";
        }

        public CustomDateTimeConverter(string format)
        {
            DateTimeFormat = format;
        }
    }

Can use it with a default custom format

class ReturnObjectA 
{
    [JsonConverter(typeof(DateFormatConverter))]
    public DateTime ReturnDate { get;set;}
}

Or any specified format for a property

class ReturnObjectB 
{
    [JsonConverter(typeof(DateFormatConverter), "dd MMM yy")]
    public DateTime ReturnDate { get;set;}
}

How to Kill A Session or Session ID (ASP.NET/C#)

Session.Abandon(); did not work for me either.

The way I had to write it to get it to work was like this. Might work for you too.

HttpContext.Current.Session.Abandon();

Getting Cannot read property 'offsetWidth' of undefined with bootstrap carousel script

I got same error. Because i used v4 alpha class names like carousel-control-next When i changed with v3, problem solved.

cannot load such file -- bundler/setup (LoadError)

You most likely have more than one Ruby installed.

If you are using RVM, you probably need to run:

rvm use system

to set the version of ruby to use.

See http://rvm.io/rubies/default

ruby -v

will tell you the version you are currently using.

AngularJS ngClass conditional

I am going to show you two methods by which you can dynamically apply ng-class

Step-1

By using ternary operator

<div ng-class="condition?'class1':'class2'"></div>

Output

If your condition is true then class1 will be applied to your element else class2 will be applied.

Disadvantage

When you will try to change the conditional value at run time the class somehow will not changed. So I will suggest you to go for step2 if you have requirement like dynamic class change.

Step-2

<div ng-class="{value1:'class1', value2:'class2'}[condition]"></div>

Output

if your condition matches with value1 then class1 will be applied to your element, if matches with value2 then class2 will be applied and so on. And dynamic class change will work fine with it.

Hope this will help you.

What is the equivalent to getLastInsertId() in Cakephp?

$this->Model->field('id', null, 'id DESC')

How to create a GUID/UUID using iOS

In Swift:

var uuid: String = NSUUID().UUIDString
println("uuid: \(uuid)")

Why does PEP-8 specify a maximum line length of 79 characters?

I believe those who study typography would tell you that 66 characters per a line is supposed to be the most readable width for length. Even so, if you need to debug a machine remotely over an ssh session, most terminals default to 80 characters, 79 just fits, trying to work with anything wider becomes a real pain in such a case. You would also be suprised by the number of developers using vim + screen as a day to day environment.

Delaying function in swift

 NSTimer.scheduledTimerWithTimeInterval(NSTimeInterval(3), target: self, selector: "functionHere", userInfo: nil, repeats: false)

This would call the function functionHere() with a 3 seconds delay

Change Primary Key

You will need to drop and re-create the primary key like this:

alter table my_table drop constraint my_pk;
alter table my_table add constraint my_pk primary key (city_id, buildtime, time);

However, if there are other tables with foreign keys that reference this primary key, then you will need to drop those first, do the above, and then re-create the foreign keys with the new column list.

An alternative syntax to drop the existing primary key (e.g. if you don't know the constraint name):

alter table my_table drop primary key;

How do I evenly add space between a label and the input field regardless of length of text?

You can use a table

<table class="formcontrols" >   
    <tr>
        <td>
            <label for="firstName">FirstName:</label>
        </td>
        <td  style="padding-left:10px;">
            <input id="firstName" name="firstName" value="John">
        </td>
    </tr>
    <tr>
        <td>
            <label for="Test">Last name:</label>
        </td>
        <td  style="padding-left:10px;">
            <input id="lastName" name="lastName" value="Travolta">
        </td>
    </tr>
</table>

The result would be: ImageResult

How does String.Index work in Swift

func change(string: inout String) {

    var character: Character = .normal

    enum Character {
        case space
        case newLine
        case normal
    }

    for i in stride(from: string.count - 1, through: 0, by: -1) {
        // first get index
        let index: String.Index?
        if i != 0 {
            index = string.index(after: string.index(string.startIndex, offsetBy: i - 1))
        } else {
            index = string.startIndex
        }

        if string[index!] == "\n" {

            if character != .normal {

                if character == .newLine {
                    string.remove(at: index!)
                } else if character == .space {
                    let number = string.index(after: string.index(string.startIndex, offsetBy: i))
                    if string[number] == " " {
                        string.remove(at: number)
                    }
                    character = .newLine
                }

            } else {
                character = .newLine
            }

        } else if string[index!] == " " {

            if character != .normal {

                string.remove(at: index!)

            } else {
                character = .space
            }

        } else {

            character = .normal

        }

    }

    // startIndex
    guard string.count > 0 else { return }
    if string[string.startIndex] == "\n" || string[string.startIndex] == " " {
        string.remove(at: string.startIndex)
    }

    // endIndex - here is a little more complicated!
    guard string.count > 0 else { return }
    let index = string.index(before: string.endIndex)
    if string[index] == "\n" || string[index] == " " {
        string.remove(at: index)
    }

}

Scanner method to get a char

You can use the Console API (which made its appearance in Java 6) as follows:

Console cons = System.console();
if(cons != null) {
  char c = (char) cons.reader().read();  // Checking for EOF omitted
  ...
}

If you just need a single line you don't even need to go through the reader object:

String s = cons.readLine();

How to avoid annoying error "declared and not used"

I ran into this issue when I wanted to temporarily disable the sending of an email while working on another part of the code.

Commenting the use of the service triggered a lot of cascade errors, so instead of commenting I used a condition

if false {
    // Technically, svc still be used so no yelling
    _, err = svc.SendRawEmail(input) 
    Check(err)
}

Generate pdf from HTML in div using Javascript

any one try this

    (function () {  
        var  
         form = $('.form'),  
         cache_width = form.width(),  
         a4 = [595.28, 841.89]; // for a4 size paper width and height  

        $('#create_pdf').on('click', function () {  
            $('body').scrollTop(0);  
            createPDF();  
        });  
        //create pdf  
        function createPDF() {  
            getCanvas().then(function (canvas) {  
                var  
                 img = canvas.toDataURL("image/png"),  
                 doc = new jsPDF({  
                     unit: 'px',  
                     format: 'a4'  
                 });  
                doc.addImage(img, 'JPEG', 20, 20);  
                doc.save('Bhavdip-html-to-pdf.pdf');  
                form.width(cache_width);  
            });  
        }  

        // create canvas object  
        function getCanvas() {  
            form.width((a4[0] * 1.33333) - 80).css('max-width', 'none');  
            return html2canvas(form, {  
                imageTimeout: 2000,  
                removeContainer: true  
            });  
        }  

    }());  

Add onClick event to document.createElement("th")

var newTH = document.createElement('th');
newTH.onclick = function() {
      //Your code here
}

Doctrine 2 ArrayCollection filter method

The Boris Guéry answer's at this post, may help you: Doctrine 2, query inside entities

$idsToFilter = array(1,2,3,4);

$member->getComments()->filter(
    function($entry) use ($idsToFilter) {
       return in_array($entry->getId(), $idsToFilter);
    }
); 

How do you reinstall an app's dependencies using npm?

npm updated the CLI command for install and added the --force flag.

npm install --force

The --force (or -f) argument will force npm to fetch remote resources even if a local copy exists on disk.

See npm install

Python, TypeError: unhashable type: 'list'

The problem is that you can't use a list as the key in a dict, since dict keys need to be immutable. Use a tuple instead.

This is a list:

[x, y]

This is a tuple:

(x, y)

Note that in most cases, the ( and ) are optional, since , is what actually defines a tuple (as long as it's not surrounded by [] or {}, or used as a function argument).

You might find the section on tuples in the Python tutorial useful:

Though tuples may seem similar to lists, they are often used in different situations and for different purposes. Tuples are immutable, and usually contain an heterogeneous sequence of elements that are accessed via unpacking (see later in this section) or indexing (or even by attribute in the case of namedtuples). Lists are mutable, and their elements are usually homogeneous and are accessed by iterating over the list.

And in the section on dictionaries:

Unlike sequences, which are indexed by a range of numbers, dictionaries are indexed by keys, which can be any immutable type; strings and numbers can always be keys. Tuples can be used as keys if they contain only strings, numbers, or tuples; if a tuple contains any mutable object either directly or indirectly, it cannot be used as a key. You can’t use lists as keys, since lists can be modified in place using index assignments, slice assignments, or methods like append() and extend().


In case you're wondering what the error message means, it's complaining because there's no built-in hash function for lists (by design), and dictionaries are implemented as hash tables.

How do you change the width and height of Twitter Bootstrap's tooltips?

Please refer the below post. cmcculloh's answer worked for me. https://stackoverflow.com/posts/31683500/edit

As hinted at in the documentation, the easiest way to ensure that your tooltip does not wrap at all is to use

.tooltip-inner {
    max-width: none;
    white-space: nowrap;
}

With this, you don't have to worry about dimension values or anything like that. Main problem being if you have a super long line of text it will just go off of the screen (as you can see in the JSBin Example).

Using prepared statements with JDBCTemplate

Try the following:

PreparedStatementCreator creator = new PreparedStatementCreator() {
    @Override
    public PreparedStatement createPreparedStatement(Connection con) throws SQLException {
        PreparedStatement updateSales = con.prepareStatement(
        "UPDATE COFFEES SET SALES = ? WHERE COF_NAME LIKE ? ");
        updateSales.setInt(1, 75); 
        updateSales.setString(2, "Colombian"); 
        return updateSales;
    }
};

Tools: replace not replacing in Android manifest

Final Working Solution for me (Highlighted the tages in the sample code):

  1. add the xmlns:tools line in the manifest tag
  2. add tools:replace in the application tag

Example:

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="pagination.yoga.com.tamiltv"
    **xmlns:tools="http://schemas.android.com/tools"**
    >

    <uses-permission android:name="android.permission.INTERNET" />
    <uses-permission android:name="android.permission.ACCESS_NETWORK_STATE" />
    <uses-permission android:name="android.permission.ACCESS_WIFI_STATE" />

    <application
        android:allowBackup="true"
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme"
        **tools:replace="android:icon,android:theme"**
        >

How to check if array is not empty?

If you are talking about Python's actual array (available through import array from array), then the principle of least astonishment applies and you can check whether it is empty the same way you'd check if a list is empty.

from array import array
an_array = array('i') # an array of ints

if an_array:
    print("this won't be printed")

an_array.append(3)

if an_array:
    print("this will be printed")

How to provide animation when calling another activity in Android?

You must use OverridePendingTransition method to achieve it, which is in the Activity class. Sample Animations in the apidemos example's res/anim folder. Check it. More than check the demo in ApiDemos/App/Activity/animation.

Example:

@Override
public void onResume(){
    // TODO LC: preliminary support for views transitions
    this.overridePendingTransition(R.anim.in_from_right, R.anim.out_to_left);
}

'Missing recommended icon file - The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format'

I created my AppIcon catalog manually and had all the correct icons in it, but my project was not using it as the icon catalog. On the project's General tab (where you can set the project name and version number), there was an entry for App Icons Source, but no way to select the catalog I created. I had to click the button to create a new catalog, then delete that new catalog, and then the button changed to a menu where I could select the existing catalog.

How to get subarray from array?

_x000D_
_x000D_
const array_one = [11, 22, 33, 44, 55];_x000D_
const start = 1;_x000D_
const end = array_one.length - 1;_x000D_
const array_2 = array_one.slice(start, end);_x000D_
console.log(array_2);
_x000D_
_x000D_
_x000D_

How to use tick / checkmark symbol (?) instead of bullets in unordered list?

You can use a pseudo-element to insert that character before each list item:

_x000D_
_x000D_
ul {_x000D_
  list-style: none;_x000D_
}_x000D_
_x000D_
ul li:before {_x000D_
  content: '?';_x000D_
}
_x000D_
<ul>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
  <li>this is my text</li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

How do I find the duplicates in a list and create another list with them?

the third example of the accepted answer give an erroneous answer and does not attempt to give duplicates. Here is the correct version :

number_lst = [1, 1, 2, 3, 5, ...]

seen_set = set()
duplicate_set = set(x for x in number_lst if x in seen_set or seen_set.add(x))
unique_set = seen_set - duplicate_set

Reset MySQL root password using ALTER USER statement after install on Mac

On MySQL 5.7.x you need to switch to native password to be able to change it, like:

ALTER USER 'root'@'localhost' IDENTIFIED WITH mysql_native_password BY 'test';

href around input type submit

Why would you want to put a submit button inside an anchor? You are either trying to submit a form or go to a different page. Which one is it?

Either submit the form:

<input type="submit" class="button_active" value="1" />

Or go to another page:

<input type="button" class="button_active" onclick="location.href='1.html';" />

spring data jpa @query and pageable

A similar question was asked on the Spring forums, where it was pointed out that to apply pagination, a second subquery must be derived. Because the subquery is referring to the same fields, you need to ensure that your query uses aliases for the entities/tables it refers to. This means that where you wrote:

select * from internal_uddi where urn like

You should instead have:

select * from internal_uddi iu where iu.urn like ...

JavaScript - Getting HTML form values

Here is an example from W3Schools:

function myFunction() {
    var elements = document.getElementById("myForm").elements;
    var obj ={};
    for(var i = 0 ; i < elements.length ; i++){
        var item = elements.item(i);
        obj[item.name] = item.value;
    }

    document.getElementById("demo").innerHTML = JSON.stringify(obj);
}

The demo can be found here.

jquery (or pure js) simulate enter key pressed for testing

Demo Here

var e = jQuery.Event("keypress");
e.which = 13; //choose the one you want
e.keyCode = 13;
$("#theInputToTest").trigger(e);

PHP Get name of current directory

To get only the name of the directory where script executed:

//Path to script: /data/html/cars/index.php
echo basename(dirname(__FILE__)); //"cars"

Parameter in like clause JPQL

  1. Use below JPQL query.
select i from Instructor i where i.address LIKE CONCAT('%',:address ,'%')");
  1. Use below Criteria code for the same:
@Test
public void findAllHavingAddressLike() {
    CriteriaBuilder cb = criteriaUtils.criteriaBuilder();
    CriteriaQuery<Instructor> cq = cb.createQuery(Instructor.class);
    Root<Instructor> root = cq.from(Instructor.class);
    printResultList(cq.select(root).where(
        cb.like(root.get(Instructor_.address), "%#1074%")));
}

How to define a Sql Server connection string to use in VB.NET?

Try

Dim connectionString AS String = "Server=my_server;Database=name_of_db;User Id=user_name;Password=my_password"

And replace my_server, name_of_db, user_name and my_password with your values.

then Using sqlCon = New SqlConnection(connectionString) should work

also I think your SQL is wrong, it should be SET clickCount= clickCount + 1 I think.

And on a general note, the page you link to has a link called Connection String which shows you how to do this.

SQL: ... WHERE X IN (SELECT Y FROM ...)

One reason why you might prefer to use a JOIN rather than NOT IN is that if the Values in the NOT IN clause contain any NULLs you will always get back no results. If you do use NOT IN remember to always consider whether the sub query might bring back a NULL value!

RE: Question in Comments

'x' NOT IN (NULL,'a','b')

= 'x' <> NULL and 'x' <> 'a' and 'x' <> 'b'

= Unknown and True and True

= Unknown

How to drop column with constraint?

You can also drop the column and its constraint(s) in a single statement rather than individually.

CREATE TABLE #T
  (
     Col1 INT CONSTRAINT UQ UNIQUE CONSTRAINT CK CHECK (Col1 > 5),
     Col2 INT
  )

ALTER TABLE #T DROP CONSTRAINT UQ , 
                    CONSTRAINT CK, 
                    COLUMN Col1


DROP TABLE #T 

Some dynamic SQL that will look up the names of dependent check constraints and default constraints and drop them along with the column is below

(but not other possible column dependencies such as foreign keys, unique and primary key constraints, computed columns, indexes)

CREATE TABLE [dbo].[TestTable]
(
A INT DEFAULT '1' CHECK (A=1),
B INT,
CHECK (A > B)
)

GO

DECLARE @TwoPartTableNameQuoted nvarchar(500) = '[dbo].[TestTable]',
        @ColumnNameUnQuoted sysname = 'A',
        @DynSQL NVARCHAR(MAX);

SELECT @DynSQL =
     'ALTER TABLE ' + @TwoPartTableNameQuoted + ' DROP' + 
      ISNULL(' CONSTRAINT ' + QUOTENAME(OBJECT_NAME(c.default_object_id)) + ',','') + 
      ISNULL(check_constraints,'') + 
      '  COLUMN ' + QUOTENAME(@ColumnNameUnQuoted)
FROM   sys.columns c
       CROSS APPLY (SELECT ' CONSTRAINT ' + QUOTENAME(OBJECT_NAME(referencing_id)) + ','
                    FROM   sys.sql_expression_dependencies
                    WHERE  referenced_id = c.object_id
                           AND referenced_minor_id = c.column_id
                           AND OBJECTPROPERTYEX(referencing_id, 'BaseType') = 'C'
                    FOR XML PATH('')) ck(check_constraints)
WHERE  c.object_id = object_id(@TwoPartTableNameQuoted)
       AND c.name = @ColumnNameUnQuoted;

PRINT @DynSQL;
EXEC (@DynSQL); 

Why does this iterative list-growing code give IndexError: list assignment index out of range?

One more way:

j=i[0]
for k in range(1,len(i)):
    j = numpy.vstack([j,i[k]])

In this case j will be a numpy array

How to export all collections in MongoDB?

First, of Start the Mongo DB - for that go to the path as ->

C:\Program Files\MongoDB\Server\3.2\bin and click on the mongod.exe file to start MongoDB server.

Command in Windows to Export

  • Command to export MongoDB database in Windows from "remote-server" to the local machine in directory C:/Users/Desktop/temp-folder from the remote server with the internal IP address and port.

C:> mongodump --host remote_ip_address:27017 --db -o C:/Users/Desktop/temp-folder

Command in Windows to Import

  • Command to import MongoDB database in Windows to "remote-server" from local machine directory C:/Users/Desktop/temp-folder/db-dir

C:> mongorestore --host=ip --port=27017 -d C:/Users/Desktop/temp-folder/db-dir

You must add a reference to assembly 'netstandard, Version=2.0.0.0

This is where netstandard.dll exists: C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.7.2\Facades\netstandard.dll Add ref to your Project through this.

How to prevent browser to invoke basic auth popup and handle 401 error using Jquery?

From back side with Spring Boot I've used custom BasicAuthenticationEntryPoint:

@Override
protected void configure(HttpSecurity http) throws Exception {
    http.cors().and().authorizeRequests()
            ...
            .antMatchers(PUBLIC_AUTH).permitAll()
            .and().httpBasic()
//    https://www.baeldung.com/spring-security-basic-authentication
            .authenticationEntryPoint(authBasicAuthenticationEntryPoint())
            ...

@Bean
public BasicAuthenticationEntryPoint authBasicAuthenticationEntryPoint() {
    return new BasicAuthenticationEntryPoint() {
        {
            setRealmName("pirsApp");
        }

        @Override
        public void commence
                (HttpServletRequest request, HttpServletResponse response, AuthenticationException authEx)
                throws IOException, ServletException {
            if (request.getRequestURI().equals(PUBLIC_AUTH)) {
                response.sendError(HttpStatus.PRECONDITION_FAILED.value(), "Wrong credentials");
            } else {
                super.commence(request, response, authEx);
            }
        }
    };
}

Python: tf-idf-cosine: to find document similarity

I know its an old post. but I tried the http://scikit-learn.sourceforge.net/stable/ package. here is my code to find the cosine similarity. The question was how will you calculate the cosine similarity with this package and here is my code for that

from sklearn.feature_extraction.text import CountVectorizer
from sklearn.metrics.pairwise import cosine_similarity
from sklearn.feature_extraction.text import TfidfVectorizer

f = open("/root/Myfolder/scoringDocuments/doc1")
doc1 = str.decode(f.read(), "UTF-8", "ignore")
f = open("/root/Myfolder/scoringDocuments/doc2")
doc2 = str.decode(f.read(), "UTF-8", "ignore")
f = open("/root/Myfolder/scoringDocuments/doc3")
doc3 = str.decode(f.read(), "UTF-8", "ignore")

train_set = ["president of India",doc1, doc2, doc3]

tfidf_vectorizer = TfidfVectorizer()
tfidf_matrix_train = tfidf_vectorizer.fit_transform(train_set)  #finds the tfidf score with normalization
print "cosine scores ==> ",cosine_similarity(tfidf_matrix_train[0:1], tfidf_matrix_train)  #here the first element of tfidf_matrix_train is matched with other three elements

Here suppose the query is the first element of train_set and doc1,doc2 and doc3 are the documents which I want to rank with the help of cosine similarity. then I can use this code.

Also the tutorials provided in the question was very useful. Here are all the parts for it part-I,part-II,part-III

the output will be as follows :

[[ 1.          0.07102631  0.02731343  0.06348799]]

here 1 represents that query is matched with itself and the other three are the scores for matching the query with the respective documents.

node.js remove file

As the accepted answer, use fs.unlink to delete files.

But according to Node.js documentation

Using fs.stat() to check for the existence of a file before calling fs.open(), fs.readFile() or fs.writeFile() is not recommended. Instead, user code should open/read/write the file directly and handle the error raised if the file is not available.

To check if a file exists without manipulating it afterwards, fs.access() is recommended.

to check files can be deleted or not, Use fs.access instead

fs.access('/etc/passwd', fs.constants.R_OK | fs.constants.W_OK, (err) => {
  console.log(err ? 'no access!' : 'can read/write');
});

PHP Array to CSV

This is a simple solution that exports an array to csv string:

function array2csv($data, $delimiter = ',', $enclosure = '"', $escape_char = "\\")
{
    $f = fopen('php://memory', 'r+');
    foreach ($data as $item) {
        fputcsv($f, $item, $delimiter, $enclosure, $escape_char);
    }
    rewind($f);
    return stream_get_contents($f);
}

$list = array (
    array('aaa', 'bbb', 'ccc', 'dddd'),
    array('123', '456', '789'),
    array('"aaa"', '"bbb"')
);
var_dump(array2csv($list));

C - split string into an array of strings

Since you've already looked into strtok just continue down the same path and split your string using space (' ') as a delimiter, then use something as realloc to increase the size of the array containing the elements to be passed to execvp.

See the below example, but keep in mind that strtok will modify the string passed to it. If you don't want this to happen you are required to make a copy of the original string, using strcpy or similar function.

char    str[]= "ls -l";
char ** res  = NULL;
char *  p    = strtok (str, " ");
int n_spaces = 0, i;


/* split string and append tokens to 'res' */

while (p) {
  res = realloc (res, sizeof (char*) * ++n_spaces);

  if (res == NULL)
    exit (-1); /* memory allocation failed */

  res[n_spaces-1] = p;

  p = strtok (NULL, " ");
}

/* realloc one extra element for the last NULL */

res = realloc (res, sizeof (char*) * (n_spaces+1));
res[n_spaces] = 0;

/* print the result */

for (i = 0; i < (n_spaces+1); ++i)
  printf ("res[%d] = %s\n", i, res[i]);

/* free the memory allocated */

free (res);

res[0] = ls
res[1] = -l
res[2] = (null)

Excel VBA - Sum up a column

Here is what you can do if you want to add a column of numbers in Excel. ( I am using Excel 2010 but should not make a difference.)

Example: Lets say you want to add the cells in Column B form B10 to B100 & want the answer to be in cell X or be Variable X ( X can be any cell or any variable you create such as Dim X as integer, etc). Here is the code:

Range("B5") = "=SUM(B10:B100)"

or

X = "=SUM(B10:B100)

There are no quotation marks inside the parentheses in "=Sum(B10:B100) but there are quotation marks inside the parentheses in Range("B5"). Also there is a space between the equals sign and the quotation to the right of it.

It will not matter if some cells are empty, it will simply see them as containing zeros!

This should do it for you!

Create Hyperlink in Slack

In addition to the ?ShiftU/CtrlShiftU solution, you can also add a link quickly by doing the following:

  1. Copy a URL to the clipboard
  2. Select the text in a slack message you are writing that you want to be a link
  3. Press ?V on Mac or CtrlV

I couldn't find it documented anywhere, but it works, and seems very handy.

Difference between _self, _top, and _parent in the anchor tag target attribute

While these answers are good, IMHO I don't think they fully address the question.

The target attribute in an anchor tag tells the browser the target of the destination of the anchor. They were initially created in order to manipulate and direct anchors to the frame system of document. This was well before CSS came to the aid of HTML developers.

While target="_self" is default by browser and the most common target is target="_blank" which opens the anchor in a new window(which has been redirected to tabs by browser settings usually). The "_parent", "_top" and framename tags are left a mystery to those that aren't familiar with the days of iframe site building as the trend.

target="_self" This opens an anchor in the same frame. What is confusing is that because we generally don't write in frames anymore (and the frame and frameset tags are obsolete in HTML5) people assume this a same window function. Instead if this anchor was nested in frames it would open in a sandbox mode of sorts, meaning only in that frame.

target="_parent" Will open the in the next level up of a frame if they were nested to inside one another

target="_top" This breaks outside of all the frames it is nested in and opens the link as top document in the browser window.

target="framename This was originally deprecated but brought back in HTML5. This will target the exact frame in question. While the name was the proper method that method has been replaced with using the id identifying tag.

<!--Example:-->

<html>
<head>
</head>
<body>
<iframe src="url1" name="A"><p> This my first iframe</p></iframe>
<iframe src="url2" name="B"><p> This my second iframe</p></iframe>
<iframe src="url3" name="C"><p> This my third iframe</p></iframe>

<a href="url4" target="B"></a>
</body>
</html>

format statement in a string resource file

You should add formatted="false" to your string resource


Here is an example

In your strings.xml :

<string name="all" formatted="false">Amount: %.2f%n  for %d days</string>

In your code:

yourTextView.setText(String.format(getString(R.string.all), 3.12, 2));

CSS strikethrough different color from text?

Blazemonger's reply (above or below) needs voting up - but I don't have enough points.

I wanted to add a grey bar across some 20px wide CSS round buttons to indicate "not available" and tweaked Blazemonger's css:

.round_btn:after {
    content:"";    /* required property */
    position: absolute;
    top: 6px;
    left: -1px;
    border-top: 6px solid rgba(170,170,170,0.65);
    height: 6px;
    width: 19px;
}

SQL: How To Select Earliest Row

Simply use min()

SELECT company, workflow, MIN(date) 
FROM workflowTable 
GROUP BY company, workflow

"401 Unauthorized" on a directory

Another simple fix I found was to delete the local IIS site (from within IIS Manager) and then re-create the virtual directory from the "Properties" of your web project in Visual Studio.

What's the best way to break from nested loops in JavaScript?

Hmmm hi to the 10 years old party ?

Why not put some condition in your for ?

var condition = true
for (var i = 0 ; i < Args.length && condition ; i++) {
    for (var j = 0 ; j < Args[i].length && condition ; j++) {
        if (Args[i].obj[j] == "[condition]") {
            condition = false
        }
    }
}

Like this you stop when you want

In my case, using Typescript, we can use some() which go through the array and stop when condition is met So my code become like this :

Args.some((listObj) => {
    return listObj.some((obj) => {
        return !(obj == "[condition]")
    })
})

Like this, the loop stopped right after the condition is met

Reminder : This code run in TypeScript

How to select the comparison of two columns as one column in Oracle

select column1, coulumn2, case when colum1=column2 then 'true' else 'false' end from table;

HTH

Simplest way to do a recursive self-join?

Check following to help the understand the concept of CTE recursion

DECLARE
@startDate DATETIME,
@endDate DATETIME

SET @startDate = '11/10/2011'
SET @endDate = '03/25/2012'

; WITH CTE AS (
    SELECT
        YEAR(@startDate) AS 'yr',
        MONTH(@startDate) AS 'mm',
        DATENAME(mm, @startDate) AS 'mon',
        DATEPART(d,@startDate) AS 'dd',
        @startDate 'new_date'
    UNION ALL
    SELECT
        YEAR(new_date) AS 'yr',
        MONTH(new_date) AS 'mm',
        DATENAME(mm, new_date) AS 'mon',
        DATEPART(d,@startDate) AS 'dd',
        DATEADD(d,1,new_date) 'new_date'
    FROM CTE
    WHERE new_date < @endDate
    )
SELECT yr AS 'Year', mon AS 'Month', count(dd) AS 'Days'
FROM CTE
GROUP BY mon, yr, mm
ORDER BY yr, mm
OPTION (MAXRECURSION 1000)

Using Cookie in Asp.Net Mvc 4

We are using Response.SetCookie() for update the old one cookies and Response.Cookies.Add() are use to add the new cookies. Here below code CompanyId is update in old cookie[OldCookieName].

HttpCookie cookie = Request.Cookies["OldCookieName"];//Get the existing cookie by cookie name.
cookie.Values["CompanyID"] = Convert.ToString(CompanyId);
Response.SetCookie(cookie); //SetCookie() is used for update the cookie.
Response.Cookies.Add(cookie); //The Cookie.Add() used for Add the cookie.

GitHub - failed to connect to github 443 windows/ Failed to connect to gitHub - No Error

I got an error when I used

<git config --global http.proxy http://user:password@proxy_addr:port>

The error is that the config file cannot be identified as there is no such file. I changed the command to

<git config --system http.proxy http://user:password@proxy_addr:port>

I am running git on the Windows 7 command prompt.
The above command references the config file in GIT_HOME/etc/gitconfig.
The --global option does not.

"No such file or directory" but it exists

I had this issue and the reason was EOL in some editors such as Notepad++. You can check it in Edit menu/EOL conversion. Unix(LF) should be selected. I hope it would be useful.

Adding attribute in jQuery

You can add attributes using attr like so:

$('#someid').attr('name', 'value');

However, for DOM properties like checked, disabled and readonly, the proper way to do this (as of JQuery 1.6) is to use prop.

$('#someid').prop('disabled', true);

Manipulating an Access database from Java without ODBC

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

 

Option 1: Using Maven

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

groupId: net.sf.ucanaccess
artifactId: ucanaccess

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

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

 

Option 2: Manually adding the JARs to your project

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

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

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

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

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

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

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

BuildPath.png

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

nbAddJar.png

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

nbLibraries.png

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

IntelliJ.png

 

That's it!

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

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

 

Disclosure

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

Groovy executing shell commands

"ls".execute() returns a Process object which is why "ls".execute().text works. You should be able to just read the error stream to determine if there were any errors.

There is a extra method on Process that allow you to pass a StringBuffer to retrieve the text: consumeProcessErrorStream(StringBuffer error).

Example:

def proc = "ls".execute()
def b = new StringBuffer()
proc.consumeProcessErrorStream(b)

println proc.text
println b.toString()

Fastest way to compute entropy in Python

An answer that doesn't rely on numpy, either:

import math
from collections import Counter

def eta(data, unit='natural'):
    base = {
        'shannon' : 2.,
        'natural' : math.exp(1),
        'hartley' : 10.
    }

    if len(data) <= 1:
        return 0

    counts = Counter()

    for d in data:
        counts[d] += 1

    ent = 0

    probs = [float(c) / len(data) for c in counts.values()]
    for p in probs:
        if p > 0.:
            ent -= p * math.log(p, base[unit])

    return ent

This will accept any datatype you could throw at it:

>>> eta(['mary', 'had', 'a', 'little', 'lamb'])
1.6094379124341005

>>> eta([c for c in "mary had a little lamb"])
2.311097886212714

The answer provided by @Jarad suggested timings as well. To that end:

repeat_number = 1000000
e = timeit.repeat(
    stmt='''eta(labels)''', 
    setup='''labels=[1,3,5,2,3,5,3,2,1,3,4,5];from __main__ import eta''', 
    repeat=3, 
    number=repeat_number)

Timeit results: (I believe this is ~4x faster than the best numpy approach)

print('Method: {}, Avg.: {:.6f}'.format("eta", np.array(e).mean()))

Method: eta, Avg.: 10.461799

Delaying AngularJS route change until model loaded to prevent flicker

I worked from Misko's code above and this is what I've done with it. This is a more current solution since $defer has been changed to $timeout. Substituting $timeout however will wait for the timeout period (in Misko's code, 1 second), then return the data hoping it's resolved in time. With this way, it returns asap.

function PhoneListCtrl($scope, phones) {
  $scope.phones = phones;
  $scope.orderProp = 'age';
}

PhoneListCtrl.resolve = {

  phones: function($q, Phone) {
    var deferred = $q.defer();

    Phone.query(function(phones) {
        deferred.resolve(phones);
    });

    return deferred.promise;
  }
}

jQuery load more data on scroll

Here is an example:

  1. On scrolling to the bottom, html elements are appeneded. This appending mechanism are only done twice, and then a button with powderblue color is appended at last.

_x000D_
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
<head>_x000D_
    <title>Demo: Lazy Loader</title>_x000D_
    <script src="https://code.jquery.com/jquery-3.2.1.min.js"></script>_x000D_
    <style>_x000D_
        #myScroll {_x000D_
            border: 1px solid #999;_x000D_
        }_x000D_
_x000D_
        p {_x000D_
            border: 1px solid #ccc;_x000D_
            padding: 50px;_x000D_
            text-align: center;_x000D_
        }_x000D_
_x000D_
        .loading {_x000D_
            color: red;_x000D_
        }_x000D_
        .dynamic {_x000D_
            background-color:#ccc;_x000D_
            color:#000;_x000D_
        }_x000D_
    </style>_x000D_
    <script>_x000D_
  var counter=0;_x000D_
        $(window).scroll(function () {_x000D_
            if ($(window).scrollTop() == $(document).height() - $(window).height() && counter < 2) {_x000D_
                appendData();_x000D_
            }_x000D_
        });_x000D_
        function appendData() {_x000D_
            var html = '';_x000D_
            for (i = 0; i < 10; i++) {_x000D_
                html += '<p class="dynamic">Dynamic Data :  This is test data.<br />Next line.</p>';_x000D_
            }_x000D_
            $('#myScroll').append(html);_x000D_
   counter++;_x000D_
   _x000D_
   if(counter==2)_x000D_
   $('#myScroll').append('<button id="uniqueButton" style="margin-left: 50%; background-color: powderblue;">Click</button><br /><br />');_x000D_
        }_x000D_
    </script>_x000D_
</head>_x000D_
<body>_x000D_
    <div id="myScroll">_x000D_
        <p>_x000D_
            Contents will load here!!!.<br />_x000D_
        </p>_x000D_
        <p >This is test data.<br />Next line.</p>_x000D_
        <p >This is test data.<br />Next line.</p>_x000D_
        <p >This is test data.<br />Next line.</p>_x000D_
        <p >This is test data.<br />Next line.</p>_x000D_
        <p >This is test data.<br />Next line.</p>_x000D_
        <p >This is test data.<br />Next line.</p>_x000D_
        <p >This is test data.<br />Next line.</p>_x000D_
        <p >This is test data.<br />Next line.</p>_x000D_
        <p >This is test data.<br />Next line.</p>_x000D_
        <p >This is test data.<br />Next line.</p>_x000D_
        <p >This is test data.<br />Next line.</p>_x000D_
        <p >This is test data.<br />Next line.</p>_x000D_
        <p >This is test data.<br />Next line.</p>_x000D_
        <p >This is test data.<br />Next line.</p>_x000D_
        <p >This is test data.<br />Next line.</p>_x000D_
        <p >This is test data.<br />Next line.</p>_x000D_
        <p >This is test data.<br />Next line.</p>_x000D_
        <p >This is test data.<br />Next line.</p>_x000D_
        <p >This is test data.<br />Next line.</p>_x000D_
        <p >This is test data.<br />Next line.</p>_x000D_
        <p >This is test data.<br />Next line.</p>_x000D_
        <p >This is test data.<br />Next line.</p>_x000D_
    </div>_x000D_
</body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

How do I add an element to array in reducer of React native redux?

Two different options to add item to an array without mutation

case ADD_ITEM :
    return { 
        ...state,
        arr: [...state.arr, action.newItem]
    }

OR

case ADD_ITEM :
    return { 
        ...state,
        arr: state.arr.concat(action.newItem)
    }

Cordova : Requirements check failed for JDK 1.8 or greater

  1. Go to Control panel Home
  2. Advanced System Settings
  3. Environment Variables
  4. Choose JAVA_HOME
  5. edit
  6. variable value for the 1.8 one

How to insert new row to database with AUTO_INCREMENT column without specifying column names?

Even better, use DEFAULT instead of NULL. You want to store the default value, not a NULL that might trigger a default value.

But you'd better name all columns, with a piece of SQL you can create all the INSERT, UPDATE and DELETE's you need. Just check the information_schema and construct the queries you need. There is no need to do it all by hand, SQL can help you out.

Using Python String Formatting with Lists

Here is a one liner. A little improvised answer using format with print() to iterate a list.

How about this (python 3.x):

sample_list = ['cat', 'dog', 'bunny', 'pig']
print("Your list of animals are: {}, {}, {} and {}".format(*sample_list))

Read the docs here on using format().

Rails where condition using NOT NIL

For Rails4:

So, what you're wanting is an inner join, so you really should just use the joins predicate:

  Foo.joins(:bar)

  Select * from Foo Inner Join Bars ...

But, for the record, if you want a "NOT NULL" condition simply use the not predicate:

Foo.includes(:bar).where.not(bars: {id: nil})

Select * from Foo Left Outer Join Bars on .. WHERE bars.id IS NOT NULL

Note that this syntax reports a deprecation (it talks about a string SQL snippet, but I guess the hash condition is changed to string in the parser?), so be sure to add the references to the end:

Foo.includes(:bar).where.not(bars: {id: nil}).references(:bar)

DEPRECATION WARNING: It looks like you are eager loading table(s) (one of: ....) that are referenced in a string SQL snippet. For example:

Post.includes(:comments).where("comments.title = 'foo'")

Currently, Active Record recognizes the table in the string, and knows to JOIN the comments table to the query, rather than loading comments in a separate query. However, doing this without writing a full-blown SQL parser is inherently flawed. Since we don't want to write an SQL parser, we are removing this functionality. From now on, you must explicitly tell Active Record when you are referencing a table from a string:

Post.includes(:comments).where("comments.title = 'foo'").references(:comments)

Keep overflow div scrolled to bottom unless user scrolls up

I just implemented this and perhaps you can use my approach.

Say we have the following HTML:

<div id="out" style="overflow:auto"></div>

Then we can check if it scrolled to the bottom with:

var out = document.getElementById("out");
// allow 1px inaccuracy by adding 1
var isScrolledToBottom = out.scrollHeight - out.clientHeight <= out.scrollTop + 1;

scrollHeight gives you the height of the element, including any non visible area due to overflow. clientHeight gives you the CSS height or said in another way, the actual height of the element. Both methods returns the height without margin, so you needn't worry about that. scrollTop gives you the position of the vertical scroll. 0 is top and max is the scrollHeight of the element minus the element height itself. When using the scrollbar it can be difficult (it was in Chrome for me) to get the scrollbar all the way down to the bottom. so I threw in a 1px inaccuracy. So isScrolledToBottom will be true even if the scrollbar is 1px from the bottom. You can set this to whatever feels right to you.

Then it's simply a matter of setting the scrollTop of the element to the bottom.

if(isScrolledToBottom)
    out.scrollTop = out.scrollHeight - out.clientHeight;

I have made a fiddle for you to show the concept: http://jsfiddle.net/dotnetCarpenter/KpM5j/

EDIT: Added code snippet to clarify when isScrolledToBottom is true.

Stick scrollbar to bottom

_x000D_
_x000D_
const out = document.getElementById("out")_x000D_
let c = 0_x000D_
_x000D_
setInterval(function() {_x000D_
    // allow 1px inaccuracy by adding 1_x000D_
    const isScrolledToBottom = out.scrollHeight - out.clientHeight <= out.scrollTop + 1_x000D_
_x000D_
    const newElement = document.createElement("div")_x000D_
_x000D_
    newElement.textContent = format(c++, 'Bottom position:', out.scrollHeight - out.clientHeight,  'Scroll position:', out.scrollTop)_x000D_
_x000D_
    out.appendChild(newElement)_x000D_
_x000D_
    // scroll to bottom if isScrolledToBottom is true_x000D_
    if (isScrolledToBottom) {_x000D_
      out.scrollTop = out.scrollHeight - out.clientHeight_x000D_
    }_x000D_
}, 500)_x000D_
_x000D_
function format () {_x000D_
  return Array.prototype.slice.call(arguments).join(' ')_x000D_
}
_x000D_
#out {_x000D_
    height: 100px;_x000D_
}
_x000D_
<div id="out" style="overflow:auto"></div>_x000D_
<p>To be clear: We want the scrollbar to stick to the bottom if we have scrolled all the way down. If we scroll up, then we don't want the content to move._x000D_
</p>
_x000D_
_x000D_
_x000D_

Rename Excel Sheet with VBA Macro

The "no frills" options are as follows:

ActiveSheet.Name = "New Name"

and

Sheets("Sheet2").Name = "New Name"

You can also check out recording macros and seeing what code it gives you, it's a great way to start learning some of the more vanilla functions.

Javascript: Uncaught TypeError: Cannot call method 'addEventListener' of null

Move script tag at the end of BODY instead of HEAD because in current code when the script is computed html element doesn't exist in document.

Since you don't want to you jquery. Use window.onload or document.onload to execute the entire piece of code that you have in current script tag. window.onload vs document.onload

Set cookies for cross origin requests

What you need to do

To allow receiving & sending cookies by a CORS request successfully, do the following.

Back-end (server): Set the HTTP header Access-Control-Allow-Credentials value to true. Also, make sure the HTTP headers Access-Control-Allow-Origin and Access-Control-Allow-Headers are set and not with a wildcard *.

Recommended Cookie settings per Chrome and Firefox update in 2021: SameSite=None and Secure. See MDN documentation

For more info on setting CORS in express js read the docs here

Front-end (client): Set the XMLHttpRequest.withCredentials flag to true, this can be achieved in different ways depending on the request-response library used:

Or

Avoid having to use CORS in combination with cookies. You can achieve this with a proxy.

If you for whatever reason don't avoid it. The solution is above.

It turned out that Chrome won't set the cookie if the domain contains a port. Setting it for localhost (without port) is not a problem. Many thanks to Erwin for this tip!

How do I exit from the text window in Git?

Since you are learning Git, know that this has little to do with git but with the text editor configured for use. In vim, you can press i to start entering text and save by pressing esc and :wq and enter, this will commit with the message you typed. In your current state, to just come out without committing, you can do :q instead of the :wq as mentioned above.

Alternatively, you can just do git commit -m '<message>' instead of having git open the editor to type the message.

Note that you can also change the editor and use something you are comfortable with ( like notepad) - How can I set up an editor to work with Git on Windows?

How do I style radio buttons with images - laughing smiley for good, sad smiley for bad?

Let's keep them simple, shall we. First off, using pure HTML + CSS:

<div id="emotion">
    <input type="radio" name="emotion" id="sad" />
        <label for="sad"><img src="sad_image.png" alt="I'm sad" /></label>

    <input type="radio" name="emotion" id="happy" />
        <label for="happy"><img src="happy_image.png" alt="I'm happy" /></label>
</div>

This will degrade nicely if there's no JavaScript. Use id and for attributes to link up the label and radiobutton so that when the image is selected, the corresponding radiobutton will be filled. This is important because we'll need to hide the actual radiobutton using JavaScript. Now for some jQuery goodness. First off, creating the CSS we'll need:

.input_hidden {
    position: absolute;
    left: -9999px;
}

.selected {
    background-color: #ccc;
}

#emotion label {
    display: inline-block;
    cursor: pointer;
}

#emotion label img {
    padding: 3px;
}

Now for the JavaScript:

$('#emotion input:radio').addClass('input_hidden');
$('#emotion label').click(function(){
    $(this).addClass('selected').siblings().removeClass('selected');
});

The reason why we're not using display: none here is for accessibility reasons. See: http://www.jsfiddle.net/yijiang/Zgh24/1 for a live demo, with something more fancy.

Remove local git tags that are no longer on the remote repository

The same answer as @Richard W but for Windows (PowerShell)

git tag | foreach-object -process { git tag -d $_ }
git fetch -t

Using curl POST with variables defined in bash script functions

We can assign a variable for curl using single quote ' and wrap some other variables in double-single-double quote "'" for substitution inside curl-variable. Then easily we can use that curl-variable which here is MERGE.

Example:

# other variables ... 
REF_NAME="new-branch";

# variable for curl using single quote => ' not double "
MERGE='{
    "repository": "tmp",
    "command": "git",
    "args": [
        "pull",
        "origin",
        "'"$REF_NAME"'"
    ],
    "options": {
        "cwd": "/home/git/tmp"
    }
}';

notice this line:

    "'"$REF_NAME"'"

and then calling curl as usual:

curl -s -X POST localhost:1365/M -H 'Content-Type: application/json' --data "$MERGE" 

Storing Objects in HTML5 localStorage

There is a great library that wraps many solutions so it even supports older browsers called jStorage

You can set an object

$.jStorage.set(key, value)

And retrieve it easily

value = $.jStorage.get(key)
value = $.jStorage.get(key, "default value")

Adding data attribute to DOM

to get the text from a

<option value="1" data-sigla="AC">Acre</option>

uf = $("#selectestado option:selected").attr('data-sigla');

Where in memory are my variables stored in C?

One thing one needs to keep in mind about the storage is the as-if rule. The compiler is not required to put a variable in a specific place - instead it can place it wherever it pleases for as long as the compiled program behaves as if it were run in the abstract C machine according to the rules of the abstract C machine. This applies to all storage durations. For example:

  • a variable that is not accessed all can be eliminated completely - it has no storage... anywhere. Example - see how there is 42 in the generated assembly code but no sign of 404.
  • a variable with automatic storage duration that does not have its address taken need not be stored in memory at all. An example would be a loop variable.
  • a variable that is const or effectively const need not be in memory. Example - the compiler can prove that foo is effectively const and inlines its use into the code. bar has external linkage and the compiler cannot prove that it would not be changed outside the current module, hence it is not inlined.
  • an object allocated with malloc need not reside in memory allocated from heap! Example - notice how the code does not have a call to malloc and neither is the value 42 ever stored in memory, it is kept in a register!
  • thus an object that has been allocated by malloc and the reference is lost without deallocating the object with free need not leak memory...
  • the object allocated by malloc need not be within the heap below the program break (sbrk(0)) on Unixen...

utf-8 special characters not displaying

If you're using PHP and none of the above worked (as it was my case), you need to set the locale with utf-8 encoding.

Like this

setlocale(LC_ALL, 'fr_CA.utf-8');

How to create .pfx file from certificate and private key?

I was having the same issue. My problem was that the computer that generated the initial certificate request had crashed before the extended ssl validation process was completed. I needed to generate a new private key and then import the updated certificate from the certificate provider. If the private key doesn't exist on your computer then you can't export the certificate as pfx. They option is greyed out.

How to loop over grouped Pandas dataframe?

You can iterate over the index values if your dataframe has already been created.

df = df.groupby('l_customer_id_i').agg(lambda x: ','.join(x))
for name in df.index:
    print name
    print df.loc[name]

Fill drop down list on selection of another drop down list

enter image description here

enter image description here

enter image description here

Model:

namespace MvcApplicationrazor.Models
{
    public class CountryModel
    {
        public List<State> StateModel { get; set; }
        public SelectList FilteredCity { get; set; }
    }
    public class State
    {
        public int Id { get; set; }
        public string StateName { get; set; }
    }
    public class City
    {
        public int Id { get; set; }
        public int StateId { get; set; }
        public string CityName { get; set; }
    }
}   

Controller:

public ActionResult Index()
        {
            CountryModel objcountrymodel = new CountryModel();
            objcountrymodel.StateModel = new List<State>();
            objcountrymodel.StateModel = GetAllState();
            return View(objcountrymodel);
        }


        //Action result for ajax call
        [HttpPost]
        public ActionResult GetCityByStateId(int stateid)
        {
            List<City> objcity = new List<City>();
            objcity = GetAllCity().Where(m => m.StateId == stateid).ToList();
            SelectList obgcity = new SelectList(objcity, "Id", "CityName", 0);
            return Json(obgcity);
        }
        // Collection for state
        public List<State> GetAllState()
        {
            List<State> objstate = new List<State>();
            objstate.Add(new State { Id = 0, StateName = "Select State" });
            objstate.Add(new State { Id = 1, StateName = "State 1" });
            objstate.Add(new State { Id = 2, StateName = "State 2" });
            objstate.Add(new State { Id = 3, StateName = "State 3" });
            objstate.Add(new State { Id = 4, StateName = "State 4" });
            return objstate;
        }
        //collection for city
        public List<City> GetAllCity()
        {
            List<City> objcity = new List<City>();
            objcity.Add(new City { Id = 1, StateId = 1, CityName = "City1-1" });
            objcity.Add(new City { Id = 2, StateId = 2, CityName = "City2-1" });
            objcity.Add(new City { Id = 3, StateId = 4, CityName = "City4-1" });
            objcity.Add(new City { Id = 4, StateId = 1, CityName = "City1-2" });
            objcity.Add(new City { Id = 5, StateId = 1, CityName = "City1-3" });
            objcity.Add(new City { Id = 6, StateId = 4, CityName = "City4-2" });
            return objcity;
        }

View:

@model MvcApplicationrazor.Models.CountryModel
@{
    ViewBag.Title = "Index";
    Layout = "~/Views/Shared/_Layout.cshtml";
}

<script src="http://ajax.googleapis.com/ajax/libs/jqueryui/1.8/jquery-ui.min.js"></script>
<script language="javascript" type="text/javascript">
    function GetCity(_stateId) {
        var procemessage = "<option value='0'> Please wait...</option>";
        $("#ddlcity").html(procemessage).show();
        var url = "/Test/GetCityByStateId/";

        $.ajax({
            url: url,
            data: { stateid: _stateId },
            cache: false,
            type: "POST",
            success: function (data) {
                var markup = "<option value='0'>Select City</option>";
                for (var x = 0; x < data.length; x++) {
                    markup += "<option value=" + data[x].Value + ">" + data[x].Text + "</option>";
                }
                $("#ddlcity").html(markup).show();
            },
            error: function (reponse) {
                alert("error : " + reponse);
            }
        });

    }
</script>
<h4>
 MVC Cascading Dropdown List Using Jquery</h4>
@using (Html.BeginForm())
{
    @Html.DropDownListFor(m => m.StateModel, new SelectList(Model.StateModel, "Id", "StateName"), new { @id = "ddlstate", @style = "width:200px;", @onchange = "javascript:GetCity(this.value);" })
    <br />
    <br />
    <select id="ddlcity" name="ddlcity" style="width: 200px">

    </select>

    <br /><br />
  }

How to display div after click the button in Javascript?

<script type="text/javascript">
function showDiv(toggle){
document.getElementById(toggle).style.display = 'block';
}
</script>

<input type="button" name="answer" onclick="showDiv('toggle')">Show</input>

<div id="toggle" style="display:none">Hello</div>

Html attributes for EditorFor() in ASP.NET MVC

EditorFor works with metadata, so if you want to add html attributes you could always do it. Another option is to simply write a custom template and use TextBoxFor:

<%= Html.TextBoxFor(model => model.Control.PeriodType, 
    new { disabled = "disabled", @readonly = "readonly" }) %>    

jQuery animate backgroundColor

I like using delay() to get this done, here's an example:

jQuery(element).animate({ backgroundColor: "#FCFCD8" },1).delay(1000).animate({ backgroundColor: "#EFEAEA" }, 1500);

This can be called by a function, with "element" being the element class/name/etc. The element will instantly appear with the #FCFCD8 background, hold for a second, then fade into #EFEAEA.

Gradle: Execution failed for task ':processDebugManifest'

Maybe you have some duplicated Activities

Like this:

<activity android:name=".register.RegisterStepsActivity" />

....

<activity android:name=".register.RegisterStepsActivity" />

just comment one of them

How to have an auto incrementing version number (Visual Studio)?

Use AssemblyInfo.cs

Create the file in App_Code: and fill out the following or use Google for other attribute/property possibilities.

AssemblyInfo.cs

using System.Reflection;

[assembly: AssemblyDescription("Very useful stuff here.")]
[assembly: AssemblyCompany("companyname")]
[assembly: AssemblyCopyright("Copyright © me 2009")]
[assembly: AssemblyProduct("NeatProduct")]
[assembly: AssemblyVersion("1.1.*")]

AssemblyVersion being the part you are really after.

Then if you are working on a website, in any aspx page, or control, you can add in the <Page> tag, the following:

CompilerOptions="<folderpath>\App_Code\AssemblyInfo.cs"

(replacing folderpath with appropriate variable of course).

I don't believe you need to add compiler options in any manner for other classes; all the ones in the App_Code should receive the version information when they are compiled.

Hope that helps.

How to count string occurrence in string?

You could try this

let count = s.length - s.replace(/is/g, "").length;

Associative arrays in Shell scripts

I modified Vadim's solution with the following:

####################################################################
# Bash v3 does not support associative arrays
# and we cannot use ksh since all generic scripts are on bash
# Usage: map_put map_name key value
#
function map_put
{
    alias "${1}$2"="$3"
}

# map_get map_name key
# @return value
#
function map_get {
    if type -p "${1}$2"
        then
            alias "${1}$2" | awk -F "'" '{ print $2; }';
    fi
}

# map_keys map_name 
# @return map keys
#
function map_keys
{
    alias -p | grep $1 | cut -d'=' -f1 | awk -F"$1" '{print $2; }'
}

The change is to map_get in order to prevent it from returning errors if you request a key that doesn't exist, though the side-effect is that it will also silently ignore missing maps, but it suited my use-case better since I just wanted to check for a key in order to skip items in a loop.

"ORA-01438: value larger than specified precision allowed for this column" when inserting 3

You can't update with a number greater than 1 for datatype number(2,2) is because, the first parameter is the total number of digits in the number and the second one (.i.e 2 here) is the number of digits in decimal part. I guess you can insert or update data < 1. i.e. 0.12, 0.95 etc.

Please check NUMBER DATATYPE in NUMBER Datatype.

Trying to get the average of a count resultset

You just can put your query as a subquery:

SELECT avg(count)
  FROM 
    (
    SELECT COUNT (*) AS Count
      FROM Table T
     WHERE T.Update_time =
               (SELECT MAX (B.Update_time )
                  FROM Table B
                 WHERE (B.Id = T.Id))
    GROUP BY T.Grouping
    ) as counts

Edit: I think this should be the same:

SELECT count(*) / count(distinct T.Grouping)
  FROM Table T
 WHERE T.Update_time =
           (SELECT MAX (B.Update_time)
              FROM Table B
             WHERE (B.Id = T.Id))

Error handling in AngularJS http get then construct

Try this

function sendRequest(method, url, payload, done){

        var datatype = (method === "JSONP")? "jsonp" : "json";
        $http({
                method: method,
                url: url,
                dataType: datatype,
                data: payload || {},
                cache: true,
                timeout: 1000 * 60 * 10
        }).then(
            function(res){
                done(null, res.data); // server response
            },
            function(res){
                responseHandler(res, done);
            }
        );

    }
    function responseHandler(res, done){
        switch(res.status){
            default: done(res.status + ": " + res.statusText);
        }
    }

jQuery Toggle Text?

Improving and Simplifying @Nate's answer:

jQuery.fn.extend({
    toggleText: function (a, b){
        var that = this;
            if (that.text() != a && that.text() != b){
                that.text(a);
            }
            else
            if (that.text() == a){
                that.text(b);
            }
            else
            if (that.text() == b){
                that.text(a);
            }
        return this;
    }
});

Use as:

$("#YourElementId").toggleText('After', 'Before');

How to use jquery or ajax to update razor partial view in c#/asp.net for a MVC project

You'll need AJAX if you want to update a part of your page without reloading the entire page.

main cshtml view

<div id="refTable">
     <!-- partial view content will be inserted here -->
</div>

@Html.TextBox("yearSelect3", Convert.ToDateTime(tempItem3.Holiday_date).Year.ToString());
<button id="pY">PrevY</button>

<script>
    $(document).ready(function() {
        $("#pY").on("click", function() {
            var val = $('#yearSelect3').val();
            $.ajax({
                url: "/Holiday/Calendar",
                type: "GET",
                data: { year: ((val * 1) + 1) }
            })
            .done(function(partialViewResult) {
                $("#refTable").html(partialViewResult);
            });
        });
    });
</script>

You'll need to add the fields I have omitted. I've used a <button> instead of submit buttons because you don't have a form (I don't see one in your markup) and you just need them to trigger javascript on the client side.

The HolidayPartialView gets rendered into html and the jquery done callback inserts that html fragment into the refTable div.

HolidayController Update action

[HttpGet]
public ActionResult Calendar(int year)
{
    var dates = new List<DateTime>() { /* values based on year */ };
    HolidayViewModel model = new HolidayViewModel {
        Dates = dates
    };
    return PartialView("HolidayPartialView", model);
}

This controller action takes the year parameter and returns a list of dates using a strongly-typed view model instead of the ViewBag.

view model

public class HolidayViewModel
{
    IEnumerable<DateTime> Dates { get; set; }
}

HolidayPartialView.csthml

@model Your.Namespace.HolidayViewModel;

<table class="tblHoliday">
    @foreach(var date in Model.Dates)
    {
        <tr><td>@date.ToString("MM/dd/yyyy")</td></tr>
    }
</table>

This is the stuff that gets inserted into your div.

"Cloning" row or column vectors

You can use

np.tile(x,3).reshape((4,3))

tile will generate the reps of the vector

and reshape will give it the shape you want

Windows- Pyinstaller Error "failed to execute script " When App Clicked

In case anyone doesn't get results from the other answers, I fixed a similar problem by:

  1. adding --hidden-import flags as needed for any missing modules

  2. cleaning up the associated folders and spec files:

rmdir /s /q dist

rmdir /s /q build

del /s /q my_service.spec

  1. Running the commands for installation as Administrator

See :hover state in Chrome Developer Tools

In case it helps, this seems to be easier in the latest Chrome (47.0.2526.106):

Inspect element and then click on the three white dots in the left gutter:
click on the three white dots

Then choose the desired element state from this dropdown:
this dropdown

How to check visibility of software keyboard in Android?

After understanding some of the issues with different resolutions, I decided to use a relative size. As I noticed the difference between visible and hidden states is about 30%. So I decided to replace 128 PX with 0.3.

And I added this class listener to notify of any change.

Here is my version

import android.app.*;
import android.graphics.*;
import android.view.*;

public class SoftKeyboardState {
  public static final int HIDDEN = 0, VISIBLE = 1;
  private OnKeyboardStateChangedListener listener;
  private View decorView;

  public SoftKeyboardState(Activity activity) {
    this.decorView = activity.findViewById(android.R.id.content);
    initKeyboardListener();
  }

  private void initKeyboardListener() {
    decorView.getViewTreeObserver().addOnGlobalLayoutListener(
      new ViewTreeObserver.OnGlobalLayoutListener(){
        private final Rect windowVisibleDisplayFrame = new Rect();
        private int lastVisibleDecorViewHeight;

        @Override
        public void onGlobalLayout() {
          decorView.getWindowVisibleDisplayFrame(windowVisibleDisplayFrame);
          final int visibleDecorViewHeight = windowVisibleDisplayFrame.height();

          if (lastVisibleDecorViewHeight != 0) {
            if ((lastVisibleDecorViewHeight > visibleDecorViewHeight) && (lastVisibleDecorViewHeight / visibleDecorViewHeight >= 0.3f)) {
              // visible
              if (listener != null)listener.onKeyboardStateChanged(VISIBLE);
            } else if ((lastVisibleDecorViewHeight < visibleDecorViewHeight) && (visibleDecorViewHeight / lastVisibleDecorViewHeight >= 0.3f)) {
              // hidden
              if (listener != null)listener.onKeyboardStateChanged(HIDDEN);
            }
          }
          lastVisibleDecorViewHeight = visibleDecorViewHeight;
        }
      });
  }

  public void setOnKeyboardStateChangedListener(OnKeyboardStateChangedListener listener) {
    this.listener = listener;
  }

  public interface OnKeyboardStateChangedListener {
    public void onKeyboardStateChanged(int state);
  }
}

What characters are allowed in an email address?

Watch out! There is a bunch of knowledge rot in this thread (stuff that used to be true and now isn't).

To avoid false-positive rejections of actual email addresses in the current and future world, and from anywhere in the world, you need to know at least the high-level concept of RFC 3490, "Internationalizing Domain Names in Applications (IDNA)". I know folks in US and A often aren't up on this, but it's already in widespread and rapidly increasing use around the world (mainly the non-English dominated parts).

The gist is that you can now use addresses like mason@??.com and wildwezyr@fahrvergnügen.net. No, this isn't yet compatible with everything out there (as many have lamented above, even simple qmail-style +ident addresses are often wrongly rejected). But there is an RFC, there's a spec, it's now backed by the IETF and ICANN, and--more importantly--there's a large and growing number of implementations supporting this improvement that are currently in service.

I didn't know much about this development myself until I moved back to Japan and started seeing email addresses like hei@??.ca and Amazon URLs like this:

http://www.amazon.co.jp/????????-???????-??????????/b/ref=topnav_storetab_e?ie=UTF8&node=3210981

I know you don't want links to specs, but if you rely solely on the outdated knowledge of hackers on Internet forums, your email validator will end up rejecting email addresses that non-English-speaking users increasingly expect to work. For those users, such validation will be just as annoying as the commonplace brain-dead form that we all hate, the one that can't handle a + or a three-part domain name or whatever.

So I'm not saying it's not a hassle, but the full list of characters "allowed under some/any/none conditions" is (nearly) all characters in all languages. If you want to "accept all valid email addresses (and many invalid too)" then you have to take IDN into account, which basically makes a character-based approach useless (sorry), unless you first convert the internationalized email addresses (dead since September 2015, used to be like this—a working alternative is here) to Punycode.

After doing that you can follow (most of) the advice above.

SQL: How to to SUM two values from different tables

you can also try this in sql-server !!

select a.city,a.total + b.total as mytotal from [dbo].[cash] a join [dbo].[cheque] b on a.city=b.city 

demo

or try using sum,union

select sum(total)  as mytotal,city
from
(
    select * from cash union
    select * from cheque
) as vij
group by city 

How to set dropdown arrow in spinner?

Attach a Spinner Style using Java Code:

First, you need to a layout file such as below:

<?xml version="1.0" encoding="utf-8"?><TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@android:id/text1"
style="?android:attr/spinnerDropDownItemStyle"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ellipsize="none"
android:minHeight="?android:attr/listPreferredItemHeight" />

Let us name it spinner_item.xml and place it inside res/layouts folder.

Next, Create a String ArrayList and put all the Spinner options inside it:

ArrayList<String> spinnerArray = new ArrayList<String>();
spinnerArray.add("Item No. 1");
spinnerArray.add("Item No. 2");
spinnerArray.add("Item No. 3");
spinnerArray.add("Item No. 4");

Finally, create the Spinner object and attach the style layout to it.

Spinner spinner = new Spinner(getActivity());
spinner.setTag("some_id");
ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_spinner_dropdown_item, spinnerArray);                  spinnerArrayAdapter.setDropDownViewResource(R.layout.spinner_item);
spinner.setAdapter(spinnerArrayAdapter);

Note the Spinner(getActivity()) in the above line will be changed to Spinner(this) if you are writing this from inside Activity rather than from inside a fragment.

Thats all!


Attach a Spinner Style inside Android Layout File:

First, create a xml file the defines the style attribute (gradient_spinner.xml)

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item><layer-list>
        <item><shape>
            <gradient android:angle="90"  android:type="linear" />

            <stroke android:width="1dp" android:color="@color/colorBackground" />

            <corners android:radius="2dp" />

            <padding android:bottom="1dp" android:left="1dp" android:right="1dp" android:top="1dp" />
        </shape></item>
        <item android:right="5dp">
            <bitmap android:gravity="center_horizontal|right" android:src="@drawable/expand_icon">
            <padding android:right="2dp" />
        </bitmap>
        </item>
    </layer-list></item>

</selector>

Next, inside the style.xml file specify the style and call the gradient_spinner as background

<style name="spinner_style">
<item name="android:layout_width">match_parent</item>
<item name="android:layout_height">wrap_content</item>
<item name="android:background">@drawable/gradient_spinner</item>
<item name="android:layout_margin">1dp</item>
<item name="android:paddingLeft">5dp</item>
<item name="android:paddingRight">5dp</item>
<item name="android:paddingTop">5dp</item>
<item name="android:paddingBottom">5dp</item>
</style>

Finally, attach the above style to the Spinner:

<Spinner
   android:id="@+id/agent_id_spinner"
   android:layout_width="match_parent"
   android:layout_height="40dp"
   android:textSize="@dimen/title_text_view"
   style="@style/spinner_style"  />

Thats it!

Is there a PowerShell "string does not contain" cmdlet or syntax?

You can use the -notmatch operator to get the lines that don't have the characters you are interested in.

     Get-Content $FileName | foreach-object { 
     if ($_ -notmatch $arrayofStringsNotInterestedIn) { $) }

Ruby's File.open gives "No such file or directory - text.txt (Errno::ENOENT)" error

Next to being in the wrong directory I just tripped about another variant:

I had a File.open(my_file).each {|line| puts line} exploding but there was something by that name in the directory I was working in (ls in the command line showed the name). I checked with a File.exists?(my_file) which strangely returned false. Explanation: my_file was a symlink which target didn't exist anymore! Since File.exists? will follow a symlink it will say false though the link is still there.

How to save username and password in Git?

Attention: This method saves the credentials in plaintext on your PC's disk. Everyone on your computer can access it, e.g. malicious NPM modules.

Run

git config --global credential.helper store

then

git pull

provide a username and password and those details will then be remembered later. The credentials are stored in a file on the disk, with the disk permissions of "just user readable/writable" but still in plaintext.

If you want to change the password later

git pull

Will fail, because the password is incorrect, git then removes the offending user+password from the ~/.git-credentials file, so now re-run

git pull

to provide a new password so it works as earlier.

Programmatically generate video or animated GIF in Python?

I came upon PIL's ImageSequence module, which offers for a better (and more standard) GIF aninmation. I also use Tk's after() method this time, which is better than time.sleep().

from Tkinter import * 
from PIL import Image, ImageTk, ImageSequence

def stop(event):
  global play
  play = False
  exit() 

root = Tk()
root.bind("<Key>", stop) # Press any key to stop
GIFfile = {path_to_your_GIF_file}
im = Image.open(GIFfile); img = ImageTk.PhotoImage(im)
delay = im.info['duration'] # Delay used in the GIF file 
lbl = Label(image=img); lbl.pack() # Create a label where to display images
play = True;
while play:
  for frame in ImageSequence.Iterator(im):
    if not play: break 
    root.after(delay);
    img = ImageTk.PhotoImage(frame)
    lbl.config(image=img); root.update() # Show the new frame/image

root.mainloop()

Adding Lombok plugin to IntelliJ project

You need to Enable Annotation Processing on IntelliJ IDEA

> Settings > Build, Execution, Deployment > Compiler > Annotation Processors

enter image description here

ajax jquery simple get request

You can make AJAX requests to applications loaded from the SAME domain and SAME port.

Besides that, you should add dataType JSON if you want the result to be deserialized automatically.

$.ajax({
        url: "https://app.asana.com/-/api/0.1/workspaces/",
        type: 'GET',
        dataType: 'json', // added data type
        success: function(res) {
            console.log(res);
            alert(res);
        }
    });

http://api.jquery.com/jQuery.ajax/

Enabling WiFi on Android Emulator

As of now, with Revision 26.1.3 of the android emulator, it is finally possible on the image v8 of the API 25. If the emulator was created before you upgrade to the latest API 25 image, you need to wipe data or simply delete and recreate your image if you prefer.

Added support for Wi-Fi in some system images (currently only API level 25). An access point called "AndroidWifi" is available and Android automatically connects to it. Wi-Fi support can be disabled by running the emulator with the command line parameter -feature -Wifi.

from https://developer.android.com/studio/releases/emulator.html#26-1-3

How to fix Invalid AES key length?

Things to know in general:

  1. Key != Password
    • SecretKeySpec expects a key, not a password. See below
  2. It might be due to a policy restriction that prevents using 32 byte keys. See other answer on that

In your case

The problem is number 1: you are passing the password instead of the key.

AES only supports key sizes of 16, 24 or 32 bytes. You either need to provide exactly that amount or you derive the key from what you type in.

There are different ways to derive the key from a passphrase. Java provides a PBKDF2 implementation for such a purpose.

I used erickson's answer to paint a complete picture (only encryption, since the decryption is similar, but includes splitting the ciphertext):

SecureRandom random = new SecureRandom();
byte[] salt = new byte[16];
random.nextBytes(salt);

KeySpec spec = new PBEKeySpec("password".toCharArray(), salt, 65536, 256); // AES-256
SecretKeyFactory f = SecretKeyFactory.getInstance("PBKDF2WithHmacSHA1");
byte[] key = f.generateSecret(spec).getEncoded();
SecretKeySpec keySpec = new SecretKeySpec(key, "AES");

byte[] ivBytes = new byte[16];
random.nextBytes(ivBytes);
IvParameterSpec iv = new IvParameterSpec(ivBytes);

Cipher c = Cipher.getInstance("AES/CBC/PKCS5Padding");
c.init(Cipher.ENCRYPT_MODE, keySpec, iv);
byte[] encValue = c.doFinal(valueToEnc.getBytes());

byte[] finalCiphertext = new byte[encValue.length+2*16];
System.arraycopy(ivBytes, 0, finalCiphertext, 0, 16);
System.arraycopy(salt, 0, finalCiphertext, 16, 16);
System.arraycopy(encValue, 0, finalCiphertext, 32, encValue.length);

return finalCiphertext;

Other things to keep in mind:

  • Always use a fully qualified Cipher name. AES is not appropriate in such a case, because different JVMs/JCE providers may use different defaults for mode of operation and padding. Use AES/CBC/PKCS5Padding. Don't use ECB mode, because it is not semantically secure.
  • If you don't use ECB mode then you need to send the IV along with the ciphertext. This is usually done by prefixing the IV to the ciphertext byte array. The IV is automatically created for you and you can get it through cipherInstance.getIV().
  • Whenever you send something, you need to be sure that it wasn't altered along the way. It is hard to implement a encryption with MAC correctly. I recommend you to use an authenticated mode like CCM or GCM.

Error : ORA-01704: string literal too long

To solve this issue on my side, I had to use a combo of what was already proposed there

DECLARE
  chunk1 CLOB; chunk2 CLOB; chunk3 CLOB;
BEGIN
  chunk1 := 'very long literal part 1';
  chunk2 := 'very long literal part 2';
  chunk3 := 'very long literal part 3';

  INSERT INTO table (MY_CLOB)
  SELECT ( chunk1 || chunk2 || chunk3 ) FROM dual;
END;

Hope this helps.

Custom header to HttpClient request

Here is an answer based on that by Anubis (which is a better approach as it doesn't modify the headers for every request) but which is more equivalent to the code in the original question:

using Newtonsoft.Json;
...

var client = new HttpClient();
var httpRequestMessage = new HttpRequestMessage
    {
        Method = HttpMethod.Post,
        RequestUri = new Uri("https://api.clickatell.com/rest/message"),
        Headers = { 
            { HttpRequestHeader.Authorization.ToString(), "Bearer xxxxxxxxxxxxxxxxxxx" },
            { HttpRequestHeader.Accept.ToString(), "application/json" },
            { "X-Version", "1" }
        },
        Content = new StringContent(JsonConvert.SerializeObject(svm))
    };

var response = client.SendAsync(httpRequestMessage).Result;

How to apply a low-pass or high-pass filter to an array in Matlab?

You can design a lowpass Butterworth filter in runtime, using butter() function, and then apply that to the signal.

fc = 300; % Cut off frequency
fs = 1000; % Sampling rate

[b,a] = butter(6,fc/(fs/2)); % Butterworth filter of order 6
x = filter(b,a,signal); % Will be the filtered signal

Highpass and bandpass filters are also possible with this method. See https://www.mathworks.com/help/signal/ref/butter.html

Firing events on CSS class changes in jQuery

You can bind the DOMSubtreeModified event. I add an example here:

HTML

<div id="mutable" style="width:50px;height:50px;">sjdfhksfh<div>
<div>
  <button id="changeClass">Change Class</button>
</div>

JavaScript

$(document).ready(function() {
  $('#changeClass').click(function() {
    $('#mutable').addClass("red");
  });

  $('#mutable').bind('DOMSubtreeModified', function(e) {
      alert('class changed');
  });
});

http://jsfiddle.net/hnCxK/13/

Form/JavaScript not working on IE 11 with error DOM7011

I got the same console warning, when an ajax request was firing, so my form was also not working properly.

I disabled caching on the server's ajax call with the following response headers:

Cache-Control: no-cache, no-store, must-revalidate
Expires: -1
Pragma: no-cache

After this, the form was working. Refer to the server language (c#, php, java etc) you are using on how to add these response headers.

How to convert an iterator to a stream?

Great suggestion! Here's my reusable take on it:

public class StreamUtils {

    public static <T> Stream<T> asStream(Iterator<T> sourceIterator) {
        return asStream(sourceIterator, false);
    }

    public static <T> Stream<T> asStream(Iterator<T> sourceIterator, boolean parallel) {
        Iterable<T> iterable = () -> sourceIterator;
        return StreamSupport.stream(iterable.spliterator(), parallel);
    }
}

And usage (make sure to statically import asStream):

List<String> aPrefixedStrings = asStream(sourceIterator)
                .filter(t -> t.startsWith("A"))
                .collect(toList());

Disable validation of HTML5 form elements

you can add some javascript to surpress those obnoxious validation bubbles and add your own validators.

document.addEventListener('invalid', (function(){
    return function(e) {
      //prevent the browser from showing default error bubble / hint
      e.preventDefault();
      // optionally fire off some custom validation handler
      // myValidation();
    };
})(), true);

Difference between $.ajax() and $.get() and $.load()

Everyone explained the topic very well. There is one more point i would like add about .load() method.

As per Load document if you add suffixed selector in data url then it will not execute scripts in loading content.

Working Plunker

            $(document).ready(function(){
                $("#secondPage").load("mySecondHtmlPage.html #content");
            })

On the other hand, after removing selector in url, scripts in new content will run. Try this example

after removing #content in url in index.html file

            $(document).ready(function(){
                $("#secondPage").load("mySecondHtmlPage.html");
            })

There is no such in-built feature provided by other methods in discussion.

java.lang.IllegalAccessError: tried to access method

I was getting this error on a Spring Boot application where a @RestController ApplicationInfoResource had a nested class ApplicationInfo.

It seems the Spring Boot Dev Tools was using a different class loader.

The exception I was getting

2017-05-01 17:47:39.588 WARN 1516 --- [nio-8080-exec-9] .m.m.a.ExceptionHandlerExceptionResolver : Resolved exception caused by Handler execution: org.springframework.web.util.NestedServletException: Handler dispatch failed; nested exception is java.lang.IllegalAccessError: tried to access class com.gt.web.rest.ApplicationInfo from class com.gt.web.rest.ApplicationInfoResource$$EnhancerBySpringCGLIB$$59ce500c

Solution

I moved the nested class ApplicationInfo to a separate .java file and got rid of the problem.

How do I declare an array of undefined or no initial size?

This can be done by using a pointer, and allocating memory on the heap using malloc. Note that there is no way to later ask how big that memory block is. You have to keep track of the array size yourself.

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

int main(int argc, char** argv)
{
  /* declare a pointer do an integer */
  int *data; 
  /* we also have to keep track of how big our array is - I use 50 as an example*/
  const int datacount = 50;
  data = malloc(sizeof(int) * datacount); /* allocate memory for 50 int's */
  if (!data) { /* If data == 0 after the call to malloc, allocation failed for some reason */
    perror("Error allocating memory");
    abort();
  }
  /* at this point, we know that data points to a valid block of memory.
     Remember, however, that this memory is not initialized in any way -- it contains garbage.
     Let's start by clearing it. */
  memset(data, 0, sizeof(int)*datacount);
  /* now our array contains all zeroes. */
  data[0] = 1;
  data[2] = 15;
  data[49] = 66; /* the last element in our array, since we start counting from 0 */
  /* Loop through the array, printing out the values (mostly zeroes, but even so) */
  for(int i = 0; i < datacount; ++i) {
    printf("Element %d: %d\n", i, data[i]);
  }
}

That's it. What follows is a more involved explanation of why this works :)

I don't know how well you know C pointers, but array access in C (like array[2]) is actually a shorthand for accessing memory via a pointer. To access the memory pointed to by data, you write *data. This is known as dereferencing the pointer. Since data is of type int *, then *data is of type int. Now to an important piece of information: (data + 2) means "add the byte size of 2 ints to the adress pointed to by data".

An array in C is just a sequence of values in adjacent memory. array[1] is just next to array[0]. So when we allocate a big block of memory and want to use it as an array, we need an easy way of getting the direct adress to every element inside. Luckily, C lets us use the array notation on pointers as well. data[0] means the same thing as *(data+0), namely "access the memory pointed to by data". data[2] means *(data+2), and accesses the third int in the memory block.

How to set label size in Bootstrap

if you have

<span class="label label-default">New</span>

just add the style="font-size:XXpx;", ej.

<span class="label label-default" style="font-size:15px;">New</span>

Is there a css cross-browser value for "width: -moz-fit-content;"?

I use these:

.right {display:table; margin:-18px 0 0 auto;}
.center {display:table; margin:-18px auto 0 auto;}

How do I test a private function or a class that has private methods, fields or inner classes?

Today, I pushed a Java library to help testing private methods and fields. It has been designed with Android in mind, but it can really be used for any Java project.

If you got some code with private methods or fields or constructors, you can use BoundBox. It does exactly what you are looking for. Here below is an example of a test that accesses two private fields of an Android activity to test it:

@UiThreadTest
public void testCompute() {

    // Given
    boundBoxOfMainActivity = new BoundBoxOfMainActivity(getActivity());

    // When
    boundBoxOfMainActivity.boundBox_getButtonMain().performClick();

    // Then
    assertEquals("42", boundBoxOfMainActivity.boundBox_getTextViewMain().getText());
}

BoundBox makes it easy to test private/protected fields, methods and constructors. You can even access stuff that is hidden by inheritance. Indeed, BoundBox breaks encapsulation. It will give you access to all that through reflection, BUT everything is checked at compile time.

It is ideal for testing some legacy code. Use it carefully. ;)

https://github.com/stephanenicolas/boundbox

Regular Expressions: Is there an AND operator?

Look at this example:

We have 2 regexps A and B and we want to match both of them, so in pseudo-code it looks like this:

pattern = "/A AND B/"

It can be written without using the AND operator like this:

pattern = "/NOT (NOT A OR NOT B)/"

in PCRE:

"/(^(^A|^B))/"

regexp_match(pattern,data)

How to set the id attribute of a HTML element dynamically with angularjs (1.x)?

In case you came to this question but related to newer Angular version >= 2.0.

<div [id]="element.id"></div>

How to use SVN, Branch? Tag? Trunk?

I thinks there is two way about committing frequency:

  1. Commit very often, for each implemented method, small part of code, etc.
  2. Commit only completed parts of code, like modules, etc.

I prefer the first one - because using source control system is very useful not only for project or company, the first of all it's useful for the developer. For me the best feature is to roll back all code while searching the best assigned task implementation.

What does += mean in Python?

it means "append "THIS" to the current value"

example:

a = "hello"; a += " world";

printing a now will output: "hello world"

How to apply color in Markdown?

I have started using Markdown to post some of my documents to an internal web site for in-house users. It is an easy way to have a document shared but not able to be edited by the viewer.

So, this marking of text in color is “Great”. I have use several like this and works wonderful.

<span style="color:blue">some *This is Blue italic.* text</span>

Turns into This is Blue italic.

And

<span style="color:red">some **This is Red Bold.** text</span>

Turns into This is Red Bold.

I love the flexibility and ease of use.

Installing a local module using npm?

Since asked and answered by the same person, I'll add a npm link as an alternative.

from docs:

This is handy for installing your own stuff, so that you can work on it and test it iteratively without having to continually rebuild.

cd ~/projects/node-bloggy  # go into the dir of your main project
npm link ../node-redis     # link the dir of your dependency

[Edit] As of NPM 2.0, you can declare local dependencies in package.json

"dependencies": {
    "bar": "file:../foo/bar"
  }

How to hide image broken Icon using only CSS/HTML?

in case you like to keep/need the image as a placeholder, you could change the opacity to 0 with an onerror and some CSS to set the image size. This way you will not see the broken link, but the page loads as normal.

<img src="<your-image-link->" onerror="this.style.opacity='0'" />

img {
    width: 75px;
    height: 100px;
}

Changing SQL Server collation to case insensitive from case sensitive?

You can do that but the changes will affect for new data that is inserted on the database. On the long run follow as suggested above.

Also there are certain tricks you can override the collation, such as parameters for stored procedures or functions, alias data types, and variables are assigned the default collation of the database. To change the collation of an alias type, you must drop the alias and re-create it.

You can override the default collation of a literal string by using the COLLATE clause. If you do not specify a collation, the literal is assigned the database default collation. You can use DATABASEPROPERTYEX to find the current collation of the database.

You can override the server, database, or column collation by specifying a collation in the ORDER BY clause of a SELECT statement.

android.widget.Switch - on/off event listener?

Define your XML layout:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.neoecosystem.samplex.SwitchActivity">

    <Switch
        android:id="@+id/myswitch"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content" />

</RelativeLayout> 

Then create an Activity

public class SwitchActivity extends ActionBarActivity implements CompoundButton.OnCheckedChangeListener {

    Switch mySwitch = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_switch);


        mySwitch = (Switch) findViewById(R.id.myswitch);
        mySwitch.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            // do something when check is selected
        } else {
            //do something when unchecked
        }
    }

    ****
}

======== For below API 14 use SwitchCompat =========

XML

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="com.neoecosystem.samplex.SwitchActivity">

    <android.support.v7.widget.SwitchCompat
        android:id="@+id/myswitch"
        android:layout_height="wrap_content"
        android:layout_width="wrap_content" />

</RelativeLayout>

Activity

public class SwitchActivity extends ActionBarActivity implements CompoundButton.OnCheckedChangeListener {

    SwitchCompat mySwitch = null;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_switch);


        mySwitch = (SwitchCompat) findViewById(R.id.myswitch);
        mySwitch.setOnCheckedChangeListener(this);
    }

    @Override
    public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
        if (isChecked) {
            // do something when checked is selected
        } else {
            //do something when unchecked
        }
    }
   *****
}

Purpose of #!/usr/bin/python3 shebang

Actually the determination of what type of file a file is very complicated, so now the operating system can't just know. It can make lots of guesses based on -

  • extension
  • UTI
  • MIME

But the command line doesn't bother with all that, because it runs on a limited backwards compatible layer, from when that fancy nonsense didn't mean anything. If you double click it sure, a modern OS can figure that out- but if you run it from a terminal then no, because the terminal doesn't care about your fancy OS specific file typing APIs.

Regarding the other points. It's a convenience, it's similarly possible to run

python3 path/to/your/script

If your python isn't in the path specified, then it won't work, but we tend to install things to make stuff like this work, not the other way around. It doesn't actually matter if you're under *nix, it's up to your shell whether to consider this line because it's a shellcode. So for example you can run bash under Windows.

You can actually ommit this line entirely, it just mean the caller will have to specify an interpreter. Also don't put your interpreters in nonstandard locations and then try to call scripts without providing an interpreter.

Getting request URL in a servlet

The getRequestURL() omits the port when it is 80 while the scheme is http, or when it is 443 while the scheme is https.

So, just use getRequestURL() if all you want is obtaining the entire URL. This does however not include the GET query string. You may want to construct it as follows then:

StringBuffer requestURL = request.getRequestURL();
if (request.getQueryString() != null) {
    requestURL.append("?").append(request.getQueryString());
}
String completeURL = requestURL.toString();

ERROR 1452: Cannot add or update a child row: a foreign key constraint fails

This helped me out after reading @Mr-Faizan's and other answers.

Untick the 'Enable foreign key checks'

in phpMyAdmin and hit the query. I don't know about WorkBench but the other answers might help you out.

Twitter Bootstrap button click to toggle expand/collapse text section above button

Elaborating a bit more on Taylor Gautier's reply (sorry, I dont have enough reputation to add a comment), I'd reply to Dean Richardson on how to do what he wanted, without any additional JS code. Pure CSS.

You would replace his .btn with the following:

<a class="btn showdetails" data-toggle="collapse" data-target="#viewdetails"></a>

And add a small CSS for when the content is displayed:

.in.collapse+a.btn.showdetails:before { 
    content:'Hide details «';
}
.collapse+a.btn.showdetails:before { 
    content:'Show details »'; 
}

Here is his modified example

What are the proper permissions for an upload folder with PHP/Apache?

I would go with Ryan's answer if you really want to do this.

In general on a *nix environment, you always want to err on giving away as little permissions as possible.

9 times out of 10, 755 is the ideal permission for this - as the only user with the ability to modify the files will be the webserver. Change this to 775 with your ftp user in a group if you REALLY need to change this.

Since you're new to php by your own admission, here's a helpful link for improving the security of your upload service: move_uploaded_file

jQuery - determine if input element is textbox or select list

You could do this:

if( ctrl[0].nodeName.toLowerCase() === 'input' ) {
    // it was an input
}

or this, which is slower, but shorter and cleaner:

if( ctrl.is('input') ) {
    // it was an input
}

If you want to be more specific, you can test the type:

if( ctrl.is('input:text') ) {
    // it was an input
}

How to pass a user / password in ansible command

I used the command

ansible -i inventory example -m ping -u <your_user_name> --ask-pass

And it will ask for your password.

For anyone who gets the error:

to use the 'ssh' connection type with passwords, you must install the sshpass program

On MacOS, you can follow below instructions to install sshpass:

  1. Download the Source Code
  2. Extract it and cd into the directory
  3. ./configure
  4. sudo make install

Is it possible to run .APK/Android apps on iPad/iPhone devices?

It is not natively possible to run Android application under iOS (which powers iPhone, iPad, iPod, etc.)

This is because both runtime stacks use entirely different approaches. Android runs Dalvik (a "variant of Java") bytecode packaged in APK files while iOS runs Compiled (from Obj-C) code from IPA files. Excepting time/effort/money and litigations (!), there is nothing inherently preventing an Android implementation on Apple hardware, however.

It looks to package a small Dalvik VM with each application and targeted towards developers.

See iPhoDroid:

Looks to be a dual-boot solution for 2G/3G jailbroken devices. Very little information available, but there are some YouTube videos.

See iAndroid:

iAndroid is a new iOS application for jailbroken devices that simulates the Android operating system experience on the iPhone or iPod touch. While it’s still very far from completion, the project is taking shape.

I am not sure the approach(es) it uses to enable this: it could be emulation or just a simulation (e.g. "looks like"). The requirement of being jailbroken makes it sound like emulation might be used ..

See BlueStacks, per the Holo Dev's comment:

It looks to be an "Android App Player" for OS X (and Windows). However, afaik, it does not [currently] target iOS devices ..

YMMV

Jquery: Checking to see if div contains text, then action

Here's a vanilla Javascript solution in 2020:

const fieldItem = document.querySelector('#field .field-item')
fieldItem.innerText === 'someText' ? fieldItem.classList.add('red') : '';

Installing Oracle Instant Client

If you want to use SQL Server Management Studio, you want to install the full Oracle client, not the Instant Client. The full Oracle client is on the same download page as the Oracle database. Assuming that you are installing on a 64-bit version of Windows, I expect you want the "Oracle Database 11g Release 2 Client (11.2.0.1.0) for Microsoft Windows (x64)" download. This is several hundred MB rather than a couple of MB for the Instant Client.

How can I plot separate Pandas DataFrames as subplots?

You can see e.gs. in the documentation demonstrating joris answer. Also from the documentation, you could also set subplots=True and layout=(,) within the pandas plot function:

df.plot(subplots=True, layout=(1,2))

You could also use fig.add_subplot() which takes subplot grid parameters such as 221, 222, 223, 224, etc. as described in the post here. Nice examples of plot on pandas data frame, including subplots, can be seen in this ipython notebook.

How to get array keys in Javascript?

The question is pretty old, but nowadays you can use forEach, which is efficient and will retain the keys as numbers:

let keys = widthRange.map((v,k) => k).filter(i=>i!==undefined))

This loops through widthRange and makes a new array with the value of the keys, and then filters out all sparce slots by only taking the values that are defined.

(Bad idea, but for thorughness: If slot 0 was always empty, that could be shortened to filter(i=>i) or filter(Boolean)

And, it may be less efficient, but the numbers can be cast with let keys = Object.keys(array).map(i=>i*1)

CSS media query to target iPad and iPad only?

<html>
<head>
    <title>orientation and device detection in css3</title>

    <link rel="stylesheet" media="all and (max-device-width: 480px) and (orientation:portrait)" href="iphone-portrait.css" />
    <link rel="stylesheet" media="all and (max-device-width: 480px) and (orientation:landscape)" href="iphone-landscape.css" />
    <link rel="stylesheet" media="all and (device-width: 768px) and (device-height: 1024px) and (orientation:portrait)" href="ipad-portrait.css" />
    <link rel="stylesheet" media="all and (device-width: 768px) and (device-height: 1024px) and (orientation:landscape)" href="ipad-landscape.css" />
    <link rel="stylesheet" media="all and (device-width: 800px) and (device-height: 1184px) and (orientation:portrait)" href="htcdesire-portrait.css" />
    <link rel="stylesheet" media="all and (device-width: 800px) and (device-height: 390px) and (orientation:landscape)" href="htcdesire-landscape.css" />
    <link rel="stylesheet" media="all and (min-device-width: 1025px)" href="desktop.css" />

</head>
<body>
    <div id="iphonelandscape">iphone landscape</div>
    <div id="iphoneportrait">iphone portrait</div>
    <div id="ipadlandscape">ipad landscape</div>
    <div id="ipadportrait">ipad portrait</div>
    <div id="htcdesirelandscape">htc desire landscape</div>
    <div id="htcdesireportrait">htc desire portrait</div>
    <div id="desktop">desktop</div>
    <script type="text/javascript">
        function res() { document.write(screen.width + ', ' + screen.height); }
        res();
    </script>
</body>
</html>

DOM element to corresponding vue.js component

In Vue.js 2 Inside a Vue Instance or Component:

  • Use this.$el to get the HTMLElement the instance/component was mounted to

From an HTMLElement:

  • Use .__vue__ from the HTMLElement
    • E.g. var vueInstance = document.getElementById('app').__vue__;

Having a VNode in a variable called vnode you can:

  • use vnode.elm to get the element that VNode was rendered to
  • use vnode.context to get the VueComponent instance that VNode's component was declared (this usually returns the parent component, but may surprise you when using slots.
  • use vnode.componentInstance to get the Actual VueComponent instance that VNode is about

Source, literally: vue/flow/vnode.js.

Runnable Demo:

_x000D_
_x000D_
Vue.config.productionTip = false; // disable developer version warning
console.log('-------------------')

Vue.component('my-component', {
  template: `<input>`,
  mounted: function() {
    console.log('[my-component] is mounted at element:', this.$el);
  }
});

Vue.directive('customdirective', {
  bind: function (el, binding, vnode) {
    console.log('[DIRECTIVE] My Element is:', vnode.elm);
    console.log('[DIRECTIVE] My componentInstance is:', vnode.componentInstance);
    console.log('[DIRECTIVE] My context is:', vnode.context);
    // some properties, such as $el, may take an extra tick to be set, thus you need to...
    Vue.nextTick(() => console.log('[DIRECTIVE][AFTER TICK] My context is:', vnode.context.$el))
  }
})

new Vue({
  el: '#app',
  mounted: function() {
    console.log('[ROOT] This Vue instance is mounted at element:', this.$el);
    
    console.log('[ROOT] From the element to the Vue instance:', document.getElementById('app').__vue__);
    console.log('[ROOT] Vue component instance of my-component:', document.querySelector('input').__vue__);
  }
})
_x000D_
<script src="https://unpkg.com/[email protected]/dist/vue.min.js"></script>

<h1>Open the browser's console</h1>
<div id="app">
  <my-component v-customdirective=""></my-component>
</div>
_x000D_
_x000D_
_x000D_

Section vs Article HTML5

In the W3 wiki page about structuring HTML5, it says:

<section>: Used to either group different articles into different purposes or subjects, or to define the different sections of a single article.

And then displays an image that I cleaned up:

enter image description here

It also describes how to use the <article> tag (from same W3 link above):

<article> is related to <section>, but is distinctly different. Whereas <section> is for grouping distinct sections of content or functionality, <article> is for containing related individual standalone pieces of content, such as individual blog posts, videos, images or news items. Think of it this way - if you have a number of items of content, each of which would be suitable for reading on their own, and would make sense to syndicate as separate items in an RSS feed, then <article> is suitable for marking them up.

In our example, <section id="main"> contains blog entries. Each blog entry would be suitable for syndicating as an item in an RSS feed, and would make sense when read on its own, out of context, therefore <article> is perfect for them:

<section id="main">
    <article>
      <!-- first blog post -->
    </article>

    <article>
      <!-- second blog post  -->
    </article>

    <article>
      <!-- third blog post -->
    </article>
</section>

Simple huh? Be aware though that you can also nest sections inside articles, where it makes sense to do so. For example, if each one of these blog posts has a consistent structure of distinct sections, then you could put sections inside your articles as well. It could look something like this:

<article>
  <section id="introduction">
  </section>

  <section id="content">
  </section>

  <section id="summary">
  </section>
</article>

Can someone explain how to append an element to an array in C programming?

For some people which might still see this question, there is another way on how to append another array element(s) in C. You can refer to this blog which shows a C code on how to append another element in your array.

But you can also use memcpy() function, to append element(s) of another array. You can use memcpy()like this:

#include <stdio.h>
#include <string.h>

int main(void)
{

int first_array[10] = {45, 2, 48, 3, 6};
int scnd_array[] = {8, 14, 69, 23, 5};

// 5 is the number of the elements which are going to be appended
memcpy(a + 5, b, 5 * sizeof(int));

// loop through and print all the array
for (i = 0; i < 10; i++) {
    printf("%d\n", a[i]);
  }

}

What does "to stub" mean in programming?

This phrase is almost certainly an analogy with a phase in house construction — "stubbing out" plumbing. During construction, while the walls are still open, the rough plumbing is put in. This is necessary for the construction to continue. Then, when everything around it is ready enough, one comes back and adds faucets and toilets and the actual end-product stuff. (See for example How to Install a Plumbing Stub-Out.)

When you "stub out" a function in programming, you build enough of it to work around (for testing or for writing other code). Then, you come back later and replace it with the full implementation.

Disable and enable buttons in C#

In your button1_click function you are using '==' for button2.Enabled == true;

This should be button2.Enabled = true;

PDF Editing in PHP?

If you are taking a 'fill in the blank' approach, you can precisely position text anywhere you want on the page. So it's relatively easy (if not a bit tedious) to add the missing text to the document. For example with Zend Framework:

<?php
require_once 'Zend/Pdf.php';

$pdf = Zend_Pdf::load('blank.pdf');
$page = $pdf->pages[0];
$font = Zend_Pdf_Font::fontWithName(Zend_Pdf_Font::FONT_HELVETICA);
$page->setFont($font, 12);
$page->drawText('Hello world!', 72, 720);
$pdf->save('zend.pdf');

If you're trying to replace inline content, such as a "[placeholder string]," it gets much more complicated. While it's technically possible to do, you're likely to mess up the layout of the page.

A PDF document is comprised of a set of primitive drawing operations: line here, image here, text chunk there, etc. It does not contain any information about the layout intent of those primitives.

error LNK2038: mismatch detected for '_MSC_VER': value '1600' doesn't match value '1700' in CppFile1.obj

for each project in your solution make sure that

Properties > Config. Properties > General > Platform Toolset

is one for all of them, v100 for visual studio 2010, v110 for visual studio 2012

you also may be working on v100 from visual studio 2012

How to set up datasource with Spring for HikariCP?

This last error is caused by the library SLF4J not being found. HikariCP has two dependencies: slf4j and javassist. BTW, HikariDataSource does have a default constructor and does not need HikariConfig, see this link. So that was never the problem.

javax.net.ssl.SSLHandshakeException: Received fatal alert: handshake_failure

Issue resolved.!!! Below are the solutions.

For Java 6: Add below jars into {JAVA_HOME}/jre/lib/ext. 1. bcprov-ext-jdk15on-154.jar 2. bcprov-jdk15on-154.jar

Add property into {JAVA_HOME}/jre/lib/security/java.security security.provider.1=org.bouncycastle.jce.provider.BouncyCastleProvider

Java 7:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce-7-download-432124.html

Java 8:download jar from below link and add to {JAVA_HOME}/jre/lib/security http://www.oracle.com/technetwork/java/javase/downloads/jce8-download-2133166.html

Issue is that it is failed to decrypt 256 bits of encryption.

powershell is missing the terminator: "

In your script, why are you using single quotes around the variables? These will not be expanded. Use double quotes for variable expansion or just the variable names themselves.

unzipRelease –Src '$ReleaseFile' -Dst '$Destination'

to

unzipRelease –Src "$ReleaseFile" -Dst "$Destination"

How to allow download of .json file with ASP.NET

  1. Navigate to C:\Users\username\Documents\IISExpress\config
  2. Open applicationhost.config with Visual Studio or your favorite text-editor.
  3. Search for the word mimeMap, you should find lots of 'em.
  4. Add the following line to the top of the list: .

Python FileNotFound

try block should be around open. Not around prompt.

while True:
    prompt = input("\n Hello to Sudoku valitator,"
    "\n \n Please type in the path to your file and press 'Enter': ")
    try:
        sudoku = open(prompt, 'r').readlines()
    except FileNotFoundError:
        print("Wrong file or file path")
    else:
        break

How to initialize a struct in accordance with C programming language standards

In (ANSI) C99, you can use a designated initializer to initialize a structure:

MY_TYPE a = { .flag = true, .value = 123, .stuff = 0.456 };

Edit: Other members are initialized as zero: "Omitted field members are implicitly initialized the same as objects that have static storage duration." (https://gcc.gnu.org/onlinedocs/gcc/Designated-Inits.html)

Python read next()

You don't need to read the next line, you are iterating through the lines. lines is a list (an array), and for line in lines is iterating over it. Every time you are finished with one you move onto the next line. If you want to skip to the next line just continue out of the current loop.

filne = "D:/testtube/testdkanimfilternode.txt"
f = open(filne, 'r+')

lines = f.readlines() # get all lines as a list (array)

# Iterate over each line, printing each line and then move to the next
for line in lines:
    print line

f.close()

Difference between Build Solution, Rebuild Solution, and Clean Solution in Visual Studio?

The one major thing I think people are leaving out is that Build and Clean are both tasks that are performed based on Visual Studio's knowledge of your Project/Solution. I see a lot of complaining that Clean doesn't work or leaves leftover files or is not trustworthy, when in fact, the reasons you say it isn't trustworthy actually makes it more trustworthy.

Clean will only remove (clean) files and/or directories that Visual Studio or the compiler themselves have in fact created. If you copy your own files or files/folder structures get created from an outside tool or source, then Visual Studio doesn't "know they exist" and therefore, should not touch them.

Can you imagine if the Clean operation basically performed a "del *.*" ? This could be catastrophic.

Build performs a compile on changed or necessary projects.

Rebuild performs a compile regardless of change or what's necessary.

Clean removes files/folders it has created in the past, but leaves anything that it didn't have anything to do with, initially.

I hope this elaborates a bit and helps.

iOS 7 - Failing to instantiate default view controller

Setup the window manually,

- (void)applicationDidBecomeActive:(UIApplication *)application
{
    if (!application.keyWindow.rootViewController) 
     {
        UIStoryboard *storyboard = [UIStoryboard storyboardWithName:@"MainStoryboard" bundle:nil];

        UIViewController *myViewController= [storyboard instantiateViewControllerWithIdentifier:@"myViewController identifier"];

         application.keyWindow.rootViewController = myViewController;
     }
}

Python function overloading

The @overload decorator was added with type hints (PEP 484).

While this doesn't change the behaviour of Python, it does make it easier to understand what is going on, and for mypy to detect errors.

See: Type hints and PEP 484

How can I use inverse or negative wildcards when pattern matching in a unix/linux shell?

If you want to avoid the mem cost of using the exec command, I believe you can do better with xargs. I think the following is a more efficient alternative to

find foo -type f ! -name '*Music*' -exec cp {} bar \; # new proc for each exec



find . -maxdepth 1 -name '*Music*' -prune -o -print0 | xargs -0 -i cp {} dest/

Is there anything like .NET's NotImplementedException in Java?

No there isn't and it's probably not there, because there are very few valid uses for it. I would think twice before using it. Also, it is indeed easy to create yourself.

Please refer to this discussion about why it's even in .NET.

I guess UnsupportedOperationException comes close, although it doesn't say the operation is just not implemented, but unsupported even. That could imply no valid implementation is possible. Why would the operation be unsupported? Should it even be there? Interface segregation or Liskov substitution issues maybe?

If it's work in progress I'd go for ToBeImplementedException, but I've never caught myself defining a concrete method and then leave it for so long it makes it into production and there would be a need for such an exception.

Sql server - log is full due to ACTIVE_TRANSACTION

Here is what I ended up doing to work around the error.

First, I set up the database recovery model as SIMPLE. More information here.

Then, by deleting some old files I was able to make 5GB of free space which gave the log file more space to grow.

I reran the DELETE statement sucessfully without any warning.

I thought that by running the DELETE statement the database would inmediately become smaller thus freeing space in my hard drive. But that was not true. The space freed after a DELETE statement is not returned to the operating system inmediatedly unless you run the following command:

DBCC SHRINKDATABASE (MyDb, 0);
GO

More information about that command here.

Checkbox value true/false

Checkboxes can be really weird in JS. You're best off checking for the presence of the checked attribute. (I've had older jQuery versions return true even if checked is set to 'false'.) Once you've determined that something is checked then you can get the value from the value attribute.

Accessing the logged-in user in a template

{{ app.user.username|default('') }}

Just present login username for example, filter function default('') should be nice when user is NOT login by just avoid annoying error message.

Current date and time as string

Non C++11 solution: With the <ctime> header, you could use strftime. Make sure your buffer is large enough, you wouldn't want to overrun it and wreak havoc later.

#include <iostream>
#include <ctime>

int main ()
{
  time_t rawtime;
  struct tm * timeinfo;
  char buffer[80];

  time (&rawtime);
  timeinfo = localtime(&rawtime);

  strftime(buffer,sizeof(buffer),"%d-%m-%Y %H:%M:%S",timeinfo);
  std::string str(buffer);

  std::cout << str;

  return 0;
}

is python capable of running on multiple cores?

Python threads cannot take advantage of many cores. This is due to an internal implementation detail called the GIL (global interpreter lock) in the C implementation of python (cPython) which is almost certainly what you use.

The workaround is the multiprocessing module http://www.python.org/dev/peps/pep-0371/ which was developed for this purpose.

Documentation: http://docs.python.org/library/multiprocessing.html

(Or use a parallel language.)

How can I wrap or break long text/word in a fixed width span?

By default a span is an inline element... so that's not the default behavior.

You can make the span behave that way by adding display: block; to your CSS.

span {
    display: block;
    width: 100px;
}

How to start nginx via different port(other than 80)

If you are on windows then below port related server settings are present in file nginx.conf at < nginx installation path >/conf folder.

server {
    listen       80;
    server_name  localhost;
....

Change the port number and restart the instance.

Capture key press without placing an input element on the page?

jQuery also has an excellent implementation that's incredibly easy to use. Here's how you could implement this functionality across browsers:

$(document).keypress(function(e){
    var checkWebkitandIE=(e.which==26 ? 1 : 0);
    var checkMoz=(e.which==122 && e.ctrlKey ? 1 : 0);

    if (checkWebkitandIE || checkMoz) $("body").append("<p>ctrl+z detected!</p>");
});

Tested in IE7,Firefox 3.6.3 & Chrome 4.1.249.1064

Another way of doing this is to use the keydown event and track the event.keyCode. However, since jQuery normalizes keyCode and charCode using event.which, their spec recommends using event.which in a variety of situations:

$(document).keydown(function(e){
if (e.keyCode==90 && e.ctrlKey)
    $("body").append("<p>ctrl+z detected!</p>");
});