Programs & Examples On #Pubdate

Iterating through a JSON object

Adding another solution (Python 3) - Iterating over json files in a directory and on each file iterating over all objects and printing relevant fields.

See comments in the code.

import os,json

data_path = '/path/to/your/json/files'  

# 1. Iterate over directory
directory = os.fsencode(data_path)
for file in os.listdir(directory):
    filename = os.fsdecode(file)
    # 2. Take only json files
    if filename.endswith(".json"):
        file_full_path=data_path+filename
        # 3. Open json file 
        with open(file_full_path, encoding='utf-8', errors='ignore') as json_data:
            data_in_file = json.load(json_data, strict=False)
            # 4. Iterate over objects and print relevant fields
            for json_object in data_in_file:
                print("ttl: %s, desc: %s" % (json_object['title'],json_object['description']) )

Is there an XSL "contains" directive?

Sure there is! For instance:

<xsl:if test="not(contains($hhref, '1234'))">
  <li>
    <a href="{$hhref}" title="{$pdate}">
      <xsl:value-of select="title"/>
    </a>
  </li>
</xsl:if>

The syntax is: contains(stringToSearchWithin, stringToSearchFor)

Insert 2 million rows into SQL Server quickly

You can try with SqlBulkCopy class.

Lets you efficiently bulk load a SQL Server table with data from another source.

There is a cool blog post about how you can use it.

How do I get the total number of unique pairs of a set in the database?

I was solving this algorithm and get stuck with the pairs part.

This explanation help me a lot https://betterexplained.com/articles/techniques-for-adding-the-numbers-1-to-100/

So to calculate the sum of series of numbers:

n(n+1)/2

But you need to calculate this

1 + 2 + ... + (n-1)

So in order to get this you can use

n(n+1)/2 - n

that is equal to

n(n-1)/2

How do I view 'git diff' output with my preferred diff tool/ viewer?

You may want to try out xd http://github.com/jiqingtang/xd, which is GUI wrapper for GIT/SVN diff. It is NOT a diff tool itself. You run xd when you want to run git diff or svn diff and it will show you a list of files, a preview window and you can launch any diff tool you like, including tkdiff, xxdiff, gvimdiff, emacs(ediff), xemacs(ediff), meld, diffuse, kompare and kdiff3. You can also run any custom tool.

Unfortunately the tool doesn't support Windows.

Disclosure: I am the author of this tool.

What is the difference between MacVim and regular Vim?

unfortunately, with "mvim -v", ALT plus arrow windows still does not work. I have not found any way to enable it :-(

Substitute multiple whitespace with single whitespace in Python

For completeness, you can also use:

mystring = mystring.strip()  # the while loop will leave a trailing space, 
                  # so the trailing whitespace must be dealt with
                  # before or after the while loop
while '  ' in mystring:
    mystring = mystring.replace('  ', ' ')

which will work quickly on strings with relatively few spaces (faster than re in these situations).

In any scenario, Alex Martelli's split/join solution performs at least as quickly (usually significantly more so).

In your example, using the default values of timeit.Timer.repeat(), I get the following times:

str.replace: [1.4317800167340238, 1.4174888149192384, 1.4163512401715934]
re.sub:      [3.741931446594549,  3.8389395858970374, 3.973777672860706]
split/join:  [0.6530919432498195, 0.6252146571700905, 0.6346594329726258]


EDIT:

Just came across this post which provides a rather long comparison of the speeds of these methods.

Converting byte array to string in javascript

This should work:

String.fromCharCode(...array);

Or

String.fromCodePoint(...array)

Android Get Current timestamp?

From developers blog:

System.currentTimeMillis() is the standard "wall" clock (time and date) expressing milliseconds since the epoch. The wall clock can be set by the user or the phone network (see setCurrentTimeMillis(long)), so the time may jump backwards or forwards unpredictably. This clock should only be used when correspondence with real-world dates and times is important, such as in a calendar or alarm clock application. Interval or elapsed time measurements should use a different clock. If you are using System.currentTimeMillis(), consider listening to the ACTION_TIME_TICK, ACTION_TIME_CHANGED and ACTION_TIMEZONE_CHANGED Intent broadcasts to find out when the time changes.

How to initialize log4j properly?

As explained earlier there are 2 approaches

First one is to just add this line to your main method:

BasicConfigurator.configure();

Second approach is to add this standard log4j.properties file to your classpath:

While taking second approach you need to make sure you initialize the file properly.

Eg.

Properties props = new Properties();

props.load(new FileInputStream("log4j property file path"));

props.setProperty("log4j.appender.File.File", "Folder where you want to store log files/" + "File Name");

Make sure you create required folder to store log files.

VBA EXCEL To Prompt User Response to Select Folder and Return the Path as String Variable

Consider:

Function GetFolder() As String
    Dim fldr As FileDialog
    Dim sItem As String
    Set fldr = Application.FileDialog(msoFileDialogFolderPicker)
    With fldr
        .Title = "Select a Folder"
        .AllowMultiSelect = False
        .InitialFileName = Application.DefaultFilePath
        If .Show <> -1 Then GoTo NextCode
        sItem = .SelectedItems(1)
    End With
NextCode:
    GetFolder = sItem
    Set fldr = Nothing
End Function

This code was adapted from Ozgrid

and as jkf points out, from Mr Excel

Options for HTML scraping?

For Perl, there's WWW::Mechanize.

How do I send a file in Android from a mobile device to server using http?

Wrap it all up in an Async task to avoid threading errors.

public class AsyncHttpPostTask extends AsyncTask<File, Void, String> {

    private static final String TAG = AsyncHttpPostTask.class.getSimpleName();
    private String server;

    public AsyncHttpPostTask(final String server) {
        this.server = server;
    }

    @Override
    protected String doInBackground(File... params) {
        Log.d(TAG, "doInBackground");
        HttpClient http = AndroidHttpClient.newInstance("MyApp");
        HttpPost method = new HttpPost(this.server);
        method.setEntity(new FileEntity(params[0], "text/plain"));
        try {
            HttpResponse response = http.execute(method);
            BufferedReader rd = new BufferedReader(new InputStreamReader(
                    response.getEntity().getContent()));
            final StringBuilder out = new StringBuilder();
            String line;
            try {
                while ((line = rd.readLine()) != null) {
                    out.append(line);
                }
            } catch (Exception e) {}
            // wr.close();
            try {
                rd.close();
            } catch (IOException e) {
                e.printStackTrace();
            }
            // final String serverResponse = slurp(is);
            Log.d(TAG, "serverResponse: " + out.toString());
        } catch (ClientProtocolException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return null;
    }
}

Perl: Use s/ (replace) and return new string

If you wanted to make your own (for semantic reasons or otherwise), see below for an example, though s/// should be all you need:

#!/usr/bin/perl -w    

use strict;     

   main();   

   sub main{    
      my $foo = "blahblahblah";          
      print '$foo: ' , replace("lah","ar",$foo) , "\n";  #$foo: barbarbar

   }        

   sub replace {
      my ($from,$to,$string) = @_;
      $string =~s/$from/$to/ig;                          #case-insensitive/global (all occurrences)

      return $string;
   }

Bootstrap modal not displaying

Delete the data-target attribute from button type. Then add onClick="$('#your_modal_name').modal('show')" in the button tag. I hope it will work as I faced the same problem & I fixed the issue by calling the show class of modal via jQuery.

File uploading with Express 4.0: req.files undefined

Please use below code

app.use(fileUpload());

Element-wise addition of 2 lists?

As described by others, a fast and also space efficient solution is using numpy (np) with it's built-in vector manipulation capability:

1. With Numpy

x = np.array([1,2,3])
y = np.array([2,3,4])
print x+y

2. With built-ins

2.1 Lambda

list1=[1, 2, 3]
list2=[4, 5, 6]
print map(lambda x,y:x+y, list1, list2)

Notice that map() supports multiple arguments.

2.2 zip and list comprehension

list1=[1, 2, 3]
list2=[4, 5, 6]
print [x + y for x, y in zip(list1, list2)]

Why should I use core.autocrlf=true in Git?

For me.

Edit .gitattributes file.

add

*.dll binary

Then everything goes well.

How can I get the request URL from a Java Filter?

Building on another answer on this page,

public static String getCurrentUrlFromRequest(ServletRequest request)
{
   if (! (request instanceof HttpServletRequest))
       return null;

   return getCurrentUrlFromRequest((HttpServletRequest)request);
}

public static String getCurrentUrlFromRequest(HttpServletRequest request)
{
    StringBuffer requestURL = request.getRequestURL();
    String queryString = request.getQueryString();

    if (queryString == null)
        return requestURL.toString();

    return requestURL.append('?').append(queryString).toString();
}

What is the difference between user variables and system variables?

Just recreate the Path variable in users. Go to user variables, highlight path, then new, the type in value. Look on another computer with same version windows. Usually it is in windows 10: Path %USERPROFILE%\AppData\Local\Microsoft\WindowsApps;

How to initialize a dict with keys from a list and empty value in Python?

default_keys = [1, "name"]

To get dictionary with None as values:

dict.fromkeys(default_keys)  

Output :

{1: None, 'name': None}

To get dictionary with default values:

dict.fromkeys(default_keys, [])  

Output :

{1: [], 'name': []}

How to store arbitrary data for some HTML tags

In html, we can store custom attributes with the prefix 'data-' before the attribute name like

<p data-animal='dog'>This animal is a dog.</p>. Check documentation

We can use this property to dynamically set and get attributes using jQuery like: If we have a p tag like

<p id='animal'>This animal is a dog.</p>

Then to create an attribute called 'breed' for the above tag, we can write:

$('#animal').attr('data-breed', 'pug');

To retrieve the data anytime, we can write:

var breedtype = $('#animal').data('breed');

How do I enable TODO/FIXME/XXX task tags in Eclipse?

For me, such tags are enabled by default. You can configure which task tags should be used in the workspace options: Java > Compiler > Task tags

alt text

Check if they are enabled in this location, and that should be enough to have them appear in the Task list (or the Markers view).

Extra note: reinstalling Eclipse won't change anything most of the time if you work on the same workspace. Most settings used by Eclipse are stored in the .metadata folder, in your workspace folder.

A CSS selector to get last visible div

You could select and style this with JavaScript or jQuery, but CSS alone can't do this.

For example, if you have jQuery implemented on the site, you could just do:

var last_visible_element = $('div:visible:last');

Although hopefully you'll have a class/ID wrapped around the divs you're selecting, in which case your code would look like:

var last_visible_element = $('#some-wrapper div:visible:last');

Freeze screen in chrome debugger / DevTools panel for popover inspection?

I tried the other solutions here, they work but I'm lazy so this is my solution

  1. hover over the element to trigger expanded state
  2. ctrl+shift+c
  3. hover over element again
  4. right click
  5. navigate to the debugger

by right clicking it no longer registers mouse event since a context menu pops up, so you can move the mouse away safely

Can not run Java Applets in Internet Explorer 11 using JRE 7u51

I had similar problem and I've solved them using embed tag instead of object. I'm deploying applet using JQuery and:

  • embed works on IE 11, Firefox 26.0,
  • object works on Firefox 26.0, Chrome 32, (on IE 11 was about 10 second delay after each page reload) and
  • applet works on Firefox 26.0, Chrome 32.

I put draft of my script bellow:

var baseurl = location.protocol + "//" + location.host + "//";
var common = 'id="appletid"'; // and more
if (priv.IsIE()) {
    var embedTag = '<embed ' + common +
    ' code="main.java.MyApplet.class"' +
    ' name="' + appletName + '"' +
    ' codebase="' + baseurl + 'Applet"' +
    ' archive="Applet.jar,jna.jar"' +
    ' scriptable="true"' +
    ' mayscript="true"' +
    ' cache_option="Plugin"' +
    ' codebase_lookup="false"' +
    '></embed>';
    appletHtml = embedTag;
} else {
    var objectTag = '<object' + common + '>' +
    '<param name="java_code" value="main/java/MyApplet.class" />' +
    '<param name="mayscript" value="true" />' +
    '<param name="scriptable" value="true" />' +
    '<param name="cache_option" value="Plugin" />' +
    '<param name="codebase_lookup" value="false" />' +
    '<param name="java_codebase" value="' + baseurl + 'Applet" />' +
    '<param name="cache_archive" value="Applet.jar,jna.jar" />' +
    '</object>';
    appletHtml = objectTag;
}
$('body').append(appletHtml);

What is the Regular Expression For "Not Whitespace and Not a hyphen"

Which programming language are you using? May be you just need to escape the backslash like "[^\\s-]"

how to convert object to string in java

Might not be so related to the issue above. However if you are looking for a way to serialize Java object as string, this could come in hand

package pt.iol.security;

import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.ObjectInputStream;
import java.io.ObjectOutputStream;
import java.util.zip.GZIPInputStream;
import java.util.zip.GZIPOutputStream;
import org.apache.commons.codec.binary.Base64;

public class ObjectUtil {

    static final Base64 base64 = new Base64();

    public static String serializeObjectToString(Object object) throws IOException {
        try (
                ByteArrayOutputStream arrayOutputStream = new ByteArrayOutputStream();
                GZIPOutputStream gzipOutputStream = new GZIPOutputStream(arrayOutputStream);
                ObjectOutputStream objectOutputStream = new ObjectOutputStream(gzipOutputStream);) {
            objectOutputStream.writeObject(object);
            objectOutputStream.flush();
            return new String(base64.encode(arrayOutputStream.toByteArray()));
        }
    }

    public static Object deserializeObjectFromString(String objectString) throws IOException, ClassNotFoundException {
        try (
                ByteArrayInputStream arrayInputStream = new ByteArrayInputStream(base64.decode(objectString));
                GZIPInputStream gzipInputStream = new GZIPInputStream(arrayInputStream);
                ObjectInputStream objectInputStream = new ObjectInputStream(gzipInputStream)) {
            return objectInputStream.readObject();
        }
    }
}

Add objects to an array of objects in Powershell

To append to an array, just use the += operator.

$Target += $TargetObject

Also, you need to declare $Target = @() before your loop because otherwise, it will empty the array every loop.

Is it possible to get a list of files under a directory of a website? How?

Yes, you can, but you need a few tools first. You need to know a little about basic coding, FTP clients, port scanners and brute force tools, if it has a .htaccess file.

If not just try tgp.linkurl.htm or html, ie default.html, www/home/siteurl/web/, or wap /index/ default /includes/ main/ files/ images/ pics/ vids/, could be possible file locations on the server, so try all of them so www/home/siteurl/web/includes/.htaccess or default.html. You'll hit a file after a few tries then work off that. Yahoo has a site file viewer too: you can try to scan sites file indexes.

Alternatively, try brutus aet, trin00, trinity.x, or whiteshark airtool to crack the site's FTP login (but it's illegal and I do not condone that).

What is the difference between single-quoted and double-quoted strings in PHP?

PHP strings can be specified not just in two ways, but in four ways.

  1. Single quoted strings will display things almost completely "as is." Variables and most escape sequences will not be interpreted. The exception is that to display a literal single quote, you can escape it with a back slash \', and to display a back slash, you can escape it with another backslash \\ (So yes, even single quoted strings are parsed).
  2. Double quote strings will display a host of escaped characters (including some regexes), and variables in the strings will be evaluated. An important point here is that you can use curly braces to isolate the name of the variable you want evaluated. For example let's say you have the variable $type and you want to echo "The $types are". That will look for the variable $types. To get around this use echo "The {$type}s are" You can put the left brace before or after the dollar sign. Take a look at string parsing to see how to use array variables and such.
  3. Heredoc string syntax works like double quoted strings. It starts with <<<. After this operator, an identifier is provided, then a newline. The string itself follows, and then the same identifier again to close the quotation. You don't need to escape quotes in this syntax.
  4. Nowdoc (since PHP 5.3.0) string syntax works essentially like single quoted strings. The difference is that not even single quotes or backslashes have to be escaped. A nowdoc is identified with the same <<< sequence used for heredocs, but the identifier which follows is enclosed in single quotes, e.g. <<<'EOT'. No parsing is done in nowdoc.

Notes: Single quotes inside of single quotes and double quotes inside of double quotes must be escaped:

$string = 'He said "What\'s up?"';
$string = "He said \"What's up?\"";

Speed:
I would not put too much weight on single quotes being faster than double quotes. They probably are faster in certain situations. Here's an article explaining one manner in which single and double quotes are essentially equally fast since PHP 4.3 (Useless Optimizations toward the bottom, section C). Also, this benchmarks page has a single vs double quote comparison. Most of the comparisons are the same. There is one comparison where double quotes are slower than single quotes.

how to write procedure to insert data in to the table in phpmyadmin?

Try this-

CREATE PROCEDURE simpleproc (IN name varchar(50),IN user_name varchar(50),IN branch varchar(50))
BEGIN
    insert into student (name,user_name,branch) values (name ,user_name,branch);
END

How to set Toolbar text and back arrow color

To change the Toolbar's back icon drawable you can use this:
Add the <item name="toolbarStyle">@style/ToolbarStyle</item> into your Theme.
And here is the ToolbarStyle itself:

<style name="ToolbarStyle" parent="Widget.AppCompat.Toolbar">
    <item name="navigationIcon">@drawable/ic_up_indicator</item>
</style>

Good PHP ORM Library?

Try PHP ADOdb.

I can't say it's the best, because I haven't used the others. But it's fast, it supports Memcached and caching.

And it's waaaay faster than Zend Framework's DB/Select.

CORS: Cannot use wildcard in Access-Control-Allow-Origin when credentials flag is true

This works for me in development but I can't advise that in production, it's just a different way of getting the job done that hasn't been mentioned yet but probably not the best. Anyway here goes:

You can get the origin from the request, then use that in the response header. Here's how it looks in express:

app.use(function(req, res, next) {
  res.header('Access-Control-Allow-Origin', req.header('origin') );
  next();
});

I don't know what that would look like with your python setup but that should be easy to translate.

Cron and virtualenv

Rather than mucking around with virtualenv-specific shebangs, just prepend PATH onto the crontab.

From an activated virtualenv, run these three commands and python scripts should just work:

$ echo "PATH=$PATH" > myserver.cron
$ crontab -l >> myserver.cron
$ crontab myserver.cron

The crontab's first line should now look like this:

PATH=/home/me/virtualenv/bin:/usr/bin:/bin:  # [etc...]

maven command line how to point to a specific settings.xml for a single command?

You can simply use:

mvn --settings YourOwnSettings.xml clean install

or

mvn -s YourOwnSettings.xml clean install

How do you create a Distinct query in HQL

You can simply add GROUP BY instead of Distinct

@Query(value = "from someTableEntity where entityCode in :entityCode" +
            " group by entityCode, entityName, entityType")
List<someTableEntity > findNameByCode(@Param("entityCode") List<String> entityCode);

Reusing a PreparedStatement multiple times

The loop in your code is only an over-simplified example, right?

It would be better to create the PreparedStatement only once, and re-use it over and over again in the loop.

In situations where that is not possible (because it complicated the program flow too much), it is still beneficial to use a PreparedStatement, even if you use it only once, because the server-side of the work (parsing the SQL and caching the execution plan), will still be reduced.

To address the situation that you want to re-use the Java-side PreparedStatement, some JDBC drivers (such as Oracle) have a caching feature: If you create a PreparedStatement for the same SQL on the same connection, it will give you the same (cached) instance.

About multi-threading: I do not think JDBC connections can be shared across multiple threads (i.e. used concurrently by multiple threads) anyway. Every thread should get his own connection from the pool, use it, and return it to the pool again.

Remove IE10's "clear field" X button on certain inputs?

I would apply this rule to all input fields of type text, so it doesn't need to be duplicated later:

input[type=text]::-ms-clear { display: none; }

One can even get less specific by using just:

::-ms-clear { display: none; }

I have used the later even before adding this answer, but thought that most people would prefer to be more specific than that. Both solutions work fine.

Adding items to end of linked list

public static Node insertNodeAtTail(Node head,Object data) {
               Node node = new Node(data);
                 node.next = null;
                if (head == null){
                    return node;
                }
                else{
                    Node temp = head;
                    while(temp.next != null){
                        temp = temp.next;
                    }
                    temp.next = node; 
                    return head;
                }        
    }

Synchronizing a local Git repository with a remote one

If you are talking about syncing a forked repo then you can follow these steps.

How to sync a fork repository from git

  1. check your current git branch

    git branch

  2. checkout to master if you are not on master

    git checkout master

  3. Fetch the upstream repository if you have correct access rights

    git fetch upstream

  4. If you are getting below error then run

    git remote add upstream [email protected]:upstream_clone_repo_url/xyz.git

    fatal: 'upstream/master' does not appear to be a git repository  
    fatal: Could not read from remote repository.
    Please make sure you have the correct access rights and the repository exists.
    
  5. Now run the below command.

    git fetch upstream

  6. Now if you are on master then merge the upstream/master into master branch

    git merge upstream/master

    That's it!!

    Crosscheck via git remote command, more specific git remote -v

    If I also have commit rights to the upstream repo, I can create a local upstream branch and do work that will go upstream there.

Understanding MongoDB BSON Document size limit

To post a clarification answer here for those who get directed here by Google.

The document size includes everything in the document including the subdocuments, nested objects etc.

So a document of:

{
  "_id": {},
  "na": [1, 2, 3],
  "naa": [
    { "w": 1, "v": 2, "b": [1, 2, 3] },
    { "w": 5, "b": 2, "h": [{ "d": 5, "g": 7 }, {}] }
  ]
}

Has a maximum size of 16 MB.

Subdocuments and nested objects are all counted towards the size of the document.

What is the most efficient/quickest way to loop through rows in VBA (excel)?

If you are just looping through 10k rows in column A, then dump the row into a variant array and then loop through that.

You can then either add the elements to a new array (while adding rows when needed) and using Transpose() to put the array onto your range in one move, or you can use your iterator variable to track which row you are on and add rows that way.

Dim i As Long
Dim varray As Variant

varray = Range("A2:A" & Cells(Rows.Count, "A").End(xlUp).Row).Value

For i = 1 To UBound(varray, 1)
    ' do stuff to varray(i, 1)
Next

Here is an example of how you could add rows after evaluating each cell. This example just inserts a row after every row that has the word "foo" in column A. Not that the "+2" is added to the variable i during the insert since we are starting on A2. It would be +1 if we were starting our array with A1.

Sub test()

Dim varray As Variant
Dim i As Long

varray = Range("A2:A10").Value

'must step back or it'll be infinite loop
For i = UBound(varray, 1) To LBound(varray, 1) Step -1
    'do your logic and evaluation here
    If varray(i, 1) = "foo" Then
       'not how to offset the i variable 
       Range("A" & i + 2).EntireRow.Insert
    End If
Next

End Sub

mysql said: Cannot connect: invalid settings. xampp

$cfg['Servers'][$i]['host'] = '127.0.0.1:3307';

if u change port address

Close popup window

Your web_window variable must have gone out of scope when you tried to close the window. Add this line into your _openpageview function to test:

setTimeout(function(){web_window.close();},1000);

Simple int to char[] conversion

Use this. Beware of i's larger than 9, as these will require a char array with more than 2 elements to avoid a buffer overrun.

char c[2];
int i=1;
sprintf(c, "%d", i);

SLF4J: Failed to load class "org.slf4j.impl.StaticLoggerBinder". error

Paste this code to your pom.xml file. It works for me.

<dependency>
    <groupId>org.slf4j</groupId>
    <artifactId>slf4j-simple</artifactId>
    <version>1.6.1</version>
    <scope>test</scope>
</dependency>

What is simplest way to read a file into String?

Yes, you can do this in one line (though for robust IOException handling you wouldn't want to).

String content = new Scanner(new File("filename")).useDelimiter("\\Z").next();
System.out.println(content);

This uses a java.util.Scanner, telling it to delimit the input with \Z, which is the end of the string anchor. This ultimately makes the input have one actual token, which is the entire file, so it can be read with one call to next().

There is a constructor that takes a File and a String charSetName (among many other overloads). These two constructor may throw FileNotFoundException, but like all Scanner methods, no IOException can be thrown beyond these constructors.

You can query the Scanner itself through the ioException() method if an IOException occurred or not. You may also want to explicitly close() the Scanner after you read the content, so perhaps storing the Scanner reference in a local variable is best.

See also

Related questions


Third-party library options

For completeness, these are some really good options if you have these very reputable and highly useful third party libraries:

Guava

com.google.common.io.Files contains many useful methods. The pertinent ones here are:

Apache Commons/IO

org.apache.commons.io.IOUtils also offer similar functionality:

  • String toString(InputStream, String encoding)
    • Using the specified character encoding, gets the contents of an InputStream as a String
  • List readLines(InputStream, String encoding)
    • ... as a (raw) List of String, one entry per line

Related questions

How to install node.js as windows service?

From this blog

Next up, I wanted to host node as a service, just like IIS. This way it’d start up with my machine, run in the background, restart automatically if it crashes and so forth.

This is where nssm, the non-sucking service manager, enters the picture. This tool lets you host a normal .exe as a Windows service.

Here are the commands I used to setup an instance of the your node application as a service, open your cmd like administrator and type following commands:

nssm.exe install service_name c:\your_nodejs_directory\node.exe c:\your_application_directory\server.js
net start service_name

Issue with adding common code as git submodule: "already exists in the index"

Go to the repository folder. Delete relevant submodules from .gitmodules. Select show hidden files. Go to .git folder, delete the submodules from module folder and config.

How to see data from .RData file?

You can also import the data via the "Import Dataset" tab in RStudio, under "global environment." Use the text data option in the drop down list and select your .RData file from the folder. Once the import is complete, it will display the data in the console. Hope this helps.

Chrome violation : [Violation] Handler took 83ms of runtime

"Chrome violations" don't represent errors in either Chrome or your own web app. They are instead warnings to help you improve your app. In this case, Long running JavaScript and took 83ms of runtime are alerting you there's probably an opportunity to speed up your script.

("Violation" is not the best terminology; it's used here to imply the script "violates" a pre-defined guideline, but "warning" or similar would be clearer. These messages first appeared in Chrome in early 2017 and should ideally have a "More info" prompt to elaborate on the meaning and give suggested actions to the developer. Hopefully those will be added in the future.)

How do I remove a library from the arduino environment?

as of 1.8.X IDE C:\Users***\Documents\Arduino\Libraries\

How to define global variable in Google Apps Script

I'm using a workaround by returning a function with an object of my global variables:

function globalVariables(){
  var variables = {
    sheetName: 'Sheet1',
    variable1: 1,
    variable2: 2
  };
  return variables;
}

function functionThatUsesVariable (){
  var sheet =   SpreadsheetApp.getActiveSpreadsheet().getSheetByName(globalVariables().sheetName);
}

How to measure time in milliseconds using ANSI C?

Under windows:

SYSTEMTIME t;
GetLocalTime(&t);
swprintf_s(buff, L"[%02d:%02d:%02d:%d]\t", t.wHour, t.wMinute, t.wSecond, t.wMilliseconds);

Split string on whitespace in Python

Another method through re module. It does the reverse operation of matching all the words instead of spitting the whole sentence by space.

>>> import re
>>> s = "many   fancy word \nhello    \thi"
>>> re.findall(r'\S+', s)
['many', 'fancy', 'word', 'hello', 'hi']

Above regex would match one or more non-space characters.

Is there a native jQuery function to switch elements?

I used a technique like this before. I use it for the connector list on http://mybackupbox.com

// clone element1 and put the clone before element2
$('element1').clone().before('element2').end();

// replace the original element1 with element2
// leaving the element1 clone in it's place
$('element1').replaceWith('element2');

How to find out what character key is pressed?

There are a million duplicates of this question on here, but here goes again anyway:

document.onkeypress = function(evt) {
    evt = evt || window.event;
    var charCode = evt.keyCode || evt.which;
    var charStr = String.fromCharCode(charCode);
    alert(charStr);
};

The best reference on key events I've seen is http://unixpapa.com/js/key.html.

Gridview get Checkbox.Checked value

    foreach (GridViewRow row in GridView1.Rows)
    {
        CheckBox chkbox = (CheckBox)row.FindControl("CheckBox1");
        if (chkbox.Checked == true)
        {
            // Your Code
        }
    }

Classpath including JAR within a JAR

I was about to advise to extract all the files at the same level, then to make a jar out of the result, since the package system should keep them neatly separated. That would be the manual way, I suppose the tools indicated by Steve will do that nicely.

Pandas Split Dataframe into two Dataframes at a specific row

I generally use array split because it's easier simple syntax and scales better with more than 2 partitions.

import numpy as np
partitions = 2
dfs = np.array_split(df, partitions)

np.split(df, [100,200,300], axis=0] wants explicit index numbers which may or may not be desirable.

How do I clone a subdirectory only of a Git repository?

If you never plan to interact with the repository from which you cloned, you can do a full git clone and rewrite your repository using git filter-branch --subdirectory-filter. This way, at least the history will be preserved.

Git command to checkout any branch and overwrite local changes

The new git-switch command (starting in GIT 2.23) also has a flag --discard-changes which should help you. git pull might be necessary afterwards.

Warning: it's still considered to be experimental.

Maven2 property that indicates the parent directory

In an answer to another question I showed how the maven-properties-plugin could be extended to use external property descriptors defined in Maven dependencies.

You could extend that idea to have multiple descriptor jars, each with the environment name as part of the artifactId, containing a ${env}.properties. Then you can use the property to select the appropriate jar and properties file, for example:

<plugin>
  <groupId>org.codehaus.mojo</groupId>
  <artifactId>properties-ext-maven-plugin</artifactId>
  <version>0.0.1</version>
  <executions>
    <execution>
      <id>read-properties</id>
      <phase>initialize</phase>
      <goals>
        <goal>read-project-properties</goal>
      </goals>
    </execution>
  </executions>                              
  <configuration>
    <filePaths>
      <!--assume the descriptor project has a file in the root of the jar -->
      <filePath>${env}.properties</filePath>
    </filePaths>
  </configuration> 
  <dependencies>
    <!-- reference the properties jar for the particular environment-->
    <dependency>
      <groupId>some.descriptor.group</groupId>
      <artifactId>env-${env}-descriptor</artifactId>
      <version>0.0.1</version>
    </dependency>
  </dependencies>
</plugin>

Get the filename of a fileupload in a document through JavaScript

Try document.getElementById("FileUpload1").value this value should have a path for a file to be uploaded, just strip all dirs from that value and you will have file name.

How to downgrade php from 7.1.1 to 5.6 in xampp 7.1.1?

I know it might be late but I'm just adding to Lanti's answer since it's the most popular, I had the same problem as Wouter Vanherck in the comments and I can't comment yet.

What helped for me was instead of just replacing \xampp\apache\conf\extra\httpd-xampp.conf I replaced the whole apache folder. I basically did the same thing with it as with the php folder (steps 2 and 3).

Now the error is fixed and Apache starts just fine.

Does JavaScript guarantee object property order?

In ES2015, it does, but not to what you might think

The order of keys in an object wasn't guaranteed until ES2015. It was implementation-defined.

However, in ES2015 in was specified. Like many things in JavaScript, this was done for compatibility purposes and generally reflected an existing unofficial standard among most JS engines (with you-know-who being an exception).

The order is defined in the spec, under the abstract operation OrdinaryOwnPropertyKeys, which underpins all methods of iterating over an object's own keys. Paraphrased, the order is as follows:

  1. All integer index keys (stuff like "1123", "55", etc) in ascending numeric order.

  2. All string keys which are not integer indices, in order of creation (oldest-first).

  3. All symbol keys, in order of creation (oldest-first).

It's silly to say that the order is unreliable - it is reliable, it's just probably not what you want, and modern browsers implement this order correctly.

Some exceptions include methods of enumerating inherited keys, such as the for .. in loop. The for .. in loop doesn't guarantee order according to the specification.

How to make a back-to-top button using CSS and HTML only?

I used a form with a single submit button. Point the "action" attribute to the ID of the element that needs to be navigated to. Worked for me with just "#top" without needing to define an ID in my stylesheet:

<form action="#top">
    <button type="submit">Back to Top</button>
</form>

Maybe a couple extra lines than is desirable but it's a button, at least. I find this the most concise and descriptive way to go about it.

Slicing of a NumPy 2d array, or how do I extract an mxm submatrix from an nxn array (n>m)?

I have a similar question here: Writting in sub-ndarray of a ndarray in the most pythonian way. Python 2 .

Following the solution of previous post for your case the solution looks like:

columns_to_keep = [1,3] 
rows_to_keep = [1,3]

An using ix_:

x[np.ix_(rows_to_keep, columns_to_keep)] 

Which is:

array([[ 5,  7],
       [13, 15]])

Bootstrap : TypeError: $(...).modal is not a function

I had also faced same error when i was trying to call bootstrap modal from jquery. But this happens because we are using bootstrap modal and for this we need to attach one cdn bootstrap.min.js which is

<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script>

Hope this will help as I missed that when i was trying to call bootstrap modal from jQuery using

$('#button').on('click',function(){ $('#myModal').modal(); });

myModal is the id of Bootstrap modal and you have to give a click event to a button when you call click that button a pop up modal will be displayed.

The server is not responding (or the local MySQL server's socket is not correctly configured) in wamp server

If you use MAMP, make sure it's started. :)

I just ran into this problem, and after starting MAMP the error went away. Not my finest moment.

Error "library not found for" after putting application in AdMob

I was getting similar bugs on library not found. Ultimately this is how I was able to resolve it

  1. Before starting with Xcode Archive, used flutter build iOS
  2. Changed the IOS Deployment Target to a higher target iOS 11.2 . Earlier I had something like 8.0 which was giving all the above errors.
  3. Made sure that the IOS deployment targets in Xcode are same in the Project, Target and Pods

Javascript String to int conversion

Although parseInt is the official function to do this, you can achieve the same with this code:

number*1

The advantage is that you save some characters, which might save bandwidth if your code has to lots of such conversations.

How to copy a selection to the OS X clipboard

if you have the +clipboard option on your Vim installation (you can check with :version) and you are in visual mode you can do "+y This will yank the selection to the buffer + that is the clipboard.

I have added the following maps to my vimrc and it works fine.

vmap <leader>y "+y : With this I can do leader key follow by y to copy to the clipboard in visual mode.

nmap <leader>p "+p : With this I can do leader key follow by p to paste from the clipboard on normal mode.

PD : On Ubuntu I had to install vim-gtk to get the +clipboard option.

To compare two elements(string type) in XSLT?

First of all, the provided long code:

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

is equivalent to this, much shorter code:

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

Now, to your question:

how to compare two elements coming from xml as string

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

$str1 = $str2

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

not($str1 = $str2)

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

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

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

$el1 = $el2

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

not($el1 = $el2)

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

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

 $ns = $str

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

$ns1 = $ns2

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

Therefore, the expression:

OU_NAME='OU_ADDR1'

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

This is obviously not what you want!

Most probably you want:

OU_NAME=OU_ADDR1

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

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

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

Datagrid binding in WPF

Without seeing said object list, I believe you should be binding to the DataGrid's ItemsSource property, not its DataContext.

<DataGrid x:Name="Imported" VerticalAlignment="Top" ItemsSource="{Binding Source=list}"  AutoGenerateColumns="False" CanUserResizeColumns="True">
    <DataGrid.Columns>                
        <DataGridTextColumn Header="ID" Binding="{Binding ID}"/>
        <DataGridTextColumn Header="Date" Binding="{Binding Date}"/>
   </DataGrid.Columns>
</DataGrid>

(This assumes that the element [UserControl, etc.] that contains the DataGrid has its DataContext bound to an object that contains the list collection. The DataGrid is derived from ItemsControl, which relies on its ItemsSource property to define the collection it binds its rows to. Hence, if list isn't a property of an object bound to your control's DataContext, you might need to set both DataContext={Binding list} and ItemsSource={Binding list} on the DataGrid...)

Creating a fixed sidebar alongside a centered Bootstrap 3 grid

As drew_w said, you can find a good example here.

HTML

<div id="wrapper">
    <div id="sidebar-wrapper">
        <ul class="sidebar-nav">
            <li class="sidebar-brand"><a href="#">Home</a></li>
            <li><a href="#">Another link</a></li>
            <li><a href="#">Next link</a></li>
            <li><a href="#">Last link</a></li>
        </ul>
    </div>
    <div id="page-content-wrapper">
        <div class="page-content">
            <div class="container">
                <div class="row">
                    <div class="col-md-12">
                        <!-- content of page -->
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

CSS

#wrapper {
  padding-left: 250px;
  transition: all 0.4s ease 0s;
}

#sidebar-wrapper {
  margin-left: -250px;
  left: 250px;
  width: 250px;
  background: #CCC;
  position: fixed;
  height: 100%;
  overflow-y: auto;
  z-index: 1000;
  transition: all 0.4s ease 0s;
}

#page-content-wrapper {
  width: 100%;
}

.sidebar-nav {
  position: absolute;
  top: 0;
  width: 250px;
  list-style: none;
  margin: 0;
  padding: 0;
}

@media (max-width:767px) {

    #wrapper {
      padding-left: 0;
    }

    #sidebar-wrapper {
      left: 0;
    }

    #wrapper.active {
      position: relative;
      left: 250px;
    }

    #wrapper.active #sidebar-wrapper {
      left: 250px;
      width: 250px;
      transition: all 0.4s ease 0s;
    }

}

JSFIDDLE

Android Device not recognized by adb

Go to prompt command and type "adb devices". If it is empty, then make sure you allowed for "MTP Transfer" or similar and you enabled debugging on your phone.

To enable debugging, follow this tutorial: https://www.kingoapp.com/root-tutorials/how-to-enable-usb-debugging-mode-on-android.htm

Then type "adb devices" again. If a device is listed in there, then it should work now.

Do I need to compile the header files in a C program?

Okay, let's understand the difference between active and passive code.

The active code is the implementation of functions, procedures, methods, i.e. the pieces of code that should be compiled to executable machine code. We store it in .c files and sure we need to compile it.

The passive code is not being execute itself, but it needed to explain the different modules how to communicate with each other. Usually, .h files contains only prototypes (function headers), structures.

An exception are macros, that formally can contain an active pieces, but you should understand that they are using at the very early stage of building (preprocessing) with simple substitution. At the compile time macros already are substituted to your .c file.

Another exception are C++ templates, that should be implemented in .h files. But here is the story similar to macros: they are substituted on the early stage (instantiation) and formally, each other instantiation is another type.

In conclusion, I think, if the modules formed properly, we should never compile the header files.

How to Fill an array from user input C#?

Could you clarify the question a bit? Are you trying to get a fixed number of answers from the user? What data type do you expect -- text, integers, floating-point decimal numbers? That makes a big difference.

If you wanted, for instance, an array of integers, you could ask the user to enter them separated by spaces or commas, then use

string foo = Console.ReadLine();
string[] tokens = foo.Split(",");
List<int> nums = new List<int>();
int oneNum;
foreach(string s in tokens)
{
    if(Int32.TryParse(s, out oneNum))
        nums.Add(oneNum);
}

Of course, you don't necessarily have to go the extra step of converting to ints, but I thought it might help to show how you would.

Cast IList to List

If you have an IList containing interfaces, you can cast it like this:

List to IList

List<Foo> Foos = new List<Foo>(); 
IList<IFoo> IFoos = Foos.ToList<IFoo>();

IList to List

IList<IFoo> IFoos = new List<IFoo>();
List<Foo> Foos = new List<Foo>(IFoos.Select(x => (Foo)x));

This assumes Foo has IFoo interfaced.

git pull error "The requested URL returned error: 503 while accessing"

I received the same error when trying to clone a heroku git repository.

Upon accessing heroku dashboard I saw a warning that the tool was under maintenance, and should come back in a few hours.

Cloning into 'foo-repository'...
remote: !        Heroku has temporarily disabled this feature, please try again shortly. See https://status.heroku.com for current Heroku platform status.
fatal: unable to access 'https://git.heroku.com/foo-repository.git/': The requested URL returned error: 503

If you receive the same error, check the service status

SQL error "ORA-01722: invalid number"

The ORA-01722 error is pretty straightforward. According to Tom Kyte:

We've attempted to either explicity or implicity convert a character string to a number and it is failing.

However, where the problem is is often not apparent at first. This page helped me to troubleshoot, find, and fix my problem. Hint: look for places where you are explicitly or implicitly converting a string to a number. (I had NVL(number_field, 'string') in my code.)

WCF gives an unsecured or incorrectly secured fault error

In my case, it was a setting on the IIS application pool.

Select the application pool --> Advanced Settings --> Set 'Enable 32 Bit Applications' to True.

Then recycle the application pool.

Add SUM of values of two LISTS into new LIST

Here is another way to do it. We make use of the internal __add__ function of python:

class SumList(object):
    def __init__(self, this_list):
        self.mylist = this_list

    def __add__(self, other):
        new_list = []
        zipped_list = zip(self.mylist, other.mylist)
        for item in zipped_list:
            new_list.append(item[0] + item[1])
        return SumList(new_list)

    def __repr__(self):
        return str(self.mylist)

list1 = SumList([1,2,3,4,5])
list2 = SumList([10,20,30,40,50])
sum_list1_list2 = list1 + list2
print(sum_list1_list2)

Output

[11, 22, 33, 44, 55]

java.lang.ClassNotFoundException: sun.jdbc.odbc.JdbcOdbcDriver Exception occurring. Why?

Make sure you have closed your MSAccess file before running the java program.

What's the difference between "2*2" and "2**2" in Python?

Try:

2**3*2

and

2*3*2

to see the difference.

** is the operator for "power of". In your particular operation, 2 to the power of 2 yields the same as 2 times 2.

What is the difference between SQL Server 2012 Express versions?

Scroll down on that page and you'll see:

Express with Tools (with LocalDB) Includes the database engine and SQL Server Management Studio Express)
This package contains everything needed to install and configure SQL Server as a database server. Choose either LocalDB or Express depending on your needs above.

That's the SQLEXPRWT_x64_ENU.exe download.... (WT = with tools)


Express with Advanced Services (contains the database engine, Express Tools, Reporting Services, and Full Text Search)
This package contains all the components of SQL Express. This is a larger download than “with Tools,” as it also includes both Full Text Search and Reporting Services.

That's the SQLEXPRADV_x64_ENU.exe download ... (ADV = Advanced Services)


The SQLEXPR_x64_ENU.exe file is just the database engine - no tools, no Reporting Services, no fulltext-search - just barebones engine.

Select from one table where not in another

To expand on Johan's answer, if the part_num column in the sub-select can contain null values then the query will break.

To correct this, add a null check...

SELECT pm.id FROM r2r.partmaster pm
WHERE pm.id NOT IN 
      (SELECT pd.part_num FROM wpsapi4.product_details pd 
                  where pd.part_num is not null)
  • Sorry but I couldn't add a comment as I don't have the rep!

How to zero pad a sequence of integers in bash so that all have the same width?

Use awk like this:

awk -v start=1 -v end=10 'BEGIN{for (i=start; i<=end; i++) printf("%05d\n", i)}'

OUTPUT:

00001
00002
00003
00004
00005
00006
00007
00008
00009
00010

Update:

As pure bash alternative you can do this to get same output:

for i in {1..10}
do
   printf "%05d\n" $i
done

This way you can avoid using an external program seq which is NOT available on all the flavors of *nix.

Getting the last revision number in SVN?

I think you are looking for

svn info -r HEAD

Can you shell to that command?

You'll probably need to supply login credentials with the repository as well.

Changing background color of text box input not working when empty

You could have the CSS first style the textbox, then have js change it:

<input type="text" style="background-color: yellow;" id="subEmail" />

js:

function changeColor() {
  document.getElementById("subEmail").style.backgroundColor = "Insert color here"
}

Modifying Objects within stream in Java8 while iterating

Instead of creating strange things, you can just filter() and then map() your result.

This is much more readable and sure. Streams will make it in only one loop.

Illegal character in path at index 16

I ran into the same thing with the Bing Map API. URLEncoder just made things worse, but a replaceAll(" ","%20"); did the trick.

How to insert data into SQL Server

I think you lack to pass Connection object to your command object. and it is much better if you will use command and parameters for that.

using (SqlConnection connection = new SqlConnection("ConnectionStringHere"))
{
    using (SqlCommand command = new SqlCommand())
    {
        command.Connection = connection;            // <== lacking
        command.CommandType = CommandType.Text;
        command.CommandText = "INSERT into tbl_staff (staffName, userID, idDepartment) VALUES (@staffName, @userID, @idDepart)";
        command.Parameters.AddWithValue("@staffName", name);
        command.Parameters.AddWithValue("@userID", userId);
        command.Parameters.AddWithValue("@idDepart", idDepart);

        try
        {
            connection.Open();
            int recordsAffected = command.ExecuteNonQuery();
        }
        catch(SqlException)
        {
            // error here
        }
        finally
        {
            connection.Close();
        }
    }
}

How to pass multiple parameters from ajax to mvc controller?

I think you may need to stringify the data using JSON.stringify.

 var data = JSON.stringify({ 
                 'StrContactDetails': Details,
                 'IsPrimary':true
               });

$.ajax({
        type: "POST",
        url: @url.Action("Dhp","SaveEmergencyContact"),
        data: data,
        success: function(){},
        contentType: 'application/json'
    });

So the controller method would look like,

public ActionResult SaveEmergencyContact(string  StrContactDetails, bool IsPrimary)

Getting values from JSON using Python

If you want to iterate over both keys and values of the dictionary, do this:

for key, value in data.items():
    print key, value

What is the difference between ArrayList.clear() and ArrayList.removeAll()?

They serve different purposes. clear() clears an instance of the class, removeAll() removes all the given objects and returns the state of the operation.

Windows could not start the SQL Server (MSSQLSERVER) on Local Computer... (error code 3417)

This usually occurs when the master.mdf or the mastlog.ldf gets corrupt . In order to solve the issue goto the following path C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL , there you will find a folder ” Template Data ” , copy the master.mdf and mastlog.ldf and replace it in C:\Program Files\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQL\Data folder . Thats it . Now start the MS SQL service and you are done

Difference between JE/JNE and JZ/JNZ

JE and JZ are just different names for exactly the same thing: a conditional jump when ZF (the "zero" flag) is equal to 1.

(Similarly, JNE and JNZ are just different names for a conditional jump when ZF is equal to 0.)

You could use them interchangeably, but you should use them depending on what you are doing:

  • JZ/JNZ are more appropriate when you are explicitly testing for something being equal to zero:

    dec  ecx
    jz   counter_is_now_zero
    
  • JE and JNE are more appropriate after a CMP instruction:

    cmp  edx, 42
    je   the_answer_is_42
    

    (A CMP instruction performs a subtraction, and throws the value of the result away, while keeping the flags; which is why you get ZF=1 when the operands are equal and ZF=0 when they're not.)

How do I list one filename per output line in Linux?

Use the -1 option (note this is a "one" digit, not a lowercase letter "L"), like this:

ls -1a

First, though, make sure your ls supports -1. GNU coreutils (installed on standard Linux systems) and Solaris do; but if in doubt, use man ls or ls --help or check the documentation. E.g.:

$ man ls
...
       -1     list one file per line.  Avoid '\n' with -q or -b

What's the difference between an element and a node in XML?

Different W3C specifications define different sets of "Node" types.

Thus, the DOM spec defines the following types of nodes:

  • Document -- Element (maximum of one), ProcessingInstruction, Comment, DocumentType
  • DocumentFragment -- Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference
  • DocumentType -- no children
  • EntityReference -- Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference
  • Element -- Element, Text, Comment, ProcessingInstruction, CDATASection, EntityReference
  • Attr -- Text, EntityReference
  • ProcessingInstruction -- no children
  • Comment -- no children
  • Text -- no children
  • CDATASection -- no children
  • Entity -- Element, ProcessingInstruction, Comment, Text, CDATASection, EntityReference
  • Notation -- no children

The XML Infoset (used by XPath) has a smaller set of nodes:

  • The Document Information Item
  • Element Information Items
  • Attribute Information Items
  • Processing Instruction Information Items
  • Unexpanded Entity Reference Information Items
  • Character Information Items
  • Comment Information Items
  • The Document Type Declaration Information Item
  • Unparsed Entity Information Items
  • Notation Information Items
  • Namespace Information Items
  • XPath has the following Node types:

    • root nodes
    • element nodes
    • text nodes
    • attribute nodes
    • namespace nodes
    • processing instruction nodes
    • comment nodes

    The answer to your question "What is the difference between an element and a node" is:

    An element is a type of node. Many other types of nodes exist and serve different purposes.

    LINQ to SQL - How to select specific columns and return strongly typed list

    The issue was in fact that one of the properties was a relation to another table. I changed my LINQ query so that it could get the same data from a different method without needing to load the entire table.

    Thank you all for your help!

    How to pass parameters using ui-sref in ui-router to controller

    You don't necessarily need to have the parameters inside the URL.

    For instance, with:

    $stateProvider
    .state('home', {
      url: '/',
      views: {
        '': {
          templateUrl: 'home.html',
          controller: 'MainRootCtrl'
    
        },
      },
      params: {
        foo: null,
        bar: null
      }
    })
    

    You will be able to send parameters to the state, using either:

    $state.go('home', {foo: true, bar: 1});
    // or
    <a ui-sref="home({foo: true, bar: 1})">Go!</a>
    

    Of course, if you reload the page once on the home state, you will loose the state parameters, as they are not stored anywhere.

    A full description of this behavior is documented here, under the params row in the state(name, stateConfig) section.

    JavaScript - populate drop down list with array

    Something like this should work:

    var dropdown = document.getElementById("dropdown1");
    if (dropdown) {
        for (var i=0; i < month.length;++i){    
            addOption(dropdown, month[i], month[i]);
        }
    }
    
    addOption = function(selectbox, text, value) {
        var optn = document.createElement("OPTION");
        optn.text = text;
        optn.value = value;
        selectbox.options.add(optn);  
    }
    

    You can refer to this article for more details:
    http://www.plus2net.com/javascript_tutorial/list-adding.php

    Get webpage contents with Python?

    A solution with works with Python 2.X and Python 3.X:

    try:
        # For Python 3.0 and later
        from urllib.request import urlopen
    except ImportError:
        # Fall back to Python 2's urllib2
        from urllib2 import urlopen
    
    url = 'http://hiscore.runescape.com/index_lite.ws?player=zezima'
    response = urlopen(url)
    data = str(response.read())
    

    "make_sock: could not bind to address [::]:443" when restarting apache (installing trac and mod_wsgi)

    You guys are going to laugh at this. I had an extra Listen 443 in ports.conf that shouldn't have been there. Removing that solved this.

    Can I convert a boolean to Yes/No in a ASP.NET GridView

    It's easy with Format()-Function

    Format(aBoolean, "YES/NO")
    

    Please find details here: https://msdn.microsoft.com/en-us/library/aa241719(v=vs.60).aspx

    Android: How can I get the current foreground activity (from a service)?

    Update: this no longer works with other apps' activities as of Android 5.0


    Here's a good way to do it using the activity manager. You basically get the runningTasks from the activity manager. It will always return the currently active task first. From there you can get the topActivity.

    Example here

    There's an easy way of getting a list of running tasks from the ActivityManager service. You can request a maximum number of tasks running on the phone, and by default, the currently active task is returned first.

    Once you have that you can get a ComponentName object by requesting the topActivity from your list.

    Here's an example.

        ActivityManager am = (ActivityManager) this.getSystemService(ACTIVITY_SERVICE);
        List<ActivityManager.RunningTaskInfo> taskInfo = am.getRunningTasks(1);
        Log.d("topActivity", "CURRENT Activity ::" + taskInfo.get(0).topActivity.getClassName());
        ComponentName componentInfo = taskInfo.get(0).topActivity;
        componentInfo.getPackageName();
    

    You will need the following permission on your manifest:

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

    How to get JSON objects value if its name contains dots?

    If json object key/name contains dot......! like

    var myJson = {"my.name":"vikas","my.age":27}
    

    Than you can access like

    myJson["my.name"]
    myJson["my.age"]
    

    Change the icon of the exe file generated from Visual Studio 2010

    To specify an application icon

    1. In Solution Explorer, choose a project node (not the Solution node).
    2. On the menu bar, choose Project, Properties.
    3. When the Project Designer appears, choose the Application tab.
    4. In the Icon list, choose an icon (.ico) file.

    To specify an application icon and add it to your project

    1. In Solution Explorer, choose a project node (not the Solution node).
    2. On the menu bar, choose Project, Properties.
    3. When the Project Designer appears, choose the Application tab.
    4. Near the Icon list, choose the button, and then browse to the location of the icon file that you want.

    The icon file is added to your project as a content file.

    reference : for details see here

    How to restart VScode after editing extension's config?

    Execute the workbench.action.reloadWindow command.

    There are some ways to do so:

    1. Open the command palette (Ctrl + Shift + P) and execute the command:

      >Reload Window    
      
    2. Define a keybinding for the command (for example CTRL+F5) in keybindings.json:

      [
        {
          "key": "ctrl+f5",
          "command": "workbench.action.reloadWindow",
          "when": "editorTextFocus"
        }
      ]
      

    Character Limit on Instagram Usernames

    Limit - 30 symbols. Username must contains only letters, numbers, periods and underscores.

    Selecting only first-level elements in jquery

    You can also use $("ul li:first-child") to only get the direct children of the UL.

    I agree though, you need an ID or something else to identify the main UL otherwise it will just select them all. If you had a div with an ID around the UL the easiest thing to do would be$("#someDiv > ul > li")

    Copy table to a different database on a different SQL Server

    SQL Server(2012) provides another way to generate script for the SQL Server databases with its objects and data. This script can be used to copy the tables’ schema and data from the source database to the destination one in our case.

    1. Using the SQL Server Management Studio, right-click on the source database from the object explorer, then from Tasks choose Generate Scripts. enter image description here
    2. In the Choose objects window, choose Select Specific Database Objects to specify the tables that you will generate script for, then choose the tables by ticking beside each one of it. Click Next. enter image description here
    3. In the Set Scripting Options window, specify the path where you will save the generated script file, and click Advanced. enter image description here
    4. From the appeared Advanced Scripting Options window, specify Schema and Data as Types of Data to Script. You can decide from here if you want to script the indexes and keys in your tables. Click OK. enter image description here Getting back to the Advanced Scripting Options window, click Next.
    5. Review the Summary window and click Next. enter image description here
    6. You can monitor the progress from the Save or Publish Scripts window. If there is no error click Finish and you will find the script file in the specified path. enter image description here

    SQL Scripting method is useful to generate one single script for the tables’ schema and data, including the indexes and keys. But again this method doesn’t generate the tables’ creation script in the correct order if there are relations between the tables.

    Regular Expressions: Is there an AND operator?

    Use AND outside the regular expression. In PHP lookahead operator did not not seem to work for me, instead I used this

    if( preg_match("/^.{3,}$/",$pass1) && !preg_match("/\s{1}/",$pass1))
        return true;
    else
        return false;
    

    The above regex will match if the password length is 3 characters or more and there are no spaces in the password.

    Docker - Cannot remove dead container

    Try kill it and then remove >:) i.e.
    docker kill $(docker ps -q)

    View the change history of a file using Git versioning

    You can also try this which lists the commits that has changed a specific part of a file (Implemented in Git 1.8.4).

    Result returned would be the list of commits that modified this particular part. Command :

    git log --pretty=short -u -L <upperLimit>,<lowerLimit>:<path_to_filename>
    

    where upperLimit is the start_line_number and lowerLimit is the ending_line_number of the file.

    More details at https://www.techpurohit.com/list-some-useful-git-commands

    how to extract only the year from the date in sql server 2008?

    SQL Server Script

    declare @iDate datetime
    set @iDate=GETDATE()
    
    print year(@iDate) -- for Year
    
    print month(@iDate) -- for Month
    
    print day(@iDate) -- for Day
    

    How to execute a JavaScript function when I have its name as a string

    Don't use eval unless you absolutely, positively have no other choice.

    As has been mentioned, using something like this would be the best way to do it:

    window["functionName"](arguments);
    

    That, however, will not work with a namespace'd function:

    window["My.Namespace.functionName"](arguments); // fail
    

    This is how you would do that:

    window["My"]["Namespace"]["functionName"](arguments); // succeeds
    

    In order to make that easier and provide some flexibility, here is a convenience function:

    function executeFunctionByName(functionName, context /*, args */) {
      var args = Array.prototype.slice.call(arguments, 2);
      var namespaces = functionName.split(".");
      var func = namespaces.pop();
      for(var i = 0; i < namespaces.length; i++) {
        context = context[namespaces[i]];
      }
      return context[func].apply(context, args);
    }
    

    You would call it like so:

    executeFunctionByName("My.Namespace.functionName", window, arguments);
    

    Note, you can pass in whatever context you want, so this would do the same as above:

    executeFunctionByName("Namespace.functionName", My, arguments);
    

    How to change the current URL in javascript?

    This is more robust:

    mi = location.href.split(/(\d+)/);
    no = mi.length - 2;
    os = mi[no];
    mi[no]++;
    if ((mi[no] + '').length < os.length) mi[no] = os.match(/0+/) + mi[no];
    location.href = mi.join('');
    

    When the URL has multiple numbers, it will change the last one:

    http://mywebsite.com/8815/1.html
    

    It supports numbers with leading zeros:

    http://mywebsite.com/0001.html
    

    Example

    How do I create a branch?

    Below are the steps to create a branch from trunk using TortoiseSVN in windows machine. This obviously needs TortoiseSVN client to be installed.

    1. Right Click on updated trunk from local windows machine
    2. Select TortoiseSVN
    3. Click branch/Tag
    4. Select the To path in SVN repository. Note that destination URL is updated according to the path and branch name given
    5. Do not create folder inside branches in repository browser
    6. Add branches path. For example, branches/
    7. Add a meaningful log message for your reference
    8. Click Ok, this creates new folder on local system
    9. Checkout the branch created into new folder

    Exception thrown inside catch block - will it be caught again?

    As said above...
    I would add that if you have trouble seeing what is going on, if you can't reproduce the issue in the debugger, you can add a trace before re-throwing the new exception (with the good old System.out.println at worse, with a good log system like log4j otherwise).

    How to solve Notice: Undefined index: id in C:\xampp\htdocs\invmgt\manufactured_goods\change.php on line 21

    if you are getting id from url try

    $id = (isset($_GET['id']) ? $_GET['id'] : '');
    

    if getting from form you need to use POST method cause your form has method="post"

     $id = (isset($_POST['id']) ? $_POST['id'] : '');
    

    For php notices use isset() or empty() to check values exist or not or initialize variable first with blank or a value

    $id= '';
    

    Sublime Text 3, convert spaces to tabs

    You can do replace tabs with spaces in all project files by:

    1. Doing a Replace all Ctrl+Shif+F
    2. Set regex search ^\A(.*)$
    3. Set directory to Your dir
    4. Replace by \1

      enter image description here

    5. This will cause all project files to be opened, with their buffer marked as dirty. With this, you can now optionally enable these next Sublime Text settings, to trim all files trailing white space and ensure a new line at the end of every file.

      You can enabled these settings by going on the menu Preferences -> Settings and adding these contents to your settings file:

      1. "ensure_newline_at_eof_on_save": true,
      2. "trim_trailing_white_space_on_save": true,
    6. Open the Sublime Text console, by going on the menu View -> Show Console (Ctrl+`) and run the command: import threading; threading.Thread( args=(set(),), target=lambda counterset: [ (view.run_command( "expand_tabs", {"set_translate_tabs": True} ), print( "Processing {:>5} view of {:>5}, view id {} {}".format( len( counterset ) + 1, len( window.views() ), view.id(), ( "Finished converting!" if len( counterset ) > len( window.views() ) - 2 else "" ) ) ), counterset.add( len( counterset ) ) ) for view in window.views() ] ).start()
    7. Now, save all changed files by going to the menu File -> Save All

    Access PHP variable in JavaScript

    I'm not sure how necessary this is, and it adds a call to getElementById, but if you're really keen on getting inline JavaScript out of your code, you can pass it as an HTML attribute, namely:

    <span class="metadata" id="metadata-size-of-widget" title="<?php echo json_encode($size_of_widget) ?>"></span>
    

    And then in your JavaScript:

    var size_of_widget = document.getElementById("metadata-size-of-widget").title;
    

    Arduino Tools > Serial Port greyed out

    I had the same problem, with which I struggled for few days, reading all the blog posts, watching videos and finally after i changed my uno board, it worked perfectly well. But before I did that, there were a few things I tried, which I think also had an effect.

    • Extracted the files to opt folder, change the preference --> behavior --> executable text files --> ask what to do. After that, double clicked arduino on the folder, selected run by terminal
    • added user dialout like described in other answers.

    Hope this answer helps you.

    Storyboard doesn't contain a view controller with identifier

    Use your identifier(@"drivingDetails") as Storyboard ID.

    Synchronous Requests in Node.js

    See sync-request: https://github.com/ForbesLindesay/sync-request

    Example:

    var request = require('sync-request');
    var res = request('GET', 'http://example.com');
    console.log(res.getBody());
    

    Disable Buttons in jQuery Mobile

      $(document).ready(function () {
            // Set button disabled
    
            $('#save_info').button("disable");
    
    
            $(".name").bind("change", function (event, ui) {
    
                var edit = $("#your_name").val();
                var edit_surname = $("#your_surname").val();
                console.log(edit);
    
                if (edit != ''&& edit_surname!='') {
                    //name.addClass('hightlight');
                    $('#save_info').button("enable");
                    console.log("enable");
    
                    return false;
                } else {
    
                    $('#save_info').button("disable");
    
                    console.log("disable");
                }
    
            });
    
    
        <ul data-role="listview" data-inset="true" data-split-icon="gear" data-split-theme="d">
            <li>
                <input type="text" name="your_name" id="your_name" class="name" value="" placeholder="Frist Name" /></li>
            <li>
                <input type="text" name="your_surname" id="your_surname"  class="name" value="" placeholder="Last Name" /></li>
            <li>
                <button data-icon="info" href="" data-role="submit" data-inline="true" id="save_info">
                Save</button>
    

    This one work for me you might need to workout the logic, of disable -enable

    Using NotNull Annotation in method argument

    I do this to create my own validation annotation and validator:

    ValidCardType.java(annotation to put on methods/fields)

    @Constraint(validatedBy = {CardTypeValidator.class})
    @Documented
    @Target( { ElementType.ANNOTATION_TYPE, ElementType.METHOD, ElementType.FIELD })
    @Retention(RetentionPolicy.RUNTIME)
    public @interface ValidCardType {
        String message() default "Incorrect card type, should be among: \"MasterCard\" | \"Visa\"";
        Class<?>[] groups() default {};
        Class<? extends Payload>[] payload() default {};
    }
    

    And, the validator to trigger the check: CardTypeValidator.java:

    public class CardTypeValidator implements ConstraintValidator<ValidCardType, String> {
        private static final String[] ALL_CARD_TYPES = {"MasterCard", "Visa"};
    
        @Override
        public void initialize(ValidCardType status) {
        }
        public boolean isValid(String value, ConstraintValidatorContext context) {
            return (Arrays.asList(ALL_CARD_TYPES).contains(value));
        }
    }
    

    You can do something very similar to check @NotNull.

    When does socket.recv(recv_size) return?

    I think you conclusions are correct but not accurate.

    As the docs indicates, socket.recv is majorly focused on the network buffers.

    When socket is blocking, socket.recv will return as long as the network buffers have bytes. If bytes in the network buffers are more than socket.recv can handle, it will return the maximum number of bytes it can handle. If bytes in the network buffers are less than socket.recv can handle, it will return all the bytes in the network buffers.

    Create a custom View by inflating a layout?

    Yes you can do this. RelativeLayout, LinearLayout, etc are Views so a custom layout is a custom view. Just something to consider because if you wanted to create a custom layout you could.

    What you want to do is create a Compound Control. You'll create a subclass of RelativeLayout, add all our your components in code (TextView, etc), and in your constructor you can read the attributes passed in from the XML. You can then pass that attribute to your title TextView.

    http://developer.android.com/guide/topics/ui/custom-components.html

    Git ignore file for Xcode projects

    We did find that even if you add the .gitignore and the .gitattribte the *.pbxproj file can get corrupted. So we have a simple plan.

    Every person that codes in office simply discards the changes made to this file. In the commit we simple mention the files that are added into the source. And then push to the server. Our integration manager than pulls and sees the commit details and adds the files into the resources.

    Once he updates the remote everyone will always have a working copy. In case something is missing then we inform him to add it in and then pull once again.

    This has worked out for us without any issues.

    Http Servlet request lose params from POST body after read it once

    I know I'm late, but this question was still relevant for me and this SO post was one of the top hits in Google. I'm going ahead and post my solution in the hopes that someone else might save couple of hours.

    In my case I needed to log all requests and responses with their bodies. Using Spring Framework the answer is actually quite simple, just use ContentCachingRequestWrapper and ContentCachingResponseWrapper.

    import org.springframework.web.util.ContentCachingRequestWrapper;
    import org.springframework.web.util.ContentCachingResponseWrapper;
    
    import javax.servlet.*;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;
    import java.io.IOException;
    
    public class LoggingFilter implements Filter {
    
        @Override
        public void init(FilterConfig filterConfig) throws ServletException {
    
        }
    
        @Override
        public void destroy() {
    
        }
    
        @Override
        public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain)
                throws IOException, ServletException {
    
            ContentCachingRequestWrapper requestWrapper = new ContentCachingRequestWrapper((HttpServletRequest) request);
            ContentCachingResponseWrapper responseWrapper = new ContentCachingResponseWrapper((HttpServletResponse) response);
    
            try {
                chain.doFilter(requestWrapper, responseWrapper);
            } finally {
    
                String requestBody = new String(requestWrapper.getContentAsByteArray());
                String responseBody = new String(responseWrapper.getContentAsByteArray());
                // Do not forget this line after reading response content or actual response will be empty!
                responseWrapper.copyBodyToResponse();
    
                // Write request and response body, headers, timestamps etc. to log files
    
            }
    
        }
    
    }
    

    jQuery selector for id starts with specific text

    Add a common class to all the div. For example add foo to all the divs.

    $('.foo').each(function () {
       $(this).dialog({
        autoOpen: false,
        show: {
          effect: "blind",
          duration: 1000
        },
        hide: {
          effect: "explode",
          duration: 1000
        }
      });
    });
    

    What exactly is the 'react-scripts start' command?

    As Sagiv b.g. pointed out, the npm start command is a shortcut for npm run start. I just wanted to add a real-life example to clarify it a bit more.

    The setup below comes from the create-react-app github repo. The package.json defines a bunch of scripts which define the actual flow.

    "scripts": {
      "start": "npm-run-all -p watch-css start-js",
      "build": "npm run build-css && react-scripts build",
      "watch-css": "npm run build-css && node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/ --watch --recursive",
      "build-css": "node-sass-chokidar --include-path ./src --include-path ./node_modules src/ -o src/",
      "start-js": "react-scripts start"
    },
    

    For clarity, I added a diagram. enter image description here

    The blue boxes are references to scripts, all of which you could executed directly with an npm run <script-name> command. But as you can see, actually there are only 2 practical flows:

    • npm run start
    • npm run build

    The grey boxes are commands which can be executed from the command line.

    So, for instance, if you run npm start (or npm run start) that actually translate to the npm-run-all -p watch-css start-js command, which is executed from the commandline.

    In my case, I have this special npm-run-all command, which is a popular plugin that searches for scripts that start with "build:", and executes all of those. I actually don't have any that match that pattern. But it can also be used to run multiple commands in parallel, which it does here, using the -p <command1> <command2> switch. So, here it executes 2 scripts, i.e. watch-css and start-js. (Those last mentioned scripts are watchers which monitor file changes, and will only finish when killed.)

    • The watch-css makes sure that the *.scss files are translated to *.cssfiles, and looks for future updates.

    • The start-js points to the react-scripts start which hosts the website in a development mode.

    In conclusion, the npm start command is configurable. If you want to know what it does, then you have to check the package.json file. (and you may want to make a little diagram when things get complicated).

    Using union and count(*) together in SQL query

    If you have supporting indexes, and relatively high counts, something like this may be considerably faster than the solutions suggested:

    SELECT name, MAX(Rcount) + MAX(Acount) AS TotalCount
    FROM (
      SELECT name, COUNT(*) AS Rcount, 0 AS Acount
      FROM Results GROUP BY name
      UNION ALL
      SELECT name, 0, count(*)
      FROM Archive_Results
      GROUP BY name
    ) AS Both
    GROUP BY name
    ORDER BY name;
    

    Angular 2.0 and Modal Dialog

    try to use ng-window, it's allow developer to open and full control multiple windows in single page applications in simple way, No Jquery, No Bootstrap.

    enter image description here

    Avilable Configration

    • Maxmize window
    • Minimize window
    • Custom size,
    • Custom posation
    • the window is dragable
    • Block parent window or not
    • Center the window or not
    • Pass values to chield window
    • Pass values from chield window to parent window
    • Listening to closing chield window in parent window
    • Listen to resize event with your custom listener
    • Open with maximum size or not
    • Enable and disable window resizing
    • Enable and disable maximization
    • Enable and disable minimization

    PowerShell Connect to FTP server and get files

    The AlexFTPS library used in the question seems to be dead (was not updated since 2011).


    With no external libraries

    You can try to implement this without any external library. But unfortunately, neither the .NET Framework nor PowerShell have any explicit support for downloading all files in a directory (let only recursive file downloads).

    You have to implement that yourself:

    • List the remote directory
    • Iterate the entries, downloading files (and optionally recursing into subdirectories - listing them again, etc.)

    Tricky part is to identify files from subdirectories. There's no way to do that in a portable way with the .NET framework (FtpWebRequest or WebClient). The .NET framework unfortunately does not support the MLSD command, which is the only portable way to retrieve directory listing with file attributes in FTP protocol. See also Checking if object on FTP server is file or directory.

    Your options are:

    • If you know that the directory does not contain any subdirectories, use the ListDirectory method (NLST FTP command) and simply download all the "names" as files.
    • Do an operation on a file name that is certain to fail for file and succeeds for directories (or vice versa). I.e. you can try to download the "name".
    • You may be lucky and in your specific case, you can tell a file from a directory by a file name (i.e. all your files have an extension, while subdirectories do not)
    • You use a long directory listing (LIST command = ListDirectoryDetails method) and try to parse a server-specific listing. Many FTP servers use *nix-style listing, where you identify a directory by the d at the very beginning of the entry. But many servers use a different format. The following example uses this approach (assuming the *nix format)
    function DownloadFtpDirectory($url, $credentials, $localPath)
    {
        $listRequest = [Net.WebRequest]::Create($url)
        $listRequest.Method = [System.Net.WebRequestMethods+Ftp]::ListDirectoryDetails
        $listRequest.Credentials = $credentials
    
        $lines = New-Object System.Collections.ArrayList
    
        $listResponse = $listRequest.GetResponse()
        $listStream = $listResponse.GetResponseStream()
        $listReader = New-Object System.IO.StreamReader($listStream)
        while (!$listReader.EndOfStream)
        {
            $line = $listReader.ReadLine()
            $lines.Add($line) | Out-Null
        }
        $listReader.Dispose()
        $listStream.Dispose()
        $listResponse.Dispose()
    
        foreach ($line in $lines)
        {
            $tokens = $line.Split(" ", 9, [StringSplitOptions]::RemoveEmptyEntries)
            $name = $tokens[8]
            $permissions = $tokens[0]
    
            $localFilePath = Join-Path $localPath $name
            $fileUrl = ($url + $name)
    
            if ($permissions[0] -eq 'd')
            {
                if (!(Test-Path $localFilePath -PathType container))
                {
                    Write-Host "Creating directory $localFilePath"
                    New-Item $localFilePath -Type directory | Out-Null
                }
    
                DownloadFtpDirectory ($fileUrl + "/") $credentials $localFilePath
            }
            else
            {
                Write-Host "Downloading $fileUrl to $localFilePath"
    
                $downloadRequest = [Net.WebRequest]::Create($fileUrl)
                $downloadRequest.Method = [System.Net.WebRequestMethods+Ftp]::DownloadFile
                $downloadRequest.Credentials = $credentials
    
                $downloadResponse = $downloadRequest.GetResponse()
                $sourceStream = $downloadResponse.GetResponseStream()
                $targetStream = [System.IO.File]::Create($localFilePath)
                $buffer = New-Object byte[] 10240
                while (($read = $sourceStream.Read($buffer, 0, $buffer.Length)) -gt 0)
                {
                    $targetStream.Write($buffer, 0, $read);
                }
                $targetStream.Dispose()
                $sourceStream.Dispose()
                $downloadResponse.Dispose()
            }
        }
    }
    

    Use the function like:

    $credentials = New-Object System.Net.NetworkCredential("user", "mypassword") 
    $url = "ftp://ftp.example.com/directory/to/download/"
    DownloadFtpDirectory $url $credentials "C:\target\directory"
    

    The code is translated from my C# example in C# Download all files and subdirectories through FTP.


    Using 3rd party library

    If you want to avoid troubles with parsing the server-specific directory listing formats, use a 3rd party library that supports the MLSD command and/or parsing various LIST listing formats. And ideally with a support for downloading all files from a directory or even recursive downloads.

    For example with WinSCP .NET assembly you can download whole directory with a single call to Session.GetFiles:

    # Load WinSCP .NET assembly
    Add-Type -Path "WinSCPnet.dll"
    
    # Setup session options
    $sessionOptions = New-Object WinSCP.SessionOptions -Property @{
        Protocol = [WinSCP.Protocol]::Ftp
        HostName = "ftp.example.com"
        UserName = "user"
        Password = "mypassword"
    }
    
    $session = New-Object WinSCP.Session
    
    try
    {
        # Connect
        $session.Open($sessionOptions)
    
        # Download files
        $session.GetFiles("/directory/to/download/*", "C:\target\directory\*").Check()
    }
    finally
    {
        # Disconnect, clean up
        $session.Dispose()
    }    
    

    Internally, WinSCP uses the MLSD command, if supported by the server. If not, it uses the LIST command and supports dozens of different listing formats.

    The Session.GetFiles method is recursive by default.

    (I'm the author of WinSCP)

    How to detect if CMD is running as Administrator/has elevated privileges?

    I know I'm really late to this party, but here's my one liner to determine admin-hood.

    It doesn't rely on error level, just on systeminfo:

    for /f "tokens=1-6" %%a in ('"net user "%username%" | find /i "Local Group Memberships""') do (set admin=yes & if not "%%d" == "*Administrators" (set admin=no) & echo %admin%)
    

    It returns either yes or no, depending on the user's admin status...

    It also sets the value of the variable "admin" to equal yes or no accordingly.

    VB.NET 'If' statement with 'Or' conditional has both sides evaluated?

    It's your "fault" in that that's how Or is defined, so it's the behaviour you should expect:

    In a Boolean comparison, the Or operator always evaluates both expressions, which could include making procedure calls. The OrElse Operator (Visual Basic) performs short-circuiting, which means that if expression1 is True, then expression2 is not evaluated.

    But you don't have to endure it. You can use OrElse to get short-circuiting behaviour.

    So you probably want:

    If (example Is Nothing OrElse Not example.Item = compare.Item) Then
        'Proceed
    End If
    

    I can't say it reads terribly nicely, but it should work...

    How to find Current open Cursors in Oracle

    This could work:

    SELECT    sql_text "SQL Query", 
              Count(*) AS "Open Cursors" 
    FROM      v$open_cursor 
    GROUP BY  sql_text 
    HAVING    Count(*) > 2 
    ORDER BY  Count(*) DESC; 
    

    Javascript: formatting a rounded number to N decimals

    If you do not really care about rounding, just added a toFixed(x) and then removing trailing 0es and the dot if necessary. It is not a fast solution.

    function format(value, decimals) {
        if (value) {
            value = value.toFixed(decimals);            
        } else {
            value = "0";
        }
        if (value.indexOf(".") < 0) { value += "."; }
        var dotIdx = value.indexOf(".");
        while (value.length - dotIdx <= decimals) { value += "0"; } // add 0's
    
        return value;
    }
    

    MySQL: Grant **all** privileges on database

    Hello I used this code to have the super user in mysql

    GRANT EXECUTE, PROCESS, SELECT, SHOW DATABASES, SHOW VIEW, ALTER, ALTER ROUTINE,
        CREATE, CREATE ROUTINE, CREATE TEMPORARY TABLES, CREATE VIEW, DELETE, DROP,
        EVENT, INDEX, INSERT, REFERENCES, TRIGGER, UPDATE, CREATE USER, FILE,
        LOCK TABLES, RELOAD, REPLICATION CLIENT, REPLICATION SLAVE, SHUTDOWN,
        SUPER
            ON *.* TO mysql@'%'
        WITH GRANT OPTION;
    

    and then

    FLUSH PRIVILEGES;
    

    How can I check if string contains characters & whitespace, not just whitespace?

    if (/^\s+$/.test(myString))
    {
          //string contains only whitespace
    }
    

    this checks for 1 or more whitespace characters, if you it to also match an empty string then replace + with *.

    ReactJS call parent method

    React 16+

    Child Component

    import React from 'react'
    
    class ChildComponent extends React.Component
    {
        constructor(props){
            super(props);       
        }
    
        render()
        {
            return <div>
                <button onClick={()=>this.props.greetChild('child')}>Call parent Component</button>
            </div>
        }
    }
    
    export default ChildComponent;
    

    Parent Component

    import React from "react";
    import ChildComponent from "./childComponent";
    
    class MasterComponent extends React.Component
    {
        constructor(props)
        {
            super(props);
            this.state={
                master:'master',
                message:''
            }
            this.greetHandler=this.greetHandler.bind(this);
        }
    
        greetHandler(childName){
            if(typeof(childName)=='object')
            {
                this.setState({            
                    message:`this is ${this.state.master}`
                });
            }
            else
            {
                this.setState({            
                    message:`this is ${childName}`
                });
            }
    
        }
    
        render()
        {
            return <div>
               <p> {this.state.message}</p>
                <button onClick={this.greetHandler}>Click Me</button>
                <ChildComponent greetChild={this.greetHandler}></ChildComponent>
            </div>
        }
    }
    export default  MasterComponent;
    

    jQuery checkbox change and click event

    Most of the answers won't catch it (presumably) if you use <label for="cbId">cb name</label>. This means when you click the label it will check the box instead of directly clicking on the checkbox. (Not exactly the question, but various search results tend to come here)

    <div id="OuterDivOrBody">
        <input type="checkbox" id="checkbox1" />
        <label for="checkbox1">Checkbox label</label>
        <br />
        <br />
        The confirm result:
        <input type="text" id="textbox1" />
    </div>
    

    In which case you could use:

    Earlier versions of jQuery:

    $('#OuterDivOrBody').delegate('#checkbox1', 'change', function () {
        // From the other examples
        if (!this.checked) {
            var sure = confirm("Are you sure?");
            this.checked = !sure;
            $('#textbox1').val(sure.toString());
        }
    });
    

    JSFiddle example with jQuery 1.6.4

    jQuery 1.7+

    $('#checkbox1').on('change', function() { 
        // From the other examples
        if (!this.checked) {
            var sure = confirm("Are you sure?");
            this.checked = !sure;
            $('#textbox1').val(sure.toString());
        }
    });
    

    JSFiddle example with the latest jQuery 2.x

    • Added jsfiddle examples and the html with the clickable checkbox label

    Angular 2 / 4 / 5 not working in IE11

    You'll need to adjust the polyfills.ts file for your target browsers by uncommenting the appropriate sections.

    /** IE9, IE10 and IE11 requires all of the following polyfills. **/
    import 'core-js/es6/symbol';
    import 'core-js/es6/object';
    import 'core-js/es6/function';
    import 'core-js/es6/parse-int';
    import 'core-js/es6/parse-float';
    import 'core-js/es6/number';
    import 'core-js/es6/math';
    import 'core-js/es6/string';
    import 'core-js/es6/date';
    import 'core-js/es6/array';
    import 'core-js/es6/regexp';
    import 'core-js/es6/map';
    import 'core-js/es6/weak-map';
    import 'core-js/es6/set';
    

    Defining lists as global variables in Python

    When you assign a variable (x = ...), you are creating a variable in the current scope (e.g. local to the current function). If it happens to shadow a variable fron an outer (e.g. global) scope, well too bad - Python doesn't care (and that's a good thing). So you can't do this:

    x = 0
    def f():
        x = 1
    f()
    print x #=>0
    

    and expect 1. Instead, you need do declare that you intend to use the global x:

    x = 0
    def f():
        global x
        x = 1
    f()
    print x #=>1
    

    But note that assignment of a variable is very different from method calls. You can always call methods on anything in scope - e.g. on variables that come from an outer (e.g. the global) scope because nothing local shadows them.

    Also very important: Member assignment (x.name = ...), item assignment (collection[key] = ...), slice assignment (sliceable[start:end] = ...) and propably more are all method calls as well! And therefore you don't need global to change a global's members or call it methods (even when they mutate the object).

    Easy way to convert Iterable to Collection

    This is not an answer to your question but I believe it is the solution to your problem. The interface org.springframework.data.repository.CrudRepository does indeed have methods that return java.lang.Iterable but you should not use this interface. Instead use sub interfaces, in your case org.springframework.data.mongodb.repository.MongoRepository. This interface has methods that return objects of type java.util.List.

    How to install mechanize for Python 2.7?

    You need to install the python-setuptools package:

    apt-get install python-setuptools on Debian-ish systems yum install python-setuptools on Redhat-ish systems

    Use sudo if applicable

    How to schedule a stored procedure in MySQL

    If you're open to out-of-the-DB solution: You could set up a cron job that runs a script that will itself call the procedure.

    add commas to a number in jQuery

    Another way to do it:

    function addCommas(n){
      var s = "",
          r;
    
      while (n) {
        r = n % 1000;
        s = r + s;
        n = (n - r)/1000;
        s = (n ? "," : "") + s;
      }
    
      return s;
    }
    
    alert(addCommas(12345678));
    

    How to select distinct rows in a datatable and store into an array

    DataView view = new DataView(table);
    DataTable distinctValues = view.ToTable(true, "Column1", "Column2" ...);
    

    What is the purpose of mvnw and mvnw.cmd files?

    Command mvnw uses Maven that is by default downloaded to ~/.m2/wrapper on the first use.

    URL with Maven is specified in each project at .mvn/wrapper/maven-wrapper.properties:

    distributionUrl=https://repo1.maven.org/maven2/org/apache/maven/apache-maven/3.3.9/apache-maven-3.3.9-bin.zip
    

    To update or change Maven version invoke the following (remember about --non-recursive for multi-module projects):

    ./mvnw io.takari:maven:wrapper -Dmaven=3.3.9 
    

    or just modify .mvn/wrapper/maven-wrapper.properties manually.

    To generate wrapper from scratch using Maven (you need to have it already in PATH run:

    mvn io.takari:maven:wrapper -Dmaven=3.3.9 
    

    Python: How to get values of an array at certain index positions?

    Just index using you ind_pos

    ind_pos = [1,5,7]
    print (a[ind_pos]) 
    [88 85 16]
    
    
    In [55]: a = [0,88,26,3,48,85,65,16,97,83,91]
    
    In [56]: import numpy as np
    
    In [57]: arr = np.array(a)
    
    In [58]: ind_pos = [1,5,7]
    
    In [59]: arr[ind_pos]
    Out[59]: array([88, 85, 16])
    

    Validate that text field is numeric usiung jQuery

    Regex isn't needed, nor is plugins

    if (isNaN($('#Field').val() / 1) == false) {
        your code here
    }
    

    PHPExcel - set cell type before writing a value in it

    For Numbers with leading zeroes and comma separated:

    You can put 'A' to affect the entire column'.

    $objPHPExcel->getActiveSheet()->getStyle('A1')->getNumberFormat()->setFormatCode(PHPExcel_Style_NumberFormat::FORMAT_NUMBER_COMMA_SEPARATED1);
    

    Then you can write to the cell as you normally would.

    Using Custom Domains With IIS Express

    Just in case if someone may need...

    My requirement was:

    • SSL enabled
    • Custom domain
    • Running in (default) port: 443

    Setup this URL in IISExpress: http://my.customdomain.com

    To setup this I used following settings:

    Project Url: http://localhost:57400

    Start URL: http://my.customdomain.com

    /.vs/{solution-name}/config/applicationhost.config settings:

    <site ...>
        <application>
            ...
        </application>
        <bindings>
            <binding protocol="http" bindingInformation="*:57400:" />
            <binding protocol="https" bindingInformation="*:443:my.customdomain.com" />
        </bindings>
    </site>
    

    The type 'string' must be a non-nullable type in order to use it as parameter T in the generic type or method 'System.Nullable<T>'

    Please note that in upcoming version of C# which is 8, the answers are not true.

    All the reference types are non-nullable by default and you can actually do the following:

    public string? MyNullableString; 
    this.MyNullableString = null; //Valid
    

    However,

    public string MyNonNullableString; 
    this.MyNonNullableString = null; //Not Valid and you'll receive compiler warning. 
    

    The important thing here is to show the intent of your code. If the "intent" is that the reference type can be null, then mark it so otherwise assigning null value to non-nullable would result in compiler warning.

    More info

    How do I get the name of a Ruby class?

    If you want to get a class name from inside a class method, class.name or self.class.name won't work. These will just output Class, since the class of a class is Class. Instead, you can just use name:

    module Foo
      class Bar
        def self.say_name
          puts "I'm a #{name}!"
        end
      end
    end
    
    Foo::Bar.say_name
    

    output:

    I'm a Foo::Bar!
    

    Unit Testing: DateTime.Now

    You can change the class you are testing to use a Func<DateTime> which will be passed through it's constructor parameters, so when you create instance of the class in real code, you can pass () => DateTime.UtcNow to the Func<DateTime> parameter, and on the test, you can pass the time you wish to test.

    For example:

        [TestMethod]
        public void MyTestMethod()
        {
            var instance = new MyClass(() => DateTime.MinValue);
            Assert.AreEqual(instance.MyMethod(), DateTime.MinValue);
        } 
    
        public void RealWorldInitialization()
        {
            new MyClass(() => DateTime.UtcNow);
        }
    
        class MyClass
        {
            private readonly Func<DateTime> _utcTimeNow;
    
            public MyClass(Func<DateTime> UtcTimeNow)
            {
                _utcTimeNow = UtcTimeNow;
            }
    
            public DateTime MyMethod()
            {
                return _utcTimeNow();
            }
        }
    

    Vertical Tabs with JQuery?

    I wouldn't expect vertical tabs to need different Javascript from horizontal tabs. The only thing that would be different is the CSS for presenting the tabs and content on the page. JS for tabs generally does no more than show/hide/maybe load content.

    Best way to incorporate Volley (or other library) into Android Studio project

    UPDATE:

    compile 'com.android.volley:volley:1.0.0'
    

    OLD ANSWER: You need the next in your build.gradle of your app module:

    dependencies {
            compile 'com.mcxiaoke.volley:library:1.0.19'
            (Rest of your dependencies)
    
        }
    

    This is not the official repo but is a highly trusted one.

    Compile error: package javax.servlet does not exist

    place jakarta and delete javax

    if you download servlet.api.jar :

    NOTICE : this answer every time is not correct ( can be javax in JEE )

    Correct

    jakarta.servlet.*;

    Incorrect

    javax.servlet.*;

    else :

    place jar files into JAVA_HOME/jre/lib/ext

    Difference between numeric, float and decimal in SQL Server

    Although the question didn't include the MONEY data type some people coming across this thread might be tempted to use the MONEY data type for financial calculations.

    Be wary of the MONEY data type, it's of limited precision.

    There is a lot of good information about it in the answers to this Stackoverflow question:

    Should you choose the MONEY or DECIMAL(x,y) datatypes in SQL Server?

    How to update npm

    nvm install-latest-npm
    

    if you happen to use nvm

    take(1) vs first()

    Here are three Observables A, B, and C with marble diagrams to explore the difference between first, take, and single operators:

    first vs take vs single operators comparison

    * Legend:
    --o-- value
    ----! error
    ----| completion

    Play with it at https://thinkrx.io/rxjs/first-vs-take-vs-single/ .

    Already having all the answers, I wanted to add a more visual explanation

    Hope it helps someone

    How to use subprocess popen Python

    Using Subprocess in easiest way!!

    import subprocess
    cmd = 'pip install numpy'.split()  #replace with your command
    subprocess.call(cmd)
    

    How to set JFrame to appear centered, regardless of monitor resolution?

    You can use this method, which allows the JFrame to be centered and full screen at the same time.

    yourframe.setExtendedState(JFrame.MAXIMIZED_BOTH);
    

    Converting String to Int using try/except in Python

    Firstly, try / except are not functions, but statements.

    To convert a string (or any other type that can be converted) to an integer in Python, simply call the int() built-in function. int() will raise a ValueError if it fails and you should catch this specifically:

    In Python 2.x:

    >>> for value in '12345', 67890, 3.14, 42L, 0b010101, 0xFE, 'Not convertible':
    ...     try:
    ...         print '%s as an int is %d' % (str(value), int(value))
    ...     except ValueError as ex:
    ...         print '"%s" cannot be converted to an int: %s' % (value, ex)
    ...
    12345 as an int is 12345
    67890 as an int is 67890
    3.14 as an int is 3
    42 as an int is 42
    21 as an int is 21
    254 as an int is 254
    "Not convertible" cannot be converted to an int: invalid literal for int() with base 10: 'Not convertible'
    

    In Python 3.x

    the syntax has changed slightly:

    >>> for value in '12345', 67890, 3.14, 42, 0b010101, 0xFE, 'Not convertible':
    ...     try:
    ...         print('%s as an int is %d' % (str(value), int(value)))
    ...     except ValueError as ex:
    ...         print('"%s" cannot be converted to an int: %s' % (value, ex))
    ...
    12345 as an int is 12345
    67890 as an int is 67890
    3.14 as an int is 3
    42 as an int is 42
    21 as an int is 21
    254 as an int is 254
    "Not convertible" cannot be converted to an int: invalid literal for int() with base 10: 'Not convertible'
    

    Error in setting JAVA_HOME

    JAVA_HOME should point to jdk directory and not to jre directory. Also JAVA_HOME should point to the home jdk directory and not to jdk/bin directory.

    Assuming that you have JDK installed in your program files directory then you need to set the JAVA_HOME like this:

    JAVA_HOME="C:\Program Files\Java\jdkxxx"
    

    xxx is the jdk version

    Follow this link to learn more about setting JAVA_HOME:

    http://docs.oracle.com/cd/E19182-01/820-7851/inst_cli_jdk_javahome_t/index.html

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

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

    Best Practice: Software Versioning

    I use this rule for my applications:

    x.y.z

    Where:

    • x = main version number, 1-~.
    • y = feature number, 0-9. Increase this number if the change contains new features with or without bug fixes.
    • z = hotfix number, 0-~. Increase this number if the change only contains bug fixes.

    Example:

    • For new application, the version number starts with 1.0.0.
    • If the new version contains only bug fixes, increase the hotfix number so the version number will be 1.0.1.
    • If the new version contains new features with or without bug fixes, increase the feature number and reset the hotfix number to zero so the version number will be 1.1.0. If the feature number reaches 9, increase the main version number and reset the feature and hotfix number to zero (2.0.0 etc)

    try/catch with InputMismatchException creates infinite loop

    another option is to define Scanner input = new Scanner(System.in); inside the try block, this will create a new object each time you need to re-enter the values.

    What is the purpose of Looper and how to use it?

    Looper allows tasks to be executed sequentially on a single thread. And handler defines those tasks that we need to be executed. It is a typical scenario that I am trying to illustrate in this example:

    class SampleLooper extends Thread {
    @Override
    public void run() {
      try {
        // preparing a looper on current thread     
        // the current thread is being detected implicitly
        Looper.prepare();
    
        // now, the handler will automatically bind to the
        // Looper that is attached to the current thread
        // You don't need to specify the Looper explicitly
        handler = new Handler();
    
        // After the following line the thread will start
        // running the message loop and will not normally
        // exit the loop unless a problem happens or you
        // quit() the looper (see below)
        Looper.loop();
      } catch (Throwable t) {
        Log.e(TAG, "halted due to an error", t);
      } 
    }
    }
    

    Now we can use the handler in some other threads(say ui thread) to post the task on Looper to execute.

    handler.post(new Runnable()
    {
    public void run() {
    //This will be executed on thread using Looper.
        }
    });
    

    On UI thread we have an implicit Looper that allow us to handle the messages on ui thread.

    Enum to String C++

    enum Enum{ Banana, Orange, Apple } ;
    static const char * EnumStrings[] = { "bananas & monkeys", "Round and orange", "APPLE" };
    
    const char * getTextForEnum( int enumVal )
    {
      return EnumStrings[enumVal];
    }
    

    How to remove all null elements from a ArrayList or String Array?

    List<String> colors = new ArrayList<>(
    Arrays.asList("RED", null, "BLUE", null, "GREEN"));
    // using removeIf() + Objects.isNull()
    colors.removeIf(Objects::isNull);
    

    How do you find the current user in a Windows environment?

    This is the main difference between username variable and whoami command:

    C:\Users\user.name>echo %username%
    user.name
    
    C:\Users\user.name>whoami
    domain\user.name
    
    DOMAIN = bios name of the domain (not fqdn)
    

    Getting reference to child component in parent component

    You may actually go with ViewChild API...

    parent.ts

    <button (click)="clicked()">click</button>
    
    export class App {
      @ViewChild(Child) vc:Child;
      constructor() {
        this.name = 'Angular2'
      }
    
      func(e) {
        console.log(e)
    
      }
      clicked(){
       this.vc.getName();
      }
    }
    

    child.ts

    export class Child implements OnInit{
    
      onInitialized = new EventEmitter<Child>();
      ...  
      ...
      getName()
      {
         console.log('called by vc')
         console.log(this.name);
      }
    }
    

    Display a RecyclerView in Fragment

    I faced same problem. And got the solution when I use this code to call context. I use Grid Layout. If you use another one you can change.

       recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),1));
    

    if you have adapter to set. So you can follow this. Just call the getContext

      adapter = new Adapter(getContext(), myModelList);
    

    If you have Toast to show, use same thing above

       Toast.makeText(getContext(), "Error in "+e, Toast.LENGTH_SHORT).show();
    

    Hope this will work.

    HappyCoding

    Rename multiple files in a directory in Python

    This command will remove the initial "CHEESE_" string from all the files in the current directory, using renamer:

    $ renamer --find "/^CHEESE_/" *
    

    What are the differences between a multidimensional array and an array of arrays in C#?

    Array of arrays (jagged arrays) are faster than multi-dimensional arrays and can be used more effectively. Multidimensional arrays have nicer syntax.

    If you write some simple code using jagged and multidimensional arrays and then inspect the compiled assembly with an IL disassembler you will see that the storage and retrieval from jagged (or single dimensional) arrays are simple IL instructions while the same operations for multidimensional arrays are method invocations which are always slower.

    Consider the following methods:

    static void SetElementAt(int[][] array, int i, int j, int value)
    {
        array[i][j] = value;
    }
    
    static void SetElementAt(int[,] array, int i, int j, int value)
    {
        array[i, j] = value;
    }
    

    Their IL will be the following:

    .method private hidebysig static void  SetElementAt(int32[][] 'array',
                                                        int32 i,
                                                        int32 j,
                                                        int32 'value') cil managed
    {
      // Code size       7 (0x7)
      .maxstack  8
      IL_0000:  ldarg.0
      IL_0001:  ldarg.1
      IL_0002:  ldelem.ref
      IL_0003:  ldarg.2
      IL_0004:  ldarg.3
      IL_0005:  stelem.i4
      IL_0006:  ret
    } // end of method Program::SetElementAt
    
    .method private hidebysig static void  SetElementAt(int32[0...,0...] 'array',
                                                        int32 i,
                                                        int32 j,
                                                        int32 'value') cil managed
    {
      // Code size       10 (0xa)
      .maxstack  8
      IL_0000:  ldarg.0
      IL_0001:  ldarg.1
      IL_0002:  ldarg.2
      IL_0003:  ldarg.3
      IL_0004:  call       instance void int32[0...,0...]::Set(int32,
                                                               int32,
                                                               int32)
      IL_0009:  ret
    } // end of method Program::SetElementAt
    

    When using jagged arrays you can easily perform such operations as row swap and row resize. Maybe in some cases usage of multidimensional arrays will be more safe, but even Microsoft FxCop tells that jagged arrays should be used instead of multidimensional when you use it to analyse your projects.

    Default Activity not found in Android Studio

    1. In Android Studio

    2. Go to edit Configuration .

    3. Select the app.

    4. choose the lunch Activity path.

    5. apply, OK.

      Thanks!!

    how to check if a form is valid programmatically using jQuery Validation Plugin

    For a group of inputs you can use an improved version based in @mikemaccana's answer

    $.fn.isValid = function(){
        var validate = true;
        this.each(function(){
            if(this.checkValidity()==false){
                validate = false;
            }
        });
    };
    

    now you can use this to verify if the form is valid:

    if(!$(".form-control").isValid){
        return;
    }
    

    You could use the same technique to get all the error messages:

    $.fn.getVelidationMessage = function(){
        var message = "";
        var name = "";
        this.each(function(){
            if(this.checkValidity()==false){
                name = ($( "label[for=" + this.id + "] ").html() || this.placeholder || this.name || this.id);
                message = message + name +":"+ (this.validationMessage || 'Invalid value.')+"\n<br>";
            }
        })
        return message;
    }
    

    css with background image without repeating the image

    Instead of

    background-repeat-x: no-repeat;
    background-repeat-y: no-repeat;
    

    which is not correct, use

    background-repeat: no-repeat;
    

    Using the last-child selector

    Another way to do it is using the last-child selector in jQuery and then use the .css() method. Be weary though because some people are still in the stone age using JavaScript disabled browsers.

    Show default value in Spinner in android

    Spinner don't support Hint, i recommend you to make a custom spinner adapter.

    check this link : https://stackoverflow.com/a/13878692/1725748

    Best practices for circular shift (rotate) operations in C++

    Source Code x bit number

    int x =8;
    data =15; //input
    unsigned char tmp;
    for(int i =0;i<x;i++)
    {
    printf("Data & 1    %d\n",data&1);
    printf("Data Shifted value %d\n",data>>1^(data&1)<<(x-1));
    tmp = data>>1|(data&1)<<(x-1);
    data = tmp;  
    }
    

    SVN Error - Not a working copy

    If you get a "not a working copy" when doing a recursive svn cleanup my guess is that you have a directory which should be a working copy (i.e. the .svn directory at the top level says so), but it is missing its own .svn directory. In that case, you could try to just remove/move that directory and then do a local update (i.e. rm -rf content; svn checkout content).

    If you get a not a working copy error, it means that Subversion cannot find a proper .svn directory in there. Check to see if there is an .svn directory in contents

    The ideal solution is a fresh checkout, if possible.

    How to emulate a BEFORE INSERT trigger in T-SQL / SQL Server for super/subtype (Inheritance) entities?

    While Andriy's proposal will work well for INSERTs of a small number of records, full table scans will be done on the final join as both 'enumerated' and '@new_super' are not indexed, resulting in poor performance for large inserts.

    This can be resolved by specifying a primary key on the @new_super table, as follows:

    DECLARE @new_super TABLE (
      row_num INT IDENTITY(1,1) PRIMARY KEY CLUSTERED,
      super_id   int
    );
    

    This will result in the SQL optimizer scanning through the 'enumerated' table but doing an indexed join on @new_super to get the new key.

    Conditional formatting, entire row based

    Use the "indirect" function on conditional formatting.

    1. Select Conditional Formatting
    2. Select New Rule
    3. Select "Use a Formula to determine which cells to format"
    4. Enter the Formula, =INDIRECT("g"&ROW())="X"
    5. Enter the Format you want (text color, fill color, etc).
    6. Select OK to save the new format
    7. Open "Manage Rules" in Conditional Formatting
    8. Select "This Worksheet" if you can't see your new rule.
    9. In the "Applies to" box of your new rule, enter =$A$1:$Z$1500 (or however wide/long you want the conditional formatting to extend depending on your worksheet)

    For every row in the G column that has an X, it will now turn to the format you specified. If there isn't an X in the column, the row won't be formatted.

    You can repeat this to do multiple row formatting depending on a column value. Just change either the g column or x specific text in the formula and set different formats.

    For example, if you add a new rule with the formula, =INDIRECT("h"&ROW())="CAR", then it will format every row that has CAR in the H Column as the format you specified.

    HTTP Error 500.30 - ANCM In-Process Start Failure

    I got this problem when my Azure service was immediately trying to get a secret from Azure KeyVault and I had forgotten to give the service permission by KeyVault.

    Does --disable-web-security Work In Chrome Anymore?

    The new tag for recent Chrome and Chromium browsers is :

    --disable-web-security --user-data-dir=c:\my\data
    

    How to pass values between Fragments

    This is a stone age question and yet still very relevant. Specially now that Android team is pushing more towards adhering to single activity models, communication between the fragments becomes all the more important. LiveData and Interfaces are perfectly fine ways to tackle this issue. But now Google has finally addressed this problem and tried to bring a much simpler solution using FragmentManager. Here's how it can be done in Kotlin.

    In receiver fragment add a listener:

    setFragmentResultListener(
        "data_request_key",
        lifecycleOwner,
        FragmentResultListener { requestKey: String, bundle: Bundle ->
            // unpack the bundle and use data
            val frag1Str = bundle.getString("frag1_data_key")
    
        })
    

    In sender fragment(frag1):

    setFragmentResult(
        "data_request_key",
        bundleOf("frag1_data_key" to value)
    )
    

    Remember this functionality is only available in fragment-ktx version 1.3.0-alpha04 and up.

    Credits and further reading:

    A New Way to Pass Data Between Fragments

    Android Fragments: Fragment Result

    read subprocess stdout line by line

    It's been a long time since I last worked with Python, but I think the problem is with the statement for line in proc.stdout, which reads the entire input before iterating over it. The solution is to use readline() instead:

    #filters output
    import subprocess
    proc = subprocess.Popen(['python','fake_utility.py'],stdout=subprocess.PIPE)
    while True:
      line = proc.stdout.readline()
      if not line:
        break
      #the real code does filtering here
      print "test:", line.rstrip()
    

    Of course you still have to deal with the subprocess' buffering.

    Note: according to the documentation the solution with an iterator should be equivalent to using readline(), except for the read-ahead buffer, but (or exactly because of this) the proposed change did produce different results for me (Python 2.5 on Windows XP).

    How to get last 7 days data from current datetime to last 7 days in sql server

    This worked for me!!

    SELECT * FROM `users` where `created_at` BETWEEN CURDATE()-7 AND CURDATE()
    

    "The Controls collection cannot be modified because the control contains code blocks"

    I had same issue in the user control. My page that was hosting the control had comments in the head tag, I removed those comments, everything worked afterwards. Some posts also suggest removing scripts from head and placing them in the body.

    Countdown timer in React

    You have to setState every second with the seconds remaining (every time the interval is called). Here's an example:

    _x000D_
    _x000D_
    class Example extends React.Component {_x000D_
      constructor() {_x000D_
        super();_x000D_
        this.state = { time: {}, seconds: 5 };_x000D_
        this.timer = 0;_x000D_
        this.startTimer = this.startTimer.bind(this);_x000D_
        this.countDown = this.countDown.bind(this);_x000D_
      }_x000D_
    _x000D_
      secondsToTime(secs){_x000D_
        let hours = Math.floor(secs / (60 * 60));_x000D_
    _x000D_
        let divisor_for_minutes = secs % (60 * 60);_x000D_
        let minutes = Math.floor(divisor_for_minutes / 60);_x000D_
    _x000D_
        let divisor_for_seconds = divisor_for_minutes % 60;_x000D_
        let seconds = Math.ceil(divisor_for_seconds);_x000D_
    _x000D_
        let obj = {_x000D_
          "h": hours,_x000D_
          "m": minutes,_x000D_
          "s": seconds_x000D_
        };_x000D_
        return obj;_x000D_
      }_x000D_
    _x000D_
      componentDidMount() {_x000D_
        let timeLeftVar = this.secondsToTime(this.state.seconds);_x000D_
        this.setState({ time: timeLeftVar });_x000D_
      }_x000D_
    _x000D_
      startTimer() {_x000D_
        if (this.timer == 0 && this.state.seconds > 0) {_x000D_
          this.timer = setInterval(this.countDown, 1000);_x000D_
        }_x000D_
      }_x000D_
    _x000D_
      countDown() {_x000D_
        // Remove one second, set state so a re-render happens._x000D_
        let seconds = this.state.seconds - 1;_x000D_
        this.setState({_x000D_
          time: this.secondsToTime(seconds),_x000D_
          seconds: seconds,_x000D_
        });_x000D_
        _x000D_
        // Check if we're at zero._x000D_
        if (seconds == 0) { _x000D_
          clearInterval(this.timer);_x000D_
        }_x000D_
      }_x000D_
    _x000D_
      render() {_x000D_
        return(_x000D_
          <div>_x000D_
            <button onClick={this.startTimer}>Start</button>_x000D_
            m: {this.state.time.m} s: {this.state.time.s}_x000D_
          </div>_x000D_
        );_x000D_
      }_x000D_
    }_x000D_
    _x000D_
    ReactDOM.render(<Example/>, document.getElementById('View'));
    _x000D_
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>_x000D_
    <script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>_x000D_
    <div id="View"></div>
    _x000D_
    _x000D_
    _x000D_

    How to create a new branch from a tag?

    If you simply want to create a new branch without immediately changing to it, you could do the following:

    git branch newbranch v1.0