Programs & Examples On #File io

File I/O is input/output that involves the file system. This could include performing operations on directories and files, such as creation and deletion, reading files, and writing output to files.

How do I read the first line of a file using cat?

There is plenty of good answer to this question. Just gonna drop another one into the basket if you wish to do it with lolcat

lolcat FileName.csv | head -n 1

How to delete all files older than 3 days when "Argument list too long"?

Can also use:

find . -mindepth 1 -mtime +3 -delete

To not delete target directory

Open Excel file for reading with VBA without display

A much simpler approach that doesn't involve manipulating active windows:

Dim wb As Workbook
Set wb = Workbooks.Open("workbook.xlsx")
wb.Windows(1).Visible = False

From what I can tell the Windows index on the workbook should always be 1. If anyone knows of any race conditions that would make this untrue please let me know.

How to save a BufferedImage as a File

Create and save a java.awt.image.bufferedImage to file:

import java.io.*;
import java.awt.image.*;
import javax.imageio.*;
public class Main{
    public static void main(String args[]){
        try{
            BufferedImage img = new BufferedImage( 
                500, 500, BufferedImage.TYPE_INT_RGB );

            File f = new File("MyFile.png");
            int r = 5;
            int g = 25;
            int b = 255;
            int col = (r << 16) | (g << 8) | b;
            for(int x = 0; x < 500; x++){
                for(int y = 20; y < 300; y++){
                    img.setRGB(x, y, col);
                }
            }
            ImageIO.write(img, "PNG", f);
        }
        catch(Exception e){
            e.printStackTrace();
        }
    }
}

Notes:

  1. Creates a file called MyFile.png.
  2. Image is 500 by 500 pixels.
  3. Overwrites the existing file.
  4. The color of the image is black with a blue stripe across the top.

How can I lock a file using java (if possible)

Below is a sample snippet code to lock a file until it's process is done by JVM.

 public static void main(String[] args) throws InterruptedException {
    File file = new File(FILE_FULL_PATH_NAME);
    RandomAccessFile in = null;
    try {
        in = new RandomAccessFile(file, "rw");
        FileLock lock = in.getChannel().lock();
        try {

            while (in.read() != -1) {
                System.out.println(in.readLine());
            }
        } finally {
            lock.release();
        }
    } catch (FileNotFoundException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }finally {
        try {
            in.close();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

}

Read from file in eclipse

I am using eclipse and I was stuck on not being able to read files because of a "file not found exception". What I did to solve this problem was I moved the file to the root of my project. Hope this helps.

getResourceAsStream returns null

Don't know if of help, but in my case I had my resource in the /src/ folder and was getting this error. I then moved the picture to the bin folder and it fixed the issue.

How to write console output to a txt file

You can use System.setOut() at the start of your program to redirect all output via System.out to your own PrintStream.

How to read an entire file to a string using C#?

string contents = System.IO.File.ReadAllText(path)

Here's the MSDN documentation

How to read a single character at a time from a file in Python?

Python itself can help you with this, in interactive mode:

>>> help(file.read)
Help on method_descriptor:

read(...)
    read([size]) -> read at most size bytes, returned as a string.

    If the size argument is negative or omitted, read until EOF is reached.
    Notice that when in non-blocking mode, less data than what was requested
    may be returned, even if no size parameter was given.

How do I append text to a file?

Other possible way is:

echo "text" | tee -a filename >/dev/null

The -a will append at the end of the file.

If needing sudo, use:

echo "text" | sudo tee -a filename >/dev/null

How to read a file byte by byte in Python and how to print a bytelist as a binary?

There's a python module especially made for reading and writing to and from binary encoded data called 'struct'. Since versions of Python under 2.6 doesn't support str.format, a custom method needs to be used to create binary formatted strings.

import struct

# binary string
def bstr(n): # n in range 0-255
    return ''.join([str(n >> x & 1) for x in (7,6,5,4,3,2,1,0)])

# read file into an array of binary formatted strings.
def read_binary(path):
    f = open(path,'rb')
    binlist = []
    while True:
        bin = struct.unpack('B',f.read(1))[0] # B stands for unsigned char (8 bits)
        if not bin:
            break
        strBin = bstr(bin)
        binlist.append(strBin)
    return binlist

File to byte[] in Java

//The file that you wanna convert into byte[]
File file=new File("/storage/0CE2-EA3D/DCIM/Camera/VID_20190822_205931.mp4"); 

FileInputStream fileInputStream=new FileInputStream(file);
byte[] data=new byte[(int) file.length()];
BufferedInputStream bufferedInputStream=new BufferedInputStream(fileInputStream);
bufferedInputStream.read(data,0,data.length);

//Now the bytes of the file are contain in the "byte[] data"

Reading file contents on the client-side in javascript in various browsers

In order to read a file chosen by the user, using a file open dialog, you can use the <input type="file"> tag. You can find information on it from MSDN. When the file is chosen you can use the FileReader API to read the contents.

_x000D_
_x000D_
function onFileLoad(elementId, event) {_x000D_
    document.getElementById(elementId).innerText = event.target.result;_x000D_
}_x000D_
_x000D_
function onChooseFile(event, onLoadFileHandler) {_x000D_
    if (typeof window.FileReader !== 'function')_x000D_
        throw ("The file API isn't supported on this browser.");_x000D_
    let input = event.target;_x000D_
    if (!input)_x000D_
        throw ("The browser does not properly implement the event object");_x000D_
    if (!input.files)_x000D_
        throw ("This browser does not support the `files` property of the file input.");_x000D_
    if (!input.files[0])_x000D_
        return undefined;_x000D_
    let file = input.files[0];_x000D_
    let fr = new FileReader();_x000D_
    fr.onload = onLoadFileHandler;_x000D_
    fr.readAsText(file);_x000D_
}
_x000D_
<input type='file' onchange='onChooseFile(event, onFileLoad.bind(this, "contents"))' />_x000D_
<p id="contents"></p>
_x000D_
_x000D_
_x000D_

Java IOException "Too many open files"

You're obviously not closing your file descriptors before opening new ones. Are you on windows or linux?

Create a file from a ByteArrayOutputStream

You can use a FileOutputStream for this.

FileOutputStream fos = null;
try {
    fos = new FileOutputStream(new File("myFile")); 
    ByteArrayOutputStream baos = new ByteArrayOutputStream();

    // Put data in your baos

    baos.writeTo(fos);
} catch(IOException ioe) {
    // Handle exception here
    ioe.printStackTrace();
} finally {
    fos.close();
}

Batch file to delete files older than N days

Might I add a humble contribution to this already valuable thread. I'm finding that other solutions might get rid of the actual error text but are ignoring the %ERRORLEVEL% which signals a fail in my application. AND I legitimately want %ERRORLEVEL% just as long as it isn't the "No files found" error.

Some Examples:

Debugging and eliminating the error specifically:

forfiles /p "[file path...]\IDOC_ARCHIVE" /s /m *.txt /d -1 /c "cmd /c del @path" 2>&1 |  findstr /V /O /C:"ERROR: No files found with the specified search criteria."2>&1 | findstr ERROR&&ECHO found error||echo found success

Using a oneliner to return ERRORLEVEL success or failure:

forfiles /p "[file path...]\IDOC_ARCHIVE" /s /m *.txt /d -1 /c "cmd /c del @path" 2>&1 |  findstr /V /O /C:"ERROR: No files found with the specified search criteria."2>&1 | findstr ERROR&&EXIT /B 1||EXIT /B 0

Using a oneliner to keep the ERRORLEVEL at zero for success within the context of a batchfile in the midst of other code (ver > nul resets the ERRORLEVEL):

forfiles /p "[file path...]\IDOC_ARCHIVE" /s /m *.txt /d -1 /c "cmd /c del @path" 2>&1 |  findstr /V /O /C:"ERROR: No files found with the specified search criteria."2>&1 | findstr ERROR&&ECHO found error||ver > nul

For a SQL Server Agent CmdExec job step I landed on the following. I don't know if it's a bug, but the CmdExec within the step only recognizes the first line of code:

cmd /e:on /c "forfiles /p "C:\SQLADMIN\MAINTREPORTS\SQL2" /s /m *.txt /d -1 /c "cmd /c del @path" 2>&1 |  findstr /V /O /C:"ERROR: No files found with the specified search criteria."2>&1 | findstr ERROR&&EXIT 1||EXIT 0"&exit %errorlevel%

What is the simplest way to write the contents of a StringBuilder to a text file in .NET 1.1?

You still have access to StreamWriter:

using (System.IO.StreamWriter file = new System.IO.StreamWriter(@"\hereIam.txt"))
{
    file.WriteLine(sb.ToString()); // "sb" is the StringBuilder
}

From the MSDN documentation: Writing to a Text File (Visual C#).

For newer versions of the .NET Framework (Version 2.0. onwards), this can be achieved with one line using the File.WriteAllText method.

System.IO.File.WriteAllText(@"C:\TextFile.txt", stringBuilder.ToString());

Replace string within file contents

If you'd like to replace the strings in the same file, you probably have to read its contents into a local variable, close it, and re-open it for writing:

I am using the with statement in this example, which closes the file after the with block is terminated - either normally when the last command finishes executing, or by an exception.

def inplace_change(filename, old_string, new_string):
    # Safely read the input filename using 'with'
    with open(filename) as f:
        s = f.read()
        if old_string not in s:
            print('"{old_string}" not found in {filename}.'.format(**locals()))
            return

    # Safely write the changed content, if found in the file
    with open(filename, 'w') as f:
        print('Changing "{old_string}" to "{new_string}" in {filename}'.format(**locals()))
        s = s.replace(old_string, new_string)
        f.write(s)

It is worth mentioning that if the filenames were different, we could have done this more elegantly with a single with statement.

Read whole ASCII file into C++ std::string

Try one of these two methods:

string get_file_string(){
    std::ifstream ifs("path_to_file");
    return string((std::istreambuf_iterator<char>(ifs)),
                  (std::istreambuf_iterator<char>()));
}

string get_file_string2(){
    ifstream inFile;
    inFile.open("path_to_file");//open the input file

    stringstream strStream;
    strStream << inFile.rdbuf();//read the file
    return strStream.str();//str holds the content of the file
}

Python, Pandas : write content of DataFrame into text File

@AHegde - To get the tab delimited output use separator sep='\t'.

For df.to_csv:

df.to_csv(r'c:\data\pandas.txt', header=None, index=None, sep='\t', mode='a')

For np.savetxt:

np.savetxt(r'c:\data\np.txt', df.values, fmt='%d', delimiter='\t')

How do relative file paths work in Eclipse?

A project's build path defines which resources from your source folders are copied to your output folders. Usually this is set to Include all files.

New run configurations default to using the project directory for the working directory, though this can also be changed.

This code shows the difference between the working directory, and the location of where the class was loaded from:

public class TellMeMyWorkingDirectory {
    public static void main(String[] args) {
        System.out.println(new java.io.File("").getAbsolutePath());
        System.out.println(TellMeMyWorkingDirectory.class.getClassLoader().getResource("").getPath());
    }
}

The output is likely to be something like:

C:\your\project\directory
/C:/your/project/directory/bin/

How do I create directory if it doesn't exist to create a file?

An elegant way to move your file to an nonexistent directory is to create the following extension to native FileInfo class:

public static class FileInfoExtension
{
    //second parameter is need to avoid collision with native MoveTo
    public static void MoveTo(this FileInfo file, string destination, bool autoCreateDirectory) { 

        if (autoCreateDirectory)
        {
            var destinationDirectory = new DirectoryInfo(Path.GetDirectoryName(destination));

            if (!destinationDirectory.Exists)
                destinationDirectory.Create();
        }

        file.MoveTo(destination);
    }
}

Then use brand new MoveTo extension:

 using <namespace of FileInfoExtension>;
 ...
 new FileInfo("some path")
     .MoveTo("target path",true);

Check Methods extension documentation.

Reading a plain text file in Java

For JSF-based Maven web applications, just use ClassLoader and the Resources folder to read in any file you want:

  1. Put any file you want to read in the Resources folder.
  2. Put the Apache Commons IO dependency into your POM:

    <dependency>
        <groupId>org.apache.commons</groupId>
        <artifactId>commons-io</artifactId>
        <version>1.3.2</version>
    </dependency>
    
  3. Use the code below to read it (e.g. below is reading in a .json file):

    String metadata = null;
    FileInputStream inputStream;
    try {
    
        ClassLoader loader = Thread.currentThread().getContextClassLoader();
        inputStream = (FileInputStream) loader
                .getResourceAsStream("/metadata.json");
        metadata = IOUtils.toString(inputStream);
        inputStream.close();
    }
    catch (FileNotFoundException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    return metadata;
    

You can do the same for text files, .properties files, XSD schemas, etc.

How to get all files under a specific directory in MATLAB?

You're looking for dir to return the directory contents.

To loop over the results, you can simply do the following:

dirlist = dir('.');
for i = 1:length(dirlist)
    dirlist(i)
end

This should give you output in the following format, e.g.:

name: 'my_file'
date: '01-Jan-2010 12:00:00'
bytes: 56
isdir: 0
datenum: []

How to write a multidimensional array to a text file?

If you want to write it to disk so that it will be easy to read back in as a numpy array, look into numpy.save. Pickling it will work fine, as well, but it's less efficient for large arrays (which yours isn't, so either is perfectly fine).

If you want it to be human readable, look into numpy.savetxt.

Edit: So, it seems like savetxt isn't quite as great an option for arrays with >2 dimensions... But just to draw everything out to it's full conclusion:

I just realized that numpy.savetxt chokes on ndarrays with more than 2 dimensions... This is probably by design, as there's no inherently defined way to indicate additional dimensions in a text file.

E.g. This (a 2D array) works fine

import numpy as np
x = np.arange(20).reshape((4,5))
np.savetxt('test.txt', x)

While the same thing would fail (with a rather uninformative error: TypeError: float argument required, not numpy.ndarray) for a 3D array:

import numpy as np
x = np.arange(200).reshape((4,5,10))
np.savetxt('test.txt', x)

One workaround is just to break the 3D (or greater) array into 2D slices. E.g.

x = np.arange(200).reshape((4,5,10))
with open('test.txt', 'w') as outfile:
    for slice_2d in x:
        np.savetxt(outfile, slice_2d)

However, our goal is to be clearly human readable, while still being easily read back in with numpy.loadtxt. Therefore, we can be a bit more verbose, and differentiate the slices using commented out lines. By default, numpy.loadtxt will ignore any lines that start with # (or whichever character is specified by the comments kwarg). (This looks more verbose than it actually is...)

import numpy as np

# Generate some test data
data = np.arange(200).reshape((4,5,10))

# Write the array to disk
with open('test.txt', 'w') as outfile:
    # I'm writing a header here just for the sake of readability
    # Any line starting with "#" will be ignored by numpy.loadtxt
    outfile.write('# Array shape: {0}\n'.format(data.shape))
    
    # Iterating through a ndimensional array produces slices along
    # the last axis. This is equivalent to data[i,:,:] in this case
    for data_slice in data:

        # The formatting string indicates that I'm writing out
        # the values in left-justified columns 7 characters in width
        # with 2 decimal places.  
        np.savetxt(outfile, data_slice, fmt='%-7.2f')

        # Writing out a break to indicate different slices...
        outfile.write('# New slice\n')

This yields:

# Array shape: (4, 5, 10)
0.00    1.00    2.00    3.00    4.00    5.00    6.00    7.00    8.00    9.00   
10.00   11.00   12.00   13.00   14.00   15.00   16.00   17.00   18.00   19.00  
20.00   21.00   22.00   23.00   24.00   25.00   26.00   27.00   28.00   29.00  
30.00   31.00   32.00   33.00   34.00   35.00   36.00   37.00   38.00   39.00  
40.00   41.00   42.00   43.00   44.00   45.00   46.00   47.00   48.00   49.00  
# New slice
50.00   51.00   52.00   53.00   54.00   55.00   56.00   57.00   58.00   59.00  
60.00   61.00   62.00   63.00   64.00   65.00   66.00   67.00   68.00   69.00  
70.00   71.00   72.00   73.00   74.00   75.00   76.00   77.00   78.00   79.00  
80.00   81.00   82.00   83.00   84.00   85.00   86.00   87.00   88.00   89.00  
90.00   91.00   92.00   93.00   94.00   95.00   96.00   97.00   98.00   99.00  
# New slice
100.00  101.00  102.00  103.00  104.00  105.00  106.00  107.00  108.00  109.00 
110.00  111.00  112.00  113.00  114.00  115.00  116.00  117.00  118.00  119.00 
120.00  121.00  122.00  123.00  124.00  125.00  126.00  127.00  128.00  129.00 
130.00  131.00  132.00  133.00  134.00  135.00  136.00  137.00  138.00  139.00 
140.00  141.00  142.00  143.00  144.00  145.00  146.00  147.00  148.00  149.00 
# New slice
150.00  151.00  152.00  153.00  154.00  155.00  156.00  157.00  158.00  159.00 
160.00  161.00  162.00  163.00  164.00  165.00  166.00  167.00  168.00  169.00 
170.00  171.00  172.00  173.00  174.00  175.00  176.00  177.00  178.00  179.00 
180.00  181.00  182.00  183.00  184.00  185.00  186.00  187.00  188.00  189.00 
190.00  191.00  192.00  193.00  194.00  195.00  196.00  197.00  198.00  199.00 
# New slice

Reading it back in is very easy, as long as we know the shape of the original array. We can just do numpy.loadtxt('test.txt').reshape((4,5,10)). As an example (You can do this in one line, I'm just being verbose to clarify things):

# Read the array from disk
new_data = np.loadtxt('test.txt')

# Note that this returned a 2D array!
print new_data.shape

# However, going back to 3D is easy if we know the 
# original shape of the array
new_data = new_data.reshape((4,5,10))
    
# Just to check that they're the same...
assert np.all(new_data == data)

Saving any file to in the database, just convert it to a byte array?

Yes, generally the best way to store a file in a database is to save the byte array in a BLOB column. You will probably want a couple of columns to additionally store the file's metadata such as name, extension, and so on.

It is not always a good idea to store files in the database - for instance, the database size will grow fast if you store files in it. But that all depends on your usage scenario.

Read CSV file column by column

I sugges to use the Apache Commons CSV https://commons.apache.org/proper/commons-csv/

Here is one example:

    Path currentRelativePath = Paths.get("");
    String currentPath = currentRelativePath.toAbsolutePath().toString();
    String csvFile = currentPath + "/pathInYourProject/test.csv";

    Reader in;
    Iterable<CSVRecord> records = null;
    try
    {
        in = new FileReader(csvFile);
        records = CSVFormat.EXCEL.withHeader().parse(in); // header will be ignored
    }
    catch (IOException e)
    {
        e.printStackTrace();
    }

    for (CSVRecord record : records) {
        String line = "";
        for ( int i=0; i < record.size(); i++)
        {
            if ( line == "" )
                line = line.concat(record.get(i));
            else
                line = line.concat("," + record.get(i));
        }
        System.out.println("read line: " + line);
    }

It automaticly recognize , and " but not ; (maybe it can be configured...).

My example file is:

col1,col2,col3
val1,"val2",val3
"val4",val5
val6;val7;"val8"

And output is:

read line: val1,val2,val3
read line: val4,val5
read line: val6;val7;"val8"

Last line is considered like one value.

How to add a new line of text to an existing file in Java?

Try: "\r\n"

Java 7 example:

// append = true
try(PrintWriter output = new PrintWriter(new FileWriter("log.txt",true))) 
{
    output.printf("%s\r\n", "NEWLINE");
} 
catch (Exception e) {}

How to copy a file from one directory to another using PHP?

Hi guys wanted to also add on how to copy using a dynamic copying and pasting.

let say we don't know the actual folder the user will create but we know in that folder we need files to be copied to, to activate some function like delete, update, views etc.

you can use something like this... I used this code in one of the complex project which I am currently busy on. i just build it myself because all answers i got on the internet was giving me an error.

    $dirPath1 = "users/$uniqueID"; #creating main folder and where $uniqueID will be called by a database when a user login.
    $result = mkdir($dirPath1, 0755);
            $dirPath2 = "users/$uniqueID/profile"; #sub folder
            $result = mkdir($dirPath2, 0755);
                $dirPath3 = "users/$uniqueID/images"; #sub folder 
                $result = mkdir($dirPath3, 0755);
                    $dirPath4 = "users/$uniqueID/uploads";#sub folder
                    $result = mkdir($dirPath4, 0755);
                    @copy('blank/dashboard.php', 'users/'.$uniqueID.'/dashboard.php');#from blank folder to dynamic user created folder
                    @copy('blank/views.php', 'users/'.$uniqueID.'/views.php'); #from blank folder to dynamic user created folder
                    @copy('blank/upload.php', 'users/'.$uniqueID.'/upload.php'); #from blank folder to dynamic user created folder
                    @copy('blank/delete.php', 'users/'.$uniqueID.'/delete.php'); #from blank folder to dynamic user created folder

I think facebook or twitter uses something like this to build every new user dashboard dynamic....

How to open a file for both reading and writing?

r+ is the canonical mode for reading and writing at the same time. This is not different from using the fopen() system call since file() / open() is just a tiny wrapper around this operating system call.

Copy entire directory contents to another directory?

With Groovy, you can leverage Ant to do:

new AntBuilder().copy( todir:'/path/to/destination/folder' ) {
  fileset( dir:'/path/to/src/folder' )
}

AntBuilder is part of the distribution and the automatic imports list which means it is directly available for any groovy code.

How to read a local text file?

You need to check for status 0 (as when loading files locally with XMLHttpRequest, you don't get a status returned because it's not from a Webserver)

function readTextFile(file)
{
    var rawFile = new XMLHttpRequest();
    rawFile.open("GET", file, false);
    rawFile.onreadystatechange = function ()
    {
        if(rawFile.readyState === 4)
        {
            if(rawFile.status === 200 || rawFile.status == 0)
            {
                var allText = rawFile.responseText;
                alert(allText);
            }
        }
    }
    rawFile.send(null);
}

And specify file:// in your filename:

readTextFile("file:///C:/your/path/to/file.txt");

Python read JSON file and modify

try this script:

with open("data.json") as f:
    data = json.load(f)
    data["id"] = 134
    json.dump(data, open("data.json", "w"), indent = 4)

the result is:

{
    "name":"mynamme",
    "id":134
}

Just the arrangement is different, You can solve the problem by converting the "data" type to a list, then arranging it as you wish, then returning it and saving the file, like that:

index_add = 0
with open("data.json") as f:
    data = json.load(f)
    data_li = [[k, v] for k, v in data.items()]
    data_li.insert(index_add, ["id", 134])
    data = {data_li[i][0]:data_li[i][1] for i in range(0, len(data_li))}
    json.dump(data, open("data.json", "w"), indent = 4)

the result is:

{
    "id":134,
    "name":"myname"
}

you can add if condition in order not to repeat the key, just change it, like that:

index_add = 0
n_k = "id"
n_v = 134
with open("data.json") as f:
    data = json.load(f)
    if n_k in data:
        data[n_k] = n_v
    else:
       data_li = [[k, v] for k, v in data.items()]
       data_li.insert(index_add, [n_k, n_v])
       data = {data_li[i][0]:data_li[i][1] for i in range(0, len(data_li))}
    json.dump(data, open("data.json", "w"), indent = 4)

Write lines of text to a file in R

To round out the possibilities, you can use writeLines() with sink(), if you want:

> sink("tempsink", type="output")
> writeLines("Hello\nWorld")
> sink()
> file.show("tempsink", delete.file=TRUE)
Hello
World

To me, it always seems most intuitive to use print(), but if you do that the output won't be what you want:

...
> print("Hello\nWorld")
...
[1] "Hello\nWorld"

PHP: How to check if image file exists?

If the file is on your local domain, you don't need to put the full URL. Only the path to the file. If the file is in a different directory, then you need to preface the path with "."

$file = './images/image.jpg';
if (file_exists($file)) {}

Often times the "." is left off which will cause the file to be shown as not existing, when it in fact does.

C read file line by line

A complete, fgets() solution:

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

#define MAX_LEN 256

int main(void)
{
    FILE* fp;
    fp = fopen("file.txt", "r");
    if (fp == NULL) {
      perror("Failed: ");
      return 1;
    }

    char buffer[MAX_LEN];
    // -1 to allow room for NULL terminator for really long string
    while (fgets(buffer, MAX_LEN - 1, fp))
    {
        // Remove trailing newline
        buffer[strcspn(buffer, "\n")] = 0;
        printf("%s\n", buffer);
    }

    fclose(fp);
    return 0;
}

Output:

First line of file
Second line of file
Third (and also last) line of file

Remember, if you want to read from Standard Input (rather than a file as in this case), then all you have to do is pass stdin as the third parameter of fgets() method, like this:

while(fgets(buffer, MAX_LEN - 1, stdin))

Appendix

Removing trailing newline character from fgets() input

how to detect a file is opened or not in c

How to read file from res/raw by name

Here is example of taking XML file from raw folder:

 InputStream XmlFileInputStream = getResources().openRawResource(R.raw.taskslists5items); // getting XML

Then you can:

 String sxml = readTextFile(XmlFileInputStream);

when:

 public String readTextFile(InputStream inputStream) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        byte buf[] = new byte[1024];
        int len;
        try {
            while ((len = inputStream.read(buf)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.close();
            inputStream.close();
        } catch (IOException e) {

        }
        return outputStream.toString();
    }

Create Excel files from C# without office

Try EPPlus if you use Excel 2007. Supports ranges, cellstyling, charts, shapes, pictures and a lot of other stuff

Write output to a text file in PowerShell

The simplest way is to just redirect the output, like so:

Compare-Object $(Get-Content c:\user\documents\List1.txt) $(Get-Content c:\user\documents\List2.txt) > c:\user\documents\diff_output.txt

> will cause the output file to be overwritten if it already exists.
>> will append new text to the end of the output file if it already exists.

Python, add items from txt file into a list

Read the documentation:

with open('names.txt', 'r') as f:
    myNames = f.readlines()

The others already provided answers how to get rid of the newline character.

Update:

Fred Larson provides a nice solution in his comment:

with open('names.txt', 'r') as f:
    myNames = [line.strip() for line in f]

How do I add a resources folder to my Java project in Eclipse

Try To Give Full path for reading image.

Example image = ImageIO.read(new File("D:/work1/Jan14Stackoverflow/src/Strawberry.jpg"));

your code is not producing any exception after giving the full path. If you want to just read an image file in java code. Refer the following - http://docs.oracle.com/javase/tutorial/2d/images/examples/LoadImageApp.java

If the object of your class is created at end your code works fine for me and displays the image

// PracticeFrame pframe = new PracticeFrame();//comment this

new PracticeFrame().add(panel);

How to delete only the content of file in python

I think the easiest is to simply open the file in write mode and then close it. For example, if your file myfile.dat contains:

"This is the original content"

Then you can simply write:

f = open('myfile.dat', 'w')
f.close()

This would erase all the content. Then you can write the new content to the file:

f = open('myfile.dat', 'w')
f.write('This is the new content!')
f.close()

Trying to create a file in Android: open failed: EROFS (Read-only file system)

To use internal storage for the application, you don't need permission, but you may need to use: File directory = getApplication().getCacheDir(); to get the allowed directory for the app.

Or:
getCashDir(); <-- should work
context.getCashDir(); (if in a broadcast receiver)
getDataDir(); <--Api 24

Renaming a directory in C#

There is no difference between moving and renaming; you should simply call Directory.Move.

In general, if you're only doing a single operation, you should use the static methods in the File and Directory classes instead of creating FileInfo and DirectoryInfo objects.

For more advice when working with files and directories, see here.

Delete all files in directory (but not directory) - one liner solution

Do you mean like?

for(File file: dir.listFiles()) 
    if (!file.isDirectory()) 
        file.delete();

This will only delete files, not directories.

Cross-browser custom styling for file upload button

Please find below a way that works on all browsers. Basically I put the input on top the image. I make it huge using font-size so the user is always clicking the upload button.

_x000D_
_x000D_
.myFile {_x000D_
  position: relative;_x000D_
  overflow: hidden;_x000D_
  float: left;_x000D_
  clear: left;_x000D_
}_x000D_
.myFile input[type="file"] {_x000D_
  display: block;_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  right: 0;_x000D_
  opacity: 0;_x000D_
  font-size: 100px;_x000D_
  filter: alpha(opacity=0);_x000D_
  cursor: pointer;_x000D_
}
_x000D_
<label class="myFile">_x000D_
  <img src="http://wscont1.apps.microsoft.com/winstore/1x/c37a9d99-6698-4339-acf3-c01daa75fb65/Icon.13385.png" alt="" />_x000D_
  <input type="file" />_x000D_
</label>
_x000D_
_x000D_
_x000D_

Closing a file after File.Create

File.WriteAllText(file,content)

create write close

File.WriteAllBytes--   type binary

:)

Creating files in C++

#include <iostream>
#include <fstream>

int main() {
  std::ofstream o("Hello.txt");

  o << "Hello, World\n" << std::endl;

  return 0;
}

ValueError : I/O operation on closed file

Indent correctly; your for statement should be inside the with block:

import csv    

with open('v.csv', 'w') as csvfile:
    cwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL)

    for w, c in p.items():
        cwriter.writerow(w + c)

Outside the with block, the file is closed.

>>> with open('/tmp/1', 'w') as f:
...     print(f.closed)
... 
False
>>> print(f.closed)
True

How to search file text for a pattern and replace it with a given value

There isn't really a way to edit files in-place. What you usually do when you can get away with it (i.e. if the files are not too big) is, you read the file into memory (File.read), perform your substitutions on the read string (String#gsub) and then write the changed string back to the file (File.open, File#write).

If the files are big enough for that to be unfeasible, what you need to do, is read the file in chunks (if the pattern you want to replace won't span multiple lines then one chunk usually means one line - you can use File.foreach to read a file line by line), and for each chunk perform the substitution on it and append it to a temporary file. When you're done iterating over the source file, you close it and use FileUtils.mv to overwrite it with the temporary file.

C Programming: How to read the whole file contents into a buffer

Portability between Linux and Windows is a big headache, since Linux is a POSIX-conformant system with - generally - a proper, high quality toolchain for C, whereas Windows doesn't even provide a lot of functions in the C standard library.

However, if you want to stick to the standard, you can write something like this:

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

FILE *f = fopen("textfile.txt", "rb");
fseek(f, 0, SEEK_END);
long fsize = ftell(f);
fseek(f, 0, SEEK_SET);  /* same as rewind(f); */

char *string = malloc(fsize + 1);
fread(string, 1, fsize, f);
fclose(f);

string[fsize] = 0;

Here string will contain the contents of the text file as a properly 0-terminated C string. This code is just standard C, it's not POSIX-specific (although that it doesn't guarantee it will work/compile on Windows...)

How do I serialize an object and save it to a file in Android?

I've tried this 2 options (read/write), with plain objects, array of objects (150 objects), Map:

Option1:

FileOutputStream fos = context.openFileOutput(fileName, Context.MODE_PRIVATE);
ObjectOutputStream os = new ObjectOutputStream(fos);
os.writeObject(this);
os.close();

Option2:

SharedPreferences mPrefs=app.getSharedPreferences(app.getApplicationInfo().name, Context.MODE_PRIVATE);
SharedPreferences.Editor ed=mPrefs.edit();
Gson gson = new Gson(); 
ed.putString("myObjectKey", gson.toJson(objectToSave));
ed.commit();

Option 2 is twice quicker than option 1

The option 2 inconvenience is that you have to make specific code for read:

Gson gson = new Gson();
JsonParser parser=new JsonParser();
//object arr example
JsonArray arr=parser.parse(mPrefs.getString("myArrKey", null)).getAsJsonArray();
events=new Event[arr.size()];
int i=0;
for (JsonElement jsonElement : arr)
    events[i++]=gson.fromJson(jsonElement, Event.class);
//Object example
pagination=gson.fromJson(parser.parse(jsonPagination).getAsJsonObject(), Pagination.class);

Reading a text file in MATLAB line by line

If you really want to process your file line by line, a solution might be to use fgetl:

  1. Open the data file with fopen
  2. Read the next line into a character array using fgetl
  3. Retreive the data you need using sscanf on the character array you just read
  4. Perform any relevant test
  5. Output what you want to another file
  6. Back to point 2 if you haven't reached the end of your file.

Unlike the previous answer, this is not very much in the style of Matlab but it might be more efficient on very large files.

Hope this will help.

Python recursive folder read

If you want a flat list of all paths under a given dir (like find . in the shell):

   files = [ 
       os.path.join(parent, name)
       for (parent, subdirs, files) in os.walk(YOUR_DIRECTORY)
       for name in files + subdirs
   ]

To only include full paths to files under the base dir, leave out + subdirs.

Easiest way to read from and write to files

The easiest way to read from a file and write to a file:

//Read from a file
string something = File.ReadAllText("C:\\Rfile.txt");

//Write to a file
using (StreamWriter writer = new StreamWriter("Wfile.txt"))
{
    writer.WriteLine(something);
}

Print string to text file

If you are using Python3.

then you can use Print Function :

your_data = {"Purchase Amount": 'TotalAmount'}
print(your_data,  file=open('D:\log.txt', 'w'))

For python2

this is the example of Python Print String To Text File

def my_func():
    """
    this function return some value
    :return:
    """
    return 25.256


def write_file(data):
    """
    this function write data to file
    :param data:
    :return:
    """
    file_name = r'D:\log.txt'
    with open(file_name, 'w') as x_file:
        x_file.write('{} TotalAmount'.format(data))


def run():
    data = my_func()
    write_file(data)


run()

getResourceAsStream() vs FileInputStream

FileInputStream will load a the file path you pass to the constructor as relative from the working directory of the Java process. Usually in a web container, this is something like the bin folder.

getResourceAsStream() will load a file path relative from your application's classpath.

How to safely open/close files in python 2.4

No need to close the file according to the docs if you use with:

It is good practice to use the with keyword when dealing with file objects. This has the advantage that the file is properly closed after its suite finishes, even if an exception is raised on the way. It is also much shorter than writing equivalent try-finally blocks:

>>> with open('workfile', 'r') as f:
...     read_data = f.read()
>>> f.closed
True

More here: https://docs.python.org/2/tutorial/inputoutput.html#methods-of-file-objects

Objective-C: Reading a file line by line

You can use NSInputStream which has a basic implementation for file streams. You can read bytes into a buffer (read:maxLength: method). You have to scan the buffer for newlines yourself.

How can I open multiple files using "with open" in Python?

With python 2.6 It will not work, we have to use below way to open multiple files:

with open('a', 'w') as a:
    with open('b', 'w') as b:

Reading input files by line using read command in shell scripting skips last line

read reads until it finds a newline character or the end of file, and returns a non-zero exit code if it encounters an end-of-file. So it's quite possible for it to both read a line and return a non-zero exit code.

Consequently, the following code is not safe if the input might not be terminated by a newline:

while read LINE; do
  # do something with LINE
done

because the body of the while won't be executed on the last line.

Technically speaking, a file not terminated with a newline is not a text file, and text tools may fail in odd ways on such a file. However, I'm always reluctant to fall back on that explanation.

One way to solve the problem is to test if what was read is non-empty (-n):

while read -r LINE || [[ -n $LINE ]]; do
  # do something with LINE
done

Other solutions include using mapfile to read the file into an array, piping the file through some utility which is guaranteed to terminate the last line properly (grep ., for example, if you don't want to deal with blank lines), or doing the iterative processing with a tool like awk (which is usually my preference).

Note that -r is almost certainly needed in the read builtin; it causes read to not reinterpret \-sequences in the input.

How to delete a whole folder and content?

I'm using this recursive function to do the job:

public static void deleteDirAndContents(@NonNull File mFile){
    if (mFile.isDirectory() && mFile.listFiles() != null && mFile.listFiles().length > 0x0) {
        for (File file : mFile.listFiles()) {
            deleteDirAndContents(file);
        }
    } else {
        mFile.delete();
    }
}

The function checks if it is a directory or a file.

If it is a directory checks if it has child files, if it has child files will call herself again passing the children and repeating.

If it is a file it delete it.

(Don't use this function to clear the app cache by passing the cache dir because it will delete the cache dir too so the app will crash... If you want to clear the cache you use this function that won't delete the dir you pass to it:

public static void deleteDirContents(@NonNull File mFile){
        if (mFile.isDirectory() && mFile.listFiles() != null && mFile.listFiles().length > 0x0) {
            for (File file : mFile.listFiles()) {
                deleteDirAndContents(file);
            }
        }
    }

or you can check if it is the cache dir using:

if (!mFile.getAbsolutePath().equals(context.getCacheDir().getAbsolutePath())) {
    mFile.delete();
}

Example code to clear app cache:

public static void clearAppCache(Context context){
        try {
            File cache = context.getCacheDir();
            FilesUtils.deleteDirContents(cache);
        } catch (Exception e){
            MyLogger.onException(TAG, e);
        }
    }

Bye, Have a nice day & coding :D

Read a file one line at a time in node.js?

I wrap the whole logic of daily line processing as a npm module: line-kit https://www.npmjs.com/package/line-kit

_x000D_
_x000D_
// example_x000D_
var count = 0_x000D_
require('line-kit')(require('fs').createReadStream('/etc/issue'),_x000D_
                    (line) => { count++; },_x000D_
                    () => {console.log(`seen ${count} lines`)})
_x000D_
_x000D_
_x000D_

Read file line by line using ifstream in C++

Since your coordinates belong together as pairs, why not write a struct for them?

struct CoordinatePair
{
    int x;
    int y;
};

Then you can write an overloaded extraction operator for istreams:

std::istream& operator>>(std::istream& is, CoordinatePair& coordinates)
{
    is >> coordinates.x >> coordinates.y;

    return is;
}

And then you can read a file of coordinates straight into a vector like this:

#include <fstream>
#include <iterator>
#include <vector>

int main()
{
    char filename[] = "coordinates.txt";
    std::vector<CoordinatePair> v;
    std::ifstream ifs(filename);
    if (ifs) {
        std::copy(std::istream_iterator<CoordinatePair>(ifs), 
                std::istream_iterator<CoordinatePair>(),
                std::back_inserter(v));
    }
    else {
        std::cerr << "Couldn't open " << filename << " for reading\n";
    }
    // Now you can work with the contents of v
}

Save bitmap to file function

Here is the function which help you

private void saveBitmap(Bitmap bitmap,String path){
        if(bitmap!=null){
            try {
                FileOutputStream outputStream = null;
                try {
                    outputStream = new FileOutputStream(path); //here is set your file path where you want to save or also here you can set file object directly

                    bitmap.compress(Bitmap.CompressFormat.PNG, 100, outputStream); // bitmap is your Bitmap instance, if you want to compress it you can compress reduce percentage
                    // PNG is a lossless format, the compression factor (100) is ignored
                } catch (Exception e) {
                    e.printStackTrace();
                } finally {
                    try {
                        if (outputStream != null) {
                            outputStream.close();
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                }
            } catch (Exception e) {
                e.printStackTrace();
            }    
        }
    }

Split files using tar, gz, zip, or bzip2

use tar to split into multiple archives

there are plenty of programs that will work with tar files on windows, including cygwin.

How to both read and write a file in C#

You need a single stream, opened for both reading and writing.

FileStream fileStream = new FileStream(
      @"c:\words.txt", FileMode.OpenOrCreate, 
      FileAccess.ReadWrite, FileShare.None);

Does Java have a path joining method?

Try:

String path1 = "path1";
String path2 = "path2";

String joinedPath = new File(path1, path2).toString();

How do I check if a file exists in Java?

Don't use File constructor with String.
This may not work!
Instead of this use URI:

File f = new File(new URI("file:///"+filePathString.replace('\\', '/')));
if(f.exists() && !f.isDirectory()) { 
    // to do
}

How to append new data onto a new line

I presume that all you are wanting is simple string concatenation:

def storescores():

   hs = open("hst.txt","a")
   hs.write(name + " ")
   hs.close() 

Alternatively, change the " " to "\n" for a newline.

List all files from a directory recursively with Java

In Java 8, it's a 1-liner via Files.find() with an arbitrarily large depth (eg 999) and BasicFileAttributes of isRegularFile()

public static printFnames(String sDir) {
    Files.find(Paths.get(sDir), 999, (p, bfa) -> bfa.isRegularFile()).forEach(System.out::println);
}

To add more filtering, enhance the lambda, for example all jpg files modified in the last 24 hours:

(p, bfa) -> bfa.isRegularFile()
  && p.getFileName().toString().matches(".*\\.jpg")
  && bfa.lastModifiedTime().toMillis() > System.currentMillis() - 86400000

Batch Renaming of Files in a Directory

If you would like to modify file names in an editor (such as vim), the click library comes with the command click.edit(), which can be used to receive user input from an editor. Here is an example of how it can be used to refactor files in a directory.

import click
from pathlib import Path

# current directory
direc_to_refactor = Path(".")

# list of old file paths
old_paths = list(direc_to_refactor.iterdir())

# list of old file names
old_names = [str(p.name) for p in old_paths]

# modify old file names in an editor,
# and store them in a list of new file names
new_names = click.edit("\n".join(old_names)).split("\n")

# refactor the old file names
for i in range(len(old_paths)):
    old_paths[i].replace(direc_to_refactor / new_names[i])

I wrote a command line application that uses the same technique, but that reduces the volatility of this script, and comes with more options, such as recursive refactoring. Here is the link to the github page. This is useful if you like command line applications, and are interested in making some quick edits to file names. (My application is similar to the "bulkrename" command found in ranger).

How to delete a file or folder?

shutil.rmtree is the asynchronous function, so if you want to check when it complete, you can use while...loop

import os
import shutil

shutil.rmtree(path)

while os.path.exists(path):
  pass

print('done')

How to read numbers separated by space using scanf

int main()
{
char string[200];
int g,a,i,G[20],A[20],met;

gets(string);
g=convert_input(G,string);

for(i=0;i<=g;i++)
    printf("\n%d>>%d",i,G[i]);
return 0;
}

int convert_input(int K[],char string[200])
{
int j=0,i=0,temp=0;
while(string[i]!='\0')
{
    temp=0;
    while(string[i]!=' ' && string[i]!='\0')
        temp=temp*10 + (string[i++]-'0') ;
    if(string[i]==' ')
        i++;
    K[j++]=temp;
}
return j-1;
}

Groovy write to file (newline)

As @Steven points out, a better way would be:

public void writeToFile(def directory, def fileName, def extension, def infoList) {
  new File("$directory/$fileName$extension").withWriter { out ->
    infoList.each {
      out.println it
    }
  }
}

As this handles the line separator for you, and handles closing the writer as well

(and doesn't open and close the file each time you write a line, which could be slow in your original version)

Can .NET load and parse a properties file equivalent to Java Properties class?

No there is no built-in support for this.

You have to make your own "INIFileReader". Maybe something like this?

var data = new Dictionary<string, string>();
foreach (var row in File.ReadAllLines(PATH_TO_FILE))
  data.Add(row.Split('=')[0], string.Join("=",row.Split('=').Skip(1).ToArray()));

Console.WriteLine(data["ServerName"]);

Edit: Updated to reflect Paul's comment.

Read a text file in R line by line

I suggest you check out chunked and disk.frame. They both have functions for reading in CSVs chunk-by-chunk.

In particular, disk.frame::csv_to_disk.frame may be the function you are after?

Batch file to copy files from one folder to another folder

To bypass the 'specify a file name or directory name on the target (F = file, D = directory)?' prompt with xcopy, you can do the following...

echo f | xcopy /f /y srcfile destfile

or for those of us just copying large substructures/folders:

use /i which specifies destination must be a directory if copying more than one file

Is there a way to check if a file is in use?

Use this to check if a file is locked:

using System.IO;
using System.Runtime.InteropServices;
internal static class Helper
{
const int ERROR_SHARING_VIOLATION = 32;
const int ERROR_LOCK_VIOLATION = 33;

private static bool IsFileLocked(Exception exception)
{
    int errorCode = Marshal.GetHRForException(exception) & ((1 << 16) - 1);
    return errorCode == ERROR_SHARING_VIOLATION || errorCode == ERROR_LOCK_VIOLATION;
}

internal static bool CanReadFile(string filePath)
{
    //Try-Catch so we dont crash the program and can check the exception
    try {
        //The "using" is important because FileStream implements IDisposable and
        //"using" will avoid a heap exhaustion situation when too many handles  
        //are left undisposed.
        using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None)) {
            if (fileStream != null) fileStream.Close();  //This line is me being overly cautious, fileStream will never be null unless an exception occurs... and I know the "using" does it but its helpful to be explicit - especially when we encounter errors - at least for me anyway!
        }
    }
    catch (IOException ex) {
        //THE FUNKY MAGIC - TO SEE IF THIS FILE REALLY IS LOCKED!!!
        if (IsFileLocked(ex)) {
            // do something, eg File.Copy or present the user with a MsgBox - I do not recommend Killing the process that is locking the file
            return false;
        }
    }
    finally
    { }
    return true;
}
}

For performance reasons I recommend you read the file content in the same operation. Here are some examples:

public static byte[] ReadFileBytes(string filePath)
{
    byte[] buffer = null;
    try
    {
        using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
        {
            int length = (int)fileStream.Length;  // get file length
            buffer = new byte[length];            // create buffer
            int count;                            // actual number of bytes read
            int sum = 0;                          // total number of bytes read

            // read until Read method returns 0 (end of the stream has been reached)
            while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
                sum += count;  // sum is a buffer offset for next reading

            fileStream.Close(); //This is not needed, just me being paranoid and explicitly releasing resources ASAP
        }
    }
    catch (IOException ex)
    {
        //THE FUNKY MAGIC - TO SEE IF THIS FILE REALLY IS LOCKED!!!
        if (IsFileLocked(ex))
        {
            // do something? 
        }
    }
    catch (Exception ex)
    {
    }
    finally
    {
    }
    return buffer;
}

public static string ReadFileTextWithEncoding(string filePath)
{
    string fileContents = string.Empty;
    byte[] buffer;
    try
    {
        using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
        {
            int length = (int)fileStream.Length;  // get file length
            buffer = new byte[length];            // create buffer
            int count;                            // actual number of bytes read
            int sum = 0;                          // total number of bytes read

            // read until Read method returns 0 (end of the stream has been reached)
            while ((count = fileStream.Read(buffer, sum, length - sum)) > 0)
            {
                sum += count;  // sum is a buffer offset for next reading
            }

            fileStream.Close(); //Again - this is not needed, just me being paranoid and explicitly releasing resources ASAP

            //Depending on the encoding you wish to use - I'll leave that up to you
            fileContents = System.Text.Encoding.Default.GetString(buffer);
        }
    }
    catch (IOException ex)
    {
        //THE FUNKY MAGIC - TO SEE IF THIS FILE REALLY IS LOCKED!!!
        if (IsFileLocked(ex))
        {
            // do something? 
        }
    }
    catch (Exception ex)
    {
    }
    finally
    { }     
    return fileContents;
}

public static string ReadFileTextNoEncoding(string filePath)
{
    string fileContents = string.Empty;
    byte[] buffer;
    try
    {
        using (FileStream fileStream = File.Open(filePath, FileMode.Open, FileAccess.ReadWrite, FileShare.None))
        {
            int length = (int)fileStream.Length;  // get file length
            buffer = new byte[length];            // create buffer
            int count;                            // actual number of bytes read
            int sum = 0;                          // total number of bytes read

            // read until Read method returns 0 (end of the stream has been reached)
            while ((count = fileStream.Read(buffer, sum, length - sum)) > 0) 
            {
                sum += count;  // sum is a buffer offset for next reading
            }

            fileStream.Close(); //Again - this is not needed, just me being paranoid and explicitly releasing resources ASAP

            char[] chars = new char[buffer.Length / sizeof(char) + 1];
            System.Buffer.BlockCopy(buffer, 0, chars, 0, buffer.Length);
            fileContents = new string(chars);
        }
    }
    catch (IOException ex)
    {
        //THE FUNKY MAGIC - TO SEE IF THIS FILE REALLY IS LOCKED!!!
        if (IsFileLocked(ex))
        {
            // do something? 
        }
    }
    catch (Exception ex)
    {
    }
    finally
    {
    }

    return fileContents;
}

Try it out yourself:

byte[] output1 = Helper.ReadFileBytes(@"c:\temp\test.txt");
string output2 = Helper.ReadFileTextWithEncoding(@"c:\temp\test.txt");
string output3 = Helper.ReadFileTextNoEncoding(@"c:\temp\test.txt");

Read file from line 2 or skip header row

f = open(fname,'r')
lines = f.readlines()[1:]
f.close()

Writing a list to a file with Python

This logic will first convert the items in list to string(str). Sometimes the list contains a tuple like

alist = [(i12,tiger), 
(113,lion)]

This logic will write to file each tuple in a new line. We can later use eval while loading each tuple when reading the file:

outfile = open('outfile.txt', 'w') # open a file in write mode
for item in list_to_persistence:    # iterate over the list items
   outfile.write(str(item) + '\n') # write to the file
outfile.close()   # close the file 

Get last n lines of a file, similar to tail

Simple :

with open("test.txt") as f:
data = f.readlines()
tail = data[-2:]
print(''.join(tail)

How to delete a folder with files using Java

You can use FileUtils.deleteDirectory. JAVA can't delete the non-empty foldres with File.delete().

File being used by another process after using File.Create()

I think I know the reason for this exception. You might be running this code snippet in multiple threads.

How to read a file into vector in C++?

Just a piece of advice. Instead of writing

for (int i=0; i=((Main.size())-1); i++) {
   cout << Main[i] << '\n';
}

as suggested above, write a:

for (vector<double>::iterator it=Main.begin(); it!=Main.end(); it++) {
   cout << *it << '\n';
}

to use iterators. If you have C++11 support, you can declare i as auto i=Main.begin() (just a handy shortcut though)

This avoids the nasty one-position-out-of-bound error caused by leaving out a -1 unintentionally.

How to read and write into file using JavaScript?

Writing this answer for people who wants to get a file to download with specific content from javascript. I was struggling with the same thing.

const data = {name: 'Ronn', age: 27};              //sample json
const a = document.createElement('a');
const blob = new Blob([JSON.stringify(data)]);
a.href = URL.createObjectURL(blob);
a.download = 'sample-profile';                     //filename to download
a.click();

Check Blob documentation here - Blob MDN

Getting path relative to the current working directory?

public string MakeRelativePath(string workingDirectory, string fullPath)
{
    string result = string.Empty;
    int offset;

    // this is the easy case.  The file is inside of the working directory.
    if( fullPath.StartsWith(workingDirectory) )
    {
        return fullPath.Substring(workingDirectory.Length + 1);
    }

    // the hard case has to back out of the working directory
    string[] baseDirs = workingDirectory.Split(new char[] { ':', '\\', '/' });
    string[] fileDirs = fullPath.Split(new char[] { ':', '\\', '/' });

    // if we failed to split (empty strings?) or the drive letter does not match
    if( baseDirs.Length <= 0 || fileDirs.Length <= 0 || baseDirs[0] != fileDirs[0] )
    {
        // can't create a relative path between separate harddrives/partitions.
        return fullPath;
    }

    // skip all leading directories that match
    for (offset = 1; offset < baseDirs.Length; offset++)
    {
        if (baseDirs[offset] != fileDirs[offset])
            break;
    }

    // back out of the working directory
    for (int i = 0; i < (baseDirs.Length - offset); i++)
    {
        result += "..\\";
    }

    // step into the file path
    for (int i = offset; i < fileDirs.Length-1; i++)
    {
        result += fileDirs[i] + "\\";
    }

    // append the file
    result += fileDirs[fileDirs.Length - 1];

    return result;
}

This code is probably not bullet-proof but this is what I came up with. It's a little more robust. It takes two paths and returns path B as relative to path A.

example:

MakeRelativePath("c:\\dev\\foo\\bar", "c:\\dev\\junk\\readme.txt")
//returns: "..\\..\\junk\\readme.txt"

MakeRelativePath("c:\\dev\\foo\\bar", "c:\\dev\\foo\\bar\\docs\\readme.txt")
//returns: "docs\\readme.txt"

How to Write text file Java

It does work with me. Make sure that you append ".txt" next to timeLog. I used it in a simple program opened with Netbeans and it writes the program in the main folder (where builder and src folders are).

Read a HTML file into a string variable in memory

Use File.ReadAllText(path_to_file) to read

How to pass a file path which is in assets folder to File(String path)?

Unless you unpack them, assets remain inside the apk. Accordingly, there isn't a path you can feed into a File. The path you've given in your question will work with/in a WebView, but I think that's a special case for WebView.

You'll need to unpack the file or use it directly.

If you have a Context, you can use context.getAssets().open("myfoldername/myfilename"); to open an InputStream on the file. With the InputStream you can use it directly, or write it out somewhere (after which you can use it with File).

How to create an Excel File with Nodejs?

Use msexcel-builder. Install it with:

npm install msexcel-builder

Then:

// Create a new workbook file in current working-path 
var workbook = excelbuilder.createWorkbook('./', 'sample.xlsx')

// Create a new worksheet with 10 columns and 12 rows 
var sheet1 = workbook.createSheet('sheet1', 10, 12);

// Fill some data 
sheet1.set(1, 1, 'I am title');
for (var i = 2; i < 5; i++)
  sheet1.set(i, 1, 'test'+i);

// Save it 
workbook.save(function(ok){
  if (!ok) 
    workbook.cancel();
  else
    console.log('congratulations, your workbook created');
});

How to copy a file to another path?

This is what I did to move a test file from the downloads to the desktop. I hope its useful.

private void button1_Click(object sender, EventArgs e)//Copy files to the desktop
    {
        string sourcePath = @"C:\Users\UsreName\Downloads";
        string targetPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop);
        string[] shortcuts = {
            "FileCopyTest.txt"};

        try
        {
            listbox1.Items.Add("Starting: Copy shortcuts to dektop.");
            for (int i = 0; i < shortcuts.Length; i++)
            {
                if (shortcuts[i]!= null)
                {
                    File.Copy(Path.Combine(sourcePath, shortcuts[i]), Path.Combine(targetPath, shortcuts[i]), true);                        
                    listbox1.Items.Add(shortcuts[i] + " was moved to desktop!");
                }
                else
                {
                    listbox1.Items.Add("Shortcut " + shortcuts[i] + " Not found!");
                }
            }
        }
        catch (Exception ex)
        {
            listbox1.Items.Add("Unable to Copy file. Error : " + ex);
        }
    }        

How to read a text file from server using JavaScript?

I really think your going about this in the wrong manner. Trying to download and parse a +3Mb text file is complete insanity. Why not parse the file on the server side, storing the results viva an ORM to a database(your choice, SQL is good but it also depends on the content key-value data works better on something like CouchDB) then use ajax to parse data on the client end.

Plus, an even better idea would to skip the text file entirely for even better performance if at all possible.

Scanner vs. BufferedReader

Following are the differences between BufferedReader and Scanner

  1. BufferedReader only read data but scanner also parse data.
  2. you can only read String using BufferedReader, but you can read int, long or float using Scanner.
  3. BufferedReader is older from Scanner,it exists from jdk 1.1 while Scanner was added on JDK 5 release.
  4. The Buffer size of BufferedReader is large(8KB) as compared to 1KB of Scanner.
  5. BufferedReader is more suitable for reading file with long String while Scanner is more suitable for reading small user input from command prompt.
  6. BufferedReader is synchronized but Scanner is not, which means you cannot share Scanner among multiple threads.
  7. BufferedReader is faster than Scanner because it doesn't spent time on parsing
  8. BufferedReader is a bit faster as compared to Scanner
  9. BufferedReader is from java.io package and Scanner is from java.util package on basis of the points we can select our choice.

Thanks

Getting the inputstream from a classpath resource (XML file)

ClassLoader.class.getResourceAsStream("/path/to/your/xml") and make sure that your compile script is copying the xml file to where in your CLASSPATH.

LOAD DATA INFILE Error Code : 13

There is one property in mysql configuration file under section [mysqld] with name - tmpdir

for example:

tmpdir = c:/temp (Windows) or tmpdir = /tmp (Linux)

and LOAD DATA INFILE command can perform read and write on this location only.

so if you put your file at that specified location then LOAD DATA INFILE can read/write any file easily.

One more solution

we can import data by following command too

load data local infile

In this case there is no need to move file to tmpdir, you can give the absolute path of file, but to execute this command, you need to change one flag value. The flag is

--local-infile

you can change its value by command prompt while getting access of mysql

mysql -u username -p --local-infile=1

Cheers

Saving response from Requests to file

As Peter already pointed out:

In [1]: import requests

In [2]: r = requests.get('https://api.github.com/events')

In [3]: type(r)
Out[3]: requests.models.Response

In [4]: type(r.content)
Out[4]: str

You may also want to check r.text.

Also: https://2.python-requests.org/en/latest/user/quickstart/

Reading entire html file to String?

There's the IOUtils.toString(..) utility from Apache Commons.

If you're using Guava there's also Files.readLines(..) and Files.toString(..).

MySQL said: Documentation #1045 - Access denied for user 'root'@'localhost' (using password: NO)

I think to troubleshoot your problem you should try the following:

  1. Check whether the MySQL service is running (Control Panel --> services)
  2. Use a MySQL client like SQLYOG to check whether you are able to connect to MYSQL Server with the username and password you are using in your code.
  3. Just try a sample php program, which fetches the data from table Ex. http://www.anyexample.com/programming/php/php_mysql_example__display_table_as_html.xml

Concatenate two NumPy arrays vertically

If the actual problem at hand is to concatenate two 1-D arrays vertically, and we are not fixated on using concatenate to perform this operation, I would suggest the use of np.column_stack:

In []: a = np.array([1,2,3])
In []: b = np.array([4,5,6])
In []: np.column_stack((a, b))
array([[1, 4],
       [2, 5],
       [3, 6]])

How to check for null in a single statement in scala?

Option(getObject) foreach (QueueManager add)

Setting Column width in Apache POI

Unfortunately there is only the function setColumnWidth(int columnIndex, int width) from class Sheet; in which width is a number of characters in the standard font (first font in the workbook) if your fonts are changing you cannot use it. There is explained how to calculate the width in function of a font size. The formula is:

width = Truncate([{NumOfVisibleChar} * {MaxDigitWidth} + {5PixelPadding}] / {MaxDigitWidth}*256) / 256

You can always use autoSizeColumn(int column, boolean useMergedCells) after inputting the data in your Sheet.

What's the fastest way to loop through an array in JavaScript?

It's just 2018 so an update could be nice...

And I really have to disagree with the accepted answer. It defers on different browsers. some do forEach faster, some for-loop, and some while here is a benchmark on all method http://jsben.ch/mW36e

arr.forEach( a => {
  // ...
}

and since you can see alot of for-loop like for(a = 0; ... ) then worth to mention that without 'var' variables will be define globally and this can dramatically affects on speed so it'll get slow.

Duff's device run faster on opera but not in firefox

_x000D_
_x000D_
var arr = arr = new Array(11111111).fill(255);_x000D_
var benches =     _x000D_
[ [ "empty", () => {_x000D_
  for(var a = 0, l = arr.length; a < l; a++);_x000D_
}]_x000D_
, ["for-loop", () => {_x000D_
  for(var a = 0, l = arr.length; a < l; ++a)_x000D_
    var b = arr[a] + 1;_x000D_
}]_x000D_
, ["for-loop++", () => {_x000D_
  for(var a = 0, l = arr.length; a < l; a++)_x000D_
    var b = arr[a] + 1;_x000D_
}]_x000D_
, ["for-loop - arr.length", () => {_x000D_
  for(var a = 0; a < arr.length; ++a )_x000D_
    var b = arr[a] + 1;_x000D_
}]_x000D_
, ["reverse for-loop", () => {_x000D_
  for(var a = arr.length - 1; a >= 0; --a )_x000D_
    var b = arr[a] + 1;_x000D_
}]_x000D_
,["while-loop", () => {_x000D_
  var a = 0, l = arr.length;_x000D_
  while( a < l ) {_x000D_
    var b = arr[a] + 1;_x000D_
    ++a;_x000D_
  }_x000D_
}]_x000D_
, ["reverse-do-while-loop", () => {_x000D_
  var a = arr.length - 1; // CAREFUL_x000D_
  do {_x000D_
    var b = arr[a] + 1;_x000D_
  } while(a--);   _x000D_
}]_x000D_
, ["forEach", () => {_x000D_
  arr.forEach( a => {_x000D_
    var b = a + 1;_x000D_
  });_x000D_
}]_x000D_
, ["for const..in (only 3.3%)", () => {_x000D_
  var ar = arr.slice(0,arr.length/33);_x000D_
  for( const a in ar ) {_x000D_
    var b = a + 1;_x000D_
  }_x000D_
}]_x000D_
, ["for let..in (only 3.3%)", () => {_x000D_
  var ar = arr.slice(0,arr.length/33);_x000D_
  for( let a in ar ) {_x000D_
    var b = a + 1;_x000D_
  }_x000D_
}]_x000D_
, ["for var..in (only 3.3%)", () => {_x000D_
  var ar = arr.slice(0,arr.length/33);_x000D_
  for( var a in ar ) {_x000D_
    var b = a + 1;_x000D_
  }_x000D_
}]_x000D_
, ["Duff's device", () => {_x000D_
  var len = arr.length;_x000D_
  var i, n = len % 8 - 1;_x000D_
_x000D_
  if (n > 0) {_x000D_
    do {_x000D_
      var b = arr[len-n] + 1;_x000D_
    } while (--n); // n must be greater than 0 here_x000D_
  }_x000D_
  n = (len * 0.125) ^ 0;_x000D_
  if (n > 0) { _x000D_
    do {_x000D_
      i = --n <<3;_x000D_
      var b = arr[i] + 1;_x000D_
      var c = arr[i+1] + 1;_x000D_
      var d = arr[i+2] + 1;_x000D_
      var e = arr[i+3] + 1;_x000D_
      var f = arr[i+4] + 1;_x000D_
      var g = arr[i+5] + 1;_x000D_
      var h = arr[i+6] + 1;_x000D_
      var k = arr[i+7] + 1;_x000D_
    }_x000D_
    while (n); // n must be greater than 0 here also_x000D_
  }_x000D_
}]];_x000D_
function bench(title, f) {_x000D_
  var t0 = performance.now();_x000D_
  var res = f();_x000D_
  return performance.now() - t0; // console.log(`${title} took ${t1-t0} msec`);_x000D_
}_x000D_
var globalVarTime = bench( "for-loop without 'var'", () => {_x000D_
  // Here if you forget to put 'var' so variables'll be global_x000D_
  for(a = 0, l = arr.length; a < l; ++a)_x000D_
     var b = arr[a] + 1;_x000D_
});_x000D_
var times = benches.map( function(a) {_x000D_
                      arr = new Array(11111111).fill(255);_x000D_
                      return [a[0], bench(...a)]_x000D_
                     }).sort( (a,b) => a[1]-b[1] );_x000D_
var max = times[times.length-1][1];_x000D_
times = times.map( a => {a[2] = (a[1]/max)*100; return a; } );_x000D_
var template = (title, time, n) =>_x000D_
  `<div>` +_x000D_
    `<span>${title} &nbsp;</span>` +_x000D_
    `<span style="width:${3+n/2}%">&nbsp;${Number(time.toFixed(3))}msec</span>` +_x000D_
  `</div>`;_x000D_
_x000D_
var strRes = times.map( t => template(...t) ).join("\n") + _x000D_
            `<br><br>for-loop without 'var' ${globalVarTime} msec.`;_x000D_
var $container = document.getElementById("container");_x000D_
$container.innerHTML = strRes;
_x000D_
body { color:#fff; background:#333; font-family:helvetica; }_x000D_
body > div > div {  clear:both   }_x000D_
body > div > div > span {_x000D_
  float:left;_x000D_
  width:43%;_x000D_
  margin:3px 0;_x000D_
  text-align:right;_x000D_
}_x000D_
body > div > div > span:nth-child(2) {_x000D_
  text-align:left;_x000D_
  background:darkorange;_x000D_
  animation:showup .37s .111s;_x000D_
  -webkit-animation:showup .37s .111s;_x000D_
}_x000D_
@keyframes showup { from { width:0; } }_x000D_
@-webkit-keyframes showup { from { width:0; } }
_x000D_
<div id="container"> </div>
_x000D_
_x000D_
_x000D_

Convert a PHP object to an associative array

Also you can use The Symfony Serializer Component

use Symfony\Component\Serializer\Encoder\JsonEncoder;
use Symfony\Component\Serializer\Normalizer\ObjectNormalizer;
use Symfony\Component\Serializer\Serializer;

$serializer = new Serializer([new ObjectNormalizer()], [new JsonEncoder()]);
$array = json_decode($serializer->serialize($object, 'json'), true);

Unique random string generation

Using Guid would be a pretty good way, but to get something looking like your example, you probably want to convert it to a Base64 string:

    Guid g = Guid.NewGuid();
    string GuidString = Convert.ToBase64String(g.ToByteArray());
    GuidString = GuidString.Replace("=","");
    GuidString = GuidString.Replace("+","");

I get rid of "=" and "+" to get a little closer to your example, otherwise you get "==" at the end of your string and a "+" in the middle. Here's an example output string:

"OZVV5TpP4U6wJthaCORZEQ"

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

A conditional insert for use typically in a MySQL script would be:

insert into t1(col1,col2,col3,...)
select val1,val2,val3,...
  from dual
 where [conditional predicate];

You need to use dummy table dual.

In this example, only the second insert-statement will actually insert data into the table:

create table t1(col1 int);
insert into t1(col1) select 1 from dual where 1=0;
insert into t1(col1) select 2 from dual where 1=1;
select * from t1;
+------+
| col1 |
+------+
|    2 |
+------+
1 row in set (0.00 sec)

How to save username and password in Git?

For global setting, open the terminal (from any where) run the following:

  git config --global user.name "your username"
  git config --global user.password "your password"

By that, any local git repo that you have on your machine will use that information.

You can individually config for each repo by doing:

  • open terminal at the repo folder.
  • run the following:

    git config user.name "your username"
    git config user.password "your password"
    

It affects only that folder (because your configuration is local).

Where can I find MySQL logs in phpMyAdmin?

If you are using XAMPP as your server, you'll find a logs directory as a child of the XAMPP directory. If you have not tried XAMPP, which runs on any system (Windows, Mac OS & Linux) find more here: http://www.apachefriends.org/en/xampp.html

DD/MM/YYYY Date format in Moment.js

You can use this

moment().format("DD/MM/YYYY");

However, this returns a date string in the specified format for today, not a moment date object. Doing the following will make it a moment date object in the format you want.

var someDateString = moment().format("DD/MM/YYYY");
var someDate = moment(someDateString, "DD/MM/YYYY");

Java GC (Allocation Failure)

"Allocation Failure" is a cause of GC cycle to kick in.

"Allocation Failure" means that no more space left in Eden to allocate object. So, it is normal cause of young GC.

Older JVM were not printing GC cause for minor GC cycles.

"Allocation Failure" is almost only possible cause for minor GC. Another reason for minor GC to kick could be CMS remark phase (if +XX:+ScavengeBeforeRemark is enabled).

How to use timeit module

The way timeit works is to run setup code once and then make repeated calls to a series of statements. So, if you want to test sorting, some care is required so that one pass at an in-place sort doesn't affect the next pass with already sorted data (that, of course, would make the Timsort really shine because it performs best when the data already partially ordered).

Here is an example of how to set up a test for sorting:

>>> import timeit

>>> setup = '''
import random

random.seed('slartibartfast')
s = [random.random() for i in range(1000)]
timsort = list.sort
'''

>>> print min(timeit.Timer('a=s[:]; timsort(a)', setup=setup).repeat(7, 1000))
0.334147930145

Note that the series of statements makes a fresh copy of the unsorted data on every pass.

Also, note the timing technique of running the measurement suite seven times and keeping only the best time -- this can really help reduce measurement distortions due to other processes running on your system.

Those are my tips for using timeit correctly. Hope this helps :-)

position: fixed doesn't work on iPad and iPhone

A lot of mobile browsers deliberately do not support position:fixed; on the grounds that fixed elements could get in the way on a small screen.

The Quirksmode.org site has a very good blog post that explains the problem: http://www.quirksmode.org/blog/archives/2010/12/the_fifth_posit.html

Also see this page for a compatibility chart showing which mobile browsers support position:fixed;: http://www.quirksmode.org/m/css.html

(but note that the mobile browser world is moving very quickly, so tables like this may not stay up-to-date for long!)

Update: iOS 5 and Android 4 are both reported to have position:fixed support now.

I tested iOS 5 myself in an Apple store today and can confirm that it does work with position fixed. There are issues with zooming in and panning around a fixed element though.

I found this compatibility table far more up to date and useful than the quirksmode one: http://caniuse.com/#search=fixed

It has up to date info on Android, Opera (mini and mobile) & iOS.

Ajax using https on an http page

Try JSONP.

most JS libraries make it just as easy as other AJAX calls, but internally use an iframe to do the query.

if you're not using JSON for your payload, then you'll have to roll your own mechanism around the iframe.

personally, i'd just redirect form the http:// page to the https:// one

Resizing an Image without losing any quality

Unless you're doing vector graphics, there's no way to resize an image without potentially losing some image quality.

How do I efficiently iterate over each entry in a Java Map?

Example of using iterator and generics:

Iterator<Map.Entry<String, String>> entries = myMap.entrySet().iterator();
while (entries.hasNext()) {
  Map.Entry<String, String> entry = entries.next();
  String key = entry.getKey();
  String value = entry.getValue();
  // ...
}

How do I write a custom init for a UIView subclass in Swift?

Here is how I do it on iOS 9 in Swift -

import UIKit

class CustomView : UIView {

    init() {
        super.init(frame: UIScreen.mainScreen().bounds);

        //for debug validation
        self.backgroundColor = UIColor.blueColor();
        print("My Custom Init");

        return;
    }

    required init?(coder aDecoder: NSCoder) { fatalError("init(coder:) has not been implemented"); }
}

Here is a full project with example:

Char array to hex string C++

You can try this code for converting bytes from packet to a null-terminated string and store to "string" variable for processing.

const int buffer_size = 2048;
// variable for storing buffer as printable HEX string
char data[buffer_size*2];
// receive message from socket
int ret = recvfrom(sock, buffer, sizeofbuffer, 0, reinterpret_cast<SOCKADDR *>(&from), &size);
// bytes converting cycle
for (int i=0,j=0; i<ret; i++,j+=2){ 
    char res[2]; 
    itoa((buffer[i] & 0xFF), res, 16);
        if (res[1] == 0) {
            data[j] = 0x30; data[j+1] = res[0];
        }else {
            data[j] = res[0]; data[j + 1] = res[1];
        }
}
// Null-Terminating the string with converted buffer
data[(ret * 2)] = 0;

When we send message with hex bytes 0x01020E0F, variable "data" had char array with string "01020e0f".

Duplicate ID, tag null, or parent id with another fragment for com.google.android.gms.maps.MapFragment

  1. As mentioned by @Justin Breitfeller, @Vidar Wahlberg solution is a hack which might not work in future version of Android.
  2. @Vidar Wahlberg perfer a hack because other solution might "cause the map to be recreated and redrawn, which isn't always desirable". Map redraw could be prevented by maintaining the old map fragment, rather than creating a new instance every time.
  3. @Matt solution doesn't work for me (IllegalStateException)
  4. As quoted by @Justin Breitfeller, "You cannot inflate a layout into a fragment when that layout includes a . Nested fragments are only supported when added to a fragment dynamically."

My solution:

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,                              Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_map_list, container, false);

    // init
    //mapFragment = (SupportMapFragment)getChildFragmentManager().findFragmentById(R.id.map);
    // don't recreate fragment everytime ensure last map location/state are maintain
    if (mapFragment == null) {
        mapFragment = SupportMapFragment.newInstance();
        mapFragment.getMapAsync(this);
    }
    FragmentTransaction transaction = getChildFragmentManager().beginTransaction();
    // R.id.map is a layout
    transaction.replace(R.id.map, mapFragment).commit();

    return view;
}

JavaScript get clipboard data on paste event (Cross browser)

This worked for me :

function onPasteMe(currentData, maxLen) {
    // validate max length of pasted text
    var totalCharacterCount = window.clipboardData.getData('Text').length;
}

<input type="text" onPaste="return onPasteMe(this, 50);" />

Java naming convention for static final variables

The dialog on this seems to be the antithesis of the conversation on naming interface and abstract classes. I find this alarming, and think that the decision runs much deeper than simply choosing one naming convention and using it always with static final.

Abstract and Interface

When naming interfaces and abstract classes, the accepted convention has evolved into not prefixing or suffixing your abstract class or interface with any identifying information that would indicate it is anything other than a class.

public interface Reader {}
public abstract class FileReader implements Reader {}
public class XmlFileReader extends FileReader {}

The developer is said not to need to know that the above classes are abstract or an interface.

Static Final

My personal preference and belief is that we should follow similar logic when referring to static final variables. Instead, we evaluate its usage when determining how to name it. It seems the all uppercase argument is something that has been somewhat blindly adopted from the C and C++ languages. In my estimation, that is not justification to continue the tradition in Java.

Question of Intention

We should ask ourselves what is the function of static final in our own context. Here are three examples of how static final may be used in different contexts:

public class ChatMessage {
    //Used like a private variable
    private static final Logger logger = LoggerFactory.getLogger(XmlFileReader.class);

    //Used like an Enum
    public class Error {
        public static final int Success = 0;
        public static final int TooLong = 1;
        public static final int IllegalCharacters = 2;
    }

    //Used to define some static, constant, publicly visible property
    public static final int MAX_SIZE = Integer.MAX_VALUE;
}

Could you use all uppercase in all three scenarios? Absolutely, but I think it can be argued that it would detract from the purpose of each. So, let's examine each case individually.


Purpose: Private Variable

In the case of the Logger example above, the logger is declared as private, and will only be used within the class, or possibly an inner class. Even if it were declared at protected or package visibility, its usage is the same:

public void send(final String message) {
    logger.info("Sending the following message: '" + message + "'.");
    //Send the message
}

Here, we don't care that logger is a static final member variable. It could simply be a final instance variable. We don't know. We don't need to know. All we need to know is that we are logging the message to the logger that the class instance has provided.

public class ChatMessage {
    private final Logger logger = LoggerFactory.getLogger(getClass());
}

You wouldn't name it LOGGER in this scenario, so why should you name it all uppercase if it was static final? Its context, or intention, is the same in both circumstances.

Note: I reversed my position on package visibility because it is more like a form of public access, restricted to package level.


Purpose: Enum

Now you might say, why are you using static final integers as an enum? That is a discussion that is still evolving and I'd even say semi-controversial, so I'll try not to derail this discussion for long by venturing into it. However, it would be suggested that you could implement the following accepted enum pattern:

public enum Error {
    Success(0),
    TooLong(1),
    IllegalCharacters(2);

    private final int value;

    private Error(final int value) {
        this.value = value;
    }

    public int value() {
        return value;
    }

    public static Error fromValue(final int value) {
        switch (value) {
        case 0:
            return Error.Success;
        case 1:
            return Error.TooLong;
        case 2:
            return Error.IllegalCharacters;
        default:
            throw new IllegalArgumentException("Unknown Error value.");
        }
    }
}

There are variations of the above that achieve the same purpose of allowing explicit conversion of an enum->int and int->enum. In the scope of streaming this information over a network, native Java serialization is simply too verbose. A simple int, short, or byte could save tremendous bandwidth. I could delve into a long winded compare and contrast about the pros and cons of enum vs static final int involving type safety, readability, maintainability, etc.; fortunately, that lies outside the scope of this discussion.

The bottom line is this, sometimes static final int will be used as an enum style structure.

If you can bring yourself to accept that the above statement is true, we can follow that up with a discussion of style. When declaring an enum, the accepted style says that we don't do the following:

public enum Error {
    SUCCESS(0),
    TOOLONG(1),
    ILLEGALCHARACTERS(2);
}

Instead, we do the following:

public enum Error {
    Success(0),
    TooLong(1),
    IllegalCharacters(2);
}

If your static final block of integers serves as a loose enum, then why should you use a different naming convention for it? Its context, or intention, is the same in both circumstances.


Purpose: Static, Constant, Public Property

This usage case is perhaps the most cloudy and debatable of all. The static constant size usage example is where this is most often encountered. Java removes the need for sizeof(), but there are times when it is important to know how many bytes a data structure will occupy.

For example, consider you are writing or reading a list of data structures to a binary file, and the format of that binary file requires that the total size of the data chunk be inserted before the actual data. This is common so that a reader knows when the data stops in the scenario that there is more, unrelated, data that follows. Consider the following made up file format:

File Format: MyFormat (MYFM) for example purposes only
[int filetype: MYFM]
[int version: 0] //0 - Version of MyFormat file format
[int dataSize: 325] //The data section occupies the next 325 bytes
[int checksumSize: 400] //The checksum section occupies 400 bytes after the data section (16 bytes each)
[byte[] data]
[byte[] checksum]

This file contains a list of MyObject objects serialized into a byte stream and written to this file. This file has 325 bytes of MyObject objects, but without knowing the size of each MyObject you have no way of knowing which bytes belong to each MyObject. So, you define the size of MyObject on MyObject:

public class MyObject {
    private final long id; //It has a 64bit identifier (+8 bytes)
    private final int value; //It has a 32bit integer value (+4 bytes)
    private final boolean special; //Is it special? (+1 byte)

    public static final int SIZE = 13; //8 + 4 + 1 = 13 bytes
}

The MyObject data structure will occupy 13 bytes when written to the file as defined above. Knowing this, when reading our binary file, we can figure out dynamically how many MyObject objects follow in the file:

int dataSize = buffer.getInt();
int totalObjects = dataSize / MyObject.SIZE;

This seems to be the typical usage case and argument for all uppercase static final constants, and I agree that in this context, all uppercase makes sense. Here's why:

Java doesn't have a struct class like the C language, but a struct is simply a class with all public members and no constructor. It's simply a data structure. So, you can declare a class in struct like fashion:

public class MyFile {
    public static final int MYFM = 0x4D59464D; //'MYFM' another use of all uppercase!

    //The struct
    public static class MyFileHeader {
        public int fileType = MYFM;
        public int version = 0;
        public int dataSize = 0;
        public int checksumSize = 0;
    }
}

Let me preface this example by stating I personally wouldn't parse in this manner. I'd suggest an immutable class instead that handles the parsing internally by accepting a ByteBuffer or all 4 variables as constructor arguments. That said, accessing (setting in this case) this structs members would look something like:

MyFileHeader header = new MyFileHeader();
header.fileType     = buffer.getInt();
header.version      = buffer.getInt();
header.dataSize     = buffer.getInt();
header.checksumSize = buffer.getInt();

These aren't static or final, yet they are publicly exposed members that can be directly set. For this reason, I think that when a static final member is exposed publicly, it makes sense to uppercase it entirely. This is the one time when it is important to distinguish it from public, non-static variables.

Note: Even in this case, if a developer attempted to set a final variable, they would be met with either an IDE or compiler error.


Summary

In conclusion, the convention you choose for static final variables is going to be your preference, but I strongly believe that the context of use should heavily weigh on your design decision. My personal recommendation would be to follow one of the two methodologies:

Methodology 1: Evaluate Context and Intention [highly subjective; logical]

  • If it's a private variable that should be indistinguishable from a private instance variable, then name them the same. all lowercase
  • If it's intention is to serve as a type of loose enum style block of static values, then name it as you would an enum. pascal case: initial-cap each word
  • If it's intention is to define some publicly accessible, constant, and static property, then let it stand out by making it all uppercase

Methodology 2: Private vs Public [objective; logical]

Methodology 2 basically condenses its context into visibility, and leaves no room for interpretation.

  • If it's private or protected then it should be all lowercase.
  • If it's public or package then it should be all uppercase.

Conclusion

This is how I view the naming convention of static final variables. I don't think it is something that can or should be boxed into a single catch all. I believe that you should evaluate its intent before deciding how to name it.

However, the main objective should be to try and stay consistent throughout your project/package's scope. In the end, that is all you have control over.

(I do expect to be met with resistance, but also hope to gather some support from the community on this approach. Whatever your stance, please keep it civil when rebuking, critiquing, or acclaiming this style choice.)

How to see local history changes in Visual Studio Code?

Basic Functionality

  • Automatically saved local edit history is available with the Local History extension.
  • Manually saved local edit history is available with the Checkpoints extension (this is the IntelliJ equivalent to adding tags to the local history).

Advanced Functionality

  • None of the extensions mentioned above support edit history when a file is moved or renamed.
  • The extensions above only support edit history. They do not support move/delete history, for example, like IntelliJ does.

Open Request

If you'd like to see this feature added natively, along with all of the advanced functionality, I'd suggest upvoting the open GitHub issue here.

Efficient iteration with index in Scala

The proposed solutions suffer from the fact that they either explicitly iterate over a collection or stuff the collection into a function. It is more natural to stick with the usual idioms of Scala and put the index inside the usual map- or foreach-methods. This can be done using memoizing. The resulting code might look like

myIterable map (doIndexed(someFunction))

Here is a way to achieve this purpose. Consider the following utility:

object TraversableUtil {
    class IndexMemoizingFunction[A, B](f: (Int, A) => B) extends Function1[A, B] {
        private var index = 0
        override def apply(a: A): B = {
            val ret = f(index, a)
            index += 1
            ret
        }
    }

    def doIndexed[A, B](f: (Int, A) => B): A => B = {
        new IndexMemoizingFunction(f)
    }
}

This is already all you need. You can apply this for instance as follows:

import TraversableUtil._
List('a','b','c').map(doIndexed((i, char) => char + i))

which results in the list

List(97, 99, 101)

This way, you can use the usual Traversable-functions at the expense of wrapping your effective function. Enjoy!

Is there anything like .NET's NotImplementedException in Java?

As mentioned, the JDK does not have a close match. However, my team occasionally has a use for such an exception as well. We could have gone with UnsupportedOperationException as suggested by other answers, but we prefer a custom exception class in our base library that has deprecated constructors:

public class NotYetImplementedException extends RuntimeException
{
    /**
     * @deprecated Deprecated to remind you to implement the corresponding code
     *             before releasing the software.
     */
    @Deprecated
    public NotYetImplementedException()
    {
    }

    /**
     * @deprecated Deprecated to remind you to implement the corresponding code
     *             before releasing the software.
     */
    @Deprecated
    public NotYetImplementedException(String message)
    {
        super(message);
    }
}

This approach has the following benefits:

  1. When readers see NotYetImplementedException, they know that an implementation was planned and was either forgotten or is still in progress, whereas UnsupportedOperationException says (in line with collection contracts) that something will never be implemented. That's why we have the word "yet" in the class name. Also, an IDE can easily list the call sites.
  2. With the deprecation warning at each call site, your IDE and static code analysis tool can remind you where you still have to implement something. (This use of deprecation may feel wrong to some, but in fact deprecation is not limited to announcing removal.)
  3. The constructors are deprecated, not the class. This way, you only get a deprecation warning inside the method that needs implementing, not at the import line (JDK 9 fixed this, though).

Google maps responsive resize

Move your map variable into a scope where the event listener can use it. You are creating the map inside your initialize() function and nothing else can use it when created that way.

var map; //<-- This is now available to both event listeners and the initialize() function
function initialize() {
  var mapOptions = {
   center: new google.maps.LatLng(40.5472,12.282715),
   zoom: 6,
   mapTypeId: google.maps.MapTypeId.ROADMAP
  };
  map = new google.maps.Map(document.getElementById("map-canvas"),
            mapOptions);
}
google.maps.event.addDomListener(window, 'load', initialize);
google.maps.event.addDomListener(window, "resize", function() {
 var center = map.getCenter();
 google.maps.event.trigger(map, "resize");
 map.setCenter(center); 
});

Java - Check if JTextField is empty or not

The following will return true if the JTextField "name" does not contain text:

name.getText().isEmpty

How do I handle too long index names in a Ruby on Rails ActiveRecord migration?

I'm afraid none of these solutions worked for me. Perhaps because I was using belongs_to in my create_table migration for a polymorphic association.

I'll add my code below and a link to the solution that helped me in case anyone else stumbles upon when searching for 'Index name is too long' in connection with polymorphic associations.

The following code did NOT work for me:

def change
  create_table :item_references do |t|
    t.text :item_unique_id
    t.belongs_to :referenceable, polymorphic: true
    t.timestamps
  end
  add_index :item_references, [:referenceable_id, :referenceable_type], name: 'idx_item_refs'
end

This code DID work for me:

def change
  create_table :item_references do |t|
    t.text :item_unique_id
    t.belongs_to :referenceable, polymorphic: true, index: { name: 'idx_item_refs' }

    t.timestamps
  end
end

This is the SO Q&A that helped me out: https://stackoverflow.com/a/30366460/3258059

Checking to see if one array's elements are in another array in PHP

That code is invalid as you can only pass variables into language constructs. empty() is a language construct.

You have to do this in two lines:

$result = array_intersect($people, $criminals);
$result = !empty($result);

how to check which version of nltk, scikit learn installed?

In Windows® systems you can simply try

pip3 list | findstr scikit

scikit-learn                  0.22.1

If you are on Anaconda try

conda list scikit

scikit-learn              0.22.1           py37h6288b17_0

And this can be used to find out the version of any package you have installed. For example

pip3 list | findstr numpy

numpy                         1.17.4
numpydoc                      0.9.2

Or if you want to look for more than one package at a time

pip3 list | findstr "scikit numpy"

numpy                         1.17.4
numpydoc                      0.9.2
scikit-learn                  0.22.1

Note the quote characters are required when searching for more than one word.

Take care.

How to "pull" from a local branch into another one?

What you are looking for is merging.

git merge master

With pull you fetch changes from a remote repository and merge them into the current branch.

How to assign a value to a TensorFlow variable?

There is an easier approach:

x = tf.Variable(0)
x = x + 1
print x.eval()

CMD: Export all the screen content to a text file

If you are looking for each command separately

To export all the output of the command prompt in text files. Simply follow the following syntax.

C:> [syntax] >file.txt

The above command will create result of syntax in file.txt. Where new file.txt will be created on the current folder that you are in.

For example,

C:Result> dir >file.txt

To copy the whole session, Try this:

Copy & Paste a command session as follows:

1.) At the end of your session, click the upper left corner to display the menu.
Then select.. Edit -> Select all

2.) Again, click the upper left corner to display the menu.
Then select.. Edit -> Copy

3.) Open your favorite text editor and use Ctrl+V or your normal
Paste operation to paste in the text.

What does the "$" sign mean in jQuery or JavaScript?

In JavaScript it has no special significance (no more than a or Q anyway). It is just an uninformative variable name.

In jQuery the variable is assigned a copy of the jQuery function. This function is heavily overloaded and means half a dozen different things depending on what arguments it is passed. In this particular example you are passing it a string that contains a selector, so the function means "Create a jQuery object containing the element with the id Text".

remove table row with specific id

$('#3').remove();

Might not work with numeric id's though.

Why is "throws Exception" necessary when calling a function?

In Java, as you may know, exceptions can be categorized into two: One that needs the throws clause or must be handled if you don't specify one and another one that doesn't. Now, see the following figure:

enter image description here

In Java, you can throw anything that extends the Throwable class. However, you don't need to specify a throws clause for all classes. Specifically, classes that are either an Error or RuntimeException or any of the subclasses of these two. In your case Exception is not a subclass of an Error or RuntimeException. So, it is a checked exception and must be specified in the throws clause, if you don't handle that particular exception. That is why you needed the throws clause.


From Java Tutorial:

An exception is an event, which occurs during the execution of a program, that disrupts the normal flow of the program's instructions.

Now, as you know exceptions are classified into two: checked and unchecked. Why these classification?

Checked Exception: They are used to represent problems that can be recovered during the execution of the program. They usually are not the programmer's fault. For example, a file specified by user is not readable, or no network connection available, etc., In all these cases, our program doesn't need to exit, instead it can take actions like alerting the user, or go into a fallback mechanism(like offline working when network not available), etc.

Unchecked Exceptions: They again can be divided into two: Errors and RuntimeExceptions. One reason for them to be unchecked is that they are numerous in number, and required to handle all of them will clutter our program and reduce its clarity. The other reason is:

  • Runtime Exceptions: They usually happen due to a fault by the programmer. For example, if an ArithmeticException of division by zero occurs or an ArrayIndexOutOfBoundsException occurs, it is because we are not careful enough in our coding. They happen usually because some errors in our program logic. So, they must be cleared before our program enters into production mode. They are unchecked in the sense that, our program must fail when it occurs, so that we programmers can resolve it at the time of development and testing itself.

  • Errors: Errors are situations from which usually the program cannot recover. For example, if a StackOverflowError occurs, our program cannot do much, such as increase the size of program's function calling stack. Or if an OutOfMemoryError occurs, we cannot do much to increase the amount of RAM available to our program. In such cases, it is better to exit the program. That is why they are made unchecked.

For detailed information see:

How to add files/folders to .gitignore in IntelliJ IDEA?

Intellij had .ignore plugin to support this. https://plugins.jetbrains.com/plugin/7495?pr=idea

After you install the plugin, you right click on the project and select new -> .ignore file -> .gitignore file (Git) enter image description here

Then, select the type of project you have to generate a template and click Generate. enter image description here

Any implementation of Ordered Set in Java?

IndexedTreeSet from the indexed-tree-map project provides this functionality (ordered/sorted set with list-like access by index).

StringLength vs MaxLength attributes ASP.NET MVC with Entity Framework EF Code First

MaxLengthAttribute means Max. length of array or string data allowed

StringLengthAttribute means Min. and max. length of characters that are allowed in a data field

Visit http://joeylicc.wordpress.com/2013/06/20/asp-net-mvc-model-validation-using-data-annotations/

mysql.h file can't be found

For those who are using Eclipse IDE.

After installing the full MySQL together with mysql client and mysql server and any mysql dev libraries,

You will need to tell Eclipse IDE about the following

  • Where to find mysql.h
  • Where to find libmysqlclient library
  • The path to search for libmysqlclient library

Here is how you go about it.

To Add mysql.h

1. GCC C Compiler -> Includes -> Include paths(-l) then click + and add path to your mysql.h In my case it was /usr/include/mysql

enter image description here

To add mysqlclient library and search path to where mysqlclient library see steps 3 and 4.

2. GCC C Linker -> Libraries -> Libraries(-l) then click + and add mysqlcient

enter image description here

3. GCC C Linker -> Libraries -> Library search path (-L) then click + and add search path to mysqlcient. In my case it was /usr/lib64/mysql because I am using a 64 bit Linux OS and a 64 bit MySQL Database.

Otherwise, if you are using a 32 bit Linux OS, you may find that it is found at /usr/lib/mysql

enter image description here

How to make my layout able to scroll down?

Yes, it is very Simple. Just Put your Code Inside this:

<androidx.core.widget.NestedScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" 
    android:layout_height="match_parent">

//YOUR CODE

</androidx.core.widget.NestedScrollView>

Check if a string within a list contains a specific string with Linq

I think you want Any:

if (myList.Any(str => str.Contains("Mdd LH")))

It's well worth becoming familiar with the LINQ standard query operators; I would usually use those rather than implementation-specific methods (such as List<T>.ConvertAll) unless I was really bothered by the performance of a specific operator. (The implementation-specific methods can sometimes be more efficient by knowing the size of the result etc.)

Is there a way since (iOS 7's release) to get the UDID without using iTunes on a PC/Mac?

Navigate to http://get.udid.io/ from Safari on your iOS device. It works like a charm and requires neither iTunes nor any other computer. No app installed either.

EDIT:

Also, have a look at Getting a device UDID from .mobileconfig if you (understandably) would rather have this .mobileconfig certificate hosted on a server of yours.

MAKE YOUR OWN:

Have a copy of the .mobileconfig example hosted on your server and write 2-3 small scripts in your favorite language to handle the following flow:

  1. Navigate on Safari to a URL redirecting to enroll.mobileconfig below. This makes iOS open the Settings app and show the profile.
  2. Upon accepting the profile, iOS switches back to Safari and posts the DeviceAttributes array to the URL specified enroll.mobileconfig.
  3. The POST data will contain a .plist file with the requested attributes (see example below). One of which will be the holy UDID.

Remark: You should probably have some user friendly messages. Specifically, we even have a step 0. where the user is asked to provide their name and e-mail that we store temporarily in the HTTP session and then redirect the request to the mobileconfig profile. We ultimately match this info with the iPhone data and send a friendly confirmation e-mail. HTH.

enroll.mobileconfig

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
    <dict>
        <key>PayloadContent</key>
        <dict>
            <key>URL</key>
            <string>http://support.devcorp.com/uuid/returnurl/</string>
            <key>DeviceAttributes</key>
            <array>
            <string>DEVICE_NAME</string>
            <string>UDID</string>
            <string>PRODUCT</string>
            <string>VERSION</string>
            <string>SERIAL</string>
            </array>
        </dict>
        <key>PayloadOrganization</key>
        <string>DevCorp Inc.</string>
        <key>PayloadDisplayName</key>
        <string>Profile Service</string>
        <key>PayloadVersion</key>
        <integer>1</integer>
        <key>PayloadUUID</key>
        <string>C5FB9D0D-0BE7-4F98-82CC-5D0EA74F8CF8</string> <!-- any random UUID -->
        <key>PayloadIdentifier</key>
        <string>com.devcorp.profile-service</string>
        <key>PayloadDescription</key>
        <string>This is a temporary profile to enroll your device for ad-hoc app distribution</string>
        <key>PayloadType</key>
        <string>Profile Service</string>
    </dict>
</plist>

sample .plist POSTed by the iPhone to the given URL

<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE plist PUBLIC "-//Apple//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd">
<plist version="1.0">
<dict>
    <key>PRODUCT</key>
    <string>iPhone4,1</string>
    <key>SERIAL</key>
    <string>DNPGWR2VCTC0</string>
    <key>UDID</key>
    <string>b01ea7bc2237fed21bfe403c6d2b942ddb3c12c3</string>
    <key>VERSION</key>
    <string>11A465</string>
</dict>

Converting HTML to plain text in PHP for e-mail

Use html2text (example HTML to text), licensed under the Eclipse Public License. It uses PHP's DOM methods to load from HTML, and then iterates over the resulting DOM to extract plain text. Usage:

// when installed using the Composer package
$text = Html2Text\Html2Text::convert($html);

// usage when installed using html2text.php
require('html2text.php');
$text = convert_html_to_text($html);

Although incomplete, it is open source and contributions are welcome.

Issues with other conversion scripts:

  • Since html2text (GPL) is not EPL-compatible.
  • lkessler's link (attribution) is incompatible with most open source licenses.

How to get JSON data from the URL (REST API) to UI using jQuery or plain JavaScript?

 jquery.ajax({
            url: `//your api url`
            type: "GET",
            dataType: "json",
            success: function(data) {
                jQuery.each(data, function(index, value) {
                        console.log(data);
                        `All you API data is here`
                    }
                }
            });     

PHP: how can I get file creation date?

Unfortunately if you are running on linux you cannot access the information as only the last modified date is stored.

It does slightly depend on your filesystem tho. I know that ext2 and ext3 do not support creation time but I think that ext4 does.

Passing data through intent using Serializable

1- You are using android.graphics.Bitmap which doesn't implements Serializable class so you have to remove that class then it will work.

2- for brief you can visit how to pass data between intents.

Ruby String to Date Conversion

Date.strptime(updated,"%a, %d %m %Y %H:%M:%S %Z")

Should be:

Date.strptime(updated, '%a, %d %b %Y %H:%M:%S %Z')

JavaScript closure inside loops – simple practical example

Well, the problem is that the variable i, within each of your anonymous functions, is bound to the same variable outside of the function.

ES6 solution: let

ECMAScript 6 (ES6) introduces new let and const keywords that are scoped differently than var-based variables. For example, in a loop with a let-based index, each iteration through the loop will have a new variable i with loop scope, so your code would work as you expect. There are many resources, but I'd recommend 2ality's block-scoping post as a great source of information.

for (let i = 0; i < 3; i++) {
  funcs[i] = function() {
    console.log("My value: " + i);
  };
}

Beware, though, that IE9-IE11 and Edge prior to Edge 14 support let but get the above wrong (they don't create a new i each time, so all the functions above would log 3 like they would if we used var). Edge 14 finally gets it right.


ES5.1 solution: forEach

With the relatively widespread availability of the Array.prototype.forEach function (in 2015), it's worth noting that in those situations involving iteration primarily over an array of values, .forEach() provides a clean, natural way to get a distinct closure for every iteration. That is, assuming you've got some sort of array containing values (DOM references, objects, whatever), and the problem arises of setting up callbacks specific to each element, you can do this:

var someArray = [ /* whatever */ ];
// ...
someArray.forEach(function(arrayElement) {
  // ... code code code for this one element
  someAsynchronousFunction(arrayElement, function() {
    arrayElement.doSomething();
  });
});

The idea is that each invocation of the callback function used with the .forEach loop will be its own closure. The parameter passed in to that handler is the array element specific to that particular step of the iteration. If it's used in an asynchronous callback, it won't collide with any of the other callbacks established at other steps of the iteration.

If you happen to be working in jQuery, the $.each() function gives you a similar capability.


Classic solution: Closures

What you want to do is bind the variable within each function to a separate, unchanging value outside of the function:

_x000D_
_x000D_
var funcs = [];

function createfunc(i) {
  return function() {
    console.log("My value: " + i);
  };
}

for (var i = 0; i < 3; i++) {
  funcs[i] = createfunc(i);
}

for (var j = 0; j < 3; j++) {
  // and now let's run each one to see
  funcs[j]();
}
_x000D_
_x000D_
_x000D_

Since there is no block scope in JavaScript - only function scope - by wrapping the function creation in a new function, you ensure that the value of "i" remains as you intended.

Can iterators be reset in Python?

There's a bug in using .seek(0) as advocated by Alex Martelli and Wilduck above, namely that the next call to .next() will give you a dictionary of your header row in the form of {key1:key1, key2:key2, ...}. The work around is to follow file.seek(0) with a call to reader.next() to get rid of the header row.

So your code would look something like this:

f_in = open('myfile.csv','r')
reader = csv.DictReader(f_in)

for record in reader:
    if some_condition:
        # reset reader to first row of data on 2nd line of file
        f_in.seek(0)
        reader.next()
        continue
    do_something(record)

Setting values of input fields with Angular 6

You should use the following:

       <td><input id="priceInput-{{orderLine.id}}" type="number" [(ngModel)]="orderLine.price"></td>

You will need to add the FormsModule to your app.module in the inputs section as follows:

import { FormsModule } from '@angular/forms';

@NgModule({
  declarations: [
    ...
  ],
  imports: [
    BrowserModule,
    FormsModule
  ],
  ..

The use of the brackets around the ngModel are as follows:

  • The [] show that it is taking an input from your TS file. This input should be a public member variable. A one way binding from TS to HTML.

  • The () show that it is taking output from your HTML file to a variable in the TS file. A one way binding from HTML to TS.

  • The [()] are both (e.g. a two way binding)

See here for more information: https://angular.io/guide/template-syntax

I would also suggest replacing id="priceInput-{{orderLine.id}}" with something like this [id]="getElementId(orderLine)" where getElementId(orderLine) returns the element Id in the TS file and can be used anywere you need to reference the element (to avoid simple bugs like calling it priceInput1 in one place and priceInput-1 in another. (if you still need to access the input by it's Id somewhere else)

YouTube Autoplay not working

It's not working since April of 2018 because Google decided to give greater control of playback to users. You just need to add &mute=1 to your URL. Autoplay Policy Changes

<iframe id="existing-iframe-example"
          width="640" height="360"
          src="https://www.youtube.com/embed/-SFcIUEvNOQ?autoplay=1&mute=1&enablejsapi=1"
          frameborder="0"
          style="border: solid 4px #37474F"
          ></iframe>

Update :

Audio/Video Updates in Chrome 73

Google said : Now that Progressive Web Apps (PWAs) are available on all desktop platforms, we are extending the rule that we had on mobile to desktop: autoplay with sound is now allowed for installed PWAs. Note that it only applies to pages in the scope of the web app manifest. https://developers.google.com/web/updates/2019/02/chrome-73-media-updates#autoplay-pwa

Internet Explorer 11 disable "display intranet sites in compatibility view" via meta tag not working

Make sure:

<meta http-equiv="X-UA-Compatible" content="IE=edge">

is the first <meta> tag on your page, otherwise IE may not respect it.

Alternatively, the problem may be that IE is using Enterprise Mode for this website:

  • Your question mentioned that the console shows: HTML1122: Internet Explorer is running in Enterprise Mode emulating IE8.
  • If so you may need to disable enterprise mode (or like this) or turn it off for that website from the Tools menu in IE.
  • However Enterprise Mode should in theory be overridden by the X-UA-Compatible tag, but IE might have a bug...

Adding system header search path to Xcode

We have two options.

  1. Look at Preferences->Locations->"Custom Paths" in Xcode's preference. A path added here will be a variable which you can add to "Header Search Paths" in project build settings as "$cppheaders", if you saved the custom path with that name.

  2. Set HEADER_SEARCH_PATHS parameter in build settings on project info. I added "${SRCROOT}" here without recursion. This setting works well for most projects.

About 2nd option:

Xcode uses Clang which has GCC compatible command set. GCC has an option -Idir which adds system header searching paths. And this option is accessible via HEADER_SEARCH_PATHS in Xcode project build setting.

However, path string added to this setting should not contain any whitespace characters because the option will be passed to shell command as is.

But, some OS X users (like me) may put their projects on path including whitespace which should be escaped. You can escape it like /Users/my/work/a\ project\ with\ space if you input it manually. You also can escape them with quotes to use environment variable like "${SRCROOT}".

Or just use . to indicate current directory. I saw this trick on Webkit's source code, but I am not sure that current directory will be set to project directory when building it.

The ${SRCROOT} is predefined value by Xcode. This means source directory. You can find more values in Reference document.

PS. Actually you don't have to use braces {}. I get same result with $SRCROOT. If you know the difference, please let me know.

best practice to generate random token for forgot password

You can also use DEV_RANDOM, where 128 = 1/2 the generated token length. Code below generates 256 token.

$token = bin2hex(mcrypt_create_iv(128, MCRYPT_DEV_RANDOM));

How to wait until an element exists?

I used this approach to wait for an element to appear so I can execute the other functions after that.

Let's say doTheRestOfTheStuff(parameters) function should only be called after the element with ID the_Element_ID appears or finished loading, we can use,

var existCondition = setInterval(function() {
 if ($('#the_Element_ID').length) {
    console.log("Exists!");
    clearInterval(existCondition);
    doTheRestOfTheStuff(parameters);
 }
}, 100); // check every 100ms

JavaScript/jQuery - "$ is not defined- $function()" error

Im using Asp.Net Core 2.2 with MVC and Razor cshtml My JQuery is referenced in a layout page I needed to add the following to my view.cshtml:

@section Scripts {
$script-here
}

Protractor : How to wait for page complete after click a button?

browser.waitForAngular();

btnLoginEl.click().then(function() { Do Something });

to solve the promise.

Pandas Merging 101

This post aims to give readers a primer on SQL-flavored merging with pandas, how to use it, and when not to use it.

In particular, here's what this post will go through:

  • The basics - types of joins (LEFT, RIGHT, OUTER, INNER)

    • merging with different column names
    • merging with multiple columns
    • avoiding duplicate merge key column in output

What this post (and other posts by me on this thread) will not go through:

  • Performance-related discussions and timings (for now). Mostly notable mentions of better alternatives, wherever appropriate.
  • Handling suffixes, removing extra columns, renaming outputs, and other specific use cases. There are other (read: better) posts that deal with that, so figure it out!

Note
Most examples default to INNER JOIN operations while demonstrating various features, unless otherwise specified.

Furthermore, all the DataFrames here can be copied and replicated so you can play with them. Also, see this post on how to read DataFrames from your clipboard.

Lastly, all visual representation of JOIN operations have been hand-drawn using Google Drawings. Inspiration from here.



Enough Talk, just show me how to use merge!

Setup & Basics

np.random.seed(0)
left = pd.DataFrame({'key': ['A', 'B', 'C', 'D'], 'value': np.random.randn(4)})    
right = pd.DataFrame({'key': ['B', 'D', 'E', 'F'], 'value': np.random.randn(4)})
  
left

  key     value
0   A  1.764052
1   B  0.400157
2   C  0.978738
3   D  2.240893

right

  key     value
0   B  1.867558
1   D -0.977278
2   E  0.950088
3   F -0.151357

For the sake of simplicity, the key column has the same name (for now).

An INNER JOIN is represented by

Note
This, along with the forthcoming figures all follow this convention:

  • blue indicates rows that are present in the merge result
  • red indicates rows that are excluded from the result (i.e., removed)
  • green indicates missing values that are replaced with NaNs in the result

To perform an INNER JOIN, call merge on the left DataFrame, specifying the right DataFrame and the join key (at the very least) as arguments.

left.merge(right, on='key')
# Or, if you want to be explicit
# left.merge(right, on='key', how='inner')

  key   value_x   value_y
0   B  0.400157  1.867558
1   D  2.240893 -0.977278

This returns only rows from left and right which share a common key (in this example, "B" and "D).

A LEFT OUTER JOIN, or LEFT JOIN is represented by

This can be performed by specifying how='left'.

left.merge(right, on='key', how='left')

  key   value_x   value_y
0   A  1.764052       NaN
1   B  0.400157  1.867558
2   C  0.978738       NaN
3   D  2.240893 -0.977278

Carefully note the placement of NaNs here. If you specify how='left', then only keys from left are used, and missing data from right is replaced by NaN.

And similarly, for a RIGHT OUTER JOIN, or RIGHT JOIN which is...

...specify how='right':

left.merge(right, on='key', how='right')

  key   value_x   value_y
0   B  0.400157  1.867558
1   D  2.240893 -0.977278
2   E       NaN  0.950088
3   F       NaN -0.151357

Here, keys from right are used, and missing data from left is replaced by NaN.

Finally, for the FULL OUTER JOIN, given by

specify how='outer'.

left.merge(right, on='key', how='outer')

  key   value_x   value_y
0   A  1.764052       NaN
1   B  0.400157  1.867558
2   C  0.978738       NaN
3   D  2.240893 -0.977278
4   E       NaN  0.950088
5   F       NaN -0.151357

This uses the keys from both frames, and NaNs are inserted for missing rows in both.

The documentation summarizes these various merges nicely:

enter image description here


Other JOINs - LEFT-Excluding, RIGHT-Excluding, and FULL-Excluding/ANTI JOINs

If you need LEFT-Excluding JOINs and RIGHT-Excluding JOINs in two steps.

For LEFT-Excluding JOIN, represented as

Start by performing a LEFT OUTER JOIN and then filtering (excluding!) rows coming from left only,

(left.merge(right, on='key', how='left', indicator=True)
     .query('_merge == "left_only"')
     .drop('_merge', 1))

  key   value_x  value_y
0   A  1.764052      NaN
2   C  0.978738      NaN

Where,

left.merge(right, on='key', how='left', indicator=True)

  key   value_x   value_y     _merge
0   A  1.764052       NaN  left_only
1   B  0.400157  1.867558       both
2   C  0.978738       NaN  left_only
3   D  2.240893 -0.977278       both

And similarly, for a RIGHT-Excluding JOIN,

(left.merge(right, on='key', how='right', indicator=True)
     .query('_merge == "right_only"')
     .drop('_merge', 1))

  key  value_x   value_y
2   E      NaN  0.950088
3   F      NaN -0.151357

Lastly, if you are required to do a merge that only retains keys from the left or right, but not both (IOW, performing an ANTI-JOIN),

You can do this in similar fashion—

(left.merge(right, on='key', how='outer', indicator=True)
     .query('_merge != "both"')
     .drop('_merge', 1))

  key   value_x   value_y
0   A  1.764052       NaN
2   C  0.978738       NaN
4   E       NaN  0.950088
5   F       NaN -0.151357

Different names for key columns

If the key columns are named differently—for example, left has keyLeft, and right has keyRight instead of key—then you will have to specify left_on and right_on as arguments instead of on:

left2 = left.rename({'key':'keyLeft'}, axis=1)
right2 = right.rename({'key':'keyRight'}, axis=1)

left2
 
  keyLeft     value
0       A  1.764052
1       B  0.400157
2       C  0.978738
3       D  2.240893

right2

  keyRight     value
0        B  1.867558
1        D -0.977278
2        E  0.950088
3        F -0.151357
left2.merge(right2, left_on='keyLeft', right_on='keyRight', how='inner')

  keyLeft   value_x keyRight   value_y
0       B  0.400157        B  1.867558
1       D  2.240893        D -0.977278

Avoiding duplicate key column in output

When merging on keyLeft from left and keyRight from right, if you only want either of the keyLeft or keyRight (but not both) in the output, you can start by setting the index as a preliminary step.

left3 = left2.set_index('keyLeft')
left3.merge(right2, left_index=True, right_on='keyRight')
    
    value_x keyRight   value_y
0  0.400157        B  1.867558
1  2.240893        D -0.977278

Contrast this with the output of the command just before (that is, the output of left2.merge(right2, left_on='keyLeft', right_on='keyRight', how='inner')), you'll notice keyLeft is missing. You can figure out what column to keep based on which frame's index is set as the key. This may matter when, say, performing some OUTER JOIN operation.


Merging only a single column from one of the DataFrames

For example, consider

right3 = right.assign(newcol=np.arange(len(right)))
right3
  key     value  newcol
0   B  1.867558       0
1   D -0.977278       1
2   E  0.950088       2
3   F -0.151357       3

If you are required to merge only "new_val" (without any of the other columns), you can usually just subset columns before merging:

left.merge(right3[['key', 'newcol']], on='key')

  key     value  newcol
0   B  0.400157       0
1   D  2.240893       1

If you're doing a LEFT OUTER JOIN, a more performant solution would involve map:

# left['newcol'] = left['key'].map(right3.set_index('key')['newcol']))
left.assign(newcol=left['key'].map(right3.set_index('key')['newcol']))

  key     value  newcol
0   A  1.764052     NaN
1   B  0.400157     0.0
2   C  0.978738     NaN
3   D  2.240893     1.0

As mentioned, this is similar to, but faster than

left.merge(right3[['key', 'newcol']], on='key', how='left')

  key     value  newcol
0   A  1.764052     NaN
1   B  0.400157     0.0
2   C  0.978738     NaN
3   D  2.240893     1.0

Merging on multiple columns

To join on more than one column, specify a list for on (or left_on and right_on, as appropriate).

left.merge(right, on=['key1', 'key2'] ...)

Or, in the event the names are different,

left.merge(right, left_on=['lkey1', 'lkey2'], right_on=['rkey1', 'rkey2'])

Other useful merge* operations and functions

This section only covers the very basics, and is designed to only whet your appetite. For more examples and cases, see the documentation on merge, join, and concat as well as the links to the function specs.



Continue Reading

Jump to other topics in Pandas Merging 101 to continue learning:

* you are here

iOS9 getting error “an SSL error has occurred and a secure connection to the server cannot be made”

Even though allowing arbitrary loads (NSAllowsArbitraryLoads = true) is a good workaround, you shouldn't entirely disable ATS but rather enable the HTTP connection you want to allow:

<key>NSAppTransportSecurity</key>
<dict>
  <key>NSExceptionDomains</key>
  <dict>
    <key>yourserver.com</key>
    <dict>
      <!--Include to allow subdomains-->
      <key>NSIncludesSubdomains</key>
      <true/>
      <!--Include to allow HTTP requests-->
      <key>NSTemporaryExceptionAllowsInsecureHTTPLoads</key>
      <true/>
      <!--Include to specify minimum TLS version-->
      <key>NSTemporaryExceptionMinimumTLSVersion</key>
      <string>TLSv1.1</string>
    </dict>
  </dict>
</dict>

Should you choose the MONEY or DECIMAL(x,y) datatypes in SQL Server?

I found a reason about using decimal over money in accuracy subject.

DECLARE @dOne   DECIMAL(19,4),
        @dThree DECIMAL(19,4),
        @mOne   MONEY,
        @mThree MONEY,
        @fOne   FLOAT,
        @fThree FLOAT

 SELECT @dOne   = 1,
        @dThree = 3,    
        @mOne   = 1,
        @mThree = 3,    
        @fOne   = 1,
        @fThree = 3

 SELECT (@dOne/@dThree)*@dThree AS DecimalResult,
        (@mOne/@mThree)*@mThree AS MoneyResult,
        (@fOne/@fThree)*@fThree AS FloatResult

DecimalResult > 1.000000

MoneyResult > 0.9999

FloatResult > 1

Just test it and make your decision.

How to solve Object reference not set to an instance of an object.?

I think you just need;

List<string> list = new List<string>();
list.Add("hai");

There is a difference between

List<string> list; 

and

List<string> list = new List<string>();

When you didn't use new keyword in this case, your list didn't initialized. And when you try to add it hai, obviously you get an error.

I need a Nodejs scheduler that allows for tasks at different intervals

I have written a node module that provides a wrapper around setInterval using moment durations providing a declarative interface:

npm install every-moment

var every = require('every-moment');

var timer = every(5, 'seconds', function() {
    console.log(this.duration);
});

every(2, 'weeks', function() {
    console.log(this.duration);
    timer.stop();
    this.set(1, 'week');
    this.start();
});

https://www.npmjs.com/package/every-moment

https://github.com/raygerrard/every-moment

How to Maximize window in chrome using webDriver (python)

Based on what Janek answered, this worked for me (Linux):

from selenium import webdriver

options = webdriver.ChromeOptions()
options.add_argument("--start-maximized")

driver = webdriver.Chrome(chrome_options=options)

Default behavior of "git push" without a branch specified

A git push will try and push all local branches to the remote server, this is likely what you do not want. I have a couple of conveniences setup to deal with this:

Alias "gpull" and "gpush" appropriately:

In my ~/.bash_profile

get_git_branch() {
  echo `git branch 2> /dev/null | sed -e '/^[^*]/d' -e 's/* \(.*\)/\1/'`
}
alias gpull='git pull origin `get_git_branch`'
alias gpush='git push origin `get_git_branch`'

Thus, executing "gpush" or "gpull" will push just my "currently on" branch.

Waiting until two async blocks are executed before starting another block

Accepted answer in swift:

let group = DispatchGroup()

group.async(group: DispatchQueue.global(qos: .default), execute: {
    // block1
    print("Block1")
    Thread.sleep(forTimeInterval: 5.0)
    print("Block1 End")
})


group.async(group: DispatchQueue.global(qos: .default), execute: {
    // block2
    print("Block2")
    Thread.sleep(forTimeInterval: 8.0)
    print("Block2 End")
})

dispatch_group_notify(group, DispatchQueue.global(qos: .default), {
    // block3
    print("Block3")
})

// only for non-ARC projects, handled automatically in ARC-enabled projects.
dispatch_release(group)

Run java jar file on a server as background process

Run in background and add logs to log file using the following:

nohup java -jar /web/server.jar > log.log 2>&1 &

Maven project version inheritance - do I have to specify the parent version?

EDIT: Since Maven 3.5.0 there is a nice solution for this using ${revision} placeholder. See FrVaBe's answer for details. For previous Maven versions see my original answer below.


No, there isn't. You always have to specify parent's version. Fortunately, it is inherited as the module's version what is desirable in most cases. Moreover, this parent's version declaration is bumped automatically by Maven Release Plugin, so - in fact - it's not a problem that you have version in 2 places as long as you use Maven Release Plugin for releasing or just bumping versions.

Notice that there are some cases when this behaviour is actually pretty OK and gives more flexibility you may need. Sometimes you want to use some of previous parent's version to inherit, however that's not a mainstream case.

What is the difference between json.load() and json.loads() functions

In python3.7.7, the definition of json.load is as below according to cpython source code:

def load(fp, *, cls=None, object_hook=None, parse_float=None,
        parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):

    return loads(fp.read(),
        cls=cls, object_hook=object_hook,
        parse_float=parse_float, parse_int=parse_int,
        parse_constant=parse_constant, object_pairs_hook=object_pairs_hook, **kw)

json.load actually calls json.loads and use fp.read() as the first argument.

So if your code is:

with open (file) as fp:
    s = fp.read()
    json.loads(s)

It's the same to do this:

with open (file) as fp:
    json.load(fp)

But if you need to specify the bytes reading from the file as like fp.read(10) or the string/bytes you want to deserialize is not from file, you should use json.loads()

As for json.loads(), it not only deserialize string but also bytes. If s is bytes or bytearray, it will be decoded to string first. You can also find it in the source code.

def loads(s, *, encoding=None, cls=None, object_hook=None, parse_float=None,
        parse_int=None, parse_constant=None, object_pairs_hook=None, **kw):
    """Deserialize ``s`` (a ``str``, ``bytes`` or ``bytearray`` instance
    containing a JSON document) to a Python object.

    ...

    """
    if isinstance(s, str):
        if s.startswith('\ufeff'):
            raise JSONDecodeError("Unexpected UTF-8 BOM (decode using utf-8-sig)",
                                  s, 0)
    else:
        if not isinstance(s, (bytes, bytearray)):
            raise TypeError(f'the JSON object must be str, bytes or bytearray, '
                            f'not {s.__class__.__name__}')
        s = s.decode(detect_encoding(s), 'surrogatepass')

How to perform keystroke inside powershell?

Also the $wshell = New-Object -ComObject wscript.shell; helped a script that was running in the background, it worked fine with just but adding $wshell. fixed it from running as background! [Microsoft.VisualBasic.Interaction]::AppActivate("App Name")

jQuery check if an input is type checkbox?

>>> a=$("#communitymode")[0]
<input id="communitymode" type="checkbox" name="communitymode">
>>> a.type
"checkbox"

Or, more of the style of jQuery:

$("#myinput").attr('type') == 'checkbox'

jQuery Validate - Enable validation for hidden fields

This worked for me within an ASP.NET site. To enable validation on some hidden fields use this code

$("form").data("validator").settings.ignore = ":hidden:not(#myitem)";

To enable validation for all elements of form use this one $("form").data("validator").settings.ignore = "";

Note that use them within $(document).ready(function() { })

change html text from link with jquery

From W3 Schools HTML DOM Changes: If you look at the 3rd example it shows how you can change the text in your link, "click here". Example:

<a id="a_tbnotesverbergen" href="#nothing">click here</a>

JS:

var element=document.getElementById("a_tbnotesverbergen"); 
element.innerHTML="New Text";

How to return a string from a C++ function?

You never give any value to your strings in main so they are empty, and thus obviously the function returns an empty string.

Replace:

string str1, str2, str3;

with:

string str1 = "the dog jumped over the fence";
string str2 = "the";
string str3 = "that";

Also, you have several problems in your replaceSubstring function:

int index = s1.find(s2, 0);
s1.replace(index, s2.length(), s3);
  • std::string::find returns a std::string::size_type (aka. size_t) not an int. Two differences: size_t is unsigned, and it's not necessarily the same size as an int depending on your platform (eg. on 64 bits Linux or Windows size_t is unsigned 64 bits while int is signed 32 bits).
  • What happens if s2 is not part of s1? I'll leave it up to you to find how to fix that. Hint: std::string::npos ;)

Does dispatch_async(dispatch_get_main_queue(), ^{...}); wait until done?

No it doesn't wait and the way you are doing it in that sample is not good practice.

dispatch_async is always asynchronous. It's just that you are enqueueing all the UI blocks to the same queue so the different blocks will run in sequence but parallel with your data processing code.

If you want the update to wait you can use dispatch_sync instead.

// This will wait to finish
dispatch_sync(dispatch_get_main_queue(), ^{
    // Update the UI on the main thread.
});

Another approach would be to nest enqueueing the block. I wouldn't recommend it for multiple levels though.

dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
    // Background work

    dispatch_async(dispatch_get_main_queue(), ^{
        // Update UI

        dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
            // Background work

            dispatch_async(dispatch_get_main_queue(), ^{
                // Update UI
            });
        });
    });
});

If you need the UI updated to wait then you should use the synchronous versions. It's quite okay to have a background thread wait for the main thread. UI updates should be very quick.

How to cache Google map tiles for offline usage?

On Android platforms, Oruxmaps (http://www.oruxmaps.com) does a great job at caching all WMS sources. It is available in the play store. I use it daily in remote areas without any connectivity, works like a charm.

Please run `npm cache clean`

As of npm@5, the npm cache self-heals from corruption issues and data extracted from the cache is guaranteed to be valid. If you want to make sure everything is consistent, use npm cache verify instead. On the other hand, if you're debugging an issue with the installer, you can use npm install --cache /tmp/empty-cache to use a temporary cache instead of nuking the actual one.

If you're sure you want to delete the entire cache, rerun:

npm cache clean --force

A complete log of this run can be found in /Users/USERNAME/.npm/_logs/2019-01-08T21_29_30_811Z-debug.log.

programming a servo thru a barometer

You could define a mapping of air pressure to servo angle, for example:

def calc_angle(pressure, min_p=1000, max_p=1200):     return 360 * ((pressure - min_p) / float(max_p - min_p))  angle = calc_angle(pressure) 

This will linearly convert pressure values between min_p and max_p to angles between 0 and 360 (you could include min_a and max_a to constrain the angle, too).

To pick a data structure, I wouldn't use a list but you could look up values in a dictionary:

d = {1000:0, 1001: 1.8, ...}  angle = d[pressure] 

but this would be rather time-consuming to type out!

How to install pip for Python 3 on Mac OS X?

I had the same problem with python3 and pip3. Decision: solving all conflicts with links and other stuff when do

brew doctor

After that

brew reinstall python3

Multiple cases in switch statement

An awful lot of work seems to have been put into finding ways to get one of C# least used syntaxes to somehow look better or work better. Personally I find the switch statement is seldom worth using. I would strongly suggest analyzing what data you are testing and the end results you are wanting.

Let us say for example you want to quickly test values in a known range to see if they are prime numbers. You want to avoid having your code do the wasteful calculations and you can find a list of primes in the range you want online. You could use a massive switch statement to compare each value to known prime numbers.

Or you could just create an array map of primes and get immediate results:

    bool[] Primes = new bool[] {
        false, false, true, true, false, true, false,    
        true, false, false, false, true, false, true,
        false,false,false,true,false,true,false};
    private void button1_Click(object sender, EventArgs e) {
        int Value = Convert.ToInt32(textBox1.Text);
        if ((Value >= 0) && (Value < Primes.Length)) {
            bool IsPrime = Primes[Value];
            textBox2.Text = IsPrime.ToString();
        }
    }

Maybe you want to see if a character in a string is hexadecimal. You could use an ungly and somewhat large switch statement.

Or you could use either regular expressions to test the char or use the IndexOf function to search for the char in a string of known hexadecimal letters:

        private void textBox2_TextChanged(object sender, EventArgs e) {
        try {
            textBox1.Text = ("0123456789ABCDEFGabcdefg".IndexOf(textBox2.Text[0]) >= 0).ToString();
        } catch {
        }
    }

Let us say you want to do one of 3 different actions depending on a value that will be the range of 1 to 24. I would suggest using a set of IF statements. And if that became too complex (Or the numbers were larger such as 5 different actions depending on a value in the range of 1 to 90) then use an enum to define the actions and create an array map of the enums. The value would then be used to index into the array map and get the enum of the action you want. Then use either a small set of IF statements or a very simple switch statement to process the resulting enum value.

Also, the nice thing about an array map that converts a range of values into actions is that it can be easily changed by code. With hard wired code you can't easily change behaviour at runtime but with an array map it is easy.

How to create javascript delay function

You can create a delay using the following example

setInterval(function(){alert("Hello")},3000);

Replace 3000 with # of milliseconds

You can place the content of what you want executed inside the function.

Print a file's last modified date in Bash

EDITED: turns out that I had forgotten the quotes needed for $entry in order to print correctly and not give the "no such file or directory" error. Thank you all so much for helping me!

Here is my final code:

    echo "Please type in the directory you want all the files to be listed with last modified dates" #bash can't find file creation dates

read directory

for entry in "$directory"/*

do
modDate=$(stat -c %y "$entry") #%y = last modified. Qoutes are needed otherwise spaces in file name with give error of "no such file"
modDate=${modDate%% *} #%% takes off everything off the string after the date to make it look pretty
echo $entry:$modDate

Prints out like this:

/home/joanne/Dropbox/cheat sheet.docx:2012-03-14
/home/joanne/Dropbox/Comp:2013-05-05
/home/joanne/Dropbox/Comp 150 java.zip:2013-02-11
/home/joanne/Dropbox/Comp 151 Java 2.zip:2013-02-11
/home/joanne/Dropbox/Comp 162 Assembly Language.zip:2013-02-11
/home/joanne/Dropbox/Comp 262 Comp Architecture.zip:2012-12-12
/home/joanne/Dropbox/Comp 345 Image Processing.zip:2013-02-11
/home/joanne/Dropbox/Comp 362 Operating Systems:2013-05-05
/home/joanne/Dropbox/Comp 447 Societal Issues.zip:2013-02-11

Select multiple rows with the same value(s)

The problem is GROUP BY - if you group results by Locus, you only get one result per locus.

Try:

SELECT * FROM Genes WHERE Locus = '3' AND Chromosome = '10';

If you prefer using HAVING syntax, then GROUP BY id or something that is not repeating in the result set.

How to uninstall Apache with command line

sc delete Apache2.4

Remove service in windows

AngularJS - value attribute for select

You can't really do this unless you build them yourself in an ng-repeat.

<select ng-model="foo">
   <option ng-repeat="item in items" value="{{item.code}}">{{item.name}}</option>
</select>

BUT... it's probably not worth it. It's better to leave it function as designed and let Angular handle the inner workings. Angular uses the index this way so you can actually use an entire object as a value. So you can use a drop down binding to select a whole value rather than just a string, which is pretty awesome:

<select ng-model="foo" ng-options="item as item.name for item in items"></select>

{{foo | json}}

Vertically align an image inside a div with responsive height

With flexbox this is easy:

FIDDLE

Just add the following to the image container:

.img-container {
    position: absolute;
    top: 0;
    bottom: 0;
    left: 0;
    right: 0;
    display: flex; /* add */
    justify-content: center; /* add to align horizontal */
    align-items: center; /* add to align vertical */
}

Excel function to get first word from sentence in other cell

If you want to cater to 1-word cell, use this... based upon astander's

=IFERROR(LEFT(A1,SEARCH(" ",A1)-1),A1)

In Java, how do you determine if a thread is running?

Check the thread status by calling Thread.isAlive.

Expected corresponding JSX closing tag for input Reactjs

All tags must have enclosing tags. In my case, the hr and input elements weren't closed properly.

Parent Error was: JSX element 'div' has no corresponding closing tag, due to code below:

<hr class="my-4">
<input
  type="password"
  id="inputPassword"
  class="form-control"
  placeholder="Password"
  required
 >

Fix:

<hr class="my-4"/>
<input
 type="password"
 id="inputPassword"
 class="form-control"
 placeholder="Password"
 required
/>

The parent elements will show errors due to child element errors. Therefore, start investigating from most inner elements up to the parent ones.

Get Number of Rows returned by ResultSet in Java

In my case, I needed to get the total rows from a ResultSet and also access the ResultSet values ??if the total rows did not reach the limit of an XLS file.

For that, I had to make two adjustments to my code:

1) Change in object construction PreparedStatement

A default ResultSet object has a cursor that moves forward only. Thus, you can iterate through it only once and only from the first row to the last row. It is possible to produce ResultSet objects that are scrollable. The following code fragment illustrates how to make a result set that is scrollable and insensitive to updates by others.

PreparedStatement ps = connection.prepareStatement(sql, ResultSet.TYPE_SCROLL_INSENSITIVE, 
ResultSet.CONCUR_READ_ONLY);

2) Get total rows. The following code fragment illustrates how:

ResultSet rs = ps.executeQuery();
rs.last();
int totalRowsResult = rs.getRow();

PS: If the number of records of the query result is too large, you may run out of memory on the Java server by getting an exception: java.lang.OutOfMemoryError: Java heap space. This exception will occur when executing the rs.last () method

3) Access again the ResultSet and you don't get the message: exhaused result set. So, vou need reset the result set to the top, using rs.first() or rs.absolute(1). The following code fragment illustrates how:

rs.first();
System.out.println(rs.getString(1));

Cast received object to a List<object> or IEnumerable<object>

Nowadays it's like:

var collection = new List<object>(objectVar);

How can I delete one element from an array by value

Non-destructive removal of first occurrence:

a = [2, 4, 6, 3, 8]
n = a.index 3
a.take(n)+a.drop(n+1)

Implementing INotifyPropertyChanged - does a better way exist?

I haven't actually had a chance to try this myself yet, but next time I'm setting up a project with a big requirement for INotifyPropertyChanged I'm intending on writing a Postsharp attribute that will inject the code at compile time. Something like:

[NotifiesChange]
public string FirstName { get; set; }

Will become:

private string _firstName;

public string FirstName
{
   get { return _firstname; }
   set
   {
      if (_firstname != value)
      {
          _firstname = value;
          OnPropertyChanged("FirstName")
      }
   }
}

I'm not sure if this will work in practice and I need to sit down and try it out, but I don't see why not. I may need to make it accept some parameters for situations where more than one OnPropertyChanged needs to be triggered (if, for example, I had a FullName property in the class above)

Currently I'm using a custom template in Resharper, but even with that I'm getting fed up of all my properties being so long.


Ah, a quick Google search (which I should have done before I wrote this) shows that at least one person has done something like this before here. Not exactly what I had in mind, but close enough to show that the theory is good.

How to check if variable's type matches Type stored in a variable

The other answers all contain significant omissions.

The is operator does not check if the runtime type of the operand is exactly the given type; rather, it checks to see if the runtime type is compatible with the given type:

class Animal {}
class Tiger : Animal {}
...
object x = new Tiger();
bool b1 = x is Tiger; // true
bool b2 = x is Animal; // true also! Every tiger is an animal.

But checking for type identity with reflection checks for identity, not for compatibility

bool b5 = x.GetType() == typeof(Tiger); // true
bool b6 = x.GetType() == typeof(Animal); // false! even though x is an animal

or with the type variable
bool b7 = t == typeof(Tiger); // true
bool b8 = t == typeof(Animal); // false! even though x is an 

If that's not what you want, then you probably want IsAssignableFrom:

bool b9 = typeof(Tiger).IsAssignableFrom(x.GetType()); // true
bool b10 = typeof(Animal).IsAssignableFrom(x.GetType()); // true! A variable of type Animal may be assigned a Tiger.

or with the type variable
bool b11 = t.IsAssignableFrom(x.GetType()); // true
bool b12 = t.IsAssignableFrom(x.GetType()); // true! A 

Oracle: how to INSERT if a row doesn't exist

In addition to the perfect and valid answers given so far, there is also the ignore_row_on_dupkey_index hint you might want to use:

create table tq84_a (
  name varchar2 (20) primary key,
  age  number
);

insert /*+ ignore_row_on_dupkey_index(tq84_a(name)) */ into tq84_a values ('Johnny',   77);
insert /*+ ignore_row_on_dupkey_index(tq84_a(name)) */ into tq84_a values ('Pete'  ,   28);
insert /*+ ignore_row_on_dupkey_index(tq84_a(name)) */ into tq84_a values ('Sue'   ,   35);
insert /*+ ignore_row_on_dupkey_index(tq84_a(name)) */ into tq84_a values ('Johnny', null);

select * from tq84_a;

The hint is described on Tahiti.

How do I add all new files to SVN

If svn add whatever/directory/* doesn't work, you can do it the tough way:

svn st | grep ^\? | cut -c 2- | xargs svn add

How Connect to remote host from Aptana Studio 3

Window -> Show View -> Other -> Studio/Remote

(Drag this tabbed window wherever)

Click the add FTP button (see below); #profit

Add New FTP Site...

CSS: fixed to bottom and centered

I have encased the 'problem div in another div' lets call this div the enclose div... make the enclose div in css have a width of 100% and postion fixed with a bottom of 0... then insert the problem div into the enclose div this is how it would look

#problem {margin-right:auto;margin-left:auto; /*what ever other styles*/}
#enclose {position:fixed;bottom:0px;width:100%;}

then in html...

<div id="enclose">
    <div id="problem">
    <!--this is where the text/markup would go-->
    </div>
</div>

There ya go!
-Hypertextie

How to run Python script on terminal?

This Depends on what version of python is installed on you system. See below.

If You have Python 2.* version you have to run this command

python gameover.py

But if you have Python 3.* version you have to run this command

python3 gameover.py

Because for MAC with Python version 3.* you will get command not found error

if you run "python gameover.py"

Best way to combine two or more byte arrays in C#

Concat is the right answer, but for some reason a handrolled thing is getting the most votes. If you like that answer, perhaps you'd like this more general solution even more:

    IEnumerable<byte> Combine(params byte[][] arrays)
    {
        foreach (byte[] a in arrays)
            foreach (byte b in a)
                yield return b;
    }

which would let you do things like:

    byte[] c = Combine(new byte[] { 0, 1, 2 }, new byte[] { 3, 4, 5 }).ToArray();

How to use protractor to check if an element is visible?

If there are multiple elements in DOM with same class name. But only one of element is visible.

element.all(by.css('.text-input-input')).filter(function(ele){
        return ele.isDisplayed();
    }).then(function(filteredElement){
        filteredElement[0].click();
    });

In this example filter takes a collection of elements and returns a single visible element using isDisplayed().

How to get the connection String from a database

A very simple way to retrieve a connection string, is to create a text file, change the extension from .txt to .udl.

Double-clicking the .udl file will open the Data Link Properties wizard.

Configure and test the connection to your database server.

Close the wizard and open the .udl file with the text editor of your choice and simply copy the connection string (without the Provider=<driver>part) to use it in your C# application.

sample udl file content

[oledb]
; Everything after this line is an OLE DB initstring
Provider=SQLNCLI11.1;Integrated Security=SSPI;Persist Security Info=False;User ID="";Initial Catalog=YOURDATABASENAME;Data Source=YOURSERVERNAME;Initial File Name="";Server SPN=""

what you need to copy from it

Integrated Security=SSPI;Initial Catalog=YOURDATABASENAME;Data Source=YOURSERVERNAME;

If you want to specify username and password you can adopt from other answers.

Tutorial: https://teusje.wordpress.com/2012/02/21/how-to-test-an-sql-server-connection/

Full Screen DialogFragment in Android

This is what you need to set to fragment:

/* theme is optional, I am using leanback... */
setStyle(STYLE_NORMAL, R.style.AppTheme_Leanback);

In your case:

DialogFragment newFragment = new DetailsDialogFragment();
newFragment.setStyle(STYLE_NORMAL, R.style.AppTheme_Leanback);
newFragment.show(ft, "dialog");

And why? Because DialogFragment (when not told explicitly), will use its inner styles that will wrap your custom layout in it (no fullscreen, etc.).

And layout? No hacky way needed, this is working just fine:

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

Enjoy

Ruby: Can I write multi-line string with no concatenation?

conn.exec [
  "select attr1, attr2, attr3, ...",
  "from table1, table2, table3, ...",
  "where ..."
].join(' ')

This suggestion has the advantage over here-documents and long strings that auto-indenters can indent each part of the string appropriately. But it comes at an efficiency cost.

Decoding and verifying JWT token using System.IdentityModel.Tokens.Jwt

Within the package there is a class called JwtSecurityTokenHandler which derives from System.IdentityModel.Tokens.SecurityTokenHandler. In WIF this is the core class for deserialising and serialising security tokens.

The class has a ReadToken(String) method that will take your base64 encoded JWT string and returns a SecurityToken which represents the JWT.

The SecurityTokenHandler also has a ValidateToken(SecurityToken) method which takes your SecurityToken and creates a ReadOnlyCollection<ClaimsIdentity>. Usually for JWT, this will contain a single ClaimsIdentity object that has a set of claims representing the properties of the original JWT.

JwtSecurityTokenHandler defines some additional overloads for ValidateToken, in particular, it has a ClaimsPrincipal ValidateToken(JwtSecurityToken, TokenValidationParameters) overload. The TokenValidationParameters argument allows you to specify the token signing certificate (as a list of X509SecurityTokens). It also has an overload that takes the JWT as a string rather than a SecurityToken.

The code to do this is rather complicated, but can be found in the Global.asax.cx code (TokenValidationHandler class) in the developer sample called "ADAL - Native App to REST service - Authentication with ACS via Browser Dialog", located at

http://code.msdn.microsoft.com/AAL-Native-App-to-REST-de57f2cc

Alternatively, the JwtSecurityToken class has additional methods that are not on the base SecurityToken class, such as a Claims property that gets the contained claims without going via the ClaimsIdentity collection. It also has a Payload property that returns a JwtPayload object that lets you get at the raw JSON of the token. It depends on your scenario which approach it most appropriate.

The general (i.e. non JWT specific) documentation for the SecurityTokenHandler class is at

http://msdn.microsoft.com/en-us/library/system.identitymodel.tokens.securitytokenhandler.aspx

Depending on your application, you can configure the JWT handler into the WIF pipeline exactly like any other handler.

There are 3 samples of it in use in different types of application at

http://code.msdn.microsoft.com/site/search?f%5B0%5D.Type=SearchText&f%5B0%5D.Value=aal&f%5B1%5D.Type=User&f%5B1%5D.Value=Azure%20AD%20Developer%20Experience%20Team&f%5B1%5D.Text=Azure%20AD%20Developer%20Experience%20Team

Probably, one will suite your needs or at least be adaptable to them.

How can I make space between two buttons in same div?

Dragan B. solution is correct. In my case I needed the buttons to be spaced vertically when stacking so I added the mb-2 property to them.

<div class="btn-toolbar">
   <button type="button" class="btn btn-primary mr-2 mb-2">First</button>
   <button type="button" class="btn btn-primary mr-2 mb-2">Second</button>
   <button type="button" class="btn btn-primary mr-2 mb-2">Third</button>
</div>

Convert string to date in bash

date only work with GNU date (usually comes with Linux)

for OS X, two choices:

  1. change command (verified)

    #!/bin/sh
    #DATE=20090801204150
    #date -jf "%Y%m%d%H%M%S" $DATE "+date \"%A,%_d %B %Y %H:%M:%S\""
    date "Saturday, 1 August 2009 20:41:50"
    

    http://www.unix.com/shell-programming-and-scripting/116310-date-conversion.html

  2. Download the GNU Utilities from Coreutils - GNU core utilities (not verified yet) http://www.unix.com/emergency-unix-and-linux-support/199565-convert-string-date-add-1-a.html

Git: How to pull a single file from a server repository in Git?

I was looking for slightly different task, but this looks like what you want:

git archive --remote=$REPO_URL HEAD:$DIR_NAME -- $FILE_NAME |
tar xO > /where/you/want/to/have.it

I mean, if you want to fetch path/to/file.xz, you will set DIR_NAME to path/to and FILE_NAME to file.xz. So, you'll end up with something like

git archive --remote=$REPO_URL HEAD:path/to -- file.xz |
tar xO > /where/you/want/to/have.it

And nobody keeps you from any other form of unpacking instead of tar xO of course (It was me who need a pipe here, yeah).

Setting up Eclipse with JRE Path

You can add this line to eclipse.ini :

-vm 
D:/work/Java/jdk1.6.0_13/bin/javaw.exe  <-- change to your JDK actual path
-vmargs <-- needs to be after -vm <path>

But it's worth setting JAVA_HOME and JRE_HOME anyway because it may not work as if the path environment points to a different java version.

Because the next one to complain will be Maven, etc.

R: how to label the x-axis of a boxplot

If you read the help file for ?boxplot, you'll see there is a names= parameter.

     boxplot(apple, banana, watermelon, names=c("apple","banana","watermelon"))

enter image description here

How to Convert UTC Date To Local time Zone in MySql Select Query

 select convert_tz(now(),@@session.time_zone,'+05:30')

replace '+05:30' with desired timezone. see here - https://stackoverflow.com/a/3984412/2359994

to format into desired time format, eg:

 select DATE_FORMAT(convert_tz(now(),@@session.time_zone,'+05:30') ,'%b %d %Y %h:%i:%s %p') 

you will get similar to this -> Dec 17 2014 10:39:56 AM

How to resize superview to fit all subviews with autolayout?

You can do this by creating a constraint and connecting it via interface builder

See explanation: Auto_Layout_Constraints_in_Interface_Builder

raywenderlich beginning-auto-layout

AutolayoutPG Articles constraint Fundamentals

@interface ViewController : UIViewController {
    IBOutlet NSLayoutConstraint *leadingSpaceConstraint;
    IBOutlet NSLayoutConstraint *topSpaceConstraint;
}
@property (weak, nonatomic) IBOutlet NSLayoutConstraint *leadingSpaceConstraint;

connect this Constraint outlet with your sub views Constraint or connect super views Constraint too and set it according to your requirements like this

 self.leadingSpaceConstraint.constant = 10.0;//whatever you want to assign

I hope this clarifies it.

Given a class, see if instance has method (Ruby)

Actually this doesn't work for both Objects and Classes.

This does:

class TestClass
  def methodName
  end
end

So with the given answer, this works:

TestClass.method_defined? :methodName # => TRUE

But this does NOT work:

t = TestClass.new
t.method_defined? : methodName  # => ERROR!

So I use this for both classes and objects:

Classes:

TestClass.methods.include? 'methodName'  # => TRUE

Objects:

t = TestClass.new
t.methods.include? 'methodName'  # => TRUE

Use StringFormat to add a string to a WPF XAML binding

Here's an alternative that works well for readability if you have the Binding in the middle of the string or multiple bindings:

<TextBlock>
  <Run Text="Temperature is "/>
  <Run Text="{Binding CelsiusTemp}"/>
  <Run Text="°C"/>  
</TextBlock>

<!-- displays: 0°C (32°F)-->
<TextBlock>
  <Run Text="{Binding CelsiusTemp}"/>
  <Run Text="°C"/>
  <Run Text=" ("/>
  <Run Text="{Binding Fahrenheit}"/>
  <Run Text="°F)"/>
</TextBlock>

Print a div content using Jquery

Without using any plugin you can opt this logic.

$("#btn").click(function () {
    //Hide all other elements other than printarea.
    $("#printarea").show();
    window.print();
});

SQL query to find Nth highest salary from a salary table

SELECT * FROM Employee Emp1 
WHERE (N-1) = ( 
    SELECT COUNT(DISTINCT(Emp2.Salary)) 
    FROM  Employee Emp2 
    WHERE Emp2.Salary > Emp1.Salary)

For each record processed by outer query, inner query will be executed and will return how many records has records has salary less than the current salary. If you are looking for second highest salary then your query will stop as soon as inner query will return N-1.

How to access pandas groupby dataframe by key

gb = df.groupby(['A'])

gb_groups = grouped_df.groups

If you are looking for selective groupby objects then, do: gb_groups.keys(), and input desired key into the following key_list..

gb_groups.keys()

key_list = [key1, key2, key3 and so on...]

for key, values in gb_groups.iteritems():
    if key in key_list:
        print df.ix[values], "\n"

Best way to script remote SSH commands in Batch (Windows)

The -m switch of PuTTY takes a path to a script file as an argument, not a command.

Reference: https://the.earth.li/~sgtatham/putty/latest/htmldoc/Chapter3.html#using-cmdline-m

So you have to save your command (command_run) to a plain text file (e.g. c:\path\command.txt) and pass that to PuTTY:

putty.exe -ssh user@host -pw password -m c:\path\command.txt

Though note that you should use Plink (a command-line connection tool from PuTTY suite). It's a console application, so you can redirect its output to a file (what you cannot do with PuTTY).

A command-line syntax is identical, an output redirection added:

plink.exe -ssh user@host -pw password -m c:\path\command.txt > output.txt

See Using the command-line connection tool Plink.

And with Plink, you can actually provide the command directly on its command-line:

plink.exe -ssh user@host -pw password command > output.txt

Similar questions:
Automating running command on Linux from Windows using PuTTY
Executing command in Plink from a batch file

JavaScript, Node.js: is Array.forEach asynchronous?

Here is a small example you can run to test it:

[1,2,3,4,5,6,7,8,9].forEach(function(n){
    var sum = 0;
    console.log('Start for:' + n);
    for (var i = 0; i < ( 10 - n) * 100000000; i++)
        sum++;

    console.log('Ended for:' + n, sum);
});

It will produce something like this(if it takes too less/much time, increase/decrease the number of iterations):

(index):48 Start for:1
(index):52 Ended for:1 900000000
(index):48 Start for:2
(index):52 Ended for:2 800000000
(index):48 Start for:3
(index):52 Ended for:3 700000000
(index):48 Start for:4
(index):52 Ended for:4 600000000
(index):48 Start for:5
(index):52 Ended for:5 500000000
(index):48 Start for:6
(index):52 Ended for:6 400000000
(index):48 Start for:7
(index):52 Ended for:7 300000000
(index):48 Start for:8
(index):52 Ended for:8 200000000
(index):48 Start for:9
(index):52 Ended for:9 100000000
(index):45 [Violation] 'load' handler took 7285ms

How to kill zombie process

Sometimes the parent ppid cannot be killed, hence kill the zombie pid

kill -9 $(ps -A -ostat,pid | awk '/[zZ]/{ print $2 }')

Python: importing a sub-package or sub-module

If all you're trying to do is to get attribute1 in your global namespace, version 3 seems just fine. Why is it overkill prefix ?

In version 2, instead of

from module import attribute1

you can do

attribute1 = module.attribute1

Showing Thumbnail for link in WhatsApp || og:image meta-tag doesn't work

This Solution works for me:

    <meta property="og:title" content="Testing Title" />
    <meta
      property="og:description"
      content="This is best way to view your Time Table & Join Meetings"
    />
    <meta
      property="og:image"
      itemprop="image"
      content="//upload.wikimedia.org/wikipedia/commons/d/d4/JPEG_example_image_decompressed.jpg"
    />
    <meta property="og:url" content="https://google.com/" />
    <meta property="og:type" content="website" />
    <meta property="og:image:type" content="image/jpeg" />

tested on codesandbox.io

here's the link: https://l8ogr.csb.app/

one silly little thing did that magic, by removing "http" or "https" from the Image Url

if your image URL is ex: https://test.com/img.jpeg to //test.com/img.jpeg

<meta property="og:image" itemprop="image" content="//test.com/img.jpg"/>

How to import .py file from another directory?

Python3:

import importlib.machinery

loader = importlib.machinery.SourceFileLoader('report', '/full/path/report/other_py_file.py')
handle = loader.load_module('report')

handle.mainFunction(parameter)

This method can be used to import whichever way you want in a folder structure (backwards, forwards doesn't really matter, i use absolute paths just to be sure).

There's also the more normal way of importing a python module in Python3,

import importlib
module = importlib.load_module('folder.filename')
module.function()

Kudos to Sebastian for spplying a similar answer for Python2:

import imp

foo = imp.load_source('module.name', '/path/to/file.py')
foo.MyClass()

Install npm (Node.js Package Manager) on Windows (w/o using Node.js MSI)

https://nodejs.org/download/ . The page has Windows Installer (.msi) as well as other installers and binaries.Download and install for windows.

Node.js comes with NPM.

NPM is located in the directory where Node.js is installed.

android download pdf from url then open it with a pdf reader

This is the best method to download and view PDF file.You can just call it from anywhere as like

PDFTools.showPDFUrl(context, url);

here below put the code. It will works fine

public class PDFTools {
private static final String TAG = "PDFTools";
private static final String GOOGLE_DRIVE_PDF_READER_PREFIX = "http://drive.google.com/viewer?url=";
private static final String PDF_MIME_TYPE = "application/pdf";
private static final String HTML_MIME_TYPE = "text/html";


public static void showPDFUrl(final Context context, final String pdfUrl ) {
    if ( isPDFSupported( context ) ) {
        downloadAndOpenPDF(context, pdfUrl);
    } else {
        askToOpenPDFThroughGoogleDrive( context, pdfUrl );
    }
}


@TargetApi(Build.VERSION_CODES.GINGERBREAD)
public static void downloadAndOpenPDF(final Context context, final String pdfUrl) {
    // Get filename
    //final String filename = pdfUrl.substring( pdfUrl.lastIndexOf( "/" ) + 1 );
    String filename = "";
    try {
        filename = new GetFileInfo().execute(pdfUrl).get();
    } catch (InterruptedException e) {
        e.printStackTrace();
    } catch (ExecutionException e) {
        e.printStackTrace();
    }
    // The place where the downloaded PDF file will be put
    final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), filename );
    Log.e(TAG,"File Path:"+tempFile);
    if ( tempFile.exists() ) {
        // If we have downloaded the file before, just go ahead and show it.
        openPDF( context, Uri.fromFile( tempFile ) );
        return;
    }

    // Show progress dialog while downloading
    final ProgressDialog progress = ProgressDialog.show( context, context.getString( R.string.pdf_show_local_progress_title ), context.getString( R.string.pdf_show_local_progress_content ), true );

    // Create the download request
    DownloadManager.Request r = new DownloadManager.Request( Uri.parse( pdfUrl ) );
    r.setDestinationInExternalFilesDir( context, Environment.DIRECTORY_DOWNLOADS, filename );
    final DownloadManager dm = (DownloadManager) context.getSystemService( Context.DOWNLOAD_SERVICE );
    BroadcastReceiver onComplete = new BroadcastReceiver() {
        @Override
        public void onReceive(Context context, Intent intent) {
            if ( !progress.isShowing() ) {
                return;
            }
            context.unregisterReceiver( this );

            progress.dismiss();
            long downloadId = intent.getLongExtra( DownloadManager.EXTRA_DOWNLOAD_ID, -1 );
            Cursor c = dm.query( new DownloadManager.Query().setFilterById( downloadId ) );

            if ( c.moveToFirst() ) {
                int status = c.getInt( c.getColumnIndex( DownloadManager.COLUMN_STATUS ) );
                if ( status == DownloadManager.STATUS_SUCCESSFUL ) {
                    openPDF( context, Uri.fromFile( tempFile ) );
                }
            }
            c.close();
        }
    };
    context.registerReceiver( onComplete, new IntentFilter( DownloadManager.ACTION_DOWNLOAD_COMPLETE ) );

    // Enqueue the request
    dm.enqueue( r );
}


public static void askToOpenPDFThroughGoogleDrive( final Context context, final String pdfUrl ) {
    new AlertDialog.Builder( context )
            .setTitle( R.string.pdf_show_online_dialog_title )
            .setMessage( R.string.pdf_show_online_dialog_question )
            .setNegativeButton( R.string.pdf_show_online_dialog_button_no, null )
            .setPositiveButton( R.string.pdf_show_online_dialog_button_yes, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    openPDFThroughGoogleDrive(context, pdfUrl);
                }
            })
            .show();
}

public static void openPDFThroughGoogleDrive(final Context context, final String pdfUrl) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    i.setDataAndType(Uri.parse(GOOGLE_DRIVE_PDF_READER_PREFIX + pdfUrl ), HTML_MIME_TYPE );
    context.startActivity( i );
}

public static final void openPDF(Context context, Uri localUri ) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    i.setDataAndType( localUri, PDF_MIME_TYPE );
    context.startActivity( i );
}

public static boolean isPDFSupported( Context context ) {
    Intent i = new Intent( Intent.ACTION_VIEW );
    final File tempFile = new File( context.getExternalFilesDir( Environment.DIRECTORY_DOWNLOADS ), "test.pdf" );
    i.setDataAndType( Uri.fromFile( tempFile ), PDF_MIME_TYPE );
    return context.getPackageManager().queryIntentActivities( i, PackageManager.MATCH_DEFAULT_ONLY ).size() > 0;
}

// get File name from url
static class GetFileInfo extends AsyncTask<String, Integer, String>
{
    protected String doInBackground(String... urls)
    {
        URL url;
        String filename = null;
        try {
            url = new URL(urls[0]);
            HttpURLConnection conn = (HttpURLConnection) url.openConnection();
            conn.connect();
            conn.setInstanceFollowRedirects(false);
            if(conn.getHeaderField("Content-Disposition")!=null){
                String depo = conn.getHeaderField("Content-Disposition");

                String depoSplit[] = depo.split("filename=");
                filename = depoSplit[1].replace("filename=", "").replace("\"", "").trim();
            }else{
                filename = "download.pdf";
            }
        } catch (MalformedURLException e1) {
            e1.printStackTrace();
        } catch (IOException e) {
        }
        return filename;
    }

    @Override
    protected void onPreExecute() {
        super.onPreExecute();
    }
    @Override
    protected void onPostExecute(String result) {
        super.onPostExecute(result);
        // use result as file name
    }
}

}

try it. it will works, enjoy

Drag and drop a DLL to the GAC ("assembly") in windows server 2008 .net 4.0

The gacutil utility is not available on client machines, and the Window SDK license forbids redistributing it to your customers. When your customer can not, will not, (and really should not) download the 300MB Windows SDK as part of your application's install process.

There is an officially supported API you (or your installer) can use to register an assembly in the global assembly cache. Microsoft's Windows Installer technology knows how to call this API for you. You would have to consult your MSI installer utility (e.g. WiX, InnoSetup) for their own syntax of how to indicate you want an assembly to be registered in the Global Assembly Cache.

But MSI, and gacutil, are doing nothing special. They simply call the same API you can call yourself. For documentation on how to register an assembly through code, see:

KB317540: DOC: Global Assembly Cache (GAC) APIs Are Not Documented in the .NET Framework Software Development Kit (SDK) Documentation

var IAssemblyCache assemblyCache;
CreateAssemblyCache(ref assemblyCache, 0);


String manifestPath = "D:\Program Files\Contoso\Frobber\Grob.dll";

FUSION_INSTALL_REFERENCE refData;
refData.cbSize = SizeOf(refData); //The size of the structure in bytes
refData.dwFlags = 0; //Reserved, must be zero
refData.guidScheme = FUSION_REFCOUNT_FILEPATH_GUID; //The assembly is referenced by an application that is represented by a file in the file system. The szIdentifier field is the path to this file.
refData.szIdentifier = "D:\Program Files\Contoso\Frobber\SuperGrob.exe"; //A unique string that identifies the application that installed the assembly
refData.szNonCannonicalData = "Super cool grobber 9000"; //A string that is only understood by the entity that adds the reference. The GAC only stores this string

//Add a new assembly to the GAC. 
//The assembly must be persisted in the file system and is copied to the GAC.
assemblyCache.InstallAssembly(
      IASSEMBLYCACHE_INSTALL_FLAG_FORCE_REFRESH, //The files of an existing assembly are overwritten regardless of their version number
      manifestPath, //A string pointing to the dynamic-linked library (DLL) that contains the assembly manifest. Other assembly files must reside in the same directory as the DLL that contains the assembly manifest.
      refData);

More documentation before the KB article is deleted:

The fields of the structure are defined as follows:

  • cbSize - The size of the structure in bytes.
  • dwFlags - Reserved, must be zero.
  • guidScheme - The entity that adds the reference.
  • szIdentifier - A unique string that identifies the application that installed the assembly.
  • szNonCannonicalData - A string that is only understood by the entity that adds the reference. The GAC only stores this string.

Possible values for the guidScheme field can be one of the following:

FUSION_REFCOUNT_MSI_GUID - The assembly is referenced by an application that has been installed by using Windows Installer. The szIdentifier field is set to MSI, and szNonCannonicalData is set to Windows Installer. This scheme must only be used by Windows Installer itself. FUSION_REFCOUNT_UNINSTALL_SUBKEY_GUID - The assembly is referenced by an application that appears in Add/Remove Programs. The szIdentifier field is the token that is used to register the application with Add/Remove programs. FUSION_REFCOUNT_FILEPATH_GUID - The assembly is referenced by an application that is represented by a file in the file system. The szIdentifier field is the path to this file. FUSION_REFCOUNT_OPAQUE_STRING_GUID - The assembly is referenced by an application that is only represented by an opaque string. The szIdentifier is this opaque string. The GAC does not perform existence checking for opaque references when you remove this.

How to stop console from closing on exit?

Add a Console.ReadKey call to your program to force it to wait for you to press a key before exiting.

What is the purpose and use of **kwargs?

Unpacking dictionaries

** unpacks dictionaries.

This

func(a=1, b=2, c=3)

is the same as

args = {'a': 1, 'b': 2, 'c':3}
func(**args)

It's useful if you have to construct parameters:

args = {'name': person.name}
if hasattr(person, "address"):
    args["address"] = person.address
func(**args)  # either expanded to func(name=person.name) or
              #                    func(name=person.name, address=person.address)

Packing parameters of a function

def setstyle(**styles):
    for key, value in styles.iteritems():      # styles is a regular dictionary
        setattr(someobject, key, value)

This lets you use the function like this:

setstyle(color="red", bold=False)

an htop-like tool to display disk activity in linux

Use collectl which has extensive process I/O monitoring including monitoring threads.

Be warned that there are I/O counters for I/O being written to cache and I/O going to disk. collectl reports them separately. If you're not careful you can misinterpret the data. See http://collectl.sourceforge.net/Process.html

Of course, it shows a lot more than just process stats because you'd want one tool to provide everything rather than a bunch of different one that displays everything in different formats, right?

How to populate/instantiate a C# array with a single value?

The code below combines simple iteration for small copies and Array.Copy for large copies

    public static void Populate<T>( T[] array, int startIndex, int count, T value ) {
        if ( array == null ) {
            throw new ArgumentNullException( "array" );
        }
        if ( (uint)startIndex >= array.Length ) {
            throw new ArgumentOutOfRangeException( "startIndex", "" );
        }
        if ( count < 0 || ( (uint)( startIndex + count ) > array.Length ) ) {
            throw new ArgumentOutOfRangeException( "count", "" );
        }
        const int Gap = 16;
        int i = startIndex;

        if ( count <= Gap * 2 ) {
            while ( count > 0 ) {
                array[ i ] = value;
                count--;
                i++;
            }
            return;
        }
        int aval = Gap;
        count -= Gap;

        do {
            array[ i ] = value;
            i++;
            --aval;
        } while ( aval > 0 );

        aval = Gap;
        while ( true ) {
            Array.Copy( array, startIndex, array, i, aval );
            i += aval;
            count -= aval;
            aval *= 2;
            if ( count <= aval ) {
                Array.Copy( array, startIndex, array, i, count );
                break;
            }
        }
    }

The benchmarks for different array length using an int[] array are :

         2 Iterate:     1981 Populate:     2845
         4 Iterate:     2678 Populate:     3915
         8 Iterate:     4026 Populate:     6592
        16 Iterate:     6825 Populate:    10269
        32 Iterate:    16766 Populate:    18786
        64 Iterate:    27120 Populate:    35187
       128 Iterate:    49769 Populate:    53133
       256 Iterate:   100099 Populate:    71709
       512 Iterate:   184722 Populate:   107933
      1024 Iterate:   363727 Populate:   126389
      2048 Iterate:   710963 Populate:   220152
      4096 Iterate:  1419732 Populate:   291860
      8192 Iterate:  2854372 Populate:   685834
     16384 Iterate:  5703108 Populate:  1444185
     32768 Iterate: 11396999 Populate:  3210109

The first columns is the array size, followed by the time of copying using a simple iteration ( @JaredPared implementation ). The time of this method is after that. These are the benchmarks using an array of a struct of four integers

         2 Iterate:     2473 Populate:     4589
         4 Iterate:     3966 Populate:     6081
         8 Iterate:     7326 Populate:     9050
        16 Iterate:    14606 Populate:    16114
        32 Iterate:    29170 Populate:    31473
        64 Iterate:    57117 Populate:    52079
       128 Iterate:   112927 Populate:    75503
       256 Iterate:   226767 Populate:   133276
       512 Iterate:   447424 Populate:   165912
      1024 Iterate:   890158 Populate:   367087
      2048 Iterate:  1786918 Populate:   492909
      4096 Iterate:  3570919 Populate:  1623861
      8192 Iterate:  7136554 Populate:  2857678
     16384 Iterate: 14258354 Populate:  6437759
     32768 Iterate: 28351852 Populate: 12843259

Angular 5 Reactive Forms - Radio Button Group

IF you want to derive usg Boolean true False need to add "[]" around value

<form [formGroup]="form">
  <input type="radio" [value]=true formControlName="gender" >Male
  <input type="radio" [value]=false formControlName="gender">Female
</form>

Create Carriage Return in PHP String?

Fragment PHP (in console Cloud9):

echo "\n";
echo "1: first_srt=1\nsecnd_srt=2\n";
echo "\n";
echo '2: first_srt=1\nsecnd_srt=2\n';
echo "\n";
echo "==============\n";
echo "\n";

resulting output:

  1: first_srt=1
  secnd_srt=2

  2: first_srt=1\nsecnd_srt=2\n
  ==============

Difference between 1 and 2: " versus '

XAMPP permissions on Mac OS X?

If you are running your page on the new XAMPP-VM version of MacOS you will have to set daemon as user and as group. Here you can find a great step-by-step illustration with screenshots from aXfon on how to do this.

As the htdocs folder under XAMPP-VM will be mounted as external volume, you'll have to do this as root of the mounted volume (root@debian). This can be achieved through the XAMPP-VM GUI: See screenshot.

Once you are running as root of the mounted volume you can as described above change the file permission using:

chown -R daemon:daemon /opt/lampp/htdocs/FOLDER_OF_YOUR_PAGE

Source (w/ step-by-step illustration): aXfon

SQL Server 2012 can't start because of a login failure

I had a similar issue that was resolved with the following:

  1. In Services.MSC click on the Log On tab and add the user with minimum privileges and password (on the service that is throwing the login error)
  2. By Starting Sql Server to run as Administrator

If the user is a domain user use Domain username and password

Checking Bash exit status of several commands efficiently

I have a set of scripting functions that I use extensively on my Red Hat system. They use the system functions from /etc/init.d/functions to print green [ OK ] and red [FAILED] status indicators.

You can optionally set the $LOG_STEPS variable to a log file name if you want to log which commands fail.

Usage

step "Installing XFS filesystem tools:"
try rpm -i xfsprogs-*.rpm
next

step "Configuring udev:"
try cp *.rules /etc/udev/rules.d
try udevtrigger
next

step "Adding rc.postsysinit hook:"
try cp rc.postsysinit /etc/rc.d/
try ln -s rc.d/rc.postsysinit /etc/rc.postsysinit
try echo $'\nexec /etc/rc.postsysinit' >> /etc/rc.sysinit
next

Output

Installing XFS filesystem tools:        [  OK  ]
Configuring udev:                       [FAILED]
Adding rc.postsysinit hook:             [  OK  ]

Code

#!/bin/bash

. /etc/init.d/functions

# Use step(), try(), and next() to perform a series of commands and print
# [  OK  ] or [FAILED] at the end. The step as a whole fails if any individual
# command fails.
#
# Example:
#     step "Remounting / and /boot as read-write:"
#     try mount -o remount,rw /
#     try mount -o remount,rw /boot
#     next
step() {
    echo -n "$@"

    STEP_OK=0
    [[ -w /tmp ]] && echo $STEP_OK > /tmp/step.$$
}

try() {
    # Check for `-b' argument to run command in the background.
    local BG=

    [[ $1 == -b ]] && { BG=1; shift; }
    [[ $1 == -- ]] && {       shift; }

    # Run the command.
    if [[ -z $BG ]]; then
        "$@"
    else
        "$@" &
    fi

    # Check if command failed and update $STEP_OK if so.
    local EXIT_CODE=$?

    if [[ $EXIT_CODE -ne 0 ]]; then
        STEP_OK=$EXIT_CODE
        [[ -w /tmp ]] && echo $STEP_OK > /tmp/step.$$

        if [[ -n $LOG_STEPS ]]; then
            local FILE=$(readlink -m "${BASH_SOURCE[1]}")
            local LINE=${BASH_LINENO[0]}

            echo "$FILE: line $LINE: Command \`$*' failed with exit code $EXIT_CODE." >> "$LOG_STEPS"
        fi
    fi

    return $EXIT_CODE
}

next() {
    [[ -f /tmp/step.$$ ]] && { STEP_OK=$(< /tmp/step.$$); rm -f /tmp/step.$$; }
    [[ $STEP_OK -eq 0 ]]  && echo_success || echo_failure
    echo

    return $STEP_OK
}

Aggregate function in SQL WHERE-Clause

You can't use an aggregate directly in a WHERE clause; that's what HAVING clauses are for.

You can use a sub-query which contains an aggregate in the WHERE clause.

Detect HTTP or HTTPS then force HTTPS in JavaScript

You should check this: https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers/Content-Security-Policy/upgrade-insecure-requests

Add this meta tag to your index.html inside head

<meta http-equiv="Content-Security-Policy" content="upgrade-insecure-requests">

Hope it helped.

Chart.js v2 hide dataset labels

Just set the label and tooltip options like so

...
options: {
    legend: {
        display: false
    },
    tooltips: {
        callbacks: {
           label: function(tooltipItem) {
                  return tooltipItem.yLabel;
           }
        }
    }
}

Fiddle - http://jsfiddle.net/g19220r6/

Deleting DataFrame row in Pandas based on column value

The best way to do this is with boolean masking:

In [56]: df
Out[56]:
     line_date  daysago  line_race  rating    raw  wrating
0   2007-03-31       62         11      56  1.000   56.000
1   2007-03-10       83         11      67  1.000   67.000
2   2007-02-10      111          9      66  1.000   66.000
3   2007-01-13      139         10      83  0.881   73.096
4   2006-12-23      160         10      88  0.793   69.787
5   2006-11-09      204          9      52  0.637   33.106
6   2006-10-22      222          8      66  0.582   38.408
7   2006-09-29      245          9      70  0.519   36.318
8   2006-09-16      258         11      68  0.486   33.063
9   2006-08-30      275          8      72  0.447   32.160
10  2006-02-11      475          5      65  0.165   10.698
11  2006-01-13      504          0      70  0.142    9.969
12  2006-01-02      515          0      64  0.135    8.627
13  2005-12-06      542          0      70  0.118    8.246
14  2005-11-29      549          0      70  0.114    7.963
15  2005-11-22      556          0      -1  0.110   -0.110
16  2005-11-01      577          0      -1  0.099   -0.099
17  2005-10-20      589          0      -1  0.093   -0.093
18  2005-09-27      612          0      -1  0.083   -0.083
19  2005-09-07      632          0      -1  0.075   -0.075
20  2005-06-12      719          0      69  0.049    3.360
21  2005-05-29      733          0      -1  0.045   -0.045
22  2005-05-02      760          0      -1  0.040   -0.040
23  2005-04-02      790          0      -1  0.034   -0.034
24  2005-03-13      810          0      -1  0.031   -0.031
25  2004-11-09      934          0      -1  0.017   -0.017

In [57]: df[df.line_race != 0]
Out[57]:
     line_date  daysago  line_race  rating    raw  wrating
0   2007-03-31       62         11      56  1.000   56.000
1   2007-03-10       83         11      67  1.000   67.000
2   2007-02-10      111          9      66  1.000   66.000
3   2007-01-13      139         10      83  0.881   73.096
4   2006-12-23      160         10      88  0.793   69.787
5   2006-11-09      204          9      52  0.637   33.106
6   2006-10-22      222          8      66  0.582   38.408
7   2006-09-29      245          9      70  0.519   36.318
8   2006-09-16      258         11      68  0.486   33.063
9   2006-08-30      275          8      72  0.447   32.160
10  2006-02-11      475          5      65  0.165   10.698

UPDATE: Now that pandas 0.13 is out, another way to do this is df.query('line_race != 0').

Getting data-* attribute for onclick event for an html element

User $() to get jQuery object from your link and data() to get your values

<a id="option1" 
   data-id="10" 
   data-option="21" 
   href="#" 
   onclick="goDoSomething($(this).data('id'),$(this).data('option'));">
       Click to do something
</a>

Rewrite all requests to index.php with nginx

Here is what worked for me to solve part 1 of this question:

    location / {
            rewrite ^([^.]*[^/])$ $1/ permanent;
            try_files $uri $uri/ /index.php =404;
            include fastcgi_params;
            fastcgi_pass php5-fpm-sock;
            fastcgi_index index.php;
            fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;
            fastcgi_intercept_errors on;
    }

rewrite ^([^.]*[^/])$ $1/ permanent; rewrites non-file addresses (addresses without file extensions) to have a "/" at the end. I did this because I was running into "Access denied." message when I tried to access the folder without it.

try_files $uri $uri/ /index.php =404; is borrowed from SanjuD's answer, but with an extra 404 reroute if the location still isn't found.

fastcgi_index index.php; was the final piece of the puzzle that I was missing. The folder didn't reroute to the index.php without this line.

Using Rsync include and exclude options to include directory and file by pattern

The problem is that --exclude="*" says to exclude (for example) the 1260000000/ directory, so rsync never examines the contents of that directory, so never notices that the directory contains files that would have been matched by your --include.

I think the closest thing to what you want is this:

rsync -nrv --include="*/" --include="file_11*.jpg" --exclude="*" /Storage/uploads/ /website/uploads/

(which will include all directories, and all files matching file_11*.jpg, but no other files), or maybe this:

rsync -nrv --include="/[0-9][0-9][0-9]0000000/" --include="file_11*.jpg" --exclude="*" /Storage/uploads/ /website/uploads/

(same concept, but much pickier about the directories it will include).

How to call python script on excel vba?

To those who are stuck wondering why a window flashes and goes away without doing anything the python script is meant to do after calling the shell command from VBA: In my program

Sub runpython()

Dim Ret_Val
args = """F:\my folder\helloworld.py"""
Ret_Val = Shell("C:\Users\username\AppData\Local\Programs\Python\Python36\python.exe " & " " & args, vbNormalFocus)
If Ret_Val = 0 Then
   MsgBox "Couldn't run python script!", vbOKOnly
End If
End Sub

In the line args = """F:\my folder\helloworld.py""", I had to use triple quotes for this to work. If I use just regular quotes like: args = "F:\my folder\helloworld.py" the program would not work. The reason for this is that there is a space in the path (my folder). If there is a space in the path, in VBA, you need to use triple quotes.

SELECT max(x) is returning null; how can I make it return 0?

Oracle would be

SELECT NVL(MAX(X), 0) AS MaxX
FROM tbl
WHERE XID = 1;

NSCameraUsageDescription in iOS 10.0 runtime crash?

Alternatively open Info.plist as source code and add this:

<key>NSCameraUsageDescription</key>
<string>Camera usage description</string>

Python Remove last 3 characters of a string

Removing any and all whitespace:

foo = ''.join(foo.split())

Removing last three characters:

foo = foo[:-3]

Converting to capital letters:

foo = foo.upper()

All of that code in one line:

foo = ''.join(foo.split())[:-3].upper()

How to update Ruby to 1.9.x on Mac?

I'll disagree with The Tin Man here. I regard rbenv as preferable to RVM. rbenv doesn't interfere drastically with your shell the way RVM does, and it lets you add separate Ruby installations in ordinary folders that you can examine directly. It allows you to compile Ruby yourself. Good outline of the differences here: https://github.com/sstephenson/rbenv/wiki/Why-rbenv%3F

I provide instructions for compiling Ruby 1.9 for rbenv here. Further, more detailed information here. I have used this technique with easy success on Snow Leopard, Lion, and Mountain Lion.

Append same text to every cell in a column in Excel

See if this works for you.

  • All your data is in column A (beginning at row 1).
  • In column B, row 1, enter =A1&","
  • This will make cell B1 equal A1 with a comma appended.
  • Now select cell B1 and drag from the bottom right of cell down through all your rows (this copies the formula and uses the corresponding column A value.)
  • Select the newly appended data, copy it and paste it where you need using Paste -> By Value

That's It!

How can I mock the JavaScript window object using Jest?

If it's similar to the window location problem at window.location.href can't be changed in tests. #890, you could try (adjusted):

delete global.window.open;
global.window = Object.create(window);
global.window.open = jest.fn();

How to convert Set<String> to String[]?

Use toArray(T[] a) method:

String[] array = set.toArray(new String[0]);

Could not autowire field in spring. why?

I've faced the same issue today. Turned out to be I forgot to mention @Service/@Component annotation for my service implementation file, for which spring is not able autowire and failing to create the bean.

Copying HTML code in Google Chrome's inspect element

  1. Select the <html> tag in Elements.
  2. Do CTRL-C.
  3. Check if there is only lefting <!DOCTYPE html> before the <html>.

Finding median of list in Python

import numpy as np
def get_median(xs):
        mid = len(xs) // 2  # Take the mid of the list
        if len(xs) % 2 == 1: # check if the len of list is odd
            return sorted(xs)[mid] #if true then mid will be median after sorting
        else:
            #return 0.5 * sum(sorted(xs)[mid - 1:mid + 1])
            return 0.5 * np.sum(sorted(xs)[mid - 1:mid + 1]) #if false take the avg of mid
print(get_median([7, 7, 3, 1, 4, 5]))
print(get_median([1,2,3, 4,5]))

CSS to prevent child element from inheriting parent styles

Can't you style the forms themselves? Then, style the divs accordingly.

form
{
    /* styles */
}

You can always overrule inherited styles by making it important:

form
{
    /* styles */ !important
}

Parsing JSON in Excel VBA

Thanks a lot Codo.

I've just updated and completed what you have done to :

  • serialize the json (I need it to inject the json in a text-like document)
  • add, remove and update node (who knows)

    Option Explicit
    
    Private ScriptEngine As ScriptControl
    
    Public Sub InitScriptEngine()
        Set ScriptEngine = New ScriptControl
        ScriptEngine.Language = "JScript"
        ScriptEngine.AddCode "function getProperty(jsonObj, propertyName) { return jsonObj[propertyName]; } "
        ScriptEngine.AddCode "function getType(jsonObj, propertyName) {return typeof(jsonObj[propertyName]);}"
        ScriptEngine.AddCode "function getKeys(jsonObj) { var keys = new Array(); for (var i in jsonObj) { keys.push(i); } return keys; } "
        ScriptEngine.AddCode "function addKey(jsonObj, propertyName, value) { jsonObj[propertyName] = value; return jsonObj;}"
        ScriptEngine.AddCode "function removeKey(jsonObj, propertyName) { var json = jsonObj; delete json[propertyName]; return json }"
    End Sub
    Public Function removeJSONProperty(ByVal JsonObject As Object, propertyName As String)
        Set removeJSONProperty = ScriptEngine.Run("removeKey", JsonObject, propertyName)
    End Function
    
    Public Function updateJSONPropertyValue(ByVal JsonObject As Object, propertyName As String, value As String) As Object
        Set updateJSONPropertyValue = ScriptEngine.Run("removeKey", JsonObject, propertyName)
        Set updateJSONPropertyValue = ScriptEngine.Run("addKey", JsonObject, propertyName, value)
    End Function
    
    
    
    Public Function addJSONPropertyValue(ByVal JsonObject As Object, propertyName As String, value As String) As Object
        Set addJSONPropertyValue = ScriptEngine.Run("addKey", JsonObject, propertyName, value)
    End Function
    Public Function DecodeJsonString(ByVal JsonString As String)
    InitScriptEngine
        Set DecodeJsonString = ScriptEngine.Eval("(" + JsonString + ")")
    End Function
    
    Public Function GetProperty(ByVal JsonObject As Object, ByVal propertyName As String) As Variant
        GetProperty = ScriptEngine.Run("getProperty", JsonObject, propertyName)
    End Function
    
    Public Function GetObjectProperty(ByVal JsonObject As Object, ByVal propertyName As String) As Object
        Set GetObjectProperty = ScriptEngine.Run("getProperty", JsonObject, propertyName)
    End Function
    
    Public Function SerializeJSONObject(ByVal JsonObject As Object) As String()
        Dim Length As Integer
        Dim KeysArray() As String
        Dim KeysObject As Object
        Dim Index As Integer
        Dim Key As Variant
        Dim tmpString As String
        Dim tmpJSON As Object
        Dim tmpJSONArray() As Variant
        Dim tmpJSONObject() As Variant
        Dim strJsonObject As String
        Dim tmpNbElement As Long, i As Long
        InitScriptEngine
        Set KeysObject = ScriptEngine.Run("getKeys", JsonObject)
    
        Length = GetProperty(KeysObject, "length")
        ReDim KeysArray(Length - 1)
        Index = 0
        For Each Key In KeysObject
        tmpString = ""
            If ScriptEngine.Run("getType", JsonObject, Key) = "object" Then
        'MsgBox "object " & SerializeJSONObject(GetObjectProperty(JsonObject, Key))(0)
                Set tmpJSON = GetObjectProperty(JsonObject, Key)
                strJsonObject = VBA.Replace(ScriptEngine.Run("getKeys", tmpJSON), " ", "")
                tmpNbElement = Len(strJsonObject) - Len(VBA.Replace(strJsonObject, ",", ""))
    
                If VBA.IsNumeric(Left(ScriptEngine.Run("getKeys", tmpJSON), 1)) = True Then
    
                    ReDim tmpJSONArray(tmpNbElement)
                    For i = 0 To tmpNbElement
                        tmpJSONArray(i) = GetProperty(tmpJSON, i)
                    Next
                        tmpString = "[" & Join(tmpJSONArray, ",") & "]"
                Else
                    tmpString = "{" & Join(SerializeJSONObject(tmpJSON), ", ") & "}"
                End If
    
            Else
                    tmpString = GetProperty(JsonObject, Key)
    
            End If
    
            KeysArray(Index) = Key & ": " & tmpString
            Index = Index + 1
        Next
    
        SerializeJSONObject = KeysArray
    
    End Function
    
    Public Function GetKeys(ByVal JsonObject As Object) As String()
        Dim Length As Integer
        Dim KeysArray() As String
        Dim KeysObject As Object
        Dim Index As Integer
        Dim Key As Variant
    InitScriptEngine
        Set KeysObject = ScriptEngine.Run("getKeys", JsonObject)
        Length = GetProperty(KeysObject, "length")
        ReDim KeysArray(Length - 1)
        Index = 0
        For Each Key In KeysObject
            KeysArray(Index) = Key
            Index = Index + 1
        Next
        GetKeys = KeysArray
    End Function
    

Print all key/value pairs in a Java ConcurrentHashMap

  //best and simple way to show keys and values

    //initialize map
    Map<Integer, String> map = new HashMap<Integer, String>();

   //Add some values
    map.put(1, "Hi");
    map.put(2, "Hello");

    // iterate map using entryset in for loop
    for(Entry<Integer, String> entry : map.entrySet())
    {   //print keys and values
         System.out.println(entry.getKey() + " : " +entry.getValue());
    }

   //Result : 
    1 : Hi
    2 : Hello

CSS "and" and "or"

The :not pseudo-class is not supported by IE. I'd got for something like this instead:

.registration_form_right input[type="text"],
.registration_form_right input[type="password"],
.registration_form_right input[type="submit"],
.registration_form_right input[type="button"] {
  ...
}

Some duplication there, but it's a small price to pay for higher compatibility.

Programmatic equivalent of default(Type)

  • In case of a value type use Activator.CreateInstance and it should work fine.
  • When using reference type just return null
public static object GetDefault(Type type)
{
   if(type.IsValueType)
   {
      return Activator.CreateInstance(type);
   }
   return null;
}

In the newer version of .net such as .net standard, type.IsValueType needs to be written as type.GetTypeInfo().IsValueType

Can you install and run apps built on the .NET framework on a Mac?

.NetCore is a fine release from Microsoft and Visual Studio's latest version is also available for mac but there is still some limitation. Like for creating GUI based application on .net core you have to write code manually for everything. Like in older version of VS we just drag and drop the things and magic happens. But in VS latest version for mac every code has to be written manually. However you can make web application and console application easily on VS for mac.

Facebook Graph API v2.0+ - /me/friends returns empty, or only friends who also use my application

In the Facebook SDK Graph API v2.0 or above, you must request the user_friends permission from each user in the time of Facebook login since user_friends is no longer included by default in every login; we have to add that.

Each user must grant the user_friends permission in order to appear in the response to /me/friends.

let fbLoginManager : FBSDKLoginManager = FBSDKLoginManager()
fbLoginManager.loginBehavior = FBSDKLoginBehavior.web
fbLoginManager.logIn(withReadPermissions: ["email","user_friends","public_profile"], from: self) { (result, error) in
    if (error == nil) {

        let fbloginresult : FBSDKLoginManagerLoginResult = result!
        if fbloginresult.grantedPermissions != nil {
            if (fbloginresult.grantedPermissions.contains("email")) {
                // Do the stuff
            }
            else {
            }
        }
        else {
        }
    }
}

So at the time of Facebook login, it prompts with a screen which contain all the permissions:

Enter image description here

If the user presses the Continue button, the permissions will be set. When you access the friends list using Graph API, your friends who logged into the application as above will be listed

if ((FBSDKAccessToken.current()) != nil) {
    FBSDKGraphRequest(graphPath: "/me/friends", parameters: ["fields" : "id,name"]).start(completionHandler: { (connection, result, error) -> Void in
        if (error == nil) {

            print(result!)
        }
    })
}

The output will contain the users who granted the user_friends permission at the time of login to your application through Facebook.

{
    data = (
             {
                 id = xxxxxxxxxx;
                 name = "xxxxxxxx";
             }
           );
    paging = {
        cursors = {
            after = xxxxxx;
            before = xxxxxxx;
        };
    };
    summary = {
        "total_count" = 8;
    };
}

Append values to a set in Python

This question is the first one that shows up on Google when one looks up "Python how to add elements to set", so it's worth noting explicitly that, if you want to add a whole string to a set, it should be added with .add(), not .update().

Say you have a string foo_str whose contents are 'this is a sentence', and you have some set bar_set equal to set().

If you do bar_set.update(foo_str), the contents of your set will be {'t', 'a', ' ', 'e', 's', 'n', 'h', 'c', 'i'}.

If you do bar_set.add(foo_str), the contents of your set will be {'this is a sentence'}.

Plotting dates on the x-axis with Python's matplotlib

As @KyssTao has been saying, help(dates.num2date) says that the x has to be a float giving the number of days since 0001-01-01 plus one. Hence, 19910102 is not 2/Jan/1991, because if you counted 19910101 days from 0001-01-01 you'd get something in the year 54513 or similar (divide by 365.25, number of days in a year).

Use datestr2num instead (see help(dates.datestr2num)):

new_x = dates.datestr2num(date) # where date is '01/02/1991'

How do I update/upsert a document in Mongoose?

You were close with

Contact.update({phone:request.phone}, contact, {upsert: true}, function(err){...})

but your second parameter should be an object with a modification operator for example

Contact.update({phone:request.phone}, {$set: { phone: request.phone }}, {upsert: true}, function(err){...})

I want to use CASE statement to update some records in sql server 2005

Add a WHERE clause

UPDATE dbo.TestStudents  
SET     LASTNAME =  CASE  
                        WHEN LASTNAME = 'AAA' THEN 'BBB' 
                        WHEN LASTNAME = 'CCC' THEN 'DDD' 
                        WHEN LASTNAME = 'EEE' THEN 'FFF' 
                        ELSE LASTNAME
                    END 
WHERE   LASTNAME IN ('AAA', 'CCC', 'EEE')

Error : Index was outside the bounds of the array.

public int[] posStatus;       

public UsersInput()    
{    
    //It means postStatus will contain 9 elements from index 0 to 8. 
    this.posStatus = new int[9];   
}

int intUsersInput = 0;   

if (posStatus[intUsersInput-1] == 0) //if i input 9, it should go to 8?    
{    
    posStatus[intUsersInput-1] += 1; //set it to 1    
} 

SQL LIKE condition to check for integer?

I'm late to the party here, but if you're dealing with integers of a fixed length you can just do integer comparison:

SELECT * FROM books WHERE price > 89999 AND price < 90100;

Add JsonArray to JsonObject

I think it is a problem(aka. bug) with the API you are using. JSONArray implements Collection (the json.org implementation from which this API is derived does not have JSONArray implement Collection). And JSONObject has an overloaded put() method which takes a Collection and wraps it in a JSONArray (thus causing the problem). I think you need to force the other JSONObject.put() method to be used:

    jsonObject.put("aoColumnDefs",(Object)arr);

You should file a bug with the vendor, pretty sure their JSONObject.put(String,Collection) method is broken.

How to test if a double is zero?

Yes; all primitive numeric types default to 0.

However, calculations involving floating-point types (double and float) can be imprecise, so it's usually better to check whether it's close to 0:

if (Math.abs(foo.x) < 2 * Double.MIN_VALUE)

You need to pick a margin of error, which is not simple.

Easiest way to detect Internet connection on iOS?

Here is a good solution for checking connectivity using Swift, without using Reachability. I found it on this blog.

Create a new Swift file in your project called Network.swift (for example). Paste this code inside that file:

import Foundation

public class Network {

    class func isConnectedToNetwork()->Bool{

        var Status:Bool = false
        let url = NSURL(string: "http://google.com/")
        let request = NSMutableURLRequest(URL: url!)
        request.HTTPMethod = "HEAD"
        request.cachePolicy = NSURLRequestCachePolicy.ReloadIgnoringLocalAndRemoteCacheData
        request.timeoutInterval = 10.0

        var response: NSURLResponse?

        var data = NSURLConnection.sendSynchronousRequest(request, returningResponse: &response, error: nil) as NSData?

        if let httpResponse = response as? NSHTTPURLResponse {
            if httpResponse.statusCode == 200 {
                Status = true
            }
        }

        return Status
    }
}

You can then check for connectivity anywhere in your project by using:

if Network.isConnectedToNetwork() == true {
    println("Internet connection OK")
} else {
    println("Internet connection FAILED")
}

Script to get the HTTP status code of a list of urls?

Due to https://mywiki.wooledge.org/BashPitfalls#Non-atomic_writes_with_xargs_-P (output from parallel jobs in xargs risks being mixed), I would use GNU Parallel instead of xargs to parallelize:

cat url.lst |
  parallel -P0 -q curl -o /dev/null --silent --head --write-out '%{url_effective}: %{http_code}\n' > outfile

In this particular case it may be safe to use xargs because the output is so short, so the problem with using xargs is rather that if someone later changes the code to do something bigger, it will no longer be safe. Or if someone reads this question and thinks he can replace curl with something else, then that may also not be safe.

Angular 2: How to write a for loop, not a foreach loop

you can use _.range([optional] start, end). It creates a new Minified list containing an interval of numbers from start (inclusive) until the end (exclusive). Here I am using lodash.js ._range() method.

Example:

CODE

var dayOfMonth = _.range(1,32);  // It creates a new list from 1 to 31.

//HTML Now, you can use it in For loop

<div *ngFor="let day of dayOfMonth">{{day}}</div>

Is List<Dog> a subclass of List<Animal>? Why are Java generics not implicitly polymorphic?

The answer as well as other answers are correct. I am going to add to those answers with a solution that I think will be helpful. I think this comes up often in programming. One thing to note is that for Collections (Lists, Sets, etc.) the main issue is adding to the Collection. That is where things break down. Even removing is OK.

In most cases, we can use Collection<? extends T> rather then Collection<T> and that should be the first choice. However, I am finding cases where it is not easy to do that. It is up for debate as to whether that is always the best thing to do. I am presenting here a class DownCastCollection that can take convert a Collection<? extends T> to a Collection<T> (we can define similar classes for List, Set, NavigableSet,..) to be used when using the standard approach is very inconvenient. Below is an example of how to use it (we could also use Collection<? extends Object> in this case, but I am keeping it simple to illustrate using DownCastCollection.

/**Could use Collection<? extends Object> and that is the better choice. 
* But I am doing this to illustrate how to use DownCastCollection. **/

public static void print(Collection<Object> col){  
    for(Object obj : col){
    System.out.println(obj);
    }
}
public static void main(String[] args){
  ArrayList<String> list = new ArrayList<>();
  list.addAll(Arrays.asList("a","b","c"));
  print(new DownCastCollection<Object>(list));
}

Now the class:

import java.util.AbstractCollection;
import java.util.Collection;
import java.util.Iterator;
import java.util.NoSuchElementException;

public class DownCastCollection<E> extends AbstractCollection<E> implements Collection<E> {
private Collection<? extends E> delegate;

public DownCastCollection(Collection<? extends E> delegate) {
    super();
    this.delegate = delegate;
}

@Override
public int size() {
    return delegate ==null ? 0 : delegate.size();
}

@Override
public boolean isEmpty() {
    return delegate==null || delegate.isEmpty();
}

@Override
public boolean contains(Object o) {
    if(isEmpty()) return false;
    return delegate.contains(o);
}
private class MyIterator implements Iterator<E>{
    Iterator<? extends E> delegateIterator;

    protected MyIterator() {
        super();
        this.delegateIterator = delegate == null ? null :delegate.iterator();
    }

    @Override
    public boolean hasNext() {
        return delegateIterator != null && delegateIterator.hasNext();
    }

    @Override
    public  E next() {
        if(!hasNext()) throw new NoSuchElementException("The iterator is empty");
        return delegateIterator.next();
    }

    @Override
    public void remove() {
        delegateIterator.remove();

    }

}
@Override
public Iterator<E> iterator() {
    return new MyIterator();
}



@Override
public boolean add(E e) {
    throw new UnsupportedOperationException();
}

@Override
public boolean remove(Object o) {
    if(delegate == null) return false;
    return delegate.remove(o);
}

@Override
public boolean containsAll(Collection<?> c) {
    if(delegate==null) return false;
    return delegate.containsAll(c);
}

@Override
public boolean addAll(Collection<? extends E> c) {
    throw new UnsupportedOperationException();
}

@Override
public boolean removeAll(Collection<?> c) {
    if(delegate == null) return false;
    return delegate.removeAll(c);
}

@Override
public boolean retainAll(Collection<?> c) {
    if(delegate == null) return false;
    return delegate.retainAll(c);
}

@Override
public void clear() {
    if(delegate == null) return;
        delegate.clear();

}

}

PHP - how to create a newline character?

Actually \r\n is for the html side of the output. With those chars you can just create a newline in the html code to make it more readable:

echo "<html>First line \r\n Second line</html>";

will output:

<html>First line
Second line</html>

that viewing the page will be:

First line Second line

If you really meant this you have just to fix the single quote with the "" quote:

echo "\r\n";

Otherwise if you mean to split the text, in our sample 'First line' and 'Second line' you have to use the html code: <br />:

First line<br />Second line

that will output:

First line
Second line

Also it would be more readable if you replace the entire script with:

echo "$clientid $lastname \r\n";

how to get param in method post spring mvc?

  1. Spring annotations will work fine if you remove enctype="multipart/form-data".

    @RequestParam(value="txtEmail", required=false)
    
  2. You can even get the parameters from the request object .

    request.getParameter(paramName);
    
  3. Use a form in case the number of attributes are large. It will be convenient. Tutorial to get you started.

  4. Configure the Multi-part resolver if you want to receive enctype="multipart/form-data".

    <bean id="multipartResolver"
      class="org.springframework.web.multipart.commons.CommonsMultipartResolver">
        <property name="maxUploadSize" value="250000"/>
    </bean>
    

Refer the Spring documentation.

Select something that has more/less than x character

Today I was trying same in db2 and used below, in my case I had spaces at the end of varchar column data

SELECT EmployeeName FROM EmployeeTable WHERE LENGTH(TRIM(EmployeeName))> 4;

jquery function setInterval

You can use it like this:

$(document).ready(function(){

    setTimeout("swapImages()",1000);

    function swapImages(){

        var active = $('.active'); 
        var next = ($('.active').next().length > 0) ? $('.active').next() : $('#siteNewsHead img:first');

        active.removeClass('active');
        next.addClass('active');
        setTimeout("swapImages()",1000);
}

});

How to create empty constructor for data class in Kotlin Android

the modern answer for this should be using Kotlin's no-arg compiler plugin which creates a non argument construct code for classic apies more about here

simply you have to add the plugin class path in build.gradle project level

    dependencies {
    ....

    classpath "org.jetbrains.kotlin:kotlin-noarg:1.4.10"

    ....
    }

then configure your annotation to generate the no-arg constructor

apply plugin: "kotlin-noarg"

noArg {
      annotation("your.path.to.annotaion.NoArg")
      invokeInitializers = true
}

then define your annotation file NoArg.kt

 @Target(AnnotationTarget.CLASS)
 @Retention(AnnotationRetention.SOURCE)
 annotation class NoArg

finally in any data class you can simply use your own annotation

@NoArg
data class SomeClass( val datafield:Type , ...   )

I used to create my own no-arg constructor as the accepted answer , which i got by search but then this plugin released or something and I found it way cleaner .

Add property to an array of objects

With ES6 you can simply do:

 for(const element of Results) {
      element.Active = "false";
 }

How to add a new line in textarea element?

My .replace()function using the patterns described on the other answers did not work. The pattern that worked for my case was:

var str = "Test\n\n\Test\n\Test";
str.replace(/\r\n|\r|\n/g,'&#13;&#10;');

// str: "Test&#13;&#10;&#13;&#10;Test&#13;&#10;Test"

MySQL: Can't create/write to file '/tmp/#sql_3c6_0.MYI' (Errcode: 2) - What does it even mean?

Its due to access control security policies specifically when SELinux is enabled it won't allow external executables to create temporary files in the system locations.

Disable SELinux by issuing below command:

echo 0 >/selinux/enforce

You can now start mysql it wont give any permission related errror while reading/writing to /tmp or system directories.

In case you wish to enable the SELinux security back change 0 to 1 in above command.

How do I tell if an object is a Promise?

const isPromise = (value) => {
  return !!(
    value &&
    value.then &&
    typeof value.then === 'function' &&
    value?.constructor?.name === 'Promise'
  )
}

As for me - this check is better, try it out

How do I import material design library to Android Studio?

If u are using Android X: https://material.io/develop/android/docs/getting-started/ follow the instruction here

when the latest library is

implementation 'com.google.android.material:material:1.2.1'

Update : Get latest material design library from here https://maven.google.com/web/index.html?q=com.google.android.material#com.google.android.material:material

For older SDK

Add the design support library version as same as of your appcompat-v7 library

You can get the latest library from android developer documentation https://developer.android.com/topic/libraries/support-library/packages#design

implementation 'com.android.support:design:28.0.0'

Can a table row expand and close?

Well, I'd say use the DIV instead of table as it would be much easier (but there's nothing wrong with using tables).

My approach would be to use jQuery.ajax and request more data from server and that way, the selected DIV (or TD if you use table) will automatically expand based on requested content.

That way, it saves bandwidth and makes it go faster as you don't load all content at once. It loads only when it's selected.

Run a task every x-minutes with Windows Task Scheduler

You can also create a batch file like the following if you need finer granularity between calls:

:loop
CallYour.Exe
timeout /t timeToWaitBetweenCallsInSeconds /nobreak
goto :loop

Referencing system.management.automation.dll in Visual Studio

A copy of System.Management.Automation.dll is installed when you install the windows SDK (a suitable, recent version of it, anyway). It should be in C:\Program Files\Reference Assemblies\Microsoft\WindowsPowerShell\v1.0\

Why is __init__() always called after __new__()?

__new__ is static class method, while __init__ is instance method. __new__ has to create the instance first, so __init__ can initialize it. Note that __init__ takes self as parameter. Until you create instance there is no self.

Now, I gather, that you're trying to implement singleton pattern in Python. There are a few ways to do that.

Also, as of Python 2.6, you can use class decorators.

def singleton(cls):
    instances = {}
    def getinstance():
        if cls not in instances:
            instances[cls] = cls()
        return instances[cls]
    return getinstance

@singleton
class MyClass:
  ...

How do I compile a .c file on my Mac?

You will need to install the Apple Developer Tools. Once you have done that, the easiest thing is to either use the Xcode IDE or use gcc, or nowadays better cc (the clang LLVM compiler), from the command line.

According to Apple's site, the latest version of Xcode (3.2.1) only runs on Snow Leopard (10.6) so if you have an earlier version of OS X you will need to use an older version of Xcode. Your Mac should have come with a Developer Tools DVD which will contain a version that should run on your system. Also, the Apple Developer Tools site still has older versions available for download. Xcode 3.1.4 should run on Leopard (10.5).

How to execute a .sql script from bash

If you want to run a script to a database:

mysql -u user -p data_base_name_here < db.sql

Best way to incorporate Volley (or other library) into Android Studio project

As pointed out by others as well, Volley is officially available on Github:

Add this line to your gradle dependencies for volley:

compile 'com.android.volley:volley:1.0.0'


To install volley from source read below:

I like to keep the official volley repository in my app. That way I get it from the official source and can get updates without depending on anyone else and mitigating concerns expressed by other people.

Added volley as a submodule alongside app.

git submodule add -b master https://github.com/google/volley.git volley

In my settings.gradle, added the following line to add volley as a module.

include ':volley'

In my app/build.gradle, I added a compile dependency for the volley project

compile project(':volley')

That's all! Volley can now be used in my project.

Everytime I want to sync the volley module with Google's repo, i run this.

git submodule foreach git pull

The origin server did not find a current representation for the target resource or is not willing to disclose that one exists

I was running the project through Intellij and this got this error after I stopped the running server and restarted it. Killing all the java processes and restarting the app helped.

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

There is nothing to fix. You simply have made 3 commits and haven't moved them to the remote branch yet. There are several options, depending on what you want to do:

  • git push: move your changes to the remote (this might get rejected if there are already other changes on the remote)
  • do nothing and keep coding, sync another day
  • git pull: get the changes (if any) from the remote and merge them into your changes
  • git pull --rebase: as above, but try to redo your commits on top of the remote changes

You are in a classical situation (although usually you wouldn't commit a lot on master in most workflows). Here is what I would normally do: Review my changes. Maybe do a git rebase --interactive to do some cosmetics on them, drop the ones that suck, reorder them to make them more logical. Now move them to the remote with git push. If this gets rejected because my local branch is not up to date: git pull --rebase to redo my work on top of the most recent changes and git push again.

Find (and kill) process locking port 3000 on Mac

To kill multi ports.

$ npx kill-port 3000 8080 8081

Process on port 3000 killed
Process on port 8080 killed
Process on port 8081 killed

Hope this help!

How to add a constant column in a Spark DataFrame?

Spark 2.2+

Spark 2.2 introduces typedLit to support Seq, Map, and Tuples (SPARK-19254) and following calls should be supported (Scala):

import org.apache.spark.sql.functions.typedLit

df.withColumn("some_array", typedLit(Seq(1, 2, 3)))
df.withColumn("some_struct", typedLit(("foo", 1, 0.3)))
df.withColumn("some_map", typedLit(Map("key1" -> 1, "key2" -> 2)))

Spark 1.3+ (lit), 1.4+ (array, struct), 2.0+ (map):

The second argument for DataFrame.withColumn should be a Column so you have to use a literal:

from pyspark.sql.functions import lit

df.withColumn('new_column', lit(10))

If you need complex columns you can build these using blocks like array:

from pyspark.sql.functions import array, create_map, struct

df.withColumn("some_array", array(lit(1), lit(2), lit(3)))
df.withColumn("some_struct", struct(lit("foo"), lit(1), lit(.3)))
df.withColumn("some_map", create_map(lit("key1"), lit(1), lit("key2"), lit(2)))

Exactly the same methods can be used in Scala.

import org.apache.spark.sql.functions.{array, lit, map, struct}

df.withColumn("new_column", lit(10))
df.withColumn("map", map(lit("key1"), lit(1), lit("key2"), lit(2)))

To provide names for structs use either alias on each field:

df.withColumn(
    "some_struct",
    struct(lit("foo").alias("x"), lit(1).alias("y"), lit(0.3).alias("z"))
 )

or cast on the whole object

df.withColumn(
    "some_struct", 
    struct(lit("foo"), lit(1), lit(0.3)).cast("struct<x: string, y: integer, z: double>")
 )

It is also possible, although slower, to use an UDF.

Note:

The same constructs can be used to pass constant arguments to UDFs or SQL functions.

HTML input fields does not get focus when clicked

When you say

and nope, they don't have attributes: disabled="disabled" or readonly ;-)

Is this through viewing your html, the source code of the page, or the DOM?

If you inspect the DOM with Chrome or Firefox, then you will be able to see any attributes added to the input fields through javasript, or even an overlaying div

How to create a hex dump of file containing only the hex characters without spaces in bash?

Format strings can make hexdump behave exactly as you want it to (no whitespace at all, byte by byte):

hexdump -ve '1/1 "%.2x"'

1/1 means "each format is applied once and takes one byte", and "%.2x" is the actual format string, like in printf. In this case: 2-character hexadecimal number, leading zeros if shorter.

How to escape indicator characters (i.e. : or - ) in YAML

What also works and is even nicer for long, multiline texts, is putting your text indented on the next line, after a pipe or greater-than sign:

text: >
    Op dit plein stond het hoofdkantoor van de NIROM: Nederlands Indische 
    Radio Omroep

A pipe preserves newlines, a gt-sign turns all the following lines into one long string.

How to do 3 table JOIN in UPDATE query?

An alternative General Plan, which I'm only adding as an independent Answer because the blasted "comment on an answer" won't take newlines without posting the entire edit, even though it isn't finished yet.

UPDATE table A
JOIN table B ON {join fields}
JOIN table C ON {join fields}
JOIN {as many tables as you need}
SET A.column = {expression}

Example:

UPDATE person P
JOIN address A ON P.home_address_id = A.id
JOIN city C ON A.city_id = C.id
SET P.home_zip = C.zipcode;

Handle file download from ajax post

Below is my solution for downloading multiple files depending on some list which consists of some ids and looking up in database, files will be determined and ready for download - if those exist. I am calling C# MVC action for each file using Ajax.

And Yes, like others said, it is possible to do it in jQuery Ajax. I did it with Ajax success and I am always sending response 200.

So, this is the key:

  success: function (data, textStatus, xhr) {

And this is my code:

var i = 0;
var max = 0;
function DownloadMultipleFiles() {
            if ($(".dataTables_scrollBody>tr.selected").length > 0) {
                var list = [];
                showPreloader();
                $(".dataTables_scrollBody>tr.selected").each(function (e) {
                    var element = $(this);
                    var orderid = element.data("orderid");
                    var iscustom = element.data("iscustom");
                    var orderlineid = element.data("orderlineid");
                    var folderPath = "";
                    var fileName = "";

                    list.push({ orderId: orderid, isCustomOrderLine: iscustom, orderLineId: orderlineid, folderPath: folderPath, fileName: fileName });
                });
                i = 0;
                max = list.length;
                DownloadFile(list);
            }
        }

Then calling:

function DownloadFile(list) {
        $.ajax({
            url: '@Url.Action("OpenFile","OrderLines")',
            type: "post",
            data: list[i],
            xhrFields: {
                responseType: 'blob'
            },
            beforeSend: function (xhr) {
                xhr.setRequestHeader("RequestVerificationToken",
                    $('input:hidden[name="__RequestVerificationToken"]').val());

            },
            success: function (data, textStatus, xhr) {
                // check for a filename
                var filename = "";
                var disposition = xhr.getResponseHeader('Content-Disposition');
                if (disposition && disposition.indexOf('attachment') !== -1) {
                    var filenameRegex = /filename[^;=\n]*=((['"]).*?\2|[^;\n]*)/;
                    var matches = filenameRegex.exec(disposition);
                    if (matches != null && matches[1]) filename = matches[1].replace(/['"]/g, '');
                    var a = document.createElement('a');
                    var url = window.URL.createObjectURL(data);
                    a.href = url;
                    a.download = filename;
                    document.body.append(a);
                    a.click();
                    a.remove();
                    window.URL.revokeObjectURL(url);
                }
                else {
                    getErrorToastMessage("Production file for order line " + list[i].orderLineId + " does not exist");
                }
                i = i + 1;
                if (i < max) {
                    DownloadFile(list);
                }
            },
            error: function (XMLHttpRequest, textStatus, errorThrown) {

            },
            complete: function () {
                if(i===max)
                hidePreloader();
            }
        });
    }

C# MVC:

 [HttpPost]
 [ValidateAntiForgeryToken]
public IActionResult OpenFile(OrderLineSimpleModel model)
        {
            byte[] file = null;

            try
            {
                if (model != null)
                {
                    //code for getting file from api - part is missing here as not important for this example
                    file = apiHandler.Get<byte[]>(downloadApiUrl, token);

                    var contentDispositionHeader = new System.Net.Mime.ContentDisposition
                    {
                        Inline = true,
                        FileName = fileName
                    };
                    //    Response.Headers.Add("Content-Disposition", contentDispositionHeader.ToString() + "; attachment");
                    Response.Headers.Add("Content-Type", "application/pdf");
                    Response.Headers.Add("Content-Disposition", "attachment; filename=" + fileName);
                    Response.Headers.Add("Content-Transfer-Encoding", "binary");
                    Response.Headers.Add("Content-Length", file.Length.ToString());

                }
            }
            catch (Exception ex)
            {
                this.logger.LogError(ex, "Error getting pdf", null);
                return Ok();
            }

            return File(file, System.Net.Mime.MediaTypeNames.Application.Pdf);
        }

As long as you return response 200, success in Ajax can work with it, you can check if file actually exist or not as the line below in this case would be false and you can inform user about that:

 if (disposition && disposition.indexOf('attachment') !== -1) {

Firing events on CSS class changes in jQuery

I would suggest you override the addClass function. You can do it this way:

// Create a closure
(function(){
    // Your base, I'm in it!
    var originalAddClassMethod = jQuery.fn.addClass;

    jQuery.fn.addClass = function(){
        // Execute the original method.
        var result = originalAddClassMethod.apply( this, arguments );

        // call your function
        // this gets called everytime you use the addClass method
        myfunction();

        // return the original result
        return result;
    }
})();

// document ready function
$(function(){
    // do stuff
});

What are some uses of template template parameters?

Say you're using CRTP to provide an "interface" for a set of child templates; and both the parent and the child are parametric in other template argument(s):

template <typename DERIVED, typename VALUE> class interface {
    void do_something(VALUE v) {
        static_cast<DERIVED*>(this)->do_something(v);
    }
};

template <typename VALUE> class derived : public interface<derived, VALUE> {
    void do_something(VALUE v) { ... }
};

typedef interface<derived<int>, int> derived_t;

Note the duplication of 'int', which is actually the same type parameter specified to both templates. You can use a template template for DERIVED to avoid this duplication:

template <template <typename> class DERIVED, typename VALUE> class interface {
    void do_something(VALUE v) {
        static_cast<DERIVED<VALUE>*>(this)->do_something(v);
    }
};

template <typename VALUE> class derived : public interface<derived, VALUE> {
    void do_something(VALUE v) { ... }
};

typedef interface<derived, int> derived_t;

Note that you are eliminating directly providing the other template parameter(s) to the derived template; the "interface" still receives them.

This also lets you build up typedefs in the "interface" that depend on the type parameters, which will be accessible from the derived template.

The above typedef doesn't work because you can't typedef to an unspecified template. This works, however (and C++11 has native support for template typedefs):

template <typename VALUE>
struct derived_interface_type {
    typedef typename interface<derived, VALUE> type;
};

typedef typename derived_interface_type<int>::type derived_t;

You need one derived_interface_type for each instantiation of the derived template unfortunately, unless there's another trick I haven't learned yet.