Programs & Examples On #Pearson

in statistics, Pearson's r, the Pearson product moment correlation coefficient, shows the extent of a linear relationship between two data sets on a scale from -1 to 1.

ValueError: shape mismatch: objects cannot be broadcast to a single shape

This particular error implies that one of the variables being used in the arithmetic on the line has a shape incompatible with another on the same line (i.e., both different and non-scalar). Since n and the output of np.add.reduce() are both scalars, this implies that the problem lies with xm and ym, the two of which are simply your x and y inputs minus their respective means.

Based on this, my guess is that your x and y inputs have different shapes from one another, making them incompatible for element-wise multiplication.

** Technically, it's not that variables on the same line have incompatible shapes. The only problem is when two variables being added, multiplied, etc., have incompatible shapes, whether the variables are temporary (e.g., function output) or not. Two variables with different shapes on the same line are fine as long as something else corrects the issue before the mathematical expression is evaluated.

Extracting Ajax return data in jQuery

on success: function (response) { alert(response.d); }

Filename too long in Git for Windows

git config --global core.longpaths true

The above command worked for me. Using '--system' gave me config file not locked error

Pretty-Printing JSON with PHP

Gluing several answers together fit my need for existing json:

Code:
echo "<pre>"; 
echo json_encode(json_decode($json_response), JSON_PRETTY_PRINT); 
echo "</pre>";

Output:
{
    "data": {
        "token_type": "bearer",
        "expires_in": 3628799,
        "scopes": "full_access",
        "created_at": 1540504324
    },
    "errors": [],
    "pagination": {},
    "token_type": "bearer",
    "expires_in": 3628799,
    "scopes": "full_access",
    "created_at": 1540504324
}

How to properly use jsPDF library

You only need this link jspdf.min.js

It has everything in it.

<script src="https://cdnjs.cloudflare.com/ajax/libs/jspdf/1.3.2/jspdf.min.js"></script>

Create <div> and append <div> dynamically

window.onload = function() {
  var iDiv = document.createElement('div');
  iDiv.id = 'block';
  iDiv.className = 'block';
  document.body.appendChild(iDiv);

  var iiDiv = document.createElement('div');
  iiDiv.className = 'block-2';

  var s = document.getElementById('block');
  s.appendChild(iiDiv);
}

CURRENT_DATE/CURDATE() not working as default DATE value

----- 2016-07-04 MariaDB 10.2.1 -- Release Note -- -----

Support for DEFAULT with expressions (MDEV-10134).

----- 2018-10-22 8.0.13 General Availability -- -- -----

MySQL now supports use of expressions as default values in data type specifications. This includes the use of expressions as default values for the BLOB, TEXT, GEOMETRY, and JSON data types, which previously could not be assigned default values at all. For details, see Data Type Default Values.

Change a Rails application to production

If you're running on Passenger, then the default is to run in production, in your apache conf:

<VirtualHost *:80>
  ServerName application_name.rails.local
  DocumentRoot "/Users/rails/application_name/public"
  RailsEnv production ## This is the default
</VirtualHost>

If you're just running a local server with mongrel or webrick, you can do:

./script/server -e production

or in bash:

RAILS_ENV=production ./script/server

actually overriding the RAILS_ENV constant in the enviornment.rb should probably be your last resort, as it's probably not going to stay set (see another answer I gave on that)

ImageView rounded corners

Create a Drawable XML file

<shape xmlns:android="http://schemas.android.com/apk/res/android"
        android:shape="rectangle">
        <corners android:radius="8dp" />
       <solid android:color="@android:color/white" />
<stroke
    android:width="1dp"
    android:color="@color/md_white_1000" />

In your layout you add the drawable as a background on the imageView.

    <ImageView
        android:layout_width="200dp"
        android:layout_height="200dp"
        android:src="@drawable/photo"
        android:background="@drawable/roundcorners"/>

Then you add this line in your Java code.

ImageView.setClipToOutline(true);

Note: this only works with level 21+

What is the difference between java and core java?

According to some developers, "Core Java" refers to package API java.util.*, which is mostly used in coding.

The term "Core Java" is not defined by Sun, it's just a slang definition.

J2ME / J2EE still depend on J2SDK API's for compilation and execution.

Nobody would say java.util.* is separated from J2SDK for usage.

append multiple values for one key in a dictionary

If you want a (almost) one-liner:

from collections import deque

d = {}
deque((d.setdefault(year, []).append(value) for year, value in source_of_data), maxlen=0)

Using dict.setdefault, you can encapsulate the idea of "check if the key already exists and make a new list if not" into a single call. This allows you to write a generator expression which is consumed by deque as efficiently as possible since the queue length is set to zero. The deque will be discarded immediately and the result will be in d.

This is something I just did for fun. I don't recommend using it. There is a time and a place to consume arbitrary iterables through a deque, and this is definitely not it.

Resource interpreted as Document but transferred with MIME type application/zip

I had a similar issue when performing a file download through Javascript. Adding the download attribute made no difference but adding target='_blank' did - I no longer get the 'Resource interpreted as Document...' console message.

Here's my nicely simple code:

var link = document.createElement('a');
link.target = '_blank';
link.href = url;
document.body.appendChild(link); // Required for Firefox
link.click();
link.remove(); 

I haven't tried it with direct HTML but would expect it to work.

Note I discovered that Firefox requires the link to be appended to the document whereas Chrome will work without it.

javac: file not found: first.java Usage: javac <options> <source files>

So I had the same problem because I wasn't in the right directory where my file was located. So when I ran javac Example.java (for me) it said it couldn't find it. But I needed to go to where my Example.java file was located. So I used the command cd and right after that the location of the file. That worked for me. Tell me if it helps! Thanks!

Is it possible to set the equivalent of a src attribute of an img tag in CSS?

No you can't set the image src attribute via CSS. The closest you can get is, as you say, background or background-image. I wouldn't recommend doing that anyway as it would be somewhat illogical.

However, there is a CSS3 solution available to you, if the browsers you're targeting are able to use it. Use content:url as described in Pacerier's answer. You can find other, cross-browser solutions in the other answers below.

Where to put default parameter value in C++?

the declaration is generally the most 'useful', but that depends on how you want to use the class.

both is not valid.

Get an object's class name at runtime

Solution using Decorators that survives minification/uglification

We use code generation to decorate our Entity classes with metadata like so:

@name('Customer')
export class Customer {
  public custId: string;
  public name: string;
}

Then consume with the following helper:

export const nameKey = Symbol('name');

/**
 * To perserve class name though mangling.
 * @example
 * @name('Customer')
 * class Customer {}
 * @param className
 */
export function name(className: string): ClassDecorator {
  return (Reflect as any).metadata(nameKey, className);
}

/**
 * @example
 * const type = Customer;
 * getName(type); // 'Customer'
 * @param type
 */
export function getName(type: Function): string {
  return (Reflect as any).getMetadata(nameKey, type);
}

/**
 * @example
 * const instance = new Customer();
 * getInstanceName(instance); // 'Customer'
 * @param instance
 */
export function getInstanceName(instance: Object): string {
  return (Reflect as any).getMetadata(nameKey, instance.constructor);
}

Extra info:

  • You may need to install reflect-metadata
  • reflect-metadata is pollyfill written by members ot TypeScript for the proposed ES7 Reflection API
  • The proposal for decorators in JS can be tracked here

Find when a file was deleted in Git

Git log but you need to prefix the path with --

Eg:

dan-mac:test dani$ git log file1.txt
fatal: ambiguous argument 'file1.txt': unknown revision or path not in the working tree.

dan-mac:test dani$ git log -- file1.txt
 commit 0f7c4e1c36e0b39225d10b26f3dea40ad128b976
 Author: Daniel Palacio <[email protected]>
 Date:   Tue Jul 26 23:32:20 2011 -0500

 foo

How do I start my app on startup?

Listen for the ACTION_BOOT_COMPLETE and do what you need to from there. There is a code snippet here.

Update:

Original link on answer is down, so based on the comments, here it is linked code, because no one would ever miss the code when the links are down.

In AndroidManifest.xml (application-part):

<receiver android:enabled="true" android:name=".BootUpReceiver"
        android:permission="android.permission.RECEIVE_BOOT_COMPLETED">

        <intent-filter>
                <action android:name="android.intent.action.BOOT_COMPLETED" />
                <category android:name="android.intent.category.DEFAULT" />
        </intent-filter>
</receiver>

...

<uses-permission android:name="android.permission.RECEIVE_BOOT_COMPLETED" />

...

public class BootUpReceiver extends BroadcastReceiver{

        @Override
        public void onReceive(Context context, Intent intent) {
                Intent i = new Intent(context, MyActivity.class);  //MyActivity can be anything which you want to start on bootup...
                i.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                context.startActivity(i);  
        }

}

Source: https://web.archive.org/web/20150520124552/http://www.androidsnippets.com/autostart-an-application-at-bootup

java.net.MalformedURLException: no protocol

Try instead of db.parse(xml):

Document doc = db.parse(new InputSource(new StringReader(**xml**)));

Creating a script for a Telnet session?

This vbs script reloads a cisco switch, make sure telnet is installed on windows.

Option explicit
Dim oShell
set oShell= Wscript.CreateObject("WScript.Shell")
oShell.Run "telnet"
WScript.Sleep 1000
oShell.Sendkeys "open 172.25.15.9~"
WScript.Sleep 1000
oShell.Sendkeys "password~"
WScript.Sleep 1000
oShell.Sendkeys "en~"
WScript.Sleep 1000
oShell.Sendkeys "password~"
WScript.Sleep 1000
oShell.Sendkeys "reload~"
WScript.Sleep 1000
oShell.Sendkeys "~"
Wscript.Quit

Java SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ss'Z'") gives timezone as IST

and if you don't have the option to go on java8 better use 'yyyy-MM-dd'T'HH:mm:ssXXX' as this gets correctly parsed again (while with only one X this may not be the case... depending on your parsing function)

X generates: +01

XXX generates: +01:00

Imshow: extent and aspect

From plt.imshow() official guide, we know that aspect controls the aspect ratio of the axes. Well in my words, the aspect is exactly the ratio of x unit and y unit. Most of the time we want to keep it as 1 since we do not want to distort out figures unintentionally. However, there is indeed cases that we need to specify aspect a value other than 1. The questioner provided a good example that x and y axis may have different physical units. Let's assume that x is in km and y in m. Hence for a 10x10 data, the extent should be [0,10km,0,10m] = [0, 10000m, 0, 10m]. In such case, if we continue to use the default aspect=1, the quality of the figure is really bad. We can hence specify aspect = 1000 to optimize our figure. The following codes illustrate this method.

%matplotlib inline
import numpy as np
import matplotlib.pyplot as plt
rng=np.random.RandomState(0)
data=rng.randn(10,10)
plt.imshow(data, origin = 'lower',  extent = [0, 10000, 0, 10], aspect = 1000)

enter image description here

Nevertheless, I think there is an alternative that can meet the questioner's demand. We can just set the extent as [0,10,0,10] and add additional xy axis labels to denote the units. Codes as follows.

plt.imshow(data, origin = 'lower',  extent = [0, 10, 0, 10])
plt.xlabel('km')
plt.ylabel('m')

enter image description here

To make a correct figure, we should always bear in mind that x_max-x_min = x_res * data.shape[1] and y_max - y_min = y_res * data.shape[0], where extent = [x_min, x_max, y_min, y_max]. By default, aspect = 1, meaning that the unit pixel is square. This default behavior also works fine for x_res and y_res that have different values. Extending the previous example, let's assume that x_res is 1.5 while y_res is 1. Hence extent should equal to [0,15,0,10]. Using the default aspect, we can have rectangular color pixels, whereas the unit pixel is still square!

plt.imshow(data, origin = 'lower',  extent = [0, 15, 0, 10])
# Or we have similar x_max and y_max but different data.shape, leading to different color pixel res.
data=rng.randn(10,5)
plt.imshow(data, origin = 'lower',  extent = [0, 5, 0, 5])

enter image description here enter image description here

The aspect of color pixel is x_res / y_res. setting its aspect to the aspect of unit pixel (i.e. aspect = x_res / y_res = ((x_max - x_min) / data.shape[1]) / ((y_max - y_min) / data.shape[0])) would always give square color pixel. We can change aspect = 1.5 so that x-axis unit is 1.5 times y-axis unit, leading to a square color pixel and square whole figure but rectangular pixel unit. Apparently, it is not normally accepted.

data=rng.randn(10,10)
plt.imshow(data, origin = 'lower',  extent = [0, 15, 0, 10], aspect = 1.5)

enter image description here

The most undesired case is that set aspect an arbitrary value, like 1.2, which will lead to neither square unit pixels nor square color pixels.

plt.imshow(data, origin = 'lower',  extent = [0, 15, 0, 10], aspect = 1.2)

enter image description here

Long story short, it is always enough to set the correct extent and let the matplotlib do the remaining things for us (even though x_res!=y_res)! Change aspect only when it is a must.

Docker remove <none> TAG images

docker system prune will do the trick, it removes

- all stopped containers
- all networks not used by at least one container
- all dangling images
- all dangling build cache

But use it, with the caution!

Create a new TextView programmatically then display it below another TextView

Try this code:

final String[] str = {"one","two","three","asdfgf"};
final RelativeLayout rl = (RelativeLayout) findViewById(R.id.rl);
final TextView[] tv = new TextView[10];

for (int i=0; i<str.length; i++)
{
    tv[i] = new TextView(this); 
    RelativeLayout.LayoutParams params=new RelativeLayout.LayoutParams
         ((int)LayoutParams.WRAP_CONTENT,(int)LayoutParams.WRAP_CONTENT);
    params.leftMargin = 50;
    params.topMargin  = i*50;
    tv[i].setText(str[i]);
    tv[i].setTextSize((float) 20);
    tv[i].setPadding(20, 50, 20, 50);
    tv[i].setLayoutParams(params);
    rl.addView(tv[i]);  
}

What is the difference between a process and a thread?

Threads within the same process share the Memory, but each thread has its own stack and registers, and threads store thread-specific data in the heap. Threads never execute independently, so the inter-thread communication is much faster when compared to inter-process communication.

Processes never share the same memory. When a child process creates it duplicates the memory location of the parent process. Process communication is done by using pipe, shared memory, and message parsing. Context switching between threads is very slow.

JavaScript: Difference between .forEach() and .map()

Diffrence between Foreach & map :

Map() : If you use map then map can return new array by iterating main array.

Foreach() : If you use Foreach then it can not return anything for each can iterating main array.

useFul link : use this link for understanding diffrence

https://codeburst.io/javascript-map-vs-foreach-f38111822c0f

How to make phpstorm display line numbers by default?

On the Mac version 8.0.1 has this setting here:

PhpStorm > Preferences > Editor (this is in the second section on the left - i.e. IDE Settings NOT Project Settings) > Appearance > Show line numbers

Develop Android app using C#

Having used Mono, I would NOT recommend it. The Mono runtime is bundled with your app, so your apk ends up being bloated at more than 6MB. A better programming solution for C# would be dot42. Both Mono and dot42 are licensed products.

Personally, I would recommend using Java with the IntelliJ IDEA dev environment. I say this for 3 reasons:

  1. There is so much Java code out there for Android already; do yourself a favour and don't re-invent the wheel.
  2. IDEA is similar enough to Visual Studio as to be a cinch to learn; it is made by JetBrains and the intelli-sense is better than VS.
  3. IDEA is free.

I have been a C# programmer for 12 years and started developing for Android with C# but ended up jumping ship and going the Java route. The languages are so similar you really won't notice much of a learning curve.

P.S. If you want to use LINQ, serialization and other handy features that are native to C# then you just need to look for the equivalent java library.

Installing Python library from WHL file

From How do I install a Python package with a .whl file? [sic], How do I install a Python package USING a .whl file ?

For all Windows platforms:

1) Download the .WHL package install file.

2) Make Sure path [C:\Progra~1\Python27\Scripts] is in the system PATH string. This is for using both [pip.exe] and [easy-install.exe].

3) Make sure the latest version of pip.EXE is now installed. At this time of posting:

pip.EXE --version

  pip 9.0.1 from C:\PROGRA~1\Python27\lib\site-packages (python 2.7)

4) Run pip.EXE in an Admin command shell.

 - Open an Admin privileged command shell.

 > easy_install.EXE --upgrade  pip

 - Check the pip.EXE version:
 > pip.EXE --version

 pip 9.0.1 from C:\PROGRA~1\Python27\lib\site-packages (python 2.7)

 > pip.EXE install --use-wheel --no-index 
     --find-links="X:\path to wheel file\DownloadedWheelFile.whl"

Be sure to double-quote paths or path\filenames with embedded spaces in them ! Alternatively, use the MSW 'short' paths and filenames.

What are the differences between Visual Studio Code and Visual Studio?

For Unity3D users ...

  • VSCode is incredibly faster than VS. Files open instantly from Unity. VS is very slow. VSCode launches instantly. VS takes forever to launch.

  • VS can literally compile code, build apps and so on, it's a huge IDE like Unity itself or XCode. VSCode is indeed "just" a full-featured text editor. VSCode is NOT a compiler (far less a huge, build-everything system that can literally create apps and software of all types): VSCode is literally "just a text editor".

  • With VSCode, you DO need to install the "Visual Studio Code" package. (Not to be confused with the "Visual Studio" package.) (It seems to me that VS works fine without the VS package, but, with VS Code, you must install Unity's VSCode package.)

enter image description here

  • When you first download and install VSCode, simply open any C# file on your machine. It will instantly prompt you to install the needed C# package. This is harmless and easy.

  • Unfortunately VSCode generally has only one window! You cannot, really, easily drag files to separate windows. If this is important to you, you may need to go with VS.

  • The biggest problem with VS is that the overall concept of settings and preferences are absolutely horrible. In VS, it is all-but impossible to change the font, etc. In contrast, VSCode has FANTASTIC preferences - dead simple, never a problem.

  • As far as I can see, every single feature in VS which you use in Unity is present in VSCode. (So, code coloring, jump to definitions, it understands/autocompletes every single thing in Unity, it opens from Unity, double clicking something in the Unity console opens the file to that line, etc etc)

  • If you are used to VS. And you want to change to VSCode. It's always hard changing editors, they are so intimate, but it's pretty similar; you won't have a big heartache.

In short if you're a VS for Unity3D user,

and you're going to try VSCode...

  1. VSCode is on the order of 19 trillion times faster in every way. It will blow your mind.

  2. It does seem to have every feature.

  3. Basically VS is the world's biggest IDE and application building system: VSCode is just an editor. (Indeed, that's exactly what you want with Unity, since Unity itself is the IDE.)

  4. Don't forget to just click to install the relevant Unity package.

If I'm not mistaken, there is no reason whatsoever to use VS with Unity.

Unity is an IDE so you just need a text editor, and that is what VSCode is. VSCode is hugely better in both speed and preferences. The only possible problem - multiple-windows are a bit clunky in VSCode!

That horrible "double copy" problem in VS ... solved!

If you are using VS with Unity. There is an infuriating problem where often VS will try to open twice, that is you will end up with two or more copies of VS running. Nobody has ever been able to fix this or figure out what the hell causes it. Fortunately, this problem never happens with VSCode.

Installing VSCode on a Mac - unbelievably easy.

There are no installers, etc etc etc. On the download page, you download a zipped Mac app. Put it in the Applications folder and you're done.

Folding! (Mac/Windows keystrokes are different)

Bizarrely there's no menu entry / docu whatsoever for folding, but here are the keys:

https://stackoverflow.com/a/30077543/294884

Setting colors and so on in VSCode - the critical tips

Particularly for Mac users who may find the colors strange:

Priceless post #1:

https://stackoverflow.com/a/45640244/294884

Priceless post #2:

https://stackoverflow.com/a/63303503/294884

Meta files ...

To keep the "Explorer" list of files on the left tidy, in the Unity case:

enter image description here

How to get a variable type in Typescript?

I'd like to add that TypeGuards only work on strings or numbers, if you want to compare an object use instanceof

if(task.id instanceof UUID) {
  //foo
}

Running conda with proxy

The best way I settled with is to set proxy environment variables right before using conda or pip install/update commands. Simply run:

set HTTP_PROXY=http://username:password@proxy_url:port

For example, your actual command could be like

set HTTP_PROXY=http://yourname:[email protected]_company.com:8080

If your company uses https proxy, then also

set HTTPS_PROXY=https://username:password@proxy_url:port

Once you exit Anaconda prompt then this setting is gone, so your username/password won't be saved after the session.

I didn't choose other methods mentioned in Anaconda documentation or some other sources, because they all require hardcoding of username/password into

  • Windows environment variables (also this requires restart of Anaconda prompt for the first time)
  • Conda .condarc or .netrc configuration files (also this won't work for PIP)
  • A batch/script file loaded while starting Anaconda prompt (also this might require configuring the path)

All of these are unsafe and will require constant update later. And if you forget where to update? More troubleshooting will come your way...

Accessing Session Using ASP.NET Web API

Last one is not working now, take this one, it worked for me.

in WebApiConfig.cs at App_Start

    public static string _WebApiExecutionPath = "api";

    public static void Register(HttpConfiguration config)
    {
        var basicRouteTemplate = string.Format("{0}/{1}", _WebApiExecutionPath, "{controller}");

        // Controller Only
        // To handle routes like `/api/VTRouting`
        config.Routes.MapHttpRoute(
            name: "ControllerOnly",
            routeTemplate: basicRouteTemplate//"{0}/{controller}"
        );

        // Controller with ID
        // To handle routes like `/api/VTRouting/1`
        config.Routes.MapHttpRoute(
            name: "ControllerAndId",
            routeTemplate: string.Format ("{0}/{1}", basicRouteTemplate, "{id}"),
            defaults: null,
            constraints: new { id = @"^\d+$" } // Only integers 
        );

Global.asax

protected void Application_PostAuthorizeRequest()
{
  if (IsWebApiRequest())
  {
    HttpContext.Current.SetSessionStateBehavior(SessionStateBehavior.Required);
  }
}

private static bool IsWebApiRequest()
{
  return HttpContext.Current.Request.AppRelativeCurrentExecutionFilePath.StartsWith(_WebApiExecutionPath);
}

fournd here: http://forums.asp.net/t/1773026.aspx/1

How to disable sort in DataGridView?

For extending control functionality like this, I like to use extension methods so that it can be reused easily. Here is a starter extensions file that contains an extension to disable sorting on a datagridview.

To use it, just include it in your project and call like this

myDatagridView.DisableSorting()

In my case, I added this line of code in the DataBindingComplete eventhandler of the DataGridView where I wanted sorting disabled

Imports System.ComponentModel
Imports System.Reflection
Imports System.Runtime.CompilerServices
Imports System.Windows.Forms

Public Module Extensions

<Extension()>
Public Sub DisableSorting(datagrid As DataGridView)
    For index = 0 To datagrid.Columns.Count - 1
        datagrid.Columns(index).SortMode = DataGridViewColumnSortMode.NotSortable
    Next
End Sub


End Module

google chrome extension :: console.log() from background page?

const log = chrome.extension.getBackgroundPage().console.log;
log('something')

Open log:

  • Open: chrome://extensions/
  • Details > Background page

jquery draggable: how to limit the draggable area?

$(function() { $( "#draggable" ).draggable({ containment: "window" }); });

of this code does not display. Full code and Demo: http://www.limitsizbilgi.com/div-tasima-surukle-birak-div-drag-and-drop-jquery.html

In order to limit the element inside its parent:

$( "#draggable" ).draggable({ containment: "window" });

The I/O operation has been aborted because of either a thread exit or an application request

What I do when it happens is Disable the COM port into the Device Manager and Enable it again.

It stop the communications with another program or thread and become free for you.

I hope this works for you. Regards.

Is there a way to "limit" the result with ELOQUENT ORM of Laravel?

Also, we can use it following ways

To get only first

 $cat_details = DB::table('an_category')->where('slug', 'people')->first();

To get by limit and offset

$top_articles = DB::table('an_pages')->where('status',1)->limit(30)->offset(0)->orderBy('id', 'DESC')->get();
$remaining_articles = DB::table('an_pages')->where('status',1)->limit(30)->offset(30)->orderBy('id', 'DESC')->get();

val() doesn't trigger change() in jQuery

You can very easily override the val function to trigger change by replacing it with a proxy to the original val function.

just add This code somewhere in your document (after loading jQuery)

(function($){
    var originalVal = $.fn.val;
    $.fn.val = function(){
        var result =originalVal.apply(this,arguments);
        if(arguments.length>0)
            $(this).change(); // OR with custom event $(this).trigger('value-changed');
        return result;
    };
})(jQuery);

A working example: here

(Note that this will always trigger change when val(new_val) is called even if the value didn't actually changed.)

If you want to trigger change ONLY when the value actually changed, use this one:

//This will trigger "change" event when "val(new_val)" called 
//with value different than the current one
(function($){
    var originalVal = $.fn.val;
    $.fn.val = function(){
        var prev;
        if(arguments.length>0){
            prev = originalVal.apply(this,[]);
        }
        var result =originalVal.apply(this,arguments);
        if(arguments.length>0 && prev!=originalVal.apply(this,[]))
            $(this).change();  // OR with custom event $(this).trigger('value-changed')
        return result;
    };
})(jQuery);

Live example for that: http://jsfiddle.net/5fSmx/1/

Comparing HTTP and FTP for transferring files

One advantage of FTP is that there is a standard way to list files using dir or ls. Because of this, ftp plays nice with tools such as rsync. Granted, rsync is usually done over ssh, but the option is there.

Where can I find a list of keyboard keycodes?

I know this was asked awhile back, but I found a comprehensive list of the virtual keyboard key codes right in MSDN, for use in C/C++. This also includes the mouse events. Note it is different than the javascript key codes (I noticed it around the VK_OEM section).

Here's the link:
http://msdn.microsoft.com/en-us/library/windows/desktop/dd375731(v=vs.85).aspx

Font.createFont(..) set color and size (java.awt.Font)

Font's don't have a color; only when using the font you can set the color of the component. For example, when using a JTextArea:

JTextArea txt = new JTextArea();
Font font = new Font("Verdana", Font.BOLD, 12);
txt.setFont(font);
txt.setForeground(Color.BLUE);

According to this link, the createFont() method creates a new Font object with a point size of 1 and style PLAIN. So, if you want to increase the size of the Font, you need to do this:

 Font font = Font.createFont(Font.TRUETYPE_FONT, new File("A.ttf"));
 return font.deriveFont(12f);

Optimal number of threads per core

If your threads don't do I/O, synchronization, etc., and there's nothing else running, 1 thread per core will get you the best performance. However that very likely not the case. Adding more threads usually helps, but after some point, they cause some performance degradation.

Not long ago, I was doing performance testing on a 2 quad-core machine running an ASP.NET application on Mono under a pretty decent load. We played with the minimum and maximum number of threads and in the end we found out that for that particular application in that particular configuration the best throughput was somewhere between 36 and 40 threads. Anything outside those boundaries performed worse. Lesson learned? If I were you, I would test with different number of threads until you find the right number for your application.

One thing for sure: 4k threads will take longer. That's a lot of context switches.

Maven Java EE Configuration Marker with Java Server Faces 1.2

You should check your project facets in the project configuration. This is where you may uncheck the JSF dependency.

enter image description here

In Python how should I test if a variable is None, True or False

if result is None:
    print "error parsing stream"
elif result:
    print "result pass"
else:
    print "result fail"

keep it simple and explicit. You can of course pre-define a dictionary.

messages = {None: 'error', True: 'pass', False: 'fail'}
print messages[result]

If you plan on modifying your simulate function to include more return codes, maintaining this code might become a bit of an issue.

The simulate might also raise an exception on the parsing error, in which case you'd either would catch it here or let it propagate a level up and the printing bit would be reduced to a one-line if-else statement.

Password encryption at client side

For a similar situation I used this PKCS #5: Password-Based Cryptography Standard from RSA laboratories. You can avoid storing password, by substituting it with something that can be generated only from the password (in one sentence). There are some JavaScript implementations.

filename and line number of Python script

import inspect    

file_name = __FILE__
current_line_no = inspect.stack()[0][2]
current_function_name = inspect.stack()[0][3]

#Try printing inspect.stack() you can see current stack and pick whatever you want 

curl POST format for CURLOPT_POSTFIELDS

This answer took me forever to find as well. I discovered that all you have to do is concatenate the URL ('?' after the file name and extension) with the URL-encoded query string. It doesn't even look like you have to set the POST cURL options. See the fake example below:

//create URL
$exampleURL = 'http://www.example.com/example.php?';

// create curl resource
$ch = curl_init(); 

// build URL-encoded query string
$data = http_build_query(
    array('first' => 'John', 'last' => 'Smith', '&'); // set url
curl_setopt($ch, CURLOPT_URL, $exampleURL . $data); 

// return the transfer as a string
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1); 

// $output contains the output string
$output = curl_exec($ch); 

// close curl resource to free up system resources <br/>
curl_close($ch);

You can also use file_get_contents():

// read entire webpage file into a string
$output = file_get_contents($exampleURL . $data);

How to calculate Average Waiting Time and average Turn-around time in SJF Scheduling?

SJF are two type - i) non preemptive SJF ii)pre-emptive SJF

I have re-arranged the processes according to Arrival time. here is the non preemptive SJF

A.T= Arrival Time

B.T= Burst Time

C.T= Completion Time

T.T = Turn around Time = C.T - A.T

W.T = Waiting Time = T.T - B.T

enter image description here

Here is the preemptive SJF Note: each process will preempt at time a new process arrives.Then it will compare the burst times and will allocate the process which have shortest burst time. But if two process have same burst time then the process which came first that will be allocated first just like FCFS.

enter image description here

jQuery: read text file from file system

This doesn't work and it shouldn't because it would be a giant security hole.

Have a look at the new File System API. It allows you to request access to a virtual, sandboxed filesystem governed by the browser. You will have to request your user to "upload" their file into the sandboxed filesystem once, but afterwards you can work with it very elegantly.

While this definitely is the future, it is still highly experimental and only works in Google Chrome as far as CanIUse knows.

Get key by value in dictionary

I found this answer very effective but not very easy to read for me.

To make it more clear you can invert the key and the value of a dictionary. This is make the keys values and the values keys, as seen here.

mydict = {'george':16,'amber':19}
res = dict((v,k) for k,v in mydict.iteritems())
print(res[16]) # Prints george

or

mydict = {'george':16,'amber':19}
dict((v,k) for k,v in mydict.iteritems())[16]

which is essentially the same that this other answer.

How to make all controls resize accordingly proportionally when window is maximized?

Well, it's fairly simple to do.

On the window resize event handler, calculate how much the window has grown/shrunk, and use that fraction to adjust 1) Height, 2) Width, 3) Canvas.Top, 4) Canvas.Left properties of all the child controls inside the canvas.

Here's the code:

private void window1_SizeChanged(object sender, SizeChangedEventArgs e)
        {
            myCanvas.Width = e.NewSize.Width;
            myCanvas.Height = e.NewSize.Height;

            double xChange = 1, yChange = 1;

            if (e.PreviousSize.Width != 0)
            xChange = (e.NewSize.Width/e.PreviousSize.Width);

            if (e.PreviousSize.Height != 0)
            yChange = (e.NewSize.Height / e.PreviousSize.Height);

            foreach (FrameworkElement fe in myCanvas.Children )
            {   
                /*because I didn't want to resize the grid I'm having inside the canvas in this particular instance. (doing that from xaml) */            
                if (fe is Grid == false)
                {
                    fe.Height = fe.ActualHeight * yChange;
                    fe.Width = fe.ActualWidth * xChange;

                    Canvas.SetTop(fe, Canvas.GetTop(fe) * yChange);
                    Canvas.SetLeft(fe, Canvas.GetLeft(fe) * xChange);

                }
            }
        }

How to remove all namespaces from XML with C#?

I think this is shortest answer(but for constuctions like , you will have another discussion, I also have regex to convert "<bcm:info></bcm:info>" to "<info></info>" but it wasn't optimized, If someone ask me I will share it. So, my solution is:

    public string RemoveAllNamespaces(string xmlDocument)
    {
        return Regex.Replace(xmlDocument, @"\sxmlns(\u003A\w+)?\u003D\u0022.+\u0022", " ");
    }

Delete all records in a table of MYSQL in phpMyAdmin

  • Visit phpmyadmin
  • Select your database and click on structure
  • In front of your table, you can see Empty, click on it to clear all the entries from the selected table.

demo-database-structure

Or you can do the same using sql query:

Click on SQL present along side Structure

TRUNCATE tablename; //offers better performance, but used only when all entries need to be cleared
or
DELETE FROM tablename; //returns the number of rows deleted

Refer to DELETE and TRUNCATE for detailed documentaion

Split string in JavaScript and detect line break

You should try detect the first line.

Then the:

if(n == 0){
  line = words[n]+"\n";
}

I'm not sure, but maybe it helps.

Converting DateTime format using razor

Below code will help you

@Html.Label(@item.Date.Value.ToString("dd - M - yy"))

Pandas group-by and sum

Both the other answers accomplish what you want.

You can use the pivot functionality to arrange the data in a nice table

df.groupby(['Fruit','Name'],as_index = False).sum().pivot('Fruit','Name').fillna(0)



Name    Bob     Mike    Steve   Tom    Tony
Fruit                   
Apples  16.0    9.0     10.0    0.0     0.0
Grapes  35.0    0.0     0.0     87.0    15.0
Oranges 67.0    57.0    0.0     15.0    1.0

In Firebase, is there a way to get the number of children of a node without loading all the node data?

Save the count as you go - and use validation to enforce it. I hacked this together - for keeping a count of unique votes and counts which keeps coming up!. But this time I have tested my suggestion! (notwithstanding cut/paste errors!).

The 'trick' here is to use the node priority to as the vote count...

The data is:

vote/$issueBeingVotedOn/user/$uniqueIdOfVoter = thisVotesCount, priority=thisVotesCount vote/$issueBeingVotedOn/count = 'user/'+$idOfLastVoter, priority=CountofLastVote

,"vote": {
  ".read" : true
  ,".write" : true
  ,"$issue" : {
    "user" : {
      "$user" : {
        ".validate" : "!data.exists() && 
             newData.val()==data.parent().parent().child('count').getPriority()+1 &&
             newData.val()==newData.GetPriority()" 

user can only vote once && count must be one higher than current count && data value must be same as priority.

      }
    }
    ,"count" : {
      ".validate" : "data.parent().child(newData.val()).val()==newData.getPriority() &&
             newData.getPriority()==data.getPriority()+1 "
    }

count (last voter really) - vote must exist and its count equal newcount, && newcount (priority) can only go up by one.

  }
}

Test script to add 10 votes by different users (for this example, id's faked, should user auth.uid in production). Count down by (i--) 10 to see validation fail.

<script src='https://cdn.firebase.com/v0/firebase.js'></script>
<script>
  window.fb = new Firebase('https:...vote/iss1/');
  window.fb.child('count').once('value', function (dss) {
    votes = dss.getPriority();
    for (var i=1;i<10;i++) vote(dss,i+votes);
  } );

function vote(dss,count)
{
  var user='user/zz' + count; // replace with auth.id or whatever
  window.fb.child(user).setWithPriority(count,count);
  window.fb.child('count').setWithPriority(user,count);
}
</script>

The 'risk' here is that a vote is cast, but the count not updated (haking or script failure). This is why the votes have a unique 'priority' - the script should really start by ensuring that there is no vote with priority higher than the current count, if there is it should complete that transaction before doing its own - get your clients to clean up for you :)

The count needs to be initialised with a priority before you start - forge doesn't let you do this, so a stub script is needed (before the validation is active!).

"&" meaning after variable type

It means you're passing the variable by reference.

In fact, in a declaration of a type, it means reference, just like:

int x = 42;
int& y = x;

declares a reference to x, called y.

Scrolling an iframe with JavaScript?

var $iframe = document.getElementByID('myIfreme');
var childDocument = iframe.contentDocument ? iframe.contentDocument : iframe.contentWindow.document;
 childDocument.documentElement.scrollTop = 0;

How do I create directory if it doesn't exist to create a file?

var filePath = context.Server.MapPath(Convert.ToString(ConfigurationManager.AppSettings["ErrorLogFile"]));

var file = new FileInfo(filePath);

file.Directory.Create(); If the directory already exists, this method does nothing.

var sw = new StreamWriter(filePath, true);

sw.WriteLine(Enter your message here);

sw.Close();

Android AudioRecord example

Here is an end to end solution I implemented for streaming Android microphone audio to a server for playback: Android AudioRecord to Server over UDP Playback Issues

Set background image on grid in WPF using C#

Did you forget the Background Property. The brush should be an ImageBrush whose ImageSource could be set to your image path.

<Grid>
    <Grid.Background>
        <ImageBrush ImageSource="/path/to/image.png" Stretch="UniformToFill"/>
    </Grid.Background>

    <...>
</Grid>

ERROR Source option 1.5 is no longer supported. Use 1.6 or later

I think this means that

  • You are using JDK9 or later
  • Your project uses maven-compiler-plugin with an old version which defaults to Java 5.

You have three options to solve this

  1. Downgrade to JDK7 or JDK8 (meh)
  2. Use maven-compiler-plugin version or later, because

    NOTE: Since 3.8.0 the default value has changed from 1.5 to 1.6 See https://maven.apache.org/plugins/maven-compiler-plugin/compile-mojo.html#target

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <version>3.8.0</version>
    </plugin>
    
  3. Indicate to the maven-compiler-plugin to use source level 6 and target 6 (or later).

    Best practice recommended by https://maven.apache.org/plugins/maven-compiler-plugin/

    Also note that at present the default source setting is 1.6 and the default target setting is 1.6, independently of the JDK you run Maven with. You are highly encouraged to change these defaults by setting source and target as described in Setting the -source and -target of the Java Compiler.

    <plugin>
        <groupId>org.apache.maven.plugins</groupId>
        <artifactId>maven-compiler-plugin</artifactId>
        <configuration>
            <source>1.6</source>
            <target>1.6</target>
        </configuration>
    </plugin>
    

    or use

    <properties>
      <maven.compiler.source>1.6</maven.compiler.source>
      <maven.compiler.target>1.6</maven.compiler.target>
    </properties>
    

What is the usefulness of PUT and DELETE HTTP request methods?

Safe Methods : Get Resource/No modification in resource
Idempotent : No change in resource status if requested many times
Unsafe Methods : Create or Update Resource/Modification in resource
Non-Idempotent : Change in resource status if requested many times

According to your requirement :

1) For safe and idempotent operation (Fetch Resource) use --------- GET METHOD
2) For unsafe and non-idempotent operation (Insert Resource) use--------- POST METHOD
3) For unsafe and idempotent operation (Update Resource) use--------- PUT METHOD
3) For unsafe and idempotent operation (Delete Resource) use--------- DELETE METHOD

Handling very large numbers in Python

Python supports a "bignum" integer type which can work with arbitrarily large numbers. In Python 2.5+, this type is called long and is separate from the int type, but the interpreter will automatically use whichever is more appropriate. In Python 3.0+, the int type has been dropped completely.

That's just an implementation detail, though — as long as you have version 2.5 or better, just perform standard math operations and any number which exceeds the boundaries of 32-bit math will be automatically (and transparently) converted to a bignum.

You can find all the gory details in PEP 0237.

SVN Commit specific files

Due to my subversion state, I had to get creative. svn st showed M,A and ~ statuses. I only wanted M and A so...

svn st | grep ^[A\|M] | cut -d' ' -f8- > targets.txt

This command says find all the lines output by svn st that start with M or A, cut using space delimiter, then get colums 8 to the end. Dump that into targets.txt and overwrite.

Then modify targets.txt to prune the file list further. Then run below to commit:

svn ci -m "My commit message" --targets targets.txt

Probably not the most common use case, but hopefully it helps someone.

Iterate two Lists or Arrays with one ForEach statement in C#

I understand/hope that the lists have the same length: No, your only bet is going with a plain old standard for loop.

Set min-width either by content or 200px (whichever is greater) together with max-width

The problem is that flex: 1 sets flex-basis: 0. Instead, you need

.container .box {
  min-width: 200px;
  max-width: 400px;
  flex-basis: auto; /* default value */
  flex-grow: 1;
}

_x000D_
_x000D_
.container {_x000D_
  display: -webkit-flex;_x000D_
  display: flex;_x000D_
  -webkit-flex-wrap: wrap;_x000D_
  flex-wrap: wrap;_x000D_
}_x000D_
_x000D_
.container .box {_x000D_
  -webkit-flex-grow: 1;_x000D_
  flex-grow: 1;_x000D_
  min-width: 100px;_x000D_
  max-width: 400px;_x000D_
  height: 200px;_x000D_
  background-color: #fafa00;_x000D_
  overflow: hidden;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
  <div class="box">_x000D_
    <table>_x000D_
      <tr>_x000D_
        <td>Content</td>_x000D_
        <td>Content</td>_x000D_
      </tr>_x000D_
    </table>    _x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Count distinct values

You can use this:

select count(customer) as count, pets
from table
group by pets

How to change the colors of a PNG image easily?

Ok guys it can be done easy in photoshop.

Open png photo and then check image -> mode value(i had indexed color). Go image -> mode and check rgb color. Now change your color EASY.

What is a good regular expression to match a URL?

These are the droids you're looking for. This is taken from validator.js which is the library you should really use to do this. But if you want to roll your own, who am I to stop you? If you want pure regex then you can just take out the length check. I think it's a good idea to test the length of the URL though if you really want to determine compliance with the spec.

 function isURL(str) {
     var urlRegex = '^(?!mailto:)(?:(?:http|https|ftp)://)(?:\\S+(?::\\S*)?@)?(?:(?:(?:[1-9]\\d?|1\\d\\d|2[01]\\d|22[0-3])(?:\\.(?:1?\\d{1,2}|2[0-4]\\d|25[0-5])){2}(?:\\.(?:[0-9]\\d?|1\\d\\d|2[0-4]\\d|25[0-4]))|(?:(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)(?:\\.(?:[a-z\\u00a1-\\uffff0-9]+-?)*[a-z\\u00a1-\\uffff0-9]+)*(?:\\.(?:[a-z\\u00a1-\\uffff]{2,})))|localhost)(?::\\d{2,5})?(?:(/|\\?|#)[^\\s]*)?$';
     var url = new RegExp(urlRegex, 'i');
     return str.length < 2083 && url.test(str);
}

How do I change the language of moment.js?

I'm using angular2-moment, but usage must be similar.

import { MomentModule } from "angular2-moment";
import moment = require("moment");

export class AppModule {

  constructor() {
    moment.locale('ru');
  }
}

ARG or ENV, which one to use in this case?

From Dockerfile reference:

  • The ARG instruction defines a variable that users can pass at build-time to the builder with the docker build command using the --build-arg <varname>=<value> flag.

  • The ENV instruction sets the environment variable <key> to the value <value>.
    The environment variables set using ENV will persist when a container is run from the resulting image.

So if you need build-time customization, ARG is your best choice.
If you need run-time customization (to run the same image with different settings), ENV is well-suited.

If I want to add let's say 20 (a random number) of extensions or any other feature that can be enable|disable

Given the number of combinations involved, using ENV to set those features at runtime is best here.

But you can combine both by:

  • building an image with a specific ARG
  • using that ARG as an ENV

That is, with a Dockerfile including:

ARG var
ENV var=${var}

You can then either build an image with a specific var value at build-time (docker build --build-arg var=xxx), or run a container with a specific runtime value (docker run -e var=yyy)

How can I programmatically generate keypress events in C#?

The question is tagged WPF but the answers so far are specific WinForms and Win32.

To do this in WPF, simply construct a KeyEventArgs and call RaiseEvent on the target. For example, to send an Insert key KeyDown event to the currently focused element:

var key = Key.Insert;                    // Key to send
var target = Keyboard.FocusedElement;    // Target element
var routedEvent = Keyboard.KeyDownEvent; // Event to send
     target.RaiseEvent(
  new KeyEventArgs(
    Keyboard.PrimaryDevice,
    PresentationSource.FromVisual(target),
    0,
    key)
  { RoutedEvent=routedEvent }
);

This solution doesn't rely on native calls or Windows internals and should be much more reliable than the others. It also allows you to simulate a keypress on a specific element.

Note that this code is only applicable to PreviewKeyDown, KeyDown, PreviewKeyUp, and KeyUp events. If you want to send TextInput events you'll do this instead:

var text = "Hello";
var target = Keyboard.FocusedElement;
var routedEvent = TextCompositionManager.TextInputEvent;

target.RaiseEvent(
  new TextCompositionEventArgs(
    InputManager.Current.PrimaryKeyboardDevice,
    new TextComposition(InputManager.Current, target, text))
  { RoutedEvent = routedEvent }
);

Also note that:

  • Controls expect to receive Preview events, for example PreviewKeyDown should precede KeyDown

  • Using target.RaiseEvent(...) sends the event directly to the target without meta-processing such as accelerators, text composition and IME. This is normally what you want. On the other hand, if you really do what to simulate actual keyboard keys for some reason, you would use InputManager.ProcessInput() instead.

Waiting for HOME ('android.process.acore') to be launched

I created a new device. Deleted the previous one.

Using Auto Layout in UITableView for dynamic cell layouts & variable row heights

The solution proposed by @smileyborg is almost perfect. If you have a custom cell and you want one or more UILabel with dynamic heights then the systemLayoutSizeFittingSize method combined with AutoLayout enabled returns a CGSizeZero unless you move all your cell constraints from the cell to its contentView (as suggested by @TomSwift here How to resize superview to fit all subviews with autolayout?).

To do so you need to insert the following code in your custom UITableViewCell implementation (thanks to @Adrian).

- (void)awakeFromNib{
    [super awakeFromNib];
    for (NSLayoutConstraint *cellConstraint in self.constraints) {
        [self removeConstraint:cellConstraint];
        id firstItem = cellConstraint.firstItem == self ? self.contentView : cellConstraint.firstItem;
        id seccondItem = cellConstraint.secondItem == self ? self.contentView : cellConstraint.secondItem;
        NSLayoutConstraint *contentViewConstraint =
        [NSLayoutConstraint constraintWithItem:firstItem
                                 attribute:cellConstraint.firstAttribute
                                 relatedBy:cellConstraint.relation
                                    toItem:seccondItem
                                 attribute:cellConstraint.secondAttribute
                                multiplier:cellConstraint.multiplier
                                  constant:cellConstraint.constant];
        [self.contentView addConstraint:contentViewConstraint];
    }
}

Mixing @smileyborg answer with this should works.

difference between throw and throw new Exception()

One other point that I didn't see anyone make:

If you don't do anything in your catch {} block, having a try...catch is pointless. I see this all the time:

try 
{
  //Code here
}
catch
{
    throw;
}

Or worse:

try 
{
  //Code here
}
catch(Exception ex)
{
    throw ex;
}

Worst yet:

try 
{
  //Code here
}
catch(Exception ex)
{
    throw new System.Exception(ex.Message);
}

javascript scroll event for iPhone/iPad?

For iOS you need to use the touchmove event as well as the scroll event like this:

document.addEventListener("touchmove", ScrollStart, false);
document.addEventListener("scroll", Scroll, false);

function ScrollStart() {
    //start of scroll event for iOS
}

function Scroll() {
    //end of scroll event for iOS
    //and
    //start/end of scroll event for other browsers
}

PadLeft function in T-SQL

I created a function:

CREATE FUNCTION [dbo].[fnPadLeft](@int int, @Length tinyint)
RETURNS varchar(255) 
AS 
BEGIN
    DECLARE @strInt varchar(255)

    SET @strInt = CAST(@int as varchar(255))
    RETURN (REPLICATE('0', (@Length - LEN(@strInt))) + @strInt);
END;

Use: select dbo.fnPadLeft(123, 10)

Returns: 0000000123

Extracting text from a PDF file using PDFMiner in python?

terrific answer from DuckPuncher, for Python3 make sure you install pdfminer2 and do:

import io

from pdfminer.pdfinterp import PDFResourceManager, PDFPageInterpreter
from pdfminer.converter import TextConverter
from pdfminer.layout import LAParams
from pdfminer.pdfpage import PDFPage


def convert_pdf_to_txt(path):
    rsrcmgr = PDFResourceManager()
    retstr = io.StringIO()
    codec = 'utf-8'
    laparams = LAParams()
    device = TextConverter(rsrcmgr, retstr, codec=codec, laparams=laparams)
    fp = open(path, 'rb')
    interpreter = PDFPageInterpreter(rsrcmgr, device)
    password = ""
    maxpages = 0
    caching = True
    pagenos = set()

    for page in PDFPage.get_pages(fp, pagenos, maxpages=maxpages,
                                  password=password,
                                  caching=caching,
                                  check_extractable=True):
        interpreter.process_page(page)



    fp.close()
    device.close()
    text = retstr.getvalue()
    retstr.close()
    return text

how to get the base url in javascript

One way is to use a script tag to import the variables you want to your views:

<script type="text/javascript">
window.base_url = <?php echo json_encode(base_url()); ?>;
</script>

Here, I wrapped the base_url with json_encode so that it'll automatically escape any characters to valid Javascript. I put base_url to the global Window so you can use it anywhere just by calling base_url, but make sure to put the script tag above any Javascript that calls it. With your given example:

...
$('#style_color').attr("href", base_url + "assets/css/themes/" + color_ + ".css");

Access to the path 'c:\inetpub\wwwroot\myapp\App_Data' is denied

I finally found the answer for 2019. You need to add 'IIS APPPOOL\DefaultAppPool' to the list of users that have security rights to the directory that is to be modified. Make sure they have full rights.

Grouping functions (tapply, by, aggregate) and the *apply family

In the collapse package recently released on CRAN, I have attempted to compress most of the common apply functionality into just 2 functions:

  1. dapply (Data-Apply) applies functions to rows or (default) columns of matrices and data.frames and (default) returns an object of the same type and with the same attributes (unless the result of each computation is atomic and drop = TRUE). The performance is comparable to lapply for data.frame columns, and about 2x faster than apply for matrix rows or columns. Parallelism is available via mclapply (only for MAC).

Syntax:

dapply(X, FUN, ..., MARGIN = 2, parallel = FALSE, mc.cores = 1L, 
       return = c("same", "matrix", "data.frame"), drop = TRUE)

Examples:

# Apply to columns:
dapply(mtcars, log)
dapply(mtcars, sum)
dapply(mtcars, quantile)
# Apply to rows:
dapply(mtcars, sum, MARGIN = 1)
dapply(mtcars, quantile, MARGIN = 1)
# Return as matrix:
dapply(mtcars, quantile, return = "matrix")
dapply(mtcars, quantile, MARGIN = 1, return = "matrix")
# Same for matrices ...
  1. BY is a S3 generic for split-apply-combine computing with vector, matrix and data.frame method. It is significantly faster than tapply, by and aggregate (an also faster than plyr, on large data dplyr is faster though).

Syntax:

BY(X, g, FUN, ..., use.g.names = TRUE, sort = TRUE,
   expand.wide = FALSE, parallel = FALSE, mc.cores = 1L,
   return = c("same", "matrix", "data.frame", "list"))

Examples:

# Vectors:
BY(iris$Sepal.Length, iris$Species, sum)
BY(iris$Sepal.Length, iris$Species, quantile)
BY(iris$Sepal.Length, iris$Species, quantile, expand.wide = TRUE) # This returns a matrix 
# Data.frames
BY(iris[-5], iris$Species, sum)
BY(iris[-5], iris$Species, quantile)
BY(iris[-5], iris$Species, quantile, expand.wide = TRUE) # This returns a wider data.frame
BY(iris[-5], iris$Species, quantile, return = "matrix") # This returns a matrix
# Same for matrices ...

Lists of grouping variables can also be supplied to g.

Talking about performance: A main goal of collapse is to foster high-performance programming in R and to move beyond split-apply-combine alltogether. For this purpose the package has a full set of C++ based fast generic functions: fmean, fmedian, fmode, fsum, fprod, fsd, fvar, fmin, fmax, ffirst, flast, fNobs, fNdistinct, fscale, fbetween, fwithin, fHDbetween, fHDwithin, flag, fdiff and fgrowth. They perform grouped computations in a single pass through the data (i.e. no splitting and recombining).

Syntax:

fFUN(x, g = NULL, [w = NULL,] TRA = NULL, [na.rm = TRUE,] use.g.names = TRUE, drop = TRUE)

Examples:

v <- iris$Sepal.Length
f <- iris$Species

# Vectors
fmean(v)             # mean
fmean(v, f)          # grouped mean
fsd(v, f)            # grouped standard deviation
fsd(v, f, TRA = "/") # grouped scaling
fscale(v, f)         # grouped standardizing (scaling and centering)
fwithin(v, f)        # grouped demeaning

w <- abs(rnorm(nrow(iris)))
fmean(v, w = w)      # Weighted mean
fmean(v, f, w)       # Weighted grouped mean
fsd(v, f, w)         # Weighted grouped standard-deviation
fsd(v, f, w, "/")    # Weighted grouped scaling
fscale(v, f, w)      # Weighted grouped standardizing
fwithin(v, f, w)     # Weighted grouped demeaning

# Same using data.frames...
fmean(iris[-5], f)                # grouped mean
fscale(iris[-5], f)               # grouped standardizing
fwithin(iris[-5], f)              # grouped demeaning

# Same with matrices ...

In the package vignettes I provide benchmarks. Programming with the fast functions is significantly faster than programming with dplyr or data.table, especially on smaller data, but also on large data.

parsing JSONP $http.jsonp() response in angular.js

This was very helpful. Angular doesn't work exactly like JQuery. It has its own jsonp() method, which indeed requires "&callback=JSON_CALLBACK" at the end of the query string. Here's an example:

var librivoxSearch = angular.module('librivoxSearch', []);
librivoxSearch.controller('librivoxSearchController', function ($scope, $http) {
    $http.jsonp('http://librivox.org/api/feed/audiobooks/author/Melville?format=jsonp&callback=JSON_CALLBACK').success(function (data) {
        $scope.data = data;
    });
});

Then display or manipulate {{ data }} in your Angular template.

Initializing a dictionary in python with a key value and no corresponding values

q = input("Apple")
w = input("Ball")
Definition = {'apple': q, 'ball': w}

How to get access to job parameters from ItemReader, in Spring Batch?

Pretty late, but you can also do this by annotating a @BeforeStep method:

@BeforeStep
    public void beforeStep(final StepExecution stepExecution) {
        JobParameters parameters = stepExecution.getJobExecution().getJobParameters();
        //use your parameters
}

How to create a self-signed certificate for a domain name for development?

Another easy way to generate a self signed certificate is to use Jexus Manager,

Jexus Manager

  1. Choose a server node in the Connections panel.
  2. In the middle panel, click Server Certificates icon to open the management page.
  3. Under Actions panel, click “Generate Self-Signed Certificate...” menu item.

https://www.jexusmanager.com/en/latest/tutorials/self-signed.html

What does 'wb' mean in this code, using Python?

File mode, write and binary. Since you are writing a .jpg file, it looks fine.

But if you supposed to read that jpg file you need to use 'rb'

More info

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files.

Get class name using jQuery

After getting the element as jQuery object via other means than its class, then

var className = $('#sidebar div:eq(14)').attr('class');

should do the trick. For the ID use .attr('id').

If you are inside an event handler or other jQuery method, where the element is the pure DOM node without wrapper, you can use:

this.className // for classes, and
this.id // for IDs

Both are standard DOM methods and well supported in all browsers.

How is CountDownLatch used in Java Multithreading?

package practice;

import java.util.concurrent.CountDownLatch;

public class CountDownLatchExample {

    public static void main(String[] args) throws InterruptedException {
        CountDownLatch c= new CountDownLatch(3);  // need to decrements the count (3) to zero by calling countDown() method so that main thread will wake up after calling await() method 
        Task t = new Task(c);
        Task t1 = new Task(c);
        Task t2 = new Task(c);
        t.start();
        t1.start();
        t2.start();
        c.await(); // when count becomes zero main thread will wake up 
        System.out.println("This will print after count down latch count become zero");
    }
}

class Task extends Thread{
    CountDownLatch c;

    public Task(CountDownLatch c) {
        this.c = c;
    }

    @Override
    public void run() {
        try {
            System.out.println(Thread.currentThread().getName());
            Thread.sleep(1000);
            c.countDown();   // each thread decrement the count by one 
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
    }
}

How to download Visual Studio Community Edition 2015 (not 2017)

The "official" way to get the vs2015 is to go to https://my.visualstudio.com/ ; join the " Visual Studio Dev Essentials" and then search the relevant file to download https://my.visualstudio.com/Downloads?q=Visual%20Studio%202015%20with%20Update%203

What is @ModelAttribute in Spring MVC?

Take any web application whether it is Gmail or Facebook or Instagram or any other web application, it's all about exchanging data or information between the end user and the application or the UI and the back end application. Even in Spring MVC world there are two ways to exchange data:

  1. from the Controller to the UI, and
  2. from the UI to the Controller.

What we are interested here is how the data is communicated from the UI to Controller. This can also be done in 2 ways:

  1. Using an HTML Form
  2. Using Query Parameters.

Using an HTML Form: Consider the below scenario,

Form Submission Representation

When we submit the form data from the web browser, we can access that data in our Controller class as an object. When we submit an HTML form, the Spring Container does four things. It will,

  1. first read all the data that is submitted that comes in the request using the request.getParameter method.
  2. once it reads them, it will convert them into the appropriate Java type using integer.parseInt, double.parseDouble and all the other parse methods that are available based on the data type of the data.
  3. once parsed, it will create a object of the model class that we created. For example, in this scenario, it is the user information that is being submitted and we create a class called User, which the Container will create an object of and it will set all the values that come in automatically into that object.
  4. it will then handover that object by setting the values to the Controller.

To get this whole thing to work, we'll have to follow certain steps.

Internal working

We first need to define a model class, like User, in which the number of fields should exactly match the number of fields in the HTML form. Also, the names that we use in the HTML form should match the names that we have in the Java class. These two are very important. Names should match, the number of fields in the form should match the number of fields in the class that we create. Once we do that, the Container will automatically read the data that comes in, creates an object of this model, sets the values and it hands it over to the Controller. To read those values inside the Controller, we use the @ModelAttribute annotation on the method parameters. When we create methods in the Controller, we are going to use the @ModelAttribute and add a parameter to it which will automatically have this object given by the Container.

Here is an example code for registering an user:

@RequestMapping(value = "registerUser", method = RequestMethod.POST)
public String registerUser(@ModelAttribute("user") User user, ModelMap model) {
    model.addAttribute("user", user);
    return "regResult";
}

Hope this diagrammatic explanation helped!

java.sql.SQLException: Missing IN or OUT parameter at index:: 1

You must use the column names and then set the values to insert (both ? marks):

//insert 1st row            
String inserting = "INSERT INTO employee(emp_name ,emp_address) values(?,?)";
System.out.println("insert " + inserting);//
PreparedStatement ps = con.prepareStatement(inserting); 
ps.setString(1, "hans");
ps.setString(2, "germany");
ps.executeUpdate();

How to style a div to be a responsive square?

To achieve what you are looking for you can use the viewport-percentage length vw.

Here is a quick example I made on jsfiddle.

HTML:

<div class="square">
    <h1>This is a Square</h1>
</div>

CSS:

.square {
    background: #000;
    width: 50vw;
    height: 50vw;
}
.square h1 {
    color: #fff;
}

I am sure there are many other ways to do this but this way seemed the best to me.

How to $http Synchronous call with AngularJS

Not currently. If you look at the source code (from this point in time Oct 2012), you'll see that the call to XHR open is actually hard-coded to be asynchronous (the third parameter is true):

 xhr.open(method, url, true);

You'd need to write your own service that did synchronous calls. Generally that's not something you'll usually want to do because of the nature of JavaScript execution you'll end up blocking everything else.

... but.. if blocking everything else is actually desired, maybe you should look into promises and the $q service. It allows you to wait until a set of asynchronous actions are done, and then execute something once they're all complete. I don't know what your use case is, but that might be worth a look.

Outside of that, if you're going to roll your own, more information about how to make synchronous and asynchronous ajax calls can be found here.

I hope that is helpful.

How does one capture a Mac's command key via JavaScript?

EDIT: As of 2019, e.metaKey is supported on all major browsers as per the MDN.

Note that on Windows, although the ? Windows key is considered to be the "meta" key, it is not going to be captured by browsers as such.

This is only for the command key on MacOS/keyboards.


Unlike Shift/Alt/Ctrl, the Cmd (“Apple”) key is not considered a modifier key—instead, you should listen on keydown/keyup and record when a key is pressed and then depressed based on event.keyCode.

Unfortunately, these key codes are browser-dependent:

  • Firefox: 224
  • Opera: 17
  • WebKit browsers (Safari/Chrome): 91 (Left Command) or 93 (Right Command)

You might be interested in reading the article JavaScript Madness: Keyboard Events, from which I learned that knowledge.

How to encode Doctrine entities to JSON in Symfony 2.0 AJAX application?

I found the solution to the problem of serializing entities was as follows:

#config/config.yml

services:
    serializer.method:
        class: Symfony\Component\Serializer\Normalizer\GetSetMethodNormalizer
    serializer.encoder.json:
        class: Symfony\Component\Serializer\Encoder\JsonEncoder
    serializer:
        class: Symfony\Component\Serializer\Serializer
        arguments:
            - [@serializer.method]
            - {json: @serializer.encoder.json }

in my controller:

$serializer = $this->get('serializer');

$entity = $this->get('doctrine')
               ->getRepository('myBundle:Entity')
               ->findOneBy($params);


$collection = $this->get('doctrine')
               ->getRepository('myBundle:Entity')
               ->findBy($params);

$toEncode = array(
    'response' => array(
        'entity' => $serializer->normalize($entity),
        'entities' => $serializer->normalize($collection)
    ),
);

return new Response(json_encode($toEncode));

other example:

$serializer = $this->get('serializer');

$collection = $this->get('doctrine')
               ->getRepository('myBundle:Entity')
               ->findBy($params);

$json = $serializer->serialize($collection, 'json');

return new Response($json);

you can even configure it to deserialize arrays in http://api.symfony.com/2.0

How to get position of a certain element in strings vector, to use it as an index in ints vector?

I am a beginner so here is a beginners answer. The if in the for loop gives i which can then be used however needed such as Numbers[i] in another vector. Most is fluff for examples sake, the for/if really says it all.

int main(){
vector<string>names{"Sara", "Harold", "Frank", "Taylor", "Sasha", "Seymore"};
string req_name;
cout<<"Enter search name: "<<'\n';
cin>>req_name;
    for(int i=0; i<=names.size()-1; ++i) {
        if(names[i]==req_name){
            cout<<"The index number for "<<req_name<<" is "<<i<<'\n';
            return 0;
        }
        else if(names[i]!=req_name && i==names.size()-1) {
            cout<<"That name is not an element in this vector"<<'\n';
        } else {
            continue;
        }
    }

Is it possible to dynamically compile and execute C# code fragments?

The best solution in C#/all static .NET languages is to use the CodeDOM for such things. (As a note, its other main purpose is for dynamically constructing bits of code, or even whole classes.)

Here's a nice short example take from LukeH's blog, which uses some LINQ too just for fun.

using System;
using System.Collections.Generic;
using System.Linq;
using Microsoft.CSharp;
using System.CodeDom.Compiler;

class Program
{
    static void Main(string[] args)
    {
        var csc = new CSharpCodeProvider(new Dictionary<string, string>() { { "CompilerVersion", "v3.5" } });
        var parameters = new CompilerParameters(new[] { "mscorlib.dll", "System.Core.dll" }, "foo.exe", true);
        parameters.GenerateExecutable = true;
        CompilerResults results = csc.CompileAssemblyFromSource(parameters,
        @"using System.Linq;
            class Program {
              public static void Main(string[] args) {
                var q = from i in Enumerable.Range(1,100)
                          where i % 2 == 0
                          select i;
              }
            }");
        results.Errors.Cast<CompilerError>().ToList().ForEach(error => Console.WriteLine(error.ErrorText));
    }
}

The class of primary importance here is the CSharpCodeProvider which utilises the compiler to compile code on the fly. If you want to then run the code, you just need to use a bit of reflection to dynamically load the assembly and execute it.

Here is another example in C# that (although slightly less concise) additionally shows you precisely how to run the runtime-compiled code using the System.Reflection namespace.

Set selected option of select box

I have found using the jQuery .val() method to have a significant drawback.

<select id="gate"></select>
$("#gate").val("Gateway 2");

If this select box (or any other input object) is in a form and there is a reset button used in the form, when the reset button is clicked the set value will get cleared and not reset to the beginning value as you would expect.

This seems to work the best for me.

For Select boxes

<select id="gate"></select>
$("#gate option[value='Gateway 2']").attr("selected", true);

For text inputs

<input type="text" id="gate" />
$("#gate").attr("value", "your desired value")

For textarea inputs

<textarea id="gate"></textarea>
$("#gate").html("your desired value")

For checkbox boxes

<input type="checkbox" id="gate" />
$("#gate option[value='Gateway 2']").attr("checked", true);

For radio buttons

<input type="radio" id="gate" value="this"/> or <input type="radio" id="gate" value="that"/>
$("#gate[value='this']").attr("checked", true);

SQL Server Convert Varchar to Datetime

SELECT CONVERT(VARCHAR(10), GETDATE(), 105) + ' ' + CONVERT(VARCHAR(10), GETDATE(), 108)

How to fill in proxy information in cntlm config file?

Just to add , if you are performing a "pip" operation , you might need to add and additional "--proxy=localhost:port_number"

e.g pip install --proxy=localhost:3128 matplotlib

Visit this link to see full details.

Java Date cut off time information

Date date = new Date();
Calendar cal = Calendar.getInstance();
cal.setTime(date);
cal.set(Calendar.HOUR_OF_DAY, 0);
cal.set(Calendar.MINUTE, 0);
cal.set(Calendar.SECOND, 0);
cal.set(Calendar.MILLISECOND, 0);
date = cal.getTime();

Calling a method inside another method in same class

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

How can I save a screenshot directly to a file in Windows?

Of course you could write a program that monitors the clipboard and displays an annoying SaveAs-dialog for every image in the clipboard ;-). I guess you can even find out if the last key pressed was PrintScreen to limit the number of false positives.

While I'm thinking about it.. you could also google for someone who already did exactly that.


EDIT: .. or just wait for someone to post the source here - as just happend :-)

How to push changes to github after jenkins build completes?

Actually, the "Checkout to specific local branch" from Claus's answer isn't needed as well.

You can just do changes, execute git commit -am "message" and then use "Git Publisher" with "Branch to push" = /refs/heads/master (or develop or whatever branch you need to push to), "Target remote name" = origin.

How to display scroll bar onto a html table

I resolved this problem by separating my content into two tables.

One table is the header row.

The seconds is also <table> tag, but wrapped by <div> with static height and overflow scroll.

What are the differences between Deferred, Promise and Future in JavaScript?

In light of apparent dislike for how I've attempted to answer the OP's question. The literal answer is, a promise is something shared w/ other objects, while a deferred should be kept private. Primarily, a deferred (which generally extends Promise) can resolve itself, while a promise might not be able to do so.

If you're interested in the minutiae, then examine Promises/A+.


So far as I'm aware, the overarching purpose is to improve clarity and loosen coupling through a standardized interface. See suggested reading from @jfriend00:

Rather than directly passing callbacks to functions, something which can lead to tightly coupled interfaces, using promises allows one to separate concerns for code that is synchronous or asynchronous.

Personally, I've found deferred especially useful when dealing with e.g. templates that are populated by asynchronous requests, loading scripts that have networks of dependencies, and providing user feedback to form data in a non-blocking manner.

Indeed, compare the pure callback form of doing something after loading CodeMirror in JS mode asynchronously (apologies, I've not used jQuery in a while):

/* assume getScript has signature like: function (path, callback, context) 
   and listens to onload && onreadystatechange */
$(function () {
   getScript('path/to/CodeMirror', getJSMode);

   // onreadystate is not reliable for callback args.
   function getJSMode() {
       getScript('path/to/CodeMirror/mode/javascript/javascript.js', 
           ourAwesomeScript);
   };

   function ourAwesomeScript() {
       console.log("CodeMirror is awesome, but I'm too impatient.");
   };
});

To the promises formulated version (again, apologies, I'm not up to date on jQuery):

/* Assume getScript returns a promise object */
$(function () {
   $.when(
       getScript('path/to/CodeMirror'),
       getScript('path/to/CodeMirror/mode/javascript/javascript.js')
   ).then(function () {
       console.log("CodeMirror is awesome, but I'm too impatient.");
   });
});

Apologies for the semi-pseudo code, but I hope it makes the core idea somewhat clear. Basically, by returning a standardized promise, you can pass the promise around, thus allowing for more clear grouping.

AngularJS: How to make angular load script inside ng-include?

Short answer: AngularJS ("jqlite") doesn't support this. Include jQuery on your page (before including Angular), and it should work. See https://groups.google.com/d/topic/angular/H4haaMePJU0/discussion

Iterate through DataSet

Just loop...

foreach(var table in DataSet1.Tables) {
    foreach(var col in table.Columns) {
       ...
    }
    foreach(var row in table.Rows) {
        object[] values = row.ItemArray;
        ...
    }
}

Replace multiple characters in one replace call

Chaining is cool, why dismiss it?

Anyway, here is another option in one replace:

string.replace(/#|_/g,function(match) {return (match=="#")?"":" ";})

The replace will choose "" if match=="#", " " if not.

[Update] For a more generic solution, you could store your replacement strings in an object:

var replaceChars={ "#":"" , "_":" " };
string.replace(/#|_/g,function(match) {return replaceChars[match];})

How to use lifecycle method getDerivedStateFromProps as opposed to componentWillReceiveProps

About the removal of componentWillReceiveProps: you should be able to handle its uses with a combination of getDerivedStateFromProps and componentDidUpdate, see the React blog post for example migrations. And yes, the object returned by getDerivedStateFromProps updates the state similarly to an object passed to setState.

In case you really need the old value of a prop, you can always cache it in your state with something like this:

state = {
  cachedSomeProp: null
  // ... rest of initial state
};

static getDerivedStateFromProps(nextProps, prevState) {
  // do things with nextProps.someProp and prevState.cachedSomeProp
  return {
    cachedSomeProp: nextProps.someProp,
    // ... other derived state properties
  };
}

Anything that doesn't affect the state can be put in componentDidUpdate, and there's even a getSnapshotBeforeUpdate for very low-level stuff.

UPDATE: To get a feel for the new (and old) lifecycle methods, the react-lifecycle-visualizer package may be helpful.

Truncate (not round) decimal places in SQL Server

This will remove the decimal part of any number

SELECT ROUND(@val,0,1)

How do I style appcompat-v7 Toolbar like Theme.AppCompat.Light.DarkActionBar?

To customize tool bar style, first create tool bar custom style inheriting Widget.AppCompat.Toolbar, override properties and then add it to custom app theme as shown below, see http://www.zoftino.com/android-toolbar-tutorial for more information tool bar and styles.

   <style name="MyAppTheme" parent="Theme.AppCompat.Light.NoActionBar">
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="toolbarStyle">@style/MyToolBarStyle</item>
    </style>
    <style name="MyToolBarStyle" parent="Widget.AppCompat.Toolbar">
        <item name="android:background">#80deea</item>
        <item name="titleTextAppearance">@style/MyTitleTextAppearance</item>
        <item name="subtitleTextAppearance">@style/MySubTitleTextAppearance</item>
    </style>
    <style name="MyTitleTextAppearance" parent="TextAppearance.Widget.AppCompat.Toolbar.Title">
        <item name="android:textSize">35dp</item>
        <item name="android:textColor">#ff3d00</item>
    </style>
    <style name="MySubTitleTextAppearance" parent="TextAppearance.Widget.AppCompat.Toolbar.Subtitle">
        <item name="android:textSize">30dp</item>
        <item name="android:textColor">#1976d2</item>
    </style>

How can I lookup a Java enum from its String value?

You can use the Enum::valueOf() function as suggested by Gareth Davis & Brad Mace above, but make sure you handle the IllegalArgumentException that would be thrown if the string used is not present in the enum.

error: Error parsing XML: not well-formed (invalid token) ...?

I tried everything on my end and ended up with the following.

I had the first line as:

<?xmlversion="1.0"encoding="utf-8"?>

And I was missing two spaces there, and it should be:

<?xml version="1.0" encoding="utf-8"?>

Before the version and before the encoding there should be a space.

How do I turn off the output from tar commands on Unix?

Just drop the option v.

-v is for verbose. If you don't use it then it won't display:

tar -zxf tmp.tar.gz -C ~/tmp1

SQLAlchemy ORDER BY DESCENDING?

from sqlalchemy import desc
someselect.order_by(desc(table1.mycol))

Usage from @jpmc26

INSERT INTO from two different server database

It sounds like you might need to create and query linked database servers in SQL Server

At the moment you've created a query that's going between different databases using a 3 part name mydatabase.dbo.mytable but you need to go up a level and use a 4 part name myserver.mydatabase.dbo.mytable, see this post on four part naming for more info

edit
The four part naming for your existing query would be as shown below (which I suspect you may have already tried?), but this assumes you can "get to" the remote database with the four part name, you might need to edit your host file / register the server or otherwise identify where to find database.windows.net.

INSERT INTO [DATABASE.WINDOWS.NET].[basecampdev].[dbo].[invoice]
       ([InvoiceNumber]
       ,[TotalAmount]
       ,[IsActive]
       ,[CreatedBy]
       ,[UpdatedBy]
       ,[CreatedDate]
       ,[UpdatedDate]
       ,[Remarks])
SELECT [InvoiceNumber]
       ,[TotalAmount]
       ,[IsActive]
       ,[CreatedBy]
       ,[UpdatedBy]
       ,[CreatedDate]
       ,[UpdatedDate]
       ,[Remarks] FROM [BC1-PC].[testdabse].[dbo].[invoice]

If you can't access the remote server then see if you can create a linked database server:

EXEC sp_addlinkedserver [database.windows.net];
GO
USE tempdb;
GO
CREATE SYNONYM MyInvoice FOR 
    [database.windows.net].basecampdev.dbo.invoice;
GO

Then you can just query against MyEmployee without needing the full four part name

How to keep environment variables when using sudo

The trick is to add environment variables to sudoers file via sudo visudo command and add these lines:

Defaults env_keep += "ftp_proxy http_proxy https_proxy no_proxy"

taken from ArchLinux wiki.

For Ubuntu 14, you need to specify in separate lines as it returns the errors for multi-variable lines:

Defaults  env_keep += "http_proxy"
Defaults  env_keep += "https_proxy"
Defaults  env_keep += "HTTP_PROXY"
Defaults  env_keep += "HTTPS_PROXY"

Representing EOF in C code?

The EOF character recognized by the command interpreter on Windows (and MSDOS, and CP/M) is 0x1a (decimal 26, aka Ctrl+Z aka SUB)

It can still be be used today for example to mark the end of a human-readable header in a binary file: if the file begins with "Some description\x1a" the user can dump the file content to the console using the TYPE command and the dump will stop at the EOF character, i.e. print Some description and stop, instead of continuing with the garbage that follows.

Uses of Action delegate in C#

MSDN says:

This delegate is used by the Array.ForEach method and the List.ForEach method to perform an action on each element of the array or list.

Except that, you can use it as a generic delegate that takes 1-3 parameters without returning any value.

How to evaluate http response codes from bash/shell script?

I haven't tested this on a 500 code, but it works on others like 200, 302 and 404.

response=$(curl --write-out '%{http_code}' --silent --output /dev/null servername)

Note, format provided for --write-out should be quoted. As suggested by @ibai, add --head to make a HEAD only request. This will save time when the retrieval is successful since the page contents won't be transmitted.

Math constant PI value in C

Depending on the library you are using the standard GNU C Predefined Mathematical Constants are here... https://www.gnu.org/software/libc/manual/html_node/Mathematical-Constants.html

You already have them so why redefine them? Your system desktop calculators probably have them and are even more accurate so you could but just be sure you're not conflicting with existing defined ones to save on compile warnings as they tend to get defaults for things like that. Enjoy!

How to get selected value from Dropdown list in JavaScript

Here is a simple example to get the selected value of dropdown in javascript

First we design the UI for dropdown

<div class="col-xs-12">
<select class="form-control" id="language">
    <option>---SELECT---</option>
    <option>JAVA</option>
    <option>C</option>
    <option>C++</option>
    <option>PERL</option>
</select>

Next we need to write script to get the selected item

<script type="text/javascript">
$(document).ready(function () {
    $('#language').change(function () {
        var doc = document.getElementById("language");
        alert("You selected " + doc.options[doc.selectedIndex].value);
    });
});

Now When change the dropdown the selected item will be alert.

how to return index of a sorted list?

How about

l1 = [2,3,1,4,5]
l2 = [l1.index(x) for x in sorted(l1)]

Ant build failed: "Target "build..xml" does not exist"

I'm probably late but this worked for me:


  1. Open your build.xml file located in your project's directory.
  2. Copy and Paste the following code in the main project tag : <target name="build" />

Negate if condition in bash script

Better

if ! wget -q --spider --tries=10 --timeout=20 google.com
then
  echo 'Sorry you are Offline'
  exit 1
fi

Where is NuGet.Config file located in Visual Studio project?

I have created an answer for this post that might help: https://stackoverflow.com/a/63816822/2399164

Summary:

I am a little late to the game but I believe I found a simple solution to this problem...

  1. Create a "NuGet.Config" file in the same directory as your .sln
<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <packageSources>
    <add key="nuget.org" value="https://api.nuget.org/v3/index.json" protocolVersion="3" />
    <add key="{{CUSTOM NAME}}" value="{{CUSTOM SOURCE}}" />
  </packageSources>
  <packageRestore>
    <add key="enabled" value="True" />
    <add key="automatic" value="True" />
  </packageRestore>
  <bindingRedirects>
    <add key="skip" value="False" />
  </bindingRedirects>
  <packageManagement>
    <add key="format" value="0" />
    <add key="disabled" value="False" />
  </packageManagement>
</configuration>
  1. That is it! Create your "Dockerfile" here as well

  2. Run docker build with your Dockerfile and all will get resolved

How can I tell if I'm running in 64-bit JVM or 32-bit JVM (from within a program)?

To get the version of JVM currently running the program

System.out.println(Runtime.class.getPackage().getImplementationVersion());

What is the difference between 'E', 'T', and '?' for Java generics?

A type variable, <T>, can be any non-primitive type you specify: any class type, any interface type, any array type, or even another type variable.

The most commonly used type parameter names are:

  • E - Element (used extensively by the Java Collections Framework)
  • K - Key
  • N - Number
  • T - Type
  • V - Value

In Java 7 it is permitted to instantiate like this:

Foo<String, Integer> foo = new Foo<>(); // Java 7
Foo<String, Integer> foo = new Foo<String, Integer>(); // Java 6

Is this a good way to clone an object in ES6?

This is good for shallow cloning. The object spread is a standard part of ECMAScript 2018.

For deep cloning you'll need a different solution.

const clone = {...original} to shallow clone

const newobj = {...original, prop: newOne} to immutably add another prop to the original and store as a new object.

Responsive Images with CSS

um responsive is simple

  • first off create a class named cell give it the property of display:table-cell
  • then @ max-width:700px do {display:block; width:100%; clear:both}

and that's it no absolute divs ever; divs needs to be 100% then max-width: - desired width - for inner framming. A true responsive sites has less than 9 lines of css anything passed that you are in a world of shit and over complicated things.

PS : reset.css style sheets are what makes css blinds there was a logical reason why they gave default styles in the first place.

How to locate and insert a value in a text box (input) using Python Selenium?

Assuming your page is available under "http://example.com"

from selenium import webdriver
from selenium.webdriver.common.keys import Keys

driver = webdriver.Firefox()
driver.get("http://example.com")

Select element by id:

inputElement = driver.find_element_by_id("a1")
inputElement.send_keys('1')

Now you can simulate hitting ENTER:

inputElement.send_keys(Keys.ENTER)

or if it is a form you can submit:

inputElement.submit() 

How can I increase the cursor speed in terminal?

If by "cursor speed", you mean the repeat rate when holding down a key - then have a look here: http://hints.macworld.com/article.php?story=20090823193018149

To summarize, open up a Terminal window and type the following command:

defaults write NSGlobalDomain KeyRepeat -int 0

More detail from the article:

Everybody knows that you can get a pretty fast keyboard repeat rate by changing a slider on the Keyboard tab of the Keyboard & Mouse System Preferences panel. But you can make it even faster! In Terminal, run this command:

defaults write NSGlobalDomain KeyRepeat -int 0

Then log out and log in again. The fastest setting obtainable via System Preferences is 2 (lower numbers are faster), so you may also want to try a value of 1 if 0 seems too fast. You can always visit the Keyboard & Mouse System Preferences panel to undo your changes.

You may find that a few applications don't handle extremely fast keyboard input very well, but most will do just fine with it.

Get selected item value from Bootstrap DropDown with specific ID

Try this code

<input type="TextBox" ID="yearBox" border="0" disabled>

$('#yearSelected li').on('click', function(){
                $('#yearBox').val($(this).text());
            });



<a href="#" class="dropdown-toggle" data-toggle="dropdown"> <i class="fas fa-calendar-alt"></i> <span>Academic Years</span> <i class="fas fa-chevron-down"></i> </a>
          <ul class="dropdown-menu">
            <li>
              <ul class="menu" id="yearSelected">
                <li><a href="#">2014-2015</a></li>
                <li><a href="#">2015-2016</a></li>
                <li><a href="#">2016-2017</a></li>
                <li><a href="#">2017-2018</a></li>

              </ul>
            </li>
          </ul>

its work for me

jQuery remove selected option from this

$('#some_select_box option:selected').remove();

Counter exit code 139 when running, but gdb make it through

this error is also caused by null pointer reference. if you are using a pointer who is not initialized then it causes this error.

to check either a pointer is initialized or not you can try something like

Class *pointer = new Class();
if(pointer!=nullptr){
    pointer->myFunction();
}

What is the difference between .text, .value, and .value2?

.Text gives you a string representing what is displayed on the screen for the cell. Using .Text is usually a bad idea because you could get ####

.Value2 gives you the underlying value of the cell (could be empty, string, error, number (double) or boolean)

.Value gives you the same as .Value2 except if the cell was formatted as currency or date it gives you a VBA currency (which may truncate decimal places) or VBA date.

Using .Value or .Text is usually a bad idea because you may not get the real value from the cell, and they are slower than .Value2

For a more extensive discussion see my Text vs Value vs Value2

How to parse json string in Android?

Use JSON classes for parsing e.g

JSONObject mainObject = new JSONObject(Your_Sring_data);
JSONObject uniObject = mainObject.getJSONObject("university");
String  uniName = uniObject.getString("name");
String uniURL = uniObject.getString("url");

JSONObject oneObject = mainObject.getJSONObject("1");
String id = oneObject.getString("id");
....

How to replace item in array?

 items[items.indexOf(3452)] = 1010

great for simple swaps. try the snippet below

_x000D_
_x000D_
const items = Array(523, 3452, 334, 31, 5346);
console.log(items)

items[items.indexOf(3452)] = 1010
console.log(items)
_x000D_
_x000D_
_x000D_

What is the difference between H.264 video and MPEG-4 video?

H.264 is a new standard for video compression which has more advanced compression methods than the basic MPEG-4 compression. One of the advantages of H.264 is the high compression rate. It is about 1.5 to 2 times more efficient than MPEG-4 encoding. This high compression rate makes it possible to record more information on the same hard disk.
The image quality is also better and playback is more fluent than with basic MPEG-4 compression. The most interesting feature however is the lower bit-rate required for network transmission.
So the 3 main advantages of H.264 over MPEG-4 compression are:
- Small file size for longer recording time and better network transmission.
- Fluent and better video quality for real time playback
- More efficient mobile surveillance application

H264 is now enshrined in MPEG4 as part 10 also known as AVC

Refer to: http://www.velleman.eu/downloads/3/h264_vs_mpeg4_en.pdf

Hope this helps.

Java TreeMap Comparator

The comparator should be only for the key, not for the whole entry. It sorts the entries based on the keys.

You should change it to something as follows

SortedMap<String, Double> myMap = 
    new TreeMap<String, Double>(new Comparator<String>()
    {
        public int compare(String o1, String o2)
        {
            return o1.compareTo(o2);
        } 
});

Update

You can do something as follows (create a list of entries in the map and sort the list base on value, but note this not going to sort the map itself) -

List<Map.Entry<String, Double>> entryList = new ArrayList<Map.Entry<String, Double>>(myMap.entrySet());
    Collections.sort(entryList, new Comparator<Map.Entry<String, Double>>() {
        @Override
        public int compare(Entry<String, Double> o1, Entry<String, Double> o2) {
            return o1.getValue().compareTo(o2.getValue());
        }
    });

Eclipse does not highlight matching variables

If highlighting is not working for large files, scalability mode has to be off. Properties / (c/c++) / Editor / Scalability

Changing the size of a column referenced by a schema-bound view in SQL Server

If anyone wants to "Increase the column width of the replicated table" in SQL Server 2008, then no need to change the property of "replicate_ddl=1". Simply follow below steps --

  1. Open SSMS
  2. Connect to Publisher database
  3. run command -- ALTER TABLE [Table_Name] ALTER COLUMN [Column_Name] varchar(22)
  4. It will increase the column width from varchar(x) to varchar(22) and same change you can see on subscriber (transaction got replicated). So no need to re-initialize the replication

Hope this will help all who are looking for it.

Failed to resolve: com.google.firebase:firebase-core:9.0.0

Need to Update

Android SDK : SDK Tools -> Support Repository -> Google Repository

After updating the Android SDK need to sync gradle build in Android studio.

Update with two tables?

I was scratching my head, not being able to get John Sansom's Join syntax work, at least in MySQL 5.5.30 InnoDB.

It turns out that this doesn't work.

UPDATE A 
    SET A.x = 1
FROM A INNER JOIN B 
        ON A.name = B.name
WHERE A.x <> B.x

But this works:

UPDATE A INNER JOIN B 
    ON A.name = B.name
SET A.x = 1
WHERE A.x <> B.x

Is it possible to use a batch file to establish a telnet session, send a command and have the output written to a file?

First of all, a caveat. Why do you want to use telnet? telnet is an old protocol, unsafe and impractical for remote access. It's been (almost)totally replaced by ssh.

To answer your questions, it depends. It depends on the telnet client you use. If you use microsoft telnet, you can't. Microsoft telnet does not have any mean to send commands from a batch file or a command line.

Bootstrap 3: How do you align column content to bottom of row

When working with bootsrap usually face three main problems:

  1. How to place the content of the column to the bottom?
  2. How to create a multi-row gallery of columns of equal height in one .row?
  3. How to center columns horizontally if their total width is less than 12 and the remaining width is odd?

To solve first two problems download this small plugin https://github.com/codekipple/conformity

The third problem is solved here http://www.minimit.com/articles/solutions-tutorials/bootstrap-3-responsive-centered-columns

Common code

<style>
    [class*=col-] {position: relative}
    .row-conformity .to-bottom {position:absolute; bottom:0; left:0; right:0}
    .row-centered {text-align:center}   
    .row-centered [class*=col-] {display:inline-block; float:none; text-align:left; margin-right:-4px; vertical-align:top} 
</style>

<script src="assets/conformity/conformity.js"></script>
<script>
    $(document).ready(function () {
        $('.row-conformity > [class*=col-]').conformity();
        $(window).on('resize', function() {
            $('.row-conformity > [class*=col-]').conformity();
        });
    });
</script>

1. Aligning content of the column to the bottom

<div class="row row-conformity">
    <div class="col-sm-3">
        I<br>create<br>highest<br>column
    </div>
    <div class="col-sm-3">
        <div class="to-bottom">
            I am on the bottom
        </div>
    </div>
</div>

2. Gallery of columns of equal height

<div class="row row-conformity">
    <div class="col-sm-4">We all have equal height</div>
    <div class="col-sm-4">...</div>
    <div class="col-sm-4">...</div>
    <div class="col-sm-4">...</div>
    <div class="col-sm-4">...</div>
    <div class="col-sm-4">...</div>
</div>

3. Horizontal alignment of columns to the center (less than 12 col units)

<div class="row row-centered">
    <div class="col-sm-3">...</div>
    <div class="col-sm-4">...</div>
</div>

All classes can work together

<div class="row row-conformity row-centered">
    ...
</div>

mySQL Error 1040: Too Many Connection

In your program you would have opened the connections and left open without closing it.

I faced a same problem and finally identified.

I added this code, after try catch.

finally{
    try {
        rs.close();
        p.close();
        conn.close();
    } catch (SQLException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

"Invalid JSON primitive" in Ajax processing

Here dataTpe is "json" so, data/reqParam must be in the form of string while calling API, many as much as object as you want but at last inside $.ajax's data stringify the object.

             let person= {  name: 'john',
                age: 22
            };

           var personStr = JSON.stringify(person); 

            $.ajax({
                url: "@Url.Action("METHOD", "CONTROLLER")",
                type: "POST",
                data: JSON.stringify( { param1: personStr } ),
                contentType: "application/json;charset=utf-8",
                dataType: "json",
        success: function (response) {

            console.log("Success");

        },
        error: function (error) {
            console.log("error found",error);
        }
    });

OR,

       $.ajax({
                url: "@Url.Action("METHOD", "CONTROLLER")",
                type: "POST",
                data: personStr,
                contentType: "application/json;charset=utf-8",
                dataType: "json",
        success: function (response) {

            console.log("Success");

        },
        error: function (error) {
            console.log("error found",error);
        }
    });

Dynamically access object property using variable

You can do it like this using Lodash get

_.get(object, 'a[0].b.c');

Selecting multiple items in ListView

To "update" the Toast message after unchecking some items, just put this line inside the for loop:

if (sp.valueAt(i))

so it results:

for(int i=0;i<sp.size();i++)
{
    if (sp.valueAt(i))
        str+=names[sp.keyAt(i)]+",";
}

Is there a goto statement in Java?

It's very much considered one of those things you Do Not Do, but was probably listed as a reserved word to avoid confusion for developers.

Compiling/Executing a C# Source File in Command Prompt

For the latest version, first open a Powershell window, go to any folder (e.g. c:\projects\) and run the following

# Get nuget.exe command line
wget https://dist.nuget.org/win-x86-commandline/latest/nuget.exe -OutFile nuget.exe

# Download the C# Roslyn compiler (just a few megs, no need to 'install')
.\nuget.exe install Microsoft.Net.Compilers

# Compiler, meet code
.\Microsoft.Net.Compilers.1.3.2\tools\csc.exe .\HelloWorld.cs

# Run it
.\HelloWorld.exe    

An example HelloWorld.cs

using System;

public class HelloWorld {
    public static void Main() 
    {
        Console.WriteLine("Hello world!");
    }
}

You can also try the new C# interpreter ;)

.\Microsoft.Net.Compilers.1.3.2\tools\csi.exe
> Console.WriteLine("Hello world!");
Hello world!

How can I change UIButton title color?

If you are using Swift, this will do the same:

buttonName.setTitleColor(UIColor.blackColor(), forState: .Normal)

Hope that helps!

Write-back vs Write-Through caching?

Write-back and write-through describe policies when a write hit occurs, that is when the cache has the requested information. In these examples, we assume a single processor is writing to main memory with a cache.

Write-through: The information is written to the cache and memory, and the write finishes when both have finished. This has the advantage of being simpler to implement, and the main memory is always consistent (in sync) with the cache (for the uniprocessor case - if some other device modifies main memory, then this policy is not enough), and a read miss never results in writes to main memory. The obvious disadvantage is that every write hit has to do two writes, one of which accesses slower main memory.

Write-back: The information is written to a block in the cache. The modified cache block is only written to memory when it is replaced (in effect, a lazy write). A special bit for each cache block, the dirty bit, marks whether or not the cache block has been modified while in the cache. If the dirty bit is not set, the cache block is "clean" and a write miss does not have to write the block to memory.

The advantage is that writes can occur at the speed of the cache, and if writing within the same block only one write to main memory is needed (when the previous block is being replaced). The disadvantages are that this protocol is harder to implement, main memory can be not consistent (not in sync) with the cache, and reads that result in replacement may cause writes of dirty blocks to main memory.

The policies for a write miss are detailed in my first link.

These protocols don't take care of the cases with multiple processors and multiple caches, as is common in modern processors. For this, more complicated cache coherence mechanisms are required. Write-through caches have simpler protocols since a write to the cache is immediately reflected in memory.

Good resources:

How to place the ~/.composer/vendor/bin directory in your PATH?

In Ubuntu 16.04 LTS with composer globally installed, this worked for me.

Edit the .bashrc file in your home directory puting the path to the composer bin folder that is located in /your/home/.config/composer/vendor/bin

echo 'export PATH="$PATH:$HOME/.config/composer/vendor/bin"' >> ~/.bashrc

source ~/.bashrc

If not works, verify the path to the composer bin directory and close and reopen the terminal. Otherwise, try to logoff and login in the Ubuntu.

Also works in ubuntu 18.04. Thanks @chifliiiii for your feedback.

Align image to left of text on same line - Twitter Bootstrap3

You can use floating:

<div class="paragraphs">
  <div class="row">
    <div class="span4">
      <img style="float:left" src="../site/img/success32.png"/>
      <div class="content-heading"><h3>Experience &nbsp </h3></div>
      <p style="clear:both">Donec id elit non mi porta gravida at eget metus. Etiam porta sem malesuada magna mollis euismod. Donec sed odio dui.</p>
    </div>
  </div>
</div>

If you want the following <p> to stay at the same line too, remove its

style="clear:both"

but then you should add

<div style="clear:both"></div>

after it.

Unable to connect to mongodb Error: couldn't connect to server 127.0.0.1:27017 at src/mongo/shell/mongo.js:L112

Please Start the MongoDB server first and try to connect.

Pre-requisite:

Create space for storing DB and tables in any directory Example (windows): D:\mongodbdata\

Steps:

  1. Start server

    mongod --port 5000 --dbpath D:\mongodbdata\ (please mention above created path)

  2. Connect mongodb server (Run in another terminal/console)

    mongo --port 5000

Limiting the number of characters in a JTextField

Here is an optimized version of npinti's answer:

import javax.swing.text.AttributeSet;
import javax.swing.text.BadLocationException;
import javax.swing.text.JTextComponent;
import javax.swing.text.PlainDocument;
import java.awt.*;

public class TextComponentLimit extends PlainDocument
{
    private int charactersLimit;

    private TextComponentLimit(int charactersLimit)
    {
        this.charactersLimit = charactersLimit;
    }

    @Override
    public void insertString(int offset, String input, AttributeSet attributeSet) throws BadLocationException
    {
        if (isAllowed(input))
        {
            super.insertString(offset, input, attributeSet);
        } else
        {
            Toolkit.getDefaultToolkit().beep();
        }
    }

    private boolean isAllowed(String string)
    {
        return (getLength() + string.length()) <= charactersLimit;
    }

    public static void addTo(JTextComponent textComponent, int charactersLimit)
    {
        TextComponentLimit textFieldLimit = new TextComponentLimit(charactersLimit);
        textComponent.setDocument(textFieldLimit);
    }
}

To add a limit to your JTextComponent, simply write the following line of code:

JTextFieldLimit.addTo(myTextField, myMaximumLength);

The ResourceConfig instance does not contain any root resource classes

I am getting this exception, because of a missing ResourseConfig in Web.xml.

Add:

<init-param>
    <param-name>com.sun.jersey.config.property.packages</param-name>
    <param-value>/* Name of Package where your service class exists */</param-value>
</init-param>

Service class means: class which contains services like: @Path("/orders")

Window vs Page vs UserControl for WPF navigation?

Most of all has posted correct answer. I would like to add few links, so that you can refer to them and have clear and better ideas about the same:

UserControl: http://msdn.microsoft.com/en-IN/library/a6h7e207(v=vs.71).aspx

The difference between page and window with respect to WPF: Page vs Window in WPF?

Difference between adjustResize and adjustPan in android?

From the Android Developer Site link

"adjustResize"

The activity's main window is always resized to make room for the soft keyboard on screen.

"adjustPan"

The activity's main window is not resized to make room for the soft keyboard. Rather, the contents of the window are automatically panned so that the current focus is never obscured by the keyboard and users can always see what they are typing. This is generally less desirable than resizing, because the user may need to close the soft keyboard to get at and interact with obscured parts of the window.

according to your comment, use following in your activity manifest

<activity android:windowSoftInputMode="adjustResize"> </activity>

See what's in a stash without applying it

From the man git-stash page:

The modifications stashed away by this command can be listed with git stash list, inspected with git stash show

show [<stash>]
       Show the changes recorded in the stash as a diff between the stashed state and
       its original parent. When no <stash> is given, shows the latest one. By default,
       the command shows the diffstat, but it will accept any format known to git diff
       (e.g., git stash show -p stash@{1} to view the second most recent stash in patch
       form).

To list the stashed modifications

git stash list

To show files changed in the last stash

git stash show

So, to view the content of the most recent stash, run

git stash show -p

To view the content of an arbitrary stash, run something like

git stash show -p stash@{1}

Kotlin - Property initialization using "by lazy" vs. "lateinit"

Here are the significant differences between lateinit var and by lazy { ... } delegated property:

  • lazy { ... } delegate can only be used for val properties, whereas lateinit can only be applied to vars, because it can't be compiled to a final field, thus no immutability can be guaranteed;

  • lateinit var has a backing field which stores the value, and by lazy { ... } creates a delegate object in which the value is stored once calculated, stores the reference to the delegate instance in the class object and generates the getter for the property that works with the delegate instance. So if you need the backing field present in the class, use lateinit;

  • In addition to vals, lateinit cannot be used for nullable properties or Java primitive types (this is because of null used for uninitialized value);

  • lateinit var can be initialized from anywhere the object is seen from, e.g. from inside a framework code, and multiple initialization scenarios are possible for different objects of a single class. by lazy { ... }, in turn, defines the only initializer for the property, which can be altered only by overriding the property in a subclass. If you want your property to be initialized from outside in a way probably unknown beforehand, use lateinit.

  • Initialization by lazy { ... } is thread-safe by default and guarantees that the initializer is invoked at most once (but this can be altered by using another lazy overload). In the case of lateinit var, it's up to the user's code to initialize the property correctly in multi-threaded environments.

  • A Lazy instance can be saved, passed around and even used for multiple properties. On contrary, lateinit vars do not store any additional runtime state (only null in the field for uninitialized value).

  • If you hold a reference to an instance of Lazy, isInitialized() allows you to check whether it has already been initialized (and you can obtain such instance with reflection from a delegated property). To check whether a lateinit property has been initialized, you can use property::isInitialized since Kotlin 1.2.

  • A lambda passed to by lazy { ... } may capture references from the context where it is used into its closure.. It will then store the references and release them only once the property has been initialized. This may lead to object hierarchies, such as Android activities, not being released for too long (or ever, if the property remains accessible and is never accessed), so you should be careful about what you use inside the initializer lambda.

Also, there's another way not mentioned in the question: Delegates.notNull(), which is suitable for deferred initialization of non-null properties, including those of Java primitive types.

JSON parsing using Gson for Java

This is simple code to do it, I avoided all checks but this is the main idea.

 public String parse(String jsonLine) {
    JsonElement jelement = new JsonParser().parse(jsonLine);
    JsonObject  jobject = jelement.getAsJsonObject();
    jobject = jobject.getAsJsonObject("data");
    JsonArray jarray = jobject.getAsJsonArray("translations");
    jobject = jarray.get(0).getAsJsonObject();
    String result = jobject.get("translatedText").getAsString();
    return result;
}

To make the use more generic - you will find that Gson's javadocs are pretty clear and helpful.

TypeScript: casting HTMLElement

We could type our variable with an explicit return type:

const script: HTMLScriptElement = document.getElementsByName(id).item(0);

Or assert as (needed with TSX):

const script = document.getElementsByName(id).item(0) as HTMLScriptElement;

Or in simpler cases assert with angle-bracket syntax.


A type assertion is like a type cast in other languages, but performs no special checking or restructuring of data. It has no runtime impact, and is used purely by the compiler.

Documentation:

TypeScript - Basic Types - Type assertions

Check if a list contains an item in Ansible

You do not need {{}} in when conditions. What you are searching for is:

- fail: msg="unsupported version"
  when: version not in acceptable_versions

How to solve "Could not establish trust relationship for the SSL/TLS secure channel with authority"

the first two use lambda, the third uses regular code... hope you find it helpful

            //Trust all certificates
            System.Net.ServicePointManager.ServerCertificateValidationCallback =
                ((sender, certificate, chain, sslPolicyErrors) => true);

            // trust sender
            System.Net.ServicePointManager.ServerCertificateValidationCallback
                = ((sender, cert, chain, errors) => cert.Subject.Contains("YourServerName"));

            // validate cert by calling a function
            ServicePointManager.ServerCertificateValidationCallback += new RemoteCertificateValidationCallback(ValidateRemoteCertificate);

    // callback used to validate the certificate in an SSL conversation
    private static bool ValidateRemoteCertificate(object sender, X509Certificate cert, X509Chain chain, SslPolicyErrors policyErrors)
    {
        bool result = false;
        if (cert.Subject.ToUpper().Contains("YourServerName"))
        {
            result = true;
        }

        return result;
    }

cURL error 60: SSL certificate: unable to get local issuer certificate

I just experienced this same problem with the Laravel 4 php framework which uses the guzzlehttp/guzzle composer package. For some reason, the SSL certificate for mailgun stopped validating suddenly and I got that same "error 60" message.

If, like me, you are on a shared hosting without access to php.ini, the other solutions are not possible. In any case, Guzzle has this client initializing code that would most likely nullify the php.ini effects:

// vendor/guzzlehttp/guzzle/src/Client.php
    $settings = [
        'allow_redirects' => true,
        'exceptions'      => true,
        'decode_content'  => true,
        'verify'          => __DIR__ . '/cacert.pem'
    ];

Here Guzzle forces usage of its own internal cacert.pem file, which is probably now out of date, instead of using the one provided by cURL's environment. Changing this line (on Linux at least) configures Guzzle to use cURL's default SSL verification logic and fixed my problem:

        'verify'          => true

You can also set this to false if you don't care about the security of your SSL connection, but that's not a good solution.

Since the files in vendor are not meant to be tampered with, a better solution would be to configure the Guzzle client on usage, but this was just too difficult to do in Laravel 4.

Hope this saves someone else a couple hours of debugging...

What's the "Content-Length" field in HTTP header?

rfc2616

The Content-Length entity-header field indicates the size of the entity-body, in decimal number of OCTETs, sent to the recipient or, in the case of the HEAD method, the size of the entity-body that would have been sent had the request been a GET.

It doesn't matter what the content-type is.

Extension at post below.

php mail setup in xampp

XAMPP should have come with a "fake" sendmail program. In that case, you can use sendmail as well:

[mail function]
; For Win32 only.
; http://php.net/smtp
;SMTP = localhost
; http://php.net/smtp-port
;smtp_port = 25

; For Win32 only.
; http://php.net/sendmail-from
;sendmail_from = [email protected]

; For Unix only.  You may supply arguments as well (default: "sendmail -t -i").
; http://php.net/sendmail-path
sendmail_path = "C:/xampp/sendmail/sendmail.exe -t -i"

Sendmail should have a sendmail.ini with it; it should be configured as so:

# Example for a user configuration file

# Set default values for all following accounts.
defaults
logfile "C:\xampp\sendmail\sendmail.log"

# Mercury
#account Mercury
#host localhost
#from postmaster@localhost
#auth off

# A freemail service example
account ACCOUNTNAME_HERE
tls on
tls_certcheck off
host smtp.gmail.com
from EMAIL_HERE
auth on
user EMAIL_HERE
password PASSWORD_HERE

# Set a default account
account default : ACCOUNTNAME_HERE

Of course, replace ACCOUNTNAME_HERE with an arbitrary account name, replace EMAIL_HERE with a valid email (such as a Gmail or Hotmail), and replace PASSWORD_HERE with the password to your email. Now, you should be able to send mail. Remember to restart Apache (from the control panel or the batch files) to allow the changes to PHP to work.

JAVA Unsupported major.minor version 51.0

The Java runtime you try to execute your program with is an earlier version than Java 7 which was the target you compile your program for.

For Ubuntu use

apt-get install openjdk-7-jdk

to get Java 7 as default. You may have to uninstall openjdk-6 first.

bootstrap 3 wrap text content within div for horizontal alignment

1) Maybe oveflow: hidden; will do the trick?

2) You need to set the size of each div with the text and button so that each of these divs have the same height. Then for your button:

button {
  position: absolute;
  bottom: 0;
}

What is the difference between ports 465 and 587?

I don't want to name names, but someone appears to be completely wrong. The referenced standards body stated the following: submissions 465 tcp Message Submission over TLS protocol [IESG] [IETF_Chair] 2017-12-12 [RFC8314]

If you are so inclined, you may wish to read the referenced RFC.

This seems to clearly imply that port 465 is the best way to force encrypted communication and be sure that it is in place. Port 587 offers no such guarantee.

PHP: date function to get month of the current date

To compare with an int do this:

<?php
$date = date("m");
$dateToCompareTo = 05;
if (strval($date) == strval($dateToCompareTo)) {
    echo "They are the same";
}
?>

What's the difference between identifying and non-identifying relationships?

If you consider that the child item should be deleted when the parent is deleted, then it is an identifying relationship.

If the child item should be kept even though the parent is deleted, then it is a non-identifying relatio?ship.

As an example, I have a training database with trainees, trainings, diplomas and training sessions :

  • trainees have an identifying relationship with training sessions
  • trainings have an identifying relationship with training sessions
  • but trainees have a non-identifying relationship with diplomas

Only training sessions should be deleted if one of the related trainee, training or diploma is deleted.

How to set java.net.preferIPv4Stack=true at runtime?

I ran into this very problem trying to send mail with javax.mail from a web application in a web server running Java 7. Internal mail server destinations failed with "network unreachable", despite telnet and ping working from the same host, and while external mail servers worked. I tried

System.setProperty("java.net.preferIPv4Stack" , "true");

in the code, but that failed. So the parameter value was probably cached earlier by the system. Setting the VM argument

-Djava.net.preferIPv4Stack=true

in the web server startup script worked.

One further bit of evidence: in a very small targeted test program, setting the system property in the code did work. So the parameter is probably cached when the first Socket is used, probably not just as the JVM starts.

How to check if a map contains a key in Go?

Searched on the go-nuts email list and found a solution posted by Peter Froehlich on 11/15/2009.

package main

import "fmt"

func main() {
        dict := map[string]int {"foo" : 1, "bar" : 2}
        value, ok := dict["baz"]
        if ok {
                fmt.Println("value: ", value)
        } else {
                fmt.Println("key not found")
        }
}

Or, more compactly,

if value, ok := dict["baz"]; ok {
    fmt.Println("value: ", value)
} else {
    fmt.Println("key not found")
}

Note, using this form of the if statement, the value and ok variables are only visible inside the if conditions.

removeEventListener on anonymous functions in JavaScript

window.document.onkeydown = function(){};

Android: findviewbyid: finding view by id when view is not on the same layout invoked by setContentView

Another way to do this is:

// inflate the layout
View myLayout = LayoutInflater.from(this).inflate(R.layout.MY_LAYOUT,null);

// load the text view
TextView myView = (TextView) myLayout.findViewById(R.id.MY_VIEW);

Pandas split column of lists into multiple columns

Here's another solution using df.transform and df.set_index:

>>> (df['teams']
       .transform([lambda x:x[0], lambda x:x[1]])
       .set_axis(['team1','team2'],
                  axis=1,
                  inplace=False)
    )

  team1 team2
0    SF   NYG
1    SF   NYG
2    SF   NYG
3    SF   NYG
4    SF   NYG
5    SF   NYG
6    SF   NYG

How can I get the baseurl of site?

I go with

HttpContext.Current.Request.ServerVariables["HTTP_HOST"]

How to add line break for UILabel?

If you read a string from an XML file, the line break \n in this string will not work in UILabel text. The \n is not parsed to a line break.

Here is a little trick to solve this issue:

// correct next line \n in string from XML file
NSString *myNewLineStr = @"\n";
myLabelText = [myLabelText stringByReplacingOccurrencesOfString:@"\\n" withString:myNewLineStr];

myLabel.text = myLabelText;

So you have to replace the unparsed \n part in your string by a parsed \n in a hardcoded NSString.

Here are my other label settings:

myLabel.numberOfLines = 0;
myLabel.backgroundColor = [UIColor lightGrayColor];
myLabel.textColor = [UIColor redColor]; 
myLabel.font = [UIFont fontWithName:@"Helvetica Neue" size:14.0];   
myLabel.textAlignment = UITextAlignmentCenter;

Most important is to set numberOfLines to 0 (= unlimited number of lines in label).

No idea why Apple has chosen to not parse \n in strings read from XML?

Hope this helps.

PHP, pass array through POST

Edit If you are asking about security, see my addendum at the bottom Edit

PHP has a serialize function provided for this specific purpose. Pass it an array, and it will give you a string representation of it. When you want to convert it back to an array, you just use the unserialize function.

$data = array('one'=>1, 'two'=>2, 'three'=>33);
$dataString = serialize($data);
//send elsewhere
$data = unserialize($dataString);

This is often used by lazy coders to save data to a database. Not recommended, but works as a quick/dirty solution.

Addendum

I was under the impression that you were looking for a way to send the data reliably, not "securely". No matter how you pass the data, if it is going through the users system, you cannot trust it at all. Generally, you should store it somewhere on the server & use a credential (cookie, session, password, etc) to look it up.

CSS Animation and Display None

CSS (or jQuery, for that matter) can't animate between display: none; and display: block;. Worse yet: it can't animate between height: 0 and height: auto. So you need to hard code the height (if you can't hard code the values then you need to use javascript, but this is an entirely different question);

#main-image{
    height: 0;
    overflow: hidden;
    background: red;
   -prefix-animation: slide 1s ease 3.5s forwards;
}

@-prefix-keyframes slide {
  from {height: 0;}
  to {height: 300px;}
}

You mention that you're using Animate.css, which I'm not familiar with, so this is a vanilla CSS.

You can see a demo here: http://jsfiddle.net/duopixel/qD5XX/

Eclipse will not start and I haven't changed anything

I moved workbench.xmi located at workspace/.metadata/.plugins/org.eclipse.e4.workbench/workbench.xmi to a backup folder. Then started eclipse and waited for all background processes to finish. Then I closed eclipse and moved my backup copy of workbench.xmi back (overwriting the one created with the last launch). Eclipse launched fine and I got all my settings back.

Run Command Line & Command From VBS

Set oShell = CreateObject ("WScript.Shell") 
oShell.run "cmd.exe /C copy ""S:Claims\Sound.wav"" ""C:\WINDOWS\Media\Sound.wav"" "

Convert NSNumber to int in Objective-C

Have a look at the documentation. Use the intValue method:

NSNumber *number = [dict objectForKey:@"integer"];
int intValue = [number intValue];

How to set HttpResponse timeout for Android in Java

public boolean isInternetWorking(){
    try {
        int timeOut = 5000;
        Socket socket = new Socket();
        SocketAddress socketAddress = new InetSocketAddress("8.8.8.8",53);
        socket.connect(socketAddress,timeOut);
        socket.close();
        return true;
    } catch (IOException e) {
        //silent
    }
    return false;
}

How to add title to seaborn boxplot

.set_title('') can be used to add title to Seaborn Plot

import seaborn as sb
sb.boxplot().set_title('Title')

How do I show the value of a #define at compile-time?

In Microsoft C/C++, you can use the built-in _CRT_STRINGIZE() to print constants. Many of my stdafx.h files contain some combination of these:

#pragma message("_MSC_VER      is " _CRT_STRINGIZE(_MSC_VER))
#pragma message("_MFC_VER      is " _CRT_STRINGIZE(_MFC_VER))
#pragma message("_ATL_VER      is " _CRT_STRINGIZE(_ATL_VER))
#pragma message("WINVER        is " _CRT_STRINGIZE(WINVER))
#pragma message("_WIN32_WINNT  is " _CRT_STRINGIZE(_WIN32_WINNT))
#pragma message("_WIN32_IE     is " _CRT_STRINGIZE(_WIN32_IE))
#pragma message("NTDDI_VERSION is " _CRT_STRINGIZE(NTDDI_VERSION)) 

and outputs something like this:

_MSC_VER      is 1915
_MFC_VER      is 0x0E00
_ATL_VER      is 0x0E00
WINVER        is 0x0600
_WIN32_WINNT  is 0x0600
_WIN32_IE     is 0x0700
NTDDI_VERSION is 0x06000000

How to change fontFamily of TextView in Android

I had to parse /system/etc/fonts.xml in a recent project. Here are the current font families as of Lollipop:

+---------------------------------------------------------------+
¦    ¦ FONT FAMILY                ¦ TTF FILE                    ¦
¦----+----------------------------+-----------------------------¦
¦  1 ¦ casual                     ¦ ComingSoon.ttf              ¦
¦  2 ¦ cursive                    ¦ DancingScript-Regular.ttf   ¦
¦  3 ¦ monospace                  ¦ DroidSansMono.ttf           ¦
¦  4 ¦ sans-serif                 ¦ Roboto-Regular.ttf          ¦
¦  5 ¦ sans-serif-black           ¦ Roboto-Black.ttf            ¦
¦  6 ¦ sans-serif-condensed       ¦ RobotoCondensed-Regular.ttf ¦
¦  7 ¦ sans-serif-condensed-light ¦ RobotoCondensed-Light.ttf   ¦
¦  8 ¦ sans-serif-light           ¦ Roboto-Light.ttf            ¦
¦  9 ¦ sans-serif-medium          ¦ Roboto-Medium.ttf           ¦
¦ 10 ¦ sans-serif-smallcaps       ¦ CarroisGothicSC-Regular.ttf ¦
¦ 11 ¦ sans-serif-thin            ¦ Roboto-Thin.ttf             ¦
¦ 12 ¦ serif                      ¦ NotoSerif-Regular.ttf       ¦
¦ 13 ¦ serif-monospace            ¦ CutiveMono.ttf              ¦
+---------------------------------------------------------------+

Here is the parser (based off FontListParser):

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

import org.xmlpull.v1.XmlPullParser;
import org.xmlpull.v1.XmlPullParserException;

import android.util.Xml;

/**
 * Helper class to get the current font families on an Android device.</p>
 * 
 * Usage:</p> {@code List<SystemFont> fonts = FontListParser.safelyGetSystemFonts();}</p>
 */
public final class FontListParser {

    private static final File FONTS_XML = new File("/system/etc/fonts.xml");

    private static final File SYSTEM_FONTS_XML = new File("/system/etc/system_fonts.xml");

    public static List<SystemFont> getSystemFonts() throws Exception {
        String fontsXml;
        if (FONTS_XML.exists()) {
            fontsXml = FONTS_XML.getAbsolutePath();
        } else if (SYSTEM_FONTS_XML.exists()) {
            fontsXml = SYSTEM_FONTS_XML.getAbsolutePath();
        } else {
            throw new RuntimeException("fonts.xml does not exist on this system");
        }
        Config parser = parse(new FileInputStream(fontsXml));
        List<SystemFont> fonts = new ArrayList<>();

        for (Family family : parser.families) {
            if (family.name != null) {
                Font font = null;
                for (Font f : family.fonts) {
                    font = f;
                    if (f.weight == 400) {
                        break;
                    }
                }
                SystemFont systemFont = new SystemFont(family.name, font.fontName);
                if (fonts.contains(systemFont)) {
                    continue;
                }
                fonts.add(new SystemFont(family.name, font.fontName));
            }
        }

        for (Alias alias : parser.aliases) {
            if (alias.name == null || alias.toName == null || alias.weight == 0) {
                continue;
            }
            for (Family family : parser.families) {
                if (family.name == null || !family.name.equals(alias.toName)) {
                    continue;
                }
                for (Font font : family.fonts) {
                    if (font.weight == alias.weight) {
                        fonts.add(new SystemFont(alias.name, font.fontName));
                        break;
                    }
                }
            }
        }

        if (fonts.isEmpty()) {
            throw new Exception("No system fonts found.");
        }

        Collections.sort(fonts, new Comparator<SystemFont>() {

            @Override
            public int compare(SystemFont font1, SystemFont font2) {
                return font1.name.compareToIgnoreCase(font2.name);
            }

        });

        return fonts;
    }

    public static List<SystemFont> safelyGetSystemFonts() {
        try {
            return getSystemFonts();
        } catch (Exception e) {
            String[][] defaultSystemFonts = {
                    {
                            "cursive", "DancingScript-Regular.ttf"
                    }, {
                            "monospace", "DroidSansMono.ttf"
                    }, {
                            "sans-serif", "Roboto-Regular.ttf"
                    }, {
                            "sans-serif-light", "Roboto-Light.ttf"
                    }, {
                            "sans-serif-medium", "Roboto-Medium.ttf"
                    }, {
                            "sans-serif-black", "Roboto-Black.ttf"
                    }, {
                            "sans-serif-condensed", "RobotoCondensed-Regular.ttf"
                    }, {
                            "sans-serif-thin", "Roboto-Thin.ttf"
                    }, {
                            "serif", "NotoSerif-Regular.ttf"
                    }
            };
            List<SystemFont> fonts = new ArrayList<>();
            for (String[] names : defaultSystemFonts) {
                File file = new File("/system/fonts", names[1]);
                if (file.exists()) {
                    fonts.add(new SystemFont(names[0], file.getAbsolutePath()));
                }
            }
            return fonts;
        }
    }

    /* Parse fallback list (no names) */
    public static Config parse(InputStream in) throws XmlPullParserException, IOException {
        try {
            XmlPullParser parser = Xml.newPullParser();
            parser.setInput(in, null);
            parser.nextTag();
            return readFamilies(parser);
        } finally {
            in.close();
        }
    }

    private static Alias readAlias(XmlPullParser parser) throws XmlPullParserException, IOException {
        Alias alias = new Alias();
        alias.name = parser.getAttributeValue(null, "name");
        alias.toName = parser.getAttributeValue(null, "to");
        String weightStr = parser.getAttributeValue(null, "weight");
        if (weightStr == null) {
            alias.weight = 0;
        } else {
            alias.weight = Integer.parseInt(weightStr);
        }
        skip(parser); // alias tag is empty, ignore any contents and consume end tag
        return alias;
    }

    private static Config readFamilies(XmlPullParser parser) throws XmlPullParserException,
            IOException {
        Config config = new Config();
        parser.require(XmlPullParser.START_TAG, null, "familyset");
        while (parser.next() != XmlPullParser.END_TAG) {
            if (parser.getEventType() != XmlPullParser.START_TAG) {
                continue;
            }
            if (parser.getName().equals("family")) {
                config.families.add(readFamily(parser));
            } else if (parser.getName().equals("alias")) {
                config.aliases.add(readAlias(parser));
            } else {
                skip(parser);
            }
        }
        return config;
    }

    private static Family readFamily(XmlPullParser parser) throws XmlPullParserException,
            IOException {
        String name = parser.getAttributeValue(null, "name");
        String lang = parser.getAttributeValue(null, "lang");
        String variant = parser.getAttributeValue(null, "variant");
        List<Font> fonts = new ArrayList<Font>();
        while (parser.next() != XmlPullParser.END_TAG) {
            if (parser.getEventType() != XmlPullParser.START_TAG) {
                continue;
            }
            String tag = parser.getName();
            if (tag.equals("font")) {
                String weightStr = parser.getAttributeValue(null, "weight");
                int weight = weightStr == null ? 400 : Integer.parseInt(weightStr);
                boolean isItalic = "italic".equals(parser.getAttributeValue(null, "style"));
                String filename = parser.nextText();
                String fullFilename = "/system/fonts/" + filename;
                fonts.add(new Font(fullFilename, weight, isItalic));
            } else {
                skip(parser);
            }
        }
        return new Family(name, fonts, lang, variant);
    }

    private static void skip(XmlPullParser parser) throws XmlPullParserException, IOException {
        int depth = 1;
        while (depth > 0) {
            switch (parser.next()) {
            case XmlPullParser.START_TAG:
                depth++;
                break;
            case XmlPullParser.END_TAG:
                depth--;
                break;
            }
        }
    }

    private FontListParser() {

    }

    public static class Alias {

        public String name;

        public String toName;

        public int weight;
    }

    public static class Config {

        public List<Alias> aliases;

        public List<Family> families;

        Config() {
            families = new ArrayList<Family>();
            aliases = new ArrayList<Alias>();
        }

    }

    public static class Family {

        public List<Font> fonts;

        public String lang;

        public String name;

        public String variant;

        public Family(String name, List<Font> fonts, String lang, String variant) {
            this.name = name;
            this.fonts = fonts;
            this.lang = lang;
            this.variant = variant;
        }

    }

    public static class Font {

        public String fontName;

        public boolean isItalic;

        public int weight;

        Font(String fontName, int weight, boolean isItalic) {
            this.fontName = fontName;
            this.weight = weight;
            this.isItalic = isItalic;
        }

    }

    public static class SystemFont {

        public String name;

        public String path;

        public SystemFont(String name, String path) {
            this.name = name;
            this.path = path;
        }

    }
}

Feel free to use the above class in your project. For example, you could give your users a selection of font families and set the typeface based on their preference.

A small incomplete example:

final List<FontListParser.SystemFont> fonts = FontListParser.safelyGetSystemFonts();
String[] items = new String[fonts.size()];
for (int i = 0; i < fonts.size(); i++) {
    items[i] = fonts.get(i).name;
}

new AlertDialog.Builder(this).setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
    @Override
    public void onClick(DialogInterface dialog, int which) {
        FontListParser.SystemFont selectedFont = fonts.get(which);
        // TODO: do something with the font
        Toast.makeText(getApplicationContext(), selectedFont.path, Toast.LENGTH_LONG).show();
    }
}).show();

Allowed memory size of 33554432 bytes exhausted (tried to allocate 43148176 bytes) in php

Run this command in your Magento root directory php -d memory_limit=4G bin/magento

How to use curl in a shell script?

#!/bin/bash                                                                                                                                                                                     
CURL='/usr/bin/curl'
RVMHTTP="https://raw.github.com/wayneeseguin/rvm/master/binscripts/rvm-installer"
CURLARGS="-f -s -S -k"

# you can store the result in a variable
raw="$($CURL $CURLARGS $RVMHTTP)"

# or you can redirect it into a file:
$CURL $CURLARGS $RVMHTTP > /tmp/rvm-installer

or:

Execute bash script from URL

Reading in from System.in - Java

You can use System.in to read from the standard input. It works just like entering it from a keyboard. The OS handles going from file to standard input.

class MyProg {

    public static void main(String[] args) {
        Scanner sc = new Scanner(System.in);
        System.out.println("Printing the file passed in:");
        while(sc.hasNextLine()) System.out.println(sc.nextLine());
    }
}

Convert an image to grayscale

"I want a Bitmap d, that is grayscale. I do see a consructor that includes System.Drawing.Imaging.PixelFormat, but I don't understand how to use that."

Here is how to do this

Bitmap grayScaleBP = new 
         System.Drawing.Bitmap(2, 2, System.Drawing.Imaging.PixelFormat.Format16bppGrayScale);

EDIT: To convert to grayscale

             Bitmap c = new Bitmap("fromFile");
             Bitmap d;
             int x, y;

             // Loop through the images pixels to reset color.
             for (x = 0; x < c.Width; x++)
             {
                 for (y = 0; y < c.Height; y++)
                 {
                     Color pixelColor = c.GetPixel(x, y);
                     Color newColor = Color.FromArgb(pixelColor.R, 0, 0);
                     c.SetPixel(x, y, newColor); // Now greyscale
                 }
             }
            d = c;   // d is grayscale version of c  

Faster Version from switchonthecode follow link for full analysis:

public static Bitmap MakeGrayscale3(Bitmap original)
{
   //create a blank bitmap the same size as original
   Bitmap newBitmap = new Bitmap(original.Width, original.Height);

   //get a graphics object from the new image
   using(Graphics g = Graphics.FromImage(newBitmap)){

       //create the grayscale ColorMatrix
       ColorMatrix colorMatrix = new ColorMatrix(
          new float[][] 
          {
             new float[] {.3f, .3f, .3f, 0, 0},
             new float[] {.59f, .59f, .59f, 0, 0},
             new float[] {.11f, .11f, .11f, 0, 0},
             new float[] {0, 0, 0, 1, 0},
             new float[] {0, 0, 0, 0, 1}
          });

       //create some image attributes
       using(ImageAttributes attributes = new ImageAttributes()){

           //set the color matrix attribute
           attributes.SetColorMatrix(colorMatrix);

           //draw the original image on the new image
           //using the grayscale color matrix
           g.DrawImage(original, new Rectangle(0, 0, original.Width, original.Height),
                       0, 0, original.Width, original.Height, GraphicsUnit.Pixel, attributes);
       }
   }
   return newBitmap;
}