Programs & Examples On #Ashx

ASP.NET Web Handler file extension

.aspx vs .ashx MAIN difference

Page is a special case handler.

Generic Web handler (*.ashx, extension based processor) is the default HTTP handler for all Web handlers that do not have a UI and that include the @WebHandler directive.

ASP.NET page handler (*.aspx) is the default HTTP handler for all ASP.NET pages.

Among the built-in HTTP handlers there are also Web service handler (*.asmx) and Trace handler (trace.axd)

MSDN says:

An ASP.NET HTTP handler is the process (frequently referred to as the "endpoint") that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page through the page handler.

The image below illustrates this: request pipe line

As to your second question:

Does ashx handle more connections than aspx?

Don't think so (but for sure, at least not less than).

What is the most efficient way to concatenate N arrays?

The fastest by a factor of 10 is to iterate over the arrays as if they are one, without actually joining them (if you can help it).

I was surprised that concat is slightly faster than push, unless the test is somehow unfair.

_x000D_
_x000D_
const arr1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'];
const arr2 = ['j', 'k', 'l', 'i', 'm', 'n', 'o', 'p', 'q', 'r', 's'];
const arr3 = ['t', 'u', 'v', 'w'];
const arr4 = ['x', 'y', 'z'];

let start;

// Not joining but iterating over all arrays - fastest
// at about 0.06ms
start = performance.now()

const joined = [arr1, arr2, arr3, arr4];

for (let j = 0; j < 1000; j++) {
  let i = 0;
  while (joined.length) {
    // console.log(joined[0][i]);
    if (i < joined[0].length - 1) i++;
    else {
      joined.shift()
      i = 0;
    }
  }
}

console.log(performance.now() - start);

// Concating (0.51ms).
start = performance.now()

for (let j = 0; j < 1000; j++) {
  const a = [].concat(arr1, arr2, arr3, arr4);
}

console.log(performance.now() - start);

// Pushing on to an array (mutating). Slowest (0.77ms)
start = performance.now()

const joined2 = [arr1, arr2, arr3, arr4];

for (let j = 0; j < 1000; j++) {
  const arr = [];
  for (let i = 0; i < joined2.length; i++) {
    Array.prototype.push.apply(arr, joined2[i])
  }
}

console.log(performance.now() - start);
_x000D_
_x000D_
_x000D_

You can make the iteration without joining cleaner if you abstract it and it's still twice as fast:

_x000D_
_x000D_
const arr1 = ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i'];
const arr2 = ['j', 'k', 'l', 'i', 'm', 'n', 'o', 'p', 'q', 'r', 's'];
const arr3 = ['t', 'u', 'v', 'w'];
const arr4 = ['x', 'y', 'z'];

function iterateArrays(arrays, onEach) {
  let i = 0;
  while (joined.length) {
    onEach(joined[0][i]);
    if (i < joined[0].length - 1) i++;
    else {
      joined.shift();
      i = 0;
    }
  }
}

// About 0.23ms.
let start = performance.now()

const joined = [arr1, arr2, arr3, arr4];

for (let j = 0; j < 1000; j++) {
  iterateArrays(joined, item => {
    //console.log(item);
  });
}

console.log(performance.now() - start);
_x000D_
_x000D_
_x000D_

How do malloc() and free() work?

Well it depends on the memory allocator implementation and the OS.

Under windows for example a process can ask for a page or more of RAM. The OS then assigns those pages to the process. This is not, however, memory allocated to your application. The CRT memory allocator will mark the memory as a contiguous "available" block. The CRT memory allocator will then run through the list of free blocks and find the smallest possible block that it can use. It will then take as much of that block as it needs and add it to an "allocated" list. Attached to the head of the actual memory allocation will be a header. This header will contain various bit of information (it could, for example, contain the next and previous allocated blocks to form a linked list. It will most probably contain the size of the allocation).

Free will then remove the header and add it back to the free memory list. If it forms a larger block with the surrounding free blocks these will be added together to give a larger block. If a whole page is now free the allocator will, most likely, return the page to the OS.

It is not a simple problem. The OS allocator portion is completely out of your control. I recommend you read through something like Doug Lea's Malloc (DLMalloc) to get an understanding of how a fairly fast allocator will work.

Edit: Your crash will be caused by the fact that by writing larger than the allocation you have overwritten the next memory header. This way when it frees it gets very confused as to what exactly it is free'ing and how to merge into the following block. This may not always cause a crash straight away on the free. It may cause a crash later on. In general avoid memory overwrites!

Windows command prompt log to a file

You can redirect the output of a cmd prompt to a file using > or >> to append to a file.

i.e.

echo Hello World >C:\output.txt
echo Hello again! >>C:\output.txt

or

mybatchfile.bat >C:\output.txt

Note that using > will automatically overwrite the file if it already exists.

You also have the option of redirecting stdin, stdout and stderr.

See here for a complete list of options.

Select the first 10 rows - Laravel Eloquent

First you can use a Paginator. This is as simple as:

$allUsers = User::paginate(15);

$someUsers = User::where('votes', '>', 100)->paginate(15);

The variables will contain an instance of Paginator class. all of your data will be stored under data key.

Or you can do something like:

Old versions Laravel.

Model::all()->take(10)->get();

Newer version Laravel.

Model::all()->take(10);

For more reading consider these links:

Using JAXB to unmarshal/marshal a List<String>

@GET
@Path("/test2")
public Response test2(){
   List<String> list=new Vector<String>();
   list.add("a");
   list.add("b");

   final GenericEntity<List<String>> entity = new GenericEntity<List<String>>(list) { };
   return Response.ok().entity(entity).build();
}

How to get an ASP.NET MVC Ajax response to redirect to new page instead of inserting view into UpdateTargetId?

Add a helper class:

public static class Redirector {
        public static void RedirectTo(this Controller ct, string action) {
            UrlHelper urlHelper = new UrlHelper(ct.ControllerContext.RequestContext);

            ct.Response.Headers.Add("AjaxRedirectURL", urlHelper.Action(action));
        }

        public static void RedirectTo(this Controller ct, string action, string controller) {
            UrlHelper urlHelper = new UrlHelper(ct.ControllerContext.RequestContext);

            ct.Response.Headers.Add("AjaxRedirectURL", urlHelper.Action(action, controller));
        }

        public static void RedirectTo(this Controller ct, string action, string controller, object routeValues) {
            UrlHelper urlHelper = new UrlHelper(ct.ControllerContext.RequestContext);

            ct.Response.Headers.Add("AjaxRedirectURL", urlHelper.Action(action, controller, routeValues));
        }
    }

Then call in your action:

this.RedirectTo("Index", "Cement");

Add javascript code to any global javascript included file or layout file to intercept all ajax requests:

_x000D_
_x000D_
<script type="text/javascript">_x000D_
  $(function() {_x000D_
    $(document).ajaxComplete(function (event, xhr, settings) {_x000D_
            var urlHeader = xhr.getResponseHeader('AjaxRedirectURL');_x000D_
_x000D_
            if (urlHeader != null && urlHeader !== undefined) {_x000D_
                window.location = xhr.getResponseHeader('AjaxRedirectURL');_x000D_
            }_x000D_
        });_x000D_
  });_x000D_
</script>
_x000D_
_x000D_
_x000D_

Exit a Script On Error

Here is the way to do it:

#!/bin/sh

abort()
{
    echo >&2 '
***************
*** ABORTED ***
***************
'
    echo "An error occurred. Exiting..." >&2
    exit 1
}

trap 'abort' 0

set -e

# Add your script below....
# If an error occurs, the abort() function will be called.
#----------------------------------------------------------
# ===> Your script goes here
# Done!
trap : 0

echo >&2 '
************
*** DONE *** 
************
'

Adding a legend to PyPlot in Matplotlib in the simplest manner possible

    # Dependencies
    import numpy as np
    import matplotlib.pyplot as plt

    #Set Axes
    # Set x axis to numerical value for month
    x_axis_data = np.arange(1,13,1)
    x_axis_data

    # Average weather temp
    points = [39, 42, 51, 62, 72, 82, 86, 84, 77, 65, 55, 44]

    # Plot the line
    plt.plot(x_axis_data, points)
    plt.show()

    # Convert to Celsius C = (F-32) * 0.56
    points_C = [round((x-32) * 0.56,2) for x in points]
    points_C

    # Plot using Celsius
    plt.plot(x_axis_data, points_C)
    plt.show()

    # Plot both on the same chart
    plt.plot(x_axis_data, points)
    plt.plot(x_axis_data, points_C)

    #Line colors
    plt.plot(x_axis_data, points, "-b", label="F")
    plt.plot(x_axis_data, points_C, "-r", label="C")

    #locate legend
    plt.legend(loc="upper left")
    plt.show()

How to clear a data grid view

dataGridView1.Rows.Clear();
dataGridView1.Refresh();

Implement division with bit-wise operator

The below method is the implementation of binary divide considering both numbers are positive. If subtraction is a concern we can implement that as well using binary operators.

Code

-(int)binaryDivide:(int)numerator with:(int)denominator
{
    if (numerator == 0 || denominator == 1) {
        return numerator;
    }

    if (denominator == 0) {

        #ifdef DEBUG
            NSAssert(denominator == 0, @"denominator should be greater then 0");
        #endif
        return INFINITY;
    }

    // if (numerator <0) {
    //     numerator = abs(numerator);
    // }

    int maxBitDenom = [self getMaxBit:denominator];
    int maxBitNumerator = [self getMaxBit:numerator];
    int msbNumber = [self getMSB:maxBitDenom ofNumber:numerator];

    int qoutient = 0;

    int subResult = 0;

    int remainingBits = maxBitNumerator-maxBitDenom;

    if (msbNumber >= denominator) {
        qoutient |=1;
        subResult = msbNumber - denominator;
    }
    else {
        subResult = msbNumber;
    }

    while (remainingBits>0) {
        int msbBit = (numerator & (1 << (remainingBits-1)))>0 ? 1 : 0;
        subResult = (subResult << 1) |msbBit;
        if (subResult >= denominator) {
            subResult = subResult-denominator;
            qoutient = (qoutient << 1) | 1;
        }
        else {
            qoutient = qoutient << 1;
        }
        remainingBits--;
    }
    return qoutient;
}


-(int)getMaxBit:(int)inputNumber
{
    int maxBit =0;
    BOOL isMaxBitSet = NO;
    for (int i=0; i<sizeof(inputNumber)*8; i++) {
        if (inputNumber & (1 << i) ) {
            maxBit = i;
            isMaxBitSet=YES;
        }
    }
    if (isMaxBitSet) {
        maxBit += 1;
    }
    return maxBit;
}


-(int)getMSB:(int)bits ofNumber:(int)number
{
    int numbeMaxBit = [self getMaxBit:number];
    return number >> (numbeMaxBit -bits);
}

How to convert milliseconds to "hh:mm:ss" format?

I tried as shown in the first answer. It works, but minus brought me into confusion. My answer by Groovy:

import static java.util.concurrent.TimeUnit.*

...

private static String formatElapsedTime(long millis) {

    int hrs = MILLISECONDS.toHours(millis) % 24
    int min = MILLISECONDS.toMinutes(millis) % 60
    int sec = MILLISECONDS.toSeconds(millis) % 60
    int mls = millis % 1000

    sprintf( '%02d:%02d:%02d (%03d)', [hrs, min, sec, mls])
}

Cannot attach the file *.mdf as database

If you happen to apply migrations already this may fix it.

Go to your Web.config and update your connection string based on your migration files.

Data Source=(LocalDb)\MSSQLLocalDB;AttachDbFilename=|DataDirectory|\aspnet-GigHub-201802102244201.mdf;Initial Catalog=aspnet-GigHub-201802102244201;

The datestrings should match the first numbers on your Migrations.

Android, How can I Convert String to Date?

SimpleDateFormat dateFormat = new SimpleDateFormat("dd-MM-yyyy");
Date d = dateFormat.parse(datestring)

Disable activity slide-in animation when launching new activity?

I had a similar problem of getting a black screen appear on sliding transition from one activity to another using overridependingtransition. and I followed the way below and it worked

1) created a noanim.xml in anim folder

<?xml version="1.0" encoding="utf-8"?>
<translate 
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:duration="@android:integer/config_longAnimTime"
    android:fromYDelta="0%p"
    android:toYDelta="0%p" />

and used

overridePendingTransition(R.drawable.lefttorightanim, R.anim.noanim);

The first parameter as my original animation and second parameter which is the exit animation as my dummy animation

laravel 5.3 new Auth::routes()

This worked for me with Laravel 5.6.

In the file web.php, just replace:

Auth::routes();

By:

//Auth::routes();
// Authentication Routes...
Route::get('admin/login', 'Auth\LoginController@showLoginForm')->name('login');
Route::post('admin/login', 'Auth\LoginController@login');
Route::post('admin/logout', 'Auth\LoginController@logout')->name('logout');
// Password Reset Routes...
Route::get('password/reset', 'Auth\ForgotPasswordController@showLinkRequestForm')->name('password.request');
Route::post('password/email', 'Auth\ForgotPasswordController@sendResetLinkEmail')->name('password.email');
Route::get('password/reset/{token}', 'Auth\ResetPasswordController@showResetForm')->name('password.reset');
Route::post('password/reset', 'Auth\ResetPasswordController@reset');

And remove the Register link in the two files below:

welcome.blade.php
layouts/app.blade.php

C++ Array of pointers: delete or delete []?

For new you should use delete. For new[] use delete[]. Your second variant is correct.

How do I define a method in Razor?

Leaving alone any debates over when (if ever) it should be done, @functions is how you do it.

@functions {

    // Add code here.

}

How to show Snackbar when Activity starts?

Try this

Snackbar.make(findViewById(android.R.id.content), "Got the Result", Snackbar.LENGTH_LONG)
                        .setAction("Submit", mOnClickListener)
                        .setActionTextColor(Color.RED)
                        .show();

How to get just the responsive grid from Bootstrap 3?

Just choose Grid system and "responsive utilities" it gives you this: http://jsfiddle.net/7LVzs/

Unique random string generation

I simplified @Michael Kropats solution and made a LINQ-esque version.

string RandomString(int length, string alphabet = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789")
{       
    var outOfRange = byte.MaxValue + 1 - (byte.MaxValue + 1) % alphabet.Length;

    return string.Concat(
        Enumerable
            .Repeat(0, int.MaxValue)
            .Select(e => RandomByte())
            .Where(randomByte => randomByte < outOfRange)
            .Take(length)
            .Select(randomByte => alphabet[randomByte % alphabet.Length])
    );
}

byte RandomByte()
{
    using (var randomizationProvider = new RNGCryptoServiceProvider())
    {
        var randomBytes = new byte[1];
        randomizationProvider.GetBytes(randomBytes);
        return randomBytes.Single();
    }   
}

Loading local JSON file

Found this thread when trying (unsuccessfully) to load a local json file. This solution worked for me...

function load_json(src) {
  var head = document.getElementsByTagName('head')[0];

  //use class, as we can't reference by id
  var element = head.getElementsByClassName("json")[0];

  try {
    element.parentNode.removeChild(element);
  } catch (e) {
    //
  }

  var script = document.createElement('script');
  script.type = 'text/javascript';
  script.src = src;
  script.className = "json";
  script.async = false;
  head.appendChild(script);

  //call the postload function after a slight delay to allow the json to load
  window.setTimeout(postloadfunction, 100)
}

... and is used like this...

load_json("test2.html.js")

...and this is the <head>...

<head>
  <script type="text/javascript" src="test.html.js" class="json"></script>
</head>

Using onBackPressed() in Android Fragments

This works for me :D

    @Override
    public void onResume() {
    super.onResume();

    if(getView() == null){
        return;
    }

    getView().setFocusableInTouchMode(true);
    getView().requestFocus();
    getView().setOnKeyListener(new View.OnKeyListener() {
        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {

            if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK){
                // handle back button's click listener
                return true;
            }
            return false;
        }
    });}

Cross-platform way of getting temp directory in Python

I use:

from pathlib import Path
import platform
import tempfile

tempdir = Path("/tmp" if platform.system() == "Darwin" else tempfile.gettempdir())

This is because on MacOS, i.e. Darwin, tempfile.gettempdir() and os.getenv('TMPDIR') return a value such as '/var/folders/nj/269977hs0_96bttwj2gs_jhhp48z54/T'; it is one that I do not always want.

Clearing a string buffer/builder after loop

You have two options:

Either use:

sb.setLength(0);  // It will just discard the previous data, which will be garbage collected later.  

Or use:

sb.delete(0, sb.length());  // A bit slower as it is used to delete sub sequence.  

NOTE

Avoid declaring StringBuffer or StringBuilder objects within the loop else it will create new objects with each iteration. Creating of objects requires system resources, space and also takes time. So for long run, avoid declaring them within a loop if possible.

Angular 2 router.navigate

If the first segment doesn't start with / it is a relative route. router.navigate needs a relativeTo parameter for relative navigation

Either you make the route absolute:

this.router.navigate(['/foo-content', 'bar-contents', 'baz-content', 'page'], this.params.queryParams)

or you pass relativeTo

this.router.navigate(['../foo-content', 'bar-contents', 'baz-content', 'page'], {queryParams: this.params.queryParams, relativeTo: this.currentActivatedRoute})

See also

SVN change username

You can change the user with

  • Subversion 1.6 and earlier:

    svn switch --relocate protocol://currentUser@server/path protocol://newUser@server/path
    
  • Subversion 1.7 and later:

    svn relocate protocol://currentUser@server/path protocol://newUser@server/path
    

To find out what protocol://currentUser@server/path is, run

svn info

in your working copy.

How to implement a Map with multiple keys?

Yet another solution is to use Google's Guava

import com.google.common.collect.Table;
import com.google.common.collect.HashBasedTable;

Table<String, String, Integer> table = HashBasedTable.create();

The usage is really simple:

String row = "a";
String column = "b";
int value = 1;

if (!table.contains(row, column)) {
    table.put(row, column, value);
}

System.out.println("value = " + table.get(row, column));

The method HashBasedTable.create() is basically doing something like this:

Table<String, String, Integer> table = Tables.newCustomTable(
        Maps.<String, Map<String, Integer>>newHashMap(),
        new Supplier<Map<String, Integer>>() {
    public Map<String, Integer> get() {
        return Maps.newHashMap();
    }
});

if you're trying to create some custom maps, you should go for the second option (as @Karatheodory suggests) otherwise you should be fine with the first one.

Not unique table/alias

 select persons.personsid,name,info.id,address
    -> from persons
    -> inner join persons on info.infoid = info.info.id;

Powershell: convert string to number

Simply casting the string as an int won't work reliably. You need to convert it to an int32. For this you can use the .NET convert class and its ToInt32 method. The method requires a string ($strNum) as the main input, and the base number (10) for the number system to convert to. This is because you can not only convert to the decimal system (the 10 base number), but also to, for example, the binary system (base 2).

Give this method a try:

[string]$strNum = "1.500"
[int]$intNum = [convert]::ToInt32($strNum, 10)

$intNum

How to get element value in jQuery

<ul id="unOrderedList">
<li value="2">Whatever</li>
.
.



 $('#unOrderedList li').click(function(){
      var value = $(this).attr('value');
     alert(value); 
  });

Your looking for the attribute "value" inside the "li" tag

Creating a script for a Telnet session?

Expect is built for this and can handle the input/output plus timeouts etc. Note that if you're not a TCL fan, there are Expect modules for Perl/Python/Java.

EDIT: The above page suggests that the Wikipedia Expect entry is a useful resource :-)

What does ECU units, CPU core and memory mean when I launch a instance

For linuxes I've figured out that ECU could be measured by sysbench:

sysbench --num-threads=128 --test=cpu --cpu-max-prime=50000 --max-requests=50000 run

Total time (t) should be calculated by formula:

ECU=1925/t

And my example test results:

|   instance type   |   time   |   ECU   |
|-------------------|----------|---------|
| m1.small          |  1735,62 |       1 |
| m3.xlarge         |   147,62 |      13 |
| m3.2xlarge        |    74,61 |      26 |
| r3.large          |   295,84 |       7 |
| r3.xlarge         |   148,18 |      13 |
| m4.xlarge         |   146,71 |      13 |
| m4.2xlarge        |    73,69 |      26 |
| c4.xlarge         |   123,59 |      16 |
| c4.2xlarge        |    61,91 |      31 |
| c4.4xlarge        |    31,14 |      62 |

Float vs Decimal in ActiveRecord

I remember my CompSci professor saying never to use floats for currency.

The reason for that is how the IEEE specification defines floats in binary format. Basically, it stores sign, fraction and exponent to represent a Float. It's like a scientific notation for binary (something like +1.43*10^2). Because of that, it is impossible to store fractions and decimals in Float exactly.

That's why there is a Decimal format. If you do this:

irb:001:0> "%.47f" % (1.0/10)
=> "0.10000000000000000555111512312578270211815834045" # not "0.1"!

whereas if you just do

irb:002:0> (1.0/10).to_s
=> "0.1" # the interprer rounds the number for you

So if you are dealing with small fractions, like compounding interests, or maybe even geolocation, I would highly recommend Decimal format, since in decimal format 1.0/10 is exactly 0.1.

However, it should be noted that despite being less accurate, floats are processed faster. Here's a benchmark:

require "benchmark" 
require "bigdecimal" 

d = BigDecimal.new(3) 
f = Float(3)

time_decimal = Benchmark.measure{ (1..10000000).each { |i| d * d } } 
time_float = Benchmark.measure{ (1..10000000).each { |i| f * f } }

puts time_decimal 
#=> 6.770960 seconds 
puts time_float 
#=> 0.988070 seconds

Answer

Use float when you don't care about precision too much. For example, some scientific simulations and calculations only need up to 3 or 4 significant digits. This is useful in trading off accuracy for speed. Since they don't need precision as much as speed, they would use float.

Use decimal if you are dealing with numbers that need to be precise and sum up to correct number (like compounding interests and money-related things). Remember: if you need precision, then you should always use decimal.

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

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

How to change MySQL timezone in a database connection using Java?

For applications such as Squirrel SQL Client (http://squirrel-sql.sourceforge.net/) version 4 you can set "serverTimezone" under "driver properties" to GMT+1 (example of timezone "Europe/Vienna).

Getting a count of objects in a queryset in django

Use related name to count votes for a specific contest

class Item(models.Model):
    name = models.CharField()

class Contest(models.Model);
    name = models.CharField()

class Votes(models.Model):
    user = models.ForeignKey(User)
    item = models.ForeignKey(Item)
    contest = models.ForeignKey(Contest, related_name="contest_votes")
    comment = models.TextField()

>>> comments = Contest.objects.get(id=contest_id).contest_votes.count()

To compare two elements(string type) in XSLT?

First of all, the provided long code:

    <xsl:choose>
        <xsl:when test="OU_NAME='OU_ADDR1'">   --comparing two elements coming from XML             
            <!--remove if  adrees already contain  operating unit name <xsl:value-of select="OU_NAME"/> <fo:block/>-->
            <xsl:if test="OU_ADDR1 !='' ">
                <xsl:value-of select="OU_ADDR1"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR2 !='' ">
                <xsl:value-of select="OU_ADDR2"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR3 !='' ">
                <xsl:value-of select="OU_ADDR3"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="OU_TOWN_CITY !=''">
                <xsl:value-of select="OU_TOWN_CITY"/>,
                <fo:leader leader-pattern="space" leader-length="2.0pt"/>
            </xsl:if>
            <xsl:value-of select="OU_REGION2"/>
            <fo:leader leader-pattern="space" leader-length="3.0pt"/>
            <xsl:value-of select="OU_POSTALCODE"/>
            <fo:block/>
            <xsl:value-of select="OU_COUNTRY"/>
        </xsl:when>
        <xsl:otherwise>
            <xsl:value-of select="OU_NAME"/>
            <fo:block/>
            <xsl:if test="OU_ADDR1 !='' ">
                <xsl:value-of select="OU_ADDR1"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR2 !='' ">
                <xsl:value-of select="OU_ADDR2"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR3 !='' ">
                <xsl:value-of select="OU_ADDR3"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="OU_TOWN_CITY !=''">
                <xsl:value-of select="OU_TOWN_CITY"/>,
                <fo:leader leader-pattern="space" leader-length="2.0pt"/>
            </xsl:if>
            <xsl:value-of select="OU_REGION2"/>
            <fo:leader leader-pattern="space" leader-length="3.0pt"/>
            <xsl:value-of select="OU_POSTALCODE"/>
            <fo:block/>
            <xsl:value-of select="OU_COUNTRY"/>
        </xsl:otherwise>
    </xsl:choose>

is equivalent to this, much shorter code:

<xsl:if test="not(OU_NAME='OU_ADDR1)'">
              <xsl:value-of select="OU_NAME"/>
        </xsl:if>
            <xsl:if test="OU_ADDR1 !='' ">
                <xsl:value-of select="OU_ADDR1"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR2 !='' ">
                <xsl:value-of select="OU_ADDR2"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="LE_ADDR3 !='' ">
                <xsl:value-of select="OU_ADDR3"/>
                <fo:block/>
            </xsl:if>
            <xsl:if test="OU_TOWN_CITY !=''">
                <xsl:value-of select="OU_TOWN_CITY"/>,
                <fo:leader leader-pattern="space" leader-length="2.0pt"/>
            </xsl:if>
            <xsl:value-of select="OU_REGION2"/>
            <fo:leader leader-pattern="space" leader-length="3.0pt"/>
            <xsl:value-of select="OU_POSTALCODE"/>
            <fo:block/>
            <xsl:value-of select="OU_COUNTRY"/>

Now, to your question:

how to compare two elements coming from xml as string

In Xpath 1.0 strings can be compared only for equality (or inequality), using the operator = and the function not() together with the operator =.

$str1 = $str2

evaluates to true() exactly when the string $str1 is equal to the string $str2.

not($str1 = $str2)

evaluates to true() exactly when the string $str1 is not equal to the string $str2.

There is also the != operator. It generally should be avoided because it has anomalous behavior whenever one of its operands is a node-set.

Now, the rules for comparing two element nodes are similar:

$el1 = $el2

evaluates to true() exactly when the string value of $el1 is equal to the string value of $el2.

not($el1 = $el2)

evaluates to true() exactly when the string value of $el1 is not equal to the string value of $el2.

However, if one of the operands of = is a node-set, then

 $ns = $str

evaluates to true() exactly when there is at least one node in the node-set $ns1, whose string value is equal to the string $str

$ns1 = $ns2

evaluates to true() exactly when there is at least one node in the node-set $ns1, whose string value is equal to the string value of some node from $ns2

Therefore, the expression:

OU_NAME='OU_ADDR1'

evaluates to true() only when there is at least one element child of the current node that is named OU_NAME and whose string value is the string 'OU_ADDR1'.

This is obviously not what you want!

Most probably you want:

OU_NAME=OU_ADDR1

This expression evaluates to true exactly there is at least one OU_NAME child of the current node and one OU_ADDR1 child of the current node with the same string value.

Finally, in XPath 2.0, strings can be compared also using the value comparison operators lt, le, eq, gt, ge and the inherited from XPath 1.0 general comparison operator =.

Trying to evaluate a value comparison operator when one or both of its arguments is a sequence of more than one item results in error.

Fastest way to write huge data in text file Java

For these bulky reads from DB you may want to tune your Statement's fetch size. It might save a lot of roundtrips to DB.

http://download.oracle.com/javase/1.5.0/docs/api/java/sql/Statement.html#setFetchSize%28int%29

How to insert a new line in strings in Android

I would personally prefer using "\n". This just puts a line break in Linux or Android.

For example,

String str = "I am the first part of the info being emailed.\nI am the second part.\n\nI am the third part.";

Output

I am the first part of the info being emailed.
I am the second part.

I am the third part.

A more generalized way would be to use,

System.getProperty("line.separator")

For example,

String str = "I am the first part of the info being emailed." + System.getProperty("line.separator") + "I am the second part." + System.getProperty("line.separator") + System.getProperty("line.separator") + "I am the third part.";

brings the same output as above. Here, the static getProperty() method of the System class can be used to get the "line.seperator" for the particular OS.

But this is not necessary at all, as the OS here is fixed, that is, Android. So, calling a method every time is a heavy and unnecessary operation.

Moreover, this also increases your code length and makes it look kind of messy. A "\n" is sweet and simple.

Is it possible to simulate key press events programmatically?

Building on the answer from alex2k8, here's a revised version that works in all browsers that jQuery supports (the problem was in missing arguments to jQuery.event.trigger, which is easy to forget when using that internal function).

// jQuery plugin. Called on a jQuery object, not directly.
jQuery.fn.simulateKeyPress = function (character) {
  // Internally calls jQuery.event.trigger with arguments (Event, data, elem).
  // That last argument, 'elem', is very important!
  jQuery(this).trigger({ type: 'keypress', which: character.charCodeAt(0) });
};

jQuery(function ($) {
  // Bind event handler
  $('body').keypress(function (e) {
    alert(String.fromCharCode(e.which));
    console.log(e);
  });
  // Simulate the key press
  $('body').simulateKeyPress('x');
});

You could even push this further and let it not only simulate the event but actually insert the character (if it is an input element), however there are many cross-browser gotcha's when trying to do that. Better use a more elaborate plugin like SendKeys.

static constructors in C++? I need to initialize private static objects

The concept of static constructors was introduced in Java after they learned from the problems in C++. So we have no direct equivalent.

The best solution is to use POD types that can be initialised explicitly.
Or make your static members a specific type that has its own constructor that will initialize it correctly.

//header

class A
{
    // Make sure this is private so that nobody can missues the fact that
    // you are overriding std::vector. Just doing it here as a quicky example
    // don't take it as a recomendation for deriving from vector.
    class MyInitedVar: public std::vector<char>
    {
        public:
        MyInitedVar()
        {
           // Pre-Initialize the vector.
           for(char c = 'a';c <= 'z';++c)
           {
               push_back(c);
           }
        }
    };
    static int          count;
    static MyInitedVar  var1;

};


//source
int            A::count = 0;
A::MyInitedVar A::var1;

Difference between string object and string literal

Some disassembly is always interesting...

$ cat Test.java 
public class Test {
    public static void main(String... args) {
        String abc = "abc";
        String def = new String("def");
    }
}

$ javap -c -v Test
Compiled from "Test.java"
public class Test extends java.lang.Object
  SourceFile: "Test.java"
  minor version: 0
  major version: 50
  Constant pool:
const #1 = Method  #7.#16;  //  java/lang/Object."<init>":()V
const #2 = String  #17;     //  abc
const #3 = class   #18;     //  java/lang/String
const #4 = String  #19;     //  def
const #5 = Method  #3.#20;  //  java/lang/String."<init>":(Ljava/lang/String;)V
const #6 = class   #21;     //  Test
const #7 = class   #22;     //  java/lang/Object
const #8 = Asciz   <init>;
...

{
public Test(); ...    

public static void main(java.lang.String[]);
  Code:
   Stack=3, Locals=3, Args_size=1
    0:    ldc #2;           // Load string constant "abc"
    2:    astore_1          // Store top of stack onto local variable 1
    3:    new #3;           // class java/lang/String
    6:    dup               // duplicate top of stack
    7:    ldc #4;           // Load string constant "def"
    9:    invokespecial #5; // Invoke constructor
   12:    astore_2          // Store top of stack onto local variable 2
   13:    return
}

What is the { get; set; } syntax in C#?

  • The get/set pattern provides a structure that allows logic to be added during the setting ('set') or retrieval ('get') of a property instance of an instantiated class, which can be useful when some instantiation logic is required for the property.

  • A property can have a 'get' accessor only, which is done in order to make that property read-only

  • When implementing a get/set pattern, an intermediate variable is used as a container into which a value can be placed and a value extracted. The intermediate variable is usually prefixed with an underscore. this intermediate variable is private in order to ensure that it can only be accessed via its get/set calls. See the answer from Brandon, as his answer demonstrates the most commonly used syntax conventions for implementing get/set.

Apache HttpClient 4.0.3 - how do I set cookie with sessionID for POST request?

I am so glad to solve this problem:

HttpPost httppost = new HttpPost(postData); 
CookieStore cookieStore = new BasicCookieStore(); 
BasicClientCookie cookie = new BasicClientCookie("JSESSIONID", getSessionId());

//cookie.setDomain("your domain");
cookie.setPath("/");

cookieStore.addCookie(cookie); 
client.setCookieStore(cookieStore); 
response = client.execute(httppost); 

So Easy!

Is there a performance difference between CTE , Sub-Query, Temporary Table or Table Variable?

Just 2 things I think make it ALWAYS preferable to use a # Temp Table rather then a CTE are:

  1. You can not put a primary key on a CTE so the data being accessed by the CTE will have to traverse each one of the indexes in the CTE's tables rather then just accessing the PK or Index on the temp table.

  2. Because you can not add constraints, indexes and primary keys to a CTE they are more prone to bugs creeping in and bad data.


-onedaywhen yesterday

Here is an example where #table constraints can prevent bad data which is not the case in CTE's

DECLARE @BadData TABLE ( 
                       ThisID int
                     , ThatID int );
INSERT INTO @BadData
       ( ThisID
       , ThatID
       ) 
VALUES
       ( 1, 1 ),
       ( 1, 2 ),
       ( 2, 2 ),
       ( 1, 1 );

IF OBJECT_ID('tempdb..#This') IS NOT NULL
    DROP TABLE #This;
CREATE TABLE #This ( 
             ThisID int NOT NULL
           , ThatID int NOT NULL
                        UNIQUE(ThisID, ThatID) );
INSERT INTO #This
SELECT * FROM @BadData;
WITH This_CTE
     AS (SELECT *
           FROM @BadData)
     SELECT *
       FROM This_CTE;

How do I iterate through the files in a directory in Java?

I like to use Optional and streams to have a net and clear solution, i use the below code to iterate over a directory. the below cases are handled by the code:

  1. handle the case of empty directory
  2. Laziness

but as mentioned by others, you still have to pay attention for outOfMemory in case you have huge folders

    File directoryFile = new File("put your path here");
    Stream<File> files = Optional.ofNullable(directoryFile// directoryFile
                                                          .listFiles(File::isDirectory)) // filter only directories(change with null if you don't need to filter)
                                 .stream()
                                 .flatMap(Arrays::stream);// flatmap from Stream<File[]> to Stream<File>

Calculating time difference in Milliseconds

In the old days (you know, anytime before yesterday) a PC's BIOS timer would "tick" at a certain interval. That interval would be on the order of 12 milliseconds. Thus, it's quite easy to perform two consecutive calls to get the time and have them return a difference of zero. This only means that the timer didn't "tick" between your two calls. Try getting the time in a loop and displaying the values to the console. If your PC and display are fast enough, you'll see that time jumps, making it look as though it's quantized! (Einstein would be upset!) Newer PCs also have a high resolution timer. I'd imagine that nanoTime() uses the high resolution timer.

Why does background-color have no effect on this DIV?

Since the outer div only contains floated divs, it renders with 0 height. Either give it a height or set its overflow to hidden.

Error:Unable to locate adb within SDK in Android Studio

I know this is silly, but in my case while I was getting the same error message, just changing the USB cable used to connect the device fixed the problem :O

Perhaps this might benefit someone else as well?!

How to find the Vagrant IP?

I know this post is old but i want to add a few points to this!

you can try

vagrant ssh -c "ifconfig | grep inet" hostname 

this will be easy if you have setup a name to your guests individually!

What's the difference between primitive and reference types?

These are the primitive types in Java:

  • boolean
  • byte
  • short
  • char
  • int
  • long
  • float
  • double

All the other types are reference types: they reference objects.

This is the first part of the Java tutorial about the basics of the language.

Multiple github accounts on the same computer?

Personal Directory .gitconfig using a personal access token

If you do not want to modify your host file, use SSH keys, or setup a .gitconfig for each repo, then you may use a personal .gitconfig that you basically include from the root level config. Given an OSX directory structure like

# root level git config
~/.gitconfig

# your personal repos under some folder like
../personal/
../home/
~/Dropbox/

Add a .gitconfig in your personal folder, such as ~/Dropbox/.gitconfig

[user]
    email = [email protected]
    name = First Last
[credential]
    username = PersonalGithubUsername
    helper = osxkeychain

In your root level .gitconfig add an includeIf section to source your personal config whenever you are in your personal directory. Any settings there will override the root config as long as the includeIf comes after the settings you want to override.

[user]
    email = [email protected]
    name = "First Last"
[credential]
    helper = osxkeychain
[includeIf "gitdir:~/Dropbox/**"]
    path = ~/Dropbox/.gitconfig

Try pushing to your personal repo or pulling from your private repo

git push
# prompts for password

When prompted enter either your personal password or, better yet, your personal access token that you have created in your account developer settings. Enter that token as your password.

Assuming you are already using git-credential-osxkeychain, your personal credentials should be stored in your keychain, so two github entries will show up, but with different accounts.

OSX keychain 2 entires for Github

Center text output from Graphics.DrawString()

Here's some code. This assumes you are doing this on a form, or a UserControl.

Graphics g = this.CreateGraphics();
SizeF size = g.MeasureString("string to measure");

int nLeft = Convert.ToInt32((this.ClientRectangle.Width / 2) - (size.Width / 2));
int nTop = Convert.ToInt32((this.ClientRectangle.Height / 2) - (size.Height / 2));

From your post, it sounds like the ClientRectangle part (as in, you're not using it) is what's giving you difficulty.

Reset all changes after last commit in git

There are two commands which will work in this situation,

root>git reset --hard HEAD~1

root>git push -f

For more git commands refer this page

Disable Pinch Zoom on Mobile Web

To everyone who said that this is a bad idea I want to say it is not always a bad one. Sometimes it is very boring to have to zoom out to see all the content. For example when you type on an input on iOS it zooms to get it in the center of the screen. You have to zoom out after that cause closing the keyboard does not do the work. Also I agree that when you put many I hours in making a great layout and user experience you don't want it to be messed up by a zoom.

But the other argument is valuable as well for people with vision issues. However In my opinion if you have issues with your eyes you are already using the zooming features of the system so there is no need to disturb the content.

How to create a drop-down list?

simple / elegant / how I do it:

Preview:

enter image description here

XML:

<Spinner
    android:id="@+id/spinner1"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@android:drawable/btn_dropdown"
    android:spinnerMode="dropdown"/>

spinnerMode set to dropdown is androids way to make a dropdown. (https://developer.android.com/reference/android/widget/Spinner#attr_android:spinnerMode)

Java:

//get the spinner from the xml.
Spinner dropdown = findViewById(R.id.spinner1);
//create a list of items for the spinner.
String[] items = new String[]{"1", "2", "three"};
//create an adapter to describe how the items are displayed, adapters are used in several places in android.
//There are multiple variations of this, but this is the basic variant.
ArrayAdapter<String> adapter = new ArrayAdapter<>(this, android.R.layout.simple_spinner_dropdown_item, items);
//set the spinners adapter to the previously created one.
dropdown.setAdapter(adapter);

Documentation:

This is the basics but there is more to be self taught with experimentation. https://developer.android.com/guide/topics/ui/controls/spinner.html

  1. You can use a setOnItemSelectedListener with this. (https://developer.android.com/guide/topics/ui/controls/spinner.html#SelectListener)
  2. You can add a strings list from xml. (https://developer.android.com/guide/topics/ui/controls/spinner.html#Populate)
  3. There is an appCompat version of this view. (https://developer.android.com/reference/androidx/appcompat/widget/AppCompatSpinner)

Get element inside element by class and ID - JavaScript

Well, first you need to select the elements with a function like getElementById.

var targetDiv = document.getElementById("foo").getElementsByClassName("bar")[0];

getElementById only returns one node, but getElementsByClassName returns a node list. Since there is only one element with that class name (as far as I can tell), you can just get the first one (that's what the [0] is for—it's just like an array).

Then, you can change the html with .textContent.

targetDiv.textContent = "Goodbye world!";

_x000D_
_x000D_
var targetDiv = document.getElementById("foo").getElementsByClassName("bar")[0];_x000D_
targetDiv.textContent = "Goodbye world!";
_x000D_
<div id="foo">_x000D_
    <div class="bar">_x000D_
        Hello world!_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Dismissing a Presented View Controller

This is for view controller reusability.

Your view controller shouldn't care if it is being presented as a modal, pushed on a navigation controller, or whatever. If your view controller dismisses itself, then you're assuming it is being presented modally. You won't be able to push that view controller onto a navigation controller.

By implementing a protocol, you let the parent view controller decide how it should be presented/pushed and dismissed/popped.

Git: Merge a Remote branch locally

Fetch the remote branch from the origin first.

git fetch origin remote_branch_name

Merge the remote branch to the local branch

git merge origin/remote_branch_name

File Upload to HTTP server in iphone programming

An update to @Brandon's answer, generalized to a method

- (NSString*) postToUrl:(NSString*)urlString data:(NSData*)dataToSend withFilename:(NSString*)filename
{
    NSMutableURLRequest *request= [[NSMutableURLRequest alloc] init];
    [request setURL:[NSURL URLWithString:urlString]];
    [request setHTTPMethod:@"POST"];
    NSString *boundary = @"---------------------------14737809831466499882746641449";
    NSString *contentType = [NSString stringWithFormat:@"multipart/form-data; boundary=%@", boundary];
    [request addValue:contentType forHTTPHeaderField: @"Content-Type"];
    NSMutableData *postbody = [NSMutableData data];
    [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[[NSString stringWithFormat:@"Content-Disposition: form-data; name=\"userfile\"; filename=\"%@\"\r\n", filename] dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[@"Content-Type: application/octet-stream\r\n\r\n" dataUsingEncoding:NSUTF8StringEncoding]];
    [postbody appendData:[NSData dataWithData:dataToSend]];
    [postbody appendData:[[NSString stringWithFormat:@"\r\n--%@--\r\n", boundary] dataUsingEncoding:NSUTF8StringEncoding]];
    [request setHTTPBody:postbody];

    NSError* error;
    NSData *returnData = [NSURLConnection sendSynchronousRequest:request returningResponse:nil error:&error];
    if (returnData) {
        return [[NSString alloc] initWithData:returnData encoding:NSUTF8StringEncoding];
    }
    else {
        return nil;
    }
}

Invoke like so, sending data from a string:

[self postToUrl:@"<#Your url string#>"
           data:[@"<#Your string to send#>" dataUsingEncoding:NSUTF8StringEncoding]
   withFilename:@"<#Filename to post with#>"];

How can I generate a list or array of sequential integers in Java?

You could use Guava Ranges

You can get a SortedSet by using

ImmutableSortedSet<Integer> set = Ranges.open(1, 5).asSet(DiscreteDomains.integers());
// set contains [2, 3, 4]

How to recover Git objects damaged by hard disk failure?

Here are the steps I followed to recover from a corrupt blob object.

1) Identify corrupt blob

git fsck --full
  error: inflate: data stream error (incorrect data check)
  error: sha1 mismatch 241091723c324aed77b2d35f97a05e856b319efd
  error: 241091723c324aed77b2d35f97a05e856b319efd: object corrupt or missing
  ...

Corrupt blob is 241091723c324aed77b2d35f97a05e856b319efd

2) Move corrupt blob to a safe place (just in case)

mv .git/objects/24/1091723c324aed77b2d35f97a05e856b319efd ../24/

3) Get parent of corrupt blob

git fsck --full
  Checking object directories: 100% (256/256), done.
  Checking objects: 100% (70321/70321), done.
  broken link from    tree 0716831e1a6c8d3e6b2b541d21c4748cc0ce7180
              to    blob 241091723c324aed77b2d35f97a05e856b319efd

Parent hash is 0716831e1a6c8d3e6b2b541d21c4748cc0ce7180.

4) Get file name corresponding to corrupt blob

git ls-tree 0716831e1a6c8d3e6b2b541d21c4748cc0ce7180
  ...
  100644 blob 241091723c324aed77b2d35f97a05e856b319efd    dump.tar.gz
  ...

Find this particular file in a backup or in the upstream git repository (in my case it is dump.tar.gz). Then copy it somewhere inside your local repository.

5) Add previously corrupted file in the git object database

git hash-object -w dump.tar.gz

6) Celebrate!

git gc
  Counting objects: 75197, done.
  Compressing objects: 100% (21805/21805), done.
  Writing objects: 100% (75197/75197), done.
  Total 75197 (delta 52999), reused 69857 (delta 49296)

There is no tracking information for the current branch

ComputerDruid's answer is great but I don't think it's necessary to set upstream manually unless you want to. I'm adding this answer because people might think that that's a necessary step.

This error will be gone if you specify the remote that you want to pull like below:

git pull origin master

Note that origin is the name of the remote and master is the branch name.


1) How to check remote's name

git remote -v

2) How to see what branches available in the repository.

git branch -r

Setting active profile and config location from command line in spring boot

you can use the following command line:

java -jar -Dspring.profiles.active=[yourProfileName] target/[yourJar].jar

Font Awesome & Unicode

There are three different font families that I know of that you can choose from and each has its own weight element that needs to be applied:

First

font-family: 'Font Awesome 5 Brands'; content: "\f373";

Second

font-family: 'Font Awesome 5 Free'; content: "\f061"; font-weight: 900;

Third

font-family: 'Font Awesome 5 Pro';

Reference here - https://fontawesome.com/how-to-use/on-the-web/advanced/css-pseudo-elements

Hope this helps.

Why am I getting "undefined reference to sqrt" error even though I include math.h header?

Because you didn't tell the linker about location of math library. Compile with gcc test.c -o test -lm

Declaring variables in Excel Cells

You can name cells. This is done by clicking the Name Box (that thing next to the formula bar which says "A1" for example) and typing a name, such as, "myvar". Now you can use that name instead of the cell reference:

= myvar*25

How to compile C programming in Windows 7?

You can get MinGW (as others have suggested) but I would recommend getting a simple IDE (not VS Express). You can try Dev C++ http://www.bloodshed.net/devcpp.html Its a simple IDE for C/C++ and uses MinGW internally. In this you can write and compile single C files without creating a full-blown "project".

Visual Studio 2017 error: Unable to start program, An operation is not legal in the current state

I just closed all open chrome instances, stopped my project and then start it again. that fixed the problem for me.

VB.NET - Remove a characters from a String

The String class has a Replace method that will do that.

Dim clean as String
clean = myString.Replace(",", "")

An Iframe I need to refresh every 30 seconds (but not the whole page)

You can put a meta refresh Tag in the irc_online.php

<meta http-equiv="refresh" content="30">

OR you can use Javascript with setInterval to refresh the src of the Source...

<script>
window.setInterval("reloadIFrame();", 30000);

function reloadIFrame() {
 document.frames["frameNameHere"].location.reload();
}
</script>

/usr/bin/codesign failed with exit code 1

I have to agree with Tobias. The error is too generic. When the same thing happened to me I dug into the error message and realized I'd screwed up something in the build properties, but not the code signing. So yeah, I'd dig in to the details.

Clear form after submission with jQuery

Propably this would do it for you.

 $('input').val('').removeAttr('checked').removeAttr('selected');

How to resize JLabel ImageIcon?

Resizing the icon is not straightforward. You need to use Java's graphics 2D to scale the image. The first parameter is a Image class which you can easily get from ImageIcon class. You can use ImageIcon class to load your image file and then simply call getter method to get the image.

private Image getScaledImage(Image srcImg, int w, int h){
    BufferedImage resizedImg = new BufferedImage(w, h, BufferedImage.TYPE_INT_ARGB);
    Graphics2D g2 = resizedImg.createGraphics();

    g2.setRenderingHint(RenderingHints.KEY_INTERPOLATION, RenderingHints.VALUE_INTERPOLATION_BILINEAR);
    g2.drawImage(srcImg, 0, 0, w, h, null);
    g2.dispose();

    return resizedImg;
}

Can't execute jar- file: "no main manifest attribute"

For me this error occurred simply because I forgot tell Eclipse that I wanted a runnable jar file and not a simple library jar file. So when you create the jar file in Eclipse make sure that you click the right radio button

Readably print out a python dict() sorted by key

An easy way to print the sorted contents of the dictionary, in Python 3:

>>> dict_example = {'c': 1, 'b': 2, 'a': 3}
>>> for key, value in sorted(dict_example.items()):
...   print("{} : {}".format(key, value))
... 
a : 3
b : 2
c : 1

The expression dict_example.items() returns tuples, which can then be sorted by sorted():

>>> dict_example.items()
dict_items([('c', 1), ('b', 2), ('a', 3)])
>>> sorted(dict_example.items())
[('a', 3), ('b', 2), ('c', 1)]

Below is an example to pretty print the sorted contents of a Python dictionary's values.

for key, value in sorted(dict_example.items(), key=lambda d_values: d_values[1]): 
    print("{} : {}".format(key, value))

Which SchemaType in Mongoose is Best for Timestamp?

The current version of Mongoose (v4.x) has time stamping as a built-in option to a schema:

var mySchema = new mongoose.Schema( {name: String}, {timestamps: true} );

This option adds createdAt and updatedAt properties that are timestamped with a Date, and which does all the work for you. Any time you update the document, it updates the updatedAt property. Schema Timestamps Docs.

How do I deal with special characters like \^$.?*|+()[{ in my regex?

Escape with a double backslash

R treats backslashes as escape values for character constants. (... and so do regular expressions. Hence the need for two backslashes when supplying a character argument for a pattern. The first one isn't actually a character, but rather it makes the second one into a character.) You can see how they are processed using cat.

y <- "double quote: \", tab: \t, newline: \n, unicode point: \u20AC"
print(y)
## [1] "double quote: \", tab: \t, newline: \n, unicode point: €"
cat(y)
## double quote: ", tab:    , newline: 
## , unicode point: €

Further reading: Escaping a backslash with a backslash in R produces 2 backslashes in a string, not 1

To use special characters in a regular expression the simplest method is usually to escape them with a backslash, but as noted above, the backslash itself needs to be escaped.

grepl("\\[", "a[b")
## [1] TRUE

To match backslashes, you need to double escape, resulting in four backslashes.

grepl("\\\\", c("a\\b", "a\nb"))
## [1]  TRUE FALSE

The rebus package contains constants for each of the special characters to save you mistyping slashes.

library(rebus)
OPEN_BRACKET
## [1] "\\["
BACKSLASH
## [1] "\\\\"

For more examples see:

?SpecialCharacters

Your problem can be solved this way:

library(rebus)
grepl(OPEN_BRACKET, "a[b")

Form a character class

You can also wrap the special characters in square brackets to form a character class.

grepl("[?]", "a?b")
## [1] TRUE

Two of the special characters have special meaning inside character classes: \ and ^.

Backslash still needs to be escaped even if it is inside a character class.

grepl("[\\\\]", c("a\\b", "a\nb"))
## [1]  TRUE FALSE

Caret only needs to be escaped if it is directly after the opening square bracket.

grepl("[ ^]", "a^b")  # matches spaces as well.
## [1] TRUE
grepl("[\\^]", "a^b") 
## [1] TRUE

rebus also lets you form a character class.

char_class("?")
## <regex> [?]

Use a pre-existing character class

If you want to match all punctuation, you can use the [:punct:] character class.

grepl("[[:punct:]]", c("//", "[", "(", "{", "?", "^", "$"))
## [1] TRUE TRUE TRUE TRUE TRUE TRUE TRUE

stringi maps this to the Unicode General Category for punctuation, so its behaviour is slightly different.

stri_detect_regex(c("//", "[", "(", "{", "?", "^", "$"), "[[:punct:]]")
## [1]  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE

You can also use the cross-platform syntax for accessing a UGC.

stri_detect_regex(c("//", "[", "(", "{", "?", "^", "$"), "\\p{P}")
## [1]  TRUE  TRUE  TRUE  TRUE  TRUE FALSE FALSE

Use \Q \E escapes

Placing characters between \\Q and \\E makes the regular expression engine treat them literally rather than as regular expressions.

grepl("\\Q.\\E", "a.b")
## [1] TRUE

rebus lets you write literal blocks of regular expressions.

literal(".")
## <regex> \Q.\E

Don't use regular expressions

Regular expressions are not always the answer. If you want to match a fixed string then you can do, for example:

grepl("[", "a[b", fixed = TRUE)
stringr::str_detect("a[b", fixed("["))
stringi::stri_detect_fixed("a[b", "[")

List all files from a directory recursively with Java

public class GetFilesRecursive {
    public static List <String> getFilesRecursively(File dir){
        List <String> ls = new ArrayList<String>();
        for (File fObj : dir.listFiles()) {
            if(fObj.isDirectory()) {
                ls.add(String.valueOf(fObj));
                ls.addAll(getFilesRecursively(fObj));               
            } else {
                ls.add(String.valueOf(fObj));       
            }
        }

        return ls;
    }
    public static List <String> getListOfFiles(String fullPathDir) {
        List <String> ls = new ArrayList<String> ();
        File f = new File(fullPathDir);
        if (f.exists()) {
            if(f.isDirectory()) {
                ls.add(String.valueOf(f));
                ls.addAll(getFilesRecursively(f));
            }
        } else {
            ls.add(fullPathDir);
        }
        return ls;
    }

    public static void main(String[] args) {
        List <String> ls = getListOfFiles("/Users/srinivasab/Documents");
        for (String file:ls) {
            System.out.println(file);
        }
        System.out.println(ls.size());
    }
}

Is generator.next() visible in Python 3?

Try:

next(g)

Check out this neat table that shows the differences in syntax between 2 and 3 when it comes to this.

How to install an apk on the emulator in Android Studio?

Drag and drop apk if the emulator is launched from Android Studio. If the emulator is started from command line, drag and drop doesn't work, but @Tarek K. Ajaj instructions (above) work.

Note: Installed app won't automatically appear on the home screen, it is in the apps container - the dotted grid icon. It can be dragged from there to the home screen.

Sending POST data without form

If you don't want your data to be seen by the user, use a PHP session.

Data in a post request is still accessible (and manipulable) by the user.

Checkout this tutorial on PHP Sessions.

Should I use PATCH or PUT in my REST API?

I would recommend using PATCH, because your resource 'group' has many properties but in this case, you are updating only the activation field(partial modification)

according to the RFC5789 (https://tools.ietf.org/html/rfc5789)

The existing HTTP PUT method only allows a complete replacement of a document. This proposal adds a new HTTP method, PATCH, to modify an existing HTTP resource.

Also, in more details,

The difference between the PUT and PATCH requests is reflected in the way the server processes the enclosed entity to modify the resource
identified by the Request-URI. In a PUT request, the enclosed entity is considered to be a modified version of the resource stored on the
origin server, and the client is requesting that the stored version
be replaced. With PATCH, however, the enclosed entity contains a set of instructions describing how a resource currently residing on the
origin server should be modified to produce a new version. The PATCH method affects the resource identified by the Request-URI, and it
also MAY have side effects on other resources; i.e., new resources
may be created, or existing ones modified, by the application of a
PATCH.

PATCH is neither safe nor idempotent as defined by [RFC2616], Section 9.1.

Clients need to choose when to use PATCH rather than PUT. For
example, if the patch document size is larger than the size of the
new resource data that would be used in a PUT, then it might make
sense to use PUT instead of PATCH. A comparison to POST is even more difficult, because POST is used in widely varying ways and can
encompass PUT and PATCH-like operations if the server chooses. If
the operation does not modify the resource identified by the Request- URI in a predictable way, POST should be considered instead of PATCH
or PUT.

The response code for PATCH is

The 204 response code is used because the response does not carry a message body (which a response with the 200 code would have). Note that other success codes could be used as well.

also refer thttp://restcookbook.com/HTTP%20Methods/patch/

Caveat: An API implementing PATCH must patch atomically. It MUST not be possible that resources are half-patched when requested by a GET.

SQL Server: Attach incorrect version 661

To clarify, a database created under SQL Server 2008 R2 was being opened in an instance of SQL Server 2008 (the version prior to R2). The solution for me was to simply perform an upgrade installation of SQL Server 2008 R2. I can only speak for the Express edition, but it worked.

Oddly, though, the Web Platform Installer indicated that I had Express R2 installed. The better way to tell is to ask the database server itself:

SELECT @@VERSION

T-SQL string replace in Update

update YourTable
    set YourColumn = replace(YourColumn, '@domain2', '@domain1')
    where charindex('@domain2', YourColumn) <> 0

Displaying tooltip on mouse hover of a text

I would also like to add something here that if you load desired form that contain tooltip controll before the program's run then tool tip control on that form will not work as described below...

    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        objfrmmain = new Frm_Main();
        Showtop();//this is procedure in program.cs to load an other form, so if that contain's tool tip control then it will not work
        Application.Run(objfrmmain);


    }

so I solved this problem by puting following code in Fram_main_load event procedure like this

    private void Frm_Main_Load(object sender, EventArgs e)
    {
        Program.Showtop();
    }

How to show full column content in a Spark Dataframe?

PYSPARK

In the below code, df is the name of dataframe. 1st parameter is to show all rows in the dataframe dynamically rather than hardcoding a numeric value. The 2nd parameter will take care of displaying full column contents since the value is set as False.

df.show(df.count(),False)

enter image description here


SCALA

In the below code, df is the name of dataframe. 1st parameter is to show all rows in the dataframe dynamically rather than hardcoding a numeric value. The 2nd parameter will take care of displaying full column contents since the value is set as false.

df.show(df.count().toInt,false)

enter image description here

How do I cast a JSON Object to a TypeScript class?

Pass the object as is to the class constructor; No conventions or checks

interface iPerson {
   name: string;
   age: number;
}

class Person {
   constructor(private person: iPerson) { }

   toString(): string {
      return this.person.name + ' is ' + this.person.age;
   }  
}


// runs this as // 
const object1 = { name: 'Watson1', age: 64 };
const object2 = { name: 'Watson2' };            // age is missing

const person1 = new Person(object1);
const person2 = new Person(object2 as iPerson); // now matches constructor

console.log(person1.toString())  // Watson1 is 64
console.log(person2.toString())  // Watson2 is undefined

How to download dependencies in gradle

You should try this one :

task getDeps(type: Copy) {
    from configurations.runtime
    into 'runtime/'
}

I was was looking for it some time ago when working on a project in which we had to download all dependencies into current working directory at some point in our provisioning script. I guess you're trying to achieve something similar.

Calculating percentile of dataset column

table_ages <- subset(infert, select=c("age"))
summary(table_ages)
#            age       
#  Min.   :21.00  
#  1st Qu.:28.00  
#  Median :31.00  
#  Mean   :31.50  
#  3rd Qu.:35.25  
#  Max.   :44.00  

This is probably what they're looking for. summary(...) applied to a numeric returns the min, max, mean, median, and 25th and 75th percentile of the data.

Note that

summary(infert$age)
#    Min. 1st Qu.  Median    Mean 3rd Qu.    Max. 
#   21.00   28.00   31.00   31.50   35.25   44.00 

The numbers are the same but the format is different. This is because table_ages is a data frame with one column (ages), whereas infert$age is a numeric vector. Try typing summary(infert).

How can I take a screenshot with Selenium WebDriver?

Ruby

require 'rubygems'
require 'selenium-webdriver'

driver = Selenium::WebDriver.for :ie
driver.get "https://www.google.com"
driver.save_screenshot("./screen.png")

More file types and options are available and you can see them in file takes_screenshot.rb.

How to call an action after click() in Jquery?

you can write events on elements like chain,

$(element).on('click',function(){
   //action on click
}).on('mouseup',function(){
   //action on mouseup (just before click event)
});

i've used it for removing cart items. same object, doing some action, after another action

What is content-type and datatype in an AJAX request?

From the jQuery documentation - http://api.jquery.com/jQuery.ajax/

contentType When sending data to the server, use this content type.

dataType The type of data that you're expecting back from the server. If none is specified, jQuery will try to infer it based on the MIME type of the response

"text": A plain text string.

So you want contentType to be application/json and dataType to be text:

$.ajax({
    type : "POST",
    url : /v1/user,
    dataType : "text",
    contentType: "application/json",
    data : dataAttribute,
    success : function() {

    },
    error : function(error) {

    }
});

Generate a dummy-variable

The simplest way to produce these dummy variables is something like the following:

> print(year)
[1] 1956 1957 1957 1958 1958 1959
> dummy <- as.numeric(year == 1957)
> print(dummy)
[1] 0 1 1 0 0 0
> dummy2 <- as.numeric(year >= 1957)
> print(dummy2)
[1] 0 1 1 1 1 1

More generally, you can use ifelse to choose between two values depending on a condition. So if instead of a 0-1 dummy variable, for some reason you wanted to use, say, 4 and 7, you could use ifelse(year == 1957, 4, 7).

How do I Set Background image in Flutter?

You can use Stack to make the image stretch to the full screen.

Stack(
        children: <Widget>
        [
          Positioned.fill(  //
            child: Image(
              image: AssetImage('assets/placeholder.png'),
              fit : BoxFit.fill,
           ),
          ), 
          ...... // other children widgets of Stack
          ..........
          .............
         ]
 );

Note: Optionally if are using a Scaffold, you can put the Stack inside the Scaffold with or without AppBar according to your needs.

how can I check if a file exists?

Start with this:

Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists(path)) Then
   msg = path & " exists."
Else
   msg = path & " doesn't exist."
End If

Taken from the documentation.

Python send POST with header

Thanks a lot for your link to the requests module. It's just perfect. Below the solution to my problem.

import requests
import json

url = 'https://www.mywbsite.fr/Services/GetFromDataBaseVersionned'
payload = {
    "Host": "www.mywbsite.fr",
    "Connection": "keep-alive",
    "Content-Length": 129,
    "Origin": "https://www.mywbsite.fr",
    "X-Requested-With": "XMLHttpRequest",
    "User-Agent": "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/536.5 (KHTML, like Gecko) Chrome/19.0.1084.52 Safari/536.5",
    "Content-Type": "application/json",
    "Accept": "*/*",
    "Referer": "https://www.mywbsite.fr/data/mult.aspx",
    "Accept-Encoding": "gzip,deflate,sdch",
    "Accept-Language": "fr-FR,fr;q=0.8,en-US;q=0.6,en;q=0.4",
    "Accept-Charset": "ISO-8859-1,utf-8;q=0.7,*;q=0.3",
    "Cookie": "ASP.NET_SessionId=j1r1b2a2v2w245; GSFV=FirstVisit=; GSRef=https://www.google.fr/url?sa=t&rct=j&q=&esrc=s&source=web&cd=1&ved=0CHgQFjAA&url=https://www.mywbsite.fr/&ei=FZq_T4abNcak0QWZ0vnWCg&usg=AFQjCNHq90dwj5RiEfr1Pw; HelpRotatorCookie=HelpLayerWasSeen=0; NSC_GSPOUGS!TTM=ffffffff09f4f58455e445a4a423660; GS=Site=frfr; __utma=1.219229010.1337956889.1337956889.1337958824.2; __utmb=1.1.10.1337958824; __utmc=1; __utmz=1.1337956889.1.1.utmcsr=google|utmccn=(organic)|utmcmd=organic|utmctr=(not%20provided)"
}
# Adding empty header as parameters are being sent in payload
headers = {}
r = requests.post(url, data=json.dumps(payload), headers=headers)
print(r.content)

git rebase fatal: Needed a single revision

The error occurs when your repository does not have the default branch set for the remote. You can use the git remote set-head command to modify the default branch, and thus be able to use the remote name instead of a specified branch in that remote.

To query the remote (in this case origin) for its HEAD (typically master), and set that as the default branch:

$ git remote set-head origin --auto

If you want to use a different default remote branch locally, you can specify that branch:

$ git remote set-head origin new-default

Once the default branch is set, you can use just the remote name in git rebase <remote> and any other commands instead of explicit <remote>/<branch>.

Behind the scenes, this command updates the reference in .git/refs/remotes/origin/HEAD.

$ cat .git/refs/remotes/origin/HEAD 
ref: refs/remotes/origin/master

See the git-remote man page for further details.

Session unset, or session_destroy?

Unset will destroy a particular session variable whereas session_destroy() will destroy all the session data for that user.

It really depends on your application as to which one you should use. Just keep the above in mind.

unset($_SESSION['name']); // will delete just the name data

session_destroy(); // will delete ALL data associated with that user.

Convert a double to a QString

Instead of QString::number() i would use QLocale::toString(), so i can get locale aware group seperatores like german "1.234.567,89".

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

The code below resolved the issue

ServicePointManager.SecurityProtocol = SecurityProtocolType.Tls Or SecurityProtocolType.Ssl3

Why is Visual Studio 2013 very slow?

I had the same problem and all the solutions mentioned here didn't work out for me.

After uninstalling the "Productivity Power Tools 2013" extension, the performance was back to normal.

Java reading a file into an ArrayList?

To share some analysis info. With a simple test how long it takes to read ~1180 lines of values.

If you need to read the data very fast, use the good old BufferedReader FileReader example. It took me ~8ms

The Scanner is much slower. Took me ~138ms

The nice Java 8 Files.lines(...) is the slowest version. Took me ~388ms.

Can I invoke an instance method on a Ruby module without including it?

Not sure if someone still needs it after 10 years but I solved it using eigenclass.

module UsefulThings
  def useful_thing_1
    "thing_1"
  end

  class << self
    include UsefulThings
  end
end

class A
  include UsefulThings
end

class B
  extend UsefulThings
end

UsefulThings.useful_thing_1 # => "thing_1"
A.new.useful_thing_1 # => "thing_1"
B.useful_thing_1 # => "thing_1"

Overriding the java equals() method - not working?

Another fast solution that saves boilerplate code is Lombok EqualsAndHashCode annotation. It is easy, elegant and customizable. And does not depends on the IDE. For example;

import lombok.EqualsAndHashCode;

@EqualsAndHashCode(of={"errorNumber","messageCode"}) // Will only use this fields to generate equals.
public class ErrorMessage{

    private long        errorNumber;
    private int         numberOfParameters;
    private Level       loggingLevel;
    private String      messageCode;

See the options avaliable to customize which fields to use in the equals. Lombok is avalaible in maven. Just add it with provided scope:

<dependency>
    <groupId>org.projectlombok</groupId>
    <artifactId>lombok</artifactId>
    <version>1.14.8</version>
    <scope>provided</scope>
</dependency>

Center a H1 tag inside a DIV

<div id="AlertDiv" style="width:600px;height:400px;border:SOLID 1px;">
    <h1 style="width:100%;height:10%;text-align:center;position:relative;top:40%;">Yes</h1>
</div>

You can try the code here:

http://htmledit.squarefree.com/

How to use ng-repeat for dictionaries in AngularJs?

JavaScript developers tend to refer to the above data-structure as either an object or hash instead of a Dictionary.

Your syntax above is wrong as you are initializing the users object as null. I presume this is a typo, as the code should read:

// Initialize users as a new hash.
var users = {};
users["182982"] = "...";

To retrieve all the values from a hash, you need to iterate over it using a for loop:

function getValues (hash) {
    var values = [];
    for (var key in hash) {

        // Ensure that the `key` is actually a member of the hash and not
        // a member of the `prototype`.
        // see: http://javascript.crockford.com/code.html#for%20statement
        if (hash.hasOwnProperty(key)) {
            values.push(key);
        }
    }
    return values;
};

If you plan on doing a lot of work with data-structures in JavaScript then the underscore.js library is definitely worth a look. Underscore comes with a values method which will perform the above task for you:

var values = _.values(users);

I don't use Angular myself, but I'm pretty sure there will be a convenience method build in for iterating over a hash's values (ah, there we go, Artem Andreev provides the answer above :))

What is the .idea folder?

As of year 2020, JetBrains suggests to commit the .idea folder.
The JetBrains IDEs (webstorm, intellij, android studio, pycharm, clion, etc.) automatically add that folder to your git repository (if there's one).
Inside the folder .idea, has been already created a .gitignore, updated by the IDE itself to avoid to commit user related settings that may contains privacy/password data.

It is safe (and usually useful) to commit the .idea folder.

Go to first line in a file in vim?

Type "gg" in command mode. This brings the cursor to the first line.

C# binary literals

Adding to @StriplingWarrior's answer about bit flags in enums, there's an easy convention you can use in hexadecimal for counting upwards through the bit shifts. Use the sequence 1-2-4-8, move one column to the left, and repeat.

[Flags]
enum Scenery
{
  Trees   = 0x001, // 000000000001
  Grass   = 0x002, // 000000000010
  Flowers = 0x004, // 000000000100
  Cactus  = 0x008, // 000000001000
  Birds   = 0x010, // 000000010000
  Bushes  = 0x020, // 000000100000
  Shrubs  = 0x040, // 000001000000
  Trails  = 0x080, // 000010000000
  Ferns   = 0x100, // 000100000000
  Rocks   = 0x200, // 001000000000
  Animals = 0x400, // 010000000000
  Moss    = 0x800, // 100000000000
}

Scan down starting with the right column and notice the pattern 1-2-4-8 (shift) 1-2-4-8 (shift) ...


To answer the original question, I second @Sahuagin's suggestion to use hexadecimal literals. If you're working with binary numbers often enough for this to be a concern, it's worth your while to get the hang of hexadecimal.

If you need to see binary numbers in source code, I suggest adding comments with binary literals like I have above.

Run a command shell in jenkins

Error shows that script does not exists

The file does not exists. check your full path

C:\Windows\TEMP\hudson6299483223982766034.sh
The system cannot find the file specified

Moreover, to launch .sh scripts into windows, you need to have CYGWIN installed and well configured into your path

Confirm that script exists.

Into jenkins script, do the following to confirm that you do have the file

cd C:\Windows\TEMP\
ls -rtl
sh -xe hudson6299483223982766034.sh

Get the current time in C

Copy-pasted from here:

/* localtime example */
#include <stdio.h>
#include <time.h>

int main ()
{
  time_t rawtime;
  struct tm * timeinfo;

  time ( &rawtime );
  timeinfo = localtime ( &rawtime );
  printf ( "Current local time and date: %s", asctime (timeinfo) );
  
  return 0;
}

(just add void to the main() arguments list in order for this to work in C)

Use python requests to download CSV

This should help:

import csv
import requests

CSV_URL = 'http://samplecsvs.s3.amazonaws.com/Sacramentorealestatetransactions.csv'


with requests.Session() as s:
    download = s.get(CSV_URL)

    decoded_content = download.content.decode('utf-8')

    cr = csv.reader(decoded_content.splitlines(), delimiter=',')
    my_list = list(cr)
    for row in my_list:
        print(row)

Ouput sample:

['street', 'city', 'zip', 'state', 'beds', 'baths', 'sq__ft', 'type', 'sale_date', 'price', 'latitude', 'longitude']
['3526 HIGH ST', 'SACRAMENTO', '95838', 'CA', '2', '1', '836', 'Residential', 'Wed May 21 00:00:00 EDT 2008', '59222', '38.631913', '-121.434879']
['51 OMAHA CT', 'SACRAMENTO', '95823', 'CA', '3', '1', '1167', 'Residential', 'Wed May 21 00:00:00 EDT 2008', '68212', '38.478902', '-121.431028']
['2796 BRANCH ST', 'SACRAMENTO', '95815', 'CA', '2', '1', '796', 'Residential', 'Wed May 21 00:00:00 EDT 2008', '68880', '38.618305', '-121.443839']
['2805 JANETTE WAY', 'SACRAMENTO', '95815', 'CA', '2', '1', '852', 'Residential', 'Wed May 21 00:00:00 EDT 2008', '69307', '38.616835', '-121.439146']
[...]

Related question with answer: https://stackoverflow.com/a/33079644/295246


Edit: Other answers are useful if you need to download large files (i.e. stream=True).

MongoDb shuts down with Code 100

In my case, I got a similar error and it was happening because I had run mongod with the root user and that had created a log file only accessible by the root. I could fix this by changing the ownership from root to the user you normally run mongod from. The log file was in /var/lib/mongodb/journal/

How to make Java Set?

Like this:

import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);

Or adding from an Array/ or multiple literals; wrap to a list, first.

Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b));         // from an array variable
b.addAll( Arrays.asList( 8, 9, 10));  // from literals

To get the intersection:

// copies all from A;  then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print;   r.toString() implied.
System.out.println("A intersect B="+r);

Hope this answer helps. Vote for it!

How to generate java classes from WSDL file

i founded a great toool to auto parse and connect to web services

http://www.wsdl2code.com

http://www.wsdl2code.com/pages/Example.aspx

 SampleService srv1 = new SampleService();
     req = new Request();                     
     req.companyId = "1";
     req.userName = "userName";                                     
     req.password = "pas";
     Response response =    srv1.ServiceSample(req);

How can I find the dimensions of a matrix in Python?

As Ayman farhat mentioned you can use the simple method len(matrix) to get the length of rows and get the length of the first row to get the no. of columns using len(matrix[0]) :

>>> a=[[1,5,6,8],[1,2,5,9],[7,5,6,2]]
>>> len(a)
3
>>> len(a[0])
4

Also you can use a library that helps you with matrices "numpy":

>>> import numpy 
>>> numpy.shape(a)
(3,4)

how to read System environment variable in Spring applicationContext

Nowadays you can put

@Autowired
private Environment environment;

in your @Component, @Bean, etc., and then access the properties through the Environment class:

environment.getProperty("myProp");

For a single property in a @Bean

@Value("${my.another.property:123}") // value after ':' is the default
Integer property;

Another way are the handy @ConfigurationProperties beans:

@ConfigurationProperties(prefix="my.properties.prefix")
public class MyProperties {
  // value from my.properties.prefix.myProperty will be bound to this variable
  String myProperty;

  // and this will even throw a startup exception if the property is not found
  @javax.validation.constraints.NotNull
  String myRequiredProperty;

  //getters
}

@Component
public class MyOtherBean {
  @Autowired
  MyProperties myProperties;
}

Note: Just remember to restart eclipse after setting a new environment variable

how to set the background color of the whole page in css

Looks to me like you need to set the yellow on #doc3 and then get rid of the white that is called out on the #yui-main (which is covering up the color of the #doc3). This gets you yellow between header and footer.

Roblox Admin Command Script

for i=1,#target do
    game.Players.target[i].Character:BreakJoints()
end

Is incorrect, if "target" contains "FakeNameHereSoNoStalkers" then the run code would be:

game.Players.target.1.Character:BreakJoints()

Which is completely incorrect.


c = game.Players:GetChildren()

Never use "Players:GetChildren()", it is not guaranteed to return only players.

Instead use:

c = Game.Players:GetPlayers()

if msg:lower()=="me" then
    table.insert(people, source)
    return people

Here you add the player's name in the list "people", where you in the other places adds the player object.


Fixed code:

local Admins = {"FakeNameHereSoNoStalkers"}

function Kill(Players)
    for i,Player in ipairs(Players) do
        if Player.Character then
            Player.Character:BreakJoints()
        end
    end
end

function IsAdmin(Player)
    for i,AdminName in ipairs(Admins) do
        if Player.Name:lower() == AdminName:lower() then return true end
    end
    return false
end

function GetPlayers(Player,Msg)
    local Targets = {}
    local Players = Game.Players:GetPlayers()

    if Msg:lower() == "me" then
        Targets = { Player }
    elseif Msg:lower() == "all" then
        Targets = Players
    elseif Msg:lower() == "others" then
        for i,Plr in ipairs(Players) do
            if Plr ~= Player then
                table.insert(Targets,Plr)
            end
        end
    else
        for i,Plr in ipairs(Players) do
            if Plr.Name:lower():sub(1,Msg:len()) == Msg then
                table.insert(Targets,Plr)
            end
        end
    end
    return Targets
end

Game.Players.PlayerAdded:connect(function(Player)
    if IsAdmin(Player) then
        Player.Chatted:connect(function(Msg)
            if Msg:lower():sub(1,6) == ":kill " then
                Kill(GetPlayers(Player,Msg:sub(7)))
            end
        end)
    end
end)

How to check if all list items have the same value and return it, or return an “otherValue” if they don’t?

public int GetResult(List<int> list){
int first = list.First();
return list.All(x => x == first) ? first : SOME_OTHER_VALUE;
}

@Autowired - No qualifying bean of type found for dependency

I ran in to this recently, and as it turned out, I've imported the wrong annotation in my service class. Netbeans has an option to hide import statements, that's why I did not see it for some time.

I've used @org.jvnet.hk2.annotations.Service instead of @org.springframework.stereotype.Service.

Limit on the WHERE col IN (...) condition

Depending on the database engine you are using, there can be limits on the length of an instruction.

SQL Server has a very large limit:

http://msdn.microsoft.com/en-us/library/ms143432.aspx

ORACLE has a very easy to reach limit on the other side.

So, for large IN clauses, it's better to create a temp table, insert the values and do a JOIN. It works faster also.

Rails 4 - passing variable to partial

ou are able to create local variables once you call the render function on a partial, therefore if you want to customize a partial you can for example render the partial _form.html.erb by:

<%= render 'form', button_label: "Create New Event", url: new_event_url %>
<%= render 'form', button_label: "Update Event", url: edit_event_url %>

this way you can access in the partial to the label for the button and the URL, those are different if you try to create or update a record. finally, for accessing to this local variables you have to put in your code local_assigns[:button_label] (local_assigns[:name_of_your_variable])

<%=form_for(@event, url: local_assigns[:url]) do |f|  %>
<%= render 'shared/error_messages_events' %>
<%= f.label :title ,"Title"%>
  <%= f.text_field :title, class: 'form-control'%>
  <%=f.label :date, "Date"%>
  <%=f.date_field :date, class: 'form-control'  %>
  <%=f.label :description, "Description"%>
  <%=f.text_area :description, class: 'form-control'  %>
  <%= f.submit local_assigns[:button_label], class:"btn btn-primary"%>
<%end%>

Iterating through a List Object in JSP

 <c:forEach items="${sessionScope.empL}" var="emp">
            <tr>
                <td>Employee ID: <c:out value="${emp.eid}"/></td>
                <td>Employee Pass: <c:out value="${emp.ename}"/></td>  
            </tr>
        </c:forEach>

Laravel Checking If a Record Exists

you can use laravel validation if you want to insert a unique record:

$validated = $request->validate([
    'title' => 'required|unique:usersTable,emailAddress|max:255',
]);

But you use these ways also:

1:

if (User::where('email',  $request->email)->exists())
{
  // object exists
} else {
  // object not found
}

2:

$user = User::where('email',  $request->email)->first();

if ($user)
{
  // object exists
} else {
  // object not found
}

3:

$user = User::where('email',  $request->email)->first();

if ($user->isEmpty())
{
  // object exists
} else {
  // object not found
}

4:

$user = User::where('email',  $request->email)->firstOrCreate([
      'email' => 'email'
],$request->all());

Error: No default engine was specified and no extension was provided

You are missing the view engine, for example use jade:

change your

app.set('view engine', 'html');

with

app.set('view engine', 'jade');

If you want use a html friendly syntax use instead ejs

app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');

EDIT

As you can read from view.js Express View Module

module.exports = View;

/**
 * Initialize a new `View` with the given `name`.
 *
 * Options:
 *
 *   - `defaultEngine` the default template engine name
 *   - `engines` template engine require() cache
 *   - `root` root path for view lookup
 *
 * @param {String} name
 * @param {Object} options
 * @api private
 */

function View(name, options) {
  options = options || {};
  this.name = name;
  this.root = options.root;
  var engines = options.engines;
  this.defaultEngine = options.defaultEngine;
  var ext = this.ext = extname(name);
  if (!ext && !this.defaultEngine) throw new Error('No default engine was specified and no extension was provided.');
  if (!ext) name += (ext = this.ext = ('.' != this.defaultEngine[0] ? '.' : '') + this.defaultEngine);
  this.engine = engines[ext] || (engines[ext] = require(ext.slice(1)).__express);
  this.path = this.lookup(name);
}

You must have installed a default engine

Express search default layout view by program.template as you can read below:

mkdir(path + '/views', function(){
      switch (program.template) {
        case 'ejs':
          write(path + '/views/index.ejs', ejsIndex);
          break;
        case 'jade':
          write(path + '/views/layout.jade', jadeLayout);
          write(path + '/views/index.jade', jadeIndex);
          break;
        case 'jshtml':
          write(path + '/views/layout.jshtml', jshtmlLayout);
          write(path + '/views/index.jshtml', jshtmlIndex);
          break;
        case 'hjs':
          write(path + '/views/index.hjs', hoganIndex);
          break;

      }
    });

and as you can read below:

program.template = 'jade';
if (program.ejs) program.template = 'ejs';
if (program.jshtml) program.template = 'jshtml';
if (program.hogan) program.template = 'hjs';

the default view engine is jade

Properties private set;

Perhaps, you can have them marked as internal, and in this case only classes in your DAL or BL (assuming they are separate dlls) would be able to set it.

You could also supply a constructor that takes the fields and then only exposes them as properties.

Replacing few values in a pandas dataframe column with another value

loc function can be used to replace multiple values, Documentation for it : loc

df.loc[df['BrandName'].isin(['ABC', 'AB'])]='A'

How do I create a random alpha-numeric string in C++?

Let's make random convenient again!

I made up a nice C++11 header only solution. You could easily add one header file to your project and then add your tests or use random strings for another purposes.

That's a quick description, but you can follow the link to check full code. The main part of solution is in class Randomer:

class Randomer {
    // random seed by default
    std::mt19937 gen_;
    std::uniform_int_distribution<size_t> dist_;

public:
    /* ... some convenience ctors ... */

    Randomer(size_t min, size_t max, unsigned int seed = std::random_device{}())
        : gen_{seed}, dist_{min, max} {
    }

    // if you want predictable numbers
    void SetSeed(unsigned int seed) {
        gen_.seed(seed);
    }

    size_t operator()() {
        return dist_(gen_);
    }
};

Randomer incapsulates all random stuff and you can add your own functionality to it easily. After we have Randomer, it's very easy to generate strings:

std::string GenerateString(size_t len) {
    std::string str;
    auto rand_char = [](){ return alphabet[randomer()]; };
    std::generate_n(std::back_inserter(str), len, rand_char);
    return str;
}

Write your suggestions for improvement below. https://gist.github.com/VjGusev/e6da2cb4d4b0b531c1d009cd1f8904ad

Proxy with express.js

First install express and http-proxy-middleware

npm install express http-proxy-middleware --save

Then in your server.js

const express = require('express');
const proxy = require('http-proxy-middleware');

const app = express();
app.use(express.static('client'));

// Add middleware for http proxying 
const apiProxy = proxy('/api', { target: 'http://localhost:8080' });
app.use('/api', apiProxy);

// Render your site
const renderIndex = (req, res) => {
  res.sendFile(path.resolve(__dirname, 'client/index.html'));
}
app.get('/*', renderIndex);

app.listen(3000, () => {
  console.log('Listening on: http://localhost:3000');
});

In this example we serve the site on port 3000, but when a request end with /api we redirect it to localhost:8080.

http://localhost:3000/api/login redirect to http://localhost:8080/api/login

Python: find position of element in array

You should do:

try:
    value_index = my_list.index(value)
except:
    value_index = -1;

How do I pass along variables with XMLHTTPRequest

Following is correct way:

xmlhttp.open("GET","getuser.php?fname="+abc ,true);

Replacement for "rename" in dplyr

The next version of dplyr will support an improved version of select that also incorporates renaming:

> mtcars2 <- select( mtcars, disp2 = disp )
> head( mtcars2 )
                  disp2
Mazda RX4         160
Mazda RX4 Wag     160
Datsun 710        108
Hornet 4 Drive    258
Hornet Sportabout 360
Valiant           225
> changes( mtcars, mtcars2 )
Changed variables:
      old         new
disp  0x105500400
disp2             0x105500400

Changed attributes:
      old         new
names 0x106d2cf50 0x106d28a98

How could others, on a local network, access my NodeJS app while it's running on my machine?

I had this problem. The solution was to allow node.js through the server's firewall.

How to concatenate items in a list to a single string?

A more generic way to convert python lists to strings would be:

>>> my_lst = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
>>> my_lst_str = ''.join(map(str, my_lst))
>>> print(my_lst_str)
'12345678910'

Plot size and resolution with R markdown, knitr, pandoc, beamer

I think that is a frequently asked question about the behavior of figures in beamer slides produced from Pandoc and markdown. The real problem is, R Markdown produces PNG images by default (from knitr), and it is hard to get the size of PNG images correct in LaTeX by default (I do not know why). It is fairly easy, however, to get the size of PDF images correct. One solution is to reset the default graphical device to PDF in your first chunk:

```{r setup, include=FALSE}
knitr::opts_chunk$set(dev = 'pdf')
```

Then all the images will be written as PDF files, and LaTeX will be happy.

Your second problem is you are mixing up the HTML units with LaTeX units in out.width / out.height. LaTeX and HTML are very different technologies. You should not expect \maxwidth to work in HTML, or 200px in LaTeX. Especially when you want to convert Markdown to LaTeX, you'd better not set out.width / out.height (use fig.width / fig.height and let LaTeX use the original size).

How to completely remove borders from HTML table

For me I needed to do something like this to completely remove the borders from the table and all cells. This does not require modifying the HTML at all, which was helpful in my case.

table, tr, td {
    border: none;
}

JVM heap parameters

Apart from standard Heap parameters -Xms and -Xmx it's also good to know -XX:PermSize and -XX:MaxPermSize, which is used to specify size of Perm Gen space because even though you could have space in other generation in heap you can run out of memory if your perm gen space gets full. This link also has nice overview of some important JVM parameters.

How to create temp table using Create statement in SQL Server?

Same thing, Just start the table name with # or ##:

CREATE TABLE #TemporaryTable          -- Local temporary table - starts with single #
(
    Col1 int,
    Col2 varchar(10)
    ....
);

CREATE TABLE ##GlobalTemporaryTable   -- Global temporary table - note it starts with ##.
(
    Col1 int,
    Col2 varchar(10)
    ....
);

Temporary table names start with # or ## - The first is a local temporary table and the last is a global temporary table.

Here is one of many articles describing the differences between them.

Tick symbol in HTML/XHTML

although sets browser encoding to UTF-8

(If you're using numeric character references of course it doesn't matter what encoding is being used, browsers will get the correct Unicode codepoint directly from the number.)

<span style="font-family: wingdings; font-size: 200%;">&#252;</span>

I would appreciate if someone could check under FF on Windows. I am pretty sure it won't work on a non Windows box.

Fails for me in Firefox 3, Opera, and Safari. Curiously, works in the other Webkit browser, Chrome. Also fails on Linux (obviously, as Wingdings isn't installed there; it is installed on Macs, but that doesn't help you if Safari's not having it).

Also it's a pretty nasty hack — that character is to all intents and purposes “ü” and will appear that way to things like search engines, or if the text is copy-and-pasted. Proper Unicode code points are the way to go unless you really have no alternative.

The problem is that no font bundled with Windows supplies U+2713 CHECK MARK (‘?’). The only one that you're at all likely to find on a Windows machine is “Arial Unicode MS”, which is not really to be relied upon. So in the end I think you'll have to either:

  • use a different character which is better supported (eg. ‘?’ — bullet, as used by SO), or
  • use an image, with ‘?’ as the alt text.

How to sort an ArrayList in Java

Try BeanComparator from Apache Commons.

import org.apache.commons.beanutils.BeanComparator;


BeanComparator fieldComparator = new BeanComparator("fruitName");
Collections.sort(fruits, fieldComparator);

Good Free Alternative To MS Access

Much in line with Aurelio's answer, I now work in Ruby on Rails on some applications that I might formerly have done in MS Access. The back end database for a Rails App. is usually, MySql (works well enough and is available on most shared Web hosting) or PostgreSQL (the better choice when possible).

How do I vertical center text next to an image in html/css?

There are to ways: Use the attribute of the image tag align="absmiddle" or locate the image and the text in a container DIV or TD in a table and use

style="vertical-align:middle"

What is :: (double colon) in Python when subscripting sequences?

seq[::n] is a sequence of each n-th item in the entire sequence.

Example:

>>> range(10)[::2]
[0, 2, 4, 6, 8]

The syntax is:

seq[start:end:step]

So you can do (in Python 2):

>>> range(100)[5:18:2]
[5, 7, 9, 11, 13, 15, 17]

How do I add multiple conditions to "ng-disabled"?

Wanny is correct. The && operator doesn't work in HTML. With Angular, you must use the double pipes (||)for multiple conditions.

What causes: "Notice: Uninitialized string offset" to appear?

The error may occur when the number of times you iterate the array is greater than the actual size of the array. for example:

 $one="909";
 for($i=0;$i<10;$i++)
    echo ' '.$one[$i];

will show the error. first case u can take the mod of i.. for example

function mod($i,$length){
  $m = $i % $size;
  if ($m > $size)
  mod($m,$size)
  return $m;
}

for($i=0;$i<10;$i++)
{
  $k=mod($i,3);
  echo ' '.$one[$k];
}

or might be it not an array (maybe it was a value and you tried to access it like an array) for example:

$k = 2;
$k[0];

Changing background color of selected cell?

I created UIView and set the property of cell selectedBackgroundView:

UIView *v = [[UIView alloc] init];
v.backgroundColor = [UIColor redColor];
cell.selectedBackgroundView = v;

React JS Error: is not defined react/jsx-no-undef

You have to tell it which component you want to import by explicitly giving the class name..in your case it's Map

import Map from './Map';

class App extends Component{
    /*your code here...*/
}

Min / Max Validator in Angular 2 Final

Apparently, Angular had the max/min directives for template driven forms at some point but had to remove them in v4.2.0. You can read about the regression that caused the removal here: https://github.com/angular/angular/issues/17491

For now the only working solution that I know of is to use custom directive as @amd suggested. Here's how to use it with Bootstrap 4.

min-validator.directive.ts

import { Directive, Input } from '@angular/core'
import { NG_VALIDATORS, Validator, AbstractControl, Validators } from '@angular/forms'

@Directive({
  selector: '[min]',
  providers: [{ provide: NG_VALIDATORS, useExisting: MinDirective, multi: true }]
})
export class MinDirective implements Validator {

  @Input() min: number;

  validate(control: AbstractControl): { [key: string]: any } {    
    return Validators.min(this.min)(control)    
  }
}

And in your template:

<input type="number" [min]="minAge" #age="ngModel" [(ngModel)]="person.age" class="form-control" [ngClass]="{'is-invalid':age.invalid}">
<div *ngIf="age.invalid && (age.dirty || age.touched)" class="invalid-feedback">You need to be older than {{minAge}} to participate</div>

Hope this helps!

How to show "Done" button on iPhone number pad

I modified Bryan's solution to be a little more robust, so that it would play nicely with other types of keyboards that could appear in the same view. It's described here:

Create a DONE button on the iOS numpad UIKeyboard

I'd try to explain it here, but most of it is code to look at that wouldn't easily fit here

Understanding inplace=True

Yes, in Pandas we have many functions has the parameter inplace but by default it is assigned to False.

So, when you do df.dropna(axis='index', how='all', inplace=False) it thinks that you do not want to change the orignial DataFrame, therefore it instead creates a new copy for you with the required changes.

But, when you change the inplace parameter to True

Then it is equivalent to explicitly say that I do not want a new copy of the DataFrame instead do the changes on the given DataFrame

This forces the Python interpreter to not to create a new DataFrame

But you can also avoid using the inplace parameter by reassigning the result to the orignal DataFrame

df = df.dropna(axis='index', how='all')

Setting DEBUG = False causes 500 Error

I started to get the 500 for debug=False in the form of

django.urls.exceptions.NoReverseMatch: Reverse for 'home' not found.
or...
django.urls.exceptions.NoReverseMatch: Reverse for 'about' not found.

when raising django.core.exceptions.ValidationError instead of raising rest_framework.serializers.ValidationError

To be fair, it was already raising a 500 before, but as a ValidationError, with debug=False, this changed into the NoReverseMatch.

Why is it bad style to `rescue Exception => e` in Ruby?

TL;DR: Use StandardError instead for general exception catching. When the original exception is re-raised (e.g. when rescuing to log the exception only), rescuing Exception is probably okay.


Exception is the root of Ruby's exception hierarchy, so when you rescue Exception you rescue from everything, including subclasses such as SyntaxError, LoadError, and Interrupt.

Rescuing Interrupt prevents the user from using CTRLC to exit the program.

Rescuing SignalException prevents the program from responding correctly to signals. It will be unkillable except by kill -9.

Rescuing SyntaxError means that evals that fail will do so silently.

All of these can be shown by running this program, and trying to CTRLC or kill it:

loop do
  begin
    sleep 1
    eval "djsakru3924r9eiuorwju3498 += 5u84fior8u8t4ruyf8ihiure"
  rescue Exception
    puts "I refuse to fail or be stopped!"
  end
end

Rescuing from Exception isn't even the default. Doing

begin
  # iceberg!
rescue
  # lifeboats
end

does not rescue from Exception, it rescues from StandardError. You should generally specify something more specific than the default StandardError, but rescuing from Exception broadens the scope rather than narrowing it, and can have catastrophic results and make bug-hunting extremely difficult.


If you have a situation where you do want to rescue from StandardError and you need a variable with the exception, you can use this form:

begin
  # iceberg!
rescue => e
  # lifeboats
end

which is equivalent to:

begin
  # iceberg!
rescue StandardError => e
  # lifeboats
end

One of the few common cases where it’s sane to rescue from Exception is for logging/reporting purposes, in which case you should immediately re-raise the exception:

begin
  # iceberg?
rescue Exception => e
  # do some logging
  raise # not enough lifeboats ;)
end

What is default session timeout in ASP.NET?

  1. The Default Expiration Period for Session is 20 Minutes.
  2. The Default Expiration Period for Cookie is 30 Minutes.
  3. Maximum Size of ViewState is 25% of Page Size

Error: Failed to execute 'appendChild' on 'Node': parameter 1 is not of type 'Node'

It's actually a simple answer.

Your function is returning a string rather than the div node. appendChild can only append a node.

For example, if you try to appendChild the string:

var z = '<p>test satu dua tiga</p>'; // is a string 
document.body.appendChild(z);

The above code will never work. What will work is:

var z = document.createElement('p'); // is a node
z.innerHTML = 'test satu dua tiga';
document.body.appendChild(z);

Converting a generic list to a CSV string

For whatever reason, @AliUmair reverted the edit to his answer that fixes his code that doesn't run as is, so here is the working version that doesn't have the file access error and properly handles null object property values:

/// <summary>
/// Creates the CSV from a generic list.
/// </summary>;
/// <typeparam name="T"></typeparam>;
/// <param name="list">The list.</param>;
/// <param name="csvNameWithExt">Name of CSV (w/ path) w/ file ext.</param>;
public static void CreateCSVFromGenericList<T>(List<T> list, string csvCompletePath)
{
    if (list == null || list.Count == 0) return;

    //get type from 0th member
    Type t = list[0].GetType();
    string newLine = Environment.NewLine;

    if (!Directory.Exists(Path.GetDirectoryName(csvCompletePath))) Directory.CreateDirectory(Path.GetDirectoryName(csvCompletePath));

    using (var sw = new StreamWriter(csvCompletePath))
    {
        //make a new instance of the class name we figured out to get its props
        object o = Activator.CreateInstance(t);
        //gets all properties
        PropertyInfo[] props = o.GetType().GetProperties();

        //foreach of the properties in class above, write out properties
        //this is the header row
        sw.Write(string.Join(",", props.Select(d => d.Name).ToArray()) + newLine);

        //this acts as datarow
        foreach (T item in list)
        {
            //this acts as datacolumn
            var row = string.Join(",", props.Select(d => $"\"{item.GetType().GetProperty(d.Name).GetValue(item, null)?.ToString()}\"")
                                                    .ToArray());
            sw.Write(row + newLine);

        }
    }
}

How to validate an email address in JavaScript

If you're using Closure you can use the built-in goog.format.EmailAddress type:

http://docs.closure-library.googlecode.com/git/class_goog_format_EmailAddress.html

For example:

goog.format.EmailAddress.isValidAddrSpec("[email protected]")

Note that by reading the source (linked above) you can see the comments state that IDN are not supported and that it only aims to cover most addresses:

// This is a fairly naive implementation, but it covers 99% of use cases.
// For more details, see http://en.wikipedia.org/wiki/Email_address#Syntax
// TODO(mariakhomenko): we should also be handling i18n domain names as per
// http://en.wikipedia.org/wiki/Internationalized_domain_name

convert array into DataFrame in Python

In general you can use pandas rename function here. Given your dataframe you could change to a new name like this. If you had more columns you could also rename those in the dictionary. The 0 is the current name of your column

import pandas as pd    
import numpy as np   
e = np.random.normal(size=100)  
e_dataframe = pd.DataFrame(e)      

e_dataframe.rename(index=str, columns={0:'new_column_name'})

Get Category name from Post ID

Use get_the_category() function.

$post_categories = wp_get_post_categories( 4 );
$categories = get_the_category($post_categories[0]);
var_dump($categories);

Credit card expiration dates - Inclusive or exclusive?

lots of big companies dont even use your expiration date anymore because it causes auto-renewal of payments to be lost when cards are issued with new expiration dates and the same account number. This has been a huge problem in the service industry, so these companies have cornered the card issuers into processing payments w/o expiration dates to avoid this pitfall. Not many people know about this yet, so not all companies use this practice.

Call an overridden method from super class in typescript

below is an generic example

    //base class
    class A {
        
        // The virtual method
        protected virtualStuff1?():void;
    
        public Stuff2(){
            //Calling overridden child method by parent if implemented
            this.virtualStuff1 && this.virtualStuff1();
            alert("Baseclass Stuff2");
        }
    }
    
    //class B implementing virtual method
    class B extends A{
        
        // overriding virtual method
        public virtualStuff1()
        {
            alert("Class B virtualStuff1");
        }
    }
    
    //Class C not implementing virtual method
    class C extends A{
     
    }
    
    var b1 = new B();
    var c1= new C();
    b1.Stuff2();
    b1.virtualStuff1();
    c1.Stuff2();

How to get response body using HttpURLConnection, when code other than 2xx is returned?

Wrong method was used for errors, here is the working code:

BufferedReader br = null;
if (100 <= conn.getResponseCode() && conn.getResponseCode() <= 399) {
    br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} else {
    br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
}

How to encode the filename parameter of Content-Disposition header in HTTP?

We had a similar problem in a web application, and ended up by reading the filename from the HTML <input type="file">, and setting that in the url-encoded form in a new HTML <input type="hidden">. Of course we had to remove the path like "C:\fakepath\" that is returned by some browsers.

Of course this does not directly answer OPs question, but may be a solution for others.

Adobe Acrobat Pro make all pages the same dimension

The page sizes are looking different in your PDF because the images were originally set to different DPI (even if images are identical HxW in pixels). The good news is - it's only a display issue - and can be fixed easily.

An image with a higher DPI value would display smaller in a PDF (displays at the 'print-size' of the image). To avoid this, open each image in an image editor like GIMP or Photoshop. Open relevant image print control dialog box and set a suitable uniform DPI info for all the images. Remake the PDF with these new images. If in the new PDF images are too big - redo the DPI setting for each to a higher value. If in the new PDF pages are too small to read on-screen without zooming, again - redo DPI adjustment, this time put a lower DPI value. Ideally, 150 DPI should be good enough for images of 2500X2500 pixel - on a 17 inch monitor set to 1366x768 resolution.

BTW, the PDF file shall print each page at the specified DPI of that page. If all images are same DPI, you'll get a uniform printing.

Hope this helps :)

How Long Does it Take to Learn Java for a Complete Newbie?

My experience in Java programming for beginner is not difficult to learn; however it is really depended on how your object-oriented programming skills are. As you posed that you had no programming experience , I guess that I recommend a web site, http://www.exampledepot.com/ , and type any java keyword such as Swing, FileInputStream, it provides a lot of practical examples that you can apply into a project.

Please, buy a java book (Sams'java 6 in 24 hours) as reference. It will give you really basic skills for java within a short time. and I sure you will have enough time to learn about the java and J2ME within 10 weeks. Good Luck.

Tiger

Convert int (number) to string with leading zeros? (4 digits)

Use String.PadLeft like this:

var result = input.ToString().PadLeft(length, '0');

Shell Script: How to write a string to file and to stdout on console?

Use the tee command:

echo "hello" | tee logfile.txt

PostgreSQL unnest() with element number

unnest2() as exercise

Older versions before pg v8.4 need a user-defined unnest(). We can adapt this old function to return elements with an index:

CREATE FUNCTION unnest2(anyarray)
  RETURNS setof record  AS
$BODY$
  SELECT $1[i], i
  FROM   generate_series(array_lower($1,1),
                         array_upper($1,1)) i;
$BODY$ LANGUAGE sql IMMUTABLE;

Send multiple checkbox data to PHP via jQuery ajax()

var myCheckboxes = new Array();
$("input:checked").each(function() {
   data['myCheckboxes[]'].push($(this).val());
});

You are pushing checkboxes to wrong array data['myCheckboxes[]'] instead of myCheckboxes.push

Exact time measurement for performance testing

A better way is to use the Stopwatch class:

using System.Diagnostics;
// ...

Stopwatch sw = new Stopwatch();

sw.Start();

// ...

sw.Stop();

Console.WriteLine("Elapsed={0}",sw.Elapsed);

How to format font style and color in echo

You should also use the style 'color' and not 'font-color'

<?php

foreach($months as $key => $month){
  if(strpos($filename,$month)!==false){
        echo "<style = 'color: #ff0000;'> Movie List for {$key} 2013 </style>";
    }
}

?>

In general, the comments on double and single quotes are correct in other suggestions. $Variables only execute in double quotes.

How to send a simple email from a Windows batch file?

Max is on he right track with the suggestion to use Windows Scripting for a way to do it without installing any additional executables on the machine. His code will work if you have the IIS SMTP service setup to forward outbound email using the "smart host" setting, or the machine also happens to be running Microsoft Exchange. Otherwise if this is not configured, you will find your emails just piling up in the message queue folder (\inetpub\mailroot\queue). So, unless you can configure this service, you also want to be able to specify the email server you want to use to send the message with. To do that, you can do something like this in your windows script file:

Set objMail = CreateObject("CDO.Message")
Set objConf = CreateObject("CDO.Configuration")
Set objFlds = objConf.Fields
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendusing") = 2 'cdoSendUsingPort
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpserver") = "smtp.your-site-url.com" 'your smtp server domain or IP address goes here
objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpserverport") = 25 'default port for email
'uncomment next three lines if you need to use SMTP Authorization
'objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendusername") = "your-username"
'objFlds.Item("http://schemas.microsoft.com/cdo/configuration/sendpassword") = "your-password"
'objFlds.Item("http://schemas.microsoft.com/cdo/configuration/smtpauthenticate") = 1 'cdoBasic
objFlds.Update
objMail.Configuration = objConf
objMail.FromName = "Your Name"
objMail.From = "[email protected]"
objMail.To = "[email protected]"
objMail.Subject = "Email Subject Text"
objMail.TextBody = "The message of the email..."
objMail.Send
Set objFlds = Nothing
Set objConf = Nothing
Set objMail = Nothing

GetElementByID - Multiple IDs

No, it won't work.

document.getElementById() method accepts only one argument.

However, you may always set classes to the elements and use getElementsByClassName() instead. Another option for modern browsers is to use querySelectorAll() method:

document.querySelectorAll("#myCircle1, #myCircle2, #myCircle3, #myCircle4");

How do I implement __getattribute__ without an infinite recursion error?

You get a recursion error because your attempt to access the self.__dict__ attribute inside __getattribute__ invokes your __getattribute__ again. If you use object's __getattribute__ instead, it works:

class D(object):
    def __init__(self):
        self.test=20
        self.test2=21
    def __getattribute__(self,name):
        if name=='test':
            return 0.
        else:
            return object.__getattribute__(self, name)

This works because object (in this example) is the base class. By calling the base version of __getattribute__ you avoid the recursive hell you were in before.

Ipython output with code in foo.py:

In [1]: from foo import *

In [2]: d = D()

In [3]: d.test
Out[3]: 0.0

In [4]: d.test2
Out[4]: 21

Update:

There's something in the section titled More attribute access for new-style classes in the current documentation, where they recommend doing exactly this to avoid the infinite recursion.

How to change Rails 3 server default port in develoment?

You could install $ gem install foreman, and use foreman to start your server as defined in your Procfile like:

web: bundle exec rails -p 10524

You can check foreman gem docs here: https://github.com/ddollar/foreman for more info

The benefit of this approach is not only can you set/change the port in the config easily and that it doesn't require much code to be added but also you can add different steps in the Procfile that foreman will run for you so you don't have to go though them each time you want to start you application something like:

bundle: bundle install
web: bundle exec rails -p 10524
...
...

Cheers

Run a string as a command within a Bash script

For me echo XYZ_20200824.zip | grep -Eo '[[:digit:]]{4}[[:digit:]]{2}[[:digit:]]{2}' was working fine but unable to store output of command into variable. I had same issue I tried eval but didn't got output.

Here is answer for my problem: cmd=$(echo XYZ_20200824.zip | grep -Eo '[[:digit:]]{4}[[:digit:]]{2}[[:digit:]]{2}')

echo $cmd

My output is now 20200824

How to set an HTTP proxy in Python 2.7?

On my network just setting http_proxy didn't work for me. The following points were relevant.

1 Setting http_proxy for your user wont be preserved when you execute sudo - to preserve it, do:

sudo -E yourcommand

I got my install working by first installing cntlm local proxy. The instructions here is succinct : http://www.leg.uct.ac.za/howtos/use-isa-proxies

Instead of student number, you'd put your domain username

2 To use the cntlm local proxy, exec:

pip install --proxy localhost:3128 pygments

How to resolve Error listenerStart when deploying web-app in Tomcat 5.5?

/var/lib/tomcat5.5/webapps/spaghetti/WEB-INF/lib/jsp-api-6.0.16.jar
/var/lib/tomcat5.5/webapps/spaghetti/WEB-INF/lib/servlet-api-6.0.16.jar

You should not have any server-specific libraries in the /WEB-INF/lib. Leave them in the appserver's own library. It would only lead to collisions in the classpath. Get rid of all appserver-specific libraries in /WEB-INF/lib (and also in JRE/lib and JRE/lib/ext if you have placed any of them there).

A common cause that the appserver-specific libraries are included in the webapp's library is that starters think that it is the right way to fix compilation errors of among others the javax.servlet classes not being resolveable. Putting them in webapp's library is the wrong solution. You should reference them in the classpath during compilation, i.e. javac -cp /path/to/server/lib/servlet.jar and so on, or if you're using an IDE, you should integrate the server in the IDE and associate the web project with the server. The IDE will then automatically take server-specific libraries in the classpath (buildpath) of the webapp project.

How to npm install to a specified directory?

As of npm version 3.8.6, you can use

npm install --prefix ./install/here <package>

to install in the specified directory. NPM automatically creates node_modules folder even when a node_modules directory already exists in the higher up hierarchy. You can also have a package.json in the current directory and then install it in the specified directory using --prefix option:

npm install --prefix ./install/here

As of npm 6.0.0, you can use

npm install --prefix ./install/here ./

to install the package.json in current directory to "./install/here" directory. There is one thing that I have noticed on Mac that it creates a symlink to parent folder inside the node_modules directory. But, it still works.

NOTE: NPM honours the path that you've specified through the --prefix option. It resolves as per npm documentation on folders, only when npm install is used without the --prefix option.

How do I use an image as a submit button?

Use an image type input:

<input type="image" src="/Button1.jpg" border="0" alt="Submit" />

The full HTML:

_x000D_
_x000D_
<form id='formName' name='formName' onsubmit='redirect();return false;'>_x000D_
  <div class="style7">_x000D_
    <input type='text' id='userInput' name='userInput' value=''>_x000D_
    <input type="image" name="submit" src="https://jekyllcodex.org/uploads/grumpycat.jpg" border="0" alt="Submit" style="width: 50px;" />_x000D_
  </div>_x000D_
</form> 
_x000D_
_x000D_
_x000D_

Issue pushing new code in Github

if you use the git for mac in GUI you can chose Respository->Pull or the "comm+shift+p" to "git pull" first, then publish the source.

Adding Lombok plugin to IntelliJ project

For me it didn't work after doing all of the steps suggested in the question and in the top answer. Initially the import didn't work, and then when I restarted IntelliJ, I got these messages from the Gradle Plugin:

Gradle DSL method not found: 'annotationProcessor()'
Possible causes:<ul><li>The project 'wq-handler-service' may be using a version of the Android Gradle plug-in that does not contain the method (e.g. 'testCompile' was added in 1.1.0).
Upgrade plugin to version 2.3.2 and sync project</li><li>The project 'wq-handler-service' may be using a version of Gradle that does not contain the method.
Open Gradle wrapper file</li><li>The build file may be missing a Gradle plugin.
Apply Gradle plugin</li>

This was weird because I don't develop for Android, just using IntelliJ for Mac OS.

To be fair, my build.gradle file had these lines in the dependencies section, which I copied from a colleague:

compileOnly group: 'org.projectlombok', name: 'lombok', version: '1.16.20'
annotationProcessor group: 'org.projectlombok', name: 'lombok', version: '1.16.20'

After checking versions, the only thing that completely solved my problem was adding the below to the plugins section of build.gradle, which I found on this page:

id 'net.ltgt.apt' version '0.15'

Looks like it's a

Gradle plugin making it easier/safer to use Java annotation processors

(ltgt plugin page)

XOR operation with two strings in java

Pay attention:

A Java char corresponds to a UTF-16 code unit, and in some cases two consecutive chars (a so-called surrogate pair) are needed for one real Unicode character (codepoint).

XORing two valid UTF-16 sequences (i.e. Java Strings char by char, or byte by byte after encoding to UTF-16) does not necessarily give you another valid UTF-16 string - you may have unpaired surrogates as a result. (It would still be a perfectly usable Java String, just the codepoint-concerning methods could get confused, and the ones that convert to other encodings for output and similar.)

The same is valid if you first convert your Strings to UTF-8 and then XOR these bytes - here you quite probably will end up with a byte sequence which is not valid UTF-8, if your Strings were not already both pure ASCII strings.

Even if you try to do it right and iterate over your two Strings by codepoint and try to XOR the codepoints, you can end up with codepoints outside the valid range (for example, U+FFFFF (plane 15) XOR U+10000 (plane 16) = U+1FFFFF (which would the last character of plane 31), way above the range of existing codepoints. And you could also end up this way with codepoints reserved for surrogates (= not valid ones).

If your strings only contain chars < 128, 256, 512, 1024, 2048, 4096, 8192, 16384, or 32768, then the (char-wise) XORed strings will be in the same range, and thus certainly not contain any surrogates. In the first two cases you could also encode your String as ASCII or Latin-1, respectively, and have the same XOR-result for the bytes. (You still can end up with control chars, which may be a problem for you.)


What I'm finally saying here: don't expect the result of encrypting Strings to be a valid string again - instead, simply store and transmit it as a byte[] (or a stream of bytes). (And yes, convert to UTF-8 before encrypting, and from UTF-8 after decrypting).

Evaluate list.contains string in JSTL

Sadly, I think that JSTL doesn't support anything but an iteration through all elements to figure this out. In the past, I've used the forEach method in the core tag library:

<c:set var="contains" value="false" />
<c:forEach var="item" items="${myList}">
  <c:if test="${item eq myValue}">
    <c:set var="contains" value="true" />
  </c:if>
</c:forEach>

After this runs, ${contains} will be equal to "true" if myList contained myValue.

What does the 'u' symbol mean in front of string values?

This is a feature, not a bug.

See http://docs.python.org/howto/unicode.html, specifically the 'unicode type' section.

Bootstrap 4 Center Vertical and Horizontal Alignment

From the doc (bootsrap 4):

https://getbootstrap.com/docs/4.0/utilities/flex/#justify-content

.justify-content-start
.justify-content-end
.justify-content-center
.justify-content-between
.justify-content-around
.justify-content-sm-start
.justify-content-sm-end
.justify-content-sm-center
.justify-content-sm-between
.justify-content-sm-around
.justify-content-md-start
.justify-content-md-end
.justify-content-md-center
.justify-content-md-between
.justify-content-md-around
.justify-content-lg-start
.justify-content-lg-end
.justify-content-lg-center
.justify-content-lg-between
.justify-content-lg-around
.justify-content-xl-start
.justify-content-xl-end
.justify-content-xl-center
.justify-content-xl-between
.justify-content-xl-around

What do the icons in Eclipse mean?

I can't find a way to create a table with icons in SO, so I am uploading 2 images. Objects Icons

Decorator icons

Losing scope when using ng-include

As @Renan mentioned, ng-include creates a new child scope. This scope prototypically inherits (see dashed lines below) from the HomeCtrl scope. ng-model="lineText" actually creates a primitive scope property on the child scope, not HomeCtrl's scope. This child scope is not accessible to the parent/HomeCtrl scope:

ng-include scope

To store what the user typed into HomeCtrl's $scope.lines array, I suggest you pass the value to the addLine function:

 <form ng-submit="addLine(lineText)">

In addition, since lineText is owned by the ngInclude scope/partial, I feel it should be responsible for clearing it:

 <form ng-submit="addLine(lineText); lineText=''">

Function addLine() would thus become:

$scope.addLine = function(lineText) {
    $scope.chat.addLine(lineText);
    $scope.lines.push({
        text: lineText
    });
};

Fiddle.

Alternatives:

  • define an object property on HomeCtrl's $scope, and use that in the partial: ng-model="someObj.lineText; fiddle
  • not recommended, this is more of a hack: use $parent in the partial to create/access a lineText property on the HomeCtrl $scope:  ng-model="$parent.lineText"; fiddle

It is a bit involved to explain why the above two alternatives work, but it is fully explained here: What are the nuances of scope prototypal / prototypical inheritance in AngularJS?

I don't recommend using this in the addLine() function. It becomes much less clear which scope is being accessed/manipulated.

Validate phone number using angular js

use ng-intl-tel-input to validate mobile numbers for all countries. you can set default country also. on npm: https://www.npmjs.com/package/ng-intl-tel-input

more details: https://techpituwa.wordpress.com/2017/03/29/angular-js-phone-number-validation-with-ng-intl-tel-input/

Correlation between two vectors?

Try xcorr, it's a built-in function in MATLAB for cross-correlation:

c = xcorr(A_1, A_2);

However, note that it requires the Signal Processing Toolbox installed. If not, you can look into the corrcoef command instead.

Convert negative data into positive data in SQL Server

Use the absolute value function ABS. The syntax is

ABS ( numeric_expression )

How do I install Composer on a shared hosting?

I was able to install composer on HostGator's shared hosting. Logged in to SSH with Putty, right after login you should be in your home directory, which is usually /home/username, where username is your username obviously. Then ran the curl command posted by @niutech above. This downloaded the composer to my home directory and it's now accessible and working well.

PHP cURL error code 60

php --ini

This will tell you exactly which php.ini file is being loaded, so you know which one to modify. I wasted a lot of time changing the wrong php.ini file because I had WAMP and XAMPP installed.

Also, don't forget to restart the WAMP server (or whatever you use) after changing php.ini.

How to check if internet connection is present in Java?

If you're on java 6 can use NetworkInterface to check for available network interfaces. I.e. something like this:

Enumeration<NetworkInterface> interfaces = NetworkInterface.getNetworkInterfaces();
while (interfaces.hasMoreElements()) {
  NetworkInterface interf = interfaces.nextElement();
  if (interf.isUp() && !interf.isLoopback())
    return true;
}

Haven't tried it myself, yet.

Is there an equivalent of 'which' on the Windows command line?

For you Windows XP users (who have no where command built-in), I have written a "where like" command as a rubygem called whichr.

To install it, install Ruby.

Then

gem install whichr

Run it like:

C:> whichr cmd_here

Makefile - missing separator

You need to precede the lines starting with gcc and rm with a hard tab. Commands in make rules are required to start with a tab (unless they follow a semicolon on the same line). The result should look like this:

PROG = semsearch
all: $(PROG)
%: %.c
        gcc -o $@ $< -lpthread

clean:
        rm $(PROG)

Note that some editors may be configured to insert a sequence of spaces instead of a hard tab. If there are spaces at the start of these lines you'll also see the "missing separator" error. If you do have problems inserting hard tabs, use the semicolon way:

PROG = semsearch
all: $(PROG)
%: %.c ; gcc -o $@ $< -lpthread

clean: ; rm $(PROG)