Programs & Examples On #Microsoft glee

GLEE (Graph Layout Execution Engine) is the now-obsolete name for Microsoft Automatic Graph Layout (MSAGL), a .NET library for automatic graph layout based on layered graph drawing ("Sugiyama style"). Not to be confused with OpenGL Easy Extension library.

AngularJS : ng-model binding not updating when changed with jQuery

Whatever happens outside the Scope of Angular, Angular will never know that.

Digest cycle put the changes from the model -> controller and then from controller -> model.

If you need to see the latest Model, you need to trigger the digest cycle

But there is a chance of a digest cycle in progress, so we need to check and init the cycle.

Preferably, always perform a safe apply.

       $scope.safeApply = function(fn) {
            if (this.$root) {
                var phase = this.$root.$$phase;
                if (phase == '$apply' || phase == '$digest') {
                    if (fn && (typeof (fn) === 'function')) {
                        fn();
                    }
                } else {
                    this.$apply(fn);
                }
            }
        };


      $scope.safeApply(function(){
          // your function here.
      });

Generate full SQL script from EF 5 Code First Migrations

For anyone using entity framework core ending up here. This is how you do it.

# Powershell / Package manager console
Script-Migration

# Cli 
dotnet ef migrations script

You can use the -From and -To parameter to generate an update script to update a database to a specific version.

Script-Migration -From 20190101011200_Initial-Migration -To 20190101021200_Migration-2

https://docs.microsoft.com/en-us/ef/core/managing-schemas/migrations/#generate-sql-scripts

There are several options to this command.

The from migration should be the last migration applied to the database before running the script. If no migrations have been applied, specify 0 (this is the default).

The to migration is the last migration that will be applied to the database after running the script. This defaults to the last migration in your project.

An idempotent script can optionally be generated. This script only applies migrations if they haven't already been applied to the database. This is useful if you don't exactly know what the last migration applied to the database was or if you are deploying to multiple databases that may each be at a different migration.

how to toggle (hide/show) a table onClick of <a> tag in java script

You are trying to alter the behaviour of onclick inside the same function call. Try it like this:

Anchor tag

<a id="loginLink" onclick="toggleTable();" href="#">Login</a>

JavaScript

function toggleTable() {
    var lTable = document.getElementById("loginTable");
    lTable.style.display = (lTable.style.display == "table") ? "none" : "table";
}

How to decode HTML entities using jQuery?

I think you're confusing the text and HTML methods. Look at this example, if you use an element's inner HTML as text, you'll get decoded HTML tags (second button). But if you use them as HTML, you'll get the HTML formatted view (first button).

<div id="myDiv">
    here is a <b>HTML</b> content.
</div>
<br />
<input value="Write as HTML" type="button" onclick="javascript:$('#resultDiv').html($('#myDiv').html());" />
&nbsp;&nbsp;
<input value="Write as Text" type="button" onclick="javascript:$('#resultDiv').text($('#myDiv').html());" />
<br /><br />
<div id="resultDiv">
    Results here !
</div>

First button writes : here is a HTML content.

Second button writes : here is a <B>HTML</B> content.

By the way, you can see a plug-in that I found in jQuery plugin - HTML decode and encode that encodes and decodes HTML strings.

PHP, get file name without file extension

@fire incase the filename uses dots, you could get the wrong output. I would use @Gordon method but get the extension too, so the basename function works with all extensions, like this:

$path = "/home/httpd/html/index.php";
$ext = pathinfo($path, PATHINFO_EXTENSION);

$file = basename($path, ".".$ext); // $file is set to "index"

How to automatically update an application without ClickOnce?

There are a lot of questions already about this, so I will refer you to those.

One thing you want to make sure to prevent the need for uninstallation, is that you use the same upgrade code on every release, but change the product code. These values are located in the Installshield project properties.

Some references:

Redirect website after certain amount of time

Place the following HTML redirect code between the and tags of your HTML code.

<meta HTTP-EQUIV="REFRESH" content="3; url=http://www.yourdomain.com/index.html">

The above HTML redirect code will redirect your visitors to another web page instantly. The content="3; may be changed to the number of seconds you want the browser to wait before redirecting. 4, 5, 8, 10 or 15 seconds, etc.

Reading file from Workspace in Jenkins with Groovy script

As mentioned in a different post Read .txt file from workspace groovy script in Jenkins I was struggling to make it work for the pom modules for a file in the workspace, in the Extended Choice Parameter. Here is my solution with the printlns:

import groovy.util.XmlSlurper
import java.util.Map
import jenkins.*
import jenkins.model.*
import hudson.*
import hudson.model.*    

try{
//get Jenkins instance
    def jenkins = Jenkins.instance
//get job Item
    def item = jenkins.getItemByFullName("The_JOB_NAME")
    println item
// get workspacePath for the job Item
    def workspacePath = jenkins.getWorkspaceFor (item)
    println workspacePath

    def file = new File(workspacePath.toString()+"\\pom.xml")
    def pomFile = new XmlSlurper().parse(file)
    def pomModules = pomFile.modules.children().join(",")
    return pomModules
} catch (Exception ex){
    println ex.message
}

How do I use shell variables in an awk script?

Getting shell variables into awk

may be done in several ways. Some are better than others. This should cover most of them. If you have a comment, please leave below.                                                                                    v1.5


Using -v (The best way, most portable)

Use the -v option: (P.S. use a space after -v or it will be less portable. E.g., awk -v var= not awk -vvar=)

variable="line one\nline two"
awk -v var="$variable" 'BEGIN {print var}'
line one
line two

This should be compatible with most awk, and the variable is available in the BEGIN block as well:

If you have multiple variables:

awk -v a="$var1" -v b="$var2" 'BEGIN {print a,b}'

Warning. As Ed Morton writes, escape sequences will be interpreted so \t becomes a real tab and not \t if that is what you search for. Can be solved by using ENVIRON[] or access it via ARGV[]

PS If you like three vertical bar as separator |||, it can't be escaped, so use -F"[|][|][|]"

Example on getting data from a program/function inn to awk (here date is used)

awk -v time="$(date +"%F %H:%M" -d '-1 minute')" 'BEGIN {print time}'

Variable after code block

Here we get the variable after the awk code. This will work fine as long as you do not need the variable in the BEGIN block:

variable="line one\nline two"
echo "input data" | awk '{print var}' var="${variable}"
or
awk '{print var}' var="${variable}" file
  • Adding multiple variables:

awk '{print a,b,$0}' a="$var1" b="$var2" file

  • In this way we can also set different Field Separator FS for each file.

awk 'some code' FS=',' file1.txt FS=';' file2.ext

  • Variable after the code block will not work for the BEGIN block:

echo "input data" | awk 'BEGIN {print var}' var="${variable}"


Here-string

Variable can also be added to awk using a here-string from shells that support them (including Bash):

awk '{print $0}' <<< "$variable"
test

This is the same as:

printf '%s' "$variable" | awk '{print $0}'

P.S. this treats the variable as a file input.


ENVIRON input

As TrueY writes, you can use the ENVIRON to print Environment Variables. Setting a variable before running AWK, you can print it out like this:

X=MyVar
awk 'BEGIN{print ENVIRON["X"],ENVIRON["SHELL"]}'
MyVar /bin/bash

ARGV input

As Steven Penny writes, you can use ARGV to get the data into awk:

v="my data"
awk 'BEGIN {print ARGV[1]}' "$v"
my data

To get the data into the code itself, not just the BEGIN:

v="my data"
echo "test" | awk 'BEGIN{var=ARGV[1];ARGV[1]=""} {print var, $0}' "$v"
my data test

Variable within the code: USE WITH CAUTION

You can use a variable within the awk code, but it's messy and hard to read, and as Charles Duffy points out, this version may also be a victim of code injection. If someone adds bad stuff to the variable, it will be executed as part of the awk code.

This works by extracting the variable within the code, so it becomes a part of it.

If you want to make an awk that changes dynamically with use of variables, you can do it this way, but DO NOT use it for normal variables.

variable="line one\nline two"
awk 'BEGIN {print "'"$variable"'"}'
line one
line two

Here is an example of code injection:

variable='line one\nline two" ; for (i=1;i<=1000;++i) print i"'
awk 'BEGIN {print "'"$variable"'"}'
line one
line two
1
2
3
.
.
1000

You can add lots of commands to awk this way. Even make it crash with non valid commands.


Extra info:

Use of double quote

It's always good to double quote variable "$variable"
If not, multiple lines will be added as a long single line.

Example:

var="Line one
This is line two"

echo $var
Line one This is line two

echo "$var"
Line one
This is line two

Other errors you can get without double quote:

variable="line one\nline two"
awk -v var=$variable 'BEGIN {print var}'
awk: cmd. line:1: one\nline
awk: cmd. line:1:    ^ backslash not last character on line
awk: cmd. line:1: one\nline
awk: cmd. line:1:    ^ syntax error

And with single quote, it does not expand the value of the variable:

awk -v var='$variable' 'BEGIN {print var}'
$variable

More info about AWK and variables

Read this faq.

docker cannot start on windows

I had the same problem.

Starting the docker daemon resolved the issue. Just search for docker pressing windows key and click on "Docker Dekstop". Daemon should be running in a minute. enter image description here

Invalid argument supplied for foreach()

More concise extension of @Kris's code

function secure_iterable($var)
{
    return is_iterable($var) ? $var : array();
}

foreach (secure_iterable($values) as $value)
{
     //do stuff...
}

especially for using inside template code

<?php foreach (secure_iterable($values) as $value): ?>
    ...
<?php endforeach; ?>

How can I add additional PHP versions to MAMP

First stop the Server if its running. Go to "/Applications/MAMP/bin/", rename the PHP Version you don't need (MAMP is only allowed to use 2 PHP Versions), e.g. "_php5.2.17". Now MAMP will use the php versions that are left. Go to the MAMP Manager and then settings, then switch to the php version you need.

One problem with this solution I encountered was the httpd process (took me a while to figure that out xD). If you have the httpd process running in the background, then the php switch won't work, until you stop those processes (sometimes MAMP has an awkward problem to stop the server, thats why this process can be still alive). Start your Activity Monitor on your Mac (Shortcut: Press Command+Space and type in activity...), go to the Search Function and type in "httpd", close all those processes. Now you should be able to switch your PHP Version with the MAMP Manager.

Window vs Page vs UserControl for WPF navigation?

A Window object is just what it sounds like: its a new Window for your application. You should use it when you want to pop up an entirely new window. I don't often use more than one Window in WPF because I prefer to put dynamic content in my main Window that changes based on user action.

A Page is a page inside your Window. It is mostly used for web-based systems like an XBAP, where you have a single browser window and different pages can be hosted in that window. It can also be used in Navigation Applications like sellmeadog said.

A UserControl is a reusable user-created control that you can add to your UI the same way you would add any other control. Usually I create a UserControl when I want to build in some custom functionality (for example, a CalendarControl), or when I have a large amount of related XAML code, such as a View when using the MVVM design pattern.

When navigating between windows, you could simply create a new Window object and show it

var NewWindow = new MyWindow();
newWindow.Show();

but like I said at the beginning of this answer, I prefer not to manage multiple windows if possible.

My preferred method of navigation is to create some dynamic content area using a ContentControl, and populate that with a UserControl containing whatever the current view is.

<Window x:Class="MyNamespace.MainWindow" ...>
    <DockPanel>
        <ContentControl x:Name="ContentArea" />
    </DockPanel>
</Window>

and in your navigate event you can simply set it using

ContentArea.Content = new MyUserControl();

But if you're working with WPF, I'd highly recommend the MVVM design pattern. I have a very basic example on my blog that illustrates how you'd navigate using MVVM, using this pattern:

<Window x:Class="SimpleMVVMExample.ApplicationView"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:local="clr-namespace:SimpleMVVMExample"
        Title="Simple MVVM Example" Height="350" Width="525">

   <Window.Resources>
      <DataTemplate DataType="{x:Type local:HomeViewModel}">
         <local:HomeView /> <!-- This is a UserControl -->
      </DataTemplate>
      <DataTemplate DataType="{x:Type local:ProductsViewModel}">
         <local:ProductsView /> <!-- This is a UserControl -->
      </DataTemplate>
   </Window.Resources>

   <DockPanel>
      <!-- Navigation Buttons -->
      <Border DockPanel.Dock="Left" BorderBrush="Black"
                                    BorderThickness="0,0,1,0">
         <ItemsControl ItemsSource="{Binding PageViewModels}">
            <ItemsControl.ItemTemplate>
               <DataTemplate>
                  <Button Content="{Binding Name}"
                          Command="{Binding DataContext.ChangePageCommand,
                             RelativeSource={RelativeSource AncestorType={x:Type Window}}}"
                          CommandParameter="{Binding }"
                          Margin="2,5"/>
               </DataTemplate>
            </ItemsControl.ItemTemplate>
         </ItemsControl>
      </Border>

      <!-- Content Area -->
      <ContentControl Content="{Binding CurrentPageViewModel}" />
   </DockPanel>
</Window>

Screenshot1 Screenshot2

String.Format for Hex

You can also pad the characters left by including a number following the X, such as this: string.format("0x{0:X8}", string_to_modify), which yields "0x00000C20".

How do I change the language of moment.js?

I had to import also the language:

import moment from 'moment'
import 'moment/locale/es'  // without this line it didn't work
moment.locale('es')

Then use moment like you normally would

alert(moment(date).fromNow())

Iterate all files in a directory using a 'for' loop

Here's my go with comments in the code.

I'm just brushing up by biatch skills so forgive any blatant errors.

I tried to write an all in one solution as best I can with a little modification where the user requires it.

Some important notes: Just change the variable recursive to FALSE if you only want the root directories files and folders processed. Otherwise, it goes through all folders and files.

C&C most welcome...

@echo off
title %~nx0
chcp 65001 >NUL
set "dir=c:\users\%username%\desktop"
::
:: Recursive Loop routine - First Written by Ste on - 2020.01.24 - Rev 1
::
setlocal EnableDelayedExpansion
rem THIS IS A RECURSIVE SOLUTION [ALBEIT IF YOU CHANGE THE RECURSIVE TO FALSE, NO]
rem By removing the /s switch from the first loop if you want to loop through
rem the base folder only.
set recursive=TRUE
if %recursive% equ TRUE ( set recursive=/s ) else ( set recursive= )
endlocal & set recursive=%recursive%
cd /d %dir%
echo Directory %cd%
for %%F in ("*") do (echo    ? %%F)                                 %= Loop through the current directory. =%
for /f "delims==" %%D in ('dir "%dir%" /ad /b %recursive%') do (    %= Loop through the sub-directories only if the recursive variable is TRUE. =%
  echo Directory %%D
  echo %recursive% | find "/s" >NUL 2>NUL && (
    pushd %%D
    cd /d %%D
    for /f "delims==" %%F in ('dir "*" /b') do (                      %= Then loop through each pushd' folder and work on the files and folders =%
      echo %%~aF | find /v "d" >NUL 2>NUL && (                        %= This will weed out the directories by checking their attributes for the lack of 'd' with the /v switch therefore you can now work on the files only. =%
      rem You can do stuff to your files here.
      rem Below are some examples of the info you can get by expanding the %%F variable.
      rem Uncomment one at a time to see the results.
      echo    ? %%~F           &rem expands %%F removing any surrounding quotes (")
      rem echo    ? %%~dF          &rem expands %%F to a drive letter only
      rem echo    ? %%~fF          &rem expands %%F to a fully qualified path name
      rem echo    ? %%~pF          &rem expands %%A to a path only
      rem echo    ? %%~nF          &rem expands %%F to a file name only
      rem echo    ? %%~xF          &rem expands %%F to a file extension only
      rem echo    ? %%~sF          &rem expanded path contains short names only
      rem echo    ? %%~aF          &rem expands %%F to file attributes of file
      rem echo    ? %%~tF          &rem expands %%F to date/time of file
      rem echo    ? %%~zF          &rem expands %%F to size of file
      rem echo    ? %%~dpF         &rem expands %%F to a drive letter and path only
      rem echo    ? %%~nxF         &rem expands %%F to a file name and extension only
      rem echo    ? %%~fsF         &rem expands %%F to a full path name with short names only
      rem echo    ? %%~dp$dir:F    &rem searches the directories listed in the 'dir' environment variable and expands %%F to the fully qualified name of the first one found. If the environment variable name is not defined or the file is not found by the search, then this modifier expands to the empty string
      rem echo    ? %%~ftzaF       &rem expands %%F to a DIR like output line
      )
      )
    popd
    )
  )
echo/ & pause & cls

How to set the min and max height or width of a Frame?

There is no single magic function to force a frame to a minimum or fixed size. However, you can certainly force the size of a frame by giving the frame a width and height. You then have to do potentially two more things: when you put this window in a container you need to make sure the geometry manager doesn't shrink or expand the window. Two, if the frame is a container for other widget, turn grid or pack propagation off so that the frame doesn't shrink or expand to fit its own contents.

Note, however, that this won't prevent you from resizing a window to be smaller than an internal frame. In that case the frame will just be clipped.

import Tkinter as tk

root = tk.Tk()
frame1 = tk.Frame(root, width=100, height=100, background="bisque")
frame2 = tk.Frame(root, width=50, height = 50, background="#b22222")

frame1.pack(fill=None, expand=False)
frame2.place(relx=.5, rely=.5, anchor="c")

root.mainloop()

How to install plugins to Sublime Text 2 editor?

Install the Package Control first.

The simplest method of installation is through the Sublime Text console. The console is accessed via the Ctrl+` shortcut or the View > Show Console menu. Once open, paste the appropriate Python code for your version of Sublime Text into the console.

Code for Sublime Text 3

import urllib.request,os; pf = 'Package Control.sublime-package'; ipp = sublime.installed_packages_path(); urllib.request.install_opener( urllib.request.build_opener( urllib.request.ProxyHandler()) ); open(os.path.join(ipp, pf), 'wb').write(urllib.request.urlopen( 'http://sublime.wbond.net/' + pf.replace(' ','%20')).read())

Code for Sublime Text 2

import urllib2,os; pf='Package Control.sublime-package'; ipp = sublime.installed_packages_path(); os.makedirs( ipp ) if not os.path.exists(ipp) else None; urllib2.install_opener( urllib2.build_opener( urllib2.ProxyHandler( ))); open( os.path.join( ipp, pf), 'wb' ).write( urllib2.urlopen( 'http://sublime.wbond.net/' +pf.replace( ' ','%20' )).read()); print( 'Please restart Sublime Text to finish installation')

For the up-to-date installation code, please check Package Control Installation Guide.

Manual

If for some reason the console installation instructions do not work for you (such as having a proxy on your network), perform the following steps to manually install Package Control:

  1. Click the Preferences > Browse Packages… menu
  2. Browse up a folder and then into the Installed Packages/ folder
  3. Download Package Control.sublime-package and copy it into the Installed Packages/ directory
  4. Restart Sublime Text

Usage

Package Control is driven by the Command Pallete. To open the pallete, press Ctrl+Shift+p (Win, Linux) or CMD+Shift+p (OSX). All Package Control commands begin with Package Control:, so start by typing Package.

Swift - Split string over multiple lines

Swift:

@connor is the right answer, but if you want to add lines in a print statement what you are looking for is \n and/or \r, these are called Escape Sequences or Escaped Characters, this is a link to Apple documentation on the topic..

Example:

print("First line\nSecond Line\rThirdLine...")

Docker error: invalid reference format: repository name must be lowercase

"docker build -f Dockerfile -t SpringBoot-Docker ." As in the above commend, we are creating an image file for docker container. commend says create image use file(-f refer to docker file) and -t for the target of the image file we are going to push to docker. the "." represents the current directory

solution for the above problem: provide target image name in lowercase

Difference between using bean id and name in Spring configuration file

Either one would work. It depends on your needs:
If your bean identifier contains special character(s) for example (/viewSummary.html), it wont be allowed as the bean id, because it's not a valid XML ID. In such cases you could skip defining the bean id and supply the bean name instead.
The name attribute also helps in defining aliases for your bean, since it allows specifying multiple identifiers for a given bean.

label or @html.Label ASP.net MVC 4

The helpers are there mainly to help you display labels, form inputs, etc for the strongly typed properties of your model. By using the helpers and Visual Studio Intellisense, you can greatly reduce the number of typos that you could make when generating a web page.

With that said, you can continue to create your elements manually for both properties of your view model or items that you want to display that are not part of your view model.

angular.js ng-repeat li items with html content

use ng-bind-html-unsafe

it will apply html with text inside like below:

    <li ng-repeat=" opt in opts" ng-bind-html-unsafe="opt.text" >
        {{ opt.text }}
    </li>

What was the strangest coding standard rule that you were forced to follow?

If I remember correctly the delphi IDE did a default indent of two spaces. Most of the legacy code for the company had three spaces and was written by the VP IT and the CEO. One day, all the programmers were talking about what we should do to make our lives easier and a contractor who knew Delphi pretty well said, "Hey the ide defaults to two spaces does anyone have a problem with us doing this going forward for new code?" All of us looked at each other, and pretty much thought it was a no brainer and said that we agreed.

Two days later the VP and CEO found out we were going to make such a dangerous change that could "cause problems" and instructed us that we would be using three indents for everything until the two of them could accurately evaluate the impact of such a change. Now I am all for following standards, but these are the same people who thought oo programming was creating an object with one function that had all of the logic necessary to perform an action, and that source control was moving the code files to a different directory.

How to check whether java is installed on the computer

Type in the command window

java -version

If it gives an output everything should be fine. If you want to develop software you might want to set the PATH.

X-Frame-Options on apache

This worked for me on all browsers:

  1. Created one page with all my javascript
  2. Created a 2nd page on the same server and embedded the first page using the object tag.
  3. On my third party site I used the Object tag to embed the 2nd page.
  4. Created a .htaccess file on the original server in the public_html folder and put Header unset X-Frame-Options in it.

Join two data frames, select all columns from one and some columns from the other

drop duplicate b_id

c = a.join(b, a.a_id == b.b_id).drop(b.b_id)

Renaming branches remotely in Git

If you really just want to rename branches remotely, without renaming any local branches at the same time, you can do this with a single command:

git push <remote> <remote>/<old_name>:refs/heads/<new_name> :<old_name>

I wrote this script (git-rename-remote-branch) which provides a handy shortcut to do the above easily.

As a bash function:

git-rename-remote-branch(){
  if [ $# -ne 3 ]; then
    echo "Rationale : Rename a branch on the server without checking it out."
    echo "Usage     : ${FUNCNAME[0]} <remote> <old name> <new name>"
    echo "Example   : ${FUNCNAME[0]} origin master release"
    return 1 
  fi

  git push $1 $1/$2\:refs/heads/$3 :$2
}

To integrate @ksrb's comment: What this basically does is two pushes in a single command, first git push <remote> <remote>/<old_name>:refs/heads/<new_name> to push a new remote branch based on the old remote tracking branch and then git push <remote> :<old_name> to delete the old remote branch.

How do I separate an integer into separate digits in an array in JavaScript?

What about:

const n = 123456;
Array.from(n.toString()).map(Number);
// [1, 2, 3, 4, 5, 6]

how to generate public key from windows command prompt

ssh-keygen isn't a windows executable.
You can use PuttyGen (http://www.chiark.greenend.org.uk/~sgtatham/putty/download.html) for example to create a key

Rails: How can I set default values in ActiveRecord?

class Item < ActiveRecord::Base
  def status
    self[:status] or ACTIVE
  end

  before_save{ self.status ||= ACTIVE }
end

What is the difference between task and thread?

In addition to above points, it would be good to know that:

  1. A task is by default a background task. You cannot have a foreground task. On the other hand a thread can be background or foreground (Use IsBackground property to change the behavior).
  2. Tasks created in thread pool recycle the threads which helps save resources. So in most cases tasks should be your default choice.
  3. If the operations are quick, it is much better to use a task instead of thread. For long running operations, tasks do not provide much advantages over threads.

How do I install command line MySQL client on mac?

For installing mysql-shell with homebrew, run

brew cask install mysql-shell

you can then launch the mysql shell with

mysqlsh

if you want to enter SQL mode directly, run

mysqlsh --sql

sqlalchemy filter multiple columns

There are number of ways to do it:

Using filter() (and operator)

query = meta.Session.query(User).filter(
    User.firstname.like(search_var1),
    User.lastname.like(search_var2)
    )

Using filter_by() (and operator)

query = meta.Session.query(User).filter_by(
    firstname.like(search_var1),
    lastname.like(search_var2)
    )

Chaining filter() or filter_by() (and operator)

query = meta.Session.query(User).\
    filter_by(firstname.like(search_var1)).\
    filter_by(lastname.like(search_var2))

Using or_(), and_(), and not()

from sqlalchemy import and_, or_, not_

query = meta.Session.query(User).filter(
    and_(
        User.firstname.like(search_var1),
        User.lastname.like(search_var2)
    )
)

How can I make robocopy silent in the command line except for progress?

A workaround, if you want it to be absolutely silent, is to redirect the output to a file (and optionally delete it later).

Robocopy src dest > output.log
del output.log

How to detect input type=file "change" for the same file?

This work for me

<input type="file" onchange="function();this.value=null;return false;">

PHP How to find the time elapsed since a date time?

I liked Mithun's code, but I tweaked it a bit to make it give more reasonable answers.

function getTimeSince($eventTime)
{
    $totaldelay = time() - strtotime($eventTime);
    if($totaldelay <= 0)
    {
        return '';
    }
    else
    {
        $first = '';
        $marker = 0;
        if($years=floor($totaldelay/31536000))
        {
            $totaldelay = $totaldelay % 31536000;
            $plural = '';
            if ($years > 1) $plural='s';
            $interval = $years." year".$plural;
            $timesince = $timesince.$first.$interval;
            if ($marker) return $timesince;
            $marker = 1;
            $first = ", ";
        }
        if($months=floor($totaldelay/2628000))
        {
            $totaldelay = $totaldelay % 2628000;
            $plural = '';
            if ($months > 1) $plural='s';
            $interval = $months." month".$plural;
            $timesince = $timesince.$first.$interval;
            if ($marker) return $timesince;
            $marker = 1;
            $first = ", ";
        }
        if($days=floor($totaldelay/86400))
        {
            $totaldelay = $totaldelay % 86400;
            $plural = '';
            if ($days > 1) $plural='s';
            $interval = $days." day".$plural;
            $timesince = $timesince.$first.$interval;
            if ($marker) return $timesince;
            $marker = 1;
            $first = ", ";
        }
        if ($marker) return $timesince;
        if($hours=floor($totaldelay/3600))
        {
            $totaldelay = $totaldelay % 3600;
            $plural = '';
            if ($hours > 1) $plural='s';
            $interval = $hours." hour".$plural;
            $timesince = $timesince.$first.$interval;
            if ($marker) return $timesince;
            $marker = 1;
            $first = ", ";

        }
        if($minutes=floor($totaldelay/60))
        {
            $totaldelay = $totaldelay % 60;
            $plural = '';
            if ($minutes > 1) $plural='s';
            $interval = $minutes." minute".$plural;
            $timesince = $timesince.$first.$interval;
            if ($marker) return $timesince;
            $first = ", ";
        }
        if($seconds=floor($totaldelay/1))
        {
            $totaldelay = $totaldelay % 1;
            $plural = '';
            if ($seconds > 1) $plural='s';
            $interval = $seconds." second".$plural;
            $timesince = $timesince.$first.$interval;
        }        
        return $timesince;

    }
}

Import txt file and having each line as a list

with open('path/to/file') as infile: # try open('...', 'rb') as well
    answer = [line.strip().split(',') for line in infile]

If you want the numbers as ints:

with open('path/to/file') as infile:
    answer = [[int(i) for i in line.strip().split(',')] for line in infile]

How to check if a file exists from inside a batch file

if exist <insert file name here> (
    rem file exists
) else (
    rem file doesn't exist
)

Or on a single line (if only a single action needs to occur):

if exist <insert file name here> <action>

for example, this opens notepad on autoexec.bat, if the file exists:

if exist c:\autoexec.bat notepad c:\autoexec.bat

If...Then...Else with multiple statements after Then

Multiple statements are to be separated by a new line:

If SkyIsBlue Then
  StartEngines
  Pollute
ElseIf SkyIsRed Then
  StopAttack
  Vent
ElseIf SkyIsYellow Then
  If Sunset Then
    Sleep
  ElseIf Sunrise or IsMorning Then
    Smoke
    GetCoffee
  Else
    Error
  End If
Else
  Joke
  Laugh
End If

CR LF notepad++ removal

View -> Show Symbol -> uncheck Show End of Line.

Error: Cannot find module 'gulp-sass'

Edit your package.json. Change:

"gulp-sass": "^2.3.2"

to

"gulp-sass": "3.0.0"

Delete the node_modules folder and run npm install again.

Source: https://github.com/codecombat/codecombat/issues/4430#issuecomment-348927771

How can I emulate a get request exactly like a web browser?

i'll make an example, first decide what browser you want to emulate, in this case i chose Firefox 60.6.1esr (64-bit), and check what GET request it issues, this can be obtained with a simple netcat server (MacOS bundles netcat, most linux distributions bunles netcat, and Windows users can get netcat from.. Cygwin.org , among other places),

setting up the netcat server to listen on port 9999: nc -l 9999

now hitting http://127.0.0.1:9999 in firefox, i get:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1

now let us compare that with this simple script:

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_exec($ch);

i get:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
Accept: */*

there are several missing headers here, they can all be added with the CURLOPT_HTTPHEADER option of curl_setopt, but the User-Agent specifically should be set with CURLOPT_USERAGENT instead (it will be persistent across multiple calls to curl_exec() and if you use CURLOPT_FOLLOWLOCATION then it will persist across http redirections as well), and the Accept-Encoding header should be set with CURLOPT_ENCODING instead (if they're set with CURLOPT_ENCODING then curl will automatically decompress the response if the server choose to compress it, but if you set it via CURLOPT_HTTPHEADER then you must manually detect and decompress the content yourself, which is a pain in the ass and completely unnecessary, generally speaking) so adding those we get:

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_setopt_array($ch,array(
        CURLOPT_USERAGENT=>'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0',
        CURLOPT_ENCODING=>'gzip, deflate',
        CURLOPT_HTTPHEADER=>array(
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language: en-US,en;q=0.5',
                'Connection: keep-alive',
                'Upgrade-Insecure-Requests: 1',
        ),
));
curl_exec($ch);

now running that code, our netcat server gets:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept-Encoding: gzip, deflate
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Connection: keep-alive
Upgrade-Insecure-Requests: 1

and voila! our php-emulated browser GET request should now be indistinguishable from the real firefox GET request :)

this next part is just nitpicking, but if you look very closely, you'll see that the headers are stacked in the wrong order, firefox put the Accept-Encoding header in line 6, and our emulated GET request puts it in line 3.. to fix this, we can manually put the Accept-Encoding header in the right line,

<?php
$ch=curl_init("http://127.0.0.1:9999");
curl_setopt_array($ch,array(
        CURLOPT_USERAGENT=>'Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0',
        CURLOPT_ENCODING=>'gzip, deflate',
        CURLOPT_HTTPHEADER=>array(
                'Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8',
                'Accept-Language: en-US,en;q=0.5',
                'Accept-Encoding: gzip, deflate',
                'Connection: keep-alive',
                'Upgrade-Insecure-Requests: 1',
        ),
));
curl_exec($ch);

running that, our netcat server gets:

$ nc -l 9999
GET / HTTP/1.1
Host: 127.0.0.1:9999
User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:60.0) Gecko/20100101 Firefox/60.0
Accept: text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8
Accept-Language: en-US,en;q=0.5
Accept-Encoding: gzip, deflate
Connection: keep-alive
Upgrade-Insecure-Requests: 1

problem solved, now the headers is even in the correct order, and the request seems to be COMPLETELY INDISTINGUISHABLE from the real firefox request :) (i don't actually recommend this last step, it's a maintenance burden to keep CURLOPT_ENCODING in sync with the custom Accept-Encoding header, and i've never experienced a situation where the order of the headers are significant)

Regular expression to find URLs within a string

I think this regex pattern handle precisely what you want

/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/

and this is an snippet example to extract Urls:

// The Regular Expression filter
$reg_exUrl = "/(http|https|ftp|ftps)\:\/\/[a-zA-Z0-9\-\.]+\.[a-zA-Z]{2,3}(\/\S*)?/";

// The Text you want to filter for urls
$text = "The text you want  https://stackoverflow.com/questions/6038061/regular-expression-to-find-urls-within-a-string to filter goes here.";

// Check if there is a url in the text
preg_match_all($reg_exUrl, $text, $url,$matches);
var_dump($matches);

Difference between / and /* in servlet mapping url pattern

<url-pattern>/*</url-pattern>

The /* on a servlet overrides all other servlets, including all servlets provided by the servletcontainer such as the default servlet and the JSP servlet. Whatever request you fire, it will end up in that servlet. This is thus a bad URL pattern for servlets. Usually, you'd like to use /* on a Filter only. It is able to let the request continue to any of the servlets listening on a more specific URL pattern by calling FilterChain#doFilter().

<url-pattern>/</url-pattern>

The / doesn't override any other servlet. It only replaces the servletcontainer's builtin default servlet for all requests which doesn't match any other registered servlet. This is normally only invoked on static resources (CSS/JS/image/etc) and directory listings. The servletcontainer's builtin default servlet is also capable of dealing with HTTP cache requests, media (audio/video) streaming and file download resumes. Usually, you don't want to override the default servlet as you would otherwise have to take care of all its tasks, which is not exactly trivial (JSF utility library OmniFaces has an open source example). This is thus also a bad URL pattern for servlets. As to why JSP pages doesn't hit this servlet, it's because the servletcontainer's builtin JSP servlet will be invoked, which is already by default mapped on the more specific URL pattern *.jsp.

<url-pattern></url-pattern>

Then there's also the empty string URL pattern . This will be invoked when the context root is requested. This is different from the <welcome-file> approach that it isn't invoked when any subfolder is requested. This is most likely the URL pattern you're actually looking for in case you want a "home page servlet". I only have to admit that I'd intuitively expect the empty string URL pattern and the slash URL pattern / be defined exactly the other way round, so I can understand that a lot of starters got confused on this. But it is what it is.

Front Controller

In case you actually intend to have a front controller servlet, then you'd best map it on a more specific URL pattern like *.html, *.do, /pages/*, /app/*, etc. You can hide away the front controller URL pattern and cover static resources on a common URL pattern like /resources/*, /static/*, etc with help of a servlet filter. See also How to prevent static resources from being handled by front controller servlet which is mapped on /*. Noted should be that Spring MVC has a builtin static resource servlet, so that's why you could map its front controller on / if you configure a common URL pattern for static resources in Spring. See also How to handle static content in Spring MVC?

Force sidebar height 100% using CSS (with a sticky bottom image)?

I would use css tables to achieve a 100% sidebar height.

The basic idea is to wrap the sidebar and main divs in a container.

Give the container a display:table

And give the 2 child divs (sidebar and main) a display: table-cell

Like so..

#container {
display: table;
}
#main {
display: table-cell;
vertical-align: top;
}
#sidebar {
display: table-cell;
vertical-align: top;
} 

Take a look at this LIVE DEMO where I have modified your initial markup using the above technique (I have used background colors for the different divs so that you can see which ones are which)

How do I rename a column in a SQLite database table?

change table column < id > to < _id >

 String LastId = "id";

    database.execSQL("ALTER TABLE " + PhraseContract.TABLE_NAME + " RENAME TO " + PhraseContract.TABLE_NAME + "old");
    database.execSQL("CREATE TABLE " + PhraseContract.TABLE_NAME
    +"("
            + PhraseContract.COLUMN_ID + " INTEGER PRIMARY KEY,"
            + PhraseContract.COLUMN_PHRASE + " text ,"
            + PhraseContract.COLUMN_ORDER  + " text ,"
            + PhraseContract.COLUMN_FROM_A_LANG + " text"
    +")"
    );
    database.execSQL("INSERT INTO " +
            PhraseContract.TABLE_NAME + "("+ PhraseContract.COLUMN_ID +" , "+ PhraseContract.COLUMN_PHRASE + " , "+ PhraseContract.COLUMN_ORDER +" , "+ PhraseContract.COLUMN_FROM_A_LANG +")" +
            " SELECT " + LastId +" , "+ PhraseContract.COLUMN_PHRASE + " , "+ PhraseContract.COLUMN_ORDER +" , "+ PhraseContract.COLUMN_FROM_A_LANG +
            " FROM " + PhraseContract.TABLE_NAME + "old");
    database.execSQL("DROP TABLE " + PhraseContract.TABLE_NAME + "old");

Benefits of EBS vs. instance-store (and vice-versa)

For someone new to all this and if accidentally landed here

As of now all AMI's in quickstart section are EBS backed

enter image description here

Also there's a good explanation at official doc for difference between EBS and Instance store

& this image pretty much sums it up enter image description here

Is it possible to execute multiple _addItem calls asynchronously using Google Analytics?

From the docs:

_trackTrans() Sends both the transaction and item data to the Google Analytics server. This method should be called after _trackPageview(), and used in conjunction with the _addItem() and addTrans() methods. It should be called after items and transaction elements have been set up.

So, according to the docs, the items get sent when you call trackTrans(). Until you do, you can add items, but the transaction will not be sent.

Edit: Further reading led me here:

http://www.analyticsmarket.com/blog/edit-ecommerce-data

Where it clearly says you can start another transaction with an existing ID. When you commit it, the new items you listed will be added to that transaction.

How to amend older Git commit?

You can use git rebase --interactive, using the edit command on the commit you want to amend.

How do I correctly clone a JavaScript object?

//
// creates 'clone' method on context object
//
//  var 
//     clon = Object.clone( anyValue );
//
!((function (propertyName, definition) {
    this[propertyName] = definition();
}).call(
    Object,
    "clone",
    function () {
        function isfn(fn) {
            return typeof fn === "function";
        }

        function isobj(o) {
            return o === Object(o);
        }

        function isarray(o) {
            return Object.prototype.toString.call(o) === "[object Array]";
        }

        function fnclon(fn) {
            return function () {
                fn.apply(this, arguments);
            };
        }

        function owns(obj, p) {
            return obj.hasOwnProperty(p);
        }

        function isemptyobj(obj) {
            for (var p in obj) {
                return false;
            }
            return true;
        }

        function isObject(o) {
            return Object.prototype.toString.call(o) === "[object Object]";
        }
        return function (input) {
            if (isfn(input)) {
                return fnclon(input);
            } else if (isobj(input)) {
                var cloned = {};
                for (var p in input) {
                    owns(Object.prototype, p)
                    || (
                        isfn(input[p])
                        && ( cloned[p] = function () { return input[p].apply(input, arguments); } )
                        || ( cloned[p] = input[p] )
                    );
                }
                if (isarray(input)) {
                    cloned.length = input.length;
                    "concat every filter forEach indexOf join lastIndexOf map pop push reduce reduceRight reverse shift slice some sort splice toLocaleString toString unshift"
                    .split(" ")
                    .forEach(
                      function (methodName) {
                        isfn( Array.prototype[methodName] )
                        && (
                            cloned[methodName] =
                            function () {
                                return Array.prototype[methodName].apply(cloned, arguments);
                            }
                        );
                      }
                    );
                }
                return isemptyobj(cloned)
                       ? (
                          isObject(input)
                          ? cloned
                          : input
                        )
                       : cloned;
            } else {
                return input;
            }
        };
    }
));
//

Difference between natural join and inner join

Inner join, join two table where column name is same.

Natural join, join two table where column name and data types are same.

Rounding up to next power of 2

Check the Bit Twiddling Hacks. You need to get the base 2 logarithm, then add 1 to that. Example for a 32-bit value:

Round up to the next highest power of 2

unsigned int v; // compute the next highest power of 2 of 32-bit v

v--;
v |= v >> 1;
v |= v >> 2;
v |= v >> 4;
v |= v >> 8;
v |= v >> 16;
v++;

The extension to other widths should be obvious.

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; }
}

Can I have multiple background images using CSS?

Yes, it is possible, and has been implemented by popular usability testing website Silverback. If you look through the source code you can see that the background is made up of several images, placed on top of each other.

Here is the article demonstrating how to do the effect can be found on Vitamin. A similar concept for wrapping these 'onion skin' layers can be found on A List Apart.

Convert UTC to local time in Rails 3

Rails has its own names. See them with:

rake time:zones:us

You can also run rake time:zones:all for all time zones. To see more zone-related rake tasks: rake -D time

So, to convert to EST, catering for DST automatically:

Time.now.in_time_zone("Eastern Time (US & Canada)")

Wordpress - Images not showing up in the Media Library

Here's something a guy on Wordpress forum showed us. Add the following to your functions.php file. (remember to create a backup of your functions.php first)

add_filter( 'wp_image_editors', 'change_graphic_lib' );
function change_graphic_lib($array) {
  return array( 'WP_Image_Editor_GD', 'WP_Image_Editor_Imagick' );
}

...it was that simple.

Change color of PNG image via CSS?

Think I have a solution for this that's a) exactly what you were looking for 5 years ago, and b) is a bit simpler than the other code options here.

With any white png (eg, white icon on transparent background), you can add an ::after selector to recolor.

.icon {
    background: url(img/icon.png); /* Your icon */
    position: relative; /* Allows an absolute positioned psuedo element */
}

.icon::after{
    position: absolute; /* Positions psuedo element relative to .icon */
    width: 100%; /* Same dimensions as .icon */
    height: 100%;
    content: ""; /* Allows psuedo element to show */
    background: #EC008C; /* The color you want the icon to change to */
    mix-blend-mode: multiply; /* Only apply color on top of white, use screen if icon is black */
}

See this codepen (applying the color swap on hover): http://codepen.io/chrscblls/pen/bwAXZO

How do I put a border around an Android textview?

Changing Konstantin Burov answer because not work in my case:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item>
        <shape android:shape="rectangle">
            <solid android:color="@android:color/white" />
            <stroke android:width="2dip" android:color="#4fa5d5"/>
            <corners android:radius="7dp"/>
        </shape>
    </item>
</selector>

compileSdkVersion 26 (Android 8.0), minSdkVersion 21 (Android 5.0), targetSdkVersion 26, implementation 'com.android.support:appcompat-v7:26.1.0', gradle:4.1

What is the copy-and-swap idiom?

There are some good answers already. I'll focus mainly on what I think they lack - an explanation of the "cons" with the copy-and-swap idiom....

What is the copy-and-swap idiom?

A way of implementing the assignment operator in terms of a swap function:

X& operator=(X rhs)
{
    swap(rhs);
    return *this;
}

The fundamental idea is that:

  • the most error-prone part of assigning to an object is ensuring any resources the new state needs are acquired (e.g. memory, descriptors)

  • that acquisition can be attempted before modifying the current state of the object (i.e. *this) if a copy of the new value is made, which is why rhs is accepted by value (i.e. copied) rather than by reference

  • swapping the state of the local copy rhs and *this is usually relatively easy to do without potential failure/exceptions, given the local copy doesn't need any particular state afterwards (just needs state fit for the destructor to run, much as for an object being moved from in >= C++11)

When should it be used? (Which problems does it solve [/create]?)

  • When you want the assigned-to objected unaffected by an assignment that throws an exception, assuming you have or can write a swap with strong exception guarantee, and ideally one that can't fail/throw..†

  • When you want a clean, easy to understand, robust way to define the assignment operator in terms of (simpler) copy constructor, swap and destructor functions.

    • Self-assignment done as a copy-and-swap avoids oft-overlooked edge cases.‡

  • When any performance penalty or momentarily higher resource usage created by having an extra temporary object during the assignment is not important to your application. ?

swap throwing: it's generally possible to reliably swap data members that the objects track by pointer, but non-pointer data members that don't have a throw-free swap, or for which swapping has to be implemented as X tmp = lhs; lhs = rhs; rhs = tmp; and copy-construction or assignment may throw, still have the potential to fail leaving some data members swapped and others not. This potential applies even to C++03 std::string's as James comments on another answer:

@wilhelmtell: In C++03, there is no mention of exceptions potentially thrown by std::string::swap (which is called by std::swap). In C++0x, std::string::swap is noexcept and must not throw exceptions. – James McNellis Dec 22 '10 at 15:24


‡ assignment operator implementation that seems sane when assigning from a distinct object can easily fail for self-assignment. While it might seem unimaginable that client code would even attempt self-assignment, it can happen relatively easily during algo operations on containers, with x = f(x); code where f is (perhaps only for some #ifdef branches) a macro ala #define f(x) x or a function returning a reference to x, or even (likely inefficient but concise) code like x = c1 ? x * 2 : c2 ? x / 2 : x;). For example:

struct X
{
    T* p_;
    size_t size_;
    X& operator=(const X& rhs)
    {
        delete[] p_;  // OUCH!
        p_ = new T[size_ = rhs.size_];
        std::copy(p_, rhs.p_, rhs.p_ + rhs.size_);
    }
    ...
};

On self-assignment, the above code delete's x.p_;, points p_ at a newly allocated heap region, then attempts to read the uninitialised data therein (Undefined Behaviour), if that doesn't do anything too weird, copy attempts a self-assignment to every just-destructed 'T'!


? The copy-and-swap idiom can introduce inefficiencies or limitations due to the use of an extra temporary (when the operator's parameter is copy-constructed):

struct Client
{
    IP_Address ip_address_;
    int socket_;
    X(const X& rhs)
      : ip_address_(rhs.ip_address_), socket_(connect(rhs.ip_address_))
    { }
};

Here, a hand-written Client::operator= might check if *this is already connected to the same server as rhs (perhaps sending a "reset" code if useful), whereas the copy-and-swap approach would invoke the copy-constructor which would likely be written to open a distinct socket connection then close the original one. Not only could that mean a remote network interaction instead of a simple in-process variable copy, it could run afoul of client or server limits on socket resources or connections. (Of course this class has a pretty horrid interface, but that's another matter ;-P).

How to add a where clause in a MySQL Insert statement?

UPDATE users SET username='&username', password='&password' where id='&id'

This query will ask you to enter the username,password and id dynamically

Disable cache for some images

Simple, send one header location.

My site, contains one image, and after upload the image, there not change, then I add this code:

<?php header("Location: pagelocalimage.php"); ?>

Work's for me.

How to position the Button exactly in CSS

Try using absolute positioning, rather than relative positioning

this should get you close - you can adjust by tweaking margins or top/left positions

#play_button {
    position:absolute;
    transition: .5s ease;
    top: 50%;
    left: 50%;
}

http://jsfiddle.net/rolfsf/9pNqS/

Plot yerr/xerr as shaded region rather than error bars

Ignoring the smooth interpolation between points in your example graph (that would require doing some manual interpolation, or just have a higher resolution of your data), you can use pyplot.fill_between():

from matplotlib import pyplot as plt
import numpy as np

x = np.linspace(0, 30, 30)
y = np.sin(x/6*np.pi)
error = np.random.normal(0.1, 0.02, size=y.shape)
y += np.random.normal(0, 0.1, size=y.shape)

plt.plot(x, y, 'k-')
plt.fill_between(x, y-error, y+error)
plt.show()

enter image description here

See also the matplotlib examples.

Alter user defined type in SQL Server

there's a good example of a more comprehensive script here

It's worth noting that this script will include views if you have any. I ran it and instead of exec'ing inline generated a script as the output which I then tweaked and ran.

Also, if you have functions/sprocs using the user defeined types you'll need to drop those before running your script.

Lesson Learned: in future, don't bother with UDTs they're more hassle than they're worth.

SET NOCOUNT ON

DECLARE @udt VARCHAR(150)
DECLARE @udtschema VARCHAR(150)
DECLARE @newudtschema VARCHAR(150)
DECLARE @newudtDataType VARCHAR(150)
DECLARE @newudtDataSize smallint
DECLARE @OtherParameter VARCHAR(50)

SET @udt = 'Name' -- Existing UDDT
SET @udtschema = 'dbo' -- Schema of the UDDT
SET @newudtDataType = 'varchar' -- Data type for te new UDDT
SET @newudtDataSize = 500 -- Lenght of the new UDDT
SET @newudtschema = 'dbo' -- Schema of the new UDDT
SET @OtherParameter = ' NULL' -- Other parameters like NULL , NOT NULL
DECLARE @Datatype VARCHAR(50),
    @Datasize SMALLINT

DECLARE @varcharDataType VARCHAR(50)

DECLARE @Schemaname VARCHAR(50),
    @TableName VARCHAR(50),
    @FiledName VARCHAR(50)

CREATE TABLE #udtflds
    (
      Schemaname VARCHAR(50),
      TableName VARCHAR(50),
      FiledName VARCHAR(50)
    )

SELECT TOP 1
        @Datatype = Data_type,
        @Datasize = character_maximum_length
FROM    INFORMATION_SCHEMA.COLUMNS
WHERE   Domain_name = @udt
        AND Domain_schema = @udtschema

SET @varcharDataType = @Datatype
IF @DataType Like '%char%'
    AND @Datasize IS NOT NULL
    AND ( @newudtDataType <> 'varchar(max)'
          OR @newudtDataType <> 'nvarchar(max)'
        )
    BEGIN
        SET @varcharDataType = @varcharDataType + '('
            + CAST(@Datasize AS VARCHAR(50)) + ')'
    END

INSERT  INTO #udtflds
        SELECT  TABLE_SCHEMA,
                TABLE_NAME,
                Column_Name
        FROM    INFORMATION_SCHEMA.COLUMNS
        WHERE   Domain_name = @udt
                AND Domain_schema = @udtschema

DECLARE @exec VARCHAR(500)

DECLARE alter_cursor CURSOR
    FOR SELECT  Schemaname,
                TableName,
                FiledName
        FROM    #udtflds

OPEN alter_cursor
FETCH NEXT FROM alter_cursor INTO @Schemaname, @TableName, @FiledName

WHILE @@FETCH_STATUS = 0
    BEGIN
        SET @exec = 'Alter Table ' + @Schemaname + '.' + @TableName
            + '  ALTER COLUMN ' + @FiledName + ' ' + @varcharDataType
        EXECUTE ( @exec
               )
        FETCH NEXT FROM alter_cursor INTO @Schemaname, @TableName, @FiledName

    END

CLOSE alter_cursor

SET @exec = 'DROP TYPE [' + @udtschema + '].[' + @udt + ']'
EXEC ( @exec
    )

SET @varcharDataType = @newudtDataType

IF @newudtDataType Like '%char%'
    AND @newudtDataSize IS NOT NULL
    AND ( @newudtDataType <> 'varchar(max)'
          OR @newudtDataType <> 'nvarchar(max)'
        )
    BEGIN
        SET @varcharDataType = @varcharDataType + '('
            + CAST(@newudtDataSize AS VARCHAR(50)) + ')'
    END

SET @exec = 'CREATE TYPE [' + @newudtschema + '].[' + @udt + '] FROM '
    + @varcharDataType + ' ' + @OtherParameter
EXEC ( @exec
    )

OPEN alter_cursor
FETCH NEXT FROM alter_cursor INTO @Schemaname, @TableName, @FiledName

WHILE @@FETCH_STATUS = 0
    BEGIN
        SET @exec = 'Alter Table ' + @Schemaname + '.' + @TableName
            + '  ALTER COLUMN ' + @FiledName + ' ' + '[' + @newudtschema
            + '].[' + @udt + ']'
        EXECUTE ( @exec
               )
        FETCH NEXT FROM alter_cursor INTO @Schemaname, @TableName, @FiledName
    END

CLOSE alter_cursor
DEALLOCATE alter_cursor
SELECT  *
FROM    #udtflds

DROP TABLE #udtflds

1: http://www.sql-server-performance.com/2008/how-to-alter-a-uddt/ has replaced http://www.sql-server-performance.com/faq/How_to_alter_a%20_UDDT_p1.aspx

Revert a jQuery draggable object back to its original container on out event of droppable

I'm not sure if this will work for your actual use, but it works in your test case - updated at http://jsfiddle.net/sTD8y/27/ .

I just made it so that the built-in revert is only used if the item has not been dropped before. If it has been dropped, the revert is done manually. You could adjust this to animate to some calculated offset by checking the actual CSS properties, but I'll let you play with that because a lot of it depends on the CSS of the draggable and it's surrounding DOM structure.

$(function() {
    $("#draggable").draggable({
        revert:  function(dropped) {
             var $draggable = $(this),
                 hasBeenDroppedBefore = $draggable.data('hasBeenDropped'),
                 wasJustDropped = dropped && dropped[0].id == "droppable";
             if(wasJustDropped) {
                 // don't revert, it's in the droppable
                 return false;
             } else {
                 if (hasBeenDroppedBefore) {
                     // don't rely on the built in revert, do it yourself
                     $draggable.animate({ top: 0, left: 0 }, 'slow');
                     return false;
                 } else {
                     // just let the built in revert work, although really, you could animate to 0,0 here as well
                     return true;
                 }
             }
        }
    });

    $("#droppable").droppable({
        activeClass: 'ui-state-hover',
        hoverClass: 'ui-state-active',
        drop: function(event, ui) {
            $(this).addClass('ui-state-highlight').find('p').html('Dropped!');
            $(ui.draggable).data('hasBeenDropped', true);
        }
    });
});

What's the best way to get the last element of an array without deleting it?

Try

$myLastElement = end($yourArray);

To reset it (thanks @hopeseekr):

 reset($yourArray);

Link to manual

@David Murdoch added: $myLastElement = end(array_values($yourArray));// and now you don't need to call reset(). On E_STRICT this produces the warning

Strict Standards: Only variables should be passed by reference

Thanks o_O Tync and everyone!

WAMP/XAMPP is responding very slow over localhost

Power plan was the problem.Changed Balanced to High performance.

Best way to restrict a text field to numbers only?

You can do like this to accept only Numbers in text Box,

 function onChange(event){
   var ckeckChars = /[^0-9]/gi;
   if(checkChars.test(event.target.value)) {
        event.target.value = event.target.value.replace(ckeckChars,"");
  }

How do I set up a private Git repository on GitHub? Is it even possible?

Bitbucket - Their plans seem to be the best. They give you way more than GitHub do for free accounts - in fact, I'm still only using the free plan - no need to sign up to the paid ones; plus the interface is almost identical to GitHub.

A repository on Bitbucket can have up to five private users with unlimited public or private repositories - the only thing you seem to be paying for with the paid accounts are more users to access your private repositories.

Error importing Seaborn module in Python

  1. delete package whl file in 'C:\Users\hp\Anaconda3\Lib\site-packages'
  2. pip uninstlal scipy and seaborn
  3. pip install scipy nd seaborn agaian

it worked for 4, win10, anaconda

How do I extract part of a string in t-sql

LEFT ('BTA200', 3) will work for the examples you have given, as in :

SELECT LEFT(MyField, 3)
FROM MyTable

To extract the numeric part, you can use this code

SELECT RIGHT(MyField, LEN(MyField) - 3)
FROM MyTable
WHERE MyField LIKE 'BTA%' 
--Only have this test if your data does not always start with BTA.

How do you change Background for a Button MouseOver in WPF?

For change button style

1st: define resource styles

<Window.Resources>

    <Style x:Key="OvergroundIn" TargetType="Button">

        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Grid Background="#FF16832F">
                        <ContentPresenter TextBlock.Foreground="White" TextBlock.TextAlignment="Center" Margin="0,8,0,0" ></ContentPresenter>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>

        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">

                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="Button">
                            <Grid Background="#FF06731F">
                                <ContentPresenter TextBlock.Foreground="White" TextBlock.TextAlignment="Center" Margin="0,8,0,0" ></ContentPresenter>
                            </Grid>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>

            </Trigger>
        </Style.Triggers>

    </Style>

    <Style x:Key="OvergroundOut" TargetType="Button">

        <Setter Property="Template">
            <Setter.Value>
                <ControlTemplate TargetType="Button">
                    <Grid Background="#FFF35E5E">
                        <ContentPresenter TextBlock.Foreground="White" TextBlock.TextAlignment="Center" Margin="0,8,0,0" ></ContentPresenter>
                    </Grid>
                </ControlTemplate>
            </Setter.Value>
        </Setter>

        <Style.Triggers>
            <Trigger Property="IsMouseOver" Value="True">

                <Setter Property="Template">
                    <Setter.Value>
                        <ControlTemplate TargetType="Button">
                            <Grid Background="#FFE34E4E">
                                <ContentPresenter TextBlock.Foreground="White" TextBlock.TextAlignment="Center" Margin="0,8,0,0" ></ContentPresenter>
                            </Grid>
                        </ControlTemplate>
                    </Setter.Value>
                </Setter>

            </Trigger>
        </Style.Triggers>

    </Style>


</Window.Resources>

2nd define button code

                           <Border Grid.Column="2" BorderBrush="LightGray" BorderThickness="2" CornerRadius="3" Margin="2,2,2,2"  >
                                <Button Name="btnFichar" BorderThickness="0" Click="BtnFichar_Click">
                                    <Button.Content>
                                        <Grid>
                                            <TextBlock Margin="0,7,0,7" TextAlignment="Center">Fichar</TextBlock> 
                                        </Grid>
                                    </Button.Content>
                                </Button>
                            </Border>

3th code behind

    public void ShowStatus()
    {
        switch (((MainDto)this.DataContext).State)
        {
            case State.IN:
                this.btnFichar.BorderBrush = new SolidColorBrush(Color.FromRgb(243, 94, 94));
                this.btnFichar.Style = Resources["OvergroundIn"] as Style;
                this.btnFichar.Content = "Fichar Salida";
                break;

            case State.OUT:
                this.btnFichar.BorderBrush = new SolidColorBrush(Color.FromRgb(76, 106, 83));
                this.btnFichar.Style = Resources["OvergroundOut"] as Style;
                this.btnFichar.Content = "Fichar Entrada";
                break;

        }
    }

Export table to file with column headers (column names) using the bcp utility and SQL Server 2008

From all I know, BCP only exports the data - I don't think there's any way to make it export the header row with column names, too.

One common technique seen to solve this is to use a view over your actual data for export, which basically does a UNION ALL over two statements:

  • the first statement to give back one row with the column headers
  • the actual data to be export

and then use bcp on that view, instead of your underlying data table directly.

Marc

SQL DELETE with INNER JOIN

If the database is InnoDB then it might be a better idea to use foreign keys and cascade on delete, this would do what you want and also result in no redundant data being stored.

For this example however I don't think you need the first s:

DELETE s 
FROM spawnlist AS s 
INNER JOIN npc AS n ON s.npc_templateid = n.idTemplate 
WHERE n.type = "monster";

It might be a better idea to select the rows before deleting so you are sure your deleting what you wish to:

SELECT * FROM spawnlist
INNER JOIN npc ON spawnlist.npc_templateid = npc.idTemplate
WHERE npc.type = "monster";

You can also check the MySQL delete syntax here: http://dev.mysql.com/doc/refman/5.0/en/delete.html

Calling a javascript function in another js file

I have had same problem. I have had defined functions inside jquery document ready function.

$(document).ready(function() {
   function xyz()
   {
       //some code
   }
});

And this function xyz() I have called in another file. This doesn't working :) You have to defined function above document ready.

Select info from table where row has max date

Using an in can have a performance impact. Joining two subqueries will not have the same performance impact and can be accomplished like this:

SELECT *
  FROM (SELECT msisdn
              ,callid
              ,Change_color
              ,play_file_name
              ,date_played
          FROM insert_log
         WHERE play_file_name NOT IN('Prompt1','Conclusion_Prompt_1','silent')
        ORDER BY callid ASC) t1
       JOIN (SELECT MAX(date_played) AS date_played
               FROM insert_log GROUP BY callid) t2
         ON t1.date_played = t2.date_played

What's the difference between unit tests and integration tests?

A unit test is a test written by the programmer to verify that a relatively small piece of code is doing what it is intended to do. They are narrow in scope, they should be easy to write and execute, and their effectiveness depends on what the programmer considers to be useful. The tests are intended for the use of the programmer, they are not directly useful to anybody else, though, if they do their job, testers and users downstream should benefit from seeing fewer bugs.

Part of being a unit test is the implication that things outside the code under test are mocked or stubbed out. Unit tests shouldn't have dependencies on outside systems. They test internal consistency as opposed to proving that they play nicely with some outside system.

An integration test is done to demonstrate that different pieces of the system work together. Integration tests can cover whole applications, and they require much more effort to put together. They usually require resources like database instances and hardware to be allocated for them. The integration tests do a more convincing job of demonstrating the system works (especially to non-programmers) than a set of unit tests can, at least to the extent the integration test environment resembles production.

Actually "integration test" gets used for a wide variety of things, from full-on system tests against an environment made to resemble production to any test that uses a resource (like a database or queue) that isn't mocked out. At the lower end of the spectrum an integration test could be a junit test where a repository is exercised against an in-memory database, toward the upper end it could be a system test verifying applications can exchange messages.

How to detect if JavaScript is disabled?

A technique I've used in the past is to use JavaScript to write a session cookie that simply acts as a flag to say that JavaScript is enabled. Then the server-side code looks for this cookie and if it's not found takes action as appropriate. Of course this technique does rely on cookies being enabled!

Redirect all output to file using Bash on Linux?

You can execute a subshell and redirect all output while still putting the process in the background:

( ./script.sh blah > ~/log/blah.log 2>&1 ) &
echo $! > ~/pids/blah.pid

How to check if dropdown is disabled?

I was searching for something like this, because I've got to check which of all my selects are disabled.

So I use this:

let select= $("select");

for (let i = 0; i < select.length; i++) {
    const element = select[i];
    if(element.disabled == true ){
        console.log(element)
    }
}

Using multiple arguments for string formatting in Python (e.g., '%s ... %s')

If you're using more than one argument it has to be in a tuple (note the extra parentheses):

'%s in %s' % (unicode(self.author),  unicode(self.publication))

As EOL points out, the unicode() function usually assumes ascii encoding as a default, so if you have non-ASCII characters, it's safer to explicitly pass the encoding:

'%s in %s' % (unicode(self.author,'utf-8'),  unicode(self.publication('utf-8')))

And as of Python 3.0, it's preferred to use the str.format() syntax instead:

'{0} in {1}'.format(unicode(self.author,'utf-8'),unicode(self.publication,'utf-8'))

How to call one shell script from another shell script?

There are some problems to import functions from other file.
First: You needn't to do this file executable. Better not to do so! just add

. file

to import all functions. And all of them will be as if they are defined in your file.
Second: You may be define the function with the same name. It will be overwritten. It's bad. You may declare like that

declare -f new_function_name=old_function_name 

and only after that do import. So you may call old function by new name.
Third: You may import only full list of functions defined in file. If some not needed you may unset them. But if you rewrite your functions after unset they will be lost. But if you set reference to it as described above you may restore after unset with the same name.
Finally In common procedure of import is dangerous and not so simple. Be careful! You may write script to do this more easier and safe. If you use only part of functions(not all) better split them in different files. Unfortunately this technique not made well in bash. In python for example and some other script languages it's easy and safe. Possible to make partial import only needed functions with its own names. We all want that in next bush versions will be done the same functionality. But now We must write many additional cod so as to do what you want.

How to trigger an event after using event.preventDefault()

It is possible to use currentTarget of the event. Example shows how to proceed with form submit. Likewise you could get function from onclick attribute etc.

$('form').on('submit', function(event) {
  event.preventDefault();

  // code

  event.currentTarget.submit();
});

java.lang.NullPointerException: Attempt to invoke virtual method on a null object reference

Your app is crashing at:

welcomePlayer.setText("Welcome Back, " + String.valueOf(mPlayer.getName(this)) + " !");

because mPlayer=null.

You forgot to initialize Player mPlayer in your PlayGame Activity.

mPlayer = new Player(context,"");

Execute SQL script to create tables and rows

If you have password for your dB then

mysql -u <username> -p <DBName> < yourfile.sql

List all devices, partitions and volumes in Powershell

Firstly, on Unix you use mount, not ls /mnt: many things are not mounted in /mnt.

Anyhow, there's the mountvol DOS command, which continues to work in Powershell, and there's the Powershell-specific Get-PSDrive.

How do I mount a host directory as a volume in docker compose

Checkout their documentation

From the looks of it you could do the following on your docker-compose.yml

volumes:
    - ./:/app

Where ./ is the host directory, and /app is the target directory for the containers.


EDIT:
Previous documentation source now leads to version history, you'll have to select the version of compose you're using and look for the reference.

For the lazy – v3 / v2 / v1

Side note: Syntax remains the same for all versions as of this edit

jQuery Change event on an <input> element - any way to retain previous value?

You could have the value of the input field copied to a hidden field whenever focus leaves the input field (which should do what you want). See code below:

<script>
    $(document).ready(function(){
        $('#myInputElement').bind('change', function(){
            var newvalue = $(this).val();
        });
        $('#myInputElement').blur(function(){
            $('#myHiddenInput').val($(this).val());
        });
    });
</script>
<input id="myInputElement" type="text">

(untested, but it should work).

org.json.simple.JSONArray cannot be cast to org.json.simple.JSONObject

The first element of the sites array is an array, as you can see indenting the JSON:

{"units":[{"id":42,               
    ...
    "sites":
    [
      [
        {
          "id":316,
          "article":42,
          "clip":133904
        }
      ],
      {"length":5}
    ]
    ...
}

Therefore you need to treat its value accordingly; probably you could do something like:

JSONObject site = (JSONObject)(((JSONArray)jsonSites.get(i)).get(0));

Measuring function execution time in R

Another simple but very powerful way to do this is by using the package profvis. It doesn't just measure the execution time of your code but gives you a drill down for each function you execute. It can be used for Shiny as well.

library(profvis)

profvis({
  #your code here
})

Click here for some examples.

Get paragraph text inside an element

Alternatively, you can also pass the li element itself to your myfunction function as shown:

function myfunction(ctrl) {
  var TextInsideLi = ctrl.getElementsByTagName('p')[0].innerHTML;
}

and in your HTML, <li onclick="myfunction(this)">

Running Command Line in Java

Runtime rt = Runtime.getRuntime();
Process pr = rt.exec("java -jar map.jar time.rel test.txt debug");

http://docs.oracle.com/javase/7/docs/api/java/lang/Runtime.html

How to find a text inside SQL Server procedures / triggers?

I use this one for work. leave off the []'s though in the @TEXT field, seems to want to return everything...

SET NOCOUNT ON

DECLARE @TEXT   VARCHAR(250)
DECLARE @SQL    VARCHAR(250)

SELECT  @TEXT='10.10.100.50'

CREATE TABLE #results (db VARCHAR(64), objectname VARCHAR(100),xtype VARCHAR(10), definition TEXT)

SELECT @TEXT as 'Search String'
DECLARE #databases CURSOR FOR SELECT NAME FROM master..sysdatabases where dbid>4
    DECLARE @c_dbname varchar(64)   
    OPEN #databases
    FETCH #databases INTO @c_dbname   
    WHILE @@FETCH_STATUS  -1
    BEGIN
        SELECT @SQL = 'INSERT INTO #results '
        SELECT @SQL = @SQL + 'SELECT ''' + @c_dbname + ''' AS db, o.name,o.xtype,m.definition '   
        SELECT @SQL = @SQL + ' FROM '+@c_dbname+'.sys.sql_modules m '   
        SELECT @SQL = @SQL + ' INNER JOIN '+@c_dbname+'..sysobjects o ON m.object_id=o.id'   
        SELECT @SQL = @SQL + ' WHERE [definition] LIKE ''%'+@TEXT+'%'''   
        EXEC(@SQL)
        FETCH #databases INTO @c_dbname
    END
    CLOSE #databases
DEALLOCATE #databases

SELECT * FROM #results order by db, xtype, objectname
DROP TABLE #results

Android studio Gradle icon error, Manifest Merger

I have same issue , I fix it like this by adding xmlns:tools="http://schemas.android.com/tools" to the top of mainfest file , and add tools:replace="android:icon" to be look like

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"  // add tools line here 
    package="yourpackage">


    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:supportsRtl="true"
        android:theme="@style/AppTheme"
        tools:replace="android:icon"> ///add this line 

.....

</application>

</manifest>

Ruby on Rails 3 Can't connect to local MySQL server through socket '/tmp/mysql.sock' on OSX

The default location for the MySQL socket on Mac OS X is /var/mysql/mysql.sock.

VBA: activating/selecting a worksheet/row/cell

This is just a sample code, but it may help you get on your way:

Public Sub testIt()
    Workbooks("Workbook2").Activate
    ActiveWorkbook.Sheets("Sheet2").Activate
    ActiveSheet.Range("B3").Select
    ActiveCell.EntireRow.Insert
End Sub

I am assuming that you can open the book (called Workbook2 in the example).


I think (but I'm not sure) you can squash all this in a single line of code:

    Workbooks("Workbook2").Sheets("Sheet2").Range("B3").EntireRow.Insert

This way you won't need to activate the workbook (or sheet or cell)... Obviously, the book has to be open.

PHP "php://input" vs $_POST

The reason is that php://input returns all the raw data after the HTTP-headers of the request, regardless of the content type.

The PHP superglobal $_POST, only is supposed to wrap data that is either

  • application/x-www-form-urlencoded (standard content type for simple form-posts) or
  • multipart/form-data (mostly used for file uploads)

This is because these are the only content types that must be supported by user agents. So the server and PHP traditionally don't expect to receive any other content type (which doesn't mean they couldn't).

So, if you simply POST a good old HTML form, the request looks something like this:

POST /page.php HTTP/1.1

key1=value1&key2=value2&key3=value3

But if you are working with Ajax a lot, this probaby also includes exchanging more complex data with types (string, int, bool) and structures (arrays, objects), so in most cases JSON is the best choice. But a request with a JSON-payload would look something like this:

POST /page.php HTTP/1.1

{"key1":"value1","key2":"value2","key3":"value3"}

The content would now be application/json (or at least none of the above mentioned), so PHP's $_POST-wrapper doesn't know how to handle that (yet).

The data is still there, you just can't access it through the wrapper. So you need to fetch it yourself in raw format with file_get_contents('php://input') (as long as it's not multipart/form-data-encoded).

This is also how you would access XML-data or any other non-standard content type.

Dropdown select with images

You don't even need javascript to do this!

I hope this got you intrigued so here it goes. First, the html structure:

<div id="image-dropdown">
    <input type="radio" id="line1" name="line-style" value="1" checked="checked" />
    <label for="line1"></label>
    <input type="radio" id="line2" name="line-style" value="2" />
    <label for="line2"></label>
    ...
</div>

Whaaat? Radio buttons? Correct. We'll style them to look like a dropdown list with images, because that's what you're after! The trick is in knowing that when labels are correctly linked to inputs (that "for" attribute and target element id), the input will implicitly become active; click on a label = click on a radio button. Here comes comes slightly abbreviated css with comments inline:

#image-dropdown {
    /*style the "box" in its minimzed state*/
    border:1px solid black; width:200px; height:50px; overflow:hidden;
    /*animate the dropdown collapsing*/
    transition: height 0.1s;
}
#image-dropdown:hover {
    /*when expanded, the dropdown will get native means of scrolling*/
    height:200px; overflow-y:scroll;
    /*animate the dropdown expanding*/
    transition: height 0.5s;
}
#image-dropdown input {
    /*hide the nasty default radio buttons!*/
    position:absolute;top:0;left:0;opacity:0;
}
#image-dropdown label {
    /*style the labels to look like dropdown options*/
    display:none; margin:2px; height:46px; opacity:0.2; 
    background:url("http://www.google.com/images/srpr/logo3w.png") 50% 50%;}
#image-dropdown:hover label{
    /*this is how labels render in the "expanded" state.
     we want to see only the selected radio button in the collapsed menu,
     and all of them when expanded*/
    display:block;
}
#image-dropdown input:checked + label {
    /*tricky! labels immediately following a checked radio button
      (with our markup they are semantically related) should be fully opaque
      and visible even in the collapsed menu*/
    opacity:1 !important; display:block;
}

Full example here: http://jsfiddle.net/NDCSR/1/

NB1: you'll probably need to use it with position:absolute inside a container with position:relative +high z-index.

NB2: when adding more backgrounds for individual line styles, consider having the selectors based on the "for" attribute of the label like so:

label[for=linestyle2] {background-image:url(...);}

How to call an element in a numpy array?

Just use square brackets instead:

print arr[1,1]

How to write a UTF-8 file with Java?

Instead of using FileWriter, create a FileOutputStream. You can then wrap this in an OutputStreamWriter, which allows you to pass an encoding in the constructor. Then you can write your data to that inside a try-with-resources Statement:

try (OutputStreamWriter writer =
             new OutputStreamWriter(new FileOutputStream(PROPERTIES_FILE), StandardCharsets.UTF_8))
    // do stuff
}

Leader Not Available Kafka in Console Producer

I am using docker-compose to build the Kafka container using wurstmeister/kafka image. Adding KAFKA_ADVERTISED_PORT: 9092 property to my docker-compose file solved this error for me.

SQLAlchemy ORDER BY DESCENDING?

Just as an FYI, you can also specify those things as column attributes. For instance, I might have done:

.order_by(model.Entry.amount.desc())

This is handy since it avoids an import, and you can use it on other places such as in a relation definition, etc.

For more information, you can refer this

Call int() function on every list element?

Thought I'd consolidate the answers and show some timeit results.

Python 2 sucks pretty bad at this, but map is a bit faster than comprehension.

Python 2.7.13 (v2.7.13:a06454b1afa1, Dec 17 2016, 20:42:59) [MSC v.1500 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import timeit
>>> setup = """import random
random.seed(10)
l = [str(random.randint(0, 99)) for i in range(100)]"""
>>> timeit.timeit('[int(v) for v in l]', setup)
116.25092001434314
>>> timeit.timeit('map(int, l)', setup)
106.66044823117454

Python 3 is over 4x faster by itself, but converting the map generator object to a list is still faster than comprehension, and creating the list by unpacking the map generator (thanks Artem!) is slightly faster still.

Python 3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 17:54:52) [MSC v.1900 32 bit (Intel)] on win32
Type "copyright", "credits" or "license()" for more information.
>>> import timeit
>>> setup = """import random
random.seed(10)
l = [str(random.randint(0, 99)) for i in range(100)]"""
>>> timeit.timeit('[int(v) for v in l]', setup)
25.133059591551955
>>> timeit.timeit('list(map(int, l))', setup)
19.705547827217515
>>> timeit.timeit('[*map(int, l)]', setup)
19.45838406513076

Note: In Python 3, 4 elements seems to be the crossover point (3 in Python 2) where comprehension is slightly faster, though unpacking the generator is still faster than either for lists with more than 1 element.

How to exclude a directory in find . command

-prune definitely works and is the best answer because it prevents descending into the dir that you want to exclude. -not -path which still searches the excluded dir, it just doesn't print the result, which could be an issue if the excluded dir is mounted network volume or you don't permissions.

The tricky part is that find is very particular about the order of the arguments, so if you don't get them just right, your command may not work. The order of arguments is generally as such:

find {path} {options} {action}

{path}: Put all the path related arguments first, like . -path './dir1' -prune -o

{options}: I have the most success when putting -name, -iname, etc as the last option in this group. E.g. -type f -iname '*.js'

{action}: You'll want to add -print when using -prune

Here's a working example:

# setup test
mkdir dir1 dir2 dir3
touch dir1/file.txt; touch dir1/file.js
touch dir2/file.txt; touch dir2/file.js
touch dir3/file.txt; touch dir3/file.js

# search for *.js, exclude dir1
find . -path './dir1' -prune -o -type f -iname '*.js' -print

# search for *.js, exclude dir1 and dir2
find . \( -path './dir1' -o -path './dir2' \) -prune -o -type f -iname '*.js' -print

Gradle Error:Execution failed for task ':app:processDebugGoogleServices'

NEVER DELETE apply plugin: 'com.google.gms.google-services' from the gradle. Sometimes you are using com.google.gms:google-services:3.1.0 , without apply plugin: 'com.google.gms.google-services' your gradle build successfully. BUT IT IS COMPLETELY WRONG !!!! This error comes due to google-service.json file is not at the correct location. Go to your PROJECT TAB at left side above. If you display it as ANDROID make it PROJECT then check your google-service.json file is at this location. EXPAND app then see google-service.json file below the build.gradle. IF NOT PLACE IT THERE BY RIGHT CLICK ON THE app .

Entity Framework - Code First - Can't Store List<String>

Entity Framework does not support collections of primitive types. You can either create an entity (which will be saved to a different table) or do some string processing to save your list as a string and populate the list after the entity is materialized.

How to pass all arguments passed to my bash script to a function of mine?

Here's a simple script:

#!/bin/bash

args=("$@")

echo Number of arguments: $#
echo 1st argument: ${args[0]}
echo 2nd argument: ${args[1]}

$# is the number of arguments received by the script. I find easier to access them using an array: the args=("$@") line puts all the arguments in the args array. To access them use ${args[index]}.

Formatting Decimal places in R

if you just want to round a number or a list, simply use

round(data, 2)

Then, data will be round to 2 decimal place.

How do I read a resource file from a Java jar file?

Here's a sample code on how to read a file properly inside a jar file (in this case, the current executing jar file)

Just change executable with the path of your jar file if it is not the current running one.

Then change the filePath to the path of the file you want to use inside the jar file. I.E. if your file is in

someJar.jar\img\test.gif

. Set the filePath to "img\test.gif"

File executable = new File(BrowserViewControl.class.getProtectionDomain().getCodeSource().getLocation().toURI());
JarFile jar = new JarFile(executable);
InputStream fileInputStreamReader = jar.getInputStream(jar.getJarEntry(filePath));
byte[] bytes = new byte[fileInputStreamReader.available()];

int sizeOrig = fileInputStreamReader.available();
int size = fileInputStreamReader.available();
int offset = 0;
while (size != 0){
    fileInputStreamReader.read(bytes, offset, size);
    offset = sizeOrig - fileInputStreamReader.available();
    size = fileInputStreamReader.available();
}

How do I get the current date and time in PHP?

If you want to get the date like 12-3-2016, separate each day, month, and year value, then copy-paste this code:

$day = date("d");
$month = date("m");
$year = date("y");
print "date" . $day . "-" . $month . "-" . $year;

C# - Insert a variable number of spaces into a string? (Formatting an output file)

Use String.Format:

string title1 = "Sample Title One";
string element1 = "Element One";
string format = "{0,-20} {1,-10}";

string result = string.Format(format, title1, element1);
//or you can print to Console directly with
//Console.WriteLine(format, title1, element1);

In the format {0,-20} means the first argument has a fixed length 20, and the negative sign guarantees the string is printed from left to right.

Eloquent Collection: Counting and Detect Empty

I think better to used

$result->isEmpty();

The isEmpty method returns true if the collection is empty; otherwise, false is returned.

Error LNK2019: Unresolved External Symbol in Visual Studio

When you have everything #included, an unresolved external symbol is often a missing * or & in the declaration or definition of a function.

What is a void pointer in C++?

A void* does not mean anything. It is a pointer, but the type that it points to is not known.

It's not that it can return "anything". A function that returns a void* generally is doing one of the following:

  • It is dealing in unformatted memory. This is what operator new and malloc return: a pointer to a block of memory of a certain size. Since the memory does not have a type (because it does not have a properly constructed object in it yet), it is typeless. IE: void.
  • It is an opaque handle; it references a created object without naming a specific type. Code that does this is generally poorly formed, since this is better done by forward declaring a struct/class and simply not providing a public definition for it. Because then, at least it has a real type.
  • It returns a pointer to storage that contains an object of a known type. However, that API is used to deal with objects of a wide variety of types, so the exact type that a particular call returns cannot be known at compile time. Therefore, there will be some documentation explaining when it stores which kinds of objects, and therefore which type you can safely cast it to.

This construct is nothing like dynamic or object in C#. Those tools actually know what the original type is; void* does not. This makes it far more dangerous than any of those, because it is very easy to get it wrong, and there's no way to ask if a particular usage is the right one.

And on a personal note, if you see code that uses void*'s "often", you should rethink what code you're looking at. void* usage, especially in C++, should be rare, used primary for dealing in raw memory.

addEventListener in Internet Explorer

I would use these polyfill https://github.com/WebReflection/ie8

<!--[if IE 8]><script
  src="//cdnjs.cloudflare.com/ajax/libs/ie8/0.2.6/ie8.js"
></script><![endif]-->

Output first 100 characters in a string

Slicing of arrays is done with [first:last+1].

One trick I tend to use a lot of is to indicate extra information with ellipses. So, if your field is one hundred characters, I would use:

if len(s) <= 100:
    print s
else:
    print "%s..."%(s[:97])

And yes, I know () is superfluous in this case for the % formatting operator, it's just my style.

How to disable scrolling temporarily?

A simple solution that worked for me (disabling window scrolling temporarily).

Based on this fiddle: http://jsfiddle.net/dh834zgw/1/

the following snippet (using jquery) will disable the window scroll:

 var curScrollTop = $(window).scrollTop();
 $('html').toggleClass('noscroll').css('top', '-' + curScrollTop + 'px');

And in your css:

html.noscroll{
    position: fixed;
    width: 100%;
    top:0;
    left: 0;
    height: 100%;
    overflow-y: scroll !important;
    z-index: 10;
 }

Now when you remove the modal, don't forget to remove the noscroll class on the html tag:

$('html').toggleClass('noscroll');

A quick and easy way to join array elements with a separator (the opposite of split) in Java

A fast and simple solution without any 3rd party includes.

public static String strJoin(String[] aArr, String sSep) {
    StringBuilder sbStr = new StringBuilder();
    for (int i = 0, il = aArr.length; i < il; i++) {
        if (i > 0)
            sbStr.append(sSep);
        sbStr.append(aArr[i]);
    }
    return sbStr.toString();
}

PostgreSQL "DESCRIBE TABLE"

In MySQL , DESCRIBE table_name


In PostgreSQL , \d table_name


Or , you can use this long command:

SELECT
        a.attname AS Field,
        t.typname || '(' || a.atttypmod || ')' AS Type,
        CASE WHEN a.attnotnull = 't' THEN 'YES' ELSE 'NO' END AS Null,
        CASE WHEN r.contype = 'p' THEN 'PRI' ELSE '' END AS Key,
        (SELECT substring(pg_catalog.pg_get_expr(d.adbin, d.adrelid), '\'(.*)\'')
                FROM
                        pg_catalog.pg_attrdef d
                WHERE
                        d.adrelid = a.attrelid
                        AND d.adnum = a.attnum
                        AND a.atthasdef) AS Default,
        '' as Extras
FROM
        pg_class c 
        JOIN pg_attribute a ON a.attrelid = c.oid
        JOIN pg_type t ON a.atttypid = t.oid
        LEFT JOIN pg_catalog.pg_constraint r ON c.oid = r.conrelid 
                AND r.conname = a.attname
WHERE
        c.relname = 'tablename'
        AND a.attnum > 0

ORDER BY a.attnum

Explicitly set column value to null SQL Developer

Use Shift+Del.

More info: Shift+Del combination key set a field to null when you filled a field by a value and you changed your decision and you want to make it null. It is useful and I amazed from the other answers that give strange solutions.

Is there a performance difference between a for loop and a for-each loop?

The for-each loop should generally be preferred. The "get" approach may be slower if the List implementation you are using does not support random access. For example, if a LinkedList is used, you would incur a traversal cost, whereas the for-each approach uses an iterator that keeps track of its position in the list. More information on the nuances of the for-each loop.

I think the article is now here: new location

The link shown here was dead.

Remove a specific string from an array of string

Arrays in Java aren't dynamic, like collection classes. If you want a true collection that supports dynamic addition and deletion, use ArrayList<>. If you still want to live with vanilla arrays, find the index of string, construct a new array with size one less than the original, and use System.arraycopy() to copy the elements before and after. Or write a copy loop with skip by hand, on small arrays the difference will be negligible.

Where to get "UTF-8" string literal in Java?

Constant definitions for the standard. These charsets are guaranteed to be available on every implementation of the Java platform. since 1.7

 package java.nio.charset;
 Charset utf8 = StandardCharsets.UTF_8;

How do I set default terminal to terminator?

open dconf Editor and go to org > gnome > desktop > application > terminal and change gnome-terminal to terminator

Multiple submit buttons in an HTML form

With JavaScript (here jQuery), you can disable the prev button before submitting the form.

$('form').on('keypress', function(event) {
    if (event.which == 13) {
        $('input[name="prev"]').prop('type', 'button');
    }
});

How to convert XML to java.util.Map and vice versa

One option would be to roll your own. It would be fairly simple to do:

Document doc = getDocument();
Element root = doc.createElement(rootName);
doc.appendChild(root);
for (Map.Entry<String,String> element : map.entrySet() ) {
    Element e = doc.createElement(element.getKey());
    e.setTextContent(element.getValue());
    root.appendChild(e);
}
save(doc, file);

and the load is an equally simply getChildNodes and a loop. Sure it has a bit of boiler plate that the XML Gods demand but it is at most 1 hours work.

Or you could look at Properties if you are not too fused about the format of the XML.

How to build a Horizontal ListView with RecyclerView?

 <android.support.v7.widget.RecyclerView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layoutManager="android.support.v7.widget.LinearLayoutManager" />

What are the best use cases for Akka framework

We use Akka in spoken dialog systems (primetalk). Both internally and externally. In order to simultaneously run a lot of telephony channels on a single cluster node it is obviously necessary to have some multithreading framework. Akka works just perfect. We have previous nightmare with the java-concurrency. And with Akka it is just like a swing — it simply works. Robust and reliable. 24*7, non-stop.

Inside a channel we have real-time stream of events that are processed in parallel. In particular: - lengthy automatic speech recognition — is done with an actor; - audio output producer that mixes a few audio sources (including synthesized speech); - text-to-speech conversion is a separate set of actors shared between channels; - semantic and knowledge processing.

To make interconnections of complex signal processing we use SynapseGrid. It has the benefit of compile-time checking of the DataFlow in the complex actor systems.

How to get a .csv file into R?

Since you say you want to access by position once your data is read in, you should know about R's subsetting/ indexing functions.

The easiest is

df[row,column]
#example
df[1:5,] #rows 1:5, all columns
df[,5] #all rows, column 5. 

Other methods are here. I personally use the dplyr package for intuitive data manipulation (not by position).

Using Node.JS, how do I read a JSON file into (server) memory?

At least in Node v8.9.1, you can just do

var json_data = require('/path/to/local/file.json');

and access all the elements of the JSON object.

ASP.NET MVC Custom Error Handling Application_Error Global.asax?

I struggled with the idea of centralizing a global error handling routine in an MVC app before. I have a post on the ASP.NET forums.

It basically handles all your application errors in the global.asax without the need for an error controller, decorating with the [HandlerError] attribute, or fiddling with the customErrors node in the web.config.

Angular ng-repeat add bootstrap row every 3 or 4 cols

Little bit modification in @alpar 's solution

<div data-ng-app="" data-ng-init="products=['A','B','C','D','E','F', 'G','H','I','J','K','L']" class="container">
    <div ng-repeat="product in products" ng-if="$index % 6 == 0" class="row">
        <div class="col-xs-2" ng-repeat="idx in [0,1,2,3,4,5]">
        {{products[idx+$parent.$index]}} <!-- When this HTML is Big it's useful approach -->
        </div>
    </div>
</div>

jsfiddle

TortoiseGit save user authentication / credentials

If you're going to downvote this answer

I wrote this a few months prior to the inclusion of git-credential in TortoiseGit. Given the number of large security holes found in the last few years and how much I've learned about network security, I would HIGHLY recommend you use a unique (minimum 2048-bit RSA) SSH key for every server you connect to.

The below syntax is still available, though there are far better tools available today like git-credential that the accepted answer tells you how to use. Do that instead.


Try changing the remote URL to https://[email protected]/username/repo.git where username is your github username and repo is the name of your repository.

If you also want to store your password (not recommended), the URL would look like this: https://username:[email protected]/username/repo.git.

There's also another way to store the password from this github help article: https://help.github.com/articles/set-up-git#password-caching

Why are my CSS3 media queries not working on mobile devices?

The sequential order of css code also matters, for example:

@media(max-width:600px){
  .example-text{
     color:red;
   }
}
.example-text{
   color:blue;
}

the above code will not working because the executed order. Need to write as following:

.example-text{
   color:blue;
}
@media(max-width:600px){
  .example-text{
     color:red;
   }
}

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

Undirected is N^2. Simple - every node has N options of edges (himself included), total of N nodes thus N*N

Specifying number of decimal places in Python

This standard library solution likely has not been mentioned because the question is so dated. While these answers may scale to the other use cases beyond currency where differing levels of decimals are required, it seems you need it for currency.

I recommend you use the standard library locale.currency object. It seems to have been created to address this problem of currency representation.

import locale
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')

locale.currency(1.23)
>>>'$1.23'
locale.currency(1.53251)
>>>'$1.23'
locale.currency(1)
>>>'$1.00'

locale.currency(mealPrice)

Currency generalizes to other countries as well.

scikit-learn random state in splitting dataset

If you don't specify the random_state in your code, then every time you run(execute) your code a new random value is generated and the train and test datasets would have different values each time.

However, if a fixed value is assigned like random_state = 0 or 1 or 42 then no matter how many times you execute your code the result would be the same .i.e, same values in train and test datasets.

Android ADB doesn't see device

On Windows it is most probably that the device drivers are not installed properly.

First, install Google USB Driver from Android SDK Manager.

Then, go to Start, right-click on My Computer, select Properties and go to Device Manager on the left. Locate you device under Other Devices (Unknown devices, USB Devices). Right-click on it and select Properties. Navigate to Driver tab. Select Update Driver and then Browse my computer for driver software. Choose %ANDROID_SDK_HOME%\extras\google\usb_driver directory. Windows should find and install drivers there. Then run adb kill-server. Next time you do adb devices the device should be in the list.

Getting time difference between two times in PHP

<?php
$start = strtotime("12:00");
$end = // Run query to get datetime value from db
$elapsed = $end - $start;
echo date("H:i", $elapsed);
?>

How to show/hide an element on checkbox checked/unchecked states using jQuery?

$(document).ready(function() {
    $(document).on("click", ".question", function(e) {
       var checked = $(this).find("input:checkbox").is(":checked");
       if (checked) {
           $('.answer').show(300);
       } else {
           $('.answer').hide(300);
       }
    });
});

Rails - Could not find a JavaScript runtime?

if you already install nodejs from source for example, and execjs isn't recognizing it you might want to try this tip: https://coderwall.com/p/hyjdlw

Use multiple custom fonts using @font-face?

If you are having a problem with the font working I have also had this in the past and the issue I found was down to the font-family: name. This had to match what font name was actually given.

The easiest way I found to find this out was to install the font and see what display name is given.

For example, I was using Gill Sans on one project, but the actual font was called Gill Sans MT. Spacing and capitlisation was also important to get right.

Hope that helps.

"Keep Me Logged In" - the best approach

I read all the answers and still found it difficult to extract what I was supposed to do. If a picture is worth 1k words I hope this helps others implement a secure persistent storage based on Barry Jaspan's Improved Persistent Login Cookie Best Practice

enter image description here

If you have questions, feedback, or suggestions, I will try to update the diagram to reflect for the newbie trying to implement a secure persistent login.

Ruby on Rails generates model field:type - what are the options for field:type?

:primary_key, :string, :text, :integer, :float, :decimal, :datetime, :timestamp,
:time, :date, :binary, :boolean, :references

See the table definitions section.

I want to declare an empty array in java and then I want do update it but the code is not working

Your code compiles just fine. However, your array initialization line is wrong:

int array[]={};

What this does is declare an array with a size equal to the number of elements in the brackets. Since there is nothing in the brackets, you're saying the size of the array is 0 - this renders the array completely useless, since now it can't store anything.

Instead, you can either initialize the array right in your original line:

int array[] = { 5, 5, 5, 5 };

Or you can declare the size and then populate it:

int array[] = new int[4];
// ...while loop

If you don't know the size of the array ahead of time (for example, if you're reading a file and storing the contents), you should use an ArrayList instead, because that's an array that grows in size dynamically as more elements are added to it (in layman's terms).

Server certificate verification failed: issuer is not trusted

can you try to run svn checkout once manually to your URL https://yoururl/trunk C:\ant-1.8.1\Test_Checkout using command line and accept certificate.

Or as @AndrewSpear says below

Rather than checking out manually run svn list https://your.repository.url from Terminal (Mac) / Command Line (Win) to get the option to accept the certificate permanently

svn will ask you for confirmation. accept it permanently.

After that this should work for subsequent requests from ant script.

MongoDB via Mongoose JS - What is findByID?

findById is a convenience method on the model that's provided by Mongoose to find a document by its _id. The documentation for it can be found here.

Example:

// Search by ObjectId
var id = "56e6dd2eb4494ed008d595bd";
UserModel.findById(id, function (err, user) { ... } );

Functionally, it's the same as calling:

UserModel.findOne({_id: id}, function (err, user) { ... });

Note that Mongoose will cast the provided id value to the type of _id as defined in the schema (defaulting to ObjectId).

Add a new item to a dictionary in Python

It can be as simple as:

default_data['item3'] = 3

As Chris' answer says, you can use update to add more than one item. An example:

default_data.update({'item4': 4, 'item5': 5})

Please see the documentation about dictionaries as data structures and dictionaries as built-in types.

Error message "Unable to install or run the application. The application requires stdole Version 7.0.3300.0 in the GAC"

Check if you're really using EnvDTE reference. If not, remove it and recompile.

Converting .NET DateTime to JSON

What is returned is milliseconds since epoch. You could do:

var d = new Date();
d.setTime(1245398693390);
document.write(d);

On how to format the date exactly as you want, see full Date reference at http://www.w3schools.com/jsref/jsref_obj_date.asp

You could strip the non-digits by either parsing the integer (as suggested here):

var date = new Date(parseInt(jsonDate.substr(6)));

Or applying the following regular expression (from Tominator in the comments):

var jsonDate = jqueryCall();  // returns "/Date(1245398693390)/"; 
var re = /-?\d+/; 
var m = re.exec(jsonDate); 
var d = new Date(parseInt(m[0]));

Using for loop inside of a JSP

You concrete problem is caused because you're mixing discouraged and old school scriptlets <% %> with its successor EL ${}. They do not share the same variable scope. The allFestivals is not available in scriptlet scope and the i is not available in EL scope.

You should install JSTL (<-- click the link for instructions) and declare it in top of JSP as follows:

<%@taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

and then iterate over the list as follows:

<c:forEach items="${allFestivals}" var="festival">
    <tr>      
        <td>${festival.festivalName}</td>
        <td>${festival.location}</td>
        <td>${festival.startDate}</td>
        <td>${festival.endDate}</td>
        <td>${festival.URL}</td>  
    </tr>
</c:forEach>

(beware of possible XSS attack holes, use <c:out> accordingly)

Don't forget to remove the <jsp:useBean> as it has no utter value here when you're using a servlet as model-and-view controller. It would only lead to confusion. See also our servlets wiki page. Further you would do yourself a favour to disable scriptlets by the following entry in web.xml so that you won't accidently use them:

<jsp-config>
    <jsp-property-group>
        <url-pattern>*.jsp</url-pattern>
        <scripting-invalid>true</scripting-invalid>
    </jsp-property-group>
</jsp-config>

How to check if a json key exists?

Try this

if(!jsonObj.isNull("club")){
    jsonObj.getString("club");
}

Using ADB to capture the screen

To save to a file on Windows, OSX and Linux

adb exec-out screencap -p > screen.png

To copy to clipboard on Linux use

adb exec-out screencap -p | xclip -t image/png

Cannot hide status bar in iOS7

Just add these 2 lines in info.plist file. It will make the fix for iOS7 and older version both.

  • Status bar is initially hidden = YES
  • View controller-based status bar appearance = NO

Navigate to the project and select Targets -> General and see the "Status Bar style ...Hide during application launch" check box will be checked. This will work.

Run a controller function whenever a view is opened/shown

I faced at the same problem, and here i leave the reason of this behavior for everyone else with the same issue.

View LifeCycle

In order to improve performance, we've improved Ionic's ability to cache view elements and scope data. Once a controller is initialized, it may persist throughout the app’s life; it’s just hidden and removed from the watch cycle. Since we aren’t rebuilding scope, we’ve added events for which we should listen when entering the watch cycle again.

To see full description and $ionicView events go to: http://ionicframework.com/blog/navigating-the-changes/

Find duplicate records in MongoDB

The answer anhic gave can be very inefficient if you have a large database and the attribute name is present only in some of the documents.

To improve efficiency you can add a $match to the aggregation.

db.collection.aggregate(
    {"$match": {"name" :{ "$ne" : null } } }, 
    {"$group" : {"_id": "$name", "count": { "$sum": 1 } } },
    {"$match": {"count" : {"$gt": 1} } }, 
    {"$project": {"name" : "$_id", "_id" : 0} }
)

Insert and set value with max()+1 problems

You can use the INSERT ... SELECT statement to get the MAX()+1 value and insert at the same time:

INSERT INTO 
customers( customer_id, firstname, surname )
SELECT MAX( customer_id ) + 1, 'jim', 'sock' FROM customers;

Note: You need to drop the VALUES from your INSERT and make sure the SELECT selected fields match the INSERT declared fields.

C compile : collect2: error: ld returned 1 exit status

If you are using Dev C++ then your .exe or mean to say your program already running and you are trying to run it again.

SQL - Rounding off to 2 decimal places

What ever you use in denomination should be in decimal, for example 1548/100 will give 15.00

If we replace 100 with 100.0 in our example the we will get 15.48

select 1548/100 
15.00000

select 1548/100.0
15.4800

0

Could not resolve placeholder in string value

With Spring Boot :

In the pom.xml

<build>
    <plugins>
        <plugin>
            <groupId>org.springframework.boot</groupId>
            <artifactId>spring-boot-maven-plugin</artifactId>
            <configuration>
                <addResources>true</addResources>
            </configuration>
        </plugin>
    </plugins>
</build>

Example in class Java

@Configuration
@Slf4j
public class MyAppConfig {
    @Value("${foo}")
    private String foo;
    @Value("${bar}")
    private String bar;
    @Bean("foo")
    public String foo() {
        log.info("foo={}", foo);
        return foo;
    }
    @Bean("bar")
    public String bar() {
        log.info("bar={}", bar);
        return bar;
    }
    [ ... ]

In the properties files :

src/main/resources/application.properties

foo=all-env-foo

src/main/resources/application-rec.properties

bar=rec-bar

src/main/resources/application-prod.properties

bar=prod-bar

In the VM arguments of Application.java

-Dspring.profiles.active=[rec|prod]

Don't forget to run mvn command after modifying the properties !

mvn clean package -Dmaven.test.skip=true

In the log file for -Dspring.profiles.active=rec :

The following profiles are active: rec
foo=all-env-foo
bar=rec-bar

In the log file for -Dspring.profiles.active=prod :

The following profiles are active: prod
foo=all-env-foo
bar=prod-bar

In the log file for -Dspring.profiles.active=local :

Could not resolve placeholder 'bar' in value "${bar}"

Oups, I forget to create application-local.properties.

How do I clone a single branch in Git?

Open the cmd.

cd folder_name  # enter the path where to clone the branch

Just one command:

git clone url_of_projecturltoclone -b branch_name

How to extract one column of a csv file

I think the easiest is using csvkit:

Gets the 2nd column: csvcut -c 2 file.csv

However, there's also csvtool, and probably a number of other csv bash tools out there:

sudo apt-get install csvtool (for Debian-based systems)

This would return a column with the first row having 'ID' in it. csvtool namedcol ID csv_file.csv

This would return the fourth row: csvtool col 4 csv_file.csv

If you want to drop the header row:

csvtool col 4 csv_file.csv | sed '1d'

SSIS Excel Connection Manager failed to Connect to the Source

As discussed in the below:

Solution: Go to https://marketplace.visualstudio.com/items?itemName=ProBITools.MicrosoftAnalysisServicesModelingProjects and install the latest version, it has a fix in there to resolve this issue.

Reference: https://developercommunity.visualstudio.com/content/problem/745991/could-not-load-file-or-assembly-microsoftdatawareh.html

A fix for this issue has been internally implemented and is being prepared for release. We’ll update you once it becomes available for download. For now, please install latest SSAS from https://marketplace.visualstudio.com/items?itemName=ProBITools.MicrosoftAnalysisServicesModelingProjects to work around the issue. Sorry for any inconvenience.

Passing HTML to template using Flask/Jinja2

From the jinja docs section HTML Escaping:

When automatic escaping is enabled everything is escaped by default except for values explicitly marked as safe. Those can either be marked by the application or in the template by using the |safe filter.

Example:

 <div class="info">
   {{data.email_content|safe}}
 </div>

Type of expression is ambiguous without more context Swift

You have two " " before the =

let imageToDeleteParameters = imagesToDelete.map { ["id": $0.id, "url": $0.url.absoluteString, "_destroy": true] }

Why use Redux over Facebook Flux?

In Quora, somebody says:

First of all, it is totally possible to write apps with React without Flux.

Also this visual diagram which I've created to show a quick view of both, probably a quick answer for the people who don't want to read the whole explanation: Flux vs Redux

But if you still interested knowing more, read on.

I believe you should start with pure React, then learn Redux and Flux. After you will have some REAL experience with React, you will see whether Redux is helpful for you or not.

Maybe you will feel that Redux is exactly for your app and maybe you will find out, that Redux is trying to solve a problem you are not really experiencing.

If you start directly with Redux, you may end up with over-engineered code, code harder to maintain and with even more bugs and than without Redux.

From Redux docs:

Motivation
As the requirements for JavaScript single-page applications have become increasingly complicated, our code must manage more state than ever before. This state can include server responses and cached data, as well as locally created data that has not yet been persisted to the server. UI state is also increasing in complexity, as we need to manage active routes, selected tabs, spinners, pagination controls, and so on.

Managing this ever-changing state is hard. If a model can update another model, then a view can update a model, which updates another model, and this, in turn, might cause another view to update. At some point, you no longer understand what happens in your app as you have lost control over the when, why, and how of its state. When a system is opaque and non-deterministic, it's hard to reproduce bugs or add new features.

As if this wasn't bad enough, consider the new requirements becoming common in front-end product development. As developers, we are expected to handle optimistic updates, server-side rendering, fetching data before performing route transitions, and so on. We find ourselves trying to manage a complexity that we have never had to deal with before, and we inevitably ask the question: Is it time to give up? The answer is No.

This complexity is difficult to handle as we're mixing two concepts that are very hard for the human mind to reason about: mutation and asynchronicity. I call them Mentos and Coke. Both can be great when separated, but together they create a mess. Libraries like React attempt to solve this problem in the view layer by removing both asynchrony and direct DOM manipulation. However, managing the state of your data is left up to you. This is where Redux comes in.

Following in the footsteps of Flux, CQRS, and Event Sourcing, Redux attempts to make state mutations predictable by imposing certain restrictions on how and when updates can happen. These restrictions are reflected in the three principles of Redux.

Also from Redux docs:

Core Concepts
Redux itself is very simple.

Imagine your app's state is described as a plain object. For example, the state of a todo app might look like this:

{
  todos: [{
    text: 'Eat food',
    completed: true
  }, {
    text: 'Exercise',
    completed: false
  }],
  visibilityFilter: 'SHOW_COMPLETED'
}

This object is like a "model" except that there are no setters. This is so that different parts of the code can’t change the state arbitrarily, causing hard-to-reproduce bugs.

To change something in the state, you need to dispatch an action. An action is a plain JavaScript object (notice how we don't introduce any magic?) that describes what happened. Here are a few example actions:

{ type: 'ADD_TODO', text: 'Go to swimming pool' }
{ type: 'TOGGLE_TODO', index: 1 }
{ type: 'SET_VISIBILITY_FILTER', filter: 'SHOW_ALL' }

Enforcing that every change is described as an action lets us have a clear understanding of what’s going on in the app. If something changed, we know why it changed. Actions are like breadcrumbs of what has happened. Finally, to tie state and actions together, we write a function called a reducer. Again, nothing magic about it — it's just a function that takes state and action as arguments, and returns the next state of the app. It would be hard to write such a function for a big app, so we write smaller functions managing parts of the state:

function visibilityFilter(state = 'SHOW_ALL', action) {
  if (action.type === 'SET_VISIBILITY_FILTER') {
    return action.filter;
  } else {
    return state;
  }
}

function todos(state = [], action) {
  switch (action.type) {
  case 'ADD_TODO':
    return state.concat([{ text: action.text, completed: false }]);
  case 'TOGGLE_TODO':
    return state.map((todo, index) =>
      action.index === index ?
        { text: todo.text, completed: !todo.completed } :
        todo
   )
  default:
    return state;
  }
}

And we write another reducer that manages the complete state of our app by calling those two reducers for the corresponding state keys:

function todoApp(state = {}, action) {
  return {
    todos: todos(state.todos, action),
    visibilityFilter: visibilityFilter(state.visibilityFilter, action)
  };
}

This is basically the whole idea of Redux. Note that we haven't used any Redux APIs. It comes with a few utilities to facilitate this pattern, but the main idea is that you describe how your state is updated over time in response to action objects, and 90% of the code you write is just plain JavaScript, with no use of Redux itself, its APIs, or any magic.

SQL Server SELECT into existing table

select *
into existing table database..existingtable
from database..othertables....

If you have used select * into tablename from other tablenames already, next time, to append, you say select * into existing table tablename from other tablenames

NGINX: upstream timed out (110: Connection timed out) while reading response header from upstream

First figure out which upstream is slowing by consulting the nginx error log file and adjust the read time out accordingly in my case it was fastCGI

2017/09/27 13:34:03 [error] 16559#16559: *14381 upstream timed out (110: Connection timed out) while reading response header from upstream, client:xxxxxxxxxxxxxxxxxxxxxxxxx", upstream: "fastcgi://unix:/var/run/php/php5.6-fpm.sock", host: "xxxxxxxxxxxxxxx", referrer: "xxxxxxxxxxxxxxxxxxxx"

So i have to adjust the fastcgi_read_timeout in my server configuration

 location ~ \.php$ {
     fastcgi_read_timeout 240;
     ...
 }

See: original post

How SID is different from Service name in Oracle tnsnames.ora

what is a SID and Service name

please look into oracle's documentation at https://docs.oracle.com/cd/B19306_01/network.102/b14212/concepts.htm

In case if the above link is not accessable in future, At the time time of writing this answer, the above link will direct you to, "Database Service and Database Instance Identification" topic in Connectivity Concepts chapter of "Database Net Services Administrator's Guide". This guide is published by oracle as part of "Oracle Database Online Documentation, 10g Release 2 (10.2)"

When I have to use one or another? Why do I need two of them?

Consider below mapping in a RAC Environment,

SID      SERVICE_NAME
bob1    bob
bob2    bob
bob3    bob
bob4    bob

if load balancing is configured, the listener will 'balance' the workload across all four SIDs. Even if load balancing is configured, you can connect to bob1 all the time if you want to by using the SID instead of SERVICE_NAME.

Please refer, https://community.oracle.com/thread/4049517

How to pass multiple values to single parameter in stored procedure

Either use a User Defined Table

Or you can use CSV by defining your own CSV function as per This Post.

I'd probably recommend the second method, as your stored proc is already written in the correct format and you'll find it handy later on if you need to do this down the road.

Cheers!

How to receive serial data using android bluetooth

The issue with the null connection is related to the findBT() function. you must change the device name from "MattsBlueTooth" to your device name as well as confirm the UUID for your service/device. Use something like BLEScanner app to confrim both on Android.

Python Socket Receive Large Amount of Data

Disclaimer: There are very rare cases in which you really need to do this. If possible use an existing application layer protocol or define your own eg. precede each message with a fixed length integer indicating the length of data that follows or terminate each message with a '\n' character. (Adam Rosenfield's answer does a really good job at explaining that)

With that said, there is a way to read all of the data available on a socket. However, it is a bad idea to rely on this kind of communication as it introduces the risk of loosing data. Use this solution with extreme caution and only after reading the explanation below.

def recvall(sock):
    BUFF_SIZE = 4096
    data = bytearray()
    while True:
        packet = sock.recv(BUFF_SIZE)
        if not packet:  # Important!!
            break
        data.extend(packet)
    return data

Now the if not packet: line is absolutely critical! Many answers here suggested using a condition like if len(packet) < BUFF_SIZE: which is broken and will most likely cause you to close your connection prematurely and loose data. It wrongly assumes that one send on one end of a TCP socket corresponds to one receive of sent number of bytes on the other end. It does not. There is a very good chance that sock.recv(BUFF_SIZE) will return a chunk smaller than BUFF_SIZE even if there's still data waiting to be received. There is a good explanation of the issue here and here.

By using the above solution you are still risking data loss if the other end of the connection is writing data slower than you are reading. You may just simply consume all data on your end and exit when more is on the way. There are ways around it that require the use of concurrent programming, but that's another topic of its own.

Read file-contents into a string in C++

maybe not the most efficient, but reads data in one line:

#include<iostream>
#include<vector>
#include<iterator>

main(int argc,char *argv[]){
  // read standard input into vector:
  std::vector<char>v(std::istream_iterator<char>(std::cin),
                     std::istream_iterator<char>());
  std::cout << "read " << v.size() << "chars\n";
}

Getting output of system() calls in Ruby

I'd like to expand & clarify chaos's answer a bit.

If you surround your command with backticks, then you don't need to (explicitly) call system() at all. The backticks execute the command and return the output as a string. You can then assign the value to a variable like so:

output = `ls`
p output

or

printf output # escapes newline chars

dd: How to calculate optimal blocksize?

As others have said, there is no universally correct block size; what is optimal for one situation or one piece of hardware may be terribly inefficient for another. Also, depending on the health of the disks it may be preferable to use a different block size than what is "optimal".

One thing that is pretty reliable on modern hardware is that the default block size of 512 bytes tends to be almost an order of magnitude slower than a more optimal alternative. When in doubt, I've found that 64K is a pretty solid modern default. Though 64K usually isn't THE optimal block size, in my experience it tends to be a lot more efficient than the default. 64K also has a pretty solid history of being reliably performant: You can find a message from the Eug-Lug mailing list, circa 2002, recommending a block size of 64K here: http://www.mail-archive.com/[email protected]/msg12073.html

For determining THE optimal output block size, I've written the following script that tests writing a 128M test file with dd at a range of different block sizes, from the default of 512 bytes to a maximum of 64M. Be warned, this script uses dd internally, so use with caution.

dd_obs_test.sh:

#!/bin/bash

# Since we're dealing with dd, abort if any errors occur
set -e

TEST_FILE=${1:-dd_obs_testfile}
TEST_FILE_EXISTS=0
if [ -e "$TEST_FILE" ]; then TEST_FILE_EXISTS=1; fi
TEST_FILE_SIZE=134217728

if [ $EUID -ne 0 ]; then
  echo "NOTE: Kernel cache will not be cleared between tests without sudo. This will likely cause inaccurate results." 1>&2
fi

# Header
PRINTF_FORMAT="%8s : %s\n"
printf "$PRINTF_FORMAT" 'block size' 'transfer rate'

# Block sizes of 512b 1K 2K 4K 8K 16K 32K 64K 128K 256K 512K 1M 2M 4M 8M 16M 32M 64M
for BLOCK_SIZE in 512 1024 2048 4096 8192 16384 32768 65536 131072 262144 524288 1048576 2097152 4194304 8388608 16777216 33554432 67108864
do
  # Calculate number of segments required to copy
  COUNT=$(($TEST_FILE_SIZE / $BLOCK_SIZE))

  if [ $COUNT -le 0 ]; then
    echo "Block size of $BLOCK_SIZE estimated to require $COUNT blocks, aborting further tests."
    break
  fi

  # Clear kernel cache to ensure more accurate test
  [ $EUID -eq 0 ] && [ -e /proc/sys/vm/drop_caches ] && echo 3 > /proc/sys/vm/drop_caches

  # Create a test file with the specified block size
  DD_RESULT=$(dd if=/dev/zero of=$TEST_FILE bs=$BLOCK_SIZE count=$COUNT conv=fsync 2>&1 1>/dev/null)

  # Extract the transfer rate from dd's STDERR output
  TRANSFER_RATE=$(echo $DD_RESULT | \grep --only-matching -E '[0-9.]+ ([MGk]?B|bytes)/s(ec)?')

  # Clean up the test file if we created one
  if [ $TEST_FILE_EXISTS -ne 0 ]; then rm $TEST_FILE; fi

  # Output the result
  printf "$PRINTF_FORMAT" "$BLOCK_SIZE" "$TRANSFER_RATE"
done

View on GitHub

I've only tested this script on a Debian (Ubuntu) system and on OSX Yosemite, so it will probably take some tweaking to make work on other Unix flavors.

By default the command will create a test file named dd_obs_testfile in the current directory. Alternatively, you can provide a path to a custom test file by providing a path after the script name:

$ ./dd_obs_test.sh /path/to/disk/test_file

The output of the script is a list of the tested block sizes and their respective transfer rates like so:

$ ./dd_obs_test.sh
block size : transfer rate
       512 : 11.3 MB/s
      1024 : 22.1 MB/s
      2048 : 42.3 MB/s
      4096 : 75.2 MB/s
      8192 : 90.7 MB/s
     16384 : 101 MB/s
     32768 : 104 MB/s
     65536 : 108 MB/s
    131072 : 113 MB/s
    262144 : 112 MB/s
    524288 : 133 MB/s
   1048576 : 125 MB/s
   2097152 : 113 MB/s
   4194304 : 106 MB/s
   8388608 : 107 MB/s
  16777216 : 110 MB/s
  33554432 : 119 MB/s
  67108864 : 134 MB/s

(Note: The unit of the transfer rates will vary by OS)

To test optimal read block size, you could use more or less the same process, but instead of reading from /dev/zero and writing to the disk, you'd read from the disk and write to /dev/null. A script to do this might look like so:

dd_ibs_test.sh:

#!/bin/bash

# Since we're dealing with dd, abort if any errors occur
set -e

TEST_FILE=${1:-dd_ibs_testfile}
if [ -e "$TEST_FILE" ]; then TEST_FILE_EXISTS=$?; fi
TEST_FILE_SIZE=134217728

# Exit if file exists
if [ -e $TEST_FILE ]; then
  echo "Test file $TEST_FILE exists, aborting."
  exit 1
fi
TEST_FILE_EXISTS=1

if [ $EUID -ne 0 ]; then
  echo "NOTE: Kernel cache will not be cleared between tests without sudo. This will likely cause inaccurate results." 1>&2
fi

# Create test file
echo 'Generating test file...'
BLOCK_SIZE=65536
COUNT=$(($TEST_FILE_SIZE / $BLOCK_SIZE))
dd if=/dev/urandom of=$TEST_FILE bs=$BLOCK_SIZE count=$COUNT conv=fsync > /dev/null 2>&1

# Header
PRINTF_FORMAT="%8s : %s\n"
printf "$PRINTF_FORMAT" 'block size' 'transfer rate'

# Block sizes of 512b 1K 2K 4K 8K 16K 32K 64K 128K 256K 512K 1M 2M 4M 8M 16M 32M 64M
for BLOCK_SIZE in 512 1024 2048 4096 8192 16384 32768 65536 131072 262144 524288 1048576 2097152 4194304 8388608 16777216 33554432 67108864
do
  # Clear kernel cache to ensure more accurate test
  [ $EUID -eq 0 ] && [ -e /proc/sys/vm/drop_caches ] && echo 3 > /proc/sys/vm/drop_caches

  # Read test file out to /dev/null with specified block size
  DD_RESULT=$(dd if=$TEST_FILE of=/dev/null bs=$BLOCK_SIZE 2>&1 1>/dev/null)

  # Extract transfer rate
  TRANSFER_RATE=$(echo $DD_RESULT | \grep --only-matching -E '[0-9.]+ ([MGk]?B|bytes)/s(ec)?')

  printf "$PRINTF_FORMAT" "$BLOCK_SIZE" "$TRANSFER_RATE"
done

# Clean up the test file if we created one
if [ $TEST_FILE_EXISTS -ne 0 ]; then rm $TEST_FILE; fi

View on GitHub

An important difference in this case is that the test file is a file that is written by the script. Do not point this command at an existing file or the existing file will be overwritten with zeroes!

For my particular hardware I found that 128K was the most optimal input block size on a HDD and 32K was most optimal on a SSD.

Though this answer covers most of my findings, I've run into this situation enough times that I wrote a blog post about it: http://blog.tdg5.com/tuning-dd-block-size/ You can find more specifics on the tests I performed there.

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

You need to include the reference to the assembly System.Web.Mvc in you project.

you may not have the System.Web.Mvc in your C:\Program Files (x86)\Reference Assemblies\Microsoft\Framework.NETFramework\v4.0

So you need to add it and then to include it as reference to your projrect

Do I cast the result of malloc?

The best thing to do when programming in C whenever it is possible:

  1. Make your program compile through a C compiler with all warnings turned on -Wall and fix all errors and warnings
  2. Make sure there are no variables declared as auto
  3. Then compile it using a C++ compiler with -Wall and -std=c++11. Fix all errors and warnings.
  4. Now compile using the C compiler again. Your program should now compile without any warning and contain fewer bugs.

This procedure lets you take advantage of C++ strict type checking, thus reducing the number of bugs. In particular, this procedure forces you to include stdlib.hor you will get

malloc was not declared within this scope

and also forces you to cast the result of malloc or you will get

invalid conversion from void* to T*

or what ever your target type is.

The only benefits from writing in C instead of C++ I can find are

  1. C has a well specified ABI
  2. C++ may generate more code [exceptions, RTTI, templates, runtime polymorphism]

Notice that the second cons should in the ideal case disappear when using the subset common to C together with the static polymorphic feature.

For those that finds C++ strict rules inconvenient, we can use the C++11 feature with inferred type

auto memblock=static_cast<T*>(malloc(n*sizeof(T))); //Mult may overflow...

Detect if Android device has Internet connection

public boolean isInternetWorking() {
    boolean success = false;
    try {
        URL url = new URL("https://google.com");
        HttpURLConnection connection = (HttpURLConnection) url.openConnection();
        connection.setConnectTimeout(10000);
        connection.connect();
        success = connection.getResponseCode() == 200;
    } catch (IOException e) {
        e.printStackTrace();
    }
    return success;
}

return true if internet is actually available

Make sure you have these two permission

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

if http does not work its because of the new android security they donot allow plain text communication now. for now just to by pass it.

android:usesCleartextTraffic="true"

Why does the PHP json_encode function convert UTF-8 strings to hexadecimal entities?

Is this the expected behavior?

the json_encode() only works with UTF-8 encoded data.

maybe you can get an answer to convert it here: cyrillic-characters-in-phps-json-encode

Determine if running on a rooted device

RootBeer is a root checking Android library by Scott and Matthew. It uses various checks to indicate whether device is rooted or not.

Java checks

  • CheckRootManagementApps

  • CheckPotentiallyDangerousAppss

  • CheckRootCloakingApps

  • CheckTestKeys

  • checkForDangerousProps

  • checkForBusyBoxBinary

  • checkForSuBinary

  • checkSuExists

  • checkForRWSystem

Native checks

We call through to our native root checker to run some of it's own checks. Native checks are typically harder to cloak, so some root cloak apps just block the loading of native libraries that contain certain key words.

  • checkForSuBinary

SQL Server - find nth occurrence in a string

I've used a function to grab the "nth" element from a delimited string field with great success. Like mentioned above, it's not a "fast" way of dealing with things but it sure as heck is convenient.

create function GetArrayIndex(@delimited nvarchar(max), @index int,  @delimiter nvarchar(100) = ',')  returns nvarchar(max)  
as    
begin     
 declare @xml xml, @result nvarchar(max)  
 set @xml = N'<root><r>' + replace(@delimited, @delimiter,'</r><r>') + '</r></root>'  
 select @result = r.value('.','varchar(max)')   
 from @xml.nodes('//root/r[sql:variable("@index")]') as records(r)  

 return @result   
end    

Replace \n with <br />

The Problem is When you denote '\n' in the replace() call , '\n' is treated as a String length=4 made out of ' \ n '
To get rid of this, use ascii notation. http://www.asciitable.com/

example:

newLine = chr(10)
thatLine=thatLine.replace(newLine , '<br />')

print(thatLine) #python3

print thatLine #python2 .

What is the default Precision and Scale for a Number in Oracle?

I expand on spectra‘s answer so people don’t have to try it for themselves.

This was done on Oracle Database 11g Express Edition Release 11.2.0.2.0 - Production.

CREATE TABLE CUSTOMERS
(
  CUSTOMER_ID NUMBER NOT NULL,
  FOO FLOAT NOT NULL,
  JOIN_DATE DATE NOT NULL,
  CUSTOMER_STATUS VARCHAR2(8) NOT NULL,
  CUSTOMER_NAME VARCHAR2(20) NOT NULL,
  CREDITRATING VARCHAR2(10)
);

select column_name, data_type, nullable, data_length, data_precision, data_scale
from user_tab_columns where table_name ='CUSTOMERS'; 

Which yields

COLUMN_NAME      DATA_TYPE  NULLABLE DATA_LENGTH DATA_PRECISION DATA_SCALE
CUSTOMER_ID      NUMBER     N        22        
FOO              FLOAT      N        22          126    
JOIN_DATE        DATE       N        7        
CUSTOMER_STATUS  VARCHAR2   N        8        
CUSTOMER_NAME    VARCHAR2   N        20        
CREDITRATING     VARCHAR2   Y        10    

What is "with (nolock)" in SQL Server?

I use with (nolock) hint particularly in SQLServer 2000 databases with high activity. I am not certain that it is needed in SQL Server 2005 however. I recently added that hint in a SQL Server 2000 at the request of the client's DBA, because he was noticing a lot of SPID record locks.

All I can say is that using the hint has NOT hurt us and appears to have made the locking problem solve itself. The DBA at that particular client basically insisted that we use the hint.

By the way, the databases I deal with are back-ends to enterprise medical claims systems, so we are talking about millions of records and 20+ tables in many joins. I typically add a WITH (nolock) hint for each table in the join (unless it is a derived table, in which case you can't use that particular hint)

How do I execute a string containing Python code in Python?

eval and exec are the correct solution, and they can be used in a safer manner.

As discussed in Python's reference manual and clearly explained in this tutorial, the eval and exec functions take two extra parameters that allow a user to specify what global and local functions and variables are available.

For example:

public_variable = 10

private_variable = 2

def public_function():
    return "public information"

def private_function():
    return "super sensitive information"

# make a list of safe functions
safe_list = ['public_variable', 'public_function']
safe_dict = dict([ (k, locals().get(k, None)) for k in safe_list ])
# add any needed builtins back in
safe_dict['len'] = len

>>> eval("public_variable+2", {"__builtins__" : None }, safe_dict)
12

>>> eval("private_variable+2", {"__builtins__" : None }, safe_dict)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'private_variable' is not defined

>>> exec("print \"'%s' has %i characters\" % (public_function(), len(public_function()))", {"__builtins__" : None}, safe_dict)
'public information' has 18 characters

>>> exec("print \"'%s' has %i characters\" % (private_function(), len(private_function()))", {"__builtins__" : None}, safe_dict)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
  File "<string>", line 1, in <module>
NameError: name 'private_function' is not defined

In essence you are defining the namespace in which the code will be executed.

ImageMagick security policy 'PDF' blocking conversion

Works in Ubuntu 20.04

Add this line inside <policymap>

<policy domain="module" rights="read|write" pattern="{PS,PDF,XPS}" />

Comment these lines:

  <!--
  <policy domain="coder" rights="none" pattern="PS" />
  <policy domain="coder" rights="none" pattern="PS2" />
  <policy domain="coder" rights="none" pattern="PS3" />
  <policy domain="coder" rights="none" pattern="EPS" />
  <policy domain="coder" rights="none" pattern="PDF" />
  <policy domain="coder" rights="none" pattern="XPS" />
   -->

Returning value that was passed into a method

Even more useful, if you have multiple parameters you can access any/all of them with:

_mock.Setup(x => x.DoSomething(It.IsAny<string>(),It.IsAny<string>(),It.IsAny<string>())
     .Returns((string a, string b, string c) => string.Concat(a,b,c));

You always need to reference all the arguments, to match the method's signature, even if you're only going to use one of them.

How to validate a form with multiple checkboxes to have atleast one checked

I checked all answers and even in other similar questions, I tried to find optimal way with help of html class and custom rule.

my html structure for multiple checkboxes are like this

_x000D_
_x000D_
$.validator.addMethod('multicheckbox_rule', function (value, element) {_x000D_
   var $parent = $(element).closest('.checkbox_wrapper');_x000D_
   if($parent.find('.checkbox_item').is(':checked')) return true;_x000D_
            return false;_x000D_
}, 'Please at least select one');
_x000D_
<div class="checkbox_wrapper">_x000D_
<label for="checkbox-1"><input class="checkbox_item" id="checkbox-1"  name="checkbox_item[1]" type="checkbox" value="1" data-rule-multicheckbox_rule="1" /> Checkbox_item 1</label>_x000D_
<label for="checkbox-2"><input class="checkbox_item" id="checkbox-2" name="checkbox_item[2]" type="checkbox" value="1" data-rule-multicheckbox_rule="1" /> Checkbox_item 1</label>_x000D_
</div>
_x000D_
_x000D_
_x000D_

UILabel - auto-size label to fit text?

Using [label sizeToFit]; will achieve the same result from Daniels Category.

Although I recommend to use autolayout and let the label resize itself based on constraints.

Jquery Value match Regex

  • Pass a string to RegExp or create a regex using the // syntax
  • Call regex.test(string), not string.test(regex)

So

jQuery(function () {
    $(".mail").keyup(function () {
        var VAL = this.value;

        var email = new RegExp('^[A-Z0-9._%+-]+@[A-Z0-9.-]+\.[A-Z]{2,4}$');

        if (email.test(VAL)) {
            alert('Great, you entered an E-Mail-address');
        }
    });
});

Java - using System.getProperty("user.dir") to get the home directory

Program to get the current working directory=user.dir

public class CurrentDirectoryExample {

    public static void main(String args[]) {

        String current = System.getProperty("user.dir");
        System.out.println("Current working directory in Java : " + current);
    }
}

Should a 502 HTTP status code be used if a proxy receives no response at all?

Yes. Empty or incomplete headers or response body typically caused by broken connections or server side crash can cause 502 errors if accessed via a gateway or proxy.

For more information about the network errors

https://en.wikipedia.org/wiki/List_of_HTTP_status_codes

How To Create Table with Identity Column

This has already been answered, but I think the simplest syntax is:

CREATE TABLE History (
    ID int primary key IDENTITY(1,1) NOT NULL,
    . . .

The more complicated constraint index is useful when you actually want to change the options.

By the way, I prefer to name such a column HistoryId, so it matches the names of the columns in foreign key relationships.

LaTex left arrow over letter in math mode

Use \overleftarrow to create a long arrow to the left.

\overleftarrow{blahblahblah}

LaTeX output

Access Session attribute on jstl

You should definitely avoid using <jsp:...> tags. They're relics from the past and should always be avoided now.

Use the JSTL.

Now, wether you use the JSTL or any other tag library, accessing to a bean property needs your bean to have this property. A property is not a private instance variable. It's an information accessible via a public getter (and setter, if the property is writable). To access the questionPaperID property, you thus need to have a

public SomeType getQuestionPaperID() {
    //...
}

method in your bean.

Once you have that, you can display the value of this property using this code :

<c:out value="${Questions.questionPaperID}" />

or, to specifically target the session scoped attributes (in case of conflicts between scopes) :

<c:out value="${sessionScope.Questions.questionPaperID}" />

Finally, I encourage you to name scope attributes as Java variables : starting with a lowercase letter.

When is a timestamp (auto) updated?

I think you have to define the timestamp column like this

CREATE TABLE t1 
(
    ts TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
);

See here