Programs & Examples On #Flash cs3

Flash CS3 is the version 3 of Adobe Flash Professional tool, part of Adobe's Creative Suite.

How to convert Windows end of line in Unix end of line (CR/LF to LF)

Go back to Windows, tell Eclipse to change the encoding to UTF-8, then back to Unix and run d2u on the files.

matplotlib colorbar for scatter

From the matplotlib docs on scatter 1:

cmap is only used if c is an array of floats

So colorlist needs to be a list of floats rather than a list of tuples as you have it now. plt.colorbar() wants a mappable object, like the CircleCollection that plt.scatter() returns. vmin and vmax can then control the limits of your colorbar. Things outside vmin/vmax get the colors of the endpoints.

How does this work for you?

import matplotlib.pyplot as plt
cm ='RdYlBu')
xy = range(20)
z = xy
sc = plt.scatter(xy, xy, c=z, vmin=0, vmax=20, s=35, cmap=cm)

Image Example

NullPointerException: Attempt to invoke virtual method 'boolean java.lang.String.equalsIgnoreCase(java.lang.String)' on a null object reference

The exception occurs due to this statement,


It seem that the previous statement

String called_from = getIntent().getStringExtra("called");

returned a null reference.

You can check whether the intent to start this activity contains such a key "called".

How to reference Microsoft.Office.Interop.Excel dll?

If you have VS 2013 Express and you cant find Microsoft.Office namespace, try this ('Microsoft Excel 12.0 Object Library' if you want to use Office 2007)

enter image description here

Android: Clear Activity Stack

I noted that you asked for a solution that does not rely on finish(), but I wonder if this may help nonetheless.

I tracked whether an exit flag is raised with a static class variable, which survives the entire app lifespan. In each relevant activity's onResume(), use

public void onResume() {
    if (ExitHelper.isExitFlagRaised) {

The ExitHelper class

public class ExitHelper {
    public static boolean isExitFlagRaised = false;

Let's say in mainActivity, a user presses a button to exit - you can set ExitHelper.isExitFlagRaised = true; and then finish(). Thereafter, other relevant activities that are resumed automatically will be finished as well.

Pass Javascript Array -> PHP

Here's a function to convert js array or object into a php-compatible array to be sent as http get request parameter:

function obj2url(prefix, obj) {
        var args=new Array();
        if(typeof(obj) == 'object'){
            for(var i in obj)
                args[args.length]=any2url(prefix+'['+encodeURIComponent(i)+']', obj[i]);
        return args.join('&');

prefix is a parameter name.


var a = {
    one: two,
    three: four

alert('/script.php?'+obj2url('a', a)); 

Will produce


which will allow you to use $_GET['a'] as an array in script.php. You will need to figure your way into your favorite ajax engine on supplying the url to call script.php from js.

Hidden Features of Xcode

Double-click on the square brackets or parentheses to obtain bracket and parentheses matching.

org.springframework.beans.factory.NoSuchBeanDefinitionException: No bean named 'customerService' is defined

You will have to annotate your service with @Service since you have said I am using annotations for mapping

Could not load file or assembly or one of its dependencies. Access is denied. The issue is random, but after it happens once, it continues

For me, the following hack worked; Go to IIS -> Application Pools -> Advance Settings -> Process Model -> Identity Changed from Built-in Account (ApplicationPoolIdentity) to Custom Account (My Domain User)

Jquery UI datepicker. Disable array of Dates

For DD-MM-YY use this code:

var array = ["03-03-2017', '03-10-2017', '03-25-2017"]

    beforeShowDay: function(date){
    var string = jQuery.datepicker.formatDate('dd-mm-yy', date);
    return [ array.indexOf(string) == -1 ]

function highlightDays(date) {
    for (var i = 0; i < dates.length; i++) {
    if (new Date(dates[i]).toString() == date.toString()) {
        return [true, 'highlight'];
return [true, ''];

Where is the web server root directory in WAMP?

If you installed WAMP to c:\wamp then I believe your webserver root directory would be c:\wamp\www, however this might vary depending on version.

Yes, this is where you would put your site files to access them through a browser.

Interpreting segfault messages

This is a segfault due to following a null pointer trying to find code to run (that is, during an instruction fetch).

If this were a program, not a shared library

Run addr2line -e yourSegfaultingProgram 00007f9bebcca90d (and repeat for the other instruction pointer values given) to see where the error is happening. Better, get a debug-instrumented build, and reproduce the problem under a debugger such as gdb.

Since it's a shared library

You're hosed, unfortunately; it's not possible to know where the libraries were placed in memory by the dynamic linker after-the-fact. Reproduce the problem under gdb.

What the error means

Here's the breakdown of the fields:

  • address (after the at) - the location in memory the code is trying to access (it's likely that 10 and 11 are offsets from a pointer we expect to be set to a valid value but which is instead pointing to 0)
  • ip - instruction pointer, ie. where the code which is trying to do this lives
  • sp - stack pointer
  • error - An error code for page faults; see below for what this means on x86.

     * Page fault error code bits:
     *   bit 0 ==    0: no page found       1: protection fault
     *   bit 1 ==    0: read access         1: write access
     *   bit 2 ==    0: kernel-mode access  1: user-mode access
     *   bit 3 ==                           1: use of reserved bit detected
     *   bit 4 ==                           1: fault was an instruction fetch

Using pointer to char array, values in that array can be accessed?

Your should create ptr as follows:

char *ptr;

You have created ptr as an array of pointers to chars. The above creates a single pointer to a char.

Edit: complete code should be:

char *ptr;
char arr[5] = {'a','b','c','d','e'};
ptr = arr;
printf("\nvalue:%c", *(ptr+0));

Why is datetime.strptime not working in this simple example?

You should be using datetime.datetime.strptime. Note that very old versions of Python (2.4 and older) don't have datetime.datetime.strptime; use time.strptime in that case.

Can the Unix list command 'ls' output numerical chmod permissions?

Closest I can think of (keeping it simple enough) is stat, assuming you know which files you're looking for. If you don't, * can find most of them:

/usr/bin$ stat -c '%a %n' *
755 [
755 a2p
755 a2ps
755 aclocal

It handles sticky, suid and company out of the box:

$ stat -c '%a %n' /tmp /usr/bin/sudo
1777 /tmp
4755 /usr/bin/sudo

Adding parameter to ng-click function inside ng-repeat doesn't seem to work

Also worth noting, for people who find this in their searches, is this...

<div ng-repeat="button in buttons" class="bb-button" ng-click="goTo(button.path)">
  <div class="bb-button-label">{{ button.label }}</div>
  <div class="bb-button-description">{{ button.description }}</div>

Note the value of ng-click. The parameter passed to goTo() is a string from a property of the binding object (the button), but it is not wrapped in quotes. Looks like AngularJS handles that for us. I got hung up on that for a few minutes.

Laravel 5 Application Key

For me the problem was in that I had not yet ran composer update for this new project/fork. The command failed silently, nothing happened.

After running composer update it worked.

Using FFmpeg in .net?

A solution that is viable for both Linux and Windows is to just get used to using console ffmpeg in your code. I stack up threads, write a simple thread controller class, then you can easily make use of what ever functionality of ffmpeg you want to use.

As an example, this contains sections use ffmpeg to create a thumbnail from a time that I specify.

In the thread controller you have something like

List<ThrdFfmpeg> threads = new List<ThrdFfmpeg>();

Which is the list of threads that you are running, I make use of a timer to Pole these threads, you can also set up an event if Pole'ing is not suitable for your application. In this case thw class Thrdffmpeg contains,

public class ThrdFfmpeg
    public FfmpegStuff ffm { get; set; }
    public Thread thrd { get; set; }

FFmpegStuff contains the various ffmpeg functionality, thrd is obviously the thread.

A property in FfmpegStuff is the class FilesToProcess, which is used to pass information to the called process, and receive information once the thread has stopped.

public class FileToProcess
    public int videoID { get; set; }
    public string fname { get; set; }
    public int durationSeconds { get; set; }
    public List<string> imgFiles { get; set; }

VideoID (I use a database) tells the threaded process which video to use taken from the database. fname is used in other parts of my functions that use FilesToProcess, but not used here. durationSeconds - is filled in by the threads that just collect video duration. imgFiles is used to return any thumbnails that were created.

I do not want to get bogged down in my code when the purpose of this is to encourage the use of ffmpeg in easily controlled threads.

Now we have our pieces we can add to our threads list, so in our controller we do something like,

        ThrdFfmpeg thrd;
        FileToProcess ftp;

        foreach(FileToProcess ff in  `dbhelper.GetFileNames(txtCategory.Text))`
            //make a thread for each
            ftp = new FileToProcess();
            ftp = ff;
            ftp.imgFiles = new List<string>();
            thrd = new ThrdFfmpeg();
            thrd.ffm = new FfmpegStuff();
            thrd.ffm.filetoprocess = ftp;
            thrd.thrd = new   `System.Threading.Thread(thrd.ffm.CollectVideoLength);`


Now Pole'ing our threads becomes a simple task,

private void timerThreads_Tick(object sender, EventArgs e)
        int runningCount = 0;
        int finishedThreads = 0;
        foreach(ThrdFfmpeg thrd in threads)
            switch (thrd.thrd.ThreadState)
                case System.Threading.ThreadState.Running:

 //Note that you can still view data progress here,
    //but remember that you must use your safety checks
    //here more than anywhere else in your code, make sure the data
    //is readable and of the right sort, before you read it.
                case System.Threading.ThreadState.StopRequested:
                case System.Threading.ThreadState.SuspendRequested:
                case System.Threading.ThreadState.Background:
                case System.Threading.ThreadState.Unstarted:

//Any threads that have been added but not yet started, start now
                case System.Threading.ThreadState.Stopped:

//You can now safely read the results, in this case the
   //data contained in FilesToProcess
   //Such as
                    ThumbnailsReadyEvent( thrd.ffm );
                case System.Threading.ThreadState.WaitSleepJoin:
                case System.Threading.ThreadState.Suspended:
                case System.Threading.ThreadState.AbortRequested:
                case System.Threading.ThreadState.Aborted:

        {//just a simple indicator so that I can see
         //that at least one thread is still running
            lbThreadStatus.BackColor = Color.White;
            flash = false;
            lbThreadStatus.BackColor = this.BackColor;
            flash = true;
        if(finishedThreads >= threads.Count())


Putting your own events onto into the controller class works well, but in video work, when my own code is not actually doing any of the video file processing, poling then invoking an event in the controlling class works just as well.

Using this method I have slowly built up just about every video and stills function I think I will ever use, all contained in the one class, and that class as a text file is useable on the Lunux and Windows version, with just a small number of pre-process directives.

Get current URL/URI without some of $_GET variables

You are definitely searching for this


how to load url into div tag

You need to use an iframe.

<script type="text/javascript">
<iframe id="content" src="about:blank"></iframe>

Jquery in React is not defined

Just a note: if you use arrow functions you don't need the const that = this part. It might look like this:

  .then((response) => { return response.json(); }) 
  .then((myJson) => { 
     this.setState({data: myJson}); // for example

Remove directory which is not empty

2020 Answer

If you want to do it in a npm script, You DON'T need to previously install any 3rd party package if you use the command npx

If for example, you want to delete the folders dist and .cache when you run npm run clean then just add this command to your package.json

  "scripts": {
    "clean": "npx rimraf dist .cache"

It will work in any operative system

check if a std::vector contains a certain object?

If searching for an element is important, I'd recommend std::set instead of std::vector. Using this:

std::find(vec.begin(), vec.end(), x) runs in O(n) time, but std::set has its own find() member (ie. myset.find(x)) which runs in O(log n) time - that's much more efficient with large numbers of elements

std::set also guarantees all the added elements are unique, which saves you from having to do anything like if not contained then push_back()....

Python coding standards/best practices

I follow it extremely rigorously. The only god before PEP-8 is existing code bases.

What algorithm for a tic-tac-toe game can I use to determine the "best move" for the AI?

This answer assumes you understand implementing the perfect algorithm for P1 and discusses how to achieve a win in conditions against ordinary human players, who will make some mistakes more commonly than others.

The game of course should end in a draw if both players play optimally. At a human level, P1 playing in a corner produces wins far more often. For whatever psychological reason, P2 is baited into thinking that playing in the center is not that important, which is unfortunate for them, since it's the only response that does not create a winning game for P1.

If P2 does correctly block in the center, P1 should play the opposite corner, because again, for whatever psychological reason, P2 will prefer the symmetry of playing a corner, which again produces a losing board for them.

For any move P1 may make for the starting move, there is a move P2 may make that will create a win for P1 if both players play optimally thereafter. In that sense P1 may play wherever. The edge moves are weakest in the sense that the largest fraction of possible responses to this move produce a draw, but there are still responses that will create a win for P1.

Empirically (more precisely, anecdotally) the best P1 starting moves seem to be first corner, second center, and last edge.

The next challenge you can add, in person or via a GUI, is not to display the board. A human can definitely remember all the state but the added challenge leads to a preference for symmetric boards, which take less effort to remember, leading to the mistake I outlined in the first branch.

I'm a lot of fun at parties, I know.

How do I output an ISO 8601 formatted string in JavaScript?

See the last example on page

/* Use a function for the exact format desired... */
function ISODateString(d) {
    function pad(n) {return n<10 ? '0'+n : n}
    return d.getUTCFullYear()+'-'
         + pad(d.getUTCMonth()+1)+'-'
         + pad(d.getUTCDate())+'T'
         + pad(d.getUTCHours())+':'
         + pad(d.getUTCMinutes())+':'
         + pad(d.getUTCSeconds())+'Z'

var d = new Date();
console.log(ISODateString(d)); // Prints something like 2009-09-28T19:03:12Z

IndentationError: unindent does not match any outer indentation level

Other posters are probably correct...there might be spaces mixed in with your tabs. Try doing a search & replace to replace all tabs with a few spaces.

Try this:

import sys

def Factorial(n): # return factorial
    result = 1
    for i in range (1,n):
        result = result * i
    print "factorial is ",result
    return result

print Factorial(10)

How to capture Enter key press?

Try this....

HTML inline

onKeydown="Javascript: if (event.keyCode==13) fnsearch();"
onkeypress="Javascript: if (event.keyCode==13) fnsearch();"


function fnsearch()
   alert('you press enter');

How to grep a text file which contains some binary data?

One way is to simply treat binary files as text anyway, with grep --text but this may well result in binary information being sent to your terminal. That's not really a good idea if you're running a terminal that interprets the output stream (such as VT/DEC or many others).

Alternatively, you can send your file through tr with the following command:

tr '[\000-\011\013-\037\177-\377]' '.' <test.log | grep whatever

This will change anything less than a space character (except newline) and anything greater than 126, into a . character, leaving only the printables.

If you want every "illegal" character replaced by a different one, you can use something like the following C program, a classic standard input filter:

int main (void) {
    int ch;
    while ((ch = getchar()) != EOF) {
        if ((ch == '\n') || ((ch >= ' ') && (ch <= '~'))) {
            putchar (ch);
        } else {
            printf ("{{%02x}}", ch);
    return 0;

This will give you {{NN}}, where NN is the hex code for the character. You can simply adjust the printf for whatever style of output you want.

You can see that program in action here, where it:

pax$ printf 'Hello,\tBob\nGoodbye, Bob\n' | ./filterProg
Goodbye, Bob

How do I find out what License has been applied to my SQL Server installation?

When I run:

   exec sp_readerrorlog @p1 = 0
   ,@p2 = 1
   ,@p3 = N'licensing'

I get:

SQL Server detected 2 sockets with 21 cores per socket and 21 logical processors per socket, 42 total logical processors; using 20 logical processors based on SQL Server licensing. This is an informational message; no user action is required.

also, SELECT @@VERSION shows:

Microsoft SQL Server 2014 (SP1-GDR) (KB4019091) - 12.0.4237.0 (X64) Jul 5 2017 22:03:42 Copyright (c) Microsoft Corporation Enterprise Edition (64-bit) on Windows NT 6.3 (Build 9600: ) (Hypervisor)

This is a VM

How can I pass a list as a command-line argument with argparse?

I think the most elegant solution is to pass a lambda function to "type", as mentioned by Chepner. In addition to this, if you do not know beforehand what the delimiter of your list will be, you can also pass multiple delimiters to re.split:

# python3 -l "abc xyz, 123"

import re
import argparse

parser = argparse.ArgumentParser(description='Process a list.')
parser.add_argument('-l', '--list',
                    type=lambda s: re.split(' |, ', s),
                    help='comma or space delimited list of characters')

args = parser.parse_args()

# Output: ['abc', 'xyz', '123']

How to return a 200 HTTP Status Code from ASP.NET MVC 3 controller

You can simply set the status code of the response to 200 like the following

public ActionResult SomeMethod(parameters...)
   //others code here
   Response.StatusCode = 200;
   return YourObject;  

How do I reverse a commit in git?

I think you need to push a revert commit. So pull from github again, including the commit you want to revert, then use git revert and push the result.

If you don't care about other people's clones of your github repository being broken, you can also delete and recreate the master branch on github after your reset: git push origin :master.

What is {this.props.children} and when you should use it?

What even is ‘children’?

The React docs say that you can use props.children on components that represent ‘generic boxes’ and that don’t know their children ahead of time. For me, that didn’t really clear things up. I’m sure for some, that definition makes perfect sense but it didn’t for me.

My simple explanation of what this.props.children does is that it is used to display whatever you include between the opening and closing tags when invoking a component.

A simple example:

Here’s an example of a stateless function that is used to create a component. Again, since this is a function, there is no this keyword so just use props.children

const Picture = (props) => {
  return (
      <img src={props.src}/>

This component contains an <img> that is receiving some props and then it is displaying {props.children}.

Whenever this component is invoked {props.children} will also be displayed and this is just a reference to what is between the opening and closing tags of the component.

render () {
  return (
    <div className='container'>
      <Picture key={} src={picture.src}>
          //what is placed here is passed as props.children  

Instead of invoking the component with a self-closing tag <Picture /> if you invoke it will full opening and closing tags <Picture> </Picture> you can then place more code between it.

This de-couples the <Picture> component from its content and makes it more reusable.

Reference: A quick intro to React’s props.children

Setting the MySQL root user password on OS X

In the terminal, write mysql -u root -pand hit Return. Enter the current mysql password that you must have noted down. And set the password SET PASSWORD = PASSWORD('new_password');

Please refer to this documentation here for more details.

Write a number with two decimal places SQL Server

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

Edited for clarity

Visual C++: How to disable specific linker warnings?

You cannot disable linker warning 4099, as said @John Weldon.

You should rebuild library with some project configuration changes. You have several options:

  • Save PDB file with debug information is same folder where you save .lib file. Set value "$(OutDir)$(TargetName).pdb" to Properties->C/C++->Output Files-Program Database File Name
  • Save debug information in .lib file. Set value "C7 compatible (/Z7)" to Properties->C/C++->General->Debug Information Format
  • Disable generation debug information for this library. Remove value from Properties->C/C++->General->Debug Information Format

Parsing CSV / tab-delimited txt file with Python

Although there is nothing wrong with the other solutions presented, you could simplify and greatly escalate your solutions by using python's excellent library pandas.

Pandas is a library for handling data in Python, preferred by many Data Scientists.

Pandas has a simplified CSV interface to read and parse files, that can be used to return a list of dictionaries, each containing a single line of the file. The keys will be the column names, and the values will be the ones in each cell.

In your case:

    import pandas

    def create_dictionary(filename):
        my_data = pandas.DataFrame.from_csv(filename, sep='\t', index_col=False)
        # Here you can delete the dataframe columns you don't want!
        del my_data['B']
        del my_data['D']
        # ...
        # Now you transform the DataFrame to a list of dictionaries
        list_of_dicts = [item for item in my_data.T.to_dict().values()]
        return list_of_dicts

# Usage:
x = create_dictionary("myfile.csv")

How to avoid precompiled headers

The .cpp file is configured to use precompiled header, therefore it must be included first (before iostream). For Visual Studio, it's name is usually "stdafx.h".

If there are no stdafx* files in your project, you need to go to this file's options and set it as “Not using precompiled headers”.

What is the difference between iterator and iterable and how to use them?

If a collection is iterable, then it can be iterated using an iterator (and consequently can be used in a for each loop.) The iterator is the actual object that will iterate through the collection.

How to remove leading and trailing spaces from a string

text.Trim() is to be used

string txt = "                   i am a string                                    ";
txt = txt.Trim();

Regex Named Groups in Java

For people coming to this late: Java 7 adds named groups. groupName) documentation.

How to configure Eclipse build path to use Maven dependencies?

I'm assuming you are using m2eclipse as you mentioned it. However it is not clear whether you created your project under Eclipse or not so I'll try to cover all cases.

  1. If you created a "Java" project under Eclipse (Ctrl+N > Java Project), then right-click the project in the Package Explorer view and go to Maven > Enable Dependency Management (depending on the initial project structure, you may have modify it to match the maven's one, for example by adding src/java to the source folders on the build path).

  2. If you created a "Maven Project" under Eclipse (Ctrl+N > Maven Project), then it should be already "Maven ready".

  3. If you created a Maven project outside Eclipse (manually or with an archetype), then simply import it in Eclipse (right-click the Package Explorer view and select Import... > Maven Projects) and it will be "Maven ready".

Now, to add a dependency, either right-click the project and select Maven > Add Dependency) or edit the pom manually.

PS: avoid using the maven-eclipse-plugin if you are using m2eclipse. There is absolutely no need for it, it will be confusing, it will generate some mess. No, really, don't use it unless you really know what you are doing.

How do I restore a dump file from mysqldump?

If you want to view the progress of the dump try this:

pv -i 1 -p -t -e /path/to/sql/dump | mysql -u USERNAME -p DATABASE_NAME

You'll of course need 'pv' installed. This command works only on *nix.

How to use MapView in android using google map V2?

I created dummy sample for Google Maps v2 Android with Kotlin and AndroidX

You can find complete project here: github-link


class MainActivity : AppCompatActivity() {

val position = LatLng(-33.920455, 18.466941)

override fun onCreate(savedInstanceState: Bundle?) {

    with(mapView) {
        // Initialise the MapView
        // Set the map ready callback to receive the GoogleMap object

private fun setMapLocation(map : GoogleMap) {
    with(map) {
        moveCamera(CameraUpdateFactory.newLatLngZoom(position, 13f))
        mapType = GoogleMap.MAP_TYPE_NORMAL
        setOnMapClickListener {
            Toast.makeText(this@MainActivity, "Clicked on map", Toast.LENGTH_SHORT).show()

override fun onResume() {

override fun onPause() {

override fun onDestroy() {

override fun onLowMemory() {


<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android=""
      xmlns:tools="" package="com.murgupluoglu.googlemap">

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

            android:value="API_KEY_HERE" />
    <activity android:name=".MainActivity">
            <action android:name="android.intent.action.MAIN"/>

            <category android:name="android.intent.category.LAUNCHER"/>



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



Create a button programmatically and set a background image

Your code should look like below

let image = UIImage(named: "name") as UIImage?
let button   = UIButton(type: UIButtonType.Custom) as UIButton
button.frame = CGRectMake(100, 100, 100, 100)
button.setImage(image, forState: .Normal)
button.addTarget(self, action: "btnTouched:", forControlEvents:.TouchUpInside)

Creating csv file with php

Just in case if someone is wondering to save the CSV file to a specific path for email attachments. Then it can be done as follows

I know I have added a lot of comments just for newbies :)

I have added an example so that you can summarize well.

$activeUsers = /** Query to get the active users */

/** Following is the Variable to store the Users data as 
    CSV string with newline character delimiter, 

    its good idea of check the delimiter based on operating system */

$userCSVData = "Name,Email,CreatedAt\n";

/** Looping the users and appending to my earlier csv data variable */
foreach ( $activeUsers as $user ) {
    $userCSVData .= $user->name. "," . $user->email. "," . $user->created_at."\n";
/** Here you can use with H:i:s too. But I really dont care of my old file  */
$todayDate  = date('Y-m-d');
/** Create Filname and Path to Store */
$fileName   = 'Active Users '.$todayDate.'.csv';
$filePath   = public_path('uploads/'.$fileName); //I am using laravel helper, in case if your not using laravel then just add absolute or relative path as per your requirements and path to store the file

/** Just in case if I run the script multiple time 
    I want to remove the old file and add new file.

    And before deleting the file from the location I am making sure it exists */
$fp = fopen($filePath, 'w+');
fwrite($fp, $userCSVData); /** Once the data is written it will be saved in the path given */

/** Now you can send email with attachments from the $filePath */

NOTE: The following is a very bad idea to increase the memory_limit and time limit, but I have only added to make sure if anyone faces the problem of connection time out or any other. Make sure to find out some alternative before sticking to it.

You have to add the following at the start of the above script.

ini_set("memory_limit", "10056M");
ini_set('mysql.connect_timeout', '0');
ini_set('max_execution_time', '0');

How to refresh materialized view in oracle

try this:

DBMS_SNAPSHOT.REFRESH( 'v_materialized_foo_tbl','f'); 

first parameter is name of mat_view and second defines type of refresh. f denotes fast refresh. but keep this thing in mind it will override any any other refresh timing options.

ArrayList initialization equivalent to array initialization

Arrays.asList can help here:

new ArrayList<Integer>(Arrays.asList(1,2,3,5,8,13,21));

how to create virtual host on XAMPP

Write these codes end of the C:\xampp\apache\conf\extra\httpd-vhosts.conf file,

DocumentRoot "D:/xampp/htdocs/foldername"
ErrorLog "logs/"
CustomLog "logs/" common

between the virtual host tag.

and edit the file System32/Drivers/etc/hosts use notepad as administrator

add bottom of the file

How to bind WPF button to a command in ViewModelBase?

 <Grid >
        <ColumnDefinition Width="*"/>
    <Button Command="{Binding ClickCommand}" Width="100" Height="100" Content="wefwfwef"/>

the code behind for the window:

public partial class MainWindow : Window
    public MainWindow()
        DataContext = new ViewModelBase();

The ViewModel:

public class ViewModelBase
    private ICommand _clickCommand;
    public ICommand ClickCommand
            return _clickCommand ?? (_clickCommand = new CommandHandler(() => MyAction(), ()=> CanExecute));
     public bool CanExecute
            // check if executing is allowed, i.e., validate, check if a process is running, etc. 
            return true/false;

    public void MyAction()


Command Handler:

 public class CommandHandler : ICommand
    private Action _action;
    private Func<bool> _canExecute;

    /// <summary>
    /// Creates instance of the command handler
    /// </summary>
    /// <param name="action">Action to be executed by the command</param>
    /// <param name="canExecute">A bolean property to containing current permissions to execute the command</param>
    public CommandHandler(Action action, Func<bool> canExecute)
        _action = action;
        _canExecute = canExecute;

    /// <summary>
    /// Wires CanExecuteChanged event 
    /// </summary>
    public event EventHandler CanExecuteChanged
        add { CommandManager.RequerySuggested += value; }
        remove { CommandManager.RequerySuggested -= value; }

    /// <summary>
    /// Forcess checking if execute is allowed
    /// </summary>
    /// <param name="parameter"></param>
    /// <returns></returns>
    public bool CanExecute(object parameter)
        return _canExecute.Invoke();

    public void Execute(object parameter)

I hope this will give you the idea.

Python urllib2 Basic Auth Problem

Here's what I'm using to deal with a similar problem I encountered while trying to access MailChimp's API. This does the same thing, just formatted nicer.

import urllib2
import base64

chimpConfig = {
    "headers" : {
    "Content-Type": "application/json",
    "Authorization": "Basic " + base64.encodestring("hayden:MYSECRETAPIKEY").replace('\n', '')
    "url": ''}

#perform authentication
datas = None
request = urllib2.Request(chimpConfig["url"], datas, chimpConfig["headers"])
result = urllib2.urlopen(request)

Firefox setting to enable cross domain Ajax request

Have you tried using jQuery's ajax request? As of version 1.3 jQuery supports certain types of cross domain ajax requests.

Quoting from the reference above:

Note: All remote (not on the same domain) requests should be specified as GET when 'script' or 'jsonp' is the dataType (because it loads script using a DOM script tag). Ajax options that require an XMLHttpRequest object are not available for these requests. The complete and success functions are called on completion, but do not receive an XHR object; the beforeSend and dataFilter functions are not called.

As of jQuery 1.2, you can load JSON data located on another domain if you specify a JSONP callback, which can be done like so: "myurl?callback=?". jQuery automatically replaces the ? with the correct method name to call, calling your specified callback. Or, if you set the dataType to "jsonp" a callback will be automatically added to your Ajax request.

Travel/Hotel API's?

I've used the TripAdvisor API before and its suited me well. It returns, per destination, a list of top-rated hotels, along with options to retrieve reviews, photos, nearby restaurants and a couple other useful things.

From the API page (available API content) :

* Hotel, attraction and restaurant ratings and reviews
* Top 10 lists of hotels, attractions and restaurants in a destination
* Traveler photos of a destination
* Travelers' Choice award badges for hotels and destinations

To expand upon @nstehr's answer, you could also use Yahoo Pipes to facilitate a more granular local search. Go to and do a search for existing hotel pipes and you'll get the idea..

Use a normal link to submit a form

You can't really do this without some form of scripting to the best of my knowledge.

<form id="my_form">
<!-- Your Form -->    
<a href="javascript:{}" onclick="document.getElementById('my_form').submit(); return false;">submit</a>

Example from Here.

How to avoid mysql 'Deadlock found when trying to get lock; try restarting transaction'

For Java programmers using Spring, I've avoided this problem using an AOP aspect that automatically retries transactions that run into transient deadlocks.

See @RetryTransaction Javadoc for more info.

Persist javascript variables across pages?

You could use the window’s name to store the information. This is known as JavaScript session. But it only works as long as the same window/tab is used.

How do I query using fields inside the new PostgreSQL JSON datatype?

Postgres 9.2

I quote Andrew Dunstan on the pgsql-hackers list:

At some stage there will possibly be some json-processing (as opposed to json-producing) functions, but not in 9.2.

Doesn't prevent him from providing an example implementation in PLV8 that should solve your problem.

Postgres 9.3

Offers an arsenal of new functions and operators to add "json-processing".

The answer to the original question in Postgres 9.3:

FROM   json_array_elements(
  '[{"name": "Toby", "occupation": "Software Engineer"},
    {"name": "Zaphod", "occupation": "Galactic President"} ]'
  ) AS elem
WHERE elem->>'name' = 'Toby';

Advanced example:

For bigger tables you may want to add an expression index to increase performance:

Postgres 9.4

Adds jsonb (b for "binary", values are stored as native Postgres types) and yet more functionality for both types. In addition to expression indexes mentioned above, jsonb also supports GIN, btree and hash indexes, GIN being the most potent of these.

The manual goes as far as suggesting:

In general, most applications should prefer to store JSON data as jsonb, unless there are quite specialized needs, such as legacy assumptions about ordering of object keys.

Bold emphasis mine.

Performance benefits from general improvements to GIN indexes.

Postgres 9.5

Complete jsonb functions and operators. Add more functions to manipulate jsonb in place and for display.

Remove an array element and shift the remaining ones

If you are most concerned about code size and/or performance (also for WCET analysis, if you need one), I think this is probably going to be one of the more transparent solutions (for finding and removing elements):

unsigned int l=0, removed=0;

for( unsigned int i=0; i<count; i++ ) {
    if( array[i] != to_remove )
        array[l++] = array[i];

count -= removed;

How to write the Fibonacci Sequence?

The idea behind the Fibonacci sequence is shown in the following Python code:

def fib(n):
   if n == 1:
      return 1
   elif n == 0:   
      return 0            
      return fib(n-1) + fib(n-2)         

This means that fib is a function that can do one of three things. It defines fib(1) == 1, fib(0) == 0, and fib(n) to be:

fib(n-1) + fib(n-2)

Where n is an arbitrary integer. This means that fib(2) for example, expands out to the following arithmetic:

fib(2) = fib(1) + fib(0)
fib(1) = 1
fib(0) = 0
# Therefore by substitution:
fib(2) = 1 + 0
fib(2) = 1

We can calculate fib(3) the same way with the arithmetic shown below:

fib(3) = fib(2) + fib(1)
fib(2) = fib(1) + fib(0)
fib(2) = 1
fib(1) = 1
fib(0) = 0
# Therefore by substitution:
fib(3) = 1 + 1 + 0

The important thing to realize here is that fib(3) can't be calculated without calculating fib(2), which is calculated by knowing the definitions of fib(1) and fib(0). Having a function call itself like the fibonacci function does is called recursion, and it's an important topic in programming.

This sounds like a homework assignment so I'm not going to do the start/end part for you. Python is a wonderfully expressive language for this though, so this should make sense if you understand math, and will hopefully teach you about recursion. Good luck!

Edit: One potential criticism of my code is that it doesn't use the super-handy Python function yield, which makes the fib(n) function a lot shorter. My example is a little bit more generic though, since not a lot of languages outside Python actually have yield.

Elastic Search: how to see the indexed data

Absolutely the easiest way to see your indexed data is to view it in your browser. No downloads or installation needed.

I'm going to assume your elasticsearch host is

Step 1

Navigate to to list your indices. You'll see something like this:

enter image description here

Step 2

Try accessing the desired index:

The output will look something like this:

enter image description here

Notice the aliases, meaning we can as well access the index at:

Step 3

Navigate to to see your data:

enter image description here

What datatype to use when storing latitude and longitude data in SQL databases?

You can easily store a lat/lon decimal number in an unsigned integer field, instead of splitting them up in a integer and decimal part and storing those separately as somewhat suggested here using the following conversion algorithm:

as a stored mysql function:

CREATE DEFINER=`r`@`l` FUNCTION `PositionSmallToFloat`(s INT) 
RETURNS decimal(10,7)
RETURN if( ((s > 0) && (s >> 31)) , (-(0x7FFFFFFF - 
(s & 0x7FFFFFFF))) / 600000, s / 600000)

and back

CREATE DEFINER=`r`@`l` FUNCTION `PositionFloatToSmall`(s DECIMAL(10,7)) 
RETURNS int(10)
RETURN s * 600000

That needs to be stored in an unsigned int(10), this works in mysql as well as in sqlite which is typeless.

through experience, I find that this works really fast, if all you need to to is store coordinates and retrieve those to do some math with.

in php those 2 functions look like

function LatitudeSmallToFloat($LatitudeSmall){
   return (float)$LatitudeSmall/(float)600000;

and back again:

function LatitudeFloatToSmall($LatitudeFloat){
   if($Latitude<0) $Latitude+=0xFFFFFFFF;
   return $Latitude;

This has some added advantage as well in term of creating for example memcached unique keys with integers. (ex: to cache a geocode result). Hope this adds value to the discussion.

Another application could be when you are without GIS extensions and simply want to keep a few million of those lat/lon pairs, you can use partitions on those fields in mysql to benefit from the fact they are integers:

Create Table: CREATE TABLE `Locations` (
  `lat` int(10) unsigned NOT NULL,
  `lon` int(10) unsigned NOT NULL,
  `location` text,
  PRIMARY KEY (`lat`,`lon`) USING BTREE,
  KEY `index_location` (`locationText`(30))
/*!50100 PARTITION BY KEY ()

Use cell's color as condition in if statement (function)

You cannot use VBA (Interior.ColorIndex) in a formula which is why you receive the error.

It is not possible to do this without VBA.

Function YellowIt(rng As Range) As Boolean
    If rng.Interior.ColorIndex = 6 Then
        YellowIt = True
        YellowIt = False
    End If
End Function

However, I do not recommend this: it is not how user-defined VBA functions (UDFs) are intended to be used. They should reflect the behaviour of Excel functions, which cannot read the colour-formatting of a cell. (This function may not work in a future version of Excel.)

It is far better that you base a formula on the original condition (decision) that makes the cell yellow in the first place. Or, alternatively, run a Sub procedure to fill in the True or False values (although, of course, these values will no longer be linked to the original cell's formatting).

How to change the color of header bar and address bar in newest Chrome version on Lollipop?

For example, to set the background to your favorite/Branding color

Add Below Meta property to your HTML code in HEAD Section

  <meta name="theme-color" content="Your Hexadecimal Code">


  <meta name="theme-color" content="#444444">

In Below Image, I just mentioned How Chrome taken your theme-color Property

enter image description here

Firefox OS, Safari, Internet Explorer and Opera Coast allow you to define colors for elements of the browser, and even the platform using meta tags.

<!-- Windows Phone -->
<meta name="msapplication-navbutton-color" content="#4285f4">
<!-- iOS Safari -->
<meta name="apple-mobile-web-app-capable" content="yes">
<meta name="apple-mobile-web-app-status-bar-style" content="black-translucent">

Safari specific styling

From the guidelinesDocuments Here

Hiding Safari User Interface Components

Set the apple-mobile-web-app-capable meta tag to yes to turn on standalone mode. For example, the following HTML displays web content using standalone mode.

<meta name="apple-mobile-web-app-capable" content="yes">

Changing the Status Bar Appearance

You can change the appearance of the default status bar to either black or black-translucent. With black-translucent, the status bar floats on top of the full screen content, rather than pushing it down. This gives the layout more height, but obstructs the top. Here’s the code required:

<meta name="apple-mobile-web-app-status-bar-style" content="black">

For more on status bar appearance, see apple-mobile-web-app-status-bar-style.

For Example:

Screenshot using black-translucent

Screenshot using black-translucent

Screenshot using black

Screenshot using black

nodejs - first argument must be a string or Buffer - when using response.write with http.request

Although the question is solved, sharing knowledge for clarification of the correct meaning of the error.

The error says that the parameter needed to the concerned breaking function is not in the required format i.e. string or Buffer

The solution is to change the parameter to string

breakingFunction(JSON.stringify(offendingParameter), ... other params...);

or buffer

breakingFunction(BSON.serialize(offendingParameter), ... other params...);

.htaccess rewrite to redirect root URL to subdirectory

You can use a rewrite rule that uses ^$ to represent the root and rewrite that to your /store directory, like this:

RewriteEngine On
RewriteRule ^$ /store [L]

LEFT JOIN only first row

based on several answers here, i found something that worked for me and i wanted to generalize and explain what's going on.


LEFT JOIN table2 t2 ON (t2.thing = t1.thing)


LEFT JOIN table2 t2 ON (t2.p_key = (SELECT MIN(t2_.p_key) 
    FROM table2 t2_ WHERE (t2_.thing = t1.thing) LIMIT 1))

the condition that connects t1 and t2 is moved from the ON and into the inner query WHERE. the MIN(primary key) or LIMIT 1 makes sure that only 1 row is returned by the inner query.

after selecting one specific row we need to tell the ON which row it is. that's why the ON is comparing the primary key of the joined tabled.

you can play with the inner query (i.e. order+limit) but it must return one primary key of the desired row that will tell the ON the exact row to join.

Update - for MySQL 5.7+

another option relevant to MySQL 5.7+ is to use ANY_VALUE+GROUP BY. it will select an artist name that is not necessarily the first one.

SELECT feeds.*,ANY_VALUE( artist_name
    FROM feeds 
    LEFT JOIN feeds_artists ON = feeds_artists.feed_id 

more info about ANY_VALUE:

Removing multiple classes (jQuery)

The documentation says:

class (Optional) String
One or more CSS classes to remove from the elements, these are separated by spaces.


Remove the class 'blue' and 'under' from the matched elements.

$("p:odd").removeClass("blue under");

How to switch to another domain and get-aduser

Try specifying a DC in DomainB using the -Server property. Ex:

Get-ADUser -Server "dc01.DomainB.local" -Filter {EmailAddress -like "*Smith_Karla*"} -Properties EmailAddress

TypeError: $(...).modal is not a function with bootstrap Modal

i just want to emphasize what mwebber said in the comment:

also check if jQuery is not included twice


it was the issue for me

org.hibernate.MappingException: Unknown entity

My issue was resolved After adding
sessionFactory.setPackagesToScan( new String[] { "com.springhibernate.model" }); Tested this Functionality in spring boot latest version 2.1.2.

Full Method:

 @Bean( name="sessionFactoryConfig")
    public LocalSessionFactoryBean sessionFactoryConfig() {

        LocalSessionFactoryBean sessionFactory = new LocalSessionFactoryBean();

                new String[] { "com.springhibernate.model" });


        return sessionFactory;

What is the difference between using constructor vs getInitialState in React / React Native?

These days we don't have to call the constructor inside the component - we can directly call state={something:""}, otherwise previously first we have do declare constructor with super() to inherit every thing from React.Component class then inside constructor we initialize our state.

If using React.createClass then define initialize state with the getInitialState method.

Datagrid binding in WPF

PLEASE do not use object as a class name:

public class MyObject //better to choose an appropriate name
    string id;
    DateTime date;
    public string ID
       get { return id; }
       set { id = value; }
    public DateTime Date
       get { return date; }
       set { date = value; }

You should implement INotifyPropertyChanged for this class and of course call it on the Property setter. Otherwise changes are not reflected in your ui.

Your Viewmodel class/ dialogbox class should have a Property of your MyObject list. ObservableCollection<MyObject> is the way to go:

public ObservableCollection<MyObject> MyList

In your xaml you should set the Itemssource to your collection of MyObject. (the Datacontext have to be your dialogbox class!)

<DataGrid ItemsSource="{Binding Source=MyList}"  AutoGenerateColumns="False">
     <DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
     <DataGridTextColumn Header="Date" Binding="{Binding Date}"/>

What is Java EE?

I would say that J2EE experience = in-depth experience with a few J2EE technologies, general knowledge about most J2EE technologies, and general experience with enterprise software in general.

git: Your branch is ahead by X commits

The answers that suggest git pull or git fetch are correct.
The message is generated when git status sees a difference between .git/FETCH_HEAD and .git/refs/remotes/<repository>/<branch> (e.g. .git/refs/remotes/origin/master).

The latter file records the HEAD from the last fetch (for the repository/branch). Doing git fetch updates both files to the branch's current HEAD.
Of course if there is nothing to fetch (because the local repository is already up-to-date) then .git/FETCH_HEAD doesn't change.

Disable LESS-CSS Overwriting calc()

Example for escaped string with variable:

@some-variable-height: 10px;


div {
    height: ~"calc(100vh - "@some-variable-height~")";

compiles to

div {
    height: calc(100vh - 10px );

Disabled UIButton not faded or grey

Create an extension in Swift > 3.0 rather than each button by itself

extension UIButton {
    override open var isEnabled : Bool {
            if newValue == false {
                self.setTitleColor(UIColor.gray, for: UIControlState.disabled)

"The 'Microsoft.ACE.OLEDB.12.0' provider is not registered on the local machine" Error in importing process of xlsx to a sql server

Excel 2010 driver is 64 bit, while the default SSMS import export wizard is 32 therefore the error message.

You can import using the Import Export Data (64 bit) tool. ("C:\Program Files\Microsoft SQL Server\110\DTS\Binn\DTSWizard.exe") notice the path is not Program Files x86.

How to use a ViewBag to create a dropdownlist?

hope it will work

 @Html.DropDownList("accountid", (IEnumerable<SelectListItem>)ViewBag.Accounts, String.Empty, new { @class ="extra-class" })

Here String.Empty will be the empty as a default selector.

How to remove commits from a pull request

This is what helped me:

  1. Create a new branch with the existing one. Let's call the existing one branch_old and new as branch_new.

  2. Reset branch_new to a stable state, when you did not have any problem commit at all. For example, to put it at your local master's level do the following:

    git reset —hard master git push —force origin

  3. cherry-pick the commits from branch_old into branch_new

  4. git push

Could not establish secure channel for SSL/TLS with authority '*'

Ensure you run Visual Studio as an administrator.

iPad Web App: Detect Virtual Keyboard Using JavaScript in Safari?

Well, you can detect when your input boxes have the focus, and you know the height of the keyboard. There is also CSS available to get the orientation of the screen, so I think you can hack it.

You would want to handle the case of a physical keyboard somehow, though.

How to convert a string to a date in sybase

Use the convert function, for example:

select * from data 
where dateVal < convert(datetime, '01/01/2008', 103)

Where the convert style (103) determines the date format to use.

How to move the layout up when the soft keyboard is shown android

I somehow achieved this by knowing the status of the soft keyboard on the device. i move the layout to y position when the keyboard is shown and moved back to its original position when not shown. this works fine, followed this guidelines.

Adding options to a <select> using jQuery?

for whatever reason doing $("#myselect").append(new Option("text", "text")); isn't working for me in IE7+

I had to use $("#myselect").html("<option value='text'>text</option>");

javascript clear field value input

This may be what you want:

Working jsFiddle here

  • This code places a default text string Enter your name here inside the <input> textbox, and colorizes the text to light grey.

  • As soon as the box is clicked, the default text is cleared and text color set to black.

  • If text is erased, the default text string is replaced and light grey color reset.


<input id="fname" type="text" />


$(document).ready(function() {

    var curval;
    var fn = $('#fname');
    fn.val('Enter your name here').css({"color":"lightgrey"});

    fn.focus(function() {
        //Upon ENTERING the field
        curval = $(this).val();
        if (curval == 'Enter your name here' || curval == '') {
    }); //END focus()

    fn.blur(function() {
        //Upon LEAVING the field
        curval = $(this).val();
        if (curval != 'Enter your name here' && curval != '') {
            fn.val('Enter your name here').css({"color":"lightgrey"});
    }); //END blur()

}); //END document.ready

How to do integer division in javascript (Getting division answer in int not float)?

var x = parseInt(455/10);

The parseInt() function parses a string and returns an integer.

The radix parameter is used to specify which numeral system to be used, for example, a radix of 16 (hexadecimal) indicates that the number in the string should be parsed from a hexadecimal number to a decimal number.

If the radix parameter is omitted, JavaScript assumes the following:

If the string begins with "0x", the radix is 16 (hexadecimal)
If the string begins with "0", the radix is 8 (octal). This feature is deprecated
If the string begins with any other value, the radix is 10 (decimal)

How to set HTML Auto Indent format on Sublime Text 3?

One option is to type [command] + [shift] + [p] (or the equivalent) and then type 'indentation'. The top result should be 'Indendtation: Reindent Lines'. Press [enter] and it will format the document.

Another option is to install the Emmet plugin (, which will provide not only better formatting, but also a myriad of other incredible features. To get the output you're looking for using Sublime Text 3 with the Emmet plugin requires just the following:

p [tab][enter] Hello world!

When you type p [tab] Emmet expands it to:


Pressing [enter] then further expands it to:



With the cursor indented and on the line between the tags. Meaning that typing text results in:

    Hello, world!

Checking Value of Radio Button Group via JavaScript?


var selectedVal;

for( i = 0; i < document.form_name.gender.length; i++ )
    selectedVal = document.form_name.gender[i].value; //male or female

How to draw rounded rectangle in Android UI?

You could just define a new xml background in the drawables folder

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android=""
<solid android:color="enter_your_desired_color_here" />
<corners android:radius="enter_your_desired_radius_the_corners" />

After this just include it in your TextView or EditText by defining it in the background.

 android:textSize="40sp" />

How to base64 encode image in linux bash / shell

You need to use cat to get the contents of the file named 'DSC_0251.JPG', rather than the filename itself.

test="$(cat DSC_0251.JPG | base64)"

However, base64 can read from the file itself:

test=$( base64 DSC_0251.JPG )

In Python script, how do I set PYTHONPATH?

You don't set PYTHONPATH, you add entries to sys.path. It's a list of directories that should be searched for Python packages, so you can just append your directories to that list.


In fact, sys.path is initialized by splitting the value of PYTHONPATH on the path separator character (: on Linux-like systems, ; on Windows).

You can also add directories using site.addsitedir, and that method will also take into account .pth files existing within the directories you pass. (That would not be the case with directories you specify in PYTHONPATH.)

Best way to find if an item is in a JavaScript array?

A robust way to check if an object is an array in javascript is detailed here:

Here are two functions from the xa.js framework which I attach to a utils = {} ‘container’. These should help you properly detect arrays.

var utils = {};

 * utils.isArray
 * Best guess if object is an array.
utils.isArray = function(obj) {
     // do an instanceof check first
     if (obj instanceof Array) {
         return true;
     // then check for obvious falses
     if (typeof obj !== 'object') {
         return false;
     if (utils.type(obj) === 'array') {
         return true;
     return false;

 * utils.type
 * Attempt to ascertain actual object type.
utils.type = function(obj) {
    if (obj === null || typeof obj === 'undefined') {
        return String (obj);
        .replace(/\[object ([a-zA-Z]+)\]/, '$1').toLowerCase();

If you then want to check if an object is in an array, I would also include this code:

 * Adding hasOwnProperty method if needed.
if (typeof Object.prototype.hasOwnProperty !== 'function') {
    Object.prototype.hasOwnProperty = function (prop) {
        var type = utils.type(this);
        type = type.charAt(0).toUpperCase() + type.substr(1);
        return this[prop] !== undefined
            && this[prop] !== window[type].prototype[prop];

And finally this in_array function:

function in_array (needle, haystack, strict) {
    var key;

    if (strict) {
        for (key in haystack) {
            if (!haystack.hasOwnProperty[key]) continue;

            if (haystack[key] === needle) {
                return true;
    } else {
        for (key in haystack) {
            if (!haystack.hasOwnProperty[key]) continue;

            if (haystack[key] == needle) {
                return true;

    return false;

How to change the font color of a disabled TextBox?

If you want to display text that cannot be edited or selected you can simply use a label

whitespaces in the path of windows filepath

Try putting double quotes in your filepath variable

"\"E:/ABC/SEM 2/testfiles/all.txt\""

Check the permissions of the file or in any case consider renaming the folder to remove the space

Generate insert script for selected records?

SELECT 'INSERT SomeOtherDB.dbo.table(column1,column2,etc.)
  SELECT ' + CONVERT(VARCHAR(12), Pk_Id) + ','
       + '''' + REPLACE(ProductName, '''', '''''') + ''','
       + CONVERT(VARCHAR(12), Fk_CompanyId) + ','
       + CONVERT(VARCHAR(12), Price) + ';'
FROM dbo.unspecified_table_name
WHERE Fk_CompanyId = 1;

TortoiseSVN icons overlay not showing after updating to Windows 10

Tortoise Settings > Icon Overlays -> Overlay Handlers -> Start registry editor

1. Rename icon name :By adding a space(s) at the beginning of the file's name and then press F5 until it goes to top . example: " Tortoise1Normal" (in default 2 spaces included)? " Tortoise1Normal" (3 spaces)

2. Restart explorer in Task manager


Convert generic List/Enumerable to DataTable?

I've written a small library myself to accomplish this task. It uses reflection only for the first time an object type is to be translated to a datatable. It emits a method that will do all the work translating an object type.

Its blazing fast. You can find it here: ModelShredder on GoogleCode

What is the difference between bindParam and bindValue?

For the most common purpose, you should use bindValue.

bindParam has two tricky or unexpected behaviors:

  • bindParam(':foo', 4, PDO::PARAM_INT) does not work, as it requires passing a variable (as reference).
  • bindParam(':foo', $value, PDO::PARAM_INT) will change $value to string after running execute(). This, of course, can lead to subtle bugs that might be difficult to catch.


Load image from resources

ResourceManager will work if your image is in a resource file. If it is just a file in your project (let's say the root) you can get it using something like this:

System.Reflection.Assembly assembly = System.Reflection.Assembly.GetExecutingAssembly();
System.IO.Stream file = assembly .GetManifestResourceStream("AssemblyName." + channel);
this.pictureBox1.Image = Image.FromStream(file);

Or if you're in WPF:

    private ImageSource GetImage(string channel)
        StreamResourceInfo sri = Application.GetResourceStream(new Uri("/TestApp;component/" + channel, UriKind.Relative));
        BitmapImage bmp = new BitmapImage();
        bmp.StreamSource = sri.Stream;

        return bmp;

Calling a function every 60 seconds

here we console natural number 0 to ......n (next number print in console every 60 sec.) , using setInterval()

var count = 0;
function abc(){
    count ++;

Perl - Multiple condition if statement without duplicating code?

if (   ($name eq "tom" and $password eq "123!")
    or ($name eq "frank" and $password eq "321!")) {

    print "You have gained access.";
else {
    print "Access denied!";

how to check for special characters php

preg_match('/'.preg_quote('^\'£$%^&*()}{@#~?><,@|-=-_+-¬', '/').'/', $string);

Unable to execute dex: Multiple dex files define

Well for me, I deleted the file in the libs folder called android support v4.jar and it all worked out. Goodluck :)

How can I resize an image using Java?

After loading the image you can try:

BufferedImage createResizedCopy(Image originalImage, 
            int scaledWidth, int scaledHeight, 
            boolean preserveAlpha)
        int imageType = preserveAlpha ? BufferedImage.TYPE_INT_RGB : BufferedImage.TYPE_INT_ARGB;
        BufferedImage scaledBI = new BufferedImage(scaledWidth, scaledHeight, imageType);
        Graphics2D g = scaledBI.createGraphics();
        if (preserveAlpha) {
        g.drawImage(originalImage, 0, 0, scaledWidth, scaledHeight, null); 
        return scaledBI;

iOS 7 - Status bar overlaps the view

For Navigation Bar :

Writing this code :

self.navigationController.navigationBar.translucent = NO;

just did the trick for me.

jquery - fastest way to remove all rows from a very large table

It's better to avoid any kind of loops, just remove all elements directly like this:

$("#mytable > tbody").html("");

How to display a PDF via Android web browser without "downloading" first

You can open PDF in Google Docs Viewer by appending URL to:<url of a supported doc>

This would open PDF in default browser or a WebView.

A list of supported formats is given here.

Bootstrap center heading

Just use "justify-content-center" in the row's class attribute.

<div class="container">
  <div class="row justify-content-center">
    <h1>This is a header</h1>

Swift 3 URLSession.shared() Ambiguous reference to member 'dataTask(with:completionHandler:) error (bug)

Short and concise answer for Swift 3:

guard let requestUrl = URL(string: yourURL) else { return }

let request = URLRequest(url:requestUrl)
URLSession.shared.dataTask(with: request) {
    (data, response, error) in


How can I add raw data body to an axios request?

The key is to use "Content-Type": "text/plain" as mentioned by @MadhuBhat., code, { headers: { "Content-Type": "text/plain" } }).then(response => {

A thing to note if you use .NET is that a raw string to a controller will return 415 Unsupported Media Type. To get around this you need to encapsulate the raw string in hyphens like this and send it as "Content-Type": "application/json":, "\"" + code + "\"", { headers: { "Content-Type": "application/json" } }).then(response => {

C# Controller:

public async Task<ActionResult<string>> Post([FromBody] string code)
    return Ok(code);

You can also make a POST with query params if that helps:

.post(`/mails/users/sendVerificationMail`, null, { params: {
.then(response => response.status)
.catch(err => console.warn(err));

This will POST an empty body with the two query params:

POST http://localhost:8000/api/mails/users/sendVerificationMail?


Sort Array of object by object field in Angular 6

You can simply use Arrays.sort()

array.sort((a,b) => a.title.rendered.localeCompare(b.title.rendered));

Working Example :

var array = [{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"VPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""},},{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"adfPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""}},{"id":3645,"date":"2018-07-05T13:13:37","date_gmt":"2018-07-05T13:13:37","guid":{"rendered":""},"modified":"2018-07-05T13:13:37","modified_gmt":"2018-07-05T13:13:37","slug":"vpwin","status":"publish","type":"matrix","link":"","title":{"rendered":"bbfPWIN"},"content":{"rendered":"","protected":false},"featured_media":0,"parent":0,"template":"","better_featured_image":null,"acf":{"domain":"SMB","ds_rating":"3","dt_rating":""}}];_x000D_
array.sort((a,b) => a.title.rendered.localeCompare(b.title.rendered));_x000D_

In Java, how do I get the difference in seconds between 2 dates?

That should do it:

Date a = ...;
Date b = ...;


Here the relevant documentation: Date.getTime(). Be aware that this will only work for dates after January 1, 1970, 00:00:00 GMT

How to send list of file in a folder to a txt file in Linux

you can just use

ls > filenames.txt

(usually, start a shell by using "Terminal", or "shell", or "Bash".) You may need to use cd to go to that folder first, or you can ls ~/docs > filenames.txt

How can I change the color of AlertDialog title and the color of the line under it

In case you are using extending the dialog the use:


Bash loop ping successful

I use this Bash script to test the internet status every minute on OSX

#address=  # forced bad address for testing/debugging
address= #
internet=1             # default to internet is up

while true;
    # %a  Day of Week, textual
    # %b  Month, textual, abbreviated
    # %d  Day, numeric
    # %r  Timestamp AM/PM
    echo -n $(date +"%a, %b %d, %r") "-- " 
    ping -c 1 ${address} > /tmp/ping.$
    if [[ $? -ne 0 ]]; then
        if [[ ${internet} -eq 1 ]]; then   # edge trigger -- was up now down
            echo -n $(say "Internet down") # OSX Text-to-Speech
            echo -n "Internet DOWN"
            echo -n "... still down"
        if [[ ${internet} -eq 0 ]]; then     # edge trigger -- was down now up
            echo -n $(say "Internet back up") # OSX Text-To-Speech
    cat /tmp/ping.$ | head -2 | tail -1
    sleep 60 ; # sleep 60 seconds =1 min

How to shift a block of code left/right by one space in VSCode?


While these methods work, newer versions of VS Code uses the Ctrl+] shortcut to indent a block of code once, and Ctrl+[ to remove indentation.

This method detects the indentation in a file and indents accordingly.You can change the size of indentation by clicking on the Select Indentation setting in the bottom right of VS Code (looks something like "Spaces: 2"), selecting "Indent using Spaces" from the drop-down menu and then selecting by how many spaces you would like to indent.

Is it possible to use JavaScript to change the meta-tags of the page?

No, a div is a body element, not a head element

EDIT: Then the only thing SEs are going to get is the base HTML, not the ajax modified one.

How to get element-wise matrix multiplication (Hadamard product) in numpy?

just do this:

import numpy as np

a = np.array([[1,2],[3,4]])
b = np.array([[5,6],[7,8]])

a * b

Why can't DateTime.Parse parse UTC date

Just replace "UTC" with "GMT" -- simple and doesn't break correctly formatted dates:

DateTime.Parse("Tue, 1 Jan 2008 00:00:00 UTC".Replace("UTC", "GMT"))

Generate random int value from 3 to 6

In general:

select rand()*(@upper-@lower)+@lower;

For your question:

select rand()*(6-3)+3;


select rand()*3+3;

Maven won't run my Project : Failed to execute goal org.codehaus.mojo:exec-maven-plugin:1.2.1:exec

I solved this issue with right click on project -> Set as Main Project.

Loop structure inside gnuplot?

I have the script all.p

set ...
list=system('ls -1B *.dat')
plot for [file in list] file w l u 1:2 t file

Here the two last rows are literal, not heuristic. Then i run

$ gnuplot -p all.p

Change *.dat to the file type you have, or add file types.

Next step: Add to ~/.bashrc this line

alias p='gnuplot -p ~/./all.p'

and put your file all.p int your home directory and voila. You can plot all files in any directory by typing p and enter.

EDIT I changed the command, because it didn't work. Previously it contained list(i)=word(system(ls -1B *.dat),i).

RecyclerView inside ScrollView is not working

you can also override LinearLayoutManager to make recyclerview roll smoothly

    public boolean canScrollVertically(){
        return false;

View/edit ID3 data for MP3 files

Thirding TagLib Sharp.

TagLib.File f = TagLib.File.Create(path);
f.Tag.Album = "New Album Title";

How can one see content of stack with GDB?

info frame to show the stack frame info

To read the memory at given addresses you should take a look at x

x/x $esp for hex x/d $esp for signed x/u $esp for unsigned etc. x uses the format syntax, you could also take a look at the current instruction via x/i $eip etc.

SQL Server Restore Error - Access is Denied

Try this:

In the Restore DB wizard window, go to Files tab, Uncheck "Relocate All files to folder" check box then change the restore destination from C: to some other drive. Then proceed with the regular restore process. It will get restored successfully.

How to get a web page's source code from Java

Try the following code with an added request property:


public class SocketConnection
    public static String getURLSource(String url) throws IOException
        URL urlObject = new URL(url);
        URLConnection urlConnection = urlObject.openConnection();
        urlConnection.setRequestProperty("User-Agent", "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.11 (KHTML, like Gecko) Chrome/23.0.1271.95 Safari/537.11");

        return toString(urlConnection.getInputStream());

    private static String toString(InputStream inputStream) throws IOException
        try (BufferedReader bufferedReader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8")))
            String inputLine;
            StringBuilder stringBuilder = new StringBuilder();
            while ((inputLine = bufferedReader.readLine()) != null)

            return stringBuilder.toString();

How can I store and retrieve images from a MySQL database using PHP?

i also recommend thinking this thru and then choosing to store images in your file system rather than the DB .. see here: Storing Images in DB - Yea or Nay?

How can my iphone app detect its own version number?

You can use the infoDictionary which gets the version details from info.plist of you app. This code works for swift 3. Just call this method and display the version in any preferred UI element.


func getVersion() -> String {
    let dictionary = Bundle.main.infoDictionary!
    let version = dictionary["CFBundleShortVersionString"] as! String
    let build = dictionary["CFBundleVersion"] as! String
    return "v\(version).\(build)"

XSL if: test with multiple test conditions

Thanks to @IanRoberts, I had to use the normalize-space function on my nodes to check if they were empty.

<xsl:if test="((node/ABC!='') and (normalize-space(node/DEF)='') and (normalize-space(node/GHI)=''))">
  This worked perfectly fine.

how to save canvas as png image?

Try this:

jQuery('body').after('<a id="Download" target="_blank">Click Here</a>');

var canvas = document.getElementById('canvasID');
var ctx = canvas.getContext('2d');

document.getElementById('Download').addEventListener('click', function() {
    downloadCanvas(this, 'canvas', 'test.png');
}, false);

function downloadCanvas(link, canvasId, filename) {
    link.href = document.getElementById(canvasId).toDataURL();
    link.Download = filename;

You can just put this code in console in firefox or chrom and after changed your canvas tag ID in this above script and run this script in console.

After the execute this code you will see the link as text "click here" at bottom of the html page. click on this link and open the canvas drawing as a PNG image in new window save the image.

Checking for NULL pointer in C/C++

Most compilers I've used will at least warn on the if assignment without further syntax sugar, so I don't buy that argument. That said, I've used both professionally and have no preference for either. The == NULL is definitely clearer though in my opinion.

C++ string to double conversion

Coversion from string to double can be achieved by using the 'strtod()' function from the library 'stdlib.h'

#include <iostream>
#include <stdlib.h>
int main () 
    std::string data="20.9";
    double value = strtod(data.c_str(), NULL);
    return 0;

Pass parameter from a batch file to a PowerShell script

Add the parameter declaration at the top of ps1 file


  # Our preferred encoding
  [string]$Encoding = "UTF8"

write ("Encoding : {0}" -f $Encoding)


C:\temp> .\test.ps1 -Encoding ASCII
Encoding : ASCII

How to call a mysql stored procedure, with arguments, from command line?

With quotes around the date:

mysql> CALL insertEvent('2012.01.01 12:12:12');

How do I position a div at the bottom center of the screen

If you aren't comfortable with using negative margins, check this out.

div {
  position: fixed;
  left: 50%;
  bottom: 20px;
  transform: translate(-50%, -50%);
  margin: 0 auto;
  Your Text

Especially useful when you don't know the width of the div.

align="center" has no effect.

Since you have position:absolute, I would recommend positioning it 50% from the left and then subtracting half of its width from its left margin.

#manipulate {

How to know if other threads have finished?

You could also use SwingWorker, which has built-in property change support. See addPropertyChangeListener() or the get() method for a state change listener example.

Number of rows affected by an UPDATE in PL/SQL

Use the Count(*) analytic function OVER PARTITION BY NULL This will count the total # of rows

Unit test naming best practices

I like this naming style:


and so on. It makes really clear to a non-tester what the problem is.

What is log4j's default log file dumping path

To redirect your logs output to a file, you need to use the FileAppender and need to define other file details in your file. Here is a sample properties file for the same:

# Root logger option
log4j.rootLogger=INFO, file

# Direct log messages to a log file
log4j.appender.file.layout.ConversionPattern=%d{yyyy-MM-dd HH:mm:ss} %-5p %c{1}:%L - %m%n

Follow this tutorial to learn more about log4j usage:

What is the maximum recursion depth in Python, and how to increase it?

We could also use a variation of dynamic programming bottom up approach

def fib_bottom_up(n):

    bottom_up = [None] * (n+1)
    bottom_up[0] = 1
    bottom_up[1] = 1

    for i in range(2, n+1):
        bottom_up[i] = bottom_up[i-1] + bottom_up[i-2]

    return bottom_up[n]


Vertically align text to top within a UILabel

It can be done with more flexibility setting a height constraint to the label in Interface Builder, binding it to the code with an IBOutlet and changing that height to show the text in a concrete vertical position. Example for center and bottom alignment:

labelHeightConstraint.constant = centerAlignment ? 30 : 15

response.sendRedirect() from Servlet to JSP does not seem to work

Instead of using


Which does a permanent redirect to an absolute URL path,

Rather use RequestDispatcher. Example:

RequestDispatcher dispatcher = request.getRequestDispatcher("demo.jsp");
dispatcher.forward(request, response);

In what situations would AJAX long/short polling be preferred over HTML5 WebSockets?

XHR polling vs SSE vs WebSockets

  • XHR polling A Request is answered when the event occurs (could be straight away, or after a delay). Subsequent requests will need to made to receive further events.

    The browser makes an asynchronous request of the server, which may wait for data to be available before responding. The response can contain encoded data (typically XML or JSON) or Javascript to be executed by the client. At the end of the processing of the response, the browser creates and sends another XHR, to await the next event. Thus the browser always keeps a request outstanding with the server, to be answered as each event occurs. Wikipedia

  • Server Sent Events Client sends request to server. Server sends new data to webpage at any time.

    Traditionally, a web page has to send a request to the server to receive new data; that is, the page requests data from the server. With server-sent events, it's possible for a server to send new data to a web page at any time, by pushing messages to the web page. These incoming messages can be treated as Events + data inside the web page. Mozilla

  • WebSockets After the initial handshake (via HTTP protocol). Communication is done bidirectionally using the WebSocket protocol.

    The handshake starts with an HTTP request/response, allowing servers to handle HTTP connections as well as WebSocket connections on the same port. Once the connection is established, communication switches to a bidirectional binary protocol which does not conform to the HTTP protocol. Wikipedia

Force youtube embed to start in 720p

I've managed to get this working by the following fix:


You video should have the hd720 resolution to do so.

I was using the embedding via iframe, BTW. Hope someone will find this helpful.

How to convert hashmap to JSON object in Java

Better be late than never. I used GSON to convert list of HashMap to string if in case you want to have a serialized list.

List<HashMap<String, String>> list = new ArrayList<>();
HashMap<String,String> hashMap = new HashMap<>();
hashMap.add("key", "value");
hashMap.add("key", "value");
hashMap.add("key", "value");

String json = new Gson().toJson(list);

This json produces [{"key":"value","key":"value","key":"value"}]

Dealing with commas in a CSV file

The simplest solution I've found is the one LibreOffice uses:

  1. Replace all literal " by
  2. Put double quotes around your string

You can also use the one that Excel uses:

  1. Replace all literal " by ""
  2. Put double quotes around your string

Notice other people recommended to do only step 2 above, but that doesn't work with lines where a " is followed by a ,, like in a CSV where you want to have a single column with the string hello",world, as the CSV would read:


Which is interpreted as a row with two columns: hello and world"

Assigning more than one class for one event

    $('.tag1, .tag2').on('click', function() {

      if ($(this).hasClass('clickedTag')){
         // code here
      } else {
         // and here



function dothing() {
   if ($(this).hasClass('clickedTag')){
        // code here
    } else {
        // and here

$('.tag1, .tag2').on('click', dothing);


 $('[class^=tag]').on('click', dothing);

How to dynamically set bootstrap-datepicker's date value?

Better to use :

$("#datepicker").datepicker("setDate", new Date); 

instead of

$("#datepicker").datepicker("update", new Date);

If you use update, event changeDate isn't triggered.

How to get a URL parameter in Express?

If you want to grab the query parameter value in the URL, follow below code pieces


If you want to grab the URL parameter using Express param function

Express param function to grab a specific parameter. This is considered middleware and will run before the route is called.

This can be used for validations or grabbing important information about item.

An example for this would be:

// parameter middleware that will run before the next routes
app.param('tagid', function(req, res, next, tagid) {

// check if the tagid exists
// do some validations
// add something to the tagid
var modified = tagid+ '123';

// save name to the request
req.tagid= modified;


// http://localhost:8080/api/tags/98
app.get('/api/tags/:tagid', function(req, res) {
// the tagid was found and is available in req.tagid
res.send('New tag id ' + req.tagid+ '!');

Mathematical functions in Swift

For the Swift way of doing things, you can try and make use of the tools available in the Swift Standard Library. These should work on any platform that is able to run Swift.

Instead of floor(), round() and the rest of the rounding routines you can use rounded(_:):

let x = 6.5

// Equivalent to the C 'round' function:
// Prints "7.0"

// Equivalent to the C 'trunc' function:
// Prints "6.0"

// Equivalent to the C 'ceil' function:
// Prints "7.0"

// Equivalent to the C 'floor' function:
// Prints "6.0"

These are currently available on Float and Double and it should be easy enough to convert to a CGFloat for example.

Instead of sqrt() there's the squareRoot() method on the FloatingPoint protocol. Again, both Float and Double conform to the FloatingPoint protocol:

let x = 4.0
let y = x.squareRoot()

For the trigonometric functions, the standard library can't help, so you're best off importing Darwin on the Apple platforms or Glibc on Linux. Fingers-crossed they'll be a neater way in the future.

#if os(OSX) || os(iOS)
import Darwin
#elseif os(Linux)
import Glibc

let x = 1.571
// Prints "~1.0"

Getting a list item by index

you can use index to access list elements

List<string> list1 = new List<string>();
list1[0] //for getting the first element of the list

Offline Speech Recognition In Android (JellyBean)

I would like to improve the guide that the answer sends to its users, with images. It is the sentence "For those that it doesn't, this is the ‘guide’ I supply them with." that I want to improve.

The user should click on the four buttons highlighted in blue in these images:

Go to your Android Application Settings, select Languages and input, edit Settings of Google Voice typing, select Download Offline speech recognition, select your languages in the ALL tab.

Then the user can select any desired languages. When the download is done, he should disconnect from network, and then click on the "microphone" button of the keyboard.

It worked for me (android 4.1.2), then language recognition worked out of the box, without rebooting. I can now dictates instructions to the shell of Terminal Emulator ! And it is twice faster offline than online, on a padfone 2 from ASUS.

These images are licensed under cc by-sa 3.0 with attribution required to ; you may hence add these images anywhere along with this attribution.

(This the standard policy of all images and texts at

XAMPP PORT 80 is Busy / EasyPHP error in Apache configuration file:

Just do one thing

open skype > tools > advance or advance settings Change port 80 to something else 7395

Restart your system then start Apache

WPF Data Binding and Validation Rules Best Practices

Also check this article. Supposedly Microsoft released their Enterprise Library (v4.0) from their patterns and practices where they cover the validation subject but god knows why they didn't included validation for WPF, so the blog post I'm directing you to, explains what the author did to adapt it. Hope this helps!

How to use doxygen to create UML class diagrams from C++ source

Enterprise Architect will build a UML diagram from imported source code.

Conflict with dependency ''. Resolved versions for app (23.1.0) and test app (23.0.1) differ

In my case, I added below code in dependencies of app level build.gradle

androidTestCompile('', {
    exclude group: '', module: 'support-annotations'

After that, I clean the project and rebuild.My problem solved.

Setting width of spreadsheet cell using PHPExcel

This worked for me:


be sure to add setAuzoSize(false), before the setWidth(); as Rolland mentioned

How can I create Min stl priority_queue?

One way would be to define a suitable comparator with which to operate on the ordinary priority queue, such that its priority gets reversed:

 #include <iostream>  
 #include <queue>  
 using namespace std;  

 struct compare  
   bool operator()(const int& l, const int& r)  
       return l > r;  

 int main()  
     priority_queue<int,vector<int>, compare > pq;  

     while ( !pq.empty() )  
         cout << << endl;  

Which would output 1, 3, 5, 8 respectively.

Some examples of using priority queues via STL and Sedgewick's implementations are given here.

In Tensorflow, get the names of all the Tensors in a graph

This worked for me:

for n in tf.get_default_graph().as_graph_def().node:

Navigation bar with UIImage for title

    let imageView = UIImageView(frame: (CGRect(x: 0, y: 0, width: 40, height: 
    imageView.contentMode = .scaleAspectFit
    let image = UIImage (named: "logo") // logo is your NPG asset 
    imageView.image = image
    self.navigationItem.titleView = imageView

Write and read a list from file

As long as your file has consistent formatting (i.e. line-breaks), this is easy with just basic file IO and string operations:

with open('my_file.txt', 'rU') as in_file:
    data ='\n')

That will store your data file as a list of items, one per line. To then put it into a file, you would do the opposite:

with open('new_file.txt', 'w') as out_file:
    out_file.write('\n'.join(data)) # This will create a string with all of the items in data separated by new-line characters

Hopefully that fits what you're looking for.

How to display a JSON representation and not [Object Object] on the screen

If you want to see what you you have inside an object in your web app, then use the json pipe in a component HTML template, for example:

<li *ngFor="let obj of myArray">{{obj | json}}</li>

Tested and valid using Angular 4.3.2.

Creating a file only if it doesn't exist in Node.js

What about using the a option?

According to the docs:

'a+' - Open file for reading and appending. The file is created if it does not exist.

It seems to work perfectly with createWriteStream

How to restart ADB manually from Android Studio

Open task manager and kill adb.exe, now adb will start normally

What is the best way to know if all the variables in a Class are null?

I think this is a solution that solves your problem easily: (return true if any of the parameters is not null)

  public boolean isUserEmpty(){ 
boolean isEmpty;
isEmpty =  isEmpty = Stream.of(id,
        .anyMatch(userParameter -> userParameter != null);

return isEmpty;}

Another solution to the same task is:(you can change it to if(isEmpty==0) checks if all the parameters are null.

public boolean isUserEmpty(){  
       long isEmpty;
            isEmpty = Stream.of(id,
                    .filter(userParameter -> userParameter != null).count();

            if (isEmpty > 0) {
                return true;
            } else {
                return false;

jQuery how to find an element based on a data-attribute value?

When searching with [data-x=...], watch out, it doesn't work with setter:

$('<b data-x="1">'  ).is('[data-x=1]') // this works
> true

$('<b>').data('x', 1).is('[data-x=1]') // this doesn't
> false

$('<b>').attr('data-x', 1).is('[data-x=1]') // this is the workaround
> true

You can use this instead:

$.fn.filterByData = function(prop, val) {
    return this.filter(
        function() { return $(this).data(prop)==val; }

$('<b>').data('x', 1).filterByData('x', 1).length
> 1

What Makes a Method Thread-safe? What are the rules?

There is no hard and fast rule.

Here are some rules to make code thread safe in .NET and why these are not good rules:

  1. Function and all functions it calls must be pure (no side effects) and use local variables. Although this will make your code thread-safe, there is also very little amount of interesting things you can do with this restriction in .NET.
  2. Every function that operates on a common object must lock on a common thing. All locks must be done in same order. This will make the code thread safe, but it will be incredibly slow, and you might as well not use multiple threads.
  3. ...

There is no rule that makes the code thread safe, the only thing you can do is make sure that your code will work no matter how many times is it being actively executed, each thread can be interrupted at any point, with each thread being in its own state/location, and this for each function (static or otherwise) that is accessing common objects.

memcpy() vs memmove()

The code given in the links for memcpy seems to confuse me a bit, as it does not give the same output when I implemented it using the below example.

#include <memory.h>
#include <string.h>
#include <stdio.h>

char str1[11] = "abcdefghij";

void *memcpyCustom(void *dest, const void *src, size_t n)
    char *dp = (char *)dest;
    const char *sp = (char *)src;
    while (n--)
        *dp++ = *sp++;
    return dest;

void *memmoveCustom(void *dest, const void *src, size_t n)
    unsigned char *pd = (unsigned char *)dest;
    const unsigned char *ps = (unsigned char *)src;
    if ( ps < pd )
        for (pd += n, ps += n; n--;)
            *--pd = *--ps;
            *pd++ = *ps++;
    return dest;

int main( void )
    printf( "The string: %s\n", str1 );
    memcpy( str1 + 1, str1, 9 );
    printf( "Actual memcpy output: %s\n", str1 );

    strcpy_s( str1, sizeof(str1), "abcdefghij" );   // reset string

    memcpyCustom( str1 + 1, str1, 9 );
    printf( "Implemented memcpy output: %s\n", str1 );

    strcpy_s( str1, sizeof(str1), "abcdefghij" );   // reset string

    memmoveCustom( str1 + 1, str1, 9 );
    printf( "Implemented memmove output: %s\n", str1 );

Output :

The string: abcdefghij
Actual memcpy output: aabcdefghi
Implemented memcpy output: aaaaaaaaaa
Implemented memmove output: aabcdefghi

But you can now understand why memmove will take care of overlapping issue.

How to handle checkboxes in ASP.NET MVC forms?

HtmlHelper adds an hidden input to notify the controller about Unchecked status. So to have the correct checked status:

bool bChecked = form[key].Contains("true");

Clone only one branch

I have done with below single git command:

git clone [url] -b [branch-name] --single-branch

How can I change the image displayed in a UIImageView programmatically?

This question already had a lot of answers. Unfortunately none worked for me. So for the sake of completenes I add what helped me:

I had multiple images with the same name - so I ordered them in sub folders. And I had the full path to the image file I wanted to show. With a full path imageNamed: (as used in all solutions above) did not work and was the wrong method.

Instead I now use imageWithContentsOfFile: like so:

self.myUIImage.image = [UIImage imageWithContentsOfFile:_currentWord.imageFileName];

Don't know, if anyone reads that far?

If so and this one helped you: please vote up. ;-)

Simulator or Emulator? What is the difference?

Both are models of an object that you have some means of controlling inputs to and observing outputs from.

The key difference is that:

  • With an emulator, you want the output exactly match what the object you are emulating would produce.
  • With a simulator, you want certain properties of your output to be similar to what the object would produce.

Let me give an example -- suppose you want to do some system testing to see how adding a new sensor (like a thermometer) to a system would affect the system. You know that the thermometer sends a message 8 time a second containing its measurement.

Simulation -- if you do not have the thermometer yet, but you want to test that this message rate will not overload you system, you can simulate the sensor by attaching a unit that sends a random number 8 times a second. You can run any test that does not rely on the actual value the sensor sends.

Emulation -- suppose you have a very expensive thermometer that measures to 0.001 C, and you want to see if you can get by with a cheaper thermometer that only measures to the nearest 0.5 C. You can emulate the cheaper thermometer using an expensive thermometer and then rounding the reading to the nearest 0.5 C and running tests that rely on the temperature values.

Note that simulations can also be used for forecasting or predicting behavior. Finite element analysis simulations are used in many applications, including weather prediction and virtual wind tunnels.

The definitions of the terms:

  • emulation -- surpass or exactly match
  • simulate -- imitate in appearance or character

SyntaxError: Unexpected Identifier in Chrome's Javascript console

The comma got eaten by the quotes!

This part:

("username," visitorName);

Should be this:

("username", visitorName);

Aside: For pasting code into the console, you can paste them in one line at a time to help you pinpoint where things went wrong ;-)

What does it mean to "program to an interface"?

program to an interface is a term from the GOF book. i would not directly say it has to do with java interface but rather real interfaces. to achieve clean layer separation, you need to create some separation between systems for example: Let's say you had a concrete database you want to use, you would never "program to the database" , instead you would "program to the storage interface". Likewise you would never "program to a Web Service" but rather you would program to a "client interface". this is so you can easily swap things out.

i find these rules help me:

1. we use a java interface when we have multiple types of an object. if i just have single object, i dont see the point. if there are at least two concrete implementations of some idea, then i would use a java interface.

2. if as i stated above, you want to bring decoupling from an external system (storage system) to your own system (local DB) then also use a interface.

notice how there are two ways to consider when to use them. hope this helps.

What is the command to exit a Console application in C#?

You can use Environment.Exit(0); and Application.Exit

Environment.Exit(0) is cleaner.

Making button go full-width?


<div class="btn-group btn-group-justified">

but it only works for <a> elements and not <button> elements.


Dart/Flutter : Converting timestamp

if anyone come here to convert firebase Timestamp here this will help

Timestamp time;

How to update a single pod without touching other dependencies

This is a bit of an outlier and not likely to be what the OP was dealing with, but pod update <podname> will not work in all cases if you are using a local pod on your computer.

In this situation, the only thing that will trigger pod update to work is if there is a change in the podspec file. However, making a change will also allow for pod install to work as well.

In this situation, you can just modify something minor such as the description or summary by one letter, and then you can run the install or update command successfully.

Setting the JVM via the command line on Windows

yes I often need to have 3 or more JVM's installed. For example, I've noticed that sometimes the JRE is slightly different to the JDK version of the JRE.

My go to solution on Windows for a bit of 'packaging' is something like this:

@echo off
@rem  _________________________
@set  JAVA_HOME=b:\lang\java\jdk\v1.6\u45\x64\jre
@set  JAVA_EXE=%JAVA_HOME%\bin\java
@set  VER=test
@set  WRK=%~d0%~p0%VER%
@pushd %WRK%
@echo  %JAVA_EXE%  -jar %WRK%\openmrs-standalone.jar
       %JAVA_EXE%  -jar %WRK%\openmrs-standalone.jar 
@rem  _________________________
@exit /b

I think it is straightforward. The main thing is the setlocal and endlocal give your app a "personal environment" for what ever it does -- even if there's other programs to run.

How can I make an image transparent on Android?


ImageView image = (ImageView) findViewById(;
image.setAlpha(150); // Value: [0-255]. Where 0 is fully transparent
                     // and 255 is fully opaque. Set the value according
                     // to your choice, and you can also use seekbar to
                     // maintain the transparency.

Best way to find os name and version in Unix/Linux platform

this command gives you a description of your operating system

cat /etc/os-release

Disallow Twitter Bootstrap modal window from closing

Well, this is another solution that some of you guys might be looking for (as I was..)

My problem was similar, the modal box was closing while the iframe I had inside was loading, so I had to disable the modal dismiss until the Iframe finishes loading, then re-enable.

The solutions presented here were not working 100%.

My solution was this:

showLocationModal = function(loc){

    var is_loading = true;

    if(is_loading === true) {

        is_loading  = false;
        var $modal   = $('#locationModal');


        // prevent Modal to close before the iframe is loaded
        $modal.on("hide", function (e) {
            if(is_loading !== true) {
                return false

        // populate Modal
        $modal.find('.modal-body iframe').hide().attr('src',{

            is_loading = true;

So I temporarily prevent the Modal from closing with:

$modal.on("hide", function (e) {
    if(is_loading !== true) {
        return false

But ith the var is_loading that will re enable closing after the Iframe has loaded.

HashSet vs. List performance

It depends. If the exact answer really matters, do some profiling and find out. If you're sure you'll never have more than a certain number of elements in the set, go with a List. If the number is unbounded, use a HashSet.

How to get full width in body element

If its in a landscape then you will be needing more width and less height! That's just what all websites have.

Lets go with a basic first then the rest!

The basic CSS:

By CSS you can do this,

#body {
width: 100%;
height: 100%;

Here you are using a div with id body, as:

  <div id="body>
    all the text would go here!

Then you can have a web page with 100% height and width.

What if he tries to resize the window?

The issues pops up, what if he tries to resize the window? Then all the elements inside #body would try to mess up the UI. For that you can write this:

#body {
height: 100%;
width: 100%;

And just add min-height max-height min-width and max-width.

This way, the page element would stay at the place they were at the page load.

Using JavaScript:

Using JavaScript, you can control the UI, use jQuery as:

$('#body').css('min-height', '100%');

And all other remaining CSS properties, and JS will take care of the User Interface when the user is trying to resize the window.

How to not add scroll to the web page:

If you are not trying to add a scroll, then you can use this JS

$('#body').css('min-height', screen.height); // or anyother like window.height

This way, the document will get a new height whenever the user would load the page.

Second option is better, because when users would have different screen resolutions they would want a CSS or Style sheet created for their own screen. Not for others!

Tip: So try using JS to find current Screen size and edit the page! :)

Windows batch file file download from a URL

use ftp:

(ftp **-a)
cd *directory*
get *filename.doc*

Change everything in asterisks to fit your situation.

Javascript to Select Multiple options

This type of thing should be done server-side, so as to limit the amount of resources used on the client for such trivial tasks. That being said, if you were to do it on the front-end, I would encourage you to consider using something like underscore.js to keep the code clean and concise:

var values = ["Red", "Green"],
    colors = document.getElementById("colors");

_.each(colors.options, function (option) {
    option.selected = ~_.indexOf(values, option.text);

If you're using jQuery, it could be even more terse:

var values = ["Red", "Green"];

$("#colors option").prop("selected", function () {
    return ~$.inArray(this.text, values);

If you were to do this without a tool like underscore.js or jQuery, you would have a bit more to write, and may find it to be a bit more complicated:

var color, i, j,
    values = ["Red", "Green"],
    options = document.getElementById("colors").options;

for ( i = 0; i < values.length; i++ ) {
    for ( j = 0, color = values[i]; j < options.length; j++ ) {
        options[j].selected = options[j].selected || color === options[j].text;

Most efficient way to increment a Map value in Java

Memory rotation may be an issue here, since every boxing of an int larger than or equal to 128 causes an object allocation (see Integer.valueOf(int)). Although the garbage collector very efficiently deals with short-lived objects, performance will suffer to some degree.

If you know that the number of increments made will largely outnumber the number of keys (=words in this case), consider using an int holder instead. Phax already presented code for this. Here it is again, with two changes (holder class made static and initial value set to 1):

static class MutableInt {
  int value = 1;
  void inc() { ++value; }
  int get() { return value; }
Map<String,MutableInt> map = new HashMap<String,MutableInt>();
MutableInt value = map.get(key);
if (value == null) {
  value = new MutableInt();
  map.put(key, value);
} else {;

If you need extreme performance, look for a Map implementation which is directly tailored towards primitive value types. jrudolph mentioned GNU Trove.

By the way, a good search term for this subject is "histogram".

How to break out of a loop in Bash?

It's not that different in bash.

while : ; do
  if [ "$workdone" -ne 0 ]; then

: is the no-op command; its exit status is always 0, so the loop runs until workdone is given a non-zero value.

There are many ways you could set and test the value of workdone in order to exit the loop; the one I show above should work in any POSIX-compatible shell.

Explain the "setUp" and "tearDown" Python methods used in test cases

In general you add all prerequisite steps to setUp and all clean-up steps to tearDown.

You can read more with examples here.

When a setUp() method is defined, the test runner will run that method prior to each test. Likewise, if a tearDown() method is defined, the test runner will invoke that method after each test.

For example you have a test that requires items to exist, or certain state - so you put these actions(creating object instances, initializing db, preparing rules and so on) into the setUp.

Also as you know each test should stop in the place where it was started - this means that we have to restore app state to it's initial state - e.g close files, connections, removing newly created items, calling transactions callback and so on - all these steps are to be included into the tearDown.

So the idea is that test itself should contain only actions that to be performed on the test object to get the result, while setUp and tearDown are the methods to help you to leave your test code clean and flexible.

You can create a setUp and tearDown for a bunch of tests and define them in a parent class - so it would be easy for you to support such tests and update common preparations and clean ups.

If you are looking for an easy example please use the following link with example

Simple calculations for working with lat/lon and km distance?

Thanks Jim Lewis for his great answer and I would like to illustrate this solution by my function in Swift:

func getRandomLocation(forLocation location: CLLocation, withOffsetKM offset: Double) -> CLLocation {
        let latDistance = (Double(arc4random()) / Double(UInt32.max)) * offset * 2.0 - offset
        let longDistanceMax = sqrt(offset * offset - latDistance * latDistance)
        let longDistance = (Double(arc4random()) / Double(UInt32.max)) * longDistanceMax * 2.0 - longDistanceMax

        let lat: CLLocationDegrees = location.coordinate.latitude + latDistance / 110.574
        let lng: CLLocationDegrees = location.coordinate.longitude + longDistance / (111.320 * cos(lat / .pi / 180))
        return CLLocation(latitude: lat, longitude: lng)

In this function to convert distance I use following formulas:

latDistance / 110.574
longDistance / (111.320 * cos(lat / .pi / 180))

What does character set and collation mean exactly?

A character set is a subset of all written glyphs. A character encoding specifies how those characters are mapped to numeric values. Some character encodings, like UTF-8 and UTF-16, can encode any character in the Universal Character Set. Others, like US-ASCII or ISO-8859-1 can only encode a small subset, since they use 7 and 8 bits per character, respectively. Because many standards specify both a character set and a character encoding, the term "character set" is often substituted freely for "character encoding".

A collation comprises rules that specify how characters can be compared for sorting. Collations rules can be locale-specific: the proper order of two characters varies from language to language.

Choosing a character set and collation comes down to whether your application is internationalized or not. If not, what locale are you targeting?

In order to choose what character set you want to support, you have to consider your application. If you are storing user-supplied input, it might be hard to foresee all the locales in which your software will eventually be used. To support them all, it might be best to support the UCS (Unicode) from the start. However, there is a cost to this; many western European characters will now require two bytes of storage per character instead of one.

Choosing the right collation can help performance if your database uses the collation to create an index, and later uses that index to provide sorted results. However, since collation rules are often locale-specific, that index will be worthless if you need to sort results according to the rules of another locale.

Why can't I define a default constructor for a struct in .NET?

Shorter explanation:

In C++, struct and class were just two sides of the same coin. The only real difference is that one was public by default and the other was private.

In .NET, there is a much greater difference between a struct and a class. The main thing is that struct provides value-type semantics, while class provides reference-type semantics. When you start thinking about the implications of this change, other changes start to make more sense as well, including the constructor behavior you describe.

Send file via cURL from form POST in PHP

cURL file object in procedural method:

$file = curl_file_create('full path/filename','extension','filename');

cURL file object in Oop method:

$file = new CURLFile('full path/filename','extension','filename');

$post= array('file' => $file);

$curl = curl_init();  
//curl_setopt ... 
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
$response = curl_exec($curl);

Windows batch script to move files

You can try this:

:backup move C:\FilesToBeBackedUp\*.* E:\BackupPlace\ timeout 36000 goto backup

If that doesn't work try to replace "timeout" with sleep. Ik this post is over a year old, just helping anyone with the same problem.