Programs & Examples On #Live preview

How to create a file in a directory in java?

Use:

File f = new File("C:\\a\\b\\test.txt");
f.mkdirs();
f.createNewFile();

Notice I changed the forward slashes to double back slashes for paths in Windows File System. This will create an empty file on the given path.

AngularJS: How do I manually set input to $valid in controller?

It is very simple. For example : in you JS controller use this:

$scope.inputngmodel.$valid = false;

or

$scope.inputngmodel.$invalid = true;

or

$scope.formname.inputngmodel.$valid = false;

or

$scope.formname.inputngmodel.$invalid = true;

All works for me for different requirement. Hit up if this solve your problem.

A field initializer cannot reference the nonstatic field, method, or property

You need to put that code into the constructor of your class:

private Reminders reminder = new Reminders();
private dynamic defaultReminder;

public YourClass()
{
    defaultReminder = reminder.TimeSpanText[TimeSpan.FromMinutes(15)];
}

The reason is that you can't use one instance variable to initialize another one using a field initializer.

Twitter Bootstrap alert message close and open again

Data-dismiss completely removes the element. Use jQuery's .hide() method instead.

The fix-it-quick method:

Using inline javascript to hide the element onclick like this:

<div class="alert" style="display: none"> 
    <a class="close" onclick="$('.alert').hide()">×</a>  
    <strong>Warning!</strong> Best check yo self, you're not looking too good.  
</div>

<a href="#" onclick="$('alert').show()">show</a>

http://jsfiddle.net/cQNFL/

This should however only be used if you are lazy (which is no good thing if you want an maintainable app).

The do-it-right method:

Create a new data attribute for hiding an element.

Javascript:

$(function(){
    $("[data-hide]").on("click", function(){
        $("." + $(this).attr("data-hide")).hide()
        // -or-, see below
        // $(this).closest("." + $(this).attr("data-hide")).hide()
    })
})

and then change data-dismiss to data-hide in the markup. Example at jsfiddle.

$("." + $(this).attr("data-hide")).hide()

This will hide all elements with the class specified in data-hide, i.e: data-hide="alert" will hide all elements with the alert class.

Xeon06 provided an alternative solution:

$(this).closest("." + $(this).attr("data-hide")).hide()

This will only hide the closest parent element. This is very useful if you don't want to give each alert a unique class. Please note that, however, you need to place the close button within the alert.

Definition of .closest from jquery doc:

For each element in the set, get the first element that matches the selector by testing the element itself and traversing up through its ancestors in the DOM tree.

How to start MySQL server on windows xp

Type

C:\> "C:\Program Files\MySQL\MySQL Server 5.1\bin\mysqld" --console

to start the sql server and then test the client connection.

How (and why) to use display: table-cell (CSS)

After days trying to find the answer, I finally found

display: table;

There was surprisingly very little information available online about how to actually getting it to work, even here, so on to the "How":

To use this fantastic piece of code, you need to think back to when tables were the only real way to structure HTML, namely the syntax. To get a table with 2 rows and 3 columns, you'd have to do the following:

<table>
    <tr>
        <td></td>
        <td></td>
        <td></td>
    </tr>
    <tr>
        <td></td>
        <td></td>
        <td></td>
    </tr>
</table>

Similarly to get CSS to do it, you'd use the following:

HTML

<div id="table">
    <div class="tr">
        <div class="td"></div>
        <div class="td"></div>
        <div class="td"></div>
    </div>
    <div class="tr">
        <div class="td"></div>
        <div class="td"></div>
        <div class="td"></div>
    </div>
</div>

CSS

#table{ 
    display: table; 
}
.tr{ 
    display: table-row; 
}
.td{ 
    display: table-cell; }

As you can see in the JSFiddle example below, the divs in the 3rd column have no content, yet are respecting the auto height set by the text in the first 2 columns. WIN!

http://jsfiddle.net/blyzz/1djs97yv/1/

It's worth noting that display: table; does not work in IE6 or 7 (thanks, FelipeAls), so depending on your needs with regards to browser compatibility, this may not be the answer that you are seeking.

How to draw a checkmark / tick using CSS?

Also, using the awesome font, you can use the following tag. Simple and beautiful

With the possibility of changing the size and color and other features in CSS

See result here

Can I connect to SQL Server using Windows Authentication from Java EE webapp?

I was having issue with connecting to MS SQL 2005 using Windows Authentication. I was able to solve the issue with help from this and other forums. Here is what I did:

  1. Install the JTDS driver
  2. Do not use the "domain= " property in the jdbc:jtds:://[:][/][;=[;...]] string
  3. Install the ntlmauth.dll in c:\windows\system32 directory (registration of the dll was not required) on the web server machine.
  4. Change the logon identity for the Apache Tomcat service to a domain User with access to the SQL database server (it was not necessary for the user to have access to the dbo.master).

My environment: Windows XP clinet hosting Apache Tomcat 6 with MS SQL 2005 backend on Windows 2003

How to call a method defined in an AngularJS directive?

You can specify a DOM attribute that can be used to allow the directive to define a function on the parent scope. The parent scope can then call this method like any other. Here's a plunker. And below is the relevant code.

clearfn is an attribute on the directive element into which the parent scope can pass a scope property which the directive can then set to a function that accomplish's the desired behavior.

<!DOCTYPE html>
<html ng-app="myapp">
  <head>
    <script data-require="angular.js@*" data-semver="1.3.0-beta.5" src="https://code.angularjs.org/1.3.0-beta.5/angular.js"></script>
    <link rel="stylesheet" href="style.css" />
    <style>
      my-box{
        display:block;
        border:solid 1px #aaa;
        min-width:50px;
        min-height:50px;
        padding:.5em;
        margin:1em;
        outline:0px;
        box-shadow:inset 0px 0px .4em #aaa;
      }
    </style>
  </head>
  <body ng-controller="mycontroller">
    <h1>Call method on directive</h1>
    <button ng-click="clear()">Clear</button>
    <my-box clearfn="clear" contentEditable=true></my-box>
    <script>
      var app = angular.module('myapp', []);
      app.controller('mycontroller', function($scope){
      });
      app.directive('myBox', function(){
        return {
          restrict: 'E',
          scope: {
            clearFn: '=clearfn'
          },
          template: '',
          link: function(scope, element, attrs){
            element.html('Hello World!');
            scope.clearFn = function(){
              element.html('');
            };
          }
        }
      });
    </script>
  </body>
</html>

How to overwrite existing files in batch?

If destination file is read only use /y/r

xcopy /y/r source.txt dest.txt

Scope 'session' is not active for the current thread; IllegalStateException: No thread-bound request found

If anyone else stuck on same point, following solved my problem.

In web.xml

 <listener>
            <listener-class>
                    org.springframework.web.context.request.RequestContextListener 
            </listener-class>
  </listener>

In Session component

@Component
@Scope(value = "session",  proxyMode = ScopedProxyMode.TARGET_CLASS)

In pom.xml

    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib</artifactId>
        <version>3.1</version>
    </dependency>

Attempt by security transparent method 'WebMatrix.WebData.PreApplicationStartCode.Start()'

You may also get :

Could not load file or assembly 'WebMatrix.Data, Version=3.0.0.0, Culture=neutral, PublicKeyToken=31bf3856ad364e35' or one of its dependencies. The located assembly's manifest definition does not match the assembly reference. (Exception from HRESULT: 0x80131040)

This has moved to this package

 Install-Package Microsoft.AspNet.WebPages.Data

You should probably do a clean build before attempting any of the answers to this question and after updating packages

"Could not find or load main class" Error while running java program using cmd prompt

Create a folder org/tij/exercises and then move HelloWorld.java file. Then run below command

javac -cp . org/tij/exercises/HelloWorld.java

AND

java -cp . org/tij/exercises/HelloWorld

Regular expressions in C: examples?

While the answer above is good, I recommend using PCRE2. This means you can literally use all the regex examples out there now and not have to translate from some ancient regex.

I made an answer for this already, but I think it can help here too..

Regex In C To Search For Credit Card Numbers

// YOU MUST SPECIFY THE UNIT WIDTH BEFORE THE INCLUDE OF THE pcre.h

#define PCRE2_CODE_UNIT_WIDTH 8
#include <stdio.h>
#include <string.h>
#include <pcre2.h>
#include <stdbool.h>

int main(){

bool Debug = true;
bool Found = false;
pcre2_code *re;
PCRE2_SPTR pattern;
PCRE2_SPTR subject;
int errornumber;
int i;
int rc;
PCRE2_SIZE erroroffset;
PCRE2_SIZE *ovector;
size_t subject_length;
pcre2_match_data *match_data;


char * RegexStr = "(?:\\D|^)(5[1-5][0-9]{2}(?:\\ |\\-|)[0-9]{4}(?:\\ |\\-|)[0-9]{4}(?:\\ |\\-|)[0-9]{4})(?:\\D|$)";
char * source = "5111 2222 3333 4444";

pattern = (PCRE2_SPTR)RegexStr;// <<<<< This is where you pass your REGEX 
subject = (PCRE2_SPTR)source;// <<<<< This is where you pass your bufer that will be checked. 
subject_length = strlen((char *)subject);




  re = pcre2_compile(
  pattern,               /* the pattern */
  PCRE2_ZERO_TERMINATED, /* indicates pattern is zero-terminated */
  0,                     /* default options */
  &errornumber,          /* for error number */
  &erroroffset,          /* for error offset */
  NULL);                 /* use default compile context */

/* Compilation failed: print the error message and exit. */
if (re == NULL)
  {
  PCRE2_UCHAR buffer[256];
  pcre2_get_error_message(errornumber, buffer, sizeof(buffer));
  printf("PCRE2 compilation failed at offset %d: %s\n", (int)erroroffset,buffer);
  return 1;
  }


match_data = pcre2_match_data_create_from_pattern(re, NULL);

rc = pcre2_match(
  re,
  subject,              /* the subject string */
  subject_length,       /* the length of the subject */
  0,                    /* start at offset 0 in the subject */
  0,                    /* default options */
  match_data,           /* block for storing the result */
  NULL);

if (rc < 0)
  {
  switch(rc)
    {
    case PCRE2_ERROR_NOMATCH: //printf("No match\n"); //
    pcre2_match_data_free(match_data);
    pcre2_code_free(re);
    Found = 0;
    return Found;
    //  break;
    /*
    Handle other special cases if you like
    */
    default: printf("Matching error %d\n", rc); //break;
    }
  pcre2_match_data_free(match_data);   /* Release memory used for the match */
  pcre2_code_free(re);
  Found = 0;                /* data and the compiled pattern. */
  return Found;
  }


if (Debug){
ovector = pcre2_get_ovector_pointer(match_data);
printf("Match succeeded at offset %d\n", (int)ovector[0]);

if (rc == 0)
  printf("ovector was not big enough for all the captured substrings\n");


if (ovector[0] > ovector[1])
  {
  printf("\\K was used in an assertion to set the match start after its end.\n"
    "From end to start the match was: %.*s\n", (int)(ovector[0] - ovector[1]),
      (char *)(subject + ovector[1]));
  printf("Run abandoned\n");
  pcre2_match_data_free(match_data);
  pcre2_code_free(re);
  return 0;
}

for (i = 0; i < rc; i++)
  {
  PCRE2_SPTR substring_start = subject + ovector[2*i];
  size_t substring_length = ovector[2*i+1] - ovector[2*i];
  printf("%2d: %.*s\n", i, (int)substring_length, (char *)substring_start);
  }
}

else{
  if(rc > 0){
    Found = true;

    } 
} 
pcre2_match_data_free(match_data);
pcre2_code_free(re);
return Found;

}

Install PCRE using:

wget https://ftp.pcre.org/pub/pcre/pcre2-10.31.zip
make 
sudo make install 
sudo ldconfig

Compile using :

gcc foo.c -lpcre2-8 -o foo

Check my answer for more details.

Select current element in jQuery

Fortunately, jQuery selectors allow you much more freedom:

$("div a").click( function(event)
{
   var clicked = $(this); // jQuery wrapper for clicked element
   // ... click-specific code goes here ...
});

...will attach the specified callback to each <a> contained in a <div>.

iOS 7 - Failing to instantiate default view controller

If you added new storyboard then you have to check following points.

1) In your plist file check value of Main storyboard file base name (iPad) or (iPhone) should be matched with your storyboard file name (do not add extension .storyboard)

2) In storyboard there should be one view controller which set as Is initial view controller

3) Clean and build your project. :)

enter image description here

Cycles in an Undirected Graph

By the way, if you happen to know that it is connected, then simply it is a tree (thus no cycles) if and only if |E|=|V|-1. Of course that's not a small amount of information :)

HTML5 Video // Completely Hide Controls

document.addEventListener("DOMContentLoaded", function() { initialiseMediaPlayer(); }, false);


function initialiseMediaPlayer() {

    mediaPlayer = document.getElementById('media-video');

    mediaPlayer.controls = false;

    mediaPlayer.addEventListener('volumechange', function(e) { 
        // Update the button to be mute/unmute
        if (mediaPlayer.muted) changeButtonType(muteBtn, 'unmute');
        else changeButtonType(muteBtn, 'mute');
    }, false);  
    mediaPlayer.addEventListener('ended', function() { this.pause(); }, false); 
}

How to change the current URL in javascript?

This is more robust:

mi = location.href.split(/(\d+)/);
no = mi.length - 2;
os = mi[no];
mi[no]++;
if ((mi[no] + '').length < os.length) mi[no] = os.match(/0+/) + mi[no];
location.href = mi.join('');

When the URL has multiple numbers, it will change the last one:

http://mywebsite.com/8815/1.html

It supports numbers with leading zeros:

http://mywebsite.com/0001.html

Example

How can I get customer details from an order in WooCommerce?

I just dealt with this. Depending on what you really want, you can get the details from the order like this:

$field = get_post_meta($order->id, $field_name, true);

Where $field_name is '_billing_address_1' or '_shipping_address_1'or 'first_name'. You can google the other fields, but don't forget the "" at the beginning.

If you want to retrieve the customer for this order, and get its field directly, it works as in your solution, except you do not need to retrieve the full customer object:

$customer_id = (int)$order->user_id;

$field = get_user_meta($customer_id, $field_name, true);

Now in this case, the $field_name does not start with "_". For example: 'first_name' and 'billing_address_1'.

Drop shadow on a div container?

you might want to try this. Seems to be pretty easy and works on IE6 and Moz atleast.

<div id ="show" style="background-color:Silver;width:100px;height:100px;visibility:visible;border-bottom:outset 1px black;border-right:outset 1px black;" ></div>

The general syntax is : border-[postion]:[border-style] [border-width] [border-color] | inherit

The list of available [border-style]s are :

  • dashed
  • dotted
  • double
  • groove
  • hidden
  • inset
  • none
  • outset
  • ridge
  • solid
  • inherit

How to select specific columns in laravel eloquent

To get the result of specific column from table,we have to specify the column name.

Use following code : -

   $result = DB::Table('table_name')->select('column1','column2')->where('id',1)->get();  

for example -

$result = DB::Table('Student')->select('subject','class')->where('id',1)->get();  

WARNING: API 'variant.getJavaCompile()' is obsolete and has been replaced with 'variant.getJavaCompileProvider()'

Downgrading the version of Gradle worked for me:

classpath 'com.android.tools.build:gradle:3.2.0'

Javascript format date / time

For the date part:(month is 0-indexed while days are 1-indexed)

var date = new Date('2014-8-20');
console.log((date.getMonth()+1) + '/' + date.getDate() + '/' +  date.getFullYear());

for the time you'll want to create a function to test different situations and convert.

CFLAGS vs CPPFLAGS

The CPPFLAGS macro is the one to use to specify #include directories.

Both CPPFLAGS and CFLAGS work in your case because the make(1) rule combines both preprocessing and compiling in one command (so both macros are used in the command).

You don't need to specify . as an include-directory if you use the form #include "...". You also don't need to specify the standard compiler include directory. You do need to specify all other include-directories.

What is a classpath and how do I set it?

Think of it as Java's answer to the PATH environment variable - OSes search for EXEs on the PATH, Java searches for classes and packages on the classpath.

How to use Select2 with JSON via Ajax request?

Here I give you my example which contain --> Country flag, City, State, Country.

Here is my output.

enter image description here

Attach these two Cdn js or links.

<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/css/select2.min.css" rel="stylesheet" />
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.10/js/select2.min.js"></script>

js script

//for apend flag of country.

function formatState (state) {
    console.log(state);
    if (!state.id) {
      return state.text;
    }
    var baseUrl = "admin/images/flags";
    var $state = $(
      '<span><img src="'+baseUrl+ '/' + state.contryflage.toLowerCase() + '.png"  class="img-flag" /> ' +state.text+ '</span>'
    );
    return $state;
  };


$(function(){
    $("#itemSearch").select2({
    minimumInputLength: 2,
    templateResult: formatState, //this is for append country flag.
    ajax: {
        url: URL,
        dataType: 'json',
        type: "POST",
        data: function (term) {
            return {
                term: term
            };
        },
        processResults: function (data) {
            return {
                results: $.map(data, function (item) {
                    return {
                        text: item.name+', '+item.state.name+', '+item.state.coutry.name,
                        id: item.id,
                        contryflage:item.state.coutry.sortname
                    }
                })
            };
        }

    }
});

Expected JSON response.

[
   {
      "id":7570,
      "name":"Brussels",
      "state":{
         "name":"Brabant",
         "coutry":{
            "sortname":"BE",
            "name":"Belgium",

         }
      }
   },
   {
      "id":7575,
      "name":"Brussels",
      "state":{
         "name":"Brabant Wallon",
         "coutry":{
            "sortname":"BE",
            "name":"Belgium",

         }
      }
   },
   {
      "id":7578,
      "name":"Brussel",
      "state":{
         "name":"Brussel",
         "coutry":{
            "sortname":"BE",
            "name":"Belgium",

         }
      }
   },

]

How to sort an array of associative arrays by value of a given key in PHP?

Since your array elements are arrays themselves with string keys, your best bet is to define a custom comparison function. It's pretty quick and easy to do. Try this:

function invenDescSort($item1,$item2)
{
    if ($item1['price'] == $item2['price']) return 0;
    return ($item1['price'] < $item2['price']) ? 1 : -1;
}
usort($inventory,'invenDescSort');
print_r($inventory);

Produces the following:

Array
(
    [0] => Array
        (
            [type] => pork
            [price] => 5.43
        )

    [1] => Array
        (
            [type] => fruit
            [price] => 3.5
        )

    [2] => Array
        (
            [type] => milk
            [price] => 2.9
        )

)

Deserializing JSON Object Array with Json.net

You can create a new model to Deserialize your Json CustomerJson:

public class CustomerJson
{
    [JsonProperty("customer")]
    public Customer Customer { get; set; }
}

public class Customer
{
    [JsonProperty("first_name")]
    public string Firstname { get; set; }

    [JsonProperty("last_name")]
    public string Lastname { get; set; }

    ...
}

And you can deserialize your json easily :

JsonConvert.DeserializeObject<List<CustomerJson>>(json);

Hope it helps !

Documentation: Serializing and Deserializing JSON

How to write a basic swap function in Java

public class swaptemp {
    public static void main(String[] args) {
        String s1="10";
        String s2="20";
        String temp;
        System.out.println(s1);
        System.out.println(s2);

        temp=Integer.toString(Integer.parseInt(s1));
        s1=Integer.toString(Integer.parseInt(s2));
        s2=Integer.toString(Integer.parseInt(temp));

        System.out.println(s1);
        System.out.println(s2);
    }
}

How do I find duplicates across multiple columns?

 SELECT name, city, count(*) as qty 
 FROM stuff 
 GROUP BY name, city HAVING count(*)> 1

How can I reference a dll in the GAC from Visual Studio?

In VS, right click your project, select "Add Reference...", and you will see all the namespaces that exist in your GAC. Choose Microsoft.SqlServer.Management.RegisteredServers and click OK, and you should be good to go

EDIT:

That is the way you want to do this most of the time. However, after a bit of poking around I found this issue on MS Connect. MS says it is a known deployment issue, and they don't have a work around. The guy says if he copies the dll from the GAC folder and drops it in his bin, it works.

Using psql how do I list extensions installed in a database?

Additionally if you want to know which extensions are available on your server: SELECT * FROM pg_available_extensions

The ScriptManager must appear before any controls that need it

You can add your Script Manager tags just below the <Form> tag of your page. Here is how you can place your Script Manager tag.

    <asp:ScriptManager ID="ScriptManager1" runat="server">
    </asp:ScriptManager>

If you are using Master Pages, its recommended to use your Script Manager in your Master page so that you do not have to write it again and again on every page that contains AJAX controls.

How to add parameters to an external data query in Excel which can't be displayed graphically?

Excel's interface for SQL Server queries will not let you have a custom parameters.  A way around this is to create a generic Microsoft Query, then add parameters, then paste your parametorized query in the connection's properties.  Here are the detailed steps for Excel 2010:

  1. Open Excel
  2. Goto Data tab
  3. From the From Other Sources button choose From Microsoft Query
  4. The "Choose Data Source" window will appear.  Choose a datasource and click OK.
  5. The Query Qizard
    1. Choose Column: window will appear.  The goal is to create a generic query. I recommend choosing one column from a small table.
    2. Filter Data: Just click Next
    3. Sort Order: Just click Next
    4. Finish: Just click Finish.
  6. The "Import Data" window will appear:
    1. Click the Properties... button.
      1. Choose the Definition tab
      2. In the "Command text:" section add a WHERE clause that includes Excel parameters.  It's important to add all the parameters that you want now.  For example, if I want two parameters I could add this:
        WHERE 1 = ? and 2 = ?
      3. Click OK to get back to the "Import Data" window
    2. Choose PivotTable Report
    3. Click OK
  7. You will be prompted to enter the parameters value for each parameter.
  8. Once you have enter the parameters you will be at your pivot table
  9. Go batck to the Data tab and click the connections Properties button
    1. Click the Definition tab
    2. In the "Command text:" section, Paste in the real SQL Query that you want with the same number of parameters that you defined earlier.
    3. Click the Parameters... button 
      1. enter the Prompt values for each parameter
      2. Click OK
    4. Click OK to close the properties window
  10. Congratulations, you now have parameters.

Apple Mach-O Linker Error when compiling for device

I fixed it by changing Mach-O Type under linking section on the Build settings from Nothing to Executable.

Format SQL in SQL Server Management Studio

There is a special trick I discovered by accident.

  1. Select the query you wish to format.
  2. Ctrl+Shift+Q (This will open your query in the query designer)
  3. Then just go OK Voila! Query designer will format your query for you. Caveat is that you can only do this for statements and not procedural code, but its better than nothing.

Normalize numpy array columns in python

If I understand correctly, what you want to do is divide by the maximum value in each column. You can do this easily using broadcasting.

Starting with your example array:

import numpy as np

x = np.array([[1000,  10,   0.5],
              [ 765,   5,  0.35],
              [ 800,   7,  0.09]])

x_normed = x / x.max(axis=0)

print(x_normed)
# [[ 1.     1.     1.   ]
#  [ 0.765  0.5    0.7  ]
#  [ 0.8    0.7    0.18 ]]

x.max(0) takes the maximum over the 0th dimension (i.e. rows). This gives you a vector of size (ncols,) containing the maximum value in each column. You can then divide x by this vector in order to normalize your values such that the maximum value in each column will be scaled to 1.


If x contains negative values you would need to subtract the minimum first:

x_normed = (x - x.min(0)) / x.ptp(0)

Here, x.ptp(0) returns the "peak-to-peak" (i.e. the range, max - min) along axis 0. This normalization also guarantees that the minimum value in each column will be 0.

How to add a vertical Separator?

From http://social.msdn.microsoft.com/Forums/vstudio/en-US/12ead5d4-1d57-4dbb-ba81-bc13084ba370/how-can-i-add-a-line-as-a-visual-separator-to-the-content-control-like-grid?forum=wpf:

Try this example and see if it fits your needs, there are three main aspects to it.

  1. Line.Stretch is set to fill.

  2. For horizontal lines the VerticalAlignment of the line is set Bottom, and for VerticalLines the HorizontalAlignment is set to Right.

  3. We then need to tell the line how many rows or columns to span, this is done by binding to either RowDefinitions or ColumnDefintions count property.



        <Style x:Key="horizontalLineStyle" TargetType="Line" BasedOn="{StaticResource lineStyle}">  
            <Setter Property="X2" Value="1" /> 
            <Setter Property="VerticalAlignment" Value="Bottom" /> 
            <Setter Property="Grid.ColumnSpan" 
                    Value="{Binding   
                                Path=ColumnDefinitions.Count,  
                                RelativeSource={RelativeSource AncestorType=Grid}}"/> 
        </Style> 
    
        <Style x:Key="verticalLineStyle" TargetType="Line" BasedOn="{StaticResource lineStyle}">  
            <Setter Property="Y2" Value="1" /> 
            <Setter Property="HorizontalAlignment" Value="Right" /> 
            <Setter Property="Grid.RowSpan"   
                    Value="{Binding   
                                Path=RowDefinitions.Count,  
                                RelativeSource={RelativeSource AncestorType=Grid}}"/> 
        </Style> 
    </Grid.Resources>        
    
    <Grid.RowDefinitions> 
        <RowDefinition Height="20"/>  
        <RowDefinition Height="20"/>  
        <RowDefinition Height="20"/>  
        <RowDefinition Height="20"/>  
    </Grid.RowDefinitions> 
    
    <Grid.ColumnDefinitions> 
        <ColumnDefinition Width="20"/>  
        <ColumnDefinition Width="20"/>  
        <ColumnDefinition Width="20"/>  
        <ColumnDefinition Width="20"/>  
    </Grid.ColumnDefinitions> 
    
    <Line Grid.Column="0" Style="{StaticResource verticalLineStyle}"/>  
    <Line Grid.Column="1" Style="{StaticResource verticalLineStyle}"/>  
    <Line Grid.Column="2" Style="{StaticResource verticalLineStyle}"/>  
    <Line Grid.Column="3" Style="{StaticResource verticalLineStyle}"/>  
    
    <Line Grid.Row="0" Style="{StaticResource horizontalLineStyle}"/>  
    <Line Grid.Row="1" Style="{StaticResource horizontalLineStyle}"/>  
    <Line Grid.Row="2" Style="{StaticResource horizontalLineStyle}"/>  
    <Line Grid.Row="3" Style="{StaticResource horizontalLineStyle}"/>  
    

How to get back Lost phpMyAdmin Password, XAMPP

Unless you have changed your password the default setting dont require you to enter a password to connect to the MYSQL server, try:

mysql_connect('localhost','root','');

if not then you can export your databases to a external file, just follow these instructions.

http://dev.mysql.com/doc/refman/5.0/en/innodb-backup.html

if you are unable to access phpMyAdmin then try,

http://www.simplehelp.net/2008/11/26/how-to-reset-a-lost-mysql-root-password/

How to return a string from a C++ function?

string str1, str2, str3;

cout << "These are the strings: " << endl;
cout << "str1: \"the dog jumped over the fence\"" << endl;
cout << "str2: \"the\"" << endl;
cout << "str3: \"that\"" << endl << endl;

From this, I see that you have not initialized str1, str2, or str3 to contain the values that you are printing. I might suggest doing so first:

string str1 = "the dog jumped over the fence", 
       str2 = "the",
       str3 = "that";

cout << "These are the strings: " << endl;
cout << "str1: \"" << str1 << "\"" << endl;
cout << "str2: \"" << str2 << "\"" << endl;
cout << "str3: \"" << str3 << "\"" << endl << endl;

What is the `data-target` attribute in Bootstrap 3?

data-target is used by bootstrap to make your life easier. You (mostly) do not need to write a single line of Javascript to use their pre-made JavaScript components.

The data-target attribute should contain a CSS selector that points to the HTML Element that will be changed.

Modal Example Code from BS3:

<!-- Button trigger modal -->
<button class="btn btn-primary btn-lg" data-toggle="modal" data-target="#myModal">
  Launch demo modal
</button>

<!-- Modal -->
<div class="modal fade" id="myModal" tabindex="-1" role="dialog" aria-labelledby="myModalLabel" aria-hidden="true">
  [...]
</div>

In this example, the button has data-target="#myModal", if you click on it, <div id="myModal">...</div> will be modified (in this case faded in). This happens because #myModal in CSS selectors points to elements that have an id attribute with the myModal value.

Further information about the HTML5 "data-" attribute: https://developer.mozilla.org/en-US/docs/Web/Guide/HTML/Using_data_attributes

Calculate time difference in minutes in SQL Server

Try this..

select starttime,endtime, case
  when DATEDIFF(minute,starttime,endtime) < 60  then DATEDIFF(minute,starttime,endtime) 
  when DATEDIFF(minute,starttime,endtime) >= 60
  then '60,'+ cast( (cast(DATEDIFF(minute,starttime,endtime) as int )-60) as nvarchar(50) )
end from TestTable123416

All You need is DateDiff..

List of All Folders and Sub-folders

You can use find

find . -type d > output.txt

or tree

tree -d > output.txt

tree, If not installed on your system.

If you are using ubuntu

sudo apt-get install tree

If you are using mac os.

brew install tree

scrollIntoView Scrolls just too far

You can also use the element.scrollIntoView() options

el.scrollIntoView(
  { 
    behavior: 'smooth', 
    block: 'start' 
  },
);

which most browsers support

React Native Change Default iOS Simulator Device

Here is new path for changing iOS simulator you just need to change

default: 'iPhone 6' or something else 

Path:

<project_root>/node_modules/@react-native-community/cli/build/commands/runIOS/runIOS.js

How to show full height background image?

 html, body {
    height:100%;
}

body { 
    background: url(images/bg.jpg) no-repeat center center fixed; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

How to dynamically create CSS class in JavaScript and apply?

Although I'm not sure why you want to create CSS classes with JavaScript, here is an option:

var style = document.createElement('style');
style.type = 'text/css';
style.innerHTML = '.cssClass { color: #F00; }';
document.getElementsByTagName('head')[0].appendChild(style);

document.getElementById('someElementId').className = 'cssClass';

Access denied for user 'root'@'localhost' (using password: YES) after new installation on Ubuntu

from superuser accepted answer:

sudo mysql -u root
use mysql;
update user set plugin='' where User='root';
flush privileges;
exit;

Force drop mysql bypassing foreign key constraint

Since you are not interested in keeping any data, drop the entire database and create a new one.

CSS text-decoration underline color

(for fellow googlers, copied from duplicate question) This answer is outdated since text-decoration-color is now supported by most modern browsers.

You can do this via the following CSS rule as an example:

text-decoration-color:green


If this rule isn't supported by an older browser, you can use the following solution:

Setting your word with a border-bottom:

a:link {
  color: red;
  text-decoration: none;
  border-bottom: 1px solid blue;
}
a:hover {
 border-bottom-color: green;
}

Best Practices for securing a REST API / web service

One of the best posts I've ever come across regarding Security as it relates to REST is over at 1 RainDrop. The MySpace API's use OAuth also for security and you have full access to their custom channels in the RestChess code, which I did a lot of exploration with. This was demo'd at Mix and you can find the posting here.

Window.open as modal popup?

A pop-up is a child of the parent window, but it is not a child of the parent DOCUMENT. It is its own independent browser window and is not contained by the parent.

Use an absolutely-positioned DIV and a translucent overlay instead.

EDIT - example

You need jQuery for this:

<style>
html, body {
    height:100%
}


#overlay { 
    position:absolute;
    z-index:10;
    width:100%;
    height:100%;
    top:0;
    left:0;
    background-color:#f00;
    filter:alpha(opacity=10);
    -moz-opacity:0.1;
    opacity:0.1;
    cursor:pointer;

} 

.dialog {
    position:absolute;
    border:2px solid #3366CC;
    width:250px;
    height:120px;
    background-color:#ffffff;
    z-index:12;
}

</style>
<script type="text/javascript">
$(document).ready(function() { init() })

function init() {
    $('#overlay').click(function() { closeDialog(); })
}

function openDialog(element) {
    //this is the general dialog handler.
    //pass the element name and this will copy
    //the contents of the element to the dialog box

    $('#overlay').css('height', $(document.body).height() + 'px')
    $('#overlay').show()
    $('#dialog').html($(element).html())
    centerMe('#dialog')
    $('#dialog').show();
}

function closeDialog() {
    $('#overlay').hide();
    $('#dialog').hide().html('');
}

function centerMe(element) {
    //pass element name to be centered on screen
    var pWidth = $(window).width();
    var pTop = $(window).scrollTop()
    var eWidth = $(element).width()
    var height = $(element).height()
    $(element).css('top', '130px')
    //$(element).css('top',pTop+100+'px')
    $(element).css('left', parseInt((pWidth / 2) - (eWidth / 2)) + 'px')
}


</script>


<a href="javascript:;//close me" onclick="openDialog($('#content'))">show dialog A</a>

<a href="javascript:;//close me" onclick="openDialog($('#contentB'))">show dialog B</a>

<div id="dialog" class="dialog" style="display:none"></div>
<div id="overlay" style="display:none"></div>
<div id="content" style="display:none">
    Lorem ipsum dolor sit amet, consectetur adipiscing elit. Proin nisl felis, placerat in sollicitudin quis, hendrerit vitae diam. Nunc ornare iaculis urna. 
</div>

<div id="contentB" style="display:none">
    Moooo mooo moo moo moo!!! 
</div>

React "after render" code?

componentDidMount()

This method is called once after your component is rendered. So your code would look like so.

var AppBase = React.createClass({
  componentDidMount: function() {
    var $this = $(ReactDOM.findDOMNode(this));
    // set el height and width etc.
  },

  render: function () {
    return (
      <div className="wrapper">
        <Sidebar />
          <div className="inner-wrapper">
            <ActionBar title="Title Here" />
            <BalanceBar balance={balance} />
            <div className="app-content">
              <List items={items} />
          </div>
        </div>
      </div>
    );
  }
});

How to output a multiline string in Bash?

If you use the solution from @jorge and find that everything is on the same line, make sure you enclose the variable in quotes:

echo $__usage

will print everything on one line whereas

echo "$__usage"

will retain the newlines.

How do I remove the last comma from a string using PHP?

You can use one of the following technique to remove the last comma(,)

Solution1:

$string = "'name', 'name2', 'name3',";  // this is the full string or text.
$string = chop($string,",");            // remove the last character (,) and store the updated value in $string variable.
echo $string;                           // to print update string.

Solution 2:

$string = '10,20,30,';              // this is the full string or text.
$string = rtrim($string,',');
echo $string;                       // to print update string.

Solution 3:

 $string = "'name', 'name2', 'name3',";  // this is the full string or text.
 $string = substr($string , 0, -1);
 echo $string;  

Server Client send/receive simple text

Server:

namespace SocketServer    
{
    class Program
    {
        static Socket klient; 
        static void Main(string[] args)
        {
            Socket server = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp); 
            IPEndPoint endPoint = new IPEndPoint(IPAddress.Any, 8888); 
            server.Bind(endPoint);
            server.Listen(20);
            while(true)
            {
                Console.WriteLine("Waiting...");
                klient = server.Accept();

                Console.WriteLine("Client connected");
                Task t = new Task(ServisClient);
                t.Start();
            }
        }

        static void ServisClient()
        {
            try
            {
                while (true)
                {
                    byte[] buffer = new byte[64];
                    Console.WriteLine("Waiting for answer...");
                    klient.Receive(buffer, 0, buffer.Length, 0);
                    string message = Encoding.UTF8.GetString(buffer);
                    Console.WriteLine("Answer: " + message);

                    string answer = "Actualy date is " + DateTime.Now;
                    buffer = Encoding.UTF8.GetBytes(answer);
                    Console.WriteLine("Sending {0}", answer);
                    klient.Send(buffer);
                }
            }
            catch
            {
                Console.WriteLine("Disconnected");
            }
        }
    }
}

How do I get the real .height() of a overflow: hidden or overflow: scroll div?

Use the .scrollHeight property of the DOM node: $('#your_div')[0].scrollHeight

Maven version with a property

Using a property for the version generates the following warning:

[WARNING]
[WARNING] Some problems were encountered while building the effective model for xxx.yyy.sandbox:Sandbox:war:0.1.0-SNAPSHOT
[WARNING] 'version' contains an expression but should be a constant. @ xxx.yyy.sandbox:Sandbox:${my.version}, C:\Users\xxx\development\gwtsandbox\pom.xml, line 8, column 14
[WARNING]
[WARNING] It is highly recommended to fix these problems because they threaten the stability of your build.
[WARNING]
[WARNING] For this reason, future Maven versions might no longer support building such malformed projects.
[WARNING]

If your problem is that you have to change the version in multiple places because you are switching versions, then the correct thing to do is to use the Maven Release Plugin that will do this for you automatically.

textarea character limit

I found a good solution that uses the maxlength attribute if the browser supports it, and falls back to an unobtrusive javascript pollyfill in unsupporting browsers.

Thanks to @Dan Tello's comment I fixed it up so it works in IE7+ as well:

HTML:

<textarea maxlength="50" id="text">This textarea has a character limit of 50.</textarea>

Javascript:

function maxLength(el) {    
    if (!('maxLength' in el)) {
        var max = el.attributes.maxLength.value;
        el.onkeypress = function () {
            if (this.value.length >= max) return false;
        };
    }
}

maxLength(document.getElementById("text"));

Demo

There is no such thing as a minlength attribute in HTML5.
For the following input types: number, range, date, datetime, datetime-local, month, time, and week (which aren't fully supported yet) use the min and max attributes.

Git: How to remove remote origin from Git repo

You can go to the .git folder, edit the config file without using the commands.

MySQl Error #1064

At first you need to add semi colon (;) after quantity INT NOT NULL) then remove ** from ,genre,quantity)**. to insert a value with numeric data type like int, decimal, float, etc you don't need to add single quote.

Are arrays in PHP copied as value or as reference to new variables, and when passed to functions?

In PHP arrays are passed to functions by value by default, unless you explicitly pass them by reference, as the following snippet shows:

$foo = array(11, 22, 33);

function hello($fooarg) {
  $fooarg[0] = 99;
}

function world(&$fooarg) {
  $fooarg[0] = 66;
}

hello($foo);
var_dump($foo); // (original array not modified) array passed-by-value

world($foo);
var_dump($foo); // (original array modified) array passed-by-reference

Here is the output:

array(3) {
  [0]=>
  int(11)
  [1]=>
  int(22)
  [2]=>
  int(33)
}
array(3) {
  [0]=>
  int(66)
  [1]=>
  int(22)
  [2]=>
  int(33)
}

How to get day of the month?

Java 8 Update

Java 8 introduces the following packages for time and date manipulation.

java.time.*;
java.time.format.*;

java.time.chono.*;    
java.time.temporal.*;
java.time.zone.*;

These are more organized and intuitive.

We need only top two packages for the discussion.
There are 3 top level classes - LocalDate, LocalTime, LocalDateTime for describing Date, Time and DateTime respectively. Although, they are formatted properly in toString(), each class has format method which accepts DateTimeFormatter to format in customized way.

DateTimeFormatter can also be used show the date given a day. It has few

import java.time.*;
import java.time.format.*;

class DateTimeDemo{
    public static void main(String...args){
        LocalDateTime x = LocalDateTime.now();
        System.out.println(x.format(DateTimeFormatter.ofLocalizedDate(FormatStyle.FULL)));//Shows Day and Date.

        System.out.println(x.format(DateTimeFormatter.ofPattern("EE")));//Short Form
        System.out.println(x.format(DateTimeFormatter.ofPattern("EEEE")));//Long Form

    }
}

ofLocalizedTime accepts FormatStyle which is an enumeration in java.time.format

ofPattern accepts String with restricted pattern characters of restricted length. Here are the characters which can be passed into the toPattern method.

enter image description here

You can try different number of patterns to see how the output will be.

Check out more about Java 8 DateTime API here

How do I set the path to a DLL file in Visual Studio?

I had the same problem and my problem had nothing to do with paths. One of my dll-s was written in c++ and it turnes out that if your visual studio doesn't know how to open a dll file it will say that it did not find it. What i did was locate which dll it did not find, than searched for that dll in my directories and opened it in a separate visual studio window. When trying to navigate through Solution explorer of that project, visual studio said that it cannot show what is inside and that i need some extra extensions, so that it can open those files. Surely enough, after installing the recomended extension (in my case something to do with c++) the

"This application has failed to start because xxx.dll was not found."

error miraculously dissapeared.

Python function attributes - uses and abuses

I was always of the assumption that the only reason this was possible was so there was a logical place to put a doc-string or other such stuff. I know if I used it for any production code it'd confuse most who read it.

$(this).attr("id") not working

Remove the inline event handler and do it completly unobtrusive, like

?$('????#race').bind('change', function(){
  var $this = $(this),
      id    = $this[0].id;

  if(/^other$/.test($(this).val())){
      $this.replaceWith($('<input/>', {
          type: 'text',
          name:  id,
          id: id
      }));
  }
});???

Ajax request returns 200 OK, but an error event is fired instead of success

I had the same issue. My problem was my controller was returning a status code instead of JSON. Make sure that your controller returns something like:

public JsonResult ActionName(){
   // Your code
   return Json(new { });
}

sudo echo "something" >> /etc/privilegedFile doesn't work

Doing

sudo sh -c "echo >> somefile"

should work. The problem is that > and >> are handled by your shell, not by the "sudoed" command, so the permissions are your ones, not the ones of the user you are "sudoing" into.

How to hide Soft Keyboard when activity starts

I hope this will work, I tried a lot of methods but this one worked for me in fragments. just put this line in onCreateview/init.

getActivity().getWindow().setSoftInputMode(
    WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);

Missing Push Notification Entitlement

To solve this for an expo 'ejected' app, I went to the capabilities tab, enabled push, then disabled it again. This removed the APNS 'entitlements' setting from the .entitlements file.

How do you check if a JavaScript Object is a DOM Object?

I suggest a simple way to testing if a variable is an DOM element

function isDomEntity(entity) {
  if(typeof entity  === 'object' && entity.nodeType !== undefined){
     return true;
  }
  else{
     return false;
  }
}

or as HTMLGuy suggested:

const isDomEntity = entity => {
  return typeof entity   === 'object' && entity.nodeType !== undefined
}

How to export data as CSV format from SQL Server using sqlcmd?

You can run something like this:

sqlcmd -S MyServer -d myDB -E -Q "select col1, col2, col3 from SomeTable" 
       -o "MyData.csv" -h-1 -s"," -w 700
  • -h-1 removes column name headers from the result
  • -s"," sets the column seperator to ,
  • -w 700 sets the row width to 700 chars (this will need to be as wide as the longest row or it will wrap to the next line)

How to create an infinite loop in Windows batch file?

How about using good(?) old goto?

:loop

echo Ooops

goto loop

See also this for a more useful example.

How to insert a data table into SQL Server database table?

I am giving a very simple code, which i used in my solution (I have the same problem statement as yours)

    SqlConnection con = connection string ;
//new SqlConnection("Data Source=.;uid=sa;pwd=sa123;database=Example1");
con.Open();
string sql = "Create Table abcd (";
foreach (DataColumn column in dt.Columns)
{
    sql += "[" + column.ColumnName + "] " + "nvarchar(50)" + ",";
}
sql = sql.TrimEnd(new char[] { ',' }) + ")";
SqlCommand cmd = new SqlCommand(sql, con);
SqlDataAdapter da = new SqlDataAdapter(cmd);
cmd.ExecuteNonQuery();
using (var adapter = new SqlDataAdapter("SELECT * FROM abcd", con)) 
using(var builder = new SqlCommandBuilder(adapter))
{
adapter.InsertCommand = builder.GetInsertCommand();
adapter.Update(dt);
// adapter.Update(ds.Tables[0]); (Incase u have a data-set)
}
con.Close();

I have given a predefined table-name as "abcd" (you must take care that a table by this name doesn't exist in your database). Please vote my answer if it works for you!!!! :)

What does "-ne" mean in bash?

"not equal" So in this case, $RESULT is tested to not be equal to zero.

However, the test is done numerically, not alphabetically:

n1 -ne n2     True if the integers n1 and n2 are not algebraically equal.

compared to:

s1 != s2      True if the strings s1 and s2 are not identical.

Address validation using Google Maps API

A great blog describing 14 address finders: https://www.conversion-uplift.co.uk/free-address-lookup-tools/

Many address autocomplete services, including Google's Places API, appears to offer international address support but it has limited accuracy.

For example, New Zealand address and geolocation data are free to download from Land Information New Zealand (LINZ). When a user search for an address such as 76 Francis St Hauraki from Google or Address Doctor, a positive match is returned. The land parcel was matched but not the postal/delivery address, which is either 76A or 76B. The problem is amplified with apartments and units on a single land parcel.

For 100% accuracy, use a country-specific address finder instead such as https://www.addy.co.nz for NZ address autocomplete.

How many bits or bytes are there in a character?

There are 8 bits in a byte (normally speaking in Windows).

However, if you are dealing with characters, it will depend on the charset/encoding. Unicode character can be 2 or 4 bytes, so that would be 16 or 32 bits, whereas Windows-1252 sometimes incorrectly called ANSI is only 1 bytes so 8 bits.

In Asian version of Windows and some others, the entire system runs in double-byte, so a character is 16 bits.

EDITED

Per Matteo's comment, all contemporary versions of Windows use 16-bits internally per character.

Android: show soft keyboard automatically when focus is on an EditText

getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_VISIBLE);

I call this in onCreate() to show keyboard automatically, when I came in the Activity.

How can I get the corresponding table header (th) from a table cell (td)?

var $th = $("table thead tr th").eq($td.index())

It would be best to use an id to reference the table if there is more than one.

Java getting the Enum name given the Enum Value

In such cases, you can convert the values of enum to a List and stream through it. Something like below examples. I would recommend using filter().

Using ForEach:

List<Category> category = Arrays.asList(Category.values());
category.stream().forEach(eachCategory -> {
            if(eachCategory.toString().equals("3")){
                String name = eachCategory.name();
            }
        });

Or, using Filter:

When you want to find with code:

List<Category> categoryList = Arrays.asList(Category.values());
Category category = categoryList.stream().filter(eachCategory -> eachCategory.toString().equals("3")).findAny().orElse(null);

System.out.println(category.toString() + " " + category.name());

When you want to find with name:

List<Category> categoryList = Arrays.asList(Category.values());
Category category = categoryList.stream().filter(eachCategory -> eachCategory.name().equals("Apple")).findAny().orElse(null);

System.out.println(category.toString() + " " + category.name());

Hope it helps! I know this is a very old post, but someone can get help.

How to make PDF file downloadable in HTML link?

I know I am very late to answer this but I found a hack to do this in javascript.

function downloadFile(src){
    var link=document.createElement('a');
    document.body.appendChild(link);
    link.href= src;
    link.download = '';
    link.click();
}

How to initialize a variable of date type in java?

To initialize to current date, you could do something like:

Date firstDate = new Date();

To get it from String, you could use SimpleDateFormat like:

String dateInString = "10-Jan-2016";
SimpleDateFormat formatter = new SimpleDateFormat("dd-MMM-yyyy");
try {
    Date date = formatter.parse(dateInString);
    System.out.println(date);
    System.out.println(formatter.format(date));
} catch (ParseException e) {
    //handle exception if date is not in "dd-MMM-yyyy" format
}

LIMIT 10..20 in SQL Server

From the MS SQL Server online documentation (http://technet.microsoft.com/en-us/library/ms186734.aspx ), here is their example that I have tested and works, for retrieving a specific set of rows. ROW_NUMBER requires an OVER, but you can order by whatever you like:

WITH OrderedOrders AS
(
  SELECT SalesOrderID, OrderDate,
  ROW_NUMBER() OVER (ORDER BY OrderDate) AS RowNumber
  FROM Sales.SalesOrderHeader 
) 
SELECT SalesOrderID, OrderDate, RowNumber  
FROM OrderedOrders 
WHERE RowNumber BETWEEN 50 AND 60;

How can I send an xml body using requests library?

Just send xml bytes directly:

#!/usr/bin/env python2
# -*- coding: utf-8 -*-
import requests

xml = """<?xml version='1.0' encoding='utf-8'?>
<a>?</a>"""
headers = {'Content-Type': 'application/xml'} # set what your server accepts
print requests.post('http://httpbin.org/post', data=xml, headers=headers).text

Output

{
  "origin": "x.x.x.x",
  "files": {},
  "form": {},
  "url": "http://httpbin.org/post",
  "args": {},
  "headers": {
    "Content-Length": "48",
    "Accept-Encoding": "identity, deflate, compress, gzip",
    "Connection": "keep-alive",
    "Accept": "*/*",
    "User-Agent": "python-requests/0.13.9 CPython/2.7.3 Linux/3.2.0-30-generic",
    "Host": "httpbin.org",
    "Content-Type": "application/xml"
  },
  "json": null,
  "data": "<?xml version='1.0' encoding='utf-8'?>\n<a>\u0431</a>"
}

What is the size of a boolean variable in Java?

The boolean values are compiled to int data type in JVM. See here.

Fine control over the font size in Seaborn plots for academic papers

It is all but satisfying, isn't it? The easiest way I have found to specify when setting the context, e.g.:

sns.set_context("paper", rc={"font.size":8,"axes.titlesize":8,"axes.labelsize":5})   

This should take care of 90% of standard plotting usage. If you want ticklabels smaller than axes labels, set the 'axes.labelsize' to the smaller (ticklabel) value and specify axis labels (or other custom elements) manually, e.g.:

axs.set_ylabel('mylabel',size=6)

you could define it as a function and load it in your scripts so you don't have to remember your standard numbers, or call it every time.

def set_pubfig:
    sns.set_context("paper", rc={"font.size":8,"axes.titlesize":8,"axes.labelsize":5})   

Of course you can use configuration files, but I guess the whole idea is to have a simple, straightforward method, which is why the above works well.

Note: If you specify these numbers, specifying font_scale in sns.set_context is ignored for all specified font elements, even if you set it.

What is newline character -- '\n'

I see a lot of sed answers, but none for vim. To be fair, vim's treatment of newline characters is a little confusing. Search for \n but replace with \r. I recommend RTFM: :help pattern in general and :help NL-used-for-Nul in particular.

To do what you want with a :substitute command,

:%s/\_$/\r

although I think most people would use something like

:g/^/put=''

for the same effect.

Here is a way to find the answer for yourself. Run your file through xxd, which is part of the standard vim distribution.

:%!xxd

You get

0000000: 4361 6c69 666f 726e 6961 0a4d 6173 7361  California.Massa
0000010: 6368 7573 6574 7473 0a41 7269 7a6f 6e61  chusetts.Arizona
0000020: 0a                                       .

This shows that 46 is the hex code for C, 61 is the code for a, and so on. In particular, 0a (decimal 10) is the code for \n. Just for kicks, try

:set ff=dos

before filtering through xxd. You will see 0d0a (CRLF) as the line terminator.

:help /\_$
:help :g
:help :put
:help :!
:help 23.4

How to pass "Null" (a real surname!) to a SOAP web service in ActionScript 3

As a hack, you could consider having a special handling on the client side, converting 'Null' string to something that will never occur, for example, XXNULLXX and converting back on the server.

It is not pretty, but it may solve the issue for such a boundary case.

Declaring abstract method in TypeScript

If you take Erics answer a little further you can actually create a pretty decent implementation of abstract classes, with full support for polymorphism and the ability to call implemented methods from the base class. Let's start with the code:

/**
 * The interface defines all abstract methods and extends the concrete base class
 */
interface IAnimal extends Animal {
    speak() : void;
}

/**
 * The abstract base class only defines concrete methods & properties.
 */
class Animal {

    private _impl : IAnimal;

    public name : string;

    /**
     * Here comes the clever part: by letting the constructor take an 
     * implementation of IAnimal as argument Animal cannot be instantiated
     * without a valid implementation of the abstract methods.
     */
    constructor(impl : IAnimal, name : string) {
        this.name = name;
        this._impl = impl;

        // The `impl` object can be used to delegate functionality to the
        // implementation class.
        console.log(this.name + " is born!");
        this._impl.speak();
    }
}

class Dog extends Animal implements IAnimal {
    constructor(name : string) {
        // The child class simply passes itself to Animal
        super(this, name);
    }

    public speak() {
        console.log("bark");
    }
}

var dog = new Dog("Bob");
dog.speak(); //logs "bark"
console.log(dog instanceof Dog); //true
console.log(dog instanceof Animal); //true
console.log(dog.name); //"Bob"

Since the Animal class requires an implementation of IAnimal it's impossible to construct an object of type Animal without having a valid implementation of the abstract methods. Note that for polymorphism to work you need to pass around instances of IAnimal, not Animal. E.g.:

//This works
function letTheIAnimalSpeak(animal: IAnimal) {
    console.log(animal.name + " says:");
    animal.speak();
}
//This doesn't ("The property 'speak' does not exist on value of type 'Animal')
function letTheAnimalSpeak(animal: Animal) {
    console.log(animal.name + " says:");
    animal.speak();
}

The main difference here with Erics answer is that the "abstract" base class requires an implementation of the interface, and thus cannot be instantiated on it's own.

Oracle query to fetch column names

On Several occasions, we would need comma separated list of all the columns from a table in a schema. In such cases we can use this generic function which fetches the comma separated list as a string.

CREATE OR REPLACE FUNCTION cols(
    p_schema_name IN VARCHAR2,
    p_table_name  IN VARCHAR2)
  RETURN VARCHAR2
IS
  v_string VARCHAR2(4000);
BEGIN
  SELECT LISTAGG(COLUMN_NAME , ',' ) WITHIN GROUP (
  ORDER BY ROWNUM )
  INTO v_string
  FROM ALL_TAB_COLUMNS
  WHERE OWNER    = p_schema_name
  AND table_name = p_table_name;
  RETURN v_string;
END;
/

So, simply calling the function from the query yields a row with all the columns.

select cols('HR','EMPLOYEES') FROM DUAL;

EMPLOYEE_ID,FIRST_NAME,LAST_NAME,EMAIL,PHONE_NUMBER,HIRE_DATE,JOB_ID,SALARY,COMMISSION_PCT,MANAGER_ID,DEPARTMENT_ID

Note: LISTAGG will fail if the combined length of all columns exceed 4000 characters which is rare. For most cases , this will work.

Extract substring using regexp in plain bash

Using pure :

$ cat file.txt
US/Central - 10:26 PM (CST)
$ while read a b time x; do [[ $b == - ]] && echo $time; done < file.txt

another solution with bash regex :

$ [[ "US/Central - 10:26 PM (CST)" =~ -[[:space:]]*([0-9]{2}:[0-9]{2}) ]] &&
    echo ${BASH_REMATCH[1]}

another solution using grep and look-around advanced regex :

$ echo "US/Central - 10:26 PM (CST)" | grep -oP "\-\s+\K\d{2}:\d{2}"

another solution using sed :

$ echo "US/Central - 10:26 PM (CST)" |
    sed 's/.*\- *\([0-9]\{2\}:[0-9]\{2\}\).*/\1/'

another solution using perl :

$ echo "US/Central - 10:26 PM (CST)" |
    perl -lne 'print $& if /\-\s+\K\d{2}:\d{2}/'

and last one using awk :

$ echo "US/Central - 10:26 PM (CST)" |
    awk '{for (i=0; i<=NF; i++){if ($i == "-"){print $(i+1);exit}}}'

Importing Pandas gives error AttributeError: module 'pandas' has no attribute 'core' in iPython Notebook

There's this bug in the latest version of pandas (pandas 0.23) that gives you an error on importing pandas.

But this can be easily fixed by installing an earlier version of pandas (pandas 0.22) using the command pip install pandas==0.22 on Windows Command Prompt.

How to get a .csv file into R?

You can use

df <- read.csv("filename.csv", header=TRUE)

# To loop each column
for (i in 1:ncol(df))
    {
    dosomething(df[,i])
    }
# To loop each row
for (i in 1:nrow(df))
    {
    dosomething(df[i,])
    }

Also, you may want to have a look to the apply function (type ?apply or help(apply))if you want to use the same function on each row/column

Organizing a multiple-file Go project

jdi has the right information concerning the use of GOPATH. I would add that if you intend to have a binary as well you might want to add one additional level to the directories.

~/projects/src/
    myproj/
        mypack/
            lib.go
            lib_test.go
            ...
        myapp/
            main.go

running go build myproj/mypack will build the mypack package along with it's dependencies running go build myproj/myapp will build the myapp binary along with it's dependencies which probably includes the mypack library.

Bash mkdir and subfolders

You can:

mkdir -p folder/subfolder

The -p flag causes any parent directories to be created if necessary.

Save file Javascript with file name

Replace your "Save" button with an anchor link and set the new download attribute dynamically. Works in Chrome and Firefox:

var d = "ha";
$(this).attr("href", "data:image/png;base64,abcdefghijklmnop").attr("download", "file-" + d + ".png");

Here's a working example with the name set as the current date: http://jsfiddle.net/Qjvb3/

Here a compatibility table for downloadattribute: http://caniuse.com/download

Call-time pass-by-reference has been removed

Only call time pass-by-reference is removed. So change:

call_user_func($func, &$this, &$client ...

To this:

call_user_func($func, $this, $client ...

&$this should never be needed after PHP4 anyway period.

If you absolutely need $client to be passed by reference, update the function ($func) signature instead (function func(&$client) {)

Is there a way to detect if a browser window is not currently active?

var visibilityChange = (function (window) {
    var inView = false;
    return function (fn) {
        window.onfocus = window.onblur = window.onpageshow = window.onpagehide = function (e) {
            if ({focus:1, pageshow:1}[e.type]) {
                if (inView) return;
                fn("visible");
                inView = true;
            } else if (inView) {
                fn("hidden");
                inView = false;
            }
        };
    };
}(this));

visibilityChange(function (state) {
    console.log(state);
});

http://jsfiddle.net/ARTsinn/JTxQY/

How to set margin with jquery?

Set it with a px value. Changing the code like below should work

el.css('marginLeft', mrg + 'px');

How do I count unique items in field in Access query?

Access-Engine does not support

SELECT count(DISTINCT....) FROM ...

You have to do it like this:

SELECT count(*) 
FROM
(SELECT DISTINCT Name FROM table1)

Its a little workaround... you're counting a DISTINCT selection.

Static image src in Vue.js template

If you want to bind a string to the src attribute, you should wrap it on single quotes:

<img v-bind:src="'/static/img/clear.gif'">
<!-- or shorthand -->
<img :src="'/static/img/clear.gif'">

IMO you do not need to bind a string, you could use the simple way:

<img src="/static/img/clear.gif">

Check an example about the image preload here: http://codepen.io/pespantelis/pen/RWVZxL

Wrap a text within only two lines inside div

Limiting output to two lines of text is possible with CSS, if you set the line-height and height of the element, and set overflow:hidden;:

#someDiv {
    line-height: 1.5em;
    height: 3em;       /* height is 2x line-height, so two lines will display */
    overflow: hidden;  /* prevents extra lines from being visible */
}

--- jsFiddle DEMO ---

Alternatively, you can use the CSS text-overflow and white-space properties to add ellipses, but this only appears to work for a single line.

#someDiv {
    line-height: 1.5em;
    height: 3em;
    overflow: hidden;
    white-space: nowrap;
    text-overflow: ellipsis;
    width: 100%;
}

And a demo:

--- jsFiddle DEMO ---

Achieving both multiple lines of text and ellipses appears to be the realm of javascript.

How to log cron jobs?

By default cron logs to /var/log/syslog so you can see cron related entries by using:

grep CRON /var/log/syslog

https://askubuntu.com/questions/56683/where-is-the-cron-crontab-log

Python reshape list to ndim array

You can specify the interpretation order of the axes using the order parameter:

np.reshape(arr, (2, -1), order='F')

How to get out of while loop in java with Scanner method "hasNext" as condition?

You can simply use one of the system dependent end-of-file indicators ( d for Unix/Linux/Ubuntu, z for windows) to make the while statement false. This should get you out of the loop nicely. :)

Convert a RGB Color Value to a Hexadecimal String

This is an adapted version of the answer given by Vivien Barousse with the update from Vulcan applied. In this example I use sliders to dynamically retreive the RGB values from three sliders and display that color in a rectangle. Then in method toHex() I use the values to create a color and display the respective Hex color code.

This example does not include the proper constraints for the GridBagLayout. Though the code will work, the display will look strange.

public class HexColor
{

  public static void main (String[] args)
  {
   JSlider sRed = new JSlider(0,255,1);
   JSlider sGreen = new JSlider(0,255,1);
   JSlider sBlue = new JSlider(0,255,1);
   JLabel hexCode = new JLabel();
   JPanel myPanel = new JPanel();
   GridBagLayout layout = new GridBagLayout();
   JFrame frame = new JFrame();

   //set frame to organize components using GridBagLayout 
   frame.setLayout(layout);

   //create gray filled rectangle 
   myPanel.paintComponent();
   myPanel.setBackground(Color.GRAY);

   //In practice this code is replicated and applied to sGreen and sBlue. 
   //For the sake of brevity I only show sRed in this post.
   sRed.addChangeListener(
         new ChangeListener()
         {
             @Override
             public void stateChanged(ChangeEvent e){
                 myPanel.setBackground(changeColor());
                 myPanel.repaint();
                 hexCode.setText(toHex());
         }
         }
     );
   //add each component to JFrame
   frame.add(myPanel);
   frame.add(sRed);
   frame.add(sGreen);
   frame.add(sBlue);
   frame.add(hexCode);
} //end of main

  //creates JPanel filled rectangle
  protected void paintComponent(Graphics g)
  {
      super.paintComponent(g);
      g.drawRect(360, 300, 10, 10);
      g.fillRect(360, 300, 10, 10);
  }

  //changes the display color in JPanel
  private Color changeColor()
  {
    int r = sRed.getValue();
    int b = sBlue.getValue();
    int g = sGreen.getValue();
    Color c;
    return  c = new Color(r,g,b);
  }

  //Displays hex representation of displayed color
  private String toHex()
  {
      Integer r = sRed.getValue();
      Integer g = sGreen.getValue();
      Integer b = sBlue.getValue();
      Color hC;
      hC = new Color(r,g,b);
      String hex = Integer.toHexString(hC.getRGB() & 0xffffff);
      while(hex.length() < 6){
          hex = "0" + hex;
      }
      hex = "Hex Code: #" + hex;
      return hex;
  }
}

A huge thank you to both Vivien and Vulcan. This solution works perfectly and was super simple to implement.

How to pause a YouTube player when hiding the iframe?

Since you need to set ?enablejsapi=true in the src of the iframe before you can use the playVideo / pauseVideo commands mentioned in other answers, it might be useful to add this programmatically via Javascript (especially if, eg. you want this behaviour to apply to videos embedded by other users who have just cut and paste a YouTube embed code). In that case, something like this might be useful:

function initVideos() {

  // Find all video iframes on the page:
  var iframes = $(".video").find("iframe");

  // For each of them:
  for (var i = 0; i < iframes.length; i++) {
    // If "enablejsapi" is not set on the iframe's src, set it:
    if (iframes[i].src.indexOf("enablejsapi") === -1) {
      // ...check whether there is already a query string or not:
      // (ie. whether to prefix "enablejsapi" with a "?" or an "&")
      var prefix = (iframes[i].src.indexOf("?") === -1) ? "?" : "&amp;";
      iframes[i].src += prefix + "enablejsapi=true";
    }
  }
}

...if you call this on document.ready then all iframes in a div with a class of "video" will have enablejsapi=true added to their source, which allows the playVideo / pauseVideo commands to work on them.

(nb. this example uses jQuery for that one line that sets var iframes, but the general approach should work just as well with pure Javascript if you're not using jQuery).

difference between @size(max = value ) and @min(value) @max(value)

package com.mycompany;

import javax.validation.constraints.Min;
import javax.validation.constraints.NotNull;
import javax.validation.constraints.Size;

public class Car {

    @NotNull
    private String manufacturer;

    @NotNull
    @Size(min = 2, max = 14)
    private String licensePlate;

    @Min(2)
    private int seatCount;

    public Car(String manufacturer, String licencePlate, int seatCount) {
        this.manufacturer = manufacturer;
        this.licensePlate = licencePlate;
        this.seatCount = seatCount;
    }

    //getters and setters ...
}

@NotNull, @Size and @Min are so-called constraint annotations, that we use to declare constraints, which shall be applied to the fields of a Car instance:

manufacturer shall never be null

licensePlate shall never be null and must be between 2 and 14 characters long

seatCount shall be at least 2.

round a single column in pandas

For some reason the round() method doesn't work if you have float numbers with many decimal places, but this will.

decimals = 2    
df['column'] = df['column'].apply(lambda x: round(x, decimals))

How to destroy Fragment?

It's used in Kotlin

appCompatActivity?.getSupportFragmentManager()?.popBackStack()

How do I access Configuration in any class in ASP.NET Core?

I'm doing it like this at the moment:

// Requires NuGet package Microsoft.Extensions.Configuration.Json

using Microsoft.Extensions.Configuration;
using System.IO;

namespace ImagesToMssql.AppsettingsJson
{
    public static class AppSettingsJson
    {           
        public static IConfigurationRoot GetAppSettings()
        {
            string applicationExeDirectory = ApplicationExeDirectory();

            var builder = new ConfigurationBuilder()
            .SetBasePath(applicationExeDirectory)
            .AddJsonFile("appsettings.json");

            return builder.Build();
        }

        private static string ApplicationExeDirectory()
        {
            var location = System.Reflection.Assembly.GetExecutingAssembly().Location;
            var appRoot = Path.GetDirectoryName(location);

            return appRoot;
        }
    }
}

And then I use this where I need to get the data from the appsettings.json file:

var appSettingsJson = AppSettingsJson.GetAppSettings();
// appSettingsJson["keyName"]

Python Pandas: How to read only first n rows of CSV files in?

If you only want to read the first 999,999 (non-header) rows:

read_csv(..., nrows=999999)

If you only want to read rows 1,000,000 ... 1,999,999

read_csv(..., skiprows=1000000, nrows=999999)

nrows : int, default None Number of rows of file to read. Useful for reading pieces of large files*

skiprows : list-like or integer Row numbers to skip (0-indexed) or number of rows to skip (int) at the start of the file

and for large files, you'll probably also want to use chunksize:

chunksize : int, default None Return TextFileReader object for iteration

pandas.io.parsers.read_csv documentation

When running UPDATE ... datetime = NOW(); will all rows updated have the same date/time?

They should have the same time, the update is supposed to be atomic, meaning that whatever how long it takes to perform, the action is supposed to occurs as if all was done at the same time.

If you're experiencing a different behaviour, it's time to change for another DBMS.

In C#, what's the difference between \n and \r\n?

The Difference

There are a few characters which can indicate a new line. The usual ones are these two:

* '\n' or '0x0A' (10 in decimal) -> This character is called "Line Feed" (LF).
* '\r' or '0x0D' (13 in decimal) -> This one is called "Carriage return" (CR).

Different Operating Systems handle newlines in a different way. Here is a short list of the most common ones:

* DOS and Windows

They expect a newline to be the combination of two characters, namely '\r\n' (or 13 followed by 10).

* Unix (and hence Linux as well)

Unix uses a single '\n' to indicate a new line.

* Mac

Macs use a single '\r'.

Taken from Here

Bootstrap modal: is not a function

Causes for TypeError: $(…).modal is not a function:

  1. Scripts are loaded in the wrong order.
  2. Multiple jQuery instances

Solutions:

  1. In case, if a script attempt to access an element that hasn't been reached yet then you will get an error. Bootstrap depends on jQuery, so jQuery must be referenced first. So, you must be called the jquery.min.js and then bootstrap.min.js and further the bootstrap Modal error is actually the result of you not including bootstrap's javascript before calling the modal function. Modal is defined in bootstrap.js and not in jQuery. So the script should be included in this manner

       <script src="//code.jquery.com/jquery-1.11.0.min.js"></script> 
       <script type="text/javascript" src="js/bootstrap.js"></script>
    
  2. In case if there are multiple instances of jQuery, the second jQuery declaration prevents bootstrap.js from working correctly. so make use of jQuery.noConflict(); before calling the modal popup

    jQuery.noConflict();
    $('#prizePopup').modal('show');
    

    jQuery event aliases like .load, .unload or .error deprecated since jQuery 1.8.

    $(window).on('load', function(){ 
          $('#prizePopup').modal('show');
    });
    

    OR try opening the modal popup directly

    $('#prizePopup').on('shown.bs.modal', function () {
          ...
    });
    

What is the convention for word separator in Java package names?

Concatenation of words in the package name is something most developers don't do.

You can use something like.

com.stackoverflow.mypackage

Refer JLS Name Declaration

How do I create a ListView with rounded corners in Android?

Yet another solution to selection highlight problems with first, and last items in the list:

Add padding to the top and bottom of your list background equal to or greater than the radius. This ensures the selection highlighting doesn't overlap with your corner curves.

This is the easiest solution when you need non-transparent selection highlighting.

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
    <solid android:color="@color/listbg" />
    <stroke
        android:width="2dip"
        android:color="#D5D5D5" />
    <corners android:radius="10dip" />

    <!-- Make sure bottom and top padding match corner radius -->
    <padding
        android:bottom="10dip"
        android:left="2dip"
        android:right="2dip"
        android:top="10dip" />
</shape>

How to get request url in a jQuery $.get/ajax request

I can't get it to work on $.get() because it has no complete event.

I suggest to use $.ajax() like this,

$.ajax({
    url: 'http://www.example.org',
    data: {'a':1,'b':2,'c':3},
    dataType: 'xml',
    complete : function(){
        alert(this.url)
    },
    success: function(xml){
    }
});

craz demo

write() versus writelines() and concatenated strings

Actually, I think the problem is that your variable "lines" is bad. You defined lines as a tuple, but I believe that write() requires a string. All you have to change is your commas into pluses (+).

nl = "\n"
lines = line1+nl+line2+nl+line3+nl
textdoc.writelines(lines)

should work.

django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: No module named MySQLdb

Source

Install (if not found):

pip install mysql.connector

Settings:

'default': {
    'ENGINE': 'mysql.connector.django',
    'NAME': '...',
    'HOST': '...',
    'PORT': '3306',
    'USER': '...',
    'PASSWORD': '...',
}

Assign variable in if condition statement, good practice or not?

I did it many times. To bypass the JavaScript warning, I add two parens:

if ((result = get_something())) { }

You should avoid it, if you really want to use it, write a comment above it saying what you are doing.

HTML5 Canvas: Zooming

Just try this out:

<!DOCTYPE HTML>
<html>
    <head>
    <script type="text/javascript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.3.2/jquery.js"></script>
        <style>
            body {
                margin: 0px;
                padding: 0px;
            }

            #wrapper {
                position: relative;
                border: 1px solid #9C9898;
                width: 578px;
                height: 200px;
            }

            #buttonWrapper {
                position: absolute;
                width: 30px;
                top: 2px;
                right: 2px;
            }

            input[type =
            "button"] {
                padding: 5px;
                width: 30px;
                margin: 0px 0px 2px 0px;
            }
        </style>
        <script>
            function draw(scale, translatePos){
                var canvas = document.getElementById("myCanvas");
                var context = canvas.getContext("2d");

                // clear canvas
                context.clearRect(0, 0, canvas.width, canvas.height);

                context.save();
                context.translate(translatePos.x, translatePos.y);
                context.scale(scale, scale);
                context.beginPath(); // begin custom shape
                context.moveTo(-119, -20);
                context.bezierCurveTo(-159, 0, -159, 50, -59, 50);
                context.bezierCurveTo(-39, 80, 31, 80, 51, 50);
                context.bezierCurveTo(131, 50, 131, 20, 101, 0);
                context.bezierCurveTo(141, -60, 81, -70, 51, -50);
                context.bezierCurveTo(31, -95, -39, -80, -39, -50);
                context.bezierCurveTo(-89, -95, -139, -80, -119, -20);
                context.closePath(); // complete custom shape
                var grd = context.createLinearGradient(-59, -100, 81, 100);
                grd.addColorStop(0, "#8ED6FF"); // light blue
                grd.addColorStop(1, "#004CB3"); // dark blue
                context.fillStyle = grd;
                context.fill();

                context.lineWidth = 5;
                context.strokeStyle = "#0000ff";
                context.stroke();
                context.restore();
            }

            window.onload = function(){
                var canvas = document.getElementById("myCanvas");

                var translatePos = {
                    x: canvas.width / 2,
                    y: canvas.height / 2
                };

                var scale = 1.0;
                var scaleMultiplier = 0.8;
                var startDragOffset = {};
                var mouseDown = false;

                // add button event listeners
                document.getElementById("plus").addEventListener("click", function(){
                    scale /= scaleMultiplier;
                    draw(scale, translatePos);
                }, false);

                document.getElementById("minus").addEventListener("click", function(){
                    scale *= scaleMultiplier;
                    draw(scale, translatePos);
                }, false);

                // add event listeners to handle screen drag
                canvas.addEventListener("mousedown", function(evt){
                    mouseDown = true;
                    startDragOffset.x = evt.clientX - translatePos.x;
                    startDragOffset.y = evt.clientY - translatePos.y;
                });

                canvas.addEventListener("mouseup", function(evt){
                    mouseDown = false;
                });

                canvas.addEventListener("mouseover", function(evt){
                    mouseDown = false;
                });

                canvas.addEventListener("mouseout", function(evt){
                    mouseDown = false;
                });

                canvas.addEventListener("mousemove", function(evt){
                    if (mouseDown) {
                        translatePos.x = evt.clientX - startDragOffset.x;
                        translatePos.y = evt.clientY - startDragOffset.y;
                        draw(scale, translatePos);
                    }
                });

                draw(scale, translatePos);
            };



            jQuery(document).ready(function(){
               $("#wrapper").mouseover(function(e){
                  $('#status').html(e.pageX +', '+ e.pageY);
               }); 
            })  
        </script>
    </head>
    <body onmousedown="return false;">
        <div id="wrapper">
            <canvas id="myCanvas" width="578" height="200">
            </canvas>
            <div id="buttonWrapper">
                <input type="button" id="plus" value="+"><input type="button" id="minus" value="-">
            </div>
        </div>
        <h2 id="status">
        0, 0
        </h2>
    </body>
</html>

Works perfect for me with zooming and mouse movement.. you can customize it to mouse wheel up & down Njoy!!!

Here is fiddle for this Fiddle

Javascript decoding html entities

var text = '&lt;p&gt;name&lt;/p&gt;&lt;p&gt;&lt;span style="font-size:xx-small;"&gt;ajde&lt;/span&gt;&lt;/p&gt;&lt;p&gt;&lt;em&gt;da&lt;/em&gt;&lt;/p&gt;';
var decoded = $('<textarea/>').html(text).text();
alert(decoded);

This sets the innerHTML of a new element (not appended to the page), causing jQuery to decode it into HTML, which is then pulled back out with .text().

Live demo.

Histogram using gnuplot?

I have a little modification to Born2Smile's solution.

I know that doesn't make much sense, but you may want it just in case. If your data is integer and you need a float bin size (maybe for comparison with another set of data, or plot density in finer grid), you will need to add a random number between 0 and 1 inside floor. Otherwise, there will be spikes due to round up error. floor(x/width+0.5) will not do because it will create pattern that's not true to original data.

binwidth=0.3
bin(x,width)=width*floor(x/width+rand(0))

Is it possible to use the instanceof operator in a switch statement?

The Eclipse Modelling Framework has an interesting idea that also considers inheritance. The basic concept is defined in the Switch interface: switching is done by invoking the doSwitch method.

What is really interesting is the implementation. For each type of interest, a

public T caseXXXX(XXXX object);

method must be implemented (with a default implementation returning null). The doSwitch implementation will attempt to call al the caseXXX methods on the object for all its type hierarchy. Something in the lines of:

BaseType baseType = (BaseType)object;
T result = caseBaseType(eAttribute);
if (result == null) result = caseSuperType1(baseType);
if (result == null) result = caseSuperType2(baseType);
if (result == null) result = caseSuperType3(baseType);
if (result == null) result = caseSuperType4(baseType);
if (result == null) result = defaultCase(object);
return result;

The actual framework uses an integer id for each class, so the logic is actually a pure switch:

public T doSwitch(Object object) {
    return doSwitch(object.class(), eObject);
}

protected T doSwitch(Class clazz, Object object) {
    return doSwitch(getClassifierID(clazz), object);
}

protected T doSwitch(int classifierID, Object theObject) {
    switch (classifierID) {
    case MyClasses.BASETYPE:
    {
      BaseType baseType = (BaseType)object;
      ...
      return result;
    }
    case MyClasses.TYPE1:
    {
      ...
    }
  ...

You can look at a complete implementation of the ECoreSwitch to get a better idea.

Accessing bash command line args $@ vs $*

$*

Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, it expands to a single word with the value of each parameter separated by the first character of the IFS special variable. That is, "$*" is equivalent to "$1c$2c...", where c is the first character of the value of the IFS variable. If IFS is unset, the parameters are separated by spaces. If IFS is null, the parameters are joined without intervening separators.

$@

Expands to the positional parameters, starting from one. When the expansion occurs within double quotes, each parameter expands to a separate word. That is, "$@" is equivalent to "$1" "$2" ... If the double-quoted expansion occurs within a word, the expansion of the first parameter is joined with the beginning part of the original word, and the expansion of the last parameter is joined with the last part of the original word. When there are no positional parameters, "$@" and $@ expand to nothing (i.e., they are removed).

Source: Bash man

Javascript - How to detect if document has loaded (IE 7/Firefox 3)

Try this:

var body = document.getElementsByTagName('BODY')[0];
// CONDITION DOES NOT WORK
if ((body && body.readyState == 'loaded') || (body &&  body.readyState == 'complete') ) {
    DoStuffFunction();
} else {
    // CODE BELOW WORKS
    if (window.addEventListener) {
        window.addEventListener('load', DoStuffFunction, false);
    } else {
        window.attachEvent('onload',DoStuffFunction);
    }
}

Powershell Invoke-WebRequest Fails with SSL/TLS Secure Channel

It works for me...

if (-not ([System.Management.Automation.PSTypeName]'ServerCertificateValidationCallback').Type)
    {
    $certCallback = @"
        using System;
        using System.Net;
        using System.Net.Security;
        using System.Security.Cryptography.X509Certificates;
        public class ServerCertificateValidationCallback
        {
            public static void Ignore()
            {
                if(ServicePointManager.ServerCertificateValidationCallback ==null)
                {
                    ServicePointManager.ServerCertificateValidationCallback += 
                        delegate
                        (
                            Object obj, 
                            X509Certificate certificate, 
                            X509Chain chain, 
                            SslPolicyErrors errors
                        )
                        {
                            return true;
                        };
                }
            }
        }
    "@
        Add-Type $certCallback
     }
    [ServerCertificateValidationCallback]::Ignore()

Invoke-WebRequest -Uri https://apod.nasa.gov/apod/

JavaScript checking for null vs. undefined and difference between == and ===

undefined

It means the variable is not yet intialized .

Example :

var x;
if(x){ //you can check like this
   //code.
}

equals(==)

It only check value is equals not datatype .

Example :

var x = true;
var y = new Boolean(true);
x == y ; //returns true

Because it checks only value .

Strict Equals(===)

Checks the value and datatype should be same .

Example :

var x = true;
var y = new Boolean(true);
x===y; //returns false.

Because it checks the datatype x is a primitive type and y is a boolean object .

How to get item's position in a list?

Just to illustrate complete example along with the input_list which has searies1 (example: input_list[0]) in which you want to do a lookup of series2 (example: input_list[1]) and get indexes of series2 if it exists in series1.

Note: Your certain condition will go in lambda expression if conditions are simple

input_list = [[1,2,3,4,5,6,7],[1,3,7]]
series1 = input_list[0]
series2 = input_list[1]
idx_list = list(map(lambda item: series1.index(item) if item in series1 else None, series2))
print(idx_list)

output:

[0, 2, 6]

Command Line Tools not working - OS X El Capitan, Sierra, High Sierra, Mojave

Updated to High Sierra 10.13.2

xcode-select --install ALONE did not work for me.

  1. Download X-code from app store
  2. $xcode-select --install
    a. May need to update after install using softwareupdate in command line. $sudo softwareupdate -i "Command Line Tools (macOS High Sierra version 10.13) for Xcode-9.1"

  3. $sudo xcodebuild -license

How to get the connection String from a database

put below tag in web.config file in configuration node

 <connectionStrings>
<add name="NameOFConnectionString" connectionString="Data Source=Server;Initial Catalog=DatabaseName;User ID=User;Password=Pwd"
  providerName="System.Data.SqlClient" />

then you can use above connectionstring, e.g.

SqlConnection con = new SqlConnection();
            con.ConnectionString = ConfigurationManager.ConnectionStrings["NameOFConnectionString"].ToString();

To get specific part of a string in c#

Something like this?

string b = a.Split(',')[0];

Convert a double to a QString

Use QString's number method (docs are here):

double valueAsDouble = 1.2;
QString valueAsString = QString::number(valueAsDouble);

Ruby - test for array

Instead of testing for an Array, just convert whatever you get into a one-level Array, so your code only needs to handle the one case.

t = [*something]     # or...
t = Array(something) # or...
def f *x
    ...
end

Ruby has various ways to harmonize an API which can take an object or an Array of objects, so, taking a guess at why you want to know if something is an Array, I have a suggestion.

The splat operator contains lots of magic you can look up, or you can just call Array(something) which will add an Array wrapper if needed. It's similar to [*something] in this one case.

def f x
  p Array(x).inspect
  p [*x].inspect
end
f 1         # => "[1]"
f [1]       # => "[1]"
f [1,2]     # => "[1, 2]"

Or, you could use the splat in the parameter declaration and then .flatten, giving you a different sort of collector. (For that matter, you could call .flatten above, too.)

def f *x
  p x.flatten.inspect
end         # => nil
f 1         # => "[1]"
f 1,2       # => "[1, 2]"
f [1]       # => "[1]"
f [1,2]     # => "[1, 2]"
f [1,2],3,4 # => "[1, 2, 3, 4]"

And, thanks gregschlom, it's sometimes faster to just use Array(x) because when it's already an Array it doesn't need to create a new object.

What's the difference between interface and @interface in java?

The @ symbol denotes an annotation type definition.

That means it is not really an interface, but rather a new annotation type -- to be used as a function modifier, such as @override.

See this javadocs entry on the subject.

How to convert an enum type variable to a string?

A little late to the party, but here's my C++11 solution:

namespace std {
    template<> struct hash<enum_one> {
        std::size_t operator()(const enum_one & e) const {
            return static_cast<std::size_t>(e);
        }
    };
    template<> struct hash<enum_two> { //repeat for each enum type
        std::size_t operator()(const enum_two & e) const {
            return static_cast<std::size_t>(e);
        }
    };
}

const std::string & enum_name(const enum_one & e) {
    static const std::unordered_map<enum_one, const std::string> names = {
    #define v_name(n) {enum_one::n, std::string(#n)}
        v_name(value1),
        v_name(value2),
        v_name(value3)
    #undef v_name
    };
    return names.at(e);
}

const std::string & enum_name(const enum_two & e) { //repeat for each enum type
    .................
}

How do I call a JavaScript function on page load?

Your original question was unclear, assuming Kevin's edit/interpretation is correct then this first option doesn't apply

The typical options is using the onload event:

<body onload="javascript:SomeFunction()">
....

You can also place your javascript at the very end of the body; it won't start executing until the doc is complete.

<body>
  ...
  <script type="text/javascript">
    SomeFunction();
  </script>
</body>

And, another options, is to consider using a JS framework which intrinsically does this:

// jQuery
$(document).ready( function () {
  SomeFunction();
});

Gaussian fit for Python

After losing hours trying to find my error, the problem is your formula:

sigma = sum(y*(x-mean)**2)/n

This previous formula is wrong, the correct formula is the square root of this!;

sqrt(sum(y*(x-mean)**2)/n)

Hope this helps

How to use multiprocessing pool.map with multiple arguments?

Using Python 3.3+ with pool.starmap():

from multiprocessing.dummy import Pool as ThreadPool 

def write(i, x):
    print(i, "---", x)

a = ["1","2","3"]
b = ["4","5","6"] 

pool = ThreadPool(2)
pool.starmap(write, zip(a,b)) 
pool.close() 
pool.join()

Result:

1 --- 4
2 --- 5
3 --- 6

You can also zip() more arguments if you like: zip(a,b,c,d,e)

In case you want to have a constant value passed as an argument you have to use import itertools and then zip(itertools.repeat(constant), a) for example.

Trying to read cell 1,1 in spreadsheet using Google Script API

You have to first obtain the Range object. Also, getCell() will not return the value of the cell but instead will return a Range object of the cell. So, use something on the lines of

function email() {

// Opens SS by its ID

var ss = SpreadsheetApp.openById("0AgJjDgtUl5KddE5rR01NSFcxYTRnUHBCQ0stTXNMenc");

// Get the name of this SS

var name = ss.getName();  // Not necessary 

// Read cell 1,1 * Line below does't work *

// var data = Range.getCell(0, 0);
var sheet = ss.getSheetByName('Sheet1'); // or whatever is the name of the sheet 
var range = sheet.getRange(1,1); 
var data = range.getValue();

}

The hierarchy is Spreadsheet --> Sheet --> Range --> Cell.

Eclipse change project files location

You can copy your .classpath and .project files to the root of the new project directory and then choose 'Import...' from the file menu, and select 'General/Existing Projects into Workspace.' In the resulting dialog, locate the root of the new project directory and finish. Make sure that you have deleted the old project from the work space before importing.

state provider and route provider in angularJS

You shouldn't use both ngRoute and UI-router. Here's a sample code for UI-router:

_x000D_
_x000D_
repoApp.config(function($stateProvider, $urlRouterProvider) {_x000D_
  _x000D_
  $stateProvider_x000D_
    .state('state1', {_x000D_
      url: "/state1",_x000D_
      templateUrl: "partials/state1.html",_x000D_
      controller: 'YourCtrl'_x000D_
    })_x000D_
    _x000D_
    .state('state2', {_x000D_
      url: "/state2",_x000D_
      templateUrl: "partials/state2.html",_x000D_
      controller: 'YourOtherCtrl'_x000D_
    });_x000D_
    $urlRouterProvider.otherwise("/state1");_x000D_
});_x000D_
//etc.
_x000D_
_x000D_
_x000D_

You can find a great answer on the difference between these two in this thread: What is the difference between angular-route and angular-ui-router?

You can also consult UI-Router's docs here: https://github.com/angular-ui/ui-router

Display JSON as HTML

I think you meant something like this: JSON Visualization

Don't know if you might use it, but you might ask the author.

Two way sync with rsync

I'm now using SparkleShare https://www.sparkleshare.org/

works on mac, linux and windows.

Find size and free space of the filesystem containing a given file

As of Python 3.3, there an easy and direct way to do this with the standard library:

$ cat free_space.py 
#!/usr/bin/env python3

import shutil

total, used, free = shutil.disk_usage(__file__)
print(total, used, free)

$ ./free_space.py 
1007870246912 460794834944 495854989312

These numbers are in bytes. See the documentation for more info.

How to convert XML to JSON in Python?

In general, you want to go from XML to regular objects of your language (since there are usually reasonable tools to do this, and it's the harder conversion). And then from Plain Old Object produce JSON -- there are tools for this, too, and it's a quite simple serialization (since JSON is "Object Notation", natural fit for serializing objects). I assume Python has its set of tools.

Android: converting String to int

You can not convert to string if your integer value is zero or starts with zero (in which case 1st zero will be neglected). Try change.

int NUM=null;

Access XAMPP Localhost from Internet

I know this very old but for future's sake:

I also used a dynamic dns provider. Wanted to test the website (IIS) BEHIND my (home) router. So i thought i use something like this:

my.dynamic.dnss.ip:8080 (because my router's port 80 was used to admin it).

So this seemed to be the only solution.
But: Paypal seemed to not like port 8080: only port 80 and 443 are allowed (don't know why!!)

Password hash function for Excel VBA

Here's a module for calculating SHA1 hashes that is usable for Excel formulas eg. '=SHA1HASH("test")'. To use it, make a new module called 'module_sha1' and copy and paste it all in. This is based on some VBA code from http://vb.wikia.com/wiki/SHA-1.bas, with changes to support passing it a string, and executable from formulas in Excel cells.

' Based on: http://vb.wikia.com/wiki/SHA-1.bas
Option Explicit

Private Type FourBytes
    A As Byte
    B As Byte
    C As Byte
    D As Byte
End Type
Private Type OneLong
    L As Long
End Type

Function HexDefaultSHA1(Message() As Byte) As String
 Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long
 DefaultSHA1 Message, H1, H2, H3, H4, H5
 HexDefaultSHA1 = DecToHex5(H1, H2, H3, H4, H5)
End Function

Function HexSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long) As String
 Dim H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long
 xSHA1 Message, Key1, Key2, Key3, Key4, H1, H2, H3, H4, H5
 HexSHA1 = DecToHex5(H1, H2, H3, H4, H5)
End Function

Sub DefaultSHA1(Message() As Byte, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long)
 xSHA1 Message, &H5A827999, &H6ED9EBA1, &H8F1BBCDC, &HCA62C1D6, H1, H2, H3, H4, H5
End Sub

Sub xSHA1(Message() As Byte, ByVal Key1 As Long, ByVal Key2 As Long, ByVal Key3 As Long, ByVal Key4 As Long, H1 As Long, H2 As Long, H3 As Long, H4 As Long, H5 As Long)
 'CA62C1D68F1BBCDC6ED9EBA15A827999 + "abc" = "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D"
 '"abc" = "A9993E36 4706816A BA3E2571 7850C26C 9CD0D89D"

 Dim U As Long, P As Long
 Dim FB As FourBytes, OL As OneLong
 Dim i As Integer
 Dim W(80) As Long
 Dim A As Long, B As Long, C As Long, D As Long, E As Long
 Dim T As Long

 H1 = &H67452301: H2 = &HEFCDAB89: H3 = &H98BADCFE: H4 = &H10325476: H5 = &HC3D2E1F0

 U = UBound(Message) + 1: OL.L = U32ShiftLeft3(U): A = U \ &H20000000: LSet FB = OL 'U32ShiftRight29(U)

 ReDim Preserve Message(0 To (U + 8 And -64) + 63)
 Message(U) = 128

 U = UBound(Message)
 Message(U - 4) = A
 Message(U - 3) = FB.D
 Message(U - 2) = FB.C
 Message(U - 1) = FB.B
 Message(U) = FB.A

 While P < U
     For i = 0 To 15
         FB.D = Message(P)
         FB.C = Message(P + 1)
         FB.B = Message(P + 2)
         FB.A = Message(P + 3)
         LSet OL = FB
         W(i) = OL.L
         P = P + 4
     Next i

     For i = 16 To 79
         W(i) = U32RotateLeft1(W(i - 3) Xor W(i - 8) Xor W(i - 14) Xor W(i - 16))
     Next i

     A = H1: B = H2: C = H3: D = H4: E = H5

     For i = 0 To 19
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key1), ((B And C) Or ((Not B) And D)))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 20 To 39
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key2), (B Xor C Xor D))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 40 To 59
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key3), ((B And C) Or (B And D) Or (C And D)))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i
     For i = 60 To 79
         T = U32Add(U32Add(U32Add(U32Add(U32RotateLeft5(A), E), W(i)), Key4), (B Xor C Xor D))
         E = D: D = C: C = U32RotateLeft30(B): B = A: A = T
     Next i

     H1 = U32Add(H1, A): H2 = U32Add(H2, B): H3 = U32Add(H3, C): H4 = U32Add(H4, D): H5 = U32Add(H5, E)
 Wend
End Sub

Function U32Add(ByVal A As Long, ByVal B As Long) As Long
 If (A Xor B) < 0 Then
     U32Add = A + B
 Else
     U32Add = (A Xor &H80000000) + B Xor &H80000000
 End If
End Function

Function U32ShiftLeft3(ByVal A As Long) As Long
 U32ShiftLeft3 = (A And &HFFFFFFF) * 8
 If A And &H10000000 Then U32ShiftLeft3 = U32ShiftLeft3 Or &H80000000
End Function

Function U32ShiftRight29(ByVal A As Long) As Long
 U32ShiftRight29 = (A And &HE0000000) \ &H20000000 And 7
End Function

Function U32RotateLeft1(ByVal A As Long) As Long
 U32RotateLeft1 = (A And &H3FFFFFFF) * 2
 If A And &H40000000 Then U32RotateLeft1 = U32RotateLeft1 Or &H80000000
 If A And &H80000000 Then U32RotateLeft1 = U32RotateLeft1 Or 1
End Function
Function U32RotateLeft5(ByVal A As Long) As Long
 U32RotateLeft5 = (A And &H3FFFFFF) * 32 Or (A And &HF8000000) \ &H8000000 And 31
 If A And &H4000000 Then U32RotateLeft5 = U32RotateLeft5 Or &H80000000
End Function
Function U32RotateLeft30(ByVal A As Long) As Long
 U32RotateLeft30 = (A And 1) * &H40000000 Or (A And &HFFFC) \ 4 And &H3FFFFFFF
 If A And 2 Then U32RotateLeft30 = U32RotateLeft30 Or &H80000000
End Function

Function DecToHex5(ByVal H1 As Long, ByVal H2 As Long, ByVal H3 As Long, ByVal H4 As Long, ByVal H5 As Long) As String
 Dim H As String, L As Long
 DecToHex5 = "00000000 00000000 00000000 00000000 00000000"
 H = Hex(H1): L = Len(H): Mid(DecToHex5, 9 - L, L) = H
 H = Hex(H2): L = Len(H): Mid(DecToHex5, 18 - L, L) = H
 H = Hex(H3): L = Len(H): Mid(DecToHex5, 27 - L, L) = H
 H = Hex(H4): L = Len(H): Mid(DecToHex5, 36 - L, L) = H
 H = Hex(H5): L = Len(H): Mid(DecToHex5, 45 - L, L) = H
End Function

' Convert the string into bytes so we can use the above functions
' From Chris Hulbert: http://splinter.com.au/blog

Public Function SHA1HASH(str)
  Dim i As Integer
  Dim arr() As Byte
  ReDim arr(0 To Len(str) - 1) As Byte
  For i = 0 To Len(str) - 1
   arr(i) = Asc(Mid(str, i + 1, 1))
  Next i
  SHA1HASH = Replace(LCase(HexDefaultSHA1(arr)), " ", "")
End Function

Is there any way of configuring Eclipse IDE proxy settings via an autoproxy configuration script?

Download proxy script and check last line for return statement Proxy IP and Port.
Add this IP and Port using these step.

   1.  Windows -->Preferences-->General -->Network Connection
   2. Select Active Provider : Manual
   3.  Proxy entries select HTTP--> Click on Edit button
   4.  Then add Host as a proxy IP and port left Required Authentication blank.
   5.  Restart eclipse
   6.  Now Eclipse Marketplace... working.

RSA encryption and decryption in Python

# coding: utf-8
from __future__ import unicode_literals
import base64
import os

import six
from Crypto import Random
from Crypto.PublicKey import RSA


class PublicKeyFileExists(Exception): pass


class RSAEncryption(object):
    PRIVATE_KEY_FILE_PATH = None
    PUBLIC_KEY_FILE_PATH = None

    def encrypt(self, message):
        public_key = self._get_public_key()
        public_key_object = RSA.importKey(public_key)
        random_phrase = 'M'
        encrypted_message = public_key_object.encrypt(self._to_format_for_encrypt(message), random_phrase)[0]
        # use base64 for save encrypted_message in database without problems with encoding
        return base64.b64encode(encrypted_message)

    def decrypt(self, encoded_encrypted_message):
        encrypted_message = base64.b64decode(encoded_encrypted_message)
        private_key = self._get_private_key()
        private_key_object = RSA.importKey(private_key)
        decrypted_message = private_key_object.decrypt(encrypted_message)
        return six.text_type(decrypted_message, encoding='utf8')

    def generate_keys(self):
        """Be careful rewrite your keys"""
        random_generator = Random.new().read
        key = RSA.generate(1024, random_generator)
        private, public = key.exportKey(), key.publickey().exportKey()

        if os.path.isfile(self.PUBLIC_KEY_FILE_PATH):
            raise PublicKeyFileExists('???? ? ????????? ?????? ??????????. ??????? ????')
        self.create_directories()

        with open(self.PRIVATE_KEY_FILE_PATH, 'w') as private_file:
            private_file.write(private)
        with open(self.PUBLIC_KEY_FILE_PATH, 'w') as public_file:
            public_file.write(public)
        return private, public

    def create_directories(self, for_private_key=True):
        public_key_path = self.PUBLIC_KEY_FILE_PATH.rsplit('/', 1)
        if not os.path.exists(public_key_path):
            os.makedirs(public_key_path)
        if for_private_key:
            private_key_path = self.PRIVATE_KEY_FILE_PATH.rsplit('/', 1)
            if not os.path.exists(private_key_path):
                os.makedirs(private_key_path)

    def _get_public_key(self):
        """run generate_keys() before get keys """
        with open(self.PUBLIC_KEY_FILE_PATH, 'r') as _file:
            return _file.read()

    def _get_private_key(self):
        """run generate_keys() before get keys """
        with open(self.PRIVATE_KEY_FILE_PATH, 'r') as _file:
            return _file.read()

    def _to_format_for_encrypt(value):
        if isinstance(value, int):
            return six.binary_type(value)
        for str_type in six.string_types:
            if isinstance(value, str_type):
                return value.encode('utf8')
        if isinstance(value, six.binary_type):
            return value

And use

KEYS_DIRECTORY = settings.SURVEY_DIR_WITH_ENCRYPTED_KEYS

class TestingEncryption(RSAEncryption):
    PRIVATE_KEY_FILE_PATH = KEYS_DIRECTORY + 'private.key'
    PUBLIC_KEY_FILE_PATH = KEYS_DIRECTORY + 'public.key'


# django/flask
from django.core.files import File

class ProductionEncryption(RSAEncryption):
    PUBLIC_KEY_FILE_PATH = settings.SURVEY_DIR_WITH_ENCRYPTED_KEYS + 'public.key'

    def _get_private_key(self):
        """run generate_keys() before get keys """
        from corportal.utils import global_elements
        private_key = global_elements.request.FILES.get('private_key')
        if private_key:
            private_key_file = File(private_key)
            return private_key_file.read()

message = 'Hello ??? friend'
encrypted_mes = ProductionEncryption().encrypt(message)
decrypted_mes = ProductionEncryption().decrypt(message)

How in node to split string by newline ('\n')?

If the file is native to your system (certainly no guarantees of that), then Node can help you out:

var os = require('os');

a.split(os.EOL);

This is usually more useful for constructing output strings from Node though, for platform portability.

How are VST Plugins made?

Start with this link to the wiki, explains what they are and gives links to the sdk. Here is some information regarding the deve

How to compile a plugin - For making VST plugins in C++Builder, first you need the VST sdk by Steinberg. It's available from the Yvan Grabit's site (the link is at the top of the page).

The next thing you need to do is create a .def file (for example : myplugin.def). This needs to contain at least the following lines:

EXPORTS main=_main

Borland compilers add an underscore to function names, and this exports the main() function the way a VST host expects it. For more information about .def files, see the C++Builder help files.

This is not enough, though. If you're going to use any VCL element (anything to do with forms or components), you have to take care your plugin doesn't crash Cubase (or another VST host, for that matter). Here's how:

  1. Include float.h.
  2. In the constructor of your effect class, write

    _control87(PC_64|MCW_EM,MCW_PC|MCW_EM);
    

That should do the trick.

Here are some more useful sites:

http://www.steinberg.net/en/company/developer.html

how to write a vst plugin (pdf) via http://www.asktoby.com/#vsttutorial

How do I include a JavaScript file in another JavaScript file?

The old versions of JavaScript had no import, include, or require, so many different approaches to this problem have been developed.

But since 2015 (ES6), JavaScript has had the ES6 modules standard to import modules in Node.js, which is also supported by most modern browsers.

For compatibility with older browsers, build tools like Webpack and Rollup and/or transpilation tools like Babel can be used.

ES6 Modules

ECMAScript (ES6) modules have been supported in Node.js since v8.5, with the --experimental-modules flag, and since at least Node.js v13.8.0 without the flag. To enable "ESM" (vs. Node.js's previous CommonJS-style module system ["CJS"]) you either use "type": "module" in package.json or give the files the extension .mjs. (Similarly, modules written with Node.js's previous CJS module can be named .cjs if your default is ESM.)

Using package.json:

{
    "type": "module"
}

Then module.js:

export function hello() {
  return "Hello";
}

Then main.js:

import { hello } from './module.js';
let val = hello();  // val is "Hello";

Using .mjs, you'd have module.mjs:

export function hello() {
  return "Hello";
}

Then main.mjs:

import { hello } from './module.mjs';
let val = hello();  // val is "Hello";

ECMAScript modules in browsers

Browsers have had support for loading ECMAScript modules directly (no tools like Webpack required) since Safari 10.1, Chrome 61, Firefox 60, and Edge 16. Check the current support at caniuse. There is no need to use Node.js' .mjs extension; browsers completely ignore file extensions on modules/scripts.

<script type="module">
  import { hello } from './hello.mjs'; // Or it could be simply `hello.js`
  hello('world');
</script>
// hello.mjs -- or it could be simply `hello.js`
export function hello(text) {
  const div = document.createElement('div');
  div.textContent = `Hello ${text}`;
  document.body.appendChild(div);
}

Read more at https://jakearchibald.com/2017/es-modules-in-browsers/

Dynamic imports in browsers

Dynamic imports let the script load other scripts as needed:

<script type="module">
  import('hello.mjs').then(module => {
      module.hello('world');
    });
</script>

Read more at https://developers.google.com/web/updates/2017/11/dynamic-import

Node.js require

The older CJS module style, still widely used in Node.js, is the module.exports/require system.

// mymodule.js
module.exports = {
   hello: function() {
      return "Hello";
   }
}
// server.js
const myModule = require('./mymodule');
let val = myModule.hello(); // val is "Hello"   

There are other ways for JavaScript to include external JavaScript contents in browsers that do not require preprocessing.

AJAX Loading

You could load an additional script with an AJAX call and then use eval to run it. This is the most straightforward way, but it is limited to your domain because of the JavaScript sandbox security model. Using eval also opens the door to bugs, hacks and security issues.

Fetch Loading

Like Dynamic Imports you can load one or many scripts with a fetch call using promises to control order of execution for script dependencies using the Fetch Inject library:

fetchInject([
  'https://cdn.jsdelivr.net/momentjs/2.17.1/moment.min.js'
]).then(() => {
  console.log(`Finish in less than ${moment().endOf('year').fromNow(true)}`)
})

jQuery Loading

The jQuery library provides loading functionality in one line:

$.getScript("my_lovely_script.js", function() {
   alert("Script loaded but not necessarily executed.");
});

Dynamic Script Loading

You could add a script tag with the script URL into the HTML. To avoid the overhead of jQuery, this is an ideal solution.

The script can even reside on a different server. Furthermore, the browser evaluates the code. The <script> tag can be injected into either the web page <head>, or inserted just before the closing </body> tag.

Here is an example of how this could work:

function dynamicallyLoadScript(url) {
    var script = document.createElement("script");  // create a script DOM node
    script.src = url;  // set its src to the provided URL

    document.head.appendChild(script);  // add it to the end of the head section of the page (could change 'head' to 'body' to add it to the end of the body section instead)
}

This function will add a new <script> tag to the end of the head section of the page, where the src attribute is set to the URL which is given to the function as the first parameter.

Both of these solutions are discussed and illustrated in JavaScript Madness: Dynamic Script Loading.

Detecting when the script has been executed

Now, there is a big issue you must know about. Doing that implies that you remotely load the code. Modern web browsers will load the file and keep executing your current script because they load everything asynchronously to improve performance. (This applies to both the jQuery method and the manual dynamic script loading method.)

It means that if you use these tricks directly, you won't be able to use your newly loaded code the next line after you asked it to be loaded, because it will be still loading.

For example: my_lovely_script.js contains MySuperObject:

var js = document.createElement("script");

js.type = "text/javascript";
js.src = jsFilePath;

document.body.appendChild(js);

var s = new MySuperObject();

Error : MySuperObject is undefined

Then you reload the page hitting F5. And it works! Confusing...

So what to do about it ?

Well, you can use the hack the author suggests in the link I gave you. In summary, for people in a hurry, he uses an event to run a callback function when the script is loaded. So you can put all the code using the remote library in the callback function. For example:

function loadScript(url, callback)
{
    // Adding the script tag to the head as suggested before
    var head = document.head;
    var script = document.createElement('script');
    script.type = 'text/javascript';
    script.src = url;

    // Then bind the event to the callback function.
    // There are several events for cross browser compatibility.
    script.onreadystatechange = callback;
    script.onload = callback;

    // Fire the loading
    head.appendChild(script);
}

Then you write the code you want to use AFTER the script is loaded in a lambda function:

var myPrettyCode = function() {
   // Here, do whatever you want
};

Then you run all that:

loadScript("my_lovely_script.js", myPrettyCode);

Note that the script may execute after the DOM has loaded, or before, depending on the browser and whether you included the line script.async = false;. There's a great article on Javascript loading in general which discusses this.

Source Code Merge/Preprocessing

As mentioned at the top of this answer, many developers use build/transpilation tool(s) like Parcel, Webpack, or Babel in their projects, allowing them to use upcoming JavaScript syntax, provide backward compatibility for older browsers, combine files, minify, perform code splitting etc.

jQuery ajax error function

You can use something like this:
note: responseText returns server response and statusText returns the predefined
message for status error.for e.g:
responseText returns something like "Not Found (#404)" in some frameworks like Yii2 but
statusText returns "Not Found".

$.ajax({
    cache: false,
    url: "addInterview_Code.asp",
    type: "POST",
    datatype: "text",
    data: strData,
    success: function (html) {
        alert('successful : ' + html);
        $("#result").html("Successful");
    },
    error: function (data) {
        console.log(data.status + ':' + data.statusText,data.responseText);
    }
});

How do I resolve "Cannot find module" error using Node.js?

Removing node/npm and then re-installing the stable(not the latest) version worked for me.

sudo rm -rf /usr/local/{lib/node{,/.npm,_modules},bin,share/man}/{npm*,node*,man1/node*}

https://nodejs.org/en/download/

How to decompile a whole Jar file?

If you happen to have both a bash shell and jad:

JAR=(your jar file name)
unzip -d $JAR.tmp $JAR
pushd $JAR.tmp
for f in `find . -name '*.class'`; do
    jad -d $(dirname $f) -s java -lnc $f
done
popd

I might be a tiny, tiny bit off with that, but it should work more or less as advertised. You should end up with $JAR.tmp containing your decompiled files.

How to force a hover state with jQuery?

Also, you could try triggering a mouseover.

$("#btn").click(function() {
   $("#link").trigger("mouseover");
});

Not sure if this will work for your specific scenario, but I've had success triggering mouseover instead of hover for various cases.

How do I debug a stand-alone VBScript script?

This is for future readers. I found that the simplest method for me was to use Visual Studio -> Tools -> External Tools. More details in this answer.

Easier to use and good debugging tools.

My kubernetes pods keep crashing with "CrashLoopBackOff" but I can't find any log

Whilst troubleshooting the same issue I found no logs when using kubeclt logs <pod_id>. Therefore I ssh:ed in to the node instance to try to run the container using plain docker. To my surprise this failed also.

When entering the container with:

docker exec -it faulty:latest /bin/sh

and poking around I found that it wasn't the latest version.

A faulty version of the docker image was already available on the instance.

When I removed the faulty:latest instance with:

docker rmi faulty:latest

everything started to work.

How to comment multiple lines in Visual Studio Code?

You can see all available keybindings on the official documentation.

Here's the relevant bit for osx:

Key     Command

?K ?C   Add Line Comment    
?K ?U   Remove Line Comment 
?/      Toggle Line Comment 
??A     Toggle Block Comment

You will need to select the lines you want to comment first, then execute above shortcut, i.e. ?/ on osx Ctrl/ on Windows.

Handling a timeout error in python sockets

When you do from socket import * python is loading a socket module to the current namespace. Thus you can use module's members as if they are defined within your current python module.

When you do import socket, a module is loaded in a separate namespace. When you are accessing its members, you should prefix them with a module name. For example, if you want to refer to a socket class, you will need to write client_socket = socket.socket(socket.AF_INET,socket.SOCK_DGRAM).

As for the problem with timeout - all you need to do is to change except socket.Timeouterror: to except timeout:, since timeout class is defined inside socket module and you have imported all its members to your namespace.

How To Raise Property Changed events on a Dependency Property?

I agree with Sam and Xaser and have actually taken this a bit farther. I don't think you should be implementing the INotifyPropertyChanged interface in a UserControl at all...the control is already a DependencyObject and therefore already comes with notifications. Adding INotifyPropertyChanged to a DependencyObject is redundant and "smells" wrong to me.

What I did is implement both properties as DependencyProperties, as Sam suggests, but then simply had the PropertyChangedCallback from the "first" dependency property alter the value of the "second" dependency property. Since both are dependency properties, both will automatically raise change notifications to any interested subscribers (e.g. data binding etc.)

In this case, dependency property A is the string InviteText, which triggers a change in dependency property B, the Visibility property named ShowInvite. This would be a common use case if you have some text that you want to be able to hide completely in a control via data binding.

public string InviteText  
{
    get { return (string)GetValue(InviteTextProperty); }
    set { SetValue(InviteTextProperty, value); }
}

public static readonly DependencyProperty InviteTextProperty =
    DependencyProperty.Register("InviteText", typeof(string), typeof(InvitePrompt), new UIPropertyMetadata(String.Empty, OnInviteTextChanged));

private static void OnInviteTextChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
{
    InvitePrompt prompt = d as InvitePrompt;
    if (prompt != null)
    {
        string text = e.NewValue as String;
        prompt.ShowInvite = String.IsNullOrWhiteSpace(text) ? Visibility.Collapsed : Visibility.Visible;
    }
}

public Visibility ShowInvite
{
    get { return (Visibility)GetValue(ShowInviteProperty); }
    set { SetValue(ShowInviteProperty, value); }
}

public static readonly DependencyProperty ShowInviteProperty =
    DependencyProperty.Register("ShowInvite", typeof(Visibility), typeof(InvitePrompt), new PropertyMetadata(Visibility.Collapsed));

Note I'm not including the UserControl signature or constructor here because there is nothing special about them; they don't need to subclass from INotifyPropertyChanged at all.

How to check if a query string value is present via JavaScript?

Using URL:

url = new URL(window.location.href);

if (url.searchParams.get('test')) {

}

EDIT: if you're sad about compatibility, I'd highly suggest https://github.com/medialize/URI.js/.

In PHP, how do you change the key of an array element?

Simple benchmark comparison of both solution.

Solution 1 Copy and remove (order lost, but way faster) https://stackoverflow.com/a/240676/1617857

<?php
$array = ['test' => 'value'];

$array['test2'] = $array['test'];
unset($array['test']);

Solution 2 Rename the key https://stackoverflow.com/a/21299719/1617857

<?php
$array = ['test' => 'value'];

$keys = array_keys( $array );
$keys[array_search('test', $keys, true)] = 'test2';
array_combine( $keys, $array );

Benchmark:

<?php
$array = ['test' => 'value'];


for ($i =0; $i < 100000000; $i++){
    // Solution 1
}


for ($i =0; $i < 100000000; $i++){
    // Solution 2
}

Results:

php solution1.php  6.33s  user 0.02s system 99% cpu 6.356  total
php solution1.php  6.37s  user 0.01s system 99% cpu 6.390  total
php solution2.php  12.14s user 0.01s system 99% cpu 12.164 total
php solution2.php  12.57s user 0.03s system 99% cpu 12.612 total

Getting value of selected item in list box as string

The correct solution seems to be:

string text = ((ListBoxItem)ListBox1.SelectedItem).Content.ToString();

Please be sure to use .Content and not .Name.

Import CSV to SQLite

I am merging info from previous answers here with my own experience. The easiest is to add the comma-separated table headers directly to your csv file, followed by a new line, and then all your csv data.

If you are never doing sqlite stuff again (like me), this might save you a web search or two:

In the Sqlite shell enter:

$ sqlite3 yourfile.sqlite
sqlite>  .mode csv
sqlite>  .import test.csv yourtable
sqlite>  .exit

If you haven't got Sqlite installed on your Mac, run

$ brew install sqlite3

You may need to do one web search for how to install Homebrew.

I have 2 dates in PHP, how can I run a foreach loop to go through all of those days?

here's a way:

 $date = new Carbon();
 $dtStart = $date->startOfMonth();
 $dtEnd = $dtStart->copy()->endOfMonth();

 $weekendsInMoth = [];
 while ($dtStart->diffInDays($dtEnd)) {

     if($dtStart->isWeekend()) {
            $weekendsInMoth[] = $dtStart->copy();
     }

     $dtStart->addDay();
 }

The result of $weekendsInMoth is array of weekend days!

Bootstrap 4: responsive sidebar menu to top navbar

If this isn't a good solution for any reason, please let me know. It worked fine for me.

What I did is to hide the Sidebar and then make appear the navbar with breakpoints

@media screen and (max-width: 771px) {
    #fixed-sidebar {
        display: none;
    }
    #navbar-superior {
        display: block !important;
    }
}

Adding a dictionary to another

The most obvious way is:

foreach(var kvp in NewAnimals)
   Animals.Add(kvp.Key, kvp.Value); 
  //use Animals[kvp.Key] = kvp.Value instead if duplicate keys are an issue

Since Dictionary<TKey, TValue>explicitly implements theICollection<KeyValuePair<TKey, TValue>>.Addmethod, you can also do this:

var animalsAsCollection = (ICollection<KeyValuePair<string, string>>) Animals;

foreach(var kvp in NewAnimals)
   animalsAsCollection.Add(kvp);

It's a pity the class doesn't have anAddRangemethod likeList<T> does.

How to convert an Array to a Set in Java

I've written the below from the advice above - steal it... it's nice!

/**
 * Handy conversion to set
 */
public class SetUtil {
    /**
     * Convert some items to a set
     * @param items items
     * @param <T> works on any type
     * @return a hash set of the input items
     */
    public static <T> Set<T> asSet(T ... items) {
        return Stream.of(items).collect(Collectors.toSet());
    }
}

How to determine SSL cert expiration date from a PEM encoded certificate?

For MAC OSX (El Capitan) This modification of Nicholas' example worked for me.

for pem in /path/to/certs/*.pem; do
    printf '%s: %s\n' \
        "$(date -jf "%b %e %H:%M:%S %Y %Z" "$(openssl x509 -enddate -noout -in "$pem"|cut -d= -f 2)" +"%Y-%m-%d")" \
    "$pem";
done | sort

Sample Output:

2014-12-19: /path/to/certs/MDM_Certificate.pem
2015-11-13: /path/to/certs/MDM_AirWatch_Certificate.pem

macOS didn't like the --date= or --iso-8601 flags on my system.

Generating Random Passwords

This is short and it works great for me.

public static string GenerateRandomCode(int length)
{
    Random rdm = new Random();
    StringBuilder sb = new StringBuilder();

    for(int i = 0; i < length; i++)
        sb.Append(Convert.ToChar(rdm.Next(101,132)));

    return sb.ToString();
}

destination path already exists and is not an empty directory

What works for me is that, I created a new folder that doesn't contain any other files, and selected that new folder I created and put the clone there.

I hope this helps

Copying one structure to another

You can use the following solution to accomplish your goal:

struct student 
{
    char name[20];
    char country[20];
};
void main()
{
    struct student S={"Wolverine","America"};
    struct student X;
    X=S;
    printf("%s%s",X.name,X.country);
}

how to measure running time of algorithms in python

The programming language doesn't matter; measuring the runtime complexity of an algorithm works the same way regardless of the language. Analysis of Algorithms by Stanford on Google Code University is a very good resource for teaching yourself how to analyze the runtime complexity of algorithms and code.

If all you want to do is measure the elapsed time that a function or section of code took to run in Python, then you can use the timeit or time modules, depending on how long the code needs to run.

C# adding a character in a string

I had to do something similar, trying to convert a string of numbers into a timespan by adding in : and .. Basically I was taking 235959999 and needing to convert it to 23:59:59.999. For me it was easy because I knew where I needed to "insert" said characters.

ts = ts.Insert(6,".");
ts = ts.Insert(4,":");
ts = ts.Insert(2,":");

Basically reassigning ts to itself with the inserted character. I worked my way from the back to front, because I was lazy and didn't want to do additional math for the other inserted characters.

You could try something similar by doing:

alpha = alpha.Insert(5,"-");
alpha = alpha.Insert(11,"-"); //add 1 to account for 1 -
alpha = alpha.Insert(17,"-"); //add 2 to account for 2 -
...

How to send a compressed archive that contains executables so that Google's attachment filter won't reject it

Another easy way to circumvent google's check is to use another compression algorithm with tar, like bz2:

tar -cvjf my.tar.bz2 dir/

Note that 'j' (for bz2 compression) is used above instead of 'z' (gzip compression).

Using HTML data-attribute to set CSS background-image url

HTML

<div class="thumb" data-image-src="img/image.png">

jQuery

$( ".thumb" ).each(function() {
  var attr = $(this).attr('data-image-src');

  if (typeof attr !== typeof undefined && attr !== false) {
      $(this).css('background', 'url('+attr+')');
  }

});

Demo on JSFiddle

You could do this also with JavaScript.

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

Here's one way to do it—there are many others:

bool b[4];
int v = 7;  // number to dissect

for (int j = 0;  j < 4;  ++j)
   b [j] =  0 != (v & (1 << j));

It is hard to understand why use of a loop is not desired, but it is easy enough to unroll the loop:

bool b[4];
int v = 7;  // number to dissect

b [0] =  0 != (v & (1 << 0));
b [1] =  0 != (v & (1 << 1));
b [2] =  0 != (v & (1 << 2));
b [3] =  0 != (v & (1 << 3));

Or evaluating constant expressions in the last four statements:

b [0] =  0 != (v & 1);
b [1] =  0 != (v & 2);
b [2] =  0 != (v & 4);
b [3] =  0 != (v & 8);

How to find integer array size in java

The length of an array is available as

int l = array.length;

The size of a List is availabe as

int s = list.size();

changing default x range in histogram matplotlib

plt.hist(hmag, 30, range=[6.5, 12.5], facecolor='gray', align='mid')

Multi-dimensional associative arrays in JavaScript

_x000D_
_x000D_
<script language="javascript">_x000D_
_x000D_
// Set values to variable_x000D_
var sectionName = "TestSection";_x000D_
var fileMap = "fileMapData";_x000D_
var fileId = "foobar";_x000D_
var fileValue= "foobar.png";_x000D_
var fileId2 = "barfoo";_x000D_
var fileValue2= "barfoo.jpg";_x000D_
_x000D_
// Create top-level image object_x000D_
var images = {};_x000D_
_x000D_
// Create second-level object in images object with_x000D_
// the name of sectionName value_x000D_
images[sectionName] = {};_x000D_
_x000D_
// Create a third level object_x000D_
var fileMapObj = {};_x000D_
_x000D_
// Add the third level object to the second level object_x000D_
images[sectionName][fileMap] = fileMapObj;_x000D_
_x000D_
// Add forth level associate array key and value data_x000D_
images[sectionName][fileMap][fileId] = fileValue;_x000D_
images[sectionName][fileMap][fileId2] = fileValue2;_x000D_
_x000D_
_x000D_
// All variables_x000D_
alert ("Example 1 Value: " + images[sectionName][fileMap][fileId]);_x000D_
_x000D_
// All keys with dots_x000D_
alert ("Example 2 Value: " + images.TestSection.fileMapData.foobar);_x000D_
_x000D_
// Mixed with a different final key_x000D_
alert ("Example 3 Value: " + images[sectionName]['fileMapData'][fileId2]);_x000D_
_x000D_
// Mixed brackets and dots..._x000D_
alert ("Example 4 Value: " + images[sectionName]['fileMapData'].barfoo);_x000D_
_x000D_
// This will FAIL! variable names must be in brackets!_x000D_
alert ("Example 5 Value: " + images[sectionName]['fileMapData'].fileId2);_x000D_
// Produces: "Example 5 Value: undefined"._x000D_
_x000D_
// This will NOT work either. Values must be quoted in brackets._x000D_
alert ("Example 6 Value: " + images[sectionName][fileMapData].barfoo);_x000D_
// Throws and exception and stops execution with error: fileMapData is not defined_x000D_
_x000D_
// We never get here because of the uncaught exception above..._x000D_
alert ("The End!");_x000D_
</script>
_x000D_
_x000D_
_x000D_

Div side by side without float

You can also use CSS3 flexbox layout, which is well supported nowadays.

.container {
    display: flex;
    flex-flow: row nowrap;
    justify-content: space-between;
    background:black;
    height:400px;
    width:450px;
}

.left {
    flex: 0 0 300px;
    background:blue;
    height:200px;
}

.right {
    flex: 0 1 100px;
    background:green;
    height:300px;
}

See Example (with legacy styles for maximum compatiblity) & Learn more about flexbox.

Convert a python UTC datetime to a local datetime using only python standard library?

This is a terrible way to do it but it avoids creating a definition. It fulfills the requirement to stick with the basic Python3 library.

# Adjust from UST to Eastern Standard Time (dynamic)
# df.my_localtime should already be in datetime format, so just in case
df['my_localtime'] = pd.to_datetime.df['my_localtime']

df['my_localtime'] = df['my_localtime'].dt.tz_localize('UTC').dt.tz_convert('America/New_York').astype(str)
df['my_localtime'] = pd.to_datetime(df.my_localtime.str[:-6])

How to assign execute permission to a .sh file in windows to be executed in linux

This is possible using the Info-Zip open-source Zip utilities. If unzip is run with the -X parameter, it will attempt to preserve the original permissions. If the source filesystem was NTFS and the destination is a Unix one, it will attempt to translate from one to the other. I do not have a Windows system available right now to test the translation, so you will have to experiment with which group needs to be awarded execute permissions. It'll be something like "Users" or "Any user"

How do I limit the number of results returned from grep?

For 2 use cases:

  1. I only want n overall results, not n results per file, the grep -m 2 is per file max occurrence.
  2. I often use git grep which doesn't take -m

A good alternative in these scenarios is grep | sed 2q to grep first 2 occurrences across all files. sed documentation: https://www.gnu.org/software/sed/manual/sed.html

Disable double-tap "zoom" option in browser on touch devices

I just wanted to answer my question properly as some people do not read the comments below an answer. So here it is:

(function($) {
  $.fn.nodoubletapzoom = function() {
      $(this).bind('touchstart', function preventZoom(e) {
        var t2 = e.timeStamp
          , t1 = $(this).data('lastTouch') || t2
          , dt = t2 - t1
          , fingers = e.originalEvent.touches.length;
        $(this).data('lastTouch', t2);
        if (!dt || dt > 500 || fingers > 1) return; // not double-tap

        e.preventDefault(); // double tap - prevent the zoom
        // also synthesize click events we just swallowed up
        $(this).trigger('click').trigger('click');
      });
  };
})(jQuery);

I did not write this, i just modified it. I found the iOS-only version here: https://gist.github.com/2047491 (thanks Kablam)

Getting the difference between two repositories

Reminder to self... fetch first, else the repository has not local hash (I guess).

step 1. Setup the upstream remote and above^

diffing a single file follows this pattern :

git diff localBranch uptreamBranch --spacepath/singlefile

git diff master upstream/nameofrepo -- src/index.js

PHP cURL not working - WAMP on Windows 7 64 bit

This work for me: http://www.mediafire.com/?3ay381k3cq59cm2 download a paste the file in ext folder PHP 5.4.3

How to compute the sum and average of elements in an array?

Here is a quick addition to the “Math” object in javascript to add a “average” command to it!!

Math.average = function(input) {
  this.output = 0;
  for (this.i = 0; this.i < input.length; this.i++) {
    this.output+=Number(input[this.i]);
  }
  return this.output/input.length;
}

Then i have this addition to the “Math” object for getting the sum!

Math.sum = function(input) {
  this.output = 0;
  for (this.i = 0; this.i < input.length; this.i++) {
    this.output+=Number(input[this.i]);
  }
  return this.output;
}

So then all you do is

alert(Math.sum([5,5,5])); //alerts “15”
alert(Math.average([10,0,5])); //alerts “5”

And where i put the placeholder array just pass in your variable (The input if they are numbers can be a string because of it parsing to a number!)

Showing Difference between two datetime values in hours

WOW, I gotta say: keep it simple:

MessageBox.Show("Result: " + (DateTime.Now.AddDays(10) > DateTime.Now));

Result: True

and:

MessageBox.Show("Result: " + DateTime.Now.AddDays(10).Subtract(DateTime.Now));

Result: 10.00:00:00

The DateTime object has all the builtin logic to handle the Boolean result.

How do I get the first n characters of a string without checking the size or going out of bounds?

Use the substring method, as follows:

int n = 8;
String s = "Hello, World!";
System.out.println(s.substring(0,n);

If n is greater than the length of the string, this will throw an exception, as one commenter has pointed out. one simple solution is to wrap all this in the condition if(s.length()<n) in your else clause, you can choose whether you just want to print/return the whole String or handle it another way.

How to get row count in sqlite using Android?

Use android.database.DatabaseUtils to get number of count.

public long getTaskCount(long tasklist_Id) {
        return DatabaseUtils.queryNumEntries(readableDatabase, TABLE_NAME);
}

It is easy utility that has multiple wrapper methods to achieve database operations.

How do I generate sourcemaps when using babel and webpack?

Minimal webpack config for jsx with sourcemaps:

var path = require('path');
var webpack = require('webpack');

module.exports = {
  entry: `./src/index.jsx` ,
  output: {
    path:  path.resolve(__dirname,"build"),
    filename: "bundle.js"
  },
  devtool: 'eval-source-map',
  module: {
    loaders: [
      {
        test: /.jsx?$/,
        loader: 'babel-loader',
        exclude: /node_modules/,
        query: {
          presets: ['es2015', 'react']
        }
      }
    ]
  },
};

Running it:

Jozsefs-MBP:react-webpack-babel joco$ webpack -d
Hash: c75d5fb365018ed3786b
Version: webpack 1.13.2
Time: 3826ms
        Asset     Size  Chunks             Chunk Names
    bundle.js   1.5 MB       0  [emitted]  main
bundle.js.map  1.72 MB       0  [emitted]  main
    + 221 hidden modules
Jozsefs-MBP:react-webpack-babel joco$

Python Traceback (most recent call last)

You are using Python 2 for which the input() function tries to evaluate the expression entered. Because you enter a string, Python treats it as a name and tries to evaluate it. If there is no variable defined with that name you will get a NameError exception.

To fix the problem, in Python 2, you can use raw_input(). This returns the string entered by the user and does not attempt to evaluate it.

Note that if you were using Python 3, input() behaves the same as raw_input() does in Python 2.