Programs & Examples On #Blobs

How do I convert from BLOB to TEXT in MySQL?

phpMyAdmin screenshot Using phpMyAdmin you can also set the options to show BLOB content and show complete text.

How to get a file or blob from an object URL?

Modern solution:

let blob = await fetch(url).then(r => r.blob());

The url can be an object url or a normal url.

Error Message : Cannot find or open the PDB file

If that message is bother you, You need run Visual Studio with administrative rights to apply this direction on Visual Studio.

Tools-> Options-> Debugging-> Symbols and select check in a box "Microsoft Symbol Servers", mark load all modules then click Load all Symbols.

Everything else Visual Studio will do it for you, and you will have this message under Debug in Output window "Native' has exited with code 0 (0x0)"

YouTube: How to present embed video with sound muted

<iframe width="560" height="315" src="https://www.youtube-nocookie.com/embed/ObHKvS2qSp8?list=PLF8tTShmRC6uppiZ_v-Xj-E1EtR3QCTox&autoplay=1&controls=1&loop=1&mute=1" frameborder="0" allowfullscreen></iframe>



<iframe width="560" height="315" src="https://www.youtube.com/embed/ObHKvS2qSp8?list=PLF8tTShmRC6uppiZ_v-Xj-E1EtR3QCTox&autoplay=1&controls=1&loop=1&mute=1" frameborder="0" allowfullscreen></iframe>

Easy way to dismiss keyboard?

It's not pretty, but the way I resign the firstResponder when I don't know what that the responder is:

Create an UITextField, either in IB or programmatically. Make it Hidden. Link it up to your code if you made it in IB. Then, when you want to dismiss the keyboard, you switch the responder to the invisible text field, and immediately resign it:

  [self.invisibleField becomeFirstResponder];
  [self.invisibleField resignFirstResponder];

How to find children of nodes using BeautifulSoup

There's a super small section in the DOCs that shows how to find/find_all direct children.

https://www.crummy.com/software/BeautifulSoup/bs4/doc/#the-recursive-argument

In your case as you want link1 which is first direct child:

# for only first direct child
soup.find("li", { "class" : "test" }).find("a", recursive=False)

If you want all direct children:

# for all direct children
soup.find("li", { "class" : "test" }).findAll("a", recursive=False)

Renaming column names of a DataFrame in Spark Scala

Sometime we have the column name is below format in SQLServer or MySQL table

Ex  : Account Number,customer number

But Hive tables do not support column name containing spaces, so please use below solution to rename your old column names.

Solution:

val renamedColumns = df.columns.map(c => df(c).as(c.replaceAll(" ", "_").toLowerCase()))
df = df.select(renamedColumns: _*)

How to change an application icon programmatically in Android?

@P-A's solution partially works for me. Detail my findings below:

1) The first code snippet is incorrect, see below:

<activity
    ...
    <intent-filter>
        ==> <action android:name="android.intent.action.MAIN" /> <== This line shouldn't be deleted, otherwise will have compile error
        <category android:name="android.intent.category.LAUNCHER" /> //DELETE THIS LINE
    </intent-filter>
</activity>

2) Should use following code to disable all icons before enabling another one, otherwise it will add a new icon, instead of replacing it.

getPackageManager().setComponentEnabledSetting(
        getComponentName(), PackageManager.COMPONENT_ENABLED_STATE_DISABLED, PackageManager.DONT_KILL_APP);

BUT, if you use code above, then shortcut on homescreen will be removed! And it won't be automatically added back. You might be able to programmatically add icon back, but it probably won't stay in the same position as before.

3) Note that the icon won't get changed immediately, it might take several seconds. If you click it right after changing, you might get an error saying: "App isn't installed".

So, IMHO this solution is only suitable for changing icon in app launcher only, not for shortcuts (i.e. the icon on homescreen)

JVM heap parameters

if you wrote: -Xms512m -Xmx512m when it start, java allocate in those moment 512m of ram for his process and cant increment.

-Xms64m -Xmx512m when it start, java allocate only 64m of ram for his process, but java can be increment his memory occupation while 512m.

I think that second thing is better because you give to java the automatic memory management.

How do I get elapsed time in milliseconds in Ruby?

You can add a little syntax sugar to the above solution with the following:

class Time
  def to_ms
    (self.to_f * 1000.0).to_i
  end
end

start_time = Time.now
sleep(3)
end_time = Time.now
elapsed_time = end_time.to_ms - start_time.to_ms  # => 3004

How to add elements to a list in R (loop)

You should not add to your list using c inside the loop, because that can result in very very slow code. Basically when you do c(l, new_element), the whole contents of the list are copied. Instead of that, you need to access the elements of the list by index. If you know how long your list is going to be, it's best to initialise it to this size using l <- vector("list", N). If you don't you can initialise it to have length equal to some large number (e.g if you have an upper bound on the number of iterations) and then just pick the non-NULL elements after the loop has finished. Anyway, the basic point is that you should have an index to keep track of the list element and add using that eg

i <- 1
while(...) {
    l[[i]] <- new_element
    i <- i + 1
}

For more info have a look at Patrick Burns' The R Inferno (Chapter 2).

Android 8: Cleartext HTTP traffic not permitted

If possible change your url's from HTTP to HTTPS;

It works out!!!

recursively use scp but excluding some folders

This one works fine for me as the directories structure is not important for me.

scp -r USER@HOSTNAME:~/bench1/?cpu/p_?/image/ .

Assuming /bench1 is in the home directory of the current user. Also, change USER and HOSTNAME to the real values.

width:auto for <input> fields

As stated in the other answer, width: auto doesn't work due to the width being generated by the input's size attribute, which cannot be set to "auto" or anything similar.

There are a few workarounds you can use to cause it to play nicely with the box model, but nothing fantastic as far as I know.

First you can set the padding in the field using percentages, making sure that the width adds up to 100%, e.g.:

input {
  width: 98%;
  padding: 1%;
}

Another thing you might try is using absolute positioning, with left and right set to 0. Using this markup:

<fieldset>
    <input type="text" />
</fieldset>

And this CSS:

fieldset {
  position: relative;
}

input {
    position: absolute;
    left: 0;
    right: 0;
}

This absolute positioning will cause the input to fill the parent fieldset horizontally, regardless of the input's padding or margin. However a huge downside of this is that you now have to deal with the height of the fieldset, which will be 0 unless you set it. If your inputs are all the same height this will work for you, simply set the fieldset's height to whatever the input's height should be.

Other than this there are some JS solutions, but I don't like applying basic styling with JS.

How to detect reliably Mac OS X, iOS, Linux, Windows in C preprocessor?

As Jake points out, TARGET_IPHONE_SIMULATOR is a subset of TARGET_OS_IPHONE.

Also, TARGET_OS_IPHONE is a subset of TARGET_OS_MAC.

So a better approach might be:

#ifdef _WIN64
   //define something for Windows (64-bit)
#elif _WIN32
   //define something for Windows (32-bit)
#elif __APPLE__
    #include "TargetConditionals.h"
    #if TARGET_OS_IPHONE && TARGET_IPHONE_SIMULATOR
        // define something for simulator   
    #elif TARGET_OS_IPHONE
        // define something for iphone  
    #else
        #define TARGET_OS_OSX 1
        // define something for OSX
    #endif
#elif __linux
    // linux
#elif __unix // all unices not caught above
    // Unix
#elif __posix
    // POSIX
#endif

jQuery Upload Progress and AJAX file upload

Uploading files is actually possible with AJAX these days. Yes, AJAX, not some crappy AJAX wannabes like swf or java.

This example might help you out: https://webblocks.nl/tests/ajax/file-drag-drop.html

(It also includes the drag/drop interface but that's easily ignored.)

Basically what it comes down to is this:

<input id="files" type="file" />

<script>
document.getElementById('files').addEventListener('change', function(e) {
    var file = this.files[0];
    var xhr = new XMLHttpRequest();
    (xhr.upload || xhr).addEventListener('progress', function(e) {
        var done = e.position || e.loaded
        var total = e.totalSize || e.total;
        console.log('xhr progress: ' + Math.round(done/total*100) + '%');
    });
    xhr.addEventListener('load', function(e) {
        console.log('xhr upload complete', e, this.responseText);
    });
    xhr.open('post', '/URL-HERE', true);
    xhr.send(file);
});
</script>

(demo: http://jsfiddle.net/rudiedirkx/jzxmro8r/)

So basically what it comes down to is this =)

xhr.send(file);

Where file is typeof Blob: http://www.w3.org/TR/FileAPI/

Another (better IMO) way is to use FormData. This allows you to 1) name a file, like in a form and 2) send other stuff (files too), like in a form.

var fd = new FormData;
fd.append('photo1', file);
fd.append('photo2', file2);
fd.append('other_data', 'foo bar');
xhr.send(fd);

FormData makes the server code cleaner and more backward compatible (since the request now has the exact same format as normal forms).

All of it is not experimental, but very modern. Chrome 8+ and Firefox 4+ know what to do, but I don't know about any others.

This is how I handled the request (1 image per request) in PHP:

if ( isset($_FILES['file']) ) {
    $filename = basename($_FILES['file']['name']);
    $error = true;

    // Only upload if on my home win dev machine
    if ( isset($_SERVER['WINDIR']) ) {
        $path = 'uploads/'.$filename;
        $error = !move_uploaded_file($_FILES['file']['tmp_name'], $path);
    }

    $rsp = array(
        'error' => $error, // Used in JS
        'filename' => $filename,
        'filepath' => '/tests/uploads/' . $filename, // Web accessible
    );
    echo json_encode($rsp);
    exit;
}

Authentication failed because remote party has closed the transport stream

This happened to me when an web request endpoint was switched to another server that accepted TLS1.2 requests only. Tried so many attempts mostly found on Stackoverflow like

  1. Registry Keys ,
  2. Added :
    System.Net.ServicePointManager.SecurityProtocol |= System.Net.SecurityProtocolType.Tls12; to Global.ASX OnStart,
  3. Added in Web.config.
  4. Updated .Net framework to 4.7.2 Still getting same Exception.

The exception received did no make justice to the actual problem I was facing and found no help from the service operator.

To solve this I have to add a new Cipher Suite TLS_DHE_RSA_WITH_AES_256_GCM_SHA384 I have used IIS Crypto 2.0 Tool from here as shown below.

enter image description here

mongo - couldn't connect to server 127.0.0.1:27017

Error: couldn't connect to server 127.0.0.1:27017, connection attempt failed: SocketException: Error connecting to 127.0.0.1:27017 :: caused by :: No connection could be made because the target machine actively refused it.

This error caused because Mongo Server been closed

Simple Follow these steps

  1. Open Task Manager
  2. Go to >Services
  3. Find MongoDB
  4. Right click and select Start

Add a Progress Bar in WebView

Here is the code that I am using:

Inside WebViewClient:

               @Override
             public void onPageStarted(WebView view, String url, Bitmap favicon) {

              super.onPageStarted(view, url, favicon);
              findViewById(R.id.progress1).setVisibility(View.VISIBLE);
             }

            @Override
            public void onPageFinished(WebView view, String url) {
                findViewById(R.id.progress1).setVisibility(View.GONE);
            }

Here is the XML :

<ProgressBar
    android:id="@+id/progress1"
    android:layout_centerHorizontal="true"
    android:layout_centerVertical="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content" />

Hope this helps..

Array of structs example

Given an instance of the struct, you set the values.

    student thisStudent;
    Console.WriteLine("Please enter StudentId, StudentName, CourseName, Date-Of-Birth");
    thisStudent.s_id = int.Parse(Console.ReadLine());
    thisStudent.s_name = Console.ReadLine();
    thisStudent.c_name = Console.ReadLine();
    thisStudent.s_dob = Console.ReadLine();

Note this code is incredibly fragile, since we aren't checking the input from the user at all. And you aren't clear to the user that you expect each data point to be entered on a separate line.

How can I extract embedded fonts from a PDF as valid font files?

This is a followup to the font-forge section of @Kurt Pfeifle's answer, specific to Red Hat (and possibly other Linux distros).

  1. After opening the PDF and selecting the font you want, you will want to select "File -> Generate Fonts..." option.
  2. If there are errors in the file, you can choose to ignore them or save the file and edit them. Most of the errors can be fixed automatically if you click "Fix" enough times.
  3. Click "Element -> Font Info...", and "Fontname", "Family Name" and "Name for Humans" are all set to values you like. If not, modify them and save the file somewhere. These names will determine how your font appears on the system.
  4. Select your file name and click "Save..."

Once you have your TTF file, you can install it on your system by

  1. Copying it to folder /usr/share/fonts (as root)
  2. Running fc-cache -f /usr/share/fonts/ (as root)

How to get distinct values for non-key column fields in Laravel?

// Get unique value for table 'add_new_videos' column name 'project_id'
$project_id = DB::table('add_new_videos')->distinct()->get(['project_id']);

Left Outer Join using + sign in Oracle 11g

LEFT OUTER JOIN

SELECT * FROM A, B WHERE A.column = B.column(+)

RIGHT OUTER JOIN

SELECT * FROM A, B WHERE A.column (+)= B.column

Convert string into Date type on Python

While it seems the question was answered per the OP's request, none of the answers give a good way to get a datetime.date object instead of a datetime.datetime. So for those searching and finding this thread:

datetime.date has no .strptime method; use the one on datetime.datetime instead and then call .date() on it to receive the datetime.date object.

Like so:

>>> from datetime import datetime
>>> datetime.strptime('2014-12-04', '%Y-%m-%d').date()
datetime.date(2014, 12, 4)

How to convert JSON string into List of Java object?

You can also use Gson for this scenario.

Gson gson = new Gson();
NameList nameList = gson.fromJson(data, NameList.class);

List<Name> list = nameList.getList();

Your NameList class could look like:

class NameList{
 List<Name> list;
 //getter and setter
}

How to create a secure random AES key in Java?

Using KeyGenerator would be the preferred method. As Duncan indicated, I would certainly give the key size during initialization. KeyFactory is a method that should be used for pre-existing keys.

OK, so lets get to the nitty-gritty of this. In principle AES keys can have any value. There are no "weak keys" as in (3)DES. Nor are there any bits that have a specific meaning as in (3)DES parity bits. So generating a key can be as simple as generating a byte array with random values, and creating a SecretKeySpec around it.

But there are still advantages to the method you are using: the KeyGenerator is specifically created to generate keys. This means that the code may be optimized for this generation. This could have efficiency and security benefits. It might be programmed to avoid a timing side channel attacks that would expose the key, for instance. Note that it may already be a good idea to clear any byte[] that hold key information as they may be leaked into a swap file (this may be the case anyway though).

Furthermore, as said, not all algorithms are using fully random keys. So using KeyGenerator would make it easier to switch to other algorithms. More modern ciphers will only accept fully random keys though; this is seen as a major benefit over e.g. DES.

Finally, and in my case the most important reason, it that the KeyGenerator method is the only valid way of handling AES keys within a secure token (smart card, TPM, USB token or HSM). If you create the byte[] with the SecretKeySpec then the key must come from memory. That means that the key may be put in the secure token, but that the key is exposed in memory regardless. Normally, secure tokens only work with keys that are either generated in the secure token or are injected by e.g. a smart card or a key ceremony. A KeyGenerator can be supplied with a provider so that the key is directly generated within the secure token.

As indicated in Duncan's answer: always specify the key size (and any other parameters) explicitly. Do not rely on provider defaults as this will make it unclear what your application is doing, and each provider may have its own defaults.

How to display an alert box from C# in ASP.NET?

After insertion code,

ScriptManager.RegisterClientScriptBlock(this, this.GetType(), "alertMessage", "alert('Record Inserted Successfully')", true);

How to get parameter on Angular2 route in Angular way?

Update: Sep 2019

As a few people have mentioned, the parameters in paramMap should be accessed using the common MapAPI:

To get a snapshot of the params, when you don't care that they may change:

this.bankName = this.route.snapshot.paramMap.get('bank');

To subscribe and be alerted to changes in the parameter values (typically as a result of the router's navigation)

this.route.paramMap.subscribe( paramMap => {
    this.bankName = paramMap.get('bank');
})

Update: Aug 2017

Since Angular 4, params have been deprecated in favor of the new interface paramMap. The code for the problem above should work if you simply substitute one for the other.

Original Answer

If you inject ActivatedRoute in your component, you'll be able to extract the route parameters

    import {ActivatedRoute} from '@angular/router';
    ...
    
    constructor(private route:ActivatedRoute){}
    bankName:string;
    
    ngOnInit(){
        // 'bank' is the name of the route parameter
        this.bankName = this.route.snapshot.params['bank'];
    }

If you expect users to navigate from bank to bank directly, without navigating to another component first, you ought to access the parameter through an observable:

    ngOnInit(){
        this.route.params.subscribe( params =>
            this.bankName = params['bank'];
        )
    }

For the docs, including the differences between the two check out this link and search for "activatedroute"

How can I make the computer beep in C#?

Try this

Console.WriteLine("\a")

jquery/javascript convert date string to date

If you only need it once, it's overkill to load a plugin.

For a date "dd/mm/yyyy", this works for me:

new Date(d.date.substring(6, 10),d.date.substring(3, 5)-1,d.date.substring(0, 2));

Just invert month and day for mm/dd/yyyy, the syntax is new Date(y,m,d)

How to add Certificate Authority file in CentOS 7

copy your certificates inside

/etc/pki/ca-trust/source/anchors/

then run the following command

update-ca-trust

How to create empty folder in java?

You can create folder using the following Java code:

File dir = new File("nameoffolder");
dir.mkdir();

By executing above you will have folder 'nameoffolder' in current folder.

'Missing recommended icon file - The bundle does not contain an app icon for iPhone / iPod Touch of exactly '120x120' pixels, in .png format'

For any Xamarin.iOS or Xamarin.Forms developers, additionally you will want to check the .csproj file (for the iOS project) and ensure that it contains references to the PNG's and not just the Asset Catalog i.e.

<ItemGroup>
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Contents.json" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-40.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-40%402x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-40%403x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-60%402x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-60%403x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-72.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-72%402x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-76.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-76%402x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-83.5%402x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-Small-50.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-Small-50%402x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-Small.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-Small%402x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon-Small%403x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\Icon%402x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\NotificationIcon%402x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\NotificationIcon%403x.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\NotificationIcon~ipad.png" />
<ImageAsset Include="Resources\Images.xcassets\AppIcon.appiconset\NotificationIcon~ipad%402x.png" />
</ItemGroup>

Return Max Value of range that is determined by an Index & Match lookup

You can easily change the match-type to 1 when you are looking for the greatest value or to -1 when looking for the smallest value.

Select only rows if its value in a particular column is less than the value in the other column

df[df$aged <= df$laclen, ] 

Should do the trick. The square brackets allow you to index based on a logical expression.

How to substitute shell variables in complex text files

Looking, it turns out on my system there is an envsubst command which is part of the gettext-base package.

So, this makes it easy:

envsubst < "source.txt" > "destination.txt"

Note if you want to use the same file for both, you'll have to use something like moreutil's sponge, as suggested by Johnny Utahh: envsubst < "source.txt" | sponge "source.txt". (Because the shell redirect will otherwise empty the file before its read.)

Working with huge files in VIM

this is old but, use nano, vim or gvim

Git - What is the difference between push.default "matching" and "simple"

From GIT documentation: Git Docs

Below gives the full information. In short, simple will only push the current working branch and even then only if it also has the same name on the remote. This is a very good setting for beginners and will become the default in GIT 2.0

Whereas matching will push all branches locally that have the same name on the remote. (Without regard to your current working branch ). This means potentially many different branches will be pushed, including those that you might not even want to share.

In my personal usage, I generally use a different option: current which pushes the current working branch, (because I always branch for any changes). But for a beginner I'd suggest simple

push.default
Defines the action git push should take if no refspec is explicitly given. Different values are well-suited for specific workflows; for instance, in a purely central workflow (i.e. the fetch source is equal to the push destination), upstream is probably what you want. Possible values are:

nothing - do not push anything (error out) unless a refspec is explicitly given. This is primarily meant for people who want to avoid mistakes by always being explicit.

current - push the current branch to update a branch with the same name on the receiving end. Works in both central and non-central workflows.

upstream - push the current branch back to the branch whose changes are usually integrated into the current branch (which is called @{upstream}). This mode only makes sense if you are pushing to the same repository you would normally pull from (i.e. central workflow).

simple - in centralized workflow, work like upstream with an added safety to refuse to push if the upstream branch's name is different from the local one.

When pushing to a remote that is different from the remote you normally pull from, work as current. This is the safest option and is suited for beginners.

This mode will become the default in Git 2.0.

matching - push all branches having the same name on both ends. This makes the repository you are pushing to remember the set of branches that will be pushed out (e.g. if you always push maint and master there and no other branches, the repository you push to will have these two branches, and your local maint and master will be pushed there).

To use this mode effectively, you have to make sure all the branches you would push out are ready to be pushed out before running git push, as the whole point of this mode is to allow you to push all of the branches in one go. If you usually finish work on only one branch and push out the result, while other branches are unfinished, this mode is not for you. Also this mode is not suitable for pushing into a shared central repository, as other people may add new branches there, or update the tip of existing branches outside your control.

This is currently the default, but Git 2.0 will change the default to simple.

How to set the component size with GridLayout? Is there a better way?

An alternative to other layouts, might be to put your panel with the GridLayout, inside another panel that is a FlowLayout. That way your spacing will be intact but will not expand across the entire available space.

Make virtualenv inherit specific packages from your global site-packages

Create the environment with virtualenv --system-site-packages . Then, activate the virtualenv and when you want things installed in the virtualenv rather than the system python, use pip install --ignore-installed or pip install -I . That way pip will install what you've requested locally even though a system-wide version exists. Your python interpreter will look first in the virtualenv's package directory, so those packages should shadow the global ones.

Python how to plot graph sine wave

import matplotlib.pyplot as plt # For ploting
import numpy as np # to work with numerical data efficiently

fs = 100 # sample rate 
f = 2 # the frequency of the signal

x = np.arange(fs) # the points on the x axis for plotting
# compute the value (amplitude) of the sin wave at the for each sample
y = np.sin(2*np.pi*f * (x/fs)) 

#this instruction can only be used with IPython Notbook. 
% matplotlib inline
# showing the exact location of the smaples
plt.stem(x,y, 'r', )
plt.plot(x,y)

enter image description here

Getting Hour and Minute in PHP

print date('H:i');
$var = date('H:i');

Should do it, for the current time. Use a lower case h for 12 hour clock instead of 24 hour.

More date time formats listed here.

Resize HTML5 canvas to fit window

Setting the canvas coordinate space width and height based on the browser client's dimensions requires you to resize and redraw whenever the browser is resized.

A less convoluted solution is to maintain the drawable dimensions in Javascript variables, but set the canvas dimensions based on the screen.width, screen.height dimensions. Use CSS to fit:

#containingDiv { 
  overflow: hidden;
}
#myCanvas {
  position: absolute; 
  top: 0px;
  left: 0px;
} 

The browser window generally won't ever be larger than the screen itself (except where the screen resolution is misreported, as it could be with non-matching dual monitors), so the background won't show and pixel proportions won't vary. The canvas pixels will be directly proportional to the screen resolution unless you use CSS to scale the canvas.

How do I horizontally center a span element inside a div

Applying inline-block to the element that is to be centered and applying text-align:center to the parent block did the trick for me.

Works even on <span> tags.

Java system properties and environment variables

Array initialization in Perl

What do you mean by "initialize an array to zero"? Arrays don't contain "zero" -- they can contain "zero elements", which is the same as "an empty list". Or, you could have an array with one element, where that element is a zero: my @array = (0);

my @array = (); should work just fine -- it allocates a new array called @array, and then assigns it the empty list, (). Note that this is identical to simply saying my @array;, since the initial value of a new array is the empty list anyway.

Are you sure you are getting an error from this line, and not somewhere else in your code? Ensure you have use strict; use warnings; in your module or script, and check the line number of the error you get. (Posting some contextual code here might help, too.)

How to convert current date to epoch timestamp?

import time
def expires():
    '''return a UNIX style timestamp representing 5 minutes from now'''
    return int(time.time()+300)

@property retain, assign, copy, nonatomic in Objective-C

Atomic property can be accessed by only one thread at a time. It is thread safe. Default is atomic .Please note that there is no keyword atomic

Nonatomic means multiple thread can access the item .It is thread unsafe

So one should be very careful while using atomic .As it affect the performance of your code

SQL: How to get the id of values I just INSERTed?

If your using PHP and MySQL you can use the mysql_insert_id() function which will tell you the ID of item you Just instered.
But without your Language and DBMS I'm just shooting in the dark here.

LINQ: When to use SingleOrDefault vs. FirstOrDefault() with filtering criteria

Both are the element operators and they are used to select a single element from a sequence. But there is a minor difference between them. SingleOrDefault() operator would throw an exception if more than one elements are satisfied the condition where as FirstOrDefault() will not throw any exception for the same. Here is the example.

List<int> items = new List<int>() {9,10,9};
//Returns the first element of a sequence after satisfied the condition more than one elements
int result1 = items.Where(item => item == 9).FirstOrDefault();
//Throw the exception after satisfied the condition more than one elements
int result3 = items.Where(item => item == 9).SingleOrDefault();

How to get a .csv file into R?

You mention that you will call on each vertical column so that you can perform calculations. I assume that you just want to examine each single variable. This can be done through the following.

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

df$ID

df$GRADES

df$GPA

Might be helpful just to assign the data to a variable.

var3 <- df$GPA

jQuery set checkbox checked

<body>
      <input id="IsActive" name="IsActive" type="checkbox" value="false">
</body>

<script>
    $('#IsActive').change(function () {
         var chk = $("#IsActive")
         var IsChecked = chk[0].checked
         if (IsChecked) {
          chk.attr('checked', 'checked')
         } 
         else {
          chk.removeAttr('checked')                            
         }
          chk.attr('value', IsChecked)
     });
</script>

What does [object Object] mean? (JavaScript)

That is because there are different types of objects in Javascript!

For example

  • Function objects:

stringify(function (){}) -> [object Function]

  • Array objects:

stringify([]) -> [object Array]

  • RegExp objects

stringify(/x/) -> [object RegExp]

  • Date objects

stringify(new Date) -> [object Date]

...
  • Object objects!

stringify({}) -> [object Object]

the constructor function is called Object (with a capital "O"), and the term "object" (with small "o") refers to the structural nature of the thingy.

When you're talking about "objects" in Javascript, you actually mean "Object objects", and not the other types.

If you want to see value inside "[Object objects]" use:

console.log(JSON.stringify(result))

Class 'App\Http\Controllers\DB' not found and I also cannot use a new Model

Use the backslash before db on the header and you can use it then typically as you wrote it before.

Here is the example:

Use \DB;

Then inside your controller class you can use as you did before, like that ie :

$item = DB::table('items')->get();

Update all objects in a collection using LINQ

There is no built-in extension method to do this. Although defining one is fairly straight forward. At the bottom of the post is a method I defined called Iterate. It can be used like so

collection.Iterate(c => { c.PropertyToSet = value;} );

Iterate Source

public static void Iterate<T>(this IEnumerable<T> enumerable, Action<T> callback)
{
    if (enumerable == null)
    {
        throw new ArgumentNullException("enumerable");
    }

    IterateHelper(enumerable, (x, i) => callback(x));
}

public static void Iterate<T>(this IEnumerable<T> enumerable, Action<T,int> callback)
{
    if (enumerable == null)
    {
        throw new ArgumentNullException("enumerable");
    }

    IterateHelper(enumerable, callback);
}

private static void IterateHelper<T>(this IEnumerable<T> enumerable, Action<T,int> callback)
{
    int count = 0;
    foreach (var cur in enumerable)
    {
        callback(cur, count);
        count++;
    }
}

Set Response Status Code

I had the same issue with CakePHP 2.0.1

I tried using

header( 'HTTP/1.1 400 BAD REQUEST' );

and

$this->header( 'HTTP/1.1 400 BAD REQUEST' );

However, neither of these solved my issue.

I did eventually resolve it by using

$this->header( 'HTTP/1.1 400: BAD REQUEST' );

After that, no errors or warning from php / CakePHP.

*edit: In the last $this->header function call, I put a colon (:) between the 400 and the description text of the error.

Java: How to Indent XML Generated by Transformer

The following code is working for me with Java 7. I set the indent (yes) and indent-amount (2) on the transformer (not the transformer factory) to get it working.

TransformerFactory tf = TransformerFactory.newInstance();
Transformer t = tf.newTransformer();
t.setOutputProperty("{http://xml.apache.org/xslt}indent-amount", "2");
t.setOutputProperty(OutputKeys.INDENT, "yes");
t.transform(source, result);

@mabac's solution to set the attribute didn't work for me, but @lapo's comment proved helpful.

Saving the PuTTY session logging

It works fine for me, but it's a little tricky :)

  • First open the PuTTY configuration.
  • Select the session (right part of the window, Saved Sessions)
  • Click Load (now you have loaded Host Name, Port and Connection type)
  • Then click Logging (under Session on the left)
  • Change whatever settings you want
  • Go back to Session window and click the Save button

Now you have settings for this session set (every time you load session it will be logged).

Flutter Countdown Timer

Little late to the party but why don't you guys try animation.No I am not telling you to manage animation controllers and disposing them off and all that stuff.theres a built-in widget for that called TweenAnimationBuilder.You can animate between values of any type,heres an example with a Duration class

TweenAnimationBuilder<Duration>(
              duration: Duration(minutes: 3),
              tween: Tween(begin: Duration(minutes: 3), end: Duration.zero),
              onEnd: () {
                print('Timer ended');
              },
              builder: (BuildContext context, Duration value, Widget child) {
              final minutes = value.inMinutes;
              final seconds = value.inSeconds % 60;
              return Padding(
                     padding: const EdgeInsets.symmetric(vertical: 5),
                     child: Text('$minutes:$seconds',
                            textAlign: TextAlign.center,
                            style: TextStyle(
                            color: Colors.black,
                            fontWeight: FontWeight.bold,
                            fontSize: 30)));
              }),

and You also get onEnd call back which notifies you when the animation completes;

here's the output

Disable Tensorflow debugging information

To add some flexibility here, you can achieve more fine-grained control over the level of logging by writing a function that filters out messages however you like:

logging.getLogger('tensorflow').addFilter(my_filter_func)

where my_filter_func accepts a LogRecord object as input [LogRecord docs] and returns zero if you want the message thrown out; nonzero otherwise.

Here's an example filter that only keeps every nth info message (Python 3 due to the use of nonlocal here):

def keep_every_nth_info(n):
    i = -1
    def filter_record(record):
        nonlocal i
        i += 1
        return int(record.levelname != 'INFO' or i % n == 0)
    return filter_record

# Example usage for TensorFlow:
logging.getLogger('tensorflow').addFilter(keep_every_nth_info(5))

All of the above has assumed that TensorFlow has set up its logging state already. You can ensure this without side effects by calling tf.logging.get_verbosity() before adding a filter.

git diff file against its last change

One of the ways to use git diff is:

git diff <commit> <path>

And a common way to refer one commit of the last commit is as a relative path to the actual HEAD. You can reference previous commits as HEAD^ (in your example this will be 123abc) or HEAD^^ (456def in your example), etc ...

So the answer to your question is:

git diff HEAD^^ myfile

How can I copy columns from one sheet to another with VBA in Excel?

I'm not sure why you'd be getting subscript out of range unless your sheets weren't actually called Sheet1 or Sheet2. When I rename my Sheet2 to Sheet_2, I get that same problem.

In addition, some of your code seems the wrong way about (you paste before selecting the second sheet). This code works fine for me.

Sub OneCell()
    Sheets("Sheet1").Select
    Range("A1:A3").Copy
    Sheets("Sheet2").Select
    Range("b1:b3").Select
    ActiveSheet.Paste
End Sub

If you don't want to know about what the sheets are called, you can use integer indexes as follows:

Sub OneCell()
    Sheets(1).Select
    Range("A1:A3").Copy
    Sheets(2).Select
    Range("b1:b3").Select
    ActiveSheet.Paste
End Sub

Normalize numpy array columns in python

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

Starting with your example array:

import numpy as np

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

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

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

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


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

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

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

Getting the textarea value of a ckeditor textarea with javascript

Simply execute

CKEDITOR.instances[elementId].getData();

with element id = id of element assigned the editor.

How can I right-align text in a DataGridView column?

To set align text in dataGridCell you have two ways:

Set the align for a specific cell or set for each cell of row.

For one column go to Columns->DataGridViewCellStyle

or

For each column go to RowDefaultCellStyle

The control panel is the same as the follow:

enter image description here

How to read file from res/raw by name

Here is example of taking XML file from raw folder:

 InputStream XmlFileInputStream = getResources().openRawResource(R.raw.taskslists5items); // getting XML

Then you can:

 String sxml = readTextFile(XmlFileInputStream);

when:

 public String readTextFile(InputStream inputStream) {
        ByteArrayOutputStream outputStream = new ByteArrayOutputStream();

        byte buf[] = new byte[1024];
        int len;
        try {
            while ((len = inputStream.read(buf)) != -1) {
                outputStream.write(buf, 0, len);
            }
            outputStream.close();
            inputStream.close();
        } catch (IOException e) {

        }
        return outputStream.toString();
    }

Calling Web API from MVC controller

From my HomeController I want to call this Method and convert Json response to List

No you don't. You really don't want to add the overhead of an HTTP call and (de)serialization when the code is within reach. It's even in the same assembly!

Your ApiController goes against (my preferred) convention anyway. Let it return a concrete type:

public IEnumerable<QDocumentRecord> GetAllRecords()
{
    listOfFiles = ...
    return listOfFiles;
}

If you don't want that and you're absolutely sure you need to return HttpResponseMessage, then still there's absolutely no need to bother with calling JsonConvert.SerializeObject() yourself:

return Request.CreateResponse<List<QDocumentRecord>>(HttpStatusCode.OK, listOfFiles);

Then again, you don't want business logic in a controller, so you extract that into a class that does the work for you:

public class FileListGetter
{
    public IEnumerable<QDocumentRecord> GetAllRecords()
    {
        listOfFiles = ...
        return listOfFiles;
    }
}

Either way, then you can call this class or the ApiController directly from your MVC controller:

public class HomeController : Controller
{
    public ActionResult Index()
    {
        var listOfFiles = new DocumentsController().GetAllRecords();
        // OR
        var listOfFiles = new FileListGetter().GetAllRecords();

        return View(listOfFiles);
    }
}

But if you really, really must do an HTTP request, you can use HttpWebRequest, WebClient, HttpClient or RestSharp, for all of which plenty of tutorials exist.

Difference between git pull and git pull --rebase

Sometimes we have an upstream that rebased/rewound a branch we're depending on. This can be a big problem -- causing messy conflicts for us if we're downstream.

The magic is git pull --rebase

A normal git pull is, loosely speaking, something like this (we'll use a remote called origin and a branch called foo in all these examples):

# assume current checked out branch is "foo"
git fetch origin
git merge origin/foo

At first glance, you might think that a git pull --rebase does just this:

git fetch origin
git rebase origin/foo

But that will not help if the upstream rebase involved any "squashing" (meaning that the patch-ids of the commits changed, not just their order).

Which means git pull --rebase has to do a little bit more than that. Here's an explanation of what it does and how.

Let's say your starting point is this:

a---b---c---d---e  (origin/foo) (also your local "foo")

Time passes, and you have made some commits on top of your own "foo":

a---b---c---d---e---p---q---r (foo)

Meanwhile, in a fit of anti-social rage, the upstream maintainer has not only rebased his "foo", he even used a squash or two. His commit chain now looks like this:

a---b+c---d+e---f  (origin/foo)

A git pull at this point would result in chaos. Even a git fetch; git rebase origin/foo would not cut it, because commits "b" and "c" on one side, and commit "b+c" on the other, would conflict. (And similarly with d, e, and d+e).

What git pull --rebase does, in this case, is:

git fetch origin
git rebase --onto origin/foo e foo

This gives you:

 a---b+c---d+e---f---p'---q'---r' (foo)

You may still get conflicts, but they will be genuine conflicts (between p/q/r and a/b+c/d+e/f), and not conflicts caused by b/c conflicting with b+c, etc.

Answer taken from (and slightly modified):
http://gitolite.com/git-pull--rebase

How to increase the Java stack size?

It is hard to give a sensible solution since you are keen to avoid all sane approaches. Refactoring one line of code is the senible solution.

Note: Using -Xss sets the stack size of every thread and is a very bad idea.

Another approach is byte code manipulation to change the code as follows;

public static long fact(int n) { 
    return n < 2 ? n : n > 127 ? 0 : n * fact(n - 1); 
}

given every answer for n > 127 is 0. This avoid changing the source code.

How to make VS Code to treat other file extensions as certain language?

eg:

// .vscode/settings.json in workspace

{
  "files.associations": {
    "*Container.js": "javascriptreact",
    "**/components/*/*.js": "javascriptreact",
    "**/config/routes.js": "javascriptreact"
  }
}

Base64 Java encode and decode a string

Java 8 now supports BASE64 Encoding and Decoding. You can use the following classes: java.util.Base64, java.util.Base64.Encoder and java.util.Base64.Decoder.

Example usage:

// encode with padding
String encoded = Base64.getEncoder().encodeToString(someByteArray);

// encode without padding
String encoded = Base64.getEncoder().withoutPadding().encodeToString(someByteArray);

// decode a String
byte [] barr = Base64.getDecoder().decode(encoded); 

Coerce multiple columns to factors at once

Here is another tidyverse approach using the modify_at() function from the purrr package.

library(purrr)

# Data frame with only integer columns
data <- data.frame(matrix(sample(1:40), 4, 10, dimnames = list(1:4, LETTERS[1:10])))

# Modify specified columns to a factor class
data_with_factors <- data %>%
    purrr::modify_at(c("A", "C", "E"), factor)


# Check the results:
str(data_with_factors)
# 'data.frame':   4 obs. of  10 variables:
#  $ A: Factor w/ 4 levels "8","12","33",..: 1 3 4 2
#  $ B: int  25 32 2 19
#  $ C: Factor w/ 4 levels "5","15","35",..: 1 3 4 2
#  $ D: int  11 7 27 6
#  $ E: Factor w/ 4 levels "1","4","16","20": 2 3 1 4
#  $ F: int  21 23 39 18
#  $ G: int  31 14 38 26
#  $ H: int  17 24 34 10
#  $ I: int  13 28 30 29
#  $ J: int  3 22 37 9

How to execute INSERT statement using JdbcTemplate class from Spring Framework

If you are planning to use JdbcTemplate in multiple locations, it would be a good idea to create a Spring Bean for it.

Using Java Config it would be:

@Configuration
public class DBConfig {

   @Bean
   public DataSource dataSource() {
      //create a data source
   }

   @Bean
   public JdbcTemplate jdbcTemplate() {
      return new JdbcTemplate(dataSource());
   }

   @Bean
   public TransactionManager transactionManager() {
      return new DataSourceTransactionManager(dataSource());
   }

}

Then a repository that uses that JdbcTemplate could be:

@Repository
public class JdbcSomeRepository implements SomeRepository {

   private final JdbcTemplate jdbcTemplate ;

   @Autowired
   public JdbcSomeRepository(JdbcTemplate jdbcTemplate) {
      this.jdbcTemplate = jdbcTemplate;
   } 

   @Override
   @Transactional 
   public int someUpdate(SomeType someValue, SomeOtherType someOtherValue) {
      return jdbcTemplate.update("INSERT INTO SomeTable(column1, column2) VALUES(?,?)", someValue, someOtherValue)
   }
}

The update method from JdbcTemplate that I have used can be found here.

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

Disable browser 'Save Password' functionality

Markus raised a great point. I decided to look up the autocomplete attribute and got the following:

The only downside to using this attribute is that it is not standard (it works in IE and Mozilla browsers), and would cause XHTML validation to fail. I think this is a case where it's reasonable to break validation however. (source)

So I would have to say that although it doesn't work 100% across the board it is handled in the major browsers so its a great solution.

Is it possible to assign numeric value to an enum in Java?

Extending Bhesh Gurung's answer for assigning values, you can add explicit method to set value

   public ExitCode setValue( int value){
      //  A(104), B(203);
      switch(value){
        case 104: return ExitCode.A;
        case 203: return ExitCode.B;
        default:
                   return ExitCode.Unknown //Keep an default or error enum handy
      }
   }

From calling application

int i = 104; 
ExitCode serverExitCode = ExitCode.setValue(i);

//You've valid enum from now

[Unable to comment to his answer, hence posting it separately]

How can I hide an HTML table row <tr> so that it takes up no space?

HTML:

<input type="checkbox" id="attraction" checked="checked" onchange="updateMap()">poi.attraction</input>

JavaScript:

function updateMap() {
     map.setOptions({'styles': getStyles() });
} 

function getStyles() {
    var styles = [];
    for (var i=0; i < types.length; i++) {
      var style = {};
      var type = types[i];
      var enabled = document.getElementById(type).checked;
      style['featureType'] = 'poi.' + type;
      style['elementType'] = 'labels';
      style['stylers'] = [{'visibility' : (enabled ? 'on' : 'off') }];
      styles.push(style);
    }
    return styles;
}

LaTeX: Prevent line break in a span of text

Also, if you have two subsequent words in regular text and you want to avoid a line break between them, you can use the ~ character.

For example:

As we can see in Fig.~\ref{BlaBla}, there is nothing interesting to see. A~better place..

This can ensure that you don't have a line starting with a figure number (without the Fig. part) or with an uppercase A.

Filtering a pyspark dataframe using isin by exclusion

df.filter((df.bar != 'a') & (df.bar != 'b'))

The response content cannot be parsed because the Internet Explorer engine is not available, or

It is sure because the Invoke-WebRequest command has a dependency on the Internet Explorer assemblies and are invoking it to parse the result as per default behaviour. As Matt suggest, you can simply launch IE and make your selection in the settings prompt which is popping up at first launch. And the error you experience will disappear.

But this is only possible if you run your powershell scripts as the same windows user as whom you launched the IE with. The IE settings are stored under your current windows profile. So if you, like me run your task in a scheduler on a server as the SYSTEM user, this will not work.

So here you will have to change your scripts and add the -UseBasicParsing argument, as ijn this example: $WebResponse = Invoke-WebRequest -Uri $url -TimeoutSec 1800 -ErrorAction:Stop -Method:Post -Headers $headers -UseBasicParsing

find filenames NOT ending in specific extensions on Unix?

find  /data1/batch/source/export   -type f -not  -name "*.dll" -not -name "*.exe"

What's the difference between .bashrc, .bash_profile, and .environment?

According to Josh Staiger, Mac OS X's Terminal.app actually runs a login shell rather than a non-login shell by default for each new terminal window, calling .bash_profile instead of .bashrc.

He recommends:

Most of the time you don’t want to maintain two separate config files for login and non-login shells — when you set a PATH, you want it to apply to both. You can fix this by sourcing .bashrc from your .bash_profile file, then putting PATH and common settings in .bashrc.

To do this, add the following lines to .bash_profile:

if [ -f ~/.bashrc ]; then 
    source ~/.bashrc 
fi

Now when you login to your machine from a console .bashrc will be called.

Why is Python running my module when I import it, and how do I stop it?

You may write your "main.py" like this:

#!/usr/bin/env python

__all__=["somevar", "do_something"]

somevar=""

def do_something():
    pass #blahblah

if __name__=="__main__":
    do_something()

Using AJAX to pass variable to PHP and retrieve those using AJAX again

you have to pass values with the single quotes

$(document).ready(function() {    
    $("#raaagh").click(function(){    
        $.ajax({
            url: 'ajax.php', //This is the current doc
            type: "POST",
            data: ({name: '145'}), //variables should be pass like this
            success: function(data){
                console.log(data);
                           }
        });  
        $.ajax({
    url:'ajax.php',
    data:"",
    dataType:'json',
    success:function(data1){
            var y1=data1;
            console.log(data1);
            }
        });

    });
});

try it it may work.......

Duplicate line in Visual Studio Code

Update that may help Ubuntu users if they still want to use the ? and ? instead of another set of keys.

I just installed a fresh version of VSCode on Ubuntu 18.04 LTS and I had duplicate commands for Add Cursor Above and Add Cursor Below

Original Keybindings

I just removed the bindings that used Ctrl and added my own with the following

Copy Line Up

Ctrl + Shift + ?

Copy Line Down

Ctrl + Shift + ?

New Keybindings

Creating a div element inside a div element in javascript

Yes, you either need to do this onload or in a <script> tag after the closing </body> tag, when the lc element is already found in the document's DOM tree.

Can HTML checkboxes be set to readonly?

<input type="checkbox" readonly="readonly" name="..." />

with jquery:

$(':checkbox[readonly]').click(function(){
            return false;
        });

it still might be a good idea to give some visual hint (css, text,...), that the control won't accept inputs.

Call Jquery function

Just add click event by jquery in $(document).ready() like :

$(document).ready(function(){

                  $('#YourControlID').click(function(){
                     if(Check your condtion)
                     {
                             $.messager.show({  
                                title:'My Title',  
                                msg:'The message content',  
                                showType:'fade',  
                                style:{  
                                    right:'',  
                                    bottom:''  
                                }  
                            });  
                     }
                 });
            });

How can I reorder a list?

If you do not care so much about efficiency, you could rely on numpy's array indexing to make it elegant:

a = ['123', 'abc', 456]
order = [2, 0, 1]
a2 = list( np.array(a, dtype=object)[order] )

How to get string objects instead of Unicode from JSON?

As Mark (Amery) correctly notes: Using PyYaml's deserializer on a json dump works only if you have ASCII only. At least out of the box.

Two quick comments on the PyYaml approach:

  1. NEVER use yaml.load on data from the field. Its a feature(!) of yaml to execute arbitrary code hidden within the structure.

  2. You can make it work also for non ASCII via this:

    def to_utf8(loader, node):
        return loader.construct_scalar(node).encode('utf-8')
    yaml.add_constructor(u'tag:yaml.org,2002:str', to_utf8)
    

But performance wise its of no comparison to Mark Amery's answer:

Throwing some deeply nested sample dicts onto the two methods, I get this (with dt[j] = time delta of json.loads(json.dumps(m))):

     dt[yaml.safe_load(json.dumps(m))] =~ 100 * dt[j]
     dt[byteify recursion(Mark Amery)] =~   5 * dt[j]

So deserialization including fully walking the tree and encoding, well within the order of magnitude of json's C based implementation. I find this remarkably fast and its also more robust than the yaml load at deeply nested structures. And less security error prone, looking at yaml.load.

=> While I would appreciate a pointer to a C only based converter the byteify function should be the default answer.

This holds especially true if your json structure is from the field, containing user input. Because then you probably need to walk anyway over your structure - independent on your desired internal data structures ('unicode sandwich' or byte strings only).

Why?

Unicode normalisation. For the unaware: Take a painkiller and read this.

So using the byteify recursion you kill two birds with one stone:

  1. get your bytestrings from nested json dumps
  2. get user input values normalised, so that you find the stuff in your storage.

In my tests it turned out that replacing the input.encode('utf-8') with a unicodedata.normalize('NFC', input).encode('utf-8') was even faster than w/o NFC - but thats heavily dependent on the sample data I guess.

How to configure PHP to send e-mail?

To fix this, you must review your PHP.INI, and the mail services setup you have in your server.

But my best advice for you is to forget about the mail() function. It depends on PHP.INI settings, it's configuration is different depending on the platform (Linux or Windows), and it can't handle SMTP authentication, which is a big trouble in current days. Too much headache.

Use "PHP Mailer" instead (https://github.com/PHPMailer/PHPMailer), it's a PHP class available for free, and it can handle almost any SMTP server, internal or external, with or without authentication, it works exactly the same way on Linux and Windows, and it won't depend on PHP.INI settings. It comes with many examples, it's very powerful and easy to use.

find first sequence item that matches a criterion

If you don't have any other indexes or sorted information for your objects, then you will have to iterate until such an object is found:

next(obj for obj in objs if obj.val == 5)

This is however faster than a complete list comprehension. Compare these two:

[i for i in xrange(100000) if i == 1000][0]

next(i for i in xrange(100000) if i == 1000)

The first one needs 5.75ms, the second one 58.3µs (100 times faster because the loop 100 times shorter).

Proper way to return JSON using node or Express

That response is a string too, if you want to send the response prettified, for some awkward reason, you could use something like JSON.stringify(anObject, null, 3)

It's important that you set the Content-Type header to application/json, too.

var http = require('http');

var app = http.createServer(function(req,res){
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify({ a: 1 }));
});
app.listen(3000);

// > {"a":1}

Prettified:

var http = require('http');

var app = http.createServer(function(req,res){
    res.setHeader('Content-Type', 'application/json');
    res.end(JSON.stringify({ a: 1 }, null, 3));
});
app.listen(3000);

// >  {
// >     "a": 1
// >  }

I'm not exactly sure why you want to terminate it with a newline, but you could just do JSON.stringify(...) + '\n' to achieve that.

Express

In express you can do this by changing the options instead.

'json replacer' JSON replacer callback, null by default

'json spaces' JSON response spaces for formatting, defaults to 2 in development, 0 in production

Not actually recommended to set to 40

app.set('json spaces', 40);

Then you could just respond with some json.

res.json({ a: 1 });

It'll use the 'json spaces' configuration to prettify it.

What are the parameters for the number Pipe - Angular 2

  1. Regarding your first question.The pipe works as follows:

    numberValue | number: {minIntegerDigits}.{minFractionDigits}-{maxFractionDigits}

    • minIntegerDigits: Minimum number of integer digits to show before decimal point,set to 1by default
    • minFractionDigits: Minimum number of integer digits to show after the decimal point

    • maxFractionDigits: Maximum number of integer digits to show after the decimal point

2.Regarding your second question, Filter to zero decimal places as follows:

{{ numberValue | number: '1.0-0' }}

For further reading, checkout the following blog

How can I show three columns per row?

Even though the above answer appears to be correct, I wanted to add a (hopefully) more readable example that also stays in 3 columns form at different widths:

_x000D_
_x000D_
.flex-row-container {_x000D_
    background: #aaa;_x000D_
    display: flex;_x000D_
    flex-wrap: wrap;_x000D_
    align-items: center;_x000D_
    justify-content: center;_x000D_
}_x000D_
.flex-row-container > .flex-row-item {_x000D_
    flex: 1 1 30%; /*grow | shrink | basis */_x000D_
    height: 100px;_x000D_
}_x000D_
_x000D_
.flex-row-item {_x000D_
  background-color: #fff4e6;_x000D_
  border: 1px solid #f76707;_x000D_
}
_x000D_
<div class="flex-row-container">_x000D_
  <div class="flex-row-item">1</div>_x000D_
  <div class="flex-row-item">2</div>_x000D_
  <div class="flex-row-item">3</div>_x000D_
  <div class="flex-row-item">4</div>_x000D_
  <div class="flex-row-item">5</div>_x000D_
  <div class="flex-row-item">6</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Hope this helps someone else.

How to split a string into a list?

If you want all the chars of a word/sentence in a list, do this:

print(list("word"))
#  ['w', 'o', 'r', 'd']


print(list("some sentence"))
#  ['s', 'o', 'm', 'e', ' ', 's', 'e', 'n', 't', 'e', 'n', 'c', 'e']

Getting current device language in iOS?

-(NSString *)returnPreferredLanguage { //as written text

NSUserDefaults * defaults = [NSUserDefaults standardUserDefaults];
NSArray *preferredLanguages = [defaults objectForKey:@"AppleLanguages"];
NSString *preferredLanguageCode = [preferredLanguages objectAtIndex:0]; //preferred device language code
NSLocale *enLocale = [[NSLocale alloc] initWithLocaleIdentifier:@"en"]; //language name will be in English (or whatever)
NSString *languageName = [enLocale displayNameForKey:NSLocaleIdentifier value:preferredLanguageCode]; //name of language, eg. "French"
return languageName;

}

Check if a variable exists in a list in Bash

I find it's easier to use the form echo $LIST | xargs -n1 echo | grep $VALUE as illustrated below:

LIST="ITEM1 ITEM2"
VALUE="ITEM1"
if [ -n "`echo $LIST | xargs -n1 echo | grep -e \"^$VALUE`$\" ]; then
    ...
fi

This works for a space-separated list, but you could adapt it to any other delimiter (like :) by doing the following:

LIST="ITEM1:ITEM2"
VALUE="ITEM1"
if [ -n "`echo $LIST | sed 's|:|\\n|g' | grep -e \"^$VALUE`$\"`" ]; then
   ...
fi

Note that the " are required for the test to work.

How to start a Process as administrator mode in C#

var pass = new SecureString();
pass.AppendChar('s');
pass.AppendChar('e');
pass.AppendChar('c');
pass.AppendChar('r');
pass.AppendChar('e');
pass.AppendChar('t');
Process.Start("notepad", "admin", pass, "");

Works also with ProcessStartInfo:

var psi = new ProcessStartInfo
{
    FileName = "notepad",
    UserName = "admin",
    Domain = "",
    Password = pass,
    UseShellExecute = false,
    RedirectStandardOutput = true,
    RedirectStandardError = true
};
Process.Start(psi);

Loading and parsing a JSON file with multiple JSON objects

for those stumbling upon this question: the python jsonlines library (much younger than this question) elegantly handles files with one json document per line. see https://jsonlines.readthedocs.io/

How to create a BKS (BouncyCastle) format Java Keystore that contains a client certificate chain

command line:

keytool -genseckey -alias aliasName -keystore truststore.bks -providerclass org.bouncycastle.jce.provider.BouncyCastleProvider -providerpath /path/to/jar/bcprov-jdk16-1.46.jar -storetype BKS

What is the preferred syntax for defining enums in JavaScript?

It's easy to use, I think. https://stackoverflow.com/a/32245370/4365315

var A = {a:11, b:22}, 
enumA = new TypeHelper(A);

if(enumA.Value === A.b || enumA.Key === "a"){ 
... 
}

var keys = enumA.getAsList();//[object, object]

//set
enumA.setType(22, false);//setType(val, isKey)

enumA.setType("a", true);

enumA.setTypeByIndex(1);

UPDATE:

There is my helper codes(TypeHelper).

_x000D_
_x000D_
var Helper = {_x000D_
    isEmpty: function (obj) {_x000D_
        return !obj || obj === null || obj === undefined || Array.isArray(obj) && obj.length === 0;_x000D_
    },_x000D_
_x000D_
    isObject: function (obj) {_x000D_
        return (typeof obj === 'object');_x000D_
    },_x000D_
_x000D_
    sortObjectKeys: function (object) {_x000D_
        return Object.keys(object)_x000D_
            .sort(function (a, b) {_x000D_
                c = a - b;_x000D_
                return c_x000D_
            });_x000D_
    },_x000D_
    containsItem: function (arr, item) {_x000D_
        if (arr && Array.isArray(arr)) {_x000D_
            return arr.indexOf(item) > -1;_x000D_
        } else {_x000D_
            return arr === item;_x000D_
        }_x000D_
    },_x000D_
_x000D_
    pushArray: function (arr1, arr2) {_x000D_
        if (arr1 && arr2 && Array.isArray(arr1)) {_x000D_
            arr1.push.apply(arr1, Array.isArray(arr2) ? arr2 : [arr2]);_x000D_
        }_x000D_
    }_x000D_
};_x000D_
function TypeHelper() {_x000D_
    var _types = arguments[0],_x000D_
        _defTypeIndex = 0,_x000D_
        _currentType,_x000D_
        _value,_x000D_
        _allKeys = Helper.sortObjectKeys(_types);_x000D_
_x000D_
    if (arguments.length == 2) {_x000D_
        _defTypeIndex = arguments[1];_x000D_
    }_x000D_
_x000D_
    Object.defineProperties(this, {_x000D_
        Key: {_x000D_
            get: function () {_x000D_
                return _currentType;_x000D_
            },_x000D_
            set: function (val) {_x000D_
                _currentType.setType(val, true);_x000D_
            },_x000D_
            enumerable: true_x000D_
        },_x000D_
        Value: {_x000D_
            get: function () {_x000D_
                return _types[_currentType];_x000D_
            },_x000D_
            set: function (val) {_x000D_
                _value.setType(val, false);_x000D_
            },_x000D_
            enumerable: true_x000D_
        }_x000D_
    });_x000D_
    this.getAsList = function (keys) {_x000D_
        var list = [];_x000D_
        _allKeys.forEach(function (key, idx, array) {_x000D_
            if (key && _types[key]) {_x000D_
_x000D_
                if (!Helper.isEmpty(keys) && Helper.containsItem(keys, key) || Helper.isEmpty(keys)) {_x000D_
                    var json = {};_x000D_
                    json.Key = key;_x000D_
                    json.Value = _types[key];_x000D_
                    Helper.pushArray(list, json);_x000D_
                }_x000D_
            }_x000D_
        });_x000D_
        return list;_x000D_
    };_x000D_
_x000D_
    this.setType = function (value, isKey) {_x000D_
        if (!Helper.isEmpty(value)) {_x000D_
            Object.keys(_types).forEach(function (key, idx, array) {_x000D_
                if (Helper.isObject(value)) {_x000D_
                    if (value && value.Key == key) {_x000D_
                        _currentType = key;_x000D_
                    }_x000D_
                } else if (isKey) {_x000D_
                    if (value && value.toString() == key.toString()) {_x000D_
                        _currentType = key;_x000D_
                    }_x000D_
                } else if (value && value.toString() == _types[key]) {_x000D_
                    _currentType = key;_x000D_
                }_x000D_
            });_x000D_
        } else {_x000D_
            this.setDefaultType();_x000D_
        }_x000D_
        return isKey ? _types[_currentType] : _currentType;_x000D_
    };_x000D_
_x000D_
    this.setTypeByIndex = function (index) {_x000D_
        for (var i = 0; i < _allKeys.length; i++) {_x000D_
            if (index === i) {_x000D_
                _currentType = _allKeys[index];_x000D_
                break;_x000D_
            }_x000D_
        }_x000D_
    };_x000D_
_x000D_
    this.setDefaultType = function () {_x000D_
        this.setTypeByIndex(_defTypeIndex);_x000D_
    };_x000D_
_x000D_
    this.setDefaultType();_x000D_
}_x000D_
_x000D_
var TypeA = {_x000D_
    "-1": "Any",_x000D_
    "2": "2L",_x000D_
    "100": "100L",_x000D_
    "200": "200L",_x000D_
    "1000": "1000L"_x000D_
};_x000D_
_x000D_
var enumA = new TypeHelper(TypeA, 4);_x000D_
_x000D_
document.writeln("Key = ", enumA.Key,", Value = ", enumA.Value, "<br>");_x000D_
_x000D_
_x000D_
enumA.setType("200L", false);_x000D_
document.writeln("Key = ", enumA.Key,", Value = ", enumA.Value, "<br>");_x000D_
_x000D_
enumA.setDefaultType();_x000D_
document.writeln("Key = ", enumA.Key,", Value = ", enumA.Value, "<br>");_x000D_
_x000D_
_x000D_
enumA.setTypeByIndex(1);_x000D_
document.writeln("Key = ", enumA.Key,", Value = ", enumA.Value, "<br>");_x000D_
_x000D_
document.writeln("is equals = ", (enumA.Value == TypeA["2"]));
_x000D_
_x000D_
_x000D_

iPhone: Setting Navigation Bar Title

The view controller must be a child of some UINavigationController for the .title property to take effect. If the UINavigationBar is simply a view, you need to push a navigation item containing the title, or modify the last navigation item:

UINavigationItem* item = [[UINavigationItem alloc] initWithTitle:@"title text"];
...
[bar pushNavigationItem:item animated:YES];
[item release];

or

bar.topItem.title = @"title text";

Excel - Shading entire row based on change of value

you could use this formular to do the job -> get the CellValue for the specific row by typing: = indirect("$A&Cell()) depending on which column you have to check, you have to change the $A

For Example -> You could use a customized VBA Function in the Background:

Public Function IstDatum(Zelle) As Boolean IstDatum = False If IsDate(Zelle) Then IstDatum = True End Function

I need it to check for a date-entry in column A:

=IstDatum(INDIREKT("$A"&ZEILE()))

have a look at the picture:

Sending email through Gmail SMTP server with C#

I had also try to many solution but make some changes it will work

host = smtp.gmail.com
port = 587
username = [email protected]
password = password
enabledssl = true

with smtpclient above parameters are work in gmail

How to fix "Attempted relative import in non-package" even with __init__.py

To elaborate on Ignacio Vazquez-Abrams's answer:

The Python import mechanism works relative to the __name__ of the current file. When you execute a file directly, it doesn't have its usual name, but has "__main__" as its name instead. So relative imports don't work.

You can, as Igancio suggested, execute it using the -m option. If you have a part of your package that is meant to be run as a script, you can also use the __package__ attribute to tell that file what name it's supposed to have in the package hierarchy.

See http://www.python.org/dev/peps/pep-0366/ for details.

Selenium WebDriver.get(url) does not open the URL

I have resolved this issue.

If your jar files are older than the latest version and the browser has updated to latest version, then download:

error: pathspec 'test-branch' did not match any file(s) known to git

When I run git branch, it only shows *master, not the remaining two branches.

git branch doesn't list test_branch, because no such local branch exist in your local repo, yet. When cloning a repo, only one local branch (master, here) is created and checked out in the resulting clone, irrespective of the number of branches that exist in the remote repo that you cloned from. At this stage, test_branch only exist in your repo as a remote-tracking branch, not as a local branch.

And when I run

git checkout test-branch

I get the following error [...]

You must be using an "old" version of Git. In more recent versions (from v1.7.0-rc0 onwards),

If <branch> is not found but there does exist a tracking branch in exactly one remote (call it <remote>) with a matching name, treat [git checkout <branch>] as equivalent to

$ git checkout -b <branch> --track <remote>/<branch>

Simply run

git checkout -b test_branch --track origin/test_branch

instead. Or update to a more recent version of Git.

Difference between a script and a program?

See:

The Difference Between a Program and a Script

A Script is also a program but without an opaque layer hiding the (source code) whereas a program is one having clothes, you can't see it's source code unless it is decompilable.

Scripts need other programs to execute them while programs don't need one.

What was the strangest coding standard rule that you were forced to follow?

In Delphi we had to change from

if something then
begin
  ...
end
else
begin
 ...
end;

to

if something then begin
  ...
end else begin
 ...
end;

in a project with 1.5 million lines of code. Imagine how easy this was on source control, diff, and merge! It also led to forgetting begin and not noticing it right away when the compiler announced a superflous end.

Accessing an array out of bounds gives no error, why?

It's undefined behavior as far as I know. Run a larger program with that and it will crash somewhere along the way. Bounds checking is not a part of raw arrays (or even std::vector).

Use std::vector with std::vector::iterator's instead so you don't have to worry about it.

Edit:

Just for fun, run this and see how long until you crash:

int main()
{
   int array[1];

   for (int i = 0; i != 100000; i++)
   {
       array[i] = i;
   }

   return 0; //will be lucky to ever reach this
}

Edit2:

Don't run that.

Edit3:

OK, here is a quick lesson on arrays and their relationships with pointers:

When you use array indexing, you are really using a pointer in disguise (called a "reference"), that is automatically dereferenced. This is why instead of *(array[1]), array[1] automatically returns the value at that value.

When you have a pointer to an array, like this:

int array[5];
int *ptr = array;

Then the "array" in the second declaration is really decaying to a pointer to the first array. This is equivalent behavior to this:

int *ptr = &array[0];

When you try to access beyond what you allocated, you are really just using a pointer to other memory (which C++ won't complain about). Taking my example program above, that is equivalent to this:

int main()
{
   int array[1];
   int *ptr = array;

   for (int i = 0; i != 100000; i++, ptr++)
   {
       *ptr++ = i;
   }

   return 0; //will be lucky to ever reach this
}

The compiler won't complain because in programming, you often have to communicate with other programs, especially the operating system. This is done with pointers quite a bit.

How to show form input fields based on select value?

$('#dbType').change(function(){

   var selection = $(this).val();
   if(selection == 'other')
   {
      $('#otherType').show();
   }
   else
   {
      $('#otherType').hide();
   } 

});

How to call gesture tap on UIView programmatically in swift

Here is the simplest way to add Gestures on View in Swift 5

import UIKit

class ViewController: UIViewController {

    override func viewDidLoad() {
        super.viewDidLoad()
        addGestures()
    }

    // MARK: Add Gestures to target view
    func addGestures()
    {
        // 1. Single Tap or Touch
        let tapGesture = UITapGestureRecognizer(target: self, action: #selector(self.tapGetstureDetected))
        tapGesture.numberOfTapsRequired = 1
        view.addGestureRecognizer(tapGesture)

        //2. Double Tap
        let doubleTapGesture = UITapGestureRecognizer(target: self, action: #selector(self.doubleTapGestureDetected))
        doubleTapGesture.numberOfTapsRequired = 2
        view.addGestureRecognizer(doubleTapGesture)

        //3. Swipe
        let swipeGesture = UISwipeGestureRecognizer(target: self, action: #selector(self.swipeGetstureDetected))
        view.addGestureRecognizer(swipeGesture)

        //4. Pinch
        let pinchGesture = UIPinchGestureRecognizer(target: self, action: #selector(self.pinchGetstureDetected))
        view.addGestureRecognizer(pinchGesture)

        //5. Long Press
        let longPressGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.longPressGetstureDetected))
        view.addGestureRecognizer(longPressGesture)

        //6. Pan
        let panGesture = UILongPressGestureRecognizer(target: self, action: #selector(self.panGestureDetected))
        view.addGestureRecognizer(panGesture)

    }

    // MARK: Handle Gesture detection
    @objc func swipeGetstureDetected() {
        print("Swipe Gesture detected!!")
    }

    @objc func tapGetstureDetected() {
        print("Touch/Tap Gesture detected!!")
    }

    @objc func pinchGetstureDetected() {
        print("Pinch Gesture detected!!")
    }

    @objc func longPressGetstureDetected() {
        print("Long Press Gesture detected!!")
    }

    @objc func doubleTapGestureDetected() {
        print("Double Tap Gesture detected!!")
    }

    @objc func panGestureDetected()
    {
        print("Pan Gesture detected!!")
    }


    //MARK: Shake Gesture
    override func becomeFirstResponder() -> Bool {
        return true
    }
    override func motionEnded(_ motion: UIEvent.EventSubtype, with event: UIEvent?){
        if motion == .motionShake
        {
            print("Shake Gesture Detected")
        }
    }
}

How to get only filenames within a directory using c#?

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace GetNameOfFiles
{
    public class Program
    {
        static void Main(string[] args)
        {
           string[] fileArray = Directory.GetFiles(@"YOUR PATH");
           for (int i = 0; i < fileArray.Length; i++)
           {

               Console.WriteLine(fileArray[i]);
           }
            Console.ReadLine();
        }
    }
}

Convert a JSON Object to Buffer and Buffer to JSON Object back

You need to stringify the json, not calling toString

var buf = Buffer.from(JSON.stringify(obj));

And for converting string to json obj :

var temp = JSON.parse(buf.toString());

Throw keyword in function's signature

To add a bit more value to all the other answer's to this question, one should invest a few minutes in the question: What is the output of the following code?

#include <iostream>
void throw_exception() throw(const char *)
{
    throw 10;
}
void my_unexpected(){
    std::cout << "well - this was unexpected" << std::endl;
}
int main(int argc, char **argv){
    std::set_unexpected(my_unexpected);
    try{
        throw_exception();
    }catch(int x){
        std::cout << "catch int: " << x << std::endl;
    }catch(...){
        std::cout << "catch ..." << std::endl;
    }
}

Answer: As noted here, the program calls std::terminate() and thus none of the exception handlers will get called.

Details: First my_unexpected() function is called, but since it doesn't re-throw a matching exception type for the throw_exception() function prototype, in the end, std::terminate() is called. So the full output looks like this:

user@user:~/tmp$ g++ -o except.test except.test.cpp
user@user:~/tmp$ ./except.test
well - this was unexpected
terminate called after throwing an instance of 'int'
Aborted (core dumped)

How to Auto-start an Android Application?

I always get in here, for this topic. I'll put my code in here so i (or other) can use it next time. (Phew hate to search into my repository code).

Add the permission:

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

Add receiver and service:

<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>
<service android:name="Launcher" />

Create class Launcher:

public class Launcher extends Service {
    @Nullable
    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {

        new AsyncTask<Service, Void, Service>() {

            @Override
            protected Service doInBackground(Service... params) {
                Service service = params[0];
                PackageManager pm = service.getPackageManager();
                try {
                    Intent target = pm.getLaunchIntentForPackage("your.package.id");
                    if (target != null) {
                        service.startActivity(target);
                        synchronized (this) {
                            wait(3000);
                        }
                    } else {
                        throw new ActivityNotFoundException();
                    }
                } catch (ActivityNotFoundException | InterruptedException ignored) {
                }
                return service;
            }

            @Override
            protected void onPostExecute(Service service) {
                service.stopSelf();
            }

        }.execute(this);

        return START_STICKY;
    }
}

Create class BootUpReceiver to do action after android reboot.

For example launch MainActivity:

public class BootUpReceiver extends BroadcastReceiver{

    @Override
    public void onReceive(Context context, Intent intent) {
        Intent target = new Intent(context, MainActivity.class);  
        target.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        context.startActivity(target);  
    }
}

bower proxy configuration

Inside your local project open the .bowerrc that contains:

{
   "directory": "bower_components"
 }

and add the following code-line:

{
   "directory": "bower_components",
  "proxy": "http://yourProxy:yourPort",
  "https-proxy":"http://yourProxy:yourPort"
}

bower version: 1.7.1

Cheers

Writing a dictionary to a csv file with one line for every 'key: value'

#code to insert and read dictionary element from csv file
import csv
n=input("Enter I to insert or S to read : ")
if n=="I":
    m=int(input("Enter the number of data you want to insert: "))
    mydict={}
    list=[]
    for i in range(m):
        keys=int(input("Enter id :"))
        list.append(keys)
        values=input("Enter Name :")
        mydict[keys]=values

    with open('File1.csv',"w") as csvfile:
        writer = csv.DictWriter(csvfile, fieldnames=list)
        writer.writeheader()
        writer.writerow(mydict)
        print("Data Inserted")
else:
    keys=input("Enter Id to Search :")
    Id=str(keys)
    with open('File1.csv',"r") as csvfile:
        reader = csv.DictReader(csvfile)
        for row in reader:
            print(row[Id]) #print(row) to display all data

Passing $_POST values with cURL

Check out the cUrl PHP documentation page. It will help much more than just with example scripts.

SQL NVARCHAR and VARCHAR Limits

The accepted answer helped me but I got tripped up while doing concatenation of varchars involving case statements. I know the OP's question does not involve case statements but I thought this would be helpful to post here for others like me who ended up here while struggling to build long dynamic SQL statements involving case statements.

When using case statements with string concatenation the rules mentioned in the accepted answer apply to each section of the case statement independently.

declare @l_sql varchar(max) = ''

set @l_sql = @l_sql +
case when 1=1 then
    --without this correction the result is truncated
    --CONVERT(VARCHAR(MAX), '')
 +REPLICATE('1', 8000)
 +REPLICATE('1', 8000)
end

print len(@l_sql)

How much does it cost to develop an iPhone application?

The rates that were quoted above are what you would expect to pay US developers; however, I do know some people who have been able to get their apps built for as little as $4,000 by using offshore developers.

Here is a blog post from a group that did this: http://www.lolerapps.com/why-outsourcing-iphone-apps-was-a-no-brainer-for-us

Also, Carla White wrote a fantastic eBook about the process she used to outsource her app called "Inside Secrets to an iPhone App". She talks about how she got a great deal because she was willing to work with a team that was still learning iPhone app development.

So, there are alternatives to the higher price developers discussed above.

Login failed for user 'DOMAIN\MACHINENAME$'

The only point that everyone seems to have overlooked is that you may want integrated security = true. You may have the site running under a pool account. That's all fine so and it's still possible to hit the SQL server with the original user credential and not the pool's. It's called constrained delegation. If you enable it and set up an SPN windows will translate the pool's credentials with the user's on requests going to the final service (SQL is just one such service). You have to register the ONE AND ONLY SQL server that services SQL requests on the web server. Setting this all up is too much for me to try to accurately describe here. It took me quite a while to work through it myself.

Align printf output in Java

Here's a potential solution that will set the width of the bookType column (i.e. format of the bookTypes value) based on the longest bookTypes value.

public class Test {
    public static void main(String[] args) {
        String[] bookTypes = { "Newspaper", "Paper Back", "Hardcover book", "Electronic book", "Magazine" };
        double[] costs = { 1.0, 7.5, 10.0, 2.0, 3.0 };

        // Find length of longest bookTypes value.
        int maxLengthItem = 0;
        boolean firstValue = true;
        for (String bookType : bookTypes) {
            maxLengthItem = (firstValue) ? bookType.length() : Math.max(maxLengthItem, bookType.length());
            firstValue = false;
        }

        // Display rows of data
        for (int i = 0; i < bookTypes.length; i++) {
            // Use %6.2 instead of %.2 so that decimals line up, assuming max
            // book cost of $999.99. Change 6 to a different number if max cost
            // is different
            String format = "%d. %-" + Integer.toString(maxLengthItem) + "s \t\t $%9.2f\n";
            System.out.printf(format, i + 1, bookTypes[i], costs[i]);
        }
    }
}

MySQL LEFT JOIN 3 tables

try this

    SELECT p.Name, p.SS, f.Fear 
    FROM Persons p 
    LEFT JOIN Person_Fear fp 
    ON p.PersonID = fp.PersonID
    LEFT JOIN Fear f
    ON f.FearID = fp.FearID

Determine the size of an InputStream

    try {
        InputStream connInputStream = connection.getInputStream();
    } catch (IOException e) {
        e.printStackTrace();
    }

    int size = connInputStream.available();

int available () Returns an estimate of the number of bytes that can be read (or skipped over) from this input stream without blocking by the next invocation of a method for this input stream. The next invocation might be the same thread or another thread. A single read or skip of this many bytes will not block, but may read or skip fewer bytes.

InputStream - Android SDK | Android Developers

How to properly override clone method?

You can implement protected copy constructors like so:

/* This is a protected copy constructor for exclusive use by .clone() */
protected MyObject(MyObject that) {
    this.myFirstMember = that.getMyFirstMember(); //To clone primitive data
    this.mySecondMember = that.getMySecondMember().clone(); //To clone complex objects
    // etc
}

public MyObject clone() {
    return new MyObject(this);
}

mailto link multiple body lines

This is what I do, just add \n and use encodeURIComponent

Example

var emailBody = "1st line.\n 2nd line \n 3rd line";

emailBody = encodeURIComponent(emailBody);

href = "mailto:[email protected]?body=" + emailBody;

Check encodeURIComponent docs

Suppress warning messages using mysql from within Terminal, but password written in bash script

Another solution (from a script, for example):

 sed -i'' -e "s/password=.*\$/password=$pass/g" ~/.my.cnf
 mysql -h $host -u $user $db_name -e "$sql_cmd"

The -i'' option is here for compatibility with Mac OS X. Standard UNIX OSes can use straight -i

How do I count columns of a table

I have a more general answer; but I believe it is useful for counting the columns for all tables in a DB:

SELECT table_name, count(*)
FROM information_schema.columns
GROUP BY table_name;

Using PHP variables inside HTML tags?

HI Jasper,

you can do this:

<?
sprintf("<a href=\"http://www.whatever.com/%s\">Click Here</a>", $param);
?>

how to convert milliseconds to date format in android?

try this code might help, modify it suit your needs

SimpleDateFormat format = new SimpleDateFormat("EEE MMM dd HH:mm:ss z yyyy");
Date d = format.parse(fileDate);

Add row to query result using select

is it possible to extend query results with literals like this?

Yes.

Select Name
From Customers
UNION ALL
Select 'Jason'
  • Use UNION to add Jason if it isn't already in the result set.
  • Use UNION ALL to add Jason whether or not he's already in the result set.

How to convert char to int?

You may use the following extension method:

public static class CharExtensions
    {
        public static int CharToInt(this char c)
        {
            if (c < '0' || c > '9')
                throw new ArgumentException("The character should be a number", "c");

            return c - '0';
        }
    }

jquery - is not a function error

change

});


$(document).ready(function () {
    $('.smallTabsHeader a').pluginbutton();
});

to

})(jQuery); //<-- ADD THIS


$(document).ready(function () {
    $('.smallTabsHeader a').pluginbutton();
});

This is needed because, you need to call the anonymous function that you created with

(function($){

and notice that it expects an argument that it will use internally as $, so you need to pass a reference to the jQuery object.

Additionally, you will need to change all the this. to $(this)., except the first one, in which you do return this.each

In the first one (where you do not need the $()) it is because in the plugin body, this holds a reference to the jQuery object matching your selector, but anywhere deeper than that, this refers to the specific DOM element, so you need to wrap it in $().

Full code at http://jsfiddle.net/gaby/NXESk/

How to get enum value by string or int

You could use following method to do that:

public static Output GetEnumItem<Output, Input>(Input input)
    {
        //Output type checking...
        if (typeof(Output).BaseType != typeof(Enum))
            throw new Exception("Exception message...");

        //Input type checking: string type
        if (typeof(Input) == typeof(string))
            return (Output)Enum.Parse(typeof(Output), (dynamic)input);

        //Input type checking: Integer type
        if (typeof(Input) == typeof(Int16) ||
            typeof(Input) == typeof(Int32) ||
            typeof(Input) == typeof(Int64))

            return (Output)(dynamic)input;

        throw new Exception("Exception message...");
    }

Note:this method only is a sample and you can improve it.

Django request.GET

msg = request.GET.get('q','default')
if (msg == default):
    message = "YOU SUBMITTED NOTHING"
else: 
    message = "you submitted = %s" %msg"
return HttpResponse(message);

Joda DateTime to Timestamp conversion

It is a common misconception that time (a measurable 4th dimension) is different over the world. Timestamp as a moment in time is unique. Date however is influenced how we "see" time but actually it is "time of day".

An example: two people look at the clock at the same moment. The timestamp is the same, right? But one of them is in London and sees 12:00 noon (GMT, timezone offset is 0), and the other is in Belgrade and sees 14:00 (CET, Central Europe, daylight saving now, offset is +2).

Their perception is different but the moment is the same.

You can find more details in this answer.

UPDATE

OK, it's not a duplicate of this question but it is pointless since you are confusing the terms "Timestamp = moment in time (objective)" and "Date[Time] = time of day (subjective)".

Let's look at your original question code broken down like this:

// Get the "original" value from database.
Timestamp momentFromDB = rs.getTimestamp("anytimestampcolumn");

// Turn it into a Joda DateTime with time zone.
DateTime dt = new DateTime(momentFromDB, DateTimeZone.forID("anytimezone"));

// And then turn it back into a timestamp but "with time zone".
Timestamp ts = new Timestamp(dt.getMillis());

I haven't run this code but I am certain it will print true and the same number of milliseconds each time:

System.out.println("momentFromDB == dt : " + (momentFromDB.getTime() == dt.getTimeInMillis());
System.out.println("momentFromDB == ts : " + (momentFromDB.getTime() == ts.getTime()));
System.out.println("dt == ts : " + (dt.getTimeInMillis() == ts.getTime()));

System.out.println("momentFromDB [ms] : " + momentFromDB.getTime());
System.out.println("ts [ms] : " + ts.getTime());
System.out.println("dt [ms] : " + dt.getTimeInMillis());

But as you said yourself printing them out as strings will result in "different" time because DateTime applies the time zone. That's why "time" is stored and transferred as Timestamp objects (which basically wraps a long) and displayed or entered as Date[Time].

In your own answer you are artificially adding an offset and creating a "wrong" time. If you use that timestamp to create another DateTime and print it out it will be offset twice.

// Turn it back into a Joda DateTime with time zone.
DateTime dt = new DateTime(ts, DateTimeZone.forID("anytimezone"));

P.S. If you have the time go through the very complex Joda Time source code to see how it holds the time (millis) and how it prints it.

JUnit Test as proof

import static org.junit.Assert.*;
import static org.hamcrest.CoreMatchers.*;

import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.Locale;
import java.util.TimeZone;

import org.junit.Before;
import org.junit.Test;


public class WorldTimeTest {
    private static final int MILLIS_IN_HOUR = 1000 * 60 * 60;
    private static final String ISO_FORMAT_NO_TZ = "yyyy-MM-dd'T'HH:mm:ss.SSS";
    private static final String ISO_FORMAT_WITH_TZ = "yyyy-MM-dd'T'HH:mm:ss.SSSXXX";

    private TimeZone londonTimeZone;
    private TimeZone newYorkTimeZone;
    private TimeZone sydneyTimeZone;
    private long nowInMillis;
    private Date now;

    public static SimpleDateFormat createDateFormat(String pattern, TimeZone timeZone) throws Exception {
        SimpleDateFormat result = new SimpleDateFormat(pattern);
        // Must explicitly set the time zone with "setCalendar()".
        result.setCalendar(Calendar.getInstance(timeZone));
        return result;
    }

    public static SimpleDateFormat createDateFormat(String pattern) throws Exception {
        return createDateFormat(pattern, TimeZone.getDefault());
    }

    public static SimpleDateFormat createDateFormat() throws Exception {
        return createDateFormat(ISO_FORMAT_WITH_TZ, TimeZone.getDefault());
    }

    public void printSystemInfo() throws Exception {
        final String[] propertyNames = {
                "java.runtime.name", "java.runtime.version", "java.vm.name", "java.vm.version",
                "os.name", "os.version", "os.arch",
                "user.language", "user.country", "user.script", "user.variant",
                "user.language.format", "user.country.format", "user.script.format",
                "user.timezone" };

        System.out.println();
        System.out.println("System Information:");
        for (String name : propertyNames) {
            if (name == null || name.length() == 0) {
                continue;
            }
            String value = System.getProperty(name);
            if (value != null && value.length() > 0) {
                System.out.println("  " + name + " = " + value);
            }
        }

        final TimeZone defaultTZ = TimeZone.getDefault();
        final int defaultOffset = defaultTZ.getOffset(nowInMillis) / MILLIS_IN_HOUR;
        final int userOffset = TimeZone.getTimeZone(System
                .getProperty("user.timezone")).getOffset(nowInMillis) / MILLIS_IN_HOUR;
        final Locale defaultLocale = Locale.getDefault();

        System.out.println("  default.timezone-offset (hours) = " + userOffset);
        System.out.println("  default.timezone = " + defaultTZ.getDisplayName());
        System.out.println("  default.timezone.id = " + defaultTZ.getID());
        System.out.println("  default.timezone-offset (hours) = " + defaultOffset);
        System.out.println("  default.locale = "
                + defaultLocale.getLanguage() + "_" + defaultLocale.getCountry()
                + " (" + defaultLocale.getDisplayLanguage()
                + "," + defaultLocale.getDisplayCountry() + ")");
        System.out.println("  now = " + nowInMillis + " [ms] or "
                + createDateFormat().format(now));
        System.out.println();
    }

    @Before
    public void setUp() throws Exception {
        // Remember this moment.
        now = new Date();
        nowInMillis = now.getTime(); // == System.currentTimeMillis();

        // Print out some system information.
        printSystemInfo();

        // "Europe/London" time zone is DST aware, we'll use fixed offset.
        londonTimeZone = TimeZone.getTimeZone("GMT");
        // The same applies to "America/New York" time zone ...
        newYorkTimeZone = TimeZone.getTimeZone("GMT-5");
        // ... and for the "Australia/Sydney" time zone.
        sydneyTimeZone = TimeZone.getTimeZone("GMT+10");
    }

    @Test
    public void testDateFormatting() throws Exception {
        int londonOffset = londonTimeZone.getOffset(nowInMillis) / MILLIS_IN_HOUR; // in hours
        Calendar londonCalendar = Calendar.getInstance(londonTimeZone);
        londonCalendar.setTime(now);

        int newYorkOffset = newYorkTimeZone.getOffset(nowInMillis) / MILLIS_IN_HOUR;
        Calendar newYorkCalendar = Calendar.getInstance(newYorkTimeZone);
        newYorkCalendar.setTime(now);

        int sydneyOffset = sydneyTimeZone.getOffset(nowInMillis) / MILLIS_IN_HOUR;
        Calendar sydneyCalendar = Calendar.getInstance(sydneyTimeZone);
        sydneyCalendar.setTime(now);

        // Check each time zone offset.
        assertThat(londonOffset, equalTo(0));
        assertThat(newYorkOffset, equalTo(-5));
        assertThat(sydneyOffset, equalTo(10));

        // Check that calendars are not equals (due to time zone difference).
        assertThat(londonCalendar, not(equalTo(newYorkCalendar)));
        assertThat(londonCalendar, not(equalTo(sydneyCalendar)));

        // Check if they all point to the same moment in time, in milliseconds.
        assertThat(londonCalendar.getTimeInMillis(), equalTo(nowInMillis));
        assertThat(newYorkCalendar.getTimeInMillis(), equalTo(nowInMillis));
        assertThat(sydneyCalendar.getTimeInMillis(), equalTo(nowInMillis));

        // Check if they all point to the same moment in time, as Date.
        assertThat(londonCalendar.getTime(), equalTo(now));
        assertThat(newYorkCalendar.getTime(), equalTo(now));
        assertThat(sydneyCalendar.getTime(), equalTo(now));

        // Check if hours are all different (skip local time because
        // this test could be executed in those exact time zones).
        assertThat(newYorkCalendar.get(Calendar.HOUR_OF_DAY),
                not(equalTo(londonCalendar.get(Calendar.HOUR_OF_DAY))));
        assertThat(sydneyCalendar.get(Calendar.HOUR_OF_DAY),
                not(equalTo(londonCalendar.get(Calendar.HOUR_OF_DAY))));


        // Display London time in multiple forms.
        SimpleDateFormat dfLondonNoTZ = createDateFormat(ISO_FORMAT_NO_TZ, londonTimeZone);
        SimpleDateFormat dfLondonWithTZ = createDateFormat(ISO_FORMAT_WITH_TZ, londonTimeZone);
        System.out.println("London (" + londonTimeZone.getDisplayName(false, TimeZone.SHORT)
                + ", " + londonOffset + "):");
        System.out.println("  time (ISO format w/o TZ) = "
                + dfLondonNoTZ.format(londonCalendar.getTime()));
        System.out.println("  time (ISO format w/ TZ)  = "
                + dfLondonWithTZ.format(londonCalendar.getTime()));
        System.out.println("  time (default format)    = "
                + londonCalendar.getTime() + " / " + londonCalendar.toString());
        // Using system default time zone.
        System.out.println("  time (default TZ)        = "
                + createDateFormat(ISO_FORMAT_NO_TZ).format(londonCalendar.getTime())
                + " / " + createDateFormat().format(londonCalendar.getTime()));


        // Display New York time in multiple forms.
        SimpleDateFormat dfNewYorkNoTZ = createDateFormat(ISO_FORMAT_NO_TZ, newYorkTimeZone);
        SimpleDateFormat dfNewYorkWithTZ = createDateFormat(ISO_FORMAT_WITH_TZ, newYorkTimeZone);
        System.out.println("New York (" + newYorkTimeZone.getDisplayName(false, TimeZone.SHORT)
                + ", " + newYorkOffset + "):");
        System.out.println("  time (ISO format w/o TZ) = "
                + dfNewYorkNoTZ.format(newYorkCalendar.getTime()));
        System.out.println("  time (ISO format w/ TZ)  = "
                + dfNewYorkWithTZ.format(newYorkCalendar.getTime()));
        System.out.println("  time (default format)    = "
                + newYorkCalendar.getTime() + " / " + newYorkCalendar.toString());
        // Using system default time zone.
        System.out.println("  time (default TZ)        = "
                + createDateFormat(ISO_FORMAT_NO_TZ).format(newYorkCalendar.getTime())
                + " / " + createDateFormat().format(newYorkCalendar.getTime()));


        // Display Sydney time in multiple forms.
        SimpleDateFormat dfSydneyNoTZ = createDateFormat(ISO_FORMAT_NO_TZ, sydneyTimeZone);
        SimpleDateFormat dfSydneyWithTZ = createDateFormat(ISO_FORMAT_WITH_TZ, sydneyTimeZone);
        System.out.println("Sydney (" + sydneyTimeZone.getDisplayName(false, TimeZone.SHORT)
                + ", " + sydneyOffset + "):");
        System.out.println("  time (ISO format w/o TZ) = "
                + dfSydneyNoTZ.format(sydneyCalendar.getTime()));
        System.out.println("  time (ISO format w/ TZ)  = "
                + dfSydneyWithTZ.format(sydneyCalendar.getTime()));
        System.out.println("  time (default format)    = "
                + sydneyCalendar.getTime() + " / " + sydneyCalendar.toString());
        // Using system default time zone.
        System.out.println("  time (default TZ)        = "
                + createDateFormat(ISO_FORMAT_NO_TZ).format(sydneyCalendar.getTime())
                + " / " + createDateFormat().format(sydneyCalendar.getTime()));
    }

    @Test
    public void testDateParsing() throws Exception {
        // Create date parsers that look for time zone information in a date-time string.
        final SimpleDateFormat londonFormatTZ = createDateFormat(ISO_FORMAT_WITH_TZ, londonTimeZone);
        final SimpleDateFormat newYorkFormatTZ = createDateFormat(ISO_FORMAT_WITH_TZ, newYorkTimeZone);
        final SimpleDateFormat sydneyFormatTZ = createDateFormat(ISO_FORMAT_WITH_TZ, sydneyTimeZone);

        // Create date parsers that ignore time zone information in a date-time string.
        final SimpleDateFormat londonFormatLocal = createDateFormat(ISO_FORMAT_NO_TZ, londonTimeZone);
        final SimpleDateFormat newYorkFormatLocal = createDateFormat(ISO_FORMAT_NO_TZ, newYorkTimeZone);
        final SimpleDateFormat sydneyFormatLocal = createDateFormat(ISO_FORMAT_NO_TZ, sydneyTimeZone);

        // We are looking for the moment this millenium started, the famous Y2K,
        // when at midnight everyone welcomed the New Year 2000, i.e. 2000-01-01 00:00:00.
        // Which of these is the right one?
        // a) "2000-01-01T00:00:00.000-00:00"
        // b) "2000-01-01T00:00:00.000-05:00"
        // c) "2000-01-01T00:00:00.000+10:00"
        // None of them? All of them?
        // For those who guessed it - yes, it is a trick question because we didn't specify
        // the "where" part, or what kind of time (local/global) we are looking for.
        // The first (a) is the local Y2K moment in London, which is at the same time global.
        // The second (b) is the local Y2K moment in New York, but London is already celebrating for 5 hours.
        // The third (c) is the local Y2K moment in Sydney, and they started celebrating 15 hours before New York did.
        // The point here is that each answer is correct because everyone thinks of that moment in terms of "celebration at midnight".
        // The key word here is "midnight"! That moment is actually a "time of day" moment illustrating our perception of time based on the movement of our Sun.

        // These are global Y2K moments, i.e. the same moment all over the world, UTC/GMT midnight.
        final String MIDNIGHT_GLOBAL = "2000-01-01T00:00:00.000-00:00";
        final Date milleniumInLondon = londonFormatTZ.parse(MIDNIGHT_GLOBAL);
        final Date milleniumInNewYork = newYorkFormatTZ.parse(MIDNIGHT_GLOBAL);
        final Date milleniumInSydney = sydneyFormatTZ.parse(MIDNIGHT_GLOBAL);

        // Check if they all point to the same moment in time.
        // And that parser ignores its own configured time zone and uses the information from the date-time string.
        assertThat(milleniumInNewYork, equalTo(milleniumInLondon));
        assertThat(milleniumInSydney, equalTo(milleniumInLondon));


        // These are all local Y2K moments, a.k.a. midnight at each location on Earth, with time zone information.
        final String MIDNIGHT_LONDON = "2000-01-01T00:00:00.000-00:00";
        final String MIDNIGHT_NEW_YORK = "2000-01-01T00:00:00.000-05:00";
        final String MIDNIGHT_SYDNEY = "2000-01-01T00:00:00.000+10:00";
        final Date midnightInLondonTZ = londonFormatLocal.parse(MIDNIGHT_LONDON);
        final Date midnightInNewYorkTZ = newYorkFormatLocal.parse(MIDNIGHT_NEW_YORK);
        final Date midnightInSydneyTZ = sydneyFormatLocal.parse(MIDNIGHT_SYDNEY);

        // Check if they all point to the same moment in time.
        assertThat(midnightInNewYorkTZ, not(equalTo(midnightInLondonTZ)));
        assertThat(midnightInSydneyTZ, not(equalTo(midnightInLondonTZ)));

        // Check if the time zone offset is correct.
        assertThat(midnightInLondonTZ.getTime() - midnightInNewYorkTZ.getTime(),
                equalTo((long) newYorkTimeZone.getOffset(milleniumInLondon.getTime())));
        assertThat(midnightInLondonTZ.getTime() - midnightInSydneyTZ.getTime(),
                equalTo((long) sydneyTimeZone.getOffset(milleniumInLondon.getTime())));


        // These are also local Y2K moments, just withouth the time zone information.
        final String MIDNIGHT_ANYWHERE = "2000-01-01T00:00:00.000";
        final Date midnightInLondon = londonFormatLocal.parse(MIDNIGHT_ANYWHERE);
        final Date midnightInNewYork = newYorkFormatLocal.parse(MIDNIGHT_ANYWHERE);
        final Date midnightInSydney = sydneyFormatLocal.parse(MIDNIGHT_ANYWHERE);

        // Check if these are the same as the local moments with time zone information.
        assertThat(midnightInLondon, equalTo(midnightInLondonTZ));
        assertThat(midnightInNewYork, equalTo(midnightInNewYorkTZ));
        assertThat(midnightInSydney, equalTo(midnightInSydneyTZ));

        // Check if they all point to the same moment in time.
        assertThat(midnightInNewYork, not(equalTo(midnightInLondon)));
        assertThat(midnightInSydney, not(equalTo(midnightInLondon)));

        // Check if the time zone offset is correct.
        assertThat(midnightInLondon.getTime() - midnightInNewYork.getTime(),
                equalTo((long) newYorkTimeZone.getOffset(milleniumInLondon.getTime())));
        assertThat(midnightInLondon.getTime() - midnightInSydney.getTime(),
                equalTo((long) sydneyTimeZone.getOffset(milleniumInLondon.getTime())));


        // Final check - if Y2K moment is in London ..
        final String Y2K_LONDON = "2000-01-01T00:00:00.000Z";
        // .. New York local time would be still 5 hours in 1999 ..
        final String Y2K_NEW_YORK = "1999-12-31T19:00:00.000-05:00";
        // .. and Sydney local time would be 10 hours in 2000.
        final String Y2K_SYDNEY = "2000-01-01T10:00:00.000+10:00";

        final String londonTime = londonFormatTZ.format(milleniumInLondon);
        final String newYorkTime = newYorkFormatTZ.format(milleniumInLondon);
        final String sydneyTime = sydneyFormatTZ.format(milleniumInLondon);

        // WHat do you think, will the test pass?
        assertThat(londonTime, equalTo(Y2K_LONDON));
        assertThat(newYorkTime, equalTo(Y2K_NEW_YORK));
        assertThat(sydneyTime, equalTo(Y2K_SYDNEY));
    }
}

getActivity() returns null in Fragment function

Where do you call this function? If you call it in the constructor of Fragment, it will return null.

Just call getActivity() when the method onCreateView() is executed.

Apache Proxy: No protocol handler was valid

In my case, all modules were correctly set up (https://www.digitalocean.com/community/tutorials/how-to-use-apache-http-server-as-reverse-proxy-using-mod_proxy-extension is a good starter) & I had the redirection working for a base url, let's say /mysite/ but I got the errors for any child ULR, let's say /mysite/login/

http://reverse-proxy.dns.com/mysite/ was properly redirected to the remote servers while http://reverse-proxy.dns.com/mysite/login/ failed at the Apache2 reverse proxying with OP's error message.

The issue was the ending / character in the proxypass directive "/mysite/". Working configuration for child URL is :

<Proxy balancer://mysite_cluster>
    BalancerMember http://192.x.x.10:8080/mysite
    BalancerMember http://192.x.x.11:8080/mysite
</Proxy>
<VirtualHost *:80>
    [...]
    ProxyRequests Off
    ProxyPreserveHost On
    ProxyPass "/mysite" "balancer://mysite_cluster"
    ProxyPassReverse "/mysite" "balancer://mysite_cluster"       
</VirtualHost>

Trailing / truly are tricky.

How can I apply a border only inside a table?

For ordinary table markup, here's a short solution that works on all devices/browsers on BrowserStack, except IE 7 and below:

table { border-collapse: collapse; }

td + td,
th + th { border-left: 1px solid; }
tr + tr { border-top: 1px solid; }

For IE 7 support, add this:

tr + tr > td,
tr + tr > th { border-top: 1px solid; }

A test case can be seen here: http://codepen.io/dalgard/pen/wmcdE

Rewrite all requests to index.php with nginx

1 unless file exists will rewrite to index.php

Add the following to your location ~ \.php$

try_files = $uri @missing;

this will first try to serve the file and if it's not found it will move to the @missing part. so also add the following to your config (outside the location block), this will redirect to your index page

location @missing {
    rewrite ^ $scheme://$host/index.php permanent;
}

2 on the urls you never see the file extension (.php)

to remove the php extension read the following: http://www.nullis.net/weblog/2011/05/nginx-rewrite-remove-file-extension/

and the example configuration from the link:

location / {
    set $page_to_view "/index.php";
    try_files $uri $uri/ @rewrites;
    root   /var/www/site;
    index  index.php index.html index.htm;
}

location ~ \.php$ {
    include /etc/nginx/fastcgi_params;
    fastcgi_pass  127.0.0.1:9000;
    fastcgi_index index.php;
    fastcgi_param SCRIPT_FILENAME /var/www/site$page_to_view;
}

# rewrites
location @rewrites {
    if ($uri ~* ^/([a-z]+)$) {
        set $page_to_view "/$1.php";
        rewrite ^/([a-z]+)$ /$1.php last;
    }
}

Group by multiple field names in java 8

You can use List as a classifier for many fields, but you need wrap null values into Optional:

Function<String, List> classifier = (item) -> List.of(
    item.getFieldA(),
    item.getFieldB(),
    Optional.ofNullable(item.getFieldC())
);

Map<List, List<Item>> grouped = items.stream()
    .collect(Collectors.groupingBy(classifier));

How to set the holo dark theme in a Android app?

By default android will set Holo to the Dark theme. There is no theme called Holo.Dark, there's only Holo.Light, that's why you are getting the resource not found error.

So just set it to:

<style name="AppTheme" parent="android:Theme.Holo" />

How to get text from each cell of an HTML table?

Another C# example. I just made an extension method for it.

public static string GetCellFromTable(this IWebElement table, int rowIndex, int columnIndex)
    {
        return table.FindElements(By.XPath("./tbody/tr"))[rowIndex].FindElements(By.XPath("./td"))[columnIndex].Text;
    }

How do you check what version of SQL Server for a database using TSQL?

Try this:

SELECT @@VERSION[server], SERVERPROPERTY('productversion'), SERVERPROPERTY ('productlevel'), SERVERPROPERTY ('edition')

How to make readonly all inputs in some div in Angular2?

If using reactive forms, you can also disable the entire form or any sub-set of controls in a FormGroup with myFormGroup.disable().

Java - How to create a custom dialog box?

i created a custom dialog API. check it out here https://github.com/MarkMyWord03/CustomDialog. It supports message and confirmation box. input and option dialog just like in joptionpane will be implemented soon.

Sample Error Dialog from CUstomDialog API: CustomDialog Error Message

How to import component into another root component in Angular 2

above answers In simple words, you have to register under @NgModule's

declarations: [
    AppComponent, YourNewComponentHere
  ] 

of app.module.ts

do not forget to import that component.

How to hide the title bar for an Activity in XML with existing custom theme

when i tried to use all those high upvoted answers my app always crashed. (i think it has something to do with the "@android:style"?)

The best solution for me was to use the following:

android:theme="@style/Theme.AppCompat.NoActionBar"

No header / title bar anymore. Just place it in the <application>...</application> or <activity>...</activity> depending if you (don't) want it in the whole app or just a specific activity.

Mocking methods of local scope objects with Mockito

You could avoid changing the code (although I recommend Boris' answer) and mock the constructor, like in this example for mocking the creation of a File object inside a method. Don't forget to put the class that will create the file in the @PrepareForTest.

package hello.easymock.constructor;

import java.io.File;

import org.easymock.EasyMock;
import org.junit.Assert;
import org.junit.Test;
import org.junit.runner.RunWith;
import org.powermock.api.easymock.PowerMock;
import org.powermock.core.classloader.annotations.PrepareForTest;
import org.powermock.modules.junit4.PowerMockRunner;
    
@RunWith(PowerMockRunner.class)
@PrepareForTest({File.class})
public class ConstructorExampleTest {
        
    @Test
    public void testMockFile() throws Exception {

        // first, create a mock for File
        final File fileMock = EasyMock.createMock(File.class);
        EasyMock.expect(fileMock.getAbsolutePath()).andReturn("/my/fake/file/path");
        EasyMock.replay(fileMock);

        // then return the mocked object if the constructor is invoked
        Class<?>[] parameterTypes = new Class[] { String.class };
        PowerMock.expectNew(File.class, parameterTypes , EasyMock.isA(String.class)).andReturn(fileMock);
        PowerMock.replay(File.class); 
    
        // try constructing a real File and check if the mock kicked in
        final String mockedFilePath = new File("/real/path/for/file").getAbsolutePath();
        Assert.assertEquals("/my/fake/file/path", mockedFilePath);
    }
}

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.

How to fix 'Notice: Undefined index:' in PHP form action

if(isset($_POST['form_field_name'])) {
    $variable_name = $_POST['form_field_name'];
}

How can I make setInterval also work when a tab is inactive in Chrome?

It is quite old question but I encountered the same issue.
If you run your web on chrome, you could read through this post Background Tabs in Chrome 57 .

Basically the interval timer could run if it haven't run out of the timer budget.
The consumption of budget is based on CPU time usage of the task inside timer.
Based on my scenario, I draw video to canvas and transport to WebRTC.
The webrtc video connection would keep updating even the tab is inactive.

However you have to use setInterval instead of requestAnimationFrame.
it is not recommended for UI rendering though.

It would be better to listen visibilityChange event and change render mechenism accordingly.

Besides, you could try @kaan-soral and it should works based on the documentation.

Warnings Your Apk Is Using Permissions That Require A Privacy Policy: (android.permission.READ_PHONE_STATE)

If you are using the package device_id to get the unique device id then that will add an android.permission.READ_PHONE_STATE without your knowledge which eventually will lead to the Play Store warning.

Instead you can use the device_info package for the same purpose without the need of the extra permission. Check this SO thread

Change default icon

If you are using Forms you can use the icon setting in the properties pane. To do this select the form and scroll down in the properties pane till you see the icon setting. When you open the application it will have the icon wherever you have it in your application and in the task bar

Icon settings

Swift_TransportException Connection could not be established with host smtp.gmail.com

I had the same problem for a while, replacing: smtp.gmail.com with 173.194.65.108 actually worked for me!

Preserve Line Breaks From TextArea When Writing To MySQL

Got my own answer: Using this function from the data from the textarea solves the problem:

function mynl2br($text) { 
   return strtr($text, array("\r\n" => '<br />', "\r" => '<br />', "\n" => '<br />')); 
} 

More here: http://php.net/nl2br

Difference between MongoDB and Mongoose

One more difference I found with respect to both is that it is fairly easy to connect to multiple databases with mongodb native driver while you have to use work arounds in mongoose which still have some drawbacks.

So if you wanna go for a multitenant application, go for mongodb native driver.

Compare two files line by line and generate the difference in another file

Many answers already, but none of them perfect IMHO. Thanatos' answer leaves some extra characters per line and Sorpigal's answer requires the files to be sorted or pre-sorted, which may not be adequate in all circumstances.

I think the best way of getting the lines that are different and nothing else (no extra chars, no re-ordering) is a combination of diff, grep, and awk (or similar).

If the lines do not contain any "<", a short one-liner can be:

diff urls.txt* | grep "<" | sed 's/< //g'

but that will remove every instance of "< " (less than, space) from the lines, which is not always OK (e.g. source code). The safest option is to use awk:

diff urls.txt* | grep "<" | awk '{for (i=2; i<NF; i++) printf $i " "; print $NF}'

This one-liner diffs both files, then filters out the ed-style output of diff, then removes the trailing "<" that diff adds. This works even if the lines contains some "<" themselves.

Access HTTP response as string in Go

string(byteslice) will convert byte slice to string, just know that it's not only simply type conversion, but also memory copy.

How can I "disable" zoom on a mobile web page?

You can use:

<head>
  <meta name="viewport" content="target-densitydpi=device-dpi, initial-scale=1.0, user-scalable=no" />
  ...
</head>

But please note that with Android 4.4 the property target-densitydpi is no longer supported. So for Android 4.4 and later the following is suggested as best practice:

<meta name="viewport" content="width=device-width, initial-scale=1, user-scalable=no" />

SoapFault exception: Could not connect to host

For me it was a DNS issue. My VPS's nameservers crapped out, so I switched to Google's by editing my /etc/resolv.conf to be: nameserver 8.8.8.8 nameserver 8.8.4.4

Why use Select Top 100 Percent?

Just try this, it explains it pretty much itself. You can't create a view with an ORDER BY except if...

CREATE VIEW v_Test
         AS
           SELECT name
             FROM sysobjects
         ORDER BY name
        GO

Msg 1033, Level 15, State 1, Procedure TestView, Line 5 The ORDER BY clause is invalid in views, inline functions, derived tables, subqueries, and common table expressions, unless TOP, OFFSET or FOR XML is also specified.

Regex number between 1 and 100

There are many options how to write a regex pattern for that

  • ^(?:(?!0)\d{1,2}|100)$
  • ^(?:[1-9]\d?|100)$
  • ^(?!0)(?=100$|..$|.$)\d+$

How to find the maximum value in an array?

If you can change the order of the elements:

 int[] myArray = new int[]{1, 3, 8, 5, 7, };
 Arrays.sort(myArray);
 int max = myArray[myArray.length - 1];

If you can't change the order of the elements:

int[] myArray = new int[]{1, 3, 8, 5, 7, };
int max = Integer.MIN_VALUE;
for(int i = 0; i < myArray.length; i++) {
      if(myArray[i] > max) {
         max = myArray[i];
      }
}

UITableView example for Swift

The example below is an adaptation and simplification of a longer post from We ? Swift. This is what it will look like:

enter image description here

Create a New Project

It can be just the usual Single View Application.

Add the Code

Replace the ViewController.swift code with the following:

import UIKit
class ViewController: UIViewController, UITableViewDelegate, UITableViewDataSource {
    
    // Data model: These strings will be the data for the table view cells
    let animals: [String] = ["Horse", "Cow", "Camel", "Sheep", "Goat"]
    
    // cell reuse id (cells that scroll out of view can be reused)
    let cellReuseIdentifier = "cell"
    
    // don't forget to hook this up from the storyboard
    @IBOutlet var tableView: UITableView!
    
    override func viewDidLoad() {
        super.viewDidLoad()
        
        // Register the table view cell class and its reuse id
        self.tableView.register(UITableViewCell.self, forCellReuseIdentifier: cellReuseIdentifier)
        
        // (optional) include this line if you want to remove the extra empty cell divider lines
        // self.tableView.tableFooterView = UIView()

        // This view controller itself will provide the delegate methods and row data for the table view.
        tableView.delegate = self
        tableView.dataSource = self
    }
    
    // number of rows in table view
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return self.animals.count
    }
    
    // create a cell for each table view row
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        // create a new cell if needed or reuse an old one
        let cell:UITableViewCell = self.tableView.dequeueReusableCell(withIdentifier: cellReuseIdentifier) as UITableViewCell!
        
        // set the text from the data model
        cell.textLabel?.text = self.animals[indexPath.row]
        
        return cell
    }
    
    // method to run when table view cell is tapped
    func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        print("You tapped cell number \(indexPath.row).")
    }
}

Read the in-code comments to see what is happening. The highlights are

  • The view controller adopts the UITableViewDelegate and UITableViewDataSource protocols.
  • The numberOfRowsInSection method determines how many rows there will be in the table view.
  • The cellForRowAtIndexPath method sets up each row.
  • The didSelectRowAtIndexPath method is called every time a row is tapped.

Add a Table View to the Storyboard

Drag a UITableView onto your View Controller. Use auto layout to pin the four sides.

enter image description here

Hook up the Outlets

Control drag from the Table View in IB to the tableView outlet in the code.

Finished

That's all. You should be able run your app now.

This answer was tested with Xcode 9 and Swift 4


Variations

Row Deletion

You only have to add a single method to the basic project above if you want to enable users to delete rows. See this basic example to learn how.

enter image description here

Row Spacing

If you would like to have spacing between your rows, see this supplemental example.

enter image description here

Custom cells

The default layout for the table view cells may not be what you need. Check out this example to help get you started making your own custom cells.

enter image description here

Dynamic Cell Height

Sometimes you don't want every cell to be the same height. Starting with iOS 8 it is easy to automatically set the height depending on the cell content. See this example for everything you need to get you started.

enter image description here

Further Reading

Read response body in JAX-RS client from a post request

Acording with the documentation, the method getEntity in Jax rs 2.0 return a InputStream. If you need to convert to InputStream to String with JSON format, you need to cast the two formats. For example in my case, I implemented the next method:

    private String processResponse(Response response) {
    if (response.getEntity() != null) {
        try {
            InputStream salida = (InputStream) response.getEntity();
            StringWriter writer = new StringWriter();
            IOUtils.copy(salida, writer, "UTF-8");
            return writer.toString();
        } catch (IOException ex) {
            LOG.log(Level.SEVERE, null, ex);
        }
    }
    return null;
}

why I implemented this method. Because a read in differets blogs that many developers they have the same problem whit the version in jaxrs using the next methods

String output = response.readEntity(String.class)

and

String output = response.getEntity(String.class)

The first works using jersey-client from com.sun.jersey library and the second found using the jersey-client from org.glassfish.jersey.core.

This is the error that was being presented to me: org.glassfish.jersey.client.internal.HttpUrlConnector$2 cannot be cast to java.lang.String

I use the following maven dependency:

<dependency>
<groupId>org.glassfish.jersey.core</groupId>
<artifactId>jersey-client</artifactId>
<version>2.28</version>

What I do not know is why the readEntity method does not work.I hope you can use the solution.

Carlos Cepeda

Array Index Out of Bounds Exception (Java)

for ( i = 0; i < total.length; i++ );
                                    ^-- remove the semi-colon here

With this semi-colon, the loop loops until i == total.length, doing nothing, and then what you thought was the body of the loop is executed.

What causes the error "_pickle.UnpicklingError: invalid load key, ' '."?

I am not completely sure what you're trying to achieve by seeking to a specific offset and attempting to load individual values manually, the typical usage of the pickle module is:

# save data to a file
with open('myfile.pickle','wb') as fout:
    pickle.dump([1,2,3],fout)

# read data from a file
with open('myfile.pickle') as fin:
    print pickle.load(fin)

# output
>> [1, 2, 3]

If you dumped a list, you'll load a list, there's no need to load each item individually.

you're saying that you got an error before you were seeking to the -5000 offset, maybe the file you're trying to read is corrupted.

If you have access to the original data, I suggest you try saving it to a new file and reading it as in the example.

Get value of input field inside an iframe

Without Iframe We can do this by JQuery but it will give you only HTML page source and no dynamic links or html tags will display. Almost same as php solution but in JQuery :) Code---

var purl = "http://www.othersite.com";
$.getJSON('http://whateverorigin.org/get?url=' +
    encodeURIComponent(purl) + '&callback=?',
    function (data) {
    $('#viewer').html(data.contents);
});

notifyDataSetChanged example

For an ArrayAdapter, notifyDataSetChanged only works if you use the add(), insert(), remove(), and clear() on the Adapter.

When an ArrayAdapter is constructed, it holds the reference for the List that was passed in. If you were to pass in a List that was a member of an Activity, and change that Activity member later, the ArrayAdapter is still holding a reference to the original List. The Adapter does not know you changed the List in the Activity.

Your choices are:

  1. Use the functions of the ArrayAdapter to modify the underlying List (add(), insert(), remove(), clear(), etc.)
  2. Re-create the ArrayAdapter with the new List data. (Uses a lot of resources and garbage collection.)
  3. Create your own class derived from BaseAdapter and ListAdapter that allows changing of the underlying List data structure.
  4. Use the notifyDataSetChanged() every time the list is updated. To call it on the UI-Thread, use the runOnUiThread() of Activity. Then, notifyDataSetChanged() will work.

SVN Error: Commit blocked by pre-commit hook (exit code 1) with output: Error: n/a (6)

If you are getting following exception:

Error: Commit failed (details follow):
Error: Commit blocked by pre-commit hook (exit code 1) with output:
Error: svnlook: Path 'trunk/Development/ProjectName' is not a file

Then first check-in all the the directories and then all the files. It will work.

Plot two graphs in same plot in R

lines() or points() will add to the existing graph, but will not create a new window. So you'd need to do

plot(x,y1,type="l",col="red")
lines(x,y2,col="green")

Is there an alternative to string.Replace that is case-insensitive?

(Since everyone is taking a shot at this). Here's my version (with null checks, and correct input and replacement escaping) ** Inspired from around the internet and other versions:

using System;
using System.Text.RegularExpressions;

public static class MyExtensions {
    public static string ReplaceIgnoreCase(this string search, string find, string replace) {
        return Regex.Replace(search ?? "", Regex.Escape(find ?? ""), (replace ?? "").Replace("$", "$$"), RegexOptions.IgnoreCase);          
    }
}

Usage:

var result = "This is a test".ReplaceIgnoreCase("IS", "was");

How do I trim leading/trailing whitespace in a standard way?

I didn't like most of these answers because they did one or more of the following...

  1. Returned a different pointer inside the original pointer's string (kind of a pain to juggle two different pointers to the same thing).
  2. Made gratuitous use of things like strlen() that pre-iterate the entire string.
  3. Used non-portable OS-specific lib functions.
  4. Backscanned.
  5. Used comparison to ' ' instead of isspace() so that TAB / CR / LF are preserved.
  6. Wasted memory with large static buffers.
  7. Wasted cycles with high-cost functions like sscanf/sprintf.

Here is my version:

void fnStrTrimInPlace(char *szWrite) {

    const char *szWriteOrig = szWrite;
    char       *szLastSpace = szWrite, *szRead = szWrite;
    int        bNotSpace;

    // SHIFT STRING, STARTING AT FIRST NON-SPACE CHAR, LEFTMOST
    while( *szRead != '\0' ) {

        bNotSpace = !isspace((unsigned char)(*szRead));

        if( (szWrite != szWriteOrig) || bNotSpace ) {

            *szWrite = *szRead;
            szWrite++;

            // TRACK POINTER TO LAST NON-SPACE
            if( bNotSpace )
                szLastSpace = szWrite;
        }

        szRead++;
    }

    // TERMINATE AFTER LAST NON-SPACE (OR BEGINNING IF THERE WAS NO NON-SPACE)
    *szLastSpace = '\0';
}

No mapping found for HTTP request with URI Spring MVC

<servlet-mapping>
  <servlet-name>dispatcher</servlet-name>
  <url-pattern>/*</url-pattern>
</servlet-mapping>

change to:

<servlet-mapping>
  <servlet-name>dispatcher</servlet-name>
  <url-pattern>/</url-pattern>
</servlet-mapping>

Ansible - Save registered variable to file

I am using Ansible 1.9.4 and this is what worked for me -

- local_action: copy content="{{ foo_result.stdout }}" dest="/path/to/destination/file"

How to put a tooltip on a user-defined function

@will's method is the best. Just add few lines about the details for the people didn't use ExcelDNA before like me.

Download Excel-DNA IntelliSense from https://github.com/Excel-DNA/IntelliSense/releases

There are two version, one is for 64, check your Excel version. For my case, I'm using 64 version.

Open Excel/Developer/Add-Ins/Browse and select ExcelDna.IntelliSense64.xll.

Insert a new sheet, change name to "IntelliSense", add function description, as https://github.com/Excel-DNA/IntelliSense/wiki/Getting-Started

Then enjoy! :)

enter image description here

Turn off constraints temporarily (MS SQL)

You can disable FK and CHECK constraints only in SQL 2005+. See ALTER TABLE

ALTER TABLE foo NOCHECK CONSTRAINT ALL

or

ALTER TABLE foo NOCHECK CONSTRAINT CK_foo_column

Primary keys and unique constraints can not be disabled, but this should be OK if I've understood you correctly.

Are there pointers in php?

Variable names in PHP start with $ so $entryId is the name of a variable. $this is a special variable in Object Oriented programming in PHP, which is reference to current object. -> is used to access an object member (like properties or methods) in PHP, like the syntax in C++. so your code means this:

Place the value of variable $entryId into the entryId field (or property) of this object.

The & operator in PHP, means pass reference. Here is a example:

$b=2;
$a=$b;
$a=3;
print $a;
print $b;
// output is 32

$b=2;
$a=&$b; // note the & operator
$a=3;
print $a;
print $b;
// output is 33

In the above code, because we used & operator, a reference to where $b is pointing is stored in $a. So $a is actually a reference to $b.

In PHP, arguments are passed by value by default (inspired by C). So when calling a function, when you pass in your values, they are copied by value not by reference. This is the default IN MOST SITUATIONS. However there is a way to have pass by reference behaviour, when defining a function. Example:

function plus_by_reference( &$param ) {
      // what ever you do, will affect the actual parameter outside the function
      $param++;
}

$a=2;
plus_by_reference( $a );
echo $a;
// output is 3

There are many built-in functions that behave like this. Like the sort() function that sorts an array will affect directly on the array and will not return another sorted array.

There is something interesting to note though. Because pass-by-value mode could result in more memory usage, and PHP is an interpreted language (so programs written in PHP are not as fast as compiled programs), to make the code run faster and minimize memory usage, there are some tweaks in the PHP interpreter. One is lazy-copy (I'm not sure about the name). Which means this:

When you are coping a variable into another, PHP will copy a reference to the first variable into the second variable. So your new variable, is actually a reference to the first one until now. The value is not copied yet. But if you try to change any of these variables, PHP will make a copy of the value, and then changes the variable. This way you will have the opportunity to save memory and time, IF YOU DO NOT CHANGE THE VALUE.

So:

$b=3;
$a=$b;
// $a points to $b, equals to $a=&$b
$b=4;
// now PHP will copy 3 into $a, and places 4 into $b

After all this, if you want to place the value of $entryId into 'entryId' property of your object, the above code will do this, and will not copy the value of entryId, until you change any of them, results in less memory usage. If you actually want them both to point to the same value, then use this:

$this->entryId=&$entryId;

Android: How can I pass parameters to AsyncTask's onPreExecute()?

You can override the constructor. Something like:

private class MyAsyncTask extends AsyncTask<Void, Void, Void> {

    public MyAsyncTask(boolean showLoading) {
        super();
        // do stuff
    }

    // doInBackground() et al.
}

Then, when calling the task, do something like:

new MyAsyncTask(true).execute(maybe_other_params);

Edit: this is more useful than creating member variables because it simplifies the task invocation. Compare the code above with:

MyAsyncTask task = new MyAsyncTask();
task.showLoading = false;
task.execute();

html tables & inline styles

This should do the trick:

<table width="400" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td width="50" height="40" valign="top" rowspan="3">
      <img alt="" src="" width="40" height="40" style="margin: 0; border: 0; padding: 0; display: block;">
    </td>
    <td width="350" height="40" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<a href="" style="color: #D31145; font-weight: bold; text-decoration: none;">LAST FIRST</a><br>
REALTOR | P 123.456.789
    </td>
  </tr>
  <tr>
    <td width="350" height="70" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<img alt="" src="" width="200" height="60" style="margin: 0; border: 0; padding: 0; display: block;">
    </td>
  </tr>
  <tr>
    <td width="350" height="20" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 10px; color: #000000;">
all your minor text here | all your minor text here | all your minor text here
    </td>
  </tr>
</table>

UPDATE: Adjusted code per the comments:

After viewing your jsFiddle, an important thing to note about tables is that table cell widths in each additional row all have to be the same width as the first, and all cells must add to the total width of your table.

Here is an example that will NOT WORK:

<table width="600" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td width="200" bgcolor="#252525">&nbsp;
    </td>
    <td width="400" bgcolor="#454545">&nbsp;
    </td>
  </tr>
  <tr>
    <td width="300" bgcolor="#252525">&nbsp;
    </td>
    <td width="300" bgcolor="#454545">&nbsp;
    </td>
  </tr>
</table>

Although the 2nd row does add up to 600, it (and any additional rows) must have the same 200-400 split as the first row, unless you are using colspans. If you use a colspan, you could have one row, but it needs to have the same width as the cells it is spanning, so this works:

<table width="600" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td width="200" bgcolor="#252525">&nbsp;
    </td>
    <td width="400" bgcolor="#454545">&nbsp;
    </td>
  </tr>
  <tr>
    <td width="600" colspan="2" bgcolor="#353535">&nbsp;
    </td>
  </tr>
</table>

Not a full tutorial, but I hope that helps steer you in the right direction in the future.

Here is the code you are after:

<table width="900" border="0" cellpadding="0" cellspacing="0">
  <tr>
    <td width="57" height="43" valign="top" rowspan="2">
      <img alt="Rashel Adragna" src="http://zoparealtygroup.com/wp-content/uploads/2013/10/sig_head.png" width="47" height="43" style="margin: 0; border: 0; padding: 0; display: block;">
    </td>
    <td width="843" height="43" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<a href="" style="color: #D31145; font-weight: bold; text-decoration: none;">RASHEL ADRAGNA</a><br>
REALTOR | P 855.900.24KW
    </td>
  </tr>
  <tr>
    <td width="843" height="64" valign="bottom" style="font-family: Helvetica, Arial, sans-serif; font-size: 14px; color: #000000;">
<img alt="Zopa Realty Group logo" src="http://zoparealtygroup.com/wp-content/uploads/2013/10/sig_logo.png" width="177" height="54" style="margin: 0; border: 0; padding: 0; display: block;">
    </td>
  </tr>
  <tr>
    <td width="843" colspan="2" height="20" valign="bottom" align="center" style="font-family: Helvetica, Arial, sans-serif; font-size: 10px; color: #000000;">
all your minor text here | all your minor text here | all your minor text here
    </td>
  </tr>
</table>

You'll note that I've added an extra 10px to some of your table cells. This in combination with align/valigns act as padding between your cells. It is a clever way to aviod actually having to add padding, margins or empty padding cells.

AES vs Blowfish for file encryption

The algorithm choice probably doesn't matter that much. I'd use AES since it's been better researched. What's much more important is choosing the right operation mode and key derivation function.

You might want to take a look at the TrueCrypt format specification for inspiration if you want fast random access. If you don't need random access than XTS isn't the optimal mode, since it has weaknesses other modes don't. And you might want to add some kind of integrity check(or message authentication code) too.

Ways to implement data versioning in MongoDB

The first big question when diving in to this is "how do you want to store changesets"?

  1. Diffs?
  2. Whole record copies?

My personal approach would be to store diffs. Because the display of these diffs is really a special action, I would put the diffs in a different "history" collection.

I would use the different collection to save memory space. You generally don't want a full history for a simple query. So by keeping the history out of the object you can also keep it out of the commonly accessed memory when that data is queried.

To make my life easy, I would make a history document contain a dictionary of time-stamped diffs. Something like this:

{
    _id : "id of address book record",
    changes : { 
                1234567 : { "city" : "Omaha", "state" : "Nebraska" },
                1234568 : { "city" : "Kansas City", "state" : "Missouri" }
               }
}

To make my life really easy, I would make this part of my DataObjects (EntityWrapper, whatever) that I use to access my data. Generally these objects have some form of history, so that you can easily override the save() method to make this change at the same time.

UPDATE: 2015-10

It looks like there is now a spec for handling JSON diffs. This seems like a more robust way to store the diffs / changes.

No matching client found for package name (Google Analytics) - multiple productFlavors & buildTypes

go your project directory and create folders on app/src path that named your product flavors (like Alpha, Beta, Store or what ever your flavor's name is). then copy your google-services.json file to each folder. don't forget to change "package_name" field on your each product flavor's google-services.json file that you subfoldered.

Is there a format code shortcut for Visual Studio?

Ctrl + K + D (Entire document)

Ctrl + K + F (Selection only)

git remote prune – didn't show as many pruned branches as I expected

When you use git push origin :staleStuff, it automatically removes origin/staleStuff, so when you ran git remote prune origin, you have pruned some branch that was removed by someone else. It's more likely that your co-workers now need to run git prune to get rid of branches you have removed.


So what exactly git remote prune does? Main idea: local branches (not tracking branches) are not touched by git remote prune command and should be removed manually.

Now, a real-world example for better understanding:

You have a remote repository with 2 branches: master and feature. Let's assume that you are working on both branches, so as a result you have these references in your local repository (full reference names are given to avoid any confusion):

  • refs/heads/master (short name master)
  • refs/heads/feature (short name feature)
  • refs/remotes/origin/master (short name origin/master)
  • refs/remotes/origin/feature (short name origin/feature)

Now, a typical scenario:

  1. Some other developer finishes all work on the feature, merges it into master and removes feature branch from remote repository.
  2. By default, when you do git fetch (or git pull), no references are removed from your local repository, so you still have all those 4 references.
  3. You decide to clean them up, and run git remote prune origin.
  4. git detects that feature branch no longer exists, so refs/remotes/origin/feature is a stale branch which should be removed.
  5. Now you have 3 references, including refs/heads/feature, because git remote prune does not remove any refs/heads/* references.

It is possible to identify local branches, associated with remote tracking branches, by branch.<branch_name>.merge configuration parameter. This parameter is not really required for anything to work (probably except git pull), so it might be missing.

(updated with example & useful info from comments)

document.body.appendChild(i)

You could try

document.getElementsByTagName('body')[0].appendChild(i);

Now that won't do you any good if the code is running in the <head>, and running before the <body> has even been seen by the browser. If you don't want to mess with "onload" handlers, try moving your <script> block to the very end of the document instead of the <head>.

How to run a single test with Mocha?

Hi above solutions didn't work for me. The other way of running a single test is

mocha test/cartcheckout/checkout.js -g 'Test Name Goes here'

This helps to run a test case from a single file and with specific name.

Why and when to use angular.copy? (Deep Copy)

Javascript passes variables by reference, this means that:

var i = [];
var j = i;
i.push( 1 );

Now because of by reference part i is [1], and j is [1] as well, even though only i was changed. This is because when we say j = i javascript doesn't copy the i variable and assign it to j but references i variable through j.

Angular copy lets us lose this reference, which means:

var i = [];
var j = angular.copy( i );
i.push( 1 );

Now i here equals to [1], while j still equals to [].

There are situations when such kind of copy functionality is very handy.

How to append a jQuery variable value inside the .html tag

See this Link

HTML

<div id="products"></div>

JS

var someone = {
"name":"Mahmoude Elghandour",
"price":"174 SR",
"desc":"WE Will BE WITH YOU"
 };
 var name = $("<div/>",{"text":someone.name,"class":"name"
});

var price = $("<div/>",{"text":someone.price,"class":"price"});
var desc = $("<div />", {   
"text": someone.desc,
"class": "desc"
});
$("#products").fadeIn(1500);
$("#products").append(name).append(price).append(desc);

capture div into image using html2canvas

If you just want to have screenshot of a div, you can do it like this

html2canvas($('#div'), {
  onrendered: function(canvas) {
    var img = canvas.toDataURL()
    window.open(img);
  }
});

Android emulator: could not get wglGetExtensionsStringARB error

For me changing the Emulated Performance setting to "Store a snapshot for faster startup" and unchecking "Use Host GPU" fixed the problem.

Hibernate Error executing DDL via JDBC Statement

Adding this configuration in application.properties file to fixed this issue easily.

spring.jpa.properties.hibernate.globally_quoted_identifiers=true

How to read a text file directly from Internet using Java?

Use this code to read an Internet resource into a String:

public static String readToString(String targetURL) throws IOException
{
    URL url = new URL(targetURL);
    BufferedReader bufferedReader = new BufferedReader(
            new InputStreamReader(url.openStream()));

    StringBuilder stringBuilder = new StringBuilder();

    String inputLine;
    while ((inputLine = bufferedReader.readLine()) != null)
    {
        stringBuilder.append(inputLine);
        stringBuilder.append(System.lineSeparator());
    }

    bufferedReader.close();
    return stringBuilder.toString().trim();
}

This is based on here.

Is there an Eclipse plugin to run system shell in the Console?

You can also use the Termial view to ssh/telnet to your local machine. Doesn't have that funny input box for commands.

Django error - matching query does not exist

You may try this way. just use a function to get your object

def get_object(self, id):
    try:
        return Comment.objects.get(pk=id)
    except Comment.DoesNotExist:
        return False

How do I resolve a TesseractNotFoundError?

One simple thing that actually worked for me in Jupyter Notebook, was using double backslash instead of a single backslash in the pytesseract.pytesseract.tesseract_cmd path:

pytesseract.pytesseract.tesseract_cmd = 'C:\\Program Files (x86)\\Tesseract-OCR\\tesseract.exe'