Programs & Examples On #Sweave

Sweave is a system for combining S (or R) code with LaTeX in a single document.

ValueError: math domain error

you are getting math domain error for either one of the reason : either you are trying to use a negative number inside log function or a zero value.

php how to go one level up on dirname(__FILE__)

To Whom, deailing with share hosting environment and still chance to have Current PHP less than 7.0 Who does not have dirname( __FILE__, 2 ); it is possible to use following.

function dirname_safe($path, $level = 0){
    $dir = explode(DIRECTORY_SEPARATOR, $path);
    $level = $level * -1;
    if($level == 0) $level = count($dir);
    array_splice($dir, $level);
    return implode($dir, DIRECTORY_SEPARATOR).DIRECTORY_SEPARATOR;
}

print_r(dirname_safe(__DIR__, 2));

Querying date field in MongoDB with Mongoose

{ "date" : "1000000" } in your Mongo doc seems suspect. Since it's a number, it should be { date : 1000000 }

It's probably a type mismatch. Try post.findOne({date: "1000000"}, callback) and if that works, you have a typing issue.

Difference between a script and a program?

A framework or other similar schema will run/interpret a script to do a task. A program is compiled and run by a machine to do a task

Colon (:) in Python list index

: is the delimiter of the slice syntax to 'slice out' sub-parts in sequences , [start:end]

[1:5] is equivalent to "from 1 to 5" (5 not included)
[1:] is equivalent to "1 to end"
[len(a):] is equivalent to "from length of a to end"

Watch https://youtu.be/tKTZoB2Vjuk?t=41m40s at around 40:00 he starts explaining that.

Works with tuples and strings, too.

Keeping it simple and how to do multiple CTE in a query

You certainly are able to have multiple CTEs in a single query expression. You just need to separate them with a comma. Here is an example. In the example below, there are two CTEs. One is named CategoryAndNumberOfProducts and the second is named ProductsOverTenDollars.

WITH CategoryAndNumberOfProducts (CategoryID, CategoryName, NumberOfProducts) AS
(
   SELECT
      CategoryID,
      CategoryName,
      (SELECT COUNT(1) FROM Products p
       WHERE p.CategoryID = c.CategoryID) as NumberOfProducts
   FROM Categories c
),

ProductsOverTenDollars (ProductID, CategoryID, ProductName, UnitPrice) AS
(
   SELECT
      ProductID,
      CategoryID,
      ProductName,
      UnitPrice
   FROM Products p
   WHERE UnitPrice > 10.0
)

SELECT c.CategoryName, c.NumberOfProducts,
      p.ProductName, p.UnitPrice
FROM ProductsOverTenDollars p
   INNER JOIN CategoryAndNumberOfProducts c ON
      p.CategoryID = c.CategoryID
ORDER BY ProductName

How to turn NaN from parseInt into 0 for an empty string?

You can have very clean code, i had similar problems and i solved it by using :

var a="bcd";
~~parseInt(a);

Design Android EditText to show error message as described by google

TextInputLayout til = (TextInputLayout)editText.getParent();
til.setErrorEnabled(true);
til.setError("some error..");

Why are Python's 'private' methods not actually private?

Important update (Python 3.4):

Any identifier of the form __name (at least two leading underscores, at most one trailing underscore) is publicly replaced with _classname__name, where classname is the current class name with leading underscore(s) stripped.

Therefore, __name is private, while _classname__name is public.

https://docs.python.org/3/tutorial/classes.html#tut-private

Example

class Cat:
    def __init__(self, name='unnamed'):
        self.name = name
    def __print_my_name(self):
        print(self.name)
        
        
tom = Cat()
tom.__print_my_name() #Error
tom._Cat__print_my_name() #Prints name

How to convert ZonedDateTime to Date?

The accepted answer did not work for me. The Date returned is always the local Date and not the Date for the original Time Zone. I live in UTC+2.

//This did not work for me
Date.from(java.time.ZonedDateTime.now().toInstant()); 

I have come up with two alternative ways to get the correct Date from a ZonedDateTime.

Say you have this ZonedDateTime for Hawaii

LocalDateTime ldt = LocalDateTime.now();
ZonedDateTime zdt = ldt.atZone(ZoneId.of("US/Hawaii"); // UTC-10

or for UTC as asked originally

Instant zulu = Instant.now(); // GMT, UTC+0
ZonedDateTime zdt = zulu.atZone(ZoneId.of("UTC"));

Alternative 1

We can use java.sql.Timestamp. It is simple but it will probably also make a dent in your programming integrity

Date date1 = Timestamp.valueOf(zdt.toLocalDateTime());

Alternative 2

We create the Date from millis (answered here earlier). Note that local ZoneOffset is a must.

ZoneOffset localOffset = ZoneOffset.systemDefault().getRules().getOffset(LocalDateTime.now());
long zonedMillis = 1000L * zdt.toLocalDateTime().toEpochSecond(localOffset) + zdt.toLocalDateTime().getNano() / 1000000L;
Date date2 = new Date(zonedMillis);

How to set specific Java version to Maven

You could configure compiling sources using different JDK with maven-compiler-plugin.

Just specify path to javac in <executable> tag. E.g for java11 it looks like:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>3.8.0</version>
    <configuration>
        <source>11</source>
        <target>11</target>
        <fork>true</fork>
        <executable>C:\Program Files\Java\jdk-11.0.1\bin\javac</executable> <!--PATH TO JAVAC -->
    </configuration>
</plugin>

Saving images in Python at a very high quality

In case you are working with seaborn plots, instead of Matplotlib, you can save a .png image like this:

Let's suppose you have a matrix object (either Pandas or NumPy), and you want to take a heatmap:

import seaborn as sb

image = sb.heatmap(matrix)   # This gets you the heatmap
image.figure.savefig("C:/Your/Path/ ... /your_image.png")   # This saves it

This code is compatible with the latest version of Seaborn. Other code around Stack Overflow worked only for previous versions.

Another way I like is this. I set the size of the next image as follows:

plt.subplots(figsize=(15,15))

And then later I plot the output in the console, from which I can copy-paste it where I want. (Since Seaborn is built on top of Matplotlib, there will not be any problem.)

How to exclude particular class name in CSS selector?

Method 1

The problem with your code is that you are selecting the .remode_hover that is a descendant of .remode_selected. So the first part of getting your code to work correctly is by removing that space

.reMode_selected.reMode_hover:hover

Then, in order to get the style to not work, you have to override the style set by the :hover. In other words, you need to counter the background-color property. So the final code will be

.reMode_selected.reMode_hover:hover {
  background-color:inherit;
}
.reMode_hover:hover {
  background-color: #f0ac00;
}

Fiddle

Method 2

An alternative method would be to use :not(), as stated by others. This will return any element that doesn't have the class or property stated inside the parenthesis. In this case, you would put .remode_selected in there. This will target all elements that don't have a class of .remode_selected

Fiddle

However, I would not recommend this method, because of the fact that it was introduced in CSS3, so browser support is not ideal.

Method 3

A third method would be to use jQuery. You can target the .not() selector, which would be similar to using :not() in CSS, but with much better browser support

Fiddle

Can't connect to HTTPS site using cURL. Returns 0 length content instead. What can I do?

The best way to use https and avoid security issues is to use Firefox (or another tool) and download the certificate to your server. This webpage helped me a lot, and these were the steps that worked for me:

1) Open in Firefox the URL you're gonna use with CURL

2) On the address bar click on the padlock > more information (FF versions can have different menus, just find it). Click the View certificate button > Details tab.

3) Highlight the "right" certificate in Certificate hierarchy. In my case it was the second of three, called "cPanel, Inc. Certification Authority". I just discovered the right one by "trial and error" method.

4) Click the Export button. In my case the one who worked was the file type "PEM with chains" (again by trial and error method).

5) Then in your PHP script add:

curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, 2);    
curl_setopt($ch, CURLOPT_CAINFO, [PATH_TO_CRT_FILE]);

In addition I'd say that we must pay attention on the fact that these steps will probably need to be redone once a year or whenever the URL certificate is replaced or renewed.

How do you create a hidden div that doesn't create a line break or horizontal space?

To hide the element visually, but keep it in the html, you can use:

<div style='visibility:hidden; overflow:hidden; height:0; width:0;'>
  [content]
</div>

or

<div style='visibility:hidden; overflow:hidden; position:absolute;'>
  [content]
</div>

What may go wrong with display:none? It removes the element completely from the html, so some functionalities may be broken if they need to access something in the hidden element.

m2e lifecycle-mapping not found

You can use this dummy plugin:

mvn archetype:generate -DgroupId=org.eclipse.m2e -DartifactId=lifecycle-mapping -Dversion=1.0.0 -DarchetypeArtifactId=maven-archetype-mojo

After generating the project install/deploy it.

How can I copy a file on Unix using C?

There is no baked-in equivalent CopyFile function in the APIs. But sendfile can be used to copy a file in kernel mode which is a faster and better solution (for numerous reasons) than opening a file, looping over it to read into a buffer, and writing the output to another file.

Update:

As of Linux kernel version 2.6.33, the limitation requiring the output of sendfile to be a socket was lifted and the original code would work on both Linux and — however, as of OS X 10.9 Mavericks, sendfile on OS X now requires the output to be a socket and the code won't work!

The following code snippet should work on the most OS X (as of 10.5), (Free)BSD, and Linux (as of 2.6.33). The implementation is "zero-copy" for all platforms, meaning all of it is done in kernelspace and there is no copying of buffers or data in and out of userspace. Pretty much the best performance you can get.

#include <fcntl.h>
#include <unistd.h>
#if defined(__APPLE__) || defined(__FreeBSD__)
#include <copyfile.h>
#else
#include <sys/sendfile.h>
#endif

int OSCopyFile(const char* source, const char* destination)
{    
    int input, output;    
    if ((input = open(source, O_RDONLY)) == -1)
    {
        return -1;
    }    
    if ((output = creat(destination, 0660)) == -1)
    {
        close(input);
        return -1;
    }

    //Here we use kernel-space copying for performance reasons
#if defined(__APPLE__) || defined(__FreeBSD__)
    //fcopyfile works on FreeBSD and OS X 10.5+ 
    int result = fcopyfile(input, output, 0, COPYFILE_ALL);
#else
    //sendfile will work with non-socket output (i.e. regular file) on Linux 2.6.33+
    off_t bytesCopied = 0;
    struct stat fileinfo = {0};
    fstat(input, &fileinfo);
    int result = sendfile(output, input, &bytesCopied, fileinfo.st_size);
#endif

    close(input);
    close(output);

    return result;
}

EDIT: Replaced the opening of the destination with the call to creat() as we want the flag O_TRUNC to be specified. See comment below.

How to enter command with password for git pull?

Doesn't answer the question directly, but I found this question when searching for a way to, basically, not re-enter the password every single time I pull on a remote server.

Well, git allows you to cache your credentials for a finite amount of time. It's customizable in git config and this page explains it very well:

https://help.github.com/articles/caching-your-github-password-in-git/#platform-linux

In a terminal, run:

$ git config --global credential.helper cache
# Set git to use the credential memory cache

To customize the cache timeout, you can do:

$ git config --global credential.helper 'cache --timeout=3600'
# Set the cache to timeout after 1 hour (setting is in seconds)

Your credentials will then be stored in-memory for the requested amount of time.

How to undo a successful "git cherry-pick"?

A cherry-pick is basically a commit, so if you want to undo it, you just undo the commit.

when I have other local changes

Stash your current changes so you can reapply them after resetting the commit.

$ git stash
$ git reset --hard HEAD^
$ git stash pop  # or `git stash apply`, if you want to keep the changeset in the stash

when I have no other local changes

$ git reset --hard HEAD^

How do you allow spaces to be entered using scanf?

While you really shouldn't use scanf() for this sort of thing, because there are much better calls such as gets() or getline(), it can be done:

#include <stdio.h>

char* scan_line(char* buffer, int buffer_size);

char* scan_line(char* buffer, int buffer_size) {
   char* p = buffer;
   int count = 0;
   do {
       char c;
       scanf("%c", &c); // scan a single character
       // break on end of line, string terminating NUL, or end of file
       if (c == '\r' || c == '\n' || c == 0 || c == EOF) {
           *p = 0;
           break;
       }
       *p++ = c; // add the valid character into the buffer
   } while (count < buffer_size - 1);  // don't overrun the buffer
   // ensure the string is null terminated
   buffer[buffer_size - 1] = 0;
   return buffer;
}

#define MAX_SCAN_LENGTH 1024

int main()
{
   char s[MAX_SCAN_LENGTH];
   printf("Enter a string: ");
   scan_line(s, MAX_SCAN_LENGTH);
   printf("got: \"%s\"\n\n", s);
   return 0;
}

Refresh image with a new one at the same url

You can simply use fetch with the cache option set to 'reload' to update the cache:

fetch("my-image-url.jpg", {cache: 'reload', mode: 'no-cors'})

These days the fetch API is available almost everywhere (except on IE, of course).

As always you will find detailed information on how to use the fetch API on MDN.

Remove last item from array

2019 ECMA5 Solution:

const new_arr = arr.reduce((d, i, idx, l) => idx < l.length - 1 ? [...d, i] : d, [])

Non destructive, generic, one-liner and only requires a copy & paste at the end of your array.

How to restart remote MySQL server running on Ubuntu linux?

  1. SSH into the machine. Using the proper credentials and ip address, ssh [email protected]. This should provide you with shell access to the Ubuntu server.
  2. Restart the mySQL service. sudo service mysql restart should do the job.

If your mySQL service is named something else like mysqld you may have to change the command accordingly or try this: sudo /etc/init.d/mysql restart

How to print the array?

If you want to print the array like you print a 2D list in Python:

#include <stdio.h>

int main()
{
  int i, j;
  int my_array[3][3] = {{10, 23, 42}, {1, 654, 0}, {40652, 22, 0}};
  for(i = 0; i < 3; i++)
  {
      if (i == 0) {
          printf("[");
      }
      printf("[");
      for(j = 0; j < 3; j++)
      {
         printf("%d", my_array[i][j]);
         if (j < 2) {
             printf(", ");
         }
      }
    printf("]");
    if (i == 2) {
        printf("]");
    }

    if (i < 2) {
        printf(", ");
    }
  }
  return 0;
}

Output will be:

[[10, 23, 42], [1, 654, 0], [40652, 22, 0]]

IF function with 3 conditions

Using INDEX and MATCH for binning. Easier to maintain if we have more bins.

=INDEX({"Text 1","Text 2","Text 3"},MATCH(A2,{0,5,21,100}))

enter image description here

Converting ArrayList to HashMap

[edited]

using your comment about productCode (and assuming product code is a String) as reference...

 for(Product p : productList){
        s.put(p.getProductCode() , p);
    }

How to write ternary operator condition in jQuery?

I'd do (added caching):

var bbx = $("#blackbox");
 bbx.css('background-color') === 'rgb(255, 192, 203)' ? bbx.css('background','black') : bbx.css('background','pink')

wroking fiddle (new AGAIN): http://jsfiddle.net/6nar4/37/

I had to change the first operator as css() returns the rgb value of the color

Vendor code 17002 to connect to SQLDeveloper

I had the same Problem. I had start my Oracle TNS Listener, then it works normally again.

See LISTENER: TNS-12545 ... No such file or directory.

Draw line in UIView

The easiest way in your case (horizontal line) is to add a subview with black background color and frame [0, 200, 320, 1].

Code sample (I hope there are no errors - I wrote it without Xcode):

UIView *lineView = [[UIView alloc] initWithFrame:CGRectMake(0, 200, self.view.bounds.size.width, 1)];
lineView.backgroundColor = [UIColor blackColor];
[self.view addSubview:lineView];
[lineView release];
// You might also keep a reference to this view 
// if you are about to change its coordinates.
// Just create a member and a property for this...

Another way is to create a class that will draw a line in its drawRect method (you can see my code sample for this here).

Check whether an input string contains a number in javascript

You can do this using javascript. No need for Jquery or Regex

function isNumeric(n) 
{
  return !isNaN(n);
}

An exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

There are some problems with your code. First I advise to use parametrized queries so you avoid SQL Injection attacks and also parameter types are discovered by framework:

var cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = @id", con);
cmd.Parameters.AddWithValue("@id", id.Text);

Second, as you are interested only in one value getting returned from the query, it is better to use ExecuteScalar:

var name = cmd.ExecuteScalar();

if (name != null)
{
   position = name.ToString();
   Response.Write("User Registration successful");
}
else
{
    Console.WriteLine("No Employee found.");
}

The last thing is to wrap SqlConnection and SqlCommand into using so any resources used by those will be disposed of:

string position;

using (SqlConnection con = new SqlConnection("server=free-pc\\FATMAH; Integrated Security=True; database=Workflow; "))
{
  con.Open();

  using (var cmd = new SqlCommand("SELECT EmpName FROM Employee WHERE EmpID = @id", con))
  {
    cmd.Parameters.AddWithValue("@id", id.Text);
  
    var name = cmd.ExecuteScalar();
  
    if (name != null)
    {
       position = name.ToString();
       Response.Write("User Registration successful");
    }
    else
    {
        Console.WriteLine("No Employee found.");
    }
  }
}

Insertion sort vs Bubble Sort Algorithms

Number of swap in each iteration

  • Insertion-sort does at most 1 swap in each iteration.
  • Bubble-sort does 0 to n swaps in each iteration.

Accessing and changing sorted part

  • Insertion-sort accesses(and changes when needed) the sorted part to find the correct position of a number in consideration.
  • When optimized, Bubble-sort does not access what is already sorted.

Online or not

  • Insertion-sort is online. That means Insertion-sort takes one input at a time before it puts in appropriate position. It does not have to compare only adjacent-inputs.
  • Bubble-sort is not-online. It does not operate one input at a time. It handles a group of inputs(if not all) in each iteration. Bubble-sort only compare and swap adjacent-inputs in each iteration.

python numpy vector math

You can just use numpy arrays. Look at the numpy for matlab users page for a detailed overview of the pros and cons of arrays w.r.t. matrices.

As I mentioned in the comment, having to use the dot() function or method for mutiplication of vectors is the biggest pitfall. But then again, numpy arrays are consistent. All operations are element-wise. So adding or subtracting arrays and multiplication with a scalar all work as expected of vectors.

Edit2: Starting with Python 3.5 and numpy 1.10 you can use the @ infix-operator for matrix multiplication, thanks to pep 465.

Edit: Regarding your comment:

  1. Yes. The whole of numpy is based on arrays.

  2. Yes. linalg.norm(v) is a good way to get the length of a vector. But what you get depends on the possible second argument to norm! Read the docs.

  3. To normalize a vector, just divide it by the length you calculated in (2). Division of arrays by a scalar is also element-wise.

    An example in ipython:

    In [1]: import math
    
    In [2]: import numpy as np
    
    In [3]: a = np.array([4,2,7])
    
    In [4]: np.linalg.norm(a)
    Out[4]: 8.3066238629180749
    
    In [5]: math.sqrt(sum([n**2 for n in a]))
    Out[5]: 8.306623862918075
    
    In [6]: b = a/np.linalg.norm(a)
    
    In [7]: np.linalg.norm(b)
    Out[7]: 1.0
    

    Note that In [5] is an alternative way to calculate the length. In [6] shows normalizing the vector.

How to display the first few characters of a string in Python?

You can 'slice' a string very easily, just like you'd pull items from a list:

a_string = 'This is a string'

To get the first 4 letters:

first_four_letters = a_string[:4]
>>> 'This'

Or the last 5:

last_five_letters = a_string[-5:]
>>> 'string'

So applying that logic to your problem:

the_string = '416d76b8811b0ddae2fdad8f4721ddbe|d4f656ee006e248f2f3a8a93a8aec5868788b927|12a5f648928f8e0b5376d2cc07de8e4cbf9f7ccbadb97d898373f85f0a75c47f '
first_32_chars = the_string[:32]
>>> 416d76b8811b0ddae2fdad8f4721ddbe

Tomcat view catalina.out log file

Just logged in to the server and type below command

locate catalina.out

It will show all the locations where catalina file exist within this server.

How to generate a number of most distinctive colors in R?

You can generate a set of colors like this:

myCol = c("pink1", "violet", "mediumpurple1", "slateblue1", "purple", "purple3",
          "turquoise2", "skyblue", "steelblue", "blue2", "navyblue",
          "orange", "tomato", "coral2", "palevioletred", "violetred", "red2",
          "springgreen2", "yellowgreen", "palegreen4",
          "wheat2", "tan", "tan2", "tan3", "brown",
          "grey70", "grey50", "grey30")

These colors are as distinct as possible. For those similar colors, they form a gradient so that you can easily tell the differences between them.

Split string with string as delimiter

I've found two older scripts that use an indefinite or even a specific string to split. As an approach, these are always helpful.

https://www.administrator.de/contentid/226533#comment-1059704 https://www.administrator.de/contentid/267522#comment-1000886

@echo off
:noOption
if "%~1" neq "" goto :nohelp
echo Gibt eine Ausgabe bis zur angebenen Zeichenfolge&echo(
echo %~n0 ist mit Eingabeumleitung zu nutzen
echo %~n0 "Zeichenfolge" ^<Quelldatei [^>Zieldatei]&echo(
echo    Zeichenfolge    die zu suchende Zeichenfolge wird mit FIND bestimmt
echo            ohne AusgabeUmleitung Ausgabe im CMD Fenster
exit /b
:nohelp
setlocal disabledelayedexpansion
set "intemp=%temp%%time::=%"
set "string=%~1"
set "stringlength=0"
:Laenge string bestimmen
for /f eol^=^

^ delims^= %%i in (' cmd /u /von /c "echo(!string!"^|find /v "" ') do set /a Stringlength += 1

:Eingabe temporär speichern
>"%intemp%" find /n /v ""

:suchen der Zeichenfolge und Zeile bestimmen und speichen
set "NRout="
for /f "tokens=*delims=" %%a in (' find "%string%"^<"%intemp%" ') do if not defined NRout (set "LineStr=%%a"
  for /f "delims=[]" %%b in ("%%a") do set "NRout=%%b"
)
if not defined NRout >&2 echo Zeichenfolge nicht gefunden.& set /a xcode=1 &goto :end
if %NRout% gtr 1 call :Line
call :LineStr

:end
del "%intemp%"
exit /b %xcode%

:LineStr Suche nur jeden ersten Buchstaben des Strings in der Treffer-Zeile dann Ausgabe bis dahin
for /f eol^=^

^ delims^= %%a in ('cmd /u /von /c "echo(!String!"^|findstr .') do (
  for /f "delims=[]" %%i in (' cmd /u /von /c "echo(!LineStr!"^|find /n "%%a" ') do (
    setlocal enabledelayedexpansion
    for /f %%n in ('set /a %%i-1') do if !LineStr:^~%%n^,%stringlength%! equ !string! (
      set "Lineout=!LineStr:~0,%%n!!string!"
      echo(!Lineout:*]=!
      exit /b
    )
) )
exit /b 

:Line vorige Zeilen ausgeben
for /f "usebackq tokens=* delims=" %%i in ("%intemp%") do (
  for /f "tokens=1*delims=[]" %%n in ("%%i") do if %%n EQU %NRout%  exit /b
  set "Line=%%i"
  setlocal enabledelayedexpansion 
  echo(!Line:*]=!
  endlocal
)
exit /b

@echo off
:: CUTwithWildcards.cmd
:noOption
if "%~1" neq "" goto :nohelp
echo Gibt eine Ausgabe ohne die angebene Zeichenfolge.
echo Der Rest wird abgeschnitten.&echo(
echo %~n0 "Zeichenfolge" B n E [/i] &echo(
echo    Zeichenfolge    String zum Durchsuchen
echo    B   Zeichen Wonach am Anfang gesucht wird
echo    n   Auszulassende Zeichenanzahl
echo    E   Zeichen was das Ende der Zeichen Bestimmt
echo    /i  Case intensive
exit /b
:nohelp
setlocal disabledelayedexpansion
set  "Original=%~1"
set     "Begin=%~2"
set /a    Excl=%~3 ||echo Syntaxfehler.>&2 &&exit /b 1
set       "End=%~4"
if not defined end echo Syntaxfehler.>&2 &exit /b 1
set   "CaseInt=%~5"
:: end Setting Input Param
set       "out="
set      "more="
call :read Original
if errorlevel 1 echo Zeichenfolge nicht gefunden.>&2
exit /b
:read VarName B # E [/i]
for /f "delims=[]" %%a in (' cmd /u /von /c "echo  !%~1!"^|find /n %CaseInt% "%Begin%" ') do (
  if defined out exit /b 0
  for /f "delims=[]" %%b in (' cmd /u /von /c "echo !%1!"^|more +%Excl%^|find /n %CaseInt% "%End%"^|find "[%%a]" ') do (
    set "out=1"
    setlocal enabledelayedexpansion
    set "In=  !Original!"
    set "In=!In:~,%%a!"
    echo !In:^~2!
    endlocal
) )
if not defined out exit /b 1 
exit /b

::oneliner for CMDLine
set "Dq=""
for %i in ("*S??E*") do @set "out=1" &for /f "delims=[]" %a in ('cmd/u/c "echo  %i"^|find /n "S"') do @if defined out for /f "delims=[]" %b in ('cmd/u/c "echo %i"^|more +2^|find /n "E"^|find "[%a]"') do @if %a equ %b set "out=" & set in= "%i" &cmd /v/c echo ren "%i" !in:^~0^,%a!!Dq!)

Storing Data in MySQL as JSON

CouchDB and MySQL are two very different beasts. JSON is the native way to store stuff in CouchDB. In MySQL, the best you could do is store JSON data as text in a single field. This would entirely defeat the purpose of storing it in an RDBMS and would greatly complicate every database transaction.

Don't.

Having said that, FriendFeed seemed to use an extremely custom schema on top of MySQL. It really depends on what exactly you want to store, there's hardly one definite answer on how to abuse a database system so it makes sense for you. Given that the article is very old and their main reason against Mongo and Couch was immaturity, I'd re-evaluate these two if MySQL doesn't cut it for you. They should have grown a lot by now.

How to convert a String to Bytearray

The best solution I've come up with at on the spot (though most likely crude) would be:

String.prototype.getBytes = function() {
    var bytes = [];
    for (var i = 0; i < this.length; i++) {
        var charCode = this.charCodeAt(i);
        var cLen = Math.ceil(Math.log(charCode)/Math.log(256));
        for (var j = 0; j < cLen; j++) {
            bytes.push((charCode << (j*8)) & 0xFF);
        }
    }
    return bytes;
}

Though I notice this question has been here for over a year.

How to convert Calendar to java.sql.Date in Java?

stmt.setDate(1, new java.sql.Date(cal.getTime().getTime()));

Redirecting exec output to a buffer or file

After forking, use dup2(2) to duplicate the file's FD into stdout's FD, then exec.

html select option SELECTED

foreach ($array as $value => $name) {
     echo '<option value="' . htmlentities($value) . '"' . (($_GET['sel'] === $value) ? ' selected="selected"') . '>' . htmlentities($name) . '</option>';
}

This is fairly neat, and, I think, self-explanatory.

How to change the button color when it is active using bootstrap?

CSS has many pseudo selector like, :active, :hover, :focus, so you can use.

Html

<div class="col-sm-12" id="my_styles">
     <button type="submit" class="btn btn-warning" id="1">Button1</button>
     <button type="submit" class="btn btn-warning" id="2">Button2</button>
</div>

css

.btn{
    background: #ccc;
} .btn:focus{
    background: red;
}

JsFiddle

SQL Error: ORA-00922: missing or invalid option

The error you're getting appears to be the result of the fact that there is no underscore between "chartered" and "flight" in the table name. I assume you want something like this where the name of the table is chartered_flight.

CREATE TABLE chartered_flight(flight_no NUMBER(4) PRIMARY KEY
, customer_id NUMBER(6) REFERENCES customer(customer_id)
, aircraft_no NUMBER(4) REFERENCES aircraft(aircraft_no)
, flight_type VARCHAR2 (12)
, flight_date DATE NOT NULL
, flight_time INTERVAL DAY TO SECOND NOT NULL
, takeoff_at CHAR (3) NOT NULL
, destination CHAR (3) NOT NULL)

Generally, there is no benefit to declaring a column as CHAR(3) rather than VARCHAR2(3). Declaring a column as CHAR(3) doesn't force there to be three characters of (useful) data. It just tells Oracle to space-pad data with fewer than three characters to three characters. That is unlikely to be helpful if someone inadvertently enters an incorrect code. Potentially, you could declare the column as VARCHAR2(3) and then add a CHECK constraint that LENGTH(takeoff_at) = 3.

CREATE TABLE chartered_flight(flight_no NUMBER(4) PRIMARY KEY
, customer_id NUMBER(6) REFERENCES customer(customer_id)
, aircraft_no NUMBER(4) REFERENCES aircraft(aircraft_no)
, flight_type VARCHAR2 (12)
, flight_date DATE NOT NULL
, flight_time INTERVAL DAY TO SECOND NOT NULL
, takeoff_at CHAR (3) NOT NULL CHECK( length( takeoff_at ) = 3 )
, destination CHAR (3) NOT NULL CHECK( length( destination ) = 3 )
)

Since both takeoff_at and destination are airport codes, you really ought to have a separate table of valid airport codes and define foreign key constraints between the chartered_flight table and this new airport_code table. That ensures that only valid airport codes are added and makes it much easier in the future if an airport code changes.

And from a naming convention standpoint, since both takeoff_at and destination are airport codes, I would suggest that the names be complementary and indicate that fact. Something like departure_airport_code and arrival_airport_code, for example, would be much more meaningful.

Class vs. static method in JavaScript

When you try to call Foo.talk, the JS tries to search a function talk through __proto__ and, of course, it can't be found.

Foo.__proto__ is Function.prototype.

What EXACTLY is meant by "de-referencing a NULL pointer"?

A NULL pointer points to memory that doesn't exist. This may be address 0x00000000 or any other implementation-defined value (as long as it can never be a real address). Dereferencing it means trying to access whatever is pointed to by the pointer. The * operator is the dereferencing operator:

int a, b, c; // some integers
int *pi;     // a pointer to an integer

a = 5;
pi = &a; // pi points to a
b = *pi; // b is now 5
pi = NULL;
c = *pi; // this is a NULL pointer dereference

This is exactly the same thing as a NullReferenceException in C#, except that pointers in C can point to any data object, even elements inside an array.

How can I use JSON data to populate the options of a select box?

Take a look at JQuery view engine and just load the array into a dropdown:

$.ajax({
    url:'suggest.html',
    type:'POST',
    data: 'q=' + str,
    dataType: 'json',
    success: function( json ) {
          // Assumption is that API returned something like:["North","West","South","East"];
          $('#myselect').view(json);
    }
});

See details here: https://jocapc.github.io/jquery-view-engine/docs/ajax-dropdown

How to get div height to auto-adjust to background size?

I looked at some of the solutions and they're great but I think I found a surprisingly easy way.

First, we need to get the ratio from the background image. We simply divide one dimension through another. Then we get something like for example 66.4%

When we have image ratio we can simply calculate the height of the div by multiplying the ratio by viewport width:

height: calc(0.664 * 100vw);

To me, it works, sets div height properly and changes it when the window is resized.

Increase max execution time for php

Use mod_php7.c instead of mod_php5.c for PHP 7

Example

<IfModule mod_php7.c>
   php_value max_execution_time 500
</IfModule>

Copy mysql database from remote server to local computer

Often our databases are really big and the take time to take dump directly from remote machine to other machine as our friends other have suggested above.

In such cases what you can do is to take the dump on remote machine using MYSQLDUMP Command

MYSQLDUMP -uuser -p --all-databases > file_name.sql

and than transfer that file from remote server to your machine using Linux SCP Command

scp user@remote_ip:~/mysql_dump_file_name.sql ./

Create a file if one doesn't exist - C

You typically have to do this in a single syscall, or else you will get a race condition.

This will open for reading and writing, creating the file if necessary.

FILE *fp = fopen("scores.dat", "ab+");

If you want to read it and then write a new version from scratch, then do it as two steps.

FILE *fp = fopen("scores.dat", "rb");
if (fp) {
    read_scores(fp);
}

// Later...

// truncates the file
FILE *fp = fopen("scores.dat", "wb");
if (!fp)
    error();
write_scores(fp);

How to convert string to integer in PowerShell

Once you have selected the highest value, which is "12" in my example, you can then declare it as integer and increment your value:

$FileList = "1", "2", "11"
$foldername = [int]$FileList[2] + 1
$foldername

"Find next" in Vim

If you press Ctrl + Enter after you press something like "/wordforsearch", then you can find the word "wordforsearch" in the current line. Then press n for the next match; press N for previous match.

Multi-line string with extra space (preserved indentation)

echo adds spaces between the arguments passed to it. $text is subject to variable expansion and word splitting, so your echo command is equivalent to:

echo -e "this" "is" "line" "one\n" "this" "is" "line" "two\n"  ...

You can see that a space will be added before "this". You can either remove the newline characters, and quote $text to preserve the newlines:

text="this is line one
this is line two
this is line three"

echo "$text" > filename

Or you could use printf, which is more robust and portable than echo:

printf "%s\n" "this is line one" "this is line two" "this is line three" > filename

In bash, which supports brace expansion, you could even do:

printf "%s\n" "this is line "{one,two,three} > filename

Select first 4 rows of a data.frame in R

For at DataFrame one can simply type

head(data, num=10L)

to get the first 10 for example.

For a data.frame one can simply type

head(data, 10)

to get the first 10.

How to create a new column in a select query

select A, B, 'c' as C
from MyTable

Why does ANT tell me that JAVA_HOME is wrong when it is not?

Make sure you do not use the trailing semicolon: This will not work:

set JAVA_HOME=C:\Program Files (x86)\Java\jdk1.6.0_29;

This will:

set JAVA_HOME=C:\Program Files (x86)\Java\jdk1.6.0_29

How to get current timestamp in string format in Java? "yyyy.MM.dd.HH.mm.ss"

Replace

new Timestamp();

with

new java.util.Date()

because there is no default constructor for Timestamp, or you can do it with the method:

new Timestamp(System.currentTimeMillis());

Immediate exit of 'while' loop in C++

Use break?

while(choice!=99)
{
  cin>>choice;
  if (choice==99)
    break;
  cin>>gNum;
}

How do I convert from a money datatype in SQL server?

This looks like a formating issue to me.
As far as SQL Server's money type is concerned 0 == 0.00

If you're trying to display 0 in say c# rather then 0.00 you should convert it to a string, and format it as you want. (or truncate it.)

How to Create a real one-to-one relationship in SQL Server

I'm pretty sure it is technically impossible in SQL Server to have a True 1 to 1 relationship, as that would mean you would have to insert both records at the same time (otherwise you'd get a constraint error on insert), in both tables, with both tables having a foreign key relationship to each other.

That being said, your database design described with a foreign key is a 1 to 0..1 relationship. There is no constrain possible that would require a record in tableB. You can have a pseudo-relationship with a trigger that creates the record in tableB.

So there are a few pseudo-solutions

First, store all the data in a single table. Then you'll have no issues in EF.

Or Secondly, your entity must be smart enough to not allow an insert unless it has an associated record.

Or thirdly, and most likely, you have a problem you are trying to solve, and you are asking us why your solution doesn't work instead of the actual problem you are trying to solve (an XY Problem).

UPDATE

To explain in REALITY how 1 to 1 relationships don't work, I'll use the analogy of the Chicken or the egg dilemma. I don't intend to solve this dilemma, but if you were to have a constraint that says in order to add a an Egg to the Egg table, the relationship of the Chicken must exist, and the chicken must exist in the table, then you couldn't add an Egg to the Egg table. The opposite is also true. You cannot add a Chicken to the Chicken table without both the relationship to the Egg and the Egg existing in the Egg table. Thus no records can be every made, in a database without breaking one of the rules/constraints.

Database nomenclature of a one-to-one relationship is misleading. All relationships I've seen (there-fore my experience) would be more descriptive as one-to-(zero or one) relationships.

How do I plot only a table in Matplotlib?

Not sure if this is already answered, but if you want only a table in a figure window, then you can hide the axes:

fig, ax = plt.subplots()

# Hide axes
ax.xaxis.set_visible(False) 
ax.yaxis.set_visible(False)

# Table from Ed Smith answer
clust_data = np.random.random((10,3))
collabel=("col 1", "col 2", "col 3")
ax.table(cellText=clust_data,colLabels=collabel,loc='center')

How to debug Javascript with IE 8

I discovered today that we can now debug Javascript With the developer tool bar plugins integreted in IE 8.

  • Click ? Tools on the toolbar, to the right of the tabs.
  • Select Developer Tools. The Developer Tools dialogue should open.
  • Click the Script tab in the dialogue.
  • Click the Start Debugging button.

You can use watch, breakpoint, see the call stack etc, similarly to debuggers in professional browsers.

You can also use the statement debugger; in your JavaScript code the set a breakpoint.

Efficient SQL test query or validation query that will work across all (or most) databases

I use this for Firebird

select 1 from RDB$RELATION_FIELDS rows 1

How to embed fonts in CSS?

One of the best source of information on this topic is Paul Irish's Bulletproof @font-face syntax article.

Read it and you will end with something like:

/* definition */
@font-face {
  font-family: EntezareZohoor2;
  src: url('fonts/EntezareZohoor2.eot');
  src: url('fonts/EntezareZohoor2.eot?') format('?'),
       url('fonts/EntezareZohoor2.woff') format('woff'),
       url('fonts/EntezareZohoor2.ttf') format('truetype');
  font-weight: normal;
  font-style: normal;
}

/* use */
body {
    font-family: EntezareZohoor2, Tahoma, serif;
}

How to send an object from one Android Activity to another using Intents?

You'll need to serialize your object into some kind of string representation. One possible string representation is JSON, and one of the easiest ways to serialize to/from JSON in android, if you ask me, is through Google GSON.

In that case you just put the string return value from (new Gson()).toJson(myObject); and retrieve the string value and use fromJson to turn it back into your object.

If your object isn't very complex, however, it might not be worth the overhead, and you could consider passing the separate values of the object instead.

Java method to swap primitives

Try this magic

public static <T> void swap(T a, T b) {
    try {
        Field[] fields = a.getClass().getDeclaredFields();
        for (Field field : fields) {
            field.setAccessible(true);
            Object temp = field.get(a);
            field.set(a, field.get(b));
            field.set(b, temp);
        }
    } catch (IllegalAccessException e) {
        e.printStackTrace();
    }
}

And test it!

    System.out.println("a:" + a);
    System.out.println("b:" + b);
    swap(a,b);
    System.out.println("a:" + a);
    System.out.println("b:" + b);

What is the convention in JSON for empty vs. null?

Empty array for empty collections and null for everything else.

How do I rewrite URLs in a proxy response in NGINX

You may also need the following directive to be set before the first "sub_filter" for backend-servers with data compression:

proxy_set_header Accept-Encoding "";

Otherwise it may not work. For your example it will look like:

location /admin/ {
    proxy_pass http://localhost:8080/;
    proxy_set_header Accept-Encoding "";
    sub_filter "http://your_server/" "http://your_server/admin/";
    sub_filter_once off;
}

How To Include CSS and jQuery in my WordPress plugin?

To include CSS and jQuery in your plugin is easy, try this:

// register jquery and style on initialization
add_action('init', 'register_script');
function register_script() {
    wp_register_script( 'custom_jquery', plugins_url('/js/custom-jquery.js', __FILE__), array('jquery'), '2.5.1' );

    wp_register_style( 'new_style', plugins_url('/css/new-style.css', __FILE__), false, '1.0.0', 'all');
}

// use the registered jquery and style above
add_action('wp_enqueue_scripts', 'enqueue_style');

function enqueue_style(){
   wp_enqueue_script('custom_jquery');

   wp_enqueue_style( 'new_style' );
}

I found this great snipped from this site How to include jQuery and CSS in WordPress – The WordPress Way

Hope that helps.

Error System.Data.OracleClient requires Oracle client software version 8.1.7 or greater when installs setup

If you have to use the older client, here is my experience.

We are running a 32bit server so the development machines run the 32bit client. We run the 11.1 install, 11.2 gets the error. Once you have installed the 11.2 version you have to manually delete the files Oracle.Web.dll and System.Data.OracleClient.dll from the %windir%\Microsoft.NET\Framework\v2.0.50727, reinstall 11.1, then register the dlls with gacutil.exe.

This fixed the issue with my systems.

Calling stored procedure with return value

I had a similar problem with the SP call returning an error that an expected parameter was not included. My code was as follows.
Stored Procedure:

@Result int OUTPUT

And C#:

            SqlParameter result = cmd.Parameters.Add(new SqlParameter("@Result", DbType.Int32));
            result.Direction = ParameterDirection.ReturnValue;

In troubleshooting, I realized that the stored procedure was ACTUALLY looking for a direction of "InputOutput" so the following change fixed the problem.

            r

Result.Direction = ParameterDirection.InputOutput;

How to get client's IP address using JavaScript?

All the above answers have a server part, not pure client part. This should be provided by the web browser. At present, no web browser support this.

However, with this addon for firefox: https://addons.mozilla.org/en-US/firefox/addon/ip-address/ You will have to ask your users to install this addon. (it's good from me, a 3rd party).

you can test whether the user has installed it.

var installed=window.IP!==undefined;

you can get it with javascript, if it is installed, then var ip=IP.getClient(); var IPclient=ip.IP; //while ip.url is the url

ip=IP.getServer();
var IPserver=ip.IP;
var portServer=ip.port;
//while ip.url is the url

//or you can use IP.getBoth();

more information here: http://www.jackiszhp.info/tech/addon.IP.html

Is it possible to use Visual Studio on macOS?

No. Neither Visual Studio or the .NET framework will run on Mac OSX (although the latter is changing). However, if you want to write an application in a similar framework, you could use Mono and MonoDevelop.

jQuery "on create" event for dynamically-created elements

There is a plugin, adampietrasiak/jquery.initialize, which is based on MutationObserver that achieves this simply.

$.initialize(".some-element", function() {
    $(this).css("color", "blue");
});

How to generate the JPA entity Metamodel?

Let's assume our application uses the following Post, PostComment, PostDetails, and Tag entities, which form a one-to-many, one-to-one, and many-to-many table relationships:

JPA Criteria Metamodel

How to generate the JPA Criteria Metamodel

The hibernate-jpamodelgen tool provided by Hibernate ORM can be used to scan the project entities and generate the JPA Criteria Metamodel. All you need to do is add the following annotationProcessorPath to the maven-compiler-plugin in the Maven pom.xml configuration file:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-compiler-plugin</artifactId>
    <version>${maven-compiler-plugin.version}</version>
    <configuration>
        <annotationProcessorPaths>
            <annotationProcessorPath>
                <groupId>org.hibernate</groupId>
                <artifactId>hibernate-jpamodelgen</artifactId>
                <version>${hibernate.version}</version>
            </annotationProcessorPath>
        </annotationProcessorPaths>
    </configuration>
</plugin>

Now, when the project is compiled, you can see that in the target folder, the following Java classes are generated:

> tree target/generated-sources/
target/generated-sources/
+-- annotations
    +-- com
        +-- vladmihalcea
            +-- book
                +-- hpjp
                    +-- hibernate
                        +-- forum
                        ¦   +-- PostComment_.java
                        ¦   +-- PostDetails_.java
                        ¦   +-- Post_.java
                        ¦   +-- Tag_.java

Tag entity Metamodel

If the Tag entity is mapped as follows:

@Entity
@Table(name = "tag")
public class Tag {

    @Id
    private Long id;

    private String name;

    //Getters and setters omitted for brevity
}

The Tag_ Metamodel class is generated like this:

@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(Tag.class)
public abstract class Tag_ {

    public static volatile SingularAttribute<Tag, String> name;
    public static volatile SingularAttribute<Tag, Long> id;

    public static final String NAME = "name";
    public static final String ID = "id";
}

The SingularAttribute is used for the basic id and name Tag JPA entity attributes.

Post entity Metamodel

The Post entity is mapped like this:

@Entity
@Table(name = "post")
public class Post {

    @Id
    private Long id;

    private String title;

    @OneToMany(
        mappedBy = "post",
        cascade = CascadeType.ALL,
        orphanRemoval = true
    )
    private List<PostComment> comments = new ArrayList<>();

    @OneToOne(
        mappedBy = "post",
        cascade = CascadeType.ALL,
        fetch = FetchType.LAZY
    )
    @LazyToOne(LazyToOneOption.NO_PROXY)
    private PostDetails details;

    @ManyToMany
    @JoinTable(
        name = "post_tag",
        joinColumns = @JoinColumn(name = "post_id"),
        inverseJoinColumns = @JoinColumn(name = "tag_id")
    )
    private List<Tag> tags = new ArrayList<>();
    
    //Getters and setters omitted for brevity
}

The Post entity has two basic attributes, id and title, a one-to-many comments collection, a one-to-one details association, and a many-to-many tags collection.

The Post_ Metamodel class is generated as follows:

@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(Post.class)
public abstract class Post_ {

    public static volatile ListAttribute<Post, PostComment> comments;
    public static volatile SingularAttribute<Post, PostDetails> details;
    public static volatile SingularAttribute<Post, Long> id;
    public static volatile SingularAttribute<Post, String> title;
    public static volatile ListAttribute<Post, Tag> tags;

    public static final String COMMENTS = "comments";
    public static final String DETAILS = "details";
    public static final String ID = "id";
    public static final String TITLE = "title";
    public static final String TAGS = "tags";
}

The basic id and title attributes, as well as the one-to-one details association, are represented by a SingularAttribute while the comments and tags collections are represented by the JPA ListAttribute.

PostDetails entity Metamodel

The PostDetails entity is mapped like this:

@Entity
@Table(name = "post_details")
public class PostDetails {

    @Id
    @GeneratedValue
    private Long id;

    @Column(name = "created_on")
    private Date createdOn;

    @Column(name = "created_by")
    private String createdBy;

    @OneToOne(fetch = FetchType.LAZY)
    @MapsId
    @JoinColumn(name = "id")
    private Post post;
    
    //Getters and setters omitted for brevity
}

All entity attributes are going to be represented by the JPA SingularAttribute in the associated PostDetails_ Metamodel class:

@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(PostDetails.class)
public abstract class PostDetails_ {

    public static volatile SingularAttribute<PostDetails, Post> post;
    public static volatile SingularAttribute<PostDetails, String> createdBy;
    public static volatile SingularAttribute<PostDetails, Long> id;
    public static volatile SingularAttribute<PostDetails, Date> createdOn;

    public static final String POST = "post";
    public static final String CREATED_BY = "createdBy";
    public static final String ID = "id";
    public static final String CREATED_ON = "createdOn";
}

PostComment entity Metamodel

The PostComment is mapped as follows:

@Entity
@Table(name = "post_comment")
public class PostComment {

    @Id
    private Long id;

    @ManyToOne(fetch = FetchType.LAZY)
    private Post post;

    private String review;
    
    //Getters and setters omitted for brevity
}

And, all entity attributes are represented by the JPA SingularAttribute in the associated PostComments_ Metamodel class:

@Generated(value = "org.hibernate.jpamodelgen.JPAMetaModelEntityProcessor")
@StaticMetamodel(PostComment.class)
public abstract class PostComment_ {

    public static volatile SingularAttribute<PostComment, Post> post;
    public static volatile SingularAttribute<PostComment, String> review;
    public static volatile SingularAttribute<PostComment, Long> id;

    public static final String POST = "post";
    public static final String REVIEW = "review";
    public static final String ID = "id";
}

Using the JPA Criteria Metamodel

Without the JPA Metamodel, a Criteria API query that needs to fetch the PostComment entities filtered by their associated Post title would look like this:

CriteriaBuilder builder = entityManager.getCriteriaBuilder();

CriteriaQuery<PostComment> query = builder.createQuery(PostComment.class);
Root<PostComment> postComment = query.from(PostComment.class);

Join<PostComment, Post> post = postComment.join("post");

query.where(
    builder.equal(
        post.get("title"),
        "High-Performance Java Persistence"
    )
);

List<PostComment> comments = entityManager
    .createQuery(query)
    .getResultList();

Notice that we used the post String literal when creating the Join instance, and we used the title String literal when referencing the Post title.

The JPA Metamodel allows us to avoid hard-coding entity attributes, as illustrated by the following example:

CriteriaBuilder builder = entityManager.getCriteriaBuilder();

CriteriaQuery<PostComment> query = builder.createQuery(PostComment.class);
Root<PostComment> postComment = query.from(PostComment.class);

Join<PostComment, Post> post = postComment.join(PostComment_.post);

query.where(
    builder.equal(
        post.get(Post_.title),
        "High-Performance Java Persistence"
    )
);

List<PostComment> comments = entityManager
    .createQuery(query)
    .getResultList();

Or, let's say we want to fetch a DTO projection while filtering the Post title and the PostDetails createdOn attributes.

We can use the Metamodel when creating the join attributes, as well as when building the DTO projection column aliases or when referencing the entity attributes we need to filter:

CriteriaBuilder builder = entityManager.getCriteriaBuilder();

CriteriaQuery<Object[]> query = builder.createQuery(Object[].class);

Root<PostComment> postComment = query.from(PostComment.class);
Join<PostComment, Post> post = postComment.join(PostComment_.post);

query.multiselect(
    postComment.get(PostComment_.id).alias(PostComment_.ID),
    postComment.get(PostComment_.review).alias(PostComment_.REVIEW),
    post.get(Post_.title).alias(Post_.TITLE)
);

query.where(
    builder.and(
        builder.like(
            post.get(Post_.title),
            "%Java Persistence%"
        ),
        builder.equal(
            post.get(Post_.details).get(PostDetails_.CREATED_BY),
            "Vlad Mihalcea"
        )
    )
);

List<PostCommentSummary> comments = entityManager
    .createQuery(query)
    .unwrap(Query.class)
    .setResultTransformer(Transformers.aliasToBean(PostCommentSummary.class))
    .getResultList();

Cool, right?

How to compare two lists in python?

From your post I gather that you want to compare dates, not arrays. If this is the case, then use the appropriate object: a datetime object.

Please check the documentation for the datetime module. Dates are a tough cookie. Use reliable algorithms.

git pull remote branch cannot find remote ref

For me, it was because I was trying to pull a branch which was already deleted from Github.

You have not accepted the license agreements of the following SDK components

In linux

 1. Open a terminal
 2. Write: "cd $ANDROID_HOME/tools/bin (this path can be /home/your-user/Android/Sdk/tools/bin)"
 3. Write: "./sdkmanager --licenses"
 4. To accept All licenses listed, write: "y"
 5. Ready!

If your are building an app with Ionic Framework, just write again the command to build it.

How to get $HOME directory of different user in bash script?

So you want to:

  1. execute part of a bash script as a different user
  2. change to that user's $HOME directory

Inspired by this answer, here's the adapted version of your script:

#!/usr/bin/env bash

different_user=deploy

useradd -m -s /bin/bash "$different_user"

echo "Current user: $(whoami)"
echo "Current directory: $(pwd)"
echo

echo "Switching user to $different_user"
sudo -u "$different_user" -i /bin/bash - <<-'EOF'
    echo "Current user: $(id)"
    echo "Current directory: $(pwd)"
EOF
echo

echo "Switched back to $(whoami)"

different_user_home="$(eval echo ~"$different_user")"
echo "$different_user home directory: $different_user_home"

When you run it, you should get the following:

Current user: root
Current directory: /root

Switching user to deploy
Current user: uid=1003(deploy) gid=1003(deploy) groups=1003(deploy)
Current directory: /home/deploy

Switched back to root
deploy home directory: /home/deploy

How to increase MySQL connections(max_connections)?

I had the same issue and I resolved it with MySQL workbench, as shown in the attached screenshot:

  1. in the navigator (on the left side), under the section "management", click on "Status and System variables",
  2. then choose "system variables" (tab at the top),
  3. then search for "connection" in the search field,
  4. and 5. you will see two fields that need to be adjusted to fit your needs (max_connections and mysqlx_max_connections).

Hope that helps!

The system does not allow me to upload pictures, instead please click on this link and you can see my screenshot...

Turning off auto indent when pasting text into vim

I just put set clipboard=unnamed in my .vimrc. That makes the default paste buffer map to X's clipboard.

So, if I mark a bit of text in a terminal, I can simply press p to paste it in vim. Similarly, I can yank things in vim (e.g. YY to yank the current line into the buffer) and middle click in any window to paste it.

I don't know. I find it super convenient.

List passed by ref - help me explain this behaviour

While I agree with what everyone has said above. I have a different take on this code. Basically you're assigning the new list to the local variable myList not the global. if you change the signature of ChangeList(List myList) to private void ChangeList() you'll see the output of 3, 4.

Here's my reasoning... Even though list is passed by reference, think of it as passing a pointer variable by value When you call ChangeList(myList) you're passing the pointer to (Global)myList. Now this is stored in the (local)myList variable. So now your (local)myList and (global)myList are pointing to the same list. Now you do a sort => it works because (local)myList is referencing the original (global)myList Next you create a new list and assign the pointer to that your (local)myList. But as soon as the function exits the (local)myList variable is destroyed. HTH

class Test
{
    List<int> myList = new List<int>();
    public void TestMethod()
    {

        myList.Add(100);
        myList.Add(50);
        myList.Add(10);

        ChangeList();

        foreach (int i in myList)
        {
            Console.WriteLine(i);
        }
    }

    private void ChangeList()
    {
        myList.Sort();

        List<int> myList2 = new List<int>();
        myList2.Add(3);
        myList2.Add(4);

        myList = myList2;
    }
}

How should I edit an Entity Framework connection string?

Follow the next steps:

  1. Open the app.config and comment on the connection string (save file)
  2. Open the edmx (go to properties, the connection string should be blank), close the edmx file again
  3. Open the app.config and uncomment the connection string (save file)
  4. Open the edmx, go to properties, you should see the connection string uptated!!

How to see the values of a table variable at debug time in T-SQL?

In the Stored Procedure create a global temporary table ##temptable and write an insert query within your stored procedure which inserts the data in your table into this temporary table.

Once this is done you can check the content of the temporary table by opening a new query window. Just use "select * from ##temptable"

Sort matrix according to first column in R

If your data is in a matrix named foo, the line you would run is

foo.sorted=foo[order[foo[,1]]

Cannot open Windows.h in Microsoft Visual Studio

If you are targeting Windows XP (v140_xp), try installing Windows XP Support for C++.

Starting with Visual Studio 2012, the default toolset (v110) dropped support for Windows XP. As a result, a Windows.h error can occur if your project is targeting Windows XP with the default C++ packages.

Check which Windows SDK version is specified in your project's Platform Toolset. (Project ? Properties ? Configuration Properties ? General). If your Toolset ends in _xp, you'll need to install XP support.

Visual Studio: Project toolset

Open the Visual Studio Installer and click Modify for your version of Visual Studio. Open the Individual Components tab and scroll down to Compilers, build tools, and runtimes. Near the bottom, check Windows XP support for C++ and click Modify to begin installing.

Visual Studio Installer: XP Support for C++

See Also:

How do I use setsockopt(SO_REUSEADDR)?

After :

sockfd = socket(AF_INET, SOCK_STREAM, 0);
if (sockfd < 0) 
    error("ERROR opening socket");

You can add (with standard C99 compound literal support) :

if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &(int){1}, sizeof(int)) < 0)
    error("setsockopt(SO_REUSEADDR) failed");

Or :

int enable = 1;
if (setsockopt(sockfd, SOL_SOCKET, SO_REUSEADDR, &enable, sizeof(int)) < 0)
    error("setsockopt(SO_REUSEADDR) failed");

PHP CURL Enable Linux

if you have used curl above the page and below your html is present and unfortunately your html page is not able to view then just enable your curl. But in order to check CURL is enable or not in php you need to write following code:

echo 'Curl: ', function_exists('curl_version') ? 'Enabled' : 'Disabled';

How can I get city name from a latitude and longitude point?

Following Code Works Fine to Get City Name (Using Google Map Geo API) :

HTML

<p><button onclick="getLocation()">Get My Location</button></p>
<p id="demo"></p>
<script src="http://maps.google.com/maps/api/js?key=YOUR_API_KEY"></script>

SCRIPT

var x=document.getElementById("demo");
function getLocation(){
    if (navigator.geolocation){
        navigator.geolocation.getCurrentPosition(showPosition,showError);
    }
    else{
        x.innerHTML="Geolocation is not supported by this browser.";
    }
}

function showPosition(position){
    lat=position.coords.latitude;
    lon=position.coords.longitude;
    displayLocation(lat,lon);
}

function showError(error){
    switch(error.code){
        case error.PERMISSION_DENIED:
            x.innerHTML="User denied the request for Geolocation."
        break;
        case error.POSITION_UNAVAILABLE:
            x.innerHTML="Location information is unavailable."
        break;
        case error.TIMEOUT:
            x.innerHTML="The request to get user location timed out."
        break;
        case error.UNKNOWN_ERROR:
            x.innerHTML="An unknown error occurred."
        break;
    }
}

function displayLocation(latitude,longitude){
    var geocoder;
    geocoder = new google.maps.Geocoder();
    var latlng = new google.maps.LatLng(latitude, longitude);

    geocoder.geocode(
        {'latLng': latlng}, 
        function(results, status) {
            if (status == google.maps.GeocoderStatus.OK) {
                if (results[0]) {
                    var add= results[0].formatted_address ;
                    var  value=add.split(",");

                    count=value.length;
                    country=value[count-1];
                    state=value[count-2];
                    city=value[count-3];
                    x.innerHTML = "city name is: " + city;
                }
                else  {
                    x.innerHTML = "address not found";
                }
            }
            else {
                x.innerHTML = "Geocoder failed due to: " + status;
            }
        }
    );
}

Python constructor and default value

I would try:

self.wordList = list(wordList)

to force it to make a copy instead of referencing the same object.

Mysql: Setup the format of DATETIME to 'DD-MM-YYYY HH:MM:SS' when creating a table

"MySQL retrieves and displays DATETIME values in 'YYYY-MM-DD HH:MM:SS' format." This is from mysql site. You can store only this type, but you can use one of the many time format functions to change it, when you need to display it.

Mysql Time and Date functions

For example, one of those functions is the DATE_FORMAT, which can be used like so:

SELECT DATE_FORMAT(column_name, '%m/%d/%Y %H:%i') FROM tablename

Java random numbers using a seed

That's the principle of a Pseudo-RNG. The numbers are not really random. They are generated using a deterministic algorithm, but depending on the seed, the sequence of generated numbers vary. Since you always use the same seed, you always get the same sequence.

Disable F5 and browser refresh using JavaScript

Update A recent comment claims this doesn't work in the new Chrome ... As shown in jsFiddle, and tested on my personal site, this method still works as of Chrome ver 26.0.1410.64 m

This is REALLY easy in jQuery by the way:

jsFiddle

// slight update to account for browsers not supporting e.which
function disableF5(e) { if ((e.which || e.keyCode) == 116) e.preventDefault(); };
// To disable f5
    /* jQuery < 1.7 */
$(document).bind("keydown", disableF5);
/* OR jQuery >= 1.7 */
$(document).on("keydown", disableF5);

// To re-enable f5
    /* jQuery < 1.7 */
$(document).unbind("keydown", disableF5);
/* OR jQuery >= 1.7 */
$(document).off("keydown", disableF5);

On a side note: This only disables the f5 button on the keyboard. To truly disable refresh you must use a server side script to check for page state changes. Can't say I really know how to do this as I haven't done it yet.

On the software site that I work at, we use my disableF5 function in conjunction with Codeigniter's session data. For instance, there is a lock button which will lock the screen and prompt a password dialog. The function "disableF5" is quick and easy and keeps that button from doing anything. However, to prevent the mouse-click on refresh button, a couple things take place.

  1. When lock is clicked, user session data has a variable called "locked" that becomes TRUE
  2. When the refresh button is clicked, on the master page load method is a check against session data for "locked", if TRUE, then we simple don't allow the redirect and the page never changes, regardless of requested destination

TIP: Try using a server-set cookie, such as PHP's $_SESSION, or even .Net's Response.Cookies, to maintain "where" your client is in your site. This is the more Vanilla way to do what I do with CI's Session class. The big difference being that CI uses a Table in your DB, whereas these vanilla methods store an editable cookie in the client. The downside though, is a user can clear its cookies.

How do I copy an entire directory of files into an existing directory using Python?

Here is a version inspired by this thread that more closely mimics distutils.file_util.copy_file.

updateonly is a bool if True, will only copy files with modified dates newer than existing files in dst unless listed in forceupdate which will copy regardless.

ignore and forceupdate expect lists of filenames or folder/filenames relative to src and accept Unix-style wildcards similar to glob or fnmatch.

The function returns a list of files copied (or would be copied if dryrun if True).

import os
import shutil
import fnmatch
import stat
import itertools

def copyToDir(src, dst, updateonly=True, symlinks=True, ignore=None, forceupdate=None, dryrun=False):

    def copySymLink(srclink, destlink):
        if os.path.lexists(destlink):
            os.remove(destlink)
        os.symlink(os.readlink(srclink), destlink)
        try:
            st = os.lstat(srclink)
            mode = stat.S_IMODE(st.st_mode)
            os.lchmod(destlink, mode)
        except OSError:
            pass  # lchmod not available
    fc = []
    if not os.path.exists(dst) and not dryrun:
        os.makedirs(dst)
        shutil.copystat(src, dst)
    if ignore is not None:
        ignorepatterns = [os.path.join(src, *x.split('/')) for x in ignore]
    else:
        ignorepatterns = []
    if forceupdate is not None:
        forceupdatepatterns = [os.path.join(src, *x.split('/')) for x in forceupdate]
    else:
        forceupdatepatterns = []
    srclen = len(src)
    for root, dirs, files in os.walk(src):
        fullsrcfiles = [os.path.join(root, x) for x in files]
        t = root[srclen+1:]
        dstroot = os.path.join(dst, t)
        fulldstfiles = [os.path.join(dstroot, x) for x in files]
        excludefiles = list(itertools.chain.from_iterable([fnmatch.filter(fullsrcfiles, pattern) for pattern in ignorepatterns]))
        forceupdatefiles = list(itertools.chain.from_iterable([fnmatch.filter(fullsrcfiles, pattern) for pattern in forceupdatepatterns]))
        for directory in dirs:
            fullsrcdir = os.path.join(src, directory)
            fulldstdir = os.path.join(dstroot, directory)
            if os.path.islink(fullsrcdir):
                if symlinks and dryrun is False:
                    copySymLink(fullsrcdir, fulldstdir)
            else:
                if not os.path.exists(directory) and dryrun is False:
                    os.makedirs(os.path.join(dst, dir))
                    shutil.copystat(src, dst)
        for s,d in zip(fullsrcfiles, fulldstfiles):
            if s not in excludefiles:
                if updateonly:
                    go = False
                    if os.path.isfile(d):
                        srcdate = os.stat(s).st_mtime
                        dstdate = os.stat(d).st_mtime
                        if srcdate > dstdate:
                            go = True
                    else:
                        go = True
                    if s in forceupdatefiles:
                        go = True
                    if go is True:
                        fc.append(d)
                        if not dryrun:
                            if os.path.islink(s) and symlinks is True:
                                copySymLink(s, d)
                            else:
                                shutil.copy2(s, d)
                else:
                    fc.append(d)
                    if not dryrun:
                        if os.path.islink(s) and symlinks is True:
                            copySymLink(s, d)
                        else:
                            shutil.copy2(s, d)
    return fc

jQuery jump or scroll to certain position, div or target on the page from button onclick

I would style a link to look like a button, because that way there is a no-js fallback.


So this is how you could animate the jump using jquery. No-js fallback is a normal jump without animation.

Original example:

jsfiddle

_x000D_
_x000D_
$(document).ready(function() {_x000D_
  $(".jumper").on("click", function( e ) {_x000D_
_x000D_
    e.preventDefault();_x000D_
_x000D_
    $("body, html").animate({ _x000D_
      scrollTop: $( $(this).attr('href') ).offset().top _x000D_
    }, 600);_x000D_
_x000D_
  });_x000D_
});
_x000D_
#long {_x000D_
  height: 500px;_x000D_
  background-color: blue;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<!-- Links that trigger the jumping -->_x000D_
<a class="jumper" href="#pliip">Pliip</a>_x000D_
<a class="jumper" href="#ploop">Ploop</a>_x000D_
<div id="long">...</div>_x000D_
<!-- Landing elements -->_x000D_
<div id="pliip">pliip</div>_x000D_
<div id="ploop">ploop</div>
_x000D_
_x000D_
_x000D_


New example with actual button styles for the links, just to prove a point.

Everything is essentially the same, except that I changed the class .jumper to .button and I added css styling to make the links look like buttons.

Button styles example

How do I find out what all symbols are exported from a shared object?

Usually, you would also have a header file that you include in your code to access the symbols.

Passing a string with spaces as a function argument in bash

You could have an extension of this problem in case of your initial text was set into a string type variable, for example:

function status(){    
  if [ $1 != "stopped" ]; then
     artist="ABC";
     track="CDE";
     album="DEF";
     status_message="The current track is $track at $album by $artist";
     echo $status_message;
     read_status $1 "$status_message";
  fi
}

function read_status(){
  if [ $1 != "playing" ]; then
    echo $2
  fi
}

In this case if you don't pass the status_message variable forward as string (surrounded by "") it will be split in a mount of different arguments.

"$variable": The current track is CDE at DEF by ABC

$variable: The

Removing cordova plugins from the project

If the above solution didn't work and you got any unhandled promise rejection then try to follow steps :

  1. Clean the Cordova project

    cordova clean

    1. Remove platform

cordova platform remove android/ios

  1. Then remove plugin

cordova plugin remove

  1. add platforms and run the project It worked for me.

How to run a SQL query on an Excel table?

You can do this natively as follows:

  1. Select the table and use Excel to sort it on Last Name
  2. Create a 2-row by 1-column advanced filter criteria, say in E1 and E2, where E1 is empty and E2 contains the formula =C6="" where C6 is the first data cell of the phone number column.
  3. Select the table and use advanced filter, copy to a range, using the criteria range in E1:E2 and specify where you want to copy the output to

If you want to do this programmatically I suggest you use the Macro Recorder to record the above steps and look at the code.

vertical-align image in div

Old question but nowadays CSS3 makes vertical alignment really simple!

Just add to the <div> this css:

display:flex;
align-items:center;
justify-content:center;

JSFiddle demo

Live Example:

_x000D_
_x000D_
.img_thumb {_x000D_
    float: left;_x000D_
    height: 120px;_x000D_
    margin-bottom: 5px;_x000D_
    margin-left: 9px;_x000D_
    position: relative;_x000D_
    width: 147px;_x000D_
    background-color: rgba(0, 0, 0, 0.5);_x000D_
    border-radius: 3px;_x000D_
    display:flex;_x000D_
    align-items:center;_x000D_
    justify-content:center;_x000D_
}
_x000D_
<div class="img_thumb">_x000D_
    <a class="images_class" href="http://i.imgur.com/2FMLuSn.jpg" rel="images">_x000D_
       <img src="http://i.imgur.com/2FMLuSn.jpg" title="img_title" alt="img_alt" />_x000D_
    </a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What is SuppressWarnings ("unchecked") in Java?

The SuppressWarning annotation is used to suppress compiler warnings for the annotated element. Specifically, the unchecked category allows suppression of compiler warnings generated as a result of unchecked type casts.

Count immediate child div elements using jQuery

$("#foo > div") 

selects all divs that are immediate descendants of #foo
once you have the set of children you can either use the size function:

$("#foo > div").size()

or you can use

$("#foo > div").length

Both will return you the same result

Object creation on the stack/heap?

C++ has Automatic variables - not Stack variables.

Automatic variable means that C++ compiler handles memory allocation / free by itself. C++ can automatically handle objects of any class - no matter whether it has dynamically allocated members or not. It's achieved by strong guarantee of C++ that object's destructor will be called automatically when execution is going out of scope where automatic variable was declared. Inside of a C++ object can be a lot of dynamic allocations with new in constructor, and when such an object is declared as an automatic variable - all dynamic allocations will be performed, and freed then in destructor.

Stack variables in C can't be dynamically allocated. Stack in C can store pointers, or fixed arrays or structs - all of fixed size, and these things are being allocated in memory in linear order. When a C program frees a stack variable - it just moves stack pointer back and nothing more.

Even though C++ programs can use Stack memory segment for storing primitive types, function's args, or other, - it's all decided by C++ compiler, not by program developer. Thus, it is conceptually wrong to equal C++ automatic variables and C stack variables.

Update Query with INNER JOIN between tables in 2 different databases on 1 server

Should look like this:

UPDATE DHE.dbo.tblAccounts
   SET DHE.dbo.tblAccounts.ControllingSalesRep = 
       DHE_Import.dbo.tblSalesRepsAccountsLink.SalesRepCode
  from DHE.dbo.tblAccounts 
     INNER JOIN DHE_Import.dbo.tblSalesRepsAccountsLink 
        ON DHE.dbo.tblAccounts.AccountCode =
           DHE_Import.tblSalesRepsAccountsLink.AccountCode 

Update table is repeated in FROM clause.

no sqljdbc_auth in java.library.path

The error is clear, isn't it?

You've not added the path where sqljdbc_auth.dll is present. Find out in the system where the DLL is and add that to your classpath.

And if that also doesn't work, add the folder where the DLL is present (I'm assuming \Microsoft SQL Server JDBC Driver 3.0\sqljdbc_3.0\enu\auth\x86) to your PATH variable.

Again if you're going via ant or cmd you have to explicitly mention the path using -Djava.library.path=[path to MS_SQL_AUTH_DLL]

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

To compile you could just initiate a shell call to the csc compiler. You may have a headache trying to keep your paths and switches straight but it certainly can be done.

C# Corner Shell Examples

EDIT: Or better yet, use the CodeDOM as Noldorin suggested...

Python strftime - date without leading 0?

import datetime
now = datetime.datetime.now()
print now.strftime("%b %_d")

Query to get the names of all tables in SQL Server 2008 Database

To get the fields info too, you can use the following:

SELECT TABLE_SCHEMA, TABLE_NAME, 
       COLUMN_NAME, substring(DATA_TYPE, 1,1) AS DATA_TYPE
FROM information_schema.COLUMNS 
WHERE TABLE_SCHEMA NOT IN("information_schema", "mysql", "performance_schema") 
ORDER BY TABLE_SCHEMA, TABLE_NAME, ORDINAL_POSITION

Adding Google Play services version to your app's manifest?

In my case i had to install google repository from the SDK manager.

What do <o:p> elements do anyway?

Couldn't find any official documentation (no surprise there) but according to this interesting article, those elements are injected in order to enable Word to convert the HTML back to fully compatible Word document, with everything preserved.

The relevant paragraph:

Microsoft added the special tags to Word's HTML with an eye toward backward compatibility. Microsoft wanted you to be able to save files in HTML complete with all of the tracking, comments, formatting, and other special Word features found in traditional DOC files. If you save a file in HTML and then reload it in Word, theoretically you don't loose anything at all.

This makes lots of sense.

For your specific question.. the o in the <o:p> means "Office namespace" so anything following the o: in a tag means "I'm part of Office namespace" - in case of <o:p> it just means paragraph, the equivalent of the ordinary <p> tag.

I assume that every HTML tag has its Office "equivalent" and they have more.

CASE .. WHEN expression in Oracle SQL

You could use an IN clause

Something like

SELECT
  status,
  CASE
    WHEN STATUS IN('a1','a2','a3')
    THEN 'Active'
    WHEN STATUS = 'i'
    THEN 'Inactive'
    WHEN STATUS = 't'
    THEN 'Terminated'
  END AS STATUSTEXT
FROM
  STATUS

Have a look at this demo

SQL Fiddle DEMO

How do I import a .sql file in mysql database using PHP?

Solution special chars

 $link=mysql_connect($dbHost, $dbUser, $dbPass) OR die('connecting to host: '.$dbHost.' failed: '.mysql_error());
mysql_select_db($dbName) OR die('select db: '.$dbName.' failed: '.mysql_error());

//charset important
mysql_set_charset('utf8',$link);

How to automatically start a service when running a docker container?

In your Dockerfile, add at the last line

ENTRYPOINT service ssh restart && bash

It works for me

And this is the result:

root@ubuntu:/home/vagrant/docker/add# docker run -i -t ubuntu
 * Restarting OpenBSD Secure Shell server sshd   [ OK ]                                                                      
root@dccc354e422e:~# service ssh status
 * sshd is running

How to export data to an excel file using PHPExcel

If you've copied this directly, then:

->setCellValue('B2', Ackermann') 

should be

->setCellValue('B2', 'Ackermann') 

In answer to your question:

Get the data that you want from limesurvey, and use setCellValue() to store those data values in the cells where you want to store it.

The Quadratic.php example file in /Tests might help as a starting point: it takes data from an input form and sets it to cells in an Excel workbook.

EDIT

An extremely simplistic example:

// Create your database query
$query = "SELECT * FROM myDataTable";  

// Execute the database query
$result = mysql_query($query) or die(mysql_error());

// Instantiate a new PHPExcel object
$objPHPExcel = new PHPExcel(); 
// Set the active Excel worksheet to sheet 0
$objPHPExcel->setActiveSheetIndex(0); 
// Initialise the Excel row number
$rowCount = 1; 
// Iterate through each result from the SQL query in turn
// We fetch each database result row into $row in turn
while($row = mysql_fetch_array($result)){ 
    // Set cell An to the "name" column from the database (assuming you have a column called name)
    //    where n is the Excel row number (ie cell A1 in the first row)
    $objPHPExcel->getActiveSheet()->SetCellValue('A'.$rowCount, $row['name']); 
    // Set cell Bn to the "age" column from the database (assuming you have a column called age)
    //    where n is the Excel row number (ie cell A1 in the first row)
    $objPHPExcel->getActiveSheet()->SetCellValue('B'.$rowCount, $row['age']); 
    // Increment the Excel row counter
    $rowCount++; 
} 

// Instantiate a Writer to create an OfficeOpenXML Excel .xlsx file
$objWriter = new PHPExcel_Writer_Excel2007($objPHPExcel); 
// Write the Excel file to filename some_excel_file.xlsx in the current directory
$objWriter->save('some_excel_file.xlsx'); 

EDIT #2

Using your existing code as the basis

// Instantiate a new PHPExcel object 
$objPHPExcel = new PHPExcel();  
// Set the active Excel worksheet to sheet 0 
$objPHPExcel->setActiveSheetIndex(0);  
// Initialise the Excel row number 
$rowCount = 1;  

//start of printing column names as names of MySQL fields  
$column = 'A';
for ($i = 1; $i < mysql_num_fields($result); $i++)  
{
    $objPHPExcel->getActiveSheet()->setCellValue($column.$rowCount, mysql_field_name($result,$i));
    $column++;
}
//end of adding column names  

//start while loop to get data  
$rowCount = 2;  
while($row = mysql_fetch_row($result))  
{  
    $column = 'A';
    for($j=1; $j<mysql_num_fields($result);$j++)  
    {  
        if(!isset($row[$j]))  
            $value = NULL;  
        elseif ($row[$j] != "")  
            $value = strip_tags($row[$j]);  
        else  
            $value = "";  

        $objPHPExcel->getActiveSheet()->setCellValue($column.$rowCount, $value);
        $column++;
    }  
    $rowCount++;
} 


// Redirect output to a client’s web browser (Excel5) 
header('Content-Type: application/vnd.ms-excel'); 
header('Content-Disposition: attachment;filename="Limesurvey_Results.xls"'); 
header('Cache-Control: max-age=0'); 
$objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5'); 
$objWriter->save('php://output');

Is there any way to debug chrome in any IOS device

If you don't need full debugging support, you can now view JavaScript console logs directly within Chrome for iOS at chrome://inspect.

https://blog.chromium.org/2019/03/debugging-websites-in-chrome-for-ios.html

Chrome for iOS Console

getString Outside of a Context or Activity

If you have a class that you use in an activity and you want to have access the ressource in that class, I recommend you to define a context as a private variable in class and initial it in constructor:

public class MyClass (){
    private Context context;

    public MyClass(Context context){
       this.context=context;
    }

    public testResource(){
       String s=context.getString(R.string.testString).toString();
    }
}

Making an instant of class in your activity:

MyClass m=new MyClass(this);

Change Bootstrap input focus blue glow

For the input border before the focus. You can specify your favorite color you want to use and other css like padding etc


.input {
    padding: 6px 190px 6px 15px;
    outline: #2a65ea auto 105px ;
}

When we focus on input. You can specify your favorite color outline you wish


.input:focus{
    box-shadow: none;
    border-color: none;
    outline: lightgreen auto 5px ;
}

Should you commit .gitignore into the Git repos?

Committing .gitignore can be very useful but you want to make sure you don't modify it too much thereafter especially if you regularly switch between branches. If you do you might get cases where files are ignored in a branch and not in the other, forcing you to go manually delete or rename files in your work directory because a checkout failed as it would overwrite a non-tracked file.

Therefore yes, do commit your .gitignore, but not before you are reasonably sure it won't change that much thereafter.

Manage toolbar's navigation and back button from fragment in android

The easiest solution I found was to simply put that in your fragment :

androidx.appcompat.widget.Toolbar toolbar = getActivity().findViewById(R.id.toolbar);
    toolbar.setNavigationOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            NavController navController = Navigation.findNavController(getActivity(), 
R.id.nav_host_fragment);
            navController.navigate(R.id.action_position_to_destination);
        }
    });

Personnaly I wanted to go to another page but of course you can replace the 2 lines in the onClick method by the action you want to perform.

How do you perform wireless debugging in Xcode 9 with iOS 11, Apple TV 4K, etc?

Try this:

1) Plug your iOS device into your Mac using a lightning cable. You may need to select to Trust This Computer on your device.

2) Open Xcode and go to Window > Devices and Simulators.

3) Select your device and then select the Connect via network checkbox to pair your device.

4) Run your project after removing your lighting cable.

Anonymous method in Invoke call

Because Invoke/BeginInvoke accepts Delegate (rather than a typed delegate), you need to tell the compiler what type of delegate to create ; MethodInvoker (2.0) or Action (3.5) are common choices (note they have the same signature); like so:

control.Invoke((MethodInvoker) delegate {this.Text = "Hi";});

If you need to pass in parameters, then "captured variables" are the way:

string message = "Hi";
control.Invoke((MethodInvoker) delegate {this.Text = message;});

(caveat: you need to be a bit cautious if using captures async, but sync is fine - i.e. the above is fine)

Another option is to write an extension method:

public static void Invoke(this Control control, Action action)
{
    control.Invoke((Delegate)action);
}

then:

this.Invoke(delegate { this.Text = "hi"; });
// or since we are using C# 3.0
this.Invoke(() => { this.Text = "hi"; });

You can of course do the same with BeginInvoke:

public static void BeginInvoke(this Control control, Action action)
{
    control.BeginInvoke((Delegate)action);
}

If you can't use C# 3.0, you could do the same with a regular instance method, presumably in a Form base-class.

jQuery returning "parsererror" for ajax request

I have encountered such error but after modifying my response before sending it to the client it worked fine.

//Server side
response = JSON.stringify('{"status": {"code": 200},"result": '+ JSON.stringify(result)+'}');
res.send(response);  // Sending to client

//Client side
success: function(res, status) {
    response = JSON.parse(res); // Getting as expected
    //Do something
}

Forbidden :You don't have permission to access /phpmyadmin on this server

With the latest version of phpmyadmin 5.0.2+ at least

Check that the actual installation was completed correctly,

Mine had been copied over into a sub folder on a linux machine rather that being at the

/usr/share/phpmyadmin/

Escape dot in a regex range

If you using JavaScript to test your Regex, try \\. instead of \..

It acts on the same way because JS remove first backslash.

vi/vim editor, copy a block (not usual action)

Another option which may be easier to remember would be to place marks on the two lines with ma and mb, then run :'a,'byank.

Many different ways to accomplish this task, just offering another.

Sum columns with null values in oracle

The other answers regarding the use of nvl() are correct however none seem to address a more salient point:

Should you even have NULLs in this column?

Do they have a meaning other than 0?

This seems like a case where you should have a NOT NULL DEFAULT 0 on th ecolumn

converting a base 64 string to an image and saving it

I would suggest via Bitmap:

public void SaveImage(string base64)
{
    using (MemoryStream ms = new MemoryStream(Convert.FromBase64String(base64)))
    {
        using (Bitmap bm2 = new Bitmap(ms))
        {
            bm2.Save("SavingPath" + "ImageName.jpg");
        }
    }
}

How to control the line spacing in UILabel

I've found a way where you can set the real line height (not a factor) and it even renders live in Interface Builder. Just follow the instructions below. Code is written in Swift 4.


Step #1: Create a file named DesignableLabel.swift and insert the following code:

import UIKit

@IBDesignable
class DesignableLabel: UILabel {
    @IBInspectable var lineHeight: CGFloat = 20 {
        didSet {
            let paragraphStyle = NSMutableParagraphStyle()
            paragraphStyle.minimumLineHeight = lineHeight
            paragraphStyle.maximumLineHeight = lineHeight
            paragraphStyle.alignment = self.textAlignment

            let attrString = NSMutableAttributedString(string: text!)
            attrString.addAttribute(NSAttributedStringKey.font, value: font, range: NSRange(location: 0, length: attrString.length))
            attrString.addAttribute(NSAttributedStringKey.paragraphStyle, value: paragraphStyle, range: NSRange(location: 0, length: attrString.length))
            attributedText = attrString
        }
    }
}

Step #2: Place a UILabel into a Storyboard/XIB and set its class to DesignableLabel. Wait for your project to build (build must succeed!).

Specifying the class to your UILabel


Step 3: Now you should see a new property in the properties pane named "Line Height". Just set the value you like and you should see the results immediately!

Set Line Height in properties

When running WebDriver with Chrome browser, getting message, "Only local connections are allowed" even though browser launches properly

Not necessarily the best practice, but my environment was a local network with several machines which needed access to the selenium.

When running the chromedriver, you can pass through a param like so :

chromedriver --whitelisted-ips=""

This will basically whitelist all IP's, not always an ideal solution of course and be careful with it for production enviornments, but you should be presented with a verbose warning :

Starting ChromeDriver 2.16.333244 (15fb740a49ab3660b8f8d496cfab2e4d37c7e6ca) on port 9515 All remote connections are allowed. Use a whitelist instead!

A work-around at best, but it works.

Relative check-in

Allow click on twitter bootstrap dropdown toggle link?

Here's a little hack that switched from data-hover to data-toggle depending the screen width:

/**
 * Bootstrap nav menu hack
 */
$(window).on('load', function () {
    // On page load
    if ($(window).width() < 768) {
        $('.navbar-nav > li > .dropdown-toggle').removeAttr('data-hover').attr('data-toggle', 'dropdown');
    }

    // On window resize
    $(window).resize(function () {
        if ($(window).width() < 768) {
            $('.navbar-nav > li > .dropdown-toggle').removeAttr('data-hover').attr('data-toggle', 'dropdown');
        } else {
            $('.navbar-nav > li > .dropdown-toggle').removeAttr('data-toggle').attr('data-hover', 'dropdown');
        }
    });
});

Maven with Eclipse Juno

This is what I was getting when tried to install m2e from Eclipse Market place. I am using Eclipse Juno.

Cannot complete the install because one or more required items could not be found. Software being installed: m2e - Maven Integration for Eclipse (includes Incubating components) 1.5.0.20140606-0033 (org.eclipse.m2e.feature.feature.group 1.5.0.20140606-0033) Missing requirement: Maven Integration for Eclipse 1.5.0.20140606-0033 (org.eclipse.m2e.core 1.5.0.20140606-0033) requires 'bundle com.google.guava [14.0.1,16.0.0)' but it could not be found Cannot satisfy dependency: From: m2e - Maven Integration for Eclipse (includes Incubating components) 1.5.0.20140606-0033 (org.eclipse.m2e.feature.feature.group 1.5.0.20140606-0033) To: org.eclipse.m2e.core [1.5.0.20140606-0033]

However, the below links is perfect, it works for me.

http://marketplace.eclipse.org/content/maven-integration-eclipse-wtp-juno-0

Regards, Bilal

AngularJS. How to call controller function from outside of controller component

Call Angular Scope function from outside the controller.

// Simply Use "Body" tag, Don't try/confuse using id/class.

var scope = angular.element('body').scope();             
scope.$apply(function () {scope.YourAngularJSFunction()});      

Removing padding gutter from grid columns in Bootstrap 4

You should use built-in bootstrap4 spacing classes for customizing the spacing of elements, that's more convenient method .

Getting last day of the month in a given string date

The simplest way is to construt a new GregorianCalendar instance, see below:

Calendar cal = new GregorianCalendar(2013, 5, 0);
Date date = cal.getTime();
DateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
System.out.println("Date : " + sdf.format(date));

Output:

Date : 2013-05-31

Attention:

month the value used to set the MONTH calendar field in the calendar. Month value is 0-based e.g. 0 for January.

How to force div to appear below not next to another?

#map {
  float: right;
  width: 700px;
  height: 500px;
}
#list {
  float:left;
  width:200px;
  background: #eee;
  list-style: none;
  padding: 0;
}
#similar {
  float: left;
  clear: left;
  width: 200px;
  background: #000;
}

LaTex left arrow over letter in math mode

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

\overleftarrow{blahblahblah}

LaTeX output

Oracle "ORA-01008: not all variables bound" Error w/ Parameters

The ODP.Net provider from oracle uses bind by position as default. To change the behavior to bind by name. Set property BindByName to true. Than you can dismiss the double definition of parameters.

using(OracleCommand cmd = con.CreateCommand()) {
    ...
    cmd.BindByName = true;
    ...
}

Remove trailing newline from the elements of a string list

list comprehension? [x.strip() for x in lst]

How do I perform a Perl substitution on a string while keeping the original?

If you write Perl with use strict;, then you'll find that the one line syntax isn't valid, even when declared.

With:

my ($newstring = $oldstring) =~ s/foo/bar/;

You get:

Can't declare scalar assignment in "my" at script.pl line 7, near ") =~"
Execution of script.pl aborted due to compilation errors.

Instead, the syntax that you have been using, while a line longer, is the syntactically correct way to do it with use strict;. For me, using use strict; is just a habit now. I do it automatically. Everyone should.

#!/usr/bin/env perl -wT

use strict;

my $oldstring = "foo one foo two foo three";
my $newstring = $oldstring;
$newstring =~ s/foo/bar/g;

print "$oldstring","\n";
print "$newstring","\n";

Can't install gems on OS X "El Capitan"

As it have been said, the issue comes from a security function of Mac OSX since "El Capitan".

Using the default system Ruby, the install process happens in the /Library/Ruby/Gems/2.0.0 directory which is not available to the user and gives the error.

You can have a look to your Ruby environments parameters with the command

$ gem env

There is an INSTALLATION DIRECTORY and a USER INSTALLATION DIRECTORY. To use the user installation directory instead of the default installation directory, you can use --user-install parameter instead as using sudo which is never a recommanded way of doing.

$ gem install myGemName --user-install

There should not be any rights issue anymore in the process. The gems are then installed in the user directory : ~/.gem/Ruby/2.0.0/bin

But to make the installed gems available, this directory should be available in your path. According to the Ruby’s faq, you can add the following line to your ~/.bash_profile or ~/.bashrc

if which ruby >/dev/null && which gem >/dev/null; then
    PATH="$(ruby -rubygems -e 'puts Gem.user_dir')/bin:$PATH"
fi

Then close and reload your terminal or reload your .bash_profile or .bashrc (. ~/.bash_profile)

Android Fragment no view found for ID?

In my case. I have an Activity with serveral Fragments some time I need to recreate Fragments when

  • language is change
  • fragment layout some need some not need or content change need to recreate
  • other changes
  • I clear all Fragments and set all to null in activity but Fragment already create itself, while it host activty is bean set null, so before call Fragment view check it null

    for example

    Activity{
        fragment
        recreate{
           fragment = null then new instance
        }
    
    }
    
    Fragment{
        if((activity).fragment != null) {
           findViewById()
        }
    
    }
    

    Using a batch to copy from network drive to C: or D: drive

    Most importantly you need to mount the drive

    net use z: \\yourserver\sharename
    

    Of course, you need to make sure that the account the batch file runs under has permission to access the share. If you are doing this by using a Scheduled Task, you can choose the account by selecting the task, then:

    • right click Properties
    • click on General tab
    • change account under

    "When running the task, use the following user account:" That's on Windows 7, it might be slightly different on different versions of Windows.

    Then run your batch script with the following changes

    copy "z:\FolderName" "C:\TEST_BACKUP_FOLDER"
    

    How can I upload fresh code at github?

    You can create GitHub repositories via the command line using their Repositories API (http://develop.github.com/p/repo.html)

    Check Creating github repositories with command line | Do it yourself Android for example usage.

    How do I compare two columns for equality in SQL Server?

    Regarding David Elizondo's answer, this can give false positives. It also does not give zeroes where the values don't match.

    Code

    DECLARE @t1 TABLE (
        ColID   int     IDENTITY,
        Col2    int
    )
    
    DECLARE @t2 TABLE (
        ColID   int     IDENTITY,
        Col2    int
    )
    
    INSERT INTO @t1 (Col2) VALUES (123)
    INSERT INTO @t1 (Col2) VALUES (234)
    INSERT INTO @t1 (Col2) VALUES (456)
    INSERT INTO @t1 (Col2) VALUES (1)
    
    INSERT INTO @t2 (Col2) VALUES (123)
    INSERT INTO @t2 (Col2) VALUES (345)
    INSERT INTO @t2 (Col2) VALUES (456)
    INSERT INTO @t2 (Col2) VALUES (2)
    
    SELECT
        t1.Col2 AS t1Col2,
        t2.Col2 AS t2Col2,
        ISNULL(NULLIF(t1.Col2, t2.Col2), 1) AS MyDesiredResult
    FROM @t1 AS t1
    JOIN @t2 AS t2 ON t1.ColID = t2.ColID
    

    Results

         t1Col2      t2Col2 MyDesiredResult
    ----------- ----------- ---------------
            123         123               1
            234         345             234 <- Not a zero
            456         456               1
              1           2               1 <- Not a match
    

    Java 8 Lambda filter by Lists

    I would like share an example to understand the usage of stream().filter

    Code Snippet: Sample program to identify even number.

    import java.util.ArrayList;
    import java.util.List;
    import java.util.stream.Collectors;
    
    public void fetchEvenNumber(){
            List<Integer> numberList = new ArrayList<>();
            numberList.add(10);
            numberList.add(11);
            numberList.add(12);
            numberList.add(13);
            numberList.add(14);
            numberList.add(15);
    
            List<Integer> evenNumberListObj = numberList.stream().filter(i -> i%2 == 0).collect(Collectors.toList());
            System.out.println(evenNumberListObj);
    }
    

    Output will be : [10, 12, 14]

    List evenNumberListObj = numberList.stream().filter(i -> i%2 == 0).collect(Collectors.toList());

    numberList: it is an ArrayList object contains list of numbers.

    java.util.Collection.stream() : stream() will get the stream of collection, which will return the Stream of Integer.

    filter: Returns a stream that match the given predicate. i.e based on given condition (i -> i%2 != 0) returns the matching stream.

    collect: whatever the stream of Integer filter based in the filter condition, those integer will be put in a list.

    How to close a Java Swing application from the code

    Try:

    System.exit(0);
    

    Crude, but effective.

    What is the benefit of zerofill in MySQL?

    If you specify ZEROFILL for a numeric column, MySQL automatically adds the UNSIGNED attribute to the column.

    Numeric data types that permit the UNSIGNED attribute also permit SIGNED. However, these data types are signed by default, so the SIGNED attribute has no effect.

    Above description is taken from MYSQL official website.

    Listen to changes within a DIV and act accordingly

    http://api.jquery.com/change/

    change does only work on input form elements.

    you could just trigger a function after your XML / XSL transformation or make a listener:

    var html = $('#laneconfigdisplay').html()
    setInterval(function(){ if($('#laneconfigdisplay').html() != html){ alert('woo'); html = $('#laneconfigdisplay').html() } }, 10000) //checks your content box all 10 seconds and triggers alert when content has changed...
    

    How to solve SyntaxError on autogenerated manage.py?

    For running Python version 3, you need to use python3 instead of python.

    So, the final command will be:

    python3 manage.py runserver
    

    What does the SQL Server Error "String Data, Right Truncation" mean and how do I fix it?

    Either the parameter supplied for ZIP_CODE is larger (in length) than ZIP_CODEs column width or the parameter supplied for CITY is larger (in length) than CITYs column width.

    It would be interesting to know the values supplied for the two ? placeholders.

    How do I show/hide a UIBarButtonItem?

    I worked with xib and with UIToolbar. BarButtonItem was created in xib file. I created IBOutlet for BarButtonItem. And I used this code to hide my BarButtonItem

     self.myBarButtonItem.enabled = NO;
     self.myBarButtonItem.title =  nil;
    

    this helped me.

    sql select with column name like

    You need to use view INFORMATION_SCHEMA.COLUMNS

    select COLUMN_NAME from INFORMATION_SCHEMA.COLUMNS where TABLE_NAME = my_table_name AND COLUMN_NAME like 'a%'
    

    TO inline rows you can use PIVOT and for execution EXEC() function.

    Make xargs handle filenames that contain spaces

    Given the specific title of this post, here's my suggestion:

    ls | grep ' ' | tr ' ' '<' | sed 's|<|\\ |g'
    

    The idea is to convert blanks to any unique character, like '<', and then change that into '\ ', a backslash followed by a blank. You can then pipe that into any command you like, such as:

    ls | grep ' ' | tr ' ' '<' | sed 's|<|\\ |g' | xargs -L1 GetFileInfo
    

    The key here lies in the 'tr' and 'sed' commands; and you can use any character besides '<', such as '?' or even a tab-character.

    How to set environment variables in PyCharm?

    I was able to figure out this using a PyCharm plugin called EnvFile. This plugin, basically allows setting environment variables to run configurations from one or multiple files.

    The installation is pretty simple:

    Preferences > Plugins > Browse repositories... > Search for "Env File" > Install Plugin.

    Then, I created a file, in my project root, called environment.env which contains:

    DATABASE_URL=postgres://127.0.0.1:5432/my_db_name
    DEBUG=1
    

    Then I went to Run->Edit Configurations, and I followed the steps in the next image:

    Set Environment Variables

    In 3, I chose the file environment.env, and then I could just click the play button in PyCharm, and everything worked like a charm.

    Rotating videos with FFmpeg

    Smartphone: Recored a video in vertical format

    Want to send it to a webside it was 90° to the left (anti clockwise, landscape format) hmm.

    ffmpeg -i input.mp4 -vf "rotate=0" output.mp4

    does it. I got vertical format back again

    debian buster: ffmpeg --version ffmpeg version 4.1.4-1~deb10u1 Copyright (c) 2000-2019 the FFmpeg developers

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

    Passphrases can be added to an existing key or changed without regenerating the key pair:
    Note This will work if keys doesn't had a passphrase, otherwise you'll get this: Enter old passphrase: then Bad passphrase

    $ ssh-keygen -p
    Enter file in which the key is (/Users/tekkub/.ssh/id_rsa):
    Key has comment '/Users/tekkub/.ssh/id_rsa'
    Enter new passphrase (empty for no passphrase):
    Enter same passphrase again:
    Your identification has been saved with the new passphrase.
    

    If your key had passphrase then, There's no way to recover the passphrase for a pair of SSH keys. In that case you have to create a new pair of SSH keys.

    1. Generating SSH keys

    Parsing a JSON array using Json.Net

    You can get at the data values like this:

    string json = @"
    [ 
        { ""General"" : ""At this time we do not have any frequent support requests."" },
        { ""Support"" : ""For support inquires, please see our support page."" }
    ]";
    
    JArray a = JArray.Parse(json);
    
    foreach (JObject o in a.Children<JObject>())
    {
        foreach (JProperty p in o.Properties())
        {
            string name = p.Name;
            string value = (string)p.Value;
            Console.WriteLine(name + " -- " + value);
        }
    }
    

    Fiddle: https://dotnetfiddle.net/uox4Vt

    ReactJS - Get Height of an element

    I found useful npm package https://www.npmjs.com/package/element-resize-detector

    An optimized cross-browser resize listener for elements.

    Can use it with React component or functional component(Specially useful for react hooks)

    How do I filter query objects by date range in Django?

    You can get around the "impedance mismatch" caused by the lack of precision in the DateTimeField/date object comparison -- that can occur if using range -- by using a datetime.timedelta to add a day to last date in the range. This works like:

    start = date(2012, 12, 11)
    end = date(2012, 12, 18)
    new_end = end + datetime.timedelta(days=1)
    
    ExampleModel.objects.filter(some_datetime_field__range=[start, new_end])
    

    As discussed previously, without doing something like this, records are ignored on the last day.

    Edited to avoid the use of datetime.combine -- seems more logical to stick with date instances when comparing against a DateTimeField, instead of messing about with throwaway (and confusing) datetime objects. See further explanation in comments below.

    Formatting a double to two decimal places

        double d =  3.1493745;
        string s = $"{d:0.00}"; // or $"{d:#.##}"
        Console.WriteLine(s); // Displays 3.15
    

    Reducing MongoDB database file size

    I had the same problem, and solved by simply doing this at the command line:

    mongodump -d databasename
    echo 'db.dropDatabase()' | mongo databasename
    mongorestore dump/databasename
    

    How to figure out the SMTP server host?

    To automate the answer of @Jordan S. Jones at WIN/DOS command-line,

    Put this in a batch file named: getmns.bat (get mail name server):

    @echo off
    if @%1==@ goto USAGE
    echo set type=MX>mnscmd.txt
    echo %1>>mnscmd.txt
    echo exit>>mnscmd.txt
    nslookup<mnscmd.txt>mnsresult.txt
    type mnsresult.txt
    del mnsresult.txt
    goto END
    :USAGE
    echo usage:
    echo %0 domainname.ext
    :END
    echo.
    

    For example:

    getmns google.com
    

    output:

    google.com      MX preference = 20, mail exchanger = alt1.aspmx.l.google.com
    google.com      MX preference = 10, mail exchanger = aspmx.l.google.com
    google.com      MX preference = 50, mail exchanger = alt4.aspmx.l.google.com
    google.com      MX preference = 40, mail exchanger = alt3.aspmx.l.google.com
    google.com      MX preference = 30, mail exchanger = alt2.aspmx.l.google.com
    
    alt4.aspmx.l.google.com internet address = 74.125.25.27
    alt3.aspmx.l.google.com internet address = 173.194.72.27
    aspmx.l.google.com      internet address = 173.194.65.27
    alt1.aspmx.l.google.com internet address = 74.125.200.27
    alt2.aspmx.l.google.com internet address = 64.233.187.27
    

    For example to pipe the result again into a file do:

    getmns google.com > google.mns.txt
    

    :-D

    CSS to stop text wrapping under image

    Wrap a div around the image and the span and add the following to CSS like so:

    HTML

            <li id="CN2787">
              <div><img class="fav_star" src="images/fav.png"></div>
              <div><span>Text, text and more text</span></div>
            </li>
    

    CSS

                #CN2787 > div { 
                    display: inline-block;
                    vertical-align: top;
                }
    
                #CN2787 > div:first-of-type {
                    width: 35%;
                }
    
                #CN2787 > div:last-of-type {
                    width: 65%;
                }
    

    LESS

            #CN2787 {
                > div { 
                    display: inline-block;
                    vertical-align: top;
                }
    
                > div:first-of-type {
                    width: 35%;
                }
                > div:last-of-type {
                    width: 65%;
                }
            }
    

    Matplotlib scatterplot; colour as a function of a third variable

    Sometimes you may need to plot color precisely based on the x-value case. For example, you may have a dataframe with 3 types of variables and some data points. And you want to do following,

    • Plot points corresponding to Physical variable 'A' in RED.
    • Plot points corresponding to Physical variable 'B' in BLUE.
    • Plot points corresponding to Physical variable 'C' in GREEN.

    In this case, you may have to write to short function to map the x-values to corresponding color names as a list and then pass on that list to the plt.scatter command.

    x=['A','B','B','C','A','B']
    y=[15,30,25,18,22,13]
    
    # Function to map the colors as a list from the input list of x variables
    def pltcolor(lst):
        cols=[]
        for l in lst:
            if l=='A':
                cols.append('red')
            elif l=='B':
                cols.append('blue')
            else:
                cols.append('green')
        return cols
    # Create the colors list using the function above
    cols=pltcolor(x)
    
    plt.scatter(x=x,y=y,s=500,c=cols) #Pass on the list created by the function here
    plt.grid(True)
    plt.show()
    

    Coloring scatter plot as a function of x variable

    What are public, private and protected in object oriented programming?

    To sum it up,in object oriented programming, everything is modeled into classes and objects. Classes contain properties and methods. Public, private and protected keywords are used to specify access to these members(properties and methods) of a class from other classes or other .dlls or even other applications.

    Initializing a dictionary in python with a key value and no corresponding values

    q = input("Apple")
    w = input("Ball")
    Definition = {'apple': q, 'ball': w}
    

    Getting the first index of an object

    they're not really ordered, but you can do:

    var first;
    for (var i in obj) {
        if (obj.hasOwnProperty(i) && typeof(i) !== 'function') {
            first = obj[i];
            break;
        }
    }
    

    the .hasOwnProperty() is important to ignore prototyped objects.

    How to keep console window open

    There are two ways I know of

    1) Console.ReadLine() at the end of the program. Disadvantage, you have to change your code and have to remember to take it out

    2) Run outside of the debugger CONTROL-F5 this opens a console window outside of visual studio and that window won't close when finished. Advantage, you don't have to change your code. Disadvantage, if there is an exception, it won't drop into the debugger (however when you do get exceptions, you can simply just rerun it in the debugger)

    How do I change the text of a span element using JavaScript?

    _x000D_
    _x000D_
    (function ($) {
        $(document).ready(function(){
        $("#myspan").text("This is span");
      });
    }(jQuery));
    _x000D_
    <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
    <span id="myspan"> hereismytext </span>
    _x000D_
    _x000D_
    _x000D_

    user text() to change span text.

    C# DLL config file

    I had the same problem and searched the web for several hours but I couldn't find any solution so I made my own. I wondered why the .net configuration system is so inflexible.

    Background: I want to have my DAL.dll to have its own config file for database and DAL settings. I also need the app.config for Enterprise Library and its own configurations. So I need both the app.config and dll.config.

    What I did not wanted to do is pass-through every property/setting from the app to my DAL layer!

    to bend the "AppDomain.CurrentDomain.SetupInformation.ConfigurationFile" is not possible because I need it for the normal app.config behavior.

    My requirements/point of views were:

    • NO manual copy of anything from ClassLibrary1.dll.config to WindowsFormsApplication1.exe.config because this is unreproducible for other developers.
    • retain the usage of strong typing "Properties.Settings.Default.NameOfValue" (Settings behavior) because I think this is a major feature and I didn't want to lose it
    • I found out the lack of ApplicationSettingsBase to inject your own/custom config file or management (all necessary fields are private in these classes)
    • the usage of "configSource" file redirection is not possible because we would have to copy/rewrite the ClassLibrary1.dll.config and provide several XML files for several sections (I also didn't like this)
    • I didn't like to write my own SettingsProvider for this simple task as MSDN suggests because I thought that simply would be too much
    • I only need sections applicationSettings and connectionStrings from the config file

    I came up with modifying the Settings.cs file and implemented a method that opens the ClassLibrary1.dll.config and reads the section information in a private field. After that, I've overriden "this[string propertyName]" so the generated Settings.Desginer.cs calls into my new Property instead of the base class. There the setting is read out of the List.

    Finally there is the following code:

    internal sealed partial class Settings
    {
        private List<ConfigurationElement> list;
    
        /// <summary>
        /// Initializes a new instance of the <see cref="Settings"/> class.
        /// </summary>
        public Settings()
        {
            this.OpenAndStoreConfiguration();
        }
    
        /// <summary>
        /// Opens the dll.config file and reads its sections into a private List of ConfigurationElement.
        /// </summary>
        private void OpenAndStoreConfiguration()
        {
            string codebase = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;
            Uri p = new Uri(codebase);
            string localPath = p.LocalPath;
            string executingFilename = System.IO.Path.GetFileNameWithoutExtension(localPath);
            string sectionGroupName = "applicationSettings";
            string sectionName = executingFilename + ".Properties.Settings";
            string configName = localPath + ".config";
            ExeConfigurationFileMap fileMap = new ExeConfigurationFileMap();
            fileMap.ExeConfigFilename = configName;
            Configuration config = ConfigurationManager.OpenMappedExeConfiguration(fileMap, ConfigurationUserLevel.None);
    
            // read section of properties
            var sectionGroup = config.GetSectionGroup(sectionGroupName);
            var settingsSection = (ClientSettingsSection)sectionGroup.Sections[sectionName];
            list = settingsSection.Settings.OfType<ConfigurationElement>().ToList();
    
            // read section of Connectionstrings
            var sections = config.Sections.OfType<ConfigurationSection>();
            var connSection = (from section in sections
                               where section.GetType() == typeof(ConnectionStringsSection)
                               select section).FirstOrDefault() as ConnectionStringsSection;
            if (connSection != null)
            {
                list.AddRange(connSection.ConnectionStrings.Cast<ConfigurationElement>());
            }
        }
    
        /// <summary>
        /// Gets or sets the <see cref="System.Object"/> with the specified property name.
        /// </summary>
        /// <value></value>
        public override object this[string propertyName]
        {
            get
            {
                var result = (from item in list
                             where Convert.ToString(item.ElementInformation.Properties["name"].Value) == propertyName
                             select item).FirstOrDefault();
                if (result != null)
                {
                    if (result.ElementInformation.Type == typeof(ConnectionStringSettings))
                    {
                        return result.ElementInformation.Properties["connectionString"].Value;
                    }
                    else if (result.ElementInformation.Type == typeof(SettingElement))
                    {
                        return result.ElementInformation.Properties["value"].Value;
                    }
                }
                return null;
            }
            // ignore
            set
            {
                base[propertyName] = value;
            }
        }
    

    You just will have to copy your ClassLibrary1.dll.config from the ClassLibrary1 output directory to your application's output directory. Perhaps someone will find it useful.

    Homebrew install specific version of formula?

    TLDR: brew install [email protected] See answer below for more details.


    *(I’ve re-edited my answer to give a more thorough workflow for installing/using older software versions with homebrew. Feel free to add a note if you found the old version better.)

    Let’s start with the simplest case:

    1) Check, whether the version is already installed (but not activated)

    When homebrew installs a new formula, it puts it in a versioned directory like /usr/local/Cellar/postgresql/9.3.1. Only symbolic links to this folder are then installed globally. In principle, this makes it pretty easy to switch between two installed versions. (*)

    If you have been using homebrew for longer and never removed older versions (using, for example brew cleanup), chances are that some older version of your program may still be around. If you want to simply activate that previous version, brew switch is the easiest way to do this.

    Check with brew info postgresql (or brew switch postgresql <TAB>) whether the older version is installed:

    $ brew info postgresql
    postgresql: stable 9.3.2 (bottled)
    http://www.postgresql.org/
    Conflicts with: postgres-xc
    /usr/local/Cellar/postgresql/9.1.5 (2755 files, 37M)
      Built from source
    /usr/local/Cellar/postgresql/9.3.2 (2924 files, 39M) *
      Poured from bottle
    From: https://github.com/Homebrew/homebrew/commits/master/Library/Formula/postgresql.rb
    # … and some more
    

    We see that some older version is already installed. We may activate it using brew switch:

    $ brew switch postgresql 9.1.5
    Cleaning /usr/local/Cellar/postgresql/9.1.5
    Cleaning /usr/local/Cellar/postgresql/9.3.2
    384 links created for /usr/local/Cellar/postgresql/9.1.5
    

    Let’s double-check what is activated:

    $ brew info postgresql
    postgresql: stable 9.3.2 (bottled)
    http://www.postgresql.org/
    Conflicts with: postgres-xc
    /usr/local/Cellar/postgresql/9.1.5 (2755 files, 37M) *
      Built from source
    /usr/local/Cellar/postgresql/9.3.2 (2924 files, 39M)
      Poured from bottle
    From: https://github.com/Homebrew/homebrew/commits/master/Library/Formula/postgresql.rb
    # … and some more
    

    Note that the star * has moved to the newly activated version

    (*) Please note that brew switch only works as long as all dependencies of the older version are still around. In some cases, a rebuild of the older version may become necessary. Therefore, using brew switch is mostly useful when one wants to switch between two versions not too far apart.

    2) Check, whether the version is available as a tap

    Especially for larger software projects, it is very probably that there is a high enough demand for several (potentially API incompatible) major versions of a certain piece of software. As of March 2012, Homebrew 0.9 provides a mechanism for this: brew tap & the homebrew versions repository.

    That versions repository may include backports of older versions for several formulae. (Mostly only the large and famous ones, but of course they’ll also have several formulae for postgresql.)

    brew search postgresql will show you where to look:

    $ brew search postgresql
    postgresql
    homebrew/versions/postgresql8    homebrew/versions/postgresql91
    homebrew/versions/postgresql9    homebrew/versions/postgresql92
    

    We can simply install it by typing

    $ brew install homebrew/versions/postgresql8
    Cloning into '/usr/local/Library/Taps/homebrew-versions'...
    remote: Counting objects: 1563, done.
    remote: Compressing objects: 100% (943/943), done.
    remote: Total 1563 (delta 864), reused 1272 (delta 620)
    Receiving objects: 100% (1563/1563), 422.83 KiB | 339.00 KiB/s, done.
    Resolving deltas: 100% (864/864), done.
    Checking connectivity... done.
    Tapped 125 formula
    ==> Downloading http://ftp.postgresql.org/pub/source/v8.4.19/postgresql-8.4.19.tar.bz2
    # …
    

    Note that this has automatically tapped the homebrew/versions tap. (Check with brew tap, remove with brew untap homebrew/versions.) The following would have been equivalent:

    $ brew tap homebrew/versions
    $ brew install postgresql8
    

    As long as the backported version formulae stay up-to-date, this approach is probably the best way to deal with older software.

    3) Try some formula from the past

    The following approaches are listed mostly for completeness. Both try to resurrect some undead formula from the brew repository. Due to changed dependencies, API changes in the formula spec or simply a change in the download URL, things may or may not work.

    Since the whole formula directory is a git repository, one can install specific versions using plain git commands. However, we need to find a way to get to a commit where the old version was available.

    a) historic times

    Between August 2011 and October 2014, homebrew had a brew versions command, which spat out all available versions with their respective SHA hashes. As of October 2014, you have to do a brew tap homebrew/boneyard before you can use it. As the name of the tap suggests, you should probably only do this as a last resort.

    E.g.

    $ brew versions postgresql
    Warning: brew-versions is unsupported and may be removed soon.
    Please use the homebrew-versions tap instead:
      https://github.com/Homebrew/homebrew-versions
    9.3.2    git checkout 3c86d2b Library/Formula/postgresql.rb
    9.3.1    git checkout a267a3e Library/Formula/postgresql.rb
    9.3.0    git checkout ae59e09 Library/Formula/postgresql.rb
    9.2.4    git checkout e3ac215 Library/Formula/postgresql.rb
    9.2.3    git checkout c80b37c Library/Formula/postgresql.rb
    9.2.2    git checkout 9076baa Library/Formula/postgresql.rb
    9.2.1    git checkout 5825f62 Library/Formula/postgresql.rb
    9.2.0    git checkout 2f6cbc6 Library/Formula/postgresql.rb
    9.1.5    git checkout 6b8d25f Library/Formula/postgresql.rb
    9.1.4    git checkout c40c7bf Library/Formula/postgresql.rb
    9.1.3    git checkout 05c7954 Library/Formula/postgresql.rb
    9.1.2    git checkout dfcc838 Library/Formula/postgresql.rb
    9.1.1    git checkout 4ef8fb0 Library/Formula/postgresql.rb
    9.0.4    git checkout 2accac4 Library/Formula/postgresql.rb
    9.0.3    git checkout b782d9d Library/Formula/postgresql.rb
    

    As you can see, it advises against using it. Homebrew spits out all versions it can find with its internal heuristic and shows you a way to retrieve the old formulae. Let’s try it.

    # First, go to the homebrew base directory
    $ cd $( brew --prefix )
    # Checkout some old formula
    $ git checkout 6b8d25f Library/Formula/postgresql.rb
    $ brew install postgresql
    # … installing
    

    Now that the older postgresql version is installed, we can re-install the latest formula in order to keep our repository clean:

    $ git checkout -- Library/Formula/postgresql.rb
    

    brew switch is your friend to change between the old and the new.

    b) prehistoric times

    For special needs, we may also try our own digging through the homebrew repo.

    $ cd Library/Taps/homebrew/homebrew-core && git log -S'8.4.4' -- Formula/postgresql.rb
    

    git log -S looks for all commits in which the string '8.4.4' was either added or removed in the file Library/Taps/homebrew/homebrew-core/Formula/postgresql.rb. We get two commits as a result.

    commit 7dc7ccef9e1ab7d2fc351d7935c96a0e0b031552
    Author: Aku Kotkavuo
    Date:   Sun Sep 19 18:03:41 2010 +0300
    
        Update PostgreSQL to 9.0.0.
    
        Signed-off-by: Adam Vandenberg
    
    commit fa992c6a82eebdc4cc36a0c0d2837f4c02f3f422
    Author: David Höppner
    Date:   Sun May 16 12:35:18 2010 +0200
    
        postgresql: update version to 8.4.4
    

    Obviously, fa992c6a82eebdc4cc36a0c0d2837f4c02f3f422 is the commit we’re interested in. As this commit is pretty old, we’ll try to downgrade the complete homebrew installation (that way, the formula API is more or less guaranteed to be valid):

    $ git checkout -b postgresql-8.4.4 fa992c6a82eebdc4cc36a0c0d2837f4c02f3f422
    $ brew install postgresql
    $ git checkout master
    $ git branch -d postgresql-8.4.4
    

    You may skip the last command to keep the reference in your git repository.

    One note: When checking out the older commit, you temporarily downgrade your homebrew installation. So, you should be careful as some commands in homebrew might be different to the most recent version.

    4) Manually write a formula

    It’s not too hard and you may then upload it to your own repository. Used to be Homebrew-Versions, but that is now discontinued.

    A.) Bonus: Pinning

    If you want to keep a certain version of, say postgresql, around and stop it from being updated when you do the natural brew update; brew upgrade procedure, you can pin a formula:

    $ brew pin postgresql
    

    Pinned formulae are listed in /usr/local/Library/PinnedKegs/ and once you want to bring in the latest changes and updates, you can unpin it again:

    $ brew unpin postgresql
    

    Get the current fragment object

    You can create field in your parent Activity Class:

    public class MainActivity extends AppCompatActivity {
    
        public Fragment fr;
    
     @Override
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
        }
    
    }
    

    And then inside each fragment class:

    public class SomeFragment extends Fragment {
    
    @Override
        public View onCreateView(LayoutInflater inflater,
                                 ViewGroup container, Bundle savedInstanceState) {
    
            ((MainActivity) getActivity()).fr = this;
    }
    

    Your 'fr' field is current fragment Object

    It's working also with popBackStack()

    get keys of json-object in JavaScript

    The working code

    _x000D_
    _x000D_
    var jsonData = [{person:"me", age :"30"},{person:"you",age:"25"}];_x000D_
    _x000D_
    for(var obj in jsonData){_x000D_
        if(jsonData.hasOwnProperty(obj)){_x000D_
        for(var prop in jsonData[obj]){_x000D_
            if(jsonData[obj].hasOwnProperty(prop)){_x000D_
               alert(prop + ':' + jsonData[obj][prop]);_x000D_
            }_x000D_
        }_x000D_
    }_x000D_
    }
    _x000D_
    _x000D_
    _x000D_

    Oracle SQL Developer: Failure - Test failed: The Network Adapter could not establish the connection?

    I am answering this for the benefit of future community users. There were multiple issues. If you encounter this problem, I suggest you look for the following:

    • Make sure your tnsnames.ora is complete and has the databases you wish to connect to
    • Make sure you can tnsping the server you wish to connect to
    • On the server, make sure it will be open on the port you desire with the specific application you are using.

    Once I did these three things, I solved my problem.

    Negation in Python

    Combining the input from everyone else (use not, no parens, use os.mkdir) you'd get...

    special_path_for_john = "/usr/share/sounds/blues"
    if not os.path.exists(special_path_for_john):
        os.mkdir(special_path_for_john)
    

    Bootstrap 3: How do you align column content to bottom of row

    When working with bootsrap usually face three main problems:

    1. How to place the content of the column to the bottom?
    2. How to create a multi-row gallery of columns of equal height in one .row?
    3. How to center columns horizontally if their total width is less than 12 and the remaining width is odd?

    To solve first two problems download this small plugin https://github.com/codekipple/conformity

    The third problem is solved here http://www.minimit.com/articles/solutions-tutorials/bootstrap-3-responsive-centered-columns

    Common code

    <style>
        [class*=col-] {position: relative}
        .row-conformity .to-bottom {position:absolute; bottom:0; left:0; right:0}
        .row-centered {text-align:center}   
        .row-centered [class*=col-] {display:inline-block; float:none; text-align:left; margin-right:-4px; vertical-align:top} 
    </style>
    
    <script src="assets/conformity/conformity.js"></script>
    <script>
        $(document).ready(function () {
            $('.row-conformity > [class*=col-]').conformity();
            $(window).on('resize', function() {
                $('.row-conformity > [class*=col-]').conformity();
            });
        });
    </script>
    

    1. Aligning content of the column to the bottom

    <div class="row row-conformity">
        <div class="col-sm-3">
            I<br>create<br>highest<br>column
        </div>
        <div class="col-sm-3">
            <div class="to-bottom">
                I am on the bottom
            </div>
        </div>
    </div>
    

    2. Gallery of columns of equal height

    <div class="row row-conformity">
        <div class="col-sm-4">We all have equal height</div>
        <div class="col-sm-4">...</div>
        <div class="col-sm-4">...</div>
        <div class="col-sm-4">...</div>
        <div class="col-sm-4">...</div>
        <div class="col-sm-4">...</div>
    </div>
    

    3. Horizontal alignment of columns to the center (less than 12 col units)

    <div class="row row-centered">
        <div class="col-sm-3">...</div>
        <div class="col-sm-4">...</div>
    </div>
    

    All classes can work together

    <div class="row row-conformity row-centered">
        ...
    </div>
    

    Get the index of the object inside an array, matching a condition

    What TJ Crowder said, everyway will have some kind of hidden iteration, with lodash this becomes:

    var index = _.findIndex(array, {prop2: 'yutu'})
    

    Exporting result of select statement to CSV format in DB2

    I'm using IBM Data Studio v 3.1.1.0 with an underlying DB2 for z/OS and the accepted answer didn't work for me. If you're using IBM Data Studio (v3.1.1.0) you can:

    1. Expand your server connection in "Administration Explorer" view;
    2. Select tables or views;
    3. On the right panel, right click your table or view;
    4. There should be an option to extract/download data, in portuguese it says: "Descarregar -> Com sql" - something like "Download -> with sql;"

    How to position a DIV in a specific coordinates?

    You can also use position fixed css property.

    <!-- html code --> 
    <div class="box" id="myElement"></div>
    
    /* css code */
    .box {
        position: fixed;
    }
    
    // js code
    
    document.getElementById('myElement').style.top = 0; //or whatever 
    document.getElementById('myElement').style.left = 0; // or whatever
    

    Ansible: create a user with sudo privileges

    Sometimes it's knowing what to ask. I didn't know as I am a developer who has taken on some DevOps work.

    Apparently 'passwordless' or NOPASSWD login is a thing which you need to put in the /etc/sudoers file.

    The answer to my question is at Ansible: best practice for maintaining list of sudoers.

    The Ansible playbook code fragment looks like this from my problem:

    - name: Make sure we have a 'wheel' group
      group:
        name: wheel
        state: present
    
    - name: Allow 'wheel' group to have passwordless sudo
      lineinfile:
        dest: /etc/sudoers
        state: present
        regexp: '^%wheel'
        line: '%wheel ALL=(ALL) NOPASSWD: ALL'
        validate: 'visudo -cf %s'
    
    - name: Add sudoers users to wheel group
      user:
        name=deployer
        groups=wheel
        append=yes
        state=present
        createhome=yes
    
    - name: Set up authorized keys for the deployer user
      authorized_key: user=deployer key="{{item}}"
      with_file:
        - /home/railsdev/.ssh/id_rsa.pub
    

    And the best part is that the solution is idempotent. It doesn't add the line

    %wheel ALL=(ALL) NOPASSWD: ALL
    

    to /etc/sudoers when the playbook is run a subsequent time. And yes...I was able to ssh into the server as "deployer" and run sudo commands without having to give a password.

    Insert Multiple Rows Into Temp Table With SQL Server 2012

    Yes, SQL Server 2012 supports multiple inserts - that feature was introduced in SQL Server 2008.

    That makes me wonder if you have Management Studio 2012, but you're really connected to a SQL Server 2005 instance ...

    What version of the SQL Server engine do you get from SELECT @@VERSION ??

    Fragment onCreateView and onActivityCreated called twice

    Ok, Here's what I found out.

    What I didn't understand is that all fragments that are attached to an activity when a config change happens (phone rotates) are recreated and added back to the activity. (which makes sense)

    What was happening in the TabListener constructor was the tab was detached if it was found and attached to the activity. See below:

    mFragment = mActivity.getFragmentManager().findFragmentByTag(mTag);
        if (mFragment != null && !mFragment.isDetached()) {
            Log.d(TAG, "constructor: detaching fragment " + mTag);
            FragmentTransaction ft = mActivity.getFragmentManager().beginTransaction();
            ft.detach(mFragment);
            ft.commit();
        }
    

    Later in the activity onCreate the previously selected tab was selected from the saved instance state. See below:

    if (savedInstanceState != null) {
        bar.setSelectedNavigationItem(savedInstanceState.getInt("tab", 0));
        Log.d(TAG, "FragmentTabs.onCreate tab: " + savedInstanceState.getInt("tab"));
        Log.d(TAG, "FragmentTabs.onCreate number: " + savedInstanceState.getInt("number"));
    }
    

    When the tab was selected it would be reattached in the onTabSelected callback.

    public void onTabSelected(Tab tab, FragmentTransaction ft) {
        if (mFragment == null) {
            mFragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs);
            Log.d(TAG, "onTabSelected adding fragment " + mTag);
            ft.add(android.R.id.content, mFragment, mTag);
        } else {
            Log.d(TAG, "onTabSelected attaching fragment " + mTag);
            ft.attach(mFragment);
        }
    }
    

    The fragment being attached is the second call to the onCreateView and onActivityCreated methods. (The first being when the system is recreating the acitivity and all attached fragments) The first time the onSavedInstanceState Bundle would have saved data but not the second time.

    The solution is to not detach the fragment in the TabListener constructor, just leave it attached. (You still need to find it in the FragmentManager by it's tag) Also, in the onTabSelected method I check to see if the fragment is detached before I attach it. Something like this:

    public void onTabSelected(Tab tab, FragmentTransaction ft) {
                if (mFragment == null) {
                    mFragment = Fragment.instantiate(mActivity, mClass.getName(), mArgs);
                    Log.d(TAG, "onTabSelected adding fragment " + mTag);
                    ft.add(android.R.id.content, mFragment, mTag);
                } else {
    
                    if(mFragment.isDetached()) {
                        Log.d(TAG, "onTabSelected attaching fragment " + mTag);
                        ft.attach(mFragment);
                    } else {
                        Log.d(TAG, "onTabSelected fragment already attached " + mTag);
                    }
                }
            }
    

    How to improve a case statement that uses two columns

    You could do it this way:

    -- Notice how STATE got moved inside the condition:
    CASE WHEN STATE = 2 AND RetailerProcessType IN (1, 2) THEN '"AUTHORISED"'
         WHEN STATE = 1 AND RetailerProcessType = 2 THEN '"PENDING"'
         ELSE '"DECLINED"'
    END
    

    The reason you can do an AND here is that you are not checking the CASE of STATE, but instead you are CASING Conditions.

    The key part here is that the STATE condition is a part of the WHEN.

    copy all files and folders from one drive to another drive using DOS (command prompt)

    try this command, xcopy c:\ (file or directory path) F:\ /e. If you want more details refer this site [[http://www.computerhope.com/xcopyhlp.htm]]

    Rename package in Android Studio

    go to AndroidManifest.xml There you will find package as the attribute of manifest tag. Just select the part you want to change, right click-> refactor -> rename

    Maybe earlier it was hard, but as of today it is not anymore.

    You might also want to change the app id in

    defaultConfig {
        applicationId 
    }
    

    Short & Sweet

    Hide element by class in pure Javascript

    document.getElementsByClassName returns an HTMLCollection(an array-like object) of all elements matching the class name. The style property is defined for Element not for HTMLCollection. You should access the first element using the bracket(subscript) notation.

    document.getElementsByClassName('appBanner')[0].style.visibility = 'hidden';
    

    Updated jsFiddle

    To change the style rules of all elements matching the class, using the Selectors API:

    [].forEach.call(document.querySelectorAll('.appBanner'), function (el) {
      el.style.visibility = 'hidden';
    });
    

    If for...of is available:

    for (let el of document.querySelectorAll('.appBanner')) el.style.visibility = 'hidden';
    

    How to send a POST request from node.js Express?

    As described here for a post request :

    var http = require('http');
    
    var options = {
      host: 'www.host.com',
      path: '/',
      port: '80',
      method: 'POST'
    };
    
    callback = function(response) {
      var str = ''
      response.on('data', function (chunk) {
        str += chunk;
      });
    
      response.on('end', function () {
        console.log(str);
      });
    }
    
    var req = http.request(options, callback);
    //This is the data we are posting, it needs to be a string or a buffer
    req.write("data");
    req.end();
    

    How to pass data using NotificationCenter in swift 3.0 and NSNotificationCenter in swift 2.0?

    For Swift 3

    let imageDataDict:[String: UIImage] = ["image": image]
    
      // post a notification
      NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict) 
      // `default` is now a property, not a method call
    
     // Register to receive notification in your class
     NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)
    
     // handle notification
     func showSpinningWheel(_ notification: NSNotification) {
            print(notification.userInfo ?? "")
            if let dict = notification.userInfo as NSDictionary? {
                if let id = dict["image"] as? UIImage{
                    // do something with your image
                }
            }
     }
    

    For Swift 4

    let imageDataDict:[String: UIImage] = ["image": image]
    
      // post a notification
      NotificationCenter.default.post(name: NSNotification.Name(rawValue: "notificationName"), object: nil, userInfo: imageDataDict) 
      // `default` is now a property, not a method call
    
     // Register to receive notification in your class
     NotificationCenter.default.addObserver(self, selector: #selector(self.showSpinningWheel(_:)), name: NSNotification.Name(rawValue: "notificationName"), object: nil)
    
     // handle notification
     @objc func showSpinningWheel(_ notification: NSNotification) {
            print(notification.userInfo ?? "")
            if let dict = notification.userInfo as NSDictionary? {
                if let id = dict["image"] as? UIImage{
                    // do something with your image
                }
            }
     }
    

    Python function as a function argument?

    Can a Python function be an argument of another function?

    Yes.

    def myfunc(anotherfunc, extraArgs):
        anotherfunc(*extraArgs)
    

    To be more specific ... with various arguments ...

    >>> def x(a,b):
    ...     print "param 1 %s param 2 %s"%(a,b)
    ...
    >>> def y(z,t):
    ...     z(*t)
    ...
    >>> y(x,("hello","manuel"))
    param 1 hello param 2 manuel
    >>>
    

    PostgreSQL: how to convert from Unix epoch to date?

    /* Current time */
     select now(); 
    
    /* Epoch from current time;
       Epoch is number of seconds since 1970-01-01 00:00:00+00 */
     select extract(epoch from now()); 
    
    /* Get back time from epoch */
     -- Option 1 - use to_timestamp function
     select to_timestamp( extract(epoch from now()));
     -- Option 2 - add seconds to 'epoch'
     select timestamp with time zone 'epoch' 
             + extract(epoch from now()) * interval '1 second';
    
    /* Cast timestamp to date */
     -- Based on Option 1
     select to_timestamp(extract(epoch from now()))::date;
     -- Based on Option 2
     select (timestamp with time zone 'epoch' 
              + extract(epoch from now()) * interval '1 second')::date; 
    
     /* For column epoch_ms */
     select to_timestamp(extract(epoch epoch_ms))::date;
    

    PostgreSQL Docs

    Is it possible to simulate key press events programmatically?

    Here's a library that really helps: https://cdn.rawgit.com/ccampbell/mousetrap/2e5c2a8adbe80a89050aaf4e02c45f02f1cc12d4/tests/libs/key-event.js

    I don't know from where did it came from, but it is helpful. It adds a .simulate() method to window.KeyEvent, so you use it simply with KeyEvent.simulate(0, 13) for simulating an enter or KeyEvent.simulate(81, 81) for a 'Q'.

    I got it at https://github.com/ccampbell/mousetrap/tree/master/tests.

    How to post raw body data with curl?

    curl's --data will by default send Content-Type: application/x-www-form-urlencoded in the request header. However, when using Postman's raw body mode, Postman sends Content-Type: text/plain in the request header.

    So to achieve the same thing as Postman, specify -H "Content-Type: text/plain" for curl:

    curl -X POST -H "Content-Type: text/plain" --data "this is raw data" http://78.41.xx.xx:7778/
    

    Note that if you want to watch the full request sent by Postman, you can enable debugging for packed app. Check this link for all instructions. Then you can inspect the app (right-click in Postman) and view all requests sent from Postman in the network tab :

    enter image description here

    Safely turning a JSON string into an object

    Parse the JSON string with JSON.parse(), and the data becomes a JavaScript object:

    JSON.parse(jsonString)
    

    Here, JSON represents to process JSON dataset.

    Imagine we received this text from a web server:

    '{ "name":"John", "age":30, "city":"New York"}'
    

    To parse into a JSON object:

    var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}'); 
    

    Here obj is the respective JSON object which looks like:

    { "name":"John", "age":30, "city":"New York"}
    

    To fetch a value use the . operator:

    obj.name // John
    obj.age //30
    

    Convert a JavaScript object into a string with JSON.stringify().

    Visual Studio setup problem - 'A problem has been encountered while loading the setup components. Canceling setup.'

    Thanks, riaraos, uninstalling KB952241 was the solution for me, too. Before doing that I tried to run the installer from "Programs and Features" and from the installation DVD without success. I did not want to completely remove the VS 2008 installation but only add a few components.

    Notes on my system:

    Windows 7 Beta 1 Visual Studio 2008 SP1

    PyTorch: How to get the shape of a Tensor as a list of int

    Previous answers got you list of torch.Size Here is how to get list of ints

    listofints = [int(x) for x in tensor.shape]
    

    Python : List of dict, if exists increment a dict value, if not append a new dict

    To do it exactly your way? You could use the for...else structure

    for url in list_of_urls:
        for url_dict in urls:
            if url_dict['url'] == url:
                url_dict['nbr'] += 1
                break
        else:
            urls.append(dict(url=url, nbr=1))
    

    But it is quite inelegant. Do you really have to store the visited urls as a LIST? If you sort it as a dict, indexed by url string, for example, it would be way cleaner:

    urls = {'http://www.google.fr/': dict(url='http://www.google.fr/', nbr=1)}
    
    for url in list_of_urls:
        if url in urls:
            urls[url]['nbr'] += 1
        else:
            urls[url] = dict(url=url, nbr=1)
    

    A few things to note in that second example:

    • see how using a dict for urls removes the need for going through the whole urls list when testing for one single url. This approach will be faster.
    • Using dict( ) instead of braces makes your code shorter
    • using list_of_urls, urls and url as variable names make the code quite hard to parse. It's better to find something clearer, such as urls_to_visit, urls_already_visited and current_url. I know, it's longer. But it's clearer.

    And of course I'm assuming that dict(url='http://www.google.fr', nbr=1) is a simplification of your own data structure, because otherwise, urls could simply be:

    urls = {'http://www.google.fr':1}
    
    for url in list_of_urls:
        if url in urls:
            urls[url] += 1
        else:
            urls[url] = 1
    

    Which can get very elegant with the defaultdict stance:

    urls = collections.defaultdict(int)
    for url in list_of_urls:
        urls[url] += 1
    

    Can't resolve module (not found) in React.js

    Check for the import statements.It should be ended with semicolon. If you miss any, you will get this error.

    Also check whether following import statement added in you component.

    import { threadId } from 'worker_threads';

    If so remove that line. It works for me.

    How do you echo a 4-digit Unicode character in Bash?

    Here is a list of all unicode emoji's available:

    https://en.wikipedia.org/wiki/Emoji#Unicode_blocks

    Example:

    echo -e "\U1F304"
    
    

    For get the ASCII value of this character use hexdump

    echo -e "" | hexdump -C
    
    00000000  f0 9f 8c 84 0a                                    |.....|
    00000005
    

    And then use the values informed in hex format

    echo -e "\xF0\x9F\x8C\x84\x0A"