Programs & Examples On #Rxtx

RXTX is a Java library, using a native implementation (via JNI), providing serial and parallel communication for the Java Development Toolkit (JDK).

Javascript reduce on array of objects

Array reduce function takes three parameters i.e, initialValue(default it's 0) , accumulator and current value . By default the value of initialValue will be "0" . which is taken by accumulator

Let's see this in code .

var arr =[1,2,4] ;
arr.reduce((acc,currVal) => acc + currVal ) ; 
// (remember Initialvalue is 0 by default )

//first iteration** : 0 +1 => Now accumulator =1;
//second iteration** : 1 +2 => Now accumulator =3;
//third iteration** : 3 + 4 => Now accumulator = 7;
No more array properties now the loop breaks .
// solution = 7

Now same example with initial Value :

var initialValue = 10;
var arr =[1,2,4] ;
arr.reduce((acc,currVal) => acc + currVal,initialValue ) ; 
/
// (remember Initialvalue is 0 by default but now it's 10 )

//first iteration** : 10 +1 => Now accumulator =11;
//second iteration** : 11 +2 => Now accumulator =13;
//third iteration** : 13 + 4 => Now accumulator = 17;
No more array properties now the loop breaks .
//solution=17

Same applies for the object arrays as well(the current stackoverflow question) :

var arr = [{x:1},{x:2},{x:4}]
arr.reduce(function(acc,currVal){return acc + currVal.x}) 
// destructing {x:1} = currVal;
Now currVal is object which have all the object properties .So now 
currVal.x=>1 
//first iteration** : 0 +1 => Now accumulator =1;
//second iteration** : 1 +2 => Now accumulator =3;
//third iteration** : 3 + 4 => Now accumulator = 7;
No more array properties now the loop breaks 
//solution=7

ONE THING TO BARE IN MIND is InitialValue by default is 0 and can be given anything i mean {},[] and number

Sql Server string to date conversion

In SQL Server Denali, you will be able to do something that approaches what you're looking for. But you still can't just pass any arbitrarily defined wacky date string and expect SQL Server to accommodate. Here is one example using something you posted in your own answer. The FORMAT() function and can also accept locales as an optional argument - it is based on .Net's format, so most if not all of the token formats you'd expect to see will be there.

DECLARE @d DATETIME = '2008-10-13 18:45:19';

-- returns Oct-13/2008 18:45:19:
SELECT FORMAT(@d, N'MMM-dd/yyyy HH:mm:ss');

-- returns NULL if the conversion fails:
SELECT TRY_PARSE(FORMAT(@d, N'MMM-dd/yyyy HH:mm:ss') AS DATETIME);

-- returns an error if the conversion fails:
SELECT PARSE(FORMAT(@d, N'MMM-dd/yyyy HH:mm:ss') AS DATETIME);

I strongly encourage you to take more control and sanitize your date inputs. The days of letting people type dates using whatever format they want into a freetext form field should be way behind us by now. If someone enters 8/9/2011 is that August 9th or September 8th? If you make them pick a date on a calendar control, then the app can control the format. No matter how much you try to predict your users' behavior, they'll always figure out a dumber way to enter a date that you didn't plan for.

Until Denali, though, I think that @Ovidiu has the best advice so far... this can be made fairly trivial by implementing your own CLR function. Then you can write a case/switch for as many wacky non-standard formats as you want.


UPDATE for @dhergert:

SELECT TRY_PARSE('10/15/2008 10:06:32 PM' AS DATETIME USING 'en-us');
SELECT TRY_PARSE('15/10/2008 10:06:32 PM' AS DATETIME USING 'en-gb');

Results:

2008-10-15 22:06:32.000
2008-10-15 22:06:32.000

You still need to have that other crucial piece of information first. You can't use native T-SQL to determine whether 6/9/2012 is June 9th or September 6th.

How To Run PHP From Windows Command Line in WAMPServer

The PHP CLI as its called ( php for the Command Line Interface ) is called php.exe It lives in c:\wamp\bin\php\php5.x.y\php.exe ( where x and y are the version numbers of php that you have installed )

If you want to create php scrips to run from the command line then great its easy and very useful.

Create yourself a batch file like this, lets call it phppath.cmd :

PATH=%PATH%;c:\wamp\bin\php\phpx.y.z
php -v

Change x.y.z to a valid folder name for a version of PHP that you have installed within WAMPServer

Save this into one of your folders that is already on your PATH, so you can run it from anywhere.

Now from a command window, cd into your source folder and run >phppath.

Then run

php your_script.php

It should work like a dream.

Here is an example that configures PHP Composer and PEAR if required and they exist

@echo off

REM **************************************************************
REM * PLACE This file in a folder that is already on your PATH
REM * Or just put it in your C:\Windows folder as that is on the
REM * Search path by default
REM * - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
REM * EDIT THE NEXT 3 Parameters to fit your installed WAMPServer
REM **************************************************************


set baseWamp=D:\wamp
set defaultPHPver=7.4.3
set composerInstalled=%baseWamp%\composer
set phpFolder=\bin\php\php

if %1.==. (
    set phpver=%baseWamp%%phpFolder%%defaultPHPver%
) else (
    set phpver=%baseWamp%%phpFolder%%1
)

PATH=%PATH%;%phpver%
php -v
echo ---------------------------------------------------------------


REM IF PEAR IS INSTALLED IN THIS VERSION OF PHP

IF exist %phpver%\pear (
    set PHP_PEAR_SYSCONF_DIR=%baseWamp%%phpFolder%%phpver%
    set PHP_PEAR_INSTALL_DIR=%baseWamp%%phpFolder%%phpver%\pear
    set PHP_PEAR_DOC_DIR=%baseWamp%%phpFolder%%phpver%\docs
    set PHP_PEAR_BIN_DIR=%baseWamp%%phpFolder%%phpver%
    set PHP_PEAR_DATA_DIR=%baseWamp%%phpFolder%%phpver%\data
    set PHP_PEAR_PHP_BIN=%baseWamp%%phpFolder%%phpver%\php.exe
    set PHP_PEAR_TEST_DIR=%baseWamp%%phpFolder%%phpver%\tests

    echo PEAR INCLUDED IN THIS CONFIG
    echo ---------------------------------------------------------------
) else (
    echo PEAR DOES NOT EXIST IN THIS VERSION OF php
    echo ---------------------------------------------------------------
)

REM IF A GLOBAL COMPOSER EXISTS ADD THAT TOO
REM **************************************************************
REM * IF A GLOBAL COMPOSER EXISTS ADD THAT TOO
REM *
REM * This assumes that composer is installed in /wamp/composer
REM *
REM **************************************************************
IF EXIST %composerInstalled% (
    ECHO COMPOSER INCLUDED IN THIS CONFIG
    echo ---------------------------------------------------------------
    set COMPOSER_HOME=%baseWamp%\composer
    set COMPOSER_CACHE_DIR=%baseWamp%\composer

    PATH=%PATH%;%baseWamp%\composer

    rem echo TO UPDATE COMPOSER do > composer self-update
    echo ---------------------------------------------------------------
) else (
    echo ---------------------------------------------------------------
    echo COMPOSER IS NOT INSTALLED
    echo ---------------------------------------------------------------
)

set baseWamp=
set defaultPHPver=
set composerInstalled=
set phpFolder=

Call this command file like this to use the default version of PHP

> phppath

Or to get a specific version of PHP like this

> phppath 5.6.30

How to automatically crop and center an image

There is another way you can crop image centered:

.thumbnail{position: relative; overflow: hidden; width: 320px; height: 640px;}
.thumbnail img{
    position: absolute; top: -999px; bottom: -999px; left: -999px; right: -999px;
    width: auto !important; height: 100% !important; margin: auto;
}
.thumbnail img.vertical{width: 100% !important; height: auto !important;}

The only thing you will need is to add class "vertical" to vertical images, you can do it with this code:

jQuery(function($) {
    $('img').one('load', function () {
        var $img = $(this);
        var tempImage1 = new Image();
        tempImage1.src = $img.attr('src');
        tempImage1.onload = function() {
            var ratio = tempImage1.width / tempImage1.height;
            if(!isNaN(ratio) && ratio < 1) $img.addClass('vertical');
        }
    }).each(function () {
        if (this.complete) $(this).load();
    });
});

Note: "!important" is used to override possible width, height attributes on img tag.

Python initializing a list of lists

The problem is that they're all the same exact list in memory. When you use the [x]*n syntax, what you get is a list of n many x objects, but they're all references to the same object. They're not distinct instances, rather, just n references to the same instance.

To make a list of 3 different lists, do this:

x = [[] for i in range(3)]

This gives you 3 separate instances of [], which is what you want

[[]]*n is similar to

l = []
x = []
for i in range(n):
    x.append(l)

While [[] for i in range(3)] is similar to:

x = []
for i in range(n):
    x.append([])   # appending a new list!

In [20]: x = [[]] * 4

In [21]: [id(i) for i in x]
Out[21]: [164363948, 164363948, 164363948, 164363948] # same id()'s for each list,i.e same object


In [22]: x=[[] for i in range(4)]

In [23]: [id(i) for i in x]
Out[23]: [164382060, 164364140, 164363628, 164381292] #different id(), i.e unique objects this time

async await return Task

This is a Task that is returning a Task of type String (C# anonymous function or in other word a delegation is used 'Func')

    public static async Task<string> MyTask()
    {
        //C# anonymous AsyncTask
        return await Task.FromResult<string>(((Func<string>)(() =>
        {
            // your code here
            return  "string result here";

        }))());
    }

Why is php not running?

When installing Apache and PHP under Ubuntu 14.04, I needed to specifically enable php configs by issuing a2enmod php5-cgi

Slide right to left?

Another worth mentioning library is animate.css. It works great with jQuery, and you can do a lot of interesting animations simply by toggling CSS classs.

Like..

$("#slide").toggle().toggleClass('animated bounceInLeft');

Reimport a module in python while interactive

This should work:

reload(my.module)

From the Python docs

Reload a previously imported module. The argument must be a module object, so it must have been successfully imported before. This is useful if you have edited the module source file using an external editor and want to try out the new version without leaving the Python interpreter.

If running Python 3.4 and up, do import importlib, then do importlib.reload(nameOfModule).

Don't forget the caveats of using this method:

  • When a module is reloaded, its dictionary (containing the module’s global variables) is retained. Redefinitions of names will override the old definitions, so this is generally not a problem, but if the new version of a module does not define a name that was defined by the old version, the old definition is not removed.

  • If a module imports objects from another module using from ... import ..., calling reload() for the other module does not redefine the objects imported from it — one way around this is to re-execute the from statement, another is to use import and qualified names (module.*name*) instead.

  • If a module instantiates instances of a class, reloading the module that defines the class does not affect the method definitions of the instances — they continue to use the old class definition. The same is true for derived classes.

Java reading a file into an ArrayList?

//CS124 HW6 Wikipedia Relation Extraction
//Alan Joyce (ajoyce)
public List<String> addWives(String fileName) {
    List<String> wives = new ArrayList<String>();
    try {
        BufferedReader input = new BufferedReader(new FileReader(fileName));
        // for each line
        for(String line = input.readLine(); line != null; line = input.readLine()) {
            wives.add(line);
        }
        input.close();
    } catch(IOException e) {
        e.printStackTrace();
        System.exit(1);
        return null;
    }
    return wives;
}

How to place the cursor (auto focus) in text box when a page gets loaded without javascript support?

An expansion for those who did a bit of fiddling around like I did.

The following work (from W3):

<input type="text" autofocus />
<input type="text" autofocus="" />
<input type="text" autofocus="autofocus" />
<input type="text" autofocus="AuToFoCuS" />

It is important to note that this does not work in CSS though. I.e. you can't use:

.first-input {
    autofocus:"autofocus"
}

At least it didn't work for me...

Can regular expressions be used to match nested patterns?

Yes, if it is .NET RegEx-engine. .Net engine supports finite state machine supplied with an external stack. see details

Cannot attach the file *.mdf as database

I had the same error while following the tutorial on "Getting Started with ASP.NET MVC 5 | Microsoft Docs". I was on Visual Studio 2015. I opened View-> SQL Server Object Explorer and deleted the database named after the tutorial, then it could work. see Delete .mdf file from app_data causes exception cannot attach the file as database

What's the difference between lists and tuples?

Lists are for looping, tuples are for structures i.e. "%s %s" %tuple.

Lists are usually homogeneous, tuples are usually heterogeneous.

Lists are for variable length, tuples are for fixed length.

How to read numbers from file in Python?

To make the answer simple here is a program that reads integers from the file and sorting them

f = open("input.txt", 'r')

nums = f.readlines()
nums = [int(i) for i in nums]

After reading each line of the file converting each string to a digit

nums.sort()

Sorting the numbers

f.close()

f = open("input.txt", 'w')
for num in nums:
    f.write("%d\n" %num)

f.close()

Writing them back As easy as that, Hope this helps

How to initialize log4j properly?

If you are having this error on Intellij IDEA even after adding the log4j.properties or log4j.xml file on your resources test folder, maybe the Intellij IDEA is not aware yet about the existence of the file.

So, after add the file, right click on the file and choose Recompile log4j.xml.

LIMIT 10..20 in SQL Server

A good way is to create a procedure:

create proc pagination (@startfrom int ,@endto int) as
SELECT * FROM ( 
  SELECT *, ROW_NUMBER() OVER (ORDER BY name desc) as row FROM sys.databases 
 ) a WHERE a.row > @startfrom and a.row <= @endto

just like limit 0,2 /////////////// execute pagination 0,4

error code 1292 incorrect date value mysql

Insert date in the following format yyyy-MM-dd example,

INSERT INTO `PROGETTO`.`ALBERGO`(`ID`, `nome`, `viale`, `num_civico`, `data_apertura`, `data_chiusura`, `orario_apertura`, `orario_chiusura`, `posti_liberi`, `costo_intero`, `costo_ridotto`, `stelle`, `telefono`, `mail`, `web`, `Nome-paese`, `Comune`) 
VALUES(0, 'Hotel Centrale', 'Via Passo Rolle', '74', '2012-05-01', '2012-09-31', '06:30', '24:00', 80, 50, 25, 3, '43968083', '[email protected]', 'http://www.hcentrale.it/', 'Trento', 'TN')

How to read text files with ANSI encoding and non-English letters?

using (StreamWriter writer = new StreamWriter(File.Open(@"E:\Sample.txt", FileMode.Append), Encoding.GetEncoding(1250)))  ////File.Create(path)
        {
            writer.Write("Sample Text");
        }

python global name 'self' is not defined

self is the self-reference in a Class. Your code is not in a class, you only have functions defined. You have to wrap your methods in a class, like below. To use the method main(), you first have to instantiate an object of your class and call the function on the object.

Further, your function setavalue should be in __init___, the method called when instantiating an object. The next step you probably should look at is supplying the name as an argument to init, so you can create arbitrarily named objects of the Name class ;)

class Name:
    def __init__(self):
        self.myname = "harry"

    def printaname(self):
        print "Name", self.myname     

    def main(self):
        self.printaname()

if __name__ == "__main__":
    objName = Name()
    objName.main() 

Have a look at the Classes chapter of the Python tutorial an at Dive into Python for further references.

Bootstrap - floating navbar button right

Create a separate ul.nav for just that list item and float that ul right.

jsFiddle

PowerShell equivalent to grep -f

but select-String doesn't seem to have this option.

Correct. PowerShell is not a clone of *nix shells' toolset.

However it is not hard to build something like it yourself:

$regexes = Get-Content RegexFile.txt | 
           Foreach-Object { new-object System.Text.RegularExpressions.Regex $_ }

$fileList | Get-Content | Where-Object {
  foreach ($r in $regexes) {
    if ($r.IsMatch($_)) {
      $true
      break
    }
  }
  $false
}

Parsing command-line arguments in C

argstream is quite similar to boost.program_option: it permits to bind variables to options, etc. However it does not handle options stored in a configuration file.

Message 'src refspec master does not match any' when pushing commits in Git

Check your commit title, because if you forget the git commit -m "xxxx" command, you get the same problem

git commit -m "initial commit"

How to run multiple SQL commands in a single SQL connection?

I have not tested , but what the main idea is: put semicolon on each query.

SqlConnection connection = new SqlConnection();
SqlCommand command = new SqlCommand();
connection.ConnectionString = connectionString; // put your connection string
command.CommandText = @"
     update table
     set somecol = somevalue;
     insert into someTable values(1,'test');";
command.CommandType = CommandType.Text;
command.Connection = connection;

try
{
    connection.Open();
}
finally
{
    command.Dispose();
    connection.Dispose();
}

Update: you can follow Is it possible to have multiple SQL instructions in a ADO.NET Command.CommandText property? too

How to execute .sql file using powershell?

Quoting from Import the SQLPS Module on MSDN,

The recommended way to manage SQL Server from PowerShell is to import the sqlps module into a Windows PowerShell 2.0 environment.

So, yes, you could use the Add-PSSnapin approach detailed by Christian, but it is also useful to appreciate the recommended sqlps module approach.

The simplest case assumes you have SQL Server 2012: sqlps is included in the installation so you simply load the module like any other (typically in your profile) via Import-Module sqlps. You can check if the module is available on your system with Get-Module -ListAvailable.

If you do not have SQL Server 2012, then all you need do is download the sqlps module into your modules directory so Get-Module/Import-Module will find it. Curiously, Microsoft does not make this module available for download! However, Chad Miller has kindly packaged up the requisite pieces and provided this module download. Unzip it under your ...Documents\WindowsPowerShell\Modules directory and proceed with the import.

It is interesting to note that the module approach and the snapin approach are not identical. If you load the snapins then run Get-PSSnapin (without the -Registered parameter, to show only what you have loaded) you will see the SQL snapins. If, on the other hand, you load the sqlps module Get-PSSnapin will not show the snapins loaded, so the various blog entries that test for the Invoke-Sqlcmd cmdlet by only examining snapins could be giving a false negative result.

2012.10.06 Update

For the complete story on the sqlps module vs. the sqlps mini-shell vs. SQL Server snap-ins, take a look at my two-part mini-series Practical PowerShell for SQL Server Developers and DBAs recently published on Simple-Talk.com where I have, according to one reader's comment, successfully "de-confused" the issue. :-)

Scale image to fit a bounding box

This helped me:

.img-class {
  width: <img width>;
  height: <img height>;
  content: url('/path/to/img.png');
}

Then on the element (you can use javascript or media queries to add responsiveness):

<div class='img-class' style='transform: scale(X);'></div>

Hope this helps!

Protecting cells in Excel but allow these to be modified by VBA script

A basic but simple to understand answer:

Sub Example()
    ActiveSheet.Unprotect
    Program logic...
    ActiveSheet.Protect
End Sub

Websocket connections with Postman

I've run into this issue often enough that I finally created my own barebones GUI for testing websockets. It's called Socket Wrench, it supports

  • multiple concurrent connections to servers (with all responses and connections displayed in the same view),
  • comprehensive message history to enable easy re-use of messages, and
  • custom headers for the initial connection request.

It's available for Mac OS X, Windows and Linux and you can get it from here.

Java balanced expressions check {[()]}

**// balanced parentheses problem (By fabboys)**
#include <iostream>
#include <string.h>

using namespace std;

class Stack{

char *arr;
int size;
int top;

public:

Stack(int s)
{
  size = s;
  arr = new char[size];
  top = -1;
}

bool isEmpty()
{
  if(top == -1)
    return true;
 else
    return false;
 }

 bool isFull()
 {
  if(top == size-1)
    return true;
 else
    return false;
 }


 void push(char n)
 {
 if(isFull() == false)
 {
     top++;
     arr[top] = n;
 }
}

char pop()
{
 if(isEmpty() == false)
 {
     char x = arr[top];
     top--;
     return x;
 }
 else
    return -1;
}

char Top()
{
 if(isEmpty() == false)
 {
    return arr[top];
 }
 else
    return -1;
}
Stack{
 delete []arr;
 }

};

int main()
{
int size=0;


string LineCode;
cout<<"Enter a String : ";
  cin >> LineCode;



    size = LineCode.length();

    Stack s1(size);


    char compare;

    for(int i=0;i<=size;i++)
    {

 if(LineCode[i]=='(' || LineCode[i] == '{' || LineCode[i] =='[')

 s1.push(LineCode[i]);

 else if(LineCode[i]==']')
 {
     if(s1.isEmpty()==false){
                    compare =  s1.pop();
                if(compare == 91){}
                    else
                        {
                        cout<<" Error Founded";
                            return 0;}
        }
            else
            {
               cout<<" Error Founded";
               return 0;
            }

 } else if(LineCode[i] == ')')
 {
     if(s1.isEmpty() == false)
     {
         compare = s1.pop();
         if(compare == 40){}
         else{
            cout<<" Error Founded";
                            return 0;
         }
     }else
     {
        cout<<"Error Founded";
               return 0;
     }
 }else if(LineCode[i] == '}')
 {
       if(s1.isEmpty() == false)
     {
         compare = s1.pop();
         if(compare == 123){}
         else{
            cout<<" Error Founded";
                            return 0;
         }
     }else
     {
        cout<<" Error Founded";
               return 0;
     }


 }
}

if(s1.isEmpty()==true)
{
    cout<<"No Error in Program:\n";
}
else
{
     cout<<" Error Founded";
}

 return 0;
}

How comment a JSP expression?

your <%= //map.size() %> doesnt simply work because it should have been

<% //= map.size() %>

Conversion from List<T> to array T[]

List<int> list = new List<int>();
int[] intList = list.ToArray();

is it your solution?

Converting a string to int in Groovy

Several ways to do it, this one's my favorite:

def number = '123' as int

How to use ? : if statements with Razor and inline code blocks

This should work:

<span class="vote-up@(puzzle.UserVote == VoteType.Up ? "-selected" : "")">Vote Up</span>

How to retrieve Jenkins build parameters using the Groovy API?

Get all of the parameters:

System.getenv().each{
  println it
}

Or more sophisticated:

def myvariables = getBinding().getVariables()
for (v in myvariables) {
   echo "${v} " + myvariables.get(v)
}

You will need to disable "Use Groovy Sandbox" for both.

What does operator "dot" (.) mean?

The dot itself is not an operator, .^ is.

The .^ is a pointwise¹ (i.e. element-wise) power, as .* is the pointwise product.

.^ Array power. A.^B is the matrix with elements A(i,j) to the B(i,j) power. The sizes of A and B must be the same or be compatible.

C.f.

¹) Hence the dot.

How can I convert a DateTime to the number of seconds since 1970?

If the rest of your system is OK with DateTimeOffset instead of DateTime, there's a really convenient feature:

long unixSeconds = DateTimeOffset.Now.ToUnixTimeSeconds();

Using global variables between files?

See Python's document on sharing global variables across modules:

The canonical way to share information across modules within a single program is to create a special module (often called config or cfg).

config.py:

x = 0   # Default value of the 'x' configuration setting

Import the config module in all modules of your application; the module then becomes available as a global name.

main.py:

import config
print (config.x)

or

from config import x
print (x)

In general, don’t use from modulename import *. Doing so clutters the importer’s namespace, and makes it much harder for linters to detect undefined names.

How to get rid of punctuation using NLTK tokenizer?

You can do it in one line without nltk (python 3.x).

import string
string_text= string_text.translate(str.maketrans('','',string.punctuation))

How to make lists contain only distinct element in Python?

If all elements of the list may be used as dictionary keys (i.e. they are all hashable) this is often faster. Python Programming FAQ

d = {}
for x in mylist:
    d[x] = 1
mylist = list(d.keys())

How can I check which version of Angular I'm using?

enter image description hereIn the new version of angular cli the [ng -v] will not work.yoy have to type [ng version].

FirstOrDefault returns NullReferenceException if no match is found

Simply use the question mark trick for null checks:

string displayName = Dictionary.FirstOrDefault(x => x.Value.ID == long.Parse(options.ID))?.Value.DisplayName ?? "DEFINE A DEFAULT DISPLAY NAME HERE";

Control cannot fall through from one case label

You need to break;, throw, goto, or return from each of your case labels. In a loop you may also continue.

        switch (searchType)
        {
            case "SearchBooks":
                Selenium.Type("//*[@id='SearchBooks_TextInput']", searchText);
                Selenium.Click("//*[@id='SearchBooks_SearchBtn']");
                break;

            case "SearchAuthors":
                Selenium.Type("//*[@id='SearchAuthors_TextInput']", searchText);
                Selenium.Click("//*[@id='SearchAuthors_SearchBtn']");
                break;
        }

The only time this isn't true is when the case labels are stacked like this:

 case "SearchBooks": // no code inbetween case labels.
 case "SearchAuthors":
    // handle both of these cases the same way.
    break;

Replace given value in vector

A simple way to do this is using ifelse, which is vectorized. If the condition is satisfied, we use a replacement value, otherwise we use the original value.

v <- c(3, 2, 1, 0, 4, 0)
ifelse(v == 0, 1, v)

We can avoid a named variable by using a pipe.

c(3, 2, 1, 0, 4, 0) %>% ifelse(. == 0, 1, .)

A common task is to do multiple replacements. Instead of nested ifelse statements, we can use case_when from dplyr:

case_when(v == 0 ~ 1,
          v == 1 ~ 2,
          TRUE ~ v)

Old answer:

For factor or character vectors, we can use revalue from plyr:

> revalue(c("a", "b", "c"), c("b" = "B"))
[1] "a" "B" "c"

This has the advantage of only specifying the input vector once, so we can use a pipe like

x %>% revalue(c("b" = "B"))

App not setup: This app is still in development mode

2020 UPDATE

Visit https://developers.facebook.com/apps/ and select your application.

Go to Settings -> Basic. Add a Contact Email and a Privacy Policy URL. The Privacy Policy URL should be a webpage where you have hosted the terms and conditions of your application and data used.

Toggle the button in the top of the screen, as seen below, in order to switch from Development to Live.

enter image description here

Java 8: merge lists with stream API

Alternative: Stream.concat()

Stream.concat(map.values().stream(), listContainer.lst.stream())
                             .collect(Collectors.toList()

How to change column datatype from character to numeric in PostgreSQL 8.4

Step 1: Add new column with integer or numeric as per your requirement

Step 2: Populate data from varchar column to numeric column

Step 3: drop varchar column

Step 4: change new numeric column name as per old varchar column

POST data to a URL in PHP

Your question is not particularly clear, but in case you want to send POST data to a url without using a form, you can use either fsockopen or curl.

Here's a pretty good walkthrough of both

Does Django scale?

Note that if you're expecting 100K users per day, that are active for hours at a time (meaning max of 20K+ concurrent users), you're going to need A LOT of servers. SO has ~15,000 registered users, and most of them are probably not active daily. While the bulk of traffic comes from unregistered users, I'm guessing that very few of them stay on the site more than a couple minutes (i.e. they follow google search results then leave).

For that volume, expect at least 30 servers ... which is still a rather heavy 1,000 concurrent users per server.

How to concatenate and minify multiple CSS and JavaScript files with Grunt.js (0.3.x)

You don't need to add the concat package, you can do this via cssmin like this:

cssmin : {
      options: {
            keepSpecialComments: 0
      },
      minify : {
            expand : true,
            cwd : '/library/css',
            src : ['*.css', '!*.min.css'],
            dest : '/library/css',
            ext : '.min.css'
      },
      combine : {
        files: {
            '/library/css/app.combined.min.css': ['/library/css/main.min.css', '/library/css/font-awesome.min.css']
        }
      }
    }

And for js, use uglify like this:

uglify: {
      my_target: {
        files: {
            '/library/js/app.combined.min.js' : ['/app.js', '/controllers/*.js']
        }
      }
    }

jQuery: Currency Format Number

Divide by 1000, and use .toFixed(3) to fix the number of decimal places.

var output = (input/1000).toFixed(3);

[EDIT]

The above solution only applies if the dot in the original question is for a decimal point. However the OP's comment below implies that it is intended as a thousands separator.

In this case, there isn't a single line solution (Javascript doesn't have it built in), but it can be achieved with a fairly short function.

A good example can be found here: http://www.mredkj.com/javascript/numberFormat.html#addcommas

Alternatively, a more complex string formatting function which mimics the printf() function from the C language can be found here: http://www.diveintojavascript.com/projects/javascript-sprintf

NotificationCompat.Builder deprecated in Android O

Notification notification = new Notification.Builder(MainActivity.this)
        .setContentTitle("New Message")
        .setContentText("You've received new messages.")
        .setSmallIcon(R.drawable.ic_notify_status)
        .setChannelId(CHANNEL_ID)
        .build();  

Right code will be :

Notification.Builder notification=new Notification.Builder(this)

with dependency 26.0.1 and new updated dependencies such as 28.0.0.

Some users use this code in the form of this :

Notification notification=new NotificationCompat.Builder(this)//this is also wrong code.

So Logic is that which Method you will declare or initilize then the same methode on Right side will be use for Allocation. if in Leftside of = you will use some method then the same method will be use in right side of = for Allocation with new.

Try this code...It will sure work

Google Maps API V3 : How show the direction from a point A to point B (Blue line)?

Use directions service of Google Maps API v3. It's basically the same as directions API, but nicely packed in Google Maps API which also provides convenient way to easily render the route on the map.

Information and examples about rendering the directions route on the map can be found in rendering directions section of Google Maps API v3 documentation.

Parse JSON String to JSON Object in C#.NET

Another choice besides JObject is System.Json.JsonValue for Weak-Typed JSON object.

It also has a JsonValue blob = JsonValue.Parse(json); you can use. The blob will most likely be of type JsonObject which is derived from JsonValue, but could be JsonArray. Check the blob.JsonType if you need to know.

And to answer you question, YES, you may replace json with the name of your actual variable that holds the JSON string. ;-D

There is a System.Json.dll you should add to your project References.

-Jesse

How to recover deleted rows from SQL server table?

It is possible using Apex Recovery Tool,i have successfully recovered my table rows which i accidentally deleted

if you download the trial version it will recover only 10th row

check here http://www.apexsql.com/sql_tools_log.aspx

How to force the browser to reload cached CSS and JavaScript files

Say you have a file available at:

/styles/screen.css

You can either append a query parameter with version information onto the URI, e.g.:

/styles/screen.css?v=1234

Or you can prepend version information, e.g.:

/v/1234/styles/screen.css

IMHO, the second method is better for CSS files, because they can refer to images using relative URLs which means that if you specify a background-image like so:

body {
    background-image: url('images/happy.gif');
}

Its URL will effectively be:

/v/1234/styles/images/happy.gif

This means that if you update the version number used, the server will treat this as a new resource and not use a cached version. If you base your version number on the Subversion, CVS, etc. revision this means that changes to images referenced in CSS files will be noticed. That isn't guaranteed with the first scheme, i.e. the URL images/happy.gif relative to /styles/screen.css?v=1235 is /styles/images/happy.gif which doesn't contain any version information.

I have implemented a caching solution using this technique with Java servlets and simply handle requests to /v/* with a servlet that delegates to the underlying resource (i.e. /styles/screen.css). In development mode I set caching headers that tell the client to always check the freshness of the resource with the server (this typically results in a 304 if you delegate to Tomcat's DefaultServlet and the .css, .js, etc. file hasn't changed) while in deployment mode I set headers that say "cache forever".

Visual Studio breakpoints not being hit

I struggled forever trying to fix this. Finally this is what did it for me.

Select Debug->Options->Debugging->General

Tick Enable .NET Framework source stepping.

(This may be all you need to do but if you are like me, you also have to do the ones stated below. The below solution will also fix errors where your project is loading old assemblies/.pdb files despite rebuilding and cleaning.)

Select Tools -> Options -> Projects and Solutions -> Build and Run,

Untick the checkbox of "Only Build startup projects and dependencies on Run",

Select Always Build from the "On Run, when project are out of date" dropdown.

How do I get only directories using Get-ChildItem?

Use

Get-ChildItem -dir #lists only directories
Get-ChildItem -file #lists only files

If you prefer aliases, use

ls -dir #lists only directories
ls -file #lists only files

or

dir -dir #lists only directories
dir -file #lists only files

To recurse subdirectories as well, add -r option.

ls -dir -r #lists only directories recursively
ls -file -r #lists only files recursively 

Tested on PowerShell 4.0, PowerShell 5.0 (Windows 10), PowerShell Core 6.0 (Windows 10, Mac, and Linux), and PowerShell 7.0 (Windows 10, Mac, and Linux).

Note: On PowerShell Core, symlinks are not followed when you specify the -r switch. To follow symlinks, specify the -FollowSymlink switch with -r.

Note 2: PowerShell is now cross-platform, since version 6.0. The cross-platform version was originally called PowerShell Core, but the the word "Core" has been dropped since PowerShell 7.0+.

Get-ChildItem documentation: https://docs.microsoft.com/en-us/powershell/module/microsoft.powershell.management/get-childitem

How to generate a Dockerfile from an image?

I somehow absolutely missed the actual command in the accepted answer, so here it is again, bit more visible in its own paragraph, to see how many people are like me

$ docker history --no-trunc <IMAGE_ID>

how do I get eclipse to use a different compiler version for Java?

First off, are you setting your desired JRE or your desired JDK?

Even if your Eclipse is set up properly, there might be a wacky project-specific setting somewhere. You can open up a context menu on a given Java project in the Project Explorer and select Properties > Java Compiler to check on that.

If none of that helps, leave a comment and I'll take another look.

AndroidStudio: Failed to sync Install build tools

I had the same problem, in my cases this happened because I changed the time on my computer to load .apk on google play. I spent a few hours to fix "this" problem until I remembered and changed the time back.

dpi value of default "large", "medium" and "small" text views android

See in the android sdk directory.

In \platforms\android-X\data\res\values\themes.xml:

    <item name="textAppearanceLarge">@android:style/TextAppearance.Large</item>
    <item name="textAppearanceMedium">@android:style/TextAppearance.Medium</item>
    <item name="textAppearanceSmall">@android:style/TextAppearance.Small</item>

In \platforms\android-X\data\res\values\styles.xml:

<style name="TextAppearance.Large">
    <item name="android:textSize">22sp</item>
</style>

<style name="TextAppearance.Medium">
    <item name="android:textSize">18sp</item>
</style>

<style name="TextAppearance.Small">
    <item name="android:textSize">14sp</item>
    <item name="android:textColor">?textColorSecondary</item>
</style>

TextAppearance.Large means style is inheriting from TextAppearance style, you have to trace it also if you want to see full definition of a style.

Link: http://developer.android.com/design/style/typography.html

How to check if an object is a list or tuple (but not string)?

Python 3 has this:

from typing import List

def isit(value):
    return isinstance(value, List)

isit([1, 2, 3])  # True
isit("test")  # False
isit({"Hello": "Mars"})  # False
isit((1, 2))  # False

So to check for both Lists and Tuples, it would be:

from typing import List, Tuple

def isit(value):
    return isinstance(value, List) or isinstance(value, Tuple)

Remove decimal values using SQL query

First of all, you tried to replace the entire 12.00 with '', which isn't going to give your desired results.

Second you are trying to do replace directly on a decimal. Replace must be performed on a string, so you have to CAST.

There are many ways to get your desired results, but this replace would have worked (assuming your column name is "height":

REPLACE(CAST(height as varchar(31)),'.00','')

EDIT:

This script works:

DECLARE @Height decimal(6,2);
SET @Height = 12.00;
SELECT @Height, REPLACE(CAST(@Height AS varchar(31)),'.00','');

correct PHP headers for pdf file download

Example 2 on w3schools shows what you are trying to achieve.

<?php
header("Content-type:application/pdf");

// It will be called downloaded.pdf
header("Content-Disposition:attachment;filename='downloaded.pdf'");

// The PDF source is in original.pdf
readfile("original.pdf");
?>

Also remember that,

It is important to notice that header() must be called before any actual output is sent (In PHP 4 and later, you can use output buffering to solve this problem)

How do you handle a form change in jQuery?

Extending Udi's answer, this only checks on form submission, not on every input change.

$(document).ready( function () {
  var form_data = $('#myform').serialize();
  $('#myform').submit(function () {
      if ( form_data == $(this).serialize() ) {
        alert('no change');
      } else {
        alert('change');
      }
   });
});

Connecting to Oracle Database through C#?

The next approach work to me with Visual Studio 2013 Update 4 1- From Solution Explorer right click on References then select add references 2- Assemblies > Framework > System.Data.OracleClient > OK and after that you free to add using System.Data.OracleClient in your application and deal with database like you do with Sql Server database except changing the prefix from Sql to Oracle as in SqlCommand become OracleCommand for example to link to Oracle XE

OracleConnection oraConnection = new OracleConnection(@"Data Source=XE; User ID=system; Password=*myPass*");
public void Open()
{
if (oraConnection.State != ConnectionState.Open)
{
oraConnection.Open();
}
}
public void Close()
{
if (oraConnection.State == ConnectionState.Open)
{
oraConnection.Close();
}}

and to execute some command like INSERT, UPDATE, or DELETE using stored procedure we can use the following method

public void ExecuteCMD(string storedProcedure, OracleParameter[] param)
{
OracleCommand oraCmd = new OracleCommand();
oraCmd,CommandType = CommandType.StoredProcedure;
oraCmd.CommandText = storedProcedure;
oraCmd.Connection = oraConnection;

if(param!=null)
{
oraCmd.Parameters.AddRange(param);
}
try
{
oraCmd.ExecuteNoneQuery();
}
catch (Exception)
{
MessageBox.Show("Sorry We've got Unknown Error","Connection Error",MessageBoxButtons.OK,MessageBoxIcon.Error);
}
}

How to insert an item at the beginning of an array in PHP?

Or you can use temporary array and then delete the real one if you want to change it while in cycle:

$array = array(0 => 'a', 1 => 'b', 2 => 'c');
$temp_array = $array[1];

unset($array[1]);
array_unshift($array , $temp_array);

the output will be:

array(0 => 'b', 1 => 'a', 2 => 'c')

and when are doing it while in cycle, you should clean $temp_array after appending item to array.

When is JavaScript synchronous?

Definition

The term "asynchronous" can be used in slightly different meanings, resulting in seemingly conflicting answers here, while they are actually not. Wikipedia on Asynchrony has this definition:

Asynchrony, in computer programming, refers to the occurrence of events independent of the main program flow and ways to deal with such events. These may be "outside" events such as the arrival of signals, or actions instigated by a program that take place concurrently with program execution, without the program blocking to wait for results.

non-JavaScript code can queue such "outside" events to some of JavaScript's event queues. But that is as far as it goes.

No Preemption

There is no external interruption of running JavaScript code in order to execute some other JavaScript code in your script. Pieces of JavaScript are executed one after the other, and the order is determined by the order of events in each event queue, and the priority of those queues.

For instance, you can be absolutely sure that no other JavaScript (in the same script) will ever execute while the following piece of code is executing:

let a = [1, 4, 15, 7, 2];
let sum = 0;
for (let i = 0; i < a.length; i++) {
    sum += a[i];
}

In other words, there is no preemption in JavaScript. Whatever may be in the event queues, the processing of those events will have to wait until such piece of code has ran to completion. The EcmaScript specification says in section 8.4 Jobs and Jobs Queues:

Execution of a Job can be initiated only when there is no running execution context and the execution context stack is empty.

Examples of Asynchrony

As others have already written, there are several situations where asynchrony comes into play in JavaScript, and it always involves an event queue, which can only result in JavaScript execution when there is no other JavaScript code executing:

  • setTimeout(): the agent (e.g. browser) will put an event in an event queue when the timeout has expired. The monitoring of the time and the placing of the event in the queue happens by non-JavaScript code, and so you could imagine this happens in parallel with the potential execution of some JavaScript code. But the callback provided to setTimeout can only execute when the currently executing JavaScript code has ran to completion and the appropriate event queue is being read.

  • fetch(): the agent will use OS functions to perform an HTTP request and monitor for any incoming response. Again, this non-JavaScript task may run in parallel with some JavaScript code that is still executing. But the promise resolution procedure, that will resolve the promise returned by fetch(), can only execute when the currently executing JavaScript has ran to completion.

  • requestAnimationFrame(): the browser's rendering engine (non-JavaScript) will place an event in the JavaScript queue when it is ready to perform a paint operation. When JavaScript event is processed the callback function is executed.

  • queueMicrotask(): immediately places an event in the microtask queue. The callback will be executed when the call stack is empty and that event is consumed.

There are many more examples, but all these functions are provided by the host environment, not by core EcmaScript. With core EcmaScript you can synchronously place an event in a Promise Job Queue with Promise.resolve().

Language Constructs

EcmaScript provides several language constructs to support the asynchrony pattern, such as yield, async, await. But let there be no mistake: no JavaScript code will be interrupted by an external event. The "interruption" that yield and await seem to provide is just a controlled, predefined way of returning from a function call and restoring its execution context later on, either by JS code (in the case of yield), or the event queue (in the case of await).

DOM event handling

When JavaScript code accesses the DOM API, this may in some cases make the DOM API trigger one or more synchronous notifications. And if your code has an event handler listening to that, it will be called.

This may come across as pre-emptive concurrency, but it is not: once your event handler(s) return(s), the DOM API will eventually also return, and the original JavaScript code will continue.

In other cases the DOM API will just dispatch an event in the appropriate event queue, and JavaScript will pick it up once the call stack has been emptied.

See synchronous and asynchronous events

setBackground vs setBackgroundDrawable (Android)

you could use setBackgroundResource() instead i.e. relativeLayout.setBackgroundResource(R.drawable.back);

this works for me.

How to tell if a string is not defined in a Bash shell script

~> if [ -z $FOO ]; then echo "EMPTY"; fi
EMPTY
~> FOO=""
~> if [ -z $FOO ]; then echo "EMPTY"; fi
EMPTY
~> FOO="a"
~> if [ -z $FOO ]; then echo "EMPTY"; fi
~> 

-z works for undefined variables too. To distinguish between an undefined and a defined you'd use the things listed here or, with clearer explanations, here.

Cleanest way is using expansion like in these examples. To get all your options check the Parameter Expansion section of the manual.

Alternate word:

~$ unset FOO
~$ if test ${FOO+defined}; then echo "DEFINED"; fi
~$ FOO=""
~$ if test ${FOO+defined}; then echo "DEFINED"; fi
DEFINED

Default value:

~$ FOO=""
~$ if test "${FOO-default value}" ; then echo "UNDEFINED"; fi
~$ unset FOO
~$ if test "${FOO-default value}" ; then echo "UNDEFINED"; fi
UNDEFINED

Of course you'd use one of these differently, putting the value you want instead of 'default value' and using the expansion directly, if appropriate.

How do you do block comments in YAML?

An alternative approach:

If

  • your YAML structure has well defined fields to be used by your app
  • AND you may freely add additional fields that won't mess up with your app

then

  • at any level you may add a new block text field named like "Description" or "Comment" or "Notes" or whatever

Example:

Instead of

# This comment
# is too long

use

Description: >
  This comment
  is too long

or

Comment: >
    This comment is also too long
    and newlines survive from parsing!

More advantages:

  1. If the comments become large and complex and have a repeating pattern, you may promote them from plain text blocks to objects
  2. Your app may -in the future- read or update those comments

How to grep and replace

Usually not with grep, but rather with sed -i 's/string_to_find/another_string/g' or perl -i.bak -pe 's/string_to_find/another_string/g'.

How can I align button in Center or right using IONIC framework?

Ultimately, we are trying to get to this.

<div style="display: flex; justify-content: center;">
    <button ion-button>Login</button>
</div>

SQL Stored Procedure set variables using SELECT

select @currentTerm = CurrentTerm, @termID = TermID, @endDate = EndDate
    from table1
    where IsCurrent = 1

Codeigniter how to create PDF

I've used dompdf with some success before. Although it can be a bit fussy about malformed HTML and there are still some CSS methods that aren't supported (e.g. css float does not work).

Download the package from github, and place it into a folder called dompdf in your application/thirdparty directory.

You can then create a helper with some functions to use the dompdf library, here is an example:

dompdf_helper.php :

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

function pdf_create($html, $filename='', $stream=TRUE) 
{
    include APPPATH.'thirdparty/dompdf/dompdf_config.inc.php';

    $dompdf = new DOMPDF();
    $dompdf->load_html($html);
    $dompdf->render();
    if ($stream) {
        $dompdf->stream($filename.".pdf", array("Attachment" => 0));
    } else {
        return $dompdf->output();
    }
}

You simply pass the pdf_create method your HTML as a string, the filename for the pdf file it will generate, and then an optional thirdparameter. The third parameter is a true/false flag to determine if it should save the file to your server before prompting the user to download it or not.

How to use patterns in a case statement?

I don't think you can use braces.

According to the Bash manual about case in Conditional Constructs.

Each pattern undergoes tilde expansion, parameter expansion, command substitution, and arithmetic expansion.

Nothing about Brace Expansion unfortunately.

So you'd have to do something like this:

case $1 in
    req*)
        ...
        ;;
    met*|meet*)
        ...
        ;;
    *)
        # You should have a default one too.
esac

How can I indent multiple lines in Xcode?

? + [ and ? + ] are the equivalents to shift+tab in Xcode.

How can I create a progress bar in Excel VBA?

Hi modified version of another post by Marecki. Has 4 styles

1. dots ....
2  10 to 1 count down
3. progress bar (default)
4. just percentage.

Before you ask why I didn't edit that post is I did and it got rejected was told to post a new answer.

Sub ShowProgress()

  Const x As Long = 150000
  Dim i&, PB$

  For i = 1 To x
  DoEvents
  UpdateProgress i, x
  Next i

  Application.StatusBar = ""
End Sub 'ShowProgress

Sub UpdateProgress(icurr As Long, imax As Long, Optional istyle As Integer = 3)
    Dim PB$
    PB = Format(icurr / imax, "00 %")
    If istyle = 1 Then ' text dots >>....    <<'
        Application.StatusBar = "Progress: " & PB & "  >>" & String(Val(PB), Chr(183)) & String(100 - Val(PB), Chr(32)) & "<<"
    ElseIf istyle = 2 Then ' 10 to 1 count down  (eight balls style)
        Application.StatusBar = "Progress: " & PB & "  " & ChrW$(10111 - Val(PB) / 11)
    ElseIf istyle = 3 Then ' solid progres bar (default)
        Application.StatusBar = "Progress: " & PB & "  " & String(100 - Val(PB), ChrW$(9608))
    Else ' just 00 %
        Application.StatusBar = "Progress: " & PB
    End If
End Sub

How do I remove the old history from a git repository?

I needed to read several answers and some other info to understand what I was doing.

1. Ignore everything older than a certain commit

The file .git/info/grafts can define fake parents for a commit. A line with just a commit id, says that the commit doesn't have a parent. If we wanted to say that we care only about the last 2000 commits, we can type:

git rev-parse HEAD~2000 > .git/info/grafts

git rev-parse gives us the commit id of the 2000th parent of the current commit. The above command will overwrite the grafts file if present. Check if it's there first.

2. Rewrite the Git history (optional)

If you want to make this grafted fake parent a real one, then run:

git filter-branch -- --all

It will change all commit ids. Every copy of this repository needs to be updated forcefully.

3. Clean up disk space

I didn't done step 2, because I wanted my copy to stay compatible with the upstream. I just wanted to save some disk space. In order to forget all the old commits:

git prune
git gc

Alternative: shallow copies

If you have a shallow copy of another repository and just want to save some disk space, you can update .git/shallow. But be careful that nothing is pointing at a commit from before. So you could run something like this:

git fetch --prune
git rev-parse HEAD~2000 > .git/shallow
git prune
git gc

The entry in shallow works like a graft. But be careful not to use grafts and shallow at the same time. At least, don't have the same entries in there, it will fail.

If you still have some old references (tags, branches, remote heads) that point to older commits, they won't be cleaned up and you won't save more disk space.

How to check whether an object is a date?

This is a pretty simple approach and doesn't experience a lot of the edge cases in the existing answers.

// Invalid Date.getTime() will produce NaN
if (date instanceof Date && date.getTime()) {
    console.log("is date!");
}

It won't fire with other objects like numbers, makes sure the value is actually a Date (rather than an object that looks like one), and it avoids Invalid Dates.

C++ Passing Pointer to Function (Howto) + C++ Pointer Manipulation

To pass a pointer to an int it should be void Fun(int* pointer).

Passing a reference to an int would look like this...

void Fun(int& ref) {
   ref = 10;
}

int main() {
   int test = 5;
   cout << test << endl;  // prints 5

   Fun(test);
   cout << test << endl;  // prints 10 because Fun modified the value

   return 1;
}

jQuery UI Dialog - missing close icon

I got stuck with the same problem and after read and try all the suggestions above I just tried to replace manually this image (which you can find it here) in the CSS after downloaded it and saved in the images folder on my app and voilá, problem solved!

here is the CSS:

.ui-state-default .ui-icon {
        background-image: url("../img/ui-icons_888888_256x240.png");
}

Is it fine to have foreign key as primary key?

Short answer: DEPENDS.... In this particular case, it might be fine. However, experts will recommend against it just about every time; including your case.

Why?

Keys are seldomly unique in tables when they are foreign (originated in another table) to the table in question. For example, an item ID might be unique in an ITEMS table, but not in an ORDERS table, since the same type of item will most likely exist in another order. Likewise, order IDs might be unique (might) in the ORDERS table, but not in some other table like ORDER_DETAILS where an order with multiple line items can exist and to query against a particular item in a particular order, you need the concatenation of two FK (order_id and item_id) as the PK for this table.

I am not DB expert, but if you can justify logically to have an auto-generated value as your PK, I would do that. If this is not practical, then a concatenation of two (or maybe more) FK could serve as your PK. BUT, I cannot think of any case where a single FK value can be justified as the PK.

Android Service Stops When App Is Closed

Using the same process for the service and the activity and START_STICKY or START_REDELIVER_INTENT in the service is the only way to be able to restart the service when the application restarts, which happens when the user closes the application for example, but also when the system decides to close it for optimisations reasons. You CAN NOT have a service that will run permanently without any interruption. This is by design, smartphones are not made to run continuous processes for long period of time. This is due to the fact that battery life is the highest priority. You need to design your service so it handles being stopped at any point.

Convert String to System.IO.Stream

System.IO.MemoryStream mStream = new System.IO.MemoryStream(System.Text.Encoding.UTF8.GetBytes( contents));

Using the "animated circle" in an ImageView while loading stuff

You can use this code from firebase github samples ..

You don't need to edit in layout files ... just make a new class "BaseActivity"

package com.example;

import android.app.ProgressDialog;
import android.support.annotation.VisibleForTesting;
import android.support.v7.app.AppCompatActivity;


public class BaseActivity extends AppCompatActivity {

    @VisibleForTesting
    public ProgressDialog mProgressDialog;

    public void showProgressDialog() {
        if (mProgressDialog == null) {
            mProgressDialog = new ProgressDialog(this);
            mProgressDialog.setMessage("Loading ...");
            mProgressDialog.setIndeterminate(true);
        }

        mProgressDialog.show();
    }


    public void hideProgressDialog() {
        if (mProgressDialog != null && mProgressDialog.isShowing()) {
            mProgressDialog.dismiss();
        }
    }

    @Override
    public void onStop() {
        super.onStop();
        hideProgressDialog();
    }

}

In your Activity that you want to use the progress dialog ..

public class MyActivity extends BaseActivity

Before/After the function that take time

showProgressDialog();
.... my code that take some time
showProgressDialog();

JDBC connection to MSSQL server in windows authentication mode

For the current MS SQL JDBC driver (6.4.0) tested under Windows 7 from within DataGrip:

  1. as per documentation on authenticationScheme use fully qualified domain name as host e.g. server.your.domain not just server; the documentation also mentions the possibility to specify serverSpn=MSSQLSvc/fqdn:port@REALM, but I can not provide you with details on how to use this. When specifying a fqdn as host the spn is auto-generated.
  2. set authenticationScheme=JavaKerberos
  3. set integratedSecurity=true
  4. use your unqualified user-name (and password) to log in

As this is using JavaKerberos I would appreciate feedback on whether or not this works from outside Windows. I believe that no .dll is needed, but as I used DataGrip to create the connection I am uncertain; I would also appreciate Feedback on this!

What is the cause for "angular is not defined"

You have to put your script tag after the one that references Angular. Move it out of the head:

<script type="text/javascript" src="angular.min.js"></script>
<script type="text/javascript" src="main.js"></script>

The way you've set it up now, your script runs before Angular is loaded on the page.

An App ID with Identifier '' is not available. Please enter a different string

Me also got the same issue.

In my case i already registerd with my free account. We can't delete that app bundle id from our free account.

So i changed bundle id not app name and again i tried it's working.

Converting NSString to NSDate (and back again)

NSString to NSDate or NSDate to NSString

//This method is used to get NSDate from string 
//Pass the date formate ex-"dd-MM-yyyy hh:mm a"
+ (NSDate*)getDateFromString:(NSString *)dateString withFormate:(NSString *)formate  {

    // Converted date from date string
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    [dateFormatter setDateFormat:formate];
    NSDate *convertedDate         = [dateFormatter dateFromString:dateString];
    return convertedDate;
}

//This method is used to get the NSString for NSDate
//Pass the date formate ex-"dd-MM-yyyy hh:mm a"
+ (NSString *)getDateStringFromDate:(NSDate *)date withFormate:(NSString *)formate {

    // Converted date from date string
    NSDateFormatter *dateFormatter = [[NSDateFormatter alloc] init];
    //[dateFormatter setLocale:[[NSLocale alloc] initWithLocaleIdentifier:@"en_US"]];
    [dateFormatter setDateFormat:formate];
    NSString *convertedDate         = [dateFormatter stringFromDate:date];
    return convertedDate;
}

java.lang.ClassNotFoundException: com.mysql.jdbc.Driver in Eclipse

It seems the mysql connectivity library is not included in the project. Solve the problem following one of the proposed solutions:

  • MAVEN PROJECTS SOLUTION

Add the mysql-connector dependency to the pom.xml project file:

<dependency>
    <groupId>mysql</groupId>
    <artifactId>mysql-connector-java</artifactId>
    <version>5.1.39</version>
</dependency>

Here you are all the versions: https://mvnrepository.com/artifact/mysql/mysql-connector-java

  • ALL PROJECTS SOLUTION

Add the jar library manually to the project.

Right Click the project -- > build path -- > configure build path

In Libraries Tab press Add External Jar and Select your jar.

You can find zip for mysql-connector here

  • Explanation:

When building the project, java throws you an exception because a file (the com.mysql.jdbc.Driver class) from the mysql connectivity library is not found. The solution is adding the library to the project, and java will find the com.mysql.jdbc.Driver

How to get error information when HttpWebRequest.GetResponse() fails

You can also use this library which wraps HttpWebRequest and Response into simple methods that return objects based on the results. It uses some of the techniques described in these answers and has plenty of code inspired by answers from this and similar threads. It automatically catches any exceptions, seeks to abstract as much boiler plate code needed to make these web requests as possible, and automatically deserializes the response object.

An example of what your code would look like using this wrapper is as simple as

    var response = httpClient.Get<SomeResponseObject>(request);
    
    if(response.StatusCode == HttpStatusCode.OK)
    {
        //do something with the response
        console.Writeline(response.Body.Id); //where the body param matches the object you pass in as an anonymous type.  
    }else {
         //do something with the error
         console.Writelint(string.Format("{0}: {1}", response.StatusCode.ToString(), response.ErrorMessage);

    }

Full disclosure This library is a free open source wrapper library, and I am the author of said library. I make no money off of this but have found it immensely useful over the years and am sure anyone who is still using the HttpWebRequest / HttpWebResponse classes will too.

It is not a silver bullet but supports get, post, delete with both async and non-async for get and post as well as JSON or XML requests and responses. It is being actively maintained as of 6/21/2020

How do I check out a specific version of a submodule using 'git submodule'?

Step 1: Add the submodule

   git submodule add git://some_repository.git some_repository

Step 2: Fix the submodule to a particular commit

By default the new submodule will be tracking HEAD of the master branch, but it will NOT be updated as you update your primary repository. In order to change the submodule to track a particular commit or different branch, change directory to the submodule folder and switch branches just like you would in a normal repository.

   git checkout -b some_branch origin/some_branch

Now the submodule is fixed on the development branch instead of HEAD of master.

From Two Guys Arguing — Tie Git Submodules to a Particular Commit or Branch .

How to use a WSDL file to create a WCF service (not make a call)

Use svcutil.exe with the /sc switch to generate the WCF contracts. This will create a code file that you can add to your project. It will contain all interfaces and data types you need to create your service. Change the output location using the /o switch, or you can find the file in the folder where you ran svcutil.exe. The default language is C# but I think (I've never tried it) you should be able to change this using /l:vb.

svcutil /sc "WSDL file path"

If your WSDL has any supporting XSD files pass those in as arguments after the WSDL.

svcutil /sc "WSDL file path" "XSD 1 file path" "XSD 2 file path" ... "XSD n file path"

Then create a new class that is your service and implement the contract interface you just created.

MySQL Trigger: Delete From Table AFTER DELETE

Why not set ON CASCADE DELETE on Foreign Key patron_info.pid?

Format an Integer using Java String Format

String.format("%03d", 1)  // => "001"
//              ¦¦¦   +-- print the number one
//              ¦¦+------ ... as a decimal integer
//              ¦+------- ... minimum of 3 characters wide
//              +-------- ... pad with zeroes instead of spaces

See java.util.Formatter for more information.

What key in windows registry disables IE connection parameter "Automatically Detect Settings"?

I can confirm this works. I exported the reg file after I had made the adjustments and then put it in a logon script like this:

REM ------ IE Auto Detect Settings FIX ------------------
REG IMPORT \\mydomain.local\netlogon\IE-Autofix.reg 2>NUL

Vertical align middle with Bootstrap responsive grid

Add !important rule to display: table of your .v-center class.

.v-center {
    display:table !important;
    border:2px solid gray;
    height:300px;
}

Your display property is being overridden by bootstrap to display: block.

Example

How to use .htaccess in WAMP Server?

click: WAMP icon->Apache->Apache modules->chose rewrite_module

and do restart for all services.

How to compile makefile using MinGW?

First check if mingw32-make is installed on your system. Use mingw32-make.exe command in windows terminal or cmd to check, else install the package mingw32-make-bin.

then go to bin directory default ( C:\MinGW\bin) create new file make.bat

@echo off
"%~dp0mingw32-make.exe" %*

add the above content and save it

set the env variable in powershell

$Env:CC="gcc"

then compile the file

make hello

where hello.c is the name of source code

How to find all the dependencies of a table in sql server

Besides the methods described in other answers (sp_depends system stored procedure, SQL Server dynamic management functions) you can also view dependencies between SQL Server objects - from SSMS.

You can use the View Dependencies option from SSMS. From the Object Explorer pane, right click on the object and from the context menu, select the View Dependencies option

I myself prefer a 3rd party dependency viewer called ApexSQL Search. It is a free add-in, which integrates into SSMS and Visual Studio for SQL object and data text search, extended property management, safe object rename, and relationship visualization.

Changing Locale within the app itself

If you want to effect on the menu options for changing the locale immediately.You have to do like this.

//onCreate method calls only once when menu is called first time.
public boolean onCreateOptionsMenu(Menu menu) {
    super.onCreateOptionsMenu(menu);
    //1.Here you can add your  locale settings . 
    //2.Your menu declaration.
}
//This method is called when your menu is opend to again....
@Override
public boolean onMenuOpened(int featureId, Menu menu) {
    menu.clear();
    onCreateOptionsMenu(menu);
    return super.onMenuOpened(featureId, menu);
}

How to create named and latest tag in Docker?

Once you have your image, you can use

$ docker tag <image> <newName>/<repoName>:<tagName>
  1. Build and tag the image with creack/node:latest

    $ ID=$(docker build -q -t creack/node .)
    
  2. Add a new tag

    $ docker tag $ID creack/node:0.10.24
    
  3. You can use this and skip the -t part from build

    $ docker tag $ID creack/node:latest
    

Exception thrown inside catch block - will it be caught again?

No, since the catches all refer to the same try block, so throwing from within a catch block would be caught by an enclosing try block (probably in the method that called this one)

Uploading both data and files in one form using Ajax?

I was having this same issue in ASP.Net MVC with HttpPostedFilebase and instead of using form on Submit I needed to use button on click where I needed to do some stuff and then if all OK the submit form so here is how I got it working

$(".submitbtn").on("click", function(e) {

    var form = $("#Form");

    // you can't pass Jquery form it has to be javascript form object
    var formData = new FormData(form[0]);

    //if you only need to upload files then 
    //Grab the File upload control and append each file manually to FormData
    //var files = form.find("#fileupload")[0].files;

    //$.each(files, function() {
    //  var file = $(this);
    //  formData.append(file[0].name, file[0]);
    //});

    if ($(form).valid()) {
        $.ajax({
            type: "POST",
            url: $(form).prop("action"),
            //dataType: 'json', //not sure but works for me without this
            data: formData,
            contentType: false, //this is requireded please see answers above
            processData: false, //this is requireded please see answers above
            //cache: false, //not sure but works for me without this
            error   : ErrorHandler,
            success : successHandler
        });
    }
});

this will than correctly populate your MVC model, please make sure in your Model, The Property for HttpPostedFileBase[] has the same name as the Name of the input control in html i.e.

<input id="fileupload" type="file" name="UploadedFiles" multiple>

public class MyViewModel
{
    public HttpPostedFileBase[] UploadedFiles { get; set; }
}

Counter increment in Bash loop not working

minimalist

counter=0
((counter++))
echo $counter

Is there a mechanism to loop x times in ES6 (ECMAScript 6) without mutable variables?

Advantages of this solution

  • Simplest to read / use (imo)
  • Return value can be used as a sum, or just ignored
  • Plain es6 version, also link to TypeScript version of the code

Disadvantages - Mutation. Being internal only I don't care, maybe some others will not either.

Examples and Code

times(5, 3)                       // 15    (3+3+3+3+3)

times(5, (i) => Math.pow(2,i) )   // 31    (1+2+4+8+16)

times(5, '<br/>')                 // <br/><br/><br/><br/><br/>

times(3, (i, count) => {          // name[0], name[1], name[2]
    let n = 'name[' + i + ']'
    if (i < count-1)
        n += ', '
    return n
})

function times(count, callbackOrScalar) {
    let type = typeof callbackOrScalar
    let sum
    if (type === 'number') sum = 0
    else if (type === 'string') sum = ''

    for (let j = 0; j < count; j++) {
        if (type === 'function') {
            const callback = callbackOrScalar
            const result = callback(j, count)
            if (typeof result === 'number' || typeof result === 'string')
                sum = sum === undefined ? result : sum + result
        }
        else if (type === 'number' || type === 'string') {
            const scalar = callbackOrScalar
            sum = sum === undefined ? scalar : sum + scalar
        }
    }
    return sum
}

TypeScipt version
https://codepen.io/whitneyland/pen/aVjaaE?editors=0011

Installing SciPy and NumPy using pip

What operating system is this? The answer might depend on the OS involved. However, it looks like you need to find this BLAS library and install it. It doesn't seem to be in PIP (you'll have to do it by hand thus), but if you install it, it ought let you progress your SciPy install.

How create table only using <div> tag and Css

In building a custom set of layout tags, I found another answer to this problem. Provided here is the custom set of tags and their CSS classes.

HTML

<layout-table>
   <layout-header> 
       <layout-column> 1 a</layout-column>
       <layout-column>  </layout-column>
       <layout-column> 3 </layout-column>
       <layout-column> 4 </layout-column>
   </layout-header>

   <layout-row> 
       <layout-column> a </layout-column>
       <layout-column> a 1</layout-column>
       <layout-column> a </layout-column>
       <layout-column> a </layout-column>
   </layout-row>

   <layout-footer> 
       <layout-column> 1 </layout-column>
       <layout-column>  </layout-column>
       <layout-column> 3 b</layout-column>
       <layout-column> 4 </layout-column>
   </layout-footer>
</layout-table>

CSS

layout-table
{
    display : table;
    clear : both;
    table-layout : fixed;
    width : 100%;
}

layout-table:unresolved
{
    color : red;
    border: 1px blue solid;
    empty-cells : show;
}

layout-header, layout-footer, layout-row 
{
    display : table-row;
    clear : both;   
    empty-cells : show;
    width : 100%;
}

layout-column 
{ 
    display : table-column;
    float : left;
    width : 25%;
    min-width : 25%;
    empty-cells : show;
    box-sizing: border-box;
    /* border: 1px solid white; */
    padding : 1px 1px 1px 1px;
}

layout-row:nth-child(even)
{ 
    background-color : lightblue;
}

layout-row:hover 
{ background-color: #f5f5f5 }

The key to getting empty cells and cells in general to be the right size, is Box-Sizing and Padding. Border will do the same thing as well, but creates a line in the row. Padding doesn't. And, while I haven't tried it, I think Margin will act the same way as Padding, in forcing and empty cell to be rendered properly.

Writing html form data to a txt file without the use of a webserver

I know this is old, but it's the first example of saving form data to a txt file I found in a quick search. So I've made a couple edits to the above code that makes it work more smoothly. It's now easier to add more fields, including the radio button as @user6573234 requested.

https://jsfiddle.net/cgeiser/m0j7Lwyt/1/

<!DOCTYPE html>
<html>
<head>
<style>
form * {
  display: block;
  margin: 10px;
}
</style>
<script language="Javascript" >
function download() {
  var filename = window.document.myform.docname.value;
  var name =  window.document.myform.name.value;
  var text =  window.document.myform.text.value;
  var problem =  window.document.myform.problem.value;
  
  var pom = document.createElement('a');
  pom.setAttribute('href', 'data:text/plain;charset=utf-8,' + 
    "Your Name: " + encodeURIComponent(name) + "\n\n" +
    "Problem: " + encodeURIComponent(problem) + "\n\n" +
    encodeURIComponent(text)); 

  pom.setAttribute('download', filename);

  pom.style.display = 'none';
  document.body.appendChild(pom);

  pom.click();

  document.body.removeChild(pom);
}
</script>
</head>
<body>
<form name="myform" method="post" >
  <input type="text" id="docname" value="test.txt" />
  <input type="text" id="name" placeholder="Your Name" />
  <div style="display:unblock">
    Option 1 <input type="radio" value="Option 1" onclick="getElementById('problem').value=this.value; getElementById('problem').show()" style="display:inline" />
    Option 2 <input type="radio" value="Option 2" onclick="getElementById('problem').value=this.value;" style="display:inline" />
    <input type="text" id="problem" />
  </div>
  <textarea rows=3 cols=50 id="text" />Please type in this box. 
When you click the Download button, the contents of this box will be downloaded to your machine at the location you specify. Pretty nifty. </textarea>
  
  <input id="download_btn" type="submit" class="btn" style="width: 125px" onClick="download();" />
  
</form>
</body>
</html>

instanceof Vs getClass( )

I know it has been a while since this was asked, but I learned an alternative yesterday

We all know you can do:

if(o instanceof String) {   // etc

but what if you dont know exactly what type of class it needs to be? you cannot generically do:

if(o instanceof <Class variable>.getClass()) {   

as it gives a compile error.
Instead, here is an alternative - isAssignableFrom()

For example:

public static boolean isASubClass(Class classTypeWeWant, Object objectWeHave) {

    return classTypeWeWant.isAssignableFrom(objectWeHave.getClass())
}

Why use #define instead of a variable

#define can accomplish some jobs that normal C++ cannot, like guarding headers and other tasks. However, it definitely should not be used as a magic number- a static const should be used instead.

What's the difference between select_related and prefetch_related in Django ORM?

Both methods achieve the same purpose, to forego unnecessary db queries. But they use different approaches for efficiency.

The only reason to use either of these methods is when a single large query is preferable to many small queries. Django uses the large query to create models in memory preemptively rather than performing on demand queries against the database.

select_related performs a join with each lookup, but extends the select to include the columns of all joined tables. However this approach has a caveat.

Joins have the potential to multiply the number of rows in a query. When you perform a join over a foreign key or one-to-one field, the number of rows won't increase. However, many-to-many joins do not have this guarantee. So, Django restricts select_related to relations that won't unexpectedly result in a massive join.

The "join in python" for prefetch_related is a little more alarming then it should be. It creates a separate query for each table to be joined. It filters each of these table with a WHERE IN clause, like:

SELECT "credential"."id",
       "credential"."uuid",
       "credential"."identity_id"
FROM   "credential"
WHERE  "credential"."identity_id" IN
    (84706, 48746, 871441, 84713, 76492, 84621, 51472);

Rather than performing a single join with potentially too many rows, each table is split into a separate query.

Execute a file with arguments in Python shell

If you set PYTHONINSPECT in the python file you want to execute

[repl.py]

import os
import sys
from time import time 
os.environ['PYTHONINSPECT'] = 'True'
t=time()
argv=sys.argv[1:len(sys.argv)]

there is no need to use execfile, and you can directly run the file with arguments as usual in the shell:

python repl.py one two 3
>>> t
1513989378.880822
>>> argv
['one', 'two', '3']

Output an Image in PHP

If you have the liberty to configure your webserver yourself, tools like mod_xsendfile (for Apache) are considerably better than reading and printing the file in PHP. Your PHP code would look like this:

header("Content-type: $type");
header("X-Sendfile: $file"); # make sure $file is the full path, not relative
exit();

mod_xsendfile picks up the X-Sendfile header and sends the file to the browser itself. This can make a real difference in performance, especially for big files. Most of the proposed solutions read the whole file into memory and then print it out. That's OK for a 20kbyte image file, but if you have a 200 MByte TIFF file, you're bound to get problems.

accessing a file using [NSBundle mainBundle] pathForResource: ofType:inDirectory:

Go to "Target" -> "Build Phases", select your target, select the “Build Phases” tab, click “Add Build Phase”, and select “Add Copy Files”. Change the destination to “Products Directory”. Drag your file into the “Add files” section.

Thread pooling in C++11

Follwoing [PhD EcE](https://stackoverflow.com/users/3818417/phd-ece) suggestion, I implemented the thread pool:

function_pool.h

#pragma once
#include <queue>
#include <functional>
#include <mutex>
#include <condition_variable>
#include <atomic>
#include <cassert>

class Function_pool
{

private:
    std::queue<std::function<void()>> m_function_queue;
    std::mutex m_lock;
    std::condition_variable m_data_condition;
    std::atomic<bool> m_accept_functions;

public:

    Function_pool();
    ~Function_pool();
    void push(std::function<void()> func);
    void done();
    void infinite_loop_func();
};

function_pool.cpp

#include "function_pool.h"

Function_pool::Function_pool() : m_function_queue(), m_lock(), m_data_condition(), m_accept_functions(true)
{
}

Function_pool::~Function_pool()
{
}

void Function_pool::push(std::function<void()> func)
{
    std::unique_lock<std::mutex> lock(m_lock);
    m_function_queue.push(func);
    // when we send the notification immediately, the consumer will try to get the lock , so unlock asap
    lock.unlock();
    m_data_condition.notify_one();
}

void Function_pool::done()
{
    std::unique_lock<std::mutex> lock(m_lock);
    m_accept_functions = false;
    lock.unlock();
    // when we send the notification immediately, the consumer will try to get the lock , so unlock asap
    m_data_condition.notify_all();
    //notify all waiting threads.
}

void Function_pool::infinite_loop_func()
{
    std::function<void()> func;
    while (true)
    {
        {
            std::unique_lock<std::mutex> lock(m_lock);
            m_data_condition.wait(lock, [this]() {return !m_function_queue.empty() || !m_accept_functions; });
            if (!m_accept_functions && m_function_queue.empty())
            {
                //lock will be release automatically.
                //finish the thread loop and let it join in the main thread.
                return;
            }
            func = m_function_queue.front();
            m_function_queue.pop();
            //release the lock
        }
        func();
    }
}

main.cpp

#include "function_pool.h"
#include <string>
#include <iostream>
#include <mutex>
#include <functional>
#include <thread>
#include <vector>

Function_pool func_pool;

class quit_worker_exception : public std::exception {};

void example_function()
{
    std::cout << "bla" << std::endl;
}

int main()
{
    std::cout << "stating operation" << std::endl;
    int num_threads = std::thread::hardware_concurrency();
    std::cout << "number of threads = " << num_threads << std::endl;
    std::vector<std::thread> thread_pool;
    for (int i = 0; i < num_threads; i++)
    {
        thread_pool.push_back(std::thread(&Function_pool::infinite_loop_func, &func_pool));
    }

    //here we should send our functions
    for (int i = 0; i < 50; i++)
    {
        func_pool.push(example_function);
    }
    func_pool.done();
    for (unsigned int i = 0; i < thread_pool.size(); i++)
    {
        thread_pool.at(i).join();
    }
}

Flatten list of lists

Given

d = [[180.0], [173.8], [164.2], [156.5], [147.2], [138.2]]

and your specific question: How can I remove the brackets?

Using list comprehension :

new_d = [i[0] for i in d]

will give you this

[180.0, 173.8, 164.2, 156.5, 147.2, 138.2]

then you can access individual items with the appropriate index, e.g., new_d[0] will give you 180.0 etc which you can then use for math.

If you are going to have a collection of data, you will have some sort of bracket or parenthesis.

Note, this solution is aimed specifically at your question/problem, it doesn't provide a generalized solution. I.e., it will work for your case.

Getting key with maximum value in dictionary?

+1 to @Aric Coady's simplest solution.
And also one way to random select one of keys with max value in the dictionary:

stats = {'a':1000, 'b':3000, 'c': 100, 'd':3000}

import random
maxV = max(stats.values())
# Choice is one of the keys with max value
choice = random.choice([key for key, value in stats.items() if value == maxV])

How to convert comma-separated String to List?

There is no built-in method for this but you can simply use split() method in this.

String commaSeparated = "item1 , item2 , item3";
ArrayList<String> items = 
new  ArrayList<String>(Arrays.asList(commaSeparated.split(",")));

Why am I getting error CS0246: The type or namespace name could not be found?

I have resolved this problem by adding the reference to System.Web.

Initializing default values in a struct

You don't even need to define a constructor

struct foo {
    bool a = true;
    bool b = true;
    bool c;
 } bar;

To clarify: these are called brace-or-equal-initializers (because you may also use brace initialization instead of equal sign). This is not only for aggregates: you can use this in normal class definitions. This was added in C++11.

Change type of varchar field to integer: "cannot be cast automatically to type integer"

Try this, it will work for sure.

When writing Rails migrations to convert a string column to an integer you'd usually say:

change_column :table_name, :column_name, :integer

However, PostgreSQL will complain:

PG::DatatypeMismatch: ERROR:  column "column_name" cannot be cast automatically to type integer
HINT:  Specify a USING expression to perform the conversion.

The "hint" basically tells you that you need to confirm you want this to happen, and how data shall be converted. Just say this in your migration:

change_column :table_name, :column_name, 'integer USING CAST(column_name AS integer)'

The above will mimic what you know from other database adapters. If you have non-numeric data, results may be unexpected (but you're converting to an integer, after all).

How to redirect both stdout and stderr to a file

You can do it like that 2>&1:

 command > file 2>&1

Convert to Datetime MM/dd/yyyy HH:mm:ss in Sql Server

Supported by SQL Server 2005 and later versions

SELECT CONVERT(VARCHAR(10), GETDATE(), 101) 
       + ' ' + CONVERT(VARCHAR(8), GETDATE(), 108)

* See Microsoft's documentation to understand what the 101 and 108 style codes above mean.

Supported by SQL Server 2012 and later versions

SELECT FORMAT(GETDATE() , 'MM/dd/yyyy HH:mm:ss')

Result

Both of the above methods will return:

10/16/2013 17:00:20

'str' object does not support item assignment in Python

The other answers are correct, but you can, of course, do something like:

>>> str1 = "mystring"
>>> list1 = list(str1)
>>> list1[5] = 'u'
>>> str1 = ''.join(list1)
>>> print(str1)
mystrung
>>> type(str1)
<type 'str'>

if you really want to.

ssh connection refused on Raspberry Pi

I think pi has ssh server enabled by default. Mine have always worked out of the box. Depends which operating system version maybe.

Most of the time when it fails for me it is because the ip address has been changed. Perhaps you are pinging something else now? Also sometimes they just refuse to connect and need a restart.

round up to 2 decimal places in java?

Go back to your code, and replace 100 by 100.00 and let me know if it works. However, if you want to be formal, try this:

import java.text.DecimalFormat;
DecimalFormat df=new DecimalFormat("0.00");
String formate = df.format(value); 
double finalValue = (Double)df.parse(formate) ;

How to select/get drop down option in Selenium 2

you can do like this :

public void selectDropDownValue(String ValueToSelect) 
{

    webelement findDropDownValue=driver.findElements(By.id("id1"))    //this will find that dropdown 

    wait.until(ExpectedConditions.visibilityOf(findDropDownValue));    // wait till that dropdown appear

    super.highlightElement(findDropDownValue);   // highlight that dropdown     

    new Select(findDropDownValue).selectByValue(ValueToSelect);    //select that option which u had passed as argument
}

Extract substring from a string

Here is a real world example:

String hallostring = "hallo";
String asubstring = hallostring.substring(0, 1); 

In the example asubstring would return: h

Modifying CSS class property values on the fly with JavaScript / jQuery

YUI 2 and 3 has a module stylesheet that will let you do just that (edit stylesheets on the fly with javascript). http://yuilibrary.com/yui/docs/stylesheet/. So I think it is possible. This is not the same as $(".some").css({...}) but really change/add/remove styles definition from stylesheet, just like the user asked.

How to hide the title bar for an Activity in XML with existing custom theme

add in manifiest file ,

  android:theme="@android:style/Theme.Translucent.NoTitleBar"

add following line into ur java file,

  this.requestWindowFeature(Window.FEATURE_NO_TITLE);

How to convert a JSON string to a Map<String, String> with Jackson JSON

The following works for me:

Map<String, String> propertyMap = getJsonAsMap(json);

where getJsonAsMap is defined like so:

public HashMap<String, String> getJsonAsMap(String json)
{
    try
    {
        ObjectMapper mapper = new ObjectMapper();
        TypeReference<Map<String,String>> typeRef = new TypeReference<Map<String,String>>() {};
        HashMap<String, String> result = mapper.readValue(json, typeRef);

        return result;
    }
    catch (Exception e)
    {
        throw new RuntimeException("Couldnt parse json:" + json, e);
    }
}

Note that this will fail if you have child objects in your json (because they're not a String, they're another HashMap), but will work if your json is a key value list of properties like so:

{
    "client_id": "my super id",
    "exp": 1481918304,
    "iat": "1450382274",
    "url": "http://www.example.com"
}

How to post query parameters with Axios?

axios signature for post is axios.post(url[, data[, config]]). So you want to send params object within the third argument:

.post(`/mails/users/sendVerificationMail`, null, { params: {
  mail,
  firstname
}})
.then(response => response.status)
.catch(err => console.warn(err));

This will POST an empty body with the two query params:

POST http://localhost:8000/api/mails/users/sendVerificationMail?mail=lol%40lol.com&firstname=myFirstName

Can't use WAMP , port 80 is used by IIS 7.5

Google search of "remove iis from port 80" leads here currently. Instead of removing IIS, here are the steps to just stop IIS from listening on port 80:

STEP 1: Open IIS Window. You can do this by, simply hitting the ‘Windows’ key and typing in ‘IIS’ or ‘Internet Information Services’. The result will be shown up there. Click it, you will get the window opened for you.

STEP 2: On the ‘Connections’ pane, click the default one to expand it. Usually (PC-NAME(PC-NAME\user), where ‘PC-NAME’ is your PC name, and ‘user’ is the username.

STEP 3: Click ‘Sites’ and expand it. Now select ‘Default Web Site’. On the ‘Actions’ pane, click ‘Bindings’ under the ‘Edit Site’.

STEP 4: Now a window named ‘Site Binding Opens. Click ‘http’ and then click edit. Change the port to another number, say 8000 and click ‘Ok’.

How to get the index with the key in Python dictionary?

Dictionaries in python have no order. You could use a list of tuples as your data structure instead.

d = { 'a': 10, 'b': 20, 'c': 30}
newd = [('a',10), ('b',20), ('c',30)]

Then this code could be used to find the locations of keys with a specific value

locations = [i for i, t in enumerate(newd) if t[0]=='b']

>>> [1]

How to add a fragment to a programmatically generated layout?

At some point, I suppose you will add your programatically created LinearLayout to some root layout that you defined in .xml. This is just a suggestion of mine and probably one of many solutions, but it works: Simply set an ID for the programatically created layout, and add it to the root layout that you defined in .xml, and then use the set ID to add the Fragment.

It could look like this:

LinearLayout rowLayout = new LinearLayout();
rowLayout.setId(whateveryouwantasid);
// add rowLayout to the root layout somewhere here

FragmentManager fragMan = getFragmentManager();
FragmentTransaction fragTransaction = fragMan.beginTransaction();   

Fragment myFrag = new ImageFragment();
fragTransaction.add(rowLayout.getId(), myFrag , "fragment" + fragCount);
fragTransaction.commit();

Simply choose whatever Integer value you want for the ID:

rowLayout.setId(12345);

If you are using the above line of code not just once, it would probably be smart to figure out a way to create unique-IDs, in order to avoid duplicates.

UPDATE:

Here is the full code of how it should be done: (this code is tested and works) I am adding two Fragments to a LinearLayout with horizontal orientation, resulting in the Fragments being aligned next to each other. Please also be aware, that I used a fixed height and width of 200dp, so that one Fragment does not use the full screen as it would with "match_parent".

MainActivity.java:

public class MainActivity extends Activity {

    @SuppressLint("NewApi")
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);     

        LinearLayout fragContainer = (LinearLayout) findViewById(R.id.llFragmentContainer);

        LinearLayout ll = new LinearLayout(this);
        ll.setOrientation(LinearLayout.HORIZONTAL);

        ll.setId(12345);

        getFragmentManager().beginTransaction().add(ll.getId(), TestFragment.newInstance("I am frag 1"), "someTag1").commit();
        getFragmentManager().beginTransaction().add(ll.getId(), TestFragment.newInstance("I am frag 2"), "someTag2").commit();

        fragContainer.addView(ll);
    }
}

TestFragment.java:

public class TestFragment extends Fragment {

    public static TestFragment newInstance(String text) {

        TestFragment f = new TestFragment();

        Bundle b = new Bundle();
        b.putString("text", text);
        f.setArguments(b);
        return f;
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {

        View v =  inflater.inflate(R.layout.fragment, container, false);

        ((TextView) v.findViewById(R.id.tvFragText)).setText(getArguments().getString("text"));     
        return v;
    }
}

activity_main.xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/rlMain"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="5dp"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <LinearLayout
        android:id="@+id/llFragmentContainer"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_alignLeft="@+id/textView1"
        android:layout_below="@+id/textView1"
        android:layout_marginTop="19dp"
        android:orientation="vertical" >
    </LinearLayout>
</RelativeLayout>

fragment.xml:

  <?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="200dp"
    android:layout_height="200dp" >

    <TextView
        android:id="@+id/tvFragText"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:text="" />

</RelativeLayout>

And this is the result of the above code: (the two Fragments are aligned next to each other) result

Can you have a <span> within a <span>?

Yes. You can have a span within a span. Your problem stems from something else.

How to check if a subclass is an instance of a class at runtime?

Maybe I'm missing something, but wouldn't this suffice:

if (view instanceof B) {
    // this view is an instance of B
}

Why does sudo change the PATH?

the recommended solution in the comments on the OpenSUSE distro suggests to change:

Defaults env_reset

to:

Defaults !env_reset

and then presumably to comment out the following line which isn't needed:

Defaults env_keep = "LANG LC_ADDRESS LC_CTYPE LC_COLLATE LC_IDENTIFICATION LC_MEASURE    MENT LC_MESSAGES LC_MONETARY LC_NAME LC_NUMERIC LC_PAPER LC_TELEPHONE LC_TIME LC_ALL L    ANGUAGE LINGUAS XDG_SESSION_COOKIE"

How do you change the size of figures drawn with matplotlib?

This works well for me:

from matplotlib import pyplot as plt

F = plt.gcf()
Size = F.get_size_inches()
F.set_size_inches(Size[0]*2, Size[1]*2, forward=True) # Set forward to True to resize window along with plot in figure.
plt.show() # or plt.imshow(z_array) if using an animation, where z_array is a matrix or numpy array

This might also help: http://matplotlib.1069221.n5.nabble.com/Resizing-figure-windows-td11424.html

How do I authenticate a WebClient request?

This helped me to call API that was using cookie authentication. I have passed authorization in header like this:

request.Headers.Set("Authorization", Utility.Helper.ReadCookie("AuthCookie"));

complete code:

// utility method to read the cookie value:
        public static string ReadCookie(string cookieName)
        {
            var cookies = HttpContext.Current.Request.Cookies;
            var cookie = cookies.Get(cookieName);
            if (cookie != null)
                return cookie.Value;
            return null;
        }

// using statements where you are creating your webclient
using System.Web.Script.Serialization;
using System.Net;
using System.IO;

// WebClient:

var requestUrl = "<API_url>";
var postRequest = new ClassRoom { name = "kushal seth" };

using (var webClient = new WebClient()) {
      JavaScriptSerializer serializer = new JavaScriptSerializer();
      byte[] requestData = Encoding.ASCII.GetBytes(serializer.Serialize(postRequest));
      HttpWebRequest request = WebRequest.Create(requestUrl) as HttpWebRequest;
      request.Method = "POST";
      request.ContentType = "application/json";                        
      request.ContentLength = requestData.Length;
      request.ContentType = "application/json";
      request.Expect = "application/json";
      request.Headers.Set("Authorization", Utility.Helper.ReadCookie("AuthCookie"));
      request.GetRequestStream().Write(requestData, 0, requestData.Length);

      using (var response = (HttpWebResponse)request.GetResponse()) {
         var reader = new StreamReader(response.GetResponseStream());
         var objText = reader.ReadToEnd(); // objText will have the value
      }
}


Python: How to remove empty lists from a list?

You can use filter() instead of a list comprehension:

list2 = filter(None, list1)

If None is used as first argument to filter(), it filters out every value in the given list, which is False in a boolean context. This includes empty lists.

It might be slightly faster than the list comprehension, because it only executes a single function in Python, the rest is done in C.

How to change font in ipython notebook

You can hover to .ipython folder (i.e. you can type $ ipython locate in your terminal/bash OR CMD.exe Prompt from your Anaconda Navigator to see where is your ipython is located)

Then, in .ipython, you will see profile_default directory which is the default one. This directory will have static/custom/custom.css file located.

You can now apply change to this custom.css file. There are a lot of styles in the custom.css file that you can use or search for. For example, you can see this link (which is my own customize custom.css file)

Basically, this custom.css file apply changes to your browser. You can use inspect elements in your ipython notebook to see which elements you want to change. Then, you can changes to the custom.css file. For example, you can add these chunk to change font in .CodeMirror pre to type Monaco

.CodeMirror pre {font-family: Monaco; font-size: 9pt;}

Note that now for Jupyter notebook version >= 4.1, the custom css file is moved to ~/.jupyter/custom/custom.css instead.

CSS-moving text from left to right

If I understand you question correctly, you could create a wrapper around your marquee and then assign a width (or max-width) to the wrapping element. For example:

<div id="marquee-wrapper">
    <div class="marquee">This is a marquee!</div>   
</div>

And then #marquee-wrapper { width: x }.

How to show soft-keyboard when edittext is focused

The following code is pillaged from the Google's 4.1 source code for SearchView. Seems to work, fine on lesser versions of Android as well.

private Runnable mShowImeRunnable = new Runnable() {
    public void run() {
        InputMethodManager imm = (InputMethodManager) getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);

        if (imm != null) {
            imm.showSoftInput(editText, 0);
        }
    }
};

private void setImeVisibility(final boolean visible) {
    if (visible) {
        post(mShowImeRunnable);
    } else {
        removeCallbacks(mShowImeRunnable);
        InputMethodManager imm = (InputMethodManager) getContext()
                .getSystemService(Context.INPUT_METHOD_SERVICE);

        if (imm != null) {
            imm.hideSoftInputFromWindow(getWindowToken(), 0);
        }
    }
}

Then in addition, the following code needs to be added as the Control/Activity is created. (In my case it's a composite control, rather than an activity).

this.editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
    public void onFocusChange(View v, boolean hasFocus) {
        setImeVisibility(hasFocus);
    }
});

Regex to remove letters, symbols except numbers

You can use \D which means non digits.

var removedText = self.val().replace(/\D+/g, '');

jsFiddle.

You could also use the HTML5 number input.

<input type="number" name="digit" />

jsFiddle.

How to change plot background color?

If you already have axes object, just like in Nick T's answer, you can also use

 ax.patch.set_facecolor('black')

How to use Oracle ORDER BY and ROWNUM correctly?

An alternate I would suggest in this use case is to use the MAX(t_stamp) to get the latest row ... e.g.

select t.* from raceway_input_labo t
where t.t_stamp = (select max(t_stamp) from raceway_input_labo) 
limit 1

My coding pattern preference (perhaps) - reliable, generally performs at or better than trying to select the 1st row from a sorted list - also the intent is more explicitly readable.
Hope this helps ...

SQLer

CSS :: child set to change color on parent hover, but changes also when hovered itself

If you don't care about supporting old browsers, you can use :not() to exclude that element:

.parent:hover span:not(:hover) {
    border: 10px solid red;
}

Demo: http://jsfiddle.net/vz9A9/1/

If you do want to support them, the I guess you'll have to either use JavaScript or override the CSS properties again:

.parent span:hover {
    border: 10px solid green;
}

postgreSQL - psql \i : how to execute script in a given path

Have you tried using Unix style slashes (/ instead of \)?

\ is often an escape or command character, and may be the source of confusion. I have never had issues with this, but I also do not have Windows, so I cannot test it.

Additionally, the permissions may be based on the user running psql, or maybe the user executing the postmaster service, check that both have read to that file in that directory.

Declare a variable as Decimal

To declare a variable as a Decimal, first declare it as a Variant and then convert to Decimal with CDec. The type would be Variant/Decimal in the watch window:

enter image description here

Considering that programming floating point arithmetic is not what one has studied during Maths classes at school, one should always try to avoid common pitfalls by converting to decimal whenever possible.

In the example below, we see that the expression:

0.1 + 0.11 = 0.21

is either True or False, depending on whether the collectibles (0.1,0.11) are declared as Double or as Decimal:

Public Sub TestMe()

    Dim preciseA As Variant: preciseA = CDec(0.1)
    Dim preciseB As Variant: preciseB = CDec(0.11)

    Dim notPreciseA As Double: notPreciseA = 0.1
    Dim notPreciseB As Double: notPreciseB = 0.11

    Debug.Print preciseA + preciseB
    Debug.Print preciseA + preciseB = 0.21 'True

    Debug.Print notPreciseA + notPreciseB
    Debug.Print notPreciseA + notPreciseB = 0.21 'False

End Sub

enter image description here

Escape single quote character for use in an SQLite query

I believe you'd want to escape by doubling the single quote:

INSERT INTO table_name (field1, field2) VALUES (123, 'Hello there''s');

how can I debug a jar at runtime?

You can activate JVM's debugging capability when starting up the java command with a special option:

java -agentlib:jdwp=transport=dt_socket,address=8000,server=y,suspend=y -jar path/to/some/war/or/jar.jar

Starting up jar.jar like that on the command line will:

  • put this JVM instance in the role of a server (server=y) listening on port 8000 (address=8000)
  • write Listening for transport dt_socket at address: 8000 to stdout and
  • then pause the application (suspend=y) until some debugger connects. The debugger acts as the client in this scenario.

Common options for selecting a debugger are:

  • Eclipse Debugger: Under Run -> Debug Configurations... -> select Remote Java Application -> click the New launch configuration button. Provide an arbitrary Name for this debug configuration, Connection Type: Standard (Socket Attach) and as Connection Properties the entries Host: localhost, Port: 8000. Apply the Changes and click Debug. At the moment the Eclipse Debugger has successfully connected to the JVM, jar.jar should begin executing.
  • jdb command-line tool: Start it up with jdb -connect com.sun.jdi.SocketAttach:port=8000

How to concatenate strings with padding in sqlite

SQLite has a printf function which does exactly that:

SELECT printf('%s-%.2d-%.4d', col1, col2, col3) FROM mytable

linux find regex

Regular expressions with character classes (e.g. [[:digit:]]) are not supported in the default regular expression syntax used by find. You need to specify a different regex type such as posix-extended in order to use them.

Take a look at GNU Find's Regular Expression documentation which shows you all the regex types and what they support.

How to print time in format: 2009-08-10 18:17:54.811

time.h defines a strftime function which can give you a textual representation of a time_t using something like:

#include <stdio.h>
#include <time.h>
int main (void) {
    char buff[100];
    time_t now = time (0);
    strftime (buff, 100, "%Y-%m-%d %H:%M:%S.000", localtime (&now));
    printf ("%s\n", buff);
    return 0;
}

but that won't give you sub-second resolution since that's not available from a time_t. It outputs:

2010-09-09 10:08:34.000

If you're really constrained by the specs and do not want the space between the day and hour, just remove it from the format string.

Windows equivalent of linux cksum command

It looks as if there is an unsupported tool for checksums from MS. It's light on features but appears to do what you're asking for. It was published in August of 2012. It's called "Microsoft File Checksum Integrity Verifier".

http://www.microsoft.com/en-us/download/details.aspx?id=11533

error: expected ‘=’, ‘,’, ‘;’, ‘asm’ or ‘__attribute__’ before ‘{’ token

  1. You seem to be including one C file from anther. #include should normally be used with header files only.

  2. Within the definition of struct ast_node you refer to struct AST_NODE, which doesn't exist. C is case-sensitive.

How to get everything after last slash in a URL?

Here's a more general, regex way of doing this:

    re.sub(r'^.+/([^/]+)$', r'\1', url)

How can I call the 'base implementation' of an overridden virtual method?

Using the C# language constructs, you cannot explicitly call the base function from outside the scope of A or B. If you really need to do that, then there is a flaw in your design - i.e. that function shouldn't be virtual to begin with, or part of the base function should be extracted to a separate non-virtual function.

You can from inside B.X however call A.X

class B : A
{
  override void X() { 
    base.X();
    Console.WriteLine("y"); 
  }
}

But that's something else.

As Sasha Truf points out in this answer, you can do it through IL. You can probably also accomplish it through reflection, as mhand points out in the comments.

how do I get the bullet points of a <ul> to center with the text?

You can do that with list-style-position: inside; on the ul element :

ul {
    list-style-position: inside;
}

See working fiddle

Is there a version of JavaScript's String.indexOf() that allows for regular expressions?

It does not natively, but you certainly can add this functionality

<script type="text/javascript">

String.prototype.regexIndexOf = function( pattern, startIndex )
{
    startIndex = startIndex || 0;
    var searchResult = this.substr( startIndex ).search( pattern );
    return ( -1 === searchResult ) ? -1 : searchResult + startIndex;
}

String.prototype.regexLastIndexOf = function( pattern, startIndex )
{
    startIndex = startIndex === undefined ? this.length : startIndex;
    var searchResult = this.substr( 0, startIndex ).reverse().regexIndexOf( pattern, 0 );
    return ( -1 === searchResult ) ? -1 : this.length - ++searchResult;
}

String.prototype.reverse = function()
{
    return this.split('').reverse().join('');
}

// Indexes 0123456789
var str = 'caabbccdda';

alert( [
        str.regexIndexOf( /[cd]/, 4 )
    ,   str.regexLastIndexOf( /[cd]/, 4 )
    ,   str.regexIndexOf( /[yz]/, 4 )
    ,   str.regexLastIndexOf( /[yz]/, 4 )
    ,   str.lastIndexOf( 'd', 4 )
    ,   str.regexLastIndexOf( /d/, 4 )
    ,   str.lastIndexOf( 'd' )
    ,   str.regexLastIndexOf( /d/ )
    ]
);

</script>

I didn't fully test these methods, but they seem to work so far.

How to fix committing to the wrong Git branch?

To elaborate on this answer, in case you have multiple commits to move from, e.g. develop to new_branch:

git checkout develop # You're probably there already
git reflog # Find LAST_GOOD, FIRST_NEW, LAST_NEW hashes
git checkout new_branch
git cherry-pick FIRST_NEW^..LAST_NEW # ^.. includes FIRST_NEW
git reflog # Confirm that your commits are safely home in their new branch!
git checkout develop
git reset --hard LAST_GOOD # develop is now back where it started

How can I make a CSS glass/blur effect work for an overlay?

I was able to piece together information from everyone here and further Googling, and I came up with the following which works in Chrome and Firefox: http://jsfiddle.net/xtbmpcsu/. I'm still working on making this work for IE and Opera.

The key is putting the content inside of the div to which the filter is applied:

<div id="mask">
    <p>Lorem ipsum ...</p>
    <img src="http://www.byui.edu/images/agriculture-life-sciences/flower.jpg" />
</div>

And then the CSS:

body {
    background: #300000;
    background: linear-gradient(45deg, #300000, #000000, #300000, #000000);
    color: white;
}
#mask {
    position: absolute;
    left: 0;
    top: 0;
    right: 0;
    bottom: 0;
    background-color: black;
    opacity: 0.5;
}
img {
    filter: blur(10px);
    -webkit-filter: blur(10px);
    -moz-filter: blur(10px);
    -o-filter: blur(10px);
    -ms-filter: blur(10px);
    position: absolute;
    left: 100px;
    top: 100px;
    height: 300px;
    width: auto;
}

So mask has the filters applied. Also, note the use of url() for a filter with an <svg> tag for the value -- that idea came from http://codepen.io/AmeliaBR/pen/xGuBr. If you happen to minify your CSS, you might need to replace any spaces in the SVG filter markup with "%20".

So now, everything inside the mask div is blurred.

Finding what branch a Git commit came from

Update December 2013:

sschuberth comments

git-what-branch (Perl script, see below) does not seem to be maintained anymore. git-when-merged is an alternative written in Python that's working very well for me.

It is based on "Find merge commit which include a specific commit".

git when-merged [OPTIONS] COMMIT [BRANCH...]

Find when a commit was merged into one or more branches.
Find the merge commit that brought COMMIT into the specified BRANCH(es).

Specifically, look for the oldest commit on the first-parent history of BRANCH that contains the COMMIT as an ancestor.


Original answer September 2010:

Sebastien Douche just twitted (16 minutes before this SO answer):

git-what-branch: Discover what branch a commit is on, or how it got to a named branch

This is a Perl script from Seth Robertson that seems very interesting:

SYNOPSIS

git-what-branch [--allref] [--all] [--topo-order | --date-order ]
[--quiet] [--reference-branch=branchname] [--reference=reference]
<commit-hash/tag>...

OVERVIEW

Tell us (by default) the earliest causal path of commits and merges to cause the requested commit got onto a named branch. If a commit was made directly on a named branch, that obviously is the earliest path.

By earliest causal path, we mean the path which merged into a named branch the earliest, by commit time (unless --topo-order is specified).

PERFORMANCE

If many branches (e.g. hundreds) contain the commit, the system may take a long time (for a particular commit in the Linux tree, it took 8 second to explore a branch, but there were over 200 candidate branches) to track down the path to each commit.
Selection of a particular --reference-branch --reference tag to examine will be hundreds of times faster (if you have hundreds of candidate branches).

EXAMPLES

 # git-what-branch --all 1f9c381fa3e0b9b9042e310c69df87eaf9b46ea4
 1f9c381fa3e0b9b9042e310c69df87eaf9b46ea4 first merged onto master using the following minimal temporal path:
   v2.6.12-rc3-450-g1f9c381 merged up at v2.6.12-rc3-590-gbfd4bda (Thu May  5 08:59:37 2005)
   v2.6.12-rc3-590-gbfd4bda merged up at v2.6.12-rc3-461-g84e48b6 (Tue May  3 18:27:24 2005)
   v2.6.12-rc3-461-g84e48b6 is on master
   v2.6.12-rc3-461-g84e48b6 is on v2.6.12-n
   [...]

This program does not take into account the effects of cherry-picking the commit of interest, only merge operations.

When would you use the Builder Pattern?

The key difference between a builder and factory IMHO, is that a builder is useful when you need to do lots of things to build an object. For example imagine a DOM. You have to create plenty of nodes and attributes to get your final object. A factory is used when the factory can easily create the entire object within one method call.

One example of using a builder is a building an XML document, I've used this model when building HTML fragments for example I might have a Builder for building a specific type of table and it might have the following methods (parameters are not shown):

BuildOrderHeaderRow()
BuildLineItemSubHeaderRow()
BuildOrderRow()
BuildLineItemSubRow()

This builder would then spit out the HTML for me. This is much easier to read than walking through a large procedural method.

Check out Builder Pattern on Wikipedia.

CSS '>' selector; what is it?

As others have said, it's a direct child, but it's worth noting that this is different to just leaving a space... a space is for any descendant.

<div>
  <span>Some text</span>
</div>

div>span would match this, but it would not match this:

<div>
  <p><span>Some text</span></p>
</div>

To match that, you could do div>p>span or div span.

How do I create a new class in IntelliJ without using the mouse?

I do this a lot, and I don't have an insert key on my laptop, so I made my own keybinding for it. You can do this by opening Settings > IDE Settings > Keymap and navigating to Main menu > File > New... (I would recommend typing "new" into the search box - that will narrow it down considerably).

Then you can add a new keyboard shortcut for it by double clicking on that item and selecting Add Keyboard Shortcut.

Can I have two JavaScript onclick events in one element?

This one works:

<input type="button" value="test" onclick="alert('hey'); alert('ho');" />

And this one too:

function Hey()
{
    alert('hey');
}

function Ho()
{
    alert('ho');
}

.

<input type="button" value="test" onclick="Hey(); Ho();" />

So the answer is - yes you can :) However, I'd recommend to use unobtrusive JavaScript.. mixing js with HTML is just nasty.

Using jQuery to see if a div has a child with a certain class

Use the children funcion of jQuery.

$("#text-field").keydown(function(event) {
    if($('#popup').children('p.filled-text').length > 0) {
        console.log("Found");
     }
});

$.children('').length will return the count of child elements which match the selector.

Select records from today, this week, this month php mysql

Assuming your date column is an actual MySQL date column:

SELECT * FROM jokes WHERE date > DATE_SUB(NOW(), INTERVAL 1 DAY) ORDER BY score DESC;        
SELECT * FROM jokes WHERE date > DATE_SUB(NOW(), INTERVAL 1 WEEK) ORDER BY score DESC;
SELECT * FROM jokes WHERE date > DATE_SUB(NOW(), INTERVAL 1 MONTH) ORDER BY score DESC;

Use of *args and **kwargs

Just imagine you have a function but you don't want to restrict the number of parameter it takes. Example:

>>> import operator
>>> def multiply(*args):
...  return reduce(operator.mul, args)

Then you use this function like:

>>> multiply(1,2,3)
6

or

>>> numbers = [1,2,3]
>>> multiply(*numbers)
6

Using AND/OR in if else PHP statement

AND and OR are just syntactic sugar for && and ||, like in JavaScript, or other C styled syntax languages.

It appears AND and OR have lower precedence than their C style equivalents.

Using .htaccess to make all .html pages to run as .php files?

Normally you should add:

Options +ExecCGI
 AddType application/x-httpd-php .php .html
 AddHandler x-httpd-php5 .php .html

However for GoDaddy shared hosting (php-cgi), you need to add also these lines:

AddHandler fcgid-script .html
FCGIWrapper /usr/local/cpanel/cgi-sys/php5 .html

Source: Parse HTML As PHP Using HTACCESS File On Godaddy.

Git push failed, "Non-fast forward updates were rejected"

I've had the same problem.
The reason was, that my local branch had somehow lost the tracking to the remote counterpart.

After

git branch branch_name --set-upstream-to=origin/branch_name
git pull

and resolving the merging conflicts, I was able to push.

jQuery and TinyMCE: textarea value doesn't submit

I had this problem for a while and triggerSave() didn't work, nor did any of the other methods.

So I found a way that worked for me ( I'm adding this here because other people may have already tried triggerSave and etc... ):

tinyMCE.init({
   selector: '.tinymce', // This is my <textarea> class
   setup : function(ed) {
                  ed.on('change', function(e) {
                     // This will print out all your content in the tinyMce box
                     console.log('the content '+ed.getContent());
                     // Your text from the tinyMce box will now be passed to your  text area ... 
                     $(".tinymce").text(ed.getContent()); 
                  });
            }
   ... Your other tinyMce settings ...
});

When you're submitting your form or whatever all you have to do is grab the data from your selector ( In my case: .tinymce ) using $('.tinymce').text().

How can two strings be concatenated?

Another non-paste answer:

x <- capture.output(cat(data, sep = ","))
x
[1] "GAD,AB"

Where

 data <- c("GAD", "AB")

Convert bytes to int?

Lists of bytes are subscriptable (at least in Python 3.6). This way you can retrieve the decimal value of each byte individually.

>>> intlist = [64, 4, 26, 163, 255]
>>> bytelist = bytes(intlist)       # b'@x04\x1a\xa3\xff'

>>> for b in bytelist:
...    print(b)                     # 64  4  26  163  255

>>> [b for b in bytelist]           # [64, 4, 26, 163, 255]

>>> bytelist[2]                     # 26 

Thymeleaf: Concatenation - Could not parse as expression

But from what I see you have quite a simple error in syntax

<p th:text="${bean.field} + '!' + ${bean.field}">Static content</p>

the correct syntax would look like

<p th:text="${bean.field + '!' + bean.field}">Static content</p>

As a matter of fact, the syntax th:text="'static part' + ${bean.field}" is equal to th:text="${'static part' + bean.field}".

Try it out. Even though this is probably kind of useless now after 6 months.

How do I write JSON data to a file?

I would answer with slight modification with aforementioned answers and that is to write a prettified JSON file which human eyes can read better. For this, pass sort_keys as True and indent with 4 space characters and you are good to go. Also take care of ensuring that the ascii codes will not be written in your JSON file:

with open('data.txt', 'w') as outfile:
     json.dump(jsonData, outfile, sort_keys = True, indent = 4,
               ensure_ascii = False)

Extract values in Pandas value_counts()

If anyone missed it out in the comments, try this:

dataframe[column].value_counts().to_frame()

How do I get the current timezone name in Postgres 9.3?

See this answer: Source

If timezone is not specified in postgresql.conf or as a server command-line option, the server attempts to use the value of the TZ environment variable as the default time zone. If TZ is not defined or is not any of the time zone names known to PostgreSQL, the server attempts to determine the operating system's default time zone by checking the behavior of the C library function localtime(). The default time zone is selected as the closest match among PostgreSQL's known time zones. (These rules are also used to choose the default value of log_timezone, if not specified.) source

This means that if you do not define a timezone, the server attempts to determine the operating system's default time zone by checking the behavior of the C library function localtime().

If timezone is not specified in postgresql.conf or as a server command-line option, the server attempts to use the value of the TZ environment variable as the default time zone.

It seems to have the System's timezone to be set is possible indeed.

Get the OS local time zone from the shell. In psql:

=> \! date +%Z

How to float a div over Google Maps?

Just set the position of the div and you may have to set the z-index.

ex.

div#map-div {
    position: absolute;
    left: 10px;
    top: 10px;
}
div#cover-div {
    position:absolute;
    left:10px;
    top: 10px;
    z-index:3;
}

Iterating over a numpy array

I see that no good desciption for using numpy.nditer() is here. So, I am gonna go with one. According to NumPy v1.21 dev0 manual, The iterator object nditer, introduced in NumPy 1.6, provides many flexible ways to visit all the elements of one or more arrays in a systematic fashion.

I have to calculate mean_squared_error and I have already calculate y_predicted and I have y_actual from the boston dataset, available with sklearn.

def cal_mse(y_actual, y_predicted):
    """ this function will return mean squared error
       args:
           y_actual (ndarray): np array containing target variable
           y_predicted (ndarray): np array containing predictions from DecisionTreeRegressor
       returns:
           mse (integer)
    """
    sq_error = 0
    for i in np.nditer(np.arange(y_pred.shape[0])):
        sq_error += (y_actual[i] - y_predicted[i])**2
    mse = 1/y_actual.shape[0] * sq_error
    
    return mse

Hope this helps :). for further explaination visit

Which version of Python do I have installed?

To verify the Python version for commands on Windows, run the following commands in a command prompt and verify the output:

c:\> python -V
Python 2.7.16

c:\> py -2 -V
Python 2.7.16

c:\> py -3 -V
Python 3.7.3

Also, to see the folder configuration for each Python version, run the following commands:

For Python 2, 'py -2 -m site'
For Python 3, 'py -3 -m site'

How to find out the server IP address (using JavaScript) that the browser is connected to?

I believe John's answer is correct. For instance, I'm using my laptop through a wifi service run by a conference centre -- I'm pretty sure that there is no way for javascript running within my browser to discover the IP address being used by the service provider. On the other hand, it may be possible to address a suitable external resource from javascript. You can write your own if your own by making an ajax call to a server which can take the IP address from the HTTP headers and return it, or try googling "find my ip". The cleanest solution is probably to capture the information before the page is served and insert it in the html returned to the user. See How to get a viewer's IP address with python? for info on how to capture the information if you are serving the page with python.

How can I join multiple SQL tables using the IDs?

SELECT 
    a.nameA, /* TableA.nameA */
    d.nameD /* TableD.nameD */
FROM TableA a 
    INNER JOIN TableB b on b.aID = a.aID 
    INNER JOIN TableC c on c.cID = b.cID 
    INNER JOIN TableD d on d.dID = a.dID 
WHERE DATE(c.`date`) = CURDATE()

How do I make Visual Studio pause after executing a console application in debug mode?

Do a readline at the end (it's the "forma cochina", like we say in Colombia, but it works):

static void Main(string[] args)
{
    .
    .
    .
    String temp = Console.ReadLine();
}

oracle sql: update if exists else insert

MERGE doesn't need "multiple tables", but it does need a query as the source. Something like this should work:

MERGE INTO mytable d
USING (SELECT 1 id, 'x' name from dual) s
ON (d.id = s.id)
WHEN MATCHED THEN UPDATE SET d.name = s.name
WHEN NOT MATCHED THEN INSERT (id, name) VALUES (s.id, s.name);

Alternatively you can do this in PL/SQL:

BEGIN
  INSERT INTO mytable (id, name) VALUES (1, 'x');
EXCEPTION
  WHEN DUP_VAL_ON_INDEX THEN
    UPDATE mytable
    SET    name = 'x'
    WHERE id = 1;
END;

Change marker size in Google maps V3

The size arguments are in pixels. So, to double your example's marker size the fifth argument to the MarkerImage constructor would be:

new google.maps.Size(42,68)

I find it easiest to let the map API figure out the other arguments, unless I need something other than the bottom/center of the image as the anchor. In your case you could do:

var pinIcon = new google.maps.MarkerImage(
    "http://chart.apis.google.com/chart?chst=d_map_pin_letter&chld=%E2%80%A2|" + pinColor,
    null, /* size is determined at runtime */
    null, /* origin is 0,0 */
    null, /* anchor is bottom center of the scaled image */
    new google.maps.Size(42, 68)
);

Attaching a Sass/SCSS to HTML docs

You can not "attach" a SASS/SCSS file to an HTML document.

SASS/SCSS is a CSS preprocessor that runs on the server and compiles to CSS code that your browser understands.

There are client-side alternatives to SASS that can be compiled in the browser using javascript such as LESS CSS, though I advise you compile to CSS for production use.

It's as simple as adding 2 lines of code to your HTML file.

<link rel="stylesheet/less" type="text/css" href="styles.less" />
<script src="less.js" type="text/javascript"></script>

Why can't I have "public static const string S = "stuff"; in my Class?

const is similar to static we can access both varables with class name but diff is static variables can be modified and const can not.