Programs & Examples On #Function interposition

Replacing a function in a dynamic library by providing an alternative definition

How can I quantify difference between two images?

You can compare two images using functions from PIL.

import Image
import ImageChops

im1 = Image.open("splash.png")
im2 = Image.open("splash2.png")

diff = ImageChops.difference(im2, im1)

The diff object is an image in which every pixel is the result of the subtraction of the color values of that pixel in the second image from the first image. Using the diff image you can do several things. The simplest one is the diff.getbbox() function. It will tell you the minimal rectangle that contains all the changes between your two images.

You can probably implement approximations of the other stuff mentioned here using functions from PIL as well.

Get all photos from Instagram which have a specific hashtag with PHP

To get more than 20 you can use a load more button.

index.php

<!DOCTYPE html>
<html>
<head>
  <meta charset="utf-8" />
  <title>Instagram more button example</title>
  <!--
    Instagram PHP API class @ Github
    https://github.com/cosenary/Instagram-PHP-API
  -->
  <style>
    article, aside, figure, footer, header, hgroup, 
    menu, nav, section { display: block; }
    ul {
      width: 950px;
    }
    ul > li {
      float: left;
      list-style: none;
      padding: 4px;
    }
    #more {
      bottom: 8px;
      margin-left: 80px;
      position: fixed;
      font-size: 13px;
      font-weight: 700;
      line-height: 20px;
    }
  </style>
  <script src="https://ajax.googleapis.com/ajax/libs/jquery/1.7.2/jquery.min.js"></script>
  <script>
    $(document).ready(function() {
      $('#more').click(function() {
        var tag   = $(this).data('tag'),
            maxid = $(this).data('maxid');

        $.ajax({
          type: 'GET',
          url: 'ajax.php',
          data: {
            tag: tag,
            max_id: maxid
          },
          dataType: 'json',
          cache: false,
          success: function(data) {
            // Output data
            $.each(data.images, function(i, src) {
              $('ul#photos').append('<li><img src="' + src + '"></li>');
            });

            // Store new maxid
            $('#more').data('maxid', data.next_id);
          }
        });
      });
    });
  </script>
</head>
<body>

<?php
  /**
   * Instagram PHP API
   */

   require_once 'instagram.class.php';

    // Initialize class with client_id
    // Register at http://instagram.com/developer/ and replace client_id with your own
    $instagram = new Instagram('ENTER CLIENT ID HERE');

    // Get latest photos according to geolocation for Växjö
    // $geo = $instagram->searchMedia(56.8770413, 14.8092744);

    $tag = 'sweden';

    // Get recently tagged media
    $media = $instagram->getTagMedia($tag);

    // Display first results in a <ul>
    echo '<ul id="photos">';

    foreach ($media->data as $data) 
    {
        echo '<li><img src="'.$data->images->thumbnail->url.'"></li>';
    }
    echo '</ul>';

    // Show 'load more' button
    echo '<br><button id="more" data-maxid="'.$media->pagination->next_max_id.'" data-tag="'.$tag.'">Load more ...</button>';
?>

</body>
</html>

ajax.php

<?php
    /**
     * Instagram PHP API
     */

     require_once 'instagram.class.php';

      // Initialize class for public requests
      $instagram = new Instagram('ENTER CLIENT ID HERE');

      // Receive AJAX request and create call object
      $tag = $_GET['tag'];
      $maxID = $_GET['max_id'];
      $clientID = $instagram->getApiKey();

      $call = new stdClass;
      $call->pagination->next_max_id = $maxID;
      $call->pagination->next_url = "https://api.instagram.com/v1/tags/{$tag}/media/recent?client_id={$clientID}&max_tag_id={$maxID}";

      // Receive new data
      $media = $instagram->getTagMedia($tag,$auth=false,array('max_tag_id'=>$maxID));

      // Collect everything for json output
      $images = array();
      foreach ($media->data as $data) {
        $images[] = $data->images->thumbnail->url;
      }

      echo json_encode(array(
        'next_id' => $media->pagination->next_max_id,
        'images'  => $images
      ));
?>

instagram.class.php

Find the function getTagMedia() and replace with:

public function getTagMedia($name, $auth=false, $params=null) {
    return $this->_makeCall('tags/' . $name . '/media/recent', $auth, $params);
}

Woocommerce, get current product id

2017 Update - since WooCommerce 3:

global $product;
$id = $product->get_id();

Woocommerce doesn't like you accessing those variables directly. This will get rid of any warnings from woocommerce if your wp_debug is true.

Vertically and horizontally centering text in circle in CSS (like iphone notification badge)

Horizontal centering is easy: text-align: center;. Vertical centering of text inside an element can be done by setting line-height equal to the container height, but this has subtle differences between browsers. On small elements, like a notification badge, these are more pronounced.

Better is to set line-height equal to font-size (or slightly smaller) and use padding. You'll have to adjust your height to accomodate.

Here's a CSS-only, single <div> solution that looks pretty iPhone-like. They expand with content.

Demo: http://jsfiddle.net/ThinkingStiff/mLW47/

Output:

enter image description here

CSS:

.badge {
    background: radial-gradient( 5px -9px, circle, white 8%, red 26px );
    background-color: red;
    border: 2px solid white;
    border-radius: 12px; /* one half of ( (border * 2) + height + padding ) */
    box-shadow: 1px 1px 1px black;
    color: white;
    font: bold 15px/13px Helvetica, Verdana, Tahoma;
    height: 16px; 
    min-width: 14px;
    padding: 4px 3px 0 3px;
    text-align: center;
}

HTML:

<div class="badge">1</div>
<div class="badge">2</div>
<div class="badge">3</div>
<div class="badge">44</div>
<div class="badge">55</div>
<div class="badge">666</div>
<div class="badge">777</div>
<div class="badge">8888</div>
<div class="badge">9999</div>

Get everything after the dash in a string in JavaScript

A solution I prefer would be:

const str = 'sometext-20202';
const slug = str.split('-').pop();

Where slug would be your result

How can I programmatically generate keypress events in C#?

Easily! (because someone else already did the work for us...)

After spending a lot of time trying to this with the suggested answers I came across this codeplex project Windows Input Simulator which made it simple as can be to simulate a key press:

  1. Install the package, can be done or from the NuGet package manager or from the package manager console like:

    Install-Package InputSimulator

  2. Use this 2 lines of code:

    inputSimulator = new InputSimulator() inputSimulator.Keyboard.KeyDown(VirtualKeyCode.RETURN)

And that's it!

-------EDIT--------

The project page on codeplex is flagged for some reason, this is the link to the NuGet gallery.

Find most frequent value in SQL column

One way I like to use is:

select ,COUNT()as VAR1 from Table_Name

group by

order by VAR1 desc

limit 1

Batch file for PuTTY/PSFTP file transfer automation

set DSKTOPDIR="D:\test"
set IPADDRESS="23.23.3.23"

>%DSKTOPDIR%\script.ftp ECHO cd %PAY_REP%
>>%DSKTOPDIR%\script.ftp ECHO mget *.report
>>%DSKTOPDIR%\script.ftp ECHO bye

:: run PSFTP Commands
psftp <domain>@%IPADDRESS% -b %DSKTOPDIR%\script.ftp

Set values using set commands before above lines.

I believe this helps you.

Referre psfpt setup for below link https://www.ssh.com/ssh/putty/putty-manuals/0.68/Chapter6.html

Find by key deep in a nested array

Just use recursive function.
See example below:

_x000D_
_x000D_
const data = [
  {
    title: 'some title',
    channel_id: '123we',
    options: [
      {
        channel_id: 'abc',
        image: 'http://asdasd.com/all-inclusive-block-img.jpg',
        title: 'All-Inclusive',
        options: [
          {
            channel_id: 'dsa2',
            title: 'Some Recommends',
            options: [
              {
                image: 'http://www.asdasd.com',
                title: 'Sandals',
                id: '1',
                content: {},
              }
            ]
          }
        ]
      }
    ]
  }
]

function _find(collection, key, value) {
  for (const o of collection) {
    for (const [k, v] of Object.entries(o)) {
      if (k === key && v === value) {
        return o
      }
      if (Array.isArray(v)) {
        const _o = _find(v, key, value)
        if (_o) {
          return _o
        }
      }
    }
  }
}

console.log(_find(data, 'channel_id', 'dsa2'))
_x000D_
_x000D_
_x000D_

How do I dynamically assign properties to an object in TypeScript?

The best practice is use safe typing, I recommend you:

interface customObject extends MyObject {
   newProp: string;
   newProp2: number;
}

How to print a query string with parameter values when using Hibernate

The solution is correct but logs also all bindings for the result objects. To prevent this it's possibile to create a separate appender and enable filtering, for example:

<!-- A time/date based rolling appender -->
<appender name="FILE_HIBERNATE" class="org.jboss.logging.appender.DailyRollingFileAppender">
    <errorHandler class="org.jboss.logging.util.OnlyOnceErrorHandler"/>
    <param name="File" value="${jboss.server.log.dir}/hiber.log"/>
    <param name="Append" value="false"/>
    <param name="Threshold" value="TRACE"/>
    <!-- Rollover at midnight each day -->
    <param name="DatePattern" value="'.'yyyy-MM-dd"/>

    <layout class="org.apache.log4j.PatternLayout">
        <!-- The default pattern: Date Priority [Category] Message\n -->
        <param name="ConversionPattern" value="%d %-5p [%c] %m%n"/>
    </layout>

    <filter class="org.apache.log4j.varia.StringMatchFilter">
        <param name="StringToMatch" value="bind" />
        <param name="AcceptOnMatch" value="true" />
    </filter>
    <filter class="org.apache.log4j.varia.StringMatchFilter">
        <param name="StringToMatch" value="select" />
        <param name="AcceptOnMatch" value="true" />
    </filter>  
    <filter class="org.apache.log4j.varia.DenyAllFilter"/>
</appender> 

<category name="org.hibernate.type">
  <priority value="TRACE"/>
</category>

<logger name="org.hibernate.type">
   <level value="TRACE"/> 
   <appender-ref ref="FILE_HIBERNATE"/>
</logger>

<logger name="org.hibernate.SQL">
   <level value="TRACE"/> 
   <appender-ref ref="FILE_HIBERNATE"/>
</logger>

How to test Spring Data repositories?

This may come a bit too late, but I have written something for this very purpose. My library will mock out the basic crud repository methods for you as well as interpret most of the functionalities of your query methods. You will have to inject functionalities for your own native queries, but the rest are done for you.

Take a look:

https://github.com/mmnaseri/spring-data-mock

UPDATE

This is now in Maven central and in pretty good shape.

Seaborn plots not showing up

Plots created using seaborn need to be displayed like ordinary matplotlib plots. This can be done using the

plt.show()

function from matplotlib.

Originally I posted the solution to use the already imported matplotlib object from seaborn (sns.plt.show()) however this is considered to be a bad practice. Therefore, simply directly import the matplotlib.pyplot module and show your plots with

import matplotlib.pyplot as plt
plt.show()

If the IPython notebook is used the inline backend can be invoked to remove the necessity of calling show after each plot. The respective magic is

%matplotlib inline

d3.select("#element") not working when code above the html element

Use jQuery $(document) function...

$(document).ready(function(){

var margin = {top: 20, right: 20, bottom: 30, left: 40},
    width = 960 - margin.left - margin.right,
    height = 500 - margin.top - margin.bottom;

var x0 = d3.scale.ordinal()
    .rangeRoundBands([0, width], .1);

var x1 = d3.scale.ordinal();

var y = d3.scale.linear()
    .range([height, 0]);

var color = d3.scale.ordinal()
    .range(["#98abc5", "#8a89a6", "#7b6888", "#6b486b", "#a05d56", "#d0743c", "#ff8c00"]);

var xAxis = d3.svg.axis()
    .scale(x0)
    .orient("bottom");

var yAxis = d3.svg.axis()
    .scale(y)
    .orient("left")
    .tickFormat(d3.format(".2s"));

//d3.select('#chart svg')
//d3.select("body").append("svg")


    //var svg = d3.select("#chart").append("svg:svg");

    var svg = d3.select("#BarChart").append("svg:svg")
    .attr("width", width + margin.left + margin.right)
    .attr("height", height + margin.top + margin.bottom)
    .append("g")
    .attr("transform", "translate(" + margin.left + "," + margin.top + ")");

    var updateData = function(getData){

    d3.selectAll('svg > g > *').remove();

    d3.csv(getData, function(error, data) {
      if (error) throw error;

      var ageNames = d3.keys(data[0]).filter(function(key) { return key !== "State"; });

      data.forEach(function(d) {
        d.ages = ageNames.map(function(name) { return {name: name, value: +d[name]}; });
      });

      x0.domain(data.map(function(d) { return d.State; }));
      x1.domain(ageNames).rangeRoundBands([0, x0.rangeBand()]);
      y.domain([0, d3.max(data, function(d) { return d3.max(d.ages, function(d) { return d.value; }); })]);

      svg.append("g")
          .attr("class", "x axis")
          .attr("transform", "translate(0," + height + ")")
          .call(xAxis);

      svg.append("g")
          .attr("class", "y axis")
          .call(yAxis)
        .append("text")
          .attr("transform", "rotate(-90)")
          .attr("y", 6)
          .attr("dy", ".71em")
          .style("text-anchor", "end")
          .text("Population");

      var state = svg.selectAll(".state")
          .data(data)
        .enter().append("g")
          .attr("class", "state")
          .attr("transform", function(d) { return "translate(" + x0(d.State) + ",0)"; });

      state.selectAll("rect")
          .data(function(d) { return d.ages; })
        .enter().append("rect")
          .attr("width", x1.rangeBand())
          .attr("x", function(d) { return x1(d.name); })
          .attr("y", function(d) { return y(d.value); })
          .attr("height", function(d) { return height - y(d.value); })
          .style("fill", function(d) { return color(d.name); });

      var legend = svg.selectAll(".legend")
          .data(ageNames.slice().reverse())
        .enter().append("g")
          .attr("class", "legend")
          .attr("transform", function(d, i) { return "translate(0," + i * 20 + ")"; });

      legend.append("rect")
          .attr("x", width - 18)
          .attr("width", 18)
          .attr("height", 18)
          .style("fill", color);

      legend.append("text")
          .attr("x", width - 24)
          .attr("y", 9)
          .attr("dy", ".35em")
          .style("text-anchor", "end")
          .text(function(d) { return d; });

    });

}

updateData('data1.csv');

});

Re-sign IPA (iPhone)

Finally got this working!

Tested with a IPA signed with cert1 for app store submission with no devices added in the provisioning profile. Results in a new IPA signed with a enterprise account and a mobile provisioning profile for in house deployment (the mobile provisioning profile gets embedded to the IPA).

Solution:

Unzip the IPA

unzip Application.ipa

Remove old CodeSignature

rm -r "Payload/Application.app/_CodeSignature" "Payload/Application.app/CodeResources" 2> /dev/null | true

Replace embedded mobile provisioning profile

cp "MyEnterprise.mobileprovision" "Payload/Application.app/embedded.mobileprovision"

Re-sign

/usr/bin/codesign -f -s "iPhone Distribution: Certificate Name" --resource-rules "Payload/Application.app/ResourceRules.plist" "Payload/Application.app"

Re-package

zip -qr "Application.resigned.ipa" Payload

Edit: Removed the Entitlement part (see alleys comment, thanks)

Spark RDD to DataFrame python

Try if that works

sc = spark.sparkContext

# Infer the schema, and register the DataFrame as a table.
schemaPeople = spark.createDataFrame(RddName)
schemaPeople.createOrReplaceTempView("RddName")

Sublime 3 - Set Key map for function Goto Definition

On a mac you have to set keybinding yourself. Simply go to

Sublime --> Preference --> Key Binding - User  

and input the following:

{ "keys": ["shift+command+m"], "command": "goto_definition" }

This will enable keybinding of Shift + Command + M to enable goto definition. You can set the keybinding to anything you would like of course.

Remove icon/logo from action bar on android

getActionBar().setIcon(android.R.color.transparent);

This worked for me.

Best Practices for Custom Helpers in Laravel 5

instead of including your custom helper class, you can actually add to your config/app.php file under aliases.

should be look like this.

 'aliases' => [ 
    ...
    ...
    'Helper' => App\Http\Services\Helper::class,
 ]

and then to your Controller, include the Helper using the method 'use Helper' so you can simply call some of the method on your Helper class.

eg. Helper::some_function();

or in resources view you can directly call the Helper class already.

eg. {{Helper::foo()}}

But this is still the developer coding style approach to be followed. We may have different way of solving problems, and i just want to share what i have too for beginners.

HTTP 401 - what's an appropriate WWW-Authenticate header value?

No, you'll have to specify the authentication method to use (typically "Basic") and the authentication realm. See http://en.wikipedia.org/wiki/Basic_access_authentication for an example request and response.

You might also want to read RFC 2617 - HTTP Authentication: Basic and Digest Access Authentication.

Choosing the default value of an Enum type without having to change values

You can't, but if you want, you can do some trick. :)

    public struct Orientation
    {
        ...
        public static Orientation None = -1;
        public static Orientation North = 0;
        public static Orientation East = 1;
        public static Orientation South = 2;
        public static Orientation West = 3;
    }

usage of this struct as simple enum.
where you can create p.a == Orientation.East (or any value that you want) by default
to use the trick itself, you need to convert from int by code.
there the implementation:

        #region ConvertingToEnum
        private int val;
        static Dictionary<int, string> dict = null;

        public Orientation(int val)
        {
            this.val = val;
        }

        public static implicit operator Orientation(int value)
        {
            return new Orientation(value - 1);
        }

        public static bool operator ==(Orientation a, Orientation b)
        {
            return a.val == b.val;
        }

        public static bool operator !=(Orientation a, Orientation b)
        {
            return a.val != b.val;
        }

        public override string ToString()
        {
            if (dict == null)
                InitializeDict();
            if (dict.ContainsKey(val))
                return dict[val];
            return val.ToString();
        }

        private void InitializeDict()
        {
            dict = new Dictionary<int, string>();
            foreach (var fields in GetType().GetFields(BindingFlags.Public | BindingFlags.Static))
            {
                dict.Add(((Orientation)fields.GetValue(null)).val, fields.Name);
            }
        } 
        #endregion

Import module from subfolder

Just create an empty __init__.py file and add it in root as well as all the sub directory/folder of your python application where you have other python modules. See https://docs.python.org/3/tutorial/modules.html#packages

java IO Exception: Stream Closed

You're calling writer.close(); after you've done writing to it. Once a stream is closed, it can not be written to again. Usually, the way I go about implementing this is by moving the close out of the write to method.

public void writeToFile(){
    String file_text= pedStatusText + "     " + gatesStatus + "     " + DrawBridgeStatusText;
    try {
        writer.write(file_text);
        writer.flush();
    } catch (IOException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

And add a method cleanUp to close the stream.

public void cleanUp() {
     writer.close();
}

This means that you have the responsibility to make sure that you're calling cleanUp when you're done writing to the file. Failure to do this will result in memory leaks and resource locking.

EDIT: You can create a new stream each time you want to write to the file, by moving writer into the writeToFile() method..

 public void writeToFile() {
    FileWriter writer = new FileWriter("status.txt", true);
    // ... Write to the file.

    writer.close();
 }

Finding a substring within a list in Python

I'd just use a simple regex, you can do something like this

import re
old_list = ['abc123', 'def456', 'ghi789']
new_list = [x for x in old_list if re.search('abc', x)]
for item in new_list:
    print item

Angular2 RC5: Can't bind to 'Property X' since it isn't a known property of 'Child Component'

I fixed it with adding the prefix (attr.) :

<create-report-card-form [attr.currentReportCardCount]="expression" ...

Unfortunately this haven't documented properly yet.

more detail here

background: fixed no repeat not working on mobile

Found a perfect solution for the problem 100% working on mobile as well as desktop

https://codepen.io/mrinaljain/pen/YObgEP

_x000D_
_x000D_
.jpx-is-wrapper {_x000D_
    display: block;_x000D_
    margin: 0 auto;_x000D_
    overflow: hidden;_x000D_
    position: relative;_x000D_
    z-index: 314749261;_x000D_
    width: 100vw;_x000D_
    height: 300px_x000D_
}_x000D_
_x000D_
.jpx-is-wrapper>.jpx-is-container {_x000D_
    background-color: transparent;_x000D_
    border: 0;_x000D_
    box-sizing: content-box;_x000D_
    clip: rect(auto auto auto auto);_x000D_
    color: black;_x000D_
    left: 0;_x000D_
    margin: 0 auto;_x000D_
    overflow: visible;_x000D_
    position: absolute;_x000D_
    text-align: left;_x000D_
    top: 0;_x000D_
    visibility: visible;_x000D_
    width: 100%;_x000D_
    z-index: auto;_x000D_
    height: 300px_x000D_
}_x000D_
_x000D_
.jpx-is-wrapper>.jpx-is-container>.jpx-is-content {_x000D_
    left: 0;_x000D_
    overflow: hidden;_x000D_
    right: 0;_x000D_
    top: 0;_x000D_
    visibility: visible;_x000D_
    width: 100%;_x000D_
    position: relative;_x000D_
    height: 300px;_x000D_
    display: block_x000D_
}_x000D_
_x000D_
.jpx-is-wrapper>.jpx-is-container>.jpx-is-content>.jpx-is-ad {_x000D_
    -webkit-box-shadow: rgba(0,0,0,0.65) 0 0 4px 2px;_x000D_
    -moz-box-shadow: rgba(0,0,0,0.65) 0 0 4px 2px;_x000D_
    box-shadow: rgba(0,0,0,0.65) 0 0 4px 2px;_x000D_
    bottom: 26px;_x000D_
    left: 0;_x000D_
    margin: 0 auto;_x000D_
    right: 0;_x000D_
    text-align: center;_x000D_
    height: 588px;_x000D_
    top: 49px;_x000D_
    bottom: auto;_x000D_
    -webkit-transform: translateZ(0);_x000D_
    -moz-transform: translateZ(0);_x000D_
    -ms-transform: translateZ(0);_x000D_
    -o-transform: translateZ(0);_x000D_
    transform: translateZ(0)_x000D_
}_x000D_
_x000D_
.jpx-position-fixed {_x000D_
    position: fixed_x000D_
}_x000D_
_x000D_
.jpx-is-wrapper>.jpx-is-container>.jpx-is-content>.jpx-is-ad>.jpx-is-ad-frame {_x000D_
    width: 100%;_x000D_
    height: 100%_x000D_
}_x000D_
_x000D_
.black-fader {_x000D_
    position: absolute;_x000D_
    z-index: 1;_x000D_
    width: 100%;_x000D_
    height: 100%;_x000D_
    opacity: 0.75_x000D_
}_x000D_
_x000D_
.video-containers {_x000D_
    position: absolute;_x000D_
    top: 0;_x000D_
    bottom: 0;_x000D_
    width: 100%;_x000D_
    height: 100%;_x000D_
    overflow: hidden;_x000D_
    z-index: 0_x000D_
}_x000D_
_x000D_
.video-containers video,.video-containers img {_x000D_
    min-width: 100%;_x000D_
    min-height: 100%;_x000D_
    width: auto;_x000D_
    height: auto;_x000D_
    position: absolute;_x000D_
    top: 50%;_x000D_
    left: 50%;_x000D_
    transform: translate(-50%, -50%)_x000D_
}
_x000D_
<p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p>_x000D_
_x000D_
<div class="jpx-is-wrapper">_x000D_
                       <div class="jpx-is-container">_x000D_
                          <div class="jpx-is-content">_x000D_
                             <div class="jpx-is-ad jpx-position-fixed">_x000D_
                                   <div scrolling="no" width="100%" height="100%" class="jcl-wrapper" style="border: 0px; display: block; width: 100%; height: 100%;">_x000D_
                                       <div class="video-containers" id="video-container">_x000D_
                                          <img src="https://via.placeholder.com/350x150" alt="" class="">_x000D_
                                       </div>_x000D_
                                  </div>_x000D_
                             </div>_x000D_
                          </div>_x000D_
                       </div>_x000D_
                    </div>_x000D_
_x000D_
<p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p><p>Salman's arrest has created a wave of tension in Bollywood because of all his projects that were lined up, especially his most awaited film.</p>
_x000D_
_x000D_
_x000D_

Declaring variables inside or outside of a loop

Declaring String str outside of the while loop allows it to be referenced inside & outside the while loop. Declaring String str inside of the while loop allows it to only be referenced inside that while loop.

Installing Homebrew on OS X

add the following in your terminal and click enter then follow the instruction in the terminal. /usr/bin/ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/install/master/install)"

A warning - comparison between signed and unsigned integer expressions

At the extreme ranges, an unsigned int can become larger than an int.
Therefore, the compiler generates a warning. If you are sure that this is not a problem, feel free to cast the types to the same type so the warning disappears (use C++ cast so that they are easy to spot).

Alternatively, make the variables the same type to stop the compiler from complaining.
I mean, is it possible to have a negative padding? If so then keep it as an int. Otherwise you should probably use unsigned int and let the stream catch the situations where the user types in a negative number.

How to Convert an int to a String?

Use the Integer class' static toString() method.

int sdRate=5;
text_Rate.setText(Integer.toString(sdRate));

You seem to not be depending on "@angular/core". This is an error

Below steps worked for me:

1) Delete the node_modules/ folder and package-lock.json file.

2) npm install

3) ng serve

How can I parse String to Int in an Angular expression?

You can create a Pipe and use it wherever you want in your system.

import { Pipe, PipeTransform } from '@angular/core';
 @Pipe({
     // tslint:disable-next-line:pipe-naming
     name: 'toNumber',
     pure: false }) export class ToNumberPipe implements PipeTransform { 
     public transform(items: any): any {
         if (!items) {
             return 0;
         }
         return parseInt(items, 10);
     } }

In the HTML

{{ attr.text | toNumber }}

Remember to declare this Pipe to be accessfull in your modules file.

how to compare two string dates in javascript?

var d1 = Date.parse("2012-11-01");
var d2 = Date.parse("2012-11-04");
if (d1 < d2) {
    alert ("Error!");
}

Demo Jsfiddle

How to compile makefile using MinGW?

Excerpt from http://www.mingw.org/wiki/FAQ:

What's the difference between make and mingw32-make?

The "native" (i.e.: MSVCRT dependent) port of make is lacking in some functionality and has modified functionality due to the lack of POSIX on Win32. There also exists a version of make in the MSYS distribution that is dependent on the MSYS runtime. This port operates more as make was intended to operate and gives less headaches during execution. Based on this, the MinGW developers/maintainers/packagers decided it would be best to rename the native version so that both the "native" version and the MSYS version could be present at the same time without file name collision.

So,look into C:\MinGW\bin directory and first make sure what make executable, have you installed.(make.exe or mingw32-make.exe)

Before using MinGW, you should add C:\MinGW\bin; to the PATH environment variable using the instructions mentioned at http://www.mingw.org/wiki/Getting_Started/

Then cd to your directory, where you have the makefile and Try using mingw32-make.exe makefile.in or simply make.exe makefile.in(depending on executables in C:\MinGW\bin).

If you want a GUI based solution, install DevCPP IDE and then re-make.

Open a PDF using VBA in Excel

Hope this helps. I was able to open pdf files from all subfolders of a folder and copy content to the macro enabled workbook using shell as recommended above.Please see below the code .

Sub ConsolidateWorkbooksLTD()
Dim adobeReaderPath As String
Dim pathAndFileName As String
Dim shellPathName As String
Dim fso, subFldr, subFlodr
Dim FolderPath
Dim Filename As String
Dim Sheet As Worksheet
Dim ws As Worksheet
Dim HK As String
Dim s As String
Dim J As String
Dim diaFolder As FileDialog
Dim mFolder As String
Dim Basebk As Workbook
Dim Actbk As Workbook

Application.ScreenUpdating = False

Set Basebk = ThisWorkbook

' Open the file dialog
Set diaFolder = Application.FileDialog(msoFileDialogFolderPicker)
diaFolder.AllowMultiSelect = False
diaFolder.Show
MsgBox diaFolder.SelectedItems(1) & "\"
mFolder = diaFolder.SelectedItems(1) & "\"
Set diaFolder = Nothing
Set fso = CreateObject("Scripting.FileSystemObject")
Set FolderPath = fso.GetFolder(mFolder)
For Each subFldr In FolderPath.SubFolders
subFlodr = subFldr & "\"
Filename = Dir(subFldr & "\*.csv*")
Do While Len(Filename) > 0
J = Filename
J = Left(J, Len(J) - 4) & ".pdf"
   Workbooks.Open Filename:=subFldr & "\" & Filename, ReadOnly:=True
   For Each Sheet In ActiveWorkbook.Sheets
   Set Actbk = ActiveWorkbook
   s = ActiveWorkbook.Name
   HK = Left(s, Len(s) - 4)
   If InStrRev(HK, "_S") <> 0 Then
   HK = Right(HK, Len(HK) - InStrRev(HK, "_S"))
   Else
   HK = Right(HK, Len(HK) - InStrRev(HK, "_L"))
   End If
   Sheet.Copy After:=ThisWorkbook.Sheets(1)
   ActiveSheet.Name = HK

   ' Open pdf file to copy SIC Decsription
   pathAndFileName = subFlodr & J
   adobeReaderPath = "C:\Program Files (x86)\Adobe\Acrobat Reader DC\Reader\AcroRd32.exe"
   shellPathName = adobeReaderPath & " """ & pathAndFileName & """"
   Call Shell( _
    pathname:=shellPathName, _
    windowstyle:=vbNormalFocus)
    Application.Wait Now + TimeValue("0:00:2")

    SendKeys "%vpc"
    SendKeys "^a", True
    Application.Wait Now + TimeValue("00:00:2")

    ' send key to copy
     SendKeys "^c"
    ' wait 2 secs
     Application.Wait Now + TimeValue("00:00:2")
      ' activate this workook and paste the data
        ThisWorkbook.Activate
        Set ws = ThisWorkbook.Sheets(HK)
        Range("O1:O5").Select
        ws.Paste

        Application.Wait Now + TimeValue("00:00:3")
        Application.CutCopyMode = False
        Application.Wait Now + TimeValue("00:00:3")
       Call Shell("TaskKill /F /IM AcroRd32.exe", vbHide)
       ' send key to close pdf file
        SendKeys "^q"
       Application.Wait Now + TimeValue("00:00:3")
 Next Sheet
 Workbooks(Filename).Close SaveAs = True
 Filename = Dir()
Loop
Next
Application.ScreenUpdating = True
End Sub

I wrote the piece of code to copy from pdf and csv to the macro enabled workbook and you may need to fine tune as per your requirement

Regards, Hema Kasturi

VirtualBox error "Failed to open a session for the virtual machine"

maybe it is caused by privilege, please try this:

#sudo chmod 755 /Applications 
#sudo chmod 755 /Applications/Virtualbox.app

How to use localization in C#

In my case

[assembly: System.Resources.NeutralResourcesLanguage("ru-RU")]

in the AssemblyInfo.cs prevented things to work as usual.

Selenium WebDriver: Wait for complex page with JavaScript to load

Don't know how to do that but in my case, end of page load & rendering match with FAVICON displayed in Firefox tab.

So if we can get the favicon image in the webbrowser, the web page is fully loaded.

But how perform this ....

How to import RecyclerView for Android L-preview

include the dependency in the build.gradle, and sync the project with gradle files

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation 'com.android.support:appcompat-v7:25.1.0'

    //include the revision no, i.e 25.1.1
    implementation 'com.android.support:recyclerview-v7:25.1.1'
}

Include the revision(here its 25.1.1) to avoid unpredictable builds, check library revisions

.Net System.Mail.Message adding multiple "To" addresses

You can do this either with multiple System.Net.Mail.MailAddress objects or you can provide a single string containing all of the addresses separated by commas

How to use OrderBy with findAll in Spring Data

Please have a look at the Spring Data JPA - Reference Documentation, section 5.3. Query Methods, especially at section 5.3.2. Query Creation, in "Table 3. Supported keywords inside method names" (links as of 2019-05-03).

I think it has exactly what you need and same query as you stated should work...

Lodash remove duplicates from array

Or simply Use union, for simple array.

_.union([1,2,3,3], [3,5])

// [1,2,3,5]

Update Angular model after setting input value with jQuery

The accepted answer which was triggering input event with jQuery didn't work for me. Creating an event and dispatching with native JavaScript did the trick.

$("input")[0].dispatchEvent(new Event("input", { bubbles: true }));

Formatting doubles for output in C#

Another method, starting with the method:

double i = (10 * 0.69);
Console.Write(ToStringFull(i));       // Output 6.89999999999999946709294817
Console.Write(ToStringFull(-6.9)      // Output -6.90000000000000035527136788
Console.Write(ToStringFull(i - 6.9)); // Output -0.00000000000000088817841970012523233890533

A Drop-In Function...

public static string ToStringFull(double value)
{
    if (value == 0.0) return "0.0";
    if (double.IsNaN(value)) return "NaN";
    if (double.IsNegativeInfinity(value)) return "-Inf";
    if (double.IsPositiveInfinity(value)) return "+Inf";

    long bits = BitConverter.DoubleToInt64Bits(value);
    BigInteger mantissa = (bits & 0xfffffffffffffL) | 0x10000000000000L;
    int exp = (int)((bits >> 52) & 0x7ffL) - 1023;
    string sign = (value < 0) ? "-" : "";

    if (54 > exp)
    {
        double offset = (exp / 3.321928094887362358); //...or =Math.Log10(Math.Abs(value))
        BigInteger temp = mantissa * BigInteger.Pow(10, 26 - (int)offset) >> (52 - exp);
        string numberText = temp.ToString();
        int digitsNeeded = (int)((numberText[0] - '5') / 10.0 - offset);
        if (exp < 0)
            return sign + "0." + new string('0', digitsNeeded) + numberText;
        else
            return sign + numberText.Insert(1 - digitsNeeded, ".");
    }
    return sign + (mantissa >> (52 - exp)).ToString();
}

How it works

To solve this problem I used the BigInteger tools. Large values are simple as they just require left shifting the mantissa by the exponent. For small values we cannot just directly right shift as that would lose the precision bits. We must first give it some extra size by multiplying it by a 10^n and then do the right shifts. After that, we move over the decimal n places to the left. More text/code here.

How to detect when cancel is clicked on file input?

Shiboe's solution would be a good one if it worked on mobile webkit, but it doesn't. What I can come up with is to add a mousemove event listener to some dom object at the time that the file input window is opened, like so:

 $('.upload-progress').mousemove(function() {
        checkForFiles(this);
      });
      checkForFiles = function(me) {
        var filefield = $('#myfileinput');
        var files = filefield.get(0).files;
        if (files == undefined || files[0] == undefined) $(me).remove(); // user cancelled the upload
      };

The mousemove event is blocked from the page while the file dialog is open, and when its closed one checks to see if there are any files in the file input. In my case I want an activity indicator blocking things till the file is uploaded, so I only want to remove my indicator on cancel.

However this doesn't solve for mobile, since there is no mouse to move. My solution there is less than perfect, but I think its good enough.

       $('.upload-progress').bind('touchstart', function() {
        checkForFiles(this);
      });

Now we're listening for a touch on the screen to do the same files check. I'm pretty confident that the user's finger will be put on the screen pretty quickly after cancel and dismiss this activity indicator.

One could also just add the activity indicator on the file input change event, but on mobile there is often a few seconds lag between selecting the image and the change event firing, so its just much better UX for the activity indicator to be displayed at the start of the process.

How to iterate through a list of dictionaries in Jinja template?

{% for i in yourlist %}
  {% for k,v in i.items() %}
    {# do what you want here #}
  {% endfor %}
{% endfor %}

How to do a background for a label will be without color?

You are right. but here is the simplest way for making the back color of the label transparent In the properties window of that label select Web.. In Web select Transparent :)

Django: TemplateSyntaxError: Could not parse the remainder

You have indented part of your code in settings.py:

# Uncomment the next line to enable the admin:
     'django.contrib.admin',
    # Uncomment the next line to enable admin documentation:
    #'django.contrib.admindocs',
     'tinymce',
     'sorl.thumbnail',
     'south',
     'django_facebook',
     'djcelery',
     'devserver',
     'main',

Therefore, it is giving you an error.

Android: how do I check if activity is running?

Not sure it is a "proper" way to "do things".
If there's no API way to resolve the (or a) question than you should think a little, maybe you're doing something wrong and read more docs instead etc.
(As I understood static variables is a commonly wrong way in android. Of cause it could work, but there definitely will be cases when it wont work[for example, in production, on million devices]).
Exactly in your case I suggest to think why do you need to know if another activity is alive?.. you can start another activity for result to get its functionality. Or you can derive the class to obtain its functionality and so on.
Best Regards.

How to convert datatype:object to float64 in python?

I had this problem in a DataFrame (df) created from an Excel-sheet with several internal header rows.

After cleaning out the internal header rows from df, the columns' values were of "non-null object" type (DataFrame.info()).

This code converted all numerical values of multiple columns to int64 and float64 in one go:

for i in range(0, len(df.columns)):
    df.iloc[:,i] = pd.to_numeric(df.iloc[:,i], errors='ignore')
    # errors='ignore' lets strings remain as 'non-null objects'

How to set Meld as git mergetool

After installing it http://meldmerge.org/ I had to tell git where it was:

git config --global merge.tool meld
git config --global diff.tool meld
git config --global mergetool.meld.path “C:\Program Files (x86)\Meld\meld.exe”

And that seems to work. Both merging and diffing with “git difftool” or “git mergetool”

If someone facing issue such as Meld crash after starting (problem indication with python) then you need to set up Meld/lib to your system environment variable as bellow C:\Program Files (x86)\Meld\lib

PyCharm import external library

In my case, the correct menu path was:

File > Default settings > Project Interpreter

Illegal mix of collations MySQL Error

In general the best way is to Change the table collation. However I have an old application and are not really able to estimate the outcome whether this has side effects. Therefore I tried somehow to convert the string into some other format that solved the collation problem. What I found working is to do the string compare by converting the strings into a hexadecimal representation of it's characters. On the database this is done with HEX(column). For PHP you may use this function:

public static function strToHex($string)
{
    $hex = '';
    for ($i=0; $i<strlen($string); $i++){
        $ord = ord($string[$i]);
        $hexCode = dechex($ord);
        $hex .= substr('0'.$hexCode, -2);
    }
    return strToUpper($hex);
}

When doing the database query, your original UTF8 string must be converted first into an iso string (e.g. using utf8_decode() in PHP) before using it in the DB. Because of the collation type the database cannot have UTF8 characters inside so the comparism should work event though this changes the original string (converting UTF8 characters that are not existend in the ISO charset result in a ? or these are removed entirely). Just make sure that when you write data into the database, that you use the same UTF8 to ISO conversion.

JS: Failed to execute 'getComputedStyle' on 'Window': parameter is not of type 'Element'

For those who got this error in AngularJS and not jQuery:

I got it in AngularJS v1.5.8 by trying to ng-include a type="text/ng-template" that didn't exist.

 <div ng-include="tab.content">...</div>

Make sure that when you use ng-include, the data for that directive points to an actual page/section. Otherwise, you probably wanted:

<div>{{tab.content}}</div>

(Built-in) way in JavaScript to check if a string is a valid number

If anyone ever gets this far down, I spent some time hacking on this trying to patch moment.js (https://github.com/moment/moment). Here's something that I took away from it:

function isNumeric(val) {
    var _val = +val;
    return (val !== val + 1) //infinity check
        && (_val === +val) //Cute coercion check
        && (typeof val !== 'object') //Array/object check
}

Handles the following cases:

True! :

isNumeric("1"))
isNumeric(1e10))
isNumeric(1E10))
isNumeric(+"6e4"))
isNumeric("1.2222"))
isNumeric("-1.2222"))
isNumeric("-1.222200000000000000"))
isNumeric("1.222200000000000000"))
isNumeric(1))
isNumeric(0))
isNumeric(-0))
isNumeric(1010010293029))
isNumeric(1.100393830000))
isNumeric(Math.LN2))
isNumeric(Math.PI))
isNumeric(5e10))

False! :

isNumeric(NaN))
isNumeric(Infinity))
isNumeric(-Infinity))
isNumeric())
isNumeric(undefined))
isNumeric('[1,2,3]'))
isNumeric({a:1,b:2}))
isNumeric(null))
isNumeric([1]))
isNumeric(new Date()))

Ironically, the one I am struggling with the most:

isNumeric(new Number(1)) => false

Any suggestions welcome. :]

Set field value with reflection

It's worth reading Oracle Java Tutorial - Getting and Setting Field Values

Field#set(Object object, Object value) sets the field represented by this Field object on the specified object argument to the specified new value.

It should be like this

f.set(objectOfTheClass, new ConcurrentHashMap<>());

You can't set any value in null Object If tried then it will result in NullPointerException


Note: Setting a field's value via reflection has a certain amount of performance overhead because various operations must occur such as validating access permissions. From the runtime's point of view, the effects are the same, and the operation is as atomic as if the value was changed in the class code directly.

perform an action on checkbox checked or unchecked event on html form

Given you use JQuery, you can do something like below :

HTML

<form id="myform">
    syn<input type="checkbox" name="checkfield" id="g01-01"  onclick="doalert()"/>
</form>

JS

function doalert() {
  if ($("#g01-01").is(":checked")) {
    alert ("hi");
  } else {
    alert ("bye");
  }
}

How to increment a datetime by one day?

This was a straightforward solution for me:

from datetime import timedelta, datetime

today = datetime.today().strftime("%Y-%m-%d")
tomorrow = datetime.today() + timedelta(1)

How to get option text value using AngularJS?

Also you can do like this:

<select class="form-control postType" ng-model="selectedProd">
    <option ng-repeat="product in productList" value="{{product}}">{{product.name}}</option>
</select>

where "selectedProd" will be selected product.

Setting and getting localStorage with jQuery

The localStorage can only store string content and you are trying to store a jQuery object since html(htmlString) returns a jQuery object.

You need to set the string content instead of an object. And use the setItem method to add data and getItem to get data.

window.localStorage.setItem('content', 'Test');
$('#test').html(window.localStorage.getItem('content'));

How can I iterate through a string and also know the index (current position)?

Since std::distance is only constant time for random-access iterators, I would probably prefer explicit iterator arithmetic. Also, since we're writing C++ code here, I do believe a more C++ idiomatic solution is preferable over a C-style approach.

string str{"Test string"};
auto begin = str.begin();

for (auto it = str.begin(), end = str.end(); it != end; ++it)
{
    cout << it - begin << *it;
}

How can I autoformat/indent C code in vim?

Try the following keystrokes:

gg=G

Explanation: gg goes to the top of the file, = is a command to fix the indentation and G tells it to perform the operation to the end of the file.

Failed to load resource under Chrome

FYI - I had this issue as well and it turned out that my html listed the .jpg file with a .JPG in caps, but the file itself was lowercase .jpg. That rendered fine locally and using Codekit, but when it was pushed to the web it wouldn't load. Simply changing the file names to have a lowercase .jpg extension to match the html did the trick.

Error reading JObject from JsonReader. Current JsonReader item is not an object: StartArray. Path

I ran into a very similar problem with my Xamarin Windows Phone 8.1 app. The reason JObject.Parse(json) would not work for me was because my Json had a beginning "[" and an ending "]". In order to make it work, I had to remove those two characters. From your example, it looks like you might have the same issue.

jsonResult = jsonResult.TrimStart(new char[] { '[' }).TrimEnd(new char[] { ']' });

I was then able to use the JObject.Parse(jsonResult) and everything worked.

Animate element transform rotate

//this should allow you to replica an animation effect for any css property, even //properties //that transform animation jQuery plugins do not allow

            function twistMyElem(){
                var ball = $('#form');
                document.getElementById('form').style.zIndex = 1;
                ball.animate({ zIndex : 360},{
                    step: function(now,fx){
                        ball.css("transform","rotateY(" + now + "deg)");
                    },duration:3000
                }, 'linear');
            } 

Speed up rsync with Simultaneous/Concurrent File Transfers?

The simplest I've found is using background jobs in the shell:

for d in /main/files/*; do
    rsync -a "$d" remote:/main/files/ &
done

Beware it doesn't limit the amount of jobs! If you're network-bound this is not really a problem but if you're waiting for spinning rust this will be thrashing the disk.

You could add

while [ $(jobs | wc -l | xargs) -gt 10 ]; do sleep 1; done

inside the loop for a primitive form of job control.

What is the difference between POST and GET?

Whilst not a description of the differences, below are a couple of things to think about when choosing the correct method.

  • GET requests can get cached by the browser which can be a problem (or benefit) when using ajax.
  • GET requests expose parameters to users (POST does as well but they are less visible).
  • POST can pass much more information to the server and can be of almost any length.

How to make in CSS an overlay over an image?

A bit late for this, but this thread comes up in Google as a top result when searching for an overlay method.

You could simply use a background-blend-mode

.foo {
    background-image: url(images/image1.png), url(images/image2.png);
    background-color: violet;
    background-blend-mode: screen multiply;
}

What this does is it takes the second image, and it blends it with the background colour by using the multiply blend mode, and then it blends the first image with the second image and the background colour by using the screen blend mode. There are 16 different blend modes that you could use to achieve any overlay.

multiply, screen, overlay, darken, lighten, color-dodge, color-burn, hard-light, soft-light, difference, exclusion, hue, saturation, color and luminosity.

How to create an instance of System.IO.Stream stream

Stream is a base class, you need to create one of the specific types of streams, such as MemoryStream.

How do I pretty-print existing JSON data with Java?

Another way to use gson:

String json_String_to_print = ...
Gson gson = new GsonBuilder().setPrettyPrinting().create();
JsonParser jp = new JsonParser();
return gson.toJson(jp.parse(json_String_to_print));

It can be used when you don't have the bean as in susemi99's post.

React Js conditionally applying class attributes

<div className={['foo', condition && 'bar'].filter(Boolean).join(' ')} />

.filter(Boolean) removes "falsey" values from the array. Since class names must be strings, anything other than that would not be included in the new filtered array.

_x000D_
_x000D_
console.log(  ['foo', true  && 'bar'].filter(Boolean).join(' ')  )
console.log(  ['foo', false && 'bar'].filter(Boolean).join(' ')  )
_x000D_
_x000D_
_x000D_

Above written as a function:

const cx = (...list) => list.filter(Boolean).join(' ')

// usage:
<div className={cx('foo', condition && 'bar')} />

_x000D_
_x000D_
var cx = (...list) => list.filter(Boolean).join(' ')
console.log(  cx('foo', 1 && 'bar', 1 && 'baz')  )
console.log(  cx('foo', 0 && 'bar', 1 && 'baz')  )
console.log(  cx('foo', 0 && 'bar', 0 && 'baz')  )
_x000D_
_x000D_
_x000D_

Pass variable to function in jquery AJAX success callback

I've meet the probleme recently. The trouble is coming when the filename lenght is greather than 20 characters. So the bypass is to change your filename length, but the trick is also a good one.

$.ajaxSetup({async: false}); // passage en mode synchrone
$.ajax({
   url: pathpays,
   success: function(data) {
      //debug(data);
      $(data).find("a:contains(.png),a:contains(.jpg)").each(function() {
         var image = $(this).attr("href");
         // will loop through
         debug("Found a file: " + image);
         text +=  '<img class="arrondie" src="' + pathpays + image + '" />';
      });
      text = text + '</div>';
      //debug(text);
   }
});

After more investigation the trouble is coming from ajax request: Put an eye to the html code returned by ajax:

<a href="Paris-Palais-de-la-cite%20-%20Copie.jpg">Paris-Palais-de-la-c..&gt;</a>
</td>
<td align="right">2015-09-05 09:50 </td>
<td align="right">4.3K</td>
<td>&nbsp;</td>
</tr>

As you can see the filename is splitted after the character 20, so the $(data).find("a:contains(.png)) is not able to find the correct extention.

But if you check the value of the href parameter it contents the fullname of the file.

I dont know if I can to ask to ajax to return the full filename in the text area?

Hope to be clear

I've found the right test to gather all files:

$(data).find("[href$='.jpg'],[href$='.png']").each(function() {  
var image = $(this).attr("href");

Is Java's assertEquals method reliable?

Yes, it is used all the time for testing. It is very likely that the testing framework uses .equals() for comparisons such as these.

Below is a link explaining the "string equality mistake". Essentially, strings in Java are objects, and when you compare object equality, typically they are compared based on memory address, and not by content. Because of this, two strings won't occupy the same address, even if their content is identical, so they won't match correctly, even though they look the same when printed.

http://blog.enrii.com/2006/03/15/java-string-equality-common-mistake/

Finding row index containing maximum value using R

See ?order. You just need the last index (or first, in decreasing order), so this should do the trick:

order(matrix[,2],decreasing=T)[1]

How to wrap async function calls into a sync function in Node.js or Javascript?

Nowadays this generator pattern can be a solution in many situations.

Here an example of sequential console prompts in nodejs using async readline.question function:

var main = (function* () {

  // just import and initialize 'readline' in nodejs
  var r = require('readline')
  var rl = r.createInterface({input: process.stdin, output: process.stdout })

  // magic here, the callback is the iterator.next
  var answerA = yield rl.question('do you want this? ', r=>main.next(r))    

  // and again, in a sync fashion
  var answerB = yield rl.question('are you sure? ', r=>main.next(r))        

  // readline boilerplate
  rl.close()

  console.log(answerA, answerB)

})()  // <-- executed: iterator created from generator
main.next()     // kick off the iterator, 
                // runs until the first 'yield', including rightmost code
                // and waits until another main.next() happens

What data is stored in Ephemeral Storage of Amazon EC2 instance?

ephemeral is just another name of root volume when you launch Instance from AMI backed from Amazon EC2 instance store

So Everything will be stored on ephemeral.

if you have launched your instance from AMI backed by EBS volume then your instance does not have ephemeral.

connect local repo with remote repo

I know it has been quite sometime that you asked this but, if someone else needs, I did what was saying here " How to upload a project to Github " and after the top answer of this question right here. And after was the top answer was saying here "git error: failed to push some refs to" I don't know what exactly made everything work. But now is working.

Why use deflate instead of gzip for text files served by Apache?

There shouldn't be any difference in gzip & deflate for decompression. Gzip is just deflate with a few dozen byte header wrapped around it including a checksum. The checksum is the reason for the slower compression. However when you're precompressing zillions of files you want those checksums as a sanity check in your filesystem. In addition you can utilize commandline tools to get stats on the file. For our site we are precompressing a ton of static data (the entire open directory, 13,000 games, autocomplete for millions of keywords, etc.) and we are ranked 95% faster than all websites by Alexa. Faxo Search. However, we do utilize a home grown proprietary web server. Apache/mod_deflate just didn't cut it. When those files are compressed into the filesystem not only do you take a hit for your file with the minimum filesystem block size but all the unnecessary overhead in managing the file in the filesystem that the webserver could care less about. Your concerns should be total disk footprint and access/decompression time and secondarily speed in being able to get this data precompressed. The footprint is important because even though disk space is cheap you want as much as possible to fit in the cache.

Defining TypeScript callback type

To go one step further, you could declare a type pointer to a function signature like:

interface myCallbackType { (myArgument: string): void }

and use it like this:

public myCallback : myCallbackType;

ASP.NET MVC Yes/No Radio Buttons with Strongly Bound Model MVC

Adding label tags around the radio buttons using regular HTML will fix the 'labelfor' issue as well:

<label><%= Html.RadioButton("blah", !Model.blah) %> Yes</label>
<label><%= Html.RadioButton("blah", Model.blah) %> No</label>

Clicking on the text now selects the appropriate radio button.

Multiple Buttons' OnClickListener() android

public void onClick(View v) {
    int id = v.getId();
    switch (id){
        case R.id.button1:
            //do ur code
            Toast.makeText(this,"This is button 1",Toast.LENGTH_SHORT).show();
            break;
        case R.id.button2:
            Intent intent = new Intent(this,SecondActivity.class);
            Intent.putExtra("key",value);
            startActivity(intent);
            break;
        case R.id.button3:
            //do ur code
            break;
        case R.id.button4:
            //do ur code;
            break;
        default:
            //do ur code;
    }
}

Execution failed for task 'app:mergeDebugResources' Crunching Cruncher....png failed

I faced this problem when I copied my images (no matter JPEG or PNG) into the drawable folder manually. There might be different kinds of temporary solutions to this problem, but one best eternal way is to use the Drawable importer plugin for Android studio.

Install it by going to: menu File ? Settings ? Plugins ? Browse Repositories ? search "Drawable". You'll find Drawable importer as the first option. Click install on the right panel.

Use it by right clicking on the Drawable resource folder and then new. Now you can see four new options added to the bottom of the list, and among those you will find your appropriate option. In this case the "Batch drawable import" would do the trick.

How can I render a list select box (dropdown) with bootstrap?

The Bootstrap3 .form-control is cool but for those who love or need the drop-down with button and ul option, here is the updated code. I have edited the code by Steve to fix jumping to the hash link and closing the drop-down after selection.

Thanks to Steve, Ben and Skelly!

$(".dropdown-menu li a").click(function () {
    var selText = $(this).text();
    $(this).closest('div').find('button[data-toggle="dropdown"]').html(selText + ' <span class="caret"></span>');
    $(this).closest('.dropdown').removeClass("open");
    return false;
});

How to set column widths to a jQuery datatable?

The best solution I found this to work for me guys after trying all the other solutions.... Basically i set the sScrollX to 200% then set the individual column widths to the required % that I wanted. The more columns that you have and the more space that you require then you need to raise the sScrollX %... The null means that I want those columns to retain the datatables auto width they have set in their code. enter image description here

            $('#datatables').dataTable
            ({  
                "sScrollX": "200%", //This is what made my columns increase in size.
                "bScrollCollapse": true,
                "sScrollY": "320px",

                "bAutoWidth": false,
                "aoColumns": [
                    { "sWidth": "10%" }, // 1st column width 
                    { "sWidth": "null" }, // 2nd column width 
                    { "sWidth": "null" }, // 3rd column width
                    { "sWidth": "null" }, // 4th column width 
                    { "sWidth": "40%" }, // 5th column width 
                    { "sWidth": "null" }, // 6th column width
                    { "sWidth": "null" }, // 7th column width 
                    { "sWidth": "10%" }, // 8th column width 
                    { "sWidth": "10%" }, // 9th column width
                    { "sWidth": "40%" }, // 10th column width
                    { "sWidth": "null" } // 11th column width
                    ],
                "bPaginate": true,              
                "sDom": '<"H"TCfr>t<"F"ip>',
                "oTableTools": 
                {
                    "aButtons": [ "copy", "csv", "print", "xls", "pdf" ],
                    "sSwfPath": "copy_cvs_xls_pdf.swf"
                },
                "sPaginationType":"full_numbers",
                "aaSorting":[[0, "desc"]],
                "bJQueryUI":true    

            });

How to use Fiddler to monitor WCF service

This is straightforward if you have control over the client that is sending the communications. All you need to do is set the HttpProxy on the client-side service class.

I did this, for example, to trace a web service client running on a smartphone. I set the proxy on that client-side connection to the IP/port of Fiddler, which was running on a PC on the network. The smartphone app then sent all of its outgoing communication to the web service, through Fiddler.

This worked perfectly.

If your client is a WCF client, then see this Q&A for how to set the proxy.

Even if you don't have the ability to modify the code of the client-side app, you may be able to set the proxy administratively, depending on the webservices stack your client uses.

How to pass arguments to entrypoint in docker-compose.yml

The command clause does work as @Karthik says above.

As a simple example, the following service will have a -inMemory added to its ENTRYPOINT when docker-compose up is run.

version: '2'
services:
  local-dynamo:
    build: local-dynamo
    image: spud/dynamo
    command: -inMemory

How do I make a transparent border with CSS?

The easiest solution to this is to use rgba as the color: border-color: rgba(0,0,0,0); That is fully transparent border color.

ExecuteNonQuery doesn't return results

Because the SET NOCOUNT option is set to on. Remove the line "SET NOCOUNT ON;" in your query or stored procedure.

See more at SqlCommand.ExecuteNonQuery() returns -1 when doing Insert / Update / Delete.

How to Programmatically Add Views to Views

for anyone yet interested:

the best way I found is to use the inflate static method of View.

View inflatedView = View.inflate(context, yourViewXML, yourLinearLayout);

where yourViewXML is something like R.layout.myView

please notice that you need a ViewGroup in order to add a view (which is any layout you can think of)

so as an example lets say you have a fragment which it view already been inflated and you know that the root view is a layout, and you want to add a view to it:

    View view = getView(); // returns base view of the fragment
    if (view == null)
        return;
    if (!(view instanceof ViewGroup))
        return;

    ViewGroup viewGroup = (ViewGroup) view;
    View popup = View.inflate(viewGroup.getContext(), R.layout.someView, viewGroup);

Given a class, see if instance has method (Ruby)

Actually this doesn't work for both Objects and Classes.

This does:

class TestClass
  def methodName
  end
end

So with the given answer, this works:

TestClass.method_defined? :methodName # => TRUE

But this does NOT work:

t = TestClass.new
t.method_defined? : methodName  # => ERROR!

So I use this for both classes and objects:

Classes:

TestClass.methods.include? 'methodName'  # => TRUE

Objects:

t = TestClass.new
t.methods.include? 'methodName'  # => TRUE

Unstage a deleted file in git

The answers to your two questions are related. I'll start with the second:

Once you have staged a file (often with git add, though some other commands implicitly stage the changes as well, like git rm) you can back out that change with git reset -- <file>.

In your case you must have used git rm to remove the file, which is equivalent to simply removing it with rm and then staging that change. If you first unstage it with git reset -- <file> you can then recover it with git checkout -- <file>.

Laravel Eloquent inner join with multiple conditions

//You may use this example. Might be help you...

$user = User::select("users.*","items.id as itemId","jobs.id as jobId")
        ->join("items","items.user_id","=","users.id")
        ->join("jobs",function($join){
            $join->on("jobs.user_id","=","users.id")
                ->on("jobs.item_id","=","items.id");
        })
        ->get();
print_r($user);

MySQL direct INSERT INTO with WHERE clause

you can use UPDATE command.

UPDATE table_name SET name=@name, email=@email, phone=@phone WHERE client_id=@client_id

What's a .sh file?

open the location in terminal then type these commands 1. chmod +x filename.sh 2. ./filename.sh that's it

Making WPF applications look Metro-styled, even in Windows 7? (Window Chrome / Theming / Theme)

The solution I ended up choosing was MahApps.Metro (github), which (after using it on two pieces of software now) I consider an excellent UI kit (credit to Oliver Vogel for the suggestion).

Window style

It skins the application with very little effort required, and has adaptations of the standard Windows 8 controls. It's very robust.

Text box watermark

A version is available on Nuget:

You can install MahApps.Metro via Nuget using the GUI (right click on your project, Manage Nuget References, search for ‘MahApps.Metro’) or via the console:

PM> Install-Package MahApps.Metro

It's also free -- even for commercial use.

Update 10-29-2013:

I discovered that the Github version of MahApps.Metro is packed with controls and styles that aren't available in the current nuget version, including:

Datagrids:

enter image description here

Clean Window:

enter image description here

Flyouts:

enter image description here

Tiles:

enter image description here

The github repository is very active with quite a bit of user contributions. I recommend checking it out.

jQuery if statement, syntax

To add to what the others are saying, A and B can be function calls as well that return boolean values. If A returns false then B would never be called.

if (A() && B()) {
    // if A() returns false then B() is never called...
}

How do you get the magnitude of a vector in Numpy?

Yet another alternative is to use the einsum function in numpy for either arrays:

In [1]: import numpy as np

In [2]: a = np.arange(1200.0).reshape((-1,3))

In [3]: %timeit [np.linalg.norm(x) for x in a]
100 loops, best of 3: 3.86 ms per loop

In [4]: %timeit np.sqrt((a*a).sum(axis=1))
100000 loops, best of 3: 15.6 µs per loop

In [5]: %timeit np.sqrt(np.einsum('ij,ij->i',a,a))
100000 loops, best of 3: 8.71 µs per loop

or vectors:

In [5]: a = np.arange(100000)

In [6]: %timeit np.sqrt(a.dot(a))
10000 loops, best of 3: 80.8 µs per loop

In [7]: %timeit np.sqrt(np.einsum('i,i', a, a))
10000 loops, best of 3: 60.6 µs per loop

There does, however, seem to be some overhead associated with calling it that may make it slower with small inputs:

In [2]: a = np.arange(100)

In [3]: %timeit np.sqrt(a.dot(a))
100000 loops, best of 3: 3.73 µs per loop

In [4]: %timeit np.sqrt(np.einsum('i,i', a, a))
100000 loops, best of 3: 4.68 µs per loop

HTML embed autoplay="false", but still plays automatically

Just change the mime type to: type="audio/mpeg", this way chrome will honor the autostart="false" parameter.

Iteration over std::vector: unsigned vs signed index variable

I usually use BOOST_FOREACH:

#include <boost/foreach.hpp>

BOOST_FOREACH( vector_type::value_type& value, v ) {
    // do something with 'value'
}

It works on STL containers, arrays, C-style strings, etc.

How to display multiple images in one figure correctly?

Here is my approach that you may try:

import numpy as np
import matplotlib.pyplot as plt

w=10
h=10
fig=plt.figure(figsize=(8, 8))
columns = 4
rows = 5
for i in range(1, columns*rows +1):
    img = np.random.randint(10, size=(h,w))
    fig.add_subplot(rows, columns, i)
    plt.imshow(img)
plt.show()

The resulting image:

output_image

(Original answer date: Oct 7 '17 at 4:20)

Edit 1

Since this answer is popular beyond my expectation. And I see that a small change is needed to enable flexibility for the manipulation of the individual plots. So that I offer this new version to the original code. In essence, it provides:-

  1. access to individual axes of subplots
  2. possibility to plot more features on selected axes/subplot

New code:

import numpy as np
import matplotlib.pyplot as plt

w = 10
h = 10
fig = plt.figure(figsize=(9, 13))
columns = 4
rows = 5

# prep (x,y) for extra plotting
xs = np.linspace(0, 2*np.pi, 60)  # from 0 to 2pi
ys = np.abs(np.sin(xs))           # absolute of sine

# ax enables access to manipulate each of subplots
ax = []

for i in range(columns*rows):
    img = np.random.randint(10, size=(h,w))
    # create subplot and append to ax
    ax.append( fig.add_subplot(rows, columns, i+1) )
    ax[-1].set_title("ax:"+str(i))  # set title
    plt.imshow(img, alpha=0.25)

# do extra plots on selected axes/subplots
# note: index starts with 0
ax[2].plot(xs, 3*ys)
ax[19].plot(ys**2, xs)

plt.show()  # finally, render the plot

The resulting plot:

enter image description here

Edit 2

In the previous example, the code provides access to the sub-plots with single index, which is inconvenient when the figure has many rows/columns of sub-plots. Here is an alternative of it. The code below provides access to the sub-plots with [row_index][column_index], which is more suitable for manipulation of array of many sub-plots.

import matplotlib.pyplot as plt
import numpy as np

# settings
h, w = 10, 10        # for raster image
nrows, ncols = 5, 4  # array of sub-plots
figsize = [6, 8]     # figure size, inches

# prep (x,y) for extra plotting on selected sub-plots
xs = np.linspace(0, 2*np.pi, 60)  # from 0 to 2pi
ys = np.abs(np.sin(xs))           # absolute of sine

# create figure (fig), and array of axes (ax)
fig, ax = plt.subplots(nrows=nrows, ncols=ncols, figsize=figsize)

# plot simple raster image on each sub-plot
for i, axi in enumerate(ax.flat):
    # i runs from 0 to (nrows*ncols-1)
    # axi is equivalent with ax[rowid][colid]
    img = np.random.randint(10, size=(h,w))
    axi.imshow(img, alpha=0.25)
    # get indices of row/column
    rowid = i // ncols
    colid = i % ncols
    # write row/col indices as axes' title for identification
    axi.set_title("Row:"+str(rowid)+", Col:"+str(colid))

# one can access the axes by ax[row_id][col_id]
# do additional plotting on ax[row_id][col_id] of your choice
ax[0][2].plot(xs, 3*ys, color='red', linewidth=3)
ax[4][3].plot(ys**2, xs, color='green', linewidth=3)

plt.tight_layout(True)
plt.show()

The resulting plot:

plot3

AttributeError: Can only use .dt accessor with datetimelike values

When you write

df['Date'] = pd.to_datetime(df['Date'], errors='coerce')
df['Date'] = df['Date'].dt.strftime('%m/%d')

It can fixed

Java double.MAX_VALUE?

Double.MAX_VALUE is the maximum value a double can represent (somewhere around 1.7*10^308).

This should end in some calculation problems, if you try to subtract the maximum possible value of a data type.

Even though when you are dealing with money you should never use floating point values especially while rounding this can cause problems (you will either have to much or less money in your system then).

JSON.net: how to deserialize without using the default constructor?

Solution:

public Response Get(string jsonData) {
    var json = JsonConvert.DeserializeObject<modelname>(jsonData);
    var data = StoredProcedure.procedureName(json.Parameter, json.Parameter, json.Parameter, json.Parameter);
    return data;
}

Model:

public class modelname {
    public long parameter{ get; set; }
    public int parameter{ get; set; }
    public int parameter{ get; set; }
    public string parameter{ get; set; }
}

Can´t run .bat file under windows 10

There is no inherent reason that a simple batch file would run in XP but not Windows 10. It is possible you are referencing a command or a 3rd party utility that no longer exists. To know more about what is actually happening, you will need to do one of the following:

  • Add a pause to the batch file so that you can see what is happening before it exits.
    1. Right click on one of the .bat files and select "edit". This will open the file in notepad.
    2. Go to the very end of the file and add a new line by pressing "enter".
    3. type pause.
    4. Save the file.
    5. Run the file again using the same method you did before.

- OR -

  • Run the batch file from a static command prompt so the window does not close.
    1. In the folder where the .bat files are located, hold down the "shift" key and right click in the white space.
    2. Select "Open Command Window Here".
    3. You will now see a new command prompt. Type in the name of the batch file and press enter.

Once you have done this, I recommend creating a new question with the output you see after using one of the methods above.

How do I activate a specific workbook and a specific sheet?

You have to set a reference to the workbook you're opening. Then you can do anything you want with that workbook by using its reference.

Dim wkb As Workbook
Set wkb = Workbooks.Open("Tire.xls") ' open workbook and set reference!

wkb.Sheets("Sheet1").Activate
wkb.Sheets("Sheet1").Cells(2, 1).Value = 123

Could even set a reference to the sheet, which will make life easier later:

Dim wkb As Workbook
Dim sht As Worksheet

Set wkb = Workbooks.Open("Tire.xls")
Set sht = wkb.Sheets("Sheet2")

sht.Activate
sht.Cells(2, 1) = 123

Others have pointed out that .Activate may be superfluous in your case. You don't strictly need to activate a sheet before editing its cells. But, if that's what you want to do, it does no harm to activate -- except for a small hit to performance which should not be noticeable as long as you do it only once or a few times. However, if you activate many times e.g. in a loop, it will slow things down significantly, so activate should be avoided.

How to handle Pop-up in Selenium WebDriver using Java

You can handle popup window or alert box:

Alert alert = driver.switchTo().alert();
alert.accept();

You can also decline the alert box:

Alert alert = driver.switchTo().alert();
alert().dismiss();

What is the difference between parseInt(string) and Number(string) in JavaScript?

The parseInt function allows you to specify a radix for the input string and is limited to integer values.

parseInt('Z', 36) === 35

The Number constructor called as a function will parse the string with a grammar and is limited to base 10 and base 16.

StringNumericLiteral :::
    StrWhiteSpaceopt 
    StrWhiteSpaceopt StrNumericLiteral StrWhiteSpaceopt

StrWhiteSpace :::
    StrWhiteSpaceChar StrWhiteSpaceopt

StrWhiteSpaceChar :::
    WhiteSpace 
    LineTerminator

StrNumericLiteral :::
    StrDecimalLiteral 
    HexIntegerLiteral

StrDecimalLiteral :::
    StrUnsignedDecimalLiteral 
    + StrUnsignedDecimalLiteral 
    - StrUnsignedDecimalLiteral

StrUnsignedDecimalLiteral :::
    Infinity 
    DecimalDigits . DecimalDigitsopt ExponentPartopt 
    . DecimalDigits ExponentPartopt     
    DecimalDigits ExponentPartopt

DecimalDigits :::
    DecimalDigit 
    DecimalDigits DecimalDigit

DecimalDigit ::: one of
    0 1 2 3 4 5 6 7 8 9

ExponentPart :::
    ExponentIndicator SignedInteger

ExponentIndicator ::: one of
    e E

SignedInteger :::
    DecimalDigits 
    + DecimalDigits 
    - DecimalDigits

HexIntegerLiteral :::
    0x HexDigit 
    0X HexDigit 
    HexIntegerLiteral HexDigit

HexDigit ::: one of
    0 1 2 3 4 5 6 7 8 9 a b c d e f A B C D E F

How to debug external class library projects in visual studio?

[according to Martin Beckett, the guy who send me this answer ]

You can debug into an external library.

In the project settings tab look for 'visual studio directories' in the 'source code' field include the path to the openCV sources. Then make sure that the .pdb files for each of the debug dll are in the same directory as the dll.

How to call jQuery function onclick?

Try this:

HTML:

<input type="submit" value="submit" name="submit" onclick="myfunction()">

jQuery:

<script type="text/javascript">
 function myfunction() 
 {
    var url = $(location).attr('href');
    $('#spn_url').html('<strong>' + url + '</strong>');
 }
</script>

IntelliJ: Working on multiple projects

Yes, your intuition was good. You shouldn't use three instances of intellij. You can open one Project and add other 'parts' of application as Modules. Add them via project browser, default hotkey is alt+1

Iterating through populated rows

I'm going to make a couple of assumptions in my answer. I'm assuming your data starts in A1 and there are no empty cells in the first column of each row that has data.

This code will:

  1. Find the last row in column A that has data
  2. Loop through each row
  3. Find the last column in current row with data
  4. Loop through each cell in current row up to last column found.

This is not a fast method but will iterate through each one individually as you suggested is your intention.


Sub iterateThroughAll()
    ScreenUpdating = False
    Dim wks As Worksheet
    Set wks = ActiveSheet

    Dim rowRange As Range
    Dim colRange As Range

    Dim LastCol As Long
    Dim LastRow As Long
    LastRow = wks.Cells(wks.Rows.Count, "A").End(xlUp).Row

    Set rowRange = wks.Range("A1:A" & LastRow)

    'Loop through each row
    For Each rrow In rowRange
        'Find Last column in current row
        LastCol = wks.Cells(rrow, wks.Columns.Count).End(xlToLeft).Column
        Set colRange = wks.Range(wks.Cells(rrow, 1), wks.Cells(rrow, LastCol))

        'Loop through all cells in row up to last col
        For Each cell In colRange
            'Do something to each cell
            Debug.Print (cell.Value)
        Next cell
    Next rrow
    ScreenUpdating = True
End Sub

How do I append text to a file?

How about:

echo "hello" >> <filename>

Using the >> operator will append data at the end of the file, while using the > will overwrite the contents of the file if already existing.

You could also use printf in the same way:

printf "hello" >> <filename>

Note that it can be dangerous to use the above. For instance if you already have a file and you need to append data to the end of the file and you forget to add the last > all data in the file will be destroyed. You can change this behavior by setting the noclobber variable in your .bashrc:

set -o noclobber

Now when you try to do echo "hello" > file.txt you will get a warning saying cannot overwrite existing file.

To force writing to the file you must now use the special syntax:

echo "hello" >| <filename>

You should also know that by default echo adds a trailing new-line character which can be suppressed by using the -n flag:

echo -n "hello" >> <filename>

References

MySQL ERROR 1045 (28000): Access denied for user 'bill'@'localhost' (using password: YES)

MySQL account names consist of a user name and a host name, The name 'localhost' in host name indicates the local host also You can use the wildcard characters “%” and “_” in host name or IP address values. These have the same meaning as for pattern-matching operations performed with the LIKE operator. For example, a host value of '%' matches any host name, whereas a value of '%.mysql.com' matches any host in the mysql.com domain. '192.168.1.%' matches any host in the 192.168.1 class C network.

Above was just introduction:

actually both users 'bill'@'localhost' and 'bill'@'%' are different MySQL accounts, hence both should use their own authentication details like password.

For more information refer http://dev.mysql.com/doc/refman//5.5/en/account-names.html

How to get the Google Map based on Latitude on Longitude?

<script>
    function initMap() {
        //echo hiii;

        var map = new google.maps.Map(document.getElementById('map'), {
          center: new google.maps.LatLng(8.5241, 76.9366),
          zoom: 12
        });
        var infoWindow = new google.maps.InfoWindow;

        // Change this depending on the name of your PHP or XML file
        downloadUrl('https://storage.googleapis.com/mapsdevsite/json/mapmarkers2.xml', function(data) {
            var xml = data.responseXML;
            var markers = xml.documentElement.getElementsByTagName('package');
            Array.prototype.forEach.call(markers, function(markerElem) {
                var id = markerElem.getAttribute('id');
                // var name = markerElem.getAttribute('name');
                // var address = markerElem.getAttribute('address');
                // var type = markerElem.getAttribute('type');
                // var latitude = results[0].geometry.location.lat();
                // var longitude = results[0].geometry.location.lng();
                var point = new google.maps.LatLng(
                    parseFloat(markerElem.getAttribute('latitude')),
                    parseFloat(markerElem.getAttribute('longitude'))
                );

                var infowincontent = document.createElement('div');
                var strong = document.createElement('strong');
                strong.textContent = name
                infowincontent.appendChild(strong);
                infowincontent.appendChild(document.createElement('br'));

                var text = document.createElement('text');
                text.textContent = address
                infowincontent.appendChild(text);
                var icon = customLabel[type] || {};
                var package = new google.maps.Marker({
                    map: map,
                    position: point,
                    label: icon.label
                });

                package.addListener('click', function() {
                    infoWindow.setContent(infowincontent);
                    infoWindow.open(map, package);
                });
            });
        });
    }


    function downloadUrl(url, callback) {
        var request = window.ActiveXObject ?
            new ActiveXObject('Microsoft.XMLHTTP') :
            new XMLHttpRequest;

        request.onreadystatechange = function() {
            if (request.readyState == 4) {
                request.onreadystatechange = doNothing;
                callback(request, request.status);
            }
        };

        request.open('GET', url, true);
        request.send(null);
    }

Abort Ajax requests using jQuery

As many people on the thread have noted, just because the request is aborted on the client-side, the server will still process the request. This creates unnecessary load on the server because it's doing work that we've quit listening to on the front-end.

The problem I was trying to solve (that others may run in to as well) is that when the user entered information in an input field, I wanted to fire off a request for a Google Instant type of feel.

To avoid firing unnecessary requests and to maintain the snappiness of the front-end, I did the following:

var xhrQueue = [];
var xhrCount = 0;

$('#search_q').keyup(function(){

    xhrQueue.push(xhrCount);

    setTimeout(function(){

        xhrCount = ++xhrCount;

        if (xhrCount === xhrQueue.length) {
            // Fire Your XHR //
        }

    }, 150);

});

This will essentially send one request every 150ms (a variable that you can customize for your own needs). If you're having trouble understanding what exactly is happening here, log xhrCount and xhrQueue to the console just before the if block.

#pragma mark in Swift?

I think Extensions is a better way instead of #pragma mark.

The Code before using Extensions:

class ViewController: UIViewController, UICollectionViewDataSource, UICollectionViewDelegate {
    ...

    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        ...
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        ...
    }

    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
        ...
    }
}

The code after using Extensions:

class ViewController: UIViewController {
    ...
}

extension ViewController: UICollectionViewDataSource {
    func collectionView(_ collectionView: UICollectionView, numberOfItemsInSection section: Int) -> Int {
        ...
    }

    func collectionView(_ collectionView: UICollectionView, cellForItemAt indexPath: IndexPath) -> UICollectionViewCell {
        ...
    }
}

extension ViewController: UICollectionViewDelegate {
    func collectionView(_ collectionView: UICollectionView, didSelectItemAt indexPath: IndexPath) {
       ...
    }
}

Convert a string to integer with decimal in Python

"Convert" only makes sense when you change from one data type to another without loss of fidelity. The number represented by the string is a float and will lose precision upon being forced into an int.

You want to round instead, probably (I hope that the numbers don't represent currency because then rounding gets a whole lot more complicated).

round(float('23.45678'))

json_encode/json_decode - returns stdClass instead of Array in PHP

Take a closer look at the second parameter of json_decode($json, $assoc, $depth) at https://secure.php.net/json_decode

How to fire a button click event from JavaScript in ASP.NET

You can just place this line in a JavaScript function:

__doPostBack('btnSubmit','OnClick');

Or do something like this:

$('#btnSubmit').trigger('click');

Create an instance of a class from a string

To create an instance of a class from another project in the solution, you can get the assembly indicated by the name of any class (for example BaseEntity) and create a new instance:

  var newClass = System.Reflection.Assembly.GetAssembly(typeof(BaseEntity)).CreateInstance("MyProject.Entities.User");

Convert Text to Uppercase while typing in Text box

**/*Css Class*/**
.upCase
{
    text-transform: uppercase;
}

<asp:TextBox ID="TextBox1" runat="server" Text="abc" Cssclass="upCase"></asp:TextBox>

Finding all positions of substring in a larger string in C#

I found this example and incorporated it into a function:

    public static int solution1(int A, int B)
    {
        // Check if A and B are in [0...999,999,999]
        if ( (A >= 0 && A <= 999999999) && (B >= 0 && B <= 999999999))
        {
            if (A == 0 && B == 0)
            {
                return 0;
            }
            // Make sure A < B
            if (A < B)
            {                    
                // Convert A and B to strings
                string a = A.ToString();
                string b = B.ToString();
                int index = 0;

                // See if A is a substring of B
                if (b.Contains(a))
                {
                    // Find index where A is
                    if (b.IndexOf(a) != -1)
                    {                            
                        while ((index = b.IndexOf(a, index)) != -1)
                        {
                            Console.WriteLine(A + " found at position " + index);
                            index++;
                        }
                        Console.ReadLine();
                        return b.IndexOf(a);
                    }
                    else
                        return -1;
                }
                else
                {
                    Console.WriteLine(A + " is not in " + B + ".");
                    Console.ReadLine();

                    return -1;
                }
            }
            else
            {
                Console.WriteLine(A + " must be less than " + B + ".");
               // Console.ReadLine();

                return -1;
            }                
        }
        else
        {
            Console.WriteLine("A or B is out of range.");
            //Console.ReadLine();

            return -1;
        }
    }

    static void Main(string[] args)
    {
        int A = 53, B = 1953786;
        int C = 78, D = 195378678;
        int E = 57, F = 153786;

        solution1(A, B);
        solution1(C, D);
        solution1(E, F);

        Console.WriteLine();
    }

Returns:

53 found at position 2

78 found at position 4
78 found at position 7

57 is not in 153786

Disable/Enable button in Excel/VBA

Others are correct in saying that setting button.enabled = false doesn't prevent the button from triggering. However, I found that setting button.visible = false does work. The button disappears and can't be clicked until you set visible to true again.

HQL Hibernate INNER JOIN

You can do it without having to create a real Hibernate mapping. Try this:

SELECT * FROM Employee e, Team t WHERE e.Id_team=t.Id_team

Enter key press behaves like a Tab in Javascript

Here's what I came up with.

form.addEventListener("submit", (e) => { //On Submit
 let key = e.charCode || e.keyCode || 0 //get the key code
 if (key = 13) { //If enter key
    e.preventDefault()
    const inputs = Array.from(document.querySelectorAll("form input")) //Get array of inputs
    let nextInput = inputs[inputs.indexOf(document.activeElement) + 1] //get index of input after the current input
    nextInput.focus() //focus new input
}
}

How to define a relative path in java

Example for Spring Boot. My WSDL-file is in Resources in "wsdl" folder. The path to the WSDL-file is:

resources/wsdl/WebServiceFile.wsdl

To get the path from some method to this file you can do the following:

String pathToWsdl = this.getClass().getClassLoader().
                    getResource("wsdl\\WebServiceFile.wsdl").toString();

Calling a method inside another method in same class

It is just an overload. The add method is from the ArrayList class. Look that Staff inherits from it.

TypeError: method() takes 1 positional argument but 2 were given

In simple words.

In Python you should add self argument as the first argument to all defined methods in classes:

class MyClass:
  def method(self, arg):
    print(arg)

Then you can use your method according to your intuition:

>>> my_object = MyClass()
>>> my_object.method("foo")
foo

This should solve your problem :)

For a better understanding, you can also read the answers to this question: What is the purpose of self?

Sort hash by key, return hash in Ruby

Sort hash by key, return hash in Ruby

With destructuring and Hash#sort

hash.sort { |(ak, _), (bk, _)| ak <=> bk }.to_h

Enumerable#sort_by

hash.sort_by { |k, v| k }.to_h

Hash#sort with default behaviour

h = { "b" => 2, "c" => 1, "a" => 3  }
h.sort         # e.g. ["a", 20] <=> ["b", 30]
hash.sort.to_h #=> { "a" => 3, "b" => 2, "c" => 1 }

Note: < Ruby 2.1

array = [["key", "value"]] 
hash  = Hash[array]
hash #=> {"key"=>"value"}

Note: > Ruby 2.1

[["key", "value"]].to_h #=> {"key"=>"value"}

Add a string of text into an input field when user clicks a button

this will do it with just javascript - you can also put the function in a .js file and call it with onclick

//button
<div onclick="
   document.forms['name_of_the_form']['name_of_the_input'].value += 'text you want to add to it'"
>button</div>

LogisticRegression: Unknown label type: 'continuous' using sklearn in python

You are passing floats to a classifier which expects categorical values as the target vector. If you convert it to int it will be accepted as input (although it will be questionable if that's the right way to do it).

It would be better to convert your training scores by using scikit's labelEncoder function.

The same is true for your DecisionTree and KNeighbors qualifier.

from sklearn import preprocessing
from sklearn import utils

lab_enc = preprocessing.LabelEncoder()
encoded = lab_enc.fit_transform(trainingScores)
>>> array([1, 3, 2, 0], dtype=int64)

print(utils.multiclass.type_of_target(trainingScores))
>>> continuous

print(utils.multiclass.type_of_target(trainingScores.astype('int')))
>>> multiclass

print(utils.multiclass.type_of_target(encoded))
>>> multiclass

How to vertically align a html radio button to it's label?

I like putting the inputs inside the labels (added bonus: now you don't need the for attribute on the label), and put vertical-align: middle on the input.

_x000D_
_x000D_
label > input[type=radio] {_x000D_
    vertical-align: middle;_x000D_
    margin-top: -2px;_x000D_
}_x000D_
_x000D_
#d2 {  _x000D_
    font-size: 30px;_x000D_
}
_x000D_
<div>_x000D_
 <label><input type="radio" name="radio" value="1">Good</label>_x000D_
 <label><input type="radio" name="radio" value="2">Excellent</label>_x000D_
<div>_x000D_
<br>_x000D_
<div id="d2">_x000D_
 <label><input type="radio" name="radio2" value="1">Good</label>_x000D_
 <label><input type="radio" name="radio2" value="2">Excellent</label>_x000D_
<div>
_x000D_
_x000D_
_x000D_

(The -2px margin-top is a matter of taste.)

Another option I really like is using a table. (Hold your pitch forks! It's really nice!) It does mean you need to add the for attribute to all your labels and ids to your inputs. I'd recommended this option for labels with long text content, over multiple lines.

_x000D_
_x000D_
<table><tr><td>_x000D_
    <input id="radioOption" name="radioOption" type="radio" />_x000D_
    </td><td>_x000D_
    <label for="radioOption">                     _x000D_
        Really good option_x000D_
    </label>_x000D_
</td></tr></table>
_x000D_
_x000D_
_x000D_

How to Specify "Vary: Accept-Encoding" header in .htaccess

if anyone needs this for NGINX configuration file here is the snippet:

location ~* \.(js|css|xml|gz)$ {
    add_header Vary "Accept-Encoding";
    (... other headers or rules ...)
}

Find max and second max salary for a employee table MySQL

This is awesome Query to find the nth Maximum: For example: -

  1. You want to find salary 8th row Salary, Just Changed the indexed value to 8.

  2. Suppose you have 100 rows with Salary. Now you want to find Max salary for 90th row. Just changed the Indexed Value to 90.

    set @n:=0;
    select * from (select *, (@n:=@n+1) as indexed from employee order by Salary desc)t where t.indexed = 1;
    

Mockito: List Matchers with generics

In addition to anyListOf above, you can always specify generics explicitly using this syntax:

when(mock.process(Matchers.<List<Bar>>any(List.class)));

Java 8 newly allows type inference based on parameters, so if you're using Java 8, this may work as well:

when(mock.process(Matchers.any()));

Remember that neither any() nor anyList() will apply any checks, including type or null checks. In Mockito 2.x, any(Foo.class) was changed to mean "any instanceof Foo", but any() still means "any value including null".

NOTE: The above has switched to ArgumentMatchers in newer versions of Mockito, to avoid a name collision with org.hamcrest.Matchers. Older versions of Mockito will need to keep using org.mockito.Matchers as above.

Simple line plots using seaborn

It's possible to get this done using seaborn.lineplot() but it involves some additional work of converting numpy arrays to pandas dataframe. Here's a complete example:

# imports
import seaborn as sns
import numpy as np
import pandas as pd

# inputs
In [41]: num = np.array([1, 2, 3, 4, 5])
In [42]: sqr = np.array([1, 4, 9, 16, 25])

# convert to pandas dataframe
In [43]: d = {'num': num, 'sqr': sqr}
In [44]: pdnumsqr = pd.DataFrame(d)

# plot using lineplot
In [45]: sns.set(style='darkgrid')
In [46]: sns.lineplot(x='num', y='sqr', data=pdnumsqr)
Out[46]: <matplotlib.axes._subplots.AxesSubplot at 0x7f583c05d0b8>

And we get the following plot:

square plot

Populating a data frame in R in a loop

It is often preferable to avoid loops and use vectorized functions. If that is not possible there are two approaches:

  1. Preallocate your data.frame. This is not recommended because indexing is slow for data.frames.
  2. Use another data structure in the loop and transform into a data.frame afterwards. A list is very useful here.

Example to illustrate the general approach:

mylist <- list() #create an empty list

for (i in 1:5) {
  vec <- numeric(5) #preallocate a numeric vector
  for (j in 1:5) { #fill the vector
    vec[j] <- i^j 
  }
  mylist[[i]] <- vec #put all vectors in the list
}
df <- do.call("rbind",mylist) #combine all vectors into a matrix

In this example it is not necessary to use a list, you could preallocate a matrix. However, if you do not know how many iterations your loop will need, you should use a list.

Finally here is a vectorized alternative to the example loop:

outer(1:5,1:5,function(i,j) i^j)

As you see it's simpler and also more efficient.

How can I load the contents of a text file into a batch file variable?

Can you define further processing?

You can use a for loop to almost do this, but there's no easy way to insert CR/LF into an environment variable, so you'll have everything in one line. (you may be able to work around this depending on what you need to do.)

You're also limited to less than about 8k text files this way. (You can't create a single env var bigger than around 8k.)

Bill's suggestion of a for loop is probably what you need. You process the file one line at a time:

(use %i at a command line %%i in a batch file)

for /f "tokens=1 delims=" %%i in (file.txt) do echo %%i

more advanced:

for /f "tokens=1 delims=" %%i in (file.txt) do call :part2 %%i
goto :fin

:part2
echo %1
::do further processing here
goto :eof

:fin

Android emulator failed to allocate memory 8

Update: Starting with Android SDK Manager version 21, the solution is to edit C:\Users\.android\avd\.avd\config.ini and change the value

hw.ramSize=1024 to

hw.ramSize=1024MB

OR

hw.ramSize=512MB

Compare cell contents against string in Excel

You can use the EXACT Function for exact string comparisons.

=IF(EXACT(A1, "ENG"), 1, 0)

Loop through each cell in a range of cells when given a Range object

I'm resurrecting the dead here, but because a range can be defined as "A:A", using a for each loop ends up with a potential infinite loop. The solution, as far as I know, is to use the Do Until loop.

Do Until Selection.Value = ""
  Rem Do things here...
Loop

Best way to save a trained model in PyTorch?

The pickle Python library implements binary protocols for serializing and de-serializing a Python object.

When you import torch (or when you use PyTorch) it will import pickle for you and you don't need to call pickle.dump() and pickle.load() directly, which are the methods to save and to load the object.

In fact, torch.save() and torch.load() will wrap pickle.dump() and pickle.load() for you.

A state_dict the other answer mentioned deserves just few more notes.

What state_dict do we have inside PyTorch? There are actually two state_dicts.

The PyTorch model is torch.nn.Module has model.parameters() call to get learnable parameters (w and b). These learnable parameters, once randomly set, will update over time as we learn. Learnable parameters are the first state_dict.

The second state_dict is the optimizer state dict. You recall that the optimizer is used to improve our learnable parameters. But the optimizer state_dict is fixed. Nothing to learn in there.

Because state_dict objects are Python dictionaries, they can be easily saved, updated, altered, and restored, adding a great deal of modularity to PyTorch models and optimizers.

Let's create a super simple model to explain this:

import torch
import torch.optim as optim

model = torch.nn.Linear(5, 2)

# Initialize optimizer
optimizer = optim.SGD(model.parameters(), lr=0.001, momentum=0.9)

print("Model's state_dict:")
for param_tensor in model.state_dict():
    print(param_tensor, "\t", model.state_dict()[param_tensor].size())

print("Model weight:")    
print(model.weight)

print("Model bias:")    
print(model.bias)

print("---")
print("Optimizer's state_dict:")
for var_name in optimizer.state_dict():
    print(var_name, "\t", optimizer.state_dict()[var_name])

This code will output the following:

Model's state_dict:
weight   torch.Size([2, 5])
bias     torch.Size([2])
Model weight:
Parameter containing:
tensor([[ 0.1328,  0.1360,  0.1553, -0.1838, -0.0316],
        [ 0.0479,  0.1760,  0.1712,  0.2244,  0.1408]], requires_grad=True)
Model bias:
Parameter containing:
tensor([ 0.4112, -0.0733], requires_grad=True)
---
Optimizer's state_dict:
state    {}
param_groups     [{'lr': 0.001, 'momentum': 0.9, 'dampening': 0, 'weight_decay': 0, 'nesterov': False, 'params': [140695321443856, 140695321443928]}]

Note this is a minimal model. You may try to add stack of sequential

model = torch.nn.Sequential(
          torch.nn.Linear(D_in, H),
          torch.nn.Conv2d(A, B, C)
          torch.nn.Linear(H, D_out),
        )

Note that only layers with learnable parameters (convolutional layers, linear layers, etc.) and registered buffers (batchnorm layers) have entries in the model's state_dict.

Non learnable things, belong to the optimizer object state_dict, which contains information about the optimizer's state, as well as the hyperparameters used.

The rest of the story is the same; in the inference phase (this is a phase when we use the model after training) for predicting; we do predict based on the parameters we learned. So for the inference, we just need to save the parameters model.state_dict().

torch.save(model.state_dict(), filepath)

And to use later model.load_state_dict(torch.load(filepath)) model.eval()

Note: Don't forget the last line model.eval() this is crucial after loading the model.

Also don't try to save torch.save(model.parameters(), filepath). The model.parameters() is just the generator object.

On the other side, torch.save(model, filepath) saves the model object itself, but keep in mind the model doesn't have the optimizer's state_dict. Check the other excellent answer by @Jadiel de Armas to save the optimizer's state dict.

error 1265. Data truncated for column when trying to load data from txt file

You're missing FIELDS TERMINATED BY ',' and it's assuming you're delimiting by tabs by default.

How merge two objects array in angularjs?

$scope.actions.data.concat is not a function 

same problem with me but i solve the problem by

 $scope.actions.data = [].concat($scope.actions.data , data)

How can you search Google Programmatically Java API

As an alternative to BalusC answer as it has been deprecated and you have to use proxies, you can use this package. Code sample:

Map<String, String> parameter = new HashMap<>();
parameter.put("q", "Coffee");
parameter.put("location", "Portland");
GoogleSearchResults serp = new GoogleSearchResults(parameter);

JsonObject data = serp.getJson();
JsonArray results = (JsonArray) data.get("organic_results");
JsonObject first_result = results.get(0).getAsJsonObject();
System.out.println("first coffee: " + first_result.get("title").getAsString());

Library on GitHub

Get the IP Address of local computer

The problem with all the approaches based on gethostbyname is that you will not get all IP addresses assigned to a particular machine. Servers usually have more than one adapter.

Here is an example of how you can iterate through all Ipv4 and Ipv6 addresses on the host machine:

void ListIpAddresses(IpAddresses& ipAddrs)
{
  IP_ADAPTER_ADDRESSES* adapter_addresses(NULL);
  IP_ADAPTER_ADDRESSES* adapter(NULL);

  // Start with a 16 KB buffer and resize if needed -
  // multiple attempts in case interfaces change while
  // we are in the middle of querying them.
  DWORD adapter_addresses_buffer_size = 16 * KB;
  for (int attempts = 0; attempts != 3; ++attempts)
  {
    adapter_addresses = (IP_ADAPTER_ADDRESSES*)malloc(adapter_addresses_buffer_size);
    assert(adapter_addresses);

    DWORD error = ::GetAdaptersAddresses(
      AF_UNSPEC, 
      GAA_FLAG_SKIP_ANYCAST | 
        GAA_FLAG_SKIP_MULTICAST | 
        GAA_FLAG_SKIP_DNS_SERVER |
        GAA_FLAG_SKIP_FRIENDLY_NAME, 
      NULL, 
      adapter_addresses,
      &adapter_addresses_buffer_size);

    if (ERROR_SUCCESS == error)
    {
      // We're done here, people!
      break;
    }
    else if (ERROR_BUFFER_OVERFLOW == error)
    {
      // Try again with the new size
      free(adapter_addresses);
      adapter_addresses = NULL;

      continue;
    }
    else
    {
      // Unexpected error code - log and throw
      free(adapter_addresses);
      adapter_addresses = NULL;

      // @todo
      LOG_AND_THROW_HERE();
    }
  }

  // Iterate through all of the adapters
  for (adapter = adapter_addresses; NULL != adapter; adapter = adapter->Next)
  {
    // Skip loopback adapters
    if (IF_TYPE_SOFTWARE_LOOPBACK == adapter->IfType)
    {
      continue;
    }

    // Parse all IPv4 and IPv6 addresses
    for (
      IP_ADAPTER_UNICAST_ADDRESS* address = adapter->FirstUnicastAddress; 
      NULL != address;
      address = address->Next)
    {
      auto family = address->Address.lpSockaddr->sa_family;
      if (AF_INET == family)
      {
        // IPv4
        SOCKADDR_IN* ipv4 = reinterpret_cast<SOCKADDR_IN*>(address->Address.lpSockaddr);

        char str_buffer[INET_ADDRSTRLEN] = {0};
        inet_ntop(AF_INET, &(ipv4->sin_addr), str_buffer, INET_ADDRSTRLEN);
        ipAddrs.mIpv4.push_back(str_buffer);
      }
      else if (AF_INET6 == family)
      {
        // IPv6
        SOCKADDR_IN6* ipv6 = reinterpret_cast<SOCKADDR_IN6*>(address->Address.lpSockaddr);

        char str_buffer[INET6_ADDRSTRLEN] = {0};
        inet_ntop(AF_INET6, &(ipv6->sin6_addr), str_buffer, INET6_ADDRSTRLEN);

        std::string ipv6_str(str_buffer);

        // Detect and skip non-external addresses
        bool is_link_local(false);
        bool is_special_use(false);

        if (0 == ipv6_str.find("fe"))
        {
          char c = ipv6_str[2];
          if (c == '8' || c == '9' || c == 'a' || c == 'b')
          {
            is_link_local = true;
          }
        }
        else if (0 == ipv6_str.find("2001:0:"))
        {
          is_special_use = true;
        }

        if (! (is_link_local || is_special_use))
        {
          ipAddrs.mIpv6.push_back(ipv6_str);
        }
      }
      else
      {
        // Skip all other types of addresses
        continue;
      }
    }
  }

  // Cleanup
  free(adapter_addresses);
  adapter_addresses = NULL;

  // Cheers!
}

PHP code to convert a MySQL query to CSV

If you'd like the download to be offered as a download that can be opened directly in Excel, this may work for you: (copied from an old unreleased project of mine)

These functions setup the headers:

function setExcelContentType() {
    if(headers_sent())
        return false;

    header('Content-type: application/vnd.ms-excel');
    return true;
}

function setDownloadAsHeader($filename) {
    if(headers_sent())
        return false;

    header('Content-disposition: attachment; filename=' . $filename);
    return true;
}

This one sends a CSV to a stream using a mysql result

function csvFromResult($stream, $result, $showColumnHeaders = true) {
    if($showColumnHeaders) {
        $columnHeaders = array();
        $nfields = mysql_num_fields($result);
        for($i = 0; $i < $nfields; $i++) {
            $field = mysql_fetch_field($result, $i);
            $columnHeaders[] = $field->name;
        }
        fputcsv($stream, $columnHeaders);
    }

    $nrows = 0;
    while($row = mysql_fetch_row($result)) {
        fputcsv($stream, $row);
        $nrows++;
    }

    return $nrows;
}

This one uses the above function to write a CSV to a file, given by $filename

function csvFileFromResult($filename, $result, $showColumnHeaders = true) {
    $fp = fopen($filename, 'w');
    $rc = csvFromResult($fp, $result, $showColumnHeaders);
    fclose($fp);
    return $rc;
}

And this is where the magic happens ;)

function csvToExcelDownloadFromResult($result, $showColumnHeaders = true, $asFilename = 'data.csv') {
    setExcelContentType();
    setDownloadAsHeader($asFilename);
    return csvFileFromResult('php://output', $result, $showColumnHeaders);
}

For example:

$result = mysql_query("SELECT foo, bar, shazbot FROM baz WHERE boo = 'foo'");
csvToExcelDownloadFromResult($result);

Why is a primary-foreign key relation required when we can join without it?

The main reason for primary and foreign keys is to enforce data consistency.

A primary key enforces the consistency of uniqueness of values over one or more columns. If an ID column has a primary key then it is impossible to have two rows with the same ID value. Without that primary key, many rows could have the same ID value and you wouldn't be able to distinguish between them based on the ID value alone.

A foreign key enforces the consistency of data that points elsewhere. It ensures that the data which is pointed to actually exists. In a typical parent-child relationship, a foreign key ensures that every child always points at a parent and that the parent actually exists. Without the foreign key you could have "orphaned" children that point at a parent that doesn't exist.

How do I dump an object's fields to the console?

Possibly:

puts variable.inspect

Performing SQL queries on an Excel Table within a Workbook with VBA Macro

One thing you may be able to do is get the address of the dynamic named range, and use that as the input in your SQL string. Something like:

Sheets("shtName").range("namedRangeName").Address

Which will spit out an address string, something like $A$1:$A$8

Edit:

As I said in my comment below, you can dynamically get the full address (including sheet name) and either use it directly or parse the sheet name for later use:

ActiveWorkbook.Names.Item("namedRangeName").RefersToLocal

Which results in a string like =Sheet1!$C$1:$C$4. So for your code example above, your SQL statement could be

strRangeAddress = Mid(ActiveWorkbook.Names.Item("namedRangeName").RefersToLocal,2)

strSQL = "SELECT * FROM [strRangeAddress]"

How to find the unclosed div tag

Use notepad ++ . you can find them easily

http://notepad-plus-plus.org/download/

Or you can View source from FIREfox - Unclosed divs will be shown in RED

How to convert the following json string to java object?

Check out Google's Gson: http://code.google.com/p/google-gson/

From their website:

Gson gson = new Gson(); // Or use new GsonBuilder().create();
MyType target2 = gson.fromJson(json, MyType.class); // deserializes json into target2

You would just need to make a MyType class (renamed, of course) with all the fields in the json string. It might get a little more complicated when you're doing the arrays, if you prefer to do all of the parsing manually (also pretty easy) check out http://www.json.org/ and download the Java source for the Json parser objects.

How to make HTTP Post request with JSON body in Swift

you can do something like this:

func HTTPPostJSON(url: String,  data: NSData,
    callback: (String, String?) -> Void) {

        var request = NSMutableURLRequest(URL: NSURL(string: url)!)
        request.HTTPMethod = "POST"
        request.addValue("application/json",forHTTPHeaderField: "Content-Type")
        request.addValue("application/json",forHTTPHeaderField: "Accept")
        request.HTTPBody = data
        HTTPsendRequest(request, callback: callback)
}

func HTTPsendRequest(request: NSMutableURLRequest,
    callback: (String, String?) -> Void) {
        let task = NSURLSession.sharedSession()
            .dataTaskWithRequest(request) {
                (data, response, error) -> Void in
                if (error != nil) {
                    callback("", error.localizedDescription)
                } else {
                    callback(NSString(data: data,
                        encoding: NSUTF8StringEncoding)! as String, nil)
                }
        }

        task.resume()
}
//use
var data :Dictionary<String, AnyObject> = yourDictionaryData<--
var requestNSData:NSData = NSJSONSerialization.dataWithJSONObject(request, options:NSJSONWritingOptions(0), error: &err)!
HTTPPostJSON("http://yourPosturl..", data: requestNSData) { (response, error) -> Void in
    if error != nil{
        //error
        return;
    }

    println(response);
}

Extract digits from a string in Java

I have finalized the code for phone numbers +9 (987) 124124.

Unicode characters occupy 4 bytes.

public static String stripNonDigitsV2( CharSequence input ) {
    if (input == null)
        return null;
    if ( input.length() == 0 )
        return "";

    char[] result = new char[input.length()];
    int cursor = 0;
    CharBuffer buffer = CharBuffer.wrap( input );
    int i=0;
    while ( i< buffer.length()  ) { //buffer.hasRemaining()
        char chr = buffer.get(i);
        if (chr=='u'){
            i=i+5;
            chr=buffer.get(i);
        }

        if ( chr > 39 && chr < 58 )
            result[cursor++] = chr;
        i=i+1;
    }

    return new String( result, 0, cursor );
}

SQL Server, division returns zero

Simply mutiply the bottom of the division by 1.0 (or as many decimal places as you want)

PRINT @set1 
PRINT @set2 
SET @weight= @set1 / @set2 *1.00000; 
PRINT @weight

What is the difference between Cloud, Grid and Cluster?

Cloud is a marketing term, with the bare minimum feature relating to fast automated provisioning of new servers. HA, utility billing, etc are all features people can lump on top to define it to their own liking.

Grid [Computing] is an extension of clusters where multiple loosely coupled systems are used to solve a single problem. They tend to be multi-tenant, sharing some likeness to Clouds, but tend to rely heavily upon custom frameworks that manage the interop between grid nodes.

Cluster hosting is a specialization of clusters where a load balancer is used to direct incoming traffic to one of many worker nodes. It predates grid computing and doesn't rely on a homogenous abstraction of the underlying nodes as much as Grid computing. A web farm tends to have very specialized machines dedicated to each component type and is far more optimized for that specific task.

For pure hosting, Grid computing is the wrong tool. If you have no idea what your traffic shape is, then a Cloud would be useful. For predictable usage that changes at a reasonable pace, then a traditional cluster is fine and the most efficient.

JavaScript - document.getElementByID with onClick

In JavaScript functions are objects.

document.getElementById('foo').onclick = function(){
    prompt('Hello world');
}

Entity Framework - Include Multiple Levels of Properties

I made a little helper for Entity Framework 6 (.Net Core style), to include sub-entities in a nice way.

It is on NuGet now : Install-Package ThenInclude.EF6

using System.Data.Entity;

var thenInclude = context.One.Include(x => x.Twoes)
    .ThenInclude(x=> x.Threes)
    .ThenInclude(x=> x.Fours)
    .ThenInclude(x=> x.Fives)
    .ThenInclude(x => x.Sixes)
    .Include(x=> x.Other)
    .ToList();

The package is available on GitHub.

Mercurial undo last commit

Since you can't rollback you should merge that commit into the new head you got when you pulled. If you don't want any of the work you did in it you can easily do that using this tip.

So if you've pulled and updated to their head you can do this:

hg --config ui.merge=internal:local merge

keeps all the changes in the currently checked out revision, and none of the changes in the not-checked-out revision (the one you wrote that you no longer want).

This is a great way to do it because it keeps your history accurate and complete. If 2 years from now someone finds a bug in what you pulled down you can look in your (unused but saved) implementation of the same thing and go, "oh, I did it right". :)

Simplest PHP example for retrieving user_timeline with Twitter API version 1.1

If you have the OAuth PHP library installed, you don't have to worry about forming the request yourself.

$oauth = new OAuth($consumer_key, $consumer_secret, OAUTH_SIG_METHOD_HMACSHA1, OAUTH_AUTH_TYPE_URI);
$oauth->setToken($access_token, $access_secret);

$oauth->fetch("https://api.twitter.com/1.1/statuses/user_timeline.json");
$twitter_data = json_decode($oauth->getLastResponse());

print_r($twitter_data);

For more information, check out The docs or their example. You can use pecl install oauth to get the library.

Write a number with two decimal places SQL Server

Generally you can define the precision of a number in SQL by defining it with parameters. For most cases this will be NUMERIC(10,2) or Decimal(10,2) - will define a column as a Number with 10 total digits with a precision of 2 (decimal places).

Edited for clarity

Listing files in a directory matching a pattern in Java

The following code will create a list of files based on the accept method of the FileNameFilter.

List<File> list = Arrays.asList(dir.listFiles(new FilenameFilter(){
        @Override
        public boolean accept(File dir, String name) {
            return name.endsWith(".exe"); // or something else
        }}));

How can one see the structure of a table in SQLite?

Invoke the sqlite3 utility on the database file, and use its special dot commands:

  • .tables will list tables
  • .schema [tablename] will show the CREATE statement(s) for a table or tables

There are many other useful builtin dot commands -- see the documentation at http://www.sqlite.org/sqlite.html, section Special commands to sqlite3.

Example:

sqlite> entropy:~/Library/Mail>sqlite3 Envelope\ Index
SQLite version 3.6.12
Enter ".help" for instructions
Enter SQL statements terminated with a ";"
sqlite> .tables
addresses              ews_folders            subjects
alarms                 feeds                  threads
associations           mailboxes              todo_notes
attachments            messages               todos
calendars              properties             todos_deleted_log
events                 recipients             todos_server_snapshot
sqlite> .schema alarms
CREATE TABLE alarms (ROWID INTEGER PRIMARY KEY AUTOINCREMENT, alarm_id,
                     todo INTEGER, flags INTEGER, offset_days INTEGER,
                     reminder_date INTEGER, time INTEGER, argument,
                     unrecognized_data BLOB);
CREATE INDEX alarm_id_index ON alarms(alarm_id);
CREATE INDEX alarm_todo_index ON alarms(todo);

Note also that SQLite saves the schema and all information about tables in the database itself, in a magic table named sqlite_master, and it's also possible to execute normal SQL queries against that table. For example, the documentation link above shows how to derive the behavior of the .schema and .tables commands, using normal SQL commands (see section: Querying the database schema).

How to find out when an Oracle table was updated the last time

How long does the batch process take to write the file? It may be easiest to let it go ahead and then compare the file against a copy of the file from the previous run to see if they are identical.

Call Activity method from adapter

In Kotlin there is now a cleaner way by using lambda functions, no need for interfaces:

class MyAdapter(val adapterOnClick: (Any) -> Unit) {
    fun setItem(item: Any) {
        myButton.setOnClickListener { adapterOnClick(item) }
    }
}

class MyActivity {
    override fun onCreate(savedInstanceState: Bundle?) {
        var myAdapter = MyAdapter { item -> doOnClick(item) }
    }


    fun doOnClick(item: Any) {

    }
}

Portable way to check if directory exists [Windows/Linux, C]

You can use the GTK glib to abstract from OS stuff.

glib provides a g_dir_open() function which should do the trick.

PHP namespaces and "use"

The use operator is for giving aliases to names of classes, interfaces or other namespaces. Most use statements refer to a namespace or class that you'd like to shorten:

use My\Full\Namespace;

is equivalent to:

use My\Full\Namespace as Namespace;
// Namespace\Foo is now shorthand for My\Full\Namespace\Foo

If the use operator is used with a class or interface name, it has the following uses:

// after this, "new DifferentName();" would instantiate a My\Full\Classname
use My\Full\Classname as DifferentName;

// global class - making "new ArrayObject()" and "new \ArrayObject()" equivalent
use ArrayObject;

The use operator is not to be confused with autoloading. A class is autoloaded (negating the need for include) by registering an autoloader (e.g. with spl_autoload_register). You might want to read PSR-4 to see a suitable autoloader implementation.

Javascript Get Values from Multiple Select Option Box

The for loop is getting one extra run. Change

for (x=0;x<=InvForm.SelBranch.length;x++)

to

for (x=0; x < InvForm.SelBranch.length; x++)

How can I make a TextBox be a "password box" and display stars when using MVVM?

As Tasnim Fabiha mentioned, it is possible to change font for TextBox in order to show only dots/asterisks. But I wasn't able to find his font...so I give you my working example:

<TextBox Text="{Binding Password}" 
     FontFamily="pack://application:,,,/Resources/#password" />

Just copy-paste won't work. Firstly you have to download mentioned font "password.ttf" link: https://github.com/davidagraf/passwd/blob/master/public/ttf/password.ttf Then copy that to your project Resources folder (Project->Properties->Resources->Add resource->Add existing file). Then set it's Build Action to: Resource.

After this you will see just dots, but you can still copy text from that, so it is needed to disable CTRL+C shortcut like this:

<TextBox Text="{Binding Password}" 
     FontFamily="pack://application:,,,/Resources/#password" > 
    <TextBox.InputBindings>
        <!--Disable CTRL+C -->
        <KeyBinding Command="ApplicationCommands.NotACommand"
            Key="C"
            Modifiers="Control" />
    </TextBox.InputBindings>
</TextBox>

How can I add a vertical scrollbar to my div automatically?

I'm not quite sure what you're attempting to use the div for, but this is an example with some random text.

Mr_Green gave the correct instructions when he said to add overflow-y: auto as that restricts it to vertical scrolling. This is a JSFiddle example:

JSFiddle

Android on-screen keyboard auto popping up

Add this in your AndroidManifest.xml :

android:windowSoftInputMode="stateHidden|adjustResize"

It works perfectly. :)

Update UI from Thread in Android

You should do this with the help of AsyncTask (an intelligent backround thread) and ProgressDialog

AsyncTask enables proper and easy use of the UI thread. This class allows to perform background operations and publish results on the UI thread without having to manipulate threads and/or handlers.

An asynchronous task is defined by a computation that runs on a background thread and whose result is published on the UI thread. An asynchronous task is defined by 3 generic types, called Params, Progress and Result, and 4 steps, called begin, doInBackground, processProgress and end.

The 4 steps

When an asynchronous task is executed, the task goes through 4 steps:

onPreExecute(), invoked on the UI thread immediately after the task is executed. This step is normally used to setup the task, for instance by showing a progress bar in the user interface.

doInBackground(Params...), invoked on the background thread immediately after onPreExecute() finishes executing. This step is used to perform background computation that can take a long time. The parameters of the asynchronous task are passed to this step. The result of the computation must be returned by this step and will be passed back to the last step. This step can also use publishProgress(Progress...) to publish one or more units of progress. These values are published on the UI thread, in the onProgressUpdate(Progress...) step.

onProgressUpdate(Progress...), invoked on the UI thread after a call to publishProgress(Progress...). The timing of the execution is undefined. This method is used to display any form of progress in the user interface while the background computation is still executing. For instance, it can be used to animate a progress bar or show logs in a text field.

onPostExecute(Result), invoked on the UI thread after the background computation finishes. The result of the background computation is passed to this step as a parameter. Threading rules

There are a few threading rules that must be followed for this class to work properly:

The task instance must be created on the UI thread. execute(Params...) must be invoked on the UI thread. Do not call onPreExecute(), onPostExecute(Result), doInBackground(Params...), onProgressUpdate(Progress...) manually. The task can be executed only once (an exception will be thrown if a second execution is attempted.)

Example code
What the adapter does in this example is not important, more important to understand that you need to use AsyncTask to display a dialog for the progress.

private class PrepareAdapter1 extends AsyncTask<Void,Void,ContactsListCursorAdapter > {
    ProgressDialog dialog;
    @Override
    protected void onPreExecute() {
        dialog = new ProgressDialog(viewContacts.this);
        dialog.setMessage(getString(R.string.please_wait_while_loading));
        dialog.setIndeterminate(true);
        dialog.setCancelable(false);
        dialog.show();
    }
    /* (non-Javadoc)
     * @see android.os.AsyncTask#doInBackground(Params[])
     */
    @Override
    protected ContactsListCursorAdapter doInBackground(Void... params) {
        cur1 = objItem.getContacts();
        startManagingCursor(cur1);

        adapter1 = new ContactsListCursorAdapter (viewContacts.this,
                R.layout.contact_for_listitem, cur1, new String[] {}, new int[] {});

        return adapter1;
    }

    protected void onPostExecute(ContactsListCursorAdapter result) {
        list.setAdapter(result);
        dialog.dismiss();
    }
}

How should I deal with "package 'xxx' is not available (for R version x.y.z)" warning?

I had the same problem (on Linux) which could be solved changing the proxy settings. If you are behind a proxy server check the configuration using Sys.getenv("http_proxy") within R. In my ~/.Renviron I had the following lines (from https://support.rstudio.com/hc/en-us/articles/200488488-Configuring-R-to-Use-an-HTTP-or-HTTPS-Proxy) causing the problem:

http_proxy=https://proxy.dom.com:port
http_proxy_user=user:passwd

Changing it to

http_proxy="http://user:[email protected]:port"

solved the problem. You can do the same for https.

It was not the first thought when I read "package xxx is not available for r version-x-y-z" ...

HTH

Return sql rows where field contains ONLY non-alphanumeric characters

If you have short strings you should be able to create a few LIKE patterns ('[^a-zA-Z0-9]', '[^a-zA-Z0-9][^a-zA-Z0-9]', ...) to match strings of different length. Otherwise you should use CLR user defined function and a proper regular expression - Regular Expressions Make Pattern Matching And Data Extraction Easier.

How to write a test which expects an Error to be thrown in Jasmine?

For anyone who still might be facing this issue, for me the posted solution didn't work and it kept on throwing this error: Error: Expected function to throw an exception. I later realised that the function which I was expecting to throw an error was an async function and was expecting promise to be rejected and then throw error and that's what I was doing in my code:

throw new Error('REQUEST ID NOT FOUND');

and thats what I did in my test and it worked:

it('Test should throw error if request not found', willResolve(() => {
         const promise = service.getRequestStatus('request-id');
                return expectToReject(promise).then((err) => {
                    expect(err.message).toEqual('REQUEST NOT FOUND');
                });
            }));

How to add a new line of text to an existing file in Java?

You can use the FileWriter(String fileName, boolean append) constructor if you want to append data to file.

Change your code to this:

output = new BufferedWriter(new FileWriter(my_file_name, true));

From FileWriter javadoc:

Constructs a FileWriter object given a file name. If the second argument is true, then bytes will be written to the end of the file rather than the beginning.

Add space between cells (td) using css

Mine is:

border-spacing: 10px;
border-collapse: separate;

Intercept a form submit in JavaScript and prevent normal submission

<form onSubmit="return captureForm()"> that should do. Make sure that your captureForm() method returns false.

Writing data to a local text file with javascript

Our HTML:

<div id="addnew">
    <input type="text" id="id">
    <input type="text" id="content">
    <input type="button" value="Add" id="submit">
</div>

<div id="check">
    <input type="text" id="input">
    <input type="button" value="Search" id="search">
</div>

JS (writing to the txt file):

function writeToFile(d1, d2){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.OpenTextFile("data.txt", 8, false, 0);
    fh.WriteLine(d1 + ',' + d2);
    fh.Close();
}
var submit = document.getElementById("submit");
submit.onclick = function () {
    var id      = document.getElementById("id").value;
    var content = document.getElementById("content").value;
    writeToFile(id, content);
}

checking a particular row:

function readFile(){
    var fso = new ActiveXObject("Scripting.FileSystemObject");
    var fh = fso.OpenTextFile("data.txt", 1, false, 0);
    var lines = "";
    while (!fh.AtEndOfStream) {
        lines += fh.ReadLine() + "\r";
    }
    fh.Close();
    return lines;
}
var search = document.getElementById("search");
search.onclick = function () {
    var input   = document.getElementById("input").value;
    if (input != "") {
        var text    = readFile();
        var lines   = text.split("\r");
        lines.pop();
        var result;
        for (var i = 0; i < lines.length; i++) {
            if (lines[i].match(new RegExp(input))) {
                result = "Found: " + lines[i].split(",")[1];
            }
        }
        if (result) { alert(result); }
        else { alert(input + " not found!"); }
    }
}

Put these inside a .hta file and run it. Tested on W7, IE11. It's working. Also if you want me to explain what's going on, say so.

How do I add a project as a dependency of another project?

Assuming the MyEjbProject is not another Maven Project you own or want to build with maven, you could use system dependencies to link to the existing jar file of the project like so

<project>
   ...
   <dependencies>
      <dependency>
         <groupId>yourgroup</groupId>
         <artifactId>myejbproject</artifactId>
         <version>2.0</version>
         <scope>system</scope>
         <systemPath>path/to/myejbproject.jar</systemPath>
      </dependency>
   </dependencies>
   ...
</project>

That said it is usually the better (and preferred way) to install the package to the repository either by making it a maven project and building it or installing it the way you already seem to do.


If they are, however, dependent on each other, you can always create a separate parent project (has to be a "pom" project) declaring the two other projects as its "modules". (The child projects would not have to declare the third project as their parent). As a consequence you'd get a new directory for the new parent project, where you'd also quite probably put the two independent projects like this:

parent
|- pom.xml
|- MyEJBProject
|   `- pom.xml
`- MyWarProject
    `- pom.xml

The parent project would get a "modules" section to name all the child modules. The aggregator would then use the dependencies in the child modules to actually find out the order in which the projects are to be built)

<project>
   ...
   <artifactId>myparentproject</artifactId>
   <groupId>...</groupId>
   <version>...</version>

   <packaging>pom</packaging>
   ...
   <modules>
     <module>MyEJBModule</module>
     <module>MyWarModule</module>
   </modules>
   ...
</project>

That way the projects can relate to each other but (once they are installed in the local repository) still be used independently as artifacts in other projects


Finally, if your projects are not in related directories, you might try to give them as relative modules:

filesystem
 |- mywarproject
 |   `pom.xml
 |- myejbproject
 |   `pom.xml
 `- parent
     `pom.xml

now you could just do this (worked in maven 2, just tried it):

<!--parent-->
<project>
  <modules>
    <module>../mywarproject</module>
    <module>../myejbproject</module>
  </modules>
</project>

How to upgrade Angular CLI project?

JJB's answer got me on the right track, but the upgrade didn't go very smoothly. My process is detailed below. Hopefully the process becomes easier in the future and JJB's answer can be used or something even more straightforward.

Solution Details

I have followed the steps captured in JJB's answer to update the angular-cli precisely. However, after running npm install angular-cli was broken. Even trying to do ng version would produce an error. So I couldn't do the ng init command. See error below:

$ ng init
core_1.Version is not a constructor
TypeError: core_1.Version is not a constructor
    at Object.<anonymous> (C:\_git\my-project\code\src\main\frontend\node_modules\@angular\compiler-cli\src\version.js:18:19)
    at Module._compile (module.js:556:32)
    at Object.Module._extensions..js (module.js:565:10)
    at Module.load (module.js:473:32)
    ...

To be able to use any angular-cli commands, I had to update my package.json file by hand and bump the @angular dependencies to 2.4.1, then do another npm install.

After this I was able to do ng init. I updated my configuration files, but none of my app/* files. When this was done, I was still getting errors. The first one is detailed below, the second was the same type of error but in a different file.

ERROR in Error encountered resolving symbol values statically. Function calls are not supported. Consider replacing the function or lambda with a reference to an exported function (position 62:9 in the original .ts file), resolving symbol AppModule in C:/_git/my-project/code/src/main/frontend/src/app/app.module.ts

This error is tied to the following factory provider in my AppModule

{ provide: Http, useFactory: 
    (backend: XHRBackend, options: RequestOptions, router: Router, navigationService: NavigationService, errorService: ErrorService) => {
    return new HttpRerouteProvider(backend, options, router, navigationService, errorService);  
  }, deps: [XHRBackend, RequestOptions, Router, NavigationService, ErrorService]
}

To address this error, I had use an exported function and made the following change to the provider.

    { 
      provide: Http, 
      useFactory: httpFactory, 
      deps: [XHRBackend, RequestOptions, Router, NavigationService, ErrorService]
    }

... // elsewhere in AppModule

export function httpFactory(backend: XHRBackend, 
                            options: RequestOptions, 
                            router: Router, 
                            navigationService: NavigationService, 
                            errorService: ErrorService) {
  return new HttpRerouteProvider(backend, options, router, navigationService, errorService);
}

Summary

To summarize what I understand to be the most important details, the following changes were required:

  1. Update angular-cli version using the steps detailed in JJB's answer (and on their github page).

  2. Updating @angular version by hand, 2.0.0 did not seem to be supported by angular-cli version 1.0.0-beta.24

  3. With the assistance of angular-cli and the ng init command, I updated my configuration files. I think the critical changes were to angular-cli.json and package.json. See configuration file changes at the bottom.

  4. Make code changes to export functions before I reference them, as captured in the solution details.

Key Configuration Changes

angular-cli.json changes

{
  "project": {
    "version": "1.0.0-beta.16",
    "name": "frontend"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": "assets",
...

changed to...

{
  "project": {
    "version": "1.0.0-beta.24",
    "name": "frontend"
  },
  "apps": [
    {
      "root": "src",
      "outDir": "dist",
      "assets": [
        "assets",
        "favicon.ico"
      ],
...

My package.json looks like this after a manual merge that considers the versions used by ng-init. Note my angular version is not 2.4.1, but the change I was after was component inheritance which was introduced in 2.3, so I was fine with these versions. The original package.json is in the question.

{
  "name": "frontend",
  "version": "0.0.0",
  "license": "MIT",
  "angular-cli": {},
  "scripts": {
    "ng": "ng",
    "start": "ng serve",
    "lint": "tslint \"src/**/*.ts\"",
    "test": "ng test",
    "pree2e": "webdriver-manager update --standalone false --gecko false",
    "e2e": "protractor",
    "build": "ng build",
    "buildProd": "ng build --env=prod"
  },
  "private": true,
  "dependencies": {
    "@angular/common": "^2.3.1",
    "@angular/compiler": "^2.3.1",
    "@angular/core": "^2.3.1",
    "@angular/forms": "^2.3.1",
    "@angular/http": "^2.3.1",
    "@angular/platform-browser": "^2.3.1",
    "@angular/platform-browser-dynamic": "^2.3.1",
    "@angular/router": "^3.3.1",
    "@angular/material": "^2.0.0-beta.1",
    "@types/google-libphonenumber": "^7.4.8",
    "angular2-datatable": "^0.4.2",
    "apollo-client": "^0.4.22",
    "core-js": "^2.4.1",
    "rxjs": "^5.0.1",
    "ts-helpers": "^1.1.1",
    "zone.js": "^0.7.2",
    "google-libphonenumber": "^2.0.4",
    "graphql-tag": "^0.1.15",
    "hammerjs": "^2.0.8",
    "ng2-bootstrap": "^1.1.16"
  },
  "devDependencies": {
    "@types/hammerjs": "^2.0.33",
    "@angular/compiler-cli": "^2.3.1",
    "@types/jasmine": "2.5.38",
    "@types/lodash": "^4.14.39",
    "@types/node": "^6.0.42",
    "angular-cli": "1.0.0-beta.24",
    "codelyzer": "~2.0.0-beta.1",
    "jasmine-core": "2.5.2",
    "jasmine-spec-reporter": "2.5.0",
    "karma": "1.2.0",
    "karma-chrome-launcher": "^2.0.0",
    "karma-cli": "^1.0.1",
    "karma-jasmine": "^1.0.2",
    "karma-remap-istanbul": "^0.2.1",
    "protractor": "~4.0.13",
    "ts-node": "1.2.1",
    "tslint": "^4.0.2",
    "typescript": "~2.0.3",
    "typings": "1.4.0"
  }
}

How to uncheck a checkbox in pure JavaScript?

<html>
    <body>
        <input id="check1" type="checkbox" checked="" name="copyNewAddrToBilling">
    </body>
    <script language="javascript">
        document.getElementById("check1").checked = true;
        document.getElementById("check1").checked = false;
    </script>
</html>

I have added the language attribute to the script element, but it is unnecessary because all browsers use this as a default, but it leaves no doubt what this example is showing.

If you want to use javascript to access elements, it has a very limited set of GetElement* functions. So you are going to need to get into the habit of giving every element a UNIQUE id attribute.

How to copy a file from remote server to local machine?

When you use scp you have to tell the host name and ip address from where you want to copy the file. For instance, if you are at the remote host and you want to transfer the file to your pc you may use something like this:

scp -P[portnumber] myfile_at_remote_host [user]@[your_ip_address]:/your/path/

Example:

scp -P22 table [email protected]:/home/me/Desktop/

On the other hand, if you are at your are actually on your machine you may use something like this:

scp -P[portnumber] [remote_login]@[remote's_ip_address]:/remote/path/myfile_at_remote_host /your/path/

Example:

scp -P22 [fake_user]@222.222.222.222:/remote/path/table /home/me/Desktop/

How to store printStackTrace into a string

Guava makes this easy with Throwables.getStackTraceAsString(Throwable):

Exception e = ...
String stackTrace = Throwables.getStackTraceAsString(e);

Internally, this does what @Zach L suggests.

Wavy shape with css

My pure CSS implementation based on above with 100% width. Hope it helps!

_x000D_
_x000D_
#wave-container {_x000D_
  width: 100%;_x000D_
  height: 100px;_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
#wave {_x000D_
  display: block;_x000D_
  position: relative;_x000D_
  height: 40px;_x000D_
  background: black;_x000D_
}_x000D_
_x000D_
#wave:before {_x000D_
  content: "";_x000D_
  display: block;_x000D_
  position: absolute;_x000D_
  border-radius: 100%;_x000D_
  width: 100%;_x000D_
  height: 300px;_x000D_
  background-color: white;_x000D_
  right: -25%;_x000D_
  top: 20px_x000D_
}_x000D_
_x000D_
#wave:after {_x000D_
  content: "";_x000D_
  display: block;_x000D_
  position: absolute;_x000D_
  border-radius: 100%;_x000D_
  width: 100%;_x000D_
  height: 300px;_x000D_
  background-color: black;_x000D_
  left: -25%;_x000D_
  top: -240px;_x000D_
}
_x000D_
<div id="wave-container">_x000D_
  <div id="wave">_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

What's the difference between ".equals" and "=="?

public static void main(String[] args){
        String s1 = new String("hello");
        String s2 = new String("hello");

        System.out.println(s1.equals(s2));
        ////
        System.out.println(s1 == s2);

    System.out.println("-----------------------------");

        String s3 = "hello";
        String s4 = "hello";

        System.out.println(s3.equals(s4));
        ////
        System.out.println(s3 == s4);
    }

Here in this code u can campare the both '==' and '.equals'

here .equals is used to compare the reference objects and '==' is used to compare state of objects..

How to scroll to specific item using jQuery?

You can use the the jQuery scrollTo plugin plugin:

$('div').scrollTo('#row_8');

Creating a list of pairs in java

Sounds like you need to create your own pair class (see discussion here). Then make a List of that pair class you created

MySQL WHERE IN ()

you must have record in table or array record in database.

example:

SELECT * FROM tabel_record
WHERE table_record.fieldName IN (SELECT fieldName FROM table_reference);

How is malloc() implemented internally?

It's also important to realize that simply moving the program break pointer around with brk and sbrk doesn't actually allocate the memory, it just sets up the address space. On Linux, for example, the memory will be "backed" by actual physical pages when that address range is accessed, which will result in a page fault, and will eventually lead to the kernel calling into the page allocator to get a backing page.

Scp command syntax for copying a folder from local machine to a remote server

scp -r C:/site user@server_ip:path

path is the place, where site will be copied into the remote server


EDIT: As I said in my comment, try pscp, as you want to use scp using PuTTY.

The other option is WinSCP

How to set environment variables in Python?

You should assign string value to environment variable.

os.environ["DEBUSSY"] = "1"

If you want to read or print the environment variable just use

print os.environ["DEBUSSY"]

This changes will be effective only for the current process where it was assigned, it will no change the value permanently. The child processes will automatically inherit the environment of the parent process.

enter image description here

What is the difference between String.slice and String.substring?

substr: It's providing us to fetch part of the string based on specified index. syntax of substr- string.substr(start,end) start - start index tells where the fetching start. end - end index tells upto where string fetches. It's optional.

slice: It's providing to fetch part of the string based on the specified index. It's allows us to specify positive and index. syntax of slice - string.slice(start,end) start - start index tells where the fetching start.It's end - end index tells upto where string fetches. It's optional. In 'splice' both start and end index helps to take positive and negative index.

sample code for 'slice' in string

var str="Javascript";
console.log(str.slice(-5,-1));

output: crip

sample code for 'substring' in string

var str="Javascript";
console.log(str.substring(1,5));

output: avas

[*Note: negative indexing starts at the end of the string.]

How to use sys.exit() in Python

I think you can use

sys.exit(0)

You may check it here in the python 2.7 doc:

The optional argument arg can be an integer giving the exit status (defaulting to zero), or another type of object. If it is an integer, zero is considered “successful termination” and any nonzero value is considered “abnormal termination” by shells and the like.

When must we use NVARCHAR/NCHAR instead of VARCHAR/CHAR in SQL Server?

TL;DR;
Unicode - (nchar, nvarchar, and ntext)
Non-unicode - (char, varchar, and text).

From MSDN

Collations in SQL Server provide sorting rules, case, and accent sensitivity properties for your data. Collations that are used with character data types such as char and varchar dictate the code page and corresponding characters that can be represented for that data type.

Assuming you are using default SQL collation SQL_Latin1_General_CP1_CI_AS then following script should print out all the symbols that you can fit in VARCHAR since it uses one byte to store one character (256 total) if you don't see it on the list printed - you need NVARCHAR.

declare @i int = 0;
while (@i < 256)
begin
print cast(@i as varchar(3)) + '  '+  char(@i)  collate SQL_Latin1_General_CP1_CI_AS 
print cast(@i as varchar(3)) + '  '+ char(@i)  collate Japanese_90_CI_AS  
set @i = @i+1;
end

If you change collation to lets say japanese you will notice that all the weird European letters turned into normal and some symbols into ? marks.

Unicode is a standard for mapping code points to characters. Because it is designed to cover all the characters of all the languages of the world, there is no need for different code pages to handle different sets of characters. If you store character data that reflects multiple languages, always use Unicode data types (nchar, nvarchar, and ntext) instead of the non-Unicode data types (char, varchar, and text).

Otherwise your sorting will go weird.

How to do the equivalent of pass by reference for primitives in Java

You have several choices. The one that makes the most sense really depends on what you're trying to do.

Choice 1: make toyNumber a public member variable in a class

class MyToy {
  public int toyNumber;
}

then pass a reference to a MyToy to your method.

void play(MyToy toy){  
    System.out.println("Toy number in play " + toy.toyNumber);   
    toy.toyNumber++;  
    System.out.println("Toy number in play after increement " + toy.toyNumber);   
}

Choice 2: return the value instead of pass by reference

int play(int toyNumber){  
    System.out.println("Toy number in play " + toyNumber);   
    toyNumber++;  
    System.out.println("Toy number in play after increement " + toyNumber);   
    return toyNumber
}

This choice would require a small change to the callsite in main so that it reads, toyNumber = temp.play(toyNumber);.

Choice 3: make it a class or static variable

If the two functions are methods on the same class or class instance, you could convert toyNumber into a class member variable.

Choice 4: Create a single element array of type int and pass that

This is considered a hack, but is sometimes employed to return values from inline class invocations.

void play(int [] toyNumber){  
    System.out.println("Toy number in play " + toyNumber[0]);   
    toyNumber[0]++;  
    System.out.println("Toy number in play after increement " + toyNumber[0]);   
}

virtualbox Raw-mode is unavailable courtesy of Hyper-V windows 10

You need to disable the windows Hyper-V feature and bcd. Then Virtual Box will run in latest Windows 10 versions (Jan-Mar 2018). Windows 10 Hyper-V is having clash on VirtualBox features.

I have resolved this by following steps-

  1. bcdedit /set hypervisorlaunchtype off
  2. Disable-WindowsOptionalFeature -Online -FeatureName Microsoft-Hyper-V-All
  3. Restart your windows

Detailed discussion on this are available at - https://forums.virtualbox.org/viewtopic.php?f=6&t=87237

Alternatively you can install linux (Ubuntu) in Windows 10 from the latest bash command - https://www.windowscentral.com/how-install-bash-shell-command-line-windows-10

How do I center an SVG in a div?

For me, the fix was to add margin: 0 auto; onto the element containing the <svg>.

Like this:

<div style="margin: 0 auto">
   <svg ...</svg>
</div>