Programs & Examples On #Overload resolution

Overload resolution is a language mechanism to select among several viable function overloads. Its rules are intricate and often surprising, even for experienced users.

Different class for the last element in ng-repeat

It's easier and cleaner to do it with CSS.

HTML:

<div ng-repeat="file in files" class="file">
  {{ file.name }}
</div>

CSS:

.file:last-of-type {
    color: #800;
}

The :last-of-type selector is currently supported by 98% of browsers

How to get the difference (only additions) between two files in linux

A similar approach to https://stackoverflow.com/a/15385080/337172 but hopefully more understandable and easy to tweak:

diff \
  --new-line-format="%L" \
  --old-line-format="" \
  --unchanged-line-format="" \
  A1 A2

Bootstrap - floating navbar button right

Create a separate ul.nav for just that list item and float that ul right.

jsFiddle

Is Eclipse the best IDE for Java?

[This is not really an answer, just an anecdote. I worked with guys who used emacs heavily loaded with macros and color coded. Crazy! Why do that when there are so many good IDEs out there?]

if you know you way around emacs you can code 100x faster then an IDE. And it can handle bunch of diffrent languages so you do not need to change your coding enviroment if you need to code in another language. Works on all operating systems, you can custimize/add anything you want. Even edit files half way across the world over ssh.(no downloading or uploading). Before calling them crazy you gotto use it first. i am sure they are calling you crazy for using an IDE :).

How can I split this comma-delimited string in Python?

Question is a little vague.

list_of_lines = multiple_lines.split("\n")
for line in list_of_lines:
    list_of_items_in_line = line.split(",")
    first_int = int(list_of_items_in_line[0])

etc.

How Big can a Python List Get?

I'd say you're only limited by the total amount of RAM available. Obviously the larger the array the longer operations on it will take.

SSH Private Key Permissions using Git GUI or ssh-keygen are too open

My system is a bit of a mess with bash/cygwin/git/msysgit/maybe-more...

chmod had no effect on the key, or the config file.

Then I decided to approach it from Windows, which worked.

  1. Right-Click the file whose permission needs fixing.
  2. Select Properties.
  3. Select the Security tab.
  4. Click Advanced near the bottom.
  5. Click Change, next to Owner near the top.
  6. Type "My-Awesome-Username" (obviously change that to your current Windows username), and click Check Names, then OK.
  7. Under Permission entries:, highlight each user that isn't "My-Awesome-Username", and select Remove. Repeat this until "My-Awesome-Username" is the only one left.
  8. Select "My-Awesome-Username", and click Edit below.
  9. Make sure the Type: at the top is set to Allow, and then tick the checkbox next to Full control.
  10. Hit OK, Apply, OK, OK.

  11. Give it another try now...

Seems the sometimes the mock-bash can't control the file ownership. It's especially weird, as it's generated from a mock-bash script. Go figure.

rails bundle clean

I assume you install gems into vendor/bundle? If so, why not just delete all the gems and do a clean bundle install?

node.js execute system command synchronously

you can do synchronous shell operations in nodejs like so:

var execSync = function(cmd) {

    var exec  = require('child_process').exec;
    var fs = require('fs');

    //for linux use ; instead of &&
    //execute your command followed by a simple echo 
    //to file to indicate process is finished
    exec(cmd + " > c:\\stdout.txt && echo done > c:\\sync.txt");

    while (true) {
        //consider a timeout option to prevent infinite loop
        //NOTE: this will max out your cpu too!
        try {
            var status = fs.readFileSync('c:\\sync.txt', 'utf8');

            if (status.trim() == "done") {
                var res = fs.readFileSync("c:\\stdout.txt", 'utf8');
                fs.unlinkSync("c:\\stdout.txt"); //cleanup temp files
                fs.unlinkSync("c:\\sync.txt");
                return res;
            }
        } catch(e) { } //readFileSync will fail until file exists
    }

};

//won't return anything, but will take 10 seconds to run
console.log(execSync("sleep 10")); 

//assuming there are a lot of files and subdirectories, 
//this too may take a while, use your own applicable file path
console.log(execSync("dir /s c:\\usr\\docs\\"));

EDIT - this example is meant for windows environments, adjust for your own linux needs if necessary

Validate Dynamically Added Input fields

jquery validation plugin version work fine v1.15.0 but v1.17.0 not work for me.

$(document).find('#add_patient_form').validate({
          ignore: [],
          rules:{
            'email[]':
            {
              required:true,
            },               
          },
          messages:{
            'email[]':
            {
              'required':'Required'
            },            
          },    
        });

make html text input field grow as I type?

I just wrote this for you, I hope you like it :) No guarantees that it's cross-browser, but I think it is :)

(function(){
    var min = 100, max = 300, pad_right = 5, input = document.getElementById('adjinput');

    input.style.width = min+'px';
    input.onkeypress = input.onkeydown = input.onkeyup = function(){
        var input = this;
        setTimeout(function(){
            var tmp = document.createElement('div');
            tmp.style.padding = '0';
            if(getComputedStyle)
                tmp.style.cssText = getComputedStyle(input, null).cssText;
            if(input.currentStyle)
                tmp.style.cssText = input.currentStyle.cssText;
            tmp.style.width = '';
            tmp.style.position = 'absolute';
            tmp.innerHTML = input.value.replace(/&/g, "&amp;")
                                       .replace(/</g, "&lt;")
                                       .replace(/>/g, "&gt;")
                                       .replace(/"/g, "&quot;")
                                       .replace(/'/g, "&#039;")
                                       .replace(/ /g, '&nbsp;');
            input.parentNode.appendChild(tmp);
            var width = tmp.clientWidth+pad_right+1;
            tmp.parentNode.removeChild(tmp);
            if(min <= width && width <= max)
                input.style.width = width+'px';
        }, 1);
    }
})();

JSFiddle

How to convert Hexadecimal #FFFFFF to System.Drawing.Color

Remove the '#' and do

Color c = Color.FromArgb(int.Parse("#FFFFFF".Replace("#",""),
                         System.Globalization.NumberStyles.AllowHexSpecifier));

Targeting only Firefox with CSS

Using -engine specific rules ensures effective browser targeting.

<style type="text/css">

    //Other browsers
    color : black;


    //Webkit (Chrome, Safari)
    @media screen and (-webkit-min-device-pixel-ratio:0) { 
        color:green;
    }

    //Firefox
    @media screen and (-moz-images-in-menus:0) {
        color:orange;
    }
</style>

//Internet Explorer
<!--[if IE]>
     <style type='text/css'>
        color:blue;
    </style>
<![endif]-->

Android Open External Storage directory(sdcard) for storing file

I want to open external storage directory path for saving file programatically.I tried but not getting sdcard path. How can i do this?is there any solution for this??

To store your app files in SD card, you should use File[] getExternalFilesDirs (String type) method in Context class. Generally, second returned path would be the storage path for microSD card (if any).

On my phone, second path returned was /storage/sdcard1/Android/data/your.application.package.appname/files after passing null as argument to getExternalFilesDirs (String type). But path may vary on different phones, different Android versions.

Both File getExternalStorageDirectory () and File getExternalStoragePublicDirectory (String type) in Environment class may return SD card directory or internal memory directory depending on your phone's model and Android OS version.

Because According to Official Android Guide external storage can be

removable storage media (such as an SD card) or an internal (non-removable) storage.

The Internal and External Storage terminology according to Google/official Android docs is quite different from what we think.

Div vertical scrollbar show

Have you tried overflow-y:auto ? It is not exactly what you want, as the scrollbar will appear only when needed.

Pass multiple arguments into std::thread

Had the same problem. I was passing a non-const reference of custom class and the constructor complained (some tuple template errors). Replaced the reference with pointer and it worked.

Run a command shell in jenkins

As far as I know, Windows will not support shell scripts out of the box. You can install Cygwin or Git for Windows, go to Manage Jenkins > Configure System Shell and point it to the location of sh.exe file found in their installation. For example:

C:\Program Files\Git\bin\sh.exe

There is another option I've discovered. This one is better because it allowed me to use shell in pipeline scripts with simple sh "something".

Add the folder to system PATH. Right click on Computer, click properties > advanced system settings > environmental variables, add C:\Program Files\Git\bin\ to your system Path property.

IMPORTANT note: for some reason I had to add it to the system wide Path, adding to user Path didn't work, even though Jenkins was running on this user.

An important note (thanks bugfixr!):

This works. It should be noted that you will need to restart Jenkins in order for it to pick up the new PATH variable. I just went to my services and restated it from there.

Disclaimer: the names may differ slightly as I'm not using English Windows.

How to position background image in bottom right corner? (CSS)

This should do it:

<style>
body {
    background:url(bg.jpg) fixed no-repeat bottom right;
}
</style>

http://www.w3schools.com/cssref/pr_background-position.asp

How to Reload ReCaptcha using JavaScript?

Or you could just simulate a click on the refresh button

// If recaptcha object exists, refresh it
    if (typeof Recaptcha != "undefined") {
      jQuery('#recaptcha_reload').click();
    }

How to validate domain name in PHP?

This is validation of domain name in javascript:

<script>
function frmValidate() {
 var val=document.frmDomin.name.value;
 if (/^[a-zA-Z0-9][a-zA-Z0-9-]{1,61}[a-zA-Z0-9](?:\.[a-zA-Z]{2,})+$/.test(val)){
      alert("Valid Domain Name");
      return true;
 } else {
      alert("Enter Valid Domain Name");
      val.name.focus();
      return false;
 }
}
</script>

C++ pointer to objects

No you can not do that, MyClass *myclass will define a pointer (memory for the pointer is allocated on stack) which is pointing at a random memory location. Trying to use this pointer will cause undefined behavior.

In C++, you can create objects either on stack or heap like this:

MyClass myClass;
myClass.DoSomething();

Above will allocate myClass on stack (the term is not there in the standard I think but I am using for clarity). The memory allocated for the object is automatically released when myClass variable goes out of scope.

Other way of allocating memory is to do a new . In that case, you have to take care of releasing the memory by doing delete yourself.

MyClass* p = new MyClass();
p->DoSomething();
delete p;

Remeber the delete part, else there will be memory leak.

I always prefer to use the stack allocated objects whenever possible as I don't have to be bothered about the memory management.

How to send an email using PHP?

Using PHP's mail() function it's possible. Remember mail function will not work on a Local server.

<?php
$to      = '[email protected]';
$subject = 'the subject';
$message = 'hello';
$headers = 'From: [email protected]' . "\r\n" .
    'Reply-To: [email protected]' . "\r\n" .
    'X-Mailer: PHP/' . phpversion();

mail($to, $subject, $message, $headers);
?> 

Reference:

How to copy only a single worksheet to another workbook using vba

Sub ActiveSheet_toDESKTOP_As_Workbook()

Dim Oldname As String
Dim MyRange As Range
Dim MyWS As String

MyWS = ActiveCell.Parent.Name

    Application.DisplayAlerts = False 'hide confirmation from user
    Application.ScreenUpdating = False
    Oldname = ActiveSheet.Name
    'Sheets.Add(Before:=Sheets(1)).Name = "FirstSheet"
    
    'Get path for desktop of user PC
    Path = Environ("USERPROFILE") & "\Desktop"
    

    ActiveSheet.Cells.Copy
    Sheets.Add(After:=Sheets(Sheets.Count)).Name = "TransferSheet"
    ActiveSheet.Cells.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
    ActiveSheet.Cells.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
    ActiveSheet.Cells.Copy
    
    'Create new workbook and past copied data in new workbook & save to desktop
    Workbooks.Add (xlWBATWorksheet)
    ActiveSheet.Cells.PasteSpecial Paste:=xlPasteValues, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
    ActiveSheet.Cells.PasteSpecial Paste:=xlPasteFormats, Operation:=xlNone, SkipBlanks:=False, Transpose:=False
    ActiveSheet.Cells(1, 1).Select
    ActiveWorkbook.ActiveSheet.Name = Oldname    '"report"
    ActiveWorkbook.SaveAs Filename:=Path & "\" & Oldname & " WS " & Format(CStr(Now()), "dd-mmm (hh.mm.ss AM/PM)") & ".xlsx"
    ActiveWorkbook.Close SaveChanges:=True

    
    Sheets("TransferSheet").Delete
    
    
   Application.DisplayAlerts = True
    Application.ScreenUpdating = True
    Worksheets(MyWS).Activate
    'MsgBox "Exported to Desktop"

End Sub

How can I wait for a thread to finish with .NET?

I would have your main thread pass a callback method to your first thread, and when it's done, it will invoke the callback method on the mainthread, which can launch the second thread. This keeps your main thread from hanging while its waiting for a Join or Waithandle. Passing methods as delegates is a useful thing to learn with C# anyway.

How to enable TLS 1.2 in Java 7

You can upgrade your Java 7 version to 1.7.0_131-b31

For JRE 1.7.0_131-b31 in Oracle site :

TLSv1.2 and TLSv1.1 are now enabled by default on the TLS client end-points. This is similar behavior to what already happens in JDK 8 releases.

Connection attempt failed with "ECONNREFUSED - Connection refused by server"

FTP protocol may be blocked by your ISP firewall, try connecting via SFTP (i.e. use 22 for port num instead of 21 which is simply FTP).

For more information try this link.

Pass by Reference / Value in C++

As I parse it, those words are wrong. It should read "If the function modifies that value, the modifications appear also within the scope of the calling function when passing by reference, but not when passing by value."

Boxplot in R showing the mean

Based on the answers by @James and @Jyotirmoy Bhattacharya I came up with this solution:

zx <- replicate (5, rnorm(50))
zx_means <- (colMeans(zx, na.rm = TRUE))
boxplot(zx, horizontal = FALSE, outline = FALSE)
points(zx_means, pch = 22, col = "darkgrey", lwd = 7)

(See this post for more details)

If you would like to add points to horizontal box plots, please see this post.

How to write log to file

If you run binary on linux machine you could use shell script.

overwrite into a file

./binaryapp > binaryapp.log

append into a file

./binaryapp >> binaryapp.log

overwrite stderr into a file

./binaryapp &> binaryapp.error.log

append stderr into a file

./binaryapp &>> binalyapp.error.log

it can be more dynamic using shell script file.

mysqli or PDO - what are the pros and cons?

One thing PDO has that MySQLi doesn't that I really like is PDO's ability to return a result as an object of a specified class type (e.g. $pdo->fetchObject('MyClass')). MySQLi's fetch_object() will only return an stdClass object.

SASS - use variables across multiple files

How about writing some color-based class in a global sass file, thus we don't need to care where variables are. Just like the following:

// base.scss 
@import "./_variables.scss";

.background-color{
    background: $bg-color;
}

and then, we can use the background-color class in any file. My point is that I don't need to import variable.scss in any file, just use it.

jQuery - disable selected options

Add this line to your change event handler

    $("#theSelect option:selected").attr('disabled','disabled')
        .siblings().removeAttr('disabled');

This will disable the selected option, and enable any previously disabled options.

EDIT:

If you did not want to re-enable the previous ones, just remove this part of the line:

        .siblings().removeAttr('disabled');

EDIT:

http://jsfiddle.net/pd5Nk/1/

To re-enable when you click remove, add this to your click handler.

$("#theSelect option[value=" + value + "]").removeAttr('disabled');

JQuery Calculate Day Difference in 2 date textboxes

This is how I did it using the Math.floor() function:

var start = new Date($('#start').val());
var end = new Date($('#end').val());
var diff = Math.floor((end-start) / (365.25 * 24 * 60 * 60 * 1000));
console.log(diff);

You could also do it this way using the Math.round() function:

var start = new Date($('#start').val());
var end = new Date($('#end').val());
var diff = new Date(end - start) / (1000 * 60 * 60 * 24 * 365.25);
var age = Math.round(diff);
console.log(age);

Practical uses of different data structures

Any ranking of various data structures will be at least partially tied to problem context. It would help to learn how to analyze time and space performance of algorithms. Typically, "big O notation" is used, e.g. binary search is in O(log n) time, which means that the time to search for an element is the log (in base 2, implicitly) of the number of elements. Intuitively, since every step discards half of the remaining data as irrelevant, doubling the number of elements will increases the time by 1 step. (Binary search scales rather well.) Space performance concerns how the amount of memory grows for larger data sets. Also, note that big-O notation ignores constant factors - for smaller data sets, an O(n^2) algorithm may still be faster than an O(n * log n) algorithm that has a higher constant factor. Complex algorithms often have more work to do on startup.

Besides time and space, other characteristics include whether a data structure is sorted (trees and skiplists are sorted, hash tables are not), persistence (binary trees can reuse pointers from older versions, while hash tables are modified in place), etc.

While you'll need to learn the behavior of several data structures to be able to compare them, one way to develop a sense for why they differ in performance is to closely study a few. I'd suggest comparing singly-linked lists, binary search trees, and skip lists, all of which are relatively simple, but have very different characteristics. Think about how much work it takes to find a value, add a new value, find all values in order, etc.

There are various texts on analyzing algorithms / data structure performance that people recommend, but what really made them make sense to me was learning OCaml. Dealing with complex data structures is ML's strong suit, and their behavior is much clearer when you can avoid pointers and memory management as in C. (Learning OCaml just to understand data structures is almost certainly the long way around, though. :) )

How do I check if a number is a palindrome?

Just for fun, this one also works.

a = num;
b = 0;
if (a % 10 == 0)
  return a == 0;
do {
  b = 10 * b + a % 10;
  if (a == b)
    return true;
  a = a / 10;
} while (a > b);
return a == b;

Parsing CSV files in C#, with header

A CSV parser is now a part of .NET Framework.

Add a reference to Microsoft.VisualBasic.dll (works fine in C#, don't mind the name)

using (TextFieldParser parser = new TextFieldParser(@"c:\temp\test.csv"))
{
    parser.TextFieldType = FieldType.Delimited;
    parser.SetDelimiters(",");
    while (!parser.EndOfData)
    {
        //Process row
        string[] fields = parser.ReadFields();
        foreach (string field in fields)
        {
            //TODO: Process field
        }
    }
}

The docs are here - TextFieldParser Class

P.S. If you need a CSV exporter, try CsvExport (discl: I'm one of the contributors)

Explain why constructor inject is better than other options

By using Constructor Injection, you assert the requirement for the dependency in a container-agnostic manner

We need the assurance from the IoC container that, before using any bean, the injection of necessary beans must be done.

In setter injection strategy, we trust the IoC container that it will first create the bean first but will do the injection right before using the bean using the setter methods. And the injection is done according to your configuration. If you somehow misses to specify any beans to inject in the configuration, the injection will not be done for those beans and your dependent bean will not function accordingly when it will be in use!

But in constructor injection strategy, container imposes (or must impose) to provide the dependencies properly while constructing the bean. This was addressed as " container-agnostic manner", as we are required to provide dependencies while creating the bean, thus making the visibility of dependency, independent of any IoC container.

Edit:

Q1: And how to prevent container from creating bean by constructor with null values instead of missing beans?

You have no option to really miss any <constructor-arg> (in case of Spring), because you are imposed by IoC container to provide all the constructor arguments needed to match a provided constructor for creating the bean. If you provide null in your <constructor-arg> intentionally. Then there is nothing IoC container can do or need to do with it!

css transition opacity fade background

Please note that the problem is not white color. It is because it is being transparent.

When an element is made transparent, all of its child element's opacity; alpha filter in IE 6 7 etc, is changed to the new value.

So you cannot say that it is white!

You can place an element above it, and change that element's transparency to 1 while changing the image's transparency to .2 or what so ever you want to.

Difference between Fact table and Dimension table?

Dimension table Dimension table is a table which contain attributes of measurements stored in fact tables. This table consists of hierarchies, categories and logic that can be used to traverse in nodes.

Fact table contains the measurement of business processes, and it contains foreign keys for the dimension tables.

Example – If the business process is manufacturing of bricks

Average number of bricks produced by one person/machine – measure of the business process

Can my enums have friendly names?

Some great solutions have already been posted. When I encountered this problem, I wanted to go both ways: convert an enum into a description, and convert a string matching a description into an enum.

I have two variants, slow and fast. Both convert from enum to string and string to enum. My problem is that I have enums like this, where some elements need attributes and some don't. I don't want to put attributes on elements that don't need them. I have about a hundred of these total currently:

public enum POS
{   
    CC, //  Coordinating conjunction
    CD, //  Cardinal Number
    DT, //  Determiner
    EX, //  Existential there
    FW, //  Foreign Word
    IN, //  Preposision or subordinating conjunction
    JJ, //  Adjective
    [System.ComponentModel.Description("WP$")]
    WPDollar, //$   Possessive wh-pronoun
    WRB, //     Wh-adverb
    [System.ComponentModel.Description("#")]
    Hash,
    [System.ComponentModel.Description("$")]
    Dollar,
    [System.ComponentModel.Description("''")]
    DoubleTick,
    [System.ComponentModel.Description("(")]
    LeftParenth,
    [System.ComponentModel.Description(")")]
    RightParenth,
    [System.ComponentModel.Description(",")]
    Comma,
    [System.ComponentModel.Description(".")]
    Period,
    [System.ComponentModel.Description(":")]
    Colon,
    [System.ComponentModel.Description("``")]
    DoubleBackTick,
    };

The first method for dealing with this is slow, and is based on suggestions I saw here and around the net. It's slow because we are reflecting for every conversion:

using System;
using System.Collections.Generic;
namespace CustomExtensions
{

/// <summary>
/// uses extension methods to convert enums with hypens in their names to underscore and other variants
public static class EnumExtensions
{
    /// <summary>
    /// Gets the description string, if available. Otherwise returns the name of the enum field
    /// LthWrapper.POS.Dollar.GetString() yields "$", an impossible control character for enums
    /// </summary>
    /// <param name="value"></param>
    /// <returns></returns>
    public static string GetStringSlow(this Enum value)
    {
        Type type = value.GetType();
        string name = Enum.GetName(type, value);
        if (name != null)
        {
            System.Reflection.FieldInfo field = type.GetField(name);
            if (field != null)
            {
                System.ComponentModel.DescriptionAttribute attr =
                       Attribute.GetCustomAttribute(field,
                         typeof(System.ComponentModel.DescriptionAttribute)) as System.ComponentModel.DescriptionAttribute;
                if (attr != null)
                {
                    //return the description if we have it
                    name = attr.Description; 
                }
            }
        }
        return name;
    }

    /// <summary>
    /// Converts a string to an enum field using the string first; if that fails, tries to find a description
    /// attribute that matches. 
    /// "$".ToEnum<LthWrapper.POS>() yields POS.Dollar
    /// </summary>
    /// <typeparam name="T"></typeparam>
    /// <param name="value"></param>
    /// <returns></returns>
    public static T ToEnumSlow<T>(this string value) //, T defaultValue)
    {
        T theEnum = default(T);

        Type enumType = typeof(T);

        //check and see if the value is a non attribute value
        try
        {
            theEnum = (T)Enum.Parse(enumType, value);
        }
        catch (System.ArgumentException e)
        {
            bool found = false;
            foreach (T enumValue in Enum.GetValues(enumType))
            {
                System.Reflection.FieldInfo field = enumType.GetField(enumValue.ToString());

                System.ComponentModel.DescriptionAttribute attr =
                           Attribute.GetCustomAttribute(field,
                             typeof(System.ComponentModel.DescriptionAttribute)) as System.ComponentModel.DescriptionAttribute;

                if (attr != null && attr.Description.Equals(value))
                {
                    theEnum = enumValue;
                    found = true;
                    break;

                }
            }
            if( !found )
                throw new ArgumentException("Cannot convert " + value + " to " + enumType.ToString());
        }

        return theEnum;
    }
}
}

The problem with this is that you're doing reflection every time. I haven't measured the performance hit from doing so, but it seems alarming. Worse we are computing these expensive conversions repeatedly, without caching them.

Instead we can use a static constructor to populate some dictionaries with this conversion information, then just look up this information when needed. Apparently static classes (required for extension methods) can have constructors and fields :)

using System;
using System.Collections.Generic;
namespace CustomExtensions
{

/// <summary>
/// uses extension methods to convert enums with hypens in their names to underscore and other variants
/// I'm not sure this is a good idea. While it makes that section of the code much much nicer to maintain, it 
/// also incurs a performance hit via reflection. To circumvent this, I've added a dictionary so all the lookup can be done once at 
/// load time. It requires that all enums involved in this extension are in this assembly.
/// </summary>
public static class EnumExtensions
{
    //To avoid collisions, every Enum type has its own hash table
    private static readonly Dictionary<Type, Dictionary<object,string>> enumToStringDictionary = new Dictionary<Type,Dictionary<object,string>>();
    private static readonly Dictionary<Type, Dictionary<string, object>> stringToEnumDictionary = new Dictionary<Type, Dictionary<string, object>>();

    static EnumExtensions()
    {
        //let's collect the enums we care about
        List<Type> enumTypeList = new List<Type>();

        //probe this assembly for all enums
        System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
        Type[] exportedTypes = assembly.GetExportedTypes();

        foreach (Type type in exportedTypes)
        {
            if (type.IsEnum)
                enumTypeList.Add(type);
        }

        //for each enum in our list, populate the appropriate dictionaries
        foreach (Type type in enumTypeList)
        {
            //add dictionaries for this type
            EnumExtensions.enumToStringDictionary.Add(type, new Dictionary<object,string>() );
            EnumExtensions.stringToEnumDictionary.Add(type, new Dictionary<string,object>() );

            Array values = Enum.GetValues(type);

            //its ok to manipulate 'value' as object, since when we convert we're given the type to cast to
            foreach (object value in values)
            {
                System.Reflection.FieldInfo fieldInfo = type.GetField(value.ToString());

                //check for an attribute 
                System.ComponentModel.DescriptionAttribute attribute =
                       Attribute.GetCustomAttribute(fieldInfo,
                         typeof(System.ComponentModel.DescriptionAttribute)) as System.ComponentModel.DescriptionAttribute;

                //populate our dictionaries
                if (attribute != null)
                {
                    EnumExtensions.enumToStringDictionary[type].Add(value, attribute.Description);
                    EnumExtensions.stringToEnumDictionary[type].Add(attribute.Description, value);
                }
                else
                {
                    EnumExtensions.enumToStringDictionary[type].Add(value, value.ToString());
                    EnumExtensions.stringToEnumDictionary[type].Add(value.ToString(), value);
                }
            }
        }
    }

    public static string GetString(this Enum value)
    {
        Type type = value.GetType();
        string aString = EnumExtensions.enumToStringDictionary[type][value];
        return aString; 
    }

    public static T ToEnum<T>(this string value)
    {
        Type type = typeof(T);
        T theEnum = (T)EnumExtensions.stringToEnumDictionary[type][value];
        return theEnum;
    }
 }
}

Look how tight the conversion methods are now. The only flaw I can think of is that this requires all the converted enums to be in the current assembly. Also, I only bother with exported enums, but you could change that if you wish.

This is how to call the methods

 string x = LthWrapper.POS.Dollar.GetString();
 LthWrapper.POS y = "PRP$".ToEnum<LthWrapper.POS>();

How to convert HTML file to word?

just past this on head of your php page. before any code on this should be the top code.

<?php
header("Content-Type: application/vnd.ms-word"); 
header("Expires: 0"); 
header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
header("content-disposition: attachment;filename=Hawala.doc");

?>

this will convert all html to MSWORD, now you can customize it according to your client requirement.

Types in Objective-C on iOS

Note that you can also use the C99 fixed-width types perfectly well in Objective-C:

#import <stdint.h>
...
int32_t x; // guaranteed to be 32 bits on any platform

The wikipedia page has a decent description of what's available in this header if you don't have a copy of the C standard (you should, though, since Objective-C is just a tiny extension of C). You may also find the headers limits.h and inttypes.h to be useful.

How do I create batch file to rename large number of files in a folder?

you can do this easily without manual editing or using fancy text editors. Here's a vbscript.

Set objFS = CreateObject("Scripting.FileSystemObject")
strFolder="c:\test"
Set objFolder = objFS.GetFolder(strFolder)
For Each strFile In objFolder.Files
    If objFS.GetExtensionName(strFile) = "jpg" Then    
        strFileName = strFile.Name
        If InStr(strFileName,"Vacation2010") > 0 Then           
            strNewFileName = Replace(strFileName,"Vacation2010","December")
            strFile.Name = strNewFileName
        End If 
    End If  
Next 

save as myscript.vbs and

C:\test> cscript //nologo myscript.vbs 

How to enter quotes in a Java string?

In reference to your comment after Ian Henry's answer, I'm not quite 100% sure I understand what you are asking.

If it is about getting double quote marks added into a string, you can concatenate the double quotes into your string, for example:

String theFirst = "Java Programming";
String ROM = "\"" + theFirst + "\"";

Or, if you want to do it with one String variable, it would be:

String ROM = "Java Programming";
ROM = "\"" + ROM + "\"";

Of course, this actually replaces the original ROM, since Java Strings are immutable.

If you are wanting to do something like turn the variable name into a String, you can't do that in Java, AFAIK.

How/when to generate Gradle wrapper files?

As of Gradle 2.4, you can use gradle wrapper --gradle-version X.X to configure a specific version of the Gradle wrapper, without adding any tasks to your build.gradle file. The next time you use the wrapper, it will download the appropriate Gradle distribution to match.

How do I convert a javascript object array to a string array of the object attribute I want?

You can use this function:

function createStringArray(arr, prop) {
   var result = [];
   for (var i = 0; i < arr.length; i += 1) {
      result.push(arr[i][prop]);
   }
   return result;
}

Just pass the array of objects and the property you need. The script above will work even in old EcmaScript implementations.

Convert char * to LPWSTR

I'm using the following in VC++ and it works like a charm for me.

CA2CT(charText)

How to read text file in JavaScript

my example

<html>

<head>
  <link rel="stylesheet" href="http://code.jquery.com/ui/1.11.3/themes/smoothness/jquery-ui.css">
  <script src="http://code.jquery.com/jquery-1.10.2.js"></script>
  <script src="http://code.jquery.com/ui/1.11.3/jquery-ui.js"></script>
</head>

<body>
  <script>
    function PreviewText() {
      var oFReader = new FileReader();
      oFReader.readAsDataURL(document.getElementById("uploadText").files[0]);
      oFReader.onload = function(oFREvent) {
        document.getElementById("uploadTextValue").value = oFREvent.target.result;
        document.getElementById("obj").data = oFREvent.target.result;
      };
    };
    jQuery(document).ready(function() {
      $('#viewSource').click(function() {
        var text = $('#uploadTextValue').val();
        alert(text);
        //here ajax
      });
    });
  </script>
  <object width="100%" height="400" data="" id="obj"></object>
  <div>
    <input type="hidden" id="uploadTextValue" name="uploadTextValue" value="" />
    <input id="uploadText" style="width:120px" type="file" size="10" onchange="PreviewText();" />
  </div>
  <a href="#" id="viewSource">Source file</a>
</body>

</html>

How do I update Node.js?

open cmd and type

npm i -g npm

Move top 1000 lines from text file to a new file using Unix shell commands

Out of curiosity, I found a box with a GNU version of sed (v4.1.5) and tested the (uncached) performance of two approaches suggested so far, using an 11M line text file:

$ wc -l input
11771722 input

$ time head -1000 input > output; time tail -n +1000 input > input.tmp; time cp input.tmp input; time rm input.tmp

real    0m1.165s
user    0m0.030s
sys     0m1.130s

real    0m1.256s
user    0m0.062s
sys     0m1.162s

real    0m4.433s
user    0m0.033s
sys     0m1.282s

real    0m6.897s
user    0m0.000s
sys     0m0.159s

$ time head -1000 input > output && time sed -i '1,+999d' input

real    0m0.121s
user    0m0.000s
sys     0m0.121s

real    0m26.944s
user    0m0.227s
sys     0m26.624s

This is the Linux I was working with:

$ uname -a
Linux hostname 2.6.18-128.1.1.el5 #1 SMP Mon Jan 26 13:58:24 EST 2009 x86_64 x86_64 x86_64 GNU/Linux

For this test, at least, it looks like sed is slower than the tail approach (27 sec vs ~14 sec).

Query for documents where array size is greater than 1

Update:

For mongodb versions 2.2+ more efficient way to do this described by @JohnnyHK in another answer.


1.Using $where

db.accommodations.find( { $where: "this.name.length > 1" } );

But...

Javascript executes more slowly than the native operators listed on this page, but is very flexible. See the server-side processing page for more information.

2.Create extra field NamesArrayLength, update it with names array length and then use in queries:

db.accommodations.find({"NamesArrayLength": {$gt: 1} });

It will be better solution, and will work much faster (you can create index on it).

Oracle date to string conversion

Another thing to notice is you are trying to convert a date in mm/dd/yyyy but if you have any plans of comparing this converted date to some other date then make sure to convert it in yyyy-mm-dd format only since to_char literally converts it into a string and with any other format we will get undesired result. For any more explanation follow this: Comparing Dates in Oracle SQL

What is a good practice to check if an environmental variable exists or not?

I'd recommend the following solution.

It prints the env vars you didn't include, which lets you add them all at once. If you go for the for loop, you're going to have to rerun the program to see each missing var.

from os import environ

REQUIRED_ENV_VARS = {"A", "B", "C", "D"}
diff = REQUIRED_ENV_VARS.difference(environ)
if len(diff) > 0:
    raise EnvironmentError(f'Failed because {diff} are not set')

UIAlertController custom font, size, color

Swift 5 and 5.1. Create a separate file and put UIAlertController Customization code there

import Foundation
import  UIKit

extension UIAlertController {

  //Set background color of UIAlertController
  func setBackgroudColor(color: UIColor) {
    if let bgView = self.view.subviews.first,
      let groupView = bgView.subviews.first,
      let contentView = groupView.subviews.first {
      contentView.backgroundColor = color
    }
  }

  //Set title font and title color
  func setTitle(font: UIFont?, color: UIColor?) {
    guard let title = self.title else { return }
    let attributeString = NSMutableAttributedString(string: title)//1
    if let titleFont = font {
      attributeString.addAttributes([NSAttributedString.Key.font : titleFont],//2
        range: NSMakeRange(0, title.utf8.count))
    }
    if let titleColor = color {
      attributeString.addAttributes([NSAttributedString.Key.foregroundColor : titleColor],//3
        range: NSMakeRange(0, title.utf8.count))
    }
    self.setValue(attributeString, forKey: "attributedTitle")//4
  }

  //Set message font and message color
  func setMessage(font: UIFont?, color: UIColor?) {
    guard let title = self.message else {
      return
    }
    let attributedString = NSMutableAttributedString(string: title)
    if let titleFont = font {
      attributedString.addAttributes([NSAttributedString.Key.font : titleFont], range: NSMakeRange(0, title.utf8.count))
    }
    if let titleColor = color {
      attributedString.addAttributes([NSAttributedString.Key.foregroundColor : titleColor], range: NSMakeRange(0, title.utf8.count))
    }
    self.setValue(attributedString, forKey: "attributedMessage")//4
  }

  //Set tint color of UIAlertController
  func setTint(color: UIColor) {
    self.view.tintColor = color
  }
}

Now On any action Show Alert

  func tapShowAlert(sender: UIButton) {
    let alertController = UIAlertController(title: "Alert!!", message: "This is custom alert message", preferredStyle: .alert)
    // Change font and color of title
    alertController.setTitle(font: UIFont.boldSystemFont(ofSize: 26), color: UIColor.yellow)
    // Change font and color of message
    alertController.setMessage(font: UIFont(name: "AvenirNextCondensed-HeavyItalic", size: 18), color: UIColor.red)
    // Change background color of UIAlertController
    alertController.setBackgroudColor(color: UIColor.black)
    let actnOk = UIAlertAction(title: "Ok", style: .default, handler: nil)
    let actnCancel = UIAlertAction(title: "Cancel", style: .default, handler: nil)
    alertController.addAction(actnOk)
    alertController.addAction(actnCancel)
    self.present(alertController, animated: true, completion: nil)
  }

Result

enter image description here

Angular ReactiveForms: Producing an array of checkbox values?

With the help of silentsod answer, I wrote a solution to get values instead of states in my formBuilder.

I use a method to add or remove values in the formArray. It may be a bad approch, but it works !

component.html

<div *ngFor="let choice of checks; let i=index" class="col-md-2">
  <label>
    <input type="checkbox" [value]="choice.value" (change)="onCheckChange($event)">
    {{choice.description}}
  </label>
</div>

component.ts

// For example, an array of choices
public checks: Array<ChoiceClass> = [
  {description: 'descr1', value: 'value1'},
  {description: "descr2", value: 'value2'},
  {description: "descr3", value: 'value3'}
];

initModelForm(): FormGroup{
  return this._fb.group({
    otherControls: [''],
    // The formArray, empty 
    myChoices: new FormArray([]),
  }
}

onCheckChange(event) {
  const formArray: FormArray = this.myForm.get('myChoices') as FormArray;

  /* Selected */
  if(event.target.checked){
    // Add a new control in the arrayForm
    formArray.push(new FormControl(event.target.value));
  }
  /* unselected */
  else{
    // find the unselected element
    let i: number = 0;

    formArray.controls.forEach((ctrl: FormControl) => {
      if(ctrl.value == event.target.value) {
        // Remove the unselected element from the arrayForm
        formArray.removeAt(i);
        return;
      }

      i++;
    });
  }
}

When I submit my form, for example my model looks like:

  otherControls : "foo",
  myChoices : ['value1', 'value2']

Only one thing is missing, a function to fill the formArray if your model already has checked values.

HttpURLConnection timeout settings

I could get solution for such a similar problem with addition of a simple line

HttpURLConnection hConn = (HttpURLConnection) url.openConnection();
hConn.setRequestMethod("HEAD");

My requirement was to know the response code and for that just getting the meta-information was sufficient, instead of getting the complete response body.

Default request method is GET and that was taking lot of time to return, finally throwing me SocketTimeoutException. The response was pretty fast when I set the Request Method to HEAD.

Python regex findall

you can replace your pattern with

regex = ur"\[P\]([\w\s]+)\[\/P\]"

Running windows shell commands with python

Simple Import os package and run below command.

import os
os.system("python test.py")

Center HTML Input Text Field Placeholder

You can make like this:

    <center>
    <form action="" method="POST">
    <input type="text" class="emailField" placeholder="[email protected]" style="text-align: center" name="email" />
    <input type="submit" value="submit" />  
</form>
    </center>

Working CodePen here

Nesting CSS classes

Not directly. But you can use extensions such as LESS to help you achieve the same.

MySQL Sum() multiple columns

If any of your markn columns are "AllowNull" then you will need to do a little extra to insure the correct result is returned, this is because 1 NULL value will result in a NULL total.

This is what i would consider to be the correct answer.

SUM(IFNULL(`mark1`, 0) + IFNULL(`mark2`, 0) + IFNULL(`mark3`, 0)) AS `total_marks` 

IFNULL will return the 2nd parameter if the 1st is NULL. COALESCE could be used but i prefer to only use it if it is required. See What is the difference bewteen ifnull and coalesce in mysql?

SUM-ing the entire calculation is tidier than SUM-ing each column individually.

SELECT `student`, SUM(IFNULL(`mark1`, 0) + IFNULL(`mark2`, 0) + IFNULL(`mark3`, 0)) AS `total_marks` 
FROM student_scorecard
GROUP BY `student`

Jump to function definition in vim

Another common technique is to place the function name in the first column. This allows the definition to be found with a simple search.

int
main(int argc, char *argv[])
{
    ...
}

The above function could then be found with /^main inside the file or with :grep -r '^main' *.c in a directory. As long as code is properly indented the only time the identifier will occur at the beginning of a line is at the function definition.

Of course, if you aren't using ctags from this point on you should be ashamed of yourself! However, I find this coding standard a helpful addition as well.

Custom edit view in UITableViewCell while swipe left. Objective-C or Swift

You can use UITableViewRowAction's backgroundColor to set custom image or view. The trick is using UIColor(patternImage:).

Basically the width of UITableViewRowAction area is decided by its title, so you can find a exact length of title(or whitespace) and set the exact size of image with patternImage.

To implement this, I made a UIView's extension method.

func image() -> UIImage {
    UIGraphicsBeginImageContextWithOptions(bounds.size, isOpaque, 0)
    guard let context = UIGraphicsGetCurrentContext() else {
        return UIImage()
    }
    layer.render(in: context)
    let image = UIGraphicsGetImageFromCurrentImageContext()
    UIGraphicsEndImageContext()
    return image!
}

and to make a string with whitespace and exact length,

fileprivate func whitespaceString(font: UIFont = UIFont.systemFont(ofSize: 15), width: CGFloat) -> String {
    let kPadding: CGFloat = 20
    let mutable = NSMutableString(string: "")
    let attribute = [NSFontAttributeName: font]
    while mutable.size(attributes: attribute).width < width - (2 * kPadding) {
        mutable.append(" ")
    }
    return mutable as String
}

and now, you can create UITableViewRowAction.

func tableView(_ tableView: UITableView, editActionsForRowAt indexPath: IndexPath) -> [UITableViewRowAction]? {
    let whitespace = whitespaceString(width: kCellActionWidth)
    let deleteAction = UITableViewRowAction(style: .`default`, title: whitespace) { (action, indexPath) in
        // do whatever you want
    }

    // create a color from patter image and set the color as a background color of action
    let kActionImageSize: CGFloat = 34
    let view = UIView(frame: CGRect(x: 0, y: 0, width: kCellActionWidth, height: kCellHeight))
    view.backgroundColor = UIColor.white
    let imageView = UIImageView(frame: CGRect(x: (kCellActionWidth - kActionImageSize) / 2,
                                              y: (kCellHeight - kActionImageSize) / 2,
                                              width: 34,
                                              height: 34))
    imageView.image = UIImage(named: "x")
    view.addSubview(imageView)
    let image = view.image()

    deleteAction.backgroundColor = UIColor(patternImage: image)

    return [deleteAction]
}

The result will look like this.

enter image description here

Another way to do this is to import custom font which has the image you want to use as a font and use UIButton.appearance. However this will affect other buttons unless you manually set other button's font.

From iOS 11, it will show this message [TableView] Setting a pattern color as backgroundColor of UITableViewRowAction is no longer supported.. Currently it is still working, but it wouldn't work in the future update.

==========================================

For iOS 11+, you can use:

func tableView(_ tableView: UITableView, trailingSwipeActionsConfigurationForRowAt indexPath: IndexPath) -> UISwipeActionsConfiguration? {
  let deleteAction = UIContextualAction(style: .normal, title: "Delete") { (action, view, completion) in
    // Perform your action here
      completion(true)
  }

  let muteAction = UIContextualAction(style: .normal, title: "Mute") { (action, view, completion) in
    // Perform your action here
    completion(true)
  }

  deleteAction.image = UIImage(named: "icon.png")
  deleteAction.backgroundColor = UIColor.red
  return UISwipeActionsConfiguration(actions: [deleteAction, muteAction])
} 

Python: slicing a multi-dimensional array

If you use numpy, this is easy:

slice = arr[:2,:2]

or if you want the 0's,

slice = arr[0:2,0:2]

You'll get the same result.

*note that slice is actually the name of a builtin-type. Generally, I would advise giving your object a different "name".


Another way, if you're working with lists of lists*:

slice = [arr[i][0:2] for i in range(0,2)]

(Note that the 0's here are unnecessary: [arr[i][:2] for i in range(2)] would also work.).

What I did here is that I take each desired row 1 at a time (arr[i]). I then slice the columns I want out of that row and add it to the list that I'm building.

If you naively try: arr[0:2] You get the first 2 rows which if you then slice again arr[0:2][0:2], you're just slicing the first two rows over again.

*This actually works for numpy arrays too, but it will be slow compared to the "native" solution I posted above.

What is java pojo class, java bean, normal class?

POJO = Plain Old Java Object. It has properties, getters and setters for respective properties. It may also override Object.toString() and Object.equals().

Java Beans : See Wiki link.

Normal Class : Any java Class.

How do I set Java's min and max heap size through environment variables?

If you want any java process, not just ant or Tomcat, to pick up options like -Xmx use the environment variable _JAVA_OPTIONS.

In bash: export _JAVA_OPTIONS="-Xmx1g"

Why does intellisense and code suggestion stop working when Visual Studio is open?

@TonyL's answer didn't work for me, but I noticed Intellisense stopped working in the foo class after I changed the method signature in the bar class.

Closing and reopening the foo.cs file fixed it.

Regex Until But Not Including

Try this

(.*?quick.*?)z

How to define Typescript Map of key value pair. where key is a number and value is an array of objects

The most simple way is to use Record type Record<number, productDetails >

interface productDetails {
   productId : number , 
   price : number , 
   discount : number
};

const myVar : Record<number, productDetails> = {
   1: {
       productId : number , 
       price : number , 
       discount : number
   }
}

Difference between @Before, @BeforeClass, @BeforeEach and @BeforeAll

Before and BeforeClass in JUnit

The function @Before annotation will be executed before each of test function in the class having @Test annotation but the function with @BeforeClass will be execute only one time before all the test functions in the class.

Similarly function with @After annotation will be executed after each of test function in the class having @Test annotation but the function with @AfterClass will be execute only one time after all the test functions in the class.

SampleClass

public class SampleClass {
    public String initializeData(){
        return "Initialize";
    }

    public String processDate(){
        return "Process";
    }
 }

SampleTest

public class SampleTest {

    private SampleClass sampleClass;

    @BeforeClass
    public static void beforeClassFunction(){
        System.out.println("Before Class");
    }

    @Before
    public void beforeFunction(){
        sampleClass=new SampleClass();
        System.out.println("Before Function");
    }

    @After
    public void afterFunction(){
        System.out.println("After Function");
    }

    @AfterClass
    public static void afterClassFunction(){
        System.out.println("After Class");
    }

    @Test
    public void initializeTest(){
        Assert.assertEquals("Initailization check", "Initialize", sampleClass.initializeData() );
    }

    @Test
    public void processTest(){
        Assert.assertEquals("Process check", "Process", sampleClass.processDate() );
    }

}

Output

Before Class
Before Function
After Function
Before Function
After Function
After Class

In Junit 5

@Before = @BeforeEach
@BeforeClass = @BeforeAll
@After = @AfterEach
@AfterClass = @AfterAll

Is there a way to 'pretty' print MongoDB shell output to a file?

Using print and JSON.stringify you can simply produce a valid JSON result.
Use --quiet flag to filter shell noise from the output.
Use --norc flag to avoid .mongorc.js evaluation. (I had to do it because of a pretty-formatter that I use, which produces invalid JSON output) Use DBQuery.shellBatchSize = ? replacing ? with the limit of the actual result to avoid paging.

And finally, use tee to pipe the terminal output to a file:

// Shell:
mongo --quiet --norc ./query.js | tee ~/my_output.json

// query.js:
DBQuery.shellBatchSize = 2000;
function toPrint(data) {
  print(JSON.stringify(data, null, 2));
}

toPrint(
  db.getCollection('myCollection').find().toArray()
);

Hope this helps!

Jquery each - Stop loop and return object

modified $.each function

$.fn.eachReturn = function(arr, callback) {
   var result = null;
   $.each(arr, function(index, value){
       var test = callback(index, value);
       if (test) {
           result = test;
           return false;
       }
   });
   return result ;
}

it will break loop on non-false/non-empty result and return it back, so in your case it would be

return $.eachReturn(someArray, function(i){
    ...

Which font is used in Visual Studio Code Editor and how to change fonts?

In the default settings, VS Code uses the following fonts (14 pt) in descending order:

  • Monaco
  • Menlo
  • Consolas
  • "Droid Sans Mono"
  • "Inconsolata"
  • "Courier New"
  • monospace (fallback)

How to verify: VS Code runs in a browser. In the first version, you could hit F12 to open the Developer Tools. Inspecting the DOM, you can find a containing several s that make up that line of code. Inspecting one of those spans, you can see that font-family is just the list above.

relevant areas

cell format round and display 2 decimal places

I use format, Number, 2 decimal places & tick ' use 1000 separater ', then go to 'File', 'Options', 'Advanced', scroll down to 'When calculating this workbook' and tick 'set precision as displayed'. You get an error message about losing accuracy, that's good as it means it is rounding to 2 decimal places. So much better than bothering with adding a needless ROUND function.

Static Initialization Blocks

If they weren't in a static initialization block, where would they be? How would you declare a variable which was only meant to be local for the purposes of initialization, and distinguish it from a field? For example, how would you want to write:

public class Foo {
    private static final int widgets;

    static {
        int first = Widgets.getFirstCount();
        int second = Widgets.getSecondCount();
        // Imagine more complex logic here which really used first/second
        widgets = first + second;
    }
}

If first and second weren't in a block, they'd look like fields. If they were in a block without static in front of it, that would count as an instance initialization block instead of a static initialization block, so it would be executed once per constructed instance rather than once in total.

Now in this particular case, you could use a static method instead:

public class Foo {
    private static final int widgets = getWidgets();

    static int getWidgets() {
        int first = Widgets.getFirstCount();
        int second = Widgets.getSecondCount();
        // Imagine more complex logic here which really used first/second
        return first + second;
    }
}

... but that doesn't work when there are multiple variables you wish to assign within the same block, or none (e.g. if you just want to log something - or maybe initialize a native library).

Change hover color on a button with Bootstrap customization

I had to add !important to get it to work. I also made my own class button-primary-override.

.button-primary-override:hover, 
.button-primary-override:active,
.button-primary-override:focus,
.button-primary-override:visited{
    background-color: #42A5F5 !important;
    border-color: #42A5F5 !important;
    background-image: none !important;
    border: 0 !important;
}

How to get visitor's location (i.e. country) using geolocation?

For developers looking for a full-featured geolocation utility, you can have a look at geolocator.js (I'm the author).

Example below will first try HTML5 Geolocation API to obtain the exact coordinates. If fails or rejected, it will fallback to Geo-IP look-up. Once it gets the coordinates, it will reverse-geocode the coordinates into an address.

var options = {
    enableHighAccuracy: true,
    timeout: 6000,
    maximumAge: 0,
    desiredAccuracy: 30,
    fallbackToIP: true, // if HTML5 geolocation fails or rejected
    addressLookup: true, // get detailed address information
    timezone: true, 
    map: "my-map" // this will even create a map for you
};

geolocator.locate(options, function (err, location) {
    console.log(err || location);
});

It supports geo-location (via HTML5 or IP lookups), geocoding, address look-ups (reverse geocoding), distance & durations, timezone information and more...

How do you find the current user in a Windows environment?

%USERNAME% is the correct answer in batch and other in Windows environments.

Another option is to use %USERPROFILE% to get the user's path, like C:\Users\username.

Android adding simple animations while setvisibility(view.Gone)

Based on the answer of @Xaver Kapeller I figured out a way to create scroll animation when new views appear on the screen (and also animation to hide them).

It goes from this state:

  • Button
  • Last Button

to

  • Button
  • Button 1
  • Button 2
  • Button 3
  • Button 4
  • Last Button

and viceversa.

So, when the user clicks on the first button, the elements "Button 1", "Button 2", "Button 3" and "Button 4" will appear using fade animation and the element "Last Button" will move down till end. The height of the layout will change as well, allowing using scroll view properly.

This is the code to show elements with animation:

private void showElements() {
    // Precondition
    if (areElementsVisible()) {
        Log.w(TAG, "The view is already visible. Nothing to do here");
        return;
    }

    // Animate the hidden linear layout as visible and set
    // the alpha as 0.0. Otherwise the animation won't be shown
    mHiddenLinearLayout.setVisibility(View.VISIBLE);
    mHiddenLinearLayout.setAlpha(0.0f);
    mHiddenLinearLayout
            .animate()
            .setDuration(ANIMATION_TRANSITION_TIME)
            .alpha(1.0f)
            .setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    super.onAnimationEnd(animation);
                    updateShowElementsButton();
                    mHiddenLinearLayout.animate().setListener(null);
                }
            })
    ;

    mLastButton
            .animate()
            .setDuration(ANIMATION_TRANSITION_TIME)
            .translationY(mHiddenLinearLayoutHeight);

    // Update the high of all the elements relativeLayout
    LayoutParams layoutParams = mAllElementsRelativeLayout.getLayoutParams();

    // TODO: Add vertical margins
    layoutParams.height = mLastButton.getHeight() + mHiddenLinearLayoutHeight;
}

and this is the code to hide elements of the animation:

private void hideElements() {
    // Precondition
    if (!areElementsVisible()) {
        Log.w(TAG, "The view is already non-visible. Nothing to do here");
        return;
    }

    // Animate the hidden linear layout as visible and set
    mHiddenLinearLayout
            .animate()
            .setDuration(ANIMATION_TRANSITION_TIME)
            .alpha(0.0f)
            .setListener(new AnimatorListenerAdapter() {
                @Override
                public void onAnimationEnd(Animator animation) {
                    Log.v(TAG, "Animation ended. Set the view as gone");
                    super.onAnimationEnd(animation);
                    mHiddenLinearLayout.setVisibility(View.GONE);
                    // Hack: Remove the listener. So it won't be executed when
                    // any other animation on this view is executed
                    mHiddenLinearLayout.animate().setListener(null);
                    updateShowElementsButton();
                }
            })
    ;

    mLastButton
            .animate()
            .setDuration(ANIMATION_TRANSITION_TIME)
            .translationY(0);

    // Update the high of all the elements relativeLayout
    LayoutParams layoutParams = mAllElementsRelativeLayout.getLayoutParams();

    // TODO: Add vertical margins
    layoutParams.height = mLastButton.getHeight();
}

Note there is a simple hack on the method to hide the animation. On the animation listener mHiddenLinearLayout, I had to remove the listener itself by using:

mHiddenLinearLayout.animate().setListener(null);

This is because once an animation listener is attached to an view, the next time when any animation is executed in this view, the listener will be executed as well. This might be a bug in the animation listener.

The source code of the project is on GitHub: https://github.com/jiahaoliuliu/ViewsAnimated

Happy coding!

Update: For any listener attached to the views, it should be removed after the animation ends. This is done by using

view.animate().setListener(null);

C++11 reverse range-based for-loop

Does this work for you:

#include <iostream>
#include <list>
#include <boost/range/begin.hpp>
#include <boost/range/end.hpp>
#include <boost/range/iterator_range.hpp>

int main(int argc, char* argv[]){

  typedef std::list<int> Nums;
  typedef Nums::iterator NumIt;
  typedef boost::range_reverse_iterator<Nums>::type RevNumIt;
  typedef boost::iterator_range<NumIt> irange_1;
  typedef boost::iterator_range<RevNumIt> irange_2;

  Nums n = {1, 2, 3, 4, 5, 6, 7, 8};
  irange_1 r1 = boost::make_iterator_range( boost::begin(n), boost::end(n) );
  irange_2 r2 = boost::make_iterator_range( boost::end(n), boost::begin(n) );


  // prints: 1 2 3 4 5 6 7 8 
  for(auto e : r1)
    std::cout << e << ' ';

  std::cout << std::endl;

  // prints: 8 7 6 5 4 3 2 1
  for(auto e : r2)
    std::cout << e << ' ';

  std::cout << std::endl;

  return 0;
}

Difference between abstract class and interface in Python

Python >= 2.6 has Abstract Base Classes.

Abstract Base Classes (abbreviated ABCs) complement duck-typing by providing a way to define interfaces when other techniques like hasattr() would be clumsy. Python comes with many builtin ABCs for data structures (in the collections module), numbers (in the numbers module), and streams (in the io module). You can create your own ABC with the abc module.

There is also the Zope Interface module, which is used by projects outside of zope, like twisted. I'm not really familiar with it, but there's a wiki page here that might help.

In general, you don't need the concept of abstract classes, or interfaces in python (edited - see S.Lott's answer for details).

How to pass datetime from c# to sql correctly?

You've already done it correctly by using a DateTime parameter with the value from the DateTime, so it should already work. Forget about ToString() - since that isn't used here.

If there is a difference, it is most likely to do with different precision between the two environments; maybe choose a rounding (seconds, maybe?) and use that. Also keep in mind UTC/local/unknown (the DB has no concept of the "kind" of date; .NET does).

I have a table and the date-times in it are in the format: 2011-07-01 15:17:33.357

Note that datetimes in the database aren't in any such format; that is just your query-client showing you white lies. It is stored as a number (and even that is an implementation detail), because humans have this odd tendency not to realise that the date you've shown is the same as 40723.6371916281. Stupid humans. By treating it simply as a "datetime" throughout, you shouldn't get any problems.

How to bind inverse boolean properties in WPF?

I would recommend using https://quickconverter.codeplex.com/

Inverting a boolean is then as simple as: <Button IsEnabled="{qc:Binding '!$P', P={Binding IsReadOnly}}" />

That speeds the time normally needed to write converters.

How to "crop" a rectangular image into a square with CSS?

I actually came across this same problem recently and ended up with a slightly different approach (I wasn't able to use background images). It does require a tiny bit of jQuery though to determine the orientation of the images (I' sure you could use plain JS instead though).

I wrote a blog post about it if you are interested in more explaination but the code is pretty simple:

HTML:

<ul class="cropped-images">
  <li><img src="http://fredparke.com/sites/default/files/cat-portrait.jpg" /></li>
  <li><img src="http://fredparke.com/sites/default/files/cat-landscape.jpg" /></li>
</ul>

CSS:

li {
  width: 150px; // Or whatever you want.
  height: 150px; // Or whatever you want.
  overflow: hidden;
  margin: 10px;
  display: inline-block;
  vertical-align: top;
}
li img {
  max-width: 100%;
  height: auto;
  width: auto;
}
li img.landscape {
  max-width: none;
  max-height: 100%;
}

jQuery:

$( document ).ready(function() {

    $('.cropped-images img').each(function() {
      if ($(this).width() > $(this).height()) {
        $(this).addClass('landscape');        
      }
    });

});

R define dimensions of empty data frame

Just create a data frame of empty vectors:

collect1 <- data.frame(id = character(0), max1 = numeric(0), max2 = numeric(0))

But if you know how many rows you're going to have in advance, you should just create the data frame with that many rows to start with.

Scatter plot with error bars

Using ggplot and a little dplyr for data manipulation:

set.seed(42)
df <- data.frame(x = rep(1:10,each=5), y = rnorm(50))

library(ggplot2)
library(dplyr)

df.summary <- df %>% group_by(x) %>%
    summarize(ymin = min(y),
              ymax = max(y),
              ymean = mean(y))

ggplot(df.summary, aes(x = x, y = ymean)) +
    geom_point(size = 2) +
    geom_errorbar(aes(ymin = ymin, ymax = ymax))

If there's an additional grouping column (OP's example plot has two errorbars per x value, saying the data is sourced from two files), then you should get all the data in one data frame at the start, add the grouping variable to the dplyr::group_by call (e.g., group_by(x, file) if file is the name of the column) and add it as a "group" aesthetic in the ggplot, e.g., aes(x = x, y = ymean, group = file).

Bootstrap modal: close current, open new

None of the answers helped me since I wanted to achieve something which was exactly the same as mentioned in the question.

I have created a jQuery plugin for this purpose.

/*
 * Raj: This file is responsible to display the modals in a stacked fashion. Example:
 * 1. User displays modal A
 * 2. User now wants to display modal B -> This will not work by default if a modal is already displayed
 * 3. User dismisses modal B
 * 4. Modal A should now be displayed automatically -> This does not happen all by itself 
 * 
 * Trying to solve problem for: http://stackoverflow.com/questions/18253972/bootstrap-modal-close-current-open-new
 * 
 */

var StackedModalNamespace = StackedModalNamespace || (function() {
    var _modalObjectsStack = [];
    return {
        modalStack: function() {
            return _modalObjectsStack;
        },
        currentTop: function() {
            var topModal = null;
            if (StackedModalNamespace.modalStack().length) {
                topModal = StackedModalNamespace.modalStack()[StackedModalNamespace.modalStack().length-1];
            }
            return topModal;
        }
    };
}());

// http://stackoverflow.com/a/13992290/260665 difference between $.fn.extend and $.extend
jQuery.fn.extend({
    // https://api.jquery.com/jquery.fn.extend/
    showStackedModal: function() {
        var topModal = StackedModalNamespace.currentTop();
        StackedModalNamespace.modalStack().push(this);
        this.off('hidden.bs.modal').on('hidden.bs.modal', function(){   // Subscription to the hide event
            var currentTop = StackedModalNamespace.currentTop();
            if ($(this).is(currentTop)) {
                // 4. Unwinding - If user has dismissed the top most modal we need to remove it form the stack and display the now new top modal (which happens in point 3 below)
                StackedModalNamespace.modalStack().pop();
            }
            var newTop = StackedModalNamespace.currentTop();
            if (newTop) {
                // 3. Display the new top modal (since the existing modal would have been hidden by point 2 now)
                newTop.modal('show');
            }
        });
        if (topModal) {
            // 2. If some modal is displayed, lets hide it
            topModal.modal('hide');
        } else {
            // 1. If no modal is displayed, just display the modal
            this.modal('show');
        }
    },
});

Working Fiddle for reference, JSFiddle: https://jsfiddle.net/gumdal/67hzgp5c/

You just have to invoke with my new API "showStackedModal()" instead of just "modal('show')". The hide part can still be the same as before and the stacked approach of showing & hiding the modals are automatically taken care.

Return JSON for ResponseEntity<String>

@RequestMapping(value = "so", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
public @ResponseBody String so() {
    return "This is a String";
}

How to insert text in a td with id, using JavaScript

<html>

<head>
<script type="text/javascript">
function insertText () {
    document.getElementById('td1').innerHTML = "Some text to enter";
}
</script>
</head>

<body onload="insertText();">
    <table>
        <tr>
            <td id="td1"></td>
        </tr>
    </table>
</body>
</html>

Remote branch is not showing up in "git branch -r"

The remote section also specifies fetch rules. You could add something like this into it to fetch all branches from the remote:

fetch = +refs/heads/*:refs/remotes/origin/*

(Or replace origin with bitbucket.)

Please read about it here: 10.5 Git Internals - The Refspec

How to programmatically set the SSLContext of a JAX-WS client?

This is how I solved it based on this post with some minor tweaks. This solution does not require creation of any additional classes.

SSLContext sc = SSLContext.getInstance("SSLv3");

KeyManagerFactory kmf =
    KeyManagerFactory.getInstance( KeyManagerFactory.getDefaultAlgorithm() );

KeyStore ks = KeyStore.getInstance( KeyStore.getDefaultType() );
ks.load(new FileInputStream( certPath ), certPasswd.toCharArray() );

kmf.init( ks, certPasswd.toCharArray() );

sc.init( kmf.getKeyManagers(), null, null );

((BindingProvider) webservicePort).getRequestContext()
    .put(
        "com.sun.xml.internal.ws.transport.https.client.SSLSocketFactory",
        sc.getSocketFactory() );

What does the line "#!/bin/sh" mean in a UNIX shell script?

It's called a shebang, and tells the parent shell which interpreter should be used to execute the script.

#!/bin/sh <--------- bourne shell compatible script
#!/usr/bin/perl  <-- perl script
#!/usr/bin/php  <--- php script
#!/bin/false <------ do-nothing script, because false returns immediately anyways.

Most scripting languages tend to interpret a line starting with # as comment and will ignore the following !/usr/bin/whatever portion, which might otherwise cause a syntax error in the interpreted language.

Unable to call the built in mb_internal_encoding method?

apt-get install php7.3-mbstring solved the issue on ubuntu, php version is php-fpm 7.3

adb remount permission denied, but able to access super user in shell -- android

I rebooted to recovery then

adb root; adb adb remount system; 

worked for me my recovery is twrp v3.5

How do you UrlEncode without using System.Web?

System.Net.WebUtility.HtmlDecode

How to remove "disabled" attribute using jQuery?

<input type="text" disabled="disabled" class="inputDisabled" value="">
?<button id="edit">Edit</button>????????????????????????????????

$("#edit").click(function(event){
    event.preventDefault();
    $('.inputDisabled').removeAttr("disabled")
});?

http://jsfiddle.net/ZwHfY/

python request with authentication (access_token)

Have you tried the uncurl package (https://github.com/spulec/uncurl)? You can install it via pip, pip install uncurl. Your curl request returns:

>>> uncurl "curl --header \"Authorization:access_token myToken\" https://website.com/id"

requests.get("https://website.com/id",
    headers={
        "Authorization": "access_token myToken"
    },
    cookies={},
)

What is the use of "using namespace std"?

  • using: You are going to use it.
  • namespace: To use what? A namespace.
  • std: The std namespace (where features of the C++ Standard Library, such as string or vector, are declared).

After you write this instruction, if the compiler sees string it will know that you may be referring to std::string, and if it sees vector, it will know that you may be referring to std::vector. (Provided that you have included in your compilation unit the header files where they are defined, of course.)

If you don't write it, when the compiler sees string or vector it will not know what you are refering to. You will need to explicitly tell it std::string or std::vector, and if you don't, you will get a compile error.

How to sort by two fields in Java?

For a class Book like this:

package books;

public class Book {

    private Integer id;
    private Integer number;
    private String name;

    public Integer getId() {
        return id;
    }

    public void setId(Integer id) {
        this.id = id;
    }

    public Integer getNumber() {
        return number;
    }

    public void setNumber(Integer number) {
        this.number = number;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    @Override
    public String toString() {
        return "book{" +
                "id=" + id +
                ", number=" + number +
                ", name='" + name + '\'' + '\n' +
                '}';
    }
}

sorting main class with mock objects

package books;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;


public class Main {

    public static void main(String[] args) {
        System.out.println("Hello World!");

        Book b = new Book();

        Book c = new Book();

        Book d = new Book();

        Book e = new Book();

        Book f = new Book();

        Book g = new Book();
        Book g1 = new Book();
        Book g2 = new Book();
        Book g3 = new Book();
        Book g4 = new Book();




        b.setId(1);
        b.setNumber(12);
        b.setName("gk");

        c.setId(2);
        c.setNumber(12);
        c.setName("gk");

        d.setId(2);
        d.setNumber(13);
        d.setName("maths");

        e.setId(3);
        e.setNumber(3);
        e.setName("geometry");

        f.setId(3);
        f.setNumber(34);
        b.setName("gk");

        g.setId(3);
        g.setNumber(11);
        g.setName("gk");

        g1.setId(3);
        g1.setNumber(88);
        g1.setName("gk");
        g2.setId(3);
        g2.setNumber(91);
        g2.setName("gk");
        g3.setId(3);
        g3.setNumber(101);
        g3.setName("gk");
        g4.setId(3);
        g4.setNumber(4);
        g4.setName("gk");





        List<Book> allBooks = new ArrayList<Book>();

        allBooks.add(b);
        allBooks.add(c);
        allBooks.add(d);
        allBooks.add(e);
        allBooks.add(f);
        allBooks.add(g);
        allBooks.add(g1);
        allBooks.add(g2);
        allBooks.add(g3);
        allBooks.add(g4);



        System.out.println(allBooks.size());


        Collections.sort(allBooks, new Comparator<Book>() {

            @Override
            public int compare(Book t, Book t1) {
                int a =  t.getId()- t1.getId();

                if(a == 0){
                    int a1 = t.getNumber() - t1.getNumber();
                    return a1;
                }
                else
                    return a;
            }
        });
        System.out.println(allBooks);

    }


   }

Paused in debugger in chrome?

And there is some options below ,if you have checked some,when the condition is active,the breakpoint debugger also active

How to test the `Mosquitto` server?

To test and see if you can access your MQTT server from outside world (outside of your VM or local machine), you can install one of the MQTT publishing and monitoring tools such as MQTT-Spy on your outside-world machine and then subscribe for '#" (meaning all the topics).

You can follow this by the method @hardillb mentioned in his answer above and test back and forth such as this:

On the machine with Mosquitto Server running, enter image description here

On the outside-word machine with mqtt-spy running, enter image description here

I have mainly mentioned mqtt-spy since it's multi-platform and easy to use. You can go with any other tool really. And also to my knowledge to run the mosquitto_sub and mosquitto_pub you need to have mosquitto-clients installed on your Linux machine running the test (in my case Ubuntu) which can be done easily by,

sudo apt-get install mosquitto-clients

ASP.NET Core Get Json Array using IConfiguration

If you have array of complex JSON objects like this:

{
  "MySettings": {
    "MyValues": [
      { "Key": "Key1", "Value":  "Value1" },
      { "Key": "Key2", "Value":  "Value2" }
    ]
  }
}

You can retrieve settings this way:

var valuesSection = configuration.GetSection("MySettings:MyValues");
foreach (IConfigurationSection section in valuesSection.GetChildren())
{
    var key = section.GetValue<string>("Key");
    var value = section.GetValue<string>("Value");
}

What's the syntax to import a class in a default package in Java?

That's not possible.

The alternative is using reflection:

 Class.forName("SomeClass").getMethod("someMethod").invoke(null);

How can I find non-ASCII characters in MySQL?

In Oracle we can use below.

SELECT * FROM TABLE_A WHERE ASCIISTR(COLUMN_A) <> COLUMN_A;

Eclipse hangs on loading workbench

Here's a less destructive method that worked for me:

I'm on Windows machine with a copy of Spring Tool Suite (an extension of Eclipse) which I'm running from a random directory. In my command line prompt, I had to navigate to the directory which contained my STS.exe and run: STS.exe -refresh.

After that, I could open my Eclipse the normal way (which was through a pinned taskbar icon).

SELECT where row value contains string MySQL

This should work:

SELECT * FROM Accounts WHERE Username LIKE '%$query%'

How to convert an array to a string in PHP?

Using implode(), you can turn the array into a string.

$str = implode(',', $array); // 33160,33280,33180,...

Using C# to check if string contains a string in string array

Using Find or FindIndex methods of the Array class:

if(Array.Find(stringArray, stringToCheck.Contains) != null) 
{ 
}
if(Array.FindIndex(stringArray, stringToCheck.Contains) != -1) 
{ 
}

How to make a phone call using intent in Android?

In Android for certain functionalities you need to add the permission to the Manifest file.

  1. Go to the Projects AndroidManifest.xml
  2. Click on the Permissions Tab
  3. Click on Add
  4. Select Uses Permission
  5. See the snapshot belowenter image description here

6.Save the manifest file and then run your project. Your project now should run as expected.

Rails and PostgreSQL: Role postgres does not exist

In Ubuntu local user command prompt, but not root user, type

sudo -u postgres createuser username

username above should match the name indicated in the message "FATAL: role 'username' does not exist."

Enter password for username.

Then re-enter the command that generated role does not exist message.

SQL - How to find the highest number in a column?

To get it at any time, you can do SELECT MAX(Id) FROM Customers .

In the procedure you add it in, however, you can also make use of SCOPE_IDENTITY -- to get the id last added by that procedure.
This is safer, because it will guarantee you get your Id--just in case others are being added to the database at the same time.

How to install a Mac application using Terminal

Probably not exactly your issue..

Do you have any spaces in your package path? You should wrap it up in double quotes to be safe, otherwise it can be taken as two separate arguments

sudo installer -store -pkg "/User/MyName/Desktop/helloWorld.pkg" -target /

How do I set hostname in docker-compose?

This seems to work correctly. If I put your config into a file:

$ cat > compose.yml <<EOF
dns:
  image: phensley/docker-dns
  hostname: affy
  domainname: affy.com
  volumes:
    - /var/run/docker.sock:/docker.sock
EOF

And then bring things up:

$ docker-compose -f compose.yml up
Creating tmp_dns_1...
Attaching to tmp_dns_1
dns_1 | 2015-04-28T17:47:45.423387 [dockerdns] table.add tmp_dns_1.docker -> 172.17.0.5

And then check the hostname inside the container, everything seems to be fine:

$ docker exec -it stack_dns_1 hostname
affy.affy.com

Get the position of a div/span tag

While @nickf's answer works. If you don't care for older browsers, you can use this pure Javascript version. Works in IE9+, and others

var rect = el.getBoundingClientRect();

var position = {
  top: rect.top + window.pageYOffset,
  left: rect.left + window.pageXOffset
};

Best way to check that element is not present using Selenium WebDriver with java

In Python for assertion I use:

assert len(driver.find_elements_by_css_selector("your_css_selector")) == 0

JavaScript - Get Portion of URL Path

If this is the current url use window.location.pathname otherwise use this regular expression:

var reg = /.+?\:\/\/.+?(\/.+?)(?:#|\?|$)/;
var pathname = reg.exec( 'http://www.somedomain.com/account/search?filter=a#top' )[1];

Java keytool easy way to add server cert from url/port

Was looking at how to trust a certificate while using jenkins cli, and found https://issues.jenkins-ci.org/browse/JENKINS-12629 which has some recipe for that.

This will give you the certificate:

openssl s_client -connect ${HOST}:${PORT} </dev/null

if you are interested only in the certificate part, cut it out by piping it to:

| sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p'

and redirect to a file:

> ${HOST}.cert

Then import it using keytool:

keytool -import -noprompt -trustcacerts -alias ${HOST} -file ${HOST}.cert \
    -keystore ${KEYSTOREFILE} -storepass ${KEYSTOREPASS}

In one go:

HOST=myhost.example.com
PORT=443
KEYSTOREFILE=dest_keystore
KEYSTOREPASS=changeme

# get the SSL certificate
openssl s_client -connect ${HOST}:${PORT} </dev/null \
    | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > ${HOST}.cert

# create a keystore and import certificate
keytool -import -noprompt -trustcacerts \
    -alias ${HOST} -file ${HOST}.cert \
    -keystore ${KEYSTOREFILE} -storepass ${KEYSTOREPASS}

# verify we've got it.
keytool -list -v -keystore ${KEYSTOREFILE} -storepass ${KEYSTOREPASS} -alias ${HOST}

MAX(DATE) - SQL ORACLE

select * from 
  (SELECT MEMBSHIP_ID
   FROM user_payment WHERE user_id=1
   order by paym_date desc) 
where rownum=1;

Keeping ASP.NET Session Open / Alive

Here is a alternative solution that should survive if the client pc goes into sleep mode.

If you have a huge amount of logged in users then use this cautiously as this could eat a lot of server memory.

After you login (i do this in the LoggedIn event of the login control)

Dim loggedOutAfterInactivity As Integer = 999 'Minutes

'Keep the session alive as long as the authentication cookie.
Session.Timeout = loggedOutAfterInactivity

'Get the authenticationTicket, decrypt and change timeout and create a new one.
Dim formsAuthenticationTicketCookie As HttpCookie = _
        Response.Cookies(FormsAuthentication.FormsCookieName)

Dim ticket As FormsAuthenticationTicket = _
        FormsAuthentication.Decrypt(formsAuthenticationTicketCookie.Value)
Dim newTicket As New FormsAuthenticationTicket(
        ticket.Version, ticket.Name, ticket.IssueDate, 
        ticket.IssueDate.AddMinutes(loggedOutAfterInactivity), 
        ticket.IsPersistent, ticket.UserData)
formsAuthenticationTicketCookie.Value = FormsAuthentication.Encrypt(newTicket)

jQuery has deprecated synchronous XMLHTTPRequest

If we load script in partial view then this issue coming

  1. I removed script in partial view and moved to main view.

This solution working fine for me

How to pass ArrayList of Objects from one to another activity using Intent in android?

Your intent creation seems correct if your Question implements Parcelable.

In the next activity you can retrieve your list of questions like this:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if(getIntent() != null && getIntent().hasExtra("QuestionsExtra")) {
        List<Question> mQuestionsList = getIntent().getParcelableArrayListExtra("QuestionsExtra");
    }
}

How to install mechanize for Python 2.7?

sudo pip-2.7 install mechanize

Why is list initialization (using curly braces) better than the alternatives?

It only safer as long as you don't build with -Wno-narrowing like say Google does in Chromium. If you do, then it is LESS safe. Without that flag the only unsafe cases will be fixed by C++20 though.

Note: A) Curly brackets are safer because they don't allow narrowing. B) Curly brackers are less safe because they can bypass private or deleted constructors, and call explicit marked constructors implicitly.

Those two combined means they are safer if what is inside is primitive constants, but less safe if they are objects (though fixed in C++20)

Summarizing multiple columns with dplyr?

For completeness: with dplyr v0.2 ddply with colwise will also do this:

> ddply(df, .(grp), colwise(mean))
  grp        a    b        c        d
1   1 4.333333 4.00 1.000000 2.000000
2   2 2.000000 2.75 2.750000 2.750000
3   3 3.000000 4.00 4.333333 3.666667

but it is slower, at least in this case:

> microbenchmark(ddply(df, .(grp), colwise(mean)), 
                  df %>% group_by(grp) %>% summarise_each(funs(mean)))
Unit: milliseconds
                                            expr      min       lq     mean
                ddply(df, .(grp), colwise(mean))     3.278002 3.331744 3.533835
 df %>% group_by(grp) %>% summarise_each(funs(mean)) 1.001789 1.031528 1.109337

   median       uq      max neval
 3.353633 3.378089 7.592209   100
 1.121954 1.133428 2.292216   100

Extract date (yyyy/mm/dd) from a timestamp in PostgreSQL

You can cast your timestamp to a date by suffixing it with ::date. Here, in psql, is a timestamp:

# select '2010-01-01 12:00:00'::timestamp;
      timestamp      
---------------------
 2010-01-01 12:00:00

Now we'll cast it to a date:

wconrad=# select '2010-01-01 12:00:00'::timestamp::date;
    date    
------------
 2010-01-01

On the other hand you can use date_trunc function. The difference between them is that the latter returns the same data type like timestamptz keeping your time zone intact (if you need it).

=> select date_trunc('day', now());
       date_trunc
------------------------
 2015-12-15 00:00:00+02
(1 row)

Edit a text file on the console using Powershell

In linux i'm a fun of Nano or vim, i used to use nano and now vim, and they are really good choices. There is a version for windows. Here is the link https://nano-editor.org/dist/win32-support/

However more often we need to open the file in question, from the command line as quick as possible, to not loose time. We can use notepad.exe, we can use notepad++, and yea, we can use sublim text. I think there is no greater then a lightweight, Too powerful editor. Sublime text here. for the thing, we just don't want to get out of the command line, or we want to use the command line to be fast. and yea. We can use sublime text for that. it contain a command line that let you quickly open a file in sublime text. Also there is different options arguments you can make use of. Here how you do it.

First you need to know that there is subl.exe. a command line interface for sublim.

enter image description here

1-> first we create a batch file. the content is

enter image description here

@ECHO OFF

"C:\Program Files\Sublime Text 3\subl.exe" %*

We can save that wherever we want. I preferred to create a directory on sublime text installation directory. And saved there the batch file we come to write and create.

(Remark: change the path above fallowing your installation).

2-> we add that folder to the path system environment variable. and that's it.

enter image description here

or from system config (windows 7/8/10)

enter image description here

then:

enter image description here

then:

enter image description here

then we copy the path:

enter image description here

then we add that to the path variable:

enter image description here

too quick!

launch a new cmd and now you've got subl command working well!

enter image description here

to open a file you need just to use subl command as fellow:

subl myfileToOpen.txt

you can also use one of the options arguments (type --help to see them as in the image above).

Also note that you can apply the same method with mostly any editor of your choice.

seek() function?

When you open a file, the system points to the beginning of the file. Any read or write you do will happen from the beginning. A seek() operation moves that pointer to some other part of the file so you can read or write at that place.

So, if you want to read the whole file but skip the first 20 bytes, open the file, seek(20) to move to where you want to start reading, then continue with reading the file.

Or say you want to read every 10th byte, you could write a loop that does seek(9, 1) (moves 9 bytes forward relative to the current positions), read(1) (reads one byte), repeat.

Java rounding up to an int using Math.ceil

Check the solution below for your question:

int total = (int) Math.ceil(157/32);

Here you should multiply Numerator with 1.0, then it will give your answer.

int total = (int) Math.ceil(157*1.0/32);

Command line input in Python

Start your script with the following line. The script will first run and then you will get the python command prompt. At this point all variables and functions will be available for interactive use and invocations.

#!/usr/bin/env python -i

How to connect html pages to mysql database?

HTML are markup languages, basically they are set of tags like <html>, <body>, which is used to present a website using , and as a whole. All these, happen in the clients system or the user you will be browsing the website.

Now, Connecting to a database, happens on whole another level. It happens on server, which is where the website is hosted.

So, in order to connect to the database and perform various data related actions, you have to use server-side scripts, like , , etc.

Now, lets see a snippet of connection using MYSQLi Extension of PHP

$db = mysqli_connect('hostname','username','password','databasename');

This single line code, is enough to get you started, you can mix such code, combined with HTML tags to create a HTML page, which is show data based pages. For example:

<?php
    $db = mysqli_connect('hostname','username','password','databasename');
?>
<html>
    <body>
          <?php
                $query = "SELECT * FROM `mytable`;";
                $result = mysqli_query($db, $query);
                while($row = mysqli_fetch_assoc($result)) {
                      // Display your datas on the page
                }
          ?>
    </body>
</html>

In order to insert new data into the database, you can use phpMyAdmin or write a INSERT query and execute them.

Initialize Array of Objects using NSArray

This way you can Create NSArray, NSMutableArray.

NSArray keys =[NSArray arrayWithObjects:@"key1",@"key2",@"key3",nil];

NSArray objects =[NSArray arrayWithObjects:@"value1",@"value2",@"value3",nil];

MySQL: How to copy rows, but change a few fields?

This is a solution where you have many fields in your table and don't want to get a finger cramp from typing all the fields, just type the ones needed :)

How to copy some rows into the same table, with some fields having different values:

  1. Create a temporary table with all the rows you want to copy
  2. Update all the rows in the temporary table with the values you want
  3. If you have an auto increment field, you should set it to NULL in the temporary table
  4. Copy all the rows of the temporary table into your original table
  5. Delete the temporary table

Your code:

CREATE table temporary_table AS SELECT * FROM original_table WHERE Event_ID="155";

UPDATE temporary_table SET Event_ID="120";

UPDATE temporary_table SET ID=NULL

INSERT INTO original_table SELECT * FROM temporary_table;

DROP TABLE temporary_table

General scenario code:

CREATE table temporary_table AS SELECT * FROM original_table WHERE <conditions>;

UPDATE temporary_table SET <fieldx>=<valuex>, <fieldy>=<valuey>, ...;

UPDATE temporary_table SET <auto_inc_field>=NULL;

INSERT INTO original_table SELECT * FROM temporary_table;

DROP TABLE temporary_table

Simplified/condensed code:

CREATE TEMPORARY TABLE temporary_table AS SELECT * FROM original_table WHERE <conditions>;

UPDATE temporary_table SET <auto_inc_field>=NULL, <fieldx>=<valuex>, <fieldy>=<valuey>, ...;

INSERT INTO original_table SELECT * FROM temporary_table;

As creation of the temporary table uses the TEMPORARY keyword it will be dropped automatically when the session finishes (as @ar34z suggested).

HTML img onclick Javascript

here you go.

<img src="https://i.imgur.com/7KpCS0Y.jpg" onclick="window.open(this.src)">

jquery $('.class').each() how many items?

If you are using a version of jQuery that is less than version 1.8 you can use the $('.class').size() which takes zero parameters. See documentation for more information on .size() method.

However if you are using (or plan to upgrade) to 1.8 or greater you can use $('.class').length property. See documentation for more information on .length property.

Comma separated results in SQL

Use FOR XML PATH('') - which is converting the entries to a comma separated string and STUFF() -which is to trim the first comma- as follows Which gives you the same comma separated result

SELECT  STUFF((SELECT  ',' + INSTITUTIONNAME
            FROM EDUCATION EE
            WHERE  EE.STUDENTNUMBER=E.STUDENTNUMBER
            ORDER BY sortOrder
        FOR XML PATH('')), 1, 1, '') AS listStr

FROM EDUCATION E
GROUP BY E.STUDENTNUMBER

Here is the FIDDLE

Rename specific column(s) in pandas

data.rename(columns={'gdp':'log(gdp)'}, inplace=True)

The rename show that it accepts a dict as a param for columns so you just pass a dict with a single entry.

Also see related

How to get current foreground activity context in android?

I could not find a solution that our team would be happy with so we rolled our own. We use ActivityLifecycleCallbacks to keep track of current activity and then expose it through a service. More details here: https://stackoverflow.com/a/38650587/10793

VBA test if cell is in a range

Determine if a cell is within a range using VBA in Microsoft Excel:

From the linked site (maintaining credit to original submitter):

VBA macro tip contributed by Erlandsen Data Consulting offering Microsoft Excel Application development, template customization, support and training solutions

Function InRange(Range1 As Range, Range2 As Range) As Boolean
    ' returns True if Range1 is within Range2
    InRange = Not (Application.Intersect(Range1, Range2) Is Nothing)
End Function


Sub TestInRange()
    If InRange(ActiveCell, Range("A1:D100")) Then
        ' code to handle that the active cell is within the right range
        MsgBox "Active Cell In Range!"
    Else
        ' code to handle that the active cell is not within the right range
        MsgBox "Active Cell NOT In Range!"
    End If
End Sub

How do I set default value of select box in angularjs

if you don't even want to initialize ng-model to a static value and each value is DB driven, it can be done in the following way. Angular compares the evaluated value and populates the drop down.

Here below modelData.unitId is retrieved from DB and is compared to the list of unit id which is a separate list from db-

_x000D_
_x000D_
 <select id="uomList" ng-init="modelData.unitId"_x000D_
                         ng-model="modelData.unitId" ng-options="unitOfMeasurement.id as unitOfMeasurement.unitName for unitOfMeasurement in unitOfMeasurements">
_x000D_
_x000D_
_x000D_

Hide div after a few seconds

This will hide the div after 1 second (1000 milliseconds).

_x000D_
_x000D_
setTimeout(function() {_x000D_
    $('#mydiv').fadeOut('fast');_x000D_
}, 1000); // <-- time in milliseconds
_x000D_
#mydiv{_x000D_
    width: 100px;_x000D_
    height: 100px;_x000D_
    background: #000;_x000D_
    color: #fff;_x000D_
    text-align: center;_x000D_
}
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<div id="mydiv">myDiv</div>
_x000D_
_x000D_
_x000D_

If you just want to hide without fading, use hide().

Embed YouTube video - Refused to display in a frame because it set 'X-Frame-Options' to 'SAMEORIGIN'

You only need to copy <iframe> from the YouTube Embed section (click on SHARE below the video and then EMBED and copy the entire iframe).

How do I group Windows Form radio buttons?

GroupBox is better.But not only group box, even you can use Panels (System.Windows.Forms.Panel).

  • That is very usefully when you are designing Internet Protocol version 4 setting dialog.(Check it with your pc(windows),then you can understand the behavior)

Try-catch-finally-return clarification

If the return in the try block is reached, it transfers control to the finally block, and the function eventually returns normally (not a throw).

If an exception occurs, but then the code reaches a return from the catch block, control is transferred to the finally block and the function eventually returns normally (not a throw).

In your example, you have a return in the finally, and so regardless of what happens, the function will return 34, because finally has the final (if you will) word.

Although not covered in your example, this would be true even if you didn't have the catch and if an exception were thrown in the try block and not caught. By doing a return from the finally block, you suppress the exception entirely. Consider:

public class FinallyReturn {
  public static final void main(String[] args) {
    System.out.println(foo(args));
  }

  private static int foo(String[] args) {
    try {
      int n = Integer.parseInt(args[0]);
      return n;
    }
    finally {
      return 42;
    }
  }
}

If you run that without supplying any arguments:

$ java FinallyReturn

...the code in foo throws an ArrayIndexOutOfBoundsException. But because the finally block does a return, that exception gets suppressed.

This is one reason why it's best to avoid using return in finally.

Iterating through a golang map

You can make it by one line:

mymap := map[string]interface{}{"foo": map[string]interface{}{"first": 1}, "boo": map[string]interface{}{"second": 2}}
for k, v := range mymap {
    fmt.Println("k:", k, "v:", v)
}

Output is:

k: foo v: map[first:1]
k: boo v: map[second:2]

How to convert java.lang.Object to ArrayList?

An interesting note: it appears that attempting to cast from an object to a list on the JavaFX Application thread always results in a ClassCastException.

I had the same issue as you, and no answer helped. After playing around for a while, the only thing I could narrow it down to was the thread. Running the code to cast on any other thread other than the UI thread succeeds as expected, and as the other answers in this section suggest.

Thus, be careful that your source isn't running on the JavaFX application thread.

gdb fails with "Unable to find Mach task port for process-id" error

The problem is that you are not logged in as a root user (which you don't want). You need to create a certificate for gdb to be allowed access. Follow this tutorial and you should be good to go...

http://sourceware.org/gdb/wiki/BuildingOnDarwin

If all else fails, just use: sudo gdb executableFileName

MySQL Orderby a number, Nulls last

NULL LAST

SELECT * FROM table_name ORDER BY id IS NULL, id ASC

how to implement Pagination in reactJs

I have tried to recreate the simple pagination example given by piotr-berebecki which was great. But when there will be a lot of pages then the pagination will overflow in the screen. So, I used previous and back button along with forward and backward button to stream back and forth between the pages. And for design part I have used bootstrap 3.

You can customize no of pages to display in pagination using the pagebound values. Make sure to use same value for upperPageBound and pageBound.

    class TodoApp extends React.Component {
          constructor() {
            super();
            this.state = {
              todos: ['a','b','c','d','e','f','g','h','i','j','k','l','m',
'n','o','p','q','r','s','t','u','v','w','x','y','z'],
              currentPage: 1,
              todosPerPage: 3,
              upperPageBound: 3,
              lowerPageBound: 0,
              isPrevBtnActive: 'disabled',
              isNextBtnActive: '',
              pageBound: 3
            };
            this.handleClick = this.handleClick.bind(this);
            this.btnDecrementClick = this.btnDecrementClick.bind(this);
            this.btnIncrementClick = this.btnIncrementClick.bind(this);
            this.btnNextClick = this.btnNextClick.bind(this);
            this.btnPrevClick = this.btnPrevClick.bind(this);
            // this.componentDidMount = this.componentDidMount.bind(this);
            this.setPrevAndNextBtnClass = this.setPrevAndNextBtnClass.bind(this);
          }
          componentDidUpdate() {
                $("ul li.active").removeClass('active');
                $('ul li#'+this.state.currentPage).addClass('active');
          }
          handleClick(event) {
            let listid = Number(event.target.id);
            this.setState({
              currentPage: listid
            });
            $("ul li.active").removeClass('active');
            $('ul li#'+listid).addClass('active');
            this.setPrevAndNextBtnClass(listid);
          }
          setPrevAndNextBtnClass(listid) {
            let totalPage = Math.ceil(this.state.todos.length / this.state.todosPerPage);
            this.setState({isNextBtnActive: 'disabled'});
            this.setState({isPrevBtnActive: 'disabled'});
            if(totalPage === listid && totalPage > 1){
                this.setState({isPrevBtnActive: ''});
            }
            else if(listid === 1 && totalPage > 1){
                this.setState({isNextBtnActive: ''});
            }
            else if(totalPage > 1){
                this.setState({isNextBtnActive: ''});
                this.setState({isPrevBtnActive: ''});
            }
        }
          btnIncrementClick() {
              this.setState({upperPageBound: this.state.upperPageBound + this.state.pageBound});
              this.setState({lowerPageBound: this.state.lowerPageBound + this.state.pageBound});
              let listid = this.state.upperPageBound + 1;
              this.setState({ currentPage: listid});
              this.setPrevAndNextBtnClass(listid);
        }
          btnDecrementClick() {
            this.setState({upperPageBound: this.state.upperPageBound - this.state.pageBound});
            this.setState({lowerPageBound: this.state.lowerPageBound - this.state.pageBound});
            let listid = this.state.upperPageBound - this.state.pageBound;
            this.setState({ currentPage: listid});
            this.setPrevAndNextBtnClass(listid);
        }
        btnPrevClick() {
            if((this.state.currentPage -1)%this.state.pageBound === 0 ){
                this.setState({upperPageBound: this.state.upperPageBound - this.state.pageBound});
                this.setState({lowerPageBound: this.state.lowerPageBound - this.state.pageBound});
            }
            let listid = this.state.currentPage - 1;
            this.setState({ currentPage : listid});
            this.setPrevAndNextBtnClass(listid);
        }
        btnNextClick() {
            if((this.state.currentPage +1) > this.state.upperPageBound ){
                this.setState({upperPageBound: this.state.upperPageBound + this.state.pageBound});
                this.setState({lowerPageBound: this.state.lowerPageBound + this.state.pageBound});
            }
            let listid = this.state.currentPage + 1;
            this.setState({ currentPage : listid});
            this.setPrevAndNextBtnClass(listid);
        }
          render() {
            const { todos, currentPage, todosPerPage,upperPageBound,lowerPageBound,isPrevBtnActive,isNextBtnActive } = this.state;
            // Logic for displaying current todos
            const indexOfLastTodo = currentPage * todosPerPage;
            const indexOfFirstTodo = indexOfLastTodo - todosPerPage;
            const currentTodos = todos.slice(indexOfFirstTodo, indexOfLastTodo);

            const renderTodos = currentTodos.map((todo, index) => {
              return <li key={index}>{todo}</li>;
            });

            // Logic for displaying page numbers
            const pageNumbers = [];
            for (let i = 1; i <= Math.ceil(todos.length / todosPerPage); i++) {
              pageNumbers.push(i);
            }

            const renderPageNumbers = pageNumbers.map(number => {
                if(number === 1 && currentPage === 1){
                    return(
                        <li key={number} className='active' id={number}><a href='#' id={number} onClick={this.handleClick}>{number}</a></li>
                    )
                }
                else if((number < upperPageBound + 1) && number > lowerPageBound){
                    return(
                        <li key={number} id={number}><a href='#' id={number} onClick={this.handleClick}>{number}</a></li>
                    )
                }
            });
            let pageIncrementBtn = null;
            if(pageNumbers.length > upperPageBound){
                pageIncrementBtn = <li className=''><a href='#' onClick={this.btnIncrementClick}> &hellip; </a></li>
            }
            let pageDecrementBtn = null;
            if(lowerPageBound >= 1){
                pageDecrementBtn = <li className=''><a href='#' onClick={this.btnDecrementClick}> &hellip; </a></li>
            }
            let renderPrevBtn = null;
            if(isPrevBtnActive === 'disabled') {
                renderPrevBtn = <li className={isPrevBtnActive}><span id="btnPrev"> Prev </span></li>
            }
            else{
                renderPrevBtn = <li className={isPrevBtnActive}><a href='#' id="btnPrev" onClick={this.btnPrevClick}> Prev </a></li>
            }
            let renderNextBtn = null;
            if(isNextBtnActive === 'disabled') {
                renderNextBtn = <li className={isNextBtnActive}><span id="btnNext"> Next </span></li>
            }
            else{
                renderNextBtn = <li className={isNextBtnActive}><a href='#' id="btnNext" onClick={this.btnNextClick}> Next </a></li>
            }
            return (
              <div>
                  <ul>
                  {renderTodos}
                </ul>
                <ul id="page-numbers" className="pagination">
                  {renderPrevBtn}
                  {pageDecrementBtn}
                  {renderPageNumbers}
                  {pageIncrementBtn}
                  {renderNextBtn}
                </ul>
              </div>
            );
          }
        }


        ReactDOM.render(
          <TodoApp />,
          document.getElementById('app')
        );

Working demo link : https://codepen.io/mhmanandhar/pen/oEWBqx

Image : simple react pagination

Favicon: .ico or .png / correct tags?

See here: Cross Browser favicon

Thats the way to go:

<link rel="icon" type="image/png" href="http://www.example.com/image.png"><!-- Major Browsers -->
<!--[if IE]><link rel="SHORTCUT ICON" href="http://www.example.com/alternateimage.ico"/><![endif]--><!-- Internet Explorer-->

How to print something to the console in Xcode?

You can also use breakpoints. Assuming the value you want is defined within the scope of your breakpoint you have 3 options:

print it in console doing:

po some_paramter

Bare in mind in objective-c for properties you can't use self.

po _someProperty
po self.someProperty // would not work

po stands for print object.


Or can just use Xcode 'Variable Views' . See the image enter image description here

I highly recommend seeing Debugging with Xcode from Apple


Or just hover over within your code. Like the image below.

enter image description here

jQuery: set selected value of dropdown list?

You need to select jQuery in the dropdown on the left and you have a syntax error because the $(document).ready should end with }); not )}; Check this link.

How do I get a platform-dependent new line character?

In addition to the line.separator property, if you are using java 1.5 or later and the String.format (or other formatting methods) you can use %n as in

Calendar c = ...;
String s = String.format("Duke's Birthday: %1$tm %1$te,%1$tY%n", c); 
//Note `%n` at end of line                                  ^^

String s2 = String.format("Use %%n as a platform independent newline.%n"); 
//         %% becomes %        ^^
//                                        and `%n` becomes newline   ^^

See the Java 1.8 API for Formatter for more details.

Exception: "URI formats are not supported"

     string ImagePath = "";

        HttpWebRequest request = (HttpWebRequest)WebRequest.Create(ImagePath);
        string a = "";
        try
        {
            HttpWebResponse response = (HttpWebResponse)request.GetResponse(); 
            Stream receiveStream = response.GetResponseStream();
            if (receiveStream.CanRead)
            { a = "OK"; }
        }

        catch { }

Alternative to iFrames with HTML5

No, there isn't an equivalent. The <iframe> element is still valid in HTML5. Depending on what exact interaction you need there might be different APIs. For example there's the postMessage method which allows you to achieve cross domain javascript interaction. But if you want to display cross domain HTML contents (styled with CSS and made interactive with javascript) iframe stays as a good way to do.

ASP.NET Background image

resize your background image in an image editor to the size you want related to your login box, which should help page loading and preserve image quality...

hard-size your DIV relative to your image

position your asp:login control where needed...

Add a new line to a text file in MS-DOS

echo "text to echo" > file.txt

Find unique lines

I find this easier.

sort -u input_filename > output_filename

-u stands for unique.

Access camera from a browser

As of 2017, WebKit announces support for WebRTC on Safari

Now you can access them with video and standard javascript WebRTC

E.g.

var video = document.createElement('video');
video.setAttribute('playsinline', '');
video.setAttribute('autoplay', '');
video.setAttribute('muted', '');
video.style.width = '200px';
video.style.height = '200px';

/* Setting up the constraint */
var facingMode = "user"; // Can be 'user' or 'environment' to access back or front camera (NEAT!)
var constraints = {
  audio: false,
  video: {
   facingMode: facingMode
  }
};

/* Stream it to video element */
navigator.mediaDevices.getUserMedia(constraints).then(function success(stream) {
  video.srcObject = stream;
});

Have a play with it.

How can I get the Windows last reboot reason

Take a look at the Event Log API. Case a) (bluescreen, user cut the power cord or system hang) causes a note ('system did not shutdown correctly' or something like that) to be left in the 'System' event log the next time the system is rebooted properly. You should be able to access it programmatically using the above API (honestly, I've never used it but it should work).

How to create a css rule for all elements except one class?

Wouldn't setting a css rule for all tables, and then a subsequent one for tables where class="dojoxGrid" work? Or am I missing something?

json Uncaught SyntaxError: Unexpected token :

That hex might need to be wrapped in quotes and made into a string. Javascript might not like the # character

Using command line arguments in VBscript

If you need direct access:

WScript.Arguments.Item(0)
WScript.Arguments.Item(1)
...

Read lines from a file into a Bash array

Latest revision based on comment from BinaryZebra's comment and tested here. The addition of command eval allows for the expression to be kept in the present execution environment while the expressions before are only held for the duration of the eval.

Use $IFS that has no spaces\tabs, just newlines/CR

$ IFS=$'\r\n' GLOBIGNORE='*' command eval  'XYZ=($(cat /etc/passwd))'
$ echo "${XYZ[5]}"
sync:x:5:0:sync:/sbin:/bin/sync

Also note that you may be setting the array just fine but reading it wrong - be sure to use both double-quotes "" and braces {} as in the example above


Edit:

Please note the many warnings about my answer in comments about possible glob expansion, specifically gniourf-gniourf's comments about my prior attempts to work around

With all those warnings in mind I'm still leaving this answer here (yes, bash 4 has been out for many years but I recall that some macs only 2/3 years old have pre-4 as default shell)

Other notes:

Can also follow drizzt's suggestion below and replace a forked subshell+cat with

$(</etc/passwd)

The other option I sometimes use is just set IFS into XIFS, then restore after. See also Sorpigal's answer which does not need to bother with this

How to center buttons in Twitter Bootstrap 3?

You can do it by giving margin or by positioning those elements absolutely.

For example

.button{
  margin:0px auto; //it will center them 
}

0px will be from top and bottom and auto will be from left and right.

What is the best way to generate a unique and short file name in Java

Why not use synchronized to process multi thread. here is my solution,It's can generate a short file name , and it's unique.

private static synchronized String generateFileName(){
    String name = make(index);
    index ++;
    return name;
}
private static String make(int index) {
    if(index == 0) return "";
    return String.valueOf(chars[index % chars.length]) + make(index / chars.length);
}
private static int index = 1;
private static char[] chars = {'a','b','c','d','e','f','g',
        'h','i','j','k','l','m','n',
        'o','p','q','r','s','t',
        'u','v','w','x','y','z'};

blew is main function for test , It's work.

public static void main(String[] args) {
    List<String> names = new ArrayList<>();
    List<Thread> threads = new ArrayList<>();
    for (int i = 0; i < 100; i++) {
        Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                for (int i = 0; i < 1000; i++) {
                    String name = generateFileName();
                    names.add(name);
                }
            }
        });
        thread.run();
        threads.add(thread);
    }

    for (int i = 0; i < 10; i++) {
        try {
            threads.get(i).join();
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }

    System.out.println(names);
    System.out.println(names.size());

}

react button onClick redirect page

With React Router v5.1:

import {useHistory} from 'react-router-dom';
import React, {Component} from 'react';
import {Button} from 'reactstrap';
.....
.....
export class yourComponent extends Component {
    .....
    componentDidMount() { 
        let history = useHistory;
        .......
    }

    render() {
        return(
        .....
        .....
            <Button className="fooBarClass" onClick={() => history.back()}>Back</Button>

        )
    }
}

How to resolve "must be an instance of string, string given" prior to PHP 7?

I got this error when invoking a function from a Laravel Controller to a PHP file.

After a couple of hours, I found the problem: I was using $this from within a static function.

When does Git refresh the list of remote branches?

The OP did not ask for cleanup for all remotes, rather for all branches of default remote.

So git fetch --prune is what should be used.

Setting git config remote.origin.prune true makes --prune automatic. In that case just git fetch will also prune stale remote branches from the local copy. See also Automatic prune with Git fetch or pull.

Note that this does not clean local branches that are no longer tracking a remote branch. See How to prune local tracking branches that do not exist on remote anymore for that.

How to pad zeroes to a string?

For the ones who came here to understand and not just a quick answer. I do these especially for time strings:

hour = 4
minute = 3
"{:0>2}:{:0>2}".format(hour,minute)
# prints 04:03

"{:0>3}:{:0>5}".format(hour,minute)
# prints '004:00003'

"{:0<3}:{:0<5}".format(hour,minute)
# prints '400:30000'

"{:$<3}:{:#<5}".format(hour,minute)
# prints '4$$:3####'

"0" symbols what to replace with the "2" padding characters, the default is an empty space

">" symbols allign all the 2 "0" character to the left of the string

":" symbols the format_spec

Fastest way to zero out a 2d array in C?

If you initialize the array with malloc, use calloc instead; it will zero your array for free. (Same perf obviously as memset, just less code for you.)

Static extension methods

specifically I want to overload Boolean.Parse to allow an int argument.

Would an extension for int work?

public static bool ToBoolean(this int source){
    // do it
    // return it
}

Then you can call it like this:

int x = 1;

bool y = x.ToBoolean();

Convert an integer to a byte array

What's wrong with converting it to a string?

[]byte(fmt.Sprintf("%d", myint))

Check if a string is a palindrome

 public static bool IsPalindrome(string value)
        {
            int i = 0;
            int j = value.Length - 1;
            while (true)
            {
                if (i > j)
                {
                    return true;
                }
                char a = value[i];
                char b = value[j];
                if (char.ToLower(a) != char.ToLower(b))
                {
                    return false;
                }
                i++;
                j--;
            }
        }

How to hide soft keyboard on android after clicking outside EditText?

The following snippet simply hides the keyboard:

public static void hideSoftKeyboard(Activity activity) {
    InputMethodManager inputMethodManager = 
        (InputMethodManager) activity.getSystemService(
            Activity.INPUT_METHOD_SERVICE);
    inputMethodManager.hideSoftInputFromWindow(
        activity.getCurrentFocus().getWindowToken(), 0);
}

You can put this up in a utility class, or if you are defining it within an activity, avoid the activity parameter, or call hideSoftKeyboard(this).

The trickiest part is when to call it. You can write a method that iterates through every View in your activity, and check if it is an instanceof EditText if it is not register a setOnTouchListener to that component and everything will fall in place. In case you are wondering how to do that, it is in fact quite simple. Here is what you do, you write a recursive method like the following, in fact you can use this to do anything, like setup custom typefaces etc... Here is the method

public void setupUI(View view) {

    // Set up touch listener for non-text box views to hide keyboard.
    if (!(view instanceof EditText)) {
        view.setOnTouchListener(new OnTouchListener() {
            public boolean onTouch(View v, MotionEvent event) {
                hideSoftKeyboard(MyActivity.this);
                return false;
            }
        });
    }

    //If a layout container, iterate over children and seed recursion.
    if (view instanceof ViewGroup) {
        for (int i = 0; i < ((ViewGroup) view).getChildCount(); i++) {
            View innerView = ((ViewGroup) view).getChildAt(i);
            setupUI(innerView);
        }
    }
}

That is all, just call this method after you setContentView in your activity. In case you are wondering what parameter you would pass, it is the id of the parent container. Assign an id to your parent container like

<RelativeLayoutPanel android:id="@+id/parent"> ... </RelativeLayout>

and call setupUI(findViewById(R.id.parent)), that is all.

If you want to use this effectively, you may create an extended Activity and put this method in, and make all other activities in your application extend this activity and call its setupUI() in the onCreate() method.

Hope it helps.

If you use more than 1 activity define common id to parent layout like <RelativeLayout android:id="@+id/main_parent"> ... </RelativeLayout>

Then extend a class from Activity and define setupUI(findViewById(R.id.main_parent)) Within its OnResume() and extend this class instead of ``Activityin your program


Here is a Kotlin version of the above function:

@file:JvmName("KeyboardUtils")

fun Activity.hideSoftKeyboard() {
    currentFocus?.let {
        val inputMethodManager = ContextCompat.getSystemService(this, InputMethodManager::class.java)!!
        inputMethodManager.hideSoftInputFromWindow(it.windowToken, 0)
    }
}

$(form).ajaxSubmit is not a function

Try:

$(document).ready(function() {
    $('#contact-form').validate({submitHandler: function(form) {
         var data = $('#contact-form').serialize();   
         $.post(
              'url_request',
               {data: data},
               function(response){
                  console.log(response);
               }
          );
         }
    });
});

Syntax behind sorted(key=lambda: ...)

lambda is a Python keyword that is used to generate anonymous functions.

>>> (lambda x: x+2)(3)
5

Removing input background colour for Chrome autocomplete?

try this for hide autofill style

input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:active,
input:-webkit-autofill:focus {
    background-color: #FFFFFF !important;
    color: #555 !important;
    -webkit-box-shadow: 0 0 0 1000px white inset !important;
    -webkit-text-fill-color: #555555 !important;
    }

Simple logical operators in Bash

Here is the code for the short version of if-then-else statement:

( [ $a -eq 1 ] || [ $b -eq 2 ] ) && echo "ok" || echo "nok"

Pay attention to the following:

  1. || and && operands inside if condition (i.e. between round parentheses) are logical operands (or/and)

  2. || and && operands outside if condition mean then/else

Practically the statement says:

if (a=1 or b=2) then "ok" else "nok"

The source was not found, but some or all event logs could not be searched

For me just worked iisreset (run cmd as administrator -> iisreset). Maybe somebody could give it a try.

How to add a line break within echo in PHP?

You may want to try \r\n for carriage return / line feed

Python socket connection timeout

For setting the Socket timeout, you need to follow these steps:

import socket
socks = socket.socket(socket.AF_INET, socket.SOCK_STREAM)
socks.settimeout(10.0) # settimeout is the attr of socks.

System.Drawing.Image to stream C#

public static Stream ToStream(this Image image)
{
     var stream = new MemoryStream();

     image.Save(stream, image.RawFormat);
     stream.Position = 0;

     return stream;
 }

How to send post request with x-www-form-urlencoded body

string urlParameters = "param1=value1&param2=value2";
string _endPointName = "your url post api";

var httpWebRequest = (HttpWebRequest)WebRequest.Create(_endPointName);

httpWebRequest.ContentType = "application/x-www-form-urlencoded";
httpWebRequest.Method = "POST";
httpWebRequest.Headers["ContentType"] = "application/x-www-form-urlencoded";

System.Net.ServicePointManager.ServerCertificateValidationCallback +=
                                                  (se, cert, chain, sslerror) =>
                                                  {
                                                      return true;
                                                  };


using (var streamWriter = new StreamWriter(httpWebRequest.GetRequestStream()))
                {
                    streamWriter.Write(urlParameters);
                    streamWriter.Flush();
                    streamWriter.Close();
                }
var httpResponse = (HttpWebResponse)httpWebRequest.GetResponse();

using (var streamReader = new StreamReader(httpResponse.GetResponseStream()))
                {
                    var result = streamReader.ReadToEnd();
                }

latex tabular width the same as the textwidth

The tabularx package gives you

  1. the total width as a first parameter, and
  2. a new column type X, all X columns will grow to fill up the total width.

For your example:

\usepackage{tabularx}
% ...    
\begin{document}
% ...

\begin{tabularx}{\textwidth}{|X|X|X|}
\hline
Input & Output& Action return \\
\hline
\hline
DNF &  simulation & jsp\\
\hline
\end{tabularx}

How to install python developer package?

yum install python-devel will work.

If yum doesn't work then use

apt-get install python-dev

List of ANSI color escape sequences

For these who don't get proper results other than mentioned languages, if you're using C# to print a text into console(terminal) window you should replace "\033" with "\x1b". In Visual Basic it would be Chrw(27).

Typescript empty object for a typed variable

If you declare an empty object literal and then assign values later on, then you can consider those values optional (may or may not be there), so just type them as optional with a question mark:

type User = {
    Username?: string;
    Email?: string;
}

How to enable CORS in AngularJs

we can enable CORS in the frontend by using the ngResourse module. But most importantly, we should have this piece of code while making the ajax request in the controller,

$scope.weatherAPI = $resource(YOUR API,
     {callback: "JSON_CALLBACK"}, {get: {method: 'JSONP'}});
 $scope.weatherResult = $scope.weatherAPI.get(YOUR REQUEST DATA, if any);

Also, you must add ngResourse CDN in the script part and add as a dependency in the app module.

<script src="https://code.angularjs.org/1.2.16/angular-resource.js"></script>

Then use "ngResourse" in the app module dependency section

var routerApp = angular.module("routerApp", ["ui.router", 'ngResource']);

Can't include C++ headers like vector in Android NDK

In android NDK go to android-ndk-r9b>/sources/cxx-stl/gnu-libstdc++/4.X/include in linux machines

I've found solution from the below link http://osdir.com/ml/android-ndk/2011-09/msg00336.html

How to generate xsd from wsdl

  1. Soap ui -> New SOAPUI project -> use wsdl to create a project (lets assume we have a testService in it)
  2. you will have a folder called TestService and then inside it there will be tokenTestServiceSoapBinding (example) -> right click on it
  3. Export definition -> give location where you need to place the definition.
  4. Exported location will have xsd and wsdl files. Hope this helps!

Detach (move) subdirectory into separate Git repository

Check out git_split project at https://github.com/vangorra/git_split

Turn git directories into their very own repositories in their own location. No subtree funny business. This script will take an existing directory in your git repository and turn that directory into an independent repository of its own. Along the way, it will copy over the entire change history for the directory you provided.

./git_split.sh <src_repo> <src_branch> <relative_dir_path> <dest_repo>
        src_repo  - The source repo to pull from.
        src_branch - The branch of the source repo to pull from. (usually master)
        relative_dir_path   - Relative path of the directory in the source repo to split.
        dest_repo - The repo to push to.

When to use RSpec let()?

In general, let() is a nicer syntax, and it saves you typing @name symbols all over the place. But, caveat emptor! I have found let() also introduces subtle bugs (or at least head scratching) because the variable doesn't really exist until you try to use it... Tell tale sign: if adding a puts after the let() to see that the variable is correct allows a spec to pass, but without the puts the spec fails -- you have found this subtlety.

I have also found that let() doesn't seem to cache in all circumstances! I wrote it up in my blog: http://technicaldebt.com/?p=1242

Maybe it is just me?

jquery: change the URL address without redirecting?

This is achieved through URL rewriting, not through URL obfuscating, which can't be done.

Another way to do this, as has been mentioned is by changing the hashtag, with

window.location.hash = "/2131/"

Converting a UNIX Timestamp to Formatted Date String

I found the information in this conversation so helpful that I just wanted to add how I figured it out by using the timestamp from my MySQL database and a little PHP

 <?= date("Y-m-d\TH:i:s\+01:00",strtotime($column['loggedin'])) ?>

The output was: 2017-03-03T08:22:36+01:00

Thanks very much Stewe you answer was a eureka for me.

Convert list of dictionaries to a pandas DataFrame

How do I convert a list of dictionaries to a pandas DataFrame?

The other answers are correct, but not much has been explained in terms of advantages and limitations of these methods. The aim of this post will be to show examples of these methods under different situations, discuss when to use (and when not to use), and suggest alternatives.


DataFrame(), DataFrame.from_records(), and .from_dict()

Depending on the structure and format of your data, there are situations where either all three methods work, or some work better than others, or some don't work at all.

Consider a very contrived example.

np.random.seed(0)
data = pd.DataFrame(
    np.random.choice(10, (3, 4)), columns=list('ABCD')).to_dict('r')

print(data)
[{'A': 5, 'B': 0, 'C': 3, 'D': 3},
 {'A': 7, 'B': 9, 'C': 3, 'D': 5},
 {'A': 2, 'B': 4, 'C': 7, 'D': 6}]

This list consists of "records" with every keys present. This is the simplest case you could encounter.

# The following methods all produce the same output.
pd.DataFrame(data)
pd.DataFrame.from_dict(data)
pd.DataFrame.from_records(data)

   A  B  C  D
0  5  0  3  3
1  7  9  3  5
2  2  4  7  6

Word on Dictionary Orientations: orient='index'/'columns'

Before continuing, it is important to make the distinction between the different types of dictionary orientations, and support with pandas. There are two primary types: "columns", and "index".

orient='columns'
Dictionaries with the "columns" orientation will have their keys correspond to columns in the equivalent DataFrame.

For example, data above is in the "columns" orient.

data_c = [
 {'A': 5, 'B': 0, 'C': 3, 'D': 3},
 {'A': 7, 'B': 9, 'C': 3, 'D': 5},
 {'A': 2, 'B': 4, 'C': 7, 'D': 6}]
pd.DataFrame.from_dict(data_c, orient='columns')

   A  B  C  D
0  5  0  3  3
1  7  9  3  5
2  2  4  7  6

Note: If you are using pd.DataFrame.from_records, the orientation is assumed to be "columns" (you cannot specify otherwise), and the dictionaries will be loaded accordingly.

orient='index'
With this orient, keys are assumed to correspond to index values. This kind of data is best suited for pd.DataFrame.from_dict.

data_i ={
 0: {'A': 5, 'B': 0, 'C': 3, 'D': 3},
 1: {'A': 7, 'B': 9, 'C': 3, 'D': 5},
 2: {'A': 2, 'B': 4, 'C': 7, 'D': 6}}
pd.DataFrame.from_dict(data_i, orient='index')

   A  B  C  D
0  5  0  3  3
1  7  9  3  5
2  2  4  7  6

This case is not considered in the OP, but is still useful to know.

Setting Custom Index

If you need a custom index on the resultant DataFrame, you can set it using the index=... argument.

pd.DataFrame(data, index=['a', 'b', 'c'])
# pd.DataFrame.from_records(data, index=['a', 'b', 'c'])

   A  B  C  D
a  5  0  3  3
b  7  9  3  5
c  2  4  7  6

This is not supported by pd.DataFrame.from_dict.

Dealing with Missing Keys/Columns

All methods work out-of-the-box when handling dictionaries with missing keys/column values. For example,

data2 = [
     {'A': 5, 'C': 3, 'D': 3},
     {'A': 7, 'B': 9, 'F': 5},
     {'B': 4, 'C': 7, 'E': 6}]
# The methods below all produce the same output.
pd.DataFrame(data2)
pd.DataFrame.from_dict(data2)
pd.DataFrame.from_records(data2)

     A    B    C    D    E    F
0  5.0  NaN  3.0  3.0  NaN  NaN
1  7.0  9.0  NaN  NaN  NaN  5.0
2  NaN  4.0  7.0  NaN  6.0  NaN

Reading Subset of Columns

"What if I don't want to read in every single column"? You can easily specify this using the columns=... parameter.

For example, from the example dictionary of data2 above, if you wanted to read only columns "A', 'D', and 'F', you can do so by passing a list:

pd.DataFrame(data2, columns=['A', 'D', 'F'])
# pd.DataFrame.from_records(data2, columns=['A', 'D', 'F'])

     A    D    F
0  5.0  3.0  NaN
1  7.0  NaN  5.0
2  NaN  NaN  NaN

This is not supported by pd.DataFrame.from_dict with the default orient "columns".

pd.DataFrame.from_dict(data2, orient='columns', columns=['A', 'B'])
ValueError: cannot use columns parameter with orient='columns'

Reading Subset of Rows

Not supported by any of these methods directly. You will have to iterate over your data and perform a reverse delete in-place as you iterate. For example, to extract only the 0th and 2nd rows from data2 above, you can use:

rows_to_select = {0, 2}
for i in reversed(range(len(data2))):
    if i not in rows_to_select:
        del data2[i]

pd.DataFrame(data2)
# pd.DataFrame.from_dict(data2)
# pd.DataFrame.from_records(data2)

     A    B  C    D    E
0  5.0  NaN  3  3.0  NaN
1  NaN  4.0  7  NaN  6.0

The Panacea: json_normalize for Nested Data

A strong, robust alternative to the methods outlined above is the json_normalize function which works with lists of dictionaries (records), and in addition can also handle nested dictionaries.

pd.json_normalize(data)

   A  B  C  D
0  5  0  3  3
1  7  9  3  5
2  2  4  7  6
pd.json_normalize(data2)

     A    B  C    D    E
0  5.0  NaN  3  3.0  NaN
1  NaN  4.0  7  NaN  6.0

Again, keep in mind that the data passed to json_normalize needs to be in the list-of-dictionaries (records) format.

As mentioned, json_normalize can also handle nested dictionaries. Here's an example taken from the documentation.

data_nested = [
  {'counties': [{'name': 'Dade', 'population': 12345},
                {'name': 'Broward', 'population': 40000},
                {'name': 'Palm Beach', 'population': 60000}],
   'info': {'governor': 'Rick Scott'},
   'shortname': 'FL',
   'state': 'Florida'},
  {'counties': [{'name': 'Summit', 'population': 1234},
                {'name': 'Cuyahoga', 'population': 1337}],
   'info': {'governor': 'John Kasich'},
   'shortname': 'OH',
   'state': 'Ohio'}
]
pd.json_normalize(data_nested, 
                          record_path='counties', 
                          meta=['state', 'shortname', ['info', 'governor']])

         name  population    state shortname info.governor
0        Dade       12345  Florida        FL    Rick Scott
1     Broward       40000  Florida        FL    Rick Scott
2  Palm Beach       60000  Florida        FL    Rick Scott
3      Summit        1234     Ohio        OH   John Kasich
4    Cuyahoga        1337     Ohio        OH   John Kasich

For more information on the meta and record_path arguments, check out the documentation.


Summarising

Here's a table of all the methods discussed above, along with supported features/functionality.

enter image description here

* Use orient='columns' and then transpose to get the same effect as orient='index'.

What is 'PermSize' in Java?

The permament pool contains everything that is not your application data, but rather things required for the VM: typically it contains interned strings, the byte code of defined classes, but also other "not yours" pieces of data.

Open file by its full path in C++

Normally one uses the backslash character as the path separator in Windows. So:

ifstream file;
file.open("C:\\Demo.txt", ios::in);

Keep in mind that when written in C++ source code, you must use the double backslash because the backslash character itself means something special inside double quoted strings. So the above refers to the file C:\Demo.txt.