Programs & Examples On #Fork

The `fork()` function is the Unix/Linux/POSIX way of creating a new process by duplicating the calling process.

fork: retry: Resource temporarily unavailable

Another possibility is too many threads. We just ran into this error message when running a test harness against an app that uses a thread pool. We used

watch -n 5 -d "ps -eL <java_pid> | wc -l"

to watch the ongoing count of Linux native threads running within the given Java process ID. After this hit about 1,000 (for us--YMMV), we started getting the error message you mention.

Forking / Multi-Threaded Processes | Bash

Based on what you all shared I was able to put this together:

#!/usr/bin/env bash

VAR1="192.168.1.20 192.168.1.126 192.168.1.36"

for a in $VAR1; do { ssh -t -t $a -l Administrator "sudo softwareupdate -l"; } & done;
WAITPIDS="$WAITPIDS "$!;...; wait $WAITPIDS
echo "Script has finished"

Exit 1

This lists all the updates on the mac on three machines at once. Later on I used it to perform a software update for all machines when i CAT my ipaddress.txt

How to make child process die after parent exits?

I managed to do a portable, non-polling solution with 3 processes by abusing terminal control and sessions.

The trick is:

  • process A is started
  • process A creates a pipe P (and never reads from it)
  • process A forks into process B
  • process B creates a new session
  • process B allocates a virtual terminal for that new session
  • process B installs SIGCHLD handler to die when the child exits
  • process B sets a SIGPIPE handler
  • process B forks into process C
  • process C does whatever it needs (e.g. exec()s the unmodified binary or runs whatever logic)
  • process B writes to pipe P (and blocks that way)
  • process A wait()s on process B and exits when it dies

That way:

  • if process A dies: process B gets a SIGPIPE and dies
  • if process B dies: process A's wait() returns and dies, process C gets a SIGHUP (because when the session leader of a session with a terminal attached dies, all processes in the foreground process group get a SIGHUP)
  • if process C dies: process B gets a SIGCHLD and dies, so process A dies

Shortcomings:

  • process C can't handle SIGHUP
  • process C will be run in a different session
  • process C can't use session/process group API because it'll break the brittle setup
  • creating a terminal for every such operation is not the best idea ever

Differences between fork and exec

The use of fork and exec exemplifies the spirit of UNIX in that it provides a very simple way to start new processes.

The fork call basically makes a duplicate of the current process, identical in almost every way. Not everything is copied over (for example, resource limits in some implementations) but the idea is to create as close a copy as possible.

The new process (child) gets a different process ID (PID) and has the PID of the old process (parent) as its parent PID (PPID). Because the two processes are now running exactly the same code, they can tell which is which by the return code of fork - the child gets 0, the parent gets the PID of the child. This is all, of course, assuming the fork call works - if not, no child is created and the parent gets an error code.

The exec call is a way to basically replace the entire current process with a new program. It loads the program into the current process space and runs it from the entry point.

So, fork and exec are often used in sequence to get a new program running as a child of a current process. Shells typically do this whenever you try to run a program like find - the shell forks, then the child loads the find program into memory, setting up all command line arguments, standard I/O and so forth.

But they're not required to be used together. It's perfectly acceptable for a program to fork itself without execing if, for example, the program contains both parent and child code (you need to be careful what you do, each implementation may have restrictions). This was used quite a lot (and still is) for daemons which simply listen on a TCP port and fork a copy of themselves to process a specific request while the parent goes back to listening.

Similarly, programs that know they're finished and just want to run another program don't need to fork, exec and then wait for the child. They can just load the child directly into their process space.

Some UNIX implementations have an optimized fork which uses what they call copy-on-write. This is a trick to delay the copying of the process space in fork until the program attempts to change something in that space. This is useful for those programs using only fork and not exec in that they don't have to copy an entire process space.

If the exec is called following fork (and this is what happens mostly), that causes a write to the process space and it is then copied for the child process.

Note that there is a whole family of exec calls (execl, execle, execve and so on) but exec in context here means any of them.

The following diagram illustrates the typical fork/exec operation where the bash shell is used to list a directory with the ls command:

+--------+
| pid=7  |
| ppid=4 |
| bash   |
+--------+
    |
    | calls fork
    V
+--------+             +--------+
| pid=7  |    forks    | pid=22 |
| ppid=4 | ----------> | ppid=7 |
| bash   |             | bash   |
+--------+             +--------+
    |                      |
    | waits for pid 22     | calls exec to run ls
    |                      V
    |                  +--------+
    |                  | pid=22 |
    |                  | ppid=7 |
    |                  | ls     |
    V                  +--------+
+--------+                 |
| pid=7  |                 | exits
| ppid=4 | <---------------+
| bash   |
+--------+
    |
    | continues
    V

The difference between fork(), vfork(), exec() and clone()

in fork(), either child or parent process will execute based on cpu selection.. But in vfork(), surely child will execute first. after child terminated, parent will execute.

How to use execvp()

In cpp, you need to pay special attention to string types when using execvp:

#include <iostream>
#include <string>
#include <cstring>
#include <stdio.h>
#include <unistd.h>
using namespace std;

const size_t MAX_ARGC = 15; // 1 command + # of arguments
char* argv[MAX_ARGC + 1]; // Needs +1 because of the null terminator at the end
// c_str() converts string to const char*, strdup converts const char* to char*
argv[0] = strdup(command.c_str());

// start filling up the arguments after the first command
size_t arg_i = 1;
while (cin && arg_i < MAX_ARGC) {
    string arg;
    cin >> arg;
    if (arg.empty()) {
        argv[arg_i] = nullptr;
        break;
    } else {
        argv[arg_i] = strdup(arg.c_str());
    }
    ++arg_i;
}

// Run the command with arguments
if (execvp(command.c_str(), argv) == -1) {
    // Print error if command not found
    cerr << "command '" << command << "' not found\n";
}

Reference: execlp?execvp?????

What is the closest thing Windows has to fork()?

I certainly don't know the details on this because I've never done it it, but the native NT API has a capability to fork a process (the POSIX subsystem on Windows needs this capability - I'm not sure if the POSIX subsystem is even supported anymore).

A search for ZwCreateProcess() should get you some more details - for example this bit of information from Maxim Shatskih:

The most important parameter here is SectionHandle. If this parameter is NULL, the kernel will fork the current process. Otherwise, this parameter must be a handle of the SEC_IMAGE section object created on the EXE file before calling ZwCreateProcess().

Though note that Corinna Vinschen indicates that Cygwin found using ZwCreateProcess() still unreliable:

Iker Arizmendi wrote:

> Because the Cygwin project relied solely on Win32 APIs its fork
> implementation is non-COW and inefficient in those cases where a fork
> is not followed by exec.  It's also rather complex. See here (section
> 5.6) for details:
>  
> http://www.redhat.com/support/wpapers/cygnus/cygnus_cygwin/architecture.html

This document is rather old, 10 years or so. While we're still using Win32 calls to emulate fork, the method has changed noticably. Especially, we don't create the child process in the suspended state anymore, unless specific datastructes need a special handling in the parent before they get copied to the child. In the current 1.5.25 release the only case for a suspended child are open sockets in the parent. The upcoming 1.7.0 release will not suspend at all.

One reason not to use ZwCreateProcess was that up to the 1.5.25 release we're still supporting Windows 9x users. However, two attempts to use ZwCreateProcess on NT-based systems failed for one reason or another.

It would be really nice if this stuff would be better or at all documented, especially a couple of datastructures and how to connect a process to a subsystem. While fork is not a Win32 concept, I don't see that it would be a bad thing to make fork easier to implement.

Redirecting exec output to a buffer or file

You could also use the linux sh command and pass it a command that includes the redirection:

string cmd = "/bin/ls > " + filepath;

execl("/bin/sh", "sh", "-c", cmd.c_str(), 0);

fork() and wait() with two child processes

brilliant example Jonathan Leffler, to make your code work on SLES, I needed to add an additional header to allow the pid_t object :)

#include <sys/types.h>

How to make parent wait for all child processes to finish?

pid_t child_pid, wpid;
int status = 0;

//Father code (before child processes start)

for (int id=0; id<n; id++) {
    if ((child_pid = fork()) == 0) {
        //child code
        exit(0);
    }
}

while ((wpid = wait(&status)) > 0); // this way, the father waits for all the child processes 

//Father code (After all child processes end)

wait waits for a child process to terminate, and returns that child process's pid. On error (eg when there are no child processes), -1 is returned. So, basically, the code keeps waiting for child processes to finish, until the waiting errors out, and then you know they are all finished.

fork() child and parent processes

It is printing twice because you are calling printf twice, once in the execution of your program and once in the fork. Try taking your fork() out of the printf call.

How to kill a child process by the parent process?

Try something like this:

#include <signal.h>

pid_t child_pid = -1 ; //Global

void kill_child(int sig)
{
    kill(child_pid,SIGKILL);
}

int main(int argc, char *argv[])
{
    signal(SIGALRM,(void (*)(int))kill_child);
    child_pid = fork();
    if (child_pid > 0) {
     /*PARENT*/
        alarm(30);
        /*
         * Do parent's tasks here.
         */
        wait(NULL);
    }
    else if (child_pid == 0){
     /*CHILD*/
        /*
         * Do child's tasks here.
         */
    }
}

Example of waitpid() in use?

Syntax of waitpid():

pid_t waitpid(pid_t pid, int *status, int options);

The value of pid can be:

  • < -1: Wait for any child process whose process group ID is equal to the absolute value of pid.
  • -1: Wait for any child process.
  • 0: Wait for any child process whose process group ID is equal to that of the calling process.
  • > 0: Wait for the child whose process ID is equal to the value of pid.

The value of options is an OR of zero or more of the following constants:

  • WNOHANG: Return immediately if no child has exited.
  • WUNTRACED: Also return if a child has stopped. Status for traced children which have stopped is provided even if this option is not specified.
  • WCONTINUED: Also return if a stopped child has been resumed by delivery of SIGCONT.

For more help, use man waitpid.

How to use shared memory with Linux in C

Here is an example for shared memory :

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/ipc.h>
#include <sys/shm.h>

#define SHM_SIZE 1024  /* make it a 1K shared memory segment */

int main(int argc, char *argv[])
{
    key_t key;
    int shmid;
    char *data;
    int mode;

    if (argc > 2) {
        fprintf(stderr, "usage: shmdemo [data_to_write]\n");
        exit(1);
    }

    /* make the key: */
    if ((key = ftok("hello.txt", 'R')) == -1) /*Here the file must exist */ 
{
        perror("ftok");
        exit(1);
    }

    /*  create the segment: */
    if ((shmid = shmget(key, SHM_SIZE, 0644 | IPC_CREAT)) == -1) {
        perror("shmget");
        exit(1);
    }

    /* attach to the segment to get a pointer to it: */
    data = shmat(shmid, NULL, 0);
    if (data == (char *)(-1)) {
        perror("shmat");
        exit(1);
    }

    /* read or modify the segment, based on the command line: */
    if (argc == 2) {
        printf("writing to segment: \"%s\"\n", argv[1]);
        strncpy(data, argv[1], SHM_SIZE);
    } else
        printf("segment contains: \"%s\"\n", data);

    /* detach from the segment: */
    if (shmdt(data) == -1) {
        perror("shmdt");
        exit(1);
    }

    return 0;
}

Steps :

  1. Use ftok to convert a pathname and a project identifier to a System V IPC key

  2. Use shmget which allocates a shared memory segment

  3. Use shmat to attache the shared memory segment identified by shmid to the address space of the calling process

  4. Do the operations on the memory area

  5. Detach using shmdt

SQL: Group by minimum value in one field while selecting distinct rows

This does it simply:

select t2.id,t2.record_date,t2.other_cols 
from (select ROW_NUMBER() over(partition by id order by record_date)as rownum,id,record_date,other_cols from MyTable)t2 
where t2.rownum = 1

Add a CSS border on hover without moving the element

add margin:-1px; which reduces 1px to each side. or if you need only for side you can do margin-left:-1px etc.

How to redirect stderr and stdout to different files in the same line in script?

Just add them in one line command 2>> error 1>> output

However, note that >> is for appending if the file already has data. Whereas, > will overwrite any existing data in the file.

So, command 2> error 1> output if you do not want to append.

Just for completion's sake, you can write 1> as just > since the default file descriptor is the output. so 1> and > is the same thing.

So, command 2> error 1> output becomes, command 2> error > output

Unexpected 'else' in "else" error

I would suggest to read up a bit on the syntax. See here.

if (dsnt<0.05) {
  wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE) 
} else if (dst<0.05) {
    wilcox.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)
} else 
  t.test(distance[result=='nt'],distance[result=='t'],alternative=c("two.sided"),paired=TRUE)

How to get terminal's Character Encoding

locale command with no arguments will print the values of all of the relevant environment variables except for LANGUAGE.

For current encoding:

locale charmap

For available locales:

locale -a

For available encodings:

locale -m

Use cases for the 'setdefault' dict method

[Edit] Very wrong! The setdefault would always trigger long_computation, Python being eager.

Expanding on Tuttle's answer. For me the best use case is cache mechanism. Instead of:

if x not in memo:
   memo[x]=long_computation(x)
return memo[x]

which consumes 3 lines and 2 or 3 lookups, I would happily write :

return memo.setdefault(x, long_computation(x))

Get all files and directories in specific path fast

Maybe it will be helpfull for you. You could use "DirectoryInfo.EnumerateFiles" method and handle UnauthorizedAccessException as you need.

using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        DirectoryInfo diTop = new DirectoryInfo(@"d:\");
        try
        {
            foreach (var fi in diTop.EnumerateFiles())
            {
                try
                {
                    // Display each file over 10 MB; 
                    if (fi.Length > 10000000)
                    {
                        Console.WriteLine("{0}\t\t{1}", fi.FullName, fi.Length.ToString("N0"));
                    }
                }
                catch (UnauthorizedAccessException UnAuthTop)
                {
                    Console.WriteLine("{0}", UnAuthTop.Message);
                }
            }

            foreach (var di in diTop.EnumerateDirectories("*"))
            {
                try
                {
                    foreach (var fi in di.EnumerateFiles("*", SearchOption.AllDirectories))
                    {
                        try
                        {
                            // Display each file over 10 MB; 
                            if (fi.Length > 10000000)
                            {
                                Console.WriteLine("{0}\t\t{1}",  fi.FullName, fi.Length.ToString("N0"));
                            }
                        }
                        catch (UnauthorizedAccessException UnAuthFile)
                        {
                            Console.WriteLine("UnAuthFile: {0}", UnAuthFile.Message);
                        }
                    }
                }
                catch (UnauthorizedAccessException UnAuthSubDir)
                {
                    Console.WriteLine("UnAuthSubDir: {0}", UnAuthSubDir.Message);
                }
            }
        }
        catch (DirectoryNotFoundException DirNotFound)
        {
            Console.WriteLine("{0}", DirNotFound.Message);
        }
        catch (UnauthorizedAccessException UnAuthDir)
        {
            Console.WriteLine("UnAuthDir: {0}", UnAuthDir.Message);
        }
        catch (PathTooLongException LongPath)
        {
            Console.WriteLine("{0}", LongPath.Message);
        }
    }
}

-XX:MaxPermSize with or without -XX:PermSize

By playing with parameters as -XX:PermSize and -Xms you can tune the performance of - for example - the startup of your application. I haven't looked at it recently, but a few years back the default value of -Xms was something like 32MB (I think), if your application required a lot more than that it would trigger a number of cycles of fill memory - full garbage collect - increase memory etc until it had loaded everything it needed. This cycle can be detrimental for startup performance, so immediately assigning the number required could improve startup.

A similar cycle is applied to the permanent generation. So tuning these parameters can improve startup (amongst others).

WARNING The JVM has a lot of optimization and intelligence when it comes to allocating memory, dividing eden space and older generations etc, so don't do things like making -Xms equal to -Xmx or -XX:PermSize equal to -XX:MaxPermSize as it will remove some of the optimizations the JVM can apply to its allocation strategies and therefor reduce your application performance instead of improving it.

As always: make non-trivial measurements to prove your changes actually improve performance overall (for example improving startup time could be disastrous for performance during use of the application)

Tokenizing strings in C

I've made some string functions in order to split values, by using less pointers as I could because this code is intended to run on PIC18F processors. Those processors does not handle really good with pointers when you have few free RAM available:

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

char POSTREQ[255] = "pwd=123456&apply=Apply&d1=88&d2=100&pwr=1&mpx=Internal&stmo=Stereo&proc=Processor&cmp=Compressor&ip1=192&ip2=168&ip3=10&ip4=131&gw1=192&gw2=168&gw3=10&gw4=192&pt=80&lic=&A=A";

int findchar(char *string, int Start, char C) {
    while((string[Start] != 0)) { Start++; if(string[Start] == C) return Start; }
    return -1;
}

int findcharn(char *string, int Times, char C) {
   int i = 0, pos = 0, fnd = 0;

    while(i < Times) {
       fnd = findchar(string, pos, C);
        if(fnd < 0) return -1;
        if(fnd > 0) pos = fnd;
       i++;
   }
   return fnd;
}

void mid(char *in, char *out, int start, int end) {
    int i = 0;
    int size = end - start;

    for(i = 0; i < size; i++){
        out[i] = in[start + i + 1];
    }
    out[size] = 0;
}

void getvalue(char *out, int index) {
    mid(POSTREQ, out, findcharn(POSTREQ, index, '='), (findcharn(POSTREQ, index, '&') - 1));
}

void main() {
   char n_pwd[7];
   char n_d1[7];

   getvalue(n_d1, 1);

   printf("Value: %s\n", n_d1);
} 

jQuery Validation plugin: validate check box

You had several issues with your code.

1) Missing a closing brace, }, within your rules.

2) In this case, there is no reason to use a function for the required rule. By default, the plugin can handle checkbox and radio inputs just fine, so using true is enough. However, this will simply do the same logic as in your original function and verify that at least one is checked.

3) If you also want only a maximum of two to be checked, then you'll need to apply the maxlength rule.

4) The messages option was missing the rule specification. It will work, but the one custom message would apply to all rules on the same field.

5) If a name attribute contains brackets, you must enclose it within quotes.

DEMO: http://jsfiddle.net/K6Wvk/

$(document).ready(function () {

    $('#formid').validate({ // initialize the plugin
        rules: {
            'test[]': {
                required: true,
                maxlength: 2
            }
        },
        messages: {
            'test[]': {
                required: "You must check at least 1 box",
                maxlength: "Check no more than {0} boxes"
            }
        }
    });

});

history.replaceState() example?

According to MDN History doc
There is clearly said that second argument is for future used not for now. You are right that second argument is deal with web-page title but currently it's ignored by all major browser.

Firefox currently ignores this parameter, although it may use it in the future. Passing the empty string here should be safe against future changes to the method. Alternatively, you could pass a short title for the state to which you're moving.

<script> tag vs <script type = 'text/javascript'> tag

<script> is HTML 5.

<script type='text/javascript'> is HTML 4.x (and XHTML 1.x).

<script language="javascript"> is HTML 3.2.

Is it different for different webservers?

No.

when I did an offline javascript test, i realised that i need the <script type = 'text/javascript'> tag.

That isn't the case. Something else must have been wrong with your test case.

Python integer incrementing with ++

Here there is an explanation: http://bytes.com/topic/python/answers/444733-why-there-no-post-pre-increment-operator-python

However the absence of this operator is in the python philosophy increases consistency and avoids implicitness.

In addition, this kind of increments are not widely used in python code because python have a strong implementation of the iterator pattern plus the function enumerate.

How to show data in a table by using psql command line interface?

Newer versions: (from 8.4 - mentioned in release notes)

TABLE mytablename;

Longer but works on all versions:

SELECT * FROM mytablename;

You may wish to use \x first if it's a wide table, for readability.

For long data:

SELECT * FROM mytable LIMIT 10;

or similar.

For wide data (big rows), in the psql command line client, it's useful to use \x to show the rows in key/value form instead of tabulated, e.g.

 \x
SELECT * FROM mytable LIMIT 10;

Note that in all cases the semicolon at the end is important.

fetch from origin with deleted remote branches?

From http://www.gitguys.com/topics/adding-and-removing-remote-branches/

After someone deletes a branch from a remote repository, git will not automatically delete the local repository branches when a user does a git pull or git fetch. However, if the user would like to have all tracking branches removed from their local repository that have been deleted in a remote repository, they can type:

git remote prune origin

As a note, the -p param from git fetch -p actually means "prune".
Either way you chose, the non-existing remote branches will be deleted from your local repository.

Add Items to Columns in a WPF ListView

Solution With Less XAML and More C#

If you define the ListView in XAML:

<ListView x:Name="listView"/>

Then you can add columns and populate it in C#:

public Window()
{
    // Initialize
    this.InitializeComponent();

    // Add columns
    var gridView = new GridView();
    this.listView.View = gridView;
    gridView.Columns.Add(new GridViewColumn { 
        Header = "Id", DisplayMemberBinding = new Binding("Id") });
    gridView.Columns.Add(new GridViewColumn { 
        Header = "Name", DisplayMemberBinding = new Binding("Name") });

    // Populate list
    this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}

See definition of MyItem below.

Solution With More XAML and less C#

However, it's easier to define the columns in XAML (inside the ListView definition):

<ListView x:Name="listView">
    <ListView.View>
        <GridView>
            <GridViewColumn Header="Id" DisplayMemberBinding="{Binding Id}"/>
            <GridViewColumn Header="Name" DisplayMemberBinding="{Binding Name}"/>
        </GridView>
    </ListView.View>
</ListView>

And then just populate the list in C#:

public Window()
{
    // Initialize
    this.InitializeComponent();

    // Populate list
    this.listView.Items.Add(new MyItem { Id = 1, Name = "David" });
}

See definition of MyItem below.

MyItem Definition

MyItem is defined like this:

public class MyItem
{
    public int Id { get; set; }

    public string Name { get; set; }
}

How to import CSV file data into a PostgreSQL table?

Create table and have required columns that are used for creating table in csv file.

  1. Open postgres and right click on target table which you want to load & select import and Update the following steps in file options section

  2. Now browse your file in filename

  3. Select csv in format

  4. Encoding as ISO_8859_5

Now goto Misc. options and check header and click on import.

Perl regular expression (using a variable as a search string with Perl operator characters included)

Use \Q to autoescape any potentially problematic characters in your variable.

if($text_to_search =~ m/\Q$search_string/) print "wee";

How to clone git repository with specific revision/changeset?

# clone special tag/branch without history
git clone  --branch=<tag/branch> --depth=1 <repository>


# clone special revision with minimal histories
git clone --branch <branch> <repository> --shallow-since=yyyy-MM-ddTHH:mm:ss  # get the commit time
cd <dir>
git reset --hard <revision> 

you can't get a revision without histories if not set uploadpack.allowReachableSHA1InWant=true on server side, while you can create a tag for it and clone the special tag instead.

How to PUT a json object with an array using curl

Try using a single quote instead of double quotes along with -g

Following scenario worked for me

curl -g -d '{"collection":[{"NumberOfParcels":1,"Weight":1,"Length":1,"Width":1,"Height":1}]}" -H "Accept: application/json" -H "Content-Type: application/json" --user [email protected]:123456 -X POST  https://yoururl.com

WITH

curl -g -d "{'collection':[{'NumberOfParcels':1,'Weight':1,'Length':1,'Width':1,'Height':1}]}" -H "Accept: application/json" -H "Content-Type: application/json" --user [email protected]:123456 -X POST  https://yoururl.com

This especially resolved my error curl command error : bad url colon is first character

Sleep Command in T-SQL?

WAITFOR DELAY 'HH:MM:SS'

I believe the maximum time this can wait for is 23 hours, 59 minutes and 59 seconds.

Here's a Scalar-valued function to show it's use; the below function will take an integer parameter of seconds, which it then translates into HH:MM:SS and executes it using the EXEC sp_executesql @sqlcode command to query. Below function is for demonstration only, i know it's not fit for purpose really as a scalar-valued function! :-)

    CREATE FUNCTION [dbo].[ufn_DelayFor_MaxTimeIs24Hours]
    (
    @sec int
    )
    RETURNS
    nvarchar(4)
    AS
    BEGIN


    declare @hours int = @sec / 60 / 60
    declare @mins int = (@sec / 60) - (@hours * 60)
    declare @secs int = (@sec - ((@hours * 60) * 60)) - (@mins * 60)


    IF @hours > 23 
    BEGIN
    select @hours = 23
    select @mins = 59
    select @secs = 59
    -- 'maximum wait time is 23 hours, 59 minutes and 59 seconds.'
    END


    declare @sql nvarchar(24) = 'WAITFOR DELAY '+char(39)+cast(@hours as nvarchar(2))+':'+CAST(@mins as nvarchar(2))+':'+CAST(@secs as nvarchar(2))+char(39)


    exec sp_executesql @sql

    return ''
    END

IF you wish to delay longer than 24 hours, I suggest you use a @Days parameter to go for a number of days and wrap the function executable inside a loop... e.g..

    Declare @Days int = 5
    Declare @CurrentDay int = 1

    WHILE @CurrentDay <= @Days
    BEGIN

    --24 hours, function will run for 23 hours, 59 minutes, 59 seconds per run.
    [ufn_DelayFor_MaxTimeIs24Hours] 86400

    SELECT @CurrentDay = @CurrentDay + 1
    END

'any' vs 'Object'

Object is more restrictive than any. For example:

let a: any;
let b: Object;

a.nomethod(); // Transpiles just fine
b.nomethod(); // Error: Property 'nomethod' does not exist on type 'Object'.

The Object class does not have a nomethod() function, therefore the transpiler will generate an error telling you exactly that. If you use any instead you are basically telling the transpiler that anything goes, you are providing no information about what is stored in a - it can be anything! And therefore the transpiler will allow you to do whatever you want with something defined as any.

So in short

  • any can be anything (you can call any method etc on it without compilation errors)
  • Object exposes the functions and properties defined in the Object class.

How to create a label inside an <input> element?

When you start typing it will disappear.If empty it will appear again.

        <%= f.text_field :user_email,:value=>"",:placeholder => "Eg:[email protected]"%>

Simplest way...

SQL providerName in web.config

System.Data.SqlClient is the .NET Framework Data Provider for SQL Server. ie .NET library for SQL Server.

I don't know where providerName=SqlServer comes from. Could you be getting this confused with the provider keyword in your connection string? (I know I was :) )

In the web.config you should have the System.Data.SqlClient as the value of the providerName attribute. It is the .NET Framework Data Provider you are using.

<connectionStrings>
   <add 
      name="LocalSqlServer" 
      connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" 
      providerName="System.Data.SqlClient"
   />
</connectionStrings>

See http://msdn.microsoft.com/en-US/library/htw9h4z3(v=VS.80).aspx

Use of exit() function

You must add a line with #include <stdlib.h> to include that header file and exit must return a value so assign some integer in exit(any_integer).

Jquery split function

Try this. It uses the split function which is a core part of javascript, nothing to do with jQuery.

var parts = html.split(":-"),
    i, l
;
for (i = 0, l = parts.length; i < l; i += 2) {
    $("#" + parts[i]).text(parts[i + 1]);
}

gcc: undefined reference to

Are you mixing C and C++? One issue that can occur is that the declarations in the .h file for a .c file need to be surrounded by:

#if defined(__cplusplus)
  extern "C" {                 // Make sure we have C-declarations in C++ programs
#endif

and:

#if defined(__cplusplus)
  }
#endif

Note: if unable / unwilling to modify the .h file(s) in question, you can surround their inclusion with extern "C":

extern "C" {
#include <abc.h>
} //extern

Creating a simple configuration file and parser in C++

I was searching for a similar simple C++ config file parser and this tutorial website provided me with a basic yet working solution. Its quick and dirty soultion to get the job done.

myConfig.txt

gamma=2.8
mode  =  1
path = D:\Photoshop\Projects\Workspace\Images\

The following program reads the previous configuration file:

#include <iostream>
#include <fstream>
#include <algorithm>
#include <string>

int main()
{
    double gamma = 0;
    int mode = 0;
    std::string path;

    // std::ifstream is RAII, i.e. no need to call close
    std::ifstream cFile("myConfig.txt");
    if (cFile.is_open())
    {
        std::string line;
        while (getline(cFile, line)) 
        {
            line.erase(std::remove_if(line.begin(), line.end(), isspace),line.end());
            if (line[0] == '#' || line.empty()) continue;

            auto delimiterPos = line.find("=");
            auto name = line.substr(0, delimiterPos);
            auto value = line.substr(delimiterPos + 1);

            //Custom coding
            if (name == "gamma") gamma = std::stod(value);
            else if (name == "mode") mode = std::stoi(value);
            else if (name == "path") path = value;
        }
    }
    else 
    {
        std::cerr << "Couldn't open config file for reading.\n";
    }

    std::cout << "\nGamma=" << gamma;
    std::cout << "\nMode=" << mode;
    std::cout << "\nPath=" << path;
    std::getchar();
}

How to use clock() in C++

An alternative solution, which is portable and with higher precision, available since C++11, is to use std::chrono.

Here is an example:

#include <iostream>
#include <chrono>
typedef std::chrono::high_resolution_clock Clock;

int main()
{
    auto t1 = Clock::now();
    auto t2 = Clock::now();
    std::cout << "Delta t2-t1: " 
              << std::chrono::duration_cast<std::chrono::nanoseconds>(t2 - t1).count()
              << " nanoseconds" << std::endl;
}

Running this on ideone.com gave me:

Delta t2-t1: 282 nanoseconds

What's the scope of a variable initialized in an if statement?

you're executing this code from command line therefore if conditions is true and x is set. Compare:

>>> if False:
    y = 42


>>> y
Traceback (most recent call last):
  File "<pyshell#6>", line 1, in <module>
    y
NameError: name 'y' is not defined

Update multiple rows using select statement

Run a select to make sure it is what you want

SELECT t1.value AS NEWVALUEFROMTABLE1,t2.value AS OLDVALUETABLE2,*
FROM Table2 t2
INNER JOIN Table1 t1 on t1.ID = t2.ID

Update

UPDATE Table2
SET Value = t1.Value
FROM Table2 t2
INNER JOIN Table1 t1 on t1.ID = t2.ID

Also, consider using BEGIN TRAN so you can roll it back if needed, but make sure you COMMIT it when you are satisfied.

Android Fragments and animation

I'd highly suggest you use this instead of creating the animation file because it's a much better solution. Android Studio already provides default animation you can use without creating any new XML file. The animations' names are android.R.anim.slide_in_left and android.R.anim.slide_out_right and you can use them as follows:

fragmentTransaction.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right);

FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction fragmentTransaction = fragmentManager.beginTransaction();              
fragmentTransaction.setCustomAnimations(android.R.anim.slide_in_left, android.R.anim.slide_out_right);
fragmentManager.addOnBackStackChangedListener(this);
fragmentTransaction.replace(R.id.frame, firstFragment, "h");
fragmentTransaction.addToBackStack("h");
fragmentTransaction.commit();

Output:

enter image description here

git switch branch without discarding local changes

  • git stash to save your uncommited changes
  • git stash list to list your saved uncommited stashes
  • git stash apply stash@{x} where x can be 0,1,2..no of stashes that you have made

Switch statement: must default be the last case?

yes, this is valid, and under some circumstances it is even useful. Generally, if you don't need it, don't do it.

JSON to PHP Array using file_get_contents

You JSON is not a valid string as P. Galbraith has told you above.

and here is the solution for it.

<?php 
$json_url = "http://api.testmagazine.com/test.php?type=menu";
$json = file_get_contents($json_url);
$json=str_replace('},

]',"}

]",$json);
$data = json_decode($json);

echo "<pre>";
print_r($data);
echo "</pre>";
?>

Use this code it will work for you.

Should methods in a Java interface be declared with or without a public access modifier?

It's totally subjective. I omit the redundant public modifier as it seems like clutter. As mentioned by others - consistency is the key to this decision.

It's interesting to note that the C# language designers decided to enforce this. Declaring an interface method as public in C# is actually a compile error. Consistency is probably not important across languages though, so I guess this is not really directly relevant to Java.

How to convert xml into array in php?

Converting an XML string ($buffer) into a simplified array ignoring attributes and grouping child-elements with the same names:

function XML2Array(SimpleXMLElement $parent)
{
    $array = array();

    foreach ($parent as $name => $element) {
        ($node = & $array[$name])
            && (1 === count($node) ? $node = array($node) : 1)
            && $node = & $node[];

        $node = $element->count() ? XML2Array($element) : trim($element);
    }

    return $array;
}

$xml   = simplexml_load_string($buffer);
$array = XML2Array($xml);
$array = array($xml->getName() => $array);

Result:

Array
(
    [aaaa] => Array
        (
            [bbb] => Array
                (
                    [cccc] => Array
                        (
                            [dddd] => 
                            [eeee] => 
                        )

                )

        )

)

If you also want to have the attributes, they are available via JSON encoding/decoding of SimpleXMLElement. This is often the most easy quick'n'dirty solution:

$xml   = simplexml_load_string($buffer);
$array = json_decode(json_encode((array) $xml), true);
$array = array($xml->getName() => $array);

Result:

Array
(
    [aaaa] => Array
        (
            [@attributes] => Array
                (
                    [Version] => 1.0
                )

            [bbb] => Array
                (
                    [cccc] => Array
                        (
                            [dddd] => Array
                                (
                                    [@attributes] => Array
                                        (
                                            [Id] => id:pass
                                        )

                                )

                            [eeee] => Array
                                (
                                    [@attributes] => Array
                                        (
                                            [name] => hearaman
                                            [age] => 24
                                        )

                                )

                        )

                )

        )

)

Take note that all these methods only work in the namespace of the XML document.

Removing leading zeroes from a field in a SQL statement

If you want the query to return a 0 instead of a string of zeroes or any other value for that matter you can turn this into a case statement like this:

select CASE
      WHEN ColumnName = substring(ColumnName, patindex('%[^0]%',ColumnName), 10) 
       THEN '0'
      ELSE substring(ColumnName, patindex('%[^0]%',ColumnName), 10) 
      END

IntelliJ: Working on multiple projects

To Intellij IDEA 2019.2, F4 + click on module, click to + for add any project from your HDD, above this menu yo can edit the IDE with you create the project and more options, very easy

How does Tomcat find the HOME PAGE of my Web App?

In any web application, there will be a web.xml in the WEB-INF/ folder.

If you dont have one in your web app, as it seems to be the case in your folder structure, the default Tomcat web.xml is under TOMCAT_HOME/conf/web.xml

Either way, the relevant lines of the web.xml are

<welcome-file-list>
        <welcome-file>index.html</welcome-file>
        <welcome-file>index.htm</welcome-file>
        <welcome-file>index.jsp</welcome-file>
    </welcome-file-list>

so any file matching this pattern when found will be shown as the home page.

In Tomcat, a web.xml setting within your web app will override the default, if present.

Further Reading

How do I override the default home page loaded by Tomcat?

Can you call ko.applyBindings to bind a partial view?

I've managed to bind a custom model to an element at runtime. The code is here: http://jsfiddle.net/ZiglioNZ/tzD4T/457/

The interesting bit is that I apply the data-bind attribute to an element I didn't define:

    var handle = slider.slider().find(".ui-slider-handle").first();
    $(handle).attr("data-bind", "tooltip: viewModel.value");
    ko.applyBindings(viewModel.value, $(handle)[0]);

How can I switch to a tag/branch in hg?

Once you have cloned the repo, you have everything: you can then hg up branchname or hg up tagname to update your working copy.

UP: hg up is a shortcut of hg update, which also has hg checkout alias for people with git habits.

how do you insert null values into sql server

If you're using SSMS (or old school Enterprise Manager) to edit the table directly, press CTRL+0 to add a null.

Save Javascript objects in sessionStorage

Could you not 'stringify' your object...then use sessionStorage.setItem() to store that string representation of your object...then when you need it sessionStorage.getItem() and then use $.parseJSON() to get it back out?

Working example http://jsfiddle.net/pKXMa/

Finding element's position relative to the document

You can traverse the offsetParent up to the top level of the DOM.

function getOffsetLeft( elem )
{
    var offsetLeft = 0;
    do {
      if ( !isNaN( elem.offsetLeft ) )
      {
          offsetLeft += elem.offsetLeft;
      }
    } while( elem = elem.offsetParent );
    return offsetLeft;
}

How to set null to a GUID property

Is there a way to set my property as null or string.empty in order to restablish the field in the database as null.

No. Because it's non-nullable. If you want it to be nullable, you have to use Nullable<Guid> - if you didn't, there'd be no point in having Nullable<T> to start with. You've got a fundamental issue here - which you actually know, given your first paragraph. You've said, "I know if I want to achieve A, I must do B - but I want to achieve A without doing B." That's impossible by definition.

The closest you can get is to use one specific GUID to stand in for a null value - Guid.Empty (also available as default(Guid) where appropriate, e.g. for the default value of an optional parameter) being the obvious candidate, but one you've rejected for unspecified reasons.

Converting pfx to pem using openssl

You can use the OpenSSL Command line tool. The following commands should do the trick

openssl pkcs12 -in client_ssl.pfx -out client_ssl.pem -clcerts

openssl pkcs12 -in client_ssl.pfx -out root.pem -cacerts

If you want your file to be password protected etc, then there are additional options.

You can read the entire documentation here.

Convert Year/Month/Day to Day of Year in Python

DZinX's answer is a great answer for the question. I found this question and used DZinX's answer while looking for the inverse function: convert dates with the julian day-of-year into the datetimes.

I found this to work:

import datetime
datetime.datetime.strptime('1936-077T13:14:15','%Y-%jT%H:%M:%S')

>>>> datetime.datetime(1936, 3, 17, 13, 14, 15)

datetime.datetime.strptime('1936-077T13:14:15','%Y-%jT%H:%M:%S').timetuple().tm_yday

>>>> 77

Or numerically:

import datetime
year,julian = [1936,77]
datetime.datetime(year, 1, 1)+datetime.timedelta(days=julian -1)

>>>> datetime.datetime(1936, 3, 17, 0, 0)

Or with fractional 1-based jdates popular in some domains:

jdate_frac = (datetime.datetime(1936, 3, 17, 13, 14, 15)-datetime.datetime(1936, 1, 1)).total_seconds()/86400+1
display(jdate_frac)

>>>> 77.5515625

year,julian = [1936,jdate_frac]
display(datetime.datetime(year, 1, 1)+datetime.timedelta(days=julian -1))

>>>> datetime.datetime(1936, 3, 17, 13, 14, 15)

I'm not sure of etiquette around here, but I thought a pointer to the inverse functionality might be useful for others like me.

How can I list all foreign keys referencing a given table in SQL Server?

Also try.

EXEC sp_fkeys 'tableName', 'schemaName'

with sp_fkeys you may filter the result by not only pk table name and schema but also with fk table name and schema. link

Display / print all rows of a tibble (tbl_df)

i prefer to physically print my tables instead:

CONNECT_SERVER="https://196.168.1.1/"
CONNECT_API_KEY<-"hpphotosmartP9000:8273827"

data.frame = data.frame(1:1000, 1000:2)

connectServer <- Sys.getenv("CONNECT_SERVER")
apiKey <- Sys.getenv("CONNECT_API_KEY")

install.packages('print2print')

print2print::send2printer(connectServer, apiKey, data.frame)

Drop rows containing empty cells from a pandas DataFrame

There's a situation where the cell has white space, you can't see it, use

df['col'].replace('  ', np.nan, inplace=True)

to replace white space as NaN, then

df= df.dropna(subset=['col'])

ModelState.AddModelError - How can I add an error that isn't for a property?

I eventually stumbled upon an example of the usage I was looking for - to assign an error to the Model in general, rather than one of it's properties, as usual you call:

ModelState.AddModelError(string key, string errorMessage);

but use an empty string for the key:

ModelState.AddModelError(string.Empty, "There is something wrong with Foo.");

The error message will present itself in the <%: Html.ValidationSummary() %> as you'd expect.

Pass variable to function in jquery AJAX success callback

Just to share a similar problem I had in case it might help some one, I was using:

var NextSlidePage = $("bottomcontent" + Slide + ".html");

to make the variable for the load function, But I should have used:

var NextSlidePage = "bottomcontent" + Slide + ".html";

without the $( )

Don't know why but now it works! Thanks, finally i saw what was going wrong from this post!

Android Fragment handle back button press

in fragment class put this code for back event:

 rootView.setFocusableInTouchMode(true);
        rootView.requestFocus();
        rootView.setOnKeyListener( new OnKeyListener()
        {
            @Override
            public boolean onKey( View v, int keyCode, KeyEvent event )
            {
                if( keyCode == KeyEvent.KEYCODE_BACK )
                {
                    FragmentManager fragmentManager = getFragmentManager();
                    fragmentManager.beginTransaction()
                            .replace(R.id.frame_container, new Book_service_provider()).commit();

                    return true;
                }
                return false;
            }
        } );

How to pass data to view in Laravel?

For any one thinking it is really tedious in the case where you have tons of variables to pass to a view or you want the variables to be accessible to many views at the same, here is another way

In the controller, you define the variables you want to pass as global and you attribute the values to these variables.

Example global $variable; $variable = 1;

And now in the view, at the top, simply do

<?php global $variable;?>

Then you can now call your variable from any where in the view for example

{{$variable}}

hope this helps someone.

How to import large sql file in phpmyadmin

Ok you use PHPMyAdmin but sometimes the best way is through terminal:

  • Connect to database: mysql -h localhost -u root -p (switch root and localhost for user and database location)
  • Start import from dump: \. /path/to/your/file.sql
  • Go take a coffe and brag about yourself because you use terminal.

And that's it. Just remember if you are in a remote server, you must upload the .sql file to some folder.

Convert Object to JSON string

Also useful is Object.toSource() for debugging purposes, where you want to show the object and its properties for debugging purposes. This is a generic Javascript (not jQuery) function, however it only works in "modern" browsers.

How to make canvas responsive

The object-fit CSS property sets how the content of a replaced element, such as an img or video, should be resized to fit its container.

Magically, object fit also works on a canvas element. No JavaScript needed, and the canvas doesn't stretch, automatically fills to proportion.

canvas {
    width: 100%;
    object-fit: contain;
}

python numpy/scipy curve fitting

You'll first need to separate your numpy array into two separate arrays containing x and y values.

x = [1, 2, 3, 9]
y = [1, 4, 1, 3]

curve_fit also requires a function that provides the type of fit you would like. For instance, a linear fit would use a function like

def func(x, a, b):
    return a*x + b

scipy.optimize.curve_fit(func, x, y) will return a numpy array containing two arrays: the first will contain values for a and b that best fit your data, and the second will be the covariance of the optimal fit parameters.

Here's an example for a linear fit with the data you provided.

import numpy as np
from scipy.optimize import curve_fit

x = np.array([1, 2, 3, 9])
y = np.array([1, 4, 1, 3])

def fit_func(x, a, b):
    return a*x + b

params = curve_fit(fit_func, x, y)

[a, b] = params[0]

This code will return a = 0.135483870968 and b = 1.74193548387

Here's a plot with your points and the linear fit... which is clearly a bad one, but you can change the fitting function to obtain whatever type of fit you would like.

enter image description here

Request Monitoring in Chrome

You could use Fiddler which is a good free tool.

How to create a .NET DateTime from ISO 8601 format

Although MSDN says that "s" and "o" formats reflect the standard, they seem to be able to parse only a limited subset of it. Especially it is a problem if the string contains time zone specification. (Neither it does for basic ISO8601 formats, or reduced precision formats - however this is not exactly your case.) That is why I make use of custom format strings when it comes to parsing ISO8601. Currently my preferred snippet is:

static readonly string[] formats = { 
    // Basic formats
    "yyyyMMddTHHmmsszzz",
    "yyyyMMddTHHmmsszz",
    "yyyyMMddTHHmmssZ",
    // Extended formats
    "yyyy-MM-ddTHH:mm:sszzz",
    "yyyy-MM-ddTHH:mm:sszz",
    "yyyy-MM-ddTHH:mm:ssZ",
    // All of the above with reduced accuracy
    "yyyyMMddTHHmmzzz",
    "yyyyMMddTHHmmzz",
    "yyyyMMddTHHmmZ",
    "yyyy-MM-ddTHH:mmzzz",
    "yyyy-MM-ddTHH:mmzz",
    "yyyy-MM-ddTHH:mmZ",
    // Accuracy reduced to hours
    "yyyyMMddTHHzzz",
    "yyyyMMddTHHzz",
    "yyyyMMddTHHZ",
    "yyyy-MM-ddTHHzzz",
    "yyyy-MM-ddTHHzz",
    "yyyy-MM-ddTHHZ"
    };

public static DateTime ParseISO8601String ( string str )
{
    return DateTime.ParseExact ( str, formats, 
        CultureInfo.InvariantCulture, DateTimeStyles.None );
}

If you don't mind parsing TZ-less strings (I do), you can add an "s" line to greatly extend the number of covered format alterations.

python 2 instead of python 3 as the (temporary) default python?

Use python command to launch scripts, not shell directly. E.g.

  python2 /usr/bin/command

AFAIK this is the recommended method to workaround scripts with bad env interpreter line.

Running Node.js in apache?

No. NodeJS is not available as an Apache module in the way mod-perl and mod-php are, so it's not possible to run node "on top of" Apache. As hexist pointed out, it's possible to run node as a separate process and arrange communication between the two, but this is quite different to the LAMP stack you're already using.

As a replacement for Apache, node offers performance advantages if you have many simultaneous connections. There's also a huge ecosystem of modules for almost anything you can think of.

From your question, it's not clear if you need to dynamically generate pages on every request, or just generate new content periodically for caching and serving. If its the latter, you could use separate node task to generate content to a directory that Apache would serve, but again, that's quite different to PHP or Perl.

Node isn't the best way to serve static content. Nginx and Varnish are more effective at that. They can serve static content while Node handles the dynamic data.

If you're considering using node for a web application at all, Express should be high on your list. You could implement a web application purely in Node, but Express (and similar frameworks like Flatiron, Derby and Meteor) are designed to take a lot of the pain and tedium away. Although the Express documentation can seem a bit sparse at first, check out the screen casts which are still available here: http://expressjs.com/2x/screencasts.html They'll give you a good sense of what express offers and why it is useful. The github repository for ExpressJS also contains many good examples for everything from authentication to organizing your app.

Read a text file line by line in Qt

Since Qt 5.5 you can use QTextStream::readLineInto. It behaves similar to std::getline and is maybe faster as QTextStream::readLine, because it reuses the string:

QIODevice* device;
QTextStream in(&device);

QString line;
while (in.readLineInto(&line)) {
  // ...
}

jQuery $.ajax(), $.post sending "OPTIONS" as REQUEST_METHOD in Firefox

This PHP at the top of the responding script seems to work. (With Firefox 3.6.11. I have not yet done a lot of testing.)

header('Access-Control-Allow-Origin: *');
header('Access-Control-Allow-Methods: POST, GET, OPTIONS');
header('Access-Control-Max-Age: 1000');
if(array_key_exists('HTTP_ACCESS_CONTROL_REQUEST_HEADERS', $_SERVER)) {
    header('Access-Control-Allow-Headers: '
           . $_SERVER['HTTP_ACCESS_CONTROL_REQUEST_HEADERS']);
} else {
    header('Access-Control-Allow-Headers: *');
}

if("OPTIONS" == $_SERVER['REQUEST_METHOD']) {
    exit(0);
}

How can I delete using INNER JOIN with SQL Server?

You don't specify the tables for Company and Date, and you might want to fix that.

Standard SQL using MERGE:

MERGE WorkRecord2 T
   USING Employee S
      ON T.EmployeeRun = S.EmployeeNo
         AND Company = '1'
         AND Date = '2013-05-06'
WHEN MATCHED THEN DELETE;

The answer from Devart is also standard SQL, though incomplete. It should look more like this:

DELETE
  FROM WorkRecord2
  WHERE EXISTS ( SELECT *
                   FROM Employee S
                  WHERE S.EmployeeNo = WorkRecord2.EmployeeRun
                        AND Company = '1'
                        AND Date = '2013-05-06' );

The important thing to note about the above is it is clear the delete is targeting a single table, as enforced in the second example by requiring a scalar subquery.

For me, the various proprietary syntax answers are harder to read and understand. I guess the mindset for is best described in the answer by frans eilering, i.e. the person writing the code doesn't necessarily care about the person who will read and maintain the code.

Delete a database in phpMyAdmin

The delete / drop option in operations is not present in my version.

Go to CPanel -> MySQLDatabase (icon next to PhPMyAdmin) -> check the DB to be delete -> delete.

how to get the base url in javascript

var baseTags = document.getElementsByTagName("base");
var basePath = baseTags.length ? 
    baseTags[ 0 ].href.substr( location.origin.length, 999 ) : 
    "";

Good PHP ORM Library?

Doctrine is probably your best bet. Prior to Doctrine, DB_DataObject was essentially the only other utility that was open sourced.

How to change time in DateTime?

I have just come across this post because I had a similar issue whereby I wanted to set the time for an Entity Framework object in MVC that gets the date from a view (datepicker) so the time component is 00:00:00 but I need it to be the current time. Based on the answers in this post I came up with:

myEntity.FromDate += DateTime.Now.TimeOfDay;

Align nav-items to right side in bootstrap-4

Here and easy Example.

<!-- Navigation bar-->

<nav class="navbar navbar-toggleable-md bg-info navbar-inverse">
    <div class="container">
        <button class="navbar-toggler" data-toggle="collapse" data-target="#mainMenu">
            <span class="navbar-toggler-icon"></span>
            </button>
        <div class="collapse navbar-collapse" id="mainMenu">
            <div class="navbar-nav ml-auto " style="width:100%">
                <a class="nav-item nav-link active" href="#">Home</a>
                <a class="nav-item nav-link" href="#">About</a>
                <a class="nav-item nav-link" href="#">Training</a>
                <a class="nav-item nav-link" href="#">Contact</a>
            </div>
        </div>
    </div>
</nav>

How to use the COLLATE in a JOIN in SQL Server?

As a general rule, you can use Database_Default collation so you don't need to figure out which one to use. However, I strongly suggest reading Simons Liew's excellent article Understanding the COLLATE DATABASE_DEFAULT clause in SQL Server

SELECT *
  FROM [FAEB].[dbo].[ExportaComisiones] AS f
  JOIN [zCredifiel].[dbo].[optPerson] AS p
  ON (p.vTreasuryId = f.RFC) COLLATE Database_Default 

Ant: How to execute a command for each file in directory?

You can use the ant-contrib task "for" to iterate on the list of files separate by any delimeter, default delimeter is ",".

Following is the sample file which shows this:

<project name="modify-files" default="main" basedir=".">
    <taskdef resource="net/sf/antcontrib/antlib.xml"/>
    <target name="main">
        <for list="FileA,FileB,FileC,FileD,FileE" param="file">
          <sequential>
            <echo>Updating file: @{file}</echo>
            <!-- Do something with file here -->
          </sequential>
        </for>                         
    </target>
</project>

htaccess <Directory> deny from all

You cannot use the Directory directive in .htaccess. However if you create a .htaccess file in the /system directory and place the following in it, you will get the same result

#place this in /system/.htaccess as you had before
deny from all

How can I put a database under git (version control)?

  • Irmin
  • Flur.ee
  • Crux DB
  • TerminusDB

I have been looking for the same feature for Postgres (or SQL databases in general) for a while, but I found no tools to be suitable (simple and intuitive) enough. This is probably due to the binary nature of how data is stored. Klonio sounds ideal but looks dead. Noms DB looks interesting (and alive). Also take a look at Irmin (OCaml-based with Git-properties).

Though this doesn't answer the question in that it would work with Postgres, check out the Flur.ee database. It has a "time-travel" feature that allows you to query the data from an arbitrary point in time. I'm guessing it should be able to work with a "branching" model.

This database was recently being developed for blockchain-purposes. Due to the nature of blockchains, the data needs to be recorded in increments, which is exactly how git works. They are targeting an open-source release in Q2 2019.

Because each Fluree database is a blockchain, it stores the entire history of every transaction performed. This is part of how a blockchain ensures that information is immutable and secure.

Update: Also check out the Crux database, which can query across the time dimension of inserts, which you could see as 'versions'. Crux seems to be an open-source implementation of the highly appraised Datomic.

Crux is a bitemporal database that stores transaction time and valid time histories. While a [uni]temporal database enables "time travel" querying through the transactional sequence of database states from the moment of database creation to its current state, Crux also provides "time travel" querying for a discrete valid time axis without unnecessary design complexity or performance impact. This means a Crux user can populate the database with past and future information regardless of the order in which the information arrives, and make corrections to past recordings to build an ever-improving temporal model of a given domain.

Update II Check out Terminus DB: "Documentation for TerminusDB - an open-source graph database that stores data like git".

Remove x-axis label/text in chart.js

UPDATE chart.js 2.1 and above

var chart = new Chart(ctx, {
    ...
    options:{
        scales:{
            xAxes: [{
                display: false //this will remove all the x-axis grid lines
            }]
        }
    }
});


var chart = new Chart(ctx, {
    ...
    options: {
        scales: {
            xAxes: [{
                ticks: {
                    display: false //this will remove only the label
                }
            }]
        }
    }
});

Reference: chart.js documentation

Old answer (written when the current version was 1.0 beta) just for reference below:

To avoid displaying labels in chart.js you have to set scaleShowLabels : false and also avoid to pass the labels:

<script>
    var options = {
        ...
        scaleShowLabels : false
    };
    var lineChartData = {
        //COMMENT THIS LINE TO AVOID DISPLAYING THE LABELS
        //labels : ["1","2","3","4","5","6","7"],
        ... 
    }
    ...
</script>

How to install a specific version of Node on Ubuntu?

NOTE: you can use NVM software to do this in a more nodejs fashionway. However i got issues in one machine that didn't let me use NVM. So i have to look for an alternative ;-)

You can manually download and install.

go to nodejs > download > other releases http://nodejs.org/dist/

choose the version you are looking for http://nodejs.org/dist/v0.8.18/

choose distro files corresponding your environmment and download (take care of 32bits/64bits version). Example: http://nodejs.org/dist/v0.8.18/node-v0.8.18-linux-x64.tar.gz

Extract files and follow instructions on README.md :

To build:

Prerequisites (Unix only):

* Python 2.6 or 2.7
* GNU Make 3.81 or newer
* libexecinfo (FreeBSD and OpenBSD only)

Unix/Macintosh:

./configure
make
make install

If your python binary is in a non-standard location or has a non-standard name, run the following instead:

export PYTHON=/path/to/python
$PYTHON ./configure
make
make install

Windows:

vcbuild.bat

To run the tests:

Unix/Macintosh:

make test

Windows:

vcbuild.bat test

To build the documentation:

make doc

To read the documentation:

man doc/node.1

Maybe you want to (must to) move the folder to a more apropiate place like /usr/lib/nodejs/node-v0.8.18/ then create a Symbolic Lynk on /usr/bin to get acces to your install from anywhere.

sudo mv /extracted/folder/node-v0.8.18 /usr/lib/nodejs/node-v0.8.18
sudo ln -s /usr/lib/nodejs/node-v0.8.18/bin/node /usr/bin/node

And if you want different release in the same machine you can use debian alternatives. Proceed in the same way posted before to download a second release. For example the latest release.

http://nodejs.org/dist/latest/ -> http://nodejs.org/dist/latest/node-v0.10.28-linux-x64.tar.gz

Move to your favorite destination, the same of the rest of release you want to install.

sudo mv /extracted/folder/node-v0.10.28 /usr/lib/nodejs/node-v0.10.28

Follow instructions of the README.md file. Then update the alternatives, for each release you have dowload install the alternative with.

sudo update-alternatives    --install genname symlink  altern  priority  [--slave  genname  symlink altern]
          Add a group of alternatives  to  the  system.   genname  is  the
          generic  name  for  the  master link, symlink is the name of its
          symlink  in  the  alternatives  directory,  and  altern  is  the
          alternative being introduced for the master link.  The arguments
          after  --slave  are  the  generic  name,  symlink  name  in  the
          alternatives  directory  and alternative for a slave link.  Zero
          or more --slave options, each followed by three  arguments,  may
          be specified.

          If   the   master   symlink  specified  exists  already  in  the
          alternatives system’s records, the information supplied will  be
          added  as a new set of alternatives for the group.  Otherwise, a
          new group, set to  automatic  mode,  will  be  added  with  this
          information.   If  the group is in automatic mode, and the newly
          added alternatives’ priority is higher than any other  installed
          alternatives  for  this  group,  the symlinks will be updated to
          point to the newly added alternatives.

for example:

sudo update-alternatives --install /usr/bin/node node /usr/lib/nodejs/node-v0.10.28 0 --slave /usr/share/man/man1/node.1.gz node.1.gz /usr/lib/nodejs/node-v0.10.28/share/man/man1/node.1

Then you can use update-alternatives --config node to choose between any number of releases instaled in your machine.

How can I send emails through SSL SMTP with the .NET Framework?

If any doubt in this code, please ask your questions(Here for gmail Port number is 587)

// code to Send Mail 
// Add following Lines in your web.config file 
//               <system.net>
//                  <mailSettings>
//                    <smtp>
//                        <network host="smtp.gmail.com" port="587" userName="[email protected]" password="yyy"   defaultCredentials="false"/>
//                    </smtp>
//               </mailSettings>
//               </system.net>
// Add below lines in your config file inside appsetting tag <appsetting></appsetting>
//          <add key="emailFromAddress" value="[email protected]"/>
//       <add key="emailToAddress" value="[email protected]"/>
//        <add key="EmailSsl" value="true"/>

// Namespace Used

using System.Net.Mail;
     public static bool SendingMail(string subject, string content)
    {
       // getting the values from config file through c#
        string fromEmail = ConfigurationSettings.AppSettings["emailFromAddress"];
        string mailid = ConfigurationSettings.AppSettings["emailToAddress"];
        bool useSSL;
        if (ConfigurationSettings.AppSettings["EmailSsl"] == "true")
        {
            useSSL = true;
        }
        else
        {
            useSSL = false;
        }



        SmtpClient emailClient;
        MailMessage message;
        message = new MailMessage();
        message.From = new MailAddress(fromEmail);
        message.ReplyTo = new MailAddress(fromEmail);
        if (SetMailAddressCollection(message.To, mailid))
        {
            message.Subject = subject;
            message.Body = content;
            message.IsBodyHtml = true;
            emailClient = new SmtpClient();
            emailClient.EnableSsl = useSSL;
            emailClient.Send(message);
        }
        return true;
    }
    // if you are sending mail in group

    private static bool SetMailAddressCollection(MailAddressCollection toAddresses, string    mailId)
    {
        bool successfulAddressCreation = true;
        toAddresses.Add(new MailAddress(mailId));
        return successfulAddressCreation;
    }

Deleting rows with MySQL LEFT JOIN

DELETE FROM deadline where ID IN (
    SELECT d.ID FROM `deadline` d LEFT JOIN `job` ON deadline.job_id = job.job_id WHERE `status` =  'szamlazva' OR `status` = 'szamlazhato' OR `status` = 'fizetve' OR `status` = 'szallitva' OR `status` = 'storno');

I am not sure if that kind of sub query works in MySQL, but try it. I am assuming you have an ID column in your deadline table.

How to get a key in a JavaScript object by its value?

function extractKeyValue(obj, value) {
    return Object.keys(obj)[Object.values(obj).indexOf(value)];
}

Made for closure compiler to extract key name which will be unknown after compilation

More sexy version but using future Object.entries function

function objectKeyByValue (obj, val) {
  return Object.entries(obj).find(i => i[1] === val);
}

Getting unix timestamp from Date()

Use SimpleDateFormat class. Take a look on its javadoc: it explains how to use format switches.

How to create an array of 20 random bytes?

Create a Random object with a seed and get the array random by doing:

public static final int ARRAY_LENGTH = 20;

byte[] byteArray = new byte[ARRAY_LENGTH];
new Random(System.currentTimeMillis()).nextBytes(byteArray);
// get fisrt element
System.out.println("Random byte: " + byteArray[0]);

Where is the list of predefined Maven properties

Looking at the "effective POM" will probably help too. For instance, if you wanted to know what the path is for ${project.build.sourceDirectory}

you would find the related XML in the effective POM, such as: <project> <build> <sourceDirectory>/my/path</sourceDirectory>

Also helpful - you can do a real time evaluation of properties via the command line execution of mvn help:evaluate while in the same dir as the POM.

Add Expires headers

<IfModule mod_expires.c>
    # Enable expirations
    ExpiresActive On 

    # Default directive
    ExpiresDefault "access plus 1 month"

    # My favicon
    ExpiresByType image/x-icon "access plus 1 year"

    # Images
    ExpiresByType image/gif "access plus 1 month"
    ExpiresByType image/png "access plus 1 month"
    ExpiresByType image/jpg "access plus 1 month"
    ExpiresByType image/jpeg "access plus 1 month"

    # CSS
    ExpiresByType text/css "access plus 1 month"

    # Javascript
    ExpiresByType application/javascript "access plus 1 year"
</IfModule>

Detect network connection type on Android

You can use getSubtype() for more details. Check out slide 9 here: http://dl.google.com/io/2009/pres/W_0300_CodingforLife-BatteryLifeThatIs.pdf

ConnectivityManager mConnectivity = null;
TelephonyManager mTelephony = null;
// Skip if no connection, or background data disabled
NetworkInfo info = mConnectivity.getActiveNetworkInfo();
if (info == null || !mConnectivity.getBackgroundDataSetting()) {
    return false;
}

// Only update if WiFi or 3G is connected and not roaming
int netType = info.getType();
int netSubtype = info.getSubtype();
if (netType == ConnectivityManager.TYPE_WIFI) {
    return info.isConnected();
} else if (netType == ConnectivityManager.TYPE_MOBILE
    && netSubtype == TelephonyManager.NETWORK_TYPE_UMTS
    && !mTelephony.isNetworkRoaming()) {
        return info.isConnected();
} else {
    return false;
}

Also, please check out Emil's answer for a more detailed dive into this.

How to export a MySQL database to JSON?

Use the following ruby code

require 'mysql2'

client = Mysql2::Client.new(
  :host => 'your_host', `enter code here`
  :database => 'your_database',
  :username => 'your_username', 
  :password => 'your_password')
table_sql = "show tables"
tables = client.query(table_sql, :as => :array)

open('_output.json', 'a') { |f|       
    tables.each do |table|
        sql = "select * from `#{table.first}`"
        res = client.query(sql, :as => :json)
        f.puts res.to_a.join(",") + "\n"
    end
}

How do I read a specified line in a text file?

A variation. Produces an error if line number is greater than number of lines.

string GetLine(string fileName, int lineNum)
{
    using (StreamReader sr = new StreamReader(fileName))
    {
        string line;
        int count = 1;
        while ((line = sr.ReadLine()) != null)
        {
            if(count == lineNum)
            {
                return line;
            }
            count++;
        }
    }
    return "line number is bigger than number of lines";  
}

How to process each output line in a loop?

Iterate over the grep results with a while/read loop. Like:

grep pattern filename.txt | while read -r line ; do
    echo "Matched Line:  $line"
    # your code goes here
done

Adding a Time to a DateTime in C#

Combine both. The Date-Time-Picker does support picking time, too.

You just have to change the Format-Property and maybe the CustomFormat-Property.

What does it mean with bug report captured in android tablet?

It's because you have turned on USB debugging in Developer Options. You can create a bug report by holding the power + both volume up and down.

Edit: This is what the forums say:

By pressing Volume up + Volume down + power button, you will feel a vibration after a second or so, that's when the bug reporting initiated.

To disable:

/system/bin/bugmailer.sh must be deleted/renamed.

There should be a folder on your SD card called "bug reports".

Have a look at this thread: http://forum.xda-developers.com/showthread.php?t=2252948

And this one: http://forum.xda-developers.com/showthread.php?t=1405639

Calculate Age in MySQL (InnoDb)

SELECT TIMESTAMPDIFF (YEAR, YOUR_COLUMN, CURDATE()) FROM YOUR_TABLE AS AGE

Click for demo..

Simple but elegant..

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

I think you are talking about class level variables. As mentioned above using global variable/class level variables are not a good practice.

If you really want to use it. and if you are sure that there will not be impact...

Declare any variable out side the method. at the class level with out the variable type

eg:

{
   method()
   {
      a=10
      print(a)
   }

// def a or int a wont work

a=0

}

Maven project.build.directory

You can find those maven properties in the super pom.

You find the jar here:

${M2_HOME}/lib/maven-model-builder-3.0.3.jar

Open the jar with 7-zip or some other archiver (or use the jar tool).

Navigate to

org/apache/maven/model

There you'll find the pom-4.0.0.xml.

It contains all those "short cuts":

<project>
    ...
    <build>
        <directory>${project.basedir}/target</directory>
        <outputDirectory>${project.build.directory}/classes</outputDirectory>
        <finalName>${project.artifactId}-${project.version}</finalName>
        <testOutputDirectory>${project.build.directory}/test-classes</testOutputDirectory>
        <sourceDirectory>${project.basedir}/src/main/java</sourceDirectory>
        <scriptSourceDirectory>src/main/scripts</scriptSourceDirectory>
        <testSourceDirectory>${project.basedir}/src/test/java</testSourceDirectory>
        <resources>
            <resource>
                <directory>${project.basedir}/src/main/resources</directory>
            </resource>
        </resources>
        <testResources>
            <testResource>
                <directory>${project.basedir}/src/test/resources</directory>
            </testResource>
        </testResources>
        ...
    </build>
    ...
</project>

Update

After some lobbying I am adding a link to the pom-4.0.0.xml. This allows you to see the properties without opening up the local jar file.

Where is SQL Server Management Studio 2012?

I downloaded it from here (named 'Microsoft SQL Server Data Tools'). In this version you will get a Visual Studio 2012 installation with the functionality to manage the SQL Server 2012 server.

php static function

In the first class, sayHi() is actually an instance method which you are calling as a static method and you get away with it because sayHi() never refers to $this.

Static functions are associated with the class, not an instance of the class. As such, $this is not available from a static context ($this isn't pointing to any object).

global variable for all controller and views

Use the Config class:

Config::set('site_settings', $site_settings);

Config::get('site_settings');

http://laravel.com/docs/4.2/configuration

Configuration values that are set at run-time are only set for the current request, and will not be carried over to subsequent requests.

Convert any object to a byte[]

checkout this article :http://www.morgantechspace.com/2013/08/convert-object-to-byte-array-and-vice.html

Use the below code

// Convert an object to a byte array
private byte[] ObjectToByteArray(Object obj)
{
    if(obj == null)
        return null;

    BinaryFormatter bf = new BinaryFormatter();
    MemoryStream ms = new MemoryStream();
    bf.Serialize(ms, obj);

    return ms.ToArray();
}

// Convert a byte array to an Object
private Object ByteArrayToObject(byte[] arrBytes)
{
    MemoryStream memStream = new MemoryStream();
    BinaryFormatter binForm = new BinaryFormatter();
    memStream.Write(arrBytes, 0, arrBytes.Length);
    memStream.Seek(0, SeekOrigin.Begin);
    Object obj = (Object) binForm.Deserialize(memStream);

    return obj;
}

Can you append strings to variables in PHP?

PHP syntax is little different in case of concatenation from JavaScript. Instead of (+) plus a (.) period is used for string concatenation.

<?php

$selectBox = '<select name="number">';
for ($i=1;$i<=100;$i++)
{
    $selectBox += '<option value="' . $i . '">' . $i . '</option>'; // <-- (Wrong) Replace + with .
    $selectBox .= '<option value="' . $i . '">' . $i . '</option>'; // <-- (Correct) Here + is replaced .
}
$selectBox += '</select>'; // <-- (Wrong) Replace + with .
$selectBox .= '</select>'; // <-- (Correct) Here + is replaced .
echo $selectBox;

?>

How to prevent a file from direct URL Access?

RewriteEngine on
RewriteCond %{HTTP_REFERER} !^http://(www\.)?localhost.*$ [NC] 
RewriteCond %{REQUEST_URI} !^http://(www\.)?localhost/(.*)\.(gif|jpg|png|jpeg|mp4)$ [NC] 
RewriteRule . - [F]

Interface type check with Typescript

Type guards in Typescript:

TS has type guards for this purpose. They define it in the following manner:

Some expression that performs a runtime check that guarantees the type in some scope.

This basically means that the TS compiler can narrow down the type to a more specific type when it has sufficient information. For example:

function foo (arg: number | string) {
    if (typeof arg === 'number') {
        // fine, type number has toFixed method
        arg.toFixed()
    } else {
        // Property 'toFixed' does not exist on type 'string'. Did you mean 'fixed'?
        arg.toFixed()
        // TSC can infer that the type is string because 
        // the possibility of type number is eliminated at the if statement
    }
}

To come back to your question, we can also apply this concept of type guards to objects in order to determine their type. To define a type guard for objects, we need to define a function whose return type is a type predicate. For example:

interface Dog {
    bark: () => void;
}

// The function isDog is a user defined type guard
// the return type: 'pet is Dog' is a type predicate, 
// it determines whether the object is a Dog
function isDog(pet: object): pet is Dog {
  return (pet as Dog).bark !== undefined;
}

const dog: any = {bark: () => {console.log('woof')}};

if (isDog(dog)) {
    // TS now knows that objects within this if statement are always type Dog
    // This is because the type guard isDog narrowed down the type to Dog
    dog.bark();
}

file.delete() returns false even though file.exists(), file.canRead(), file.canWrite(), file.canExecute() all return true

I tried this simple thing and it seems to be working.

file.setWritable(true);
file.delete();

It works for me.

If this does not work try to run your Java application with sudo if on linux and as administrator when on windows. Just to make sure Java has rights to change the file properties.

How often should Oracle database statistics be run?

At my last job we ran statistics once a week. If I remember correctly, we scheduled them on a Thursday night, and on Friday the DBAs were very careful to monitor the longest running queries for anything unexpected. (Friday was picked because it was often just after a code release, and tended to be a fairly low traffic day.) When they saw a bad query they would find a better query plan and save that one so it wouldn't change again unexpectedly. (Oracle has tools to do this for you automatically, you tell it the query to optimize and it does.)

Many organizations avoid running statistics out of fear of bad query plans popping up unexpectedly. But this usually means that their query plans get worse and worse over time. And when they do run statistics then they encounter a number of problems. The resulting scramble to fix those issues confirms their fears about the dangers of running statistics. But if they ran statistics regularly, used the monitoring tools as they are supposed to, and fixed issues as they came up then they would have fewer headaches, and they wouldn't encounter them all at once.

How to launch PowerShell (not a script) from the command line

The color and window sizing are defined by the shortcut LNK file. I think I found a way that will do what you need, try this:

explorer.exe "Windows PowerShell.lnk"

The LNK file is in the all user start menu which is located in different places depending whether your on XP or Windows 7. In 7 the LNK file is here:

C:\ProgramData\Microsoft\Windows\Start Menu\Programs\Accessories\Windows PowerShell

Insert data to MySql DB and display if insertion is success or failure

After INSERT query you can use ROW_COUNT() to check for successful insert operation as:

SELECT IF(ROW_COUNT() = 1,  "Insert Success", "Insert Failed") As status;

Percentage width in a RelativeLayout

You can accomplish this via layout weights. A weight dictates how the unclaimed portions of the screen are divided up. Give each EditText a layout_width of 0, and some proportional weight. I.e., give one a weight of 2, and the other a weight of 1 if you want the first to take up twice as much space.

In Jinja2, how do you test if a variable is undefined?

In the Environment setup, we had undefined = StrictUndefined, which prevented undefined values from being set to anything. This fixed it:

from jinja2 import Undefined
JINJA2_ENVIRONMENT_OPTIONS = { 'undefined' : Undefined }

How to open an external file from HTML

If the file share is not open to everybody you will need to serve it up in the background from the file system via the web server.

You can use something like this "ASP.Net Serve File For Download" example (archived copy of 2).

Convert HH:MM:SS string to seconds only in javascript

You can do this dynamically - in case you encounter not only: HH:mm:ss, but also, mm:ss, or even ss alone.

var str = '12:99:07';
var times = str.split(":");
times.reverse();
var x = times.length, y = 0, z;
for (var i = 0; i < x; i++) {
    z = times[i] * Math.pow(60, i);
    y += z;
}
console.log(y);

gcloud command not found - while installing Google Cloud SDK

If you are on MAC OS and using .zsh shell then do the following:

  1. Edit your .zshrc and add the following

    # The next line updates PATH for the Google Cloud SDK.
    source /Users/USER_NAME/google-cloud-sdk/path.zsh.inc
    
    # The next line enables zsh completion for gcloud.
    source /Users/USER_NAME/google-cloud-sdk/completion.zsh.inc
    
  2. Create new file named path.zsh.inc under your home directory(/Users/USER_NAME/):

    script_link="$( readlink "$0" )" || script_link="$0"
    apparent_sdk_dir="${script_link%/*}"
    if [ "$apparent_sdk_dir" == "$script_link" ]; then
     apparent_sdk_dir=.
    fi
    sdk_dir="$( cd -P "$apparent_sdk_dir" && pwd -P )"
    bin_path="$sdk_dir/bin"
    export PATH=$bin_path:$PATH
    

Checkout more @ Official Docs

Using Pairs or 2-tuples in Java

Create a class that describes the concept you're actually modeling and use that. It can just store two Set<Long> and provide accessors for them, but it should be named to indicate what exactly each of those sets is and why they're grouped together.

fatal: The current branch master has no upstream branch

There is a simple solution to this which worked for me on macOS Sierra. I did these two commands:

git pull --rebase git_url(Ex: https://github.com/username/reponame.git)
git push origin master

If it shows any fatal error regarding upstream after any future push then simply run :

git push --set-upstream origin master

Mysql 1050 Error "Table already exists" when in fact, it does not

I had the same problem at Mac OS X and MySQL 5.1.40. I used eclipse to edit my SQL script and than I tried MySQLWorkbench 5.2.28. Probably it converted newline characters to Mac format. I had no idea about what's wrong with my script until I commented out the first line in file. After this this script was interpreted by mysql as a one single comment. I used build-in TextEdit Mac application to fix this. After line-breaks was converted to the correct format, the error 1050 gone.

Update for Eclipse users:

To set up default ending for new files created, across the entire workspace:

Window -> Preferences -> General -> Workspace -> New text file line delimiter.

To convert existing files, open file for editing and for the currently edited file, go to the menu:

File -> Convert Line Delimiters To

How to detect a textbox's content has changed

There's a complete working example here.

<html>
<title>jQuery Summing</title>
<head>
<script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.8.3/jquery.min.js"> </script>
$(document).ready(function() {
$('.calc').on('input', function() {
var t1 = document.getElementById('txt1');
var t2 = document.getElementById('txt2');
var tot=0;
if (parseInt(t1.value))
tot += parseInt(t1.value);
if (parseInt(t2.value))
tot += parseInt(t2.value);
document.getElementById('txt3').value = tot;
});
});
</script>
</head>
<body>
<input type='text' class='calc' id='txt1'>
<input type='text' class='calc' id='txt2'>
<input type='text' id='txt3' readonly>
</body>
</html>

C# HttpWebRequest The underlying connection was closed: An unexpected error occurred on a send

I had similar issue and the below line helped me solving the issue.Thanks to rene. I just pasted this line above the authentication code and it worked

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls12;

jQuery get specific option tag text

Based on the original HTML posted by Paolo I came up with the following.

$("#list").change(function() {
    alert($(this).find("option:selected").text()+' clicked!');
});

It has been tested to work on Internet Explorer and Firefox.

How do I check what version of Python is running my script?

If you want to detect pre-Python 3 and don't want to import anything...

...you can (ab)use list comprehension scoping changes and do it in a single expression:

is_python_3_or_above = (lambda x: [x for x in [False]] and None or x)(True)

if-else statement inside jsx: ReactJS

Just Tried that:

return(
  <>
    {
      main-condition-1 && 
      main-condition-2 &&
      (sub-condition ? (<p>Hi</p>) : (<p>Hello</p>))
     }
  </>
)

Let me know what you guys think!!!

Print the contents of a DIV

Slight changes over earlier version - tested on CHROME

function PrintElem(elem)
{
    var mywindow = window.open('', 'PRINT', 'height=400,width=600');

    mywindow.document.write('<html><head><title>' + document.title  + '</title>');
    mywindow.document.write('</head><body >');
    mywindow.document.write('<h1>' + document.title  + '</h1>');
    mywindow.document.write(document.getElementById(elem).innerHTML);
    mywindow.document.write('</body></html>');

    mywindow.document.close(); // necessary for IE >= 10
    mywindow.focus(); // necessary for IE >= 10*/

    mywindow.print();
    mywindow.close();

    return true;
}

How to create PDF files in Python

If you are familiar with LaTex you might want to consider pylatex

One of the advantages of pylatex is that it is easy to control the image quality. The images in your pdf will be of the same quality as the original images. When using reportlab, I experienced that the images were automatically compressed, and the image quality reduced.

The disadvantage of pylatex is that, since it is based on LaTex, it can be hard to place images exactly where you want on the page. However, I have found that using the position argument in the Figure class, and sometimes Subfigure, gives good enough results.

Example code for creating a pdf with a single image:

from pylatex import Document, Figure

doc = Document(documentclass="article")
with doc.create(Figure(position='p')) as fig:
fig.add_image('Lenna.png')

doc.generate_pdf('test', compiler='latexmk', compiler_args=["-pdf", "-pdflatex=pdflatex"], clean_tex=True)

In addition to installing pylatex (pip install pylatex), you need to install LaTex. For Ubuntu and other Debian systems you can run sudo apt-get install texlive-full. If you are using Windows I would recommend MixTex

HTML 5 input type="number" element for floating point numbers on Chrome

Try <input type="number" step="any" />

It won't have validation problems and the arrows will have step of "1"

Constraint validation: When the element has an allowed value step, and the result of applying the algorithm to convert a string to a number to the string given by the element's value is a number, and that number subtracted from the step base is not an integral multiple of the allowed value step, the element is suffering from a step mismatch.

The following range control only accepts values in the range 0..1, and allows 256 steps in that range:

<input name=opacity type=range min=0 max=1 step=0.00392156863>

The following control allows any time in the day to be selected, with any accuracy (e.g. thousandth-of-a-second accuracy or more):

<input name=favtime type=time step=any>

Normally, time controls are limited to an accuracy of one minute.

http://www.w3.org/TR/2012/WD-html5-20121025/common-input-element-attributes.html#attr-input-step

How do I decrease the size of my sql server log file?

I had the same problem, my database log file size was about 39 gigabyte, and after shrinking (both database and files) it reduced to 37 gigabyte that was not enough, so I did this solution: (I did not need the ldf file (log file) anymore)

(**Important) : Get a full backup of your database before the process.

  1. Run "checkpoint" on that database.

  2. Detach that database (right click on the database and chose tasks >> Detach...) {if you see an error, do the steps in the end of this text}

  3. Move MyDatabase.ldf to another folder, you can find it in your hard disk in the same folder as your database (Just in case you need it in the future for some reason such as what user did some task).

  4. Attach the database (right click on Databases and chose Attach...)

  5. On attach dialog remove the .ldf file (which shows 'file not found' comment) and click Ok. (don`t worry the ldf file will be created after the attachment process.)

  6. After that, a new log file create with a size of 504 KB!!!.

In step 2, if you faced an error that database is used by another user, you can:

1.run this command on master database "sp_who2" and see what process using your database.

2.read the process number, for example it is 52 and type "kill 52", now your database is free and ready to detach.

If the number of processes using your database is too much:

1.Open services (type services in windows start) find SQL Server ... process and reset it (right click and chose reset).

  1. Immediately click Ok button in the detach dialog box (that showed the detach error previously).

Disable cross domain web security in Firefox

While the question mentions Chrome and Firefox, there are other software without cross domain security. I mention it for people who ignore that such software exists.

For example, PhantomJS is an engine for browser automation, it supports cross domain security deactivation.

phantomjs.exe --web-security=no script.js

See this other comment of mine: Userscript to bypass same-origin policy for accessing nested iframes

Is there a way to define a min and max value for EditText in Android?

I stumbled upon this problem when I was making a pet project. I've read some of the answers here and I've probably adopted on or two of them in my code.

BAD NEWS: I managed to do this by using a very dirty way (you'll see why). There are still some bugs that I haven't bothered to address (I was writing this at like 2 am), like if the min value is 10, you won't be able to input a number to begin with.

GOOD NEWS: I've managed to get rid of the leading zeros bug mentioned by @nnyerges using solely the InputFilter down to only one 0, that is if the min value is 0. However, the limit of my implementation of the InputFilter comes when user deletes the first number(s) that's followed by zero(s), e.g. if at first user inputs 1000 but then deletes 1, it will become 000. That's ugly, and that's where my dirty ugly use of TextChangedListener / TextWatcher comes in. (I know OP already said that he can do it using TextWatcher, but whatever.)
Another limitation (or maybe MY limitation?) using the InputFilter is when the inputType is numberDecimal, which means user can input a decimal separator. Example case: range is 0 - 100, user inputs 99.99, user then deletes the separator, we'd have 9999. We don't want that, do we?
I've also made it to accommodate negative value.

Some features in my code, whether you like it or not, include trimming insignificant 0s, e.g. if user deletes 1 from 10032, as long as it's within the defined range, it will trim the leading 0s, so the final result will be 32. Second, when user tries to delete the negative (-) notation or the decimal separator (.), it will check whether the resulting number after deletion is still in range. If not, then it will revert back to last value. In other words, user isn't allowed to do that kind of removal. But, if you prefer to set the new values to either min or max values when that happens, you can do it, too.

NOTE: I'm too lazy to even bother with localization, so people who use comma as decimal separator will have to manually change it themselves.
SECOND NOTE: The code is very messy and probably have some or a lot of redundant checks, so be aware. Also, if you have suggestion, feel free to comment, as I want to improve it, too. I may need to use it in the future. Who knows?

Anyway, here it goes.

import android.text.InputFilter;
import android.text.Spanned;
import android.util.Log;

public class InputFilterMinMax implements InputFilter {
    
    private double min, max;
    
    public InputFilterMinMax(double min, double max) {
        this.min = min;
        this.max = max;
    }
    
    public InputFilterMinMax(String min, String max) {
        this.min = Double.parseDouble(min);
        this.max = Double.parseDouble(max);
    }
    
    @Override
    public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
        try {
            String lastVal = dest.toString();
            String newVal = lastVal.substring(0, dstart) + source.toString() + lastVal.substring(dstart);
            String strInput = source.toString();
            double input;
    
            if (strInput.equals("-") && (lastVal.length() == 0 || lastVal.equals("0"))) {
                return null;
            } else {
                input = Double.parseDouble(newVal);
            }
            
            if (isInRange(min, max, input)) {
                try {
                    if (lastVal.equals("0") && strInput.equals("0") && !strInput.equals(".")) {
                        Log.d("Checkpoint 1", "Can't put 0 again.");
                        return "";
                    } else if (strInput.equals("0")) {
                        if (dstart == 0) {
                            if (lastVal.substring(0, 1).equals("0")) {
                                Log.d("Checkpoint 2", "Can't put 0 again.");
                                return "";
                            } else if (!lastVal.substring(0, 1).equals(".")) {
                                Log.d("Checkpoint 3", "Can't put 0 in front of them.");
                                return "";
                            }
                        } else {
                            if (lastVal.substring(0, 1).equals("0") && dstart == 1) {
                                Log.d("Checkpoint 4", "Can't put 0 again.");
                                return "";
                            } else if (lastVal.substring(0, 1).equals("-")) {
                                if (Double.parseDouble(lastVal) == 0) {
                                    if (!lastVal.contains(".")) {
                                        Log.d("Checkpoint 5", "Can't put 0 here.");
                                        return "";
                                    } else {
                                        if (dstart <= lastVal.indexOf(".")) {
                                            Log.d("Checkpoint 6", "Can't put 0 here.");
                                            return "";
                                        }
                                    }
                                } else {
                                    if (lastVal.indexOf("0") == 1 && (dstart == 1 || dstart == 2)) {
                                        Log.d("Checkpoint 7", "Can't put 0 here.");
                                        return "";
                                    } else if ((!lastVal.substring(1, 2).equals("0") && !lastVal.substring(1, 2).equals(".")) && dstart == 1) {
                                        Log.d("Checkpoint 8", "Can't put 0 here.");
                                        return "";
                                    }
                                }
                            }
                        }
                    }
    
                    /**
                     * If last value is a negative that equals min value,
                     * and user tries to input a decimal separator at the
                     * very end, ignore it, because they won't be able to
                     * input anything except 0 after that anyway.
                     */
                    if (strInput.equals(".") && lastVal.substring(0,1).equals("-")
                            && Double.parseDouble(lastVal) == min && dstart == lastVal.length()) {
                        return "";
                    }
                } catch (Exception e) {
                }
                return null;
            }
        } catch (Exception ignored) {
            ignored.printStackTrace();
        }
        return "";
    }
    
    private boolean isInRange(double a, double b, double c) {
        return b > a ? c >= a && c <= b : c >= b && c <= a;
    }
}

Now, the really dirty part:

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.text.Editable;
import android.text.InputFilter;
import android.text.TextWatcher;
import android.util.Log;
import android.widget.EditText;

public class MainActivity extends AppCompatActivity implements TextWatcher {
    
    private EditText editInput;
    
    /**
     * Var to store old value in case the new value is either
     * out of range or invalid somehow. This was because I
     * needed a double value for my app, which means I can
     * enter a dot (.), and that could mean trouble if I decided
     * to delete that dot, e.g. assume the range is 0 - 100.
     * At first I enter 99.99, the InputFilter would allow that,
     * but what if somewhere down the line I decided to delete
     * the dot/decimal separator for "fun"?
     * Wow, now I have 9999.
     * Also, when I delete negative notation, it can produce
     * the same problem.
     */
    private String oldVal;
    
    private int min, max;
    
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        
        editInput = findViewById(R.id.edt_input);
        editInput.addTextChangedListener(this);
        
        min = -1600;
        max = 1500;
        
        editInput.setFilters(new InputFilter[]{new InputFilterMinMax(min, max)});
    }
    
    @Override
    public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        oldVal = saveOldValue(s, start);
    }
    
    @Override
    public void onTextChanged(CharSequence s, int start, int before, int count) {
    
    }
    
    @Override
    public void afterTextChanged(Editable s) {
            validateChange(editInput, oldVal);
    }
    
    private String saveOldValue(CharSequence s, int start) {
        String oldVal = s.toString();
        if (oldVal.contains(".") && start == oldVal.indexOf(".") && start != oldVal.length() - 1) {
            return oldVal;
        } else if (oldVal.contains("-") && start == oldVal.indexOf("-") && start != oldVal.length() - 1) {
            return oldVal;
        }
        return null;
    }
    
    private void validateChange(EditText editText, String oldVal) {
        String strNewVal = editText.getText().toString().trim();
        boolean isChanged = false;

        if (strNewVal.indexOf("0") == 0 || (strNewVal.indexOf("-") == 0 && strNewVal.indexOf("0") == 1)) {
            if (strNewVal.contains(".")) {
                while ((strNewVal.indexOf("0") == 0 && strNewVal.indexOf(".") != 1 && strNewVal.length() > 2) ||
                        (strNewVal.indexOf("0") == 1 && strNewVal.indexOf(".") != 2 && strNewVal.length() > 3)) {
                    Log.d("Trimming 0", "");
                    strNewVal = strNewVal.replaceFirst("0", "");
                    isChanged = true;
                }
            } else if (!strNewVal.contains(".")) {
                while (strNewVal.indexOf("0") == 0 && strNewVal.length() > 1) {
                    Log.d("Trimming 0", "");
                    strNewVal = strNewVal.replaceFirst("0", "");
                    isChanged = true;
                }

                if (Double.parseDouble(strNewVal) > max) {
                    editText.setText(oldVal); // Or, you can set it to max values here.
                    return;
                }
            }
        }
        
        if (strNewVal.indexOf(".") == 0) {
            strNewVal = "0" + strNewVal;
            isChanged = true;
        }

        try {
            double newVal = Double.parseDouble(strNewVal);
            Log.d("NewVal: ", String.valueOf(newVal));
            if (newVal > max || newVal < min) {
                Log.d("Over Limit", "Let's Reset");
                editText.setText(oldVal); // Or, you can set it to min or max values here.
            }
        } catch (NumberFormatException e) {
            e.printStackTrace();
        }

        if (isChanged) {
            editText.setText(strNewVal);
        }
    }
}

nginx error:"location" directive is not allowed here in /etc/nginx/nginx.conf:76

The server directive has to be in the http directive. It should not be outside of it.

Incase if you need detailed information, refer this.

What does the "More Columns than Column Names" error mean?

you have have strange characters in your heading # % -- or ,

Copy filtered data to another sheet using VBA

it needs to be .Row.count not Row.Number?

That's what I used and it works fine Sub TransfersToCleared() Dim ws As Worksheet Dim LastRow As Long Set ws = Application.Worksheets("Export (2)") 'Data Source LastRow = Range("A" & Rows.Count).End(xlUp).Row ws.Range("A2:AB" & LastRow).SpecialCells(xlCellTypeVisible).Copy

Looping over elements in jQuery

This is the simplest way to loop through a form accessing only the form elements. Inside the each function you can check and build whatever you want. When building objects note that you will want to declare it outside of the each function.

EDIT JSFIDDLE

The below will work

$('form[name=formName]').find('input, textarea, select').each(function() {
    alert($(this).attr('name'));
});

Your branch is ahead of 'origin/master' by 3 commits

Came across this issue after I merged a pull request on Bitbucket.

Had to do

git fetch

and that was it.

Loop through all the rows of a temp table and call a stored procedure for each row

Try returning the dataset from your stored procedure to your datatable in C# or VB.Net. Then the large amount of data in your datatable can be copied to your destination table using a Bulk Copy. I have used BulkCopy for loading large datatables with thousands of rows, into Sql tables with great success in terms of performance.

You may want to experiment with BulkCopy in your C# or VB.Net code.

iOS start Background Thread

Well that's pretty easy actually with GCD. A typical workflow would be something like this:

dispatch_queue_t queue = dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0ul);
    dispatch_async(queue, ^{
        // Perform async operation
        // Call your method/function here
        // Example:
        // NSString *result = [anObject calculateSomething];
                dispatch_sync(dispatch_get_main_queue(), ^{
                    // Update UI
                    // Example:
                    // self.myLabel.text = result;
                });
    });

For more on GCD you can take a look into Apple's documentation here

How to include *.so library in Android Studio?

Adding .so Library in Android Studio 1.0.2

  1. Create Folder "jniLibs" inside "src/main/"
  2. Put all your .so libraries inside "src/main/jniLibs" folder
  3. Folder structure looks like,
    |--app:
    |--|--src:
    |--|--|--main
    |--|--|--|--jniLibs
    |--|--|--|--|--armeabi
    |--|--|--|--|--|--.so Files
    |--|--|--|--|--x86
    |--|--|--|--|--|--.so Files
  4. No extra code requires just sync your project and run your application.

    Reference
    https://github.com/commonsguy/sqlcipher-gradle/tree/master/src/main

ExpressJS How to structure an application?

I have written a post exactly about this matter. It basically makes use of a routeRegistrar that iterates through files in the folder /controllers calling its function init. Function init takes the express app variable as a parameter so you can register your routes the way you want.

var fs = require("fs");
var express = require("express");
var app = express();

var controllersFolderPath = __dirname + "/controllers/";
fs.readdirSync(controllersFolderPath).forEach(function(controllerName){
    if(controllerName.indexOf("Controller.js") !== -1){
        var controller = require(controllersFolderPath + controllerName);
        controller.init(app);
    }
});

app.listen(3000);

How can I execute a python script from an html button?

Best way is to Use a Python Web Frame Work you can choose Django/Flask. I will suggest you to Use Django because it's more powerful. Here is Step by guide to get complete your task :

pip install django
django-admin createproject buttonpython

then you have to create a file name views.py in buttonpython directory.

write below code in views.py:

from django.http import HttpResponse

def sample(request):
    #your python script code
    output=code output
    return HttpResponse(output)

Once done navigate to urls.py and add this stanza

from . import views

path('', include('blog.urls')),

Now go to parent directory and execute manage.py

python manage.py runserver 127.0.0.1:8001

Step by Step Guide in Detail: Run Python script on clicking HTML button

Types in MySQL: BigInt(20) vs Int(20)

Let's give an example for int(10) one with zerofill keyword, one not, the table likes that:

create table tb_test_int_type(
    int_10 int(10),
    int_10_with_zf int(10) zerofill,
    unit int unsigned
);

Let's insert some data:

insert into tb_test_int_type(int_10, int_10_with_zf, unit)
values (123456, 123456,3147483647), (123456, 4294967291,3147483647) 
;

Then

select * from tb_test_int_type; 

# int_10, int_10_with_zf, unit
'123456', '0000123456', '3147483647'
'123456', '4294967291', '3147483647'

We can see that

  • with keyword zerofill, num less than 10 will fill 0, but without zerofill it won't

  • Secondly with keyword zerofill, int_10_with_zf becomes unsigned int type, if you insert a minus you will get error Out of range value for column...... But you can insert minus to int_10. Also if you insert 4294967291 to int_10 you will get error Out of range value for column.....

Conclusion:

  1. int(X) without keyword zerofill, is equal to int range -2147483648~2147483647

  2. int(X) with keyword zerofill, the field is equal to unsigned int range 0~4294967295, if num's length is less than X it will fill 0 to the left

Concatenation of strings in Lua

Concatenation:

The string concatenation operator in Lua is denoted by two dots ('..'). If both operands are strings or numbers, then they are converted to strings according to the rules mentioned in §2.2.1. Otherwise, the "concat" metamethod is called (see §2.8).

from: http://www.lua.org/manual/5.1/manual.html#2.5.4

How can I convert a zero-terminated byte array to string?

  • Use slices instead of arrays for reading. For example, io.Reader accepts a slice, not an array.

  • Use slicing instead of zero padding.

Example:

buf := make([]byte, 100)
n, err := myReader.Read(buf)
if n == 0 && err != nil {
    log.Fatal(err)
}

consume(buf[:n]) // consume() will see an exact (not padded) slice of read data

Node.js: get path from the request

simply call req.url. that should do the work. you'll get something like /something?bla=foo

Transparent scrollbar with css

With pure css it is not possible to make it transparent. You have to use transparent background image like this:

::-webkit-scrollbar-track-piece:start {
    background: transparent url('images/backgrounds/scrollbar.png') repeat-y !important;
}

::-webkit-scrollbar-track-piece:end {
    background: transparent url('images/backgrounds/scrollbar.png') repeat-y !important;
}

Finding the next available id in MySQL

In addition to Lukasz Lysik's answer - LEFT-JOIN kind of SQL.
As I understand, if have id's: 1,2,4,5 it should return 3.

SELECT u.Id + 1 AS FirstAvailableId
FROM users u
LEFT JOIN users u1 ON u1.Id = u.Id + 1
WHERE u1.Id IS NULL
ORDER BY u.Id
LIMIT 0, 1

Hope it will help some of visitors, although post are rather old.

jQuery UI " $("#datepicker").datepicker is not a function"

I ran into this problem recently - the issue was that I had included the jQuery UI files in the head tag, but the Telerik library I was using included jQuery at the bottom of the body tag (thus apparently re-initializing jQuery and unloading the UI plugins previously loaded).

The solution was to find out where jQuery was actually being included, and including the jQuery UI scripts after that.

Loop in react-native

 render() {
    var myloop = [];

    for (let i = 0; i < 10; i++) {
      myloop.push(
        <View key={i}>
        <Text style={{ textAlign: 'center', marginTop: 5 }} >{i}</Text>
        </View>
      );
    }

     return (

            <View >
              <Text >Welcome to React Native!</Text>
               {myloop}
            </View>


        );
      }

Output 1 2 3 4 5 6 7 8 9

Android Button click go to another xml page

There is more than one way to do this.

Here is a good resource straight from Google: http://developer.android.com/training/basics/firstapp/starting-activity.html

At developer.android.com, they have numerous tutorials explaining just about everything you need to know about android. They even provide detailed API for each class.

If that doesn't help, there are NUMEROUS different resources that can help you with this question and other android questions.

Can I use an image from my local file system as background in HTML?

You forgot the C: after the file:///
This works for me

<!DOCTYPE html>
<html>
    <head>
        <title>Experiment</title>
        <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
        <style>
            html,body { width: 100%; height: 100%; }
        </style>
    </head>
    <body style="background: url('file:///C:/Users/Roby/Pictures/battlefield-3.jpg')">
    </body>
</html>

Change Button color onClick

There are indeed global variables in javascript. You can learn more about scopes, which are helpful in this situation.

Your code could look like this:

<script>
    var count = 1;
    function setColor(btn, color) {
        var property = document.getElementById(btn);
        if (count == 0) {
            property.style.backgroundColor = "#FFFFFF"
            count = 1;        
        }
        else {
            property.style.backgroundColor = "#7FFF00"
            count = 0;
        }
    }
</script>

Hope this helps.

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

Change secret_string += str(chr(char + 7429146))

To secret_string += chr(ord(char) + 7429146)

ord() converts the character to its Unicode integer equivalent. chr() then converts this integer into its Unicode character equivalent.

Also, 7429146 is too big of a number, it should be less than 1114111

How to uninstall Golang?

On a Mac-OS system

  1. If you have used an installer, you can uninstall golang by using the same installer.
  2. If you have installed from source
    rm -rf /usr/local/go
    rm -rf $(echo $GOPATH)
    

Then, remove all entries related to go i.e. GOROOT, GOPATH from ~/.bash_profile and run

source ~/.bash_profile

On a Linux system

rm -rf /usr/local/go
rm -rf $(echo $GOPATH)

Then, remove all entries related to go i.e. GOROOT, GOPATH from ~/.bashrc and run

source ~/.bashrc

subquery in codeigniter active record

Like this in simple way .

    $this->db->select('*');
    $this->db->from('certs');
    $this->db->where('certs.id NOT IN (SELECT id_cer FROM revokace)');

    return $this->db->get()->result();

How to change title of Activity in Android?

The code helped me change the title.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_name);
    ActivityName.this.setTitle("Your Activity Title");}

Convert audio files to mp3 using ffmpeg

I had to purge my ffmpeg and then install another one from a ppa:

sudo apt-get purge ffmpeg
sudo apt-add-repository -y ppa:jon-severinsson/ffmpeg 
sudo apt-get update 
sudo apt-get install ffmpeg

Then convert:

 ffmpeg -i audio.ogg -f mp3 newfile.mp3

Using JavaScript to display a Blob

In your example, you should createElement('img').

In your link, base64blob != Base64.encode(blob).

This works, as long as your data is valid http://jsfiddle.net/SXFwP/ (I didn't have any BMP images so I had to use PNG).

How to set x axis values in matplotlib python?

The scaling on your example figure is a bit strange but you can force it by plotting the index of each x-value and then setting the ticks to the data points:

import matplotlib.pyplot as plt
x = [0.00001,0.001,0.01,0.1,0.5,1,5]
# create an index for each tick position
xi = list(range(len(x)))
y = [0.945,0.885,0.893,0.9,0.996,1.25,1.19]
plt.ylim(0.8,1.4)
# plot the index for the x-values
plt.plot(xi, y, marker='o', linestyle='--', color='r', label='Square') 
plt.xlabel('x')
plt.ylabel('y') 
plt.xticks(xi, x)
plt.title('compare')
plt.legend() 
plt.show()

Creating a config file in PHP

The options I see with relative merits / weaknesses are:

File based mechanisms

These require that your code look in specific locations to find the ini file. This is a difficult problem to solve and one which always crops up in large PHP applications. However you will likely need to solve the problem in order to find the PHP code which gets incorporated / re-used at runtime.

Common approaches to this are to always use relative directories, or to search from the current directory upwards to find a file exclusively named in the base directory of the application.

Common file formats used for config files are PHP code, ini formatted files, JSON, XML, YAML and serialized PHP

PHP code

This provides a huge amount of flexibility for representing different data structures, and (assuming it is processed via include or require) the parsed code will be available from the opcode cache - giving a performance benefit.

The include_path provides a means for abstracting the potential locations of the file without relying on additional code.

On the other hand, one of the main reasons for separating configuration from code is to separate responsibilities. It provides a route for injecting additional code into the runtime.

If the configuration is created from a tool, it may be possible to validate the data in the tool, but there is no standard function to escape data for embedding into PHP code as exists for HTML, URLs, MySQL statements, shell commands....

Serialized data This is relatively efficient for small amounts of configuration (up to around 200 items) and allows for use of any PHP data structure. It requires very little code to create/parse the data file (so you can instead expend your efforts on ensuring that the file is only written with appropriate authorization).

Escaping of content written to the file is handled automatically.

Since you can serialize objects, it does create an opportunity for invoking code simply by reading the configuration file (the __wakeup magic method).

Structured file

Storing it as a INI file as suggested by Marcel or JSON or XML also provides a simple api to map the file into a PHP data structure (and with the exception of XML, to escape the data and create the file) while eliminating the code invocation vulnerability using serialized PHP data.

It will have similar performance characteristics to the serialized data.

Database storage

This is best considered where you have a huge amount of configuration but are selective in what is needed for the current task - I was surprised to find that at around 150 data items, it was quicker to retrieve the data from a local MySQL instance than to unserialize a datafile.

OTOH its not a good place to store the credentials you use to connect to your database!

The execution environment

You can set values in the execution environment PHP is running in.

This removes any requirement for the PHP code to look in a specific place for the config. OTOH it does not scale well to large amounts of data and is difficult to change universally at runtime.

On the client

One place I've not mentioned for storing configuration data is at the client. Again the network overhead means that this does not scale well to large amounts of configuration. And since the end user has control over the data it must be stored in a format where any tampering is detectable (i.e. with a cryptographic signature) and should not contain any information which is compromised by its disclosure (i.e. reversibly encrypted).

Conversely, this has a lot of benefits for storing sensitive information which is owned by the end user - if you are not storing this on the server, it cannot be stolen from there.

Network Directories Another interesting place to store configuration information is in DNS / LDAP. This will work for a small number of small pieces of information - but you don't need to stick to 1st normal form - consider, for example SPF.

The infrastucture supports caching, replication and distribution. Hence it works well for very large infrastructures.

Version Control systems

Configuration, like code should be managed and version controlled - hence getting the configuration directly from your VC system is a viable solution. But often this comes with a significant performance overhead hence caching may be advisable.

Efficient way to insert a number into a sorted array of numbers?

function insertOrdered(array, elem) {
    let _array = array;
    let i = 0;
    while ( i < array.length && array[i] < elem ) {i ++};
    _array.splice(i, 0, elem);
    return _array;
}

Using getResources() in non-activity class

this can be done by using

context.getResources().getXml(R.xml.samplexml);

C# Base64 String to JPEG Image

So with the code you have provided.

var bytes = Convert.FromBase64String(resizeImage.Content);
using (var imageFile = new FileStream(filePath, FileMode.Create))
{
    imageFile.Write(bytes ,0, bytes.Length);
    imageFile.Flush();
}

Any free WPF themes?

There are some Microsoft Themes in the WPF page on CodePlex:

CodePlex - Windows Presentation Foundation

Which command in VBA can count the number of characters in a string variable?

Len is what you want.

word = "habit"  
length = Len(word)

How to create a horizontal loading progress bar?

Worked for me , can try with the same

<ProgressBar
    android:id="@+id/determinateBar"
    android:indeterminateOnly="true"
    android:indeterminateDrawable="@android:drawable/progress_indeterminate_horizontal"
    android:indeterminateDuration="10"
    android:indeterminateBehavior="repeat"
    android:progressBackgroundTint="#208afa"
    android:progressBackgroundTintMode="multiply"
    android:minHeight="24dip"
    android:maxHeight="24dip"
    android:layout_width="match_parent"
    android:layout_height="10dp"
    android:visibility="visible"/>

Writing new lines to a text file in PowerShell

`n is a line feed character. Notepad (prior to Windows 10) expects linebreaks to be encoded as `r`n (carriage return + line feed, CR-LF). Open the file in some useful editor (SciTE, Notepad++, UltraEdit-32, Vim, ...) and convert the linebreaks to CR-LF. Or use PowerShell:

(Get-Content $logpath | Out-String) -replace "`n", "`r`n" | Out-File $logpath

String to date in Oracle with milliseconds

I don't think you can use fractional seconds with to_date or the DATE type in Oracle. I think you need to_timestamp which returns a TIMESTAMP type.

What is the cleanest way to ssh and run multiple commands in Bash?

The easiest way to configure your system to use single ssh sessions by default with multiplexing.

This can be done by creating a folder for the sockets:

mkdir ~/.ssh/controlmasters

And then adding the following to your .ssh configuration:

Host *
    ControlMaster auto
    ControlPath ~/.ssh/controlmasters/%r@%h:%p.socket
    ControlMaster auto
    ControlPersist 10m

Now, you do not need to modify any of your code. This allows multiple calls to ssh and scp without creating multiple sessions, which is useful when there needs to be more interaction between your local and remote machines.

Thanks to @terminus's answer, http://www.cyberciti.biz/faq/linux-unix-osx-bsd-ssh-multiplexing-to-speed-up-ssh-connections/ and https://en.wikibooks.org/wiki/OpenSSH/Cookbook/Multiplexing.

Remove white space below image

You can use code below if you don't want to modify block mode:

img{vertical-align:text-bottom}

Or you can use following as Stuart suggests:

img{vertical-align:bottom}

Can't run Curl command inside my Docker Container

So I added curl AFTER my docker container was running.

(This was for debugging the container...I did not need a permanent addition)

I ran my image

docker run -d -p 8899:8080 my-image:latest

(the above makes my "app" available on my machine on port 8899) (not important to this question)

Then I listed and created terminal into the running container.

docker ps
docker exec -it my-container-id-here /bin/sh

If the exec command above does not work, check this SOF article:

Error: Cannot Start Container: stat /bin/sh: no such file or directory"

then I ran:

apk

just to prove it existed in the running container, then i ran:

apk add curl

and got the below:

apk add curl

fetch http://dl-cdn.alpinelinux.org/alpine/v3.8/main/x86_64/APKINDEX.tar.gz

fetch http://dl-cdn.alpinelinux.org/alpine/v3.8/community/x86_64/APKINDEX.tar.gz

(1/5) Installing ca-certificates (20171114-r3)

(2/5) Installing nghttp2-libs (1.32.0-r0)

(3/5) Installing libssh2 (1.8.0-r3)

(4/5) Installing libcurl (7.61.1-r1)

(5/5) Installing curl (7.61.1-r1)

Executing busybox-1.28.4-r2.trigger

Executing ca-certificates-20171114-r3.trigger

OK: 18 MiB in 35 packages

then i ran curl:

/ # curl
curl: try 'curl --help' or 'curl --manual' for more information
/ # 

Note, to get "out" of the drilled-in-terminal-window, I had to open a new terminal window and stop the running container:

docker ps
docker stop my-container-id-here

APPEND:

If you don't have "apk" (which depends on which base image you are using), then try to use "another" installer. From other answers here, you can try:

apt-get -qq update

apt-get -qq -y install curl

How to get a variable type in Typescript?

I suspect you can adjust your approach a little and use something along the lines of the example here:

https://www.typescriptlang.org/docs/handbook/advanced-types.html#user-defined-type-guards

function isFish(pet: Fish | Bird): pet is Fish {
  return (pet as Fish).swim !== undefined;
}

Get generic type of java.util.List

At runtime, no, you can't.

However via reflection the type parameters are accessible. Try

for(Field field : this.getDeclaredFields()) {
    System.out.println(field.getGenericType())
}

The method getGenericType() returns a Type object. In this case, it will be an instance of ParametrizedType, which in turn has methods getRawType() (which will contain List.class, in this case) and getActualTypeArguments(), which will return an array (in this case, of length one, containing either String.class or Integer.class).

Firebase: how to generate a unique numeric ID for key?

Adding to the @htafoya answer. The code snippet will be

const getTimeEpoch = () => {
    return new Date().getTime().toString();                             
}

How do I make a splash screen?

Another approach is achieved by using CountDownTimer

@Override
public void onCreate(Bundle savedInstanceState) {
     super.onCreate(savedInstanceState);
     setContentView(R.layout.splashscreen);

 new CountDownTimer(5000, 1000) { //5 seconds
      public void onTick(long millisUntilFinished) {
          mTextField.setText("seconds remaining: " + millisUntilFinished / 1000);
      }

     public void onFinish() {
          startActivity(new Intent(SplashActivity.this, MainActivity.class));
          finish();
     }

  }.start();
}

How to change the remote repository for a git submodule?

Just edit your .git/config file. For example; if you have a "common" submodule you can do this in the super-module:

git config submodule.common.url /data/my_local_common

Get Unix timestamp with C++

As this is the first result on google and there's no C++20 answer yet, here's how to use std::chrono to do this:

#include <chrono>

//...

using namespace std::chrono;
int64_t timestamp = duration_cast<milliseconds>(system_clock::now().time_since_epoch()).count();

In versions of C++ before 20, system_clock's epoch being Unix epoch is a de-facto convention, but it's not standardized. If you're not on C++20, use at your own risk.

Add Bean Programmatically to Spring Web App Context

First initialize Property values

MutablePropertyValues mutablePropertyValues = new MutablePropertyValues();
mutablePropertyValues.add("hostName", details.getHostName());
mutablePropertyValues.add("port", details.getPort());

DefaultListableBeanFactory context = new DefaultListableBeanFactory();
GenericBeanDefinition connectionFactory = new GenericBeanDefinition();
connectionFactory.setBeanClass(Class);
connectionFactory.setPropertyValues(mutablePropertyValues);

context.registerBeanDefinition("beanName", connectionFactory);

Add to the list of beans

ConfigurableListableBeanFactory beanFactory = ((ConfigurableApplicationContext) applicationContext).getBeanFactory();
beanFactory.registerSingleton("beanName", context.getBean("beanName"));

PHP UML Generator

I strongly recommend BOUML which:

  • is extremely fast (fastest UML tool ever created, check out benchmarks),
  • has rock solid PHP import and export support (also supports C++, Java, Python)
  • is multiplatform (Linux, Windows, other OSes),
  • is full featured, impressively intensively developed (look at development history, it's hard to believe that such fast progress is possible).
  • supports plugins, has modular architecture (this allows user contributions, looks like BOUML community is forming up)

Numpy converting array from float to strings

If the main problem is the loss of precision when converting from a float to a string, one possible way to go is to convert the floats to the decimalS: http://docs.python.org/library/decimal.html.

In python 2.7 and higher you can directly convert a float to a decimal object.

MySQL compare now() (only date, not time) with a datetime field

Compare date only instead of date + time (NOW) with:

CURDATE()

Typescript react - Could not find a declaration file for module ''react-materialize'. 'path/to/module-name.js' implicitly has an any type

Just install the necessary types for react and it should solve the error.

if you are using yarn:

yarn add @types/react @types/react-dom @types/react-router-dom -D

if you are using npm:

npm install @types/react @types/react-dom @types/react-router-dom --save-dev

In Subversion can I be a user other than my login name?

Most Subversion commands take the --username option to specify the username you want to use to the repository. Subversion remembers the last repository username and password used in each working copy, which means, among other things, that if you use svn checkout --username myuser you never need to specify the username again.

As Kamil Kisiel says, when Subversion is accessing the repository directly off the file system (that is, the repository URL is of form file:///path/to/repo or file://file-server/path/to/repo), it uses your file system permissions to access the repository. And when you connect via SSH tunneling (svn+ssh://server/path/to/repo), SVN uses your FS permissions on the server, as determined by your SSH login. In those cases, svn checkout --username may not work for your repository.

Search input with an icon Bootstrap 4

Here is an input box with a search icon on the right.

  <div class="input-group">
      <input class="form-control py-2 border-right-0 border" type="search" placeholder="Search">
      <div class="input-group-append">
          <div class="input-group-text" id="btnGroupAddon2"><i class="fa fa-search"></i></div>
      </div>
  </div>

Here is an input box with a search icon on the left.

  <div class="input-group">
      <div class="input-group-prepend">
          <div class="input-group-text" id="btnGroupAddon2"><i class="fa fa-search"></i></div>
      </div>
      <input class="form-control py-2 border-right-0 border" type="search" placeholder="Search">
  </div>

Sending commands and strings to Terminal.app with Applescript

set up passwordless ssh (ssh-keygen, then add the key to ~/.ssh/authorized_keys on the server). Make an entry in ~/.ssh/config (on your desktop), so that when you run ssh mysqlserver, it goes to user@hostname... Or make a shell alias, like gotosql, that expands to ssh user@host -t 'mysql_client ...' to start the mysql client interactively on the server.

Then you probably do need someone else's answer to script the process after that, since I don't know how to set startup commands for mysql.

At least that keeps your ssh password out of the script!

How to send an email using PHP?

<?php
include "db_conn.php";//connection file
require "PHPMailerAutoload.php";// it will be in PHPMailer
require "class.smtp.php";// it will be in PHPMailer
require "class.phpmailer.php";// it will be in PHPMailer


$response = array();
$params = json_decode(file_get_contents("php://input"));

if(!empty($params->email_id)){

    $email_id = $params->email_id;
    $flag=false;
    echo "something";
    if(!filter_var($email_id, FILTER_VALIDATE_EMAIL))
    {
        $response['ERROR']='EMAIL address format error'; 
        echo json_encode($response,JSON_UNESCAPED_SLASHES);
        return;
    }
    $sql="SELECT * from sales where email_id ='$email_id' ";

    $result = mysqli_query($conn,$sql);
    $count = mysqli_num_rows($result);

    $to = "[email protected]";
    $subject = "DEMO Subject";
    $messageBody ="demo message .";

    if($count ==0){
        $response["valid"] = false;
        $response["message"] = "User is not registered yet";
        echo json_encode($response);
        return;
    }

    else {

        $mail = new PHPMailer();
        $mail->IsSMTP();
        $mail->SMTPAuth = true; // authentication enabled
        $mail->IsHTML(true); 
        $mail->SMTPSecure = 'ssl';//turn on to send html email
        // $mail->Host = "ssl://smtp.zoho.com";
        $mail->Host = "p3plcpnl0749.prod.phx3.secureserver.net";//you can use gmail 
        $mail->Port = 465;
        $mail->Username = "[email protected]";
        $mail->Password = "demopassword";
        $mail->SetFrom("[email protected]", "Any demo alert");
        $mail->Subject = $subject;

        $mail->Body = $messageBody;
        $mail->AddAddress($to);
        echo "yes";

        if(!$mail->send()) {
           echo "Mailer Error: " . $mail->ErrorInfo;
       } 
       else {
           echo "Message has been sent successfully";
      }
    }

}
else{
    $response["valid"] = false;
    $response["message"] = "Required field(s) missing";
    echo json_encode($response);
}


?>

The above code is working for me.

Reading a file line by line in Go

Use:

  • reader.ReadString('\n')
    • If you don't mind that the line could be very long (i.e. use a lot of RAM). It keeps the \n at the end of the string returned.
  • reader.ReadLine()
    • If you care about limiting RAM consumption and don't mind the extra work of handling the case where the line is greater than the reader's buffer size.

I tested the various solutions suggested by writing a program to test the scenarios which are identified as problems in other answers:

  • A file with a 4MB line.
  • A file which doesn't end with a line break.

I found that:

  • The Scanner solution does not handle long lines.
  • The ReadLine solution is complex to implement.
  • The ReadString solution is the simplest and works for long lines.

Here is code which demonstrates each solution, it can be run via go run main.go, or at https://play.golang.org/p/RAW3sGblbas

package main

import (
    "bufio"
    "bytes"
    "fmt"
    "io"
    "os"
)

func readFileWithReadString(fn string) (err error) {
    fmt.Println("readFileWithReadString")

    file, err := os.Open(fn)
    if err != nil {
        return err
    }
    defer file.Close()

    // Start reading from the file with a reader.
    reader := bufio.NewReader(file)
    var line string
    for {
        line, err = reader.ReadString('\n')
        if err != nil && err != io.EOF {
            break
        }

        // Process the line here.
        fmt.Printf(" > Read %d characters\n", len(line))
        fmt.Printf(" > > %s\n", limitLength(line, 50))

        if err != nil {
            break
        }
    }
    if err != io.EOF {
        fmt.Printf(" > Failed with error: %v\n", err)
        return err
    }
    return
}

func readFileWithScanner(fn string) (err error) {
    fmt.Println("readFileWithScanner (scanner fails with long lines)")

    // Don't use this, it doesn't work with long lines...

    file, err := os.Open(fn)
    if err != nil {
        return err
    }
    defer file.Close()

    // Start reading from the file using a scanner.
    scanner := bufio.NewScanner(file)
    for scanner.Scan() {
        line := scanner.Text()

        // Process the line here.
        fmt.Printf(" > Read %d characters\n", len(line))
        fmt.Printf(" > > %s\n", limitLength(line, 50))
    }
    if scanner.Err() != nil {
        fmt.Printf(" > Failed with error %v\n", scanner.Err())
        return scanner.Err()
    }
    return
}

func readFileWithReadLine(fn string) (err error) {
    fmt.Println("readFileWithReadLine")

    file, err := os.Open(fn)
    if err != nil {
        return err
    }
    defer file.Close()

    // Start reading from the file with a reader.
    reader := bufio.NewReader(file)
    for {
        var buffer bytes.Buffer

        var l []byte
        var isPrefix bool
        for {
            l, isPrefix, err = reader.ReadLine()
            buffer.Write(l)
            // If we've reached the end of the line, stop reading.
            if !isPrefix {
                break
            }
            // If we're at the EOF, break.
            if err != nil {
                if err != io.EOF {
                    return err
                }
                break
            }
        }
        line := buffer.String()

        // Process the line here.
        fmt.Printf(" > Read %d characters\n", len(line))
        fmt.Printf(" > > %s\n", limitLength(line, 50))

        if err == io.EOF {
            break
        }
    }
    if err != io.EOF {
        fmt.Printf(" > Failed with error: %v\n", err)
        return err
    }
    return
}

func main() {
    testLongLines()
    testLinesThatDoNotFinishWithALinebreak()
}

func testLongLines() {
    fmt.Println("Long lines")
    fmt.Println()

    createFileWithLongLine("longline.txt")
    readFileWithReadString("longline.txt")
    fmt.Println()
    readFileWithScanner("longline.txt")
    fmt.Println()
    readFileWithReadLine("longline.txt")
    fmt.Println()
}

func testLinesThatDoNotFinishWithALinebreak() {
    fmt.Println("No linebreak")
    fmt.Println()

    createFileThatDoesNotEndWithALineBreak("nolinebreak.txt")
    readFileWithReadString("nolinebreak.txt")
    fmt.Println()
    readFileWithScanner("nolinebreak.txt")
    fmt.Println()
    readFileWithReadLine("nolinebreak.txt")
    fmt.Println()
}

func createFileThatDoesNotEndWithALineBreak(fn string) (err error) {
    file, err := os.Create(fn)
    if err != nil {
        return err
    }
    defer file.Close()

    w := bufio.NewWriter(file)
    w.WriteString("Does not end with linebreak.")
    w.Flush()
    return
}

func createFileWithLongLine(fn string) (err error) {
    file, err := os.Create(fn)
    if err != nil {
        return err
    }
    defer file.Close()

    w := bufio.NewWriter(file)
    fs := 1024 * 1024 * 4 // 4MB
    // Create a 4MB long line consisting of the letter a.
    for i := 0; i < fs; i++ {
        w.WriteRune('a')
    }
    // Terminate the line with a break.
    w.WriteRune('\n')

    // Put in a second line, which doesn't have a linebreak.
    w.WriteString("Second line.")
    w.Flush()
    return
}

func limitLength(s string, length int) string {
    if len(s) < length {
        return s
    }
    return s[:length]
}

I tested on:

  • go version go1.15 darwin/amd64
  • go version go1.7 windows/amd64
  • go version go1.6.3 linux/amd64
  • go version go1.7.4 darwin/amd64

The test program outputs:

Long lines

readFileWithReadString
 > Read 4194305 characters
 > > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 > Read 12 characters
 > > Second line.

readFileWithScanner (scanner fails with long lines)
 > Failed with error bufio.Scanner: token too long

readFileWithReadLine
 > Read 4194304 characters
 > > aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa
 > Read 12 characters
 > > Second line.
 > Read 0 characters
 > > 

No linebreak

readFileWithReadString
 > Read 28 characters
 > > Does not end with linebreak.

readFileWithScanner (scanner fails with long lines)
 > Read 28 characters
 > > Does not end with linebreak.

readFileWithReadLine
 > Read 28 characters
 > > Does not end with linebreak.
 > Read 0 characters
 > > 

How can I use LEFT & RIGHT Functions in SQL to get last 3 characters?

select right(rtrim('94342KMR'),3)

This will fetch the last 3 right string.

select substring(rtrim('94342KMR'),1,len('94342KMR')-3)

This will fetch the remaining Characters.

Why use #define instead of a variable

C didn't use to have consts, so #defines were the only way of providing constant values. Both C and C++ do have them now, so there is no point in using them, except when they are going to be tested with #ifdef/ifndef.

handling DATETIME values 0000-00-00 00:00:00 in JDBC

I stumbled across this attempting to solve the same issue. The installation I am working with uses JBOSS and Hibernate, so I had to do this a different way. For the basic case, you should be able to add zeroDateTimeBehavior=convertToNull to your connection URI as per this configuration properties page.

I found other suggestions across the land referring to putting that parameter in your hibernate config:

In hibernate.cfg.xml:

<property name="hibernate.connection.zeroDateTimeBehavior">convertToNull</property>

In hibernate.properties:

hibernate.connection.zeroDateTimeBehavior=convertToNull

But I had to put it in my mysql-ds.xml file for JBOSS as:

<connection-property name="zeroDateTimeBehavior">convertToNull</connection-property>

Hope this helps someone. :)

How to manually deploy artifacts in Nexus Repository Manager OSS 3

For Windows:

mvn deploy:deploy-file -DgroupId=joda-time -DartifactId=joda-time -Dversion=2.7 -Dpackaging=jar -Dfile=joda-time-2.7.jar 
-DgeneratePom=true -DrepositoryId=[Your ID] -Durl=[YourURL]

Format Date as "yyyy-MM-dd'T'HH:mm:ss.SSS'Z'"

Add another option, maybe not the most lightweight.

_x000D_
_x000D_
dayjs.extend(dayjs_plugin_customParseFormat)
console.log(dayjs('2018-09-06 17:00:00').format( 'YYYY-MM-DDTHH:mm:ss.000ZZ'))
_x000D_
<script src="https://cdn.jsdelivr.net/npm/[email protected]/dayjs.min.js"></script>
<script src="https://cdn.jsdelivr.net/npm/[email protected]/plugin/customParseFormat.js"></script>
_x000D_
_x000D_
_x000D_

Where is NuGet.Config file located in Visual Studio project?

If you use proxy, you will have to edit the Nuget.config file.

In Windows 7 and 10, this file is in the path:
C:\Users\YouUser\AppData\Roaming\NuGet.

Include the setting:

<config>
  <add key = "http_proxy" value = "http://Youproxy:8080" />
  <add key = "http_proxy.user" value = "YouProxyUser" />
</config>

View stored procedure/function definition in MySQL

SHOW CREATE PROCEDURE <name>

Returns the text of a previously defined stored procedure that was created using the CREATE PROCEDURE statement. Swap PROCEDURE for FUNCTION for a stored function.

Formatting dates on X axis in ggplot2

To show months as Jan 2017 Feb 2017 etc:

scale_x_date(date_breaks = "1 month", date_labels =  "%b %Y") 

Angle the dates if they take up too much space:

theme(axis.text.x=element_text(angle=60, hjust=1))

Any easy way to use icons from resources?

Forms maintain separate resource files (SomeForm.Designer.resx) added via the designer. To use icons embedded in another resource file requires codes. (this.Icone = Project.Resources.SomeIcon;)

Xcode : Adding a project as a build dependency

To add it as a dependency do the following:

  • Highlight the added project in your file explorer within xcode. In the directory browser window to the right it should show a file with a .a extension. There is a checkbox under the target column (target icon), check it.
  • Right-Click on your Target (under the targets item in the file explorer) and choose Get Info
  • On the general tab is a Direct Dependencies section. Hit the plus button
  • Choose the project and click Add Target

Passing HTML input value as a JavaScript Function Parameter

You can get the values with use of ID. But ID should be Unique.

<body>
<h1>Adding 'a' and 'b'</h1>
<form>
  a: <input type="number" name="a" id="a"><br>
  b: <input type="number" name="b" id="b"><br>
  <button onclick="add()">Add</button>
</form>
<script>
  function add() {
    a = $('#a').val();
    b = $('#b').val();
    var sum = a + b;
    alert(sum);
  }
</script>
</body>

Populating Spring @Value during Unit Test

Since Spring 4.1 you could set up property values just in code by using org.springframework.test.context.TestPropertySource annotation on Unit Tests class level. You could use this approach even for injecting properties into dependent bean instances

For example

@RunWith(SpringJUnit4ClassRunner.class)
@ContextConfiguration(classes = FooTest.Config.class)
@TestPropertySource(properties = {
    "some.bar.value=testValue",
})
public class FooTest {

  @Value("${some.bar.value}")
  String bar;

  @Test
  public void testValueSetup() {
    assertEquals("testValue", bar);
  }


  @Configuration
  static class Config {

    @Bean
    public static PropertySourcesPlaceholderConfigurer propertiesResolver() {
        return new PropertySourcesPlaceholderConfigurer();
    }

  }

}

Note: It's necessary to have instance of org.springframework.context.support.PropertySourcesPlaceholderConfigurer in Spring context

Edit 24-08-2017: If you are using SpringBoot 1.4.0 and later you could initialize tests with @SpringBootTest and @SpringBootConfiguration annotations. More info here

In case of SpringBoot we have following code

@SpringBootTest
@SpringBootConfiguration
@RunWith(SpringJUnit4ClassRunner.class)
@TestPropertySource(properties = {
    "some.bar.value=testValue",
})
public class FooTest {

  @Value("${some.bar.value}")
  String bar;

  @Test
  public void testValueSetup() {
    assertEquals("testValue", bar);
  }

}

Java ArrayList for integers

The [] makes no sense in the moment of making an ArrayList of Integers because I imagine you just want to add Integer values. Just use

List<Integer> list = new ArrayList<>();

to create the ArrayList and it will work.

Python Database connection Close

You can wrap the whole connection in a context manager, like the following:

from contextlib import contextmanager
import pyodbc
import sys

@contextmanager
def open_db_connection(connection_string, commit=False):
    connection = pyodbc.connect(connection_string)
    cursor = connection.cursor()
    try:
        yield cursor
    except pyodbc.DatabaseError as err:
        error, = err.args
        sys.stderr.write(error.message)
        cursor.execute("ROLLBACK")
        raise err
    else:
        if commit:
            cursor.execute("COMMIT")
        else:
            cursor.execute("ROLLBACK")
    finally:
        connection.close()

Then do something like this where ever you need a database connection:

with open_db_connection("...") as cursor:
    # Your code here

The connection will close when you leave the with block. This will also rollback the transaction if an exception occurs or if you didn't open the block using with open_db_connection("...", commit=True).

Compile a DLL in C/C++, then call it from another program

For VB6:

You need to declare your C functions as __stdcall, otherwise you get "invalid calling convention" type errors. About other your questions:

can I take arguments by pointer/reference from the VB front-end?

Yes, use ByRef/ByVal modifiers.

Can the DLL call a theoretical function in the front-end?

Yes, use AddressOf statement. You need to pass function pointer to dll before.

Or have a function take a "function pointer" (I don't even know if that's possible) from VB and call it?)

Yes, use AddressOf statement.

update (more questions appeared :)):

to load it into VB, do I just do the usual method (what I would do to load winsock.ocx or some other runtime, but find my DLL instead) or do I put an API call into a module?

You need to decaler API function in VB6 code, like next:

Private Declare Function SHGetSpecialFolderLocation Lib "shell32" _
   (ByVal hwndOwner As Long, _
    ByVal nFolder As Long, _
    ByRef pidl As Long) As Long

Create a unique number with javascript time

let uuid = ((new Date().getTime()).toString(36))+'_'+(Date.now() + Math.random().toString()).split('.').join("_")

sample result "k3jobnvt_15750033412250_18299601769317408"

Open Bootstrap Modal from code-behind

How about doing it like this:

1) show popup with form

2) submit form using AJAX

3) in AJAX server side code, render response that will either:

  • show popup with form with validations or just a message
  • close the popup (and maybe redirect you to new page)

Add a default value to a column through a migration

For Rails 4+, use change_column_default

def change
  change_column_default :table, :column, value
end