Programs & Examples On #Camlp4

CamlP4 is a parsing and pretty-printing framework for Objective Caml, often used as a preprocessor to extend OCaml syntax.

How to pick element inside iframe using document.getElementById

You need to make sure the frame is fully loaded the best way to do it is to use onload:

<iframe id="nesgt" src="" onload="custom()"></iframe>

function custom(){
    document.getElementById("nesgt").contentWindow.document;
    }

this function will run automatically when the iframe is fully loaded.

it could be done with setTimeout but we can't get the exact time of the frame load.

hope this helps someone.

Bootstrap combining rows (rowspan)

Note: This was for Bootstrap 2 (relevant when the question was asked).

You can accomplish this by using row-fluid to make a fluid (percentage) based row inside an existing block.

<div class="row">
   <div class="span5">span5</div>
   <div class="span3">span3</div>
   <div class="span2">
      <div class="row-fluid">
         <div class="span12">span2</div>
         <div class="span12">span2</div>
      </div>
   </div>
   <div class="span2">span2</div>
</div>
<div class="row">
   <div class="span6">
      <div class="row-fluid">
         <div class="span12">span6</div>
         <div class="span12">span6</div>
      </div>
   </div>
   <div class="span6">span6</div>
</div>

Here's a JSFiddle example.

I did notice that there was an odd left margin that appears (or does not appear) for the spans inside of the row-fluid after the first one. This can be fixed with a small CSS tweak (it's the same CSS that is applied to the first child, expanded to those past the first child):

.row-fluid [class*="span"] {
    margin-left: 0;
}

Should I size a textarea with CSS width / height or HTML cols / rows attributes?

The answer is "yes". That is, you should use both. Without rows and cols (and there are default values even if you don't use them explicitly) the textarea is unusably small if CSS is disabled or overriden by a user stylesheet. Always keep accessibility concerns in mind. That being said, if your stylesheet is allowed to control the appearance of the textarea, you will generally wind up with something that looks a whole lot better, fits into the overall page design well, and that can resize to keep up with user input (within the limits of good taste, of course).

How can I trim leading and trailing white space?

As of R 3.2.0 a new function was introduced for removing leading/trailing white spaces:

trimws()

See: Remove Leading/Trailing Whitespace

What is the difference between synchronous and asynchronous programming (in node.js)

Sync Programming

Programming languages like C, C#, Java are sync programming, what so ever you write will be execute in order of your writing.

-GET DATA FROM SQL.
//Suppose fetching data take 500 msec

-PERFORM SOME OTHER FUNCTION.
//Performing some function other will take 100 msec, but execution of other 
//task start only when fetching of sql data done (i.e some other function 
//can execute only after first in process job finishes).

-TOTAL TIME OF EXECUTION IS ALWAYS GREATER THAN (500 + 100 + processing time) 
msec

Async

NodeJs comes up with async feature, it's non-blocking in nature, suppose in any I/O task which is taking time (fetching, writing, reading), nodejs won't kept idle and wait for the task to be finish, it'll start executing next tasks in the queue, and whenever that time taking task completed it will notify using callback. Following example will help:

//Nodejs uses callback pattern to describe functions.
//Please read callback pattern to understand this example

//Suppose following function (I/O involved) took 500 msec
function timeConsumingFunction(params, callback){
  //GET DATA FROM SQL
  getDataFromSql(params, function(error, results){
    if(error){
      callback(error);
    }
    else{
      callback(null, results);
    }
  })
}

//Suppose following function is non-blocking and took 100 msec
function someOtherTask(){
  //some other task
  console.log('Some Task 1');
  console.log('Some Task 2');
}

console.log('Execution Start');

//Start With this function
timeConsumingFunction(params, function(error, results){
    if(error){
      console.log('Error')
    }
    else{
      console.log('Successfull'); 
    }
  })

//As (suppose) timeConsumingFunction took 500 msec, 
//As NodeJs is non-blocking, rather than remain idle for 500 msec, it will start 
//execute following function immediately
someOtherTask();

In Short, Output is as:

Execution Start
//Roughly after 105 msec (5 msec it'll take in processing)
Some Task 1
Some Task 2
//Roughly After 510 msec
Error/Successful //depends on success and failure of DB function execution

Difference is clear where sync will definitely take more than 600 (500 + 100 + processing time) msec, async saves time.

Check if a string is not NULL or EMPTY

You don't necessarily have to use the [string]:: prefix. This works in the same way:

if ($version)
{
    $request += "/" + $version
}

A variable that is null or empty string evaluates to false.

What is String pool in Java?

This prints true (even though we don't use equals method: correct way to compare strings)

    String s = "a" + "bc";
    String t = "ab" + "c";
    System.out.println(s == t);

When compiler optimizes your string literals, it sees that both s and t have same value and thus you need only one string object. It's safe because String is immutable in Java.
As result, both s and t point to the same object and some little memory saved.

Name 'string pool' comes from the idea that all already defined string are stored in some 'pool' and before creating new String object compiler checks if such string is already defined.

No restricted globals

For me I had issues with history and location... As the accepted answer using window before history and location (i.e) window.history and window.location solved mine

Conversion of a varchar data type to a datetime data type resulted in an out-of-range value in SQL query

Try ISDATE() function in SQL Server. If 1, select valid date. If 0 selects invalid dates.

SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)  
FROM AuditTrail 
WHERE ISDATE(LoginTime) = 1

EDIT :

As per your update i need to extract the date only and remove the time, then you could simply use the inner CONVERT

SELECT CONVERT(VARCHAR, LoginTime, 101) FROM AuditTrail 

or

SELECT LEFT(LoginTime,10) FROM AuditTrail

EDIT 2 :

The major reason for the error will be in your date in WHERE clause.ie,

SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)  
FROM AuditTrail
where CAST(CONVERT(VARCHAR, LoginTime, 101) AS DATE) <= 
CAST('06/18/2012' AS DATE)

will be different from

SELECT cast(CONVERT(varchar, LoginTime, 101) as datetime)  
FROM AuditTrail
where CAST(CONVERT(VARCHAR, LoginTime, 101) AS DATE) <= 
CAST('18/06/2012' AS DATE)

CONCLUSION

In EDIT 2 the first query tries to filter in mm/dd/yyyy format, while the second query tries to filter in dd/mm/yyyy format. Either of them will fail and throws error

The conversion of a varchar data type to a datetime data type resulted in an out-of-range value.

So please make sure to filter date either with mm/dd/yyyy or with dd/mm/yyyy format, whichever works in your db.

List passed by ref - help me explain this behaviour

There are two parts of memory allocated for an object of reference type. One in stack and one in heap. The part in stack (aka a pointer) contains reference to the part in heap - where the actual values are stored.

When ref keyword is not use, just a copy of part in stack is created and passed to the method - reference to same part in heap. Therefore if you change something in heap part, those change will stayed. If you change the copied pointer - by assign it to refer to other place in heap - it will not affect to origin pointer outside of the method.

How do I draw a circle in iOS Swift?

Swift 4 version of accepted answer:

@IBDesignable
class CircledDotView: UIView {

    @IBInspectable var mainColor: UIColor = .white {
        didSet { print("mainColor was set here") }
    }
    @IBInspectable var ringColor: UIColor = .black {
        didSet { print("bColor was set here") }
    }
    @IBInspectable var ringThickness: CGFloat = 4 {
        didSet { print("ringThickness was set here") }
    }

    @IBInspectable var isSelected: Bool = true

    override func draw(_ rect: CGRect) {
        let dotPath = UIBezierPath(ovalIn: rect)
        let shapeLayer = CAShapeLayer()
        shapeLayer.path = dotPath.cgPath
        shapeLayer.fillColor = mainColor.cgColor
        layer.addSublayer(shapeLayer)

        if (isSelected) {
            drawRingFittingInsideView(rect: rect)
        }
    }

    internal func drawRingFittingInsideView(rect: CGRect) {
        let hw: CGFloat = ringThickness / 2
        let circlePath = UIBezierPath(ovalIn: rect.insetBy(dx: hw, dy: hw))

        let shapeLayer = CAShapeLayer()
        shapeLayer.path = circlePath.cgPath
        shapeLayer.fillColor = UIColor.clear.cgColor
        shapeLayer.strokeColor = ringColor.cgColor
        shapeLayer.lineWidth = ringThickness
        layer.addSublayer(shapeLayer)
    }
}

How to get HQ youtube thumbnails?

Depending on the resolution you need, you can use a different URL:

Default Thumbnail

http://img.youtube.com/vi/<insert-youtube-video-id-here>/default.jpg

High Quality Thumbnail

http://img.youtube.com/vi/<insert-youtube-video-id-here>/hqdefault.jpg

Medium Quality

http://img.youtube.com/vi/<insert-youtube-video-id-here>/mqdefault.jpg

Standard Definition

http://img.youtube.com/vi/<insert-youtube-video-id-here>/sddefault.jpg

Maximum Resolution

http://img.youtube.com/vi/<insert-youtube-video-id-here>/maxresdefault.jpg

Note: it's a work-around if you don't want to use the YouTube Data API. Furthermore not all videos have the thumbnail images set, so the above method doesn’t work.

AFNetworking Post Request

For AFNetworking 3.0 and Swift. Maybe we can use like this:

let configutation = NSURLSessionConfiguration.defaultSessionConfiguration()
manager = AFHTTPSessionManager(sessionConfiguration: configutation)

let urlString = "url"
manager.POST(urlString, parameters: [params here], progress: nil, success: { (dataTask: NSURLSessionDataTask, response: AnyObject?) -> Void in
        print(dataTask)
        print(response)
        }) { (dataTask: NSURLSessionDataTask?, error: NSError) -> Void in
        print(error)
}

Hope this will help other find answer like me!

Find closest previous element jQuery

see http://api.jquery.com/prev/

var link = $("#me").parent("div").prev("h3").find("b");
alert(link.text());

see http://jsfiddle.net/gBwLq/

Notepad++ Regular expression find and delete a line

Using the "Replace all" functionality, you can delete a line directly by ending your pattern with:

  • If your file have linux (LF) line ending : $\n?
  • If your file have windows (CRLF) line ending : $(\r\n)?

For instance, in your case :

.*#RedirectMatch Permanent.*$\n?

Reporting Services permissions on SQL Server R2 SSRS

You need to set permissions within SSRS in two places to give yourself initial access. The set-up program only gives access to Builtin\Administrators, to gain access in order to do this you need to right click you browser link and choose Run as administrator.

  1. Run internet explorer as Administrator
  2. Open the report Manager URL, this time you should get in
  3. Go to Site Settings in the top right
  4. Click Security then New Role Assignment
  5. Enter your domain\username and select System Administrator, click ok
  6. Add other users as necessary
  7. Click home, Folder Settings, then New Role Assignment
  8. Enter your domain\username and select Content Manager, click ok
  9. Add other users as necessary
  10. Re-open internet explorer (non-admin) and recheck the url.

Android view layout_width - how to change programmatically?

You can set height and width like this also:

viewinstance.setLayoutParams(new LayoutParams(width, height));

Access Control Request Headers, is added to header in AJAX request with jQuery

Try to use the rack-cors gem. And add the header field in your Ajax call.

How do I exit the Vim editor?

Vim has three modes of operation: Input mode, Command mode & Ex mode.

Input mode - everything that you type, all keystrokes are echoed on the screen.

Command mode or Escape mode - everything that you type in this mode is interpreted as a command.

Ex mode - this is another editor, ex. It is a line editor. It works per line or based on a range of lines. In this mode, a : appears at the bottom of the screen. This is the ex editor.

In order to exit Vim, you can exit while you are in either the ex mode or in the command mode. You cannot exit Vim when you are in input mode.

Exiting from ex mode

  1. You need to be sure that you are in the Command mode. To do that, simply press the Esc key.

  2. Go to the ex mode by pressing the : key

  3. Use any of the following combinations in ex mode to exit:

    :q - quit :q! - quit without saving :wq - save & quit or write & quit :wq! - same as wq, but force write in case file permissions are readonly :x - write & quit :qa - quit all. useful when multiple files are opened like: vim abc.txt xyz.txt

Exiting from command mode

  1. Press the escape key. You probably have done this already if you are in command mode.

  2. Press capital ZZ (shift zz) - save & exit

  3. Press capital ZQ (shift zq) - exit without saving.

Adding value to input field with jQuery

You can do it as below.

$(this).prev('input').val("hello world");

Live Demo

How does one generate a random number in Apple's Swift language?

Edit for Swift 4.2

Starting in Swift 4.2, instead of using the imported C function arc4random_uniform(), you can now use Swift’s own native functions.

// Generates integers starting with 0 up to, and including, 10
Int.random(in: 0 ... 10)

You can use random(in:) to get random values for other primitive values as well; such as Int, Double, Float and even Bool.

Swift versions < 4.2

This method will generate a random Int value between the given minimum and maximum

func randomInt(min: Int, max: Int) -> Int {
    return min + Int(arc4random_uniform(UInt32(max - min + 1)))
}

How to run binary file in Linux

full path for binary file. For example: /home/vitaliy2034/binary_file_name. Or use directive "./+binary_file_name". './' in unix system it return full path to directory, in which you open terminal(shell). I hope it helps. Sorry, for my english language)

Python popen command. Wait until the command is finished

Depending on how you want to work your script you have two options. If you want the commands to block and not do anything while it is executing, you can just use subprocess.call.

#start and block until done
subprocess.call([data["om_points"], ">", diz['d']+"/points.xml"])

If you want to do things while it is executing or feed things into stdin, you can use communicate after the popen call.

#start and process things, then wait
p = subprocess.Popen([data["om_points"], ">", diz['d']+"/points.xml"])
print "Happens while running"
p.communicate() #now wait plus that you can send commands to process

As stated in the documentation, wait can deadlock, so communicate is advisable.

jQuery or JavaScript auto click

You haven't provided your javascript code, but the usual cause of this type of issue is not waiting till the page is loaded. Remember that most javascript is executed before the DOM is loaded, so code trying to manipulate it won't work.

To run code after the page has finished loading, use the $(document).ready callback:

$(document).ready(function(){
  $('#some-id').trigger('click');
});

Remove DEFINER clause from MySQL Dumps

I don't think there is a way to ignore adding DEFINERs to the dump. But there are ways to remove them after the dump file is created.

  1. Open the dump file in a text editor and replace all occurrences of DEFINER=root@localhost with an empty string ""

  2. Edit the dump (or pipe the output) using perl:

    perl -p -i.bak -e "s/DEFINER=\`\w.*\`@\`\d[0-3].*[0-3]\`//g" mydatabase.sql
    
  3. Pipe the output through sed:

    mysqldump ... | sed -e 's/DEFINER[ ]*=[ ]*[^*]*\*/\*/' > triggers_backup.sql
    

Counter exit code 139 when running, but gdb make it through

this error is also caused by null pointer reference. if you are using a pointer who is not initialized then it causes this error.

to check either a pointer is initialized or not you can try something like

Class *pointer = new Class();
if(pointer!=nullptr){
    pointer->myFunction();
}

How to hash some string with sha256 in Java?

import java.security.MessageDigest;

public class CodeSnippets {

 public static String getSha256(String value) {
    try{
        MessageDigest md = MessageDigest.getInstance("SHA-256");
        md.update(value.getBytes());
        return bytesToHex(md.digest());
    } catch(Exception ex){
        throw new RuntimeException(ex);
    }
 }
 private static String bytesToHex(byte[] bytes) {
    StringBuffer result = new StringBuffer();
    for (byte b : bytes) result.append(Integer.toString((b & 0xff) + 0x100, 16).substring(1));
    return result.toString();
 }
}

Why call super() in a constructor?

We can access super class elements by using super keyword

Consider we have two classes, Parent class and Child class, with different implementations of method foo. Now in child class if we want to call the method foo of parent class, we can do so by super.foo(); we can also access parent elements by super keyword.

    class parent {
    String str="I am parent";
    //method of parent Class
    public void foo() {
        System.out.println("Hello World " + str);
    }
}

class child extends parent {
    String str="I am child";
    // different foo implementation in child Class
    public void foo() {
        System.out.println("Hello World "+str);
    }

    // calling the foo method of parent class
    public void parentClassFoo(){
        super.foo();
    }

    // changing the value of str in parent class and calling the foo method of parent class
    public void parentClassFooStr(){
        super.str="parent string changed";
        super.foo();
    }
}


public class Main{
        public static void main(String args[]) {
            child obj = new child();
            obj.foo();
            obj.parentClassFoo();
            obj.parentClassFooStr();
        }
    }

The Network Adapter could not establish the connection when connecting with Oracle DB

Take a look at this post on Java Ranch:

http://www.coderanch.com/t/300287/JDBC/java/Io-Exception-Network-Adapter-could

"The solution for my "Io exception: The Network Adapter could not establish the connection" exception was to replace the IP of the database server to the DNS name."

RegEx for valid international mobile phone number

Even if you write a regular expression that matches exactly the subset "valid phone numbers" out of strings, there is no way to guarantee (by way of a regular expression) that they are valid mobile phone numbers. In several countries, mobile phone numbers are indistinguishable from landline phone numbers without at least a number plan lookup, and in some cases, even that won't help. For example, in Sweden, lots of people have "ported" their regular, landline-like phone number to their mobile phone. It's still the same number as they had before, but now it goes to a mobile phone instead of a landline.

Since valid phone numbers consist only of digits, I doubt that rolling your own would risk missing some obscure case of phone number at least. If you want to have better certainty, write a generator that takes a list of all valid country codes, and requires one of them at the beginning of the phone number to be matched by the generated regular expression.

Calendar.getInstance(TimeZone.getTimeZone("UTC")) is not returning UTC time

Try to use GMT instead of UTC. They refer to the same time zone, yet the name GMT is more common and might work.

Should you commit .gitignore into the Git repos?

Normally yes, .gitignore is useful for everyone who wants to work with the repository. On occasion you'll want to ignore more private things (maybe you often create LOG or something. In those cases you probably don't want to force that on anyone else.

select from one table, insert into another table oracle sql query

You will get useful information from here.

SELECT ticker
INTO quotedb
FROM tickerdb;

file_get_contents behind a proxy?

There's a similar post here: http://techpad.co.uk/content.php?sid=137 which explains how to do it.

function file_get_contents_proxy($url,$proxy){

    // Create context stream
    $context_array = array('http'=>array('proxy'=>$proxy,'request_fulluri'=>true));
    $context = stream_context_create($context_array);

    // Use context stream with file_get_contents
    $data = file_get_contents($url,false,$context);

    // Return data via proxy
    return $data;

}

NPM: npm-cli.js not found when running npm

This started happening for me after I installed GoogleChrome/puppeteer, the solution was to re-install npm:

$ npm i npm@latest

or

$ npm install npm@latest

Run git pull over all subdirectories

Original answer 2010:

If all of those directories are separate git repo, you should reference them as submodules.

That means your "origin" would be that remote repo 'plugins' which only contains references to subrepos 'cms', 'admin', 'chart'.

A git pull followed by a git submodule update would achieve what your are looking for.


Update January 2016:

With Git 2.8 (Q1 2016), you will be able to fetch submodules in parallel (!) with git fetch --recurse-submodules -j2.
See "How to speed up / parallelize downloads of git submodules using git clone --recursive?"

Most concise way to convert a Set<T> to a List<T>

Considering that we have Set<String> stringSet we can use following:

Plain Java

List<String> strList = new ArrayList<>(stringSet);

Guava

List<String> strList = Lists.newArrayList(stringSet);

Apache Commons

List<String> strList = new ArrayList<>();
CollectionUtils.addAll(strList, stringSet);

Java 10 (Unmodifiable List)

List<String> strList = List.copyOf(stringSet);
List<String> strList = stringSet.stream().collect(Collectors.toUnmodifiableList());

Java 8 (Modifiable Lists)

import static java.util.stream.Collectors.*;
List<String> stringList1 = stringSet.stream().collect(toList());

As per the doc for the method toList()

There are no guarantees on the type, mutability, serializability, or thread-safety of the List returned; if more control over the returned List is required, use toCollection(Supplier).

So if we need a specific implementation e.g. ArrayList we can get it this way:

List<String> stringList2 = stringSet.stream().
                              collect(toCollection(ArrayList::new));

Java 8 (Unmodifiable Lists)

We can make use of Collections::unmodifiableList method and wrap the list returned in previous examples. We can also write our own custom method as:

class ImmutableCollector {
    public static <T> Collector<T, List<T>, List<T>> toImmutableList(Supplier<List<T>> supplier) {
            return Collector.of( supplier, List::add, (left, right) -> {
                        left.addAll(right);
                        return left;
                    }, Collections::unmodifiableList);
        }
}

And then use it as:

List<String> stringList3 = stringSet.stream()
             .collect(ImmutableCollector.toImmutableList(ArrayList::new)); 

Another possibility is to make use of collectingAndThen method which allows some final transformation to be done before returning result:

    List<String> stringList4 = stringSet.stream().collect(collectingAndThen(
      toCollection(ArrayList::new),Collections::unmodifiableList));

One point to note is that the method Collections::unmodifiableList returns an unmodifiable view of the specified list, as per doc. An unmodifiable view collection is a collection that is unmodifiable and is also a view onto a backing collection. Note that changes to the backing collection might still be possible, and if they occur, they are visible through the unmodifiable view. But the collector method Collectors.unmodifiableList returns truly immutable list in Java 10.

R memory management / cannot allocate vector of size n Mb

Consider whether you really need all this data explicitly, or can the matrix be sparse? There is good support in R (see Matrix package for e.g.) for sparse matrices.

Keep all other processes and objects in R to a minimum when you need to make objects of this size. Use gc() to clear now unused memory, or, better only create the object you need in one session.

If the above cannot help, get a 64-bit machine with as much RAM as you can afford, and install 64-bit R.

If you cannot do that there are many online services for remote computing.

If you cannot do that the memory-mapping tools like package ff (or bigmemory as Sascha mentions) will help you build a new solution. In my limited experience ff is the more advanced package, but you should read the High Performance Computing topic on CRAN Task Views.

Finding all possible combinations of numbers to reach a given sum

Swift 3 conversion of Java solution: (by @JeremyThompson)

protocol _IntType { }
extension Int: _IntType {}


extension Array where Element: _IntType {

    func subsets(to: Int) -> [[Element]]? {

        func sum_up_recursive(_ numbers: [Element], _ target: Int, _ partial: [Element], _ solution: inout [[Element]]) {

            var sum: Int = 0
            for x in partial {
                sum += x as! Int
            }

            if sum == target {
                solution.append(partial)
            }

            guard sum < target else {
                return
            }

            for i in stride(from: 0, to: numbers.count, by: 1) {

                var remaining = [Element]()

                for j in stride(from: i + 1, to: numbers.count, by: 1) {
                    remaining.append(numbers[j])
                }

                var partial_rec = [Element](partial)
                partial_rec.append(numbers[i])

                sum_up_recursive(remaining, target, partial_rec, &solution)
            }
        }

        var solutions = [[Element]]()
        sum_up_recursive(self, to, [Element](), &solutions)

        return solutions.count > 0 ? solutions : nil
    }

}

usage:

let numbers = [3, 9, 8, 4, 5, 7, 10]

if let solution = numbers.subsets(to: 15) {
    print(solution) // output: [[3, 8, 4], [3, 5, 7], [8, 7], [5, 10]]
} else {
    print("not possible")
}

Update one MySQL table with values from another

UPDATE tobeupdated
INNER JOIN original ON (tobeupdated.value = original.value)
SET tobeupdated.id = original.id

That should do it, and really its doing exactly what yours is. However, I prefer 'JOIN' syntax for joins rather than multiple 'WHERE' conditions, I think its easier to read

As for running slow, how large are the tables? You should have indexes on tobeupdated.value and original.value

EDIT: we can also simplify the query

UPDATE tobeupdated
INNER JOIN original USING (value)
SET tobeupdated.id = original.id

USING is shorthand when both tables of a join have an identical named key such as id. ie an equi-join - http://en.wikipedia.org/wiki/Join_(SQL)#Equi-join

Set Page Title using PHP

It'll be tricky to rearrange your code to make this work, but I'll try :)

So, put this at the top of your code:

<?php require_once('mysql.php'); ?>

The top of the file should look like:

<?php require_once('mysql.php'); ?>
<html>
    <head>

    <meta name="keywords" content="Mac user Ultan Casey TheCompuGeeks UltanKC">
    <title>Ultan.me - <?php echo htmlspecialchars($title); ?> </title>

Then, create a file called mysql.php in the same directory that the file which contains the code you quoted is in.

Put this is mysql.php:

<?php
mysql_connect ('localhost', 'root', 'root');
mysql_select_db ('ultankc');

if (!isset($_GET['id']) || !is_numeric($_GET['id'])) {
    die("Invalid ID specified.");
}

$id = (int)$_GET['id'];
$sql = "SELECT * FROM php_blog WHERE id='$id' LIMIT 1";

$result = mysql_query($sql) or print ("Can't select entry from table php_blog.<br />" .       $sql . "<br />" . mysql_error());

$res = mysql_fetch_assoc($result); 

$date = date("l F d Y", $res['timestamp']);
$title = $res['title'];
$entry = $res['entry'];
$get_categories = mysql_query("SELECT * FROM php_blog_categories WHERE `category_id` = $res['category']");
$category = mysql_fetch_array($get_categories);

?>

Well, hope that helped :)

CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true

If you are using express you can use the cors package to allow CORS like so instead of writing your middleware;

var express = require('express')
, cors = require('cors')
, app = express();

app.use(cors());

app.get(function(req,res){ 
  res.send('hello');
});

JAVA_HOME directory in Linux

If $JAVA_HOME is defined in your environment...

$ echo $JAVA_HOME
$ # I am not lucky...

You can guess it from the classes that are loaded.

$ java -showversion -verbose 2>&1 | head -1
[Opened /usr/lib/jvm/java-1.7.0-openjdk-1.7.0.75.x86_64/jre/lib/rt.jar]

This method ensures you find the correct jdk/jre used in case there are multiple installations.

Or using strace:

$ strace -e open java -showversion 2>&1 | grep -m1 /jre/
open("/usr/lib/jvm/java-1.7.0-openjdk-1.7.0.75.x86_64/jre/bin/../lib/amd64/jli/tls/x86_64/libpthread.so.0", O_RDONLY) = -1 ENOENT (No such file or directory)

Delete duplicate records from a SQL table without a primary key

create unique clustered index Employee_idx
on Employee ( EmpId,EmpSSN )
with ignore_dup_key

You can drop the index if you don't need it.

How do I get values from a SQL database into textboxes using C#?

The line reader.Read() is missing in your code. You should add it. It is the function which actually reads data from the database:

string conString = "Data Source=localhost;Initial Catalog=LoginScreen;Integrated Security=True";
SqlConnection con = new SqlConnection(conString);

string selectSql = "select * from Pending_Tasks";
SqlCommand com = new SqlCommand(selectSql, con);

try
{
    con.Open();

    using (SqlDataReader read = cmd.ExecuteReader())
    {
        while(reader.Read())
        {
            CustID.Text = (read["Customer_ID"].ToString());
            CustName.Text = (read["Customer_Name"].ToString());
            Add1.Text = (read["Address_1"].ToString());
            Add2.Text = (read["Address_2"].ToString());
            PostBox.Text = (read["Postcode"].ToString());
            PassBox.Text = (read["Password"].ToString());
            DatBox.Text = (read["Data_Important"].ToString());
            LanNumb.Text = (read["Landline"].ToString());
            MobNumber.Text = (read["Mobile"].ToString());
            FaultRep.Text = (read["Fault_Report"].ToString());
        }
    }
}
finally
{
    con.Close();
}

EDIT : This code works supposing you want to write the last record to your textboxes. If you want to apply a different scenario, like for example to read all the records from database and to change data in the texboxes when you click the Next button, you should create and use your own Model, or you can store data in the DataTable and refer to them later if you wish.

How do I convert a numpy array to (and display) an image?

Supplement for doing so with matplotlib. I found it handy doing computer vision tasks. Let's say you got data with dtype = int32

from matplotlib import pyplot as plot
import numpy as np

fig = plot.figure()
ax = fig.add_subplot(1, 1, 1)
# make sure your data is in H W C, otherwise you can change it by
# data = data.transpose((_, _, _))
data = np.zeros((512,512,3), dtype=np.int32)
data[256,256] = [255,0,0]
ax.imshow(data.astype(np.uint8))

How to see query history in SQL Server Management Studio

you can use "Automatically generate script on every save", if you are using management studio. This is not certainly logging. Check if useful for you.. ;)

DB2 Timestamp select statement

@bhamby is correct. By leaving the microseconds off of your timestamp value, your query would only match on a usagetime of 2012-09-03 08:03:06.000000

If you don't have the complete timestamp value captured from a previous query, you can specify a ranged predicate that will match on any microsecond value for that time:

...WHERE id = 1 AND usagetime BETWEEN '2012-09-03 08:03:06' AND '2012-09-03 08:03:07'

or

...WHERE id = 1 AND usagetime >= '2012-09-03 08:03:06' 
   AND usagetime < '2012-09-03 08:03:07'

Parsing HTML using Python

Compared to the other parser libraries lxml is extremely fast:

And with cssselect it’s quite easy to use for scraping HTML pages too:

from lxml.html import parse
doc = parse('http://www.google.com').getroot()
for div in doc.cssselect('a'):
    print '%s: %s' % (div.text_content(), div.get('href'))

lxml.html Documentation

What is secret key for JWT based authentication and how to generate it?

You can write your own generator. The secret key is essentially a byte array. Make sure that the string that you convert to a byte array is base64 encoded.

In Java, you could do something like this.

String key = "random_secret_key";
String base64Key = DatatypeConverter.printBase64Binary(key.getBytes());
byte[] secretBytes = DatatypeConverter.parseBase64Binary(base64Key);

How to set auto increment primary key in PostgreSQL?

Try this command:

ALTER TABLE your_table ADD COLUMN key_column BIGSERIAL PRIMARY KEY;

Try it with the same DB-user as the one you have created the table.

ProgressDialog spinning circle

Put this XML to show only the wheel:

<ProgressBar
    android:indeterminate="true"
    android:id="@+id/marker_progress"
    style="?android:attr/progressBarStyle"
    android:layout_height="50dp" />

jQuery $(".class").click(); - multiple elements, click event once

when you click div with addproduct class one event is fired for that particular element, not five. you're doing something wrong in you code if event is fired 5 times.

Style input type file?

Here's a simple css only solution, that creates a consistent target area, and lets you style your faux elements however you like.

The basic idea is this:

  1. Have two "fake" elements (a text input/link) as siblings to your real file input. Absolutely position them so they're exactly on top of your target area.
  2. Wrap your file input with a div. Set overflow to hidden (so the file input doesn't spill out), and make it exactly the size that you want your target area to be.
  3. Set opacity to 0 on the file input so it's hidden but still clickable. Give it a large font size so the you can click on all portions of the target area.

Here's the jsfiddle: http://jsfiddle.net/gwwar/nFLKU/

<form>
    <input id="faux" type="text" placeholder="Upload a file from your computer" />
    <a href="#" id="browse">Browse </a>
    <div id="wrapper">
        <input id="input" size="100" type="file" />
    </div>
</form>

check if array is empty (vba excel)

Adding into this: it depends on what your array is defined as. Consider:

dim a() as integer
dim b() as string
dim c() as variant

'these doesn't work
if isempty(a) then msgbox "integer arrays can be empty"
if isempty(b) then msgbox "string arrays can be empty"

'this is because isempty can only be tested on classes which have an .empty property

'this do work
if isempty(c) then msgbox "variants can be empty"

So, what can we do? In VBA, we can see if we can trigger an error and somehow handle it, for example

dim a() as integer
dim bEmpty as boolean

bempty=false

on error resume next
bempty=not isnumeric(ubound(a))
on error goto 0

But this is really clumsy... A nicer solution is to declare a boolean variable (a public or module level is best). When the array is first initialised, then set this variable. Because it's a variable declared at the same time, if it loses it's value, then you know that you need to reinitialise your array. However, if it is initialised, then all you're doing is checking the value of a boolean, which is low cost. It depends on whether being low cost matters, and if you're going to be needing to check it often.

option explicit

'declared at module level
dim a() as integer
dim aInitialised as boolean

sub DoSomethingWithA()
if not aInitialised then InitialiseA
'you can now proceed confident that a() is intialised
end sub

sub InitialiseA()
'insert code to do whatever is required to initialise A
'e.g. 
redim a(10)
a(1)=123
'...
aInitialised=true
end sub

The last thing you can do is create a function; which in this case will need to be dependent on the clumsy on error method.

function isInitialised(byref a() as variant) as boolean
isInitialised=false
on error resume next
isinitialised=isnumeric(ubound(a))
end function

Build error, This project references NuGet

First I would check if your MusicKarma project has Microsoft.Net.Compilers in its packages.config file. If not then you could remove everything to do with that NuGet package from your MusicKarma.csproj.

If you are using the Microsoft.Net.Compilers NuGet package then my guess is that the path is incorrect. Looking at the directory name in the error message I would guess that the MusicKarma solution file (.sln) is in the same directory as the MusicKarma.csproj. If so then the packages directory is probably wrong since by default the packages directory would be inside the solution directory. So I am assuming that your packages directory is:

C:\Users\Bryan\Documents\Visual Studio 2015\Projects\MusicKarma\packages

Whilst your MusicKarma.csproj file is looking for the props file in:

C:\Users\Bryan\Documents\Visual Studio 2015\Projects\packages\Microsoft.Net.Compilers.1.1.1\build

So if that is the case then you can fix the problem by editing the path in your MusicKarma.csproj file or by reinstalling the NuGet package.

How to generate a random string of a fixed length in Go?

/*
    korzhao
*/

package rand

import (
    crand "crypto/rand"
    "math/rand"
    "sync"
    "time"
    "unsafe"
)

// Doesn't share the rand library globally, reducing lock contention
type Rand struct {
    Seed int64
    Pool *sync.Pool
}

var (
    MRand    = NewRand()
    randlist = []byte("abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890")
)

// init random number generator
func NewRand() *Rand {
    p := &sync.Pool{New: func() interface{} {
        return rand.New(rand.NewSource(getSeed()))
    },
    }
    mrand := &Rand{
        Pool: p,
    }
    return mrand
}

// get the seed
func getSeed() int64 {
    return time.Now().UnixNano()
}

func (s *Rand) getrand() *rand.Rand {
    return s.Pool.Get().(*rand.Rand)
}
func (s *Rand) putrand(r *rand.Rand) {
    s.Pool.Put(r)
}

// get a random number
func (s *Rand) Intn(n int) int {
    r := s.getrand()
    defer s.putrand(r)

    return r.Intn(n)
}

//  bulk get random numbers
func (s *Rand) Read(p []byte) (int, error) {
    r := s.getrand()
    defer s.putrand(r)

    return r.Read(p)
}

func CreateRandomString(len int) string {
    b := make([]byte, len)
    _, err := MRand.Read(b)
    if err != nil {
        return ""
    }
    for i := 0; i < len; i++ {
        b[i] = randlist[b[i]%(62)]
    }
    return *(*string)(unsafe.Pointer(&b))
}

24.0 ns/op 16 B/op 1 allocs/

How to sort a dataFrame in python pandas by two or more columns?

As of the 0.17.0 release, the sort method was deprecated in favor of sort_values. sort was completely removed in the 0.20.0 release. The arguments (and results) remain the same:

df.sort_values(['a', 'b'], ascending=[True, False])

You can use the ascending argument of sort:

df.sort(['a', 'b'], ascending=[True, False])

For example:

In [11]: df1 = pd.DataFrame(np.random.randint(1, 5, (10,2)), columns=['a','b'])

In [12]: df1.sort(['a', 'b'], ascending=[True, False])
Out[12]:
   a  b
2  1  4
7  1  3
1  1  2
3  1  2
4  3  2
6  4  4
0  4  3
9  4  3
5  4  1
8  4  1

As commented by @renadeen

Sort isn't in place by default! So you should assign result of the sort method to a variable or add inplace=True to method call.

that is, if you want to reuse df1 as a sorted DataFrame:

df1 = df1.sort(['a', 'b'], ascending=[True, False])

or

df1.sort(['a', 'b'], ascending=[True, False], inplace=True)

using lodash .groupBy. how to add your own keys for grouped output?

Example groupBy and sum of a column using Lodash 4.17.4

   var data = [{
                "name": "jim",
                "color": "blue",
                "amount": 22
                }, {
                "name": "Sam",
                "color": "blue",
                "amount": 33
                }, {
               "name": "eddie",
               "color": "green",
               "amount": 77
              }];

      var result = _(data)
                   .groupBy(x => x.color)
                   .map((value, key) => 
                   ({color: key,
                    totalamount: _.sumBy(value,'amount'),
                    users: value})).value();

                    console.log(result);

Converting Integers to Roman Numerals - Java

Alternative solution based on the OP's own solution by utilizing an enum. Additionally, a parser and round-trip tests are included.

public class RomanNumber {
    public enum Digit {
        M(1000, 3),
        CM(900, 1),
        D(500, 1),
        CD(400, 1),
        C(100, 3),
        XC(90, 1),
        L(50, 1),
        XL(40, 1),
        X(10, 3),
        IX(9, 1),
        V(5, 1),
        IV(4, 1),
        I(1, 3);

        public final int value;
        public final String symbol = name();
        public final int maxArity;

        private Digit(int value, int maxArity) {
            this.value = value;
            this.maxArity = maxArity;
        }
    }

    private static final Digit[] DIGITS = Digit.values();

    public static String of(int number) {
        if (number < 1 || 3999 < number) {
            throw new IllegalArgumentException(String.format(
                    "Roman numbers are only defined for numbers between 1 and 3999 (%d was given)",
                    number
            ));
        }

        StringBuilder sb = new StringBuilder();
        for (Digit digit : DIGITS) {
            int value = digit.value;
            String symbol = digit.symbol;

            while (number >= value) {
                sb.append(symbol);
                number -= value;
            }
        }

        return sb.toString();
    }

    public static int parse(String roman) {
        if (roman.isEmpty()) {
            throw new NumberFormatException("The empty string does not comprise a valid Roman number");
        }

        int number = 0;
        int offset = 0;
        for (Digit digit : DIGITS) {
            int value = digit.value;
            int maxArity = digit.maxArity;
            String symbol = digit.symbol;

            for (int i = 0; i < maxArity && roman.startsWith(symbol, offset); i++) {
                number += value;
                offset += symbol.length();
            }
        }
        if (offset != roman.length()) {
            throw new NumberFormatException(String.format(
                    "The string '%s' does not comprise a valid Roman number",
                    roman
            ));
        }
        return number;
    }

    /** TESTS */
    public static void main(String[] args) {

        /* Demonstrating round-trip for all possible inputs. */

        for (int number = 1; number <= 3999; number++) {
            String roman = of(number);
            int parsed = parse(roman);
            if (parsed != number) {
                System.err.format(
                        "ERROR: number: %d, roman: %s, parsed: %d\n",
                        number,
                        roman,
                        parsed
                );
            }
        }

        /* Some illegal inputs. */

        int[] illegalNumbers = { -1, 0, 4000, 4001 };
        for (int illegalNumber : illegalNumbers) {
            try {
                of(illegalNumber);
                System.err.format(
                        "ERROR: Expected failure on number %d\n",
                        illegalNumber
                );
            } catch (IllegalArgumentException e) {
                // Failed as expected.
            }
        }

        String[] illegalRomans = { "MMMM", "CDCD", "IM", "T", "", "VV", "DM" };
        for (String illegalRoman : illegalRomans) {
            try {
                parse(illegalRoman);
                System.err.format(
                        "ERROR: Expected failure on roman %s\n",
                        illegalRoman
                );
            } catch (NumberFormatException e) {
                // Failed as expected.
            }
        }
    }
}

How to mention C:\Program Files in batchfile

Surround the script call with "", generally it's good practices to do so with filepath.

"C:\Program Files"

Although for this particular name you probably should use environment variable like this :

"%ProgramFiles%\batch.cmd"

or for 32 bits program on 64 bit windows :

"%ProgramFiles(x86)%\batch.cmd"

How to get video duration, dimension and size in PHP?

If you have FFMPEG installed on your server (http://www.mysql-apache-php.com/ffmpeg-install.htm), it is possible to get the attributes of your video using the command "-vstats" and parsing the result with some regex - as shown in the example below. Then, you need the PHP funtion filesize() to get the size.

$ffmpeg_path = 'ffmpeg'; //or: /usr/bin/ffmpeg , or /usr/local/bin/ffmpeg - depends on your installation (type which ffmpeg into a console to find the install path)
$vid = 'PATH/TO/VIDEO'; //Replace here!

 if (file_exists($vid)) {

    $finfo = finfo_open(FILEINFO_MIME_TYPE);
    $mime_type = finfo_file($finfo, $vid); // check mime type
    finfo_close($finfo);

    if (preg_match('/video\/*/', $mime_type)) {

        $video_attributes = _get_video_attributes($vid, $ffmpeg_path);

        print_r('Codec: ' . $video_attributes['codec'] . '<br/>');

        print_r('Dimension: ' . $video_attributes['width'] . ' x ' . $video_attributes['height'] . ' <br/>');

        print_r('Duration: ' . $video_attributes['hours'] . ':' . $video_attributes['mins'] . ':'
                . $video_attributes['secs'] . '.' . $video_attributes['ms'] . '<br/>');

        print_r('Size:  ' . _human_filesize(filesize($vid)));

    } else {
        print_r('File is not a video.');
    }
} else {
    print_r('File does not exist.');
}

function _get_video_attributes($video, $ffmpeg) {

    $command = $ffmpeg . ' -i ' . $video . ' -vstats 2>&1';
    $output = shell_exec($command);

    $regex_sizes = "/Video: ([^,]*), ([^,]*), ([0-9]{1,4})x([0-9]{1,4})/"; // or : $regex_sizes = "/Video: ([^\r\n]*), ([^,]*), ([0-9]{1,4})x([0-9]{1,4})/"; (code from @1owk3y)
    if (preg_match($regex_sizes, $output, $regs)) {
        $codec = $regs [1] ? $regs [1] : null;
        $width = $regs [3] ? $regs [3] : null;
        $height = $regs [4] ? $regs [4] : null;
    }

    $regex_duration = "/Duration: ([0-9]{1,2}):([0-9]{1,2}):([0-9]{1,2}).([0-9]{1,2})/";
    if (preg_match($regex_duration, $output, $regs)) {
        $hours = $regs [1] ? $regs [1] : null;
        $mins = $regs [2] ? $regs [2] : null;
        $secs = $regs [3] ? $regs [3] : null;
        $ms = $regs [4] ? $regs [4] : null;
    }

    return array('codec' => $codec,
        'width' => $width,
        'height' => $height,
        'hours' => $hours,
        'mins' => $mins,
        'secs' => $secs,
        'ms' => $ms
    );
}

function _human_filesize($bytes, $decimals = 2) {
    $sz = 'BKMGTP';
    $factor = floor((strlen($bytes) - 1) / 3);
    return sprintf("%.{$decimals}f", $bytes / pow(1024, $factor)) . @$sz[$factor];
}

how to sync windows time from a ntp time server in command

If you just need to resync windows time, open an elevated command prompt and type:

w32tm /resync

C:\WINDOWS\system32>w32tm /resync 
Sending resync command to local computer 
The command completed successfully.

Angular 2 router no base href set

You can also use hash-based navigation by including the following in app.module.ts

import { LocationStrategy, HashLocationStrategy } from '@angular/common';

and by adding the following to the @NgModule({ ... })

@NgModule({
  ...
  providers:    [
      ProductService, {
          provide: LocationStrategy, useClass: HashLocationStrategy
      }
  ],
  ...
})

Angular 2 Development with TypeScript

“HashLocationStrategy—A hash sign (#) is added to the URL, and the URL segment after the hash uniquely identifies the route to be used as a web page fragment. This strategy works with all browsers, including the old ones.”

Excerpt From: Yakov Fain Anton Moiseev. “Angular 2 Development with TypeScript.”

Finding elements not in a list

No, z is undefined. item contains a list of integers.

I think what you're trying to do is this:

#z defined elsewhere
item = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]

for i in item:
  if i not in z: print i

As has been stated in other answers, you may want to try using sets.

Bloomberg Open API

I don't think so. The API's will provide access to delayed quotes, there is no way that real time data or tick data, will be provided for free.

What are the differences between B trees and B+ trees?

Define "much faster". Asymptotically they're about the same. The differences lie in how they make use of secondary storage. The Wikipedia articles on B-trees and B+trees look pretty trustworthy.

How to perform case-insensitive sorting in JavaScript?

myArray.sort(
  function(a, b) {
    if (a.toLowerCase() < b.toLowerCase()) return -1;
    if (a.toLowerCase() > b.toLowerCase()) return 1;
    return 0;
  }
);

EDIT: Please note that I originally wrote this to illustrate the technique rather than having performance in mind. Please also refer to answer @Ivan Krechetov for a more compact solution.

Get HTML code from website in C#

You can use WebClient to download the html for any url. Once you have the html, you can use a third-party library like HtmlAgilityPack to lookup values in the html as in below code -

public static string GetInnerHtmlFromDiv(string url)
    {
        string HTML;
        using (var wc = new WebClient())
        {
            HTML = wc.DownloadString(url);
        }
        var doc = new HtmlAgilityPack.HtmlDocument();
        doc.LoadHtml(HTML);
        
        HtmlNode element = doc.DocumentNode.SelectSingleNode("//div[@id='<div id here>']");
        if (element != null)
        {
            return element.InnerHtml.ToString();
        }   
        return null;            
    }

How to replace part of string by position?

ReplaceAt(int index, int length, string replace)

Here's an extension method that doesn't use StringBuilder or Substring. This method also allows the replacement string to extend past the length of the source string.

//// str - the source string
//// index- the start location to replace at (0-based)
//// length - the number of characters to be removed before inserting
//// replace - the string that is replacing characters
public static string ReplaceAt(this string str, int index, int length, string replace)
{
    return str.Remove(index, Math.Min(length, str.Length - index))
            .Insert(index, replace);
}

When using this function, if you want the entire replacement string to replace as many characters as possible, then set length to the length of the replacement string:

"0123456789".ReplaceAt(7, 5, "Hello") = "0123456Hello"

Otherwise, you can specify the amount of characters that will be removed:

"0123456789".ReplaceAt(2, 2, "Hello") = "01Hello456789"

If you specify the length to be 0, then this function acts just like the insert function:

"0123456789".ReplaceAt(4, 0, "Hello") = "0123Hello456789"

I guess this is more efficient since the StringBuilder class need not be initialized and since it uses more basic operations. Please correct me if I am wrong. :)

PreparedStatement with Statement.RETURN_GENERATED_KEYS

Not having a compiler by me right now, I'll answer by asking a question:

Have you tried this? Does it work?

long key = -1L;
PreparedStatement statement = connection.prepareStatement();
statement.executeUpdate(YOUR_SQL_HERE, PreparedStatement.RETURN_GENERATED_KEYS);
ResultSet rs = statement.getGeneratedKeys();
if (rs != null && rs.next()) {
    key = rs.getLong(1);
}

Disclaimer: Obviously, I haven't compiled this, but you get the idea.

PreparedStatement is a subinterface of Statement, so I don't see a reason why this wouldn't work, unless some JDBC drivers are buggy.

Multiple actions were found that match the request in Web Api

Without using actions the options would be:

  1. move one of the methods to a different controller, so that they don't clash.

  2. use just one method that takes the param, and if it's null call the other method from your code.

Regular expression for decimal number

In .NET, I recommend to dynamically build the regular expression with the decimal separator of the current cultural context:

using System.Globalization;

...

NumberFormatInfo nfi = NumberFormatInfo.CurrentInfo;
Regex re = new Regex("^(?\\d+(" 
                   + Regex.Escape(nfi.CurrencyDecimalSeparator) 
                   + "\\d{1,2}))$");

You might want to pimp the regexp by allowing 1000er separators the same way as the decimal separator.

Check if string ends with certain pattern

This is really simple, the String object has an endsWith method.

From your question it seems like you want either /, , or . as the delimiter set.

So:

String str = "This.is.a.great.place.to.work.";

if (str.endsWith(".work.") || str.endsWith("/work/") || str.endsWith(",work,"))
     // ... 

You can also do this with the matches method and a fairly simple regex:

if (str.matches(".*([.,/])work\\1$"))

Using the character class [.,/] specifying either a period, a slash, or a comma, and a backreference, \1 that matches whichever of the alternates were found, if any.

What's the right way to pass form element state to sibling/parent elements?

Five years later with introduction of React Hooks there is now much more elegant way of doing it with use useContext hook.

You define context in a global scope, export variables, objects and functions in the parent component and then wrap children in the App in a context provided and import whatever you need in child components. Below is a proof of concept.

import React, { useState, useContext } from "react";
import ReactDOM from "react-dom";
import styles from "./styles.css";

// Create context container in a global scope so it can be visible by every component
const ContextContainer = React.createContext(null);

const initialAppState = {
  selected: "Nothing"
};

function App() {
  // The app has a state variable and update handler
  const [appState, updateAppState] = useState(initialAppState);

  return (
    <div>
      <h1>Passing state between components</h1>

      {/* 
          This is a context provider. We wrap in it any children that might want to access
          App's variables.
          In 'value' you can pass as many objects, functions as you want. 
           We wanna share appState and its handler with child components,           
       */}
      <ContextContainer.Provider value={{ appState, updateAppState }}>
        {/* Here we load some child components */}
        <Book title="GoT" price="10" />
        <DebugNotice />
      </ContextContainer.Provider>
    </div>
  );
}

// Child component Book
function Book(props) {
  // Inside the child component you can import whatever the context provider allows.
  // Earlier we passed value={{ appState, updateAppState }}
  // In this child we need the appState and the update handler
  const { appState, updateAppState } = useContext(ContextContainer);

  function handleCommentChange(e) {
    //Here on button click we call updateAppState as we would normally do in the App
    // It adds/updates comment property with input value to the appState
    updateAppState({ ...appState, comment: e.target.value });
  }

  return (
    <div className="book">
      <h2>{props.title}</h2>
      <p>${props.price}</p>
      <input
        type="text"
        //Controlled Component. Value is reverse vound the value of the variable in state
        value={appState.comment}
        onChange={handleCommentChange}
      />
      <br />
      <button
        type="button"
        // Here on button click we call updateAppState as we would normally do in the app
        onClick={() => updateAppState({ ...appState, selected: props.title })}
      >
        Select This Book
      </button>
    </div>
  );
}

// Just another child component
function DebugNotice() {
  // Inside the child component you can import whatever the context provider allows.
  // Earlier we passed value={{ appState, updateAppState }}
  // but in this child we only need the appState to display its value
  const { appState } = useContext(ContextContainer);

  /* Here we pretty print the current state of the appState  */
  return (
    <div className="state">
      <h2>appState</h2>
      <pre>{JSON.stringify(appState, null, 2)}</pre>
    </div>
  );
}

const rootElement = document.body;
ReactDOM.render(<App />, rootElement);

You can run this example in the Code Sandbox editor.

Edit passing-state-with-context

Storage permission error in Marshmallow

Before starting your download check your runtime permissions and if you don't have permission the request permissions like this method

requestStoragePermission()

private void requestStoragePermission(){
    if (ActivityCompat.shouldShowRequestPermissionRationale(this, 
                android.Manifest.permission.READ_EXTERNAL_STORAGE))
        {

        }

        ActivityCompat.requestPermissions(this, 
            new String[]{Manifest.permission.READ_EXTERNAL_STORAGE},
            STORAGE_PERMISSION_CODE);
}

@Override
public void onRequestPermissionsResult(int requestCode, 
                @NonNull String[] permissions, 
                @NonNull int[] grantResults) {

    if(requestCode == STORAGE_PERMISSION_CODE){
        if(grantResults.length >0 && grantResults[0] == PackageManager.PERMISSION_GRANTED){
        }
        else{
            Toast.makeText(this,
                           "Oops you just denied the permission", 
                           Toast.LENGTH_LONG).show();
        }
    }
}

How to increase time in web.config for executing sql query

You should add the httpRuntime block and deal with executionTimeout (in seconds).

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
...
 <system.web>
   <httpRuntime executionTimeout="90" maxRequestLength="4096"
    useFullyQualifiedRedirectUrl="false"
    minFreeThreads="8"
    minLocalRequestFreeThreads="4"
    appRequestQueueLimit="100" />
 </system.web>
... 
</configuration>

For more information, please, see msdn page.

postgres default timezone

The time zone is a session parameter. So, you can change the timezone for the current session.

See the doc.

set timezone TO 'GMT';

Or, more closely following the SQL standard, use the SET TIME ZONE command. Notice two words for "TIME ZONE" where the code above uses a single word "timezone".

SET TIME ZONE 'UTC';

The doc explains the difference:

SET TIME ZONE extends syntax defined in the SQL standard. The standard allows only numeric time zone offsets while PostgreSQL allows more flexible time-zone specifications. All other SET features are PostgreSQL extensions.

What is the proper way to display the full InnerException?

I do:

namespace System {
  public static class ExtensionMethods {
    public static string FullMessage(this Exception ex) {
      if (ex is AggregateException aex) return aex.InnerExceptions.Aggregate("[ ", (total, next) => $"{total}[{next.FullMessage()}] ") + "]";
      var msg = ex.Message.Replace(", see inner exception.", "").Trim();
      var innerMsg = ex.InnerException?.FullMessage();
      if (innerMsg is object && innerMsg!=msg) msg = $"{msg} [ {innerMsg} ]";
      return msg;
    }
  }
}

This "pretty prints" all inner exceptions and also handles AggregateExceptions and cases where InnerException.Message is the same as Message

How to write a:hover in inline CSS?

You can do id by adding a class but never inline.

<style>.hover_pointer{cursor:pointer;}</style>
<div class="hover_pointer" style="font:bold 12pt Verdana;">Hello World</div>

2 lines but you can re-use the class everywhere.

Spring MVC: How to perform validation?

If you have same error handling logic for different method handlers, then you would end up with lots of handlers with following code pattern:

if (validation.hasErrors()) {
  // do error handling
}
else {
  // do the actual business logic
}

Suppose you're creating RESTful services and want to return 400 Bad Request along with error messages for every validation error case. Then, the error handling part would be same for every single REST endpoint that requires validation. Repeating that very same logic in every single handler is not so DRYish!

One way to solve this problem is to drop the immediate BindingResult after each To-Be-Validated bean. Now, your handler would be like this:

@RequestMapping(...)
public Something doStuff(@Valid Somebean bean) { 
    // do the actual business logic
    // Just the else part!
}

This way, if the bound bean was not valid, a MethodArgumentNotValidException will be thrown by Spring. You can define a ControllerAdvice that handles this exception with that same error handling logic:

@ControllerAdvice
public class ErrorHandlingControllerAdvice {
    @ExceptionHandler(MethodArgumentNotValidException.class)
    public SomeErrorBean handleValidationError(MethodArgumentNotValidException ex) {
        // do error handling
        // Just the if part!
    }
}

You still can examine the underlying BindingResult using getBindingResult method of MethodArgumentNotValidException.

How to delete last character in a string in C#?

string source;
// source gets initialized
string dest;
if (source.Length > 0)
{
    dest = source.Substring(0, source.Length - 1);
}

Assert that a method was called in a Python unit test

I'm not aware of anything built-in. It's pretty simple to implement:

class assertMethodIsCalled(object):
    def __init__(self, obj, method):
        self.obj = obj
        self.method = method

    def called(self, *args, **kwargs):
        self.method_called = True
        self.orig_method(*args, **kwargs)

    def __enter__(self):
        self.orig_method = getattr(self.obj, self.method)
        setattr(self.obj, self.method, self.called)
        self.method_called = False

    def __exit__(self, exc_type, exc_value, traceback):
        assert getattr(self.obj, self.method) == self.called,
            "method %s was modified during assertMethodIsCalled" % self.method

        setattr(self.obj, self.method, self.orig_method)

        # If an exception was thrown within the block, we've already failed.
        if traceback is None:
            assert self.method_called,
                "method %s of %s was not called" % (self.method, self.obj)

class test(object):
    def a(self):
        print "test"
    def b(self):
        self.a()

obj = test()
with assertMethodIsCalled(obj, "a"):
    obj.b()

This requires that the object itself won't modify self.b, which is almost always true.

Disabling and enabling a html input button

While not directly related to the question, if you hop onto this question looking to disable something other than the typical input elements button, input, textarea, the syntax won't work.

To disable a div or a span, use setAttribute

document.querySelector('#somedivorspan').setAttribute('disabled', true);

P.S: Gotcha, only call this if you intend to disable. A bug in chrome Version 83 causes this to always disable even when the second parameter is false.

Targeting .NET Framework 4.5 via Visual Studio 2010

I have been struggling with VS2010/DNFW 4.5 integration and have finally got this working. Starting in VS 2008, a cache of assemblies was introduced that is used by Visual Studio called the "Referenced Assemblies". This file cache for VS 2010 is located at \Reference Assemblies\Microsoft\Framework.NetFramework\v4.0. Visual Studio loads framework assemblies from this location instead of from the framework installation directory. When Microsoft says that VS 2010 does not support DNFW 4.5 what they mean is that this directory does not get updated when DNFW 4.5 is installed. Once you have replace the files in this location with the updated DNFW 4.5 files, you will find that VS 2010 will happily function with DNFW 4.5.

How can I preview a merge in git?

Maybe this can help you ? git-diff-tree - Compares the content and mode of blobs found via two tree objects

how to convert current date to YYYY-MM-DD format with angular 2

Here is a very nice and compact way to do this, you can also change this function as your case needs:

result: 03.11.2017

//get date now function
    getNowDate() {
    //return string
    var returnDate = "";
    //get datetime now
    var today = new Date();
    //split
    var dd = today.getDate();
    var mm = today.getMonth() + 1; //because January is 0! 
    var yyyy = today.getFullYear();
    //Interpolation date
    if (dd < 10) {
        returnDate += `0${dd}.`;
    } else {
        returnDate += `${dd}.`;
    }

    if (mm < 10) {
        returnDate += `0${mm}.`;
    } else {
        returnDate += `${mm}.`;
    }
    returnDate += yyyy;
    return returnDate;
}

Android Studio Emulator and "Process finished with exit code 0"

I solved this issue by offing all of advantage features of my graphics card in its settings(Nvidaa type). It started to throw such hanging error less a lot. But finally I found a simplier way: In avd manager you need to put less resolution for the avd. Say, 400x800. Then I reenabled graphics card features again and now it runs all ok. (I suspect my graphics card or cpu are weaker than needed. )

How do I get a substring of a string in Python?

You've got it right there except for "end". It's called slice notation. Your example should read:

new_sub_string = myString[2:]

If you leave out the second parameter it is implicitly the end of the string.

sort dict by value python

no lambda method

# sort dictionary by value
d = {'a1': 'fsdfds', 'g5': 'aa3432ff', 'ca':'zz23432'}
def getkeybyvalue(d,i):
    for k, v in d.items():
        if v == i:
            return (k)

sortvaluelist = sorted(d.values())
sortresult ={}
for i1 in sortvaluelist:   
    key = getkeybyvalue(d,i1)
    sortresult[key] = i1
print ('=====sort by value=====')
print (sortresult)
print ('=======================')

In Typescript, what is the ! (exclamation mark / bang) operator when dereferencing a member?

non-null assertion operator

With the non-null assertion operator we can tell the compiler explicitly that an expression has value other than null or undefined. This is can be useful when the compiler cannot infer the type with certainty but we more information than the compiler.

Example

TS code

function simpleExample(nullableArg: number | undefined | null) {
   const normal: number = nullableArg; 
    //   Compile err: 
    //   Type 'number | null | undefined' is not assignable to type 'number'.
    //   Type 'undefined' is not assignable to type 'number'.(2322)

   const operatorApplied: number = nullableArg!; 
    // compiles fine because we tell compiler that null | undefined are excluded 
}

Compiled JS code

Note that the JS does not know the concept of the Non-null assertion operator since this is a TS feature

_x000D_
_x000D_
"use strict";
function simpleExample(nullableArg) {
    const normal = nullableArg;
    const operatorApplied = nullableArg;
 }
_x000D_
_x000D_
_x000D_

No resource identifier found for attribute '...' in package 'com.app....'

I just changed:

xmlns:app="http://schemas.android.com/apk/res-auto" 

to:

xmlns:app="http://schemas.android.com/apk/lib/com.app.chasebank"

and it stopped generating the errors, com.app.chasebank is the name of the package. It should work according to this Stack Overflow : No resource identifier found for attribute 'adSize' in package 'com.google.example' main.xml

How to check whether mod_rewrite is enable on server?

I know this question is old but if you can edit your Apache configuration file to AllowOverride All from AllowOverride None

<Directory "${SRVROOT}/htdocs">
    #
    # Possible values for the Options directive are "None", "All",
    # or any combination of:
    #   Indexes Includes FollowSymLinks SymLinksifOwnerMatch ExecCGI MultiViews
    #
    # Note that "MultiViews" must be named *explicitly* --- "Options All"
    # doesn't give it to you.
    #
    # The Options directive is both complicated and important.  Please see
    # http://httpd.apache.org/docs/2.4/mod/core.html#options
    # for more information.
    #
    Options Indexes FollowSymLinks

    #
    # AllowOverride controls what directives may be placed in .htaccess files.
    # It can be "All", "None", or any combination of the keywords:
    #   AllowOverride FileInfo AuthConfig Limit
    #
    AllowOverride All

    #
    # Controls who can get stuff from this server.
    #
    Require all granted
</Directory>

Questions every good PHP Developer should be able to answer

Admittedly, I stole this question from somewhere else (can't remember where I read it any more) but thought it was funny:

Q: What is T_PAAMAYIM_NEKUDOTAYIM?
A: Its the scope resolution operator (double colon)

An experienced PHP'er immediately knows what it means. Less experienced (and not Hebrew) developers may want to read this.

But more serious questions now:


Q: What is the cause of this warning: 'Warning: Cannot modify header information - headers already sent', and what is a good practice to prevent it?
A: Cause: body data was sent, causing headers to be sent too.
Prevention: Be sure to execute header specific code first before you output any body data. Be sure you haven't accidentally sent out whitespace or any other characters.


Q: What is wrong with this query: "SELECT * FROM table WHERE id = $_POST[ 'id' ]"?
A: 1. It is vulnarable to SQL injection. Never use user input directly in queries. Sanitize it first. Preferebly use prepared statements (PDO) 2. Don't select all columns (*), but specify every single column. This is predominantly ment to prevent queries hogging up memory when for instance a BLOB column is added at some point in the future.


Q: What is wrong with this if statement: if( !strpos( $haystack, $needle ) ...?
A: strpos returns the index position of where it first found the $needle, which could be 0. Since 0 also resolves to false the solution is to use strict comparison: if( false !== strpos( $haystack, $needle )...


Q: What is the preferred way to write this if statement, and why?
if( 5 == $someVar ) or if( $someVar == 5 )
A: The former, as it prevents accidental assignment of 5 to $someVar when you forget to use 2 equalsigns ($someVar = 5), and will cause an error, the latter won't.


Q: Given this code:

function doSomething( &$arg )
{
    $return = $arg;
    $arg += 1;
    return $return;
}

$a = 3;
$b = doSomething( $a );

...what is the value of $a and $b after the function call and why?
A: $a is 4 and $b is 3. The former because $arg is passed by reference, the latter because the return value of the function is a copy of (not a reference to) the initial value of the argument.


OOP specific

Q: What is the difference between public, protected and private in a class definition?
A: public makes a class member available to "everyone", protected makes the class member available to only itself and derived classes, private makes the class member only available to the class itself.


Q: What is wrong with this code:

class SomeClass
{
    protected $_someMember;

    public function __construct()
    {
        $this->_someMember = 1;
    }

    public static function getSomethingStatic()
    {
        return $this->_someMember * 5; // here's the catch
    }
}

A: Static methods don't have access to $this, because static methods can be executed without instantiating a class.


Q: What is the difference between an interface and an abstract class?
A: An interface defines a contract between an implementing class is and an object that calls the interface. An abstract class pre-defines certain behaviour for classes that will extend it. To a certain degree this can also be considered a contract, since it garantuees certain methods to exist.


Q: What is wrong with classes that predominantly define getters and setters, that map straight to it's internal members, without actually having methods that execute behaviour?
A: This might be a code smell since the object acts as an ennobled array, without much other use.


Q: Why is PHP's implementation of the use of interfaces sub-optimal?
A: PHP doesn't allow you to define the expected return type of the method's, which essentially renders interfaces pretty useless. :-P

Advantages of SQL Server 2008 over SQL Server 2005?

There are new features added. But, you will have to see if it is worth the upgrade. Some good improvements in Management Studio 2008 though, especially the intellisense for the Query Editor.

Vector of structs initialization

Create vector, push_back element, then modify it as so:

struct subject {
    string name;
    int marks;
    int credits;
};


int main() {
    vector<subject> sub;

    //Push back new subject created with default constructor.
    sub.push_back(subject());

    //Vector now has 1 element @ index 0, so modify it.
    sub[0].name = "english";

    //Add a new element if you want another:
    sub.push_back(subject());

    //Modify its name and marks.
    sub[1].name = "math";
    sub[1].marks = 90;
}

You cant access a vector with [#] until an element exists in the vector at that index. This example populates the [#] and then modifies it afterward.

Why doesn't margin:auto center an image?

You need to render it as block level;

img {
   display: block;
   width: auto;
   margin: auto;
}

How to set dialog to show in full screen?

based on this link , the correct answer (which i've tested myself) is:

put this code in the constructor or the onCreate() method of the dialog:

getWindow().setLayout(WindowManager.LayoutParams.MATCH_PARENT,
                WindowManager.LayoutParams.MATCH_PARENT);

in addition , set the style of the dialog to :

<style name="full_screen_dialog">
    <item name="android:windowFrame">@null</item>
    <item name="android:windowIsFloating">true</item>
    <item name="android:windowContentOverlay">@null</item>
    <item name="android:windowAnimationStyle">@android:style/Animation.Dialog</item>
    <item name="android:windowSoftInputMode">stateUnspecified|adjustPan</item>
</style>

this could be achieved via the constructor , for example :

public FullScreenDialog(Context context)
{
  super(context, R.style.full_screen_dialog);
  ...

EDIT: an alternative to all of the above would be to set the style to android.R.style.ThemeOverlay and that's it.

RGB to hex and hex to RGB

My example =)

_x000D_
_x000D_
color: {_x000D_
            toHex: function(num){_x000D_
                var str = num.toString(16);_x000D_
                return (str.length<6?'#00'+str:'#'+str);_x000D_
            },_x000D_
            toNum: function(hex){_x000D_
                return parseInt(hex.replace('#',''), 16);_x000D_
            },_x000D_
            rgbToHex: function(color)_x000D_
            {_x000D_
                color = color.replace(/\s/g,"");_x000D_
                var aRGB = color.match(/^rgb\((\d{1,3}[%]?),(\d{1,3}[%]?),(\d{1,3}[%]?)\)$/i);_x000D_
                if(aRGB)_x000D_
                {_x000D_
                    color = '';_x000D_
                    for (var i=1;  i<=3; i++) color += Math.round((aRGB[i][aRGB[i].length-1]=="%"?2.55:1)*parseInt(aRGB[i])).toString(16).replace(/^(.)$/,'0$1');_x000D_
                }_x000D_
                else color = color.replace(/^#?([\da-f])([\da-f])([\da-f])$/i, '$1$1$2$2$3$3');_x000D_
                return '#'+color;_x000D_
            }
_x000D_
_x000D_
_x000D_

Cannot import XSSF in Apache POI

You did not described the environment, anyway, you should download apache poi libraries. If you are using eclipse , right click on your root project , so properties and in java build path add external jar and import in your project those libraries :

xmlbeans-2.6.0 ; poi-ooxml-schemas- ... ; poi-ooxml- ... ; poi- .... ;

How to configure custom PYTHONPATH with VM and PyCharm?

For PyCharm 5 (or 2016.1), you can:

  1. select Preferences > Project Interpreter
  2. to the right of interpreter selector there is a "..." button, click it
  3. select "more..."
  4. pop up a new "Project Interpreters" window
  5. select the rightest button (named "show paths for the selected interpreter")
  6. pop up a "Interpreter Paths" window
  7. click the "+" buttom > select your desired PYTHONPATH directory (the folder which contains python modules) and click OK
  8. Done! Enjoy it!

enter image description here

enter image description here

enter image description here enter image description here

How to change the font color of a disabled TextBox?

NOTE: see Cheetah's answer below as it identifies a prerequisite to get this solution to work. Setting the BackColor of the TextBox.


I think what you really want to do is enable the TextBox and set the ReadOnly property to true.

It's a bit tricky to change the color of the text in a disabled TextBox. I think you'd probably have to subclass and override the OnPaint event.

ReadOnly though should give you the same result as !Enabled and allow you to maintain control of the color and formatting of the TextBox. I think it will also still support selecting and copying text from the TextBox which is not possible with a disabled TextBox.

Another simple alternative is to use a Label instead of a TextBox.

Tomcat won't stop or restart

In my case, the tomcat.pid is under /opt/tomcat/temp/. Tried to delete it manually. Still didn't work. After check setnev.sh in /opt/tomcat/bin/, notice there is a line of code to define JAVA_HOME:

export JAVA_HOME=/usr/lib/jvm/java-1.8.0-openjdk-1.8.0.212.b04-0.el7_6.x86_64/jre

Commented out this line, restart Tomcat. It works! Since I did a yum update and a new minor version of Java update coming from 1.8.0.212 to 1.8.0.222. Lessons learned: Hard-code should be avoided.

bootstrap datepicker today as default

This should work:

$("#datepicker").datepicker("setDate", new Date());

And for autoclose (fiddle):

$('#datepicker').datepicker({
        "setDate": new Date(),
        "autoclose": true
});

jQuery > datepicker API

Setting up and using Meld as your git difftool and mergetool

It can be complicated to compute a diff in your head from the different sections in $MERGED and apply that. In my setup, meld helps by showing you these diffs visually, using:

[merge]
    tool = mymeld
    conflictstyle = diff3

[mergetool "mymeld"]
    cmd = meld --diff $BASE $REMOTE --diff $REMOTE $LOCAL --diff $LOCAL $MERGED

It looks strange but offers a very convenient work-flow, using three tabs:

  1. in tab 1 you see (from left to right) the change that you should make in tab 2 to solve the merge conflict.

  2. in the right side of tab 2 you apply the "change that you should make" and copy the entire file contents to the clipboard (using ctrl-a and ctrl-c).

  3. in tab 3 replace the right side with the clipboard contents. If everything is correct, you will now see - from left to right - the same change as shown in tab 1 (but with different contexts). Save the changes made in this tab.

Notes:

  • don't edit anything in tab 1
  • don't save anything in tab 2 because that will produce annoying popups in tab 3

Struct Constructor in C++?

Yes structures and classes in C++ are the same except that structures members are public by default whereas classes members are private by default. Anything you can do in a class you should be able to do in a structure.

struct Foo
{
  Foo()
  {
    // Initialize Foo
  }
};

Run cron job only if it isn't already running

Docs: https://www.timkay.com/solo/

solo is a very simple script (10 lines) that prevents a program from running more than one copy at a time. It is useful with cron to make sure that a job doesn't run before a previous one has finished.

Example

* * * * * solo -port=3801 ./job.pl blah blah

Proper use of mutexes in Python

I don't know why you're using the Window's Mutex instead of Python's. Using the Python methods, this is pretty simple:

from threading import Thread, Lock

mutex = Lock()

def processData(data):
    mutex.acquire()
    try:
        print('Do some stuff')
    finally:
        mutex.release()

while True:
    t = Thread(target = processData, args = (some_data,))
    t.start()

But note, because of the architecture of CPython (namely the Global Interpreter Lock) you'll effectively only have one thread running at a time anyway--this is fine if a number of them are I/O bound, although you'll want to release the lock as much as possible so the I/O bound thread doesn't block other threads from running.

An alternative, for Python 2.6 and later, is to use Python's multiprocessing package. It mirrors the threading package, but will create entirely new processes which can run simultaneously. It's trivial to update your example:

from multiprocessing import Process, Lock

mutex = Lock()

def processData(data):
    with mutex:
        print('Do some stuff')

if __name__ == '__main__':
    while True:
        p = Process(target = processData, args = (some_data,))
        p.start()

How to get selected path and name of the file opened with file dialog?

Sub GetFilePath()

Set myFile = Application.FileDialog(msoFileDialogOpen)

With myFile

.Title = "Choose File"

.AllowMultiSelect = False

If .Show <> -1 Then

Exit Sub

End If

FileSelected = Replace(.SelectedItems(1), .InitialFileName, "")

End With

ActiveSheet.Range("A1") = FileSelected

End Sub

Convert JSON array to an HTML table in jQuery

Using jQuery will make this simpler.

The following code will take an array of arrays and store convert them into rows and cells.

$.getJSON(url , function(data) {
    var tbl_body = "";
    var odd_even = false;
    $.each(data, function() {
        var tbl_row = "";
        $.each(this, function(k , v) {
            tbl_row += "<td>"+v+"</td>";
        });
        tbl_body += "<tr class=\""+( odd_even ? "odd" : "even")+"\">"+tbl_row+"</tr>";
        odd_even = !odd_even;               
    });
    $("#target_table_id tbody").html(tbl_body);
});

You could add a check for the keys you want to exclude by adding something like

var expected_keys = { key_1 : true, key_2 : true, key_3 : false, key_4 : true };

at the start of the getJSON callback function and adding:

if ( ( k in expected_keys ) && expected_keys[k] ) {
...
}

around the tbl_row += line.

Edit: Was assigning a null variable previously

Edit: Version based on Timmmm's injection-free contribution.

$.getJSON(url , function(data) {
    var tbl_body = document.createElement("tbody");
    var odd_even = false;
    $.each(data, function() {
        var tbl_row = tbl_body.insertRow();
        tbl_row.className = odd_even ? "odd" : "even";
        $.each(this, function(k , v) {
            var cell = tbl_row.insertCell();
            cell.appendChild(document.createTextNode(v.toString()));
        });        
        odd_even = !odd_even;               
    });
    $("#target_table_id").append(tbl_body);   //DOM table doesn't have .appendChild
});

The performance impact of using instanceof in Java

In modern Java version the instanceof operator is faster as a simple method call. This means:

if(a instanceof AnyObject){
}

is faster as:

if(a.getType() == XYZ){
}

Another thing is if you need to cascade many instanceof. Then a switch that only call once getType() is faster.

Passing std::string by Value or Reference

I believe the normal answer is that it should be passed by value if you need to make a copy of it in your function. Pass it by const reference otherwise.

Here is a good discussion: http://cpp-next.com/archive/2009/08/want-speed-pass-by-value/

iPhone is not available. Please reconnect the device

My experience, yesterday my iOS 13.6 is supported by Xcode 11.7 and now today the Xcode rejected my iPhone and I update the Xcode to version 12 and everything get back on track.

Solution:

Update your Xcode to the latest version.

Hint: there is no need to update iOS.

Django database query: How to get object by id?

If you want to get an object, using get() is more straightforward:

obj = Class.objects.get(pk=this_object_id)

How to validate a credit card number

A credit card number is not a bunch of random numbers. There is a formula for checking if it is correct.

After a quick Google search I found this JavaScript which will check a credit card number to be valid.

http://javascript.internet.com/forms/credit-card-number-validation.html

URL Broken: Internet archive: http://web.archive.org/web/20100129174150/http://javascript.internet.com/forms/credit-card-number-validation.html?

<!-- TWO STEPS TO INSTALL CREDIT CARD NUMBER VALIDATION:

  1.  Copy the code into the HEAD of your HTML document
  2.  Add the last code into the BODY of your HTML document  -->

<!-- STEP ONE: Paste this code into the HEAD of your HTML document  -->

<HEAD>

  <script type="text/javascript">
    <!--
    /* This script and many more are available free online at
    The JavaScript Source!! http://javascript.internet.com
    Created by: David Leppek :: https://www.azcode.com/Mod10

    Basically, the algorithm takes each digit, from right to left and muliplies each second
    digit by two. If the multiple is two-digits long (i.e.: 6 * 2 = 12) the two digits of
    the multiple are then added together for a new number (1 + 2 = 3). You then add up the
    string of numbers, both unaltered and new values and get a total sum. This sum is then
    divided by 10 and the remainder should be zero if it is a valid credit card. Hense the
    name Mod 10 or Modulus 10.
    */
    function Mod10(ccNumb) {  // v2.0
      var valid = "0123456789"  // Valid digits in a credit card number
      var len = ccNumb.length;  // The length of the submitted cc number
      var iCCN = parseInt(ccNumb);  // Integer of ccNumb
      var sCCN = ccNumb.toString();  // String of ccNumb
      sCCN = sCCN.replace (/^\s+|\s+$/g,'');  // Strip spaces
      var iTotal = 0;  // Integer total set at zero
      var bNum = true;  // By default assume it is a number
      var bResult = false;  // By default assume it is NOT a valid cc
      var temp;  // Temporary variable for parsing string
      var calc;  // Used for calculation of each digit

      // Determine if the ccNumb is in fact all numbers
      for (var j=0; j<len; j++) {
        temp = "" + sCCN.substring(j, j+1);
        if (valid.indexOf(temp) == "-1"){
          bNum = false;
        }
      }

      // If it is NOT a number, you can either alert to the fact, or just pass a failure
      if (!bNum) {
        /* alert("Not a Number"); */
        bResult = false;
      }

      // Determine if it is the proper length
      if ((len == 0) && (bResult)) {  // Nothing, the field is blank AND passed above # check
        bResult = false;
      }
      else { // ccNumb is a number and the proper length - let's
             //  see if it is a valid card number

        if (len >= 15) {  // 15 or 16 for Amex or V/MC
          for (var i=len;i>0;i--) {  // LOOP through the digits of the card
            calc = parseInt(iCCN) % 10;  // Right most digit
            calc = parseInt(calc);  // Assure it is an integer
            iTotal += calc;  // Running total of the card number as we loop - Do Nothing to first digit
            i--;  // Decrement the count - move to the next digit in the card
            iCCN = iCCN / 10;                               // Subtracts right most digit from ccNumb
            calc = parseInt(iCCN) % 10;     // NEXT right most digit
            calc = calc *2;                                 // multiply the digit by two

            // Instead of some screwy method of converting 16 to a string
            // and then parsing 1 and 6 and then adding them to make 7,
            // I use a simple switch statement to change the value
            // of calc2 to 7 if 16 is the multiple.
            switch(calc) {
              case 10: calc = 1; break;  // 5*2=10 & 1+0 = 1
              case 12: calc = 3; break;  // 6*2=12 & 1+2 = 3
              case 14: calc = 5; break;  // 7*2=14 & 1+4 = 5
              case 16: calc = 7; break;  // 8*2=16 & 1+6 = 7
              case 18: calc = 9; break;  // 9*2=18 & 1+8 = 9
              default: calc = calc;      // 4*2= 8 &   8 = 8  - the same for all lower numbers
            }
            iCCN = iCCN / 10;  // Subtracts right most digit from ccNum
            iTotal += calc;  // Running total of the card number as we loop
          } // END OF LOOP

          if ((iTotal%10)==0){  // Check to see if the sum Mod 10 is zero
            bResult = true;  // This IS (or could be) a valid credit card number.
          }
          else {
            bResult = false;  // This could NOT be a valid credit card number
          }
        }
      }

      // Change alert to on-page display or other indication as needed.
      if (bResult) {
        alert("This IS a valid Credit Card Number!");
      }
      if (!bResult) {
        alert("This is NOT a valid Credit Card Number!");
      }
      return bResult; // Return the results
    }
    // -->
  </script>

</HEAD>


<!-- STEP TWO: Copy this code into the BODY of your HTML document  -->

<BODY>

<div align="center">
  <form name="Form1">
    <table width="50%" border="0" cellspacing="0" cellpadding="5">
      <tr>
        <td width="50%" align="right">Credit Card Number:   </td>
        <td width="50%">
          <input name="CreditCard" type="text" value="4012888888881881" size="18" maxlength="16" style="border: 1px solid #000098; padding: 3px;">
        </td>
      </tr>
      <tr>
        <td colspan="2" align="center">
          <input type="button" name="Button" style="color: #fff; background: #000098; font-weight:bold; border: solid 1px #000;" value="TEST CARD NUMBER" onClick="return Mod10(document.Form1.CreditCard.value);">
        </td>
      </tr>
    </table>
  </form>
</div>

<p><center>
  <font face="arial, helvetica" size"-2">Free JavaScripts provided<br>
  by <a href="http://javascriptsource.com">The JavaScript Source</a></font>
</center><p>

<!-- Script Size:  4.97 KB -->

Java Keytool error after importing certificate , "keytool error: java.io.FileNotFoundException & Access Denied"

SOLVED

  1. Just run CMD as an administrator.
  2. Make sure your using the correct truststore password

How Can I Bypass the X-Frame-Options: SAMEORIGIN HTTP Header?

Yes Fiddler is an option for me:

  1. Open Fiddler menu > Rules > Customize Rules (this effectively edits CustomRules.js).
  2. Find the function OnBeforeResponse
  3. Add the following lines:

    oSession.oResponse.headers.Remove("X-Frame-Options");
    oSession.oResponse.headers.Add("Access-Control-Allow-Origin", "*");
    
  4. Remember to save the script!

Accessing Websites through a Different Port?

when viewing a website it gets assigned a random port, it will always come from port 80 (usually always, unless the server admin has changed the port) there's no way for someone to change that port unless you have control of the server.

Passing an array as a function parameter in JavaScript

While using spread operator we must note that it must be the last or only parameter passed. Else it will fail.

function callMe(...arr){ //valid arguments
    alert(arr);
}

function callMe(name, ...arr){ //valid arguments
    alert(arr);
}

function callMe(...arr, name){ //invalid arguments
    alert(arr);
}

If you need to pass an array as the starting argument you can do:

function callMe(arr, name){
    let newArr = [...arr];
    alert(newArr);
}

jQuery: Best practice to populate drop down?

$.getJSON("/Admin/GetFolderList/", function(result) {
    var options = $("#options");
    //don't forget error handling!
    $.each(result, function(item) {
        options.append($("<option />").val(item.ImageFolderID).text(item.Name));
    });
});

What I'm doing above is creating a new <option> element and adding it to the options list (assuming options is the ID of a drop down element.

PS My javascript is a bit rusty so the syntax may not be perfect

PHP - Insert date into mysql

try converting the date first.

$date = "2012-08-06";

mysql_query("INSERT INTO data_table (title, date_of_event)
               VALUES('" . $_POST['post_title'] . "',
                      '" . $date . "')") 
           or die(mysql_error());

How many characters can a Java String have?

Java9 uses byte[] to store String.value, so you can only get about 1GB Strings in Java9. Java8 on the other hand can have 2GB Strings.

By character I mean "char"s, some character is not representable in BMP(like some of the emojis), so it will take more(currently 2) chars.

Change value of input placeholder via model?

You can bind with a variable in the controller:

<input type="text" ng-model="inputText" placeholder="{{somePlaceholder}}" />

In the controller:

$scope.somePlaceholder = 'abc';

How to install iPhone application in iPhone Simulator

This worked for me on iOS 5.0 simulator.

  1. Run the app on the simulator.

  2. Go to the path where you can see something like this:

    /Users/arshad/Library/Application\ Support/iPhone\ Simulator/5.0/Applications/34BC3FDC-7398-42D4-9114-D5FEFC737512/…
    
  3. Copy all the package contents including the app, lib, temp and Documents.

  4. Clear all the applications installed on the simulator so that it is easier to see what is happening.

  5. Run a pre-existing app you have on your simulator.

  6. Look for the same package content for that application as in step 3 and delete all.

  7. Paste the package contents that you have previously copied.

  8. Close the simulator and start it again. The new app icon of the intended app will replace the old one.

Composer: The requested PHP extension ext-intl * is missing from your system

This is bit old question but I had faced same problem on linux base server while installing magento 2.

When I am firing composer update or composer install command from my magento root dir. Its was firing below error.

Problem 1
    - The requested PHP extension ext-intl * is missing from your system. Install or enable PHP's intl extension.
  Problem 2
    - The requested PHP extension ext-mbstring * is missing from your system. Install or enable PHP's mbstring extension.
  Problem 3
    - Installation request for pelago/emogrifier 0.1.1 -> satisfiable by pelago/emogrifier[v0.1.1].
    - pelago/emogrifier v0.1.1 requires ext-mbstring * -> the requested PHP extension mbstring is missing from your system.
   ...

Then, I searched for the available intl & intl extensions, using below commands.

yum list php*intl
yum install php-intl.x86_64  

yum list php*mbstring
yum install php-mbstring.x86_64

And it fixed the issue.

git status shows modifications, git checkout -- <file> doesn't remove them

I solved it this way:

  1. Copy the contents of the correct code you want
  2. Delete the file that is causing the problem ( the one that you can't revert ) from your disk. now you should find both versions of the same file marked as being deleted.
  3. Commit the deletion of the files.
  4. Create the file again with the same name and paste in the correct code you have copied in step 1
  5. commit the creation of the new file.

That's what worked for me.

Creation timestamp and last update timestamp with Hibernate and MySQL

We had a similar situation. We were using Mysql 5.7.

CREATE TABLE my_table (
        ...
      updated_time TIMESTAMP DEFAULT CURRENT_TIMESTAMP ON UPDATE CURRENT_TIMESTAMP
    );

This worked for us.

onchange event for input type="number"

To detect when mouse or key are pressed, you can also write:

$(document).on('keyup mouseup', '#your-id', function() {                                                                                                                     
  console.log('changed');
});

What's the canonical way to check for type in Python?

isinstance(o, str) will return True if o is an str or is of a type that inherits from str.

type(o) is str will return True if and only if o is a str. It will return False if o is of a type that inherits from str.

How do I change the background color of a plot made with ggplot2

To avoid deprecated opts and theme_rect use:

myplot + theme(panel.background = element_rect(fill='green', colour='red'))

To define your own custom theme, based on theme_gray but with some of your changes and a few added extras including control of gridline colour/size (more options available to play with at ggplot2.org):

theme_jack <- function (base_size = 12, base_family = "") {
    theme_gray(base_size = base_size, base_family = base_family) %+replace% 
        theme(
            axis.text = element_text(colour = "white"),
            axis.title.x = element_text(colour = "pink", size=rel(3)),
            axis.title.y = element_text(colour = "blue", angle=45),
            panel.background = element_rect(fill="green"),
            panel.grid.minor.y = element_line(size=3),
            panel.grid.major = element_line(colour = "orange"),
            plot.background = element_rect(fill="red")
    )   
}

To make your custom theme the default when ggplot is called in future, without masking:

theme_set(theme_jack())

If you want to change an element of the currently set theme:

theme_update(plot.background = element_rect(fill="pink"), axis.title.x = element_text(colour = "red"))

To store the current default theme as an object:

theme_pink <- theme_get()

Note that theme_pink is a list whereas theme_jack was a function. So to return the theme to theme_jack use theme_set(theme_jack()) whereas to return to theme_pink use theme_set(theme_pink).

You can replace theme_gray by theme_bw in the definition of theme_jack if you prefer. For your custom theme to resemble theme_bw but with all gridlines (x, y, major and minor) turned off:

theme_nogrid <- function (base_size = 12, base_family = "") {
    theme_bw(base_size = base_size, base_family = base_family) %+replace% 
        theme(
            panel.grid = element_blank()
    )   
}

Finally a more radical theme useful when plotting choropleths or other maps in ggplot, based on discussion here but updated to avoid deprecation. The aim here is to remove the gray background, and any other features that might distract from the map.

theme_map <- function (base_size = 12, base_family = "") {
    theme_gray(base_size = base_size, base_family = base_family) %+replace% 
        theme(
            axis.line=element_blank(),
            axis.text.x=element_blank(),
            axis.text.y=element_blank(),
            axis.ticks=element_blank(),
            axis.ticks.length=unit(0.3, "lines"),
            axis.ticks.margin=unit(0.5, "lines"),
            axis.title.x=element_blank(),
            axis.title.y=element_blank(),
            legend.background=element_rect(fill="white", colour=NA),
            legend.key=element_rect(colour="white"),
            legend.key.size=unit(1.2, "lines"),
            legend.position="right",
            legend.text=element_text(size=rel(0.8)),
            legend.title=element_text(size=rel(0.8), face="bold", hjust=0),
            panel.background=element_blank(),
            panel.border=element_blank(),
            panel.grid.major=element_blank(),
            panel.grid.minor=element_blank(),
            panel.margin=unit(0, "lines"),
            plot.background=element_blank(),
            plot.margin=unit(c(1, 1, 0.5, 0.5), "lines"),
            plot.title=element_text(size=rel(1.2)),
            strip.background=element_rect(fill="grey90", colour="grey50"),
            strip.text.x=element_text(size=rel(0.8)),
            strip.text.y=element_text(size=rel(0.8), angle=-90) 
        )   
}

Laravel Eloquent ORM Transactions

I'm Sure you are not looking for a closure solution, try this for a more compact solution

 try{
    DB::beginTransaction();

    /*
     * Your DB code
     * */

    DB::commit();
}catch(\Exception $e){
    DB::rollback();
}

MySQL Select last 7 days

The WHERE clause is misplaced, it has to follow the table references and JOIN operations.

Something like this:

 FROM tartikel p1 
 JOIN tartikelpict p2 
   ON p1.kArtikel = p2.kArtikel 
  AND p2.nNr = 1
WHERE p1.dErstellt >= DATE(NOW()) - INTERVAL 7 DAY
ORDER BY p1.kArtikel DESC

EDIT (three plus years later)

The above essentially answers the question "I tried to add a WHERE clause to my query and now the query is returning an error, how do I fix it?"

As to a question about writing a condition that checks a date range of "last 7 days"...

That really depends on interpreting the specification, what the datatype of the column in the table is (DATE or DATETIME) and what data is available... what should be returned.

To summarize: the general approach is to identify a "start" for the date/datetime range, and "end" of that range, and reference those in a query. Let's consider something easier... all rows for "yesterday".

If our column is DATE type. Before we incorporate an expression into a query, we can test it in a simple SELECT

 SELECT DATE(NOW()) + INTERVAL -1 DAY 

and verify the result returned is what we expect. Then we can use that same expression in a WHERE clause, comparing it to a DATE column like this:

 WHERE datecol = DATE(NOW()) + INTERVAL -1 DAY

For a DATETIME or TIMESTAMP column, we can use >= and < inequality comparisons to specify a range

 WHERE datetimecol >= DATE(NOW()) + INTERVAL -1 DAY
   AND datetimecol <  DATE(NOW()) + INTERVAL  0 DAY

For "last 7 days" we need to know if that mean from this point right now, back 7 days ... e.g. the last 7*24 hours , including the time component in the comparison, ...

 WHERE datetimecol >= NOW() + INTERVAL -7 DAY
   AND datetimecol <  NOW() + INTERVAL  0 DAY

the last seven complete days, not including today

 WHERE datetimecol >= DATE(NOW()) + INTERVAL -7 DAY
   AND datetimecol <  DATE(NOW()) + INTERVAL  0 DAY

or past six complete days plus so far today ...

 WHERE datetimecol >= DATE(NOW()) + INTERVAL -6 DAY
   AND datetimecol <  NOW()       + INTERVAL  0 DAY

I recommend testing the expressions on the right side in a SELECT statement, we can use a user-defined variable in place of NOW() for testing, not being tied to what NOW() returns so we can test borders, across week/month/year boundaries, and so on.

SET @clock = '2017-11-17 11:47:47' ;

SELECT DATE(@clock)
     , DATE(@clock) + INTERVAL -7 DAY 
     , @clock + INTERVAL -6 DAY 

Once we have expressions that return values that work for "start" and "end" for our particular use case, what we mean by "last 7 days", we can use those expressions in range comparisons in the WHERE clause.

(Some developers prefer to use the DATE_ADD and DATE_SUB functions in place of the + INTERVAL val DAY/HOUR/MINUTE/MONTH/YEAR syntax.

And MySQL provides some convenient functions for working with DATE, DATETIME and TIMESTAMP datatypes... DATE, LAST_DAY,

Some developers prefer to calculate the start and end in other code, and supply string literals in the SQL query, such that the query submitted to the database is

  WHERE datetimecol >= '2017-11-10 00:00'
    AND datetimecol <  '2017-11-17 00:00'

And that approach works too. (My preference would be to explicitly cast those string literals into DATETIME, either with CAST, CONVERT or just the + INTERVAL trick...

  WHERE datetimecol >= '2017-11-10 00:00' + INTERVAL 0 SECOND
    AND datetimecol <  '2017-11-17 00:00' + INTERVAL 0 SECOND

The above all assumes we are storing "dates" in appropriate DATE, DATETIME and/or TIMESTAMP datatypes, and not storing them as strings in variety of formats e.g. 'dd/mm/yyyy', m/d/yyyy, julian dates, or in sporadically non-canonical formats, or as a number of seconds since the beginning of the epoch, this answer would need to be much longer.

Left Outer Join using + sign in Oracle 11g

I saw some contradictions in the answers above, I just tried the following on Oracle 12c and the following is correct :

LEFT OUTER JOIN

SELECT *
FROM A, B
WHERE A.column = B.column(+)

RIGHT OUTER JOIN

SELECT *
FROM A, B
WHERE B.column(+) = A.column

SignalR - Sending a message to a specific user using (IUserIdProvider) *NEW 2.0.0*

Here's a start.. Open to suggestions/improvements.

Server

public class ChatHub : Hub
{
    public void SendChatMessage(string who, string message)
    {
        string name = Context.User.Identity.Name;
        Clients.Group(name).addChatMessage(name, message);
        Clients.Group("[email protected]").addChatMessage(name, message);
    }

    public override Task OnConnected()
    {
        string name = Context.User.Identity.Name;
        Groups.Add(Context.ConnectionId, name);

        return base.OnConnected();
    }
}

JavaScript

(Notice how addChatMessage and sendChatMessage are also methods in the server code above)

    $(function () {
    // Declare a proxy to reference the hub.
    var chat = $.connection.chatHub;
    // Create a function that the hub can call to broadcast messages.
    chat.client.addChatMessage = function (who, message) {
        // Html encode display name and message.
        var encodedName = $('<div />').text(who).html();
        var encodedMsg = $('<div />').text(message).html();
        // Add the message to the page.
        $('#chat').append('<li><strong>' + encodedName
            + '</strong>:&nbsp;&nbsp;' + encodedMsg + '</li>');
    };

    // Start the connection.
    $.connection.hub.start().done(function () {
        $('#sendmessage').click(function () {
            // Call the Send method on the hub.
            chat.server.sendChatMessage($('#displayname').val(), $('#message').val());
            // Clear text box and reset focus for next comment.
            $('#message').val('').focus();
        });
    });
});

Testing enter image description here

How do you UDP multicast in Python?

This example doesn't work for me, for an obscure reason.

Not obscure, it's simple routing.

On OpenBSD

route add -inet 224.0.0.0/4 224.0.0.1

You can set the route to a dev on Linux

route add -net 224.0.0.0 netmask 240.0.0.0 dev wlp2s0

force all multicast traffic to one interface on Linux

   ifconfig wlp2s0 allmulti

tcpdump is super simple

tcpdump -n multicast

In your code you have:

while True:
  # For Python 3, change next line to "print(sock.recv(10240))"

Why 10240?

multicast packet size should be 1316 bytes

How to get subarray from array?

Take a look at Array.slice(begin, end)

_x000D_
_x000D_
const ar  = [1, 2, 3, 4, 5];

// slice from 1..3 - add 1 as the end index is not included

const ar2 = ar.slice(1, 3 + 1);

console.log(ar2);
_x000D_
_x000D_
_x000D_

Excel concatenation quotes

You can also use this syntax: (in column D to concatenate A, B, and C)

=A2 & " """ & B2 & """ " & C2

Excel formula to concatenate with quotes

How to open a specific port such as 9090 in Google Compute Engine

Here is the command-line approach to answer this question:

gcloud compute firewall-rules create <rule-name> --allow tcp:9090 --source-tags=<list-of-your-instances-names> --source-ranges=0.0.0.0/0 --description="<your-description-here>"

This will open the port 9090 for the instances that you name. Omitting --source-tags and --source-ranges will apply the rule to all instances. More details are in the Gcloud documentation and the firewall-rule create command manual

The previous answers are great, but Google recommends using the newer gcloud commands instead of the gcutil commands.

PS: To get an idea of Google's firewall rules, run gcloud compute firewall-rules list and view all your firewall rules

Python extending with - using super() Python 3 vs Python 2

Another python3 implementation that involves the use of Abstract classes with super(). You should remember that

super().__init__(name, 10)

has the same effect as

Person.__init__(self, name, 10)

Remember there's a hidden 'self' in super(), So the same object passes on to the superclass init method and the attributes are added to the object that called it. Hence super()gets translated to Person and then if you include the hidden self, you get the above code frag.

from abc import ABCMeta, abstractmethod
class Person(metaclass=ABCMeta):
    name = ""
    age = 0

    def __init__(self, personName, personAge):
        self.name = personName
        self.age = personAge

    @abstractmethod
    def showName(self):
        pass

    @abstractmethod
    def showAge(self):
        pass


class Man(Person):

    def __init__(self, name, height):
        self.height = height
        # Person.__init__(self, name, 10)
        super().__init__(name, 10)  # same as Person.__init__(self, name, 10)
        # basically used to call the superclass init . This is used incase you want to call subclass init
        # and then also call superclass's init.
        # Since there's a hidden self in the super's parameters, when it's is called,
        # the superclasses attributes are a part of the same object that was sent out in the super() method

    def showIdentity(self):
        return self.name, self.age, self.height

    def showName(self):
        pass

    def showAge(self):
        pass


a = Man("piyush", "179")
print(a.showIdentity())

How do I reset a jquery-chosen select option with jQuery?

Try this to reload updated Select box with Latest Chosen JS.

$("#form_field").trigger("chosen:updated");

http://harvesthq.github.io/chosen/

It will Updated chosen drop-down with new loaded select box with Ajax.

Cannot Resolve Collation Conflict

The thing about collations is that although the database has its own collation, every table, and every column can have its own collation. If not specified it takes the default of its parent object, but can be different.

When you change collation of the database, it will be the new default for all new tables and columns, but it doesn't change the collation of existing objects inside the database. You have to go and change manually the collation of every table and column.

Luckily there are scripts available on the internet that can do the job. I am not going to recommend any as I haven't tried them but here are few links:

http://www.codeproject.com/Articles/302405/The-Easy-way-of-changing-Collation-of-all-Database

Update Collation of all fields in database on the fly

http://www.sqlservercentral.com/Forums/Topic820675-146-1.aspx

If you need to have different collation on two objects or can't change collations - you can still JOIN between them using COLLATE command, and choosing the collation you want for join.

SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE Latin1_General_CI_AS 

or using default database collation:

SELECT * FROM A JOIN B ON A.Text = B.Text COLLATE DATABASE_DEFAULT

Windows Batch: How to add Host-Entries?

Here is my modification of @rashy above. The script does the following:

  • it verifies you have access, if not, requests it
  • allows you to enter in multiple hosts in a list
  • loops through the list
  • It finds the line containing the the domain name and removes it, then re-adds it (incase the ip has changed since the last time the script was run).
  • if the domain isn't there, it just adds it.

This is the script:

@echo off
TITLE Modifying your HOSTS file
COLOR F0
ECHO.


:: BatchGotAdmin
:-------------------------------------
REM  --> Check for permissions
>nul 2>&1 "%SYSTEMROOT%\system32\cacls.exe" "%SYSTEMROOT%\system32\config\system"

REM --> If error flag set, we do not have admin.
if '%errorlevel%' NEQ '0' (
    echo Requesting administrative privileges...
    goto UACPrompt
) else ( goto gotAdmin )

:UACPrompt
    echo Set UAC = CreateObject^("Shell.Application"^) > "%temp%\getadmin.vbs"
    set params = %*:"="
    echo UAC.ShellExecute "cmd.exe", "/c %~s0 %params%", "", "runas", 1 >> "%temp%\getadmin.vbs"

    "%temp%\getadmin.vbs"
    del "%temp%\getadmin.vbs"
    exit /B

:gotAdmin
    pushd "%CD%"
    CD /D "%~dp0"
:--------------------------------------

:LOOP
SET Choice=
SET /P Choice="Do you want to modify HOSTS file ? (Y/N)"

IF NOT '%Choice%'=='' SET Choice=%Choice:~0,1%

ECHO.
IF /I '%Choice%'=='Y' GOTO ACCEPTED
IF /I '%Choice%'=='N' GOTO REJECTED
ECHO Please type Y (for Yes) or N (for No) to proceed!
ECHO.
GOTO Loop


:REJECTED
ECHO Your HOSTS file was left unchanged>>%systemroot%\Temp\hostFileUpdate.log
ECHO Finished.
GOTO END


:ACCEPTED
setlocal enabledelayedexpansion
::Create your list of host domains
set LIST=(diqc.oca wiki.oca)
::Set the ip of the domains you set in the list above
set diqc.oca=192.168.111.6
set wiki.oca=192.168.111.4
:: deletes the parentheses from LIST
set _list=%LIST:~1,-1%
::ECHO %WINDIR%\System32\drivers\etc\hosts > tmp.txt
for  %%G in (%_list%) do (
    set  _name=%%G
    set  _value=!%%G!
    SET NEWLINE=^& echo.
    ECHO Carrying out requested modifications to your HOSTS file
    ::strip out this specific line and store in tmp file
    type %WINDIR%\System32\drivers\etc\hosts | findstr /v !_name! > tmp.txt
    ::re-add the line to it
    ECHO %NEWLINE%^!_value! !_name!>>tmp.txt
    ::overwrite host file
    copy /b/v/y tmp.txt %WINDIR%\System32\drivers\etc\hosts
    del tmp.txt
)
ipconfig /flushdns
ECHO.
ECHO.
ECHO Finished, you may close this window now.
ECHO You should now open Chrome and go to "chrome://net-internals/#dns" (without quotes)
ECHO     then click the "clear host cache" button
GOTO END

:END
ECHO.
ping -n 11 192.0.2.2 > nul
EXIT

Int division: Why is the result of 1/3 == 0?

The result is 0. Why is this, and how do I solve this problem?

TL;DR

You can solve it by doing:

double g = 1.0/3.0; 

or

double g = 1.0/3; 

or

double g = 1/3.0; 

or

double g = (double) 1 / 3;

The last of these options is required when you are using variables e.g. int a = 1, b = 3; double g = (double) a / b;.

A more completed answer

double g = 1 / 3;

This result in 0 because

  • first the dividend < divisor;
  • both variables are of type int therefore resulting in int (5.6.2. JLS) which naturally cannot represent the a floating point value such as 0.333333...
  • "Integer division rounds toward 0." 15.17.2 JLS

Why double g = 1.0/3.0; and double g = ((double) 1) / 3; work?

From Chapter 5. Conversions and Promotions one can read:

One conversion context is the operand of a numeric operator such as + or *. The conversion process for such operands is called numeric promotion. Promotion is special in that, in the case of binary operators, the conversion chosen for one operand may depend in part on the type of the other operand expression.

and 5.6.2. Binary Numeric Promotion

When an operator applies binary numeric promotion to a pair of operands, each of which must denote a value that is convertible to a numeric type, the following rules apply, in order:

If any operand is of a reference type, it is subjected to unboxing conversion (§5.1.8).

Widening primitive conversion (§5.1.2) is applied to convert either or both operands as specified by the following rules:

If either operand is of type double, the other is converted to double.

Otherwise, if either operand is of type float, the other is converted to float.

Otherwise, if either operand is of type long, the other is converted to long.

Otherwise, both operands are converted to type int.

Image resolution for new iPhone 6 and 6+, @3x support added?

I have tested by making a sample project and all simulators seem to use @3x images , this is confusing.

Create different versions of an image in your asset catalog such that the image itself tells you what version it is:

enter image description here

Now run the app on each simulator in turn. You will see that the 3x image is used only on the iPhone 6 Plus.

The same thing is true if the images are drawn from the app bundle using their names (e.g. one.png, [email protected], and [email protected]) by calling imageNamed: and assigning into an image view.

(However, there's a difference if you assign the image to an image view in Interface Builder - the 2x version is ignored on double-resolution devices. This is presumably a bug, apparently a bug in pathForResource:ofType:.)

MySQL Insert into multiple tables? (Database normalization?)

Just a remark about your saying

Hi, I tried searching a way to insert information in multiple tables in the same query

Do you eat all your lunch dishes mixed with drinks in the same bowl?
I suppose - no.

Same here.
There are things we do separately.
2 insert queries are 2 insert queries. It's all right. Nothing wrong with it. No need to mash it in one.
Same for select. Query must be sensible and do it's job. That's the only reasons. Number of queries is not.

As for the transactions - you may use them, but it's not THAT big deal for the average web-site. If it happened once a year (if ever) that one user registration being broken you'll be able to fix, no doubt.
there are hundreds of thousands sites running mysql with no transaction support driver. Have you heard of terrible disasters breaking these sites apart? Me neither.

And mysql_insert_id() has noting to do with transactions. you may include in into transaction all right. it's just different matters. Someone raised this question out of nowhere.

How to set TextView textStyle such as bold, italic

It would be

yourTextView.setTypeface(null,Typeface.DEFAULT_BOLD);

and italic should be able to be with replacing Typeface.DEFAULT_BOLD with Typeface.DEFAULT_ITALC.

Let me know how it works.

How do I add a Font Awesome icon to input field?

to work this with unicode or fontawesome, you should add a span with class like below, because input tag not support pseudo classes like :after. this is not a direct solution

in html:

   <span class="button1 search"></span>
<input name="username">

in css:

.button1 {
    background-color: #B9D5AD;
    border-radius: 0.2em 0 0 0.2em;
    box-shadow: 1px 0 0 rgba(0, 0, 0, 0.5), 2px 0 0 rgba(255, 255, 255, 0.5); 
    pointer-events: none;
    margin:1px 12px;    
    border-radius: 0.2em;    
    color: #333333;
    cursor: pointer;
    position: absolute;
    padding: 3px;
    text-decoration: none;   

}

MySQL error 1449: The user specified as a definer does not exist

Try to set your procedure as SECURITY INVOKER

Mysql default sets procedures security as "DEFINER" (CREATOR OF).. you must set the security to the "invoker".

Using subprocess to run Python script on Windows

You are using a pathname separator which is platform dependent. Windows uses "\" and Unix uses "/".

Chmod recursively

Try to change all the persmissions at the same time:

chmod -R +xr

How to initialize const member variable in a class?

Another possible way are namespaces:

#include <iostream>

namespace mySpace {
   static const int T = 100; 
}

using namespace std;

class T1
{
   public:
   T1()
   {
       cout << "T1 constructor: " << mySpace::T << endl;
   }
};

The disadvantage is that other classes can also use the constants if they include the header file.

Checkbox angular material checked by default

this works for me in Angular 7

// in component.ts
checked: boolean = true;

changeValue(value) {
    this.checked = !value;
}

// in component.html
<mat-checkbox value="checked" (click)="changeValue(checked)" color="primary">
   some Label
</mat-checkbox>

I hope help someone ... greetings. let me know if someone have some easiest

Open the terminal in visual studio?

To open the terminal:

  • Use the Ctrl` keyboard shortcut with the backtick character. This command works for both Linux and macOS.
  • Use the View > Terminal menu command.
  • From the Command Palette (??P), use the View: Toggle Integrated Terminal command.

Please find more about integrated terminal here https://code.visualstudio.com/docs/editor/integrated-terminal

NodeJS/express: Cache and 304 status code

  • Operating system: Windows
  • Browser: Chrome

I used Ctrl + F5 keyboard combination. By doing so, instead of reading from cache, I wanted to get a new response. The solution is to do hard refresh the page.

On MDN Web Docs:

"The HTTP 304 Not Modified client redirection response code indicates that there is no need to retransmit the requested resources. It is an implicit redirection to a cached resource."

What does "while True" mean in Python?

In some languages True is just and alias for the number. You can learn more why this is by reading more about boolean logic.

How to use 'hover' in CSS

There are many ways of doing that. If you really want to have a 'hover' class in your A element, then you'd have to do:

a.hover:hover { code here }

Then again, it's uncommon to have such a className there, this is how you do a regular hover:

select:hover { code here }

Here are a few more examples:

1

HTML:

<a class="button" href="#" title="">Click me</a>

CSS:

.button:hover { code here }

2

HTML:

<h1>Welcome</h1>

CSS:

h1:hover { code here }

:hover is one of the many pseudo-classes.

For example you can change, you can control the styling of an element when the mouse hovers over it, when it is clicked and when it was previously clicked.

HTML:

<a class="home" href="#" title="Go back">Go home!</a>

CSS:

.home { color: red; }
.home:hover { color: green; }
.home:active { color: blue; }
.home:visited { color: black; }

Aside the awkward colors I've given as examples, the link with the 'home' class will be red by default, green when the mouse hovers them, blue when they are clicked and black after they were clicked.

Hope this helps

Generate Json schema from XML schema (XSD)

True, but after turning json to xml with xmlspy, you can use trang application (http://www.thaiopensource.com/relaxng/trang.html) to create an xsd from xml file(s).

How do I select which GPU to run a job on?

Set the following two environment variables:

NVIDIA_VISIBLE_DEVICES=$gpu_id
CUDA_VISIBLE_DEVICES=0

where gpu_id is the ID of your selected GPU, as seen in the host system's nvidia-smi (a 0-based integer) that will be made available to the guest system (e.g. to the Docker container environment).

You can verify that a different card is selected for each value of gpu_id by inspecting Bus-Id parameter in nvidia-smi run in a terminal in the guest system).

More info

This method based on NVIDIA_VISIBLE_DEVICES exposes only a single card to the system (with local ID zero), hence we also hard-code the other variable, CUDA_VISIBLE_DEVICES to 0 (mainly to prevent it from defaulting to an empty string that would indicate no GPU).

Note that the environmental variable should be set before the guest system is started (so no chances of doing it in your Jupyter Notebook's terminal), for instance using docker run -e NVIDIA_VISIBLE_DEVICES=0 or env in Kubernetes or Openshift.

If you want GPU load-balancing, make gpu_id random at each guest system start.

If setting this with python, make sure you are using strings for all environment variables, including numerical ones.

You can verify that a different card is selected for each value of gpu_id by inspecting nvidia-smi's Bus-Id parameter (in a terminal run in the guest system).

The accepted solution based on CUDA_VISIBLE_DEVICES alone does not hide other cards (different from the pinned one), and thus causes access errors if you try to use them in your GPU-enabled python packages. With this solution, other cards are not visible to the guest system, but other users still can access them and share their computing power on an equal basis, just like with CPU's (verified).

This is also preferable to solutions using Kubernetes / Openshift controlers (resources.limits.nvidia.com/gpu), that would impose a lock on the allocated card, removing it from the pool of available resources (so the number of containers with GPU access could not exceed the number of physical cards).

This has been tested under CUDA 8.0, 9.0 and 10.1 in docker containers running Ubuntu 18.04 orchestrated by Openshift 3.11.

What is mutex and semaphore in Java ? What is the main difference?

A mutex is used for serial access to a resource while a semaphore limits access to a resource up to a set number. You can think of a mutex as a semaphore with an access count of 1. Whatever you set your semaphore count to, that may threads can access the resource before the resource is blocked.

IE9 JavaScript error: SCRIPT5007: Unable to get value of the property 'ui': object is null or undefined

You could also get this error if you are viewing accessing the page locally (via file:// instead of http://)..

There is some discussion about this here: https://github.com/jeromegn/Backbone.localStorage/issues/55

Convert pandas DataFrame into list of lists

There is a built in method which would be the fastest method also, calling tolist on the .values np array:

df.values.tolist()

[[0.0, 3.61, 380.0, 3.0],
 [1.0, 3.67, 660.0, 3.0],
 [1.0, 3.19, 640.0, 4.0],
 [0.0, 2.93, 520.0, 4.0]]

Why should I use an IDE?

I have used Emacs as my primary environment for both development and mail/news for about 10 year (1994-2004). I discovered the power of IDEs when I forced myself to learn Java in 2004, and to my surprise that I actually liked the IDE (IntelliJ IDEA).

I will not go into specific reasons since a lot of them have already been mentioned here -- just remember that the different people love different features. Me and a colleague used the same IDE, both of us used just a fraction of the features available, and we disliked each others way of using the IDE (but we both liked the IDE itself).

But there is one advantage with IDEs over Emacs/Vim related environments I want to focus on: You spend less time installing/configuring the features you want.

With Wing IDE (for Python) I'm ready to start developing 15-20 minutes after installation. No idea how many hours I would need to get the features I use up and running with Emacs/Vim. :)

Run Java Code Online

rextester runs java snippets

Also accessible as runjavaonline.com

ssh_exchange_identification: Connection closed by remote host under Git bash

I solved it this way.

ssh -vvv <username>@github.com to see github IP.

Then opened browser and opened github via IP to find it was an issue with firewall.

Creating csv file with php

@Baba's answer is great. But you don't need to use explode because fputcsv takes an array as a parameter

For instance, if you have a three columns, four lines document, here's a more straight version:

header('Content-Type: text/csv');
header('Content-Disposition: attachment; filename="sample.csv"');

$user_CSV[0] = array('first_name', 'last_name', 'age');

// very simple to increment with i++ if looping through a database result 
$user_CSV[1] = array('Quentin', 'Del Viento', 34);
$user_CSV[2] = array('Antoine', 'Del Torro', 55);
$user_CSV[3] = array('Arthur', 'Vincente', 15);

$fp = fopen('php://output', 'wb');
foreach ($user_CSV as $line) {
    // though CSV stands for "comma separated value"
    // in many countries (including France) separator is ";"
    fputcsv($fp, $line, ',');
}
fclose($fp);

JSF(Primefaces) ajax update of several elements by ID's

If the to-be-updated component is not inside the same NamingContainer component (ui:repeat, h:form, h:dataTable, etc), then you need to specify the "absolute" client ID. Prefix with : (the default NamingContainer separator character) to start from root.

<p:ajax process="@this" update="count :subTotal"/>

To be sure, check the client ID of the subTotal component in the generated HTML for the actual value. If it's inside for example a h:form as well, then it's prefixed with its client ID as well and you would need to fix it accordingly.

<p:ajax process="@this" update="count :formId:subTotal"/>

Space separation of IDs is more recommended as <f:ajax> doesn't support comma separation and starters would otherwise get confused.

postgres, ubuntu how to restart service on startup? get stuck on clustering after instance reboot

ENABLE is what you are looking for

USAGE: type this command once and then you are good to go. Your service will start automaticaly at boot up

 sudo systemctl enable postgresql

DISABLE exists as well ofc

Some DOC: freedesktop man systemctl

SQL Server date format yyyymmdd

In SQL Server, you can do:

select coalesce(format(try_convert(date, col, 112), 'yyyyMMdd'), col)

This attempts the conversion, keeping the previous value if available.

Note: I hope you learned a lesson about storing dates as dates and not strings.

What is the best way to measure execution time of a function?

Tickcount is good, however i suggest running it 100 or 1000 times, and calculating an average. Not only makes it more measurable - in case of really fast/short functions, but helps dealing with some one-off effects caused by the overhead.

JQuery - File attributes

To get the filenames, use:

var files = document.getElementById('inputElementID').files;

Using jQuery (since you already are) you can adapt this to the following:

$('input[type="file"][multiple]').change(
    function(e){
        var files = this.files;
        for (i=0;i<files.length;i++){
            console.log(files[i].fileName + ' (' + files[i].fileSize + ').');
        }
        return false;
    });

JS Fiddle demo.

is inaccessible due to its protection level

The reason being you can not access protected member data through the instance of the class.

Reason why it is not allowed is explained in this blog

Loop inside React JSX

You'll want to add elements to an array and render the array of elements.
This can help reduce the time required to re-render the component.

Here's some rough code that might help:

MyClass extends Component {
    constructor() {
        super(props)
        this.state = { elements: [] }
    }
    render() {
        return (<tbody>{this.state.elements}<tbody>)
    }
    add() {
        /*
         * The line below is a cheap way of adding to an array in the state.
         * 1) Add <tr> to this.state.elements
         * 2) Trigger a lifecycle update.
         */
        this.setState({
            elements: this.state.elements.concat([<tr key={elements.length}><td>Element</td></tr>])
        })
    }
}

Android List View Drag and Drop sort

Am adding this answer for the purpose of those who google about this..

There was an episode of DevBytes (ListView Cell Dragging and Rearranging) recently which explains how to do this

You can find it here also the sample code is available here.

What this code basically does is that it creates a dynamic listview by the extension of listview that supports cell dragging and swapping. So that you can use the DynamicListView instead of your basic ListView and that's it you have implemented a ListView with Drag and Drop.

How do I access named capturing groups in a .NET Regex?

You specify the named capture group string by passing it to the indexer of the Groups property of a resulting Match object.

Here is a small example:

using System;
using System.Text.RegularExpressions;

class Program
{
    static void Main()
    {
        String sample = "hello-world-";
        Regex regex = new Regex("-(?<test>[^-]*)-");

        Match match = regex.Match(sample);

        if (match.Success)
        {
            Console.WriteLine(match.Groups["test"].Value);
        }
    }
}

How to convert this var string to URL in Swift

in swift 4 to convert to url use URL

let fileUrl = URL.init(fileURLWithPath: filePath)

or

let fileUrl = URL(fileURLWithPath: filePath)

Delete with Join in MySQL

I'm more used to the subquery solution to this, but I have not tried it in MySQL:

DELETE  FROM posts
WHERE   project_id IN (
            SELECT  project_id
            FROM    projects
            WHERE   client_id = :client_id
        );

How to handle the modal closing event in Twitter Bootstrap?

If your modal div is dynamically added then use( For bootstrap 3 and 4)

$(document).on('hide.bs.modal','#modal-id', function () {
                alert('');
 //Do stuff here
});

This will work for non-dynamic content also.

Django - filtering on foreign key properties

student_user = User.objects.get(id=user_id)
available_subjects = Subject.objects.exclude(subject_grade__student__user=student_user) # My ans
enrolled_subjects = SubjectGrade.objects.filter(student__user=student_user)
context.update({'available_subjects': available_subjects, 'student_user': student_user, 
                'request':request, 'enrolled_subjects': enrolled_subjects})

In my application above, i assume that once a student is enrolled, a subject SubjectGrade instance will be created that contains the subject enrolled and the student himself/herself.

Subject and Student User model is a Foreign Key to the SubjectGrade Model.

In "available_subjects", i excluded all the subjects that are already enrolled by the current student_user by checking all subjectgrade instance that has "student" attribute as the current student_user

PS. Apologies in Advance if you can't still understand because of my explanation. This is the best explanation i Can Provide. Thank you so much

How to add new item to hash

If you want to add new items from another hash - use merge method:

hash = {:item1 => 1}
another_hash = {:item2 => 2, :item3 => 3}
hash.merge(another_hash) # {:item1=>1, :item2=>2, :item3=>3}

In your specific case it could be:

hash = {:item1 => 1}
hash.merge({:item2 => 2}) # {:item1=>1, :item2=>2}

but it's not wise to use it when you should to add just one element more.

Pay attention that merge will replace the values with the existing keys:

hash = {:item1 => 1}
hash.merge({:item1 => 2}) # {:item1=>2}

exactly like hash[:item1] = 2

Also you should pay attention that merge method (of course) doesn't effect the original value of hash variable - it returns a new merged hash. If you want to replace the value of the hash variable then use merge! instead:

hash = {:item1 => 1}
hash.merge!({:item2 => 2})
# now hash == {:item1=>1, :item2=>2}

Why an inline "background-image" style doesn't work in Chrome 10 and Internet Explorer 8?

u must specify the width and height also

 <section class="bg-solid-light slideContainer strut-slide-0" style="background-image: url(https://accounts.icharts.net/stage/icharts-images/chartbook-images/Chart1457601371484.png); background-repeat: no-repeat;width: 100%;height: 100%;" >

How can I remove the last character of a string in python?

The simplest way is to use slice. If x is your string variable then x[:-1] will return the string variable without the last character. (BTW, x[-1] is the last character in the string variable) You are looking for

my_file_path = '/home/ro/A_Python_Scripts/flask-auto/myDirectory/scarlett Johanson/1448543562.17.jpg/' my_file_path = my_file_path[:-1]

What exactly are iterator, iterable, and iteration?

Before dealing with the iterables and iterator the major factor that decide the iterable and iterator is sequence

Sequence: Sequence is the collection of data

Iterable: Iterable are the sequence type object that support __iter__ method.

Iter method: Iter method take sequence as an input and create an object which is known as iterator

Iterator: Iterator are the object which call next method and transverse through the sequence. On calling the next method it returns the object that it traversed currently.

example:

x=[1,2,3,4]

x is a sequence which consists of collection of data

y=iter(x)

On calling iter(x) it returns a iterator only when the x object has iter method otherwise it raise an exception.If it returns iterator then y is assign like this:

y=[1,2,3,4]

As y is a iterator hence it support next() method

On calling next method it returns the individual elements of the list one by one.

After returning the last element of the sequence if we again call the next method it raise an StopIteration error

example:

>>> y.next()
1
>>> y.next()
2
>>> y.next()
3
>>> y.next()
4
>>> y.next()
StopIteration

How do I use Comparator to define a custom sort order?

Define one Enum Type as

public enum Colors {
     BLUE, SILVER, MAGENTA, RED
}

Change data type of color from String to Colors Change return type and argument type of getter and setter method of color to Colors

Define comparator type as follows

static class ColorComparator implements Comparator<CarSort>
{
    public int compare(CarSort c1, CarSort c2)
    {
        return c1.getColor().compareTo(c2.getColor());
    }
}

after adding elements to List, call sort method of Collection by passing list and comparator objects as arguments

i.e, Collections.sort(carList, new ColorComparator()); then print using ListIterator.

full class implementation is as follows:

package test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;    
import java.util.ListIterator;

public class CarSort implements Comparable<CarSort>{

    String name;
    Colors color;

    public CarSort(String name, Colors color){
        this.name = name;
        this.color = color;
    } 

    public String getName() {
        return name;
    }
    public void setName(String name) {
        this.name = name;
    }
    public Colors getColor() {
        return color;
    }
    public void setColor(Colors color) {
        this.color = color;
    }

    //Implement the natural order for this class
    public int compareTo(CarSort c)
    {
        return getName().compareTo(c.getName());
    }

    static class ColorComparator implements Comparator<CarSort>
    {
        public int compare(CarSort c1, CarSort c2)
        {
            return c1.getColor().compareTo(c2.getColor());
        }
    }

    public enum Colors {
         BLUE, SILVER, MAGENTA, RED
    }

     public static void main(String[] args)
     {
         List<CarSort> carList = new ArrayList<CarSort>();
         List<String> sortOrder = new ArrayList<String>();

         carList.add(new CarSort("Ford Figo",Colors.SILVER));
         carList.add(new CarSort("Santro",Colors.BLUE));
         carList.add(new CarSort("Honda Jazz",Colors.MAGENTA));
         carList.add(new CarSort("Indigo V2",Colors.RED));
         Collections.sort(carList, new ColorComparator());

         ListIterator<CarSort> itr=carList.listIterator();
         while (itr.hasNext()) {
            CarSort carSort = (CarSort) itr.next();
            System.out.println("Car colors: "+carSort.getColor());
        }
     }
}

shorthand c++ if else statement

try this:

bigInt.sign = number < 0 ? 0 : 1

How get sound input from microphone in python, and process it on the fly?

If you are using LINUX, you can use pyALSAAUDIO. For windows, we have PyAudio and there is also a library called SoundAnalyse.

I found an example for Linux here:

#!/usr/bin/python
## This is an example of a simple sound capture script.
##
## The script opens an ALSA pcm for sound capture. Set
## various attributes of the capture, and reads in a loop,
## Then prints the volume.
##
## To test it out, run it and shout at your microphone:

import alsaaudio, time, audioop

# Open the device in nonblocking capture mode. The last argument could
# just as well have been zero for blocking mode. Then we could have
# left out the sleep call in the bottom of the loop
inp = alsaaudio.PCM(alsaaudio.PCM_CAPTURE,alsaaudio.PCM_NONBLOCK)

# Set attributes: Mono, 8000 Hz, 16 bit little endian samples
inp.setchannels(1)
inp.setrate(8000)
inp.setformat(alsaaudio.PCM_FORMAT_S16_LE)

# The period size controls the internal number of frames per period.
# The significance of this parameter is documented in the ALSA api.
# For our purposes, it is suficcient to know that reads from the device
# will return this many frames. Each frame being 2 bytes long.
# This means that the reads below will return either 320 bytes of data
# or 0 bytes of data. The latter is possible because we are in nonblocking
# mode.
inp.setperiodsize(160)

while True:
    # Read data from device
    l,data = inp.read()
    if l:
        # Return the maximum of the absolute value of all samples in a fragment.
        print audioop.max(data, 2)
    time.sleep(.001)

SQLSTATE[HY000] [2002] Connection refused within Laravel homestead

In my case this error appeared out of blue. While staring at that mysterious error I've realized, that I was trying to run the command outside of vm...

HTML5 best practices; section/header/aside/article elements

„line 23. Is this div right? or must this be a section?“

Neither – there is a main tag for that purpose, which is only allowed once per page and should be used as a wrapper for the main content (in contrast to a sidebar or a site-wide header).

<main>
    <!-- The main content -->
</main>

http://www.w3.org/html/wg/drafts/html/master/grouping-content.html#the-main-element

Run function from the command line

python -c 'from myfile import hello; hello()' where myfile must be replaced with the basename of your Python script. (E.g., myfile.py becomes myfile).

However, if hello() is your "permanent" main entry point in your Python script, then the usual way to do this is as follows:

def hello():
    print "Hi :)"

if __name__ == "__main__":
    hello()

This allows you to execute the script simply by running python myfile.py or python -m myfile.

Some explanation here: __name__ is a special Python variable that holds the name of the module currently being executed, except when the module is started from the command line, in which case it becomes "__main__".

How to insert logo with the title of a HTML page?

Put this in the <head> section:

<link rel="icon" href="http://www.domain.com/favicon.ico" type="image/x-icon" />
<link rel="shortcut icon" href="http://www.domain.com/favicon.ico" type="image/x-icon" />

Keep the picture file named "favicon.ico". You'll have to look online to get a .ico file generator.

Spring MVC: Complex object as GET @RequestParam

Yes, You can do it in a simple way. See below code of lines.

URL - http://localhost:8080/get/request/multiple/param/by/map?name='abc' & id='123'

 @GetMapping(path = "/get/request/header/by/map")
    public ResponseEntity<String> getRequestParamInMap(@RequestParam Map<String,String> map){
        // Do your business here 
        return new ResponseEntity<String>(map.toString(),HttpStatus.OK);
    } 

How to take the nth digit of a number in python

You can do it with integer division and remainder methods

def get_digit(number, n):
    return number // 10**n % 10

get_digit(987654321, 0)
# 1

get_digit(987654321, 5)
# 6

The // performs integer division by a power of ten to move the digit to the ones position, then the % gets the remainder after division by 10. Note that the numbering in this scheme uses zero-indexing and starts from the right side of the number.

How to build minified and uncompressed bundle with webpack?

You should export an array like this:

const path = require('path');
const webpack = require('webpack');

const libName = 'YourLibraryName';

function getConfig(env) {
  const config = {
    mode: env,
    output: {
      path: path.resolve('dist'),
      library: libName,
      libraryTarget: 'umd',
      filename: env === 'production' ? `${libName}.min.js` : `${libName}.js`
    },
    target: 'web',
    .... your shared options ...
  };

  return config;
}

module.exports = [
  getConfig('development'),
  getConfig('production'),
];

Append same text to every cell in a column in Excel

See if this works for you.

  • All your data is in column A (beginning at row 1).
  • In column B, row 1, enter =A1&","
  • This will make cell B1 equal A1 with a comma appended.
  • Now select cell B1 and drag from the bottom right of cell down through all your rows (this copies the formula and uses the corresponding column A value.)
  • Select the newly appended data, copy it and paste it where you need using Paste -> By Value

That's It!

How do I convert ticks to minutes?

TimeSpan.FromTicks(28000000000).TotalMinutes;

How to convert a list into data table

Just add this function and call it, it will convert List to DataTable.

public static DataTable ToDataTable<T>(List<T> items)
{
        DataTable dataTable = new DataTable(typeof(T).Name);

        //Get all the properties
        PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        foreach (PropertyInfo prop in Props)
        {
            //Defining type of data column gives proper data table 
            var type = (prop.PropertyType.IsGenericType && prop.PropertyType.GetGenericTypeDefinition() == typeof(Nullable<>) ? Nullable.GetUnderlyingType(prop.PropertyType) : prop.PropertyType);
            //Setting column names as Property names
            dataTable.Columns.Add(prop.Name, type);
        }
        foreach (T item in items)
        {
           var values = new object[Props.Length];
           for (int i = 0; i < Props.Length; i++)
           {
                //inserting property values to datatable rows
                values[i] = Props[i].GetValue(item, null);
           }
           dataTable.Rows.Add(values);
      }
      //put a breakpoint here and check datatable
      return dataTable;
}

JSTL if tag for equal strings

<c:if test="${ansokanInfo.pSystem eq 'NAT'}">

What GRANT USAGE ON SCHEMA exactly do?

For a production system, you can use this configuration :

--ACCESS DB
REVOKE CONNECT ON DATABASE nova FROM PUBLIC;
GRANT  CONNECT ON DATABASE nova  TO user;

--ACCESS SCHEMA
REVOKE ALL     ON SCHEMA public FROM PUBLIC;
GRANT  USAGE   ON SCHEMA public  TO user;

--ACCESS TABLES
REVOKE ALL ON ALL TABLES IN SCHEMA public FROM PUBLIC ;
GRANT SELECT                         ON ALL TABLES IN SCHEMA public TO read_only ;
GRANT SELECT, INSERT, UPDATE, DELETE ON ALL TABLES IN SCHEMA public TO read_write ;
GRANT ALL                            ON ALL TABLES IN SCHEMA public TO admin ;

SQL Server using wildcard within IN

In Access SQL, I would use this. I'd imagine that SQLserver has the same syntax.

select * from jobdetails where job_no like "0711*" or job_no like "0712*"