Programs & Examples On #Fromkeys

How do I initialize a dictionary of empty lists in Python?

Use defaultdict instead:

from collections import defaultdict
data = defaultdict(list)
data[1].append('hello')

This way you don't have to initialize all the keys you want to use to lists beforehand.

What is happening in your example is that you use one (mutable) list:

alist = [1]
data = dict.fromkeys(range(2), alist)
alist.append(2)
print data

would output {0: [1, 2], 1: [1, 2]}.

Where's my JSON data in my incoming Django request?

I had the same problem. I had been posting a complex JSON response, and I couldn't read my data using the request.POST dictionary.

My JSON POST data was:

//JavaScript code:
//Requires json2.js and jQuery.
var response = {data:[{"a":1, "b":2},{"a":2, "b":2}]}
json_response = JSON.stringify(response); // proper serialization method, read 
                                          // http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/
$.post('url',json_response);

In this case you need to use method provided by aurealus. Read the request.body and deserialize it with the json stdlib.

#Django code:
import json
def save_data(request):
  if request.method == 'POST':
    json_data = json.loads(request.body) # request.raw_post_data w/ Django < 1.4
    try:
      data = json_data['data']
    except KeyError:
      HttpResponseServerError("Malformed data!")
    HttpResponse("Got json data")

Eclipse will not open due to environment variables

Eclipse and Java JDK (or JRE) must match regarding the BIT Version

For example:

32 Bit Eclipse won't work with 64 Bit Java!

32 Bit Eclipse needs 32 Bit Java!

Passing string to a function in C - with or without pointers?

Assuming that you meant to write

char *functionname(char *string[256])

Here you are declaring a function that takes an array of 256 pointers to char as argument and returns a pointer to char. Here, on the other hand,

char functionname(char string[256])

You are declaring a function that takes an array of 256 chars as argument and returns a char.

In other words the first function takes an array of strings and returns a string, while the second takes a string and returns a character.

Spark read file from S3 using sc.textFile ("s3n://...)

You probably have to use s3a:/ scheme instead of s3:/ or s3n:/ However, it is not working out of the box (for me) for the spark shell. I see the following stacktrace:

java.lang.RuntimeException: java.lang.ClassNotFoundException: Class org.apache.hadoop.fs.s3a.S3AFileSystem not found
        at org.apache.hadoop.conf.Configuration.getClass(Configuration.java:2074)
        at org.apache.hadoop.fs.FileSystem.getFileSystemClass(FileSystem.java:2578)
        at org.apache.hadoop.fs.FileSystem.createFileSystem(FileSystem.java:2591)
        at org.apache.hadoop.fs.FileSystem.access$200(FileSystem.java:91)
        at org.apache.hadoop.fs.FileSystem$Cache.getInternal(FileSystem.java:2630)
        at org.apache.hadoop.fs.FileSystem$Cache.get(FileSystem.java:2612)
        at org.apache.hadoop.fs.FileSystem.get(FileSystem.java:370)
        at org.apache.hadoop.fs.Path.getFileSystem(Path.java:296)
        at org.apache.hadoop.mapred.FileInputFormat.singleThreadedListStatus(FileInputFormat.java:256)
        at org.apache.hadoop.mapred.FileInputFormat.listStatus(FileInputFormat.java:228)
        at org.apache.hadoop.mapred.FileInputFormat.getSplits(FileInputFormat.java:313)
        at org.apache.spark.rdd.HadoopRDD.getPartitions(HadoopRDD.scala:207)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:219)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:217)
        at scala.Option.getOrElse(Option.scala:120)
        at org.apache.spark.rdd.RDD.partitions(RDD.scala:217)
        at org.apache.spark.rdd.MapPartitionsRDD.getPartitions(MapPartitionsRDD.scala:32)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:219)
        at org.apache.spark.rdd.RDD$$anonfun$partitions$2.apply(RDD.scala:217)
        at scala.Option.getOrElse(Option.scala:120)
        at org.apache.spark.rdd.RDD.partitions(RDD.scala:217)
        at org.apache.spark.SparkContext.runJob(SparkContext.scala:1781)
        at org.apache.spark.rdd.RDD.count(RDD.scala:1099)
        at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:24)
        at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:29)
        at $iwC$$iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:31)
        at $iwC$$iwC$$iwC$$iwC$$iwC.<init>(<console>:33)
        at $iwC$$iwC$$iwC$$iwC.<init>(<console>:35)
        at $iwC$$iwC$$iwC.<init>(<console>:37)
        at $iwC$$iwC.<init>(<console>:39)
        at $iwC.<init>(<console>:41)
        at <init>(<console>:43)
        at .<init>(<console>:47)
        at .<clinit>(<console>)
        at .<init>(<console>:7)
        at .<clinit>(<console>)
        at $print(<console>)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at org.apache.spark.repl.SparkIMain$ReadEvalPrint.call(SparkIMain.scala:1065)
        at org.apache.spark.repl.SparkIMain$Request.loadAndRun(SparkIMain.scala:1338)
        at org.apache.spark.repl.SparkIMain.loadAndRunReq$1(SparkIMain.scala:840)
        at org.apache.spark.repl.SparkIMain.interpret(SparkIMain.scala:871)
        at org.apache.spark.repl.SparkIMain.interpret(SparkIMain.scala:819)
        at org.apache.spark.repl.SparkILoop.reallyInterpret$1(SparkILoop.scala:857)
        at org.apache.spark.repl.SparkILoop.interpretStartingWith(SparkILoop.scala:902)
        at org.apache.spark.repl.SparkILoop.command(SparkILoop.scala:814)
        at org.apache.spark.repl.SparkILoop.processLine$1(SparkILoop.scala:657)
        at org.apache.spark.repl.SparkILoop.innerLoop$1(SparkILoop.scala:665)
        at org.apache.spark.repl.SparkILoop.org$apache$spark$repl$SparkILoop$$loop(SparkILoop.scala:670)
        at org.apache.spark.repl.SparkILoop$$anonfun$org$apache$spark$repl$SparkILoop$$process$1.apply$mcZ$sp(SparkILoop.scala:997)
        at org.apache.spark.repl.SparkILoop$$anonfun$org$apache$spark$repl$SparkILoop$$process$1.apply(SparkILoop.scala:945)
        at org.apache.spark.repl.SparkILoop$$anonfun$org$apache$spark$repl$SparkILoop$$process$1.apply(SparkILoop.scala:945)
        at scala.tools.nsc.util.ScalaClassLoader$.savingContextLoader(ScalaClassLoader.scala:135)
        at org.apache.spark.repl.SparkILoop.org$apache$spark$repl$SparkILoop$$process(SparkILoop.scala:945)
        at org.apache.spark.repl.SparkILoop.process(SparkILoop.scala:1059)
        at org.apache.spark.repl.Main$.main(Main.scala:31)
        at org.apache.spark.repl.Main.main(Main.scala)
        at sun.reflect.NativeMethodAccessorImpl.invoke0(Native Method)
        at sun.reflect.NativeMethodAccessorImpl.invoke(NativeMethodAccessorImpl.java:62)
        at sun.reflect.DelegatingMethodAccessorImpl.invoke(DelegatingMethodAccessorImpl.java:43)
        at java.lang.reflect.Method.invoke(Method.java:497)
        at org.apache.spark.deploy.SparkSubmit$.org$apache$spark$deploy$SparkSubmit$$runMain(SparkSubmit.scala:665)
        at org.apache.spark.deploy.SparkSubmit$.doRunMain$1(SparkSubmit.scala:170)
        at org.apache.spark.deploy.SparkSubmit$.submit(SparkSubmit.scala:193)
        at org.apache.spark.deploy.SparkSubmit$.main(SparkSubmit.scala:112)
        at org.apache.spark.deploy.SparkSubmit.main(SparkSubmit.scala)
Caused by: java.lang.ClassNotFoundException: Class org.apache.hadoop.fs.s3a.S3AFileSystem not found
        at org.apache.hadoop.conf.Configuration.getClassByName(Configuration.java:1980)
        at org.apache.hadoop.conf.Configuration.getClass(Configuration.java:2072)
        ... 68 more

What I think - you have to manually add the hadoop-aws dependency manually http://search.maven.org/#artifactdetails|org.apache.hadoop|hadoop-aws|2.7.1|jar But I have no idea how to add it to spark-shell properly.

How to display PDF file in HTML?

Implementation of a PDF file in your HTML web-page is very easy.

<embed src="file_name.pdf" width="800px" height="2100px" />

Make sure to change the width and height for your needs. Good luck!

Sqlite primary key on multiple columns

According to the documentation, it's

CREATE TABLE something (
  column1, 
  column2, 
  column3, 
  PRIMARY KEY (column1, column2)
);

SimpleDateFormat returns 24-hour date: how to get 12-hour date?

SimpleDateFormat dateFormat = new SimpleDateFormat("dd/mm/yyyy hh:mm:ss a");

use hh in place of HH

auto create database in Entity Framework Core

If you haven't created migrations, there are 2 options

1.create the database and tables from application Main:

var context = services.GetRequiredService<YourRepository>();
context.Database.EnsureCreated();

2.create the tables if the database already exists:

var context = services.GetRequiredService<YourRepository>();
context.Database.EnsureCreated();
RelationalDatabaseCreator databaseCreator =
(RelationalDatabaseCreator)context.Database.GetService<IDatabaseCreator>();
databaseCreator.CreateTables();

Thanks to Bubi's answer

SQL DROP TABLE foreign key constraint

Here's another way to do delete all the constraints followed by the tables themselves, using a concatenation trick involving FOR XML PATH('') which allows merging multiple input rows into a single output row. Should work on anything SQL 2005 & later.

I've left the EXECUTE commands commented out for safety.

DECLARE @SQL NVARCHAR(max)
;WITH fkeys AS (
    SELECT quotename(s.name) + '.' + quotename(o.name) tablename, quotename(fk.name) constraintname 
    FROM sys.foreign_keys fk
    JOIN sys.objects o ON fk.parent_object_id = o.object_id
    JOIN sys.schemas s ON o.schema_id = s.schema_id
)
SELECT @SQL = STUFF((SELECT '; ALTER TABLE ' + tablename + ' DROP CONSTRAINT ' + constraintname
FROM fkeys
FOR XML PATH('')),1,2,'')

-- EXECUTE(@sql)

SELECT @SQL = STUFF((SELECT '; DROP TABLE ' + quotename(TABLE_SCHEMA) + '.' + quotename(TABLE_NAME) 
FROM INFORMATION_SCHEMA.TABLES 
FOR XML PATH('')),1,2,'')

-- EXECUTE(@sql)

Eclipse 3.5 Unable to install plugins

i fought with eclipse 3.5.0 (galileo) for days, i had to use this version because I am doing blackberry development and eclipse comes bundle with blackberry specifics so i need to use the package they bundled, which was not 3.5.0 (not the 3.5.1) , BUT SirFabel saved the day, thanks to all who contributed to this post

I used 3.5.0 and did "Set the following system property in you eclipse.ini file: -Dorg.eclipse.ecf.provider.filetransfer.excludeContributors=org.eclipse.ecf.provider.filetransfer.httpclient For more details on this: wiki.eclipse.org/… - Configure only the HTTP and HTTPS proxies. Not SOCKS!! "

and I am able to get through my companies proxy!!!!

get the value of DisplayName attribute

I have this generic utility method. I pass in a list of a given type (Assuming you have a supporting class) and it generates a datatable with the properties as column headers and the list items as data.

Just like in standard MVC, if you dont have DisplayName attribute defined, it will fall back to the property name so you only have to include DisplayName where it is different to the property name.

    public DataTable BuildDataTable<T>(IList<T> data)
    {
        //Get properties
        PropertyInfo[] Props = typeof(T).GetProperties(BindingFlags.Public | BindingFlags.Instance);
        //.Where(p => !p.GetGetMethod().IsVirtual && !p.GetGetMethod().IsFinal).ToArray(); //Hides virtual properties

        //Get column headers
        bool isDisplayNameAttributeDefined = false;
        string[] headers = new string[Props.Length];
        int colCount = 0;
        foreach (PropertyInfo prop in Props)
        {
            isDisplayNameAttributeDefined = Attribute.IsDefined(prop, typeof(DisplayNameAttribute));

            if (isDisplayNameAttributeDefined)
            {
                DisplayNameAttribute dna = (DisplayNameAttribute)Attribute.GetCustomAttribute(prop, typeof(DisplayNameAttribute));
                if (dna != null)
                    headers[colCount] = dna.DisplayName;
            }
            else
                headers[colCount] = prop.Name;

            colCount++;
            isDisplayNameAttributeDefined = false;
        }

        DataTable dataTable = new DataTable(typeof(T).Name);

        //Add column headers to datatable
        foreach (var header in headers)
            dataTable.Columns.Add(header);

        dataTable.Rows.Add(headers);

        //Add datalist to datatable
        foreach (T item in data)
        {
            object[] values = new object[Props.Length];
            for (int col = 0; col < Props.Length; col++)
                values[col] = Props[col].GetValue(item, null);

            dataTable.Rows.Add(values);
        }

        return dataTable;
    }

If there's a more efficient / safer way of doing this, I'd appreicate any feedback. The commented //Where clause will filter out virtual properties. Useful if you are using model classes directly as EF puts in "Navigation" properties as virtual. However it will also filter out any of your own virtual properties if you choose to extend such classes. For this reason, I prefer to make a ViewModel and decorate it with only the needed properties and display name attributes as required, then make a list of them.

Hope this helps.

How to read appSettings section in the web.config file?

Since you're accessing a web.config you should probably use

using System.Web.Configuration;

WebConfigurationManager.AppSettings["configFile"]

Bootstrap change carousel height

This worked for me.

.carousel-item {
  height: 500px;
}

.item, img{
    position: absolute;
    object-fit:cover;
    height: 100% !important;
    width:  100% !important;
    /*min-height: 500px;*/
}

How to push a new folder (containing other folders and files) to an existing git repo?

You can directly go to Web IDE and upload your folder there.

Steps:

  1. Go to Web IDE(Mostly located below the clone option).
  2. Create new directory at your path
  3. Upload your files and folders

In some cases you may not be able to directly upload entire folder containing folders, In such cases, you will have to create directory structure yourself.

Update UI from Thread in Android

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

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

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

The 4 steps

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

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

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

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

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

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

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

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

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

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

        return adapter1;
    }

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

How to make a JFrame Modal in Swing java

You can create a class that is passed a reference to the parent JFrame and holds it in a JFrame variable. Then you can lock the frame that created your new frame.

parentFrame.disable();

//Some actions

parentFrame.enable();

How to setup Main class in manifest file in jar produced by NetBeans project

Adding manifest.file=manifest.mf into project.properties and creating manifest.mf file in the project directory works fine in NB 6.9 and should work also in NB 6.8.

How to find the difference in days between two dates?

Here's the MAC OS X version for your convenience.

$ A="2002-20-10"; B="2003-22-11";
$ echo $(((`date -jf %Y-%d-%m $B +%s` - `date -jf %Y-%d-%m $A +%s`)/86400))

nJoy!

What is the maximum length of a URL in different browsers?

The HTTP 1.1 specification says:

URIs in HTTP can be represented in absolute form or relative to some
known base URI [11], depending upon the context of their use. The two
forms are differentiated by the fact that absolute URIs always begin
with a scheme name followed by a colon. For definitive information on
URL syntax and semantics, see "Uniform Resource Identifiers (URI): Generic Syntax and Semantics," RFC 2396 [42] (which replaces RFCs 1738 [4] and RFC 1808 [11]). This specification adopts the definitions of "URI-reference", "absoluteURI", "relativeURI", "port",
"host","abs_path", "rel_path", and "authority" from that
specification.

The HTTP protocol does not place any a priori limit on the length of
a URI. Servers MUST be able to handle the URI of any resource they serve, and SHOULD be able to handle URIs of unbounded length if they provide GET-based forms that could generate such URIs.*
A server SHOULD return 414 (Request-URI Too Long) status if a URI is longer than the server can handle (see section 10.4.15).

Note: Servers ought to be cautious about depending on URI lengths above 255 bytes, because some older client or proxy implementations might not properly support these lengths.

As mentioned by @Brian, the HTTP clients (e.g. browsers) may have their own limits, and HTTP servers will have different limits.

Adding elements to an xml file in C#

If you want to add an attribute, and not an element, you have to say so:

XElement root = new XElement("Snippet");
root.Add(new XAttribute("name", "name goes here"));
root.Add(new XElement("SnippetCode", "SnippetCode"));

The code above produces the following XML element:

<Snippet name="name goes here">
  <SnippetCode>SnippetCode</SnippetCode>
</Snippet> 

Responsive image map

Working for me (remember to change 3 things in code):

  • previousWidth (original size of image)

  • map_ID (id of your image map)

  • img_ID (id of your image)

HTML:

<div style="width:100%;">
    <img id="img_ID" src="http://www.gravatar.com/avatar/0865e7bad648eab23c7d4a843144de48?s=128&d=identicon&r=PG" usemap="#map" border="0" width="100%" alt="" />
</div>
<map id="map_ID" name="map">
<area shape="poly" coords="48,10,80,10,65,42" href="javascript:;" alt="Bandcamp" title="Bandcamp" />
<area shape="poly" coords="30,50,62,50,46,82" href="javascript:;" alt="Facebook" title="Facebook" />
<area shape="poly" coords="66,50,98,50,82,82" href="javascript:;" alt="Soundcloud" title="Soundcloud" />
</map>

Javascript:

window.onload = function () {
    var ImageMap = function (map, img) {
            var n,
                areas = map.getElementsByTagName('area'),
                len = areas.length,
                coords = [],
                previousWidth = 128;
            for (n = 0; n < len; n++) {
                coords[n] = areas[n].coords.split(',');
            }
            this.resize = function () {
                var n, m, clen,
                    x = img.offsetWidth / previousWidth;
                for (n = 0; n < len; n++) {
                    clen = coords[n].length;
                    for (m = 0; m < clen; m++) {
                        coords[n][m] *= x;
                    }
                    areas[n].coords = coords[n].join(',');
                }
                previousWidth = img.offsetWidth;
                return true;
            };
            window.onresize = this.resize;
        },
        imageMap = new ImageMap(document.getElementById('map_ID'), document.getElementById('img_ID'));
    imageMap.resize();
    return;
}

JSFiddle: http://jsfiddle.net/p7EyT/154/

I want to get the type of a variable at runtime

If by the type of a variable you mean the runtime class of the object that the variable points to, then you can get this through the class reference that all objects have.

val name = "sam";
name: java.lang.String = sam
name.getClass
res0: java.lang.Class[_] = class java.lang.String

If you however mean the type that the variable was declared as, then you cannot get that. Eg, if you say

val name: Object = "sam"

then you will still get a String back from the above code.

Where is Maven's settings.xml located on Mac OS?

After I have downloaded the binary from apache site I, have placed the extracted folder in /Library
So now the location of the settings.xml file is in:

/Library/apache_maven_3.6.3/conf

Python: printing a file to stdout

you can also try this

print ''.join(file('example.txt'))

React-router v4 this.props.history.push(...) not working

Let's consider this scenario. You have App.jsx as the root file for you ReactJS SPA. In it your render() looks similar to this:

<Switch>
    <Route path="/comp" component={MyComponent} />
</Switch>

then, you should be able to use this.props.history inside MyComponent without a problem. Let's say you are rendering MySecondComponent inside MyComponent, in that case you need to call it in such manner:

<MySecondComponent {...props} />

which will pass the props from MyComponent down to MySecondComponent, thus making this.props.history available in MySecondComponent

Sort array by firstname (alphabetically) in Javascript

Shortest possible code with ES6!

users.sort((a, b) => a.firstname.localeCompare(b.firstname))

String.prototype.localeCompare() basic support is universal!

Detecting installed programs via registry

On 64-bit systems the x64 key is:

HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Windows\CurrentVersion\Uninstall

Most programs are listed there. Look at the keys: DisplayName DisplayVersion

Note that the last is not always set!

On 64-bit systems the x86 key (usually with more entries) is:

HKEY_LOCAL_MACHINE\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall

Show loading gif after clicking form submit using jQuery

Button inputs don't have a submit event. Try attaching the event handler to the form instead:

<script type="text/javascript">
     $('#login_form').submit(function() {
       $('#gif').show(); 
       return true;
     });
 </script>

How do I force a favicon refresh?

Also make sure you put the full image URL not just its relative path:

http://www.example.com/images/favicon.ico

And not:

images/favicon.ico

Better way to sort array in descending order

Yes, you can pass predicate to sort. That would be your reverse implementation.

How to print to the console in Android Studio?

Run your application in debug mode by clicking on

enter image description here

in the upper menu of Android Studio.

In the bottom status bar, click 5: Debug button, next to the 4: Run button.

Now you should select the Logcat console.

In search box, you can type the tag of your message, and your message should appear, like in the following picture (where the tag is CREATION):

enter image description here

Check this article for more information.

Reset Entity-Framework Migrations

Delete the Migrations Folder, Clean then Rebuild the project. This worked for me. Before Clean and Rebuild it was saying the Migration already exists since in its cached memory, it's not yet deleted.

Need to combine lots of files in a directory

Use the Windows 'copy' command.

C:\Users\dan>help copy
    Copies one or more files to another location.

    COPY [/D] [/V] [/N] [/Y | /-Y] [/Z] [/L] [/A | /B ] source [/A | /B]
         [+ source [/A | /B] [+ ...]] [destination [/A | /B]]

      source       Specifies the file or files to be copied.
      /A           Indicates an ASCII text file.
      /B           Indicates a binary file.
      /D           Allow the destination file to be created decrypted
      destination  Specifies the directory and/or filename for the new file(s).
      /V           Verifies that new files are written correctly.
      /N           Uses short filename, if available, when copying a file with 
                   a non-8dot3 name.
      /Y           Suppresses prompting to confirm you want to overwrite an
                   existing destination file.
      /-Y          Causes prompting to confirm you want to overwrite an
                   existing destination file.
      /Z           Copies networked files in restartable mode.
      /L           If the source is a symbolic link, copy the link to the 
                   target
                   instead of the actual file the source link points to.

    The switch /Y may be preset in the COPYCMD environment variable.
    This may be overridden with /-Y on the command line.  Default is
    to prompt on overwrites unless COPY command is being executed from
    within a batch script.

    **To append files, specify a single file for destination, but 
    multiple files for source (using wildcards or file1+file2+file3 
    format).**

So in your case:

copy *.txt destination.txt

Will concatenate all .txt files in alphabetical order into destination.txt

Thanks for asking, I learned something new!

Python Matplotlib figure title overlaps axes label when using twiny

Forget using plt.title and place the text directly with plt.text. An over-exaggerated example is given below:

import pylab as plt

fig = plt.figure(figsize=(5,10))

figure_title = "Normal title"
ax1  = plt.subplot(1,2,1)

plt.title(figure_title, fontsize = 20)
plt.plot([1,2,3],[1,4,9])

figure_title = "Raised title"
ax2  = plt.subplot(1,2,2)

plt.text(0.5, 1.08, figure_title,
         horizontalalignment='center',
         fontsize=20,
         transform = ax2.transAxes)
plt.plot([1,2,3],[1,4,9])

plt.show()

enter image description here

PHP - include a php file and also send query parameters

I was in the same situation and I needed to include a page by sending some parameters... But in reality what I wanted to do is to redirect the page... if is the case for you, the code is:

<?php
   header("Location: http://localhost/planner/layout.php?page=dashboard"); 
   exit();
?>

Run CRON job everyday at specific time

Cron utility is an effective way to schedule a routine background job at a specific time and/or day on an on-going basis.

Linux Crontab Format

MIN HOUR DOM MON DOW CMD

enter image description here

Example::Scheduling a Job For a Specific Time

The basic usage of cron is to execute a job in a specific time as shown below. This will execute the Full backup shell script (full-backup) on 10th June 08:30 AM.

Please note that the time field uses 24 hours format. So, for 8 AM use 8, and for 8 PM use 20.

30 08 10 06 * /home/yourname/full-backup
  • 30 – 30th Minute
  • 08 – 08 AM
  • 10 – 10th Day
  • 06 – 6th Month (June)
  • *– Every day of the week

In your case, for 2.30PM,

30 14 * * * YOURCMD
  1. 30 – 30th Minute
  2. 14 – 2PM
  3. *– Every day
  4. *– Every month
  5. *– Every day of the week

To know more about cron, visit this website.

How can I define fieldset border color?

If you don't want 3D border use:

border:#f00 1px solid;

Set order of columns in pandas dataframe

Just select the order yourself by typing in the column names. Note the double brackets:

frame = frame[['column I want first', 'column I want second'...etc.]]

Font Awesome 5 font-family issue

Requiring 900 weight is not a weirdness but a intentional restriction added by FontAwesome (since they share the same unicode but just different font-weight) so that you are not hacking your way into using the 'solid' and 'light' icons, most of which are available only in the paid 'Pro' version.

How to document a method with parameter(s)?

The mainstream is, as other answers here already pointed out, probably going with the Sphinx way so that you can use Sphinx to generate those fancy documents later.

That being said, I personally go with inline comment style occasionally.

def complex(  # Form a complex number
        real=0.0,  # the real part (default 0.0)
        imag=0.0  # the imaginary part (default 0.0)
        ):  # Returns a complex number.
    """Form a complex number.

    I may still use the mainstream docstring notation,
    if I foresee a need to use some other tools
    to generate an HTML online doc later
    """
    if imag == 0.0 and real == 0.0:
        return complex_zero
    other_code()

One more example here, with some tiny details documented inline:

def foo(  # Note that how I use the parenthesis rather than backslash "\"
          # to natually break the function definition into multiple lines.
        a_very_long_parameter_name,
            # The "inline" text does not really have to be at same line,
            # when your parameter name is very long.
            # Besides, you can use this way to have multiple lines doc too.
            # The one extra level indentation here natually matches the
            # original Python indentation style.
            #
            # This parameter represents blah blah
            # blah blah
            # blah blah
        param_b,  # Some description about parameter B.
            # Some more description about parameter B.
            # As you probably noticed, the vertical alignment of pound sign
            # is less a concern IMHO, as long as your docs are intuitively
            # readable.
        last_param,  # As a side note, you can use an optional comma for
                     # your last parameter, as you can do in multi-line list
                     # or dict declaration.
        ):  # So this ending parenthesis occupying its own line provides a
            # perfect chance to use inline doc to document the return value,
            # despite of its unhappy face appearance. :)
    pass

The benefits (as @mark-horvath already pointed out in another comment) are:

  • Most importantly, parameters and their doc always stay together, which brings the following benefits:
  • Less typing (no need to repeat variable name)
  • Easier maintenance upon changing/removing variable. There will never be some orphan parameter doc paragraph after you rename some parameter.
  • and easier to find missing comment.

Now, some may think this style looks "ugly". But I would say "ugly" is a subjective word. A more neutual way is to say, this style is not mainstream so it may look less familiar to you, thus less comfortable. Again, "comfortable" is also a subjective word. But the point is, all the benefits described above are objective. You can not achieve them if you follow the standard way.

Hopefully some day in the future, there will be a doc generator tool which can also consume such inline style. That will drive the adoption.

PS: This answer is derived from my own preference of using inline comments whenever I see fit. I use the same inline style to document a dictionary too.

Twitter bootstrap modal-backdrop doesn't disappear

Even I ran into a similar problem, I had the following two buttons

<button id="confirm-delete-btn" >Yes, Delete this note.</button>
<button id="confirm-delete-cancel" data-dismiss="modal">No</button>

I wanted to perform some ajax operation and on success of that ajax operation close the modal. So here is what I did.

$.ajax({
        url: '/ABC/Delete/' + self.model.get("Id")
            , type: 'DELETE'
            , success: function () {                    
                setTimeout(function () {
                    self.$("#confirm-delete-cancel").trigger("click");
                }, 1200);
            }
            , error: function () {}
        });

I triggered the click event of the 'No' button which had the data-dismiss="modal" property. And this worked :)

Extension mysqli is missing, phpmyadmin doesn't work

sudo apt-get install php5-mysql
sudo apt-get install php5-mysqlnd 

try both of alternatively it works for me

Git Clone: Just the files, please?

The git command that would be the closest from what you are looking for would by git archive.
See backing up project which uses git: it will include in an archive all files (including submodules if you are using the git-archive-all script)

You can then use that archive anywhere, giving you back only files, no .git directory.

git archive --remote=<repository URL> | tar -t

If you need folders and files just from the first level:

git archive --remote=<repository URL> | tar -t --exclude="*/*"

To list only first-level folders of a remote repo:

git archive --remote=<repository URL> | tar -t --exclude="*/*" | grep "/"

Note: that does not work for GitHub (not supported)

So you would need to clone (shallow to quicken the clone step), and then archive locally:

git clone --depth=1 [email protected]:xxx/yyy.git
cd yyy
git archive --format=tar aTag -o aTag.tar

Another option would be to do a shallow clone (as mentioned below), but locating the .git folder elsewhere.

git --git-dir=/path/to/another/folder.git clone --depth=1 /url/to/repo

The repo folder would include only the file, without .git.

Note: git --git-dir is an option of the command git, not git clone.


Update with Git 2.14.X/2.15 (Q4 2017): it will make sure to avoid adding empty folders.

"git archive", especially when used with pathspec, stored an empty directory in its output, even though Git itself never does so.
This has been fixed.

See commit 4318094 (12 Sep 2017) by René Scharfe (``).
Suggested-by: Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit 62b1cb7, 25 Sep 2017)

archive: don't add empty directories to archives

While git doesn't track empty directories, git archive can be tricked into putting some into archives.
While that is supported by the object database, it can't be represented in the index and thus it's unlikely to occur in the wild.

As empty directories are not supported by git, they should also not be written into archives.
If an empty directory is really needed then it can be tracked and archived by placing an empty .gitignore file in it.

get number of columns of a particular row in given excel using Java

There are two Things you can do

use

int noOfColumns = sh.getRow(0).getPhysicalNumberOfCells();

or

int noOfColumns = sh.getRow(0).getLastCellNum();

There is a fine difference between them

  1. Option 1 gives the no of columns which are actually filled with contents(If the 2nd column of 10 columns is not filled you will get 9)
  2. Option 2 just gives you the index of last column. Hence done 'getLastCellNum()'

Custom circle button

AngryTool for custom android button

You can make any kind of custom android button with this tool site... i make circle and square button with round corner with this toolsite.. Visit it may be i will help you

Java SecurityException: signer information does not match

In my case it was a package name conflict. Current project and signed referenced library had one package in common package.foo.utils. Just changed the current project error-prone package name to something else.

How to Publish Web with msbuild?

You must set your environments

  • < WebSite name>
  • < domain>

and reference my blog.(sorry post was Korean)

  • http://xyz37.blog.me/50124665657
  • http://blog.naver.com/PostSearchList.nhn?SearchText=webdeploy&blogId=xyz37&x=25&y=7

    @ECHO OFF
    :: http://stackoverflow.com/questions/5598668/valid-parameters-for-msdeploy-via-msbuild
    ::-DeployOnBuild -True
    :: -False
    :: 
    ::-DeployTarget -MsDeployPublish
    :: -Package
    :: 
    ::-Configuration -Name of a valid solution configuration
    :: 
    ::-CreatePackageOnPublish -True
    :: -False
    :: 
    ::-DeployIisAppPath -<Web Site Name>/<Folder>
    :: 
    ::-MsDeployServiceUrl -Location of MSDeploy installation you want to use
    :: 
    ::-MsDeployPublishMethod -WMSVC (Web Management Service)
    :: -RemoteAgent
    :: 
    ::-AllowUntrustedCertificate (used with self-signed SSL certificates) -True
    :: -False
    :: 
    ::-UserName
    ::-Password
    SETLOCAL
    
    IF EXIST "%SystemRoot%\Microsoft.NET\Framework\v2.0.50727" SET FXPath="%SystemRoot%\Microsoft.NET\Framework\v2.0.50727"
    IF EXIST "%SystemRoot%\Microsoft.NET\Framework\v3.5" SET FXPath="%SystemRoot%\Microsoft.NET\Framework\v3.5"
    IF EXIST "%SystemRoot%\Microsoft.NET\Framework\v4.0.30319" SET FXPath="%SystemRoot%\Microsoft.NET\Framework\v4.0.30319"
    
    SET targetFile=<web site fullPath ie. .\trunk\WebServer\WebServer.csproj
    SET configuration=Release
    SET msDeployServiceUrl=https://<domain>:8172/MsDeploy.axd
    SET msDeploySite="<WebSite name>"
    SET userName="WebDeploy"
    SET password=%USERNAME%
    SET platform=AnyCPU
    SET msbuild=%FXPath%\MSBuild.exe /MaxCpuCount:%NUMBER_OF_PROCESSORS% /clp:ShowCommandLine
    
    %MSBuild% %targetFile% /p:configuration=%configuration%;Platform=%platform% /p:DeployOnBuild=True /p:DeployTarget=MsDeployPublish /p:CreatePackageOnPublish=False /p:DeployIISAppPath=%msDeploySite% /p:MSDeployPublishMethod=WMSVC /p:MsDeployServiceUrl=%msDeployServiceUrl% /p:AllowUntrustedCertificate=True /p:UserName=%USERNAME% /p:Password=%password% /p:SkipExtraFilesOnServer=True /p:VisualStudioVersion=12.0
    
    IF NOT "%ERRORLEVEL%"=="0" PAUSE 
    ENDLOCAL
    

How to copy a file to a remote server in Python using SCP or SSH?

You can call the scp bash command (it copies files over SSH) with subprocess.run:

import subprocess
subprocess.run(["scp", FILE, "USER@SERVER:PATH"])
#e.g. subprocess.run(["scp", "foo.bar", "[email protected]:/path/to/foo.bar"])

If you're creating the file that you want to send in the same Python program, you'll want to call subprocess.run command outside the with block you're using to open the file (or call .close() on the file first if you're not using a with block), so you know it's flushed to disk from Python.

You need to generate (on the source machine) and install (on the destination machine) an ssh key beforehand so that the scp automatically gets authenticated with your public ssh key (in other words, so your script doesn't ask for a password).

Rotate and translate

I can't comment so here goes. About @David Storey answer.

Be careful on the "order of execution" in CSS3 chains! The order is right to left, not left to right.

transformation: translate(0,10%) rotate(25deg);

The rotate operation is done first, then the translate.

See: CSS3 transform order matters: rightmost operation first

How can I exclude a directory from Visual Studio Code "Explore" tab?

In newer versions of VSCode this moved to a folder-specific configuration block.

  • Go to File -> Preferences -> Settings (or on Mac Code -> Preferences -> Settings)
  • Pick the Folder Settings tab

Then add a "files.exclude" block, listing the directory globs you would like to exclude:

{
    "files.exclude": {
        "**/bin": true,
        "**/obj": true
    },
}

enter image description here

Setting graph figure size

A different approach.
On the figure() call specify properties or modify the figure handle properties after h = figure().

This creates a full screen figure based on normalized units.
figure('units','normalized','outerposition',[0 0 1 1])

The units property can be adjusted to inches, centimeters, pixels, etc.

See figure documentation.

What is the canonical way to trim a string in Ruby without creating a new string?

I guess what you want is:

@title = tokens[Title]
@title.strip!

The #strip! method will return nil if it didn't strip anything, and the variable itself if it was stripped.

According to Ruby standards, a method suffixed with an exclamation mark changes the variable in place.

Hope this helps.

Update: This is output from irb to demonstrate:

>> @title = "abc"
=> "abc"
>> @title.strip!
=> nil
>> @title
=> "abc"
>> @title = " abc "
=> " abc "
>> @title.strip!
=> "abc"
>> @title
=> "abc"

Get week day name from a given month, day and year individually in SQL Server

If you have SQL Server 2012:

If your date parts are integers then you can use DATEFROMPARTS function.

SELECT DATENAME( dw, DATEFROMPARTS( @Year, @Month, @Day ) )

If your date parts are strings, then you can use the CONCAT function.

SELECT DATENAME( dw, CONVERT( date, CONCAT( @Day, '/' , @Month, '/', @Year ), 103 ) )

How to increase MaximumErrorCount in SQL Server 2008 Jobs or Packages?

If I have open a package in BIDS ("Business Intelligence Development Studio", the tool you use to design the packages), and do not select any item in it, I have a "Properties" pane in the bottom right containing - among others, the MaximumErrorCount property. If you do not see it, maybe it is minimized and you have to open it (have a look at tabs in the right).

If you cannot find it this way, try the menu: View/Properties Window.

Or try the F4 key.

OVER_QUERY_LIMIT in Google Maps API v3: How do I pause/delay in Javascript to slow it down?

Nothing like these two lines appears in Mike Williams' tutorial:

    wait = true;
    setTimeout("wait = true", 2000);

Here's a Version 3 port:

http://acleach.me.uk/gmaps/v3/plotaddresses.htm

The relevant bit of code is

  // ====== Geocoding ======
  function getAddress(search, next) {
    geo.geocode({address:search}, function (results,status)
      { 
        // If that was successful
        if (status == google.maps.GeocoderStatus.OK) {
          // Lets assume that the first marker is the one we want
          var p = results[0].geometry.location;
          var lat=p.lat();
          var lng=p.lng();
          // Output the data
            var msg = 'address="' + search + '" lat=' +lat+ ' lng=' +lng+ '(delay='+delay+'ms)<br>';
            document.getElementById("messages").innerHTML += msg;
          // Create a marker
          createMarker(search,lat,lng);
        }
        // ====== Decode the error status ======
        else {
          // === if we were sending the requests to fast, try this one again and increase the delay
          if (status == google.maps.GeocoderStatus.OVER_QUERY_LIMIT) {
            nextAddress--;
            delay++;
          } else {
            var reason="Code "+status;
            var msg = 'address="' + search + '" error=' +reason+ '(delay='+delay+'ms)<br>';
            document.getElementById("messages").innerHTML += msg;
          }   
        }
        next();
      }
    );
  }

Converting java.sql.Date to java.util.Date

The class java.sql.Date is designed to carry only a date without time, so the conversion result you see is correct for this type. You need to use a java.sql.Timestamp to get a full date with time.

java.util.Date newDate = result.getTimestamp("VALUEDATE");

Should try...catch go inside or outside a loop?

PERFORMANCE:

There is absolutely no performance difference in where the try/catch structures are placed. Internally, they are implemented as a code-range table in a structure that is created when the method is called. While the method is executing, the try/catch structures are completely out of the picture unless a throw occurs, then the location of the error is compared against the table.

Here's a reference: http://www.javaworld.com/javaworld/jw-01-1997/jw-01-hood.html

The table is described about half-way down.

Does it matter what extension is used for SQLite database files?

If you have settled on a particular set of tools to access / modify your databases, I would go with whatever extension they expect you to use. This will avoid needless friction when doing development tasks.

For instance, SQLiteStudio v3.1.1 defaults to looking for files with the following extensions:

enter image description here

(db|sdb|sqlite|db3|s3db|sqlite3|sl3|db2|s2db|sqlite2|sl2)

If necessary for deployment your installation mechanism could rename the file if obscuring the file type seems useful to you (as some other answers have suggested). Filename requirements for development and deployment can be different.

Convert boolean result into number/integer

Use the unary + operator, which converts its operand into a number.

+ true; // 1
+ false; // 0

Note, of course, that you should still sanitise the data on the server side, because a user can send any data to your sever, no matter what the client-side code says.

How to convert string into float in JavaScript?

If they're meant to be separate values, try this:

var values = "554,20".split(",")
var v1 = parseFloat(values[0])
var v2 = parseFloat(values[1])

If they're meant to be a single value (like in French, where one-half is written 0,5)

var value = parseFloat("554,20".replace(",", "."));

jQuery select change show/hide div event

Use following JQuery. Demo

$(function() {
    $('#row_dim').hide(); 
    $('#type').change(function(){
        if($('#type').val() == 'parcel') {
            $('#row_dim').show(); 
        } else {
            $('#row_dim').hide(); 
        } 
    });
});

JQuery Ajax - How to Detect Network Connection error when making Ajax call

USE

xhr.onerror = function(e){
    if (XMLHttpRequest.readyState == 4) {
        // HTTP error (can be checked by XMLHttpRequest.status and XMLHttpRequest.statusText)
        selFoto.erroUploadFoto('Erro HTTP: '+XMLHttpRequest.statusText);
    }
    else if (XMLHttpRequest.readyState == 0) {
        // Network error (i.e. connection refused, access denied due to CORS, etc.)
        selFoto.erroUploadFoto('Erro de rede:'+XMLHttpRequest.statusText);
    }
    else {
        selFoto.erroUploadFoto('Erro desconhecido.');
    }

};

(more code below - UPLOAD IMAGE EXAMPLE)

var selFoto = {
   foto: null,

   upload: function(){
        LoadMod.show();

        var arquivo = document.frmServico.fileupload.files[0];
        var formData = new FormData();

        if (arquivo.type.match('image.*')) {
            formData.append('upload', arquivo, arquivo.name);

            var xhr = new XMLHttpRequest();
            xhr.open('POST', 'FotoViewServlet?acao=uploadFoto', true);
            xhr.responseType = 'blob';

            xhr.onload = function(e){
                if (this.status == 200) {
                    selFoto.foto = this.response;
                    var url = window.URL || window.webkitURL;
                    document.frmServico.fotoid.src = url.createObjectURL(this.response);
                    $('#foto-id').show();
                    $('#div_upload_foto').hide();           
                    $('#div_master_upload_foto').css('background-color','transparent');
                    $('#div_master_upload_foto').css('border','0');

                    Dados.foto = document.frmServico.fotoid;
                    LoadMod.hide();
                }
                else{
                    erroUploadFoto(XMLHttpRequest.statusText);
                }

                if (XMLHttpRequest.readyState == 4) {
                     selFoto.erroUploadFoto('Erro HTTP: '+XMLHttpRequest.statusText);
                }
                else if (XMLHttpRequest.readyState == 0) {
                     selFoto.erroUploadFoto('Erro de rede:'+XMLHttpRequest.statusText);                             
                }

            };

            xhr.onerror = function(e){
            if (XMLHttpRequest.readyState == 4) {
                // HTTP error (can be checked by XMLHttpRequest.status and XMLHttpRequest.statusText)
                selFoto.erroUploadFoto('Erro HTTP: '+XMLHttpRequest.statusText);
            }
            else if (XMLHttpRequest.readyState == 0) {
                 // Network error (i.e. connection refused, access denied due to CORS, etc.)
                 selFoto.erroUploadFoto('Erro de rede:'+XMLHttpRequest.statusText);
            }
            else {
                selFoto.erroUploadFoto('Erro desconhecido.');
            }
        };

        xhr.send(formData);
     }
     else{
        selFoto.erroUploadFoto('');                         
        MyCity.mensagens.push('Selecione uma imagem.');
        MyCity.showMensagensAlerta();
     }
  }, 

  erroUploadFoto : function(mensagem) {
        selFoto.foto = null;
        $('#file-upload').val('');
        LoadMod.hide();
        MyCity.mensagens.push('Erro ao atualizar a foto. '+mensagem);
        MyCity.showMensagensAlerta();
 }
 };

Send attachments with PHP Mail()?

I ended up writing my own email sending/encoding function. This has worked well for me for sending PDF attachments. I have not used the other features in production.

Note: Despite the spec being quite emphatic that you must use \r\n to separate headers, I found it only worked when I used PHP_EOL. I have only tested this on Linux. YMMV

<?php
# $args must be an associative array
#     required keys: from, to, body
#          body can be a string or a [tree of] associative arrays. See examples below
#     optional keys: subject, reply_to, cc, bcc
# EXAMPLES:
#    # text-only email:
#    email2(array(
#        'from' => '[email protected]',
#        'to' => '[email protected]',
#        'subject' => 'test',
#        # body will be text/plain because we're passing a string that doesn't start with '<'
#        'body' => 'Hi, testing 1 2 3',
#    ));
#
#    # html-only email
#    email2(array(
#        'from' => '[email protected]',
#        'to' => '[email protected]',
#        'subject' => 'test',
#        # body will be text/html because we're passing a string that starts with '<'
#        'body' => '<h1>Hi!</h1>I like <a href="http://cheese.com">cheese</a>',
#    ));
#
#    # text-only email (explicitly, in case first character is dynamic or something)
#    email2(array(
#        'from' => '[email protected]',
#        'to' => '[email protected]',
#        'subject' => 'test',
#        # body will be text/plain because we're passing a string that doesn't start with '<'
#        'body' => array(
#            'type' => 'text',
#            'body' => $message_text,
#        )
#    ));
#
#    # email with text and html alternatives (auto-detected mime types)
#    email2(array(
#        'from' => '[email protected]',
#        'to' => '[email protected]',
#        'subject' => 'test',
#        'body' => array(
#            'type' => 'alternatives',
#            'body' => array(
#                "Hi!\n\nI like cheese",
#                '<h1>Hi!</h1><p>I like <a href="http://cheese.com">cheese</a></p>',
#            )
#        )
#    ));
#
#    # email with text and html alternatives (explicit types)
#    email2(array(
#        'from' => '[email protected]',
#        'to' => '[email protected]',
#        'subject' => 'test',
#        'body' => array(
#            'type' => 'alternatives',
#            'body' => array(
#                array(
#                    'type' => 'text',
#                    'body' => "Hi!\n\nI like cheese",
#                ),
#                array(
#                    'type' => 'html',
#                    'body' => '<h1>Hi!</h1><p>I like cheese</p>',
#                ),
#            )
#        )
#    ));
#
#    # email with an attachment
#    email2(array(
#        'from' => '[email protected]',
#        'to' => '[email protected]',
#        'subject' => 'test',
#        'body' => array(
#            'type' => 'mixed',
#            'body' => array(
#                "Hi!\n\nCheck out this (inline) image",
#                array(
#                    'type' => 'image/png',
#                    'disposition' => 'inline',
#                    'body' => $image_data, # raw file contents
#                ),
#                "Hi!\n\nAnd here's an attachment",
#                array(
#                    'type' => 'application/pdf; name="attachment.pdf"',
#                    'disposition' => 'attachment; filename="attachment.pdf"',
#                    'body' => $pdf_data, # raw file contents
#                ),
#                "Or you can use shorthand:",
#                array(
#                    'type' => 'application/pdf',
#                    'attachment' => 'attachment.pdf', # name for client (not data source)
#                    'body' => $pdf_data, # raw file contents
#                ),
#            )
#        )
#    ))
function email2($args) {
    if (!isset($args['from'])) { return 1; }
    $from = $args['from'];
    if (!isset($args['to'])) { return 2; }
    $to = $args['to'];
    $subject = isset($args['subject']) ? $args['subject'] : '';
    $reply_to = isset($args['reply_to']) ? $args['reply_to'] : '';
    $cc = isset($args['cc']) ? $args['cc'] : '';
    $bcc = isset($args['bcc']) ? $args['bcc'] : '';

    #FIXME should allow many more characters here (and do Q encoding)
    $subject = isset($args['subject']) ? $args['subject'] : '';
    $subject = preg_replace("|[^a-z0-9 _/#'.:&,-]|i", '_', $subject);

    $headers = "From: $from";
    if($reply_to) {
        $headers .= PHP_EOL . "Reply-To: $reply_to";
    }
    if($cc) {
        $headers .= PHP_EOL . "CC: $cc";
    }
    if($bcc) {
        $headers .= PHP_EOL . "BCC: $bcc";
    }

    $r = email2_helper($args['body']);
    $headers .= PHP_EOL . $r[0];
    $body = $r[1];

    if (mail($to, $subject, $body, $headers)) {
        return 0;
    } else {
        return 5;
    }
}

function email2_helper($body, $top = true) {
    if (is_string($body)) {
        if (substr($body, 0, 1) == '<') {
            return email2_helper(array('type' => 'html', 'body' => $body), $top);
        } else {
            return email2_helper(array('type' => 'text', 'body' => $body), $top);
        }
    }
    # now we can assume $body is an associative array
    # defaults:
    $type = 'application/octet-stream';
    $mime = false;
    $boundary = null;
    $disposition = null;
    $charset = false;
    # process 'type' first, because it sets defaults for others
    if (isset($body['type'])) {
        $type = $body['type'];
        if ($type === 'text') {
            $type = 'text/plain';
            $charset = true;
        } elseif ($type === 'html') {
            $type = 'text/html';
            $charset = true;
        } elseif ($type === 'alternative' || $type === 'alternatives') {
            $mime = true;
            $type = 'multipart/alternative';
        } elseif ($type === 'mixed') {
            $mime = true;
            $type = 'multipart/mixed';
        }
    }
    if (isset($body['disposition'])) {
        $disposition = $body['disposition'];
    }
    if (isset($body['attachment'])) {
        if ($disposition == null) {
            $disposition = 'attachment';
        }
        $disposition .= "; filename=\"{$body['attachment']}\"";
        $type .= "; name=\"{$body['attachment']}\"";
    }
    # make headers
    $headers = array();
    if ($top && $mime) {
        $headers[] = 'MIME-Version: 1.0';
    }
    if ($mime) {
        $boundary = md5('5sd^%Ca)~aAfF0=4mIN' . rand() . rand());
        $type .= "; boundary=$boundary";
    }
    if ($charset) {
        $type .= '; charset=' . (isset($body['charset']) ? $body['charset'] : 'UTF-8');
    }
    $headers[] = "Content-Type: $type";
    if ($disposition !== null) {
        $headers[] = "Content-Disposition: {$disposition}";
    }

    $data = '';
    # return array, first el is headers, 2nd is body (php's mail() needs them separate)
    if ($mime) {
        foreach ($body['body'] as $sub_body) {
            $data .= "--$boundary" . PHP_EOL;
            $r = email2_helper($sub_body, false);
            $data .= $r[0] . PHP_EOL . PHP_EOL; # headers
            $data .= $r[1] . PHP_EOL . PHP_EOL; # body
        }
        $data .= "--$boundary--";
    } else {
        if(preg_match('/[^\x09\x0A\x0D\x20-\x7E]/', $body['body'])) {
            $headers[] = "Content-Transfer-Encoding: base64";
            $data .= chunk_split(base64_encode($body['body']));
        } else {
            $data .= $body['body'];
        }
    }
    return array(join(PHP_EOL, $headers), $data);
}

gzip: stdin: not in gzip format tar: Child returned status 1 tar: Error is not recoverable: exiting now

Sometimes the .gz extension is wrongfully appended to the filename.

  • Run file foo.csv.gz to know the actual file type.
  • Rename the file to foo.csv or whatever the actual file type is.

Must issue a STARTTLS command first

    String username = "[email protected]";
    String password = "some-password";
    String recipient = "[email protected]");

    Properties props = new Properties();

    props.put("mail.smtp.host", "smtp.gmail.com");
    props.put("mail.from", "[email protected]");
    props.put("mail.smtp.starttls.enable", "true");
    props.put("mail.smtp.port", "587");
    props.setProperty("mail.debug", "true");

    Session session = Session.getInstance(props, null);
    MimeMessage msg = new MimeMessage(session);

    msg.setRecipients(Message.RecipientType.TO, recipient);
    msg.setSubject("JavaMail hello world example");
    msg.setSentDate(new Date());
    msg.setText("Hello, world!\n");

    Transport transport = session.getTransport("smtp");

    transport.connect(username, password);
    transport.sendMessage(msg, msg.getAllRecipients());
    transport.close();

time.sleep -- sleeps thread or process?

Process is not runnable by itself. In regard to execution, process is just a container for threads. Meaning you can't pause the process at all. It is simply not applicable to process.

How to create a timeline with LaTeX?

I have been struggling to find a proper way to create a timeline, which I could finally do with this modification. Usually while creating a timeline the problem was that I could not add a text to explain each date clearly with a longer text. I modified and further utilized @Zoe Gagnon's latex script. Please feel free to see the following:

\documentclass{article}
\usepackage{tikz}
\usetikzlibrary{snakes}
\usepackage{rotating}

\begin{document}
    
\begin{center}
    \begin{tikzpicture}
        % draw horizontal line   
        \draw (-5,0) -- (6,0);
    
    
    % draw vertical lines
    \foreach \x in {-5,-4,-3,-2, -1,0,1,2}
    \draw (\x cm,3pt) -- (\x cm,-3pt);
    
    % draw nodes
    \draw (-5,0) node[below=3pt] {$ 0 $} node[above=3pt] {$  $};
    \draw (-4,0) node[below=3pt] {$ 1 $} node[above=3pt] {$\begin{turn}{45}
            All individuals vote
        \end{turn}$};
    \draw (-3,0) node[below=3pt] {$ 2 $} node[above=3pt] {$\begin{turn}{45} 
        Policy vector decided
        \end{turn}$};
    \draw (-2,0) node[below=3pt] {$ 3 $} node[above=3pt] {$\begin{turn}{45}  Becoming a bureaucrat \end{turn} $};
    \draw (-1,0) node[below=3pt] {$ 4 $} node[above=3pt] {$\begin{turn}{45} Bureaucrats' effort choice \end{turn}$};
    \draw (0,0) node[below=3pt] {$ 5 $} node[above=3pt] {$\begin{turn}{45} Tax evasion decision made \end{turn}$};
    \draw (1,0) node[below=3pt] {$  6$} node[above=3pt] {$\begin{turn}{45} $p(x_{t})$ tax evaders caught \end{turn}$};
    \draw (2,0) node[below=3pt] {$ 7 $} node[above=3pt] {$\begin{turn}{45} $q_{t}$ shirking bureaucrats \end{turn}$};
            \draw (3,0) node[below=3pt] {$ $} node[above=3pt] {$\begin{turn}{45} Public service provided  \end{turn}   $};
\end{tikzpicture}
\end{center} 
\end{document}

Longer texts are not allowed, unfortunately. It will look like this:

visual depiction of the timeline above

How do I force Postgres to use a particular index?

Assuming you're asking about the common "index hinting" feature found in many databases, PostgreSQL doesn't provide such a feature. This was a conscious decision made by the PostgreSQL team. A good overview of why and what you can do instead can be found here. The reasons are basically that it's a performance hack that tends to cause more problems later down the line as your data changes, whereas PostgreSQL's optimizer can re-evaluate the plan based on the statistics. In other words, what might be a good query plan today probably won't be a good query plan for all time, and index hints force a particular query plan for all time.

As a very blunt hammer, useful for testing, you can use the enable_seqscan and enable_indexscan parameters. See:

These are not suitable for ongoing production use. If you have issues with query plan choice, you should see the documentation for tracking down query performance issues. Don't just set enable_ params and walk away.

Unless you have a very good reason for using the index, Postgres may be making the correct choice. Why?

  • For small tables, it's faster to do sequential scans.
  • Postgres doesn't use indexes when datatypes don't match properly, you may need to include appropriate casts.
  • Your planner settings might be causing problems.

See also this old newsgroup post.

Property 'json' does not exist on type 'Object'

For future visitors: In the new HttpClient (Angular 4.3+), the response object is JSON by default, so you don't need to do response.json().data anymore. Just use response directly.

Example (modified from the official documentation):

import { HttpClient } from '@angular/common/http';

@Component(...)
export class YourComponent implements OnInit {

  // Inject HttpClient into your component or service.
  constructor(private http: HttpClient) {}

  ngOnInit(): void {
    this.http.get('https://api.github.com/users')
        .subscribe(response => console.log(response));
  }
}

Don't forget to import it and include the module under imports in your project's app.module.ts:

...
import { HttpClientModule } from '@angular/common/http';

@NgModule({
  imports: [
    BrowserModule,
    // Include it under 'imports' in your application module after BrowserModule.
    HttpClientModule,
    ...
  ],
  ...

Getting random numbers in Java

int max = 50;
int min = 1;

1. Using Math.random()

double random = Math.random() * 49 + 1;
or
int random = (int )(Math.random() * 50 + 1);

This will give you value from 1 to 50 in case of int or 1.0 (inclusive) to 50.0 (exclusive) in case of double

Why?

random() method returns a random number between 0.0 and 0.9..., you multiply it by 50, so upper limit becomes 0.0 to 49.999... when you add 1, it becomes 1.0 to 50.999..., now when you truncate to int, you get 1 to 50. (thanks to @rup in comments). leepoint's awesome write-up on both the approaches.

2. Using Random class in Java.

Random rand = new Random(); 
int value = rand.nextInt(50); 

This will give value from 0 to 49.

For 1 to 50: rand.nextInt((max - min) + 1) + min;

Source of some Java Random awesomeness.

How do I resolve git saying "Commit your changes or stash them before you can merge"?

If you are using Git Extensions you should be able to find your local changes in the Working directory as shown below:

enter image description here

If you don't see any changes, it's probably because you are on a wrong sub-module. So check all the items with a submarine icon as shown below:

enter image description here

When you found some uncommitted change:

Select the line with Working directory, navigate to Diff tab, Right click on rows with a pencil (or + or -) icon, choose Reset to first commit or commit or stash or whatever you want to do with it.

How to include duplicate keys in HashMap?

You can't have duplicate keys in a Map. You can rather create a Map<Key, List<Value>>, or if you can, use Guava's Multimap.

Multimap<Integer, String> multimap = ArrayListMultimap.create();
multimap.put(1, "rohit");
multimap.put(1, "jain");

System.out.println(multimap.get(1));  // Prints - [rohit, jain]

And then you can get the java.util.Map using the Multimap#asMap() method.

How can I quickly and easily convert spreadsheet data to JSON?

Assuming you really mean easiest and are not necessarily looking for a way to do this programmatically, you can do this:

  1. Add, if not already there, a row of "column Musicians" to the spreadsheet. That is, if you have data in columns such as:

    Rory Gallagher      Guitar
    Gerry McAvoy        Bass
    Rod de'Ath          Drums
    Lou Martin          Keyboards
    Donkey Kong Sioux   Self-Appointed Semi-official Stomper
    

    Note: you might want to add "Musician" and "Instrument" in row 0 (you might have to insert a row there)

  2. Save the file as a CSV file.

  3. Copy the contents of the CSV file to the clipboard

  4. Go to http://www.convertcsv.com/csv-to-json.htm

  5. Verify that the "First row is column names" checkbox is checked

  6. Paste the CSV data into the content area

  7. Mash the "Convert CSV to JSON" button

    With the data shown above, you will now have:

    [
      {
        "MUSICIAN":"Rory Gallagher",
        "INSTRUMENT":"Guitar"
      },
      {
        "MUSICIAN":"Gerry McAvoy",
        "INSTRUMENT":"Bass"
      },
      {
        "MUSICIAN":"Rod D'Ath",
        "INSTRUMENT":"Drums"
      },
      {
        "MUSICIAN":"Lou Martin",
        "INSTRUMENT":"Keyboards"
      }
      {
        "MUSICIAN":"Donkey Kong Sioux",
        "INSTRUMENT":"Self-Appointed Semi-Official Stomper"
      }
    ]
    

    With this simple/minimalistic data, it's probably not required, but with large sets of data, it can save you time and headache in the proverbial long run by checking this data for aberrations and abnormalcy.

  8. Go here: http://jsonlint.com/

  9. Paste the JSON into the content area

  10. Pres the "Validate" button.

If the JSON is good, you will see a "Valid JSON" remark in the Results section below; if not, it will tell you where the problem[s] lie so that you can fix it/them.

Alternative to header("Content-type: text/xml");

No. You can't send headers after they were sent. Try to use hooks in wordpress

How do I create a SQL table under a different schema?

                           create a database schema in SQL Server 2008
1. Navigate to Security > Schemas
2. Right click on Schemas and select New Schema
3. Complete the details in the General tab for the new schema. Like, the schema name is "MySchema" and the schema owner is "Admin".
4. Add users to the schema as required and set their permissions:
5. Add any extended properties (via the Extended Properties tab)
6. Click OK.
                           Add a Table to the New Schema "MySchema"
1. In Object Explorer, right click on the table name and select "Design":
2. Changing database schema for a table in SQL Server Management Studio
3. From Design view, press F4 to display the Properties window.
4. From the Properties window, change the schema to the desired schema:
5. Close Design View by right clicking the tab and selecting "Close":
6. Closing Design View
7. Click "OK" when prompted to save
8. Your table has now been transferred to the "MySchema" schema.

Refresh the Object Browser view To confirm the changes
Done

How to prevent form resubmission when page is refreshed (F5 / CTRL+R)

How to prevent php form resubmission without redirect. If you are using $_SESSION (after session_start) and a $_POST form, you can do something like this:

if ( !empty($_SESSION['act']) && !empty($_POST['act']) && $_POST['act'] == $_SESSION['act'] ) {
  // do your stuff, save data into database, etc
}

In your html form put this:

<input type="hidden" id="act" name="act" value="<?php echo ( empty($_POST['act']) || $_POST['act']==2 )? 1 : 2; ?>">
<?php
if ( $_POST['act'] == $_SESSION['act'] ){
    if ( empty( $_SESSION['act'] ) || $_SESSION['act'] == 2 ){
        $_SESSION['act'] = 1;
    } else {
        $_SESSION['act'] = 2;
    }
}
?>

So, every time when the form is submitted, a new act is generated, stored in session and compared with the post act.

Ps: if you are using an Get form, you can easily change all POST with GET and it works too.

Regex: Use start of line/end of line signs (^ or $) in different context

You can't use ^ and $ in character classes in the way you wish - they will be interpreted literally, but you can use an alternation to achieve the same effect:

(^|,)garp(,|$)

how do I change text in a label with swift?

use a simple formula: WHO.WHAT = VALUE

where,

WHO is the element in the storyboard you want to make changes to for eg. label

WHAT is the property of that element you wish to change for eg. text

VALUE is the change that you wish to be displayed

for eg. if I want to change the text from story text to You see a fork in the road in the label as shown in screenshot 1

In this case, our WHO is the label (element in the storyboard), WHAT is the text (property of element) and VALUE will be You see a fork in the road

so our final code will be as follows: Final code

screenshot 1 changes to screenshot 2 once the above code is executed.

I hope this solution helps you solve your issue. Thank you!

Stored procedure - return identity as output parameter or scalar

Another option would be as the return value for the stored procedure (I don't suggest this though, as that's usually best for error values).

I've included it as both when it's inserting a single row in cases where the stored procedure was being consumed by both other SQL procedures and a front-end which couldn't work with OUTPUT parameters (IBATIS in .NET I believe):

CREATE PROCEDURE My_Insert
    @col1            VARCHAR(20),
    @new_identity    INT    OUTPUT
AS
BEGIN
    SET NOCOUNT ON

    INSERT INTO My_Table (col1)
    VALUES (@col1)

    SELECT @new_identity = SCOPE_IDENTITY()

    SELECT @new_identity AS id

    RETURN
END

The output parameter is easier to work with in T-SQL when calling from other stored procedures IMO, but some programming languages have poor or no support for output parameters and work better with result sets.

How do I perform an IF...THEN in an SQL SELECT?

SELECT  
(CASE 
     WHEN (Obsolete = 'N' OR InStock = 'Y') THEN 'YES'
                                            ELSE 'NO' 
 END) as Salable
, * 
FROM Product

What's the difference between process.cwd() vs __dirname?

As per node js doc process.cwd()

cwd is a method of global object process, returns a string value which is the current working directory of the Node.js process.

As per node js doc __dirname

The directory name of current script as a string value. __dirname is not actually a global but rather local to each module.

Let me explain with example,

suppose we have a main.js file resides inside C:/Project/main.js and running node main.js both these values return same file

or simply with following folder structure

Project 
+-- main.js
+--lib
   +-- script.js

main.js

console.log(process.cwd())
// C:\Project
console.log(__dirname)
// C:\Project
console.log(__dirname===process.cwd())
// true

suppose we have another file script.js files inside a sub directory of project ie C:/Project/lib/script.js and running node main.js which require script.js

main.js

require('./lib/script.js')
console.log(process.cwd())
// C:\Project
console.log(__dirname)
// C:\Project
console.log(__dirname===process.cwd())
// true

script.js

console.log(process.cwd())
// C:\Project
console.log(__dirname)
// C:\Project\lib
console.log(__dirname===process.cwd())
// false

How to change the colors of a PNG image easily?

If you are like me and Photoshop is out of your price range or just overkill for what you need. Acorn 5 is a much cheaper version of Photoshop with a lot of the same features. One of those features being a color change option. You can import all of the basic image formats including SVG and PNG. The color editing software works great and allows for basic color selection, RBG selection, hex code, or even a color grabber if you do not know the color. These color features, plus a whole lot image editing features, is definitely worth the $30. The only downside is that is currently only available on Mac.

Target class controller does not exist - Laravel 8

The way to define your routes in laravel 8 is either

// Using PHP callable syntax...
use App\Http\Controllers\HomeController;
Route::get('/', [HomeController::class, 'index']);

OR

// Using string syntax...
Route::get('/', 'App\Http\Controllers\HomeController@index');

A resource route becomes

// Using PHP callable syntax...
use App\Http\Controllers\HomeController;
Route::resource('/', HomeController::class);

This means that in laravel 8, there is no automatic controller declaration prefixing by default.

If you want to stick to the old way, then you need to add a namespace property in the app\Providers\RouteServiceProvider.php and activate in the routes method.

Follow this image instructions below:

enter image description here

Display a message in Visual Studio's output window when not debug mode?

This whole thread confused the h#$l out of me until I realized you have to be running the debugger to see ANY trace or debug output. I needed a debug output (outside of the debugger) because my WebApp runs fine when I debug it but not when the debugger isn't running (SqlDataSource is instantiated correctly when running through the debugger).

Just because debug output can be seen when you're running in release mode doesn't mean you'll see anything if you're not running the debugger. Careful reading of Writing to output window of Visual Studio? gave me DebugView as an alternative. Extremely useful!

Hopefully this helps anyone else confused by this.

Android Linear Layout - How to Keep Element At Bottom Of View?

You can also use

android:layout_gravity="bottom"

for your textview

Order by multiple columns with Doctrine

You have to add the order direction right after the column name:

$qb->orderBy('column1 ASC, column2 DESC');

As you have noted, multiple calls to orderBy do not stack, but you can make multiple calls to addOrderBy:

$qb->addOrderBy('column1', 'ASC')
   ->addOrderBy('column2', 'DESC');

Removing input background colour for Chrome autocomplete?

I have a better solution.

Setting the background to another color like below didn't solve the problem for me because I needed a transparent input field

-webkit-box-shadow: 0 0 0px 1000px white inset;

So I tried some other things and I came up with this:

input:-webkit-autofill,
input:-webkit-autofill:hover,
input:-webkit-autofill:focus,
input:-webkit-autofill:active {
    transition: background-color 5000s ease-in-out 0s;
}

simple vba code gives me run time error 91 object variable or with block not set

Check the version of the excel, if you are using older version then Value2 is not available for you and thus it is showing an error, while it will work with 2007+ version. Or the other way, the object is not getting created and thus the Value2 property is not available for the object.

Cannot connect to SQL Server named instance from another SQL Server

well after spending about 10 days trying to solve this issue, i finally figured it out today and decide to post the solution

in the start menu, type RUN, open it the in the run box, type SERVICES.MSC, click okay

ensure that these two services are started SQL Server(MSSQLSERVER) SQL Server Vss writer

Setting the JVM via the command line on Windows

You should be able to do this via the command line arguments, assuming these are Sun VMs installed using the usual Windows InstallShield mechanisms with the JVM finder EXE in system32.

Type java -help for the options. In particular, see:

-version:<value>
              require the specified version to run
-jre-restrict-search | -jre-no-restrict-search
              include/exclude user private JREs in the version search

CSS show div background image on top of other contained elements

I would put an absolutely positioned, z-index: 100; span (or spans) with the background: url("myImageWithRoundedCorners.jpg"); set on it inside the #mainWrapperDivWithBGImage .

What does flex: 1 mean?

Here is the explanation:

https://www.w3.org/TR/css-flexbox-1/#flex-common

flex: <positive-number>
Equivalent to flex: <positive-number> 1 0. Makes the flex item flexible and sets the flex basis to zero, resulting in an item that receives the specified proportion of the free space in the flex container. If all items in the flex container use this pattern, their sizes will be proportional to the specified flex factor.

Therefore flex:1 is equivalent to flex: 1 1 0

Add a month to a Date

I turned antonio's thoughts into a specific function:

library(DescTools)

> AddMonths(as.Date('2004-01-01'), 1)
[1] "2004-02-01"

> AddMonths(as.Date('2004-01-31'), 1)
[1] "2004-02-29"

> AddMonths(as.Date('2004-03-30'), -1)
[1] "2004-02-29"

Select N random elements from a List<T> in C#

I recently did this on my project using an idea similar to Tyler's point 1.
I was loading a bunch of questions and selecting five at random. Sorting was achieved using an IComparer.
aAll questions were loaded in the a QuestionSorter list, which was then sorted using the List's Sort function and the first k elements where selected.

    private class QuestionSorter : IComparable<QuestionSorter>
    {
        public double SortingKey
        {
            get;
            set;
        }

        public Question QuestionObject
        {
            get;
            set;
        }

        public QuestionSorter(Question q)
        {
            this.SortingKey = RandomNumberGenerator.RandomDouble;
            this.QuestionObject = q;
        }

        public int CompareTo(QuestionSorter other)
        {
            if (this.SortingKey < other.SortingKey)
            {
                return -1;
            }
            else if (this.SortingKey > other.SortingKey)
            {
                return 1;
            }
            else
            {
                return 0;
            }
        }
    }

Usage:

    List<QuestionSorter> unsortedQuestions = new List<QuestionSorter>();

    // add the questions here

    unsortedQuestions.Sort(unsortedQuestions as IComparer<QuestionSorter>);

    // select the first k elements

CSS text-align not working

I try to avoid floating elements unless the design really needs it. Because you have floated the <li> they are out of normal flow.

If you add .navigation { text-align:center; } and change .navigation li { float: left; } to .navigation li { display: inline-block; } then entire navigation will be centred.

One caveat to this approach is that display: inline-block; is not supported in IE6 and needs a workaround to make it work in IE7.

Check if value exists in column in VBA

Just to modify scott's answer to make it a function:

Function FindFirstInRange(FindString As String, RngIn As Range, Optional UseCase As Boolean = True, Optional UseWhole As Boolean = True) As Variant

    Dim LookAtWhat As Integer

    If UseWhole Then LookAtWhat = xlWhole Else LookAtWhat = xlPart

    With RngIn
        Set FindFirstInRange = .Find(What:=FindString, _
                                     After:=.Cells(.Cells.Count), _
                                     LookIn:=xlValues, _
                                     LookAt:=LookAtWhat, _
                                     SearchOrder:=xlByRows, _
                                     SearchDirection:=xlNext, _
                                     MatchCase:=UseCase)

        If FindFirstInRange Is Nothing Then FindFirstInRange = False

    End With

End Function

This returns FALSE if the value isn't found, and if it's found, it returns the range.

You can optionally tell it to be case-sensitive, and/or to allow partial-word matches.

I took out the TRIM because you can add that beforehand if you want to.

An example:

MsgBox FindFirstInRange(StringToFind, Range("2:2"), TRUE, FALSE).Address

That does a case-sensitive, partial-word search on the 2nd row and displays a box with the address. The following is the same search, but a whole-word search that is not case-sensitive:

MsgBox FindFirstInRange(StringToFind, Range("2:2")).Address

You can easily tweak this function to your liking or change it from a Variant to to a boolean, or whatever, to speed it up a little.

Do note that VBA's Find is sometimes slower than other methods like brute-force looping or Match, so don't assume that it's the fastest just because it's native to VBA. It's more complicated and flexible, which also can make it not always as efficient. And it has some funny quirks to look out for, like the "Object variable or with block variable not set" error.

Android - Launcher Icon Size

You can create icons directly in the android studio itself.The Steps you need to follow are:

1.Right click on Res->New->Image asset

2.CHange asset type to image.

3.Load the image from the local disk

4.You have options to trim,change padding and add background also.Change the values if you need.

5.click Next->Finish.

The image wil be automatically added to mipmap-mdpi,mipmap-hdpi,mipmap-xhdpi,mipmap-xxhdpi,mipmap-xxxhdpi if you select launcher icon or drawable-mdpi,drawable-hdpi,drawable-xhdpi,drawable-xxhdpi,drawable-xxxhdpi ifyou select other icon optins.

The following artifacts could not be resolved: javax.jms:jms:jar:1.1

In fact the real solution for this issue is to use the jms-api-1.1-rev-1.jar artifact available on Maven Central : http://search.maven.org/#artifactdetails%7Cjavax.jms%7Cjms-api%7C1.1-rev-1%7Cjar

Android and setting width and height programmatically in dp units

You'll have to convert it from dps to pixels using the display scale factor.

final float scale = getContext().getResources().getDisplayMetrics().density;
int pixels = (int) (dps * scale + 0.5f);

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

The == operator compares if the objects are the same instance. The equals() oerator compares the state of the objects (e.g. if all attributes are equal). You can even override the equals() method to define yourself when an object is equal to another.

How can I represent a range in Java?

import java.util.Arrays;

class Soft{
    public static void main(String[] args){
        int[] nums=range(9, 12);
        System.out.println(Arrays.toString(nums));
    }
    static int[] range(int low, int high){
        int[] a=new int[high-low];
        for(int i=0,j=low;i<high-low;i++,j++){
            a[i]=j;
        }
        return a;

    }
}

My code is similar to Python`s range :)

JavaScript: how to change form action attribute value based on selection?

Is required that you have a form?
If not, then you could use this:

<div>
    <input type="hidden" value="ServletParameter" />
    <input type="button" id="callJavaScriptServlet" onclick="callJavaScriptServlet()" />
</div>

with the following JavaScript:

function callJavaScriptServlet() {
    this.form.action = "MyServlet";
    this.form.submit();
}

How to change dataframe column names in pyspark?

For a single column rename, you can still use toDF(). For example,

df1.selectExpr("SALARY*2").toDF("REVISED_SALARY").show()

Adding a newline character within a cell (CSV)

On Excel for Mac 2011, the newline had to be a \r instead of an \n

So

"\"first line\rsecond line\""

would show up as a cell with 2 lines

Spring data JPA query with parameter properties

You could also solve it with an interface default method:

 @Query(select p from Person p where p.forename = :forename and p.surname = :surname)
User findByForenameAndSurname(@Param("surname") String lastname,
                         @Param("forename") String firstname);

default User findByName(Name name) {
  return findByForenameAndSurname(name.getLastname(), name.getFirstname());
}

Of course you'd still have the actual repository function publicly visible...

ggplot2 plot area margins?

You can adjust the plot margins with plot.margin in theme() and then move your axis labels and title with the vjust argument of element_text(). For example :

library(ggplot2)
library(grid)
qplot(rnorm(100)) +
    ggtitle("Title") +
    theme(axis.title.x=element_text(vjust=-2)) +
    theme(axis.title.y=element_text(angle=90, vjust=-0.5)) +
    theme(plot.title=element_text(size=15, vjust=3)) +
    theme(plot.margin = unit(c(1,1,1,1), "cm"))

will give you something like this :

enter image description here

If you want more informations about the different theme() parameters and their arguments, you can just enter ?theme at the R prompt.

How do I do a simple 'Find and Replace" in MsSQL?

This pointed me in the right direction, but I have a DB that originated in MSSQL 2000 and is still using the ntext data type for the column I was replacing on. When you try to run REPLACE on that type you get this error:

Argument data type ntext is invalid for argument 1 of replace function.

The simplest fix, if your column data fits within nvarchar, is to cast the column during replace. Borrowing the code from the accepted answer:

UPDATE YourTable
SET Column1 = REPLACE(cast(Column1 as nvarchar(max)),'a','b')
WHERE Column1 LIKE '%a%'

This worked perfectly for me. Thanks to this forum post I found for the fix. Hopefully this helps someone else!

How to move Jenkins from one PC to another

Jenkins Server Automation:

Step 1:

Set up a repository to store the Jenkins home (jobs, configurations, plugins, etc.) in a GitLab local or on GitHub private repository and keep it updated regularly by pushing any new changes to Jenkins jobs, plugins, etc.

Step 2:

Configure a Puppet host-group/role for Jenkins that can be used to spin up new Jenkins servers. Do all the basic configuration in a Puppet recipe and make sure it installs the latest version of Jenkins and sets up a separate directory/mount for JENKINS_HOME.

Step 3:

Spin up a new machine using the Jenkins-puppet configuration above. When everything is installed, grab/clone the Jenkins configuration from the Git repository to the Jenkins home direcotry and restart Jenkins.

Step 4:

Go to the Jenkins URL, Manage Jenkins ? Manage Plugins and update all the plugins that require an update.

Done

You can use Docker Swarm or Kubernetes to auto-scale the slave nodes.

How to crop(cut) text files based on starting and ending line-numbers in cygwin?

And if you simply want to cut part of a file - say from line 26 to 142 - and input it to a newfile : cat file-to-cut.txt | sed -n '26,142p' >> new-file.txt

Java LinkedHashMap get first or last entry

I would recommend using ConcurrentSkipListMap which has firstKey() and lastKey() methods

Set formula to a range of cells

Range("C1:C10").Formula = "=A1+B1"

Simple as that.

It autofills (FillDown) the range with the formula.

How to Customize the time format for Python logging?

if using logging.config.fileConfig with a configuration file use something like:

[formatter_simpleFormatter]
format=%(asctime)s - %(name)s - %(levelname)s - %(message)s
datefmt=%Y-%m-%d %H:%M:%S

Get event listeners attached to node using addEventListener

Chrome DevTools, Safari Inspector and Firebug support getEventListeners(node).

getEventListeners(document)

Difference between DataFrame, Dataset, and RDD in Spark

A DataFrame is an RDD that has a schema. You can think of it as a relational database table, in that each column has a name and a known type. The power of DataFrames comes from the fact that, when you create a DataFrame from a structured dataset (Json, Parquet..), Spark is able to infer a schema by making a pass over the entire (Json, Parquet..) dataset that's being loaded. Then, when calculating the execution plan, Spark, can use the schema and do substantially better computation optimizations. Note that DataFrame was called SchemaRDD before Spark v1.3.0

Sorting dropdown alphabetically in AngularJS

For anyone who wants to sort the variable in third layer:

<select ng-option="friend.pet.name for friend in friends"></select>

you can do it like this

<select ng-option="friend.pet.name for friend in friends | orderBy: 'pet.name'"></select>

How to query a MS-Access Table from MS-Excel (2010) using VBA

The Provider piece must be Provider=Microsoft.ACE.OLEDB.12.0 if your target database is ACCDB format. Provider=Microsoft.Jet.OLEDB.4.0 only works for the older MDB format.

You shouldn't even need Access installed if you're running 32 bit Windows. Jet 4 is included as part of the operating system. If you're using 64 bit Windows, Jet 4 is not included, but you still wouldn't need Access itself installed. You can install the Microsoft Access Database Engine 2010 Redistributable. Make sure to download the matching version (AccessDatabaseEngine.exe for 32 bit Windows, or AccessDatabaseEngine_x64.exe for 64 bit).

You can avoid the issue about which ADO version reference by using late binding, which doesn't require any reference.

Dim conn As Object
Set conn = CreateObject("ADODB.Connection")

Then assign your ConnectionString property to the conn object. Here is a quick example which runs from a code module in Excel 2003 and displays a message box with the row count for MyTable. It uses late binding for the ADO connection and recordset objects, so doesn't require setting a reference.

Public Sub foo()
    Dim cn As Object
    Dim rs As Object
    Dim strSql As String
    Dim strConnection As String
    Set cn = CreateObject("ADODB.Connection")
    strConnection = "Provider=Microsoft.Jet.OLEDB.4.0;" & _
        "Data Source=C:\Access\webforums\whiteboard2003.mdb"
    strSql = "SELECT Count(*) FROM MyTable;"
    cn.Open strConnection
    Set rs = cn.Execute(strSql)
    MsgBox rs.fields(0) & " rows in MyTable"
    rs.Close
    Set rs = Nothing
    cn.Close
    Set cn = Nothing
End Sub

If this answer doesn't resolve the problem, edit your question to show us the full connection string you're trying to use and the exact error message you get in response for that connection string.

How can I get terminal output in python?

You can use Popen in subprocess as they suggest.

with os, which is not recomment, it's like below:

import os
a  = os.popen('pwd').readlines()

Is it possible to assign a base class object to a derived class reference with an explicit typecast?

Is it possible to assign a base class object to a derived class reference with an explicit typecast in C#?.

Not only explicit, but also implicit conversions are possible.

C# language doesn't permit such conversion operators, but you can still write them using pure C# and they work. Note that the class which defines the implicit conversion operator (Derived) and the class which uses the operator (Program) must be defined in separate assemblies (e.g. the Derived class is in a library.dll which is referenced by program.exe containing the Program class).

//In library.dll:
public class Base { }

public class Derived {
    [System.Runtime.CompilerServices.SpecialName]
    public static Derived op_Implicit(Base a) {
        return new Derived(a); //Write some Base -> Derived conversion code here
    }

    [System.Runtime.CompilerServices.SpecialName]
    public static Derived op_Explicit(Base a) {
        return new Derived(a); //Write some Base -> Derived conversion code here
    }
}

//In program.exe:
class Program {
    static void Main(string[] args) {
        Derived z = new Base(); //Visual Studio can show squiggles here, but it compiles just fine.
    }
}

When you reference the library using the Project Reference in Visual Studio, VS shows squiggles when you use the implicit conversion, but it compiles just fine. If you just reference the library.dll, there are no squiggles.

HTML table sort

Here is another library.

Changes required are -

  1. Add sorttable js

  2. Add class name sortable to table.

Click the table headers to sort the table accordingly:

_x000D_
_x000D_
<script src="https://www.kryogenix.org/code/browser/sorttable/sorttable.js"></script>

<table class="sortable">
  <tr>
    <th>Name</th>
    <th>Address</th>
    <th>Sales Person</th>
  </tr>

  <tr class="item">
    <td>user:0001</td>
    <td>UK</td>
    <td>Melissa</td>
  </tr>
  <tr class="item">
    <td>user:0002</td>
    <td>France</td>
    <td>Justin</td>
  </tr>
  <tr class="item">
    <td>user:0003</td>
    <td>San Francisco</td>
    <td>Judy</td>
  </tr>
  <tr class="item">
    <td>user:0004</td>
    <td>Canada</td>
    <td>Skipper</td>
  </tr>
  <tr class="item">
    <td>user:0005</td>
    <td>Christchurch</td>
    <td>Alex</td>
  </tr>

</table>
_x000D_
_x000D_
_x000D_

Javascript: How to check if a string is empty?

But for a better check:

if(str === null || str === '')
{
    //enter code here
}

ADB not responding. You can wait more,or kill "adb.exe" process manually and click 'Restart'

1.if your phone system is over 4.2.2 , there will be enter image description here

2.disconnect the USB and try again or restart your phone

3.After after all try , it didn't work. It may be a shortage power supply so try other usb interface on your computer.

I solved the problem doing the first step . anyway have try.

How do I start PowerShell from Windows Explorer?

New-PSDrive -Name HKCR -PSProvider Registry -Root HKEY_CLASSES_ROOT
if(-not (Test-Path -Path "HKCR:\Directory\shell\$KeyName"))
{
    Try
    {
        New-Item -itemType String "HKCR:\Directory\shell\$KeyName" -value "Open PowerShell in this Folder" -ErrorAction Stop
        New-Item -itemType String "HKCR:\Directory\shell\$KeyName\command" -value "$env:SystemRoot\system32\WindowsPowerShell\v1.0\powershell.exe -noexit -command Set-Location '%V'" -ErrorAction Stop
        Write-Host "Successfully!"
     }
     Catch
     {
         Write-Error $_.Exception.Message
     }
}
else
{
    Write-Warning "The specified key name already exists. Type another name and try again."
}

You can download detail script from how to start PowerShell from Windows Explorer

Error on line 2 at column 1: Extra content at the end of the document

You might have output (maybe error/debug output) that precedes your call to

header("Content-type: text/xml");

Therefore, the content being delivered to the browser is not "xml"... that's what the error message is trying to tell you (at least that was the case for me and I had the same error message as you've described).

Best way to Format a Double value to 2 Decimal places

No, there is no better way.

Actually you have an error in your pattern. What you want is:

DecimalFormat df = new DecimalFormat("#.00"); 

Note the "00", meaning exactly two decimal places.

If you use "#.##" (# means "optional" digit), it will drop trailing zeroes - ie new DecimalFormat("#.##").format(3.0d); prints just "3", not "3.00".

How to declare an array of strings in C++?

Instead of that macro, might I suggest this one:

template<typename T, int N>
inline size_t array_size(T(&)[N])
{
    return N;
}

#define ARRAY_SIZE(X)   (sizeof(array_size(X)) ? (sizeof(X) / sizeof((X)[0])) : -1)

1) We want to use a macro to make it a compile-time constant; the function call's result is not a compile-time constant.

2) However, we don't want to use a macro because the macro could be accidentally used on a pointer. The function can only be used on compile-time arrays.

So, we use the defined-ness of the function to make the macro "safe"; if the function exists (i.e. it has non-zero size) then we use the macro as above. If the function does not exist we return a bad value.

Wildcards in jQuery selectors

for classes you can use:

div[class^="jander"]

What's the difference between StaticResource and DynamicResource in WPF?

Important benefit of the dynamic resources

if application startup takes extremely long time, you must use dynamic resources, because static resources are always loaded when the window or app is created, while dynamic resources are loaded when they’re first used.

However, you won’t see any benefit unless your resource is extremely large and complex.

Should I return EXIT_SUCCESS or 0 from main()?

What you return from a program is just a convention.

No, I can't think of any circumstances where "EXIT_SUCCESS" wouldn't be "0".

Personally, I'd recommend "0".

IMHO...

Unit testing with mockito for constructors

Include this line on top of your test class

@PrepareForTest({ First.class })

How to create a inset box-shadow only on one side?

Literally you can't do such a thing, but you should try this CSS trick:

box-shadow: inset 0 3vw 6vw rgba(0,0,0,0.6), inset 0 -3vw 6vw rgba(0,0,0,0.6);

Javascript Click on Element by Class

I'd suggest:

document.querySelector('.rateRecipe.btns-one-small').click();

The above code assumes that the given element has both of those classes; otherwise, if the space is meant to imply an ancestor-descendant relationship:

document.querySelector('.rateRecipe .btns-one-small').click();

The method getElementsByClassName() takes a single class-name (rather than document.querySelector()/document.querySelectorAll(), which take a CSS selector), and you passed two (presumably class-names) to the method.

References:

Save Screen (program) output to a file

The following might be useful (tested on: Linux/Ubuntu 12.04 (Precise Pangolin)):

cat /dev/ttyUSB0

Using the above, you can then do all the re-directions that you need. For example, to dump output to your console while saving to your file, you'd do:

cat /dev/ttyUSB0 | tee console.log

Calling Javascript from a html form

In this bit of code:

getRadioButtonValue(this["whichThing"]))

you're not actually getting a reference to anything. Therefore, your radiobutton in the getradiobuttonvalue function is undefined and throwing an error.

EDIT To get the value out of the radio buttons, grab the JQuery library, and then use this:

  $('input[name=whichThing]:checked').val() 

Edit 2 Due to the desire to reinvent the wheel, here's non-Jquery code:

var t = '';
for (i=0; i<document.myform.whichThing.length; i++) {
     if (document.myform.whichThing[i].checked==true) {
         t = t + document.myform.whichThing[i].value;
     }
}

or, basically, modify the original line of code to read thusly:

getRadioButtonValue(document.myform.whichThing))

Edit 3 Here's your homework:

      function handleClick() {
        alert("Favorite weird creature: " + getRadioButtonValue(document.aye.whichThing));
        //event.preventDefault(); // disable normal form submit behavior
        return false; // prevent further bubbling of event
      }
    </script>
  </head>
<body>
<form name="aye" onSubmit="return handleClick()">
     <input name="Submit"  type="submit" value="Update" />
     Which of the following do you like best?
     <p><input type="radio" name="whichThing" value="slithy toves" />Slithy toves</p>
     <p><input type="radio" name="whichThing" value="borogoves" />Borogoves</p>
     <p><input type="radio" name="whichThing" value="mome raths" />Mome raths</p>
</form>

Notice the following, I've moved the function call to the Form's "onSubmit" event. An alternative would be to change your SUBMIT button to a standard button, and put it in the OnClick event for the button. I also removed the unneeded "JavaScript" in front of the function name, and added an explicit RETURN on the value coming out of the function.

In the function itself, I modified the how the form was being accessed. The structure is: document.[THE FORM NAME].[THE CONTROL NAME] to get at things. Since you renamed your from aye, you had to change the document.myform. to document.aye. Additionally, the document.aye["whichThing"] is just wrong in this context, as it needed to be document.aye.whichThing.

The final bit, was I commented out the event.preventDefault();. that line was not needed for this sample.

EDIT 4 Just to be clear. document.aye["whichThing"] will provide you direct access to the selected value, but document.aye.whichThing gets you access to the collection of radio buttons which you then need to check. Since you're using the "getRadioButtonValue(object)" function to iterate through the collection, you need to use document.aye.whichThing.

See the difference in this method:

function handleClick() {
   alert("Direct Access: " + document.aye["whichThing"]);
   alert("Favorite weird creature: " + getRadioButtonValue(document.aye.whichThing));
   return false; // prevent further bubbling of event
}

View markdown files offline

Consider Strapdown.

Strapdown is Javascript-based solution that renders the markdown content in the browser, which makes it great for offline-viewing. From their own description:

Strapdown.js makes it embarrassingly simple to create elegant Markdown documents. No server-side compilation required.

So rename your .md markdown file to .html, and surround it with:

<xmp theme="united" style="display:none;">
# Markdown content here
…
</xmp>
<script src="http://strapdownjs.com/v/0.2/strapdown.js"></script>

and opening in any browser will show rendered HTML. Added bonus: you can easily change the theme.

AssertionError: View function mapping is overwriting an existing endpoint function: main

Flask requires you to associate a single 'view function' with an 'endpoint'. You are calling Main.as_view('main') twice which creates two different functions (exactly the same functionality but different in memory signature). Short story, you should simply do

main_view_func = Main.as_view('main')

app.add_url_rule('/',
             view_func=main_view_func,
             methods=["GET"])

app.add_url_rule('/<page>/',
             view_func=main_view_func,
             methods=["GET"])

Codeigniter unset session

$session_data = array('username' =>"shashikant");
$this->session->set_userdata('logged_in', $session_data);

$this->session->unset_userdata('logged_in');

How do I upgrade PHP in Mac OS X?

I use this: https://github.com/Homebrew/homebrew-php

The command is:

$ xcode-select --install

$ brew tap homebrew/dupes
$ brew tap homebrew/versions
$ brew tap homebrew/homebrew-php

$ brew options php56
$ brew install php56

Then config in your .bash_profile or .bashrc

# Homebrew PHP CLI
export PATH="$(brew --prefix homebrew/php/php56)/bin:$PATH"

ASP.NET Identity's default Password Hasher - How does it work and is it secure?

I understand the accepted answer, and have up-voted it but thought I'd dump my laymen's answer here...

Creating a hash

  1. The salt is randomly generated using the function Rfc2898DeriveBytes which generates a hash and a salt. Inputs to Rfc2898DeriveBytes are the password, the size of the salt to generate and the number of hashing iterations to perform. https://msdn.microsoft.com/en-us/library/h83s4e12(v=vs.110).aspx
  2. The salt and the hash are then mashed together(salt first followed by the hash) and encoded as a string (so the salt is encoded in the hash). This encoded hash (which contains the salt and hash) is then stored (typically) in the database against the user.

Checking a password against a hash

To check a password that a user inputs.

  1. The salt is extracted from the stored hashed password.
  2. The salt is used to hash the users input password using an overload of Rfc2898DeriveBytes which takes a salt instead of generating one. https://msdn.microsoft.com/en-us/library/yx129kfs(v=vs.110).aspx
  3. The stored hash and the test hash are then compared.

The Hash

Under the covers the hash is generated using the SHA1 hash function (https://en.wikipedia.org/wiki/SHA-1). This function is iteratively called 1000 times (In the default Identity implementation)

Why is this secure

  • Random salts means that an attacker can’t use a pre-generated table of hashs to try and break passwords. They would need to generate a hash table for every salt. (Assuming here that the hacker has also compromised your salt)
  • If 2 passwords are identical they will have different hashes. (meaning attackers can’t infer ‘common’ passwords)
  • Iteratively calling SHA1 1000 times means that the attacker also needs to do this. The idea being that unless they have time on a supercomputer they won’t have enough resource to brute force the password from the hash. It would massively slow down the time to generate a hash table for a given salt.

Why should I use var instead of a type?

As the others have said, there is no difference in the compiled code (IL) when you use either of the following:

var x1 = new object();
object x2 = new object;

I suppose Resharper warns you because it is [in my opinion] easier to read the first example than the second. Besides, what's the need to repeat the name of the type twice?

Consider the following and you'll get what I mean:

KeyValuePair<string, KeyValuePair<string, int>> y1 = new KeyValuePair<string, KeyValuePair<string, int>>("key", new KeyValuePair<string, int>("subkey", 5));

It's way easier to read this instead:

var y2 = new KeyValuePair<string, KeyValuePair<string, int>>("key", new KeyValuePair<string, int>("subkey", 5));

How to parse float with two decimal places in javascript?

@sd Short Answer: There is no way in JS to have Number datatype value with trailing zeros after a decimal.

Long Answer: Its the property of toFixed or toPrecision function of JavaScript, to return the String. The reason for this is that the Number datatype cannot have value like a = 2.00, it will always remove the trailing zeros after the decimal, This is the inbuilt property of Number Datatype. So to achieve the above in JS we have 2 options

  1. Either use data as a string or
  2. Agree to have truncated value with case '0' at the end ex 2.50 -> 2.5. Number Cannot have trailing zeros after decimal

Onclick function based on element id

you can try these:

document.getElementById("RootNode").onclick = function(){/*do something*/};

or

$('#RootNode').click(function(){/*do something*/});

or

$(document).on("click", "#RootNode", function(){/*do something*/});

There is a point for the first two method which is, it matters where in your page DOM, you should put them, the whole DOM should be loaded, to be able to find the, which is usually it gets solved if you wrap them in a window.onload or DOMReady event, like:

//in Vanilla JavaScript
window.addEventListener("load", function(){
     document.getElementById("RootNode").onclick = function(){/*do something*/};
});
//for jQuery
$(document).ready(function(){
    $('#RootNode').click(function(){/*do something*/});
});

In Excel how to get the left 5 characters of each cell in a specified column and put them into a new column

I find, if the data is imported, you may need to use the trim command on top of it, to get your details. =LEFT(TRIM(B2),8) In my case, I was using it to find a IP range. 10.3.44.44 with mask 255.255.255.0, so response is: 10.3.44 Kind of handy.

PHPExcel Make first row bold

Try this

    $objPHPExcel = new PHPExcel();
    $objPHPExcel->getProperties()->setCreator("Maarten Balliauw")
                                 ->setLastModifiedBy("Maarten Balliauw")
                                 ->setTitle("Office 2007 XLSX Test Document")
                                 ->setSubject("Office 2007 XLSX Test Document")
                                 ->setDescription("Test document for Office 2007 XLSX, generated using PHP classes.")
                                 ->setKeywords("office 2007 openxml php")
                                 ->setCategory("Test result file");
    $objPHPExcel->setActiveSheetIndex(0);
    $sheet = $objPHPExcel->getActiveSheet();
    $sheet->setCellValue('A1', 'No');
    $sheet->setCellValue('B1', 'Job ID');
    $sheet->setCellValue('C1', 'Job completed Date');
    $sheet->setCellValue('D1', 'Job Archived Date');
    $styleArray = array(
        'font' => array(
        'bold' => true
        )
    );
    $sheet->getStyle('A1')->applyFromArray($styleArray);
    $sheet->getStyle('B1')->applyFromArray($styleArray);
    $sheet->getStyle('C1')->applyFromArray($styleArray);
    $sheet->getStyle('D1')->applyFromArray($styleArray);
    $sheet->getPageSetup()->setRowsToRepeatAtTopByStartAndEnd(1, 1);
    

This is give me output like below link.(https://www.screencast.com/t/ZkKFHbDq1le)

How do you print in a Go test using the "testing" package?

For testing sometimes I do

fmt.Fprintln(os.Stdout, "hello")

Also, you can print to:

fmt.Fprintln(os.Stderr, "hello)

Correct format specifier to print pointer or address?

You can use %x or %X or %p; all of them are correct.

  • If you use %x, the address is given as lowercase, for example: a3bfbc4
  • If you use %X, the address is given as uppercase, for example: A3BFBC4

Both of these are correct.

If you use %x or %X it's considering six positions for the address, and if you use %p it's considering eight positions for the address. For example:

Using jQuery to see if a div has a child with a certain class

Use the children funcion of jQuery.

$("#text-field").keydown(function(event) {
    if($('#popup').children('p.filled-text').length > 0) {
        console.log("Found");
     }
});

$.children('').length will return the count of child elements which match the selector.

How to create a pulse effect using -webkit-animation - outward rings

Or if you want a ripple pulse effect, you could use this:

http://jsfiddle.net/Fy8vD/3041/

.gps_ring {
     border: 2px solid #fff;
     -webkit-border-radius: 50%;
     height: 18px;
     width: 18px;
     position: absolute;
     left:20px;
    top:214px;
    -webkit-animation: pulsate 1s ease-out;
    -webkit-animation-iteration-count: infinite; 
    opacity: 0.0;
}
.gps_ring:before {
    content:"";
    display:block;
    border: 2px solid #fff;
    -webkit-border-radius: 50%;
    height: 30px;
    width: 30px;
    position: absolute;
    left:-8px;
    top:-8px;
    -webkit-animation: pulsate 1s ease-out;
    -webkit-animation-iteration-count: infinite; 
    -webkit-animation-delay: 0.1s;
    opacity: 0.0;
}
.gps_ring:after {
    content:"";
    display:block;
    border:2px solid #fff;
    -webkit-border-radius: 50%;
    height: 50px;
    width: 50px;
    position: absolute;
    left:-18px;
    top:-18px;
    -webkit-animation: pulsate 1s ease-out;
    -webkit-animation-iteration-count: infinite; 
    -webkit-animation-delay: 0.2s;
    opacity: 0.0;
}
@-webkit-keyframes pulsate {
    0% {-webkit-transform: scale(0.1, 0.1); opacity: 0.0;}
    50% {opacity: 1.0;}
    100% {-webkit-transform: scale(1.2, 1.2); opacity: 0.0;}
}

How to implement a binary tree?

A very quick 'n dirty way of implementing a binary tree using lists. Not the most efficient, nor does it handle nil values all too well. But it's very transparent (at least to me):

def _add(node, v):
    new = [v, [], []]
    if node:
        left, right = node[1:]
        if not left:
            left.extend(new)
        elif not right:
            right.extend(new)
        else:
            _add(left, v)
    else:
        node.extend(new)

def binary_tree(s):
    root = []
    for e in s:
        _add(root, e)
    return root

def traverse(n, order):
    if n:
        v = n[0]
        if order == 'pre':
            yield v
        for left in traverse(n[1], order):
            yield left
        if order == 'in':
            yield v
        for right in traverse(n[2], order):
            yield right
        if order == 'post':
            yield v

Constructing a tree from an iterable:

 >>> tree = binary_tree('A B C D E'.split())
 >>> print tree
 ['A', ['B', ['D', [], []], ['E', [], []]], ['C', [], []]]

Traversing a tree:

 >>> list(traverse(tree, 'pre')), list(traverse(tree, 'in')), list(traverse(tree, 'post'))
 (['A', 'B', 'D', 'E', 'C'],
  ['D', 'B', 'E', 'A', 'C'],
  ['D', 'E', 'B', 'C', 'A'])

How to import existing *.sql files in PostgreSQL 8.4?

in command line first reach the directory where psql is present then write commands like this:

psql [database name] [username]

and then press enter psql asks for password give the user password:

then write

> \i [full path and file name with extension]

then press enter insertion done.

Convert text to columns in Excel using VBA

If someone is facing issue using texttocolumns function in UFT. Please try using below function.

myxl.Workbooks.Open myexcel.xls
myxl.Application.Visible = false `enter code here`
set mysheet = myxl.ActiveWorkbook.Worksheets(1)
Set objRange = myxl.Range("A1").EntireColumn
Set objRange2 = mysheet.Range("A1")
objRange.TextToColumns objRange2,1,1, , , , true

Here we are using coma(,) as delimiter.

How can I format a String number to have commas and round?

You can do the entire conversion in one line, using the following code:

String number = "1000500000.574";
String convertedString = new DecimalFormat("#,###.##").format(Double.parseDouble(number));

The last two # signs in the DecimalFormat constructor can also be 0s. Either way works.

How do I iterate through table rows and cells in JavaScript?

_x000D_
_x000D_
var table=document.getElementById("mytab1");_x000D_
var r=0; //start counting rows in table_x000D_
while(row=table.rows[r++])_x000D_
{_x000D_
  var c=0; //start counting columns in row_x000D_
  while(cell=row.cells[c++])_x000D_
  {_x000D_
    cell.innerHTML='[R'+r+'C'+c+']'; // do sth with cell_x000D_
  }_x000D_
}
_x000D_
<table id="mytab1">_x000D_
  <tr>_x000D_
    <td>A1</td><td>A2</td><td>A3</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>B1</td><td>B2</td><td>B3</td>_x000D_
  </tr>_x000D_
  <tr>_x000D_
    <td>C1</td><td>C2</td><td>C3</td>_x000D_
  </tr>_x000D_
</table>
_x000D_
_x000D_
_x000D_

In each pass through while loop r/c iterator increases and new row/cell object from collection is assigned to row/cell variables. When there's no more rows/cells in collection, false is assigned to row/cell variable and iteration through while loop stops (exits).

What does the SQL Server Error "String Data, Right Truncation" mean and how do I fix it?

This is a known issue of the mssql ODBC driver. According to the Microsoft blog post:

The ColumnSize parameter of SQLBindParameter refers to the number of characters in the SQL type, while BufferLength is the number of bytes in the application's buffer. However, if the SQL data type is varchar(n) or char(n), the application binds the parameter as SQL_C_CHAR or SQL_C_VARCHAR, and the character encoding of the client is UTF-8, you may get a "String data, right truncation" error from the driver even if the value of ColumnSize is aligned with the size of the data type on the server. This error occurs since conversions between character encodings may change the length of the data. For example, a right apostrophe character (U+2019) is encoded in CP-1252 as the single byte 0x92, but in UTF-8 as the 3-byte sequence 0xe2 0x80 0x99.

You can find the full article here.

How to wait until an element is present in Selenium?

public WebElement fluientWaitforElement(WebElement element, int timoutSec, int pollingSec) {

    FluentWait<WebDriver> fWait = new FluentWait<WebDriver>(driver).withTimeout(timoutSec, TimeUnit.SECONDS)
        .pollingEvery(pollingSec, TimeUnit.SECONDS)
        .ignoring(NoSuchElementException.class, TimeoutException.class).ignoring(StaleElementReferenceException.class);

    for (int i = 0; i < 2; i++) {
        try {
            //fWait.until(ExpectedConditions.invisibilityOfElementLocated(By.xpath("//*[@id='reportmanager-wrapper']/div[1]/div[2]/ul/li/span[3]/i[@data-original--title='We are processing through trillions of data events, this insight may take more than 15 minutes to complete.']")));
        fWait.until(ExpectedConditions.visibilityOf(element));
        fWait.until(ExpectedConditions.elementToBeClickable(element));
        } catch (Exception e) {

        System.out.println("Element Not found trying again - " + element.toString().substring(70));
        e.printStackTrace();

        }
    }

    return element;

    }

'const string' vs. 'static readonly string' in C#

You can change the value of a static readonly string only in the static constructor of the class or a variable initializer, whereas you cannot change the value of a const string anywhere.

How to run mvim (MacVim) from Terminal?

There should be a script named mvim in the root of the .bz2 file. Copy this somewhere into your $PATH ( /usr/local/bin would be good ) and you should be sorted.

Apply .gitignore on an existing repository already tracking large number of files

If you added your .gitignore too late, git will continue to track already commited files regardless. To fix this, you can always remove all cached instances of the unwanted files.

First, to check what files are you actually tracking, you can run:

git ls-tree --name-only --full-tree -r HEAD

Let say that you found unwanted files in a directory like cache/ so, it's safer to target that directory instead of all of your files.

So instead of:

git rm -r --cached .

It's safer to target the unwanted file or directory:

git rm -r --cached cache/

Then proceed to add all changes,

git add .

and commit...

git commit -m ".gitignore is now working"

Reference: https://amyetheredge.com/code/13.html

View content of H2 or HSQLDB in-memory database

For H2, you can start a web server within your code during a debugging session if you have a database connection object. You could add this line to your code, or as a 'watch expression' (dynamically):

org.h2.tools.Server.startWebServer(conn);

The server tool will start a web browser locally that allows you to access the database.

CSV file written with Python has blank lines between each row

with open(destPath+'\\'+csvXML, 'a+') as csvFile:
    writer = csv.writer(csvFile, delimiter=';', lineterminator='\r')
    writer.writerows(xmlList)

The "lineterminator='\r'" permit to pass to next row, without empty row between two.

SQL Server 2012 column identity increment jumping from 6 to 1000+ on 7th entry

Got the same problem, found the following bug report in SQL Server 2012 If still relevant see conditions that cause the issue - there are some workarounds there as well (didn't try though). Failover or Restart Results in Reseed of Identity

Lock screen orientation (Android)

I had a similar problem.

When I entered

<activity android:name="MyActivity" android:screenOrientation="landscape"></activity>

In the manifest file this caused that activity to display in landscape. However when I returned to previous activities they displayed in lanscape even though they were set to portrait. However by adding

setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

immediately after the OnCreate section of the target activity resolved the problem. So I now use both methods.

Any implementation of Ordered Set in Java?

Try using java.util.TreeSet that implements SortedSet.

To quote the doc:

"The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used"

Note that add, remove and contains has a time cost log(n).

If you want to access the content of the set as an Array, you can convert it doing:

YourType[] array = someSet.toArray(new YourType[yourSet.size()]); 

This array will be sorted with the same criteria as the TreeSet (natural or by a comparator), and in many cases this will have a advantage instead of doing a Arrays.sort()

Set ANDROID_HOME environment variable in mac

solved my problem on mac 10.14 brew install android-sdk

Single-threaded apartment - cannot instantiate ActiveX control

Go ahead and add [STAThread] to the main entry of your application, this indicates the COM threading model is single-threaded apartment (STA)

example:

static class Program
{
    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main()
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        Application.Run(new WebBrowser());
    }
}

Update multiple rows using select statement

If you have ids in both tables, the following works:

update table2
    set value = (select value from table1 where table1.id = table2.id)

Perhaps a better approach is a join:

update table2
    set value = table1.value
    from table1
    where table1.id = table2.id

Note that this syntax works in SQL Server but may be different in other databases.

How can I read large text files in Python, line by line, without loading it into memory?

All you need to do is use the file object as an iterator.

for line in open("log.txt"):
    do_something_with(line)

Even better is using context manager in recent Python versions.

with open("log.txt") as fileobject:
    for line in fileobject:
        do_something_with(line)

This will automatically close the file as well.

What is the difference between LATERAL and a subquery in PostgreSQL?

First, Lateral and Cross Apply is same thing. Therefore you may also read about Cross Apply. Since it was implemented in SQL Server for ages, you will find more information about it then Lateral.

Second, according to my understanding, there is nothing you can not do using subquery instead of using lateral. But:

Consider following query.

Select A.*
, (Select B.Column1 from B where B.Fk1 = A.PK and Limit 1)
, (Select B.Column2 from B where B.Fk1 = A.PK and Limit 1)
FROM A 

You can use lateral in this condition.

Select A.*
, x.Column1
, x.Column2
FROM A LEFT JOIN LATERAL (
  Select B.Column1,B.Column2,B.Fk1 from B  Limit 1
) x ON X.Fk1 = A.PK

In this query you can not use normal join, due to limit clause. Lateral or Cross Apply can be used when there is not simple join condition.

There are more usages for lateral or cross apply but this is most common one I found.

Anaconda vs. miniconda

Miniconda gives you the Python interpreter itself, along with a command-line tool called conda which operates as a cross-platform package manager geared toward Python packages, similar in spirit to the apt or yum tools that Linux users might be familiar with.

Anaconda includes both Python and conda, and additionally bundles a suite of other pre-installed packages geared toward scientific computing. Because of the size of this bundle, expect the installation to consume several gigabytes of disk space.

Source: Jake VanderPlas's Python Data Science Handbook

bootstrap.min.js:6 Uncaught Error: Bootstrap dropdown require Popper.js

In my case I am using Visual Studio and Nuget packages its failing because have duplicated libraries one in the same folder as jQuery and another in the folder umd. By removing the popper javascript files from the same level as jQuery and refere to the popper.js inside the umd folder fixed my issue and I can see the tooltips correctly.

What HTTP traffic monitor would you recommend for Windows?

Try Wireshark:

Wireshark is the world's foremost network protocol analyzer, and is the de facto (and often de jure) standard across many industries and educational institutions.

There is a bit of a learning curve but it is far and away the best tool available.

Split varchar into separate columns in Oracle

Depends on the consistency of the data - assuming a single space is the separator between what you want to appear in column one vs two:

SELECT SUBSTR(t.column_one, 1, INSTR(t.column_one, ' ')-1) AS col_one,
       SUBSTR(t.column_one, INSTR(t.column_one, ' ')+1) AS col_two
  FROM YOUR_TABLE t

Oracle 10g+ has regex support, allowing more flexibility depending on the situation you need to solve. It also has a regex substring method...

Reference:

Kill a postgresql session/connection

Easier and more updated way is:

  1. Use ps -ef | grep postgres to find the connection #
  2. sudo kill -9 "#" of the connection

Note: There may be identical PID. Killing one kills all.

How to make HTML code inactive with comments

Use:

<!-- This is a comment for an HTML page and it will not display in the browser -->

For more information, I think 3 On SGML and HTML may help you.

How can I convert a std::string to int?

In Windows, you could use:

const std::wstring hex = L"0x13";
const std::wstring dec = L"19";

int ret;
if (StrToIntEx(hex.c_str(), STIF_SUPPORT_HEX, &ret)) {
    std::cout << ret << "\n";
}
if (StrToIntEx(dec.c_str(), STIF_SUPPORT_HEX, &ret)) {
    std::cout << ret << "\n";
}

strtol,stringstream need to specify the base if you need to interpret hexdecimal.

Hibernate: failed to lazily initialize a collection of role, no session or session was closed

I've had this issue especially when entities are mashalled by Jaxb + Jax-rs. I've used the pre-fetch strategy, but I have also found it effective to provide two entities:

  1. Full-blown entity with all collections mapped as EAGER
  2. Simplified entity with most or all collections trimmed out

Common fields and be mapped in @MappedSuperclass and extended by both entity implementations.

Certainly if you always need the collections loaded, then there is no reason to not to EAGER load them. In my case I wanted a stripped down version of the entity to display in a grid.

How can I select all options of multi-select select box on click?

I'm able to make it in a native way @ jsfiddle. Hope it will help.

Post improved answer when it work, and help others.

$(function () { 

    $(".example").multiselect({
                checkAllText : 'Select All',
            uncheckAllText : 'Deselect All',
            selectedText: function(numChecked, numTotal, checkedItems){
              return numChecked + ' of ' + numTotal + ' checked';
            },
            minWidth: 325
    });
    $(".example").multiselect("checkAll");    

});

http://jsfiddle.net/shivasakthi18/25uvnyra/

Attempt to write a readonly database - Django w/ SELinux error

In short, it happens when the application which writes to the sqlite database does not have write permission.

This can be solved in three ways:

  1. Granting ownership of db.sqlite3 file and its parent directory (thereby write access also) to the user using chown (Eg: chown username db.sqlite3 )
  2. Running the webserver (often gunicorn) as root user (run the command sudo -i before you run gunicorn or django runserver)
  3. Allowing read and write access to all users by running command chmod 777 db.sqlite3 (Dangerous option)

Never go for the third option unless you are running the webserver in a local machine or the data in the database is not at all important for you.

Second option is also not recommended. But you can go for it, if you are sure that your application is not vulnerable for code injection attack.

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

Use NuGet (VS 2013+):

The easiest way in any recent version of Visual Studio is to just use the NuGet package manager. (Even VS2013, with the NuGet Package Manager for Visual Studio 2013 extension.)

Right-click on "References" and choose "Manage NuGet Packages...", then just search for Excel.

enter image description here


VS 2012:

Older versions of VS didn't have access to NuGet.

  • Right-click on "References" and select "Add Reference".
  • Select "Extensions" on the left.
  • Look for Microsoft.Office.Interop.Excel.
    (Note that you can just type "excel" into the search box in the upper-right corner.)

VS2012/2013 References


VS 2008 / 2010:

  • Right-click on "References" and select "Add Reference".
  • Select the ".NET" tab.
  • Look for Microsoft.Office.Interop.Excel.

VS 2010 References

Bash script to calculate time elapsed

I find it very clean to use the internal variable "$SECONDS"

SECONDS=0 ; sleep 10 ; echo $SECONDS

Forcing to download a file using PHP

.htaccess Solution

To brute force all CSV files on your server to download, add in your .htaccess file:

AddType application/octet-stream csv

PHP Solution

header('Content-Type: application/csv');
header('Content-Disposition: attachment; filename=example.csv');
header('Pragma: no-cache');
readfile("/path/to/yourfile.csv");

Passing ArrayList from servlet to JSP

public class myActorServlet extends HttpServlet {

    private static final long serialVersionUID = 1L;
    private String name;
    private String user;
    private String pass;
    private String given_table;
    private String tid;
    private String firstname;
    private String lastname;
    private String action;

    @Override
    public void doPost(HttpServletRequest request,
            HttpServletResponse response)
            throws IOException, ServletException {

        response.setContentType("text/html");

        // connecting to database
        Connection con = null;
        Statement stmt = null;
        ResultSet rs = null;

        PrintWriter out = response.getWriter();
        name = request.getParameter("screenName");
        user = request.getParameter("username");
        pass = request.getParameter("password");
        tid = request.getParameter("tid");
        firstname = request.getParameter("firstname");
        lastname = request.getParameter("lastname");
        action = request.getParameter("action");
        given_table = request.getParameter("tableName");

        out.println("<html>");
        out.println("<head>");
        out.println("<title>Servlet JDBC</title>");
        out.println("<link rel=\"stylesheet\" type=\"text/css\" href=\"style.css\">");
        out.println("</head>");
        out.println("<body>");
        out.println("<h1>Hello, " + name + " </h1>");
        out.println("<h1>Servlet JDBC</h1>");

        /////////////////////////
        // init connection object
        String sqlSelect = "SELECT * FROM `" + given_table + "`";
        String sqlInsert = "INSERT INTO `" + given_table + "`(`firstName`, `lastName`) VALUES ('" + firstname + "', '" + lastname + "')";
        String sqlUpdate = "UPDATE `" + given_table + "` SET `firstName`='" + firstname + "',`lastName`='" + lastname + "' WHERE `id`=" + tid + "";
        String sqlDelete = "DELETE FROM `" + given_table + "` WHERE `id` = '" + tid + "'";

        //////////////////////////////////////////////////////////
        out.println(
                "<p>Reading Table Data...Pass to JSP File...Okay<p>");

        ArrayList<Actor> list = new ArrayList<Actor>();
        // connecting to database
        try {
            Class.forName("com.mysql.jdbc.Driver");
            con = DriverManager.getConnection("jdbc:mysql://localhost:3306/javabase", user, pass);
            stmt = con.createStatement();
            rs = stmt.executeQuery(sqlSelect);
            // displaying records

            while (rs.next()) {
                Actor actor = new Actor();
                actor.setId(rs.getInt("id"));
                actor.setLastname(rs.getString("lastname"));
                actor.setFirstname(rs.getString("firstname"));
                list.add(actor);
            }
            request.setAttribute("actors", list);
            RequestDispatcher view = request.getRequestDispatcher("myActors_1.jsp");
            view.forward(request, response);

        } catch (SQLException e) {
            throw new ServletException("Servlet Could not display records.", e);
        } catch (ClassNotFoundException e) {
            throw new ServletException("JDBC Driver not found.", e);
        } finally {
            try {
                if (rs != null) {
                    rs.close();
                    rs = null;
                }
                if (stmt != null) {
                    stmt.close();
                    stmt = null;
                }
                if (con != null) {
                    con.close();
                    con = null;
                }
            } catch (SQLException e) {
            }
        }
        out.println("</body></html>");

        out.close();
    }

}

BackgroundWorker vs background Thread

I knew how to use threads before I knew .NET, so it took some getting used to when I began using BackgroundWorkers. Matt Davis has summarized the difference with great excellence, but I would add that it's more difficult to comprehend exactly what the code is doing, and this can make debugging harder. It's easier to think about creating and shutting down threads, IMO, than it is to think about giving work to a pool of threads.

I still can't comment other people's posts, so forgive my momentary lameness in using an answer to address piers7

Don't use Thread.Abort(); instead, signal an event and design your thread to end gracefully when signaled. Thread.Abort() raises a ThreadAbortException at an arbitrary point in the thread's execution, which can do all kinds of unhappy things like orphan Monitors, corrupt shared state, and so on.
http://msdn.microsoft.com/en-us/library/system.threading.thread.abort.aspx

How to use find command to find all files with extensions from list?

find /path/to/ -type f -print0 | xargs -0 file | grep -i image

This uses the file command to try to recognize the type of file, regardless of filename (or extension).

If /path/to or a filename contains the string image, then the above may return bogus hits. In that case, I'd suggest

cd /path/to
find . -type f -print0 | xargs -0 file --mime-type | grep -i image/

Find the min/max element of an array in JavaScript

I managed to solve my problem this way:

    var strDiv  = "4,8,5,1"
var arrayDivs   = strDiv.split(",")
var str = "";

for (i=0;i<arrayDivs.length;i++)
{
    if (i<arrayDivs.length-1)
    {
      str = str + eval('arrayDivs['+i+']')+',';
    } 
    else if (i==arrayDivs.length-1)
    {
      str = str + eval('arrayDivs['+i+']');
    }
}

str = 'Math.max(' + str + ')';
    var numMax = eval(str);

I hope I have helped.

Best regards.

Is there a way to create key-value pairs in Bash script?

In bash, we use

declare -A name_of_dictonary_variable

so that Bash understands it is a dictionary.

For e.g. you want to create sounds dictionary then,

declare -A sounds

sounds[dog]="Bark"

sounds[wolf]="Howl"

where dog and wolf are "keys", and Bark and Howl are "values".

You can access all values using : echo ${sounds[@]} OR echo ${sounds[*]}

You can access all keys only using: echo ${!sounds[@]}

And if you want any value for a particular key, you can use:

${sounds[dog]}

this will give you value (Bark) for key (Dog).

Is there an "if -then - else " statement in XPath?

according to pkarat's, law you can achieve conditional XPath in version 1.0.

For your case, follow the concept:

concat(substring-before(your-xpath[contains(.,':')],':'),your-xpath[not(contains(.,':'))])

This will definitely work. See how it works. Give two inputs

praba:
karan

For 1st input: it contains : so condition true, string before : will be the output, say praba is your output. 2nd condition will be false so no problems.

For 2nd input: it does not contain : so condition fails, coming to 2nd condition the string doesn't contain : so condition true... therefore output karan will be thrown.

Finally your output would be praba,karan.

How can I extract all values from a dictionary in Python?

Call the values() method on the dict.

Accessing localhost:port from Android emulator

I am using Windows 10 as my development platform, accessing 10.0.2.2:port in my emulator is not working as expected, and the same result for other solutions in this question as well.

After several hours of digging, I found that if you add -writable-system argument to the emulator startup command, things will just work.

You have to start an emulator via command line like below:

 emulator.exe -avd <emulator_name> -writable-system

Then in your emulator, you can access your API service running on host machine, using LAN IP address and binding port:

http://192.168.1.2:<port>

Hope this helps you out.

About start emulator from command line: https://developer.android.com/studio/run/emulator-commandline.

json.net has key method?

JObject.ContainsKey(string propertyName) has been made as public method in 11.0.1 release

Documentation - https://www.newtonsoft.com/json/help/html/M_Newtonsoft_Json_Linq_JObject_ContainsKey.htm

SQL Server GROUP BY datetime ignore hour minute and a select with a date and sum value

SELECT CAST(Datetimefield AS DATE) as DateField, SUM(intfield) as SumField
FROM MyTable
GROUP BY CAST(Datetimefield AS DATE)

I didn't find "ZipFile" class in the "System.IO.Compression" namespace

System.IO.Compression is now available as a nuget package maintained by Microsoft.

To use ZipFile you need to download System.IO.Compression.ZipFile nuget package.

How do I install a Python package with a .whl file?

You can install the .whl file, using pip install filename. Though to use it in this form, it should be in the same directory as your command line, otherwise specify the complete filename, along with its address like pip install C:\Some\PAth\filename.

Also make sure the .whl file is of the same platform as you are using, do a python -V to find out which version of Python you are running and if it is win32 or 64, install the correct version according to it.

When do I need to use AtomicBoolean in Java?

When multiple threads need to check and change the boolean. For example:

if (!initialized) {
   initialize();
   initialized = true;
}

This is not thread-safe. You can fix it by using AtomicBoolean:

if (atomicInitialized.compareAndSet(false, true)) {
    initialize();
}

How does Python return multiple values from a function?

Whenever multiple values are returned from a function in python, does it always convert the multiple values to a list of multiple values and then returns it from the function??

I'm just adding a name and print the result that returns from the function. the type of result is 'tuple'.

  class FigureOut:
   first_name = None
   last_name = None
   def setName(self, name):
      fullname = name.split()
      self.first_name = fullname[0]
      self.last_name = fullname[1]
      self.special_name = fullname[2]
   def getName(self):
      return self.first_name, self.last_name, self.special_name

f = FigureOut()
f.setName("Allen Solly Jun")
name = f.getName()
print type(name)


I don't know whether you have heard about 'first class function'. Python is the language that has 'first class function'

I hope my answer could help you. Happy coding.

What requests do browsers' "F5" and "Ctrl + F5" refreshes generate?

At least in Firefox (v3.5), cache seems to be disabled rather than simply cleared. If there are multiple instances of the same image on a page, it will be transferred multiple times. That is also the case for img tags that are added subsequently via Ajax/JavaScript.

So in case you're wondering why the browser keeps downloading the same little icon a few hundred times on your auto-refresh Ajax site, it's because you initially loaded the page using CTRL-F5.