Programs & Examples On #Silverlight 3.0

Silverlight is Microsoft's cross-browser, cross platform plug-in for media experiences and rich interactive applications. Silverlight 3 was released July 9, 2009

Difference between web reference and service reference?

The low-level answer here is that a Web Reference will create a client proxy class that allows your code to talk to a Web Service that is described via WSDL and communicates via SOAP or HTTP GET (other posters indicate that it is only ASMX, but Web References can also talk to Java-based Web Services or Python-based or Ruby so long as they all talk WSDL and conform to the WS-I interoperability standard).

A Service Reference will create a client proxy class that communicates with a WCF-based service : regardless of whether that WCF service is a Web Service or not.

Visual Studio 2010 always thinks project is out of date, but nothing has changed

If you change the Debugging Command arguments for the project, this will also trigger the project needs to be rebuilt message. Even though the target itself is not affected by the Debugging arguments, the project properties have changed. If you do rebuild though, the message should disappear.

Opening port 80 EC2 Amazon web services

Some quick tips:

  1. Disable the inbuilt firewall on your Windows instances.
  2. Use the IP address rather than the DNS entry.
  3. Create a security group for tcp ports 1 to 65000 and for source 0.0.0.0/0. It's obviously not to be used for production purposes, but it will help avoid the Security Groups as a source of problems.
  4. Check that you can actually ping your server. This may also necessitate some Security Group modification.

How to check if variable's type matches Type stored in a variable

The other answers all contain significant omissions.

The is operator does not check if the runtime type of the operand is exactly the given type; rather, it checks to see if the runtime type is compatible with the given type:

class Animal {}
class Tiger : Animal {}
...
object x = new Tiger();
bool b1 = x is Tiger; // true
bool b2 = x is Animal; // true also! Every tiger is an animal.

But checking for type identity with reflection checks for identity, not for compatibility

bool b5 = x.GetType() == typeof(Tiger); // true
bool b6 = x.GetType() == typeof(Animal); // false! even though x is an animal

or with the type variable
bool b7 = t == typeof(Tiger); // true
bool b8 = t == typeof(Animal); // false! even though x is an 

If that's not what you want, then you probably want IsAssignableFrom:

bool b9 = typeof(Tiger).IsAssignableFrom(x.GetType()); // true
bool b10 = typeof(Animal).IsAssignableFrom(x.GetType()); // true! A variable of type Animal may be assigned a Tiger.

or with the type variable
bool b11 = t.IsAssignableFrom(x.GetType()); // true
bool b12 = t.IsAssignableFrom(x.GetType()); // true! A 

How to Change Font Size in drawString Java

All you need to do is this: click on (window) on the dropdown manue on top of your screen. click on (Editor). click on (zoom in) as many times as you need to.

What should main() return in C and C++?

I was under the impression that standard specifies that main doesn't need a return value as a successful return was OS based (zero in one could be either a success or a failure in another), therefore the absence of return was a cue for the compiler to insert the successful return itself.

However I usually return 0.

Can't install via pip because of egg_info error

For me reinstalling and then upgrading the pip worked.

  1. Reinstall pip by using below command or following link How do I install pip on macOS or OS X?

    curl https://bootstrap.pypa.io/get-pip.py -o - | python

  2. Upgrade pip after it's installed

    pip install -U pip

How to correctly implement custom iterators and const_iterators?

Check this below code, it works

#define MAX_BYTE_RANGE 255

template <typename T>
class string
{
public:
    typedef char *pointer;
    typedef const char *const_pointer;
    typedef __gnu_cxx::__normal_iterator<pointer, string> iterator;
    typedef __gnu_cxx::__normal_iterator<const_pointer, string> const_iterator;

    string() : length(0)
    {
    }
    size_t size() const
    {
        return length;
    }
    void operator=(const_pointer value)
    {
        if (value == nullptr)
            throw std::invalid_argument("value cannot be null");
        auto count = strlen(value);
        if (count > 0)
            _M_copy(value, count);
    }
    void operator=(const string &value)
    {
        if (value.length != 0)
            _M_copy(value.buf, value.length);
    }
    iterator begin()
    {
        return iterator(buf);
    }
    iterator end()
    {
        return iterator(buf + length);
    }
    const_iterator begin() const
    {
        return const_iterator(buf);
    }
    const_iterator end() const
    {
        return const_iterator(buf + length);
    }
    const_pointer c_str() const
    {
        return buf;
    }
    ~string()
    {
    }

private:
    unsigned char length;
    T buf[MAX_BYTE_RANGE];

    void _M_copy(const_pointer value, size_t count)
    {
        memcpy(buf, value, count);
        length = count;
    }
};

How to display full (non-truncated) dataframe information in html when converting from pandas dataframe to html?

For those looking to do this in dask. I could not find a similar option in dask but if I simply do this in same notebook for pandas it works for dask too.

import pandas as pd
import dask.dataframe as dd
pd.set_option('display.max_colwidth', -1) # This will set the no truncate for pandas as well as for dask. Not sure how it does for dask though. but it works

train_data = dd.read_csv('./data/train.csv')    
train_data.head(5)

How to cast Object to its actual type?

If your MyFunction() method is defined only in one class (and its descendants), try

void MyMethod(Object obj) 
{
    var o = obj as MyClass;
    if (o != null)
        o.MyFunction();
}

If you have a large number in unrelated classes defining the function you want to call, you should define an interface and make your classes define that interface:

interface IMyInterface
{
    void MyFunction();
}

void MyMethod(Object obj) 
{
    var o = obj as IMyInterface;
    if (o != null)
        o.MyFunction();
}

Difference between JSONObject and JSONArray

I always use object, it is more easily extendable, JSON array is not. For example you originally had some data as a json array, then you needed to add a status header on it you'd be a bit stuck, unless you'd nested the data in an object. The only disadvantage is a slight increase in complexity of creation / parsing.

So instead of

[datum0, datum1, datumN]

You'd have

{data: [datum0, datum1, datumN]}

then later you can add more...

{status: "foo", data: [datum0, datum1, datumN]}

Spring Boot application can't resolve the org.springframework.boot package

Mine worked by adding

<!-- https://mvnrepository.com/artifact/org.springframework.boot/spring-boot-autoconfigure -->
<dependency>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-autoconfigure</artifactId>
    <version>2.1.3.RELEASE</version>
</dependency>

instead of directly using other main dependencies, I have no idea why.

Get timezone from DateTime

DateTime itself contains no real timezone information. It may know if it's UTC or local, but not what local really means.

DateTimeOffset is somewhat better - that's basically a UTC time and an offset. However, that's still not really enough to determine the timezone, as many different timezones can have the same offset at any one point in time. This sounds like it may be good enough for you though, as all you've got to work with when parsing the date/time is the offset.

The support for time zones as of .NET 3.5 is a lot better than it was, but I'd really like to see a standard "ZonedDateTime" or something like that - a UTC time and an actual time zone. It's easy to build your own, but it would be nice to see it in the standard libraries.

EDIT: Nearly four years later, I'd now suggest using Noda Time which has a rather richer set of date/time types. I'm biased though, as the main author of Noda Time :)

Testing Private method using mockito

Here is a small example how to do it with powermock

public class Hello {
    private Hello obj;
    private Integer method1(Long id) {
        return id + 10;
    }
} 

To test method1 use code:

Hello testObj = new Hello();
Integer result = Whitebox.invokeMethod(testObj, "method1", new Long(10L));

To set private object obj use this:

Hello testObj = new Hello();
Hello newObject = new Hello();
Whitebox.setInternalState(testObj, "obj", newObject);

java.lang.ClassCastException: java.lang.Long cannot be cast to java.lang.Integer in java 1.6

Use:

((Long) userService.getAttendanceList(currentUser)).intValue();

instead.

The .intValue() method is defined in class Number, which Long extends.

Jackson Vs. Gson

Jackson and Gson are the most complete Java JSON packages regarding actual data binding support; many other packages only provide primitive Map/List (or equivalent tree model) binding. Both have complete support for generic types, as well, as enough configurability for many common use cases.

Since I am more familiar with Jackson, here are some aspects where I think Jackson has more complete support than Gson (apologies if I miss a Gson feature):

  • Extensive annotation support; including full inheritance, and advanced "mix-in" annotations (associate annotations with a class for cases where you can not directly add them)
  • Streaming (incremental) reading, writing, for ultra-high performance (or memory-limited) use cases; can mix with data binding (bind sub-trees) -- EDIT: latest versions of Gson also include streaming reader
  • Tree model (DOM-like access); can convert between various models (tree <-> java object <-> stream)
  • Can use any constructors (or static factory methods), not just default constructor
  • Field and getter/setter access (earlier gson versions only used fields, this may have changed)
  • Out-of-box JAX-RS support
  • Interoperability: can also use JAXB annotations, has support/work-arounds for common packages (joda, ibatis, cglib), JVM languages (groovy, clojure, scala)
  • Ability to force static (declared) type handling for output
  • Support for deserializing polymorphic types (Jackson 1.5) -- can serialize AND deserialize things like List correctly (with additional type information)
  • Integrated support for binary content (base64 to/from JSON Strings)

How can I plot data with confidence intervals?

Some addition to the previous answers. It is nice to regulate the density of the polygon to avoid obscuring the data points.

library(MASS)
attach(Boston)
lm.fit2 = lm(medv~poly(lstat,2))
plot(lstat,medv)
new.lstat = seq(min(lstat), max(lstat), length.out=100)
preds <- predict(lm.fit2, newdata = data.frame(lstat=new.lstat), interval = 'prediction')
lines(sort(lstat), fitted(lm.fit2)[order(lstat)], col='red', lwd=3) 
polygon(c(rev(new.lstat), new.lstat), c(rev(preds[ ,3]), preds[ ,2]), density=10, col = 'blue', border = NA)
lines(new.lstat, preds[ ,3], lty = 'dashed', col = 'red')
lines(new.lstat, preds[ ,2], lty = 'dashed', col = 'red')

drawing of the prediction interval in polynomial regression

Please note that you see the prediction interval on the picture, which is several times wider than the confidence interval. You can read here the detailed explanation of those two types of interval estimates.

How can I change my Cygwin home folder after installation?

Change your HOME environment variable.

on XP, its right-click My Computer >> Properties >> Advanced >> Environment Variables >> User Variables for >> [select variable HOME] >> edit

Convert an object to an XML string

I realize this is a very old post, but after looking at L.B's response I thought about how I could improve upon the accepted answer and make it generic for my own application. Here's what I came up with:

public static string Serialize<T>(T dataToSerialize)
{
    try
    {
        var stringwriter = new System.IO.StringWriter();
        var serializer = new XmlSerializer(typeof(T));
        serializer.Serialize(stringwriter, dataToSerialize);
        return stringwriter.ToString();
    }
    catch
    {
        throw;
    }
}

public static T Deserialize<T>(string xmlText)
{
    try
    {
        var stringReader = new System.IO.StringReader(xmlText);
        var serializer = new XmlSerializer(typeof(T));
        return (T)serializer.Deserialize(stringReader);
    }
    catch
    {
        throw;
    }
}

These methods can now be placed in a static helper class, which means no code duplication to every class that needs to be serialized.

"The underlying connection was closed: An unexpected error occurred on a send." With SSL Certificate

It if helps someone, ours was an issue with missing certificate. Environment is Windows Server 2016 Standard with .Net 4.6.

There is a self hosted WCF service https URI, for which Service.Open() would execute without errors. Another thread would keep accessing https://OurIp:443/OurService?wsdl to ensure that the service was available. Accessing the WSDL used to fail with:

The underlying connection was closed: An unexpected error occurred on a send.

Using ServicePointManager.SecurityProtocol with applicable settings did not work. Playing with server roles and features did not help either. Then stepped in Jaise George, the SE, resolving the issue in a couple of minutes. Jaise installed a self signed certificate in the IIS, poofing the issue. This is what he did to address the issue:

(1) Open IIS manager (inetmgr) (2) Click on the server node in the left panel, and double click "Server certificates". (3) Click on "Create Self-Signed Certificate" on the right panel and type in anything you want for the friendly name. (4) Click on “Default Web site” in the left panel, click "Bindings" on the right panel, click "Add", select "https", select the certificate you just created, and click "OK" (5) Access the https URL, it should be accessible.

The model backing the 'ApplicationDbContext' context has changed since the database was created

When I am developing, I prefer to use this practical class to configure Migrations.

Hope it helps.

public class ApplicationDbContext : IdentityDbContext<ApplicationUser>
{
    public ApplicationDbContext()
        : base("DefaultConnection", throwIfV1Schema: false)
    {
        this.Configuration.LazyLoadingEnabled = false;
    }

    public static ApplicationDbContext Create()
    {
        return new ApplicationDbContext();
    }

    protected override void OnModelCreating(DbModelBuilder modelBuilder)
    {
        base.OnModelCreating(modelBuilder);

        modelBuilder.Conventions.Remove<OneToManyCascadeDeleteConvention>();
        modelBuilder.Conventions.Remove<ManyToManyCascadeDeleteConvention>();

        Database.SetInitializer(new StackOverflowInitializer());
    }

    public class StackOverflowInitializer : DropCreateDatabaseIfModelChanges<ApplicationDbContext>
    {
        public StackOverflowInitializer()
        {
            // TODO NOTHING, COMMENT ALL

            // IF CHANGES, RECREATE
            Database.SetInitializer(new DropCreateDatabaseIfModelChanges<ApplicationDbContext>());

            // CREATE ONLY NOT EXITS
            //Database.SetInitializer<Context>(new CreateDatabaseIfNotExists<ApplicationDbContext>());
        }

    }

    public System.Data.Entity.DbSet<stackoverflow.Models.Company> Companies { get; set; }

}

How do I add a tool tip to a span element?

For the basic tooltip, you want:

_x000D_
_x000D_
<span title="This is my tooltip"> Hover on me to see tooltip! </span>
_x000D_
_x000D_
_x000D_

Failed to resolve: com.android.support:appcompat-v7:28.0

Add the following code on build.gragle (project) for adding Google maven repository

allprojects {
    repositories {
    ...
        maven {
            url 'https://maven.google.com/'
            name 'Google'
        }
    ...
    }
}

google-services.json for different productFlavors

    ...
    gradle.taskGraph.beforeTask { Task task ->
        if (task.name ==~ /process.*GoogleServices/) {
            android.applicationVariants.all { variant ->
                if (task.name ==~ /(?i)process${variant.flavorName}(Debug|Release)GoogleServices/) {
                    copy {
                        from "src/tenants/${variant.flavorName}"
                        include 'google-services.json'
                        into '.'
                    }
                }
            }
        }
    }

    gradle.taskGraph.afterTask { Task task ->
        if (task.name ==~ /process.*GoogleServices/) {
            android.applicationVariants.all { variant ->
                if (task.name ==~ /(?i)process${variant.flavorName}(Debug|Release)GoogleServices/) {
                    delete fileTree(".").matching {
                        include 'google-services.json'
                    }
                }
            }
        }
    }

How to "EXPIRE" the "HSET" child key in redis?

You could store key/values in Redis differently to achieve this, by just adding a prefix or namespace to your keys when you store them e.g. "hset_"

  • Get a key/value GET hset_key equals to HGET hset key

  • Add a key/value SET hset_key value equals to HSET hset key

  • Get all keys KEYS hset_* equals to HGETALL hset

  • Get all vals should be done in 2 ops, first get all keys KEYS hset_* then get the value for each key

  • Add a key/value with TTL or expire which is the topic of question:

 SET hset_key value
 EXPIRE hset_key

Note: KEYS will lookup up for matching the key in the whole database which may affect on performance especially if you have big database.

Note:

  • KEYS will lookup up for matching the key in the whole database which may affect on performance especially if you have big database. while SCAN 0 MATCH hset_* might be better as long as it doesn't block the server but still performance is an issue in case of big database.

  • You may create a new database for storing separately these keys that you want to expire especially if they are small set of keys.

Thanks to @DanFarrell who highlighted the performance issue related to KEYS

Display fullscreen mode on Tkinter

Here's a simple solution with lambdas:

root = Tk()
root.attributes("-fullscreen", True)
root.bind("<F11>", lambda event: root.attributes("-fullscreen",
                                    not root.attributes("-fullscreen")))
root.bind("<Escape>", lambda event: root.attributes("-fullscreen", False))
root.mainloop()

This will make the screen exit fullscreen when escape is pressed, and toggle fullscreen when F11 is pressed.

How do I specify "not equals to" when comparing strings in an XSLT <xsl:if>?

If you want to compare to a string literal you need to put it in (single) quotes:

<xsl:if test="Count != 'N/A'">

SQL: sum 3 columns when one column has a null value?

SELECT sum(isnull(TotalHoursM,0)) 
         + isnull(TotalHoursT,0) 
         + isnull(TotalHoursW,0) 
         + isnull(TotalHoursTH,0) 
         + isnull(TotalHoursF,0))
AS TOTAL FROM LeaveRequest

Space between two divs

Why not use margin? you can apply all kinds off margins to an element. Not just the whole margin around it.

You should use css classes since this is referencing more than one element and you can use id's for those that you want to be different specifically

i.e:

<style>
.box { height: 50px; background: #0F0; width: 100%; margin-top: 10px; }
#first { margin-top: 20px; }
#second { background: #00F; }
h1.box { background: #F00; margin-bottom: 50px;  }
</style>

<h1 class="box">Hello World</h1>
<div class="box" id="first"></div>
<div class="box" id="second"></div>?

Here is a jsfiddle example:

REFERENCE:

Find a commit on GitHub given the commit hash

A URL of the form https://github.com/<owner>/<project>/commit/<hash> will show you the changes introduced in that commit. For example here's a recent bugfix I made to one of my projects on GitHub:

https://github.com/jerith666/git-graph/commit/35e32b6a00dec02ae7d7c45c6b7106779a124685

You can also shorten the hash to any unique prefix, like so:

https://github.com/jerith666/git-graph/commit/35e32b


I know you just asked about GitHub, but for completeness: If you have the repository checked out, from the command line, you can achieve basically the same thing with either of these commands (unique prefixes work here too):

git show 35e32b6a00dec02ae7d7c45c6b7106779a124685
git log -p -1 35e32b6a00dec02ae7d7c45c6b7106779a124685

Note: If you shorten the commit hash too far, the command line gives you a helpful disambiguation message, but GitHub will just return a 404.

pretty-print JSON using JavaScript

Unsatisfied with other pretty printers for Ruby, I wrote my own (NeatJSON) and then ported it to JavaScript including a free online formatter. The code is free under MIT license (quite permissive).

Features (all optional):

  • Set a line width and wrap in a way that keeps objects and arrays on the same line when they fit, wrapping one value per line when they don't.
  • Sort object keys if you like.
  • Align object keys (line up the colons).
  • Format floating point numbers to specific number of decimals, without messing up the integers.
  • 'Short' wrapping mode puts opening and closing brackets/braces on the same line as values, providing a format that some prefer.
  • Granular control over spacing for arrays and objects, between brackets, before/after colons and commas.
  • Function is made available to both web browsers and Node.js.

I'll copy the source code here so that this is not just a link to a library, but I encourage you to go to the GitHub project page, as that will be kept up-to-date and the code below will not.

(function(exports){
exports.neatJSON = neatJSON;

function neatJSON(value,opts){
  opts = opts || {}
  if (!('wrap'          in opts)) opts.wrap = 80;
  if (opts.wrap==true) opts.wrap = -1;
  if (!('indent'        in opts)) opts.indent = '  ';
  if (!('arrayPadding'  in opts)) opts.arrayPadding  = ('padding' in opts) ? opts.padding : 0;
  if (!('objectPadding' in opts)) opts.objectPadding = ('padding' in opts) ? opts.padding : 0;
  if (!('afterComma'    in opts)) opts.afterComma    = ('aroundComma' in opts) ? opts.aroundComma : 0;
  if (!('beforeComma'   in opts)) opts.beforeComma   = ('aroundComma' in opts) ? opts.aroundComma : 0;
  if (!('afterColon'    in opts)) opts.afterColon    = ('aroundColon' in opts) ? opts.aroundColon : 0;
  if (!('beforeColon'   in opts)) opts.beforeColon   = ('aroundColon' in opts) ? opts.aroundColon : 0;

  var apad  = repeat(' ',opts.arrayPadding),
      opad  = repeat(' ',opts.objectPadding),
      comma = repeat(' ',opts.beforeComma)+','+repeat(' ',opts.afterComma),
      colon = repeat(' ',opts.beforeColon)+':'+repeat(' ',opts.afterColon);

  return build(value,'');

  function build(o,indent){
    if (o===null || o===undefined) return indent+'null';
    else{
      switch(o.constructor){
        case Number:
          var isFloat = (o === +o && o !== (o|0));
          return indent + ((isFloat && ('decimals' in opts)) ? o.toFixed(opts.decimals) : (o+''));

        case Array:
          var pieces  = o.map(function(v){ return build(v,'') });
          var oneLine = indent+'['+apad+pieces.join(comma)+apad+']';
          if (opts.wrap===false || oneLine.length<=opts.wrap) return oneLine;
          if (opts.short){
            var indent2 = indent+' '+apad;
            pieces = o.map(function(v){ return build(v,indent2) });
            pieces[0] = pieces[0].replace(indent2,indent+'['+apad);
            pieces[pieces.length-1] = pieces[pieces.length-1]+apad+']';
            return pieces.join(',\n');
          }else{
            var indent2 = indent+opts.indent;
            return indent+'[\n'+o.map(function(v){ return build(v,indent2) }).join(',\n')+'\n'+indent+']';
          }

        case Object:
          var keyvals=[],i=0;
          for (var k in o) keyvals[i++] = [JSON.stringify(k), build(o[k],'')];
          if (opts.sorted) keyvals = keyvals.sort(function(kv1,kv2){ kv1=kv1[0]; kv2=kv2[0]; return kv1<kv2?-1:kv1>kv2?1:0 });
          keyvals = keyvals.map(function(kv){ return kv.join(colon) }).join(comma);
          var oneLine = indent+"{"+opad+keyvals+opad+"}";
          if (opts.wrap===false || oneLine.length<opts.wrap) return oneLine;
          if (opts.short){
            var keyvals=[],i=0;
            for (var k in o) keyvals[i++] = [indent+' '+opad+JSON.stringify(k),o[k]];
            if (opts.sorted) keyvals = keyvals.sort(function(kv1,kv2){ kv1=kv1[0]; kv2=kv2[0]; return kv1<kv2?-1:kv1>kv2?1:0 });
            keyvals[0][0] = keyvals[0][0].replace(indent+' ',indent+'{');
            if (opts.aligned){
              var longest = 0;
              for (var i=keyvals.length;i--;) if (keyvals[i][0].length>longest) longest = keyvals[i][0].length;
              var padding = repeat(' ',longest);
              for (var i=keyvals.length;i--;) keyvals[i][0] = padRight(padding,keyvals[i][0]);
            }
            for (var i=keyvals.length;i--;){
              var k=keyvals[i][0], v=keyvals[i][1];
              var indent2 = repeat(' ',(k+colon).length);
              var oneLine = k+colon+build(v,'');
              keyvals[i] = (opts.wrap===false || oneLine.length<=opts.wrap || !v || typeof v!="object") ? oneLine : (k+colon+build(v,indent2).replace(/^\s+/,''));
            }
            return keyvals.join(',\n') + opad + '}';
          }else{
            var keyvals=[],i=0;
            for (var k in o) keyvals[i++] = [indent+opts.indent+JSON.stringify(k),o[k]];
            if (opts.sorted) keyvals = keyvals.sort(function(kv1,kv2){ kv1=kv1[0]; kv2=kv2[0]; return kv1<kv2?-1:kv1>kv2?1:0 });
            if (opts.aligned){
              var longest = 0;
              for (var i=keyvals.length;i--;) if (keyvals[i][0].length>longest) longest = keyvals[i][0].length;
              var padding = repeat(' ',longest);
              for (var i=keyvals.length;i--;) keyvals[i][0] = padRight(padding,keyvals[i][0]);
            }
            var indent2 = indent+opts.indent;
            for (var i=keyvals.length;i--;){
              var k=keyvals[i][0], v=keyvals[i][1];
              var oneLine = k+colon+build(v,'');
              keyvals[i] = (opts.wrap===false || oneLine.length<=opts.wrap || !v || typeof v!="object") ? oneLine : (k+colon+build(v,indent2).replace(/^\s+/,''));
            }
            return indent+'{\n'+keyvals.join(',\n')+'\n'+indent+'}'
          }

        default:
          return indent+JSON.stringify(o);
      }
    }
  }

  function repeat(str,times){ // http://stackoverflow.com/a/17800645/405017
    var result = '';
    while(true){
      if (times & 1) result += str;
      times >>= 1;
      if (times) str += str;
      else break;
    }
    return result;
  }
  function padRight(pad, str){
    return (str + pad).substring(0, pad.length);
  }
}
neatJSON.version = "0.5";

})(typeof exports === 'undefined' ? this : exports);

Merging two arrayLists into a new arrayList, with no duplicates and in order, in Java

I'm not sure why your current code is failing (what is the Exception you get?), but I would like to point out this approach performs O(N-squared). Consider pre-sorting your input arrays (if they are not defined to be pre-sorted) and merging the sorted arrays:

http://www.algolist.net/Algorithms/Merge/Sorted_arrays

Sorting is generally O(N logN) and the merge is O(m+n).

How do I use hexadecimal color strings in Flutter?

A simple function without using a class:

Color _colorFromHex(String hexColor) {
  final hexCode = hexColor.replaceAll('#', '');
  return Color(int.parse('FF$hexCode', radix: 16));
}

You can use it like this:

Color color1 = _colorFromHex("b74093");
Color color2 = _colorFromHex("#b74093");

How to send value attribute from radio button in PHP

When you select a radio button and click on a submit button, you need to handle the submission of any selected values in your php code using $_POST[] For example: if your radio button is:

<input type="radio" name="rdb" value="male"/>

then in your php code you need to use:

$rdb_value = $_POST['rdb'];

How to change font-color for disabled input?

You can't for Internet Explorer.

See this comment I wrote on a related topic:

There doesn't seem to be a good way, see: How to change color of disabled html controls in IE8 using css - you can set the input to readonly instead, but that has other consequences (such as with readonly, the input will be sent to the server on submit, but with disabled, it won't be): http://jsfiddle.net/wCFBw/40

Also, see: Changing font colour in Textboxes in IE which are disabled

How do I create the small icon next to the website tab for my site?

This is for the icon in the browser (most of the sites omit the type):

<link rel="icon" type="image/vnd.microsoft.icon"
     href="http://example.com/favicon.ico" />

or

<link rel="icon" type="image/png"
     href="http://example.com/image.png" />

or

<link rel="apple-touch-icon"
     href="http://example.com//apple-touch-icon.png">

for the shortcut icon:

<link rel="shortcut icon"
     href="http://example.com/favicon.ico" />

Place them in the <head></head> section.

Edit may 2019 some additional examples from MDN

ResultSet exception - before start of result set

Every answer uses .next() or uses .beforeFirst() and then .next(). But why not this:

result.first();

So You just set the pointer to the first record and go from there. It's available since java 1.2 and I just wanted to mention this for anyone whose ResultSet exists of one specific record.

Concatenating Files And Insert New Line In Between Files

If you have few enough files that you can list each one, then you can use process substitution in Bash, inserting a newline between each pair of files:

cat File1.txt <(echo) File2.txt <(echo) File3.txt > finalfile.txt

Test if registry value exists

My version, matching the exact text from the caught exception. It will return true if it's a different exception but works for this simple case. Also Get-ItemPropertyValue is new in PS 5.0

Function Test-RegValExists($Path, $Value){
$ee = @() # Exception catcher
try{
    Get-ItemPropertyValue -Path $Path -Name $Value | Out-Null
   }
catch{$ee += $_}

    if ($ee.Exception.Message -match "Property $Value does not exist"){return $false}
else {return $true}
}

Python 2.7: %d, %s, and float()

See String Formatting Operations:

%d is the format code for an integer. %f is the format code for a float.

%s prints the str() of an object (What you see when you print(object)).

%r prints the repr() of an object (What you see when you print(repr(object)).

For a float %s, %r and %f all display the same value, but that isn't the case for all objects. The other fields of a format specifier work differently as well:

>>> print('%10.2s' % 1.123) # print as string, truncate to 2 characters in a 10-place field.
        1.
>>> print('%10.2f' % 1.123) # print as float, round to 2 decimal places in a 10-place field.
      1.12

Java ResultSet how to check if there are any results

To be totally sure of rather the resultset is empty or not regardless of cursor position, I would do something like this:

public static boolean isMyResultSetEmpty(ResultSet rs) throws SQLException {
    return (!rs.isBeforeFirst() && rs.getRow() == 0);
}

This function will return true if ResultSet is empty, false if not or throw an SQLException if that ResultSet is closed/uninitialized.

MySQL - how to front pad zip code with "0"?

Ok, so you've switched the column from Number to VARCHAR(5). Now you need to update the zipcode field to be left-padded. The SQL to do that would be:

UPDATE MyTable
SET ZipCode = LPAD( ZipCode, 5, '0' );

This will pad all values in the ZipCode column to 5 characters, adding '0's on the left.

Of course, now that you've got all of your old data fixed, you need to make sure that your any new data is also zero-padded. There are several schools of thought on the correct way to do that:

  • Handle it in the application's business logic. Advantages: database-independent solution, doesn't involve learning more about the database. Disadvantages: needs to be handled everywhere that writes to the database, in all applications.

  • Handle it with a stored procedure. Advantages: Stored procedures enforce business rules for all clients. Disadvantages: Stored procedures are more complicated than simple INSERT/UPDATE statements, and not as portable across databases. A bare INSERT/UPDATE can still insert non-zero-padded data.

  • Handle it with a trigger. Advantages: Will work for Stored Procedures and bare INSERT/UPDATE statements. Disadvantages: Least portable solution. Slowest solution. Triggers can be hard to get right.

In this case, I would handle it at the application level (if at all), and not the database level. After all, not all countries use a 5-digit Zipcode (not even the US -- our zipcodes are actually Zip+4+2: nnnnn-nnnn-nn) and some allow letters as well as digits. Better NOT to try and force a data format and to accept the occasional data error, than to prevent someone from entering the correct value, even though it's format isn't quite what you expected.

CSS3 selector :first-of-type with class name?

This it not possible to use the CSS3 selector :first-of-type to select the first element with a given class name.

However, if the targeted element has a previous element sibling, you can combine the negation CSS pseudo-class and the adjacent sibling selectors to match an element that doesn't immediately have a previous element with the same class name :

:not(.myclass1) + .myclass1

Full working code example:

_x000D_
_x000D_
p:first-of-type {color:blue}_x000D_
p:not(.myclass1) + .myclass1 { color: red }_x000D_
p:not(.myclass2) + .myclass2 { color: green }
_x000D_
<div>_x000D_
  <div>This text should appear as normal</div>_x000D_
  <p>This text should be blue.</p>_x000D_
  <p class="myclass1">This text should appear red.</p>_x000D_
  <p class="myclass2">This text should appear green.</p>_x000D_
</div>
_x000D_
_x000D_
_x000D_

MySQL JOIN with LIMIT 1 on joined table

Accepted answer by @goggin13 looks wrong. Other solutions provided to-date will work, but suffer from the n+1 problem and as such, suffer a performance hit.

n+1 problem: If there are 100 categories, then we would have to do 1 select to get the categories, then for each of the 100 categories returned, we would need to do a select to get the products in that category. So 101 SELECT queries would be performed.

My alternative solution solves the n+1 problem and consequently should be significantly more performant as only 2 selects are being performed.

SELECT
  *
FROM
    (SELECT c.id, c.title, p.id AS product_id, p.title
    FROM categories AS c
    JOIN products AS p ON c.id = p.category_id
    ORDER BY c.id ASC) AS a 
GROUP BY id;

Dealing with timestamps in R

You want the (standard) POSIXt type from base R that can be had in 'compact form' as a POSIXct (which is essentially a double representing fractional seconds since the epoch) or as long form in POSIXlt (which contains sub-elements). The cool thing is that arithmetic etc are defined on this -- see help(DateTimeClasses)

Quick example:

R> now <- Sys.time()
R> now
[1] "2009-12-25 18:39:11 CST"
R> as.numeric(now)
[1] 1.262e+09
R> now + 10  # adds 10 seconds
[1] "2009-12-25 18:39:21 CST"
R> as.POSIXlt(now)
[1] "2009-12-25 18:39:11 CST"
R> str(as.POSIXlt(now))
 POSIXlt[1:9], format: "2009-12-25 18:39:11"
R> unclass(as.POSIXlt(now))
$sec
[1] 11.79

$min
[1] 39

$hour
[1] 18

$mday
[1] 25

$mon
[1] 11

$year
[1] 109

$wday
[1] 5

$yday
[1] 358

$isdst
[1] 0

attr(,"tzone")
[1] "America/Chicago" "CST"             "CDT"            
R> 

As for reading them in, see help(strptime)

As for difference, easy too:

R> Jan1 <- strptime("2009-01-01 00:00:00", "%Y-%m-%d %H:%M:%S")
R> difftime(now, Jan1, unit="week")
Time difference of 51.25 weeks
R> 

Lastly, the zoo package is an extremely versatile and well-documented container for matrix with associated date/time indices.

Show MySQL host via SQL Command

To get current host name :-

select @@hostname;
show variables where Variable_name like '%host%';

To get hosts for all incoming requests :-

select host from information_schema.processlist;

Based on your last comment,
I don't think you can resolve IP for the hostname using pure mysql function,
as it require a network lookup, which could be taking long time.

However, mysql document mention this :-

resolveip google.com.sg

docs :- http://dev.mysql.com/doc/refman/5.0/en/resolveip.html

Join String list elements with a delimiter in one step

Or Joiner from Google Guava.

Joiner joiner = Joiner.on("+");
String join = joiner.join(joinList);

Shorter syntax for casting from a List<X> to a List<Y>?

The direct cast var ListOfY = (List<Y>)ListOfX is not possible because it would require co/contravariance of the List<T> type, and that just can't be guaranteed in every case. Please read on to see the solutions to this casting problem.

While it seems normal to be able to write code like this:

List<Animal> animals = (List<Animal>) mammalList;

because we can guarantee that every mammal will be an animal, this is obviously a mistake:

List<Mammal> mammals = (List<Mammal>) animalList;

since not every animal is a mammal.

However, using C# 3 and above, you can use

IEnumerable<Animal> animals = mammalList.Cast<Animal>();

that eases the casting a little. This is syntactically equivalent to your one-by-one adding code, as it uses an explicit cast to cast each Mammal in the list to an Animal, and will fail if the cast is not successfull.

If you like more control over the casting / conversion process, you could use the ConvertAll method of the List<T> class, which can use a supplied expression to convert the items. It has the added benifit that it returns a List, instead of IEnumerable, so no .ToList() is necessary.

List<object> o = new List<object>();
o.Add("one");
o.Add("two");
o.Add(3);

IEnumerable<string> s1 = o.Cast<string>(); //fails on the 3rd item
List<string> s2 = o.ConvertAll(x => x.ToString()); //succeeds

C++ How do I convert a std::chrono::time_point to long and back

I would also note there are two ways to get the number of ms in the time point. I'm not sure which one is better, I've benchmarked them and they both have the same performance, so I guess it's a matter of preference. Perhaps Howard could chime in:

auto now = system_clock::now();

//Cast the time point to ms, then get its duration, then get the duration's count.
auto ms = time_point_cast<milliseconds>(now).time_since_epoch().count();

//Get the time point's duration, then cast to ms, then get its count.
auto ms = duration_cast<milliseconds>(tpBid.time_since_epoch()).count();

The first one reads more clearly in my mind going from left to right.

Tomcat: LifecycleException when deploying

This might be caused by issue in your code. In my case, for instance,

I had Mongo database pointing to my local(done this for testing and forgot to update it back) instead of the one on EC2 which is the same machine 
        where war file is deployed to. 

How did I figured it out? I had to compare with older version of the code which works fine.

C# - How to add an Excel Worksheet programmatically - Office XP / 2003

You need to add a COM reference in your project to the "Microsoft Excel 11.0 Object Library" - or whatever version is appropriate.

This code works for me:

private void AddWorksheetToExcelWorkbook(string fullFilename,string worksheetName)
{
    Microsoft.Office.Interop.Excel.Application xlApp = null;
    Workbook xlWorkbook = null;
    Sheets xlSheets = null;
    Worksheet xlNewSheet = null;

    try {
        xlApp = new Microsoft.Office.Interop.Excel.Application();

        if (xlApp == null)
            return;

        // Uncomment the line below if you want to see what's happening in Excel
        // xlApp.Visible = true;

        xlWorkbook = xlApp.Workbooks.Open(fullFilename, 0, false, 5, "", "",
                false, XlPlatform.xlWindows, "",
                true, false, 0, true, false, false);

        xlSheets = xlWorkbook.Sheets as Sheets;

        // The first argument below inserts the new worksheet as the first one
        xlNewSheet = (Worksheet)xlSheets.Add(xlSheets[1], Type.Missing, Type.Missing, Type.Missing);
        xlNewSheet.Name = worksheetName;

        xlWorkbook.Save();
        xlWorkbook.Close(Type.Missing,Type.Missing,Type.Missing);
        xlApp.Quit();
    }
    finally {
        Marshal.ReleaseComObject(xlNewSheet);
        Marshal.ReleaseComObject(xlSheets);
        Marshal.ReleaseComObject(xlWorkbook);
        Marshal.ReleaseComObject(xlApp);
        xlApp = null;
    }
}

Note that you want to be very careful about properly cleaning up and releasing your COM object references. Included in that StackOverflow question is a useful rule of thumb: "Never use 2 dots with COM objects". In your code; you're going to have real trouble with that. My demo code above does NOT properly clean up the Excel app, but it's a start!

Some other links that I found useful when looking into this question:

According to MSDN

To use COM interop, you must have administrator or Power User security permissions.

Hope that helps.

Extract part of a regex match

Use ( ) in regexp and group(1) in python to retrieve the captured string (re.search will return None if it doesn't find the result, so don't use group() directly):

title_search = re.search('<title>(.*)</title>', html, re.IGNORECASE)

if title_search:
    title = title_search.group(1)

How to remove "rows" with a NA value?

dat <- data.frame(x1 = c(1,2,3, NA, 5), x2 = c(100, NA, 300, 400, 500))

na.omit(dat)
  x1  x2
1  1 100
3  3 300
5  5 500

CSS text-overflow in a table cell?

To clip text with an ellipsis when it overflows a table cell, you will need to set the max-width CSS property on each td class for the overflow to work. No extra layout div elements are required:

td
{
 max-width: 100px;
 overflow: hidden;
 text-overflow: ellipsis;
 white-space: nowrap;
}

For responsive layouts; use the max-width CSS property to specify the effective minimum width of the column, or just use max-width: 0; for unlimited flexibility. Also, the containing table will need a specific width, typically width: 100%;, and the columns will typically have their width set as percentage of the total width

table {width: 100%;}
td
{
 max-width: 0;
 overflow: hidden;
 text-overflow: ellipsis;
 white-space: nowrap;
}
td.column_a {width: 30%;}
td.column_b {width: 70%;}

Historical: For IE 9 (or less) you need to have this in your HTML, to fix an IE-specific rendering issue

<!--[if IE]>
<style>
table {table-layout: fixed; width: 100px;}
</style>
<![endif]-->

Difference between using "chmod a+x" and "chmod 755"

Indeed there is.

chmod a+x is relative to the current state and just sets the x flag. So a 640 file becomes 751 (or 750?), a 644 file becomes 755.

chmod 755, however, sets the mask as written: rwxr-xr-x, no matter how it was before. It is equivalent to chmod u=rwx,go=rx.

Change the mouse pointer using JavaScript

document.body.style.cursor = 'cursorurl';

How to get the background color code of an element in hex?

There's a bit of a hack for this, since the HTML5 canvas is required to parse color values when certain properties like strokeStyle and fillStyle are set:

var ctx = document.createElement('canvas').getContext('2d');
ctx.strokeStyle = 'rgb(64, 128, 192)';
var hexColor = ctx.strokeStyle;

Apple Cover-flow effect using jQuery or other library?

Not sure if you're talking about Coverflow (scroll through images) or Quicklook (preview files in lightbox), try editing your question.

Here's some JS Coverflow implementations:

Horizontal scroll css?

use max-width instead of width

max-width:530px;

demo:http://jsfiddle.net/FPBWr/161/

Generating an MD5 checksum of a file

I'm clearly not adding anything fundamentally new, but added this answer before I was up to commenting status, plus the code regions make things more clear -- anyway, specifically to answer @Nemo's question from Omnifarious's answer:

I happened to be thinking about checksums a bit (came here looking for suggestions on block sizes, specifically), and have found that this method may be faster than you'd expect. Taking the fastest (but pretty typical) timeit.timeit or /usr/bin/time result from each of several methods of checksumming a file of approx. 11MB:

$ ./sum_methods.py
crc32_mmap(filename) 0.0241742134094
crc32_read(filename) 0.0219960212708
subprocess.check_output(['cksum', filename]) 0.0553209781647
md5sum_mmap(filename) 0.0286180973053
md5sum_read(filename) 0.0311000347137
subprocess.check_output(['md5sum', filename]) 0.0332629680634
$ time md5sum /tmp/test.data.300k
d3fe3d5d4c2460b5daacc30c6efbc77f  /tmp/test.data.300k

real    0m0.043s
user    0m0.032s
sys     0m0.010s
$ stat -c '%s' /tmp/test.data.300k
11890400

So, looks like both Python and /usr/bin/md5sum take about 30ms for an 11MB file. The relevant md5sum function (md5sum_read in the above listing) is pretty similar to Omnifarious's:

import hashlib
def md5sum(filename, blocksize=65536):
    hash = hashlib.md5()
    with open(filename, "rb") as f:
        for block in iter(lambda: f.read(blocksize), b""):
            hash.update(block)
    return hash.hexdigest()

Granted, these are from single runs (the mmap ones are always a smidge faster when at least a few dozen runs are made), and mine's usually got an extra f.read(blocksize) after the buffer is exhausted, but it's reasonably repeatable and shows that md5sum on the command line is not necessarily faster than a Python implementation...

EDIT: Sorry for the long delay, haven't looked at this in some time, but to answer @EdRandall's question, I'll write down an Adler32 implementation. However, I haven't run the benchmarks for it. It's basically the same as the CRC32 would have been: instead of the init, update, and digest calls, everything is a zlib.adler32() call:

import zlib
def adler32sum(filename, blocksize=65536):
    checksum = zlib.adler32("")
    with open(filename, "rb") as f:
        for block in iter(lambda: f.read(blocksize), b""):
            checksum = zlib.adler32(block, checksum)
    return checksum & 0xffffffff

Note that this must start off with the empty string, as Adler sums do indeed differ when starting from zero versus their sum for "", which is 1 -- CRC can start with 0 instead. The AND-ing is needed to make it a 32-bit unsigned integer, which ensures it returns the same value across Python versions.

Switch case on type c#

Here's an option that stays as true I could make it to the OP's requirement to be able to switch on type. If you squint hard enough it almost looks like a real switch statement.

The calling code looks like this:

var @switch = this.Switch(new []
{
    this.Case<WebControl>(x => { /* WebControl code here */ }),
    this.Case<TextBox>(x => { /* TextBox code here */ }),
    this.Case<ComboBox>(x => { /* ComboBox code here */ }),
});

@switch(obj);

The x in each lambda above is strongly-typed. No casting required.

And to make this magic work you need these two methods:

private Action<object> Switch(params Func<object, Action>[] tests)
{
    return o =>
    {
        var @case = tests
            .Select(f => f(o))
            .FirstOrDefault(a => a != null);

        if (@case != null)
        {
            @case();
        }
    };
}

private Func<object, Action> Case<T>(Action<T> action)
{
    return o => o is T ? (Action)(() => action((T)o)) : (Action)null;
}

Almost brings tears to your eyes, right?

Nonetheless, it works. Enjoy.

Get checkbox value in jQuery

Best way is $('input[name="line"]:checked').val()

And also you can get selected text $('input[name="line"]:checked').text()

Add value attribute and name to your radio button inputs. Make sure all inputs have same name attribute.

<div class="col-8 m-radio-inline">
    <label class="m-radio m-radio-filter">
        <input type="radio" name="line" value="1" checked> Value Text 1
    </label>
    <label class="m-radio m-radio-filter">
        <input type="radio" name="line" value="2"> Value Text 2
    </label>
    <label class="m-radio m-radio-filter">
        <input type="radio" name="line" value="3"> Value Text 3
    </label>
</div>

How do you beta test an iphone app?

With iOS 8, Xcode 6, iTunes Connect and TestFlight you don't need UDIDs and Ad Hocs anymore. You will just need an Apple ID from your beta tester. Right now you can only beta test your app with 25 internal testers, but soon 1000 external testers will be available too. This blog post shows you how to setup a beta test with internal testers.

Append data frames together in a for loop

Try to use rbindlist approach over rbind as it's very, very fast.

Example:

library(data.table)

##### example 1: slow processing ######

table.1 <- data.frame(x = NA, y = NA)
time.taken <- 0
for( i in 1:100) {
  start.time = Sys.time()
  x <- rnorm(100)
  y <- x/2 +x/3
  z <- cbind.data.frame(x = x, y = y)

  table.1 <- rbind(table.1, z)
  end.time <- Sys.time()
  time.taken  <- (end.time - start.time) + time.taken

}
print(time.taken)
> Time difference of 0.1637917 secs

####example 2: faster processing #####

table.2 <- list()
t0 <- 0
for( i in 1:100) {
  s0 = Sys.time()
  x <- rnorm(100)
  y <- x/2 + x/3

  z <- cbind.data.frame(x = x, y = y)

  table.2[[i]] <- z

  e0 <- Sys.time()
  t0  <- (e0 - s0) + t0

}
s1 = Sys.time()
table.3 <- rbindlist(table.2)
e1 = Sys.time()

t1  <- (e1-s1) + t0
t1
> Time difference of 0.03064394 secs

RegEx for matching "A-Z, a-z, 0-9, _" and "."

^[A-Za-z0-9_.]+$

From beginning until the end of the string, match one or more of these characters.

Edit:

Note that ^ and $ match the beginning and the end of a line. When multiline is enabled, this can mean that one line matches, but not the complete string.

Use \A for the beginning of the string, and \z for the end.

See for example: http://msdn.microsoft.com/en-us/library/h5181w5w(v=vs.110).aspx

run program in Python shell

If you want to avoid writing all of this everytime, you can define a function :

def run(filename):
    exec(open(filename).read())

and then call it

run('filename.py')

How to fix error "ERROR: Command errored out with exit status 1: python." when trying to install django-heroku using pip

You need to add the package containing the executable pg_config.

A prior answer should have details you need: pg_config executable not found

ActiveXObject creation error " Automation server can't create object"

For this to work you have to really, really loosen your security settings (generally NOT recommended)

You will need to add the website to your "Trusted Zone", then go into the custom settings (scroll about 1/2 way down the page) and change:

ActiveX controls and plugins - Enable (or prompt)... any of the settings that apply to your code (I think the very last one is the one you are hitting) -- "script ActiveX controls marked safe for scripting*"

That all said, unless you have a really, really good reason for doing this - you are opening up a major "hole" in your browsers security... step very carefully... and do not expect that other end users will be willing to do the same.

What's the difference between display:inline-flex and display:flex?

Open in Full page for better understanding

_x000D_
_x000D_
.item {_x000D_
  width : 100px;_x000D_
  height : 100px;_x000D_
  margin: 20px;_x000D_
  border: 1px solid blue;_x000D_
  background-color: yellow;_x000D_
  text-align: center;_x000D_
  line-height: 99px;_x000D_
}_x000D_
_x000D_
.flex-con {_x000D_
  flex-wrap: wrap;_x000D_
  /* <A>    */_x000D_
  display: flex;_x000D_
  /* 1. uncomment below 2 lines by commenting above 1 line */_x000D_
  /* <B>   */_x000D_
/*   display: inline-flex; */_x000D_
 _x000D_
}_x000D_
_x000D_
.label {_x000D_
  padding-bottom: 20px;_x000D_
}_x000D_
.flex-inline-play {_x000D_
  padding: 20px;_x000D_
  border: 1px dashed green;_x000D_
/*  <C> */_x000D_
  width: 1000px;_x000D_
/*   <D> */_x000D_
  display: flex;_x000D_
}
_x000D_
<figure>_x000D_
  <blockquote>_x000D_
     <h1>Flex vs inline-flex</h1>_x000D_
    <cite>This pen is understand difference between_x000D_
    flex and inline-flex. Follow along to understand this basic property of css</cite>_x000D_
    <ul>_x000D_
      <li>Follow #1 in CSS:_x000D_
        <ul>_x000D_
          <li>Comment <code>display: flex</code></li>_x000D_
          <li>Un-comment <code>display: inline-flex</code></li>_x000D_
        </ul>_x000D_
      </li>_x000D_
      <li>_x000D_
        Hope you would have understood till now. This is very similar to situation of `inline-block` vs `block`. Lets go beyond and understand usecase to apply learning. Now lets play with combinations of A, B, C & D by un-commenting only as instructed:_x000D_
        <ul>_x000D_
     <li>A with D -- does this do same job as <code>display: inline-flex</code>. Umm, you may be right, but not its doesnt do always, keep going !</li>_x000D_
          <li>A with C</li>_x000D_
          <li>A with C & D -- Something wrong ? Keep going !</li>_x000D_
          <li>B with C</li>_x000D_
          <li>B with C & D -- Still same ? Did you learn something ? inline-flex is useful if you have space to occupy in parent of 2 flexboxes <code>.flex-con</code>. That's the only usecase</li>_x000D_
        </ul>_x000D_
      </li>_x000D_
    </ul>_x000D_
  </blockquote>_x000D_
  _x000D_
</figure>_x000D_
<br/>_x000D_
 <div class="label">Playground:</div>_x000D_
<div class="flex-inline-play">_x000D_
  <div class="flex-con">_x000D_
    <div class="item">1</div>_x000D_
    <div class="item">2</div>_x000D_
    <div class="item">3</div>_x000D_
    <div class="item">4</div>_x000D_
  </div>_x000D_
  <div class="flex-con">_x000D_
    <div class="item">X</div>_x000D_
    <div class="item">Y</div>_x000D_
    <div class="item">Z</div>_x000D_
    <div class="item">V</div>_x000D_
    <div class="item">W</div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How to adjust the size of y axis labels only in R?

Don't know what you are doing (helpful to show what you tried that didn't work), but your claim that cex.axis only affects the x-axis is not true:

set.seed(123)
foo <- data.frame(X = rnorm(10), Y = rnorm(10))
plot(Y ~ X, data = foo, cex.axis = 3)

at least for me with:

> sessionInfo()
R version 2.11.1 Patched (2010-08-17 r52767)
Platform: x86_64-unknown-linux-gnu (64-bit)

locale:
 [1] LC_CTYPE=en_GB.UTF-8       LC_NUMERIC=C              
 [3] LC_TIME=en_GB.UTF-8        LC_COLLATE=en_GB.UTF-8    
 [5] LC_MONETARY=C              LC_MESSAGES=en_GB.UTF-8   
 [7] LC_PAPER=en_GB.UTF-8       LC_NAME=C                 
 [9] LC_ADDRESS=C               LC_TELEPHONE=C            
[11] LC_MEASUREMENT=en_GB.UTF-8 LC_IDENTIFICATION=C       

attached base packages:
[1] grid      stats     graphics  grDevices utils     datasets  methods  
[8] base     

other attached packages:
[1] ggplot2_0.8.8 proto_0.3-8   reshape_0.8.3 plyr_1.2.1   

loaded via a namespace (and not attached):
[1] digest_0.4.2 tools_2.11.1

Also, cex.axis affects the labelling of tick marks. cex.lab is used to control what R call the axis labels.

plot(Y ~ X, data = foo, cex.lab = 3)

but even that works for both the x- and y-axis.


Following up Jens' comment about using barplot(). Check out the cex.names argument to barplot(), which allows you to control the bar labels:

dat <- rpois(10, 3) names(dat) <- LETTERS[1:10] barplot(dat, cex.names = 3, cex.axis = 2)

As you mention that cex.axis was only affecting the x-axis I presume you had horiz = TRUE in your barplot() call as well? As the bar labels are not drawn with an axis() call, applying Joris' (otherwise very useful) answer with individual axis() calls won't help in this situation with you using barplot()

HTH

Simple dictionary in C++

If you are into optimization, and assuming the input is always one of the four characters, the function below might be worth a try as a replacement for the map:

char map(const char in)
{ return ((in & 2) ? '\x8a' - in : '\x95' - in); }

It works based on the fact that you are dealing with two symmetric pairs. The conditional works to tell apart the A/T pair from the G/C one ('G' and 'C' happen to have the second-least-significant bit in common). The remaining arithmetics performs the symmetric mapping. It's based on the fact that a = (a + b) - b is true for any a,b.

Window.open as modal popup?

You can try open a modal dialog with html5 and css3, try this code:

_x000D_
_x000D_
.windowModal {_x000D_
    position: fixed;_x000D_
    font-family: Arial, Helvetica, sans-serif;_x000D_
    top: 0;_x000D_
    right: 0;_x000D_
    bottom: 0;_x000D_
    left: 0;_x000D_
    background: rgba(0,0,0,0.8);_x000D_
    z-index: 99999;_x000D_
    opacity:0;_x000D_
    -webkit-transition: opacity 400ms ease-in;_x000D_
    -moz-transition: opacity 400ms ease-in;_x000D_
    transition: opacity 400ms ease-in;_x000D_
    pointer-events: none;_x000D_
}_x000D_
.windowModal:target {_x000D_
    opacity:1;_x000D_
    pointer-events: auto;_x000D_
}_x000D_
_x000D_
.windowModal > div {_x000D_
    width: 400px;_x000D_
    position: relative;_x000D_
    margin: 10% auto;_x000D_
    padding: 5px 20px 13px 20px;_x000D_
    border-radius: 10px;_x000D_
    background: #fff;_x000D_
    background: -moz-linear-gradient(#fff, #999);_x000D_
    background: -webkit-linear-gradient(#fff, #999);_x000D_
    background: -o-linear-gradient(#fff, #999);_x000D_
}_x000D_
.close {_x000D_
    background: #606061;_x000D_
    color: #FFFFFF;_x000D_
    line-height: 25px;_x000D_
    position: absolute;_x000D_
    right: -12px;_x000D_
    text-align: center;_x000D_
    top: -10px;_x000D_
    width: 24px;_x000D_
    text-decoration: none;_x000D_
    font-weight: bold;_x000D_
    -webkit-border-radius: 12px;_x000D_
    -moz-border-radius: 12px;_x000D_
    border-radius: 12px;_x000D_
    -moz-box-shadow: 1px 1px 3px #000;_x000D_
    -webkit-box-shadow: 1px 1px 3px #000;_x000D_
    box-shadow: 1px 1px 3px #000;_x000D_
}_x000D_
_x000D_
.close:hover { background: #00d9ff; }
_x000D_
<a href="#divModal">Open Modal Window</a>_x000D_
_x000D_
<div id="divModal" class="windowModal">_x000D_
    <div>_x000D_
        <a href="#close" title="Close" class="close">X</a>_x000D_
        <h2>Modal Dialog</h2>_x000D_
        <p>This example shows a modal window without using javascript only using html5 and css3, I try it it¡</p>_x000D_
        <p>Using javascript, with new versions of html5 and css3 is not necessary can do whatever we want without using js libraries.</p>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Difference between matches() and find() in Java Regex

matches() will only return true if the full string is matched. find() will try to find the next occurrence within the substring that matches the regex. Note the emphasis on "the next". That means, the result of calling find() multiple times might not be the same. In addition, by using find() you can call start() to return the position the substring was matched.

final Matcher subMatcher = Pattern.compile("\\d+").matcher("skrf35kesruytfkwu4ty7sdfs");
System.out.println("Found: " + subMatcher.matches());
System.out.println("Found: " + subMatcher.find() + " - position " + subMatcher.start());
System.out.println("Found: " + subMatcher.find() + " - position " + subMatcher.start());
System.out.println("Found: " + subMatcher.find() + " - position " + subMatcher.start());
System.out.println("Found: " + subMatcher.find());
System.out.println("Found: " + subMatcher.find());
System.out.println("Matched: " + subMatcher.matches());

System.out.println("-----------");
final Matcher fullMatcher = Pattern.compile("^\\w+$").matcher("skrf35kesruytfkwu4ty7sdfs");
System.out.println("Found: " + fullMatcher.find() + " - position " + fullMatcher.start());
System.out.println("Found: " + fullMatcher.find());
System.out.println("Found: " + fullMatcher.find());
System.out.println("Matched: " + fullMatcher.matches());
System.out.println("Matched: " + fullMatcher.matches());
System.out.println("Matched: " + fullMatcher.matches());
System.out.println("Matched: " + fullMatcher.matches());

Will output:

Found: false
Found: true - position 4
Found: true - position 17
Found: true - position 20
Found: false
Found: false
Matched: false
-----------
Found: true - position 0
Found: false
Found: false
Matched: true
Matched: true
Matched: true
Matched: true

So, be careful when calling find() multiple times if the Matcher object was not reset, even when the regex is surrounded with ^ and $ to match the full string.

PHP How to fix Notice: Undefined variable:

Declare them before the while loop.

$hn = "";
$pid = "";
$datereg = "";
$prefix = "";
$fname = "";
$lname = "";
$age = "";
$sex = "";

You are getting the notice because the variables are declared and assigned inside the loop.

Instagram API to fetch pictures with specific hashtags

Firstly, the Instagram API endpoint "tags" required OAuth authentication.

You can query results for a particular hashtag (snowy in this case) using the following url

It is rate limited to 5000 (X-Ratelimit-Limit:5000) per hour

https://api.instagram.com/v1/tags/snowy/media/recent

Sample response

{
  "pagination":  {
    "next_max_tag_id": "1370433362010",
    "deprecation_warning": "next_max_id and min_id are deprecated for this endpoint; use min_tag_id and max_tag_id instead",
    "next_max_id": "1370433362010",
    "next_min_id": "1370443976800",
    "min_tag_id": "1370443976800",
    "next_url": "https://api.instagram.com/v1/tags/snowy/media/recent?access_token=40480112.1fb234f.4866541998fd4656a2e2e2beaa5c4bb1&max_tag_id=1370433362010"
  },
  "meta":  {
    "code": 200
  },
  "data":  [
     {
      "attribution": null,
      "tags":  [
        "snowy"
      ],
      "type": "image",
      "location": null,
      "comments":  {
        "count": 0,
        "data":  []
      },
      "filter": null,
      "created_time": "1370418343",
      "link": "http://instagram.com/p/aK1yrGRi3l/",
      "likes":  {
        "count": 1,
        "data":  [
           {
            "username": "iri92lol",
            "profile_picture": "http://images.ak.instagram.com/profiles/profile_404174490_75sq_1370417509.jpg",
            "id": "404174490",
            "full_name": "Iri"
          }
        ]
      },
      "images":  {
        "low_resolution":  {
          "url": "http://distilleryimage1.s3.amazonaws.com/ecf272a2cdb311e2990322000a9f192c_6.jpg",
          "width": 306,
          "height": 306
        },
        "thumbnail":  {
          "url": "http://distilleryimage1.s3.amazonaws.com/ecf272a2cdb311e2990322000a9f192c_5.jpg",
          "width": 150,
          "height": 150
        },
        "standard_resolution":  {
          "url": "http://distilleryimage1.s3.amazonaws.com/ecf272a2cdb311e2990322000a9f192c_7.jpg",
          "width": 612,
          "height": 612
        }
      },
      "users_in_photo":  [],
      "caption":  {
        "created_time": "1370418353",
        "text": "#snowy",
        "from":  {
          "username": "iri92lol",
          "profile_picture": "http://images.ak.instagram.com/profiles/profile_404174490_75sq_1370417509.jpg",
          "id": "404174490",
          "full_name": "Iri"
        },
        "id": "471425773832908504"
      },
      "user_has_liked": false,
      "id": "471425689728724453_404174490",
      "user":  {
        "username": "iri92lol",
        "website": "",
        "profile_picture": "http://images.ak.instagram.com/profiles/profile_404174490_75sq_1370417509.jpg",
        "full_name": "Iri",
        "bio": "",
        "id": "404174490"
      }
    }
}

You can play around here :

https://apigee.com/console/instagram?req=%7B%22resource%22%3A%22get_tags_media_recent%22%2C%22params%22%3A%7B%22query%22%3A%7B%7D%2C%22template%22%3A%7B%22tag-name%22%3A%22snowy%22%7D%2C%22headers%22%3A%7B%7D%2C%22body%22%3A%7B%22attachmentFormat%22%3A%22mime%22%2C%22attachmentContentDisposition%22%3A%22form-data%22%7D%7D%2C%22verb%22%3A%22get%22%7D

You need to use "Authentication" as OAuth 2 and will be prompted to signin via Instagram. Post that you might have to reneter the "tag-name" in "Template" section.

All the pagination related data is available in the "pagination" parameter in the response and use it's "next_url" to query for the next set of result.

What does the "map" method do in Ruby?

map, along with select and each is one of Ruby's workhorses in my code.

It allows you to run an operation on each of your array's objects and return them all in the same place. An example would be to increment an array of numbers by one:

[1,2,3].map {|x| x + 1 }
#=> [2,3,4]

If you can run a single method on your array's elements you can do it in a shorthand-style like so:

  1. To do this with the above example you'd have to do something like this

    class Numeric
      def plusone
        self + 1
      end
    end
    [1,2,3].map(&:plusone)
    #=> [2,3,4]
    
  2. To more simply use the ampersand shortcut technique, let's use a different example:

    ["vanessa", "david", "thomas"].map(&:upcase)
    #=> ["VANESSA", "DAVID", "THOMAS"]
    

Transforming data in Ruby often involves a cascade of map operations. Study map & select, they are some of the most useful Ruby methods in the primary library. They're just as important as each.

(map is also an alias for collect. Use whatever works best for you conceptually.)

More helpful information:

If the Enumerable object you're running each or map on contains a set of Enumerable elements (hashes, arrays), you can declare each of those elements inside your block pipes like so:

[["audi", "black", 2008], ["bmw", "red", 2014]].each do |make, color, year|
  puts "make: #{make}, color: #{color}, year: #{year}"
end
# Output:
# make: audi, color: black, year: 2008
# make: bmw, color: red, year: 2014

In the case of a Hash (also an Enumerable object, a Hash is simply an array of tuples with special instructions for the interpreter). The first "pipe parameter" is the key, the second is the value.

{:make => "audi", :color => "black", :year => 2008}.each do |k,v|
    puts "#{k} is #{v}"
end
#make is audi
#color is black
#year is 2008

To answer the actual question:

Assuming that params is a hash, this would be the best way to map through it: Use two block parameters instead of one to capture the key & value pair for each interpreted tuple in the hash.

params = {"one" => 1, "two" => 2, "three" => 3}
params.each do |k,v|
  puts "#{k}=#{v}"
end
# one=1
# two=2
# three=3

Selecting Folder Destination in Java?

I found a good example of what you need in this link.

import javax.swing.JFileChooser;

public class Main {
  public static void main(String s[]) {
    JFileChooser chooser = new JFileChooser();
    chooser.setCurrentDirectory(new java.io.File("."));
    chooser.setDialogTitle("choosertitle");
    chooser.setFileSelectionMode(JFileChooser.DIRECTORIES_ONLY);
    chooser.setAcceptAllFileFilterUsed(false);

    if (chooser.showOpenDialog(null) == JFileChooser.APPROVE_OPTION) {
      System.out.println("getCurrentDirectory(): " + chooser.getCurrentDirectory());
      System.out.println("getSelectedFile() : " + chooser.getSelectedFile());
    } else {
      System.out.println("No Selection ");
    }
  }
}

Listview Scroll to the end of the list after updating the list

A combination of TRANSCRIPT_MODE_ALWAYS_SCROLL and setSelection made it work for me

ChatAdapter adapter = new ChatAdapter(this);

ListView lv = (ListView) findViewById(R.id.chatList);
lv.setTranscriptMode(AbsListView.TRANSCRIPT_MODE_ALWAYS_SCROLL);
lv.setAdapter(adapter);

adapter.registerDataSetObserver(new DataSetObserver() {
    @Override
    public void onChanged() {
        super.onChanged();
        lv.setSelection(adapter.getCount() - 1);    
    }
});

Read binary file as string in Ruby

You can probably encode the tar file in Base64. Base 64 will give you a pure ASCII representation of the file that you can store in a plain text file. Then you can retrieve the tar file by decoding the text back.

You do something like:

require 'base64'

file_contents = Base64.encode64(tar_file_data)

Have look at the Base64 Rubydocs to get a better idea.

How to find the socket connection state in C?

you can use SS_ISCONNECTED macro in getsockopt() function. SS_ISCONNECTED is define in socketvar.h.

Measure the time it takes to execute a t-sql query

DECLARE @StartTime datetime
DECLARE @EndTime datetime
SELECT @StartTime=GETDATE() 

 -- Write Your Query


SELECT @EndTime=GETDATE()

--This will return execution time of your query
SELECT DATEDIFF(MS,@StartTime,@EndTime) AS [Duration in millisecs]

You can also See this solution

ASP.NET Web API : Correct way to return a 401/unauthorised response

As an alternative to the other answers, you can also use this code if you want to return an IActionResult within an ASP.NET controller.

ASP.NET

 return Content(HttpStatusCode.Unauthorized, "My error message");

Update: ASP.NET Core

Above code does not work in ASP.NET Core, you can use one of these instead:

 return StatusCode((int)System.Net.HttpStatusCode.Unauthorized, "My error message");
 return StatusCode(Microsoft.AspNetCore.Http.StatusCodes.Status401Unauthorized, "My error message");
 return StatusCode(401, "My error message");

Apparently the reason phrase is pretty optional (Can an HTTP response omit the Reason-Phrase?)

Programmatically create a UIView with color gradient

Try This it worked like a charm for me,

Objective C

I have set RGB gradient background Color to UIview

   UIView *view = [[UIView alloc] initWithFrame:CGRectMake(0,0,320,35)];
   CAGradientLayer *gradient = [CAGradientLayer layer];
   gradient.frame = view.bounds;
   gradient.startPoint = CGPointZero;
   gradient.endPoint = CGPointMake(1, 1);
   gradient.colors = [NSArray arrayWithObjects:(id)[[UIColor colorWithRed:34.0/255.0 green:211/255.0 blue:198/255.0 alpha:1.0] CGColor],(id)[[UIColor colorWithRed:145/255.0 green:72.0/255.0 blue:203/255.0 alpha:1.0] CGColor], nil];
   [view.layer addSublayer:gradient];

enter image description here

UPDATED :- Swift3 +

Code :-

 var gradientView = UIView(frame: CGRect(x: 0, y: 0, width: 320, height: 35))
 let gradientLayer:CAGradientLayer = CAGradientLayer()
 gradientLayer.frame.size = self.gradientView.frame.size
 gradientLayer.colors = 
 [UIColor.white.cgColor,UIColor.red.withAlphaComponent(1).cgColor] 
//Use diffrent colors
 gradientView.layer.addSublayer(gradientLayer)

enter image description here

You can add starting and end point of gradient color.

  gradientLayer.startPoint = CGPoint(x: 0.0, y: 1.0)
  gradientLayer.endPoint = CGPoint(x: 1.0, y: 1.0)

enter image description here

For more details description refer CAGradientLayer Doc

Hope this is help for some one .

How to save the contents of a div as a image?

Do something like this:

A <div> with ID of #imageDIV, another one with ID #download and a hidden <div> with ID #previewImage.

Include the latest version of jquery, and jspdf.debug.js from the jspdf CDN

Then add this script:

var element = $("#imageDIV"); // global variable
var getCanvas; // global variable
$('document').ready(function(){
  html2canvas(element, {
    onrendered: function (canvas) {
      $("#previewImage").append(canvas);
      getCanvas = canvas;
    }
  });
});
$("#download").on('click', function () {
  var imgageData = getCanvas.toDataURL("image/png");
  // Now browser starts downloading it instead of just showing it
  var newData = imageData.replace(/^data:image\/png/, "data:application/octet-stream");
  $("#download").attr("download", "image.png").attr("href", newData);
});

The div will be saved as a PNG on clicking the #download

How do I add an element to a list in Groovy?

From the documentation:

We can add to a list in many ways:

assert [1,2] + 3 + [4,5] + 6 == [1, 2, 3, 4, 5, 6]
assert [1,2].plus(3).plus([4,5]).plus(6) == [1, 2, 3, 4, 5, 6]
    //equivalent method for +
def a= [1,2,3]; a += 4; a += [5,6]; assert a == [1,2,3,4,5,6]
assert [1, *[222, 333], 456] == [1, 222, 333, 456]
assert [ *[1,2,3] ] == [1,2,3]
assert [ 1, [2,3,[4,5],6], 7, [8,9] ].flatten() == [1, 2, 3, 4, 5, 6, 7, 8, 9]

def list= [1,2]
list.add(3) //alternative method name
list.addAll([5,4]) //alternative method name
assert list == [1,2,3,5,4]

list= [1,2]
list.add(1,3) //add 3 just before index 1
assert list == [1,3,2]
list.addAll(2,[5,4]) //add [5,4] just before index 2
assert list == [1,3,5,4,2]

list = ['a', 'b', 'z', 'e', 'u', 'v', 'g']
list[8] = 'x'
assert list == ['a', 'b', 'z', 'e', 'u', 'v', 'g', null, 'x']

You can also do:

def myNewList = myList << "fifth"

javascript how to create a validation error message without using alert

You need to stop the submission if an error occured:

HTML

<form name ="myform" onsubmit="return validation();"> 

JS

if (document.myform.username.value == "") {
     document.getElementById('errors').innerHTML="*Please enter a username*";
     return false;
}

Why aren't python nested functions called closures?

I had a situation where I needed a separate but persistent name space. I used classes. I don't otherwise. Segregated but persistent names are closures.

>>> class f2:
...     def __init__(self):
...         self.a = 0
...     def __call__(self, arg):
...         self.a += arg
...         return(self.a)
...
>>> f=f2()
>>> f(2)
2
>>> f(2)
4
>>> f(4)
8
>>> f(8)
16

# **OR**
>>> f=f2() # **re-initialize**
>>> f(f(f(f(2)))) # **nested**
16

# handy in list comprehensions to accumulate values
>>> [f(i) for f in [f2()] for i in [2,2,4,8]][-1] 
16

How does one convert a HashMap to a List in Java?

HashMap<Integer, String> map = new HashMap<Integer, String>();
map.put (1, "Mark");
map.put (2, "Tarryn");
List<String> list = new ArrayList<String>(map.values());
for (String s : list) {
    System.out.println(s);
}

Expansion of variables inside single quotes in a command in Bash

The repo command can't care what kind of quotes it gets. If you need parameter expansion, use double quotes. If that means you wind up having to backslash a lot of stuff, use single quotes for most of it, and then break out of them and go into doubles for the part where you need the expansion to happen.

repo forall -c 'literal stuff goes here; '"stuff with $parameters here"' more literal stuff'

Explanation follows, if you're interested.

When you run a command from the shell, what that command receives as arguments is an array of null-terminated strings. Those strings may contain absolutely any non-null character.

But when the shell is building that array of strings from a command line, it interprets some characters specially; this is designed to make commands easier (indeed, possible) to type. For instance, spaces normally indicate the boundary between strings in the array; for that reason, the individual arguments are sometimes called "words". But an argument may nonetheless have spaces in it; you just need some way to tell the shell that's what you want.

You can use a backslash in front of any character (including space, or another backslash) to tell the shell to treat that character literally. But while you can do something like this:

echo \”That\'ll\ be\ \$4.96,\ please,\"\ said\ the\ cashier

...it can get tiresome. So the shell offers an alternative: quotation marks. These come in two main varieties.

Double-quotation marks are called "grouping quotes". They prevent wildcards and aliases from being expanded, but mostly they're for including spaces in a word. Other things like parameter and command expansion (the sorts of thing signaled by a $) still happen. And of course if you want a literal double-quote inside double-quotes, you have to backslash it:

echo "\"That'll be \$4.96, please,\" said the cashier"

Single-quotation marks are more draconian. Everything between them is taken completely literally, including backslashes. There is absolutely no way to get a literal single quote inside single quotes.

Fortunately, quotation marks in the shell are not word delimiters; by themselves, they don't terminate a word. You can go in and out of quotes, including between different types of quotes, within the same word to get the desired result:

echo '"That'\''ll be $4.96, please," said the cashier'

So that's easier - a lot fewer backslashes, although the close-single-quote, backslashed-literal-single-quote, open-single-quote sequence takes some getting used to.

Modern shells have added another quoting style not specified by the POSIX standard, in which the leading single quotation mark is prefixed with a dollar sign. Strings so quoted follow similar conventions to string literals in the ANSI standard version of the C programming language, and are therefore sometimes called "ANSI strings" and the $'...' pair "ANSI quotes". Within such strings, the above advice about backslashes being taken literally no longer applies. Instead, they become special again - not only can you include a literal single quotation mark or backslash by prepending a backslash to it, but the shell also expands the ANSI C character escapes (like \n for a newline, \t for tab, and \xHH for the character with hexadecimal code HH). Otherwise, however, they behave as single-quoted strings: no parameter or command substitution takes place:

echo $'"That\'ll be $4.96, please," said the cashier'

The important thing to note is that the single string received as the argument to the echo command is exactly the same in all of these examples. After the shell is done parsing a command line, there is no way for the command being run to tell what was quoted how. Even if it wanted to.

How to build x86 and/or x64 on Windows from command line with CMAKE?

try use CMAKE_GENERATOR_PLATFORM

e.g.

// x86
cmake -DCMAKE_GENERATOR_PLATFORM=x86 . 

// x64
cmake -DCMAKE_GENERATOR_PLATFORM=x64 . 

Android Studio - Device is connected but 'offline'

A shorter cable did the trick.

It turns out that the wire thickness used inside the cable impacts on the resistance of the cable assembly – this resistance causes energy loss inside the cable when an attached load draws a current, and causes a voltage drop which can reduce the voltage to the end device to a point where it is not possible to charge quickly or completely.

http://goughlui.com/2014/10/01/usb-cable-resistance-why-your-phonetablet-might-be-charging-slow/

jQuery: how to change title of document during .ready()?

Like this:

$(document).ready(function ()
{
    document.title = "Hello World!";
});

Be sure to set a default-title if you want your site to be properly indexed by search-engines.

A little tip:

$(function ()
{
    // this is a shorthand for the whole document-ready thing
    // In my opinion, it's more readable 
});

How to plot a 2D FFT in Matlab?

Assuming that I is your input image and F is its Fourier Transform (i.e. F = fft2(I))

You can use this code:

F = fftshift(F); % Center FFT

F = abs(F); % Get the magnitude
F = log(F+1); % Use log, for perceptual scaling, and +1 since log(0) is undefined
F = mat2gray(F); % Use mat2gray to scale the image between 0 and 1

imshow(F,[]); % Display the result

How to compare datetime with only date in SQL Server

If you are on SQL Server 2008 or later you can use the date datatype:

SELECT *
FROM [User] U
WHERE CAST(U.DateCreated as DATE) = '2014-02-07'

It should be noted that if date column is indexed then this will still utilise the index and is SARGable. This is a special case for dates and datetimes.

enter image description here

You can see that SQL Server actually turns this into a > and < clause:

enter image description here

I've just tried this on a large table, with a secondary index on the date column as per @kobik's comments and the index is still used, this is not the case for the examples that use BETWEEN or >= and <:

SELECT *
FROM [User] U
WHERE CAST(U.DateCreated as DATE) = '2016-07-05'

showing index usage with secondary index

anaconda update all possible packages?

I solved this problem with conda and pip.

Firstly, I run:

conda uninstall qt and conda uninstall matplotlib and conda uninstall PyQt5

After that, I opened the cmd and run this code that

pip uninstall qt , pip uninstall matplotlib , pip uninstall PyQt5

Lastly, You should install matplotlib in pip by this code that pip install matplotlib

How to stop line breaking in vim

I personnally went for:

  • set wrap,
  • set linebreak
  • set breakindent
  • set showbreak=?.

Some explanation:

  • wrap option visually wraps line instead of having to scroll horizontally
  • linebreak is for wrapping long lines at a specific character instead of just anywhere when the line happens to be too long, like in the middle of a word. By default, it breaks on whitespace (word separator), but you can configure it with breakat. It also does NOT insert EOL in the file as the OP wanted.
  • breakat is the character where it will visually break the line. No need to modify it if you want to break at whitespace between two words.
  • breakindent enables to visually indent the line when it breaks.
  • showbreak enables to set the character which indicates this break.

See :h <keyword> within vim for more info.

Note that you don't need to modify textwidth nor wrapmargin if you go this route.

Validation failed for one or more entities. See 'EntityValidationErrors' property for more details

Here's how you can check the contents of the EntityValidationErrors in Visual Studio (without writing any extra code) i.e. during Debugging in the IDE.

The Problem?

You are right, the Visual Studio debugger's View Details Popup doesn't show the actual errors inside the EntityValidationErrors collection .

enter image description here

The Solution!

Just add the following expression in a Quick Watch window and click Reevaluate.

((System.Data.Entity.Validation.DbEntityValidationException)$exception).EntityValidationErrors

In my case, see how I am able to expand into the ValidationErrors List inside the EntityValidationErrors collection

enter image description here

References: mattrandle.me blog post, @yoel's answer

Finding the average of a list

suppose that

x = [
    [-5.01,-5.43,1.08,0.86,-2.67,4.94,-2.51,-2.25,5.56,1.03],
    [-8.12,-3.48,-5.52,-3.78,0.63,3.29,2.09,-2.13,2.86,-3.33],
    [-3.68,-3.54,1.66,-4.11,7.39,2.08,-2.59,-6.94,-2.26,4.33]
]

you can notice that x has dimension 3*10 if you need to get the mean to each row you can type this

theMean = np.mean(x1,axis=1)

don't forget to import numpy as np

TensorFlow not found using pip

update 2019: for install the preview version of TensorFlow 2 in Google Colab you can use:

!wget https://developer.nvidia.com/compute/cuda/10.0/Prod/local_installers/cuda-repo-ubuntu1604-10-0-local-10.0.130-410.48_1.0-1_amd64 -O cuda-repo-ubuntu1604-10-0-local-10.0.130-410.48_1.0-1_amd64.deb
!dpkg -i cuda-repo-ubuntu1604-10-0-local-10.0.130-410.48_1.0-1_amd64.deb
!apt-key add /var/cuda-repo-10-0-local-10.0.130-410.48/7fa2af80.pub
!apt-get update
!apt-get install cuda
!pip install tf-nightly-gpu-2.0-preview

and for install the TensorFlow 2 bye pip you can use: pip install tf-nightly-gpu-2.0-preview for GPU and pip install tf-nightly-2.0-preview for CPU.

How to escape % in String.Format?

Here's an option if you need to escape multiple %'s in a string with some already escaped.

(?:[^%]|^)(?:(%%)+|)(%)(?:[^%])

To sanitise the message before passing it to String.format, you can use the following

Pattern p = Pattern.compile("(?:[^%]|^)(?:(%%)+|)(%)(?:[^%])");
Matcher m1 = p.matcher(log);

StringBuffer buf = new StringBuffer();
while (m1.find())
    m1.appendReplacement(buf, log.substring(m1.start(), m1.start(2)) + "%%" + log.substring(m1.end(2), m1.end()));

// Return the sanitised message
String escapedString = m1.appendTail(buf).toString();

This works with any number of formatting characters, so it will replace % with %%, %%% with %%%%, %%%%% with %%%%%% etc.

It will leave any already escaped characters alone (e.g. %%, %%%% etc.)

How do you install Boost on MacOS?

Download MacPorts, and run the following command:

sudo port install boost 

Safely turning a JSON string into an object

Just to the cover parse for different input types

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

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

When using the JSON.parse() on a JSON derived from an array, the method will return a JavaScript array, instead of a JavaScript object.

var myArr = JSON.parse(this.responseText);
console.log(myArr[0]);

Date objects are not allowed in JSON. For Dates do somthing like this

var text = '{ "name":"John", "birth":"1986-12-14", "city":"New York"}';
var obj = JSON.parse(text);
obj.birth = new Date(obj.birth);

Functions are not allowed in JSON. If you need to include a function, write it as a string.

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

Postgres password authentication fails

I came across this question, and the answers here didn't work for me; i couldn't figure out why i can't login and got the above error.

It turns out that postgresql saves usernames lowercase, but during authentication it uses both upper- and lowercase.

CREATE USER myNewUser WITH PASSWORD 'passWord';

will create a user with the username 'mynewuser' and password 'passWord'.

This means you have to authenticate with 'mynewuser', and not with 'myNewUser'. For a newbie in pgsql like me, this was confusing. I hope it helps others who run into this problem.

Cannot import the keyfile 'blah.pfx' - error 'The keyfile may be password protected'

As a workaround, I tried running the Visual Studio 2010 as an administrator, and it worked for me.

I hope this helps.

Check if table exists and if it doesn't exist, create it in SQL Server 2008

Declare @Username varchar(20)
Set @Username = 'Mike'

if not exists 
(Select * from INFORMATION_SCHEMA.TABLES where TABLE_NAME = 'tblEmp')

Begin
    Create table tblEmp (ID int primary key, Name varchar(50))
    Print (@Username + ' Table created successfully')
End

Else

Begin
    Print (@Username + ' : this Table Already exists in the database')
End

VBA collection: list of keys

If you intend to use the default VB6 Collection, then the easiest you can do is:

col1.add array("first key", "first string"), "first key"
col1.add array("second key", "second string"), "second key"
col1.add array("third key", "third string"), "third key"

Then you can list all values:

Dim i As Variant

For Each i In col1
  Debug.Print i(1)
Next

Or all keys:

Dim i As Variant

For Each i In col1
  Debug.Print i(0)
Next

"Fatal error: Unable to find local grunt." when running "grunt" command

I had this issue on my Windows grunt because I installed the 32 bit version of Node on a 64 bit Windows OS. When I installed the 64bit version specifically, it started working.

URL encoding in Android

Find Arabic chars and replace them with its UTF-8 encoding. some thing like this:

for (int i = 0; i < urlAsString.length(); i++) {
    if (urlAsString.charAt(i) > 255) {
        urlAsString = urlAsString.substring(0, i) + URLEncoder.encode(urlAsString.charAt(i)+"", "UTF-8") + urlAsString.substring(i+1);
    }
}
encodedURL = urlAsString;

Error: 'int' object is not subscriptable - Python

The problem is in the line,

int([x[age1]])

What you want is

x = int(age1)

You also need to convert the int to a string for the output...

print "Hi, " + name1+ " you will be 21 in: " + str(twentyone) + " years."

The complete script looks like,

name1 = raw_input("What's your name? ")
age1 = raw_input ("how old are you? ")
x = 0
x = int(age1)
twentyone = 21 - x
print "Hi, " + name1+ " you will be 21 in: " + str(twentyone) + " years."

Today`s date in an excel macro

Here's an example that puts the Now() value in column A.

Sub move()
    Dim i As Integer
    Dim sh1 As Worksheet
    Dim sh2 As Worksheet
    Dim nextRow As Long
    Dim copyRange As Range
    Dim destRange As Range

    Application.ScreenUpdating = False

        Set sh1 = ActiveWorkbook.Worksheets("Sheet1")
        Set sh2 = ActiveWorkbook.Worksheets("Sheet2")
        Set copyRange = sh1.Range("A1:A5")

        i = Application.WorksheetFunction.CountA(sh2.Range("B:B")) + 4

        Set destRange = sh2.Range("B" & i)

        destRange.Resize(1, copyRange.Rows.Count).Value = Application.Transpose(copyRange.Value)
        destRange.Offset(0, -1).Value = Format(Now(), "MMM-DD-YYYY")

        copyRange.Clear

    Application.ScreenUpdating = True

End Sub

There are better ways of getting the last row in column B than using a While loop, plenty of examples around here. Some are better than others but depend on what you're doing and what your worksheet structure looks like. I used one here which assumes that column B is ALL empty except the rows/records you're moving. If that's not the case, or if B1:B3 have some values in them, you'd need to modify or use another method. Or you could just use your loop, but I'd search for alternatives :)

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

I was also looking for this, but didn't want to impersonate a user to simply acquire a path!

user_path=$(grep $username /etc/passwd|cut -f6 -d":");

Now in your script, you can refer to $user_path in most cases would be /home/username

Assumes: You have previously set $username with the value of the intended users username. Source: http://www.unix.com/shell-programming-and-scripting/171782-cut-fields-etc-passwd-file-into-variables.html

scikit-learn random state in splitting dataset

We used the random_state parameter for reproducibility of the initial shuffling of training datasets after each epoch.

How to place two forms on the same page?

Give the submit buttons for both forms different names and use PHP to check which button has submitted data.

Form one button - btn1 Form two button -btn2

PHP Code:

if($_POST['btn1']){
    //Login
}elseif($_POST['btn2']){
    //Register
}

Dividing two integers to produce a float result

Cast the operands to floats:

float ans = (float)a / (float)b;

Multiple selector chaining in jQuery?

$("#Create").find(".myClass").add("#Edit .myClass").plugin({});

Use $.fn.add to concatenate two sets.

How do I push a local repo to Bitbucket using SourceTree without creating a repo on bitbucket first?

Setup Bitbucket Repository (Command Line with Mac)

Create New APPLICATION from starting with local reposity :

  1. Terminal -> cd ~/Documents (Paste your APPLICATION base directory path)
  2. Terminal -> mkdir (create directory with )
  3. Terminal -> cd (change directory with directory)
  4. BitBucket A/C -> create repository on bitBucket account
  5. Xcode -> create new xcode project with same name
  6. Terminal -> git init (initilize empty repo)
  7. Terminal -> git remote add origin (Ex. https://[email protected]/app/app.git)
  8. Terminal -> git add .
  9. Terminal -> git status
    1. Terminal -> git commit -m "IntialCommet"
    2. Terminal -> git push origin master

Create APPLICATION clone repository :

  1. Terminal -> mkdir (create directory with )
  2. Terminal -> cd (change directory with directory)
  3. Terminal -> git clone (Ex. https://[email protected]/app/app.git)
  4. Terminal -> cd
  5. Terminal -> git status (Show edit/updated file status)
  6. Terminal -> git pull origin master
  7. Terminal -> git add .
  8. Terminal -> git push origin master

Converting .NET DateTime to JSON

You can try a 3rd party library like json.net There's documention on the project site. It does say it requires .net 3.5.

Otherwise there's another one called Nii.json which i believe is a port from java. I found a link to it on this blog

How do I pass named parameters with Invoke-Command?

My solution to this was to write the script block dynamically with [scriptblock]:Create:

# Or build a complex local script with MARKERS here, and do substitutions
# I was sending install scripts to the remote along with MSI packages
# ...for things like Backup and AV protection etc.

$p1 = "good stuff"; $p2 = "better stuff"; $p3 = "best stuff"; $etc = "!"
$script = [scriptblock]::Create("MyScriptOnRemoteServer.ps1 $p1 $p2 $etc")
#strings get interpolated/expanded while a direct scriptblock does not

# the $parms are now expanded in the script block itself
# ...so just call it:
$result = invoke-command $computer -script $script

Passing arguments was very frustrating, trying various methods, e.g.,
-arguments, $using:p1, etc. and this just worked as desired with no problems.

Since I control the contents and variable expansion of the string which creates the [scriptblock] (or script file) this way, there is no real issue with the "invoke-command" incantation.

(It shouldn't be that hard. :) )

Most efficient way to prepend a value to an array

With ES6, you can now use the spread operator to create a new array with your new elements inserted before the original elements.

_x000D_
_x000D_
// Prepend a single item._x000D_
const a = [1, 2, 3];_x000D_
console.log([0, ...a]);
_x000D_
_x000D_
_x000D_

_x000D_
_x000D_
// Prepend an array._x000D_
const a = [2, 3];_x000D_
const b = [0, 1];_x000D_
console.log([...b, ...a]);
_x000D_
_x000D_
_x000D_

Update 2018-08-17: Performance

I intended this answer to present an alternative syntax that I think is more memorable and concise. It should be noted that according to some benchmarks (see this other answer), this syntax is significantly slower. This is probably not going to matter unless you are doing many of these operations in a loop.

How do I set the default font size in Vim?

Try a \<Space> before 12, like so:

:set guifont=Monospace\ 12

How to count certain elements in array?

I'm a begin fan of js array's reduce function.

const myArray =[1, 2, 3, 5, 2, 8, 9, 2];
const count = myArray.reduce((count, num) => num === 2 ? count + 1 : count, 0)

In fact if you really want to get fancy you can create a count function on the Array prototype. Then you can reuse it.

Array.prototype.count = function(filterMethod) {
  return this.reduce((count, item) => filterMethod(item)? count + 1 : count, 0);
} 

Then do

const myArray =[1, 2, 3, 5, 2, 8, 9, 2]
const count = myArray.count(x => x==2)

How to drop a unique constraint from table column?

If you know the name of your constraint then you can directly use the command like

alter table users drop constraint constraint_name;

If you don't know the constraint name, you can get the constraint by using this command

select constraint_name,constraint_type from user_constraints where table_name = 'YOUR TABLE NAME';

How to get the unix timestamp in C#

The simple code that I am using:

public static long CurrentTimestamp()
{
   return (long)(DateTime.UtcNow.Subtract(new DateTime(1970, 1, 1)).TotalSeconds * 1000);
}

This code is giving unix timestamp, total milliseconds from 1970-01-01 to now.

HttpWebRequest using Basic authentication

I finally got it!

string url = @"https://telematicoprova.agenziadogane.it/TelematicoServiziDiUtilitaWeb/ServiziDiUtilitaAutServlet?UC=22&SC=1&ST=2";
WebRequest request = WebRequest.Create(url);
request.Credentials = GetCredential();
request.PreAuthenticate = true;

and this is GetCredential()

private CredentialCache GetCredential()
{
    string url = @"https://telematicoprova.agenziadogane.it/TelematicoServiziDiUtilitaWeb/ServiziDiUtilitaAutServlet?UC=22&SC=1&ST=2";
    ServicePointManager.SecurityProtocol = SecurityProtocolType.Ssl3;
    CredentialCache credentialCache = new CredentialCache();
    credentialCache.Add(new System.Uri(url), "Basic", new NetworkCredential(ConfigurationManager.AppSettings["ead_username"], ConfigurationManager.AppSettings["ead_password"]));
    return credentialCache;
}

YAY!

How do I concatenate or merge arrays in Swift?

var arrayOne = [1,2,3]
var arrayTwo = [4,5,6]

if you want result as : [1,2,3,[4,5,6]]

arrayOne.append(arrayTwo)

above code will convert arrayOne as a single element and add it to the end of arrayTwo.

if you want result as : [1, 2, 3, 4, 5, 6] then,

arrayOne.append(contentsOf: arrayTwo)

above code will add all the elements of arrayOne at the end of arrayTwo.

Thanks.

How to change Screen buffer size in Windows Command Prompt from batch script

I was just searching for an answer to this exact question, come to find out the command itself adjusts the buffer!

mode con:cols=140 lines=70

The lines=70 part actually adjusts the Height in the 'Screen Buffer Size' setting, NOT the Height in the 'Window Size' setting.

Easily proven by running the command with a setting for 'lines=2500' (or whatever buffer you want) and then check the 'Properties' of the window, you'll see that indeed the buffer is now set to 2500.

My batch script ends up looking like this:

@echo off
cmd "mode con:cols=140 lines=2500"

How to drop rows of Pandas DataFrame whose value in a certain column is NaN

This question is already resolved, but...

...also consider the solution suggested by Wouter in his original comment. The ability to handle missing data, including dropna(), is built into pandas explicitly. Aside from potentially improved performance over doing it manually, these functions also come with a variety of options which may be useful.

In [24]: df = pd.DataFrame(np.random.randn(10,3))

In [25]: df.iloc[::2,0] = np.nan; df.iloc[::4,1] = np.nan; df.iloc[::3,2] = np.nan;

In [26]: df
Out[26]:
          0         1         2
0       NaN       NaN       NaN
1  2.677677 -1.466923 -0.750366
2       NaN  0.798002 -0.906038
3  0.672201  0.964789       NaN
4       NaN       NaN  0.050742
5 -1.250970  0.030561 -2.678622
6       NaN  1.036043       NaN
7  0.049896 -0.308003  0.823295
8       NaN       NaN  0.637482
9 -0.310130  0.078891       NaN

In [27]: df.dropna()     #drop all rows that have any NaN values
Out[27]:
          0         1         2
1  2.677677 -1.466923 -0.750366
5 -1.250970  0.030561 -2.678622
7  0.049896 -0.308003  0.823295

In [28]: df.dropna(how='all')     #drop only if ALL columns are NaN
Out[28]:
          0         1         2
1  2.677677 -1.466923 -0.750366
2       NaN  0.798002 -0.906038
3  0.672201  0.964789       NaN
4       NaN       NaN  0.050742
5 -1.250970  0.030561 -2.678622
6       NaN  1.036043       NaN
7  0.049896 -0.308003  0.823295
8       NaN       NaN  0.637482
9 -0.310130  0.078891       NaN

In [29]: df.dropna(thresh=2)   #Drop row if it does not have at least two values that are **not** NaN
Out[29]:
          0         1         2
1  2.677677 -1.466923 -0.750366
2       NaN  0.798002 -0.906038
3  0.672201  0.964789       NaN
5 -1.250970  0.030561 -2.678622
7  0.049896 -0.308003  0.823295
9 -0.310130  0.078891       NaN

In [30]: df.dropna(subset=[1])   #Drop only if NaN in specific column (as asked in the question)
Out[30]:
          0         1         2
1  2.677677 -1.466923 -0.750366
2       NaN  0.798002 -0.906038
3  0.672201  0.964789       NaN
5 -1.250970  0.030561 -2.678622
6       NaN  1.036043       NaN
7  0.049896 -0.308003  0.823295
9 -0.310130  0.078891       NaN

There are also other options (See docs at http://pandas.pydata.org/pandas-docs/stable/generated/pandas.DataFrame.dropna.html), including dropping columns instead of rows.

Pretty handy!

How to encrypt String in Java

Update on 12-DEC-2019

Unlike some other modes like CBC, GCM mode does not require the IV to be unpredictable. The only requirement is that the IV has to be unique for each invocation with a given key. If it repeats once for a given key, security can be compromised. An easy way to achieve this is to use a random IV from a strong pseudo random number generator as shown below.

Using a sequence or timestamp as IV is also possible, but it may not be as trivial as it may sound. For example, if the system does not correctly keep track of the sequences already used as IV in a persistent store, an invocation may repeat an IV after a system reboot. Likewise, there is no perfect clock. Computer clock readjusts etc.

Also, the key should be rotated after every 2^32 invocations. For further details on the IV requirement, refer to this answer and the NIST recommendations.


This is the encryption & decryption code I just wrote in Java 8 considering the following points. Hope someone would find this useful:

  1. Encryption Algorithm: Block cipher AES with 256 bits key is considered secure enough. To encrypt a complete message, a mode needs to be selected. Authenticated encryption (which provides both confidentiality and integrity) is recommended. GCM, CCM and EAX are most commonly used authenticated encryption modes. GCM is usually preferred and it performs well in Intel architectures which provide dedicated instructions for GCM. All these three modes are CTR-based (counter-based) modes and therefore they do not need padding. As a result they are not vulnerable to padding related attacks

  2. An initialization Vector (IV) is required for GCM. The IV is not a secret. The only requirement being it has to be random or unpredictable. In Java, the SecuredRandom class is meant to produce cryptographically strong pseudo random numbers. The pseudo-random number generation algorithm can be specified in the getInstance() method. However, since Java 8, the recommended way is to use getInstanceStrong() method which will use the strongest algorithm configured and provided by the Provider

  3. NIST recommends 96 bit IV for GCM to promote interoperability, efficiency, and simplicity of design

  4. To ensure additional security, in the following implementation SecureRandom is re-seeded after producing every 2^16 bytes of pseudo random byte generation

  5. The recipient needs to know the IV to be able to decrypt the cipher text. Therefore the IV needs to be transferred along with the cipher text. Some implementations send the IV as AD (Associated Data) which means that the authentication tag will be calculated on both the cipher text and the IV. However, that is not required. The IV can be simply pre-pended with the cipher text because if the IV is changed during transmission due to a deliberate attack or network/file system error, the authentication tag validation will fail anyway

  6. Strings should not be used to hold the clear text message or the key as Strings are immutable and thus we cannot clear them after use. These uncleared Strings then linger in the memory and may show up in a heap dump. For the same reason, the client calling these encryption or decryption methods should clear all the variables or arrays holding the message or the key after they are no longer needed.

  7. No provider is hard coded in the code following the general recommendations

  8. Finally for transmission over network or storage, the key or the cipher text should be encoded using Base64 encoding. The details of Base64 can be found here. The Java 8 approach should be followed

Byte arrays can be cleared using:

Arrays.fill(clearTextMessageByteArray, Byte.MIN_VALUE);

However, as of Java 8, there is no easy way to clear SecretKeyspec and SecretKey as the implementations of these two interfaces do not seem to have implemented the method destroy() of the interface Destroyable. In the following code, a separate method is written to clear the SecretKeySpec and SecretKey using reflection.

Key should be generated using one of the two approaches mentioned below.

Note that keys are secrets like passwords, but unlike passwords which are meant for human use, keys are meant to be used by cryptographic algorithms and hence should be generated using the above way only.

package com.sapbasu.javastudy;

import java.lang.reflect.Field;
import java.security.NoSuchAlgorithmException;
import java.security.SecureRandom;
import java.util.Arrays;
import java.util.List;
import java.util.Objects;
import java.util.Optional;

import javax.crypto.Cipher;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;

public class Crypto {

  private static final int AUTH_TAG_SIZE = 128; // bits

  // NIST recommendation: "For IVs, it is recommended that implementations
  // restrict support to the length of 96 bits, to
  // promote interoperability, efficiency, and simplicity of design."
  private static final int IV_LEN = 12; // bytes

  // number of random number bytes generated before re-seeding
  private static final double PRNG_RESEED_INTERVAL = Math.pow(2, 16);

  private static final String ENCRYPT_ALGO = "AES/GCM/NoPadding";

  private static final List<Integer> ALLOWED_KEY_SIZES = Arrays
      .asList(new Integer[] {128, 192, 256}); // bits

  private static SecureRandom prng;

  // Used to keep track of random number bytes generated by PRNG
  // (for the purpose of re-seeding)
  private static int bytesGenerated = 0;

  public byte[] encrypt(byte[] input, SecretKeySpec key) throws Exception {

    Objects.requireNonNull(input, "Input message cannot be null");
    Objects.requireNonNull(key, "key cannot be null");

    if (input.length == 0) {
      throw new IllegalArgumentException("Length of message cannot be 0");
    }

    if (!ALLOWED_KEY_SIZES.contains(key.getEncoded().length * 8)) {
      throw new IllegalArgumentException("Size of key must be 128, 192 or 256");
    }

    Cipher cipher = Cipher.getInstance(ENCRYPT_ALGO);

    byte[] iv = getIV(IV_LEN);

    GCMParameterSpec gcmParamSpec = new GCMParameterSpec(AUTH_TAG_SIZE, iv);

    cipher.init(Cipher.ENCRYPT_MODE, key, gcmParamSpec);
    byte[] messageCipher = cipher.doFinal(input);

    // Prepend the IV with the message cipher
    byte[] cipherText = new byte[messageCipher.length + IV_LEN];
    System.arraycopy(iv, 0, cipherText, 0, IV_LEN);
    System.arraycopy(messageCipher, 0, cipherText, IV_LEN,
        messageCipher.length);
    return cipherText;
  }

  public byte[] decrypt(byte[] input, SecretKeySpec key) throws Exception {
    Objects.requireNonNull(input, "Input message cannot be null");
    Objects.requireNonNull(key, "key cannot be null");

    if (input.length == 0) {
      throw new IllegalArgumentException("Input array cannot be empty");
    }

    byte[] iv = new byte[IV_LEN];
    System.arraycopy(input, 0, iv, 0, IV_LEN);

    byte[] messageCipher = new byte[input.length - IV_LEN];
    System.arraycopy(input, IV_LEN, messageCipher, 0, input.length - IV_LEN);

    GCMParameterSpec gcmParamSpec = new GCMParameterSpec(AUTH_TAG_SIZE, iv);

    Cipher cipher = Cipher.getInstance(ENCRYPT_ALGO);
    cipher.init(Cipher.DECRYPT_MODE, key, gcmParamSpec);

    return cipher.doFinal(messageCipher);
  }

  public byte[] getIV(int bytesNum) {

    if (bytesNum < 1) throw new IllegalArgumentException(
        "Number of bytes must be greater than 0");

    byte[] iv = new byte[bytesNum];

    prng = Optional.ofNullable(prng).orElseGet(() -> {
      try {
        prng = SecureRandom.getInstanceStrong();
      } catch (NoSuchAlgorithmException e) {
        throw new RuntimeException("Wrong algorithm name", e);
      }
      return prng;
    });

    if (bytesGenerated > PRNG_RESEED_INTERVAL || bytesGenerated == 0) {
      prng.setSeed(prng.generateSeed(bytesNum));
      bytesGenerated = 0;
    }

    prng.nextBytes(iv);
    bytesGenerated = bytesGenerated + bytesNum;

    return iv;
  }

  private static void clearSecret(Destroyable key)
      throws IllegalArgumentException, IllegalAccessException,
      NoSuchFieldException, SecurityException {
    Field keyField = key.getClass().getDeclaredField("key");
    keyField.setAccessible(true);
    byte[] encodedKey = (byte[]) keyField.get(key);
    Arrays.fill(encodedKey, Byte.MIN_VALUE);
  }
}

The encryption key can be generated primarily in two ways:

  • Without any password

    KeyGenerator keyGen = KeyGenerator.getInstance("AES");
    keyGen.init(KEY_LEN, SecureRandom.getInstanceStrong());
    SecretKey secretKey = keyGen.generateKey();
    SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getEncoded(),
        "AES");
    Crypto.clearSecret(secretKey);
    // After encryption or decryption with key
    Crypto.clearSecret(secretKeySpec);
    
  • With password

    SecureRandom random = SecureRandom.getInstanceStrong();
    byte[] salt = new byte[32];
    random.nextBytes(salt);
    PBEKeySpec keySpec = new PBEKeySpec(password, salt, iterations, 
       keyLength);
    SecretKeyFactory keyFactory = 
        SecretKeyFactory.getInstance("PBKDF2WithHmacSHA256");
    SecretKey secretKey = keyFactory.generateSecret(keySpec);
    SecretKeySpec secretKeySpec = new SecretKeySpec(secretKey.getEncoded(),
        "AES");
    Crypto.clearSecret(secretKey);
    // After encryption or decryption with key
    Crypto.clearSecret(secretKeySpec);
    

Update Based on Comments

As pointed out by @MaartenBodewes, my answer did not handle any String as is required by the question. Therefore, I'll make an attempt to fill that gap just in case someone stumbles upon this answer and leaves wondering about handling String.

As indicated earlier in the answer, handling sensitive information in a String is, in general, not a good idea because String is immutable and thus we cannot clear it off after use. And as we know, even when a String doesn't have a strong reference, the garbage collector does not immediately rush to remove it off heap. Thus, the String continues to be around in the memory for an unknown window of time even though it is not accessible to the program. The issue with that is, a heap dump during that time frame would reveal the sensitive information. Therefore, it is always better to handle all sensitive information in a byte array or char array and then fill the array with 0s once their purpose is served.

However, with all that knowledge, if we still end up in a situation where the sensitive information to be encrypted is in a String, we first need to convert it into a byte array and invoke the encrypt and decrypt functions introduced above. (The other input key can be generated using the code snippet provided above).

A String can be converted into bytes in the following way:

byte[] inputBytes = inputString.getBytes(StandardCharsets.UTF_8);

As of Java 8, String is internally stored in heap with UTF-16 encoding. However, we have used UTF-8 here as it usually takes less space than UTF-16, especially for ASCII characters.

Likewise, the encrypted byte array can also be converted into a String as below:

String encryptedString = new String(encryptedBytes, StandardCharsets.UTF_8);

Change bootstrap datepicker date format on select

  $(function () {
    $('.datetimepicker').datetimepicker(
      {
        format: 'Y-m-d h:m:s'
     }
    );
 });`

How to convert std::chrono::time_point to calendar datetime string with fractional seconds?

I would have put this in a comment on the accepted answer, since that's where it belongs, but I can't. So, just in case anyone gets unreliable results, this could be why.

Be careful of the accepted answer, it fails if the time_point is before the epoch.

This line of code:

std::size_t fractional_seconds = ms.count() % 1000;

will yield unexpected values if ms.count() is negative (since size_t is not meant to hold negative values).

What do $? $0 $1 $2 mean in shell script?

They are called the Positional Parameters.

3.4.1 Positional Parameters

A positional parameter is a parameter denoted by one or more digits, other than the single digit 0. Positional parameters are assigned from the shell’s arguments when it is invoked, and may be reassigned using the set builtin command. Positional parameter N may be referenced as ${N}, or as $N when N consists of a single digit. Positional parameters may not be assigned to with assignment statements. The set and shift builtins are used to set and unset them (see Shell Builtin Commands). The positional parameters are temporarily replaced when a shell function is executed (see Shell Functions).

When a positional parameter consisting of more than a single digit is expanded, it must be enclosed in braces.

Performance of Java matrix math libraries?

I'm the author of Java Matrix Benchmark (JMatBench) and I'll give my thoughts on this discussion.

There are significant difference between Java libraries and while there is no clear winner across the whole range of operations, there are a few clear leaders as can be seen in the latest performance results (October 2013).

If you are working with "large" matrices and can use native libraries, then the clear winner (about 3.5x faster) is MTJ with system optimised netlib. If you need a pure Java solution then MTJ, OjAlgo, EJML and Parallel Colt are good choices. For small matrices EJML is the clear winner.

The libraries I did not mention showed significant performance issues or were missing key features.

Make multiple-select to adjust its height to fit options without scroll bar

You can only do this in Javascript/JQuery, you can do it with the following JQuery (assuming you've gave your select an id of multiselect):

$(function () {
    $("#multiSelect").css("height", parseInt($("#multiSelect option").length) * 20);
});

Demo: http://jsfiddle.net/AZEFU/

Java Wait and Notify: IllegalMonitorStateException

You're calling both wait and notifyAll without using a synchronized block. In both cases the calling thread must own the lock on the monitor you call the method on.

From the docs for notify (wait and notifyAll have similar documentation but refer to notify for the fullest description):

This method should only be called by a thread that is the owner of this object's monitor. A thread becomes the owner of the object's monitor in one of three ways:

  • By executing a synchronized instance method of that object.
  • By executing the body of a synchronized statement that synchronizes on the object.
  • For objects of type Class, by executing a synchronized static method of that class.

Only one thread at a time can own an object's monitor.

Only one thread will be able to actually exit wait at a time after notifyAll as they'll all have to acquire the same monitor again - but all will have been notified, so as soon as the first one then exits the synchronized block, the next will acquire the lock etc.

How to find my php-fpm.sock?

When you look up your php-fpm.conf

example location:
cat /usr/src/php/sapi/fpm/php-fpm.conf

you will see, that you need to configure the PHP FastCGI Process Manager to actually use Unix sockets. Per default, the listen directive` is set up to listen on a TCP socket on one port. If there's no Unix socket defined, you won't find a Unix socket file.

; The address on which to accept FastCGI requests.
; Valid syntaxes are:
;   'ip.add.re.ss:port'    - to listen on a TCP socket to a specific IPv4 address on
;                            a specific port;
;   '[ip:6:addr:ess]:port' - to listen on a TCP socket to a specific IPv6 address on
;                            a specific port;
;   'port'                 - to listen on a TCP socket to all IPv4 addresses on a
;                            specific port;
;   '[::]:port'            - to listen on a TCP socket to all addresses
;                            (IPv6 and IPv4-mapped) on a specific port;
;   '/path/to/unix/socket' - to listen on a unix socket.
; Note: This value is mandatory.
listen = 127.0.0.1:9000

Using LIKE in an Oracle IN clause

No, you cannot do this. The values in the IN clause must be exact matches. You could modify the select thusly:

SELECT *
  FROM tbl
 WHERE my_col LIKE %val1%
    OR my_col LIKE %val2%
    OR my_col LIKE %val3%
 ...

If the val1, val2, val3... are similar enough, you might be able to use regular expressions in the REGEXP_LIKE operator.

Reset input value in angular 2

If you want to clear the input by using the HTML ONLY, then you can do something like this:

<input type="text"
       (keyup)="0"
       #searchCollectorInput
       class="search-metrics"
       placeholder="Find">

Notice the importance of (keyup)=0 and the reference to the input of course.

Then reset it like this:

<span *ngIf="searchCollectorInput.value.length > 0"
      (click)="searchCollectorInput.value = ''"
      class="fa fa-close" ></span>

HttpUtility does not exist in the current context

SLaks has the right answer... but let me be a bit more specific for people, like me, who are annoyed by this and can't find it right away :

Project -> Properties -> Application -> Target Framework -> select ".Net Framework 4"

the project will then save and reload.

How to simulate "Press any key to continue?"

If you're on Windows, you can use kbhit() which is part of the Microsoft run-time library. If you're on Linux, you can implement kbhit thus (source):

#include <stdio.h>
#include <termios.h>
#include <unistd.h>
#include <fcntl.h>

int kbhit(void)
{
  struct termios oldt, newt;
  int ch;
  int oldf;

  tcgetattr(STDIN_FILENO, &oldt);
  newt = oldt;
  newt.c_lflag &= ~(ICANON | ECHO);
  tcsetattr(STDIN_FILENO, TCSANOW, &newt);
  oldf = fcntl(STDIN_FILENO, F_GETFL, 0);
  fcntl(STDIN_FILENO, F_SETFL, oldf | O_NONBLOCK);

  ch = getchar();

  tcsetattr(STDIN_FILENO, TCSANOW, &oldt);
  fcntl(STDIN_FILENO, F_SETFL, oldf);

  if(ch != EOF)
  {
    ungetc(ch, stdin);
    return 1;
  }

  return 0;
}

Update: The above function works on OS X (at least, on OS X 10.5.8 - Leopard, so I would expect it to work on more recent versions of OS X). This gist can be saved as kbhit.c and compiled on both Linux and OS X with

gcc -o kbhit kbhit.c

When run with

./kbhit

It prompts you for a keypress, and exits when you hit a key (not limited to Enter or printable keys).

@Johnsyweb - please elaborate what you mean by "detailed canonical answer" and "all the concerns". Also, re "cross-platform": With this implementation of kbhit() you can have the same functionality in a C++ program on Linux/Unix/OS X/Windows - which other platforms might you be referring to?

Further update for @Johnsyweb: C++ applications do not live in a hermetically sealed C++ environment. A big reason for C++'s success is interoperability with C. All mainstream platforms are implemented with C interfaces (even if internal implementation is using C++) so your talk of "legacy" seems out of place. Plus, as we are talking about a single function, why do you need C++ for this ("C with classes")? As I pointed out, you can write in C++ and access this functionality easily, and your application's users are unlikely to care how you implemented it.

Insert entire DataTable into database at once instead of row by row?

I discovered SqlBulkCopy is an easy way to do this, and does not require a stored procedure to be written in SQL Server.

Here is an example of how I implemented it:

// take note of SqlBulkCopyOptions.KeepIdentity , you may or may not want to use this for your situation.  

using (var bulkCopy = new SqlBulkCopy(_connection.ConnectionString, SqlBulkCopyOptions.KeepIdentity))
{
      // my DataTable column names match my SQL Column names, so I simply made this loop. However if your column names don't match, just pass in which datatable name matches the SQL column name in Column Mappings
      foreach (DataColumn col in table.Columns)
      {
          bulkCopy.ColumnMappings.Add(col.ColumnName, col.ColumnName);
      }

      bulkCopy.BulkCopyTimeout = 600;
      bulkCopy.DestinationTableName = destinationTableName;
      bulkCopy.WriteToServer(table);
}

Model backing a DB Context has changed; Consider Code First Migrations

You need to believe me. I got this error for the simple reason that I forgot to add the connection string in the App.Config(mine is a wpf project) of your startup project.

The entire config in my case

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <configSections>
    <!-- For more information on Entity Framework configuration, visit http://go.microsoft.com/fwlink/?LinkID=237468 -->
    <section name="entityFramework" type="System.Data.Entity.Internal.ConfigFile.EntityFrameworkSection, EntityFramework, Version=6.0.0.0, Culture=neutral, PublicKeyToken=b77a5c561934e089" requirePermission="false" />
  </configSections>
  <connectionStrings>
    <add name="ZzaDbContext" connectionString="Data Source=(localdb)\MSSQLLocalDB;Initial Catalog=ZaaDbInDepth;Integrated Security=True;Connect Timeout=30;Encrypt=False;TrustServerCertificate=True;ApplicationIntent=ReadWrite;MultiSubnetFailover=False" providerName="System.Data.SqlClient"/>
  </connectionStrings>
  <startup>
    <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5.2" />
  </startup>
  <entityFramework>
    <defaultConnectionFactory type="System.Data.Entity.Infrastructure.LocalDbConnectionFactory, EntityFramework">
      <parameters>
        <parameter value="mssqllocaldb" />
      </parameters>
    </defaultConnectionFactory>
    <providers>
      <provider invariantName="System.Data.SqlClient" type="System.Data.Entity.SqlServer.SqlProviderServices, EntityFramework.SqlServer" />
    </providers>
  </entityFramework>
</configuration>

CSS3 :unchecked pseudo-class

The way I handled this was switching the className of a label based on a condition. This way you only need one label and you can have different classes for different states... Hope that helps!

Xcode build failure "Undefined symbols for architecture x86_64"

UPD

Apple requires to use arm64 architecture. Do not use x32 libraries in your project

So the answer below is not correct anymore!


Old answer

The new Xcode 5.1 sets the architecture armv7,armv7s,and arm64 as default.

And sometimes the error "build failure “Undefined symbols for architecture x86_64”" may be caused by this. Because, some libs (not Apple's) were compiled for x32 originally and doesn't support x64.

So what you need, is to change the "Architectures" for your project target like this

NB. If you're using Cocoapods - you should do the same for "Pods" target.

enter image description here

How to write super-fast file-streaming code in C#?

(For future reference.)

Quite possibly the fastest way to do this would be to use memory mapped files (so primarily copying memory, and the OS handling the file reads/writes via its paging/memory management).

Memory Mapped files are supported in managed code in .NET 4.0.

But as noted, you need to profile, and expect to switch to native code for maximum performance.

Changing font size and direction of axes text in ggplot2

Adding to previous solutions, you can also specify the font size relative to the base_size included in themes such as theme_bw() (where base_size is 11) using the rel() function.

For example:

ggplot(mtcars, aes(disp, mpg)) +
  geom_point() +
  theme_bw() +
  theme(axis.text.x=element_text(size=rel(0.5), angle=90))

What ports need to be open for TortoiseSVN to authenticate (clear text) and commit?

What's the first part of your Subversion repository URL?

  • If your URL looks like: http://subversion/repos/, then you're probably going over Port 80.
  • If your URL looks like: https://subversion/repos/, then you're probably going over Port 443.
  • If your URL looks like: svn://subversion/, then you're probably going over Port 3690.
  • If your URL looks like: svn+ssh://subversion/repos/, then you're probably going over Port 22.
  • If your URL contains a port number like: http://subversion/repos:8080, then you're using that port.

I can't guarantee the first four since it's possible to reconfigure everything to use different ports, of if you go through a proxy of some sort.

If you're using a VPN, you may have to configure your VPN client to reroute these to their correct ports. A lot of places don't configure their correctly VPNs to do this type of proxying. It's either because they have some sort of anal-retentive IT person who's being overly security conscious, or because they simply don't know any better. Even worse, they'll give you a client where this stuff can't be reconfigured.

The only way around that is to log into a local machine over the VPN, and then do everything from that system.

How to display 3 buttons on the same line in css

The following will display all 3 buttons on the same line provided there is enough horizontal space to display them:

<button type="submit" class="msgBtn" onClick="return false;" >Save</button>
<button type="submit" class="msgBtn2" onClick="return false;">Publish</button>
<button class="msgBtnBack">Back</button>
// Note the lack of unnecessary divs, floats, etc. 

The only reason the buttons wouldn't display inline is if they have had display:block applied to them within your css.

How to do if-else in Thymeleaf?

This work for me when I wanted to show a photo depending on the gender of the user:

<img th:src="${generou}=='Femenino' ? @{/images/user_mujer.jpg}: @{/images/user.jpg}" alt="AdminLTE Logo" class="brand-image img-circle elevation-3">

how to add script src inside a View when using Layout

You can add the script tags like how we use in the asp.net while doing client side validations like below.

@{
    ViewBag.Title = "Index";
}

<h2>Index</h2>
<script type="text/javascript" src="~/Scripts/jquery-3.1.1.min.js"></script>
<script type="text/javascript">
    $(function () {
       //Your code
    });
</script>

Can I set an unlimited length for maxJsonLength in web.config?

For those who are having issues with in MVC3 with JSON that's automatically being deserialized for a model binder and is too large, here is a solution.

  1. Copy the code for the JsonValueProviderFactory class from the MVC3 source code into a new class.
  2. Add a line to change the maximum JSON length before the object is deserialized.
  3. Replace the JsonValueProviderFactory class with your new, modified class.

Thanks to http://blog.naver.com/techshare/100145191355 and https://gist.github.com/DalSoft/1588818 for pointing me in the right direction for how to do this. The last link on the first site contains full source code for the solution.

Granting DBA privileges to user in Oracle

You need only to write:

GRANT DBA TO NewDBA;

Because this already makes the user a DB Administrator

How to name an object within a PowerPoint slide?

While the answer above is correct I would not recommend you to change the name in order to rely on it in the code.

Names are tricky. They can change. You should use the ShapeId and SlideId.

Especially beware to change the name of a shape programmatically since PowerPoint relies on the name and it might hinder its regular operation.

Remove redundant paths from $PATH variable

Here is a one line code that cleans up the PATH

  • It does not disturb the order of the PATH, just removes duplicates
  • Treats : and empth PATH gracefully
  • No special characters used, so does not require escape
  • Uses /bin/awk so it works even when PATH is broken

    export PATH="$(echo "$PATH" |/bin/awk 'BEGIN{RS=":";}
    {sub(sprintf("%c$",10),"");if(A[$0]){}else{A[$0]=1;
    printf(((NR==1)?"":":")$0)}}')";
    

Clang vs GCC for my Linux Development project

I think clang could be an alternative.

GCC and clang have some differences on expressions like a+++++a, and I've got many different answers with my peer who use clang on Mac while I use gcc.

GCC has become the standard, and clang could be an alternative. Because GCC is very stable and clang is still under developing.

How do I pass a datetime value as a URI parameter in asp.net mvc?

Typical format of a URI for ASP .NET MVC is Controller/Action/Id where Id is an integer

I would suggest sending the date value as a parameter rather than as part of the route:

 mysite/Controller/Action?date=21-9-2009 10:20

If it's still giving you problems the date may contain characters that are not allowed in a URI and need to be encoded. Check out:

 encodeURIComponent(yourstring)

It is a method within Javascript.

On the Server Side:

public ActionResult ActionName(string date)
{
     DateTime mydate;
     DateTime.Tryparse(date, out mydate);
}

FYI, any url parameter can be mapped to an action method parameter as long as the names are the same.

Conditionally formatting if multiple cells are blank (no numerics throughout spreadsheet )

enter image description here

How about just > Format only cells that contain - in the drop down box select Blanks

How to send string from one activity to another?

You can send data from one actvity to another with an Intent

Intent sendStuff = new Intent(this, TargetActivity.class);
sendStuff.putExtra(key, stringvalue);
startActivity(sendStuff);

You then can retrieve this information in the second activity by getting the intent and extracting the string extra. Do this in your onCreate() method.

Intent startingIntent = getIntent();
String whatYouSent = startingIntent.getStringExtra(key, value);

Then all you have to do is call setText on your TextView and use that string.

Getting an object array from an Angular service

Take a look at your code :

 getUsers(): Observable<User[]> {
        return Observable.create(observer => {
            this.http.get('http://users.org').map(response => response.json();
        })
    }

and code from https://angular.io/docs/ts/latest/tutorial/toh-pt6.html (BTW. really good tutorial, you should check it out)

 getHeroes(): Promise<Hero[]> {
    return this.http.get(this.heroesUrl)
               .toPromise()
               .then(response => response.json().data as Hero[])
               .catch(this.handleError);
  }

The HttpService inside Angular2 already returns an observable, sou don't need to wrap another Observable around like you did here:

   return Observable.create(observer => {
        this.http.get('http://users.org').map(response => response.json()

Try to follow the guide in link that I provided. You should be just fine when you study it carefully.

---EDIT----

First of all WHERE you log the this.users variable? JavaScript isn't working that way. Your variable is undefined and it's fine, becuase of the code execution order!

Try to do it like this:

  getUsers(): void {
        this.userService.getUsers()
            .then(users => {
               this.users = users
               console.log('this.users=' + this.users);
            });


    }

See where the console.log(...) is!

Try to resign from toPromise() it's seems to be just for ppl with no RxJs background.

Catch another link: https://scotch.io/tutorials/angular-2-http-requests-with-observables Build your service once again with RxJs observables.

$.ajax - dataType

as per docs:

  • "json": Evaluates the response as JSON and returns a JavaScript object. In jQuery 1.4 the JSON data is parsed in a strict manner; any malformed JSON is rejected and a parse error is thrown. (See json.org for more information on proper JSON formatting.)
  • "text": A plain text string.

How can I enable CORS on Django REST Framework

Django=2.2.12 django-cors-headers=3.2.1 djangorestframework=3.11.0

Follow the official instruction doesn't work

Finally use the old way to figure it out.

ADD:

# proj/middlewares.py
from rest_framework.authentication import SessionAuthentication


class CsrfExemptSessionAuthentication(SessionAuthentication):

    def enforce_csrf(self, request):
        return  # To not perform the csrf check previously happening

#proj/settings.py

REST_FRAMEWORK = {
    'DEFAULT_AUTHENTICATION_CLASSES': (
        'proj.middlewares.CsrfExemptSessionAuthentication',
    ),
}

How to show SVG file on React Native?

Use https://github.com/kristerkari/react-native-svg-transformer

In this package it is mentioned that .svg files are not supported in React Native v0.57 and lower so use .svgx extension for svg files.

For web or react-native-web use https://www.npmjs.com/package/@svgr/webpack


To render svg files using react-native-svg-uri with react-native version 0.57 and lower, you need to add following files to your root project

Note: change extension svg to svgx

step 1: add file transformer.js to project's root

// file: transformer.js

const cleanupSvg = require('./cleanup-svg');

const upstreamTransformer = require("metro/src/transformer");

// const typescriptTransformer = require("react-native-typescript-transformer");
// const typescriptExtensions = ["ts", "tsx"];

const svgExtensions = ["svgx"]

// function cleanUpSvg(text) {
//   text = text.replace(/width="([#0-9]+)px"/gi, "");
//    text = text.replace(/height="([#0-9]+)px"/gi, "");
//    return text;
// }

function fixRenderingBugs(content) {
  // content = cleanUpSvg(content); // cleanupSvg removes width and height attributes from svg
  return "module.exports = `" + content + "`";
}


module.exports.transform = function ({ src, filename, options }) {
  // if (typescriptExtensions.some(ext => filename.endsWith("." + ext))) {
  //  return typescriptTransformer.transform({ src, filename, options })
  // }

  if (svgExtensions.some(ext => filename.endsWith("." + ext))) {
    return upstreamTransformer.transform({
      src: fixRenderingBugs(src),
      filename,
      options
    })
  }

  return upstreamTransformer.transform({ src, filename, options });
}

step 2: add rn-cli.config.js to project's root

module.exports = {
    getTransformModulePath() {
      return require.resolve("./transformer");
    },
    getSourceExts() {
      return [/* "ts", "tsx", */ "svgx"];
    }
  };

The above mentioned solutions will work in production apps too ?

Removing empty lines in Notepad++

1) Ctrl + H ( Or Search Replace..) to open Replace window.

2) Select 'Search Mode' 'Regular expression'

3) In 'Find What' type ^(\s*)(.*)(\s*)$ & in 'Replace With' type \2

  • ^ - Matches start of line character
  • (\s*) - Matches empty space characters
  • (.*) - Matches any characters
  • (\s*) - Matches empty spaces characters
  • $ - Matches end of line character
  • \2 - Denotes the matching contend of the 2nd bracket

enter image description here Refer https://www.rexegg.com/regex-quickstart.html for more on regex.

How to Customize the time format for Python logging?

From the official documentation regarding the Formatter class:

The constructor takes two optional arguments: a message format string and a date format string.

So change

# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s")

to

# create formatter
formatter = logging.Formatter("%(asctime)s;%(levelname)s;%(message)s",
                              "%Y-%m-%d %H:%M:%S")

How to use <DllImport> in VB.NET?

Imports System.Runtime.InteropServices

"continue" in cursor.forEach()

Each iteration of the forEach() will call the function that you have supplied. To stop further processing within any given iteration (and continue with the next item) you just have to return from the function at the appropriate point:

elementsCollection.forEach(function(element){
  if (!element.shouldBeProcessed)
    return; // stop processing this iteration

  // This part will be avoided if not neccessary
  doSomeLengthyOperation();
});

CASCADE DELETE just once

I took Joe Love's answer and rewrote it using the IN operator with sub-selects instead of = to make the function faster (according to Hubbitus's suggestion):

create or replace function delete_cascade(p_schema varchar, p_table varchar, p_keys varchar, p_subquery varchar default null, p_foreign_keys varchar[] default array[]::varchar[])
 returns integer as $$
declare

    rx record;
    rd record;
    v_sql varchar;
    v_subquery varchar;
    v_primary_key varchar;
    v_foreign_key varchar;
    v_rows integer;
    recnum integer;

begin

    recnum := 0;
    select ccu.column_name into v_primary_key
        from
        information_schema.table_constraints  tc
        join information_schema.constraint_column_usage AS ccu ON ccu.constraint_name = tc.constraint_name and ccu.constraint_schema=tc.constraint_schema
        and tc.constraint_type='PRIMARY KEY'
        and tc.table_name=p_table
        and tc.table_schema=p_schema;

    for rx in (
        select kcu.table_name as foreign_table_name, 
        kcu.column_name as foreign_column_name, 
        kcu.table_schema foreign_table_schema,
        kcu2.column_name as foreign_table_primary_key
        from information_schema.constraint_column_usage ccu
        join information_schema.table_constraints tc on tc.constraint_name=ccu.constraint_name and tc.constraint_catalog=ccu.constraint_catalog and ccu.constraint_schema=ccu.constraint_schema 
        join information_schema.key_column_usage kcu on kcu.constraint_name=ccu.constraint_name and kcu.constraint_catalog=ccu.constraint_catalog and kcu.constraint_schema=ccu.constraint_schema
        join information_schema.table_constraints tc2 on tc2.table_name=kcu.table_name and tc2.table_schema=kcu.table_schema
        join information_schema.key_column_usage kcu2 on kcu2.constraint_name=tc2.constraint_name and kcu2.constraint_catalog=tc2.constraint_catalog and kcu2.constraint_schema=tc2.constraint_schema
        where ccu.table_name=p_table  and ccu.table_schema=p_schema
        and TC.CONSTRAINT_TYPE='FOREIGN KEY'
        and tc2.constraint_type='PRIMARY KEY'
)
    loop
        v_foreign_key := rx.foreign_table_schema||'.'||rx.foreign_table_name||'.'||rx.foreign_column_name;
        v_subquery := 'select "'||rx.foreign_table_primary_key||'" as key from '||rx.foreign_table_schema||'."'||rx.foreign_table_name||'"
             where "'||rx.foreign_column_name||'"in('||coalesce(p_keys, p_subquery)||') for update';
        if p_foreign_keys @> ARRAY[v_foreign_key] then
            --raise notice 'circular recursion detected';
        else
            p_foreign_keys := array_append(p_foreign_keys, v_foreign_key);
            recnum:= recnum + delete_cascade(rx.foreign_table_schema, rx.foreign_table_name, null, v_subquery, p_foreign_keys);
            p_foreign_keys := array_remove(p_foreign_keys, v_foreign_key);
        end if;
    end loop;

    begin
        if (coalesce(p_keys, p_subquery) <> '') then
            v_sql := 'delete from '||p_schema||'."'||p_table||'" where "'||v_primary_key||'"in('||coalesce(p_keys, p_subquery)||')';
            --raise notice '%',v_sql;
            execute v_sql;
            get diagnostics v_rows = row_count;
            recnum := recnum + v_rows;
        end if;
        exception when others then recnum=0;
    end;

    return recnum;

end;
$$
language PLPGSQL;

Laravel Eloquent "WHERE NOT IN"

You can do following.

DB::table('book_mast') 
->selectRaw('book_name,dt_of_pub,pub_lang,no_page,book_price')  
->whereNotIn('book_price',[100,200]);

Rails 4: before_filter vs. before_action

As we can see in ActionController::Base, before_action is just a new syntax for before_filter.

However all before_filters syntax are deprecated in Rails 5.0 and will be removed in Rails 5.1

jQuery - Call ajax every 10 seconds

setInterval(function()
{ 
    $.ajax({
      type:"post",
      url:"myurl.html",
      datatype:"html",
      success:function(data)
      {
          //do something with response data
      }
    });
}, 10000);//time in milliseconds 

List Directories and get the name of the Directory

This will print all the subdirectories of the current directory:

print [name for name in os.listdir(".") if os.path.isdir(name)]

I'm not sure what you're doing with split("-"), but perhaps this code will help you find a solution?

If you want the full pathnames of the directories, use abspath:

print [os.path.abspath(name) for name in os.listdir(".") if os.path.isdir(name)]

Note that these pieces of code will only get the immediate subdirectories. If you want sub-sub-directories and so on, you should use walk as others have suggested.

How can I return the difference between two lists?

You can convert them to Set collections, and perform a set difference operation on them.

Like this:

Set<Date> ad = new HashSet<Date>(a);
Set<Date> bd = new HashSet<Date>(b);
ad.removeAll(bd);

How to do date/time comparison

For case when your interval's end it's date without hours like "from 2017-01-01 to whole day of 2017-01-16" it's better to adjust interval's to 23 hours 59 minutes and 59 seconds like:

end = end.Add(time.Duration(23*time.Hour) + time.Duration(59*time.Minute) + time.Duration(59*time.Second)) 

if now.After(start) && now.Before(end) {
    ...
}

Redis: Show database size/size for keys

I usually prefer the key sampling method to troubleshoot such scenarios.

redis-cli -p 6379 -n db_number --bigkeys

Eg:-

redis-cli -p 6370 -n 0 --bigkeys

Making a flex item float right

You can't use float inside flex container and the reason is that float property does not apply to flex-level boxes as you can see here Fiddle.

So if you want to position child element to right of parent element you can use margin-left: auto but now child element will also push other div to the right as you can see here Fiddle.

What you can do now is change order of elements and set order: 2 on child element so it doesn't affect second div

_x000D_
_x000D_
.parent {_x000D_
  display: flex;_x000D_
}_x000D_
.child {_x000D_
  margin-left: auto;_x000D_
  order: 2;_x000D_
}
_x000D_
<div class="parent">_x000D_
  <div class="child">Ignore parent?</div>_x000D_
  <div>another child</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Get program path in VB.NET?

You can also use:

Dim strPath As String = AppDomain.CurrentDomain.BaseDirectory

Make page to tell browser not to cache/preserve input values

Another approach would be to reset the form using JavaScript right after the form in the HTML:

<form id="myForm">
  <input type="text" value="" name="myTextInput" />
</form>

<script type="text/javascript">
  document.getElementById("myForm").reset();
</script>

Scrolling to an Anchor using Transition/CSS3

I guess it might be possible to set some kind of hardcore transition to the top style of a #container div to move your entire page in the desired direction when clicking your anchor. Something like adding a class that has top:-2000px.

I did use JQuery because I'm to lazy too use native JS, but it is not necessary for what I did.

This is probably not the best possible solution because the top content just moves towards the top and you can't get it back easily, you should definitely use JQuery if you really need that scroll animation.

DEMO

Difference between BYTE and CHAR in column datatypes

One has exactly space for 11 bytes, the other for exactly 11 characters. Some charsets such as Unicode variants may use more than one byte per char, therefore the 11 byte field might have space for less than 11 chars depending on the encoding.

See also http://www.joelonsoftware.com/articles/Unicode.html

JPA: JOIN in JPQL

Join on one-to-many relation in JPQL looks as follows:

select b.fname, b.lname from Users b JOIN b.groups c where c.groupName = :groupName 

When several properties are specified in select clause, result is returned as Object[]:

Object[] temp = (Object[]) em.createNamedQuery("...")
    .setParameter("groupName", groupName)
    .getSingleResult(); 
String fname = (String) temp[0];
String lname = (String) temp[1];

By the way, why your entities are named in plural form, it's confusing. If you want to have table names in plural, you may use @Table to specify the table name for the entity explicitly, so it doesn't interfere with reserved words:

@Entity @Table(name = "Users")     
public class User implements Serializable { ... } 

Output ("echo") a variable to a text file

The simplest Hello World example...

$hello = "Hello World"
$hello | Out-File c:\debug.txt

How can I enable "URL Rewrite" Module in IIS 8.5 in Server 2012?

Thought I'd give a full answer combining some of the possible intricacies required for completeness.

  1. Check if you have 32-bit or 64-bit IIS installed:
    • Go to IIS Manager ? Application Pools, choose the appropriate app pool then Advanced Settings.
    • Check the setting "Enable 32-bit Applications". If that's true, that means the worker process is forced to run in 32-bit. If the setting is false, then the app pool is running in 64-bit mode.
    • You can also open up Task Manager and check w3wp.exe. If it's showing as w3wp*32.exe then it's 32-bit.
  2. Download the appropriate version here: https://www.iis.net/downloads/microsoft/url-rewrite#additionalDownloads.
  3. Install it.
  4. Close and reopen IIS Manager to ensure the URL Rewrite module appears.

ActiveMQ connection refused

I had also similar problem. In my case brokerUrl was not configured properly. So that's way I received following Error:

Cause: Error While attempting to add new Connection to the pool: nested exception is javax.jms.JMSException: Could not connect to broker URL : tcp://localhost:61616. Reason: java.net.ConnectException: Connection refused

& I resolved it following way.

   ActiveMQConnectionFactory connectionFactory = new ActiveMQConnectionFactory();

  connectionFactory.setBrokerURL("tcp://hostname:61616");
  connectionFactory.setUserName("admin");
  connectionFactory.setPassword("admin");

libc++abi.dylib: terminating with uncaught exception of type NSException (lldb)

CMYR - "his could also happen if you've wired up a button to an IBAction that doesn't exist anymore (or has been renamed)"

If you're running into this problem make sure that you go to Main.storyboard, RIGHT click on the yellow box icon (view controller) at the top of the phone outline and DELETE the outlet(s) with yellow flags.

What happens in instances like this is you probably named an action, then renamed it. You need to delete the old name and if that was the only issue will start right up in sim!

enter image description here

any tool for java object to object mapping?

There is one more Java mapping engine/framework Nomin: http://nomin.sourceforge.net.

How to change a table name using an SQL query?

Use sp_rename:

EXEC sp_rename 'Stu_Table', 'Stu_Table_10'

You can find documentation on this procedure on MSDN.

If you need to include a schema name, this can only be included in the first parameter (that is, this cannot be used to move a table from one schema to another). So, for example, this is valid:

EXEC sp_rename 'myschema.Stu_Table', 'Stu_Table_10'

Timestamp to human readable format

here is kooilnc's answer w/ padded 0's

function getFormattedDate() {
    var date = new Date();

    var month = date.getMonth() + 1;
    var day = date.getDate();
    var hour = date.getHours();
    var min = date.getMinutes();
    var sec = date.getSeconds();

    month = (month < 10 ? "0" : "") + month;
    day = (day < 10 ? "0" : "") + day;
    hour = (hour < 10 ? "0" : "") + hour;
    min = (min < 10 ? "0" : "") + min;
    sec = (sec < 10 ? "0" : "") + sec;

    var str = date.getFullYear() + "-" + month + "-" + day + "_" +  hour + ":" + min + ":" + sec;

    /*alert(str);*/

    return str;
}

Python check if website exists

code:

a="http://www.example.com"
try:    
    print urllib.urlopen(a)
except:
    print a+"  site does not exist"

Disable back button in android

You can override the onBackPressed() method in your activity and remove the call to super class.

@Override
public void onBackPressed() {
  //remove call to the super class
  //super.onBackPressed();
}

How to check all versions of python installed on osx and centos

It depends on your default version of python setup. You can query by Python Version:

python3 --version //to check which version of python3 is installed on your computer
python2 --version // to check which version of python2 is installed on your computer
python --version // it shows your default Python installed version.

Pushing from local repository to GitHub hosted remote

open the command prompt Go to project directory

type git remote add origin your git hub repository location with.git

Does .NET provide an easy way convert bytes to KB, MB, GB, etc.?

public static class MyExtension
{
    public static string ToPrettySize(this float Size)
    {
        return ConvertToPrettySize(Size, 0);
    }
    public static string ToPrettySize(this int Size)
    {
        return ConvertToPrettySize(Size, 0);
    }
    private static string ConvertToPrettySize(float Size, int R)
    {
        float F = Size / 1024f;
        if (F < 1)
        {
            switch (R)
            {
                case 0:
                    return string.Format("{0:0.00} byte", Size);
                case 1:
                    return string.Format("{0:0.00} kb", Size);
                case 2:
                    return string.Format("{0:0.00} mb", Size);
                case 3:
                    return string.Format("{0:0.00} gb", Size);
            }
        }
        return ConvertToPrettySize(F, ++R);
    }
}

How to add color to Github's README.md file

You can use the diff language tag to generate some colored text:

```diff
- text in red
+ text in green
! text in orange
# text in gray
@@ text in purple (and bold)@@
```

However, it adds it as a new line starting with either - + ! # or starts and ends with @@

enter image description here

This issue was raised in github markup #369, but they haven't made any change in decision since then (2014).

Visualizing branch topology in Git

I've tried --simplify-by-decoration but all my merges are not shown. So I instead just prune off lines with no "\" and "/" symbols at the headers, while always keeping lines with "(" indicating branches immediately after that. When showing branch history I'm in general uninterested in commit comments, so I remove them too. I end up with the following shell alias.

gbh () { 
    git log --graph --oneline --decorate "$@" | grep '^[^0-9a-f]*[\\/][^0-9a-f]*\( [0-9a-f]\|$\)\|^[^0-9a-f]*[0-9a-f]*\ (' | sed -e 's/).*/)/'
}

Reading CSV file and storing values into an array

I have been using csvreader.com(paid component) for years, and I have never had a problem. It is solid, small and fast, but you do have to pay for it. You can set the delimiter to whatever you like.

using (CsvReader reader = new CsvReader(s) {
    reader.Settings.Delimiter = ';';
    reader.ReadHeaders();  // if headers on a line by themselves.  Makes reader.Headers[] available
    while (reader.ReadRecord())
        ... use reader.Values[col_i] ...
}

How can I find the number of years between two dates?

This will work and if you want the number of years replace 12 to 1

    String date1 = "07-01-2015";
    String date2 = "07-11-2015";
    int i = Integer.parseInt(date1.substring(6));
    int j = Integer.parseInt(date2.substring(6));
    int p = Integer.parseInt(date1.substring(3,5));
    int q = Integer.parseInt(date2.substring(3,5));


    int z;
    if(q>=p){
        z=q-p + (j-i)*12;
    }else{
        z=p-q + (j-i)*12;
    }
    System.out.println("The Total Months difference between two dates is --> "+z+" Months");

Force youtube embed to start in 720p

Youtube doesn't support playback quality anymore

Youtube doesn't support playback quality anymore