Programs & Examples On #Geshi

Geshi is a free software library that allows syntax highlighting of source code for several markup and programming languages.

lexers vs parsers

Yes, they are very different in theory, and in implementation.

Lexers are used to recognize "words" that make up language elements, because the structure of such words is generally simple. Regular expressions are extremely good at handling this simpler structure, and there are very high-performance regular-expression matching engines used to implement lexers.

Parsers are used to recognize "structure" of a language phrases. Such structure is generally far beyond what "regular expressions" can recognize, so one needs "context sensitive" parsers to extract such structure. Context-sensitive parsers are hard to build, so the engineering compromise is to use "context-free" grammars and add hacks to the parsers ("symbol tables", etc.) to handle the context-sensitive part.

Neither lexing nor parsing technology is likely to go away soon.

They may be unified by deciding to use "parsing" technology to recognize "words", as is currently explored by so-called scannerless GLR parsers. That has a runtime cost, as you are applying more general machinery to what is often a problem that doesn't need it, and usually you pay for that in overhead. Where you have lots of free cycles, that overhead may not matter. If you process a lot of text, then the overhead does matter and classical regular expression parsers will continue to be used.

jQuery AJAX file upload PHP

and this is the php file to receive the uplaoded files

<?
$data = array();
    //check with your logic
    if (isset($_FILES)) {
        $error = false;
        $files = array();

        $uploaddir = $target_dir;
        foreach ($_FILES as $file) {
            if (move_uploaded_file($file['tmp_name'], $uploaddir . basename( $file['name']))) {
                $files[] = $uploaddir . $file['name'];
            } else {
                $error = true;
            }
        }
        $data = ($error) ? array('error' => 'There was an error uploading your files') : array('files' => $files);
    } else {
        $data = array('success' => 'NO FILES ARE SENT','formData' => $_REQUEST);
    }

    echo json_encode($data);
?>

PHP: how can I get file creation date?

Use filectime. For Windows it will return the creation time, and for Unix the change time which is the best you can get because on Unix there is no creation time (in most filesystems).

Note also that in some Unix texts the ctime of a file is referred to as being the creation time of the file. This is wrong. There is no creation time for Unix files in most Unix filesystems.

Refreshing page on click of a button

There are several ways to reload the current page using a button or other trigger. The examples below use a button click to reload the page but you can use a text hyperlink or any trigger you like.

<input type="button" value="Reload Page" onClick="window.location.reload()">

<input type="button" value="Reload Page" onClick="history.go(0)">

<input type="button" value="Reload Page" onClick="window.location.href=window.location.href">

How do I build JSON dynamically in javascript?

First, I think you're calling it the wrong thing. "JSON" stands for "JavaScript Object Notation" - it's just a specification for representing some data in a string that explicitly mimics JavaScript object (and array, string, number and boolean) literals. You're trying to build up a JavaScript object dynamically - so the word you're looking for is "object".

With that pedantry out of the way, I think that you're asking how to set object and array properties.

// make an empty object
var myObject = {};

// set the "list1" property to an array of strings
myObject.list1 = ['1', '2'];

// you can also access properties by string
myObject['list2'] = [];
// accessing arrays is the same, but the keys are numbers
myObject.list2[0] = 'a';
myObject['list2'][1] = 'b';

myObject.list3 = [];
// instead of placing properties at specific indices, you
// can push them on to the end
myObject.list3.push({});
// or unshift them on to the beginning
myObject.list3.unshift({});
myObject.list3[0]['key1'] = 'value1';
myObject.list3[1]['key2'] = 'value2';

myObject.not_a_list = '11';

That code will build up the object that you specified in your question (except that I call it myObject instead of myJSON). For more information on accessing properties, I recommend the Mozilla JavaScript Guide and the book JavaScript: The Good Parts.

How to place and center text in an SVG rectangle

An easy solution to center text horizontally and vertically in SVG:

  1. Set the position of the text to the absolute center of the element in which you want to center it:

    • If it's the parent, you could just do x="50%" y ="50%".
    • If it's another element, x would be the x of that element + half its width (and similar for y but with the height).
  2. Use the text-anchor property to center the text horizontally with the value middle:

    middle

    The rendered characters are aligned such that the geometric middle of the resulting rendered text is at the initial current text position.

  3. Use the dominant-baseline property to center the text vertically with the value middle (or depending on how you want it to look like, you may want to do central)

Here is a simple demo:

_x000D_
_x000D_
<svg width="200" height="100">_x000D_
  <rect x="0" y="0" width="200" height="100" stroke="red" stroke-width="3px" fill="white"/>_x000D_
  <text x="50%" y="50%" dominant-baseline="middle" text-anchor="middle">TEXT</text>    _x000D_
</svg>
_x000D_
_x000D_
_x000D_

How to launch jQuery Fancybox on page load?

The best way I've found is:

<script type="text/javascript">
    $(document).ready(function() {
        $.fancybox(
             $("#WRAPPER_FOR_hidden_div_with_content_to_show").html(), //fancybox works perfect with hidden divs
             {
                  //fancybox options
             }
        );
    });
</script>

How to escape % in String.Format?

To complement the previous stated solution, use:

str = str.replace("%", "%%");

How can I access localhost from another computer in the same network?

You need to find what your local network's IP of that computer is. Then other people can access to your site by that IP.

You can find your local network's IP by go to Command Prompt or press Windows + R then type in ipconfig. It will give out some information and your local IP should look like 192.168.1.x.

Xcode 12, building for iOS Simulator, but linking in object file built for iOS, for architecture arm64

On Build Settings search VALID_ARCH then press delete. This should work for me with Xcode 12.0.1

VALID_ARCH on build settings

How to find the location of the Scheduled Tasks folder

On newer versions of Windows (Windows 10 and Windows Server 2016) the tasks you create are located in C:\Windows\Tasks. They will have the extension .job

For example if you create the task "DoWork" it will create the task in

C:\Windows\Tasks\DoWork.job

What is a practical use for a closure in JavaScript?

Much of the code we write in front-end JavaScript is event-based — we define some behavior, then attach it to an event that is triggered by the user (such as a click or a keypress). Our code is generally attached as a callback: a single function which is executed in response to the event. size12, size14, and size16 are now functions which will resize the body text to 12, 14, and 16 pixels, respectively. We can attach them to buttons (in this case links) as follows:

function makeSizer(size) {
    return function() {
    document.body.style.fontSize = size + 'px';
    };
}

var size12 = makeSizer(12);
var size14 = makeSizer(14);
var size16 = makeSizer(16);

document.getElementById('size-12').onclick = size12;
document.getElementById('size-14').onclick = size14;
document.getElementById('size-16').onclick = size16;

Fiddle

What Content-Type value should I send for my XML sitemap?

As a rule of thumb, the safest bet towards making your document be treated properly by all web servers, proxies, and client browsers, is probably the following:

  1. Use the application/xml content type
  2. Include a character encoding in the content type, probably UTF-8
  3. Include a matching character encoding in the encoding attribute of the XML document itself.

In terms of the RFC 3023 spec, which some browsers fail to implement properly, the major difference in the content types is in how clients are supposed to treat the character encoding, as follows:

For application/xml, application/xml-dtd, application/xml-external-parsed-entity, or any one of the subtypes of application/xml such as application/atom+xml, application/rss+xml or application/rdf+xml, the character encoding is determined in this order:

  1. the encoding given in the charset parameter of the Content-Type HTTP header
  2. the encoding given in the encoding attribute of the XML declaration within the document,
  3. utf-8.

For text/xml, text/xml-external-parsed-entity, or a subtype like text/foo+xml, the encoding attribute of the XML declaration within the document is ignored, and the character encoding is:

  1. the encoding given in the charset parameter of the Content-Type HTTP header, or
  2. us-ascii.

Most parsers don't implement the spec; they ignore the HTTP Context-Type and just use the encoding in the document. With so many ill-formed documents out there, that's unlikely to change any time soon.

Android Studio: Drawable Folder: How to put Images for Multiple dpi?

You don't create subfolders of the drawable folder but rather 'sibling' folders next to it under the /res folder for the different screen densities or screen sizes. The /drawable folder (without any dimension) is mostly used for drawables that don't relate to any screen sizes like selectors.

See this screenshot (use the name drawable-hdpi instead of mipmap-hdpi):

enter image description here

Adding 'serial' to existing column in Postgres

Look at the following commands (especially the commented block).

DROP TABLE foo;
DROP TABLE bar;

CREATE TABLE foo (a int, b text);
CREATE TABLE bar (a serial, b text);

INSERT INTO foo (a, b) SELECT i, 'foo ' || i::text FROM generate_series(1, 5) i;
INSERT INTO bar (b) SELECT 'bar ' || i::text FROM generate_series(1, 5) i;

-- blocks of commands to turn foo into bar
CREATE SEQUENCE foo_a_seq;
ALTER TABLE foo ALTER COLUMN a SET DEFAULT nextval('foo_a_seq');
ALTER TABLE foo ALTER COLUMN a SET NOT NULL;
ALTER SEQUENCE foo_a_seq OWNED BY foo.a;    -- 8.2 or later

SELECT MAX(a) FROM foo;
SELECT setval('foo_a_seq', 5);  -- replace 5 by SELECT MAX result

INSERT INTO foo (b) VALUES('teste');
INSERT INTO bar (b) VALUES('teste');

SELECT * FROM foo;
SELECT * FROM bar;

Typescript: Type X is missing the following properties from type Y length, pop, push, concat, and 26 more. [2740]

This error could also be because you are not subscribing to the Observable.

Example, instead of:

this.products = this.productService.getProducts();

do this:

   this.productService.getProducts().subscribe({
    next: products=>this.products = products,
    error: err=>this.errorMessage = err
   });

Use of exit() function

In addition to return an exit code to parent process -

In UNIX, an important aspect that I think has been left out is, that exit() at first calls (in reverse order) all those functions, which were registered by atexit() call.

Please refer to SUSv4 for details.

What is the difference between an IntentService and a Service?

In short, a Service is a broader implementation for the developer to set up background operations, while an IntentService is useful for "fire and forget" operations, taking care of background Thread creation and cleanup.

From the docs:

Service A Service is an application component representing either an application's desire to perform a longer-running operation while not interacting with the user or to supply functionality for other applications to use.

IntentService Service is a base class for IntentService Services that handle asynchronous requests (expressed as Intents) on demand. Clients send requests through startService(Intent) calls; the service is started as needed, handles each Intent in turn using a worker thread, and stops itself when it runs out of work.

Refer this doc - http://developer.android.com/reference/android/app/IntentService.html

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

The key is to encapsulate the expression in parentheses after the @ delimiter. You can make any compound expression work this way.

How do you use MySQL's source command to import large files in windows

C:\xampp\mysql\bin\mysql -u root -p testdatabase < C:\Users\Juan\Desktop\databasebackup.sql

That worked for me to import 400MB file into my database.

phpmysql error - #1273 - #1273 - Unknown collation: 'utf8mb4_general_ci'

You can fix this issue by deleting browser cookie from the begining of time. I have tried this and it is working fine for me.

To delete only cookies:

  1. hold down ctrl+shift+delete
  2. remove all check boxes except for cookies of course
  3. use the drop down on top to select "from the beginning of time
  4. click clear browsing data

jQuery AJAX single file upload

After hours of searching and looking for answer, finally I made it!!!!! Code is below :))))

HTML:

<form id="fileinfo" enctype="multipart/form-data" method="post" name="fileinfo">
    <label>File to stash:</label>
    <input type="file" name="file" required />
</form>
<input type="button" value="Stash the file!"></input>
<div id="output"></div>

jQuery:

$(function(){
    $('#uploadBTN').on('click', function(){ 
        var fd = new FormData($("#fileinfo"));
        //fd.append("CustomField", "This is some extra data");
        $.ajax({
            url: 'upload.php',  
            type: 'POST',
            data: fd,
            success:function(data){
                $('#output').html(data);
            },
            cache: false,
            contentType: false,
            processData: false
        });
    });
});

In the upload.php file you can access the data passed with $_FILES['file'].

Thanks everyone for trying to help:)

I took the answer from here (with some changes) MDN

How can I read numeric strings in Excel cells as string (not numbers)?

Try:

new java.text.DecimalFormat("0").format( cell.getNumericCellValue() )

Should format the number correctly.

How to convert WebResponse.GetResponseStream return into a string?

You can create a StreamReader around the stream, then call StreamReader.ReadToEnd().

StreamReader responseReader = new StreamReader(request.GetResponse().GetResponseStream());
var responseData = responseReader.ReadToEnd();

android View not attached to window manager

My problem was solved by uhlocking the screen rotation on my android the app which was causing me a problem now works perfectly

How to extract table as text from the PDF using Python?

If your pdf is text-based and not a scanned document (i.e. if you can click and drag to select text in your table in a PDF viewer), then you can use the module camelot-py with

import camelot
tables = camelot.read_pdf('foo.pdf')

You then can choose how you want to save the tables (as csv, json, excel, html, sqlite), and whether the output should be compressed in a ZIP archive.

tables.export('foo.csv', f='csv', compress=False)

Edit: tabula-py appears roughly 6 times faster than camelot-py so that should be used instead.

import camelot
import cProfile
import pstats
import tabula

cmd_tabula = "tabula.read_pdf('table.pdf', pages='1', lattice=True)"
prof_tabula = cProfile.Profile().run(cmd_tabula)
time_tabula = pstats.Stats(prof_tabula).total_tt

cmd_camelot = "camelot.read_pdf('table.pdf', pages='1', flavor='lattice')"
prof_camelot = cProfile.Profile().run(cmd_camelot)
time_camelot = pstats.Stats(prof_camelot).total_tt

print(time_tabula, time_camelot, time_camelot/time_tabula)

gave

1.8495559890000015 11.057014036000016 5.978199147125147

How to push both key and value into an Array in Jquery

This code

var title = news.title;
var link = news.link;
arr.push({title : link});

is not doing what you think it does. What gets pushed is a new object with a single member named "title" and with link as the value ... the actual title value is not used. To save an object with two fields you have to do something like

arr.push({title:title, link:link});

or with recent Javascript advances you can use the shortcut

arr.push({title, link}); // Note: comma "," and not colon ":"

If instead you want the key of the object to be the content of the variable title you can use

arr.push({[title]: link}); // Note that title has been wrapped in brackets

What is the facade design pattern?

Wikipedia has a great example of Facade pattern.

/* Complex parts */

class CPU {
    public void freeze() { ... }
    public void jump(long position) { ... }
    public void execute() { ... }
}

class Memory {
    public void load(long position, byte[] data) { ... }
}

class HardDrive {
    public byte[] read(long lba, int size) { ... }
}

/* Facade */

class ComputerFacade {
    private CPU processor;
    private Memory ram;
    private HardDrive hd;

    public ComputerFacade() {
        this.processor = new CPU();
        this.ram = new Memory();
        this.hd = new HardDrive();
    }

    public void start() {
        processor.freeze();
        ram.load(BOOT_ADDRESS, hd.read(BOOT_SECTOR, SECTOR_SIZE));
        processor.jump(BOOT_ADDRESS);
        processor.execute();
    }
}

/* Client */

class You {
    public static void main(String[] args) {
        ComputerFacade computer = new ComputerFacade();
        computer.start();
    }
}

PHP - iterate on string characters

Iterate string:

for ($i = 0; $i < strlen($str); $i++){
    echo $str[$i];
}

Copying a HashMap in Java

If we want to copy an object in Java, there are two possibilities that we need to consider: a shallow copy and a deep copy.

The shallow copy is the approach when we only copy field values. Therefore, the copy might be dependent on the original object. In the deep copy approach, we make sure that all the objects in the tree are deeply copied, so the copy is not dependent on any earlier existing object that might ever change.

This question is the perfect definition for the application of the deep copy approach.

First, if you have a simple HashMap<Integer, List<T>> map then we just create a workaround like this. Creating a new instance of the List<T>.

public static <T> HashMap<Integer, List<T>> deepCopyWorkAround(HashMap<Integer, List<T>> original)
{
    HashMap<Integer, List<T>> copy = new HashMap<>();
    for (Map.Entry<Integer, List<T>> entry : original.entrySet()) {
        copy.put(entry.getKey(), new ArrayList<>(entry.getValue()));
    }
    return copy;
}

This one uses Stream.collect() method to create the clone map, but uses the same idea as the previous method.

public static <T> Map<Integer, List<T>> deepCopyStreamWorkAround(Map<Integer, List<T>> original)
{
    return original
            .entrySet()
            .stream()
            .collect(Collectors.toMap(Map.Entry::getKey, valueMapper -> new ArrayList<>(valueMapper.getValue())));
}   

But, if the instances inside T are also mutable objects we have a big problem. In this case a real deep copy is an alternative that solves this problem. Its advantage is that at least each mutable object in the object graph is recursively copied. Since the copy is not dependent on any mutable object that was created earlier, it won’t get modified by accident like we saw with the shallow copy.

To solve that this deep copy implementations will do the work.

public class DeepClone
{
    public static void main(String[] args)
    {
        Map<Long, Item> itemMap = Stream.of(
                entry(0L, new Item(2558584)),
                entry(1L, new Item(254243232)),
                entry(2L, new Item(986786)),
                entry(3L, new Item(672542)),
                entry(4L, new Item(4846)),
                entry(5L, new Item(76867467)),
                entry(6L, new Item(986786)),
                entry(7L, new Item(7969768)),
                entry(8L, new Item(68868486)),
                entry(9L, new Item(923)),
                entry(10L, new Item(986786)),
                entry(11L, new Item(549768)),
                entry(12L, new Item(796168)),
                entry(13L, new Item(868421)),
                entry(14L, new Item(923)),
                entry(15L, new Item(986786)),
                entry(16L, new Item(549768)),
                entry(17L, new Item(4846)),
                entry(18L, new Item(4846)),
                entry(19L, new Item(76867467)),
                entry(20L, new Item(986786)),
                entry(21L, new Item(7969768)),
                entry(22L, new Item(923)),
                entry(23L, new Item(4846)),
                entry(24L, new Item(986786)),
                entry(25L, new Item(549768))
        ).collect(entriesToMap());


        Map<Long, Item> clone = DeepClone.deepClone(itemMap);
        clone.remove(1L);
        clone.remove(2L);

        System.out.println(itemMap);
        System.out.println(clone);
    }

    private DeepClone() {}

    public static <T> T deepClone(final T input)
    {
        if (input == null) return null;

        if (input instanceof Map<?, ?>) {
            return (T) deepCloneMap((Map<?, ?>) input);
        } else if (input instanceof Collection<?>) {
            return (T) deepCloneCollection((Collection<?>) input);
        } else if (input instanceof Object[]) {
            return (T) deepCloneObjectArray((Object[]) input);
        } else if (input.getClass().isArray()) {
            return (T) clonePrimitiveArray((Object) input);
        }

        return input;
    }

    private static Object clonePrimitiveArray(final Object input)
    {
        final int length = Array.getLength(input);
        final Object output = Array.newInstance(input.getClass().getComponentType(), length);
        System.arraycopy(input, 0, output, 0, length);
        return output;
    }

    private static <E> E[] deepCloneObjectArray(final E[] input)
    {
        final E[] clone = (E[]) Array.newInstance(input.getClass().getComponentType(), input.length);
        for (int i = 0; i < input.length; i++) {
            clone[i] = deepClone(input[i]);
        }

        return clone;
    }

    private static <E> Collection<E> deepCloneCollection(final Collection<E> input)
    {
        Collection<E> clone;
        if (input instanceof LinkedList<?>) {
            clone = new LinkedList<>();
        } else if (input instanceof SortedSet<?>) {
            clone = new TreeSet<>();
        } else if (input instanceof Set) {
            clone = new HashSet<>();
        } else {
            clone = new ArrayList<>();
        }

        for (E item : input) {
            clone.add(deepClone(item));
        }

        return clone;
    }

    private static <K, V> Map<K, V> deepCloneMap(final Map<K, V> map)
    {
        Map<K, V> clone;
        if (map instanceof LinkedHashMap<?, ?>) {
            clone = new LinkedHashMap<>();
        } else if (map instanceof TreeMap<?, ?>) {
            clone = new TreeMap<>();
        } else {
            clone = new HashMap<>();
        }

        for (Map.Entry<K, V> entry : map.entrySet()) {
            clone.put(deepClone(entry.getKey()), deepClone(entry.getValue()));
        }

        return clone;
    }
}

How do I find the PublicKeyToken for a particular dll?

Assembly.LoadFile(@"C:\Windows\Microsoft.NET\Framework\v4.0.30319\system.data.dll").FullName

Will result in

System.Data, Version=4.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089

What causes "Unable to access jarfile" error?

I was trying this:

After giving the file read, write, execute priviledges:

chmod 777 java-repl.jar

alias jr="java -jar $HOME/Dev/java-repl/java-repl.jar"

Unable to access bla bla..., this was on Mac OS though

So I tried this:

alias jr="cd $HOME/Dev/java-repl/ && java -jar java-repl.jar"

Signtool error: No certificates were found that met all given criteria with a Windows Store App?

just uncheck the 'Sign the click once manifests' from the signing tab in project properties,it will remove the error and you can create a new one as from there.

how to start stop tomcat server using CMD?

Steps to start Apache Tomcat using cmd:
1. Firstly check that the JRE_HOME or JAVA_HOME is a variable available in environment variables.(If it is not create a new variable JRE_HOME or JAVA_HOME)
2. Goto cmd and change your working directory to bin path where apache is installed (or extracted).
3. Type Command -> catalina.bat start to start the server.
4. Type Command -> catalina.bat stop to stop the server.

What's the difference between deadlock and livelock?

Maybe these two examples illustrate you the difference between a deadlock and a livelock:


Java-Example for a deadlock:

import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class DeadlockSample {

    private static final Lock lock1 = new ReentrantLock(true);
    private static final Lock lock2 = new ReentrantLock(true);

    public static void main(String[] args) {
        Thread threadA = new Thread(DeadlockSample::doA,"Thread A");
        Thread threadB = new Thread(DeadlockSample::doB,"Thread B");
        threadA.start();
        threadB.start();
    }

    public static void doA() {
        System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
        lock1.lock();
        System.out.println(Thread.currentThread().getName() + " : holds lock 1");

        try {
            System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
            lock2.lock();
            System.out.println(Thread.currentThread().getName() + " : holds lock 2");

            try {
                System.out.println(Thread.currentThread().getName() + " : critical section of doA()");
            } finally {
                lock2.unlock();
                System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
            }
        } finally {
            lock1.unlock();
            System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
        }
    }

    public static void doB() {
        System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
        lock2.lock();
        System.out.println(Thread.currentThread().getName() + " : holds lock 2");

        try {
            System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
            lock1.lock();
            System.out.println(Thread.currentThread().getName() + " : holds lock 1");

            try {
                System.out.println(Thread.currentThread().getName() + " : critical section of doB()");
            } finally {
                lock1.unlock();
                System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
            }
        } finally {
            lock2.unlock();
            System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
        }
    }
}

Sample output:

Thread A : waits for lock 1
Thread B : waits for lock 2
Thread A : holds lock 1
Thread B : holds lock 2
Thread B : waits for lock 1
Thread A : waits for lock 2

Java-Example for a livelock:


import java.util.concurrent.locks.Lock;
import java.util.concurrent.locks.ReentrantLock;

public class LivelockSample {

    private static final Lock lock1 = new ReentrantLock(true);
    private static final Lock lock2 = new ReentrantLock(true);

    public static void main(String[] args) {
        Thread threadA = new Thread(LivelockSample::doA, "Thread A");
        Thread threadB = new Thread(LivelockSample::doB, "Thread B");
        threadA.start();
        threadB.start();
    }

    public static void doA() {
        try {
            while (!lock1.tryLock()) {
                System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
                Thread.sleep(100);
            }
            System.out.println(Thread.currentThread().getName() + " : holds lock 1");

            try {
                while (!lock2.tryLock()) {
                    System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
                    Thread.sleep(100);
                }
                System.out.println(Thread.currentThread().getName() + " : holds lock 2");

                try {
                    System.out.println(Thread.currentThread().getName() + " : critical section of doA()");
                } finally {
                    lock2.unlock();
                    System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
                }
            } finally {
                lock1.unlock();
                System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
            }
        } catch (InterruptedException e) {
            // can be ignored here for this sample
        }
    }

    public static void doB() {
        try {
            while (!lock2.tryLock()) {
                System.out.println(Thread.currentThread().getName() + " : waits for lock 2");
                Thread.sleep(100);
            }
            System.out.println(Thread.currentThread().getName() + " : holds lock 2");

            try {
                while (!lock1.tryLock()) {
                    System.out.println(Thread.currentThread().getName() + " : waits for lock 1");
                    Thread.sleep(100);
                }
                System.out.println(Thread.currentThread().getName() + " : holds lock 1");

                try {
                    System.out.println(Thread.currentThread().getName() + " : critical section of doB()");
                } finally {
                    lock1.unlock();
                    System.out.println(Thread.currentThread().getName() + " : does not hold lock 1 any longer");
                }
            } finally {
                lock2.unlock();
                System.out.println(Thread.currentThread().getName() + " : does not hold lock 2 any longer");
            }
        } catch (InterruptedException e) {
            // can be ignored here for this sample
        }
    }
}

Sample output:

Thread B : holds lock 2
Thread A : holds lock 1
Thread A : waits for lock 2
Thread B : waits for lock 1
Thread B : waits for lock 1
Thread A : waits for lock 2
Thread A : waits for lock 2
Thread B : waits for lock 1
Thread B : waits for lock 1
Thread A : waits for lock 2
Thread A : waits for lock 2
Thread B : waits for lock 1
...

Both examples force the threads to aquire the locks in different orders. While the deadlock waits for the other lock, the livelock does not really wait - it desperately tries to acquire the lock without the chance of getting it. Every try consumes CPU cycles.

How does one represent the empty char?

There are two ways to do the same instruction, that is, an empty string. The first way is to allocate an empty string on static memory:

char* my_variable = "";

or, if you want to be explicit:

char my_variable = '\0';

The way posted above is only for a character. And, the second way:

#include <string.h>
char* my_variable = strdup("");

Don't forget to use free() with this one because strdup() use malloc inside.

Fatal error: Call to a member function bind_param() on boolean

Any time you get the...

"Fatal error: Call to a member function bind_param() on boolean"

...it is likely because there is an issue with your query. The prepare() might return FALSE (a Boolean), but this generic failure message doesn't leave you much in the way of clues. How do you find out what is wrong with your query? You ask!

First of all, make sure error reporting is turned on and visible: add these two lines to the top of your file(s) right after your opening <?php tag:

error_reporting(E_ALL);
ini_set('display_errors', 1);

If your error reporting has been set in the php.ini you won't have to worry about this. Just make sure you handle errors gracefully and never reveal the true cause of any issues to your users. Revealing the true cause to the public can be a gold engraved invitation for those wanting to harm your sites and servers. If you do not want to send errors to the browser you can always monitor your web server error logs. Log locations will vary from server to server e.g., on Ubuntu the error log is typically located at /var/log/apache2/error.log. If you're examining error logs in a Linux environment you can use tail -f /path/to/log in a console window to see errors as they occur in real-time....or as you make them.

Once you're squared away on standard error reporting adding error checking on your database connection and queries will give you much more detail about the problems going on. Have a look at this example where the column name is incorrect. First, the code which returns the generic fatal error message:

$sql = "SELECT `foo` FROM `weird_words` WHERE `definition` = ?";
$query = $mysqli->prepare($sql)); // assuming $mysqli is the connection
$query->bind_param('s', $definition);
$query->execute();

The error is generic and not very helpful to you in solving what is going on.

With a couple of more lines of code you can get very detailed information which you can use to solve the issue immediately. Check the prepare() statement for truthiness and if it is good you can proceed on to binding and executing.

$sql = "SELECT `foo` FROM `weird_words` WHERE `definition` = ?";
if($query = $mysqli->prepare($sql)) { // assuming $mysqli is the connection
    $query->bind_param('s', $definition);
    $query->execute();
    // any additional code you need would go here.
} else {
    $error = $mysqli->errno . ' ' . $mysqli->error;
    echo $error; // 1054 Unknown column 'foo' in 'field list'
}

If something is wrong you can spit out an error message which takes you directly to the issue. In this case there is no foo column in the table, solving the problem is trivial.

If you choose, you can include this checking in a function or class and extend it by handling the errors gracefully as mentioned previously.

SQL Server 2005 Setting a variable to the result of a select query

You could use:

declare @foo as nvarchar(25)

select @foo = 'bar'

select @foo

How to add Button over image using CSS?

Adapt this example to your code

HTML

<div class="img-holder">
    <img src="images/img-1.png" alt="image description"/>
    <a class="link" href=""></a>
</div>

CSS

.img-holder {position: relative;}
.img-holder .link {
    position: absolute;
    bottom: 10px; /*your button position*/
    right: 10px; /*your button position*/
}

Why is exception.printStackTrace() considered bad practice?

Printing the exception's stack trace in itself doesn't constitute bad practice, but only printing the stace trace when an exception occurs is probably the issue here -- often times, just printing a stack trace is not enough.

Also, there's a tendency to suspect that proper exception handling is not being performed if all that is being performed in a catch block is a e.printStackTrace. Improper handling could mean at best an problem is being ignored, and at worst a program that continues executing in an undefined or unexpected state.

Example

Let's consider the following example:

try {
  initializeState();

} catch (TheSkyIsFallingEndOfTheWorldException e) {
  e.printStackTrace();
}

continueProcessingAssumingThatTheStateIsCorrect();

Here, we want to do some initialization processing before we continue on to some processing that requires that the initialization had taken place.

In the above code, the exception should have been caught and properly handled to prevent the program from proceeding to the continueProcessingAssumingThatTheStateIsCorrect method which we could assume would cause problems.

In many instances, e.printStackTrace() is an indication that some exception is being swallowed and processing is allowed to proceed as if no problem every occurred.

Why has this become a problem?

Probably one of the biggest reason that poor exception handling has become more prevalent is due to how IDEs such as Eclipse will auto-generate code that will perform a e.printStackTrace for the exception handling:

try {
  Thread.sleep(1000);
} catch (InterruptedException e) {
  // TODO Auto-generated catch block
  e.printStackTrace();
}

(The above is an actual try-catch auto-generated by Eclipse to handle an InterruptedException thrown by Thread.sleep.)

For most applications, just printing the stack trace to standard error is probably not going to be sufficient. Improper exception handling could in many instances lead to an application running in a state that is unexpected and could be leading to unexpected and undefined behavior.

Java equivalent to Explode and Implode(PHP)

if you are talking about in the reference of String Class. so you can use

subString/split

for Explode & use String

concate

for Implode.

Detecting attribute change of value of an attribute I made

There is this extensions that adds an event listener to attribute changes.

Usage:

<script type="text/javascript" src="http://code.jquery.com/jquery.min.js"></script>
<script type="text/javascript"
  src="https://cdn.rawgit.com/meetselva/attrchange/master/js/attrchange.js"></script>

Bind attrchange handler function to selected elements

$(selector).attrchange({
    trackValues: true, /* Default to false, if set to true the event object is 
                updated with old and new value.*/
    callback: function (event) { 
        //event               - event object
        //event.attributeName - Name of the attribute modified
        //event.oldValue      - Previous value of the modified attribute
        //event.newValue      - New value of the modified attribute
        //Triggered when the selected elements attribute is added/updated/removed
    }        
});

How to get datetime in JavaScript?

@Shadow Wizard's code should return 02:45 PM instead of 14:45 PM. So I modified his code a bit:

function getNowDateTimeStr(){
 var now = new Date();
 var hour = now.getHours() - (now.getHours() >= 12 ? 12 : 0);
return [[AddZero(now.getDate()), AddZero(now.getMonth() + 1), now.getFullYear()].join("/"), [AddZero(hour), AddZero(now.getMinutes())].join(":"), now.getHours() >= 12 ? "PM" : "AM"].join(" ");
}

//Pad given value to the left with "0"
function AddZero(num) {
    return (num >= 0 && num < 10) ? "0" + num : num + "";
}

How to do left join in Doctrine?

If you have an association on a property pointing to the user (let's say Credit\Entity\UserCreditHistory#user, picked from your example), then the syntax is quite simple:

public function getHistory($users) {
    $qb = $this->entityManager->createQueryBuilder();
    $qb
        ->select('a', 'u')
        ->from('Credit\Entity\UserCreditHistory', 'a')
        ->leftJoin('a.user', 'u')
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

Since you are applying a condition on the joined result here, using a LEFT JOIN or simply JOIN is the same.

If no association is available, then the query looks like following

public function getHistory($users) {
    $qb = $this->entityManager->createQueryBuilder();
    $qb
        ->select('a', 'u')
        ->from('Credit\Entity\UserCreditHistory', 'a')
        ->leftJoin(
            'User\Entity\User',
            'u',
            \Doctrine\ORM\Query\Expr\Join::WITH,
            'a.user = u.id'
        )
        ->where('u = :user')
        ->setParameter('user', $users)
        ->orderBy('a.created_at', 'DESC');

    return $qb->getQuery()->getResult();
}

This will produce a resultset that looks like following:

array(
    array(
        0 => UserCreditHistory instance,
        1 => Userinstance,
    ),
    array(
        0 => UserCreditHistory instance,
        1 => Userinstance,
    ),
    // ...
)

No Access-Control-Allow-Origin header is present on the requested resource

Solution:
Instead of using setHeader method I have used addHeader.

response.addHeader("Access-Control-Allow-Origin", "*");

* in above line will allow access to all domains, For allowing access to specific domain only:

response.addHeader("Access-Control-Allow-Origin", "http://www.example.com");

For issues related to IE<=9, Please see here.

How to add a button dynamically using jquery

the $("body").append(r) statement should be within the test function, also there was misplaced " in the test method

function test() {
    var r=$('<input/>').attr({
        type: "button",
        id: "field",
        value: 'new'
    });
    $("body").append(r);    
}

Demo: Fiddle

Update
In that case try a more jQuery-ish solution

<!DOCTYPE html>
<html>
    <head>
        <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.2/jquery.min.js"></script>
        <script type="text/javascript">
          jQuery(function($){
              $('#mybutton').one('click', function(){
                  var r=$('<input/>').attr({
                      type: "button",
                      id: "field",
                      value: 'new'
                  });
                  $("body").append(r);   
              })
          })
        </script>
    </head>
    <body>
        <button id="mybutton">Insert after</button> 
    </body>
</html>

Demo: Plunker

What .NET collection provides the fastest search

Have you considered List.BinarySearch(item)?

You said that your large collection is already sorted so this seems like the perfect opportunity? A hash would definitely be the fastest, but this brings about its own problems and requires a lot more overhead for storage.

Angular ForEach in Angular4/Typescript?

In Typescript use the For Each like below.

selectChildren(data, $event) {
let parentChecked = data.checked;
for(var obj in this.hierarchicalData)
    {
        for (var childObj in obj )
        {
            value.checked = parentChecked;
        }
    }
}

What techniques can be used to speed up C++ compilation times?

Use

#pragma once

at the top of header files, so if they're included more than once in a translation unit, the text of the header will only get included and parsed once.

How to get request URI without context path?

If you use request.getPathInfo() inside a Filter, you always seem to get null (at least with jetty).

This terse invalid bug + response alludes to the issue I think:

https://issues.apache.org/bugzilla/show_bug.cgi?id=28323

I suspect it is related to the fact that filters run before the servlet gets the request. It may be a container bug, or expected behaviour that I haven't been able to identify.

The contextPath is available though, so fforws solution works even in filters. I don't like having to do it by hand, but the implementation is broken or

Unzip a file with php

I updated answer of Morteza Ziaeemehr to a cleaner and better code, This will unzip a file provided within form into current directory using DIR.

<!DOCTYPE html>
<html>
<head>
  <meta charset='utf-8' >
  <title>Unzip</title>
  <style>
  body{
    font-family: arial, sans-serif;
    word-wrap: break-word;
  }
  .wrapper{
    padding:20px;
    line-height: 1.5;
    font-size: 1rem;
  }
  span{
    font-family: 'Consolas', 'courier new', monospace;
    background: #eee;
    padding:2px;
  }
  </style>
</head>
<body>
  <div class="wrapper">
    <?php
    if(isset($_GET['page']))
    {
      $type = $_GET['page'];
      global $con;
      switch($type)
        {
            case 'unzip':
            {    
                $zip_filename =$_POST['filename'];
                echo "Unzipping <span>" .__DIR__. "/" .$zip_filename. "</span> to <span>" .__DIR__. "</span><br>";
                echo "current dir: <span>" . __DIR__ . "</span><br>";
                $zip = new ZipArchive;
                $res = $zip->open(__DIR__ . '/' .$zip_filename);
                if ($res === TRUE) 
                {
                    $zip->extractTo(__DIR__);
                    $zip->close();
                    echo '<p style="color:#00C324;">Extract was successful! Enjoy ;)</p><br>';
                } 
                else 
                {
                    echo '<p style="color:red;">Zip file not found!</p><br>';
                }
                break;
            }
        }
    }
?>
End Script.
</div>
    <form name="unzip" id="unzip" role="form">
        <div class="body bg-gray">
            <div class="form-group">
                <input type="text" name="filename" class="form-control" placeholder="File Name (with extension)"/>
            </div>        
        </div>
    </form>

<script type="application/javascript">
$("#unzip").submit(function(event) {
  event.preventDefault();
    var url = "function.php?page=unzip"; // the script where you handle the form input.
    $.ajax({
     type: "POST",
     url: url,
     dataType:"json",
           data: $("#unzip").serialize(), // serializes the form's elements.
           success: function(data)
           {
               alert(data.msg); // show response from the php script.
               document.getElementById("unzip").reset();
             }

           });

    return false; // avoid to execute the actual submit of the form
  });
</script>
</body>
</html> 

"make_sock: could not bind to address [::]:443" when restarting apache (installing trac and mod_wsgi)

I meet the problem in windows7, phpeclipse, when I start the XAMPP. My solution is :

  • 1.Commented out the \xampp\apache\conf\httpd.conf -> line171 -> #LoadModule ssl_module modules/mod_ssl.so

  • 2.line539 -> #Include conf/extra/httpd-ssl.conf

or you can change the 443 port to another one

req.body empty on posts

I was using restify instead of express and ran into the same problem. The solution was to do:

server.use(restify.bodyParser());

How to set delay in android?

Here's an example where I change the background image from one to another with a 2 second alpha fade delay both ways - 2s fadeout of the original image into a 2s fadein into the 2nd image.

    public void fadeImageFunction(View view) {

    backgroundImage = (ImageView) findViewById(R.id.imageViewBackground);
    backgroundImage.animate().alpha(0f).setDuration(2000);

    // A new thread with a 2-second delay before changing the background image
    new Timer().schedule(
            new TimerTask(){
                @Override
                public void run(){
                    // you cannot touch the UI from another thread. This thread now calls a function on the main thread
                    changeBackgroundImage();
                }
            }, 2000);
   }

// this function runs on the main ui thread
private void changeBackgroundImage(){
    runOnUiThread(new Runnable() {
        @Override
        public void run() {
            backgroundImage = (ImageView) findViewById(R.id.imageViewBackground);
            backgroundImage.setImageResource(R.drawable.supes);
            backgroundImage.animate().alpha(1f).setDuration(2000);
        }
    });
}

asterisk : Unable to connect to remote asterisk (does /var/run/asterisk.ctl exist?)

I had a similar issue, which was a result of the hard drive being filled up. Turns out the issue was with the cdr table being corrupted and running repair in mysql remedied the issue.

jquery: $(window).scrollTop() but no $(window).scrollBottom()

This will scroll to the very top:

$(window).animate({scrollTop: 0});

This will scroll to the very bottom:

$(window).animate({scrollTop: $(document).height() + $(window).height()});

.. change window to your desired container id or class if necessary (in quotes).

How to connect from windows command prompt to mysql command line

If you don't want to go to bin folder of MySQL then another option is to put a shortcut of mysql.exe to your default path of command prompt (C:\Users\"your user name">) with the contents of:

mysql -u(username) -p(password)

jQuery validate: How to add a rule for regular expression validation?

You can use the addMethod()

e.g

$.validator.addMethod('postalCode', function (value) { 
    return /^((\d{5}-\d{4})|(\d{5})|([A-Z]\d[A-Z]\s\d[A-Z]\d))$/.test(value); 
}, 'Please enter a valid US or Canadian postal code.');

good article here https://web.archive.org/web/20130609222116/http://www.randallmorey.com/blog/2008/mar/16/extending-jquery-form-validation-plugin/

Toggle visibility property of div

To do it with an effect like with $.fadeIn() and $.fadeOut() you can use transitions

.visible {
  visibility: visible;
  opacity: 1;
  transition: opacity 1s linear;
}
.hidden {
  visibility: hidden;
  opacity: 0;
  transition: visibility 0s 1s, opacity 1s linear;
}

What is the difference between HTML tags <div> and <span>?

As mentioned in other answers, by default div will be rendered as a block element, while span will be rendered inline within its context. But neither has any semantic value; they exist to allow you to apply styling and an identity to any given bit of content. Using styles, you can make a div act like a span and vice-versa.

One of the useful styles for div is inline-block

Examples:

  1. http://dustwell.com/div-span-inline-block.html

  2. CSS display: inline vs inline-block

I have used inline-block to a great success, in game web projects.

How do I copy items from list to list without foreach?

To add the contents of one list to another list which already exists, you can use:

targetList.AddRange(sourceList);

If you're just wanting to create a new copy of the list, see Lasse's answer.

JAVA How to remove trailing zeros from a double

Use DecimalFormat

  double answer = 5.0;
   DecimalFormat df = new DecimalFormat("###.#");
  System.out.println(df.format(answer));

How to record phone calls in android?

The accepted answer is perfect, except it does not record outgoing calls. Note that for outgoing calls it is not possible (as near as I can tell from scouring many posts) to detect when the call is actually answered (if anybody can find a way other than scouring notifications or logs please let me know). The easiest solution is to just start recording straight away when the outgoing call is placed and stop recording when IDLE is detected. Just adding the same class as above with outgoing recording in this manner for completeness:

private void startRecord(String seed) {
        String out = new SimpleDateFormat("dd-MM-yyyy hh-mm-ss").format(new Date());
        File sampleDir = new File(Environment.getExternalStorageDirectory(), "/TestRecordingDasa1");
        if (!sampleDir.exists()) {
            sampleDir.mkdirs();
        }
        String file_name = "Record" + seed;
        try {
            audiofile = File.createTempFile(file_name, ".amr", sampleDir);
        } catch (IOException e) {
            e.printStackTrace();
        }
        String path = Environment.getExternalStorageDirectory().getAbsolutePath();

        recorder = new MediaRecorder();

        recorder.setAudioSource(MediaRecorder.AudioSource.VOICE_COMMUNICATION);
        recorder.setOutputFormat(MediaRecorder.OutputFormat.AMR_NB);
        recorder.setAudioEncoder(MediaRecorder.AudioEncoder.AMR_NB);
        recorder.setOutputFile(audiofile.getAbsolutePath());
        try {
            recorder.prepare();
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        recorder.start();
        recordstarted = true;
    }


    @Override
    public void onReceive(Context context, Intent intent) {
        if (intent.getAction().equals(ACTION_IN)) {
            if ((bundle = intent.getExtras()) != null) {
                state = bundle.getString(TelephonyManager.EXTRA_STATE);
                if (state.equals(TelephonyManager.EXTRA_STATE_RINGING)) {
                    inCall = bundle.getString(TelephonyManager.EXTRA_INCOMING_NUMBER);
                    wasRinging = true;
                    Toast.makeText(context, "IN : " + inCall, Toast.LENGTH_LONG).show();
                } else if (state.equals(TelephonyManager.EXTRA_STATE_OFFHOOK)) {
                    if (wasRinging == true) {

                        Toast.makeText(context, "ANSWERED", Toast.LENGTH_LONG).show();

                        startRecord("incoming");
                    }
                } else if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
                    wasRinging = false;
                    Toast.makeText(context, "REJECT || DISCO", Toast.LENGTH_LONG).show();
                    if (recordstarted) {
                        recorder.stop();
                        recordstarted = false;
                    }
                }
            }
        } else if (intent.getAction().equals(ACTION_OUT)) {
            if ((bundle = intent.getExtras()) != null) {
                outCall = intent.getStringExtra(Intent.EXTRA_PHONE_NUMBER);
                Toast.makeText(context, "OUT : " + outCall, Toast.LENGTH_LONG).show();
                startRecord("outgoing");
                if ((bundle = intent.getExtras()) != null) {
                    state = bundle.getString(TelephonyManager.EXTRA_STATE);
                    if (state != null) {
                        if (state.equals(TelephonyManager.EXTRA_STATE_IDLE)) {
                            wasRinging = false;
                            Toast.makeText(context, "REJECT || DISCO", Toast.LENGTH_LONG).show();
                            if (recordstarted) {
                                recorder.stop();
                                recordstarted = false;
                            }
                        }
                    }


                }
            }
        }
    }

How do I insert datetime value into a SQLite database?

Use CURRENT_TIMESTAMP when you need it, instead OF NOW() (which is MySQL)

Sending email from Command-line via outlook without having to click send

You can use cURL and CRON to run .php files at set times.

Here's an example of what cURL needs to run the .php file:

curl http://localhost/myscript.php

Then setup the CRON job to run the above cURL:

nano -w /var/spool/cron/root
or
crontab -e

Followed by:

01 * * * * /usr/bin/curl http://www.yoursite.com/script.php

For more info about, check out this post: https://www.scalescale.com/tips/nginx/execute-php-scripts-automatically-using-cron-curl/

For more info about cURL: What is cURL in PHP?

For more info about CRON: http://code.tutsplus.com/tutorials/scheduling-tasks-with-cron-jobs--net-8800

Also, if you would like to learn about setting up a CRON job on your hosted server, just inquire with your host provider, and they may have a GUI for setting it up in the c-panel (such as http://godaddy.com, or http://1and1.com/ )

NOTE: Technically I believe you can setup a CRON job to run the .php file directly, but I'm not certain.

Best of luck with the automatic PHP running :-)

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

One step using Array.reduce() - no jQuery

var items = [{id: 331}, {id: 220}, {id: 872}];

var searchIndexForId = 220;
var index = items.reduce(function(searchIndex, item, index){
  if(item.id === searchIndexForId) { 
    console.log('found!');
    searchIndex = index;
  }
  return searchIndex;
}, null);

will return null if index was not found.

Git error: "Please make sure you have the correct access rights and the repository exists"

Strangely I only received this error in 1 of my many repos.

My issue was after installing the new GitHub Desktop for Windows where the previous old GitHub for Win kept keys in ~/.ssh/github_rsa and ~/.ssh/github_rsa.pub where as the new GitHub for Win expects it in ~/.ssh/id_rsa so the solution was just renaming the existing private and public keys:

~/.ssh/github_rsa -> ~/.ssh/id_rsa
~/.ssh/github_rsa.pub -> ~/.ssh/id_rsa.pub

After which let me access the repo again without issue.

Try catch statements in C

While some of the other answers have covered the simple cases using setjmp and longjmp, in a real application there's two concerns that really matter.

  1. Nesting of try/catch blocks. Using a single global variable for your jmp_buf will make these not work.
  2. Threading. A single global variable for you jmp_buf will cause all kinds of pain in this situation.

The solution to these is to maintain a thread-local stack of jmp_buf that get updated as you go. (I think this is what lua uses internally).

So instead of this (from JaredPar's awesome answer)

static jmp_buf s_jumpBuffer;

void Example() { 
  if (setjmp(s_jumpBuffer)) {
    // The longjmp was executed and returned control here
    printf("Exception happened\n");
  } else {
    // Normal code execution starts here
    Test();
  }
}

void Test() {
  // Rough equivalent of `throw`
  longjump(s_jumpBuffer, 42);
}

You'd use something like:

#define MAX_EXCEPTION_DEPTH 10;
struct exception_state {
  jmp_buf s_jumpBuffer[MAX_EXCEPTION_DEPTH];
  int current_depth;
};

int try_point(struct exception_state * state) {
  if(current_depth==MAX_EXCEPTION_DEPTH) {
     abort();
  }
  int ok = setjmp(state->jumpBuffer[state->current_depth]);
  if(ok) {
    state->current_depth++;
  } else {
    //We've had an exception update the stack.
    state->current_depth--;
  }
  return ok;
}

void throw_exception(struct exception_state * state) {
  longjump(state->current_depth-1,1);
}

void catch_point(struct exception_state * state) {
    state->current_depth--;
}

void end_try_point(struct exception_state * state) {
    state->current_depth--;
}

__thread struct exception_state g_exception_state; 

void Example() { 
  if (try_point(&g_exception_state)) {
    catch_point(&g_exception_state);
    printf("Exception happened\n");
  } else {
    // Normal code execution starts here
    Test();
    end_try_point(&g_exception_state);
  }
}

void Test() {
  // Rough equivalent of `throw`
  throw_exception(g_exception_state);
}

Again a more realistic version of this would include some way to store error information into the exception_state, better handling of MAX_EXCEPTION_DEPTH (maybe using realloc to grow the buffer, or something like that).

DISCLAIMER: The above code was written without any testing whatsoever. It is purely so you get an idea of how to structure things. Different systems and different compilers will need to implement the thread local storage differently. The code probably contains both compile errors and logic errors - so while you're free to use it as you choose, TEST it before using it ;)

Jupyter notebook not running code. Stuck on In [*]

Check the output on the server environment from which jupyter notebook was launched if you can. You'll probably find error messages and print() results.

How to create a notification with NotificationCompat.Builder?

You can try this code this works fine for me:

    NotificationCompat.Builder mBuilder= new NotificationCompat.Builder(this);

    Intent i = new Intent(noti.this, Xyz_activtiy.class);
    PendingIntent pendingIntent= PendingIntent.getActivity(this,0,i,0);

    mBuilder.setAutoCancel(true);
    mBuilder.setDefaults(NotificationCompat.DEFAULT_ALL);
    mBuilder.setWhen(20000);
    mBuilder.setTicker("Ticker");
    mBuilder.setContentInfo("Info");
    mBuilder.setContentIntent(pendingIntent);
    mBuilder.setSmallIcon(R.drawable.home);
    mBuilder.setContentTitle("New notification title");
    mBuilder.setContentText("Notification text");
    mBuilder.setSound(RingtoneManager.getDefaultUri(RingtoneManager.TYPE_NOTIFICATION));

    NotificationManager notificationManager= (NotificationManager)getSystemService(Context.NOTIFICATION_SERVICE);
    notificationManager.notify(2,mBuilder.build());

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

I'm just starting to use EC2 myself so not an expert, but Amazon's own documentation says:

we recommend that you use the local instance store for temporary data and, for data requiring a higher level of durability, we recommend using Amazon EBS volumes or backing up the data to Amazon S3.

Emphasis mine.

I do more data analysis than web hosting, so persistence doesn't matter as much to me as it might for a web site. Given the distinction made by Amazon itself, I wouldn't assume that EBS is right for everyone.

I'll try to remember to weigh in again after I've used both.

How to get the title of HTML page with JavaScript?

Can use getElementsByTagName

var x = document.getElementsByTagName("title")[0];

alert(x.innerHTML)

// or

alert(x.textContent)

// or

document.querySelector('title')

Edits as suggested by Paul

how to redirect to home page

_x000D_
_x000D_
var url = location.href;_x000D_
var newurl = url.replace('some-domain.com','another-domain.com';);_x000D_
location.href=newurl;
_x000D_
_x000D_
_x000D_

See this answer https://stackoverflow.com/a/42291014/3901511

In LaTeX, how can one add a header/footer in the document class Letter?

After I removed

\usepackage{fontspec}% font selecting commands 
\usepackage{xunicode}% unicode character macros 
\usepackage{xltxtra} % some fixes/extras 

it seems to have worked "correctly".

It may be worth noting that the headers and footers only appear from page 2 onwards. Although I've tried the fix for this given in the fancyhdr documentation, I can't get it to work either.

FYI: MikTeX 2.7 under Vista

Reducing the gap between a bullet and text in a list item

I have <a> inside the <li>s.

To the <ul> elements, apply the following CSS:

ul {
    margin: 0;
    padding: 0;
    list-style: none;
}

To the <a> elements, apply the following CSS:

a:before {
    content: "";
    height: 6px;
    width: 6px;
    border-radius: 50%;
    background: #000;
    display: inline-block;
    margin: 0 6px 0 0;
    vertical-align: middle;
}

This creates pseudo elements for the bullets. They can be styled just like any other elements.

I've implemented it here: http://www.cssdesk.com/R2AvX

Finding all the subsets of a set

here is my recursive solution.

vector<vector<int> > getSubsets(vector<int> a){


//base case
    //if there is just one item then its subsets are that item and empty item
    //for example all subsets of {1} are {1}, {}

    if(a.size() == 1){
        vector<vector<int> > temp;
        temp.push_back(a);

        vector<int> b;
        temp.push_back(b);

        return temp;

    }
    else
    {


         //here is what i am doing

         // getSubsets({1, 2, 3})
         //without = getSubsets({1, 2})
         //without = {1}, {2}, {}, {1, 2}

         //with = {1, 3}, {2, 3}, {3}, {1, 2, 3}

         //total = {{1}, {2}, {}, {1, 2}, {1, 3}, {2, 3}, {3}, {1, 2, 3}}

         //return total

        int last = a[a.size() - 1];

        a.pop_back();

        vector<vector<int> > without = getSubsets(a);

        vector<vector<int> > with = without;

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

            with[i].push_back(last);

        }

        vector<vector<int> > total;

        for(int j=0;j<without.size();j++){
            total.push_back(without[j]);
        }

        for(int k=0;k<with.size();k++){
            total.push_back(with[k]);
        }


        return total;
    }


}

getting error while updating Composer

If you're using php 7.3 for laravel 5.7. this work for me

sudo apt-get install php-gd php-xml php7.3-mbstring

Is there a Pattern Matching Utility like GREP in Windows?

On Windows I use Far Manager for file search. BSD licensed, works in console, saves time on typing cmdline parameters. Here is its search dialog invoked by Alt-F7. Alt-F7

Jenkins Slave port number for firewall

A slave isn't a server, it's a client type application. Network clients (almost) never use a specific port. Instead, they ask the OS for a random free port. This works much better since you usually run clients on many machines where the current configuration isn't known in advance. This prevents thousands of "client wouldn't start because port is already in use" bug reports every day.

You need to tell the security department that the slave isn't a server but a client which connects to the server and you absolutely need to have a rule which says client:ANY -> server:FIXED. The client port number should be >= 1024 (ports 1 to 1023 need special permissions) but I'm not sure if you actually gain anything by adding a rule for this - if an attacker can open privileged ports, they basically already own the machine.

If they argue, then ask them why they don't require the same rule for all the web browsers which people use in your company.

VBA: activating/selecting a worksheet/row/cell

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

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

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


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

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

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

String concatenation with Groovy

Reproducing tim_yates answer on current hardware and adding leftShift() and concat() method to check the finding:

  'String leftShift' {
    foo << bar << baz
  }
  'String concat' {
    foo.concat(bar)
       .concat(baz)
       .toString()
  }

The outcome shows concat() to be the faster solution for a pure String, but if you can handle GString somewhere else, GString template is still ahead, while honorable mention should go to leftShift() (bitwise operator) and StringBuffer() with initial allocation:

Environment
===========
* Groovy: 2.4.8
* JVM: OpenJDK 64-Bit Server VM (25.191-b12, Oracle Corporation)
    * JRE: 1.8.0_191
    * Total Memory: 238 MB
    * Maximum Memory: 3504 MB
* OS: Linux (4.19.13-300.fc29.x86_64, amd64)

Options
=======
* Warm Up: Auto (- 60 sec)
* CPU Time Measurement: On

                                    user  system  cpu  real

String adder                         453       7  460   469
String leftShift                     287       2  289   295
String concat                        169       1  170   173
GString template                      24       0   24    24
Readable GString template             32       0   32    32
GString template toString            400       0  400   406
Readable GString template toString   412       0  412   419
StringBuilder                        325       3  328   334
StringBuffer                         390       1  391   398
StringBuffer with Allocation         259       1  260   265

How to convert a plain object into an ES6 Map?

The answer by Nils describes how to convert objects to maps, which I found very useful. However, the OP was also wondering where this information is in the MDN docs. While it may not have been there when the question was originally asked, it is now on the MDN page for Object.entries() under the heading Converting an Object to a Map which states:

Converting an Object to a Map

The new Map() constructor accepts an iterable of entries. With Object.entries, you can easily convert from Object to Map:

const obj = { foo: 'bar', baz: 42 }; 
const map = new Map(Object.entries(obj));
console.log(map); // Map { foo: "bar", baz: 42 }

Programmatically get the version number of a DLL

While the original question may not have been specific to a web service, here is a complete testWebService you can add to display a web service non-cached response plus the file version. We use file version instead of assembly version because we want to know a version, but with all assembly versions 1.0.0.0, the web site can be easily patched (signing and demand link still active!). Replace @Class@ with the name of the web api controller this service is embedded in. It's good for a go/nogo on a web service plus a quick version check.

  [Route("api/testWebService")]
  [AllowAnonymous]
  [HttpGet]
  public HttpResponseMessage TestWebService()
  {
      HttpResponseMessage responseMessage = Request.CreateResponse(HttpStatusCode.OK);
      string loc = Assembly.GetAssembly(typeof(@Class@)).Location;
      FileVersionInfo versionInfo = FileVersionInfo.GetVersionInfo(loc);
      responseMessage.Content = new StringContent($"<h2>The XXXXX web service GET test succeeded.</h2>{DateTime.Now}<br/><br/>File Version: {versionInfo.FileVersion}");
      responseMessage.Content.Headers.ContentType = new MediaTypeHeaderValue("text/html");
      Request.RegisterForDispose(responseMessage);
      return responseMessage;
  }

I found it also necessary to add the following to web.config under configuration to make it truly anonymous

<location path="api/testwebservice">
    <system.web>
        <authorization>
            <allow users="*" />
        </authorization>
    </system.web>
</location>

Count number of occurences for each unique value

You can try also a tidyverse

library(tidyverse) 
dummyData %>% 
    as.tibble() %>% 
    count(value)
# A tibble: 2 x 2
  value     n
  <dbl> <int>
1     1    25
2     2    75

What is the naming convention in Python for variable and function names?

As mentioned, PEP 8 says to use lower_case_with_underscores for variables, methods and functions.

I prefer using lower_case_with_underscores for variables and mixedCase for methods and functions makes the code more explicit and readable. Thus following the Zen of Python's "explicit is better than implicit" and "Readability counts"

How to create Drawable from resource

I would just like to add that if you are getting "deprecated" message when using getDrawable(...) you should use the following method from the support library instead.

ContextCompat.getDrawable(getContext(),R.drawable.[name])

You do not have to use getResources() when using this method.

This is equivalent to doing something like

Drawable mDrawable;
if(android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.LOLLIPOP){
    mDrawable = ContextCompat.getDrawable(getContext(),R.drawable.[name]);
} else {
    mDrawable = getResources().getDrawable(R.id.[name]);
}

This works on both pre and post Lollipop versions.

Catching errors in Angular HttpClient

The worse thing is not having a decent stack trace which you simply cannot generate using an HttpInterceptor (hope to stand corrected). All you get is a load of zone and rxjs useless bloat, and not the line or class that generated the error.

To do this you will need to generate a stack in an extended HttpClient, so its not advisable to do this in a production environment.

/**
 * Extended HttpClient that generates a stack trace on error when not in a production build.
 */
@Injectable()
export class TraceHttpClient extends HttpClient {
  constructor(handler: HttpHandler) {
    super(handler);
  }

  request(...args: [any]): Observable<any> {
    const stack = environment.production ? null : Error().stack;
    return super.request(...args).pipe(
      catchError((err) => {
        // tslint:disable-next-line:no-console
        if (stack) console.error('HTTP Client error stack\n', stack);
        return throwError(err);
      })
    );
  }
}

Query to list all stored procedures

If you are using SQL Server 2005 the following will work:

select *
  from sys.procedures
 where is_ms_shipped = 0

How to use a RELATIVE path with AuthUserFile in htaccess?

.htpasswd requires full absolute path from the absolute root of the server.

Please get full absolute path of the file by echo echo $_SERVER['DOCUMENT_ROOT'];.

here is working basic auth .htaccess script.

AuthType Basic
AuthName "Access to the Hidden Files"
AuthUserFile 'C:/xampp/htdocs/ht/.htpasswd'
Require valid-user

Before login

enter image description here

Afetr Login

enter image description here

Is it possible to insert multiple rows at a time in an SQLite database?

in mysql lite you cannot insert multiple values, but you can save time by opening connection only one time and then doing all insertions and then closing connection. It saves a lot of time

How to find out the username and password for mysql database

If you forget your password for SQL plus 10g then follow the steps :

  1. START
  2. Type RUN in the search box
  3. Type 'cnc' in the box captioned as OPEN and a black box will appear 4.There will be some text already in the box. (C:\Users\admin>) Just beside that start typing 'sqlplus/nolog' press ENTER key
  4. On the next line type 'conn sys/change_on_install as sysdba' (press ENTER) 6.(in the next line after sql-> type) 'alter user scott account unlock' .
  5. Now open your slpplus and type user name as 'scott' and password as 'tiger'.

If it asks your old password then type the one you have given while installing.

Limit the output of the TOP command to a specific process name

I solved my problem using:

top -n1 -b | grep "proccess name"

in this case: -n is used to set how many times top will what proccess
and -b is used to show all pids

it's prevents errors like : top: pid limit (20) exceeded

Warnings Your Apk Is Using Permissions That Require A Privacy Policy: (android.permission.READ_PHONE_STATE)

If you are using the package device_id to get the unique device id then that will add an android.permission.READ_PHONE_STATE without your knowledge which eventually will lead to the Play Store warning.

Instead you can use the device_info package for the same purpose without the need of the extra permission. Check this SO thread

how to convert integer to string?

NSString* myNewString = [NSString stringWithFormat:@"%d", myInt];

How to create a directory if it doesn't exist using Node.js?

No, for multiple reasons.

  1. The path module does not have an exists/existsSync method. It is in the fs module. (Perhaps you just made a typo in your question?)

  2. The docs explicitly discourage you from using exists.

    fs.exists() is an anachronism and exists only for historical reasons. There should almost never be a reason to use it in your own code.

    In particular, checking if a file exists before opening it is an anti-pattern that leaves you vulnerable to race conditions: another process may remove the file between the calls to fs.exists() and fs.open(). Just open the file and handle the error when it's not there.

    Since we're talking about a directory rather than a file, this advice implies you should just unconditionally call mkdir and ignore EEXIST.

  3. In general, You should avoid the *Sync methods. They're blocking, which means absolutely nothing else in your program can happen while you go to the disk. This is a very expensive operation, and the time it takes breaks the core assumption of node's event loop.

    The *Sync methods are usually fine in single-purpose quick scripts (those that do one thing and then exit), but should almost never be used when you're writing a server: your server will be unable to respond to anyone for the entire duration of the I/O requests. If multiple client requests require I/O operations, your server will very quickly grind to a halt.


    The only time I'd consider using *Sync methods in a server application is in an operation that happens once (and only once), at startup. For example, require actually uses readFileSync to load modules.

    Even then, you still have to be careful because lots of synchronous I/O can unnecessarily slow down your server's startup time.


    Instead, you should use the asynchronous I/O methods.

So if we put together those pieces of advice, we get something like this:

function ensureExists(path, mask, cb) {
    if (typeof mask == 'function') { // allow the `mask` parameter to be optional
        cb = mask;
        mask = 0777;
    }
    fs.mkdir(path, mask, function(err) {
        if (err) {
            if (err.code == 'EEXIST') cb(null); // ignore the error if the folder already exists
            else cb(err); // something else went wrong
        } else cb(null); // successfully created folder
    });
}

And we can use it like this:

ensureExists(__dirname + '/upload', 0744, function(err) {
    if (err) // handle folder creation error
    else // we're all good
});

Of course, this doesn't account for edge cases like

  • What happens if the folder gets deleted while your program is running? (assuming you only check that it exists once during startup)
  • What happens if the folder already exists but with the wrong permissions?

How to turn on line numbers in IDLE?

If you are trying to track down which line caused an error, if you right-click in the Python shell where the line error is displayed it will come up with a "Go to file/line" which takes you directly to the line in question.

Java: Casting Object to Array type

What you've got (according to the debug image) is an object array containing a string array. So you need something like:

Object[] objects = (Object[]) values;
String[] strings = (String[]) objects[0];

You haven't shown the type of values - if this is already Object[] then you could just use (String[])values[0].

Of course even with the cast to Object[] you could still do it in one statement, but it's ugly:

String[] strings = (String[]) ((Object[])values)[0];

Differences between Octave and MATLAB?

The thing makes Matlab so popular and special is its excellent toolboxes in different disciplines. Since your main goal is to learn Matlab, so there is not different at all if you work with Octave or Matlab!

Just going and buying Matlab without any cool toolbox (which basically depends on your major) is not really a reasonable expense!

You can definitely have a good start with Octave, and follow tons of tutorials on Matlab on the internet.

Formatting html email for Outlook

I used VML(Vector Markup Language) based formatting in my email template. In VML Based you have write your code within comment I took help from this site.

https://litmus.com/blog/a-guide-to-bulletproof-buttons-in-email-design#supporttable

Oracle TNS names not showing when adding new connection to SQL Developer

Open SQL Developer. Go to Tools -> Preferences -> Databases -> Advanced Then explicitly set the Tnsnames Directory

My TNSNAMES was set up correctly and I could connect to Toad, SQL*Plus etc. but I needed to do this to get SQL Developer to work. Perhaps it was a Win 7 issue as it was a pain to install too.

How can I remove the string "\n" from within a Ruby string?

You need to use "\n" not '\n' in your gsub. The different quote marks behave differently.

Double quotes " allow character expansion and expression interpolation ie. they let you use escaped control chars like \n to represent their true value, in this case, newline, and allow the use of #{expression} so you can weave variables and, well, pretty much any ruby expression you like into the text.

While on the other hand, single quotes ' treat the string literally, so there's no expansion, replacement, interpolation or what have you.

In this particular case, it's better to use either the .delete or .tr String method to delete the newlines.

See here for more info

Fake "click" to activate an onclick method

Once you have selected an element you can call click()

document.getElementById('link').click();

see: https://developer.mozilla.org/En/DOM/Element.click

I don't remember if this works on IE, but it should. I don't have a windows machine nearby.

require_once :failed to open stream: no such file or directory

set_include_path(get_include_path() . $_SERVER["DOCUMENT_ROOT"] . "/mysite/php/includes/");

Also this can help.See set_include_path()

How do I find the value of $CATALINA_HOME?

Tomcat can tell you in several ways. Here's the easiest:

 $ /path/to/catalina.sh version
Using CATALINA_BASE:   /usr/local/apache-tomcat-7.0.29
Using CATALINA_HOME:   /usr/local/apache-tomcat-7.0.29
Using CATALINA_TMPDIR: /usr/local/apache-tomcat-7.0.29/temp
Using JRE_HOME:        /System/Library/Frameworks/JavaVM.framework/Versions/CurrentJDK/Home
Using CLASSPATH:       /usr/local/apache-tomcat-7.0.29/bin/bootstrap.jar:/usr/local/apache-tomcat-7.0.29/bin/tomcat-juli.jar
Server version: Apache Tomcat/7.0.29
Server built:   Jul 3 2012 11:31:52
Server number:  7.0.29.0
OS Name:        Mac OS X
OS Version:     10.7.4
Architecture:   x86_64
JVM Version:    1.6.0_33-b03-424-11M3720
JVM Vendor:     Apple Inc.

If you don't know where catalina.sh is (or it never gets called), you can usually find it via ps:

$ ps aux | grep catalina
chris            930   0.0  3.1  2987336 258328 s000  S    Wed01PM   2:29.43 /System/Library/Java/JavaVirtualMachines/1.6.0.jdk/Contents/Home/bin/java -Dnop -Djava.util.logging.manager=org.apache.juli.ClassLoaderLogManager -Djava.library.path=/usr/local/apache-tomcat-7.0.29/lib -Djava.endorsed.dirs=/usr/local/apache-tomcat-7.0.29/endorsed -classpath /usr/local/apache-tomcat-7.0.29/bin/bootstrap.jar:/usr/local/apache-tomcat-7.0.29/bin/tomcat-juli.jar -Dcatalina.base=/Users/chris/blah/blah -Dcatalina.home=/usr/local/apache-tomcat-7.0.29 -Djava.io.tmpdir=/Users/chris/blah/blah/temp org.apache.catalina.startup.Bootstrap start

From the ps output, you can see both catalina.home and catalina.base. catalina.home is where the Tomcat base files are installed, and catalina.base is where the running configuration of Tomcat exists. These are often set to the same value unless you have configured your Tomcat for multiple (configuration) instances to be launched from a single Tomcat base install.

You can also interrogate the JVM directly if you can't find it in a ps listing:

$ jinfo -sysprops 930 | grep catalina
Attaching to process ID 930, please wait...
Debugger attached successfully.
Server compiler detected.
JVM version is 20.8-b03-424
catalina.base = /Users/chris/blah/blah
[...]
catalina.home = /usr/local/apache-tomcat-7.0.29

If you can't manage that, you can always try to write a JSP that dumps the values of the two system properties catalina.home and catalina.base.

How to change Format of a Cell to Text using VBA

Well this should change your format to text.

Worksheets("Sheetname").Activate
Worksheets("SheetName").Columns(1).Select 'or Worksheets("SheetName").Range("A:A").Select
Selection.NumberFormat = "@"

Why is the GETDATE() an invalid identifier

getdate() for MS-SQL, sysdate for Oracle server

Comma separated results in SQL

For Sql Server 2017 and later you can use the new STRING_AGG function

https://docs.microsoft.com/en-us/sql/t-sql/functions/string-agg-transact-sql

The following example replaces null values with 'N/A' and returns the names separated by commas in a single result cell.

SELECT STRING_AGG ( ISNULL(FirstName,'N/A'), ',') AS csv 
FROM Person.Person;

Here is the result set.

John,N/A,Mike,Peter,N/A,N/A,Alice,Bob

Perhaps a more common use case is to group together and then aggregate, just like you would with SUM, COUNT or AVG.

SELECT a.articleId, title, STRING_AGG (tag, ',') AS tags 
FROM dbo.Article AS a       
LEFT JOIN dbo.ArticleTag AS t 
    ON a.ArticleId = t.ArticleId 
GROUP BY a.articleId, title;

How to POST the data from a modal form of Bootstrap?

You need to handle it via ajax submit.

Something like this:

$(function(){
    $('#subscribe-email-form').on('submit', function(e){
        e.preventDefault();
        $.ajax({
            url: url, //this is the submit URL
            type: 'GET', //or POST
            data: $('#subscribe-email-form').serialize(),
            success: function(data){
                 alert('successfully submitted')
            }
        });
    });
});

A better way would be to use a django form, and then render the following snippet:

<form>
    <div class="modal-body">
        <input type="email" placeholder="email"/>
        <p>This service will notify you by email should any issue arise that affects your plivo service.</p>
    </div>
    <div class="modal-footer">
        <input type="submit" value="SUBMIT" class="btn"/>
    </div>
</form>

via the context - example : {{form}}.

What is the purpose of class methods?

When a user logs in on my website, a User() object is instantiated from the username and password.

If I need a user object without the user being there to log in (e.g. an admin user might want to delete another users account, so i need to instantiate that user and call its delete method):

I have class methods to grab the user object.

class User():
    #lots of code
    #...
    # more code

    @classmethod
    def get_by_username(cls, username):
        return cls.query(cls.username == username).get()

    @classmethod
    def get_by_auth_id(cls, auth_id):
        return cls.query(cls.auth_id == auth_id).get()

SonarQube not picking up Unit Test Coverage

The presence of argLine configurations in either of surefire and jacoco plugins stops the jacoco report generation. The argLine should be defined in properties

<properties>
  <argLine>your jvm options here</argLine>
</properties>

Get type of a generic parameter in Java with reflection

This is impossible because generics in Java are only considered at compile time. Thus, the Java generics are just some kind of pre-processor. However you can get the actual class of the members of the list.

How can I tell how many objects I've stored in an S3 bucket?

aws s3 ls s3://bucket-name/folder-prefix-if-any --recursive | wc -l

Simple two column html layout without using tables

Well, if you want the super easiest method, just put

<div class="left">left</div>
<div class="right">right</div>

.left {
    float: left;    
}

though you may need more than that depending on what other layout requirements you have.

REACT - toggle class onclick

A good sample would help to understand things better:

HTML

<div id="root">
</div>

CSS

.box {
  display: block;
  width: 200px;
  height: 200px;
  background-color: gray;
  color: white;
  text-align: center;
  vertical-align: middle;
  cursor: pointer;
}
.box.green {
  background-color: green; 
}

React code

class App extends React.Component {
  constructor(props) {
    super(props);
    this.state = {addClass: false}
  }
  toggle() {
    this.setState({addClass: !this.state.addClass});
  }
  render() {
    let boxClass = ["box"];
    if(this.state.addClass) {
      boxClass.push('green');
    }
    return(
        <div className={boxClass.join(' ')} onClick={this.toggle.bind(this)}>{this.state.addClass ? "Remove a class" : "Add a class (click the box)"}<br />Read the tutorial <a href="http://www.automationfuel.com" target="_blank">here</a>.</div>       
    );
  }
}
ReactDOM.render(<App />, document.getElementById("root"));

How do you run a Python script as a service in Windows?

I started hosting as a service with pywin32.

Everything was well but I met the problem that service was not able to start within 30 seconds (default timeout for Windows) on system startup. It was critical for me because Windows startup took place simultaneous on several virtual machines hosted on one physical machine, and IO load was huge. Error messages were:

Error 1053: The service did not respond to the start or control request in a timely fashion.

Error 7009: Timeout (30000 milliseconds) waiting for the <ServiceName> service to connect.

I fought a lot with pywin, but ended up with using NSSM as it was proposed in this answer. It was very easy to migrate to it.

Convert HTML Character Back to Text Using Java Standard Library

I'm not aware of any way to do it using the standard library. But I do know and use this class that deals with html entities.

"HTMLEntities is an Open Source Java class that contains a collection of static methods (htmlentities, unhtmlentities, ...) to convert special and extended characters into HTML entitities and vice versa."

http://www.tecnick.com/public/code/cp_dpage.php?aiocp_dp=htmlentities

How to change current Theme at runtime in Android

This way work for me:

  @Override
protected void onCreate(Bundle savedInstanceState) {
    setTheme(GApplication.getInstance().getTheme());
    super.onCreate(savedInstanceState);

    setContentView(R.layout.activity_main);
}

Then you want to change a new theme:

GApplication.getInstance().setTheme(R.style.LightTheme);
recreate();

Remove Primary Key in MySQL

First modify the column to remove the auto_increment field like this: alter table user_customer_permission modify column id int;

Next, drop the primary key. alter table user_customer_permission drop primary key;

Override intranet compatibility mode IE8

I was able to override compatibility mode by specifying the meta tag as THE FIRST TAG in the head section, not just the first meta tag but as and only as the VERY FIRST TAG.

Thanks to @stefan.s for putting me on to it in your excellent answer. Prior to reading that I had:

THIS DID NOT WORK

<head> 
<link rel="stylesheet" type="text/css" href="/qmuat/plugins/editors/jckeditor/typography/typography.php"/>
<meta http-equiv="x-ua-compatible" content="IE=9" >

moved the link tag out of the way and it worked

THIS WORKS:

<head><meta http-equiv="x-ua-compatible" content="IE=9" >

So an IE8 client set to use compatibility renders the page as IE8 Standard mode - the content='IE=9' means use the highest standard available up to and including IE9.

Calling Python in Java?

Here a library that lets you write your python scripts once and decide which integration method (Jython, CPython/PyPy via Jep and Py4j) to use at runtime:

https://github.com/subes/invesdwin-context-python

Since each method has its own benefits/drawbacks as explained in the link.

mysql server port number

port number 3306 is used for MySQL and tomcat using 8080 port.more port numbers are available for run the servers or software whatever may be for our instant compilation..8080 is default for number so only we are getting port error in eclipse IDE. jvm and tomcat always prefer the 8080.3306 is default port number for MySQL.So only do not want to mention every time as "localhost:3306"

  <?php  
    $dbhost = 'localhost:3306';
//3306 default port number $dbhost='localhost'; is enough to specify the port number
//when we are utilizing xammp default port number is 8080.
      $dbuser = 'root';
      $dbpass = '';
         $db='users';

             $conn = mysqli_connect($dbhost, $dbuser, $dbpass,$db) or die ("could not connect to mysql");      

              // mysqli_select_db("users") or die ("no database");  

    if(! $conn ) {
        die('Could not connect: ' . mysqli_error($conn));
    }else{
        echo 'Connected successfully';
    }
    ?>

Google maps responsive resize

After few years, I moved to leaflet map and I have fixed this issue completely, the following could be applied to google maps too:

    var headerHeight = $("#navMap").outerHeight();
    var footerHeight = $("footer").outerHeight();
    var windowHeight = window.innerHeight;
    var mapContainerHeight = headerHeight + footerHeight;
    var totalMapHeight = windowHeight - mapContainerHeight;
    $("#map").css("margin-top", headerHeight);
    $("#map").height(totalMapHeight);

    $(window).resize(function(){
        var headerHeight = $("#navMap").outerHeight();
        var footerHeight = $("footer").outerHeight();
        var windowHeight = window.innerHeight;
        var mapContainerHeight = headerHeight + footerHeight;
        var totalMapHeight = windowHeight - mapContainerHeight;
        $("#map").css("margin-top", headerHeight);
        $("#map").height(totalMapHeight);
        map.fitBounds(group1.getBounds());
    });

Google Map API - Removing Markers

Following code might be useful if someone is using React and has a different component of Marker and want to remove marker from map.

export default function useGoogleMapMarker(props) {
  const [marker, setMarker] = useState();

  useEffect(() => {
    // ...code
    const marker = new maps.Marker({ position, map, title, icon });
    // ...code
    setMarker(marker);
    return () => marker.setMap(null); // to remove markers when unmounts
  }, []);

  return marker;
}

How to clear form after submit in Angular 2?

Below code works for me in Angular 4

import { FormBuilder, FormGroup, Validators } from '@angular/forms';
export class RegisterComponent implements OnInit {
 registerForm: FormGroup; 

 constructor(private formBuilder: FormBuilder) { }   

 ngOnInit() {
    this.registerForm = this.formBuilder.group({
      empname: [''],
      empemail: ['']
    });
 }

 onRegister(){
    //sending data to server using http request
    this.registerForm.reset()
 }

}

Java: unparseable date exception

What you're basically doing here is relying on Date#toString() which already has a fixed pattern. To convert a Java Date object into another human readable String pattern, you need SimpleDateFormat#format().

private String modifyDateLayout(String inputDate) throws ParseException{
    Date date = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss z").parse(inputDate);
    return new SimpleDateFormat("dd.MM.yyyy HH:mm:ss").format(date);
}

By the way, the "unparseable date" exception can here only be thrown by SimpleDateFormat#parse(). This means that the inputDate isn't in the expected pattern "yyyy-MM-dd HH:mm:ss z". You'll probably need to modify the pattern to match the inputDate's actual pattern.

Update: Okay, I did a test:

public static void main(String[] args) throws Exception {
    String inputDate = "2010-01-04 01:32:27 UTC";
    String newDate = new Test().modifyDateLayout(inputDate);
    System.out.println(newDate);
}

This correctly prints:

03.01.2010 21:32:27

(I'm on GMT-4)

Update 2: as per your edit, you really got a ParseException on that. The most suspicious part would then be the timezone of UTC. Is this actually known at your Java environment? What Java version and what OS version are you using? Check TimeZone.getAvailableIDs(). There must be a UTC in between.

link button property to open in new tab?

When the LinkButton Enabled property is false it just renders a standard hyperlink. When you right click any disabled hyperlink you don't get the option to open in anything.

try

lbnkVidTtile1.Enabled = true;

I'm sorry if I misunderstood. Could I just make sure that you understand the purpose of a LinkButton? It is to give the appearance of a HyperLink but the behaviour of a Button. This means that it will have an anchor tag, but there is JavaScript wired up that performs a PostBack to the page. If you want to link to another page then it is recommended here that you use a standard HyperLink control.

json_decode() expects parameter 1 to be string, array given

Ok I was running into the same issue. What I failed to notice is that I was using json_decode() instead of using json_encode() so for those who are going to come here please make sure you are using the right function, which is json_encode()

Note: Depends on what you are working on but make sure you are using the right function.

Soft Edges using CSS?

Another option is to use one of my personal favorite CSS tools: box-shadow.

A box shadow is really a drop-shadow on the node. It looks like this:

-moz-box-shadow: 1px 2px 3px rgba(0,0,0,.5);
-webkit-box-shadow: 1px 2px 3px rgba(0,0,0,.5);
box-shadow: 1px 2px 3px rgba(0,0,0,.5);

The arguments are:

1px: Horizontal offset of the effect. Positive numbers shift it right, negative left.
2px: Vertical offset of the effect. Positive numbers shift it down, negative up.
3px: The blur effect.  0 means no blur.
color: The color of the shadow.

So, you could leave your current design, and add a box-shadow like:

box-shadow: 0px -2px 2px rgba(34,34,34,0.6);

This should give you a 'blurry' top-edge.

This website will help with more information: http://css-tricks.com/snippets/css/css-box-shadow/

Converting HTML element to string in JavaScript / JQuery

Try a slight different approach:

//set string and append it as object
var myHtmlString = '<iframe id="myFrame" width="854" height="480" src="http://www.youtube.com/embed/gYKqrjq5IjU?feature=oembed" frameborder="0" allowfullscreen></iframe>';
$('body').append(myHtmlString);

//as you noticed you can't just get it back
var myHtmlStringBack = $('#myFrame').html(); 
alert(myHtmlStringBack); // will be empty (a bug in jquery?) but...

//since an id was added to your iframe so you can retrieve its attributes back...
var width = $('#myFrame').attr('width');
var height = $('#myFrame').attr('height');
var src = $('#myFrame').attr('src');
var myReconstructedString = '<iframe id="myFrame" width="'+ width +'" height="'+ height +'" src="'+ src+'" frameborder="0" allowfullscreen></iframe>';
alert(myReconstructedString);

On a CSS hover event, can I change another div's styling?

This can not be done purely with css. This is a behaviour, which affects the styling of the page.

With jquery you can quickly implement the behavior from your question:

$(function() {
  $('#a').hover(function() {
    $('#b').css('background-color', 'yellow');
  }, function() {
    // on mouseout, reset the background colour
    $('#b').css('background-color', '');
  });
});

Cannot set property 'display' of undefined

I've found this answer in the site https://plainjs.com/javascript/styles/set-and-get-css-styles-of-elements-53/.

In this code we add multiple styles in an element:

_x000D_
_x000D_
let_x000D_
    element = document.querySelector('span')_x000D_
  , cssStyle = (el, styles) => {_x000D_
      for (var property in styles) {_x000D_
          el.style[property] = styles[property];_x000D_
      }_x000D_
  }_x000D_
;_x000D_
_x000D_
cssStyle(element, { background:'tomato', color: 'white', padding: '0.5rem 1rem'});
_x000D_
span{_x000D_
font-family: sans-serif;_x000D_
color: #323232;_x000D_
background: #fff;_x000D_
}
_x000D_
<span>_x000D_
lorem ipsum_x000D_
</span>
_x000D_
_x000D_
_x000D_

How to set button click effect in Android?

This can be achieved by creating a drawable xml file containing a list of states for the button. So for example if you create a new xml file called "button.xml" with the following code:

<selector xmlns:android="http://schemas.android.com/apk/res/android">
    <item android:state_focused="true" android:state_pressed="false" android:drawable="@drawable/YOURIMAGE" />
    <item android:state_focused="true" android:state_pressed="true" android:drawable="@drawable/gradient" />
    <item android:state_focused="false" android:state_pressed="true" android:drawable="@drawable/gradient" />
    <item android:drawable="@drawable/YOURIMAGE" />
</selector>

To keep the background image with a darkened appearance on press, create a second xml file and call it gradient.xml with the following code:

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >
    <item>
        <bitmap android:src="@drawable/YOURIMAGE"/>
    </item>
    <item>
        <shape xmlns:android="http://schemas.android.com/apk/res/android">
            <gradient android:angle="90" android:startColor="#880f0f10" android:centerColor="#880d0d0f" android:endColor="#885d5d5e"/>
        </shape>
    </item>
</layer-list>

In the xml of your button set the background to be the button xml e.g.

android:background="@drawable/button"

Hope this helps!

Edit: Changed the above code to show an image (YOURIMAGE) in the button as opposed to a block colour.

How to send email via Django?

You could use "Test Mail Server Tool" to test email sending on your machine or localhost. Google and Download "Test Mail Server Tool" and set it up.

Then in your settings.py:

EMAIL_BACKEND= 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_HOST = 'localhost'
EMAIL_PORT = 25

From shell:

from django.core.mail import send_mail
send_mail('subject','message','sender email',['receipient email'],    fail_silently=False)

How do I determine whether my calculation of pi is accurate?

Since I'm the current world record holder for the most digits of pi, I'll add my two cents:

Unless you're actually setting a new world record, the common practice is just to verify the computed digits against the known values. So that's simple enough.

In fact, I have a webpage that lists snippets of digits for the purpose of verifying computations against them: http://www.numberworld.org/digits/Pi/


But when you get into world-record territory, there's nothing to compare against.

Historically, the standard approach for verifying that computed digits are correct is to recompute the digits using a second algorithm. So if either computation goes bad, the digits at the end won't match.

This does typically more than double the amount of time needed (since the second algorithm is usually slower). But it's the only way to verify the computed digits once you've wandered into the uncharted territory of never-before-computed digits and a new world record.


Back in the days where supercomputers were setting the records, two different AGM algorithms were commonly used:

These are both O(N log(N)^2) algorithms that were fairly easy to implement.

However, nowadays, things are a bit different. In the last three world records, instead of performing two computations, we performed only one computation using the fastest known formula (Chudnovsky Formula):

Enter image description here

This algorithm is much harder to implement, but it is a lot faster than the AGM algorithms.

Then we verify the binary digits using the BBP formulas for digit extraction.

Enter image description here

This formula allows you to compute arbitrary binary digits without computing all the digits before it. So it is used to verify the last few computed binary digits. Therefore it is much faster than a full computation.

The advantage of this is:

  1. Only one expensive computation is needed.

The disadvantage is:

  1. An implementation of the Bailey–Borwein–Plouffe (BBP) formula is needed.
  2. An additional step is needed to verify the radix conversion from binary to decimal.

I've glossed over some details of why verifying the last few digits implies that all the digits are correct. But it is easy to see this since any computation error will propagate to the last digits.


Now this last step (verifying the conversion) is actually fairly important. One of the previous world record holders actually called us out on this because, initially, I didn't give a sufficient description of how it worked.

So I've pulled this snippet from my blog:

N = # of decimal digits desired
p = 64-bit prime number

Enter image description here

Compute A using base 10 arithmetic and B using binary arithmetic.

Enter image description here

If A = B, then with "extremely high probability", the conversion is correct.


For further reading, see my blog post Pi - 5 Trillion Digits.

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

Here is my combined solution for various PHP versions.

In my company we are working with different servers with various PHP versions, so I had to find solution working for all.

$phpVersion = substr(phpversion(), 0, 3)*1;

if($phpVersion >= 5.4) {
  $encodedValue = json_encode($value, JSON_UNESCAPED_UNICODE);
} else {
  $encodedValue = preg_replace('/\\\\u([a-f0-9]{4})/e', "iconv('UCS-4LE','UTF-8',pack('V', hexdec('U$1')))", json_encode($value));
}

Credits should go to Marco Gasi & abu. The solution for PHP >= 5.4 is provided in the json_encode docs.

What is the difference between json.dump() and json.dumps() in python?

One notable difference in Python 2 is that if you're using ensure_ascii=False, dump will properly write UTF-8 encoded data into the file (unless you used 8-bit strings with extended characters that are not UTF-8):

dumps on the other hand, with ensure_ascii=False can produce a str or unicode just depending on what types you used for strings:

Serialize obj to a JSON formatted str using this conversion table. If ensure_ascii is False, the result may contain non-ASCII characters and the return value may be a unicode instance.

(emphasis mine). Note that it may still be a str instance as well.

Thus you cannot use its return value to save the structure into file without checking which format was returned and possibly playing with unicode.encode.

This of course is not valid concern in Python 3 any more, since there is no more this 8-bit/Unicode confusion.


As for load vs loads, load considers the whole file to be one JSON document, so you cannot use it to read multiple newline limited JSON documents from a single file.

formGroup expects a FormGroup instance

I was facing this issue and fixed by putting a check in form attribute. This issue can happen when the FormGroup is not initialized.

<form [formGroup]="loginForm" *ngIf="loginForm">
OR
<form [formGroup]="loginForm" *ngIf="this.loginForm">

This will not render the form until it is initialized.

How do a LDAP search/authenticate against this LDAP in Java

You can also use the following code :

package com.agileinfotech.bsviewer.ldap;

import java.util.Hashtable;
import java.util.ResourceBundle;

import javax.naming.Context;
import javax.naming.NamingException;
import javax.naming.directory.DirContext;
import javax.naming.directory.InitialDirContext;

public class LDAPLoginAuthentication {
    public LDAPLoginAuthentication() {
        // TODO Auto-generated constructor
    }

    ResourceBundle resBundle = ResourceBundle.getBundle("settings");

    @SuppressWarnings("unchecked")
    public String authenticateUser(String username, String password) {
        String strUrl = "success";
        Hashtable env = new Hashtable(11);
        boolean b = false;
        String Securityprinciple = "cn=" + username + "," + resBundle.getString("UserSearch");
        env.put(Context.INITIAL_CONTEXT_FACTORY, resBundle.getString("InitialContextFactory"));
        env.put(Context.PROVIDER_URL, resBundle.getString("Provider_url"));
        env.put(Context.SECURITY_AUTHENTICATION, "simple");
        env.put(Context.SECURITY_PRINCIPAL, Securityprinciple);
        env.put(Context.SECURITY_CREDENTIALS, password);

        try {
            // Create initial context
            DirContext ctx = new InitialDirContext(env);
            // Close the context when we're done
            b = true;
            ctx.close();

        } catch (NamingException e) {
            b = false;
        } finally {
            if (b) {
                strUrl = "success";
            } else {
                strUrl = "failer";
            }
        }
        return strUrl;
    }
}

List comprehension vs map

I consider that the most Pythonic way is to use a list comprehension instead of map and filter. The reason is that list comprehensions are clearer than map and filter.

In [1]: odd_cubes = [x ** 3 for x in range(10) if x % 2 == 1] # using a list comprehension

In [2]: odd_cubes_alt = list(map(lambda x: x ** 3, filter(lambda x: x % 2 == 1, range(10)))) # using map and filter

In [3]: odd_cubes == odd_cubes_alt
Out[3]: True

As you an see, a comprehension does not require extra lambda expressions as map needs. Furthermore, a comprehension also allows filtering easily, while map requires filter to allow filtering.

Responsive timeline UI with Bootstrap3

BootFlat

You can also try BootFlat, which has a section in their documentation specifically for crafting Timelines:

enter image description here

How can I split a JavaScript string by white space or comma?

input.split(/\s*[\s,]\s*/)

\s* matches zero or more white space characters (not just spaces, but also tabs and newlines).

... [\s,] matches one white space character or one comma

If you want to avoid blank elements from input like "foo,bar,,foobar", this will do the trick:

input.split(/(\s*,?\s*)+/)

The + matches one or more of the preceding character or group.

Edit:

Added ?after comma which matches zero or one comma.

Edit 2:

Turns out edit 1 was a mistake. Fixed it. Now there has to be at least one comma or one space for the expression to find a match.

What is meant by Ems? (Android TextView)

Ems is a typography term, it controls text size, etc. Check here

How do I skip a header from CSV files in Spark?

You could load each file separately, filter them with file.zipWithIndex().filter(_._2 > 0) and then union all the file RDDs.

If the number of files is too large, the union could throw a StackOverflowExeption.

Is it possible to have a HTML SELECT/OPTION value as NULL using PHP?

Yes, it is possible. You have to do something like this:

if(isset($_POST['submit']))
{
  $type_id = ($_POST['type_id'] == '' ? "null" : "'".$_POST['type_id']."'");
  $sql = "INSERT INTO `table` (`type_id`) VALUES (".$type_id.")";
}

It checks if the $_POST['type_id'] variable has an empty value. If yes, it assign NULL as a string to it. If not, it assign the value with ' to it for the SQL notation

Service Reference Error: Failed to generate code for the service reference

http://uliasz.com/2011/06/wcf-custom-tool-error-failed-to-generate-code-for-the-service-reference/#comment-1647

Thanks to the article above.

In my case, i have this issue with my WPF project in VS.Net 2008. After going through this article, i was realizing that the assembly used in the web service is different version of assembly used on client.

It works just fine after updating the assembly on the client.

How to get the current time in Google spreadsheet using script editor?

use the JavaScript Date() object. There are a number of ways to get the time, date, timestamps, etc from the object. (Reference)

function myFunction() {
  var d = new Date();
  var timeStamp = d.getTime();  // Number of ms since Jan 1, 1970

  // OR:

  var currentTime = d.toLocaleTimeString(); // "12:35 PM", for instance
}

Getting the 'external' IP address in Java

An alternative solution is to execute an external command, obviously, this solution limits the portability of the application.

For example, for an application that runs on Windows, a PowerShell command can be executed through jPowershell, as shown in the following code:

public String getMyPublicIp() {
    // PowerShell command
    String command = "(Invoke-WebRequest ifconfig.me/ip).Content.Trim()";
    String powerShellOut = PowerShell.executeSingleCommand(command).getCommandOutput();

    // Connection failed
    if (powerShellOut.contains("InvalidOperation")) {
        powerShellOut = null;
    }
    return powerShellOut;
}

get Context in non-Activity class

If your class is non-activity class, and creating an instance of it from the activiy, you can pass an instance of context via constructor of the later as follows:

class YourNonActivityClass{

// variable to hold context
private Context context;

//save the context recievied via constructor in a local variable

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

}

You can create instance of this class from the activity as follows:

new YourNonActivityClass(this);

Add data dynamically to an Array

$array[] = 'Hi';

pushes on top of the array.

$array['Hi'] = 'FooBar';

sets a specific index.

CSS scrollbar style cross browser

Webkit's support for scrollbars is quite sophisticated. This CSS gives a very minimal scrollbar, with a light grey track and a darker thumb:

::-webkit-scrollbar
{
  width: 12px;  /* for vertical scrollbars */
  height: 12px; /* for horizontal scrollbars */
}

::-webkit-scrollbar-track
{
  background: rgba(0, 0, 0, 0.1);
}

::-webkit-scrollbar-thumb
{
  background: rgba(0, 0, 0, 0.5);
}

This answer is a fantastic source of additional information.

How to import a jar in Eclipse

Adding external Jar is not smart in case you want to change the project location in filesystem.

The best way is to add the jar to build path so your project will compile if exported:

  1. Create a folder called lib in your project folder.

  2. copy to this folder all the jar files you need.

  3. Refresh your project in eclipse.

  4. Select all the jar files, then right click on one of them and select Build Path -> Add to Build Path

Tools for making latex tables in R

I'd like to add a mention of the "brew" package. You can write a brew template file which would be LaTeX with placeholders, and then "brew" it up to create a .tex file to \include or \input into your LaTeX. Something like:

\begin{tabular}{l l}
A & <%= fit$A %> \\
B & <%= fit$B %> \\
\end{tabular}

The brew syntax can also handle loops, so you can create a table row for each row of a dataframe.

What is the memory consumption of an object in Java?

In case it's useful to anyone, you can download from my web site a small Java agent for querying the memory usage of an object. It'll let you query "deep" memory usage as well.

How can I use a JavaScript variable as a PHP variable?

<script type="text/javascript">
var jvalue = 'this is javascript value';

<?php $abc = "<script>document.write(jvalue)</script>"?>   
</script>
<?php echo  'php_'.$abc;?>

How do I see what character set a MySQL database / table / column is?

Here's how I'd do it -

For Schemas (or Databases - they are synonyms):

SELECT default_character_set_name FROM information_schema.SCHEMATA 
WHERE schema_name = "schemaname";

For Tables:

SELECT CCSA.character_set_name FROM information_schema.`TABLES` T,
       information_schema.`COLLATION_CHARACTER_SET_APPLICABILITY` CCSA
WHERE CCSA.collation_name = T.table_collation
  AND T.table_schema = "schemaname"
  AND T.table_name = "tablename";

For Columns:

SELECT character_set_name FROM information_schema.`COLUMNS` 
WHERE table_schema = "schemaname"
  AND table_name = "tablename"
  AND column_name = "columnname";

Apache is "Unable to initialize module" because of module's and PHP's API don't match after changing the PHP configuration

I'd the same error even after recompiling the modules.

But I solved it you just have to specify the absolute path of your phpize.

Enable tcp\ip remote connections to sql server express already installed database with code or script(query)

I tested below code with SQL Server 2008 R2 Express and I believe we should have solution for all 6 steps you outlined. Let's take on them one-by-one:

1 - Enable TCP/IP

We can enable TCP/IP protocol with WMI:

set wmiComputer = GetObject( _
    "winmgmts:" _
    & "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProtocols = wmiComputer.ExecQuery( _
    "select * from ServerNetworkProtocol " _
    & "where InstanceName = 'SQLEXPRESS' and ProtocolName = 'Tcp'")

if tcpProtocols.Count = 1 then
    ' set tcpProtocol = tcpProtocols(0)
    ' I wish this worked, but unfortunately 
    ' there's no int-indexed Item property in this type

    ' Doing this instead
    for each tcpProtocol in tcpProtocols
        dim setEnableResult
            setEnableResult = tcpProtocol.SetEnable()
            if setEnableResult <> 0 then 
                Wscript.Echo "Failed!"
            end if
    next
end if

2 - Open the right ports in the firewall

I believe your solution will work, just make sure you specify the right port. I suggest we pick a different port than 1433 and make it a static port SQL Server Express will be listening on. I will be using 3456 in this post, but please pick a different number in the real implementation (I feel that we will see a lot of applications using 3456 soon :-)

3 - Modify TCP/IP properties enable a IP address

We can use WMI again. Since we are using static port 3456, we just need to update two properties in IPAll section: disable dynamic ports and set the listening port to 3456:

set wmiComputer = GetObject( _
    "winmgmts:" _
    & "\\.\root\Microsoft\SqlServer\ComputerManagement10")
set tcpProperties = wmiComputer.ExecQuery( _
    "select * from ServerNetworkProtocolProperty " _
    & "where InstanceName='SQLEXPRESS' and " _
    & "ProtocolName='Tcp' and IPAddressName='IPAll'")

for each tcpProperty in tcpProperties
    dim setValueResult, requestedValue

    if tcpProperty.PropertyName = "TcpPort" then
        requestedValue = "3456"
    elseif tcpProperty.PropertyName ="TcpDynamicPorts" then
        requestedValue = ""
    end if

    setValueResult = tcpProperty.SetStringValue(requestedValue)
    if setValueResult = 0 then 
        Wscript.Echo "" & tcpProperty.PropertyName & " set."
    else
        Wscript.Echo "" & tcpProperty.PropertyName & " failed!"
    end if
next

Note that I didn't have to enable any of the individual addresses to make it work, but if it is required in your case, you should be able to extend this script easily to do so.

Just a reminder that when working with WMI, WBEMTest.exe is your best friend!

4 - Enable mixed mode authentication in sql server

I wish we could use WMI again, but unfortunately this setting is not exposed through WMI. There are two other options:

  1. Use LoginMode property of Microsoft.SqlServer.Management.Smo.Server class, as described here.

  2. Use LoginMode value in SQL Server registry, as described in this post. Note that by default the SQL Server Express instance is named SQLEXPRESS, so for my SQL Server 2008 R2 Express instance the right registry key was HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10_50.SQLEXPRESS\MSSQLServer.

5 - Change user (sa) default password

You got this one covered.

6 - Finally (connect to the instance)

Since we are using a static port assigned to our SQL Server Express instance, there's no need to use instance name in the server address anymore.

SQLCMD -U sa -P newPassword -S 192.168.0.120,3456

Please let me know if this works for you (fingers crossed!).

How does Zalgo text work?

The text uses combining characters, also known as combining marks. See section 2.11 of Combining Characters in the Unicode Standard (PDF).

In Unicode, character rendering does not use a simple character cell model where each glyph fits into a box with given height. Combining marks may be rendered above, below, or inside a base character

So you can easily construct a character sequence, consisting of a base character and “combining above” marks, of any length, to reach any desired visual height, assuming that the rendering software conforms to the Unicode rendering model. Such a sequence has no meaning of course, and even a monkey could produce it (e.g., given a keyboard with suitable driver).

And you can mix “combining above” and “combining below” marks.

The sample text in the question starts with:

Remove Backslashes from Json Data in JavaScript

Your string is invalid, but assuming it was valid, you'd have to do:

var finalData = str.replace(/\\/g, "");

When you want to replace all the occurences with .replace, the first parameter must be a regex, if you supply a string, only the first occurrence will be replaced, that's why your replace wouldn't work.

Cheers

What is (functional) reactive programming?

After reading many pages about FRP I finally came across this enlightening writing about FRP, it finally made me understand what FRP really is all about.

I quote below Heinrich Apfelmus (author of reactive banana).

What is the essence of functional reactive programming?

A common answer would be that “FRP is all about describing a system in terms of time-varying functions instead of mutable state”, and that would certainly not be wrong. This is the semantic viewpoint. But in my opinion, the deeper, more satisfying answer is given by the following purely syntactic criterion:

The essence of functional reactive programming is to specify the dynamic behavior of a value completely at the time of declaration.

For instance, take the example of a counter: you have two buttons labelled “Up” and “Down” which can be used to increment or decrement the counter. Imperatively, you would first specify an initial value and then change it whenever a button is pressed; something like this:

counter := 0                               -- initial value
on buttonUp   = (counter := counter + 1)   -- change it later
on buttonDown = (counter := counter - 1)

The point is that at the time of declaration, only the initial value for the counter is specified; the dynamic behavior of counter is implicit in the rest of the program text. In contrast, functional reactive programming specifies the whole dynamic behavior at the time of declaration, like this:

counter :: Behavior Int
counter = accumulate ($) 0
            (fmap (+1) eventUp
             `union` fmap (subtract 1) eventDown)

Whenever you want to understand the dynamics of counter, you only have to look at its definition. Everything that can happen to it will appear on the right-hand side. This is very much in contrast to the imperative approach where subsequent declarations can change the dynamic behavior of previously declared values.

So, in my understanding an FRP program is a set of equations: enter image description here

j is discrete: 1,2,3,4...

f depends on t so this incorporates the possiblilty to model external stimuli

all state of the program is encapsulated in variables x_i

The FRP library takes care of progressing time, in other words, taking j to j+1.

I explain these equations in much more detail in this video.

EDIT:

About 2 years after the original answer, recently I came to the conclusion that FRP implementations have another important aspect. They need to (and usually do) solve an important practical problem: cache invalidation.

The equations for x_i-s describe a dependency graph. When some of the x_i changes at time j then not all the other x_i' values at j+1 need to be updated, so not all the dependencies need to be recalculated because some x_i' might be independent from x_i.

Furthermore, x_i-s that do change can be incrementally updated. For example let's consider a map operation f=g.map(_+1) in Scala, where f and g are List of Ints. Here f corresponds to x_i(t_j) and g is x_j(t_j). Now if I prepend an element to g then it would be wasteful to carry out the map operation for all the elements in g. Some FRP implementations (for example reflex-frp) aim to solve this problem. This problem is also known as incremental computing.

In other words, behaviours (the x_i-s ) in FRP can be thought as cache-ed computations. It is the task of the FRP engine to efficiently invalidate and recompute these cache-s (the x_i-s) if some of the f_i-s do change.

Get the position of a spinner in Android

protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        bt = findViewById(R.id.button);
        spinner = findViewById(R.id.sp_item);
        setInfo();
        spinnerAdapter = new SpinnerAdapter(this, arrayList);
        spinner.setAdapter(spinnerAdapter);



        spinner.setOnItemSelectedListener(new AdapterView.OnItemSelectedListener() {
            @Override
            public void onItemSelected(AdapterView<?> parent, View view, int position, long id) {
                //first,  we have to retrieve the item position as a string
                // then, we can change string value into integer
                String item_position = String.valueOf(position);

                int positonInt = Integer.valueOf(item_position);

                Toast.makeText(MainActivity.this, "value is "+ positonInt, Toast.LENGTH_SHORT).show();
            }

            @Override
            public void onNothingSelected(AdapterView<?> parent) {

            }
        });







note: the position of items is counted from 0.

How do I speed up the gwt compiler?

Although this entry is quite old and most of you probably already know, I think it's worth mention that GWT 2.x includes a new compile flag which speeds up compiles by skipping optimizations. You definitely shouldn't deploy JavaScript compiled that way, but it can be a time saver during non-production continuous builds.

Just include the flag: -draftCompile to your GWT compiler line.

Decoding UTF-8 strings in Python

You need to properly decode the source text. Most likely the source text is in UTF-8 format, not ASCII.

Because you do not provide any context or code for your question it is not possible to give a direct answer.

I suggest you study how unicode and character encoding is done in Python:

http://docs.python.org/2/howto/unicode.html

Negative list index?

List indexes of -x mean the xth item from the end of the list, so n[-1] means the last item in the list n. Any good Python tutorial should have told you this.

It's an unusual convention that only a few other languages besides Python have adopted, but it is extraordinarily useful; in any other language you'll spend a lot of time writing n[n.length-1] to access the last item of a list.

How do you check for permissions to write to a directory or file?

Wow...there is a lot of low-level security code in this thread -- most of which did not work for me, either -- although I learned a lot in the process. One thing that I learned is that most of this code is not geared to applications seeking per user access rights -- it is for Administrators wanting to alter rights programmatically, which -- as has been pointed out -- is not a good thing. As a developer, I cannot use the "easy way out" -- by running as Administrator -- which -- I am not one on the machine that runs the code, nor are my users -- so, as clever as these solutions are -- they are not for my situation, and probably not for most rank and file developers, either.

Like most posters of this type of question -- I initially felt it was "hackey", too -- I have since decided that it is perfectly alright to try it and let the possible exception tell you exactly what the user's rights are -- because the information I got did not tell me what the rights actually were. The code below -- did.

  Private Function CheckUserAccessLevel(folder As String) As Boolean
Try
  Dim newDir As String = String.Format("{0}{1}{2}",
                                       folder,
                                       If(folder.EndsWith("\"),
                                          "",
                                          "\"),
                                       "LookWhatICanDo")
  Dim lookWhatICanDo = Directory.CreateDirectory(newDir)

  Directory.Delete(newDir)
  Return True

Catch ex As Exception
  Return False
End Try

End Function

Strtotime() doesn't work with dd/mm/YYYY format

If nothing worked, try this.

$date = '25/05/2010'; //dd/mm/YYYY
$dateAr = explode('/',);
$date = $dateAr[2].'-'.$dateAr[1].'-'.$dateAr[0]; //YYYY-mm-dd

How does String substring work in Swift

Building on the above I needed to split a string at a non-printing character dropping the non-printing character. I developed two methods:

var str = "abc\u{1A}12345sdf"
let range1: Range<String.Index> = str.range(of: "\u{1A}")!
let index1: Int = str.distance(from: str.startIndex, to: range1.lowerBound)
let start = str.index(str.startIndex, offsetBy: index1)
let end = str.index(str.endIndex, offsetBy: -0)
let result = str[start..<end] // The result is of type Substring
let firstStr = str[str.startIndex..<range1.lowerBound]

which I put together using some of the answers above.

Because a String is a collection I then did the following:

var fString = String()
for (n,c) in str.enumerated(){

*if c == "\u{1A}" {
    print(fString);
    let lString = str.dropFirst(n + 1)
    print(lString)
    break
   }
 fString += String(c)
}*

Which for me was more intuitive. Which one is best? I have no way of telling They both work with Swift 5

Make a URL-encoded POST request using `http.NewRequest(...)`

URL-encoded payload must be provided on the body parameter of the http.NewRequest(method, urlStr string, body io.Reader) method, as a type that implements io.Reader interface.

Based on the sample code:

package main

import (
    "fmt"
    "net/http"
    "net/url"
    "strconv"
    "strings"
)

func main() {
    apiUrl := "https://api.com"
    resource := "/user/"
    data := url.Values{}
    data.Set("name", "foo")
    data.Set("surname", "bar")

    u, _ := url.ParseRequestURI(apiUrl)
    u.Path = resource
    urlStr := u.String() // "https://api.com/user/"

    client := &http.Client{}
    r, _ := http.NewRequest(http.MethodPost, urlStr, strings.NewReader(data.Encode())) // URL-encoded payload
    r.Header.Add("Authorization", "auth_token=\"XXXXXXX\"")
    r.Header.Add("Content-Type", "application/x-www-form-urlencoded")
    r.Header.Add("Content-Length", strconv.Itoa(len(data.Encode())))

    resp, _ := client.Do(r)
    fmt.Println(resp.Status)
}

resp.Status is 200 OK this way.

How to generate an openSSL key using a passphrase from the command line?

genrsa has been replaced by genpkey & when run manually in a terminal it will prompt for a password:

openssl genpkey -aes-256-cbc -algorithm RSA -out /etc/ssl/private/key.pem -pkeyopt rsa_keygen_bits:4096

However when run from a script the command will not ask for a password so to avoid the password being viewable as a process use a function in a shell script:

get_passwd() {
    local passwd=
    echo -ne "Enter passwd for private key: ? "; read -s passwd
    openssl genpkey -aes-256-cbc -pass pass:$passwd -algorithm RSA -out $PRIV_KEY -pkeyopt rsa_keygen_bits:$PRIV_KEYSIZE
}

PHP using Gettext inside <<<EOF string

As far as I can see, you just added heredoc by mistake
No need to use ugly heredoc syntax here.
Just remove it and everything will work:

<p>Hello</p>
<p><?= _("World"); ?></p>

Converting PKCS#12 certificate into PEM using OpenSSL

If you need a PEM file without any password you can use this solution.

Just copy and paste the private key and the certificate to the same file and save as .pem.

The file will look like:

-----BEGIN PRIVATE KEY-----
............................
............................
-----END PRIVATE KEY-----
-----BEGIN CERTIFICATE-----
...........................
...........................
-----END CERTIFICATE-----

That's the only way I found to upload certificates to Cisco devices for HTTPS.

How do I discard unstaged changes in Git?

In my opinion,

git clean -df

should do the trick. As per Git documentation on git clean

git-clean - Remove untracked files from the working tree

Description

Cleans the working tree by recursively removing files that are not under version control, starting from the current directory.

Normally, only files unknown to Git are removed, but if the -x option is specified, ignored files are also removed. This can, for example, be useful to remove all build products.

If any optional ... arguments are given, only those paths are affected.

Options

-d Remove untracked directories in addition to untracked files. If an untracked directory is managed by a different Git repository, it is not removed by default. Use -f option twice if you really want to remove such a directory.

-f --force If the Git configuration variable clean.requireForce is not set to false, git clean will refuse to run unless given -f, -n or -i.

deleting folder from java

You should delete the file in the folder first , then the folder.This way you will recursively call the method.

Rounding a number to the nearest 5 or 10 or X

For a strict Visual Basic approach, you can convert the floating-point value to an integer to round to said integer. VB is one of the rare languages that rounds on type conversion (most others simply truncate.)

Multiples of 5 or x can be done simply by dividing before and multiplying after the round.

If you want to round and keep decimal places, Math.round(n, d) would work.

CSS transition effect makes image blurry / moves image 1px, in Chrome?

You need to apply 3d transform to the element, so it will get its own composite layer. For instance:

.element{
    -webkit-transform: translateZ(0);
    transform: translateZ(0);
}

or

.element{
    -webkit-transform: translate3d(0,0,0);
    transform: translate3d(0,0,0);
}

More about layer creation criteria you can read right here: Accelerated Rendering in Chrome


An explanation:

Examples (hover green box):

When you use any transition on your element it cause browser to recalculate styles, then re-layout your content even if transition property is visual (in my examples it is an opacity) and finaly paint an element:

screenshot

The issue here is re-layout of the content that can make an effect of "dancing" or "blinking" elements on the page while transition happens. If you will go to settings, check "Show composite layers" checkbox and then apply 3d transform to an element, you will see that it gets it's own layer which outlined with orange border.

screenshot

After element gets its own layer, browser just needs to composite layers on transition without re-layout or even paint operations so problem have to be solved:

screenshot

Eclipse - no Java (JRE) / (JDK) ... no virtual machine

First go to computer then properties then advanced system settings then advanced

(3rd menu)

and then click environment variables button at the bottom.

To path in environment variables you add:

C:\Program Files\Java\jdk1.8.0_102\bin\;C:\Program Files\Java\jdk1.8.0_102\lib\; 

and the error will go away. This is the best one.

The other way is to copy the jre folder (C:\Program Files\Java\jre1.8.0_102) to

E:\eclipse-jee-indigo-SR2-win32\eclipse

folder. Then the error will go away.

What is the most compatible way to install python modules on a Mac?

Your question is already three years old and there are some details not covered in other answers:

Most people I know use HomeBrew or MacPorts, I prefer MacPorts because of its clean cut of what is a default Mac OS X environment and my development setup. Just move out your /opt folder and test your packages with a normal user Python environment

MacPorts is only portable within Mac, but with easy_install or pip you will learn how to setup your environment in any platform (Win/Mac/Linux/Bsd...). Furthermore it will always be more up to date and with more packages

I personally let MacPorts handle my Python modules to keep everything updated. Like any other high level package manager (ie: apt-get) it is much better for the heavy lifting of modules with lots of binary dependencies. There is no way I would build my Qt bindings (PySide) with easy_install or pip. Qt is huge and takes a lot to compile. As soon as you want a Python package that needs a library used by non Python programs, try to avoid easy_install or pip

At some point you will find that there are some packages missing within MacPorts. I do not believe that MacPorts will ever give you the whole CheeseShop. For example, recently I needed the Elixir module, but MacPorts only offers py25-elixir and py26-elixir, no py27 version. In cases like these you have:

pip-2.7 install --user elixir

( make sure you always type pip-(version) )

That will build an extra Python library in your home dir. Yes, Python will work with more than one library location: one controlled by MacPorts and a user local one for everything missing within MacPorts.

Now notice that I favor pip over easy_install. There is a good reason you should avoid setuptools and easy_install. Here is a good explanation and I try to keep away from them. One very useful feature of pip is giving you a list of all the modules (along their versions) that you installed with MacPorts, easy_install and pip itself:

pip-2.7 freeze

If you already started using easy_install, don't worry, pip can recognize everything done already by easy_install and even upgrade the packages installed with it.

If you are a developer keep an eye on virtualenv for controlling different setups and combinations of module versions. Other answers mention it already, what is not mentioned so far is the Tox module, a tool for testing that your package installs correctly with different Python versions.

Although I usually do not have version conflicts, I like to have virtualenv to set up a clean environment and get a clear view of my packages dependencies. That way I never forget any dependencies in my setup.py

If you go for MacPorts be aware that multiple versions of the same package are not selected anymore like the old Debian style with an extra python_select package (it is still there for compatibility). Now you have the select command to choose which Python version will be used (you can even select the Apple installed ones):

$  port select python
Available versions for python:
    none
    python25-apple
    python26-apple
    python27 (active)
    python27-apple
    python32

$ port select python python32

Add tox on top of it and your programs should be really portable

Get first element from a dictionary

For anyone coming to this that wants a linq-less way to get an element from a dictionary

var d = new Dictionary<string, string>();
d.Add("a", "b");
var e = d.GetEnumerator();
e.MoveNext();
var anElement = e.Current;
// anElement/e.Current is a KeyValuePair<string,string>
// where Key = "a", Value = "b"

I'm not sure if this is implementation specific, but if your Dictionary doesn't have any elements, Current will contain a KeyValuePair<string, string> where both the key and value are null.

(I looked at the logic behind linq's First method to come up with this, and tested it via LinqPad 4)

How to get all count of mongoose model?

As said before, you code will not work the way it is. A solution to that would be using a callback function, but if you think it would carry you to a 'Callback hell', you can search for "Promisses".

A possible solution using a callback function:

//DECLARE  numberofDocs OUT OF FUNCTIONS
     var  numberofDocs;
     userModel.count({}, setNumberofDocuments); //this search all DOcuments in a Collection

if you want to search the number of documents based on a query, you can do this:

 userModel.count({yourQueryGoesHere}, setNumberofDocuments);

setNumberofDocuments is a separeted function :

var setNumberofDocuments = function(err, count){ 
        if(err) return handleError(err);

        numberofDocs = count;

      };

Now you can get the number of Documents anywhere with a getFunction:

     function getNumberofDocs(){
           return numberofDocs;
        }
 var number = getNumberofDocs();

In addition , you use this asynchronous function inside a synchronous one by using a callback, example:

function calculateNumberOfDoc(someParameter, setNumberofDocuments){

       userModel.count({}, setNumberofDocuments); //this search all DOcuments in a Collection

       setNumberofDocuments(true);


} 

Hope it can help others. :)

Rails: How to run `rails generate scaffold` when the model already exists?

I had this challenge when working on a Rails 6 API application in Ubuntu 20.04.

I had already existing models, and I needed to generate corresponding controllers for the models and also add their allowed attributes in the controller params.

Here's how I did it:

I used the rails generate scaffold_controller to get it done.

I simply ran the following commands:

rails generate scaffold_controller School name:string logo:json motto:text address:text

rails generate scaffold_controller Program name:string logo:json school:references

This generated the corresponding controllers for the models and also added their allowed attributes in the controller params, including the foreign key attributes.

create  app/controllers/schools_controller.rb
invoke  test_unit
create    test/controllers/schools_controller_test.rb

create  app/controllers/programs_controller.rb
invoke  test_unit
create    test/controllers/programs_controller_test.rb

That's all.

I hope this helps

What is the difference between npm install and npm run build?

NPM in 2019

npm build no longer exists. You must call npm run build now. More info below.

TLDR;

npm install: installs dependencies, then calls the install from the package.json scripts field.

npm run build: runs the build field from the package.json scripts field.


NPM Scripts Field

https://docs.npmjs.com/misc/scripts

There are many things you can put into the npm package.json scripts field. Check out the documentation link above more above the lifecycle of the scripts - most have pre and post hooks that you can run scripts before/after install, publish, uninstall, test, start, stop, shrinkwrap, version.


To Complicate Things

  • npm install is not the same as npm run install
  • npm install installs package.json dependencies, then runs the package.json scripts.install
    • (Essentially calls npm run install after dependencies are installed.
  • npm run install only runs the package.json scripts.install, it will not install dependencies.
  • npm build used to be a valid command (used to be the same as npm run build) but it no longer is; it is now an internal command. If you run it you'll get: npm WARN build npm build called with no arguments. Did you mean to npm run-script build? You can read more on the documentation: https://docs.npmjs.com/cli/build

Extra Notes

There are still two top level commands that will run scripts, they are:

  • npm start which is the same as npm run start
  • npm test ==> npm run test

Failed loading english.pickle with nltk.data.load

nltk have its pre-trained tokenizer models. Model is downloading from internally predefined web sources and stored at path of installed nltk package while executing following possible function calls.

E.g. 1 tokenizer = nltk.data.load('nltk:tokenizers/punkt/english.pickle')

E.g. 2 nltk.download('punkt')

If you call above sentence in your code, Make sure you have internet connection without any firewall protections.

I would like to share some more better alter-net way to resolve above issue with more better deep understandings.

Please follow following steps and enjoy english word tokenization using nltk.

Step 1: First download the "english.pickle" model following web path.

Goto link "http://www.nltk.org/nltk_data/" and click on "download" at option "107. Punkt Tokenizer Models"

Step 2: Extract the downloaded "punkt.zip" file and find the "english.pickle" file from it and place in C drive.

Step 3: copy paste following code and execute.

from nltk.data import load
from nltk.tokenize.treebank import TreebankWordTokenizer

sentences = [
    "Mr. Green killed Colonel Mustard in the study with the candlestick. Mr. Green is not a very nice fellow.",
    "Professor Plum has a green plant in his study.",
    "Miss Scarlett watered Professor Plum's green plant while he was away from his office last week."
]

tokenizer = load('file:C:/english.pickle')
treebank_word_tokenize = TreebankWordTokenizer().tokenize

wordToken = []
for sent in sentences:
    subSentToken = []
    for subSent in tokenizer.tokenize(sent):
        subSentToken.extend([token for token in treebank_word_tokenize(subSent)])

    wordToken.append(subSentToken)

for token in wordToken:
    print token

Let me know, if you face any problem

How to iterate over a std::map full of strings in C++

Note that the result of dereferencing an std::map::iterator is an std::pair. The values of first and second are not functions, they are variables.

Change:

iter->first()

to

iter->first

Ditto with iter->second.

Regular expression for a hexadecimal number?

Not a big deal, but most regex engines support the POSIX character classes, and there's [:xdigit:] for matching hex characters, which is simpler than the common 0-9a-fA-F stuff.

So, the regex as requested (ie. with optional 0x) is: /(0x)?[[:xdigit:]]+/

Error when using scp command "bash: scp: command not found"

Issue is with remote server, can you login to the remote server and check if "scp" works

probable causes: - scp is not in path - openssh client not installed correctly

for more details http://www.linuxquestions.org/questions/linux-newbie-8/bash-scp-command-not-found-920513/

tqdm in Jupyter Notebook prints new progress bars repeatedly

This is an alternative answer for the case where tqdm_notebook doesn't work for you.

Given the following example:

from time import sleep
from tqdm import tqdm

values = range(3)
with tqdm(total=len(values)) as pbar:
    for i in values:
        pbar.write('processed: %d' %i)
        pbar.update(1)
        sleep(1)

The output would look something like this (progress would show up red):

  0%|          | 0/3 [00:00<?, ?it/s]
processed: 1
 67%|¦¦¦¦¦¦?   | 2/3 [00:01<00:00,  1.99it/s]
processed: 2
100%|¦¦¦¦¦¦¦¦¦¦| 3/3 [00:02<00:00,  1.53it/s]
processed: 3

The problem is that the output to stdout and stderr are processed asynchronously and separately in terms of new lines.

If say Jupyter receives on stderr the first line and then the "processed" output on stdout. Then once it receives an output on stderr to update the progress, it wouldn't go back and update the first line as it would only update the last line. Instead it will have to write a new line.

Workaround 1, writing to stdout

One workaround would be to output both to stdout instead:

import sys
from time import sleep
from tqdm import tqdm

values = range(3)
with tqdm(total=len(values), file=sys.stdout) as pbar:
    for i in values:
        pbar.write('processed: %d' % (1 + i))
        pbar.update(1)
        sleep(1)

The output will change to (no more red):

processed: 1   | 0/3 [00:00<?, ?it/s]
processed: 2   | 0/3 [00:00<?, ?it/s]
processed: 3   | 2/3 [00:01<00:00,  1.99it/s]
100%|¦¦¦¦¦¦¦¦¦¦| 3/3 [00:02<00:00,  1.53it/s]

Here we can see that Jupyter doesn't seem to clear until the end of the line. We could add another workaround for that by adding spaces. Such as:

import sys
from time import sleep
from tqdm import tqdm

values = range(3)
with tqdm(total=len(values), file=sys.stdout) as pbar:
    for i in values:
        pbar.write('processed: %d%s' % (1 + i, ' ' * 50))
        pbar.update(1)
        sleep(1)

Which gives us:

processed: 1                                                  
processed: 2                                                  
processed: 3                                                  
100%|¦¦¦¦¦¦¦¦¦¦| 3/3 [00:02<00:00,  1.53it/s]

Workaround 2, set description instead

It might in general be more straight forward not to have two outputs but update the description instead, e.g.:

import sys
from time import sleep
from tqdm import tqdm

values = range(3)
with tqdm(total=len(values), file=sys.stdout) as pbar:
    for i in values:
        pbar.set_description('processed: %d' % (1 + i))
        pbar.update(1)
        sleep(1)

With the output (description updated while it's processing):

processed: 3: 100%|¦¦¦¦¦¦¦¦¦¦| 3/3 [00:02<00:00,  1.53it/s]

Conclusion

You can mostly get it to work fine with plain tqdm. But if tqdm_notebook works for you, just use that (but then you'd probably not read that far).

What is /var/www/html?

/var/www/html is just the default root folder of the web server. You can change that to be whatever folder you want by editing your apache.conf file (usually located in /etc/apache/conf) and changing the DocumentRoot attribute (see http://httpd.apache.org/docs/current/mod/core.html#documentroot for info on that)

Many hosts don't let you change these things yourself, so your mileage may vary. Some let you change them, but only with the built in admin tools (cPanel, for example) instead of via a command line or editing the raw config files.

Python Error: "ValueError: need more than 1 value to unpack"

You have to pass the arguments in the terminal in order to store them in 'argv'. This variable holds the arguments you pass to your Python script when you run it. It later unpacks the arguments and store them in different variables you specify in the program e.g.

script, first, second = argv
print "Your file is:", script
print "Your first entry is:", first
print "Your second entry is:" second

Then in your command line you have to run your code like this,

$python ex14.py Hamburger Pizza

Your output will look like this:

Your file is: ex14.py
Your first entry is: Hamburger
Your second entry is: Pizza

Check whether a cell contains a substring

For those who would like to do this using a single function inside the IF statement, I use

=IF(COUNTIF(A1,"*TEXT*"),TrueValue,FalseValue)

to see if the substring TEXT is in cell A1

[NOTE: TEXT needs to have asterisks around it]

Multiple inputs on one line

Yes, you can.

From cplusplus.com:

Because these functions are operator overloading functions, the usual way in which they are called is:

   strm >> variable;

Where strm is the identifier of a istream object and variable is an object of any type supported as right parameter. It is also possible to call a succession of extraction operations as:

   strm >> variable1 >> variable2 >> variable3; //...

which is the same as performing successive extractions from the same object strm.

Just replace strm with cin.

How to sort in mongoose?

Chaining with the query builder interface in Mongoose 4.

// Build up a query using chaining syntax. Since no callback is passed this will create an instance of Query.
var query = Person.
    find({ occupation: /host/ }).
    where('name.last').equals('Ghost'). // find each Person with a last name matching 'Ghost'
    where('age').gt(17).lt(66).
    where('likes').in(['vaporizing', 'talking']).
    limit(10).
    sort('-occupation'). // sort by occupation in decreasing order
    select('name occupation'); // selecting the `name` and `occupation` fields


// Excute the query at a later time.
query.exec(function (err, person) {
    if (err) return handleError(err);
    console.log('%s %s is a %s.', person.name.first, person.name.last, person.occupation) // Space Ghost is a talk show host
})

See the docs for more about queries.

shared global variables in C

You put the declaration in a header file, e.g.

 extern int my_global;

In one of your .c files you define it at global scope.

int my_global;

Every .c file that wants access to my_global includes the header file with the extern in.

How to make join queries using Sequelize on Node.js

While the accepted answer isn't technically wrong, it doesn't answer the original question nor the follow up question in the comments, which was what I came here looking for. But I figured it out, so here goes.

If you want to find all Posts that have Users (and only the ones that have users) where the SQL would look like this:

SELECT * FROM posts INNER JOIN users ON posts.user_id = users.id

Which is semantically the same thing as the OP's original SQL:

SELECT * FROM posts, users WHERE posts.user_id = users.id

then this is what you want:

Posts.findAll({
  include: [{
    model: User,
    required: true
   }]
}).then(posts => {
  /* ... */
});

Setting required to true is the key to producing an inner join. If you want a left outer join (where you get all Posts, regardless of whether there's a user linked) then change required to false, or leave it off since that's the default:

Posts.findAll({
  include: [{
    model: User,
//  required: false
   }]
}).then(posts => {
  /* ... */
});

If you want to find all Posts belonging to users whose birth year is in 1984, you'd want:

Posts.findAll({
  include: [{
    model: User,
    where: {year_birth: 1984}
   }]
}).then(posts => {
  /* ... */
});

Note that required is true by default as soon as you add a where clause in.

If you want all Posts, regardless of whether there's a user attached but if there is a user then only the ones born in 1984, then add the required field back in:

Posts.findAll({
  include: [{
    model: User,
    where: {year_birth: 1984}
    required: false,
   }]
}).then(posts => {
  /* ... */
});

If you want all Posts where the name is "Sunshine" and only if it belongs to a user that was born in 1984, you'd do this:

Posts.findAll({
  where: {name: "Sunshine"},
  include: [{
    model: User,
    where: {year_birth: 1984}
   }]
}).then(posts => {
  /* ... */
});

If you want all Posts where the name is "Sunshine" and only if it belongs to a user that was born in the same year that matches the post_year attribute on the post, you'd do this:

Posts.findAll({
  where: {name: "Sunshine"},
  include: [{
    model: User,
    where: ["year_birth = post_year"]
   }]
}).then(posts => {
  /* ... */
});

I know, it doesn't make sense that somebody would make a post the year they were born, but it's just an example - go with it. :)

I figured this out (mostly) from this doc:

How to use font-family lato?

Please put this code in head section

<link href='http://fonts.googleapis.com/css?family=Lato:400,700' rel='stylesheet' type='text/css'>

and use font-family: 'Lato', sans-serif; in your css. For example:

h1 {
    font-family: 'Lato', sans-serif;
    font-weight: 400;
}

Or you can use manually also

Generate .ttf font from fontSquiral

and can try this option

    @font-face {
        font-family: "Lato";
        src: url('698242188-Lato-Bla.eot');
        src: url('698242188-Lato-Bla.eot?#iefix') format('embedded-opentype'),
        url('698242188-Lato-Bla.svg#Lato Black') format('svg'),
        url('698242188-Lato-Bla.woff') format('woff'),
        url('698242188-Lato-Bla.ttf') format('truetype');
        font-weight: normal;
        font-style: normal;
}

Called like this

body {
  font-family: 'Lato', sans-serif;
}

Convert Long into Integer

Assuming not null longVal

Integer intVal = ((Number)longVal).intValue();

It works for example y you get an Object that can be an Integer or a Long. I know that is ugly, but it happens...

how to save DOMPDF generated content to file?

<?php
$content='<table width="100%" border="1">';
$content.='<tr><th>name</th><th>email</th><th>contact</th><th>address</th><th>city</th><th>country</th><th>postcode</th></tr>';
for ($index = 0; $index < 10; $index++) { 
$content.='<tr><td>nadim</td><td>[email protected]</td><td>7737033665</td><td>247 dehligate</td><td>udaipur</td><td>india</td><td>313001</td></tr>';
}
$content.='</table>';
//$html = file_get_contents('pdf.php');
if(isset($_POST['pdf'])){
    require_once('./dompdf/dompdf_config.inc.php');
    $dompdf = new DOMPDF;                        
    $dompdf->load_html($content);
    $dompdf->render();
    $dompdf->stream("hello.pdf");
}
?>
<html>
    <body>
        <form action="#" method="post">        
            <button name="pdf" type="submit">export</button>
        <table width="100%" border="1">
           <tr><th>name</th><th>email</th><th>contact</th><th>address</th><th>city</th><th>country</th><th>postcode</th></tr>         
            <?php for ($index = 0; $index < 10; $index++) { ?>
            <tr><td>nadim</td><td>[email protected]</td><td>7737033665</td><td>247 dehligate</td><td>udaipur</td><td>india</td><td>313001</td></tr>
            <?php } ?>            
        </table>        
        </form>        
    </body>
</html>

HTML Canvas Full Screen

function resize() {
    canvas.width = window.innerWidth;
    canvas.height = window.innerHeight;
    render();
}
window.addEventListener('resize', resize, false); resize();
function render() { // draw to screen here
}

https://jsfiddle.net/jy8k6hfd/2/