Programs & Examples On #Nhibernate criteria

The NHibernate Criteria API allows performing dynamic, object oriented queries in NHibernate.

mysql query result in php variable

$query    =    "SELECT username, userid FROM user WHERE username = 'admin' ";
$result    =    $conn->query($query);

if (!$result) {
  echo 'Could not run query: ' . mysql_error();
  exit;
}

$arrayResult    =    mysql_fetch_array($result);

//Now you can access $arrayResult like this

$arrayResult['userid'];    // output will be userid which will be in database
$arrayResult['username'];  // output will be admin

//Note- userid and username will be column name of user table.

How do I print bytes as hexadecimal?

C:

static void print_buf(const char *title, const unsigned char *buf, size_t buf_len)
{
    size_t i = 0;
    fprintf(stdout, "%s\n", title);
    for(i = 0; i < buf_len; ++i)
    fprintf(stdout, "%02X%s", buf[i],
             ( i + 1 ) % 16 == 0 ? "\r\n" : " " );

}

C++:

void print_bytes(std::ostream& out, const char *title, const unsigned char *data, size_t dataLen, bool format = true) {
    out << title << std::endl;
    out << std::setfill('0');
    for(size_t i = 0; i < dataLen; ++i) {
        out << std::hex << std::setw(2) << (int)data[i];
        if (format) {
            out << (((i + 1) % 16 == 0) ? "\n" : " ");
        }
    }
    out << std::endl;
}

HTTP response header content disposition for attachments

neither use inline; nor attachment; just use

response.setContentType("text/xml");
response.setHeader( "Content-Disposition", "filename=" + filename );

or

response.setHeader( "Content-Disposition", "filename=\"" + filename + "\"" );

or

response.setHeader( "Content-Disposition", "filename=\"" + 
  filename.substring(0, filename.lastIndexOf('.')) + "\"");

The resource could not be loaded because the App Transport Security policy requires the use of a secure connection

Transport security is provided in iOS 9.0 or later, and in OS X v10.11 and later.

So by default only https calls only allowed in apps. To turn off App Transport Security add following lines in info.plist file...

<key>NSAppTransportSecurity</key>
  <dict>
    <key>NSAllowsArbitraryLoads</key>
    <true/>
  </dict>

For more info:
https://developer.apple.com/library/content/documentation/General/Reference/InfoPlistKeyReference/Articles/CocoaKeys.html#//apple_ref/doc/uid/TP40009251-SW33

Replace part of a string with another string

If you want to do it quickly you can use a two scan approach. Pseudo code:

  1. first parse. find how many matching chars.
  2. expand the length of the string.
  3. second parse. Start from the end of the string when we get a match we replace, else we just copy the chars from the first string.

I am not sure if this can be optimized to an in-place algo.

And a C++11 code example but I only search for one char.

#include <string>
#include <iostream>
#include <algorithm>
using namespace std;

void ReplaceString(string& subject, char search, const string& replace)
{   
    size_t initSize = subject.size();
    int count = 0;
    for (auto c : subject) { 
        if (c == search) ++count;
    }

    size_t idx = subject.size()-1 + count * replace.size()-1;
    subject.resize(idx + 1, '\0');

    string reverseReplace{ replace };
    reverse(reverseReplace.begin(), reverseReplace.end());  

    char *end_ptr = &subject[initSize - 1];
    while (end_ptr >= &subject[0])
    {
        if (*end_ptr == search) {
            for (auto c : reverseReplace) {
                subject[idx - 1] = c;
                --idx;              
            }           
        }
        else {
            subject[idx - 1] = *end_ptr;
            --idx;
        }
        --end_ptr;
    }
}

int main()
{
    string s{ "Mr John Smith" };
    ReplaceString(s, ' ', "%20");
    cout << s << "\n";

}

How to get complete current url for Cakephp

Getting current URL for CakePHP 3.x ?

In your layout :

<?php 
    $here = $this->request->here();
    $canonical = $this->Url->build($here, true);
?>

You will get the full URL of the current page including query string parameters.

e.g. http://website.example/controller/action?param=value

You can use it in a meta tag canonical if you need to do some SEO.

<link rel="canonical" href="<?= $canonical; ?>">

Animate background image change with jQuery

Ok, I figured it out, this is pretty simple with a little html trick:

http://jsfiddle.net/kRjrn/8/

HTML

<body>
    <div id="background">.
    </div>
    <p>hello world</p>
    <p>hello world</p>
    <p>hello world</p>
    <p>hello world</p>    
</body>?

javascript

$(document).ready(function(){
    $('#background').animate({ opacity: 1 }, 3000);
});?

CSS

#background {
    background-image: url("http://media.noupe.com//uploads/2009/10/wallpaper-pattern.jpg");
    opacity: 0;
    margin: 0;
    padding: 0;
    z-index: -1;
    position: absolute;
    width: 100%;
    height: 100%;
}?

Django - what is the difference between render(), render_to_response() and direct_to_template()?

Just one note I could not find in the answers above. In this code:

context_instance = RequestContext(request)
return render_to_response(template_name, user_context, context_instance)

What the third parameter context_instance actually does? Being RequestContext it sets up some basic context which is then added to user_context. So the template gets this extended context. What variables are added is given by TEMPLATE_CONTEXT_PROCESSORS in settings.py. For instance django.contrib.auth.context_processors.auth adds variable user and variable perm which are then accessible in the template.

The authorization mechanism you have provided is not supported. Please use AWS4-HMAC-SHA256

I have been using Django, and I had to add these extra config variables to make this work. (in addition to settings mentioned in https://simpleisbetterthancomplex.com/tutorial/2017/08/01/how-to-setup-amazon-s3-in-a-django-project.html).

AWS_S3_REGION_NAME = "ap-south-1"

Or previous to boto3 version 1.4.4:

AWS_S3_REGION_NAME = "ap-south-1"

AWS_S3_SIGNATURE_VERSION = "s3v4"

How to update Ruby with Homebrew?

To upgrade Ruby with rbenv: Per the rbenv README

  • Update first: brew upgrade rbenv ruby-build
  • See list of Ruby versions: versions available: rbenv install -l
  • Install: rbenv install <selected version>

"Gradle Version 2.10 is required." Error

My problem maybe is different,so I just wanna tell somebody who may have the same problem as me.

I solved this problem by change Terminal path. when I run gradle clean, the error come cross "Gradle version 2.10 is required. Current version is 2.2.1".

I checked .gradle directory in my project, there are two versions in it: 2.2.1, 2.10.

when I run gradle -v, it shows my current version is 2.2.1. I change my system environment GRADLE_HOME to 2.10 root directory, then I restart terminal in AS and run 'gradle -v', it still shows the current verision is 2.2.1.

open setting -> terminal change the cmd.exe path to the System32/cmd.exe. then restart terminal, run gradle clean,everything is fine.

PHP is not recognized as an internal or external command in command prompt

Set "C:\xampp\php" in your PATH Environment Variable. Then restart CMD prompt.

Typedef function pointer?

typedef is a language construct that associates a name to a type.
You use it the same way you would use the original type, for instance

  typedef int myinteger;
  typedef char *mystring;
  typedef void (*myfunc)();

using them like

  myinteger i;   // is equivalent to    int i;
  mystring s;    // is the same as      char *s;
  myfunc f;      // compile equally as  void (*f)();

As you can see, you could just replace the typedefed name with its definition given above.

The difficulty lies in the pointer to functions syntax and readability in C and C++, and the typedef can improve the readability of such declarations. However, the syntax is appropriate, since functions - unlike other simpler types - may have a return value and parameters, thus the sometimes lengthy and complex declaration of a pointer to function.

The readability may start to be really tricky with pointers to functions arrays, and some other even more indirect flavors.

To answer your three questions

  • Why is typedef used? To ease the reading of the code - especially for pointers to functions, or structure names.

  • The syntax looks odd (in the pointer to function declaration) That syntax is not obvious to read, at least when beginning. Using a typedef declaration instead eases the reading

  • Is a function pointer created to store the memory address of a function? Yes, a function pointer stores the address of a function. This has nothing to do with the typedef construct which only ease the writing/reading of a program ; the compiler just expands the typedef definition before compiling the actual code.

Example:

typedef int (*t_somefunc)(int,int);

int product(int u, int v) {
  return u*v;
}

t_somefunc afunc = &product;
...
int x2 = (*afunc)(123, 456); // call product() to calculate 123*456

In MySQL, can I copy one row to insert into the same table?

clone row with update fields and auto increment value

CREATE TEMPORARY TABLE `temp` SELECT * FROM `testing` WHERE id = 14;

UPDATE `temp` SET id = (SELECT id FROM testing ORDER by id DESC LIMIT 1
 )+1, user_id = 252 ,policy_no = "mysdddd12" where id = 14;

INSERT INTO `testing` SELECT * FROM `temp`;

DROP TEMPORARY TABLE IF EXISTS `temp`;

How does Java import work?

javac (or java during runtime) looks for the classes being imported in the classpath. If they are not there in the classpath then classnotfound exceptions are thrown.

classpath is just like the path variable in a shell, which is used by the shell to find a command or executable.

Entire directories or individual jar files can be put in the classpath. Also, yes a classpath can perhaps include a path which is not local but is somewhere on the internet. Please read more about classpath to resolve your doubts.

Remove object from a list of objects in python

If you know the array location you can can pass it into itself. If you are removing multiple items I suggest you remove them in reverse order.

#Setup array
array = [55,126,555,2,36]
#Remove 55 which is in position 0
array.remove(array[0])

How to search for a string inside an array of strings

Extending the contains function you linked to:

containsRegex(a, regex){
  for(var i = 0; i < a.length; i++) {
    if(a[i].search(regex) > -1){
      return i;
    }
  }
  return -1;
}

Then you call the function with an array of strings and a regex, in your case to look for height:

containsRegex([ '<param name=\"bgcolor\" value=\"#FFFFFF\" />', 'sdafkdf' ], /height/)

You could additionally also return the index where height was found:

containsRegex(a, regex){
  for(var i = 0; i < a.length; i++) {
    int pos = a[i].search(regex);
    if(pos > -1){
      return [i, pos];
    }
  }
  return null;
}

jQuery and AJAX response header

cballou's solution will work if you are using an old version of jquery. In newer versions you can also try:

  $.ajax({
   type: 'POST',
   url:'url.do',
   data: formData,
   success: function(data, textStatus, request){
        alert(request.getResponseHeader('some_header'));
   },
   error: function (request, textStatus, errorThrown) {
        alert(request.getResponseHeader('some_header'));
   }
  });

According to docs the XMLHttpRequest object is available as of jQuery 1.4.

What does the clearfix class do in css?

How floats work

When floating elements exist on the page, non-floating elements wrap around the floating elements, similar to how text goes around a picture in a newspaper. From a document perspective (the original purpose of HTML), this is how floats work.

float vs display:inline

Before the invention of display:inline-block, websites use float to set elements beside each other. float is preferred over display:inline since with the latter, you can't set the element's dimensions (width and height) as well as vertical paddings (top and bottom) - which floated elements can do since they're treated as block elements.

Float problems

The main problem is that we're using float against its intended purpose.

Another is that while float allows side-by-side block-level elements, floats do not impart shape to its container. It's like position:absolute, where the element is "taken out of the layout". For instance, when an empty container contains a floating 100px x 100px <div>, the <div> will not impart 100px in height to the container.

Unlike position:absolute, it affects the content that surrounds it. Content after the floated element will "wrap" around the element. It starts by rendering beside it and then below it, like how newspaper text would flow around an image.

Clearfix to the rescue

What clearfix does is to force content after the floats or the container containing the floats to render below it. There are a lot of versions for clear-fix, but it got its name from the version that's commonly being used - the one that uses the CSS property clear.

Examples

Here are several ways to do clearfix , depending on the browser and use case. One only needs to know how to use the clear property in CSS and how floats render in each browser in order to achieve a perfect cross-browser clear-fix.

What you have

Your provided style is a form of clearfix with backwards compatibility. I found an article about this clearfix. It turns out, it's an OLD clearfix - still catering the old browsers. There is a newer, cleaner version of it in the article also. Here's the breakdown:

  • The first clearfix you have appends an invisible pseudo-element, which is styled clear:both, between the target element and the next element. This forces the pseudo-element to render below the target, and the next element below the pseudo-element.

  • The second one appends the style display:inline-block which is not supported by earlier browsers. inline-block is like inline but gives you some properties that block elements, like width, height as well as vertical padding. This was targeted for IE-MAC.

  • This was the reapplication of display:block due to IE-MAC rule above. This rule was "hidden" from IE-MAC.

All in all, these 3 rules keep the .clearfix working cross-browser, with old browsers in mind.

How to inject JPA EntityManager using spring

The latest Spring + JPA versions solve this problem fundamentally. You can learn more how to use Spring and JPA togather in a separate thread

How to position one element relative to another with jQuery?

NOTE: This requires jQuery UI (not just jQuery).

You can now use:

$("#my_div").position({
    my:        "left top",
    at:        "left bottom",
    of:        this, // or $("#otherdiv")
    collision: "fit"
});

For fast positioning (jQuery UI/Position).

You can download jQuery UI here.

vbscript output to console

You only need to force cscript instead wscript. I always use this template. The function ForceConsole() will execute your vbs into cscript, also you have nice alias to print and scan text.

 Set oWSH = CreateObject("WScript.Shell")
 vbsInterpreter = "cscript.exe"

 Call ForceConsole()

 Function printf(txt)
    WScript.StdOut.WriteLine txt
 End Function

 Function printl(txt)
    WScript.StdOut.Write txt
 End Function

 Function scanf()
    scanf = LCase(WScript.StdIn.ReadLine)
 End Function

 Function wait(n)
    WScript.Sleep Int(n * 1000)
 End Function

 Function ForceConsole()
    If InStr(LCase(WScript.FullName), vbsInterpreter) = 0 Then
        oWSH.Run vbsInterpreter & " //NoLogo " & Chr(34) & WScript.ScriptFullName & Chr(34)
        WScript.Quit
    End If
 End Function

 Function cls()
    For i = 1 To 50
        printf ""
    Next
 End Function

 printf " _____ _ _           _____         _    _____         _     _   "
 printf "|  _  |_| |_ ___ ___|     |_ _ _ _| |  |   __|___ ___|_|___| |_ "
 printf "|     | | '_| . |   |   --| | | | . |  |__   |  _|  _| | . |  _|"
 printf "|__|__|_|_,_|___|_|_|_____|_____|___|  |_____|___|_| |_|  _|_|  "
 printf "                                                       |_|     v1.0"
 printl " Enter your name:"
 MyVar = scanf
 cls
 printf "Your name is: " & MyVar
 wait(5)

Standard concise way to copy a file in Java?

Three possible problems with the above code:

  1. If getChannel throws an exception, you might leak an open stream.
  2. For large files, you might be trying to transfer more at once than the OS can handle.
  3. You are ignoring the return value of transferFrom, so it might be copying just part of the file.

This is why org.apache.tools.ant.util.ResourceUtils.copyResource is so complicated. Also note that while transferFrom is OK, transferTo breaks on JDK 1.4 on Linux (see Bug ID:5056395) – Jesse Glick Jan

What is Scala's yield?

I think the accepted answer is great, but it seems many people have failed to grasp some fundamental points.

First, Scala's for comprehensions are equivalent to Haskell's do notation, and it is nothing more than a syntactic sugar for composition of multiple monadic operations. As this statement will most likely not help anyone who needs help, let's try again… :-)

Scala's for comprehensions is syntactic sugar for composition of multiple operations with map, flatMap and filter. Or foreach. Scala actually translates a for-expression into calls to those methods, so any class providing them, or a subset of them, can be used with for comprehensions.

First, let's talk about the translations. There are very simple rules:

  1. This

    for(x <- c1; y <- c2; z <-c3) {...}
    

    is translated into

    c1.foreach(x => c2.foreach(y => c3.foreach(z => {...})))
    
  2. This

    for(x <- c1; y <- c2; z <- c3) yield {...}
    

    is translated into

    c1.flatMap(x => c2.flatMap(y => c3.map(z => {...})))
    
  3. This

    for(x <- c; if cond) yield {...}
    

    is translated on Scala 2.7 into

    c.filter(x => cond).map(x => {...})
    

    or, on Scala 2.8, into

    c.withFilter(x => cond).map(x => {...})
    

    with a fallback into the former if method withFilter is not available but filter is. Please see the section below for more information on this.

  4. This

    for(x <- c; y = ...) yield {...}
    

    is translated into

    c.map(x => (x, ...)).map((x,y) => {...})
    

When you look at very simple for comprehensions, the map/foreach alternatives look, indeed, better. Once you start composing them, though, you can easily get lost in parenthesis and nesting levels. When that happens, for comprehensions are usually much clearer.

I'll show one simple example, and intentionally omit any explanation. You can decide which syntax was easier to understand.

l.flatMap(sl => sl.filter(el => el > 0).map(el => el.toString.length))

or

for {
  sl <- l
  el <- sl
  if el > 0
} yield el.toString.length

withFilter

Scala 2.8 introduced a method called withFilter, whose main difference is that, instead of returning a new, filtered, collection, it filters on-demand. The filter method has its behavior defined based on the strictness of the collection. To understand this better, let's take a look at some Scala 2.7 with List (strict) and Stream (non-strict):

scala> var found = false
found: Boolean = false

scala> List.range(1,10).filter(_ % 2 == 1 && !found).foreach(x => if (x == 5) found = true else println(x))
1
3
7
9

scala> found = false
found: Boolean = false

scala> Stream.range(1,10).filter(_ % 2 == 1 && !found).foreach(x => if (x == 5) found = true else println(x))
1
3

The difference happens because filter is immediately applied with List, returning a list of odds -- since found is false. Only then foreach is executed, but, by this time, changing found is meaningless, as filter has already executed.

In the case of Stream, the condition is not immediatelly applied. Instead, as each element is requested by foreach, filter tests the condition, which enables foreach to influence it through found. Just to make it clear, here is the equivalent for-comprehension code:

for (x <- List.range(1, 10); if x % 2 == 1 && !found) 
  if (x == 5) found = true else println(x)

for (x <- Stream.range(1, 10); if x % 2 == 1 && !found) 
  if (x == 5) found = true else println(x)

This caused many problems, because people expected the if to be considered on-demand, instead of being applied to the whole collection beforehand.

Scala 2.8 introduced withFilter, which is always non-strict, no matter the strictness of the collection. The following example shows List with both methods on Scala 2.8:

scala> var found = false
found: Boolean = false

scala> List.range(1,10).filter(_ % 2 == 1 && !found).foreach(x => if (x == 5) found = true else println(x))
1
3
7
9

scala> found = false
found: Boolean = false

scala> List.range(1,10).withFilter(_ % 2 == 1 && !found).foreach(x => if (x == 5) found = true else println(x))
1
3

This produces the result most people expect, without changing how filter behaves. As a side note, Range was changed from non-strict to strict between Scala 2.7 and Scala 2.8.

Using curl POST with variables defined in bash script functions

Curl can post binary data from a file so I have been using process substitution and taking advantage of file descriptors whenever I need to post something nasty with curl and still want access to the vars in the current shell. Something like:

curl "http://localhost:8080" \
-H "Accept: application/json" \
-H "Content-Type:application/json" \
--data @<(cat <<EOF
{
  "me": "$USER",
  "something": $(date +%s)
  }
EOF
)

This winds up looking like --data @/dev/fd/<some number> which just gets processed like a normal file. Anyway if you wanna see it work locally just run nc -l 8080 first and in a different shell fire off the above command. You will see something like:

POST / HTTP/1.1
Host: localhost:8080
User-Agent: curl/7.43.0
Accept: application/json
Content-Type:application/json
Content-Length: 43

{  "me": "username",  "something": 1465057519  }

As you can see you can call subshells and whatnot as well as reference vars in the heredoc. Happy hacking hope this helps with the '"'"'""""'''""''.

Return Boolean Value on SQL Select Statement

Notice another equivalent problem: Creating an SQL query that returns (1) if the condition is satisfied and an empty result otherwise. Notice that a solution to this problem is more general and can easily be used with the above answers to achieve the question that you asked. Since this problem is more general, I am proving its solution in addition to the beautiful solutions presented above to your problem.

SELECT DISTINCT 1 AS Expr1
FROM [User]
WHERE (UserID = 20070022)

Create a folder inside documents folder in iOS apps

Swift 1.2 and iOS 8

Create custom directory (name = "MyCustomData") inside the documents directory but only if the directory does not exist.

// path to documents directory
let documentDirectoryPath = NSSearchPathForDirectoriesInDomains(.DocumentDirectory, .UserDomainMask, true).first as! String

// create the custom folder path
let myCustomDataDirectoryPath = documentDirectoryPath.stringByAppendingPathComponent("/MyCustomData")

// check if directory does not exist
if NSFileManager.defaultManager().fileExistsAtPath(myCustomDataDirectoryPath) == false {

    // create the directory
    var createDirectoryError: NSError? = nil
    NSFileManager.defaultManager().createDirectoryAtPath(myCustomDataDirectoryPath, withIntermediateDirectories: false, attributes: nil, error: &createDirectoryError)

    // handle the error, you may call an exception
    if createDirectoryError != nil {
        println("Handle directory creation error...")
    }

}

How do I resolve a HTTP 414 "Request URI too long" error?

An excerpt from the RFC 2616: Hypertext Transfer Protocol -- HTTP/1.1:

The POST method is used to request that the origin server accept the entity enclosed in the request as a new subordinate of the resource identified by the Request-URI in the Request-Line. POST is designed to allow a uniform method to cover the following functions:

  • Annotation of existing resources;
  • Posting a message to a bulletin board, newsgroup, mailing list, or similar group of articles;
  • Providing a block of data, such as the result of submitting a form, to a data-handling process;
  • Extending a database through an append operation.

Environment variable in Jenkins Pipeline

To avoid problems of side effects after changing env, especially using multiple nodes, it is better to set a temporary context.

One safe way to alter the environment is:

 withEnv(['MYTOOL_HOME=/usr/local/mytool']) {
    sh '$MYTOOL_HOME/bin/start'
 }

This approach does not poison the env after the command execution.

How to get the Display Name Attribute of an Enum member via MVC Razor code?

UPDATE

First solution was focused on getting display names from enum. Code below should be exact solution for your problem.

You can use this helper class for enums:

using System;
using System.Collections.Generic;
using System.ComponentModel.DataAnnotations;
using System.Linq;
using System.Reflection;

public static class EnumHelper<T>
    where T : struct, Enum // This constraint requires C# 7.3 or later.
{
    public static IList<T> GetValues(Enum value)
    {
        var enumValues = new List<T>();

        foreach (FieldInfo fi in value.GetType().GetFields(BindingFlags.Static | BindingFlags.Public))
        {
            enumValues.Add((T)Enum.Parse(value.GetType(), fi.Name, false));
        }
        return enumValues;
    }

    public static T Parse(string value)
    {
        return (T)Enum.Parse(typeof(T), value, true);
    }

    public static IList<string> GetNames(Enum value)
    {
        return value.GetType().GetFields(BindingFlags.Static | BindingFlags.Public).Select(fi => fi.Name).ToList();
    }

    public static IList<string> GetDisplayValues(Enum value)
    {
        return GetNames(value).Select(obj => GetDisplayValue(Parse(obj))).ToList();
    }

    private static string lookupResource(Type resourceManagerProvider, string resourceKey)
    {
        foreach (PropertyInfo staticProperty in resourceManagerProvider.GetProperties(BindingFlags.Static | BindingFlags.NonPublic | BindingFlags.Public))
        {
            if (staticProperty.PropertyType == typeof(System.Resources.ResourceManager))
            {
                System.Resources.ResourceManager resourceManager = (System.Resources.ResourceManager)staticProperty.GetValue(null, null);
                return resourceManager.GetString(resourceKey);
            }
        }

        return resourceKey; // Fallback with the key name
    }

    public static string GetDisplayValue(T value)
    {
        var fieldInfo = value.GetType().GetField(value.ToString());

        var descriptionAttributes = fieldInfo.GetCustomAttributes(
            typeof(DisplayAttribute), false) as DisplayAttribute[];

        if (descriptionAttributes[0].ResourceType != null)
            return lookupResource(descriptionAttributes[0].ResourceType, descriptionAttributes[0].Name);

        if (descriptionAttributes == null) return string.Empty;
        return (descriptionAttributes.Length > 0) ? descriptionAttributes[0].Name : value.ToString();
    }
}

And then you can use it in your view as following:

<ul>
    @foreach (var value in @EnumHelper<UserPromotion>.GetValues(UserPromotion.None))
    {
         if (value == Model.JobSeeker.Promotion)
        {
            var description = EnumHelper<UserPromotion>.GetDisplayValue(value);
            <li>@Html.DisplayFor(e => description )</li>
        }
    }
</ul>

Hope it helps! :)

Split string into strings by length?

  • :param s: str; source string
  • :param w: int; width to split on

Using the textwrap module:

PyDocs-textwrap

import textwrap
def wrap(s, w):
    return textwrap.fill(s, w)

:return str:

Inspired by Alexander's Answer

PyDocs-data structures

def wrap(s, w):
    return [s[i:i + w] for i in range(0, len(s), w)]
  • :return list:

Inspired by Eric's answer

PyDocs-regex

import re
def wrap(s, w):    
    sre = re.compile(rf'(.{{{w}}})')
    return [x for x in re.split(sre, s) if x]
  • :return list:

Complete Code Examples/Alternative Methods

How to Get the Current URL Inside @if Statement (Blade) in Laravel 4?

instead of using the URL::path() to check your current path location, you may want to consider the Route::currentRouteName() so just in case you update your path, you don't need to explore all your pages to update the path name again.

How to get all the values of input array element jquery

Use:

function getvalues(){
var inps = document.getElementsByName('pname[]');
for (var i = 0; i <inps.length; i++) {
var inp=inps[i];
    alert("pname["+i+"].value="+inp.value);
}
}

Here is Demo.

How can I install Apache Ant on Mac OS X?

Use Brew is always good way to install ANT and other needs. To install type below command on terminal.

/usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

after Brew installation , type

brew install ant

This will install Ant on your system. Also you will not need to worry about setting up the path.

Also i have documented on the same - How to Install ANT on Mac OS?

How can I selectively merge or pick changes from another branch in Git?

1800 INFORMATION's answer is completely correct. As someone new to Git, though, "use git cherry-pick" wasn't enough for me to figure this out without a bit more digging on the Internet, so I thought I'd post a more detailed guide in case anyone else is in a similar boat.

My use case was wanting to selectively pull changes from someone else's GitHub branch into my own. If you already have a local branch with the changes, you only need to do steps 2 and 5-7.

  1. Create (if not created) a local branch with the changes you want to bring in.

    $ git branch mybranch <base branch>

  2. Switch into it.

    $ git checkout mybranch

  3. Pull down the changes you want from the other person's account. If you haven't already, you'll want to add them as a remote.

    $ git remote add repos-w-changes <git url>

  4. Pull down everything from their branch.

    $ git pull repos-w-changes branch-i-want

  5. View the commit logs to see which changes you want:

    $ git log

  6. Switch back to the branch you want to pull the changes into.

    $ git checkout originalbranch

  7. Cherry pick your commits, one by one, with the hashes.

    $ git cherry-pick -x hash-of-commit

How to multiply a BigDecimal by an integer in Java

First off, BigDecimal.multiply() returns a BigDecimal and you're trying to store that in an int.

Second, it takes another BigDecimal as the argument, not an int.

If you just use the BigDecimal for all variables involved in these calculations, it should work fine.

How to force garbage collector to run?

GC.Collect() 

from MDSN,

Use this method to try to reclaim all memory that is inaccessible.

All objects, regardless of how long they have been in memory, are considered for collection; however, objects that are referenced in managed code are not collected. Use this method to force the system to try to reclaim the maximum amount of available memory.

Monitor network activity in Android Phones

Packet Capture is the best tool to track network data on the android. DOesnot need any root access and easy to read and save the calls based on application. Check this out

how to display a div triggered by onclick event

Here you go:

div{
    display: none;
}

document.querySelector("button").addEventListener("click", function(){
    document.querySelector("div").style.display = "block";
});

<div>blah blah blah</div>
<button>Show</button>

LIVE DEMO: http://jsfiddle.net/DerekL/p78Qq/

How to call servlet through a JSP page

You can submit your jsp page to servlet. For this use <form> tag.

And to redirect use:

response.sendRedirect("servleturl")

How to disable phone number linking in Mobile Safari?

You could try encoding them as HTML entities:

&#48; = 0
&#57; = 9

Add "Are you sure?" to my excel button, how can I?

Create a new sub with the following code and assign it to your button. Change the "DeleteProcess" to the name of your code to do the deletion. This will pop up a box with OK or Cancel and will call your delete sub if you hit ok and not if you hit cancel.

Sub AreYouSure()

Dim Sure As Integer

Sure = MsgBox("Are you sure?", vbOKCancel)
If Sure = 1 Then Call DeleteProcess

End Sub

Jesse

How to delete a cookie using jQuery?

Worked for me only when path was set, i.e.:

$.cookie('name', null, {path:'/'})

SHA-1 fingerprint of keystore certificate

Easiest way for getting SHA1 Key in android studio both (Debug and release Mode)

  1. Open Android Studio
  2. Open Your Project
  3. Click on Gradle (From Right Side Panel, you will see Gradle Bar)
  4. Click on Refresh (Click on Refresh from Gradle Bar , you will see List Gradle scripts of your Project)
  5. Click on Your Project (Your Project Name form List)
  6. Click on Tasks/Android
  7. Double Click on signingReport (You will get SHA1 and MD5 in Run Bar)

If you are using new Android Studio it shows time to execute on top there is Toggle task execution mode click on that you will get you SHA-1 key. Check 2nd and 3rd reference images.

Check image for details enter image description hereenter image description here

Generate SHA-1 for Release Mode

1-First add keystore config in your gradle How to add config in gradle.

2-After Adding Config in gradle change build variant. enter image description here

3-Then Follow Above Procedure you will get SHA-1 for release mode.

4-Check Image. enter image description here

Simplest way to merge ES6 Maps/Sets?

Edit:

I benchmarked my original solution against other solutions suggests here and found that it is very inefficient.

The benchmark itself is very interesting (link) It compares 3 solutions (higher is better):

  • @fregante (formerly called @bfred.it) solution, which adds values one by one (14,955 op/sec)
  • @jameslk's solution, which uses a self invoking generator (5,089 op/sec)
  • my own, which uses reduce & spread (3,434 op/sec)

As you can see, @fregante's solution is definitely the winner.

Performance + Immutability

With that in mind, here's a slightly modified version which doesn't mutates the original set and excepts a variable number of iterables to combine as arguments:

function union(...iterables) {
  const set = new Set();

  for (const iterable of iterables) {
    for (const item of iterable) {
      set.add(item);
    }
  }

  return set;
}

Usage:

const a = new Set([1, 2, 3]);
const b = new Set([1, 3, 5]);
const c = new Set([4, 5, 6]);

union(a,b,c) // {1, 2, 3, 4, 5, 6}

Original Answer

I would like to suggest another approach, using reduce and the spread operator:

Implementation

function union (sets) {
  return sets.reduce((combined, list) => {
    return new Set([...combined, ...list]);
  }, new Set());
}

Usage:

const a = new Set([1, 2, 3]);
const b = new Set([1, 3, 5]);
const c = new Set([4, 5, 6]);

union([a, b, c]) // {1, 2, 3, 4, 5, 6}

Tip:

We can also make use of the rest operator to make the interface a bit nicer:

function union (...sets) {
  return sets.reduce((combined, list) => {
    return new Set([...combined, ...list]);
  }, new Set());
}

Now, instead of passing an array of sets, we can pass an arbitrary number of arguments of sets:

union(a, b, c) // {1, 2, 3, 4, 5, 6}

How to access iOS simulator camera

Simulator doesn't have a Camera. If you want to access a camera you need a device. You can't test camera on simulator. You can only check the photo and video gallery.

NoClassDefFoundError while trying to run my jar with java.exe -jar...what's wrong?

I have found when I am using a manifest that the listing of jars for the classpath need to have a space after the listing of each jar e.g. "required_lib/sun/pop3.jar required_lib/sun/smtp.jar ". Even if it is the last in the list.

Does the join order matter in SQL?

For INNER joins, no, the order doesn't matter. The queries will return same results, as long as you change your selects from SELECT * to SELECT a.*, b.*, c.*.


For (LEFT, RIGHT or FULL) OUTER joins, yes, the order matters - and (updated) things are much more complicated.

First, outer joins are not commutative, so a LEFT JOIN b is not the same as b LEFT JOIN a

Outer joins are not associative either, so in your examples which involve both (commutativity and associativity) properties:

a LEFT JOIN b 
    ON b.ab_id = a.ab_id
  LEFT JOIN c
    ON c.ac_id = a.ac_id

is equivalent to:

a LEFT JOIN c 
    ON c.ac_id = a.ac_id
  LEFT JOIN b
    ON b.ab_id = a.ab_id

but:

a LEFT JOIN b 
    ON  b.ab_id = a.ab_id
  LEFT JOIN c
    ON  c.ac_id = a.ac_id
    AND c.bc_id = b.bc_id

is not equivalent to:

a LEFT JOIN c 
    ON  c.ac_id = a.ac_id
  LEFT JOIN b
    ON  b.ab_id = a.ab_id
    AND b.bc_id = c.bc_id

Another (hopefully simpler) associativity example. Think of this as (a LEFT JOIN b) LEFT JOIN c:

a LEFT JOIN b 
    ON b.ab_id = a.ab_id          -- AB condition
 LEFT JOIN c
    ON c.bc_id = b.bc_id          -- BC condition

This is equivalent to a LEFT JOIN (b LEFT JOIN c):

a LEFT JOIN  
    b LEFT JOIN c
        ON c.bc_id = b.bc_id          -- BC condition
    ON b.ab_id = a.ab_id          -- AB condition

only because we have "nice" ON conditions. Both ON b.ab_id = a.ab_id and c.bc_id = b.bc_id are equality checks and do not involve NULL comparisons.

You can even have conditions with other operators or more complex ones like: ON a.x <= b.x or ON a.x = 7 or ON a.x LIKE b.x or ON (a.x, a.y) = (b.x, b.y) and the two queries would still be equivalent.

If however, any of these involved IS NULL or a function that is related to nulls like COALESCE(), for example if the condition was b.ab_id IS NULL, then the two queries would not be equivalent.

IE8 issue with Twitter Bootstrap 3

I faced the same problem, tried the first answer but something was missing.

If you guys are using Webpack, your css will be loaded as a style tag which is not supported by respond.js, it needs a file, so make sure bootstrap is loaded as a css file

Personally I used extract-text-webpack-plugin

const webpack = require("webpack")
const ExtractTextPlugin = require("extract-text-webpack-plugin")
const path = require("path")

module.exports = {
    context: __dirname+"/src",
    entry: "./index.js",
    output: {
        filename: "./dist/bundle.js",
        path: __dirname
    },
    plugins: [
        ...,
        new ExtractTextPlugin("./dist/bootstrap.css", {
            allChunks: true
        })
    ],
    module: {
        loaders: [
            ...,
            // your css loader excluding bootstrap
            {
                test: /\.css$/,
                loader: "style!css",
                exclude: [
                    path.resolve(__dirname, "node_modules/bootstrap/dist/css/bootstrap.css")
                ]
            },

            {
                // loads bootstrap as a file, change path accordingly if needs be, path needs to be absolute
                include: [
                    path.resolve(__dirname, "node_modules/bootstrap/dist/css/bootstrap.css")
                ],
                loader: ExtractTextPlugin.extract("style-loader", "css-loader?minimize")
            }
        ]
    }
}

Hope it will help you

CORS with spring-boot and angularjs not working

This is what worked for me.

@EnableWebSecurity
public class WebSecurityConfiguration extends WebSecurityConfigurerAdapter {

    @Override
    protected void configure(HttpSecurity http) throws Exception {

        http.cors();
    }

}

@Configuration
public class WebConfiguration implements WebMvcConfigurer {

    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry
            .addMapping("/**")
            .allowedMethods("*")
            .allowedHeaders("*")
            .allowedOrigins("*")
            .allowCredentials(true);
    }

}

Do I use <img>, <object>, or <embed> for SVG files?

If you need your SVGs to be fully styleable with CSS they have to be inline in the DOM. This can be achieved through SVG injection, which uses Javascript to replace a HTML element (usually an <img> element) with the contents of an SVG file after the page has loaded.

Here is a minimal example using SVGInject:

<html>
<head>
  <script src="svg-inject.min.js"></script>
</head>
<body>
  <img src="image.svg" onload="SVGInject(this)" />
</body>
</html>

After the image is loaded the onload="SVGInject(this) will trigger the injection and the <img> element will be replaced by the contents of the file provided in the src attribute. This works with all browsers that support SVG.

Disclaimer: I am the co-author of SVGInject

How to access the services from RESTful API in my angularjs page?

For instance your json looks like this : {"id":1,"content":"Hello, World!"}

You can access this thru angularjs like so:

angular.module('app', [])
    .controller('myApp', function($scope, $http) {
        $http.get('http://yourapp/api').
            then(function(response) {
                $scope.datafromapi = response.data;
            });
    });

Then on your html you would do it like this:

<!doctype html>
<html ng-app="myApp">
    <head>
        <title>Hello AngularJS</title>
        <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
        <script src="hello.js"></script>
    </head>

    <body>
        <div ng-controller="myApp">
            <p>The ID is {{datafromapi.id}}</p>
            <p>The content is {{datafromapi.content}}</p>
        </div>
    </body>
</html>

This calls the CDN for angularjs in case you don't want to download them.

<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.4.3/angular.min.js"></script>
<script src="hello.js"></script>

Hope this helps.

SQL SELECT multi-columns INTO multi-variable

SELECT @variable1 = col1, @variable2 = col2
FROM table1

Storing and retrieving datatable from session

this is just as a side note, but generally what you want to do is keep size on the Session and ViewState small. I generally just store IDs and small amounts of packets in Session and ViewState.

for instance if you want to pass large chunks of data from one page to another, you can store an ID in the querystring and use that ID to either get data from a database or a file.

PS: but like I said, this might be totally unrelated to your query :)

Mysql error 1452 - Cannot add or update a child row: a foreign key constraint fails

Make sure the value is in the other table otherwise you will get this error, in the assigned corresponding column.

So if it is assigned column is assigned to a row id of another table , make sure there is a row that is in the table otherwise this error will appear.

How can I check that JButton is pressed? If the isEnable() is not work?

Just do System.out.println(e.getActionCommand()); inside actionPerformed(ActionEvent e) function. This will tell you which command is just performed.

or

if(e.getActionCommand().equals("Add")){

   System.out.println("Add button pressed");
}

How to insert values in two dimensional array programmatically?

You can't "add" values to an array as the array length is immutable. You can set values at specific array positions.

If you know how to do it with one-dimensional arrays then you know how to do it with n-dimensional arrays: There are no n-dimensional arrays in Java, only arrays of arrays (of arrays...).

But you can chain the index operator for array element access.

String[][] x = new String[2][];
x[0] = new String[1];
x[1] = new String[2];

x[0][0] = "a1";
    // No x[0][1] available
x[1][0] = "b1";
x[1][1] = "b2";

Note the dimensions of the child arrays don't need to match.

pip cannot install anything

I had this error message occur as I had set a Windows Environment Variable to an invalid certificate file.

Check if you have a CURL_CA_BUNDLE variable by typing SET at the command prompt.

You can override it for the current session with SET CURL_CA_BUNDLE=

The pip.log contained the following:

Getting page https://pypi.python.org/simple/pip/
Could not fetch URL https://pypi.python.org/simple/pip/: connection error: [Errno 185090050] _ssl.c:340: error:0B084002:x509 certificate routines:X509_load_cert_crl_file:system lib

How do I make a composite key with SQL Server Management Studio?

here is some code to do it:

-- Sample Table
create table myTable 
(
    Column1 int not null,
    Column2 int not null
)
GO

-- Add Constraint
ALTER TABLE myTable
    ADD CONSTRAINT pk_myConstraint PRIMARY KEY (Column1,Column2)
GO

I added the constraint as a separate statement because I presume your table has already been created.

Is Xamarin free in Visual Studio 2015?

I asked the same question to Xamarin support team, they replied with following:

You can develop an app with Xamarin for commercial usage - there is no extra charge! We only require you to comply with Visual Studio's licensing terms,

which means that in companies of less than 250 employees with less than $1million USD annual revenue, you may use Visual Studio completely free (including Xamarin) for up to 5 developers.

However after you pass those barriers, you would need a Visual Studio license (which includes Xamarin).


Refer the screenshot below.

enter image description here

PHP how to get local IP of system

Depends what you mean by local:

If by local you mean the address of the server/system executing the PHP code, then there are still two avenues to discuss. If PHP is being run through a web server, then you can get the server address by reading $_SERVER['SERVER_ADDR']. If PHP is being run through a command line interface, then you would likely have to shell-execute ipconfig (Windows) / ifconfig (*nix) and grep out the address.

If by local you mean the remote address of the website visitor, but not their external IP address (since you specifically said 192.*), then you are out of luck. The whole point of NAT routing is to hide that address. You cannot identify the local addresses of individual computers behind an IP address, but there are some tricks (user agent, possibly mac address) that can help differentiate if there are multiple computers accessing from the same IP.

using facebook sdk in Android studio

People using Android Studio 0.8.6 could do these:

  1. Download Facebook-android-sdk-xxx.zip & Unzip it
  2. Copy ONLY facebook dir under the Facebook-android-sdk-xxx dir into your project along with app/

    • ImAnApp/
      • |-- app/
      • |-- build/
      • |-- facebook/
  3. Now you should see Android Studio showing facebook as module

  4. Modify the build.gradle of facebook into this.
    • provided files('../libs/bolts.jar') to provided files('./libs/bolts.jar')
    • compileSdkVersion Integer.parseInt(project.ANDROID_BUILD_SDK_VERSION) to compileSdkVersion 20 or other version you defined in the app
    • buildToolsVersion project.ANDROID_BUILD_TOOLS_VERSION to buildToolsVersion '20.0.0'
    • minSdkVersion Integer.parseInt(project.ANDROID_BUILD_MIN_SDK_VERSION) to minSdkVersion 14
    • targetSdkVersion Integer.parseInt(project.ANDROID_BUILD_TARGET_SDK_VERSION) to targetSdkVersion 20

    apply plugin: 'android-library'

    dependencies {
        compile 'com.android.support:support-v4:19.1.+'
        provided files('./libs/bolts.jar')
    }

    android {
        compileSdkVersion 20
        buildToolsVersion '20.0.0'

        defaultConfig {
            minSdkVersion 14
            targetSdkVersion 20
        }

        lintOptions {
            abortOnError false
        }

        sourceSets {
            main {
                manifest.srcFile 'AndroidManifest.xml'
                java.srcDirs = ['src']
                res.srcDirs = ['res']
            }
        }
    }

Resync your gradle file & it should just work fine!

How to put a component inside another component in Angular2?

I think in your Angular-2 version directives are not supported in Component decorator, hence you have to register directive same as other component in @NgModule and then import in component as below and also remove directives: [ChildComponent] from decorator.

import {myDirective} from './myDirective';

How do I add a margin between bootstrap columns without wrapping

If you do not need to add a border on columns, you can also simply add a transparent border on them:

[class*="col-"] {
    background-clip: padding-box;
    border: 10px solid transparent;
}

When to use Common Table Expression (CTE)

There are two reasons I see to use cte's.

To use a calculated value in the where clause. This seems a little cleaner to me than a derived table.

Suppose there are two tables - Questions and Answers joined together by Questions.ID = Answers.Question_Id (and quiz id)

WITH CTE AS
(
    Select Question_Text,
           (SELECT Count(*) FROM Answers A WHERE A.Question_ID = Q.ID) AS Number_Of_Answers
    FROM Questions Q
)
SELECT * FROM CTE
WHERE Number_Of_Answers > 0

Here's another example where I want to get a list of questions and answers. I want the Answers to be grouped with the questions in the results.

WITH cte AS
(
    SELECT [Quiz_ID] 
      ,[ID] AS Question_Id
      ,null AS Answer_Id
          ,[Question_Text]
          ,null AS Answer
          ,1 AS Is_Question
    FROM [Questions]

    UNION ALL

    SELECT Q.[Quiz_ID]
      ,[Question_ID]
      ,A.[ID] AS  Answer_Id
      ,Q.Question_Text
          ,[Answer]
          ,0 AS Is_Question
        FROM [Answers] A INNER JOIN [Questions] Q ON Q.Quiz_ID = A.Quiz_ID AND Q.Id = A.Question_Id
)
SELECT 
    Quiz_Id,
    Question_Id,
    Is_Question,
    (CASE WHEN Answer IS NULL THEN Question_Text ELSE Answer END) as Name
FROM cte    
GROUP BY Quiz_Id, Question_Id, Answer_id, Question_Text, Answer, Is_Question 
order by Quiz_Id, Question_Id, Is_Question Desc, Name

Fastest way to count number of occurrences in a Python list

You can use pandas, by transforming the list to a pd.Series then simply use .value_counts()

import pandas as pd
a = ['1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '7', '7', '7', '10', '10']
a_cnts = pd.Series(a).value_counts().to_dict()

Input  >> a_cnts["1"], a_cnts["10"]
Output >> (6, 2)

Difference between Divide and Conquer Algo and Dynamic Programming

I think of Divide & Conquer as an recursive approach and Dynamic Programming as table filling.

For example, Merge Sort is a Divide & Conquer algorithm, as in each step, you split the array into two halves, recursively call Merge Sort upon the two halves and then merge them.

Knapsack is a Dynamic Programming algorithm as you are filling a table representing optimal solutions to subproblems of the overall knapsack. Each entry in the table corresponds to the maximum value you can carry in a bag of weight w given items 1-j.

how to increase sqlplus column output length?

On Windows you may try this:

  • right-click in the sqlplus window
  • select properties ->layout
  • increase screen buffer size width to 1000

Working with huge files in VIM

It's already late but if you just want to navigate through the file without editing it, cat can do the job too.

% cat filename | less

or alternatively simple:

% less filename

Using 'make' on OS X

I agree with the other two answers: install the Apple Developer Tools.

But it is also worth noting that OS X ships with ant and rake.

How to a convert a date to a number and back again in MATLAB

Use DATESTR

>> datestr(40189)
ans =
12-Jan-0110

Unfortunately, Excel starts counting at 1-Jan-1900. Find out how to convert serial dates from Matlab to Excel by using DATENUM

>> datenum(2010,1,11)
ans =
      734149
>> datenum(2010,1,11)-40189
ans =
      693960
>> datestr(40189+693960)
ans =
11-Jan-2010

In other words, to convert any serial Excel date, call

datestr(excelSerialDate + 693960)

EDIT

To get the date in mm/dd/yyyy format, call datestr with the specified format

excelSerialDate = 40189;
datestr(excelSerialDate + 693960,'mm/dd/yyyy')
ans =
01/11/2010

Also, if you want to get rid of the leading zero for the month, you can use REGEXPREP to fix things

excelSerialDate = 40189;
regexprep(datestr(excelSerialDate + 693960,'mm/dd/yyyy'),'^0','')
ans =
1/11/2010

Remove first Item of the array (like popping from stack)

There is a function called shift(). It will remove the first element of your array.

There is some good documentation and examples.

How to concatenate int values in java?

Using Java 8 and higher, you can use the StringJoiner, a very clean and more flexible way (especially if you have a list as input instead of known set of variables a-e):

int a = 1;
int b = 0;
int c = 2;
int d = 2;
int e = 1;
List<Integer> values = Arrays.asList(a, b, c, d, e);
String result = values.stream().map(i -> i.toString()).collect(Collectors.joining());
System.out.println(result);

If you need a separator use:

String result = values.stream().map(i -> i.toString()).collect(Collectors.joining(","));

To get the following result:

1,0,2,2,1

Edit: as LuCio commented, the following code is shorter:

Stream.of(a, b, c, d, e).map(Object::toString).collect(Collectors.joining());

Codesign error: Provisioning profile cannot be found after deleting expired profile

I just encountered this problem in my Xcode 4. To fix it, you need to put all the correct provisions into both Debug and Release config.

I was trying to submit (by archiving) my app. So I just change the Debug provisions to "Don't Code Sign", and the Release provision to my app's appstore provision.

This fix it and enables me to archive normally. Hope that helps.

How to set the context path of a web application in Tomcat 7.0

Tomcat 8 : After many searches this is only working code: in server.xml

<!-- Set /apple as default path -->
    <Host name="localhost"  appBase="webapps"
         unpackWARs="true" autoDeploy="true">
     <Context path="" docBase="apple">
         <!-- Default set of monitored resources -->
         <WatchedResource>WEB-INF/web.xml</WatchedResource>
     </Context>
    </Host>

Restart Tomcat, make sure when you access 127.0.0.1:8080, it will display the content in 127.0.0.1:8080/apple

My project was java web application witch created by netbeans ,I set context path in project configuration, no other thing, even I put apple.war in webapps folder.

Error : No resource found that matches the given name (at 'icon' with value '@drawable/icon')

Yet another Googlemare Landmine.... Somehow, if you mess up, the icon line on your .gen file dies. (Empirical proof of mine after struggling 2 hours)

Insert a new icon 72x72 icon on the hdpi folder with a different name from the original, and update the name on the manifest also.

The icon somehow resurrects on the Gen file and voila!! time to move on.

Objective-C implicit conversion loses integer precision 'NSUInteger' (aka 'unsigned long') to 'int' warning

Doing the expicit casting to the "int" solves the problem in my case. I had the same issue. So:

int count = (int)[myColors count];

How to detect if multiple keys are pressed at once using JavaScript?

Easiest, and most Effective Method

//check key press
    function loop(){
        //>>key<< can be any string representing a letter eg: "a", "b", "ctrl",
        if(map[*key*]==true){
         //do something
        }
        //multiple keys
        if(map["x"]==true&&map["ctrl"]==true){
         console.log("x, and ctrl are being held down together")
        }
    }

//>>>variable which will hold all key information<<
    var map={}

//Key Event Listeners
    window.addEventListener("keydown", btnd, true);
    window.addEventListener("keyup", btnu, true);

    //Handle button down
      function btnd(e) {
      map[e.key] = true;
      }

    //Handle Button up
      function btnu(e) {
      map[e.key] = false;
      }

//>>>If you want to see the state of every Key on the Keybaord<<<
    setInterval(() => {
                for (var x in map) {
                    log += "|" + x + "=" + map[x];
                }
                console.log(log);
                log = "";
            }, 300);

Before and After Suite execution hook in jUnit 4.x

Since maven-surefire-plugin does not run Suite class first but treats suite and test classes same, so we can configure plugin as below to enable only suite classes and disable all the tests. Suite will run all the tests.

        <plugin>
            <groupId>org.apache.maven.plugins</groupId>
            <artifactId>maven-surefire-plugin</artifactId>
            <version>2.5</version>
            <configuration>
                <includes>
                    <include>**/*Suite.java</include>
                </includes>
                <excludes>
                    <exclude>**/*Test.java</exclude>
                    <exclude>**/*Tests.java</exclude>
                </excludes>
            </configuration>
        </plugin>

How to open maximized window with Javascript?

Checkout this jquery window plugin: http://fstoke.me/jquery/window/

// create a window
sampleWnd = $.window({
   .....
});

// resize the window by passed w,h parameter
sampleWnd.resize(screen.width, screen.height);

The EXECUTE permission was denied on the object 'xxxxxxx', database 'zzzzzzz', schema 'dbo'

If you make this user especial for a specific database, then maybe you do not set it as db_owner in "user mapping" of properties

Return back to MainActivity from another activity

instead of starting MainActivity again via startActivity, call finish() instead in the other activities to get back to MainActivity... as MainActivity is already in stack

Get Locale Short Date Format using javascript

There is no easy way. If you want a reliable, cross-browser solution, you'd have to build a lookup table of date, and time format strings, by culture. To format a date, parse the corresponding format string, extract the relevant parts from the date, i.e. day, month, year, and append them together.

This is essentially what Microsoft does with their AJAX library, as shown in @no's answer.

Xcode 4 - build output directory

From the Xcode menu on top, click preferences, select the locations tab, look at the build location option.

You have 2 options:

  1. Place build products in derived data location (recommended)
  2. Place build products in locations specified by targets

Update: On xcode 4.6.2 you need to click the advanced button on the right side below the derived data text field. Build Location select legacy.

VBA Runtime Error 1004 "Application-defined or Object-defined error" when Selecting Range

I had a similar problem & fixed it applying these steps:

  1. Unprotecting the sheet that I want to edit
  2. Changing the range that I had selected by every single cell in the range (exploded)

I hope this will help someone.

Rotate camera in Three.js with mouse

Take a look at THREE.PointerLockControls

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]]

Continuous CSS rotation animation on hover, animated back to 0deg on hover out

It took a few tries, but I was able to get your jsFiddle to work (for Webkit only).

There's still an issue with the animation speed when the user re-enters the div.

Basically, just set the current rotation value to a variable, then do some calculations on that value (to convert to degrees), then set that value back to the element on mouse move and mouse enter.

Check out the jsFiddle: http://jsfiddle.net/4Vz63/46/

Check out this article for more information, including how to add cross-browser compatibility: http://css-tricks.com/get-value-of-css-rotation-through-javascript/

Adding an onclicklistener to listview (android)

Try this:

    list.setOnItemSelectedListener(new OnItemSelectedListener() {

    @Override
    public void onItemSelected(AdapterView<?> arg0, View arg1,
            int arg2, long arg3)
    }

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

    }
});

How do you check if a selector matches something in jQuery?

jQuery.fn.exists = function(selector, callback) {
    var $this = $(this);
    $this.each(function() {
        callback.call(this, ($(this).find(selector).length > 0));
    });
};

calling a java servlet from javascript

So you want to fire Ajax calls to the servlet? For that you need the XMLHttpRequest object in JavaScript. Here's a Firefox compatible example:

<script>
    var xhr = new XMLHttpRequest();
    xhr.onreadystatechange = function() {
        if (xhr.readyState == 4) {
            var data = xhr.responseText;
            alert(data);
        }
    }
    xhr.open('GET', '${pageContext.request.contextPath}/myservlet', true);
    xhr.send(null);
</script>

This is however very verbose and not really crossbrowser compatible. For the best crossbrowser compatible way of firing ajaxical requests and traversing the HTML DOM tree, I recommend to grab jQuery. Here's a rewrite of the above in jQuery:

<script src="http://code.jquery.com/jquery-latest.min.js"></script>
<script>
    $.get('${pageContext.request.contextPath}/myservlet', function(data) {
        alert(data);
    });
</script>

Either way, the Servlet on the server should be mapped on an url-pattern of /myservlet (you can change this to your taste) and have at least doGet() implemented and write the data to the response as follows:

String data = "Hello World!";
response.setContentType("text/plain");
response.setCharacterEncoding("UTF-8");
response.getWriter().write(data);

This should show Hello World! in the JavaScript alert.

You can of course also use doPost(), but then you should use 'POST' in xhr.open() or use $.post() instead of $.get() in jQuery.

Then, to show the data in the HTML page, you need to manipulate the HTML DOM. For example, you have a

<div id="data"></div>

in the HTML where you'd like to display the response data, then you can do so instead of alert(data) of the 1st example:

document.getElementById("data").firstChild.nodeValue = data;

In the jQuery example you could do this in a more concise and nice way:

$('#data').text(data);

To go some steps further, you'd like to have an easy accessible data format to transfer more complex data. Common formats are XML and JSON. For more elaborate examples on them, head to How to use Servlets and Ajax?

Bash ignoring error for a particular command

No solutions worked for me from here, so I found another one:

set +e
find "./csharp/Platform.$REPOSITORY_NAME/obj" -type f -iname "*.cs" -delete
find "./csharp/Platform.$REPOSITORY_NAME.Tests/obj" -type f -iname "*.cs" -delete
set -e

This is useful for CI & CD. This way the error messages are printed but the whole script continues to execute.

Child with max-height: 100% overflows parent

http://jsfiddle.net/mpalpha/71Lhcb5q/

_x000D_
_x000D_
.container {  
display: flex;
  background: blue; 
  padding: 10px; 
  max-height: 200px; 
  max-width: 200px; 
}

img { 
 object-fit: contain;
  max-height: 100%; 
  max-width: 100%; 
}
_x000D_
<div class="container">
  <img src="http://placekitten.com/400/500" />
</div>
_x000D_
_x000D_
_x000D_

How do I programmatically click on an element in JavaScript?

Here's a cross browser working function (usable for other than click handlers too):

function eventFire(el, etype){
    if (el.fireEvent) {
      el.fireEvent('on' + etype);
    } else {
      var evObj = document.createEvent('Events');
      evObj.initEvent(etype, true, false);
      el.dispatchEvent(evObj);
    }
}

Setting background colour of Android layout element

4 possible ways, use one you need.

1. Kotlin

val ll = findViewById<LinearLayout>(R.id.your_layout_id)
ll.setBackgroundColor(ContextCompat.getColor(this, R.color.white))

2. Data Binding

<LinearLayout
    android:background="@{@color/white}"

OR more useful statement-

<LinearLayout
    android:background="@{model.colorResId}"

3. XML

<LinearLayout
    android:background="#FFFFFF"

<LinearLayout
    android:background="@color/white"

4. Java

LinearLayout ll = (LinearLayout) findViewById(R.id.your_layout_id);
ll.setBackgroundColor(ContextCompat.getColor(this, R.color.white));

Get distance between two points in canvas

Note that Math.hypot is part of the ES2015 standard. There's also a good polyfill on the MDN doc for this feature.

So getting the distance becomes as easy as Math.hypot(x2-x1, y2-y1).

Change Background color (css property) using Jquery

The code below will change the div to blue.

<script>
 $(document).ready(function(){ 
   $("#co").click({
            $("body").css("background-color","blue");
      });
    }); 
</script>
<body>
      <div id="co">hello</div>
</body>

Named tuple and default values for optional keyword arguments

I'm not sure if there's an easy way with just the built-in namedtuple. There's a nice module called recordtype that has this functionality:

>>> from recordtype import recordtype
>>> Node = recordtype('Node', [('val', None), ('left', None), ('right', None)])
>>> Node(3)
Node(val=3, left=None, right=None)
>>> Node(3, 'L')
Node(val=3, left=L, right=None)

How to use OKHTTP to make a post request?

You need to encode it yourself by escaping strings with URLEncoder and joining them with "=" and "&". Or you can use FormEncoder from Mimecraft which gives you a handy builder.

FormEncoding fe = new FormEncoding.Builder()
    .add("name", "Lorem Ipsum")
    .add("occupation", "Filler Text")
    .build();

How to ftp with a batch file?

Using the Windows FTP client you would want to use the -s:filename option to specify a script for the FTP client to run. The documentation specifically points out that you should not try to pipe input into the FTP client with a < character.

Execution of the script will start immediately, so it does work for username/password.

However, the security of this setup is questionable since you now have a username and password for the FTP server visible to anyone who decides to look at your batch file.

Either way, you can generate the script file on the fly from the batch file and then pass it to the FTP client like so:

@echo off

REM Generate the script. Will overwrite any existing temp.txt
echo open servername> temp.txt
echo username>> temp.txt
echo password>> temp.txt
echo get %1>> temp.txt
echo quit>> temp.txt

REM Launch FTP and pass it the script
ftp -s:temp.txt

REM Clean up.
del temp.txt

Replace servername, username, and password with your details and the batch file will generate the script as temp.txt launch ftp with the script and then delete the script.

If you are always getting the same file you can replace the %1 with the file name. If not you just launch the batchfile and provide the name of the file to get as an argument.

Visual Studio Code compile on save

May 2018 update:

As of May 2018 you no longer need to create tsconfig.json manually or configure task runner.

  1. Run tsc --init in your project folder to create tsconfig.json file (if you don't have one already).
  2. Press Ctrl+Shift+B to open a list of tasks in VS Code and select tsc: watch - tsconfig.json.
  3. Done! Your project is recompiled on every file save.

You can have several tsconfig.json files in your workspace and run multiple compilations at once if you want (e.g. frontend and backend separately).

Original answer:

You can do this with Build commands:

Create a simple tsconfig.json with "watch": true (this will instruct compiler to watch all compiled files):

{
    "compilerOptions": {
        "target": "es5",
        "out": "js/script.js",
        "watch": true
    }
}

Note that files array is omitted, by default all *.ts files in all subdirectories will be compiled. You can provide any other parameters or change target/out, just make sure that watch is set to true.

Configure your task (Ctrl+Shift+P -> Configure Task Runner):

{
    "version": "0.1.0",
    "command": "tsc",
    "showOutput": "silent",
    "isShellCommand": true,
    "problemMatcher": "$tsc"
}

Now press Ctrl+Shift+B to build the project. You will see compiler output in the output window (Ctrl+Shift+U).

The compiler will compile files automatically when saved. To stop the compilation, press Ctrl+P -> > Tasks: Terminate Running Task

I've created a project template specifically for this answer: typescript-node-basic

Is it better to use std::memcpy() or std::copy() in terms to performance?

I'm going to go against the general wisdom here that std::copy will have a slight, almost imperceptible performance loss. I just did a test and found that to be untrue: I did notice a performance difference. However, the winner was std::copy.

I wrote a C++ SHA-2 implementation. In my test, I hash 5 strings using all four SHA-2 versions (224, 256, 384, 512), and I loop 300 times. I measure times using Boost.timer. That 300 loop counter is enough to completely stabilize my results. I ran the test 5 times each, alternating between the memcpy version and the std::copy version. My code takes advantage of grabbing data in as large of chunks as possible (many other implementations operate with char / char *, whereas I operate with T / T * (where T is the largest type in the user's implementation that has correct overflow behavior), so fast memory access on the largest types I can is central to the performance of my algorithm. These are my results:

Time (in seconds) to complete run of SHA-2 tests

std::copy   memcpy  % increase
6.11        6.29    2.86%
6.09        6.28    3.03%
6.10        6.29    3.02%
6.08        6.27    3.03%
6.08        6.27    3.03%

Total average increase in speed of std::copy over memcpy: 2.99%

My compiler is gcc 4.6.3 on Fedora 16 x86_64. My optimization flags are -Ofast -march=native -funsafe-loop-optimizations.

Code for my SHA-2 implementations.

I decided to run a test on my MD5 implementation as well. The results were much less stable, so I decided to do 10 runs. However, after my first few attempts, I got results that varied wildly from one run to the next, so I'm guessing there was some sort of OS activity going on. I decided to start over.

Same compiler settings and flags. There is only one version of MD5, and it's faster than SHA-2, so I did 3000 loops on a similar set of 5 test strings.

These are my final 10 results:

Time (in seconds) to complete run of MD5 tests

std::copy   memcpy      % difference
5.52        5.56        +0.72%
5.56        5.55        -0.18%
5.57        5.53        -0.72%
5.57        5.52        -0.91%
5.56        5.57        +0.18%
5.56        5.57        +0.18%
5.56        5.53        -0.54%
5.53        5.57        +0.72%
5.59        5.57        -0.36%
5.57        5.56        -0.18%

Total average decrease in speed of std::copy over memcpy: 0.11%

Code for my MD5 implementation

These results suggest that there is some optimization that std::copy used in my SHA-2 tests that std::copy could not use in my MD5 tests. In the SHA-2 tests, both arrays were created in the same function that called std::copy / memcpy. In my MD5 tests, one of the arrays was passed in to the function as a function parameter.

I did a little bit more testing to see what I could do to make std::copy faster again. The answer turned out to be simple: turn on link time optimization. These are my results with LTO turned on (option -flto in gcc):

Time (in seconds) to complete run of MD5 tests with -flto

std::copy   memcpy      % difference
5.54        5.57        +0.54%
5.50        5.53        +0.54%
5.54        5.58        +0.72%
5.50        5.57        +1.26%
5.54        5.58        +0.72%
5.54        5.57        +0.54%
5.54        5.56        +0.36%
5.54        5.58        +0.72%
5.51        5.58        +1.25%
5.54        5.57        +0.54%

Total average increase in speed of std::copy over memcpy: 0.72%

In summary, there does not appear to be a performance penalty for using std::copy. In fact, there appears to be a performance gain.

Explanation of results

So why might std::copy give a performance boost?

First, I would not expect it to be slower for any implementation, as long as the optimization of inlining is turned on. All compilers inline aggressively; it is possibly the most important optimization because it enables so many other optimizations. std::copy can (and I suspect all real world implementations do) detect that the arguments are trivially copyable and that memory is laid out sequentially. This means that in the worst case, when memcpy is legal, std::copy should perform no worse. The trivial implementation of std::copy that defers to memcpy should meet your compiler's criteria of "always inline this when optimizing for speed or size".

However, std::copy also keeps more of its information. When you call std::copy, the function keeps the types intact. memcpy operates on void *, which discards almost all useful information. For instance, if I pass in an array of std::uint64_t, the compiler or library implementer may be able to take advantage of 64-bit alignment with std::copy, but it may be more difficult to do so with memcpy. Many implementations of algorithms like this work by first working on the unaligned portion at the start of the range, then the aligned portion, then the unaligned portion at the end. If it is all guaranteed to be aligned, then the code becomes simpler and faster, and easier for the branch predictor in your processor to get correct.

Premature optimization?

std::copy is in an interesting position. I expect it to never be slower than memcpy and sometimes faster with any modern optimizing compiler. Moreover, anything that you can memcpy, you can std::copy. memcpy does not allow any overlap in the buffers, whereas std::copy supports overlap in one direction (with std::copy_backward for the other direction of overlap). memcpy only works on pointers, std::copy works on any iterators (std::map, std::vector, std::deque, or my own custom type). In other words, you should just use std::copy when you need to copy chunks of data around.

The OutputPath property is not set for this project

After trying all the other suggestions posted here, I discovered the solution for me was to remove the following section from the .csproj file:

  <ItemGroup>
    <Service Include="{808359B6-6B82-4DF5-91FF-3FCBEEBAD811}" />
  </ItemGroup>

Apparently this service from the original project (unavailable on local machine) was halting the entire build process, even though it wasn't essential for compilation.

Laravel 5 not finding css files

This worked for me:
If it's a css file tap

<link href="{{ asset('css/app.css') }}" rel="stylesheet" type="text/css" >

If it's an image tap

<link href="{{ asset('css/img/logo.png') }}" rel="stylesheet" type="text/css" >

How can I get the order ID in WooCommerce?

As of woocommerce 3.0

$order->id;

will not work, it will generate notice, use getter function:

$order->get_id();

The same applies for other woocommerce objects like procut.

Installing RubyGems in Windows

Use chocolatey in PowerShell

choco install ruby -y
refreshenv
gem install bundler

SelectSingleNode returning null for known good xml node path using XPath

Sorry, you forgot the namespace. You need:

XmlNamespaceManager ns = new XmlNamespaceManager(myXmlDoc.NameTable);
ns.AddNamespace("hl7","urn:hl7-org:v3");
XmlNode idNode = myXmlDoc.SelectSingleNode("/My_RootNode/hl7:id", ns);

In fact, whether here or in web services, getting null back from an XPath operation or anything that depends on XPath usually indicates a problem with XML namespaces.

How to remove border from specific PrimeFaces p:panelGrid?

Just add those lines on your custom css mycss.css

table tbody .ui-widget-content {
    background: none repeat scroll 0 0 #FFFFFF;
    border: 0 solid #FFFFFF;
    color: #333333;
}

The value violated the integrity constraints for the column

You can replace the values "null" from the original file & field/column.

What is the difference between int, Int16, Int32 and Int64?

They both are indeed synonymous, However i found the small difference between them,

1)You cannot use Int32 while creatingenum

enum Test : Int32
{ XXX = 1   // gives you compilation error
}

enum Test : int
{ XXX = 1   // Works fine
}

2) Int32 comes under System declaration. if you remove using.System you will get compilation error but not in case for int

How do I get bit-by-bit data from an integer value in C?

If you want the k-th bit of n, then do

(n & ( 1 << k )) >> k

Here we create a mask, apply the mask to n, and then right shift the masked value to get just the bit we want. We could write it out more fully as:

    int mask =  1 << k;
    int masked_n = n & mask;
    int thebit = masked_n >> k;

You can read more about bit-masking here.

Here is a program:

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

int *get_bits(int n, int bitswanted){
  int *bits = malloc(sizeof(int) * bitswanted);

  int k;
  for(k=0; k<bitswanted; k++){
    int mask =  1 << k;
    int masked_n = n & mask;
    int thebit = masked_n >> k;
    bits[k] = thebit;
  }

  return bits;
}

int main(){
  int n=7;

  int  bitswanted = 5;

  int *bits = get_bits(n, bitswanted);

  printf("%d = ", n);

  int i;
  for(i=bitswanted-1; i>=0;i--){
    printf("%d ", bits[i]);
  }

  printf("\n");
}

Django 1.7 - "No migrations to apply" when run migrate after makemigrations

In my case I wrote like this:

python manage.py makemigrations --empty yourappname

python manage.py migrate yourappname

or:

Django keeps track of all the applied migrations in django_migrations table. So just delete all the rows in the django_migrations table that are related to you app like:

DELETE FROM django_migrations WHERE app='your-app-name'

and then do:

python manage.py makemigrations python manage.py migrate

3D Plotting from X, Y, Z Data, Excel or other Tools

You can use r libraries for 3 D plotting.

Steps are:

First create a data frame using data.frame() command.

Create a 3D plot by using scatterplot3D library.

Or You can also rotate your chart using rgl library by plot3d() command.

Alternately you can use plot3d() command from rcmdr library.

In MATLAB, you can use surf(), mesh() or surfl() command as per your requirement.

[http://in.mathworks.com/help/matlab/examples/creating-3-d-plots.html]

Automatically resize images with browser size using CSS

To make the images flexible, simply add max-width:100% and height:auto. Image max-width:100% and height:auto works in IE7, but not in IE8 (yes, another weird IE bug). To fix this, you need to add width:auto\9 for IE8.

source: http://webdesignerwall.com/tutorials/responsive-design-with-css3-media-queries

for example :

img {
    max-width: 100%;
    height: auto;
    width: auto\9; /* ie8 */
}

and then any images you add simply using the img tag will be flexible

JSFiddle example here. No JavaScript required. Works in latest versions of Chrome, Firefox and IE (which is all I've tested).

Making the main scrollbar always visible

I was able to get this to work by adding it to the body tag. Was nicer for me because I don't have anything on the html element.

body {
    overflow-y: scroll;
}

What is the difference between "px", "dip", "dp" and "sp"?

dpi -

  • Dots per inches
  • Measuring the pixel density of the screen.

px - pixel

  • For mapping screen pixels

pt - points

  • About 1/72 of an inch, with respect to physical screen size.

in - inch - with respect to physical screen size(1 inch = 2.54 cm).

mm- milimeter - with respect to physical screen size.

sp - scale-independent pixel.

  • Based on user`s font size preference.
  • Font should be in 'sp'.

dip -

  • dip == dp
  • Density independent pixel.
  • It varies based on Screen Density.
  • In 160 dpi screen, 1 dp = 1 pixel.
  • Use dp except the text font size.

In standard, dp and sp are used. sp for font size and dp for everything else.

Formula for conversion of units:

px = dp * ( dpi / 160 );

Density Bucket -> Screen Display => Physical Size        => Pixel Size                   

ldpi         -> 120 dpi          => 0.5 x 0.5 in         => 0.5 in * 120 dpi = 60x60 px   

mdpi         -> 160 dpi          => 0.5 x 0.5 in         => 0.5 in * 160 dpi = 80x80 px   

hdpi         -> 240 dpi          => 0.5 x 0.5 in         => 0.5 in * 240 dpi = 120x120 px  

xhdpi        -> 320 dpi          => 0.5 x 0.5 in         => 0.5 in * 320 dpi = 160x160 px  

xxhdpi       -> 480 dpi          => 0.5 x 0.5 in         => 0.5 in * 480 dpi = 240x240 px 

xxxhdpi      -> 640 dpi          => 0.5 x 0.5 in         => 0.5 in * 640 dpi = 320x320 px  

What's the difference between a Future and a Promise?

No set method in Future interface, only get method, so it is read-only. About CompletableFuture, this article maybe helpful. completablefuture

Copy Paste Values only( xlPasteValues )

since you only want values copied, you can pass the values of arr1 directly to arr2 and avoid copy/paste. code inside the loop:

      Sheets("SheetB").Range(arr2(i) & firstrowDB).Resize(lastrow, 1).Value = .Range(.Cells(1, arr1(i)), .Cells(lastrow, arr1(i))).Value

How to disable Compatibility View in IE

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

should force your page to render in IE8 standards. The user may add the site to compatibility list but this tag will take precedence.

A quick way to check would be to load the page and type the following the address bar :

javascript:alert(navigator.userAgent) 

If you see IE7 in the string, it is loading in compatibility mode, otherwise not.

Commenting multiple lines in DOS batch file

@jeb

And after using this, the stderr seems to be inaccessible

No, try this:

@echo off 2>Nul 3>Nul 4>Nul

   ben ali  
   mubarak 2>&1
   gadeffi
   ..next ?

   echo hello Tunisia

  pause

But why it works?

sorry, i answer the question in frensh:

( la redirection par 3> est spécial car elle persiste, on va l'utiliser pour capturer le flux des erreurs 2> est on va le transformer en un flux persistant à l'ade de 3> ceci va nous permettre d'avoir une gestion des erreur pour tout notre environement de script..par la suite si on veux recuperer le flux 'stderr' il faut faire une autre redirection du handle 2> au handle 1> qui n'est autre que la console.. )

Find the files existing in one directory but not in the other

diff -r dir1 dir2 | grep dir1 | awk '{print $4}' > difference1.txt

Explanation:

  • diff -r dir1 dir2 shows which files are only in dir1 and those only in dir2 and also the changes of the files present in both directories if any.

  • diff -r dir1 dir2 | grep dir1 shows which files are only in dir1

  • awk to print only filename.

Convert Set to List without creating new List

Map<String, List> mainMap = new HashMap<String, List>();

for(int i=0; i<something.size(); i++){
  Set set = getSet(...); //return different result each time
  mainMap.put(differentKeyName, new ArrayList(set));
}

MVC 5 Access Claims Identity User Data

shortest and simplified version of @Rosdi Kasim'd answer is

string claimvalue = ((System.Security.Claims.ClaimsIdentity)User.Identity).
    FindFirst("claimname").Value;

Claimname is the claim you want to retrieve i.e if you are looking for "StreedAddress" claim then the above answer will be like this

string claimvalue = ((System.Security.Claims.ClaimsIdentity)User.Identity).
    FindFirst("StreedAddress").Value;

Redirect all to index.php using htaccess

Your rewrite rule looks almost ok.

First make sure that your .htaccess file is in your document root (the same place as index.php) or it'll only affect the sub-folder it's in (and any sub-folders within that - recursively).

Next make a slight change to your rule so it looks something like:

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^(.*)$ /index.php?path=$1 [NC,L,QSA]

At the moment you're just matching on . which is one instance of any character, you need at least .* to match any number of instances of any character.

The $_GET['path'] variable will contain the fake directory structure, so /mvc/module/test for instance, which you can then use in index.php to determine the Controller and actions you want to perform.


If you want the whole shebang installed in a sub-directory, such as /mvc/ or /framework/ the least complicated way to do it is to change the rewrite rule slightly to take that into account.

RewriteRule ^(.*)$ /mvc/index.php?path=$1 [NC,L,QSA]

And ensure that your index.php is in that folder whilst the .htaccess file is in the document root.


Alternative to $_GET['path'] (updated Feb '18 and Jan '19)

It's not actually necessary (nor even common now) to set the path as a $_GET variable, many frameworks will rely on $_SERVER['REQUEST_URI'] to retrieve the same information - normally to determine which Controller to use - but the principle is exactly the same.

This does simplify the RewriteRule slightly as you don't need to create the path parameter (which means the OP's original RewriteRule will now work):

RewriteEngine on
RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_FILENAME} !-d
RewriteRule ^.*$ /index.php [L,QSA]

However, the rule about installing in a sub-directory still applies, e.g.

RewriteRule ^.*$ /mvc/index.php [L,QSA]



The flags:

NC = No Case (not case sensitive, not really necessary since there are no characters in the pattern)

L = Last (it'll stop rewriting at after this Rewrite so make sure it's the last thing in your list of rewrites)

QSA = Query String Append, just in case you've got something like ?like=penguins on the end which you want to keep and pass to index.php.

Why does fatal error "LNK1104: cannot open file 'C:\Program.obj'" occur when I compile a C++ project in Visual Studio?

I tried above solution but didnt work for me. So i rename the exe and rebuild the solution. It works for me.

How to set calculation mode to manual when opening an excel file?

The best way around this would be to create an Excel called 'launcher.xlsm' in the same folder as the file you wish to open. In the 'launcher' file put the following code in the 'Workbook' object, but set the constant TargetWBName to be the name of the file you wish to open.

Private Const TargetWBName As String = "myworkbook.xlsx"

'// First, a function to tell us if the workbook is already open...
Function WorkbookOpen(WorkBookName As String) As Boolean
' returns TRUE if the workbook is open
    WorkbookOpen = False
    On Error GoTo WorkBookNotOpen
    If Len(Application.Workbooks(WorkBookName).Name) > 0 Then
        WorkbookOpen = True
        Exit Function
    End If
WorkBookNotOpen:
End Function

Private Sub Workbook_Open()
    'Check if our target workbook is open
    If WorkbookOpen(TargetWBName) = False Then
        'set calculation to manual
        Application.Calculation = xlCalculationManual
        Workbooks.Open ThisWorkbook.Path & "\" & TargetWBName
        DoEvents
        Me.Close False
    End If
End Sub

Set the constant 'TargetWBName' to be the name of the workbook that you wish to open. This code will simply switch calculation to manual, then open the file. The launcher file will then automatically close itself. *NOTE: If you do not wish to be prompted to 'Enable Content' every time you open this file (depending on your security settings) you should temporarily remove the 'me.close' to prevent it from closing itself, save the file and set it to be trusted, and then re-enable the 'me.close' call before saving again. Alternatively, you could just set the False to True after Me.Close

Insert array into MySQL database with PHP

Here is my full solution to this based on the accepted answer.

Usage example:

include("./assets/php/db.php");
$data = array('field1' => 'data1', 'field2'=> 'data2');
insertArr("databaseName.tableName", $data);

db.php

<?PHP
/**
 * Class to initiate a new MySQL connection based on $dbInfo settings found in dbSettings.php
 *
 * @example
 *    $db = new database(); // Initiate a new database connection
 *    mysql_close($db->get_link());
 */
class database{
    protected $databaseLink;
    function __construct(){
        include "dbSettings.php";
        $this->database = $dbInfo['host'];
        $this->mysql_user = $dbInfo['user'];
        $this->mysql_pass = $dbInfo['pass'];
        $this->openConnection();
        return $this->get_link();
    }
    function openConnection(){
    $this->databaseLink = mysql_connect($this->database, $this->mysql_user, $this->mysql_pass);
    }

    function get_link(){
    return $this->databaseLink;
    }
}

/**
 * Insert an associative array into a MySQL database
 *
 * @example
 *    $data = array('field1' => 'data1', 'field2'=> 'data2');
 *    insertArr("databaseName.tableName", $data);
 */
function insertArr($tableName, $insData){
    $db = new database();
    $columns = implode(", ",array_keys($insData));
    $escaped_values = array_map('mysql_real_escape_string', array_values($insData));
    foreach ($escaped_values as $idx=>$data) $escaped_values[$idx] = "'".$data."'";
    $values  = implode(", ", $escaped_values);
    $query = "INSERT INTO $tableName ($columns) VALUES ($values)";
    mysql_query($query) or die(mysql_error());
    mysql_close($db->get_link());
}
?>

dbSettings.php

<?PHP
$dbInfo = array(
    'host'      => "localhost",
    'user'      => "root",
    'pass'      => "password"
);
?>

Java Runtime.getRuntime(): getting output from executing a command line program

If you write on Kotlin, you can use:

val firstProcess = ProcessBuilder("echo","hello world").start()
val firstError = firstProcess.errorStream.readBytes().decodeToString()
val firstResult = firstProcess.inputStream.readBytes().decodeToString()

Convert a list of characters into a string

This may be the fastest way:

>> from array import array
>> a = ['a','b','c','d']
>> array('B', map(ord,a)).tostring()
'abcd'

Angular/RxJs When should I unsubscribe from `Subscription`

Since seangwright's solution (Edit 3) appears to be very useful, I also found it a pain to pack this feature into base component, and hint other project teammates to remember to call super() on ngOnDestroy to activate this feature.

This answer provide a way to set free from super call, and make "componentDestroyed$" a core of base component.

class BaseClass {
    protected componentDestroyed$: Subject<void> = new Subject<void>();
    constructor() {

        /// wrap the ngOnDestroy to be an Observable. and set free from calling super() on ngOnDestroy.
        let _$ = this.ngOnDestroy;
        this.ngOnDestroy = () => {
            this.componentDestroyed$.next();
            this.componentDestroyed$.complete();
            _$();
        }
    }

    /// placeholder of ngOnDestroy. no need to do super() call of extended class.
    ngOnDestroy() {}
}

And then you can use this feature freely for example:

@Component({
    selector: 'my-thing',
    templateUrl: './my-thing.component.html'
})
export class MyThingComponent extends BaseClass implements OnInit, OnDestroy {
    constructor(
        private myThingService: MyThingService,
    ) { super(); }

    ngOnInit() {
        this.myThingService.getThings()
            .takeUntil(this.componentDestroyed$)
            .subscribe(things => console.log(things));
    }

    /// optional. not a requirement to implement OnDestroy
    ngOnDestroy() {
        console.log('everything works as intended with or without super call');
    }

}

Text-align class for inside a table

Bootstrap 4 is coming! The utility classes made familiar in Bootstrap 3.x are now break-point enabled. The default breakpoints are: xs, sm, md, lg and xl, so these text alignment classes look something like .text-[breakpoint]-[alignnment].

<div class="text-sm-left"></div> //or
<div class="text-md-center"></div> //or
<div class="text-xl-right"></div>

Important: As of writing this, Bootstrap 4 is only in Alpha 2. These classes and how they're used are subject to change without notice.

How to inject window into a service?

It is enough to do

export class AppWindow extends Window {} 

and do

{ provide: 'AppWindow', useValue: window } 

to make AOT happy

Whitespaces in java

For a non-regular expression approach, you can check Character.isWhitespace for each character.

boolean containsWhitespace(String s) {
    for (int i = 0; i < s.length(); ++i) {
        if (Character.isWhitespace(s.charAt(i)) {
            return true;
        }
    }
    return false;
}

Which are the white spaces in Java?

The documentation specifies what Java considers to be whitespace:

public static boolean isWhitespace(char ch)

Determines if the specified character is white space according to Java. A character is a Java whitespace character if and only if it satisfies one of the following criteria:

  • It is a Unicode space character (SPACE_SEPARATOR, LINE_SEPARATOR, or PARAGRAPH_SEPARATOR) but is not also a non-breaking space ('\u00A0', '\u2007', '\u202F').
  • It is '\u0009', HORIZONTAL TABULATION.
  • It is '\u000A', LINE FEED.
  • It is '\u000B', VERTICAL TABULATION.
  • It is '\u000C', FORM FEED.
  • It is '\u000D', CARRIAGE RETURN.
  • It is '\u001C', FILE SEPARATOR.
  • It is '\u001D', GROUP SEPARATOR.
  • It is '\u001E', RECORD SEPARATOR.
  • It is '\u001F', UNIT SEPARATOR.

How do I check for equality using Spark Dataframe without SQL Query?

We can write multiple Filter/where conditions in Dataframe.

For example:

table1_df
.filter($"Col_1_name" === "buddy")  // check for equal to string
.filter($"Col_2_name" === "A")
.filter(not($"Col_2_name".contains(" .sql")))  // filter a string which is    not relevent
.filter("Col_2_name is not null")   // no null filter
.take(5).foreach(println)

Moment get current date

Just call moment as a function without any arguments:

moment()

For timezone information with moment, look at the moment-timezone package: http://momentjs.com/timezone/

How do I line up 3 divs on the same row?

Put the divisions in 'td' tag. That's it done.

How to get time in milliseconds since the unix epoch in Javascript?

This will do the trick :-

new Date().valueOf() 

What does the @Valid annotation indicate in Spring?

IIRC @Valid isn't a Spring annotation but a JSR-303 annotation (which is the Bean Validation standard). What it does is it basically checks if the data that you send to the method is valid or not (it will validate the scriptFile for you).

Open another page in php

Use the following code:

if(processing == success) {
  header("Location:filename");
  exit();
}

And you are good to go.

Iterate two Lists or Arrays with one ForEach statement in C#

Here's a custom IEnumerable<> extension method that can be used to loop through two lists simultaneously.

using System;
using System.Collections.Generic;
using System.Linq;

namespace ConsoleApplication1
{
    public static class LinqCombinedSort
    {
        public static void Test()
        {
            var a = new[] {'a', 'b', 'c', 'd', 'e', 'f'};
            var b = new[] {3, 2, 1, 6, 5, 4};

            var sorted = from ab in a.Combine(b)
                         orderby ab.Second
                         select ab.First;

            foreach(char c in sorted)
            {
                Console.WriteLine(c);
            }
        }

        public static IEnumerable<Pair<TFirst, TSecond>> Combine<TFirst, TSecond>(this IEnumerable<TFirst> s1, IEnumerable<TSecond> s2)
        {
            using (var e1 = s1.GetEnumerator())
            using (var e2 = s2.GetEnumerator())
            {
                while (e1.MoveNext() && e2.MoveNext())
                {
                    yield return new Pair<TFirst, TSecond>(e1.Current, e2.Current);
                }
            }

        }


    }
    public class Pair<TFirst, TSecond>
    {
        private readonly TFirst _first;
        private readonly TSecond _second;
        private int _hashCode;

        public Pair(TFirst first, TSecond second)
        {
            _first = first;
            _second = second;
        }

        public TFirst First
        {
            get
            {
                return _first;
            }
        }

        public TSecond Second
        {
            get
            {
                return _second;
            }
        }

        public override int GetHashCode()
        {
            if (_hashCode == 0)
            {
                _hashCode = (ReferenceEquals(_first, null) ? 213 : _first.GetHashCode())*37 +
                            (ReferenceEquals(_second, null) ? 213 : _second.GetHashCode());
            }
            return _hashCode;
        }

        public override bool Equals(object obj)
        {
            var other = obj as Pair<TFirst, TSecond>;
            if (other == null)
            {
                return false;
            }
            return Equals(_first, other._first) && Equals(_second, other._second);
        }
    }

}

I just discovered why all ASP.Net websites are slow, and I am trying to work out what to do about it

For ASPNET MVC, we did the following:

  1. By default, set SessionStateBehavior.ReadOnly on all controller's action by overriding DefaultControllerFactory
  2. On controller actions that need writing to session state, mark with attribute to set it to SessionStateBehavior.Required

Create custom ControllerFactory and override GetControllerSessionBehavior.

    protected override SessionStateBehavior GetControllerSessionBehavior(RequestContext requestContext, Type controllerType)
    {
        var DefaultSessionStateBehaviour = SessionStateBehaviour.ReadOnly;

        if (controllerType == null)
            return DefaultSessionStateBehaviour;

        var isRequireSessionWrite =
            controllerType.GetCustomAttributes<AcquireSessionLock>(inherit: true).FirstOrDefault() != null;

        if (isRequireSessionWrite)
            return SessionStateBehavior.Required;

        var actionName = requestContext.RouteData.Values["action"].ToString();
        MethodInfo actionMethodInfo;

        try
        {
            actionMethodInfo = controllerType.GetMethod(actionName, BindingFlags.IgnoreCase | BindingFlags.Public | BindingFlags.Instance);
        }
        catch (AmbiguousMatchException)
        {
            var httpRequestTypeAttr = GetHttpRequestTypeAttr(requestContext.HttpContext.Request.HttpMethod);

            actionMethodInfo =
                controllerType.GetMethods().FirstOrDefault(
                    mi => mi.Name.Equals(actionName, StringComparison.CurrentCultureIgnoreCase) && mi.GetCustomAttributes(httpRequestTypeAttr, false).Length > 0);
        }

        if (actionMethodInfo == null)
            return DefaultSessionStateBehaviour;

        isRequireSessionWrite = actionMethodInfo.GetCustomAttributes<AcquireSessionLock>(inherit: false).FirstOrDefault() != null;

         return isRequireSessionWrite ? SessionStateBehavior.Required : DefaultSessionStateBehaviour;
    }

    private static Type GetHttpRequestTypeAttr(string httpMethod) 
    {
        switch (httpMethod)
        {
            case "GET":
                return typeof(HttpGetAttribute);
            case "POST":
                return typeof(HttpPostAttribute);
            case "PUT":
                return typeof(HttpPutAttribute);
            case "DELETE":
                return typeof(HttpDeleteAttribute);
            case "HEAD":
                return typeof(HttpHeadAttribute);
            case "PATCH":
                return typeof(HttpPatchAttribute);
            case "OPTIONS":
                return typeof(HttpOptionsAttribute);
        }

        throw new NotSupportedException("unable to determine http method");
    }

AcquireSessionLockAttribute

[AttributeUsage(AttributeTargets.Method)]
public sealed class AcquireSessionLock : Attribute
{ }

Hook up the created controller factory in global.asax.cs

ControllerBuilder.Current.SetControllerFactory(typeof(DefaultReadOnlySessionStateControllerFactory));

Now, we can have both read-only and read-write session state in a single Controller.

public class TestController : Controller 
{
    [AcquireSessionLock]
    public ActionResult WriteSession()
    {
        var timeNow = DateTimeOffset.UtcNow.ToString();
        Session["key"] = timeNow;
        return Json(timeNow, JsonRequestBehavior.AllowGet);
    }

    public ActionResult ReadSession()
    {
        var timeNow = Session["key"];
        return Json(timeNow ?? "empty", JsonRequestBehavior.AllowGet);
    }
}

Note: ASPNET session state can still be written to even in readonly mode and will not throw any form of exception (It just doesn't lock to guarantee consistency) so we have to be careful to mark AcquireSessionLock in controller's actions that require writing session state.

How can I copy the output of a command directly into my clipboard?

Add this to to your ~/.bashrc:

# Now `cclip' copies and `clipp' pastes'
alias cclip='xclip -selection clipboard'
alias clipp='xclip -selection clipboard -o'

Now clipp pastes and cclip copies — but you can also do fancier stuff:

clipp | sed 's/^/    /' | cclip

↑ indents your clipboard; good for sites without stack overflow's { } button

You can add it by running this:

printf "\nalias clipp=\'xclip -selection c -o\'\n" >> ~/.bashrc
printf "\nalias cclip=\'xclip -selection c -i\'\n" >> ~/.bashrc

How to resize Image in Android?

public Bitmap resizeBitmap(String photoPath, int targetW, int targetH) {
    BitmapFactory.Options bmOptions = new BitmapFactory.Options();
    bmOptions.inJustDecodeBounds = true;
    BitmapFactory.decodeFile(photoPath, bmOptions);
    int photoW = bmOptions.outWidth;
    int photoH = bmOptions.outHeight;

    int scaleFactor = 1;
    if ((targetW > 0) || (targetH > 0)) {
            scaleFactor = Math.min(photoW/targetW, photoH/targetH);        
    }

    bmOptions.inJustDecodeBounds = false;
    bmOptions.inSampleSize = scaleFactor;
    bmOptions.inPurgeable = true; //Deprecated API 21

    return BitmapFactory.decodeFile(photoPath, bmOptions);            
}

Online PHP syntax checker / validator

To expand on my comment.

You can validate on the command line using php -l [filename], which does a syntax check only (lint). This will depend on your php.ini error settings, so you can edit you php.ini or set the error_reporting in the script.

Here's an example of the output when run on a file containing:

<?php
echo no quotes or semicolon

Results in:

PHP Parse error:  syntax error, unexpected T_STRING, expecting ',' or ';' in badfile.php on line 2

Parse error: syntax error, unexpected T_STRING, expecting ',' or ';' in badfile.php on line 2

Errors parsing badfile.php

I suggested you build your own validator.

A simple page that allows you to upload a php file. It takes the uploaded file runs it through php -l and echos the output.

Note: this is not a security risk it does not execute the file, just checks for syntax errors.

Here's a really basic example of creating your own:

<?php
if (isset($_FILES['file'])) {
    echo '<pre>';
    passthru('php -l '.$_FILES['file']['tmp_name']);
    echo '</pre>';
}
?>
<form action="" method="post" enctype="multipart/form-data">
    <input type="file" name="file"/>
    <input type="submit"/>
</form>

Cannot connect to Database server (mysql workbench)

In my case, the instalation didn't add MySQL\MySQL Server 5.7/bin folder to my PATH env variable.

How to refresh Android listview?

The solutions proposed by people in this post works or not mainly depending on the Android version of your device. For Example to use the AddAll method you have to put android:minSdkVersion="10" in your android device.

To solve this questions for all devices I have created my on own method in my adapter and use inside the add and remove method inherits from ArrayAdapter that update you data without problems.

My Code: Using my own data class RaceResult, you use your own data model.

ResultGpRowAdapter.java

public class ResultGpRowAdapter extends ArrayAdapter<RaceResult> {

    Context context;
    int resource;
    List<RaceResult> data=null;

        public ResultGpRowAdapter(Context context, int resource, List<RaceResult> objects)           {
        super(context, resource, objects);

        this.context = context;
        this.resource = resource;
        this.data = objects;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {

        ........
        }

        //my own method to populate data           
        public void myAddAll(List<RaceResult> items) {

        for (RaceResult item:items){
            super.add(item);
        }
    }

ResultsGp.java

public class ResultsGp extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {

    ...........
    ...........
    ListView list = (ListView)findViewById(R.id.resultsGpList); 

    ResultGpRowAdapter adapter = new ResultGpRowAdapter(this,  R.layout.activity_result_gp_row, new ArrayList<RaceResult>()); //Empty data

   list.setAdapter(adapter);

   .... 
   ....
   ....
   //LOAD a ArrayList<RaceResult> with data

   ArrayList<RaceResult> data = new ArrayList<RaceResult>();
   data.add(new RaceResult(....));
   data.add(new RaceResult(....));
   .......

   adapter.myAddAll(data); //Your list will be udpdated!!!

Create file path from variables

You can also use an object-oriented path with pathlib (available as a standard library as of Python 3.4):

from pathlib import Path

start_path = Path('/my/root/directory')
final_path = start_path / 'in' / 'here'

TortoiseSVN icons not showing up under Windows 7

Sometimes you just need to go to TortoiseSVN "settings", turn the icons off, click "apply", turn them back on.

Windows Start->All Programs->TortoiseSVN->Settings

enter image description here

Python re.sub(): how to substitute all 'u' or 'U's with 'you'

This worked for me:

    import re
    text = 'how are u? umberella u! u. U. U@ U# u '
    rex = re.compile(r'\bu\b', re.IGNORECASE)
    print(rex.sub('you', text))

It pre-compiles the regular expression and makes use of re.IGNORECASE so that we don't have to worry about case in our regular expression! BTW, I love the funky spelling of umbrella! :-)

jQuery textbox change event

The HTML4 spec for the <input> element specifies the following script events are available:

onfocus, onblur, onselect, onchange, onclick, ondblclick, onmousedown, onmouseup, onmouseover, onmousemove, onmouseout, onkeypress, onkeydown, onkeyup

here's an example that bind's to all these events and shows what's going on http://jsfiddle.net/pxfunc/zJ7Lf/

I think you can filter out which events are truly relevent to your situation and detect what the text value was before and after the event to determine a change

Clear input fields on form submit

You can clear out their values by just setting value to an empty string:

var1.value = '';
var2.value = '';

Creating an empty list in Python

list() is inherently slower than [], because

  1. there is symbol lookup (no way for python to know in advance if you did not just redefine list to be something else!),

  2. there is function invocation,

  3. then it has to check if there was iterable argument passed (so it can create list with elements from it) ps. none in our case but there is "if" check

In most cases the speed difference won't make any practical difference though.

Change the default base url for axios

From axios docs you have baseURL and url

baseURL will be prepended to url when making requests. So you can define baseURL as http://127.0.0.1:8000 and make your requests to /url

 // `url` is the server URL that will be used for the request
 url: '/user',

 // `baseURL` will be prepended to `url` unless `url` is absolute.
 // It can be convenient to set `baseURL` for an instance of axios to pass relative URLs
 // to methods of that instance.
 baseURL: 'https://some-domain.com/api/',

Compare integer in bash, unary operator expected

Judging from the error message the value of i was the empty string when you executed it, not 0.

Warning: "continue" targeting switch is equivalent to "break". Did you mean to use "continue 2"?

I upgraded to PHP 7.3, and None of these worked for me before I used,

sudo wget https://getcomposer.org/download/1.8.0/composer.phar -O /usr/local/bin/composer && sudo chmod 755 /usr/local/bin/composer

It's just the version dependency. PHP 7.3

and composer update worked like a charm!

How do I find the index of a character within a string in C?

What about:

char *string = "qwerty";
char *e = string;
int idx = 0;
while (*e++ != 'e') idx++;

copying to e to preserve the original string, I suppose if you don't care you could just operate over *string

How can I get the error message for the mail() function?

If you are on Windows using SMTP, you can use error_get_last() when mail() returns false. Keep in mind this does not work with PHP's native mail() function.

$success = mail('[email protected]', 'My Subject', $message);
if (!$success) {
    $errorMessage = error_get_last()['message'];
}

With print_r(error_get_last()), you get something like this:

[type] => 2
[message] => mail(): Failed to connect to mailserver at "x.x.x.x" port 25, verify your "SMTP" and "smtp_port" setting in php.ini or use ini_set()
[file] => C:\www\X\X.php
[line] => 2

What is a .NET developer?

Most .NET jobs I've run across also either explicitly or implicitly assume some knowledge of SQL-based RDBMSes. While it's not "part of the description", it's usually part of the job.

How to set initial size of std::vector?

You need to use the reserve function to set an initial allocated size or do it in the initial constructor.

vector<CustomClass *> content(20000);

or

vector<CustomClass *> content;
...
content.reserve(20000);

When you reserve() elements, the vector will allocate enough space for (at least?) that many elements. The elements do not exist in the vector, but the memory is ready to be used. This will then possibly speed up push_back() because the memory is already allocated.

How to create the branch from specific commit in different branch

If you are using this form of the branch command (with start point), it does not matter where your HEAD is.

What you are doing:

git checkout dev
git branch test 07aeec983bfc17c25f0b0a7c1d47da8e35df7af8
  • First, you set your HEAD to the branch dev,

  • Second, you start a new branch on commit 07aeec98. There is no bb.txt at this commit (according to your github repo).

If you want to start a new branch at the location you have just checked out, you can either run branch with no start point:

git branch test

or as other have answered, branch and checkout there in one operation:

git checkout -b test

I think that you might be confused by that fact that 07aeec98 is part of the branch dev. It is true that this commit is an ancestor of dev, its changes are needed to reach the latest commit in dev. However, they are other commits that are needed to reach the latest dev, and these are not necessarily in the history of 07aeec98.

8480e8ae (where you added bb.txt) is for example not in the history of 07aeec98. If you branch from 07aeec98, you won't get the changes introduced by 8480e8ae.

In other words: if you merge branch A and branch B into branch C, then create a new branch on a commit of A, you won't get the changes introduced in B.

Same here, you had two parallel branches master and dev, which you merged in dev. Branching out from a commit of master (older than the merge) won't provide you with the changes of dev.


If you want to permanently integrate new changes from master into your feature branches, you should merge master into them and go on. This will create merge commits in your feature branches, though.

If you have not published your feature branches, you can also rebase them on the updated master: git rebase master featureA. Be prepared to solve possible conflicts.

If you want a workflow where you can work on feature branches free of merge commits and still integrate with newer changes in master, I recommend the following:

  • base every new feature branch on a commit of master
  • create a dev branch on a commit of master
  • when you need to see how your feature branch integrates with new changes in master, merge both master and the feature branch into dev.

Do not commit into dev directly, use it only for merging other branches.

For example, if you are working on feature A and B:

a---b---c---d---e---f---g -master
    \       \
     \       \-x -featureB
      \
       \-j---k -featureA

Merge branches into a dev branch to check if they work well with the new master:

a---b---c---d---e---f---g -master
    \       \            \
     \       \            \--x'---k' -dev
      \       \             /    /   
       \       \-x----------    /    -featureB
        \                      /
         \-j---k--------------- -featureA

You can continue working on your feature branches, and keep merging in new changes from both master and feature branches into dev regularly.

a---b---c---d---e---f---g---h---i----- -master
    \       \            \            \
     \       \            \--x'---k'---i'---l' -dev
      \       \             /    /         /
       \       \-x----------    /         /  -featureB
        \                      /         /  
         \-j---k-----------------l------ -featureA

When it is time to integrate the new features, merge the feature branches (not dev!) into master.

How to include multiple js files using jQuery $.getScript() method

What you are looking for is an AMD compliant loader (like require.js).

http://requirejs.org/

http://requirejs.org/docs/whyamd.html

There are many good open source ones if you look it up. Basically this allows you to define a module of code, and if it is dependent on other modules of code, it will wait until those modules have finished downloading before proceeding to run. This way you can load 10 modules asynchronously and there should be no problems even if one depends on a few of the others to run.

How to style UITextview to like Rounded Rect text field?

I know there are already a lot of answers to this one, but I didn't really find any of them sufficient (at least in Swift). I wanted a solution that provided the same exact border as a UITextField (not an approximated one that looks sort of like it looks right now, but one that looks exactly like it and will always look exactly like it). I needed to use a UITextField to back the UITextView for the background, but didn't want to have to create that separately every time.

The solution below is a UITextView that supplies it's own UITextField for the border. This is a trimmed down version of my full solution (which adds "placeholder" support to the UITextView in a similar way) and was posted here: https://stackoverflow.com/a/36561236/1227119

// This class implements a UITextView that has a UITextField behind it, where the 
// UITextField provides the border.
//
class TextView : UITextView, UITextViewDelegate
{
    var textField = TextField();

    required init?(coder: NSCoder)
    {
        fatalError("This class doesn't support NSCoding.")
    }

    override init(frame: CGRect, textContainer: NSTextContainer?)
    {
        super.init(frame: frame, textContainer: textContainer);

        self.delegate = self;

        // Create a background TextField with clear (invisible) text and disabled
        self.textField.borderStyle = UITextBorderStyle.RoundedRect;
        self.textField.textColor = UIColor.clearColor();
        self.textField.userInteractionEnabled = false;

        self.addSubview(textField);
        self.sendSubviewToBack(textField);
    }

    convenience init()
    {
        self.init(frame: CGRectZero, textContainer: nil)
    }

    override func layoutSubviews()
    {
        super.layoutSubviews()
        // Do not scroll the background textView
        self.textField.frame = CGRectMake(0, self.contentOffset.y, self.frame.width, self.frame.height);
    }

    // UITextViewDelegate - Note: If you replace delegate, your delegate must call this
    func scrollViewDidScroll(scrollView: UIScrollView)
    {
        // Do not scroll the background textView
        self.textField.frame = CGRectMake(0, self.contentOffset.y, self.frame.width, self.frame.height);
    }        
}

How to fix 'sudo: no tty present and no askpass program specified' error?

Other options, not based on NOPASSWD:

  • Start Netbeans with root privilege ((sudo netbeans) or similar) which will presumably fork the build process with root and thus sudo will automatically succeed.
  • Make the operations you need to do suexec -- make them owned by root, and set mode to 4755. (This will of course let any user on the machine run them.) That way, they don't need sudo at all.
  • Creating virtual hard disk files with bootsectors shouldn't need sudo at all. Files are just files, and bootsectors are just data. Even the virtual machine shouldn't necessarily need root, unless you do advanced device forwarding.

jQuery + client-side template = "Syntax error, unrecognized expression"

I guess your template is starting with a space or a tab.

You can use jQuery like that:

$($.parseHtml(modal_template_html)[1]);

or parse the string to remove spaces of the beginning:

$(modal_template_html.replace(/^[ \t]+/gm, ''));

Defining arrays in Google Scripts

This may be of help to a few who are struggling like I was:

var data = myform.getRange("A:AA").getValues().pop();
var myvariable1 = data[4];
var myvariable2 = data[7];

RandomForestClassfier.fit(): ValueError: could not convert string to float

You may not pass str to fit this kind of classifier.

For example, if you have a feature column named 'grade' which has 3 different grades:

A,B and C.

you have to transfer those str "A","B","C" to matrix by encoder like the following:

A = [1,0,0]

B = [0,1,0]

C = [0,0,1]

because the str does not have numerical meaning for the classifier.

In scikit-learn, OneHotEncoder and LabelEncoder are available in inpreprocessing module. However OneHotEncoder does not support to fit_transform() of string. "ValueError: could not convert string to float" may happen during transform.

You may use LabelEncoder to transfer from str to continuous numerical values. Then you are able to transfer by OneHotEncoder as you wish.

In the Pandas dataframe, I have to encode all the data which are categorized to dtype:object. The following code works for me and I hope this will help you.

 from sklearn import preprocessing
    le = preprocessing.LabelEncoder()
    for column_name in train_data.columns:
        if train_data[column_name].dtype == object:
            train_data[column_name] = le.fit_transform(train_data[column_name])
        else:
            pass

How to connect mySQL database using C++

Finally I could successfully compile a program with C++ connector in Ubuntu 12.04 I have installed the connector using this command

'apt-get install libmysqlcppconn-dev'

Initially I faced the same problem with "undefined reference to `get_driver_instance' " to solve this I declare my driver instance variable of MySQL_Driver type. For ready reference this type is defined in mysql_driver.h file. Here is the code snippet I used in my program.

sql::mysql::MySQL_Driver *driver;
try {     
    driver = sql::mysql::get_driver_instance();
}

and I compiled the program with -l mysqlcppconn linker option

and don't forget to include this header

#include "mysql_driver.h" 

How do I obtain a Query Execution Plan in SQL Server?

There are a number of methods of obtaining an execution plan, which one to use will depend on your circumstances. Usually you can use SQL Server Management Studio to get a plan, however if for some reason you can't run your query in SQL Server Management Studio then you might find it helpful to be able to obtain a plan via SQL Server Profiler or by inspecting the plan cache.

Method 1 - Using SQL Server Management Studio

SQL Server comes with a couple of neat features that make it very easy to capture an execution plan, simply make sure that the "Include Actual Execution Plan" menu item (found under the "Query" menu) is ticked and run your query as normal.

Include Action Execution Plan menu item

If you are trying to obtain the execution plan for statements in a stored procedure then you should execute the stored procedure, like so:

exec p_Example 42

When your query completes you should see an extra tab entitled "Execution plan" appear in the results pane. If you ran many statements then you may see many plans displayed in this tab.

Screenshot of an Execution Plan

From here you can inspect the execution plan in SQL Server Management Studio, or right click on the plan and select "Save Execution Plan As ..." to save the plan to a file in XML format.

Method 2 - Using SHOWPLAN options

This method is very similar to method 1 (in fact this is what SQL Server Management Studio does internally), however I have included it for completeness or if you don't have SQL Server Management Studio available.

Before you run your query, run one of the following statements. The statement must be the only statement in the batch, i.e. you cannot execute another statement at the same time:

SET SHOWPLAN_TEXT ON
SET SHOWPLAN_ALL ON
SET SHOWPLAN_XML ON
SET STATISTICS PROFILE ON
SET STATISTICS XML ON -- The is the recommended option to use

These are connection options and so you only need to run this once per connection. From this point on all statements run will be acompanied by an additional resultset containing your execution plan in the desired format - simply run your query as you normally would to see the plan.

Once you are done you can turn this option off with the following statement:

SET <<option>> OFF

Comparison of execution plan formats

Unless you have a strong preference my recommendation is to use the STATISTICS XML option. This option is equivalent to the "Include Actual Execution Plan" option in SQL Server Management Studio and supplies the most information in the most convenient format.

  • SHOWPLAN_TEXT - Displays a basic text based estimated execution plan, without executing the query
  • SHOWPLAN_ALL - Displays a text based estimated execution plan with cost estimations, without executing the query
  • SHOWPLAN_XML - Displays an XML based estimated execution plan with cost estimations, without executing the query. This is equivalent to the "Display Estimated Execution Plan..." option in SQL Server Management Studio.
  • STATISTICS PROFILE - Executes the query and displays a text based actual execution plan.
  • STATISTICS XML - Executes the query and displays an XML based actual execution plan. This is equivalent to the "Include Actual Execution Plan" option in SQL Server Management Studio.

Method 3 - Using SQL Server Profiler

If you can't run your query directly (or your query doesn't run slowly when you execute it directly - remember we want a plan of the query performing badly), then you can capture a plan using a SQL Server Profiler trace. The idea is to run your query while a trace that is capturing one of the "Showplan" events is running.

Note that depending on load you can use this method on a production environment, however you should obviously use caution. The SQL Server profiling mechanisms are designed to minimize impact on the database but this doesn't mean that there won't be any performance impact. You may also have problems filtering and identifying the correct plan in your trace if your database is under heavy use. You should obviously check with your DBA to see if they are happy with you doing this on their precious database!

  1. Open SQL Server Profiler and create a new trace connecting to the desired database against which you wish to record the trace.
  2. Under the "Events Selection" tab check "Show all events", check the "Performance" -> "Showplan XML" row and run the trace.
  3. While the trace is running, do whatever it is you need to do to get the slow running query to run.
  4. Wait for the query to complete and stop the trace.
  5. To save the trace right click on the plan xml in SQL Server Profiler and select "Extract event data..." to save the plan to file in XML format.

The plan you get is equivalent to the "Include Actual Execution Plan" option in SQL Server Management Studio.

Method 4 - Inspecting the query cache

If you can't run your query directly and you also can't capture a profiler trace then you can still obtain an estimated plan by inspecting the SQL query plan cache.

We inspect the plan cache by querying SQL Server DMVs. The following is a basic query which will list all cached query plans (as xml) along with their SQL text. On most database you will also need to add additional filtering clauses to filter the results down to just the plans you are interested in.

SELECT UseCounts, Cacheobjtype, Objtype, TEXT, query_plan
FROM sys.dm_exec_cached_plans 
CROSS APPLY sys.dm_exec_sql_text(plan_handle)
CROSS APPLY sys.dm_exec_query_plan(plan_handle)

Execute this query and click on the plan XML to open up the plan in a new window - right click and select "Save execution plan as..." to save the plan to file in XML format.

Notes:

Because there are so many factors involved (ranging from the table and index schema down to the data stored and the table statistics) you should always try to obtain an execution plan from the database you are interested in (normally the one that is experiencing a performance problem).

You can't capture an execution plan for encrypted stored procedures.

"actual" vs "estimated" execution plans

An actual execution plan is one where SQL Server actually runs the query, whereas an estimated execution plan SQL Server works out what it would do without executing the query. Although logically equivalent, an actual execution plan is much more useful as it contains additional details and statistics about what actually happened when executing the query. This is essential when diagnosing problems where SQL Servers estimations are off (such as when statistics are out of date).

How do I interpret a query execution plan?

This is a topic worthy enough for a (free) book in its own right.

See also:

Generating a drop down list of timezones with PHP

Editing Tamas' answer to remove all the "other" entries that the php.net site says should no longer be used.

Maybe doesn't matter, but just following best practices. See notice at bottom of: http://fr2.php.net/manual/en/timezones.others.php

Also, though this list has the Azores as GMT -1, in fact I think it's the same (at least sometimes) as GMT, but not sure.

Editing to offer this in sql so you can create the drop down list in a form and have the user's answer be tied to an index instead.

Editing again to remove leading space

CREATE TABLE IF NOT EXISTS `timezones` (
  `id` int(11) NOT NULL AUTO_INCREMENT,
  `name` varchar(44) DEFAULT NULL,
  `timezone` varchar(30) DEFAULT NULL,
  PRIMARY KEY (`id`)
) ENGINE=MyISAM  DEFAULT CHARSET=utf8 AUTO_INCREMENT=141 ;

--
-- Dumping data for table `timezones`
--

INSERT INTO `timezones` (`id`, `name`, `timezone`) VALUES
(1, '(GMT-11:00) Midway Island ', 'Pacific/Midway'),
(2, '(GMT-11:00) Samoa ', 'Pacific/Samoa'),
(3, '(GMT-10:00) Hawaii ', 'Pacific/Honolulu'),
(4, '(GMT-09:00) Alaska ', 'America/Anchorage'),
(5, '(GMT-08:00) Pacific Time (US &amp; Canada) ', 'America/Los_Angeles'),
(6, '(GMT-08:00) Tijuana ', 'America/Tijuana'),
(7, '(GMT-07:00) Chihuahua ', 'America/Chihuahua'),
(8, '(GMT-07:00) La Paz ', 'America/Chihuahua'),
(9, '(GMT-07:00) Mazatlan ', 'America/Mazatlan'),
(10, '(GMT-07:00) Mountain Time (US &amp; Canada) ', 'America/Denver'),
(11, '(GMT-06:00) Central America ', 'America/Managua'),
(12, '(GMT-06:00) Central Time (US &amp; Canada) ', 'America/Chicago'),
(13, '(GMT-06:00) Guadalajara ', 'America/Mexico_City'),
(14, '(GMT-06:00) Mexico City ', 'America/Mexico_City'),
(15, '(GMT-06:00) Monterrey ', 'America/Monterrey'),
(16, '(GMT-05:00) Bogota ', 'America/Bogota'),
(17, '(GMT-05:00) Eastern Time (US &amp; Canada) ', 'America/New_York'),
(18, '(GMT-05:00) Lima ', 'America/Lima'),
(19, '(GMT-05:00) Quito ', 'America/Bogota'),
(20, '(GMT-04:00) Atlantic Time (Canada) ', 'Canada/Atlantic'),
(21, '(GMT-04:30) Caracas ', 'America/Caracas'),
(22, '(GMT-04:00) La Paz ', 'America/La_Paz'),
(23, '(GMT-04:00) Santiago ', 'America/Santiago'),
(24, '(GMT-03:30) Newfoundland ', 'America/St_Johns'),
(25, '(GMT-03:00) Brasilia ', 'America/Sao_Paulo'),
(26, '(GMT-03:00) Buenos Aires ', 'America/Argentina/Buenos_Aires'),
(27, '(GMT-03:00) Georgetown ', 'America/Argentina/Buenos_Aires'),
(28, '(GMT-03:00) Greenland ', 'America/Godthab'),
(29, '(GMT-02:00) Mid-Atlantic ', 'America/Noronha'),
(30, '(GMT-01:00) Azores ', 'Atlantic/Azores'),
(31, '(GMT-01:00) Cape Verde Is. ', 'Atlantic/Cape_Verde'),
(32, '(GMT+00:00) Casablanca ', 'Africa/Casablanca'),
(33, '(GMT+00:00) Edinburgh ', 'Europe/London'),
(34, '(GMT+00:00) Dublin ', 'Europe/Dublin'),
(35, '(GMT+00:00) Lisbon ', 'Europe/Lisbon'),
(36, '(GMT+00:00) London ', 'Europe/London'),
(37, '(GMT+00:00) Monrovia ', 'Africa/Monrovia'),
(38, '(GMT+00:00) UTC ', 'UTC'),
(39, '(GMT+01:00) Amsterdam ', 'Europe/Amsterdam'),
(40, '(GMT+01:00) Belgrade ', 'Europe/Belgrade'),
(41, '(GMT+01:00) Berlin ', 'Europe/Berlin'),
(42, '(GMT+01:00) Bern ', 'Europe/Berlin'),
(43, '(GMT+01:00) Bratislava ', 'Europe/Bratislava'),
(44, '(GMT+01:00) Brussels ', 'Europe/Brussels'),
(45, '(GMT+01:00) Budapest ', 'Europe/Budapest'),
(46, '(GMT+01:00) Copenhagen ', 'Europe/Copenhagen'),
(47, '(GMT+01:00) Ljubljana ', 'Europe/Ljubljana'),
(48, '(GMT+01:00) Madrid ', 'Europe/Madrid'),
(49, '(GMT+01:00) Paris ', 'Europe/Paris'),
(50, '(GMT+01:00) Prague ', 'Europe/Prague'),
(51, '(GMT+01:00) Rome ', 'Europe/Rome'),
(52, '(GMT+01:00) Sarajevo ', 'Europe/Sarajevo'),
(53, '(GMT+01:00) Skopje ', 'Europe/Skopje'),
(54, '(GMT+01:00) Stockholm ', 'Europe/Stockholm'),
(55, '(GMT+01:00) Vienna ', 'Europe/Vienna'),
(56, '(GMT+01:00) Warsaw ', 'Europe/Warsaw'),
(57, '(GMT+01:00) West Central Africa ', 'Africa/Lagos'),
(58, '(GMT+01:00) Zagreb ', 'Europe/Zagreb'),
(59, '(GMT+02:00) Athens ', 'Europe/Athens'),
(60, '(GMT+02:00) Bucharest ', 'Europe/Bucharest'),
(61, '(GMT+02:00) Cairo ', 'Africa/Cairo'),
(62, '(GMT+02:00) Harare ', 'Africa/Harare'),
(63, '(GMT+02:00) Helsinki ', 'Europe/Helsinki'),
(64, '(GMT+02:00) Istanbul ', 'Europe/Istanbul'),
(65, '(GMT+02:00) Jerusalem ', 'Asia/Jerusalem'),
(66, '(GMT+02:00) Kyiv ', 'Europe/Helsinki'),
(67, '(GMT+02:00) Pretoria ', 'Africa/Johannesburg'),
(68, '(GMT+02:00) Riga ', 'Europe/Riga'),
(69, '(GMT+02:00) Sofia ', 'Europe/Sofia'),
(70, '(GMT+02:00) Tallinn ', 'Europe/Tallinn'),
(71, '(GMT+02:00) Vilnius ', 'Europe/Vilnius'),
(72, '(GMT+03:00) Baghdad ', 'Asia/Baghdad'),
(73, '(GMT+03:00) Kuwait ', 'Asia/Kuwait'),
(74, '(GMT+03:00) Minsk ', 'Europe/Minsk'),
(75, '(GMT+03:00) Nairobi ', 'Africa/Nairobi'),
(76, '(GMT+03:00) Riyadh ', 'Asia/Riyadh'),
(77, '(GMT+03:00) Volgograd ', 'Europe/Volgograd'),
(78, '(GMT+03:30) Tehran ', 'Asia/Tehran'),
(79, '(GMT+04:00) Abu Dhabi ', 'Asia/Muscat'),
(80, '(GMT+04:00) Baku ', 'Asia/Baku'),
(81, '(GMT+04:00) Moscow ', 'Europe/Moscow'),
(82, '(GMT+04:00) Muscat ', 'Asia/Muscat'),
(83, '(GMT+04:00) St. Petersburg ', 'Europe/Moscow'),
(84, '(GMT+04:00) Tbilisi ', 'Asia/Tbilisi'),
(85, '(GMT+04:00) Yerevan ', 'Asia/Yerevan'),
(86, '(GMT+04:30) Kabul ', 'Asia/Kabul'),
(87, '(GMT+05:00) Islamabad ', 'Asia/Karachi'),
(88, '(GMT+05:00) Karachi ', 'Asia/Karachi'),
(89, '(GMT+05:00) Tashkent ', 'Asia/Tashkent'),
(90, '(GMT+05:30) Chennai ', 'Asia/Calcutta'),
(91, '(GMT+05:30) Kolkata ', 'Asia/Kolkata'),
(92, '(GMT+05:30) Mumbai ', 'Asia/Calcutta'),
(93, '(GMT+05:30) New Delhi ', 'Asia/Calcutta'),
(94, '(GMT+05:30) Sri Jayawardenepura ', 'Asia/Calcutta'),
(95, '(GMT+05:45) Kathmandu ', 'Asia/Katmandu'),
(96, '(GMT+06:00) Almaty ', 'Asia/Almaty'),
(97, '(GMT+06:00) Astana ', 'Asia/Dhaka'),
(98, '(GMT+06:00) Dhaka ', 'Asia/Dhaka'),
(99, '(GMT+06:00) Ekaterinburg ', 'Asia/Yekaterinburg'),
(100, '(GMT+06:30) Rangoon ', 'Asia/Rangoon'),
(101, '(GMT+07:00) Bangkok ', 'Asia/Bangkok'),
(102, '(GMT+07:00) Hanoi ', 'Asia/Bangkok'),
(103, '(GMT+07:00) Jakarta ', 'Asia/Jakarta'),
(104, '(GMT+07:00) Novosibirsk ', 'Asia/Novosibirsk'),
(105, '(GMT+08:00) Beijing ', 'Asia/Hong_Kong'),
(106, '(GMT+08:00) Chongqing ', 'Asia/Chongqing'),
(107, '(GMT+08:00) Hong Kong ', 'Asia/Hong_Kong'),
(108, '(GMT+08:00) Krasnoyarsk ', 'Asia/Krasnoyarsk'),
(109, '(GMT+08:00) Kuala Lumpur ', 'Asia/Kuala_Lumpur'),
(110, '(GMT+08:00) Perth ', 'Australia/Perth'),
(111, '(GMT+08:00) Singapore ', 'Asia/Singapore'),
(112, '(GMT+08:00) Taipei ', 'Asia/Taipei'),
(113, '(GMT+08:00) Ulaan Bataar ', 'Asia/Ulan_Bator'),
(114, '(GMT+08:00) Urumqi ', 'Asia/Urumqi'),
(115, '(GMT+09:00) Irkutsk ', 'Asia/Irkutsk'),
(116, '(GMT+09:00) Osaka ', 'Asia/Tokyo'),
(117, '(GMT+09:00) Sapporo ', 'Asia/Tokyo'),
(118, '(GMT+09:00) Seoul ', 'Asia/Seoul'),
(119, '(GMT+09:00) Tokyo ', 'Asia/Tokyo'),
(120, '(GMT+09:30) Adelaide ', 'Australia/Adelaide'),
(121, '(GMT+09:30) Darwin ', 'Australia/Darwin'),
(122, '(GMT+10:00) Brisbane ', 'Australia/Brisbane'),
(123, '(GMT+10:00) Canberra ', 'Australia/Canberra'),
(124, '(GMT+10:00) Guam ', 'Pacific/Guam'),
(125, '(GMT+10:00) Hobart ', 'Australia/Hobart'),
(126, '(GMT+10:00) Melbourne ', 'Australia/Melbourne'),
(127, '(GMT+10:00) Port Moresby ', 'Pacific/Port_Moresby'),
(128, '(GMT+10:00) Sydney ', 'Australia/Sydney'),
(129, '(GMT+10:00) Yakutsk ', 'Asia/Yakutsk'),
(130, '(GMT+11:00) Vladivostok ', 'Asia/Vladivostok'),
(131, '(GMT+12:00) Auckland ', 'Pacific/Auckland'),
(132, '(GMT+12:00) Fiji ', 'Pacific/Fiji'),
(133, '(GMT+12:00) International Date Line West ', 'Pacific/Kwajalein'),
(134, '(GMT+12:00) Kamchatka ', 'Asia/Kamchatka'),
(135, '(GMT+12:00) Magadan ', 'Asia/Magadan'),
(136, '(GMT+12:00) Marshall Is. ', 'Pacific/Fiji'),
(137, '(GMT+12:00) New Caledonia ', 'Asia/Magadan'),
(138, '(GMT+12:00) Solomon Is. ', 'Asia/Magadan'),
(139, '(GMT+12:00) Wellington ', 'Pacific/Auckland'),
(140, '(GMT+13:00) Nuku\\alofa ', 'Pacific/Tongatapu');

/*!40101 SET CHARACTER_SET_CLIENT=@OLD_CHARACTER_SET_CLIENT */;
/*!40101 SET CHARACTER_SET_RESULTS=@OLD_CHARACTER_SET_RESULTS */;
/*!40101 SET COLLATION_CONNECTION=@OLD_COLLATION_CONNECTION */;

Fast way of finding lines in one file that are not in another?

The comm command (short for "common") may be useful comm - compare two sorted files line by line

#find lines only in file1
comm -23 file1 file2 

#find lines only in file2
comm -13 file1 file2 

#find lines common to both files
comm -12 file1 file2 

The man file is actually quite readable for this.

Non greedy (reluctant) regex matching in sed?

Non-greedy solution for more than a single character

This thread is really old but I assume people still needs it. Lets say you want to kill everything till the very first occurrence of HELLO. You cannot say [^HELLO]...

So a nice solution involves two steps, assuming that you can spare a unique word that you are not expecting in the input, say top_sekrit.

In this case we can:

s/HELLO/top_sekrit/     #will only replace the very first occurrence
s/.*top_sekrit//        #kill everything till end of the first HELLO

Of course, with a simpler input you could use a smaller word, or maybe even a single character.

HTH!

Python and SQLite: insert into table

Adapted from http://docs.python.org/library/sqlite3.html:

# Larger example
for t in [('2006-03-28', 'BUY', 'IBM', 1000, 45.00),
          ('2006-04-05', 'BUY', 'MSOFT', 1000, 72.00),
          ('2006-04-06', 'SELL', 'IBM', 500, 53.00),
         ]:
    c.execute('insert into stocks values (?,?,?,?,?)', t)

HTTP Basic: Access denied fatal: Authentication failed

  1. Generate an access token with never expire date, and select all the options available.
  2. Remove the existing SSH keys.
  3. Clone the repo with the https instead of ssh.
  4. Use the username but use the generated access token instead of password.

enter image description here

alternatively you can set remote to http by using this command in the existing repo, and use this command git remote set-url origin https://gitlab.com/[username]/[repo-name].git

Proper Linq where clauses

The second one would be more efficient as it just has one predicate to evaluate against each item in the collection where as in the first one, it's applying the first predicate to all items first and the result (which is narrowed down at this point) is used for the second predicate and so on. The results get narrowed down every pass but still it involves multiple passes.

Also the chaining (first method) will work only if you are ANDing your predicates. Something like this x.Age == 10 || x.Fat == true will not work with your first method.

Stack, Static, and Heap in C++

The following is of course all not quite precise. Take it with a grain of salt when you read it :)

Well, the three things you refer to are automatic, static and dynamic storage duration, which has something to do with how long objects live and when they begin life.


Automatic storage duration

You use automatic storage duration for short lived and small data, that is needed only locally within some block:

if(some condition) {
    int a[3]; // array a has automatic storage duration
    fill_it(a);
    print_it(a);
}

The lifetime ends as soon as we exit the block, and it starts as soon as the object is defined. They are the most simple kind of storage duration, and are way faster than in particular dynamic storage duration.


Static storage duration

You use static storage duration for free variables, which might be accessed by any code all times, if their scope allows such usage (namespace scope), and for local variables that need extend their lifetime across exit of their scope (local scope), and for member variables that need to be shared by all objects of their class (classs scope). Their lifetime depends on the scope they are in. They can have namespace scope and local scope and class scope. What is true about both of them is, once their life begins, lifetime ends at the end of the program. Here are two examples:

// static storage duration. in global namespace scope
string globalA; 
int main() {
    foo();
    foo();
}

void foo() {
    // static storage duration. in local scope
    static string localA;
    localA += "ab"
    cout << localA;
}

The program prints ababab, because localA is not destroyed upon exit of its block. You can say that objects that have local scope begin lifetime when control reaches their definition. For localA, it happens when the function's body is entered. For objects in namespace scope, lifetime begins at program startup. The same is true for static objects of class scope:

class A {
    static string classScopeA;
};

string A::classScopeA;

A a, b; &a.classScopeA == &b.classScopeA == &A::classScopeA;

As you see, classScopeA is not bound to particular objects of its class, but to the class itself. The address of all three names above is the same, and all denote the same object. There are special rule about when and how static objects are initialized, but let's not concern about that now. That's meant by the term static initialization order fiasco.


Dynamic storage duration

The last storage duration is dynamic. You use it if you want to have objects live on another isle, and you want to put pointers around that reference them. You also use them if your objects are big, and if you want to create arrays of size only known at runtime. Because of this flexibility, objects having dynamic storage duration are complicated and slow to manage. Objects having that dynamic duration begin lifetime when an appropriate new operator invocation happens:

int main() {
    // the object that s points to has dynamic storage 
    // duration
    string *s = new string;
    // pass a pointer pointing to the object around. 
    // the object itself isn't touched
    foo(s);
    delete s;
}

void foo(string *s) {
    cout << s->size();
}

Its lifetime ends only when you call delete for them. If you forget that, those objects never end lifetime. And class objects that define a user declared constructor won't have their destructors called. Objects having dynamic storage duration requires manual handling of their lifetime and associated memory resource. Libraries exist to ease use of them. Explicit garbage collection for particular objects can be established by using a smart pointer:

int main() {
    shared_ptr<string> s(new string);
    foo(s);
}

void foo(shared_ptr<string> s) {
    cout << s->size();
}

You don't have to care about calling delete: The shared ptr does it for you, if the last pointer that references the object goes out of scope. The shared ptr itself has automatic storage duration. So its lifetime is automatically managed, allowing it to check whether it should delete the pointed to dynamic object in its destructor. For shared_ptr reference, see boost documents: http://www.boost.org/doc/libs/1_37_0/libs/smart_ptr/shared_ptr.htm

Getting current unixtimestamp using Moment.js

To find the Unix Timestamp in seconds:

moment().unix()

The documentation is your friend. :)

Python send UDP packet

Here is a complete example that has been tested with Python 2.7.5 on CentOS 7.

#!/usr/bin/python

import sys, socket

def main(args):
    ip = args[1]
    port = int(args[2])
    sock = socket.socket(socket.AF_INET, socket.SOCK_DGRAM)
    file = 'sample.csv'

    fp = open(file, 'r')
    for line in fp:
        sock.sendto(line.encode('utf-8'), (ip, port))
    fp.close()

main(sys.argv)

The program reads a file, sample.csv from the current directory and sends each line in a separate UDP packet. If the program it were saved in a file named send-udp then one could run it by doing something like:

$ python send-udp 192.168.1.2 30088

How do you monitor network traffic on the iPhone?

Try Debookee on Mac OS X which will intercept transparently the traffic of your iPhone without need of a proxy, thanks to MITM, as stated before. You'll then see in real time the different protocols used by your device.

Disclaimer: I'm part of the development team of Debookee, which is a paid application. The trial version will show you all functionnalities for a limited time.

MongoError: connect ECONNREFUSED 127.0.0.1:27017

For windows - just go to Mongodb folder (ex : C:\ProgramFiles\MongoDB\Server\3.4\bin) and open cmd in the folder and type "mongod.exe --dbpath c:\data\db"

if c:\data\db folder doesn't exist then create it by yourself and run above command again.

All should work fine by now.))

How to convert seconds to HH:mm:ss in moment.js

From this post I would try this to avoid leap issues

moment("2015-01-01").startOf('day')
    .seconds(s)
    .format('H:mm:ss');

I did not run jsPerf, but I would think this is faster than creating new date objects a million times

function pad(num) {
    return ("0"+num).slice(-2);
}
function hhmmss(secs) {
  var minutes = Math.floor(secs / 60);
  secs = secs%60;
  var hours = Math.floor(minutes/60)
  minutes = minutes%60;
  return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;
  // return pad(hours)+":"+pad(minutes)+":"+pad(secs); for old browsers
}

_x000D_
_x000D_
function pad(num) {_x000D_
    return ("0"+num).slice(-2);_x000D_
}_x000D_
function hhmmss(secs) {_x000D_
  var minutes = Math.floor(secs / 60);_x000D_
  secs = secs%60;_x000D_
  var hours = Math.floor(minutes/60)_x000D_
  minutes = minutes%60;_x000D_
  return `${pad(hours)}:${pad(minutes)}:${pad(secs)}`;_x000D_
  // return pad(hours)+":"+pad(minutes)+":"+pad(secs); for old browsers_x000D_
}_x000D_
_x000D_
for (var i=60;i<=60*60*5;i++) {_x000D_
 document.write(hhmmss(i)+'<br/>');_x000D_
}_x000D_
_x000D_
_x000D_
/* _x000D_
function show(s) {_x000D_
  var d = new Date();_x000D_
  var d1 = new Date(d.getTime()+s*1000);_x000D_
  var  hms = hhmmss(s);_x000D_
  return (s+"s = "+ hms + " - "+ Math.floor((d1-d)/1000)+"\n"+d.toString().split("GMT")[0]+"\n"+d1.toString().split("GMT")[0]);_x000D_
}    _x000D_
*/
_x000D_
_x000D_
_x000D_

why are there two different kinds of for loops in java?

The second for loop is any easy way to iterate over the contents of an array, without having to manually specify the number of items in the array(manual enumeration). It is much more convenient than the first when dealing with arrays.

Remove all non-"word characters" from a String in Java, leaving accented characters?

At times you do not want to simply remove the characters, but just remove the accents. I came up with the following utility class which I use in my Java REST web projects whenever I need to include a String in an URL:

import java.text.Normalizer;
import java.text.Normalizer.Form;

import org.apache.commons.lang.StringUtils;

/**
 * Utility class for String manipulation.
 * 
 * @author Stefan Haberl
 */
public abstract class TextUtils {
    private static String[] searchList = { "Ä", "ä", "Ö", "ö", "Ü", "ü", "ß" };
    private static String[] replaceList = { "Ae", "ae", "Oe", "oe", "Ue", "ue",
            "sz" };

    /**
     * Normalizes a String by removing all accents to original 127 US-ASCII
     * characters. This method handles German umlauts and "sharp-s" correctly
     * 
     * @param s
     *            The String to normalize
     * @return The normalized String
     */
    public static String normalize(String s) {
        if (s == null)
            return null;

        String n = null;

        n = StringUtils.replaceEachRepeatedly(s, searchList, replaceList);
        n = Normalizer.normalize(n, Form.NFD).replaceAll("[^\\p{ASCII}]", "");

        return n;
    }

    /**
     * Returns a clean representation of a String which might be used safely
     * within an URL. Slugs are a more human friendly form of URL encoding a
     * String.
     * <p>
     * The method first normalizes a String, then converts it to lowercase and
     * removes ASCII characters, which might be problematic in URLs:
     * <ul>
     * <li>all whitespaces
     * <li>dots ('.')
     * <li>(semi-)colons (';' and ':')
     * <li>equals ('=')
     * <li>ampersands ('&')
     * <li>slashes ('/')
     * <li>angle brackets ('<' and '>')
     * </ul>
     * 
     * @param s
     *            The String to slugify
     * @return The slugified String
     * @see #normalize(String)
     */
    public static String slugify(String s) {

        if (s == null)
            return null;

        String n = normalize(s);
        n = StringUtils.lowerCase(n);
        n = n.replaceAll("[\\s.:;&=<>/]", "");

        return n;
    }
}

Being a German speaker I've included proper handling of German umlauts as well - the list should be easy to extend for other languages.

HTH

EDIT: Note that it may be unsafe to include the returned String in an URL. You should at least HTML encode it to prevent XSS attacks.

jQuery AJAX submit form

There are a few things you need to bear in mind.

1. There are several ways to submit a form

  • using the submit button
  • by pressing enter
  • by triggering a submit event in JavaScript
  • possibly more depending on the device or future device.

We should therefore bind to the form submit event, not the button click event. This will ensure our code works on all devices and assistive technologies now and in the future.

2. Hijax

The user may not have JavaScript enabled. A hijax pattern is good here, where we gently take control of the form using JavaScript, but leave it submittable if JavaScript fails.

We should pull the URL and method from the form, so if the HTML changes, we don't need to update the JavaScript.

3. Unobtrusive JavaScript

Using event.preventDefault() instead of return false is good practice as it allows the event to bubble up. This lets other scripts tie into the event, for example analytics scripts which may be monitoring user interactions.

Speed

We should ideally use an external script, rather than inserting our script inline. We can link to this in the head section of the page using a script tag, or link to it at the bottom of the page for speed. The script should quietly enhance the user experience, not get in the way.

Code

Assuming you agree with all the above, and you want to catch the submit event, and handle it via AJAX (a hijax pattern), you could do something like this:

$(function() {
  $('form.my_form').submit(function(event) {
    event.preventDefault(); // Prevent the form from submitting via the browser
    var form = $(this);
    $.ajax({
      type: form.attr('method'),
      url: form.attr('action'),
      data: form.serialize()
    }).done(function(data) {
      // Optionally alert the user of success here...
    }).fail(function(data) {
      // Optionally alert the user of an error here...
    });
  });
});

You can manually trigger a form submission whenever you like via JavaScript using something like:

$(function() {
  $('form.my_form').trigger('submit');
});

Edit:

I recently had to do this and ended up writing a plugin.

(function($) {
  $.fn.autosubmit = function() {
    this.submit(function(event) {
      event.preventDefault();
      var form = $(this);
      $.ajax({
        type: form.attr('method'),
        url: form.attr('action'),
        data: form.serialize()
      }).done(function(data) {
        // Optionally alert the user of success here...
      }).fail(function(data) {
        // Optionally alert the user of an error here...
      });
    });
    return this;
  }
})(jQuery)

Add a data-autosubmit attribute to your form tag and you can then do this:

HTML

<form action="/blah" method="post" data-autosubmit>
  <!-- Form goes here -->
</form>

JS

$(function() {
  $('form[data-autosubmit]').autosubmit();
});

Converting DateTime format using razor

Try this in MVC 4.0

@Html.TextBoxFor(m => m.YourDate, "{0:dd/MM/yyyy}", new { @class = "datefield form-control", @placeholder = "Enter start date..." })

shift a std_logic_vector of n bit to right or left

There are two ways that you can achieve this. Concatenation, and shift/rotate functions.

  • Concatenation is the "manual" way of doing things. You specify what part of the original signal that you want to "keep" and then concatenate on data to one end or the other. For example: tmp <= tmp(14 downto 0) & '0';

  • Shift functions (logical, arithmetic): These are generic functions that allow you to shift or rotate a vector in many ways. The functions are: sll (shift left logical), srl (shift right logical). A logical shift inserts zeros. Arithmetric shifts (sra/sla) insert the left most or right most bit, but work in the same way as logical shift. Note that for all of these operations you specify what you want to shift (tmp), and how many times you want to perform the shift (n bits)

  • Rotate functions: rol (rotate left), ror (rotate right). Rotating does just that, the MSB ends up in the LSB and everything shifts left (rol) or the other way around for ror.

Here is a handy reference I found (see the first page).

d3 add text to circle

Here's a way that I consider easier: The general idea is that you want to append a text element to a circle element then play around with its "dx" and "dy" attributes until you position the text at the point in the circle that you like. In my example, I used a negative number for the dx since I wanted to have text start towards the left of the centre.

const nodes = [ {id: ABC, group: 1, level: 1}, {id:XYZ, group: 2, level: 1}, ]

const nodeElems = svg.append('g')
.selectAll('circle')
.data(nodes)
.enter().append('circle')
.attr('r',radius)
.attr('fill', getNodeColor)

const textElems = svg.append('g')
.selectAll('text')
.data(nodes)
.enter().append('text')
.text(node => node.label)
.attr('font-size',8)//font size
.attr('dx', -10)//positions text towards the left of the center of the circle
.attr('dy',4)

Difference in make_shared and normal shared_ptr in C++

If you need special memory alignment on the object controlled by shared_ptr, you cannot rely on make_shared, but I think it's the only one good reason about not using it.

Showing/Hiding Table Rows with Javascript - can do with ID - how to do with Class?

You can change the class of the entire table and use the cascade in the CSS: http://jsbin.com/oyunuy/1/

Choose folders to be ignored during search in VS Code

This answer is outdated

If these are folders you want to ignore in a certain workspace, you can go to:

AppMenu > Preferences > Workspace Settings

Otherwise, if you want these folders to be ignored in all your workspaces, go to:

AppMenu > Preferences > User Settings

and add the following to your configuration:

//-------- Search configuration --------

// The folders to exclude when doing a full text search in the workspace.
"search.excludeFolders": [
    ".git",
    "node_modules",
    "bower_components",
    "path/to/other/folder/to/exclude"
],

The difference between workspace and user settings is explained in the customization docs

How to hide columns in an ASP.NET GridView with auto-generated columns?

As said by others, RowDataBound or RowCreated event should work but if you want to avoid events declaration and put the whole code just below DataBind function call, you can do the following:

GridView1.DataBind()
If GridView1.Rows.Count > 0 Then
    GridView1.HeaderRow.Cells(0).Visible = False
    For i As Integer = 0 To GridView1.Rows.Count - 1
        GridView1.Rows(i).Cells(0).Visible = False
    Next
End If

OpenCV C++/Obj-C: Detecting a sheet of paper / Square Detection

This is a recurring subject in Stackoverflow and since I was unable to find a relevant implementation I decided to accept the challenge.

I made some modifications to the squares demo present in OpenCV and the resulting C++ code below is able to detect a sheet of paper in the image:

void find_squares(Mat& image, vector<vector<Point> >& squares)
{
    // blur will enhance edge detection
    Mat blurred(image);
    medianBlur(image, blurred, 9);

    Mat gray0(blurred.size(), CV_8U), gray;
    vector<vector<Point> > contours;

    // find squares in every color plane of the image
    for (int c = 0; c < 3; c++)
    {
        int ch[] = {c, 0};
        mixChannels(&blurred, 1, &gray0, 1, ch, 1);

        // try several threshold levels
        const int threshold_level = 2;
        for (int l = 0; l < threshold_level; l++)
        {
            // Use Canny instead of zero threshold level!
            // Canny helps to catch squares with gradient shading
            if (l == 0)
            {
                Canny(gray0, gray, 10, 20, 3); // 

                // Dilate helps to remove potential holes between edge segments
                dilate(gray, gray, Mat(), Point(-1,-1));
            }
            else
            {
                    gray = gray0 >= (l+1) * 255 / threshold_level;
            }

            // Find contours and store them in a list
            findContours(gray, contours, CV_RETR_LIST, CV_CHAIN_APPROX_SIMPLE);

            // Test contours
            vector<Point> approx;
            for (size_t i = 0; i < contours.size(); i++)
            {
                    // approximate contour with accuracy proportional
                    // to the contour perimeter
                    approxPolyDP(Mat(contours[i]), approx, arcLength(Mat(contours[i]), true)*0.02, true);

                    // Note: absolute value of an area is used because
                    // area may be positive or negative - in accordance with the
                    // contour orientation
                    if (approx.size() == 4 &&
                            fabs(contourArea(Mat(approx))) > 1000 &&
                            isContourConvex(Mat(approx)))
                    {
                            double maxCosine = 0;

                            for (int j = 2; j < 5; j++)
                            {
                                    double cosine = fabs(angle(approx[j%4], approx[j-2], approx[j-1]));
                                    maxCosine = MAX(maxCosine, cosine);
                            }

                            if (maxCosine < 0.3)
                                    squares.push_back(approx);
                    }
            }
        }
    }
}

After this procedure is executed, the sheet of paper will be the largest square in vector<vector<Point> >:

opencv paper sheet detection

I'm letting you write the function to find the largest square. ;)

How is attr_accessible used in Rails 4?

1) Update Devise so that it can handle Rails 4.0 by adding this line to your application's Gemfile:

gem 'devise', '3.0.0.rc' 

Then execute:

$ bundle

2) Add the old functionality of attr_accessible again to rails 4.0

Try to use attr_accessible and don't comment this out.

Add this line to your application's Gemfile:

gem 'protected_attributes'

Then execute:

$ bundle

How do I manage MongoDB connections in a Node.js web application?

You should create a connection as service then reuse it when need.

// db.service.js
import { MongoClient } from "mongodb";
import database from "../config/database";

const dbService = {
  db: undefined,
  connect: callback => {
    MongoClient.connect(database.uri, function(err, data) {
      if (err) {
        MongoClient.close();
        callback(err);
      }
      dbService.db = data;
      console.log("Connected to database");
      callback(null);
    });
  }
};

export default dbService;

my App.js sample

// App Start
dbService.connect(err => {
  if (err) {
    console.log("Error: ", err);
    process.exit(1);
  }

  server.listen(config.port, () => {
    console.log(`Api runnning at ${config.port}`);
  });
});

and use it wherever you want with

import dbService from "db.service.js"
const db = dbService.db

What's the simplest way to print a Java array?

toString is a way to convert an array to string.

Also, you can use:

for (int i = 0; i < myArray.length; i++){
System.out.println(myArray[i] + " ");
}

This for loop will enable you to print each value of your array in order.

How to include layout inside layout?

Try this

<include
            android:id="@+id/OnlineOffline"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentTop="true"
            layout="@layout/YourLayoutName" />

The model item passed into the dictionary is of type .. but this dictionary requires a model item of type

Observe if the view has the model required:

View

@model IEnumerable<WFAccess.Models.ViewModels.SiteViewModel>

<div class="row">
    <table class="table table-striped table-hover table-width-custom">
        <thead>
            <tr>
....

Controller

[HttpGet]
public ActionResult ListItems()
{
    SiteStore site = new SiteStore();
    site.GetSites();

    IEnumerable<SiteViewModel> sites =
        site.SitesList.Select(s => new SiteViewModel
        {
            Id = s.Id,
            Type = s.Type
        });

    return PartialView("_ListItems", sites);
}

In my case I Use a partial view but runs in normal views