Programs & Examples On #Spatial query

Python - use list as function parameters

You can do this using the splat operator:

some_func(*params)

This causes the function to receive each list item as a separate parameter. There's a description here: http://docs.python.org/tutorial/controlflow.html#unpacking-argument-lists

How do I create a table based on another table

There is no such syntax in SQL Server, though CREATE TABLE AS ... SELECT does exist in PDW. In SQL Server you can use this query to create an empty table:

SELECT * INTO schema.newtable FROM schema.oldtable WHERE 1 = 0;

(If you want to make a copy of the table including all of the data, then leave out the WHERE clause.)

Note that this creates the same column structure (including an IDENTITY column if one exists) but it does not copy any indexes, constraints, triggers, etc.

plotting different colors in matplotlib

for color in ['r', 'b', 'g', 'k', 'm']:
    plot(x, y, color=color)

How to remove line breaks (no characters!) from the string?

I use 3 lines to do this job, so consider $s as your "stuff"...

$s=str_replace(chr(10),'',$s);
$s=str_replace(chr(13),'',$s);
$s=str_replace("\r\n"),'',$s);

Storing and Retrieving ArrayList values from hashmap

for (Map.Entry<String, ArrayList<Integer>> entry : map.entrySet()) {
 System.out.println( entry.getKey());     
 System.out.println( entry.getValue());//Returns the list of values
}

Converting a byte array to PNG/JPG

You should be able to do something like this:

byte[] bitmap = GetYourImage();

using(Image image = Image.FromStream(new MemoryStream(bitmap)))
{
    image.Save("output.jpg", ImageFormat.Jpeg);  // Or Png
}

Look here for more info.

Hopefully this helps.

Mysql Compare two datetime fields

You can use the following SQL to compare both date and time -

Select * From temp where mydate > STR_TO_DATE('2009-06-29 04:00:44', '%Y-%m-%d %H:%i:%s');

Attached mysql output when I used same SQL on same kind of table and field that you mentioned in the problem-

enter image description here

It should work perfect.

How to print table using Javascript?

My fellows,

In January 2019 I used a code made before:

 <script type="text/javascript">   
    function imprimir() {
        var divToPrint=document.getElementById("ConsutaBPM");
        newWin= window.open("");
        newWin.document.write(divToPrint.outerHTML);
        newWin.print();
        newWin.close();
    }
</script>

To undestand: ConsutaBPM is a DIV which contains inside phrases and tables. I wanted to print ALL, titles, table, and others. The problem was when TRIED to print the TABLE...

The table mas be defined with BORDER and CELLPADDING:

<table border='1' cellpadding='1' id='Tablbpm1' >

It worked fine!!!

Checkout Jenkins Pipeline Git SCM with credentials?

For what it's worth adding to the discussion... what I did that ended up helping me... Since the pipeline is run within a workspace within a docker image that is cleaned up each time it runs. I grabbed the credentials needed to perform necessary operations on the repo within my pipeline and stored them in a .netrc file. this allowed me to authorize the git repo operations successfully.

withCredentials([usernamePassword(credentialsId: '<credentials-id>', passwordVariable: 'GIT_PASSWORD', usernameVariable: 'GIT_USERNAME')]) {
    sh '''
        printf "machine github.com\nlogin $GIT_USERNAME\n password $GIT_PASSWORD" >> ~/.netrc
        // continue script as necessary working with git repo...
    '''
}

How do I expand the output display to see more columns of a pandas DataFrame?

The below line is enough to display all columns from dataframe. pd.set_option('display.max_columns', None)

Tracing XML request/responses with JAX-WS

Following options enable logging of all communication to the console (technically, you only need one of these, but that depends on the libraries you use, so setting all four is safer option). You can set it in the code like in example, or as command line parameter using -D or as environment variable as Upendra wrote.

System.setProperty("com.sun.xml.ws.transport.http.client.HttpTransportPipe.dump", "true");
System.setProperty("com.sun.xml.internal.ws.transport.http.client.HttpTransportPipe.dump", "true");
System.setProperty("com.sun.xml.ws.transport.http.HttpAdapter.dump", "true");
System.setProperty("com.sun.xml.internal.ws.transport.http.HttpAdapter.dump", "true");
System.setProperty("com.sun.xml.internal.ws.transport.http.HttpAdapter.dumpTreshold", "999999");

See question Tracing XML request/responses with JAX-WS when error occurs for details.

CodeIgniter - accessing $config variable in view

If you are trying to accessing config variable into controller than use

$this->config->item('{variable name which you define into config}');

If you are trying to accessing the config variable into outside the controller(helper/hooks) then use

$mms = get_instance();  
$mms->config->item('{variable which you define into config}');

CSS rounded corners in IE8

http://fetchak.com/ie-css3/ works for IE 6+. Use this if css3pie doesn't work for you.

Git pushing to remote branch

With modern Git versions, the command to use would be:

git push -u origin <branch_name_test>

This will automatically set the branch name to track from remote and push in one go.

How to convert list of key-value tuples into dictionary?

l=[['A', 1], ['B', 2], ['C', 3]]
d={}
for i,j in l:
d.setdefault(i,j)
print(d)

Div Background Image Z-Index Issue

Set your header and footer position to "absolute" and that should do the trick. Hope it helps and good luck with your project!

Uninstalling Android ADT

The only way to remove the ADT plugin from Eclipse is to go to Help > About Eclipse/About ADT > Installation Details.

Select a plug-in you want to uninstall, then click Uninstall... button at the bottom.

enter image description here

If you cannot remove ADT from this location, then your best option is probably to start fresh with a clean Eclipse install.

In TensorFlow, what is the difference between Session.run() and Tensor.eval()?

If you have a Tensor t, calling t.eval() is equivalent to calling tf.get_default_session().run(t).

You can make a session the default as follows:

t = tf.constant(42.0)
sess = tf.Session()
with sess.as_default():   # or `with sess:` to close on exit
    assert sess is tf.get_default_session()
    assert t.eval() == sess.run(t)

The most important difference is that you can use sess.run() to fetch the values of many tensors in the same step:

t = tf.constant(42.0)
u = tf.constant(37.0)
tu = tf.mul(t, u)
ut = tf.mul(u, t)
with sess.as_default():
   tu.eval()  # runs one step
   ut.eval()  # runs one step
   sess.run([tu, ut])  # evaluates both tensors in a single step

Note that each call to eval and run will execute the whole graph from scratch. To cache the result of a computation, assign it to a tf.Variable.

Uninstalling an MSI file from the command line without using msiexec

There are many ways to uninstall an MSI package. This is intended as a "reference".

In summary you can uninstall via: msiexec.exe, ARP, WMI, PowerShell, Deployment Systems such as SCCM, VBScript / COM Automation, DTF, or via hidden Windows cache folder, and a few other options presented below.

The first few paragraphs provide important MSI tidbits, then there are 14 sections with different ways to uninstall an MSI file. Puh.

"Babble, Babble - Over": Sections 1, 2 and 3 are the normal uninstall approaches (and hence recommended). Personally I use option 3 or 5 from section 3 (both options with logging, but option 5 runs silently as well). If you are very busy, skip all the babble and go for one of these - it will get the job done.


If you have problems uninstalling altogether and are looking for an alternative to the deprecated MsiZap.exe and / or Windows Installer CleanUp Utility (MSICUU2.exe), you can try the new FixIt tool from Microsoft (or the international page). May apparently work for other install issues as well.

Newer list of cleanup approaches: Cleaning out broken MSI uninstalls.


If you think MSI and Windows Installer is more trouble than it's worth, you might want to read about the corporate benefits of using MSI files.


Installscript MSI setups generally come wrapped in a setup.exe file. To read more about the parameters to use for uninstalling such setups please see these links: setup.exe pdf reference sheet, Setup.exe and Update.exe Command-Line Parameters.


Some MSI files are installed as part of bundles via mechanism such as Burn (WiX Toolkit) or InstallShield Suite projects. This can make uninstall slightly different from what is seen below. Here is an example for InstallShield Suite projects.


Be aware that running uninstall silently or interactively can cause different results (!). For a rather lengthy description of why this is the case, please read this post: Uninstall from Control Panel is different from Remove from .msi


If you are unexpectedly asked for the original installation media when trying to uninstall, please read this answer: Why does MSI require the original .msi file to proceed with an uninstall? and perhaps also section 12 below for some important technical details.


If you got CCleaner or similar cleanup tools installed, perhaps jump to section 11.


If uninstall is failing entirely (not possible to run), see sections 12 & 13 below for a potential way to "undo" the installation using system restore and / or cleanup tools.


1 - Using the original MSI

  • If you have access to the original MSI used for the installation, you can simply right click it in Windows Explorer and select Uninstall.
  • You can also uninstall via command line as explained in section 3.

2 - Using the old ARP Applet OR new Windows 8/10 Settings Interface

  • Just got to mention the normal approach(es) though it is obvious

  • ARP = Add / Remove Programs Applet (appwiz.cpl)

  • Windows 10 Settings Interface => New shell for same operation

  • ARP:

    • Go start ? run ? appwiz.cpl ? ENTER in order to open the add/remove programs applet (or click add/ remove programs in the control panel)
    • Click "Remove" for the product you want to uninstall
  • Settings Interface (Windows 8 / 10):

    • Use the new Settings GUI in Windows 8 / 10
      • Windows Key + Tap I => Apps & Features. Select entry and uninstall.
    • Direct shortcut:
      • Windows Key + Tap R => Type: ms-settings:appsfeatures and press Enter
    • Some reports of errors when invoking uninstall this way. Please add comments below if seen.

3 - Using msiexec.exe command line (directly or via a batch file)

  • You can uninstall via the command prompt (cmd.exe), batch file or or even from within an executable as a shell operation.
  • You do this by passing the product GUID (check below for how to find this GUID) or the path to the original MSI file, if available, to msiexec.exe.
  • For all the command lines below you can add /qn to make the uninstall run in silent mode. This is how an uninstall runs when triggered from the add/remove applet.

Option 3.1: Basic interactive uninstall (access to original MSI file):

msiexec.exe /x "c:\filename.msi"

Option 3.2: Basic interactive uninstall via product GUID (no access to original MSI file - here is how to find the product GUID - same link as below):

msiexec.exe /x {11111111-1111-1111-1111-11111111111X}

Option 3.3: Interactive uninstall with verbose log file:

msiexec.exe /x "c:\filename.msi" /L*V "C:\msilog.log"
msiexec.exe /x {11111111-1111-1111-1111-11111111111X} /L*V "C:\msilog.log"

Option 3.4: Interactive uninstall with flushed, verbose log file (verbose, flush to log option - write log continuously, can be very slow):

msiexec.exe /x "c:\filename.msi" /L*V! "C:\msilog.log"
msiexec.exe /x {11111111-1111-1111-1111-11111111111X} /L*V! "C:\msilog.log"
  • The flush to log option makes the uninstall slow because the log file is written continuously instead of in batches. This ensures no log-buffer is lost if the setup crashes.

  • In other words, enable this option if your setup is crashing and there is no helpful information in your verbose log file. Remove the exclamation mark to turn off the flush to log option and the uninstall will be much quicker. You still get verbose logging, but as stated some log buffer could be lost.

Option 3.5 (recommended): Silent uninstall with verbose log file - suppress reboots (no flush to log - see previous option for what this means):

msiexec.exe /x "c:\filename.msi" /QN /L*V "C:\msilog.log" REBOOT=R
msiexec.exe /x {11111111-1111-1111-1111-11111111111X} /QN /L*V "C:\msilog.log" REBOOT=R

Quick Parameter Explanation (since I recommend this option):

/X = run uninstall sequence
/QN = run completely silently
/L*V "C:\msilog.log"= verbose logging at path specified
{11111111-1111-1111-1111-11111111111X} = product guid of app to uninstall
REBOOT=R = prevent unexpected reboot of computer

Again, how to find the product guid: How can I find the product GUID of an installed MSI setup? (for uninstall if you don't have the original MSI to specify in the uninstall command).


4 - Using the cached MSI database in the super hidden cache folder

  • MSI strips out all cabs (older Windows versions) and caches each MSI installed in a super-hidden system folder at %SystemRoot%\Installer (you need to show hidden files to see it).
  • NB: This supper-hidden folder is now being treated differently in Windows 7 onwards. MSI files are now cached full-size. Read the linked thread for more details - recommended read for anyone who finds this answer and fiddles with dangerous Windows settings.
  • Avoid these huge cached files by using admin installations. On the topic of disk space: How can I get rid of huge cached MSI files (and other disk space cleanup tricks).
  • All the MSI files here will have a random name (hex format) assigned, but you can get information about each MSI by showing the Windows Explorer status bar (View -> Status Bar) and then selecting an MSI. The summary stream from the MSI will be visible at the bottom of the Windows Explorer window. Or as Christopher Galpin points out, turn on the "Comments" column in Windows Explorer and select the MSI file (see this article for how to do this).
  • Once you find the right MSI, just right click it and go Uninstall.
  • You can also use PowerShell to show the full path to the locally cached package along with the product name. This is the easiest option in my opinion.
  • To fire up PowerShell: hold down the Windows key, tap R, release the Windows key, type in "powershell" and press OK. Then maximize the PowerShell window and run the command below:
  get-wmiobject Win32_Product | Format-Table Name, LocalPackage -AutoSize

Enter image description here


5 - Using PowerShell


6 - Using the .NET DTF Class Library (part of the WiX toolkit)

    using Microsoft.Deployment.WindowsInstaller;

    public static void Uninstall( string productCode)
    {
      Installer.ConfigureProduct(productCode, 0, InstallState.Absent, "REBOOT=\"R\"");
    }

7 - Using the Windows Installer Automation API


8 - Using a Windows Installer major upgrade

  • A Windows Installer major upgrade may happen as part of the installation of another MSI file.
  • A major upgrade is authored by identifying related products in the MSI's "Upgrade table". These related setups are then handled as specified in the table. Generally that means they are uninstalled, but the main setup can also be aborted instead (typically used to detect higher versions of your own application present on the box).

9 - Using Deployment Systems / Remote Administration Systems

  • SCCM, CA Unicenter, IBM's Tivoli, Altiris Client Management Suite, and several others
  • These tools feature advanced client PC management, and this includes the install and uninstall of MSI files
  • These tools seem to use a combination of msiexec.exe, automation, WMI, etc... and even their own way of invoking installs and uninstalls.
  • In my experience these tools feature a lot of "personality" and you need to adapt to their different ways of doing things.

10 - Using WMI - Windows Management Instrumentation


11 - Using a third-party tool such as ccleaner or similar

  • Several Windows applications feature their own interface for uninstalling not just MSI packages, but legacy installers too.
  • I don't want to make any specific tool recommendations here (especially commercial ones), but the well known CCleaner features such an uninstall interface (and it has a free version). I should also add that this tool suffered a malware attack recently.
  • I guess we should all remember that even harmless software can be injected with malware in their download locations (FTP attack).
    • I use virustotal.com to check my downloads, and also Sysinternals Process Explorer to check running processes after installation - along with regular security software (whichever is available).
    • A surprising amount of "gray area" software is usually found with this approach (toolbars, smileys, adware, etc...), along with several false positives (they can also cause problems as security software block their access or quarantines them making a lot of fuzz). And certainly real malware as well.
    • Some usage tips for Process Explorer can be found here - a series of tweets - this Process Explorer tool hooks up to VirusTotal.com to check all running processes interactively - all you need is a few configuration steps.
    • I should note that Process Explorer yields a file signature check, but no heuristics - as far as I understand (no check for suspicious operations, just a check with 60+ security suites for flagged files). You need a regular security tool for interactive, online heuristic protection.
    • For what it is worth, I think some security software border on causing more false-positive problems than malware does damage. Famous last words in the era of ransom-ware...
    • That is a large enough digression - I just don't want to see people download malware. Do your virustotal.com check at least.
  • Uninstalling like this should work OK. I think these tools mess with too many things when you try their "cleanup features" though. Use with caution. If you only use the uninstall feature, you should be OK.

12 - Using a cleanup tool such as msizap or similar

  • For completeness msizap.exe should be mentioned though it is deprecated, unsupported and outdated. It should not be used on any newer Windows versions
  • This command line tool (msizap.exe) also had a GUI available (MSICUU2.exe). Both tools are deprectated.
  • The intended use of these tools was to clean out failing uninstalls:
  • Generally for the rare case when the cached MSI with the random name is erroneously missing and uninstall fails for this reason whilst asking for the original MSI. This is a rare problem, but I have seen it myself. Just a few potential causes: Moved to this answer.
    • Key words: system restore interference, bad cleanup apps, msiexec.exe crashing, power outage, security software interference, MSI development debugging blunders (identical package codes, etc...), user tinkering and hacking (what is in here? save space?), etc...
    • It could also be used to zap any MSI installation, though that is obviously not advisable.
    • More information: Why does MSI require the original .msi file to proceed with an uninstall?
  • This newer support tool (this tool is now also deprecated) can be tried on recent Windows versions if you have defunct MSI packages needing uninstall.
  • Some have suggested to use the tool linked to here by saschabeaumont: Uninstall without an MSI file. If you try it and it works, please be sure to let us know.
  • If you have access to the original MSI that was actually used to install the product, you can use this to run the uninstall. It must be the exact MSI that was used, and not just a similar one.

13 - Using system restore ("installation undo" - last resort IMHO)

  • This is strictly speaking not a way to "uninstall" but to "undo" the last install, or several installs for that matter.
  • Restoring via a restore point brings the system back to a previous installation state (you can find video demos of this on YouTube or a similar site).
  • Note that the feature can be disabled entirely or partly - it is possible to disable permanently for the whole machine, or adhoc per install.
  • I have seen new, unsolvable installation problems resulting from a system restore, but normally it works OK. Obviously don't use the feature for fun. It's a last resort and is best used for rollback of new drivers or setups that have just been installed and are found to cause immediate problems (bluescreen, reboots, instability, etc...).
  • The longer you go back the more rework you will create for yourself, and the higher the risk will be. Most systems feature only a few restore points, and most of them stretch back just a month or two I believe.
  • Be aware that system restore might affect Windows Updates that must then be re-applied - as well as many other system settings. Beyond pure annoyances, this can also cause security issues to resurface and you might want to run a specific security check on the target box(es) using Microsoft Baseline Security Analyzer or similar tools.
  • Since I mentioned system restore I suppose I should mention the Last Known Good Configuration feature. This feature has nothing to do with uninstall or system restore, but it is the last boot configuration that worked or resulted in a running system. It can be used to get your system running again if it bluescreens or halts during booting. This often happens after driver installs.

14 - Windows Installer Functions (C++)

For completeness I guess we should mention the core of it all - the down-to-the-metal way: the Win32 Windows Installer API functions. These are likely the functions used by most, if not all of the other approaches listed above "under the hood". They are primarily used by applications or solutions dealing directly with MSI as a technology.

There is an answer on serverfault.com which may be of interest as

Free Rest API to retrieve current datetime as string (timezone irrelevant)

If you're using Rails, you can just make an empty file in the public folder and use ajax to get that. Then parse the headers for the Date header. Files in the Public folder bypass the Rails stack, and so have lower latency.

PHP Function Comments

You can get the comments of a particular method by using the ReflectionMethod class and calling ->getDocComment().

http://www.php.net/manual/en/reflectionclass.getdoccomment.php

How do I output the difference between two specific revisions in Subversion?

See svn diff in the manual:

svn diff -r 8979:11390 http://svn.collab.net/repos/svn/trunk/fSupplierModel.php

Static Final Variable in Java

Declaring the field as 'final' will ensure that the field is a constant and cannot change. The difference comes in the usage of 'static' keyword.

Declaring a field as static means that it is associated with the type and not with the instances. i.e. only one copy of the field will be present for all the objects and not individual copy for each object. Due to this, the static fields can be accessed through the class name.

As you can see, your requirement that the field should be constant is achieved in both cases (declaring the field as 'final' and as 'static final').

Similar question is private final static attribute vs private final attribute

Hope it helps

Send FormData with other field in AngularJS

You're sending JSON-formatted data to a server which isn't expecting that format. You already provided the format that the server needs, so you'll need to format it yourself which is pretty simple.

var data = '"title='+title+'" "text='+text+'" "file='+file+'"';
$http.post(uploadUrl, data)

Hadoop "Unable to load native-hadoop library for your platform" warning

export JAVA_HOME=/home/hadoop/software/java/jdk1.7.0_80
export HADOOP_HOME=/usr/local/hadoop
export HADOOP_COMMON_LIB_NATIVE_DIR=$HADOOP_HOME/lib/native
export HADOOP_OPTS="-Djava.library.path=$HADOOP_COMMON_LIB_NATIVE_DIR"

ffmpeg usage to encode a video to H264 codec format

"C:\Program Files (x86)\ffmpegX86shared\bin\ffmpeg.exe" -y -i "C:\testfile.ts" -an -vcodec libx264 -g 75 -keyint_min 12 -vb 4000k -vprofile high -level 40 -s 1920x1080 -y -threads 0 -r 25 "C:\testfile.h264"

The above worked for me on a Windows machine using a FFmpeg Win32 shared build by Kyle Schwarz. The build was compiled on: Feb 22 2013, at: 01:09:53

Note that -an defines that audio should be skipped.

How to make unicode string with python3

What's new in Python 3.0 says:

All text is Unicode; however encoded Unicode is represented as binary data

If you want to ensure you are outputting utf-8, here's an example from this page on unicode in 3.0:

b'\x80abc'.decode("utf-8", "strict")

How to add a title to a html select tag

<select>
    <optgroup label = "Choose One">
    <option value ="sydney">Sydney</option>
    <option value ="melbourne">Melbourne</option>
    <option value ="cromwell">Cromwell</option>
    <option value ="queenstown">Queenstown</option>
    </optgroup>
</select>

List View Filter Android

Add an EditText on top of your listview in its .xml layout file. And in your activity/fragment..

lv = (ListView) findViewById(R.id.list_view);
    inputSearch = (EditText) findViewById(R.id.inputSearch);

// Adding items to listview
adapter = new ArrayAdapter<String>(this, R.layout.list_item, R.id.product_name,    products);
lv.setAdapter(adapter);       
inputSearch.addTextChangedListener(new TextWatcher() {

    @Override
    public void onTextChanged(CharSequence cs, int arg1, int arg2, int arg3) {
        // When user changed the Text
        MainActivity.this.adapter.getFilter().filter(cs);
    }

    @Override
    public void beforeTextChanged(CharSequence arg0, int arg1, int arg2, int arg3) { }

    @Override
    public void afterTextChanged(Editable arg0) {}
});

The basic here is to add an OnTextChangeListener to your edit text and inside its callback method apply filter to your listview's adapter.

EDIT

To get filter to your custom BaseAdapter you"ll need to implement Filterable interface.

class CustomAdapter extends BaseAdapter implements Filterable {

    public View getView(){
    ...
    }
    public Integer getCount()
    {
    ...
    }

    @Override
    public Filter getFilter() {

        Filter filter = new Filter() {

            @SuppressWarnings("unchecked")
            @Override
            protected void publishResults(CharSequence constraint, FilterResults results) {

                arrayListNames = (List<String>) results.values;
                notifyDataSetChanged();
            }

            @Override
            protected FilterResults performFiltering(CharSequence constraint) {

                FilterResults results = new FilterResults();
                ArrayList<String> FilteredArrayNames = new ArrayList<String>();

                // perform your search here using the searchConstraint String.

                constraint = constraint.toString().toLowerCase();
                for (int i = 0; i < mDatabaseOfNames.size(); i++) {
                    String dataNames = mDatabaseOfNames.get(i);
                    if (dataNames.toLowerCase().startsWith(constraint.toString()))  {
                        FilteredArrayNames.add(dataNames);
                    }
                }

                results.count = FilteredArrayNames.size();
                results.values = FilteredArrayNames;
                Log.e("VALUES", results.values.toString());

                return results;
            }
        };

        return filter;
    }
}

Inside performFiltering() you need to do actual comparison of the search query to values in your database. It will pass its result to publishResults() method.

How to escape double quotes in a title attribute

Here's a snippet of the HTML escape characters taken from a cached page on archive.org:

&#060   |   <   less than sign
&#064   |   @   at sign
&#093   |   ]   right bracket
&#123   |   {   left curly brace
&#125   |   }   right curly brace
&#133   |   …   ellipsis
&#135   |   ‡   double dagger
&#146   |   ’   right single quote
&#148   |   ”   right double quote
&#150   |   –   short dash
&#153   |   ™   trademark
&#162   |   ¢   cent sign
&#165   |   ¥   yen sign
&#169   |   ©   copyright sign
&#172   |   ¬   logical not sign
&#176   |   °   degree sign
&#178   |   ²   superscript 2
&#185   |   ¹   superscript 1
&#188   |   ¼   fraction 1/4
&#190   |   ¾   fraction 3/4
&#247   |   ÷   division sign
&#8221  |   ”   right double quote
&#062   |   >   greater than sign
&#091   |   [   left bracket
&#096   |   `   back apostrophe
&#124   |   |   vertical bar
&#126   |   ~   tilde
&#134   |   †   dagger
&#145   |   ‘   left single quote
&#147   |   “   left double quote
&#149   |   •   bullet
&#151   |   —   longer dash
&#161   |   ¡   inverted exclamation point
&#163   |   £   pound sign
&#166   |   ¦   broken vertical bar
&#171   |   «   double left than sign
&#174   |   ®   registered trademark sign
&#177   |   ±   plus or minus sign
&#179   |   ³   superscript 3
&#187   |   »   double greater-than sign
&#189   |   ½   fraction 1/2
&#191   |   ¿   inverted question mark
&#8220  |   “   left double quote
&#8212  |   —   dash

Twig: in_array or similar possible within if statement?

You just have to change the second line of your second code-block from

{% if myVar is in_array(array_keys(someOtherArray)) %}

to

{% if myVar in someOtherArray|keys %}

in is the containment-operator and keys a filter that returns an arrays keys.

How to create a Rectangle object in Java using g.fillRect method

Try this:

public void paint (Graphics g) {    
    Rectangle r = new Rectangle(xPos,yPos,width,height);
    g.fillRect(r.getX(), r.getY(), r.getWidth(), r.getHeight());  
}

[edit]

// With explicit casting
public void paint (Graphics g) {    
        Rectangle r = new Rectangle(xPos, yPos, width, height);
        g.fillRect(
           (int)r.getX(),
           (int)r.getY(),
           (int)r.getWidth(),
           (int)r.getHeight()
        );  
    }

Conda: Installing / upgrading directly from github

I found a reference to this in condas issues. The following should now work.

name: sample_env
channels:
dependencies:
   - requests
   - bokeh>=0.10.0
   - pip:
     - git+https://github.com/pythonforfacebook/facebook-sdk.git

Auto-indent spaces with C in vim?

Simply run:

user@host:~ $ echo set autoindent >> .vimrc

Spring Boot: Is it possible to use external application.properties files in arbitrary directories with a fat jar?

This may be coming in Late but I think I figured out a better way to load external configurations especially when you run your spring-boot app using java jar myapp.war instead of @PropertySource("classpath:some.properties")

The configuration would be loaded form the root of the project or from the location the war/jar file is being run from

public class Application implements EnvironmentAware {

    public static void main(String[] args) throws Exception {
        SpringApplication.run(Application.class, args);
    }

    @Override
    public void setEnvironment(Environment environment) {
        //Set up Relative path of Configuration directory/folder, should be at the root of the project or the same folder where the jar/war is placed or being run from
        String configFolder = "config";
        //All static property file names here
        List<String> propertyFiles = Arrays.asList("application.properties","server.properties");
        //This is also useful for appending the profile names
        Arrays.asList(environment.getActiveProfiles()).stream().forEach(environmentName -> propertyFiles.add(String.format("application-%s.properties", environmentName))); 
        for (String configFileName : propertyFiles) {
            File configFile = new File(configFolder, configFileName);
            LOGGER.info("\n\n\n\n");
            LOGGER.info(String.format("looking for configuration %s from %s", configFileName, configFolder));
            FileSystemResource springResource = new FileSystemResource(configFile);
            LOGGER.log(Level.INFO, "Config file : {0}", (configFile.exists() ? "FOund" : "Not Found"));
            if (configFile.exists()) {
                try {
                    LOGGER.info(String.format("Loading configuration file %s", configFileName));
                    PropertiesFactoryBean pfb = new PropertiesFactoryBean();
                    pfb.setFileEncoding("UTF-8");
                    pfb.setLocation(springResource);
                    pfb.afterPropertiesSet();
                    Properties properties = pfb.getObject();
                    PropertiesPropertySource externalConfig = new PropertiesPropertySource("externalConfig", properties);
                    ((ConfigurableEnvironment) environment).getPropertySources().addFirst(externalConfig);
                } catch (IOException ex) {
                    LOGGER.log(Level.SEVERE, null, ex);
                }
            } else {
                LOGGER.info(String.format("Cannot find Configuration file %s... \n\n\n\n", configFileName));

            }

        }
    }

}

Hope it helps.

function to remove duplicate characters in a string

Question: Remove Duplicate characters in a string Method 1 :(Python)

import collections

a = "GiniGinaProtijayi"

aa = collections.OrderedDict().fromkeys(a)
print(''.join(aa))

Method 2 :(Python)

a = "GiniGinaProtijayi"
list = []
aa = [ list.append(ch) for ch in a if  ch  not in list]
print( ''.join(list))

IN Java:

class test2{
    public static void main(String[] args) {

 String a = "GiniGinaProtijayi";
 List<Character> list = new ArrayList<>();

       for(int i = 0 ; i < a.length() ;i++) {
           char ch = a.charAt(i);
           if( list.size() == 0 ) {list.add(ch);}
           if(!list.contains(ch)) {list.add(ch) ;}

       }//for
       StringBuffer sbr = new StringBuffer();

      for( char ch : list) {sbr.append(ch);}
      System.out.println(sbr);

    }//main

}//end

What does 'synchronized' mean?

Synchronized simply means that multiple threads if associated with single object can prevent dirty read and write if synchronized block is used on particular object. To give you more clarity , lets take an example :

class MyRunnable implements Runnable {
    int var = 10;
    @Override
    public void run() {
        call();
    }

    public void call() {
        synchronized (this) {
            for (int i = 0; i < 4; i++) {
                var++;
                System.out.println("Current Thread " + Thread.currentThread().getName() + " var value "+var);
            }
        }
    }
}

public class MutlipleThreadsRunnable {
    public static void main(String[] args) {
        MyRunnable runnable1 = new MyRunnable();
        MyRunnable runnable2 = new MyRunnable();
        Thread t1 = new Thread(runnable1);
        t1.setName("Thread -1");
        Thread t2 = new Thread(runnable2);
        t2.setName("Thread -2");
        Thread t3 = new Thread(runnable1);
        t3.setName("Thread -3");
        t1.start();
        t2.start();
        t3.start();
    }
}

We've created two MyRunnable class objects , runnable1 being shared with thread 1 and thread 3 & runnable2 being shared with thread 2 only. Now when t1 and t3 starts without synchronized being used , PFB output which suggest that both threads 1 and 3 simultaneously affecting var value where for thread 2 , var has its own memory.

Without Synchronized keyword

    Current Thread Thread -1 var value 11
    Current Thread Thread -2 var value 11
    Current Thread Thread -2 var value 12
    Current Thread Thread -2 var value 13
    Current Thread Thread -2 var value 14
    Current Thread Thread -1 var value 12
    Current Thread Thread -3 var value 13
    Current Thread Thread -3 var value 15
    Current Thread Thread -1 var value 14
    Current Thread Thread -1 var value 17
    Current Thread Thread -3 var value 16
    Current Thread Thread -3 var value 18

Using Synchronzied, thread 3 waiting for thread 1 to complete in all scenarios. There are two locks acquired , one on runnable1 shared by thread 1 and thread 3 and another on runnable2 shared by thread 2 only.

Current Thread Thread -1 var value 11
Current Thread Thread -2 var value 11
Current Thread Thread -1 var value 12
Current Thread Thread -2 var value 12
Current Thread Thread -1 var value 13
Current Thread Thread -2 var value 13
Current Thread Thread -1 var value 14
Current Thread Thread -2 var value 14
Current Thread Thread -3 var value 15
Current Thread Thread -3 var value 16
Current Thread Thread -3 var value 17
Current Thread Thread -3 var value 18

JavaScript: Alert.Show(message) From ASP.NET Code-behind

its simple to call a message box, so if you want to code behind or call function, I think it is better or may be not. There is a process, you can just use namespace

using system.widows.forms;

then, where you want to show a message box, just call it as simple, as in C#, like:

messagebox.show("Welcome");

Escape double quotes for JSON in Python

i know this question is old, but hopefully it will help someone. i found a great plugin for those who are using PyCharm IDE: string-manipulation that can easily escape double quotes (and many more...), this plugin is great for cases where you know what the string going to be. for other cases, using json.dumps(string) will be the recommended solution

str_to_escape = 'my string with "double quotes" blablabla'

after_escape = 'my string with \"double quotes\" blablabla'

How to use executables from a package installed locally in node_modules?

I've always used the same approach as @guneysus to solve this problem, which is creating a script in the package.json file and use it running npm run script-name.

However, in the recent months I've been using npx and I love it.

For example, I downloaded an Angular project and I didn't want to install the Angular CLI globally. So, with npx installed, instead of using the global angular cli command (if I had installed it) like this:

ng serve

I can do this from the console:

npx ng serve

Here's an article I wrote about NPX and that goes deeper into it.

The property 'Id' is part of the object's key information and cannot be modified

first Remove next add

for simple

public static IEnumerable UserIntakeFoodEdit(FoodIntaked data)
        {
            DBContext db = new DBContext();
            var q = db.User_Food_UserIntakeFood.AsQueryable();
            var item = q.Where(f => f.PersonID == data.PersonID)
                  .Where(f => f.DateOfIntake == data.DateOfIntake)
                  .Where(f => f.MealTimeID == data.MealTimeIDOld)
                  .Where(f => f.NDB_No == data.NDB_No).FirstOrDefault();

            item.Amount = (decimal)data.Amount;
            item.WeightSeq = data.WeightSeq.ToString();
            item.TotalAmount = (decimal)data.TotalAmount;


            db.User_Food_UserIntakeFood.Remove(item);
            db.SaveChanges();

            item.MealTimeID = data.MealTimeID;//is key

            db.User_Food_UserIntakeFood.Add(item);
            db.SaveChanges();

            return "Edit";
        }

Adding an arbitrary line to a matplotlib plot in ipython notebook

You can directly plot the lines you want by feeding the plot command with the corresponding data (boundaries of the segments):

plot([x1, x2], [y1, y2], color='k', linestyle='-', linewidth=2)

(of course you can choose the color, line width, line style, etc.)

From your example:

import numpy as np
import matplotlib.pyplot as plt

np.random.seed(5)
x = np.arange(1, 101)
y = 20 + 3 * x + np.random.normal(0, 60, 100)
plt.plot(x, y, "o")


# draw vertical line from (70,100) to (70, 250)
plt.plot([70, 70], [100, 250], 'k-', lw=2)

# draw diagonal line from (70, 90) to (90, 200)
plt.plot([70, 90], [90, 200], 'k-')

plt.show()

new chart

Get type of a generic parameter in Java with reflection

The quick answer the the Question is no you can't, because of Java generic type erasure.

The longer answer would be that if you have created your list like this:

new ArrayList<SpideMan>(){}

Then in this case the generic type is preserved in the generic superclass of the new anonymous class above.

Not that I recommend doing this with lists, but it is a listener implementation:

new Listener<Type>() { public void doSomething(Type t){...}}

And since extrapolating the generic types of super classes and super interfaces change between JVMs, the generic solution is not as straight forward as some answers might suggest.

Here is now I did it.

How to upload images into MySQL database using PHP code

This is the perfect code for uploading and displaying image through MySQL database.

<html>
<body>
<form method="post" enctype="multipart/form-data">
<input type="file" name="image"/>
<input type="submit" name="submit" value="Upload"/>
</form>
<?php
    if(isset($_POST['submit']))
    {
     if(getimagesize($_FILES['image']['tmp_name'])==FALSE)
     {
        echo " error ";
     }
     else
     {
        $image = $_FILES['image']['tmp_name'];
        $image = addslashes(file_get_contents($image));
        saveimage($image);
     }
    }
    function saveimage($image)
    {
        $dbcon=mysqli_connect('localhost','root','','dbname');
        $qry="insert into tablename (name) values ('$image')";
        $result=mysqli_query($dbcon,$qry);
        if($result)
        {
            echo " <br/>Image uploaded.";
            header('location:urlofpage.php');
        }
        else
        {
            echo " error ";
        }
    }
?>
</body>
</html>

How do you append to an already existing string?

#!/bin/bash
message="some text"
message="$message add some more"

echo $message

some text add some more

Select parent element of known element in Selenium

There are a couple of options there. The sample code is in Java, but a port to other languages should be straightforward.

Java:

WebElement myElement = driver.findElement(By.id("myDiv"));
WebElement parent = (WebElement) ((JavascriptExecutor) driver).executeScript(
                                   "return arguments[0].parentNode;", myElement);

XPath:

WebElement myElement = driver.findElement(By.id("myDiv"));
WebElement parent = myElement.findElement(By.xpath("./.."));

Obtaining the driver from the WebElement

Note: As you can see, for the JavaScript version you'll need the driver. If you don't have direct access to it, you can retrieve it from the WebElement using:

WebDriver driver = ((WrapsDriver) myElement).getWrappedDriver();

What's the difference between @JoinColumn and mappedBy when using a JPA @OneToMany association

JPA is a layered API, the different levels have their own annotations. The highest level is the (1) Entity level which describes persistent classes then you have the (2) relational database level which assume the entities are mapped to a relational database and (3) the java model.

Level 1 annotations: @Entity, @Id, @OneToOne, @OneToMany, @ManyToOne, @ManyToMany. You can introduce persistency in your application using these high level annotations alone. But then you have to create your database according to the assumptions JPA makes. These annotations specify the entity/relationship model.

Level 2 annotations: @Table, @Column, @JoinColumn, ... Influence the mapping from entities/properties to the relational database tables/columns if you are not satisfied with JPA's defaults or if you need to map to an existing database. These annotations can be seen as implementation annotations, they specify how the mapping should be done.

In my opinion it is best to stick as much as possible to the high level annotations and then introduce the lower level annotations as needed.

To answer the questions: the @OneToMany/mappedBy is nicest because it only uses the annotations from the entity domain. The @oneToMany/@JoinColumn is also fine but it uses an implementation annotation where this is not strictly necessary.

Nginx not picking up site in sites-enabled?

Changing from:

include /etc/nginx/sites-enabled/*; 

to

include /etc/nginx/sites-enabled/*.*; 

fixed my issue

How to push JSON object in to array using javascript

You need to have the 'data' array outside of the loop, otherwise it will get reset in every loop and also you can directly push the json. Find the solution below:-

var my_json;
$.getJSON("https://api.thingspeak.com/channels/"+did+"/feeds.json?api_key="+apikey+"&results=300", function(json1) {
console.log(json1);
var data = [];
json1.feeds.forEach(function(feed,i){
    console.log("\n The details of " + i + "th Object are :  \nCreated_at: " + feed.created_at + "\nEntry_id:" + feed.entry_id + "\nField1:" + feed.field1 + "\nField2:" + feed.field2+"\nField3:" + feed.field3);      
    my_json = feed;
    console.log(my_json); //Object {created_at: "2017-03-14T01:00:32Z", entry_id: 33358, field1: "4", field2: "4", field3: "0"}
    data.push(my_json);
     //["2017-03-14T01:00:32Z", 33358, "4", "4", "0"]
}); 
console.log(data);

Check if array is empty or null

User JQuery is EmptyObject to check whether array is contains elements or not.

var testArray=[1,2,3,4,5];
var testArray1=[];
console.log(jQuery.isEmptyObject(testArray)); //false
console.log(jQuery.isEmptyObject(testArray1)); //true

Replace Fragment inside a ViewPager

I doing something to similar to wize but in my answer yo can change between the two fragments whenever you want. And with the wize answer I have some problems when changing the orientation of the screen an things like that. This is the PagerAdapter looks like:

    public class MyAdapter extends FragmentPagerAdapter
{
    static final int NUM_ITEMS = 2;
    private final FragmentManager mFragmentManager;
    private Fragment mFragmentAtPos0;
     private Map<Integer, String> mFragmentTags;
     private boolean isNextFragment=false;

    public MyAdapter(FragmentManager fm)
    {
        super(fm);
        mFragmentManager = fm;
         mFragmentTags = new HashMap<Integer, String>();
    }

    @Override
    public Fragment getItem(int position)
    {
        if (position == 0)
        {


            if (isPager) {
                mFragmentAtPos0 = new FirstPageFragment();
            } else {
                mFragmentAtPos0 = new NextFragment();
            }
            return mFragmentAtPos0;
        }
        else
            return SecondPageFragment.newInstance();
    }

    @Override
    public int getCount()
    {
        return NUM_ITEMS;
    }


 @Override
    public Object instantiateItem(ViewGroup container, int position) {
        Object obj = super.instantiateItem(container, position);
        if (obj instanceof Fragment) {
            // record the fragment tag here.
            Fragment f = (Fragment) obj;
            String tag = f.getTag();
            mFragmentTags.put(position, tag);
        }
        return obj;
    }


    public void onChange(boolean isNextFragment) {

        if (mFragmentAtPos0 == null)
            mFragmentAtPos0 = getFragment(0);
        if (mFragmentAtPos0 != null)
            mFragmentManager.beginTransaction().remove(mFragmentAtPos0).commit();


        if (!isNextFragment) {
            mFragmentAtFlashcards = new FirstPageFragment();
        } else {
            mFragmentAtFlashcards = new NextFragment();
        }

        notifyDataSetChanged();


    }


    @Override
    public int getItemPosition(Object object)
    {
        if (object instanceof FirstPageFragment && mFragmentAtPos0 instanceof NextFragment)
            return POSITION_NONE;
         if (object instanceof NextFragment && mFragmentAtPos0 instanceof FirstPageFragment)
            return POSITION_NONE;
        return POSITION_UNCHANGED;
    }


    public Fragment getFragment(int position) {
        String tag = mFragmentTags.get(position);
        if (tag == null)
            return null;
        return mFragmentManager.findFragmentByTag(tag);
    }
}

The listener I implemented in the adapter container activity to put it to the fragment when attaching it, this is the activity:

    public class PagerContainerActivity extends AppCompatActivity implements ChangeFragmentListener {

//...

  @Override
    public void onChange(boolean isNextFragment) {
        if (pagerAdapter != null)
            pagerAdapter.onChange(isNextFragment);


    }

//...
}

Then in the fragment putting the listener when attach an calling it:

public class FirstPageFragment extends Fragment{


private ChangeFragmentListener changeFragmentListener;


//...
 @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        changeFragmentListener = ((PagerContainerActivity) activity);
    }

    @Override
    public void onDetach() {
        super.onDetach();
        changeFragmentListener = null;
    }
//...
//in the on click to change the fragment
changeFragmentListener.onChange(true);
//...
}

And finally the listener:

public interface changeFragmentListener {

    void onChange(boolean isNextFragment);

}

How to install a gem or update RubyGems if it fails with a permissions error

As pointed out by bobbdelsol, rehash worked for me :

==> which ruby
/usr/bin/ruby

==> rbenv install 1.9.3-p551
Downloading ruby-1.9.3-p551.tar.bz2...
-> https://cache.ruby-lang.org/pub/ruby/1.9/ruby-1.9.3-p551.tar.bz2
Installing ruby-1.9.3-p551...
Installed ruby-1.9.3-p551 to /Users/username/.rbenv/versions/1.9.3-p551


==> which ruby
/Users/username/.rbenv/shims/ruby

==> which gem
/Users/username/.rbenv/shims/gem

==> gem install compass
ERROR:  While executing gem ... (Gem::FilePermissionError)
    You don't have write permissions for the /Library/Ruby/Gems/2.0.0 directory.


==> ruby -v
ruby 2.0.0p648 (2015-12-16 revision 53162) [universal.x86_64-darwin15]


==> rbenv global 1.9.3-p551


==> ruby -v
ruby 2.0.0p648 (2015-12-16 revision 53162) [universal.x86_64-darwin15]


==> rbenv global 1.9.3-p551


==> rbenv rehash


==> ruby -v
ruby 1.9.3p551 (2014-11-13 revision 48407) [x86_64-darwin15.4.0]


==> gem install compass
Fetching: sass-3.4.22.gem (100%)
Fetching: multi_json-1.11.3.gem (100%)
Fetching: compass-core-1.0.3.gem (100%)
Fetching: compass-import-once-1.0.5.gem (100%)
Fetching: chunky_png-1.3.5.gem (100%)
Fetching: rb-fsevent-0.9.7.gem (100%)
Fetching: ffi-1.9.10.gem (100%)
Building native extensions.  This could take a while...
Fetching: rb-inotify-0.9.7.gem (100%)
Fetching: compass-1.0.3.gem (100%)
    Compass is charityware. If you love it, please donate on our behalf at http://umdf.org/compass Thanks!
Successfully installed sass-3.4.22
Successfully installed multi_json-1.11.3
Successfully installed compass-core-1.0.3
Successfully installed compass-import-once-1.0.5
Successfully installed chunky_png-1.3.5
Successfully installed rb-fsevent-0.9.7
Successfully installed ffi-1.9.10
Successfully installed rb-inotify-0.9.7
Successfully installed compass-1.0.3
9 gems installed
Installing ri documentation for sass-3.4.22...
Installing ri documentation for multi_json-1.11.3...
Installing ri documentation for compass-core-1.0.3...
Installing ri documentation for compass-import-once-1.0.5...
Installing ri documentation for chunky_png-1.3.5...
Installing ri documentation for rb-fsevent-0.9.7...
Installing ri documentation for ffi-1.9.10...
Installing ri documentation for rb-inotify-0.9.7...
Installing ri documentation for compass-1.0.3...
Installing RDoc documentation for sass-3.4.22...
Installing RDoc documentation for multi_json-1.11.3...
Installing RDoc documentation for compass-core-1.0.3...
Installing RDoc documentation for compass-import-once-1.0.5...
Installing RDoc documentation for chunky_png-1.3.5...
Installing RDoc documentation for rb-fsevent-0.9.7...
Installing RDoc documentation for ffi-1.9.10...
Installing RDoc documentation for rb-inotify-0.9.7...
Installing RDoc documentation for compass-1.0.3...

How do I use raw_input in Python 3

This works in Python 3.x and 2.x:

# Fix Python 2.x.
try: input = raw_input
except NameError: pass
print("Hi " + input("Say something: "))

.map() a Javascript ES6 Map?

You can use this function:

function mapMap(map, fn) {
  return new Map(Array.from(map, ([key, value]) => [key, fn(value, key, map)]));
}

usage:

var map1 = new Map([["A", 2], ["B", 3], ["C", 4]]);

var map2 = mapMap(map1, v => v * v);

console.log(map1, map2);
/*
Map { A ? 2, B ? 3, C ? 4 }
Map { A ? 4, B ? 9, C ? 16 }
*/

Excel VBA - select multiple columns not in sequential order

Some of the code looks a bit complex to me. This is very simple code to select only the used rows in two discontiguous columns D and H. It presumes the columns are of unequal length and thus more flexible vs if the columns were of equal length.

As you most likely surmised 4=column D and 8=column H

Dim dlastRow As Long
Dim hlastRow As Long

dlastRow = ActiveSheet.Cells(Rows.Count, 4).End(xlUp).Row
hlastRow = ActiveSheet.Cells(Rows.Count, 8).End(xlUp).Row
Range("D2:D" & dlastRow & ",H2:H" & hlastRow).Select

Hope you find useful - DON'T FORGET THAT COMMA BEFORE THE SECOND COLUMN, AS I DID, OR IT WILL BOMB!!

Enable vertical scrolling on textarea

You can try adding:

#aboutDescription
{
    height: 100px;
    max-height: 100px;  
}

How do I reference a local image in React?

You need to wrap you image source path within {}

<img src={'path/to/one.jpeg'} />

You need to use require if using webpack

<img src={require('path/to/one.jpeg')} />

Flutter: how to make a TextField with HintText but no Underline?

new flutter sdk since after integration of web and desktop support you need to specify individually like this

TextFormField(
    cursorColor: Colors.black,
    keyboardType: inputType,
    decoration: new InputDecoration(
        border: InputBorder.none,
        focusedBorder: InputBorder.none,
        enabledBorder: InputBorder.none,
        errorBorder: InputBorder.none,
        disabledBorder: InputBorder.none,
        contentPadding:
            EdgeInsets.only(left: 15, bottom: 11, top: 11, right: 15),
        hintText: "Hint here"),
  )

How to comment multiple lines in Visual Studio Code?

This is somewhat of an extension to the answer when the comment line is too long to fit on a line (above 80 chars or whatever). If the comment is too long and text needs to wrap, it's better to keep it under control (rather than use the editor's text wrap feature). This plugin Rewrap helps do just that https://marketplace.visualstudio.com/items?itemName=stkb.rewrap&ssr=false#review-details

Install the plugin in VS Code, select the text comment, comment it using one of the right methods described in the answers (Ctrl + / is easiest) and then once it's commented, press Alt + Q and this will split the text to multiple lines and also comment it. Found it pretty useful. Hope this helps someone :)

Angular-Material DateTime Picker Component?

You can have a datetime picker when using matInput with type datetime-local like so:

  <mat-form-field>
    <input matInput type="datetime-local" placeholder="start date">
  </mat-form-field>

You can click on each part of the placeholder to set the day, month, year, hours,minutes and whether its AM or PM.

Run jar file with command line arguments

For the question

How can i run a jar file in command prompt but with arguments

.

To pass arguments to the jar file at the time of execution

java -jar myjar.jar arg1 arg2

In the main() method of "Main-Class" [mentioned in the manifest.mft file]of your JAR file. you can retrieve them like this:

String arg1 = args[0];
String arg2 = args[1];

Properly embedding Youtube video into bootstrap 3.0 page

I use bootstrap 3.x as well and the following code fore responsive youtube video embedding works like charm for me:

.videoWrapperOuter {
  max-width:640px; 
  margin-left:auto;
  margin-right:auto;
}
.videoWrapperInner {
  float: none;
  clear: both;
  width: 100%;
  position: relative;
  padding-bottom: 50%;
  padding-top: 25px;
  height: 0;
}
.videoWrapperInner iframe {
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
}
<div class="videoWrapperOuter">
  <div class="videoWrapperInner">
    <iframe src="//www.youtube.com/embed/C6-TWRn0k4I" 
      frameborder="0" allowfullscreen></iframe>
  </div>
</div>

I gave a similiar answer on another thread (Shrink a YouTube video to responsive width), but I guess my answers can help here as well.

Node / Express: EADDRINUSE, Address already in use - Kill server

I was getting this error once and took many of the approaches here.

My issues was that I had two app.listen(3000); calls in the same app.js script. The first app.listen() succeeded where the second threw the error.

Another useful command I came across that helped me debug was sudo fuser -k 3000/tcp which will kill any rogue processes you might have started (some processes may restart, e.g. if run with forever.js, but it was useful for me).

Visual Studio error "Object reference not set to an instance of an object" after install of ASP.NET and Web Tools 2015

I solved it doing

run devenv /resetuserdata

in this path:

[x64] C:\Program Files (x86)\Microsoft Visual Studio 14.0\Common7\IDE

I assume that in x86 it works in this path:

[x86] C:\Program Files\Microsoft Visual Studio 14.0\Common7\IDE

Java: How to convert List to Map

Apache Commons MapUtils.populateMap

If you don't use Java 8 and you don't want to use a explicit loop for some reason, try MapUtils.populateMap from Apache Commons.

MapUtils.populateMap

Say you have a list of Pairs.

List<ImmutablePair<String, String>> pairs = ImmutableList.of(
    new ImmutablePair<>("A", "aaa"),
    new ImmutablePair<>("B", "bbb")
);

And you now want a Map of the Pair's key to the Pair object.

Map<String, Pair<String, String>> map = new HashMap<>();
MapUtils.populateMap(map, pairs, new Transformer<Pair<String, String>, String>() {

  @Override
  public String transform(Pair<String, String> input) {
    return input.getKey();
  }
});

System.out.println(map);

gives output:

{A=(A,aaa), B=(B,bbb)}

That being said, a for loop is maybe easier to understand. (This below gives the same output):

Map<String, Pair<String, String>> map = new HashMap<>();
for (Pair<String, String> pair : pairs) {
  map.put(pair.getKey(), pair);
}
System.out.println(map);

How to check which version of Keras is installed?

You can write:

python
import keras
keras.__version__

How to use OAuth2RestTemplate?

You can find examples for writing OAuth clients here:

In your case you can't just use default or base classes for everything, you have a multiple classes Implementing OAuth2ProtectedResourceDetails. The configuration depends of how you configured your OAuth service but assuming from your curl connections I would recommend:

@EnableOAuth2Client
@Configuration
class MyConfig{

    @Value("${oauth.resource:http://localhost:8082}")
    private String baseUrl;
    @Value("${oauth.authorize:http://localhost:8082/oauth/authorize}")
    private String authorizeUrl;
    @Value("${oauth.token:http://localhost:8082/oauth/token}")
    private String tokenUrl;

    @Bean
    protected OAuth2ProtectedResourceDetails resource() {
        ResourceOwnerPasswordResourceDetails resource;
        resource = new ResourceOwnerPasswordResourceDetails();

        List scopes = new ArrayList<String>(2);
        scopes.add("write");
        scopes.add("read");
        resource.setAccessTokenUri(tokenUrl);
        resource.setClientId("restapp");
        resource.setClientSecret("restapp");
        resource.setGrantType("password");
        resource.setScope(scopes);
        resource.setUsername("**USERNAME**");
        resource.setPassword("**PASSWORD**");
        return resource;
    }

    @Bean
    public OAuth2RestOperations restTemplate() {
        AccessTokenRequest atr = new DefaultAccessTokenRequest();
        return new OAuth2RestTemplate(resource(), new DefaultOAuth2ClientContext(atr));
    }
}

@Service
@SuppressWarnings("unchecked")
class MyService {

    @Autowired
    private OAuth2RestOperations restTemplate;

    public MyService() {
        restTemplate.getAccessToken();
    }
}

Do not forget about @EnableOAuth2Client on your config class, also I would suggest to try that the urls you are using are working with curl first, also try to trace it with the debugger because lot of exceptions are just consumed and never printed out due security reasons, so it gets little hard to find where the issue is. You should use logger with debug enabled set. Good luck

I uploaded sample springboot app on github https://github.com/mariubog/oauth-client-sample to depict your situation because I could not find any samples for your scenario .

How to get all selected values of a multiple select box?

suppose the multiSelect is the Multiple-Select-Element, just use its selectedOptions Property:

//show all selected options in the console:

for ( var i = 0; i < multiSelect.selectedOptions.length; i++) {
  console.log( multiSelect.selectedOptions[i].value);
}

Add a string of text into an input field when user clicks a button

Here it is: http://jsfiddle.net/tQyvp/

Here's the code if you don't like going to jsfiddle:

html

<input id="myinputfield" value="This is some text" type="button">?

Javascript:

$('body').on('click', '#myinputfield', function(){
    var textField = $('#myinputfield');
    textField.val(textField.val()+' after clicking')       
});?

HTML input type=file, get the image before submitting the form

Image can not be shown until it serves from any server. so you need to upload the image to your server to show its preview.

findViewByID returns null

I was facing a similar problem when I was trying to do a custom view for a ListView.

I solved it simply by doing this:

public View getView(int i, View view, ViewGroup viewGroup) {

    // Gets the inflater
    LayoutInflater inflater = LayoutInflater.from(this.contexto);

    // Inflates the layout
    ConstraintLayout cl2 = (ConstraintLayout) 
    inflater.inflate(R.layout.custom_list_view, viewGroup, false);

    //Insted of calling just findViewById, I call de cl2.findViewById method. cl2 is the layout I have just inflated. 
     TextView tv1 = (TextView)cl2.findViewById(cl2);

Simple UDP example to send and receive data from same socket

I'll try to keep this short, I've done this a few months ago for a game I was trying to build, it does a UDP "Client-Server" connection that acts like TCP, you can send (message) (message + object) using this. I've done some testing with it and it works just fine, feel free to modify it if needed.

Maven Error: Could not find or load main class

I got this error using Maven, and I discovered the solution.

Error: Could not find or load main class com.mycompany.testapifactory.Main

I'm using java JDK version 1.7 on Linux, my pom.xml file was the default generated by Netbeans and I was using these commands to compile, which do work fine with a normal hello-world java application:

mvn clean compile
java -jar target/TestAPIFactory-1.0-SNAPSHOT.jar com.mycompany.testapifactory.Main

What happened:

It turns out my problem was that my Main method was extending something Exotic like this:

public class Main extends SomeExoticLibraryClass{
    public static void main(String[] args){
        //...
    }
}

It was this extending of the main class that caused the above error.

TLDR solution:

Make sure your main class isn't extending any 3rd party classes. Refactor those out and away into their own classes. That error message is awful, and requires process of elimination to find out what to do.

What is the purpose of the vshost.exe file?

Adding on, you can turn off the creation of vshost files for your Release build configuration and have it enabled for Debug.

Steps

  • Project Properties > Debug > Configuration (Release) > Disable the Visual Studio hosting process
  • Project Properties > Debug > Configuration (Debug) > Enable the Visual Studio hosting process

Screenshot from VS2010

Reference

  1. MSDN How to: Disable the Hosting Process
  2. MSDN Hosting Process (vshost.exe)

Excerpt from MSDN How to: Disable the Hosting Process

Calls to certain APIs can be affected when the hosting process is enabled. In these cases, it is necessary to disable the hosting process to return the correct results.

To disable the hosting process

  1. Open an executable project in Visual Studio. Projects that do not produce executables (for example, class library or service projects) do not have this option.
  2. On the Project menu, click Properties.
  3. Click the Debug tab.
  4. Clear the Enable the Visual Studio hosting process check box.

When the hosting process is disabled, several debugging features are unavailable or experience decreased performance. For more information, see Debugging and the Hosting Process.

In general, when the hosting process is disabled:

  • The time needed to begin debugging .NET Framework applications increases.
  • Design-time expression evaluation is unavailable.
  • Partial trust debugging is unavailable.

How to check string length with JavaScript

Basically: assign a keyup handler to the <textarea> element, in it count the length of the <textarea> and write the count to a separate <div> if its length is shorter than a minimum value.

Here's is an example-

_x000D_
_x000D_
var min = 15;_x000D_
document.querySelector('#tst').onkeyup = function(e){_x000D_
 document.querySelector('#counter').innerHTML = _x000D_
               this.value.length < min _x000D_
               ? (min - this.value.length)+' to go...'_x000D_
               : '';_x000D_
}_x000D_
    
_x000D_
body {font: normal 0.8em verdana, arial;}_x000D_
#counter {color: grey}
_x000D_
<textarea id="tst" cols="60" rows="10"></textarea>_x000D_
<div id="counter"></div>
_x000D_
_x000D_
_x000D_

Allow Access-Control-Allow-Origin header using HTML5 fetch API

If you are use nginx try this

#Control-Allow-Origin access

    # Authorization headers aren't passed in CORS preflight (OPTIONS) calls. Always return a 200 for options.
    add_header Access-Control-Allow-Credentials "true" always;
    add_header Access-Control-Allow-Origin "https://URL-WHERE-ORIGIN-FROM-HERE " always;
    add_header Access-Control-Allow-Methods "GET,OPTIONS" always;
    add_header Access-Control-Allow-Headers "x-csrf-token,authorization,content-type,accept,origin,x-requested-with,access-control-allow-origin" always;

    if ($request_method = OPTIONS ) {
        return 200;
    }

How do I use Assert to verify that an exception has been thrown?

Be wary of using ExpectedException, as it can lead to several pitfalls as demonstrated here:

http://geekswithblogs.net/sdorman/archive/2009/01/17/unit-testing-and-expected-exceptions.aspx

And here:

http://xunit.github.io/docs/comparisons.html

If you need to test for exceptions, there are less frowned upon ways. You can use the try{act/fail}catch{assert} method, which can be useful for frameworks that don't have direct support for exception tests other than ExpectedException.

A better alternative is to use xUnit.NET, which is a very modern, forward looking, and extensible unit testing framework that has learned from all the others mistakes, and improved. One such improvement is Assert.Throws, which provides a much better syntax for asserting exceptions.

You can find xUnit.NET at github: http://xunit.github.io/

Accessing member of base class

You are incorrectly using the super and this keyword. Here is an example of how they work:

class Animal {
    public name: string;
    constructor(name: string) { 
        this.name = name;
    }
    move(meters: number) {
        console.log(this.name + " moved " + meters + "m.");
    }
}

class Horse extends Animal {
    move() {
        console.log(super.name + " is Galloping...");
        console.log(this.name + " is Galloping...");
        super.move(45);
    }
}

var tom: Animal = new Horse("Tommy the Palomino");

Animal.prototype.name = 'horseee'; 

tom.move(34);
// Outputs:

// horseee is Galloping...
// Tommy the Palomino is Galloping...
// Tommy the Palomino moved 45m.

Explanation:

  1. The first log outputs super.name, this refers to the prototype chain of the object tom, not the object tom self. Because we have added a name property on the Animal.prototype, horseee will be outputted.
  2. The second log outputs this.name, the this keyword refers to the the tom object itself.
  3. The third log is logged using the move method of the Animal base class. This method is called from Horse class move method with the syntax super.move(45);. Using the super keyword in this context will look for a move method on the prototype chain which is found on the Animal prototype.

Remember TS still uses prototypes under the hood and the class and extends keywords are just syntactic sugar over prototypical inheritance.

Android - how to replace part of a string by another string?

rekaszeru

I noticed that you commented in 2011 but i thought i should post this answer anyway, in case anyone needs to "replace the original string" and runs into this answer ..

Im using a EditText as an example


// GIVE TARGET TEXT BOX A NAME

 EditText textbox = (EditText) findViewById(R.id.your_textboxID);

// STRING TO REPLACE

 String oldText = "hello"
 String newText = "Hi";      
 String textBoxText = textbox.getText().toString();

// REPLACE STRINGS WITH RETURNED STRINGS

String returnedString = textBoxText.replace( oldText, newText );

// USE RETURNED STRINGS TO REPLACE NEW STRING INSIDE TEXTBOX

textbox.setText(returnedString);

This is untested, but it's just an example of using the returned string to replace the original layouts string with setText() !

Obviously this example requires that you have a EditText with the ID set to your_textboxID

Parsing HTTP Response in Python

You can also use python's requests library instead.

import requests

url = 'http://www.quandl.com/api/v1/datasets/FRED/GDP.json'    
response = requests.get(url)    
dict = response.json()

Now you can manipulate the "dict" like a python dictionary.

Display text from .txt file in batch file

type log.txt

But that will give you the whole file. You could change it to:

echo %date%, %time% >> log.txt
echo %date%, %time% > log_last.txt
...
type log_last.txt

to get only the last one.

TSQL select into Temp table from dynamic sql

How I did it with a pivot in dynamic sql (#AccPurch was created prior to this)

DECLARE @sql AS nvarchar(MAX)
declare @Month Nvarchar(1000)

--DROP TABLE #temp
select distinct YYYYMM into #temp from #AccPurch AS ap
SELECT  @Month = COALESCE(@Month, '') + '[' + CAST(YYYYMM AS VarChar(8)) + '],' FROM    #temp

SELECT   @Month= LEFT(@Month,len(@Month)-1)


SET @sql = N'SELECT UserID, '+ @Month + N' into ##final_Donovan_12345 FROM (
Select ap.AccPurch ,
       ap.YYYYMM ,
       ap.UserID ,
       ap.AccountNumber
FROM #AccPurch AS ap 
) p
Pivot (SUM(AccPurch) FOR YYYYMM IN ('+@Month+ N')) as pvt'


EXEC sp_executesql @sql

Select * INTO #final From ##final_Donovan_12345

DROP TABLE  ##final_Donovan_12345

Select * From #final AS f

Javascript Audio Play on click

Now that the Web Audio API is here and gaining browser support, that could be a more robust option.

Zounds is a primitive wrapper around that API for playing simple one-shot sounds with a minimum of boilerplate at the point of use.

Use of "instanceof" in Java

instanceof is a keyword that can be used to test if an object is of a specified type.

Example :

public class MainClass {
    public static void main(String[] a) {

    String s = "Hello";
    int i = 0;
    String g;
    if (s instanceof java.lang.String) {
       // This is going to be printed
       System.out.println("s is a String");
    }
    if (i instanceof Integer) {
       // This is going to be printed as autoboxing will happen (int -> Integer)
       System.out.println("i is an Integer");
    }
    if (g instanceof java.lang.String) {
       // This case is not going to happen because g is not initialized and
       // therefore is null and instanceof returns false for null. 
       System.out.println("g is a String");
    } 
} 

Here is my source.

How to get min, seconds and milliseconds from datetime.now() in python?

Another similar solution:

>>> a=datetime.now()
>>> "%s:%s.%s" % (a.hour, a.minute, a.microsecond)
'14:28.971209'

Yes, I know I didn't get the string formatting perfect.

Convert JsonObject to String

You can try Gson convertor, to get the exact conversion like json.stringify

val jsonString:String = jsonObject.toString()
val gson:Gson = GsonBuilder().setPrettyPrinting().create()
val json:JsonElement = gson.fromJson(jsonString,JsonElement.class)
val jsonInString:String= gson.toJson(json)
println(jsonInString)

How to trigger a build only if changes happen on particular set of files

I answered this question in another post:

How to get list of changed files since last build in Jenkins/Hudson

#!/bin/bash

set -e

job_name="whatever"
JOB_URL="http://myserver:8080/job/${job_name}/"
FILTER_PATH="path/to/folder/to/monitor"

python_func="import json, sys
obj = json.loads(sys.stdin.read())
ch_list = obj['changeSet']['items']
_list = [ j['affectedPaths'] for j in ch_list ]
for outer in _list:
  for inner in outer:
    print inner
"

_affected_files=`curl --silent ${JOB_URL}${BUILD_NUMBER}'/api/json' | python -c "$python_func"`

if [ -z "`echo \"$_affected_files\" | grep \"${FILTER_PATH}\"`" ]; then
  echo "[INFO] no changes detected in ${FILTER_PATH}"
  exit 0
else
  echo "[INFO] changed files detected: "
  for a_file in `echo "$_affected_files" | grep "${FILTER_PATH}"`; do
    echo "    $a_file"
  done;
fi;

You can add the check directly to the top of the job's exec shell, and it will exit 0 if no changes are detected... Hence, you can always poll the top level for check-in's to trigger a build.

Is there a conditional ternary operator in VB.NET?

iif has always been available in VB, even in VB6.

Dim foo as String = iif(bar = buz, cat, dog)

It is not a true operator, as such, but a function in the Microsoft.VisualBasic namespace.

What, exactly, is needed for "margin: 0 auto;" to work?

Please go to this quick example I've created jsFiddle. Hopefull it's easy to understand. You can use a wrapper div with the width of the site to center align. The reason you must put width is that so browser knows you are not going for a liquid layout.

How to debug .htaccess RewriteRule not working

Perhaps a more logical method would be to create a file (e.g. test.html), add some content and then try to set it as the index page:

DirectoryIndex test.html

For the most part, the .htaccess rule will override the Apache configuration where working at the directory/file level

.append(), prepend(), .after() and .before()

There is a basic difference between .append() and .after() and .prepend() and .before().

.append() adds the parameter element inside the selector element's tag at the very end whereas the .after() adds the parameter element after the element's tag.

The vice-versa is for .prepend() and .before().

Fiddle

Convert bytes to a string

I think you actually want this:

>>> from subprocess import *
>>> command_stdout = Popen(['ls', '-l'], stdout=PIPE).communicate()[0]
>>> command_text = command_stdout.decode(encoding='windows-1252')

Aaron's answer was correct, except that you need to know which encoding to use. And I believe that Windows uses 'windows-1252'. It will only matter if you have some unusual (non-ASCII) characters in your content, but then it will make a difference.

By the way, the fact that it does matter is the reason that Python moved to using two different types for binary and text data: it can't convert magically between them, because it doesn't know the encoding unless you tell it! The only way YOU would know is to read the Windows documentation (or read it here).

Python Loop: List Index Out of Range

Try reducing the range of the for loop to range(len(a)-1):

a = [0,1,2,3]
b = []

for i in range(len(a)-1):
    b.append(a[i]+a[i+1])

print(b)

This can also be written as a list comprehension:

b = [a[i] + a[i+1] for i in range(len(a)-1)]
print(b)

Rails 2.3.4 Persisting Model on Validation Failure

In your controller, render the new action from your create action if validation fails, with an instance variable, @car populated from the user input (i.e., the params hash). Then, in your view, add a logic check (either an if block around the form or a ternary on the helpers, your choice) that automatically sets the value of the form fields to the params values passed in to @car if car exists. That way, the form will be blank on first visit and in theory only be populated on re-render in the case of error. In any case, they will not be populated unless @car is set.

BitBucket - download source as ZIP

For the latest version of Bitbucket (2016+), the download link can be found in the Download menu item.

enter image description here


Pre-2016

First method

In the Overview page of the repo, there is a link to download the project.

Direct download of a repo


Second method

Go to Downloads -> Branches -> Download the branch that you want (as .zip, .gz or .bz2). There you'll find download links for all tags. The links will be in the format:

https://bitbucket.org/owner/repository/get/v0.1.2.tar.gz

By tweaking it a little bit, you can also have access to any revision by changing the tag to the commit hash:

https://bitbucket.org/owner/repository/get/A0B1C2D.tar.gz

How to solve npm install throwing fsevents warning on non-MAC OS?

I also had the same issue though am using MacOS. The issue is kind of bug. I solved this issue by repeatedly running the commands,

sudo npm cache clean --force 
sudo npm uninstall 
sudo npm install

One time it did not work but when I repeatedly cleaned the cache and after uninstalling npm, reinstalling npm, the error went off. I am using Angular 8 and this issue is common

How the int.TryParse actually works

TryParse is the best way for parse or validate in single line:

int nNumber = int.TryParse("InputString", out nNumber) ? nNumber : 1;

Short description:

  1. nNumber will initialize with zero,
  2. int.TryParse() try parse "InputString" and validate it, if succeed set into nNumber.
  3. short if ?: checking int.TryParse() result, that return nNumber or 1 as default value.

What are examples of TCP and UDP in real life?

REAL TIME APPLICATION FOR TCP:

Email:

Reason: suppose if some packet(words/statement) is missing we cannot understand the content.It should be reliable.

REAL TIME APPLICATION FOR UDP:

video streaming:

* **Reason: ***suppose if some packet(frame/sequence) is missing we can understand the content.Because video is collection of frames.For 1 second video there should be 25 frames(image).Even though we can understand some frames are missing due to our imagination skills. Thats why UDP is used for video streaming.

Javascript: formatting a rounded number to N decimals

That's not a rounding ploblem, that is a display problem. A number doesn't contain information about significant digits; the value 2 is the same as 2.0000000000000. It's when you turn the rounded value into a string that you have make it display a certain number of digits.

You could just add zeroes after the number, something like:

var s = number.toString();
if (s.indexOf('.') == -1) s += '.';
while (s.length < s.indexOf('.') + 4) s += '0';

(Note that this assumes that the regional settings of the client uses period as decimal separator, the code needs some more work to function for other settings.)

Creating a new column based on if-elif-else condition

When you have multiple if conditions, numpy.select is the way to go:

In [4102]: import numpy as np
In [4098]: conditions = [df.A.eq(df.B), df.A.gt(df.B), df.A.lt(df.B)]
In [4096]: choices = [0, 1, -1]

In [4100]: df['C'] = np.select(conditions, choices)

In [4101]: df
Out[4101]: 
   A  B  C
a  2  2  0
b  3  1  1
c  1  3 -1

Why is jquery's .ajax() method not sending my session cookie?

Perhaps not 100% answering the question, but i stumbled onto this thread in the hope of solving a session problem when ajax-posting a fileupload from the assetmanager of the innovastudio editor. Eventually the solution was simple: they have a flash-uploader. Disabling that (setting

var flashUpload = false;   

in asset.php) and the lights started blinking again.

As these problems can be very hard to debug i found that putting something like the following in the upload handler will set you (well, me in this case) on the right track:

$sn=session_name();
error_log("session_name: $sn ");

if(isset($_GET[$sn])) error_log("session as GET param");
if(isset($_POST[$sn])) error_log("session as POST param");
if(isset($_COOKIE[$sn])) error_log("session as Cookie");
if(isset($PHPSESSID)) error_log("session as Global");

A dive into the log and I quickly spotted the missing session, where no cookie was sent.

Opposite of append in jquery

Use the remove() method:

$(this).children("ul").remove();

INNER JOIN vs LEFT JOIN performance in SQL Server

A LEFT JOIN is absolutely not faster than an INNER JOIN. In fact, it's slower; by definition, an outer join (LEFT JOIN or RIGHT JOIN) has to do all the work of an INNER JOIN plus the extra work of null-extending the results. It would also be expected to return more rows, further increasing the total execution time simply due to the larger size of the result set.

(And even if a LEFT JOIN were faster in specific situations due to some difficult-to-imagine confluence of factors, it is not functionally equivalent to an INNER JOIN, so you cannot simply go replacing all instances of one with the other!)

Most likely your performance problems lie elsewhere, such as not having a candidate key or foreign key indexed properly. 9 tables is quite a lot to be joining so the slowdown could literally be almost anywhere. If you post your schema, we might be able to provide more details.


Edit:

Reflecting further on this, I could think of one circumstance under which a LEFT JOIN might be faster than an INNER JOIN, and that is when:

  • Some of the tables are very small (say, under 10 rows);
  • The tables do not have sufficient indexes to cover the query.

Consider this example:

CREATE TABLE #Test1
(
    ID int NOT NULL PRIMARY KEY,
    Name varchar(50) NOT NULL
)
INSERT #Test1 (ID, Name) VALUES (1, 'One')
INSERT #Test1 (ID, Name) VALUES (2, 'Two')
INSERT #Test1 (ID, Name) VALUES (3, 'Three')
INSERT #Test1 (ID, Name) VALUES (4, 'Four')
INSERT #Test1 (ID, Name) VALUES (5, 'Five')

CREATE TABLE #Test2
(
    ID int NOT NULL PRIMARY KEY,
    Name varchar(50) NOT NULL
)
INSERT #Test2 (ID, Name) VALUES (1, 'One')
INSERT #Test2 (ID, Name) VALUES (2, 'Two')
INSERT #Test2 (ID, Name) VALUES (3, 'Three')
INSERT #Test2 (ID, Name) VALUES (4, 'Four')
INSERT #Test2 (ID, Name) VALUES (5, 'Five')

SELECT *
FROM #Test1 t1
INNER JOIN #Test2 t2
ON t2.Name = t1.Name

SELECT *
FROM #Test1 t1
LEFT JOIN #Test2 t2
ON t2.Name = t1.Name

DROP TABLE #Test1
DROP TABLE #Test2

If you run this and view the execution plan, you'll see that the INNER JOIN query does indeed cost more than the LEFT JOIN, because it satisfies the two criteria above. It's because SQL Server wants to do a hash match for the INNER JOIN, but does nested loops for the LEFT JOIN; the former is normally much faster, but since the number of rows is so tiny and there's no index to use, the hashing operation turns out to be the most expensive part of the query.

You can see the same effect by writing a program in your favourite programming language to perform a large number of lookups on a list with 5 elements, vs. a hash table with 5 elements. Because of the size, the hash table version is actually slower. But increase it to 50 elements, or 5000 elements, and the list version slows to a crawl, because it's O(N) vs. O(1) for the hashtable.

But change this query to be on the ID column instead of Name and you'll see a very different story. In that case, it does nested loops for both queries, but the INNER JOIN version is able to replace one of the clustered index scans with a seek - meaning that this will literally be an order of magnitude faster with a large number of rows.

So the conclusion is more or less what I mentioned several paragraphs above; this is almost certainly an indexing or index coverage problem, possibly combined with one or more very small tables. Those are the only circumstances under which SQL Server might sometimes choose a worse execution plan for an INNER JOIN than a LEFT JOIN.

Default visibility for C# classes and members (fields, methods, etc.)?

By default is private. Unless they're nested, classes are internal.

How do I append text to a file?

cat >> filename
This is text, perhaps pasted in from some other source.
Or else entered at the keyboard, doesn't matter. 
^D

Essentially, you can dump any text you want into the file. CTRL-D sends an end-of-file signal, which terminates input and returns you to the shell.

How to change package name in android studio?

In projects that use the Gradle build system, what you want to change is the applicationId in the build.gradle file. The build system uses this value to override anything specified by hand in the manifest file when it does the manifest merge and build.

For example, your module's build.gradle file looks something like this:

apply plugin: 'com.android.application'

android {
    compileSdkVersion 20
    buildToolsVersion "20.0.0"

    defaultConfig {
        // CHANGE THE APPLICATION ID BELOW
        applicationId "com.example.fred.myapplication"
        minSdkVersion 10
        targetSdkVersion 20
        versionCode 1
        versionName "1.0"
    }
}

applicationId is the name the build system uses for the property that eventually gets written to the package attribute of the manifest tag in the manifest file. It was renamed to prevent confusion with the Java package name (which you have also tried to modify), which has nothing to do with it.

Search for string within text column in MySQL

you mean:

SELECT * FROM items WHERE items.xml LIKE '%123456%'

Split string into string array of single characters

You can just use String.ToCharArray() and then treat each char as a string in your code.

Here's an example:

    foreach (char c in s.ToCharArray())
        Debug.Log("one character ... " +c);

How do I export an Android Studio project?

Apparently, there's a lot of "dead wood" in the "build" directories of a project.

Under linux/unix, a simple way to get a clean, private backup is to use the "tar" command along with the "--exclude=String" option.

For example, to create an archive of all my apps while excluding the build directories, I have a script that creates the following 2 commands :

cd $HOME/android/Studio
tar cvf MyBackup-2017-07-13.tar Projects --exclude=build

What is the difference between Html.Hidden and Html.HiddenFor

The Html.Hidden creates a hidden input but you have to specify the name and all the attributes you want to give that field and value. The Html.HiddenFor creates a hidden input for the object that you pass to it, they look like this:

Html.Hidden("yourProperty",model.yourProperty);

Html.HiddenFor(m => m.yourProperty)

In this case the output is the same!

wampserver doesn't go green - stays orange

I have had this issue before and it turned out that Skype was interferring with port 80. So you may have to look at your system to see if you have another application utilizing this port.

Anyway under Skype, to change this setting it was: Tools->Options->Advanced->Connection->Use port 80 and 443 as alternatives for incoming connections. Untick this, restart Skype, restart wamp.

Related question

How to make Bootstrap carousel slider use mobile left/right swipe

I'm a bit late to the party, but here's a bit of jQuery I've been using:

$('.carousel').on('touchstart', function(event){
    const xClick = event.originalEvent.touches[0].pageX;
    $(this).one('touchmove', function(event){
        const xMove = event.originalEvent.touches[0].pageX;
        const sensitivityInPx = 5;

        if( Math.floor(xClick - xMove) > sensitivityInPx ){
            $(this).carousel('next');
        }
        else if( Math.floor(xClick - xMove) < -sensitivityInPx ){
            $(this).carousel('prev');
        }
    });
    $(this).on('touchend', function(){
        $(this).off('touchmove');
    });
});

No need for jQuery mobile or any other plugins. If you need to adjust the sensitivity of the swipe adjust the 5 and -5. Hope this helps someone.

What is the actual use of Class.forName("oracle.jdbc.driver.OracleDriver") while connecting to a database?

This command loads class of Oracle jdbc driver to be available for DriverManager instance. After the class is loaded system can connect to Oracle using it. As an alternative you can use registerDriver method of DriverManager and pass it with instance of JDBC driver you need.

Can I use a case/switch statement with two variables?

Yeah, But not in a normal way. You will have to use switch as closure.

ex:-

function test(input1, input2) {
     switch (true) {
        case input1 > input2:
                    console.log(input1 + " is larger than " + input2);
                    break;
        case input1 < input2:
                    console.log(input2 + " is larger than " + input1);
        default:
                    console.log(input1 + " is equal to " + input2);
      }
   }

Warning: mysqli_num_rows() expects parameter 1 to be mysqli_result, boolean given in

The problem is your query returned false meaning there was an error in your query. After your query you could do the following:

if (!$result) {
    die(mysqli_error($link));
}

Or you could combine it with your query:

$results = mysqli_query($link, $query) or die(mysqli_error($link));

That will print out your error.

Also... you need to sanitize your input. You can't just take user input and put that into a query. Try this:

$query = "SELECT * FROM shopsy_db WHERE name LIKE '%" . mysqli_real_escape_string($link, $searchTerm) . "%'";

In reply to: Table 'sookehhh_shopsy_db.sookehhh_shopsy_db' doesn't exist

Are you sure the table name is sookehhh_shopsy_db? maybe it's really like users or something.

Singleton in Android

EDIT :

The implementation of a Singleton in Android is not "safe" (see here) and you should use a library dedicated to this kind of pattern like Dagger or other DI library to manage the lifecycle and the injection.


Could you post an example from your code ?

Take a look at this gist : https://gist.github.com/Akayh/5566992

it works but it was done very quickly :

MyActivity : set the singleton for the first time + initialize mString attribute ("Hello") in private constructor and show the value ("Hello")

Set new value to mString : "Singleton"

Launch activityB and show the mString value. "Singleton" appears...

Is there a JavaScript strcmp()?

Javascript doesn't have it, as you point out.

A quick search came up with:

function strcmp ( str1, str2 ) {
    // http://kevin.vanzonneveld.net
    // +   original by: Waldo Malqui Silva
    // +      input by: Steve Hilder
    // +   improved by: Kevin van Zonneveld (http://kevin.vanzonneveld.net)
    // +    revised by: gorthaur
    // *     example 1: strcmp( 'waldo', 'owald' );
    // *     returns 1: 1
    // *     example 2: strcmp( 'owald', 'waldo' );
    // *     returns 2: -1

    return ( ( str1 == str2 ) ? 0 : ( ( str1 > str2 ) ? 1 : -1 ) );
}

from http://kevin.vanzonneveld.net/techblog/article/javascript_equivalent_for_phps_strcmp/

Of course, you could just add localeCompare if needed:

if (typeof(String.prototype.localeCompare) === 'undefined') {
    String.prototype.localeCompare = function(str, locale, options) {
        return ((this == str) ? 0 : ((this > str) ? 1 : -1));
    };
}

And use str1.localeCompare(str2) everywhere, without having to worry wether the local browser has shipped with it. The only problem is that you would have to add support for locales and options if you care about that.

CSS values using HTML5 data attribute

You can create with javascript some css-rules, which you can later use in your styles: http://jsfiddle.net/ARTsinn/vKbda/

var addRule = (function (sheet) {
    if(!sheet) return;
    return function (selector, styles) {
        if (sheet.insertRule) return sheet.insertRule(selector + " {" + styles + "}", sheet.cssRules.length);
        if (sheet.addRule) return sheet.addRule(selector, styles);
    }
}(document.styleSheets[document.styleSheets.length - 1]));

var i = 101;
while (i--) {
    addRule("[data-width='" + i + "%']", "width:" + i + "%");
}

This creates 100 pseudo-selectors like this:

[data-width='1%'] { width: 1%; }
[data-width='2%'] { width: 2%; }
[data-width='3%'] { width: 3%; }
...
[data-width='100%'] { width: 100%; }

Note: This is a bit offtopic, and not really what you (or someone) wants, but maybe helpful.

Send SMTP email using System.Net.Mail via Exchange Online (Office 365)

Here is a side note for some that may be searching this thread for an answer to this problem. (Be sure to read cautions at the bottom before implementing this solution.) I was having trouble sending emails for a client to which my MS Office 365 subscription did not have a user or domain for. I was trying to SMTP through my [email protected] 365 account but the .NET mail message was addressed from [email protected]. This is when the "5.7.1 Client does not have permissions" error popped up for me. To remedy, the MailMessage class needed to have the Sender property set to an email address that my supplied SMTP credentials had permission in O365 to "Send As". I chose to use my main account email ([email protected]) as seen in the code below. Keep in mind I could have used ANY email address my O365 account had permission to "send as" (i.e. [email protected], [email protected], etc.)

using System;
using System.Net.Mail;

namespace ConsoleApplication1
{
   class Program
   {
      static void Main(string[] args)
      {
         using (
            MailMessage message = new MailMessage
            {
               To = { new MailAddress("[email protected]", "Recipient 1") },
               Sender = new MailAddress("[email protected]", "Me"),
               From = new MailAddress("[email protected]", "Client"),
               Subject=".net Testing"
               Body="Testing .net emailing",
               IsBodyHtml=true,
            }
         )
         {
            using (
               SmtpClient smtp = new SmtpClient
               {
                  Host = "smtp.office365.com",
                  Port = 587,
                  Credentials = new System.Net.NetworkCredential("[email protected]", "Pa55w0rd"),
                  EnableSsl = true
               }
            )
            {
               try { smtp.Send(message); }
               catch (Exception excp)
               {
                  Console.Write(excp.Message);
                  Console.ReadKey();
               }
            }
         }
      }
   }
}

Please note SmtpClient is only disposable and able to use the Using block in .NET Framework 4
Users of .NET Framework 2 through 3.5 should use SmtpClient as such...

SmtpClient smtp = new SmtpClient
{
   Host = "smtp.office365.com",
   Port = 587,
   Credentials = new System.Net.NetworkCredential("[email protected]", "Pa55w0rd"),
   EnableSsl = true
};
try { smtp.Send(message); }
catch (Exception excp)
{
   Console.Write(excp.Message);
   Console.ReadKey();
}

The resulting email's header will look something like this:

Authentication-Results: spf=none (sender IP is )  
   [email protected];  
Received: from MyPC (192.168.1.1) by  
   BLUPR13MB0036.namprd13.prod.outlook.com (10.161.123.150) with Microsoft SMTP  
   Server (TLS) id 15.1.318.9; Mon, 9 Nov 2015 16:06:58 +0000  
MIME-Version: 1.0  
From: Client <[email protected]>  
Sender: Me <[email protected]>  
To: Recipient 1 <[email protected]>  

-- Be Cautious --
Be aware some mail clients may display the Sender address as a note. For example Outlook will display something along these lines in the Reading Pane's header:

Me <[email protected]> on behalf of Client <[email protected]>

However, so long as the email client the recipient uses isn't total garbage, this shouldn't effect the Reply To address. Reply To should still use the From address. To cover all your bases, you can also utilize the MailMessage.ReplyToList property to afford every opportunity to the client to use the correct reply address.

Also, be aware that some email servers may flat out reject any emails that are Sent On Behalf of another company siting Domain Owner Policy Restrictions. Be sure to test thoroughly and look for any bounce backs. I can tell you that my personal Hotmail (mail.live.com) email account is one that will reject messages I send on behalf of a certain client of mine but others clients go through fine. Although I suspect that it has something to do with my client's domain TXT "spf1" records, I do not have an answer as to why it will reject emails sent on behalf of one domain versus another. Maybe someone who knows can shed some light on the subject?

How do I check in python if an element of a list is empty?

Suppose

letter= ['a','','b','c']

for i in range(len(letter)):
    if letter[i] =='':
        print(str(i) + ' is empty')

output- 1 is emtpy

So we can see index 1 is empty.

Using a string variable as a variable name

You can use exec for that:

>>> foo = "bar"
>>> exec(foo + " = 'something else'")
>>> print bar
something else
>>> 

How to programmatically connect a client to a WCF service?

You can also do what the "Service Reference" generated code does

public class ServiceXClient : ClientBase<IServiceX>, IServiceX
{
    public ServiceXClient() { }

    public ServiceXClient(string endpointConfigurationName) :
        base(endpointConfigurationName) { }

    public ServiceXClient(string endpointConfigurationName, string remoteAddress) :
        base(endpointConfigurationName, remoteAddress) { }

    public ServiceXClient(string endpointConfigurationName, EndpointAddress remoteAddress) :
        base(endpointConfigurationName, remoteAddress) { }

    public ServiceXClient(Binding binding, EndpointAddress remoteAddress) :
        base(binding, remoteAddress) { }

    public bool ServiceXWork(string data, string otherParam)
    {
        return base.Channel.ServiceXWork(data, otherParam);
    }
}

Where IServiceX is your WCF Service Contract

Then your client code:

var client = new ServiceXClient(new WSHttpBinding(SecurityMode.None), new EndpointAddress("http://localhost:911"));
client.ServiceXWork("data param", "otherParam param");

Array inside a JavaScript Object?

// define
var foo = {
  bar: ['foo', 'bar', 'baz']
};

// access
foo.bar[2]; // will give you 'baz'

TypeScript: Creating an empty typed container array

Please try this which it works for me.

return [] as Criminal[];

Loading PictureBox Image from resource file with path (Part 3)

It depends on your file path. For me, the current directory was [project]\bin\Debug, so I had to move to the parent folder twice.

Image image = Image.FromFile(@"..\..\Pictures\"+text+".png");
this.pictureBox1.Image = image;

To find your current directory, you can make a dummy label called label2 and write this:

this.label2.Text = System.IO.Directory.GetCurrentDirectory();

How to access global js variable in AngularJS directive

I have tried these methods and find that they dont work for my needs. In my case, I needed to inject json rendered server side into the main template of the page, so when it loads and angular inits, the data is already there and doesnt have to be retrieved (large dataset).

The easiest solution that I have found is to do the following:

In your angular code outside of the app, module and controller definitions add in a global javascript value - this definition MUST come before the angular stuff is defined.

Example:

'use strict';

//my data variable that I need access to.
var data = null;

angular.module('sample', [])

Then in your controller:

.controller('SampleApp', function ($scope, $location) {

$scope.availableList = [];

$scope.init = function () {
    $scope.availableList = data;
}

Finally, you have to init everything (order matters):

  <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.3.15/angular.min.js"></script>
  <script src="/path/to/your/angular/js/sample.js"></script>
  <script type="text/javascript">
      data = <?= json_encode($cproducts); ?>
  </script>

Finally initialize your controller and init function.

  <div ng-app="samplerrelations" ng-controller="SamplerApp" ng-init="init();">

By doing this you will now have access to whatever data you stuffed into the global variable.

vertical align middle in <div>

You can use Line height a big as height of the div. But for me best solution is this --> position:relative; top:50%; transform:translate(0,50%);

How to delete an instantiated object Python?

object.__del__(self) is called when the instance is about to be destroyed.

>>> class Test:
...     def __del__(self):
...         print "deleted"
... 
>>> test = Test()
>>> del test
deleted

Object is not deleted unless all of its references are removed(As quoted by ethan)

Also, From Python official doc reference:

del x doesn’t directly call x.del() — the former decrements the reference count for x by one, and the latter is only called when x‘s reference count reaches zero

How to convert all text to lowercase in Vim

Similar to mangledorf's solution, but shorter and layman friendly

:%s/.*/\L&/g

Regex for 1 or 2 digits, optional non-alphanumeric, 2 known alphas

^[0-9]{1,2}[:.,-]?po$

Add any other allowable non-alphanumeric characters to the middle brackets to allow them to be parsed as well.

Multiple conditions in a C 'for' loop

Of course it is right what you say at the beginning, and C logical operator && and || are what you usually use to "connect" conditions (expressions that can be evaluated as true or false); the comma operator is not a logical operator and its use in that example makes no sense, as explained by other users. You can use it e.g. to "concatenate" statements in the for itself: you can initialize and update j altogether with i; or use the comma operator in other ways

#include <stdio.h>

int main(void)  // as std wants
{
  int i, j;

  // init both i and j; condition, we suppose && is the "original"
  // intention; update i and j
  for(i=0, j=2; j>=0 && i<=5; i++, j--)
  {
       printf("%d ", i+j);
  }
  return 0;        
}

Increase bootstrap dropdown menu width

Add the following css class

.dropdown-menu {
    width: 300px !important;
    height: 400px !important;
}

Of course you can use what matches your need.

ReactJS SyntheticEvent stopPropagation() only works with React events?

I ran into this problem yesterday, so I created a React-friendly solution.

Check out react-native-listener. It's working very well so far. Feedback appreciated.

m2eclipse not finding maven dependencies, artifacts not found

I had this issue for dependencies that were created in other projects. Downloaded thirdparty dependencies showed up fine in the build path, but not a library that I had created.

SOLUTION: In the project that is not building correctly, right-click on the project and choose Properties, and then Maven. Uncheck the box labeled "Resolve dependencies from Workspace projects", hit Apply, and then OK. Right-click again on your project and do a Maven->Update Snapshots (or Update Dependencies) and your errors should go away when your project rebuilds (automatically if you have auto-build enabled).

How to convert ZonedDateTime to Date?

The accepted answer did not work for me. The Date returned is always the local Date and not the Date for the original Time Zone. I live in UTC+2.

//This did not work for me
Date.from(java.time.ZonedDateTime.now().toInstant()); 

I have come up with two alternative ways to get the correct Date from a ZonedDateTime.

Say you have this ZonedDateTime for Hawaii

LocalDateTime ldt = LocalDateTime.now();
ZonedDateTime zdt = ldt.atZone(ZoneId.of("US/Hawaii"); // UTC-10

or for UTC as asked originally

Instant zulu = Instant.now(); // GMT, UTC+0
ZonedDateTime zdt = zulu.atZone(ZoneId.of("UTC"));

Alternative 1

We can use java.sql.Timestamp. It is simple but it will probably also make a dent in your programming integrity

Date date1 = Timestamp.valueOf(zdt.toLocalDateTime());

Alternative 2

We create the Date from millis (answered here earlier). Note that local ZoneOffset is a must.

ZoneOffset localOffset = ZoneOffset.systemDefault().getRules().getOffset(LocalDateTime.now());
long zonedMillis = 1000L * zdt.toLocalDateTime().toEpochSecond(localOffset) + zdt.toLocalDateTime().getNano() / 1000000L;
Date date2 = new Date(zonedMillis);

Choosing the correct upper and lower HSV boundaries for color detection with`cv::inRange` (OpenCV)

I Created this simple program to get HSV Codes in realtime

import cv2
import numpy as np


cap = cv2.VideoCapture(0)

def nothing(x):
    pass
# Creating a window for later use
cv2.namedWindow('result')

# Starting with 100's to prevent error while masking
h,s,v = 100,100,100

# Creating track bar
cv2.createTrackbar('h', 'result',0,179,nothing)
cv2.createTrackbar('s', 'result',0,255,nothing)
cv2.createTrackbar('v', 'result',0,255,nothing)

while(1):

    _, frame = cap.read()

    #converting to HSV
    hsv = cv2.cvtColor(frame,cv2.COLOR_BGR2HSV)

    # get info from track bar and appy to result
    h = cv2.getTrackbarPos('h','result')
    s = cv2.getTrackbarPos('s','result')
    v = cv2.getTrackbarPos('v','result')

    # Normal masking algorithm
    lower_blue = np.array([h,s,v])
    upper_blue = np.array([180,255,255])

    mask = cv2.inRange(hsv,lower_blue, upper_blue)

    result = cv2.bitwise_and(frame,frame,mask = mask)

    cv2.imshow('result',result)

    k = cv2.waitKey(5) & 0xFF
    if k == 27:
        break

cap.release()

cv2.destroyAllWindows()

How to prevent caching of my Javascript file?

Configure your webserver to send caching control HTTP headers for the script.

Fake headers in the HTML documents:

  1. Aren't as well supported as real HTTP headers
  2. Apply to the HTML document, not to resources that it links to

catching stdout in realtime from subprocess

Some rules of thumb for subprocess.

  • Never use shell=True. It needlessly invokes an extra shell process to call your program.
  • When calling processes, arguments are passed around as lists. sys.argv in python is a list, and so is argv in C. So you pass a list to Popen to call subprocesses, not a string.
  • Don't redirect stderr to a PIPE when you're not reading it.
  • Don't redirect stdin when you're not writing to it.

Example:

import subprocess, time, os, sys
cmd = ["rsync.exe", "-vaz", "-P", "source/" ,"dest/"]

p = subprocess.Popen(cmd,
                     stdout=subprocess.PIPE,
                     stderr=subprocess.STDOUT)

for line in iter(p.stdout.readline, b''):
    print(">>> " + line.rstrip())

That said, it is probable that rsync buffers its output when it detects that it is connected to a pipe instead of a terminal. This is the default behavior - when connected to a pipe, programs must explicitly flush stdout for realtime results, otherwise standard C library will buffer.

To test for that, try running this instead:

cmd = [sys.executable, 'test_out.py']

and create a test_out.py file with the contents:

import sys
import time
print ("Hello")
sys.stdout.flush()
time.sleep(10)
print ("World")

Executing that subprocess should give you "Hello" and wait 10 seconds before giving "World". If that happens with the python code above and not with rsync, that means rsync itself is buffering output, so you are out of luck.

A solution would be to connect direct to a pty, using something like pexpect.

Remove a child with a specific attribute, in SimpleXML for PHP

While SimpleXML provides a way to remove XML nodes, its modification capabilities are somewhat limited. One other solution is to resort to using the DOM extension. dom_import_simplexml() will help you with converting your SimpleXMLElement into a DOMElement.

Just some example code (tested with PHP 5.2.5):

$data='<data>
    <seg id="A1"/>
    <seg id="A5"/>
    <seg id="A12"/>
    <seg id="A29"/>
    <seg id="A30"/>
</data>';
$doc=new SimpleXMLElement($data);
foreach($doc->seg as $seg)
{
    if($seg['id'] == 'A12') {
        $dom=dom_import_simplexml($seg);
        $dom->parentNode->removeChild($dom);
    }
}
echo $doc->asXml();

outputs

<?xml version="1.0"?>
<data><seg id="A1"/><seg id="A5"/><seg id="A29"/><seg id="A30"/></data>

By the way: selecting specific nodes is much more simple when you use XPath (SimpleXMLElement->xpath):

$segs=$doc->xpath('//seq[@id="A12"]');
if (count($segs)>=1) {
    $seg=$segs[0];
}
// same deletion procedure as above

How to cut first n and last n columns?

To use AWK to cut off the first and last fields:

awk '{$1 = ""; $NF = ""; print}' inputfile

Unfortunately, that leaves the field separators, so

aaa bbb ccc

becomes

[space]bbb[space]

To do this using kurumi's answer which won't leave extra spaces, but in a way that's specific to your requirements:

awk '{delim = ""; for (i=2;i<=NF-1;i++) {printf delim "%s", $i; delim = OFS}; printf "\n"}' inputfile

This also fixes a couple of problems in that answer.

To generalize that:

awk -v skipstart=1 -v skipend=1 '{delim = ""; for (i=skipstart+1;i<=NF-skipend;i++) {printf delim "%s", $i; delim = OFS}; printf "\n"}' inputfile

Then you can change the number of fields to skip at the beginning or end by changing the variable assignments at the beginning of the command.

How to keep console window open

You can handle this without requiring a user input.

Step 1. Create a ManualRestEvent at the start of Main thread

ManualResetEvent manualResetEvent = new ManualResetEvent(false);

Step 2 . Wait ManualResetEvent

manualResetEvent.WaitOne();

Step 3.To Stop

manualResetEvent.Set();

Java8: HashMap<X, Y> to HashMap<X, Z> using Stream / Map-Reduce / Collector

Does it absolutely have to be 100% functional and fluent? If not, how about this, which is about as short as it gets:

Map<String, Integer> output = new HashMap<>();
input.forEach((k, v) -> output.put(k, Integer.valueOf(v));

(if you can live with the shame and guilt of combining streams with side-effects)

I want to align the text in a <td> to the top

Use <td valign="top" style="width: 259px"> instead...

How do I convert a Swift Array to a String?

With Swift 5, according to your needs, you may choose one of the following Playground sample codes in order to solve your problem.


Turning an array of Characters into a String with no separator:

let characterArray: [Character] = ["J", "o", "h", "n"]
let string = String(characterArray)

print(string)
// prints "John"

Turning an array of Strings into a String with no separator:

let stringArray = ["Bob", "Dan", "Bryan"]
let string = stringArray.joined(separator: "")

print(string) // prints: "BobDanBryan"

Turning an array of Strings into a String with a separator between words:

let stringArray = ["Bob", "Dan", "Bryan"]
let string = stringArray.joined(separator: " ")

print(string) // prints: "Bob Dan Bryan"

Turning an array of Strings into a String with a separator between characters:

let stringArray = ["car", "bike", "boat"]
let characterArray = stringArray.flatMap { $0 }
let stringArray2 = characterArray.map { String($0) }
let string = stringArray2.joined(separator: ", ")

print(string) // prints: "c, a, r, b, i, k, e, b, o, a, t"

Turning an array of Floats into a String with a separator between numbers:

let floatArray = [12, 14.6, 35]
let stringArray = floatArray.map { String($0) }
let string = stringArray.joined(separator: "-")

print(string)
// prints "12.0-14.6-35.0"

Scrolling a flexbox with overflowing content

The solution for this problem is just to add overflow: auto; to the .content for making the content wrapper scrollable.

Furthermore, there are circumstances occurring along with Flexbox wrapper and overflowed scrollable content like this codepen.

The solution is to add overflow: hidden (or auto); to the parent of the wrapper (set with overflow: auto;) around large contents.

Check date between two other dates spring data jpa

You should take a look the reference documentation. It's well explained.

In your case, I think you cannot use between because you need to pass two parameters

Between - findByStartDateBetween … where x.startDate between ?1 and ?2

In your case take a look to use a combination of LessThan or LessThanEqual with GreaterThan or GreaterThanEqual

  • LessThan/LessThanEqual

LessThan - findByEndLessThan … where x.start< ?1

LessThanEqual findByEndLessThanEqual … where x.start <= ?1

  • GreaterThan/GreaterThanEqual

GreaterThan - findByStartGreaterThan … where x.end> ?1

GreaterThanEqual - findByStartGreaterThanEqual … where x.end>= ?1

You can use the operator And and Or to combine both.

Is there a workaround for ORA-01795: maximum number of expressions in a list is 1000 error?

There is another option: with syntax. To use the OPs example, this would look like:

with data as (
  select 'value1' name from dual
  union all
  select 'value2' name from dual
  union all
...
  select 'value10000+' name from dual)
select field1, field2, field3 
from table1 t1
inner join data on t1.name = data.name;

I ran into this problem. In my case I had a list of data in Java where each item had an item_id and a customer_id. I have two tables in the DB with subscriptions to items respective customers. I want to get a list of all subscriptions to the items or to the customer for that item, together with the item id.

I tried three variants:

  1. Multiple selects from Java (using tuples to get around the limit)
  2. With-syntax
  3. Temporary table

Option 1: Multiple Selects from Java

Basically, I first

select item_id, token 
from item_subs 
where (item_id, 0) in ((:item_id_0, 0)...(:item_id_n, 0))

Then

select cus_id, token 
from cus_subs 
where (cus_id, 0) in ((:cus_id_0, 0)...(:cus_id_n, 0))

Then I build a Map in Java with the cus_id as the key and a list of items as value, and for each found customer subscription I add (to the list returned from the first select) an entry for all relevant items with that item_id. It's much messier code

Option 2: With-syntax

Get everything at once with an SQL like

with data as (
  select :item_id_0 item_id, :cus_id_0 cus_id
  union all
  ...
  select :item_id_n item_id, :cus_id_n cus_id )
select I.item_id item_id, I.token token
from item_subs I
inner join data D on I.item_id = D.item_id
union all
select D.item_id item_id, C.token token
from cus_subs C
inner join data D on C.cus_id = D.cus_id

Option 3: Temporary table

Create a global temporary table with three fields: rownr (primary key), item_id and cus_id. Insert all the data there then run a very similar select to option 2, but linking in the temporary table instead of the with data

Performance

This is not a fully-scientific performance analysis.

  • I'm running against a development database, with slightly over 1000 rows in my data set that I want to find subscriptions for.
  • I've only tried one data set.
  • I'm not in the same physical location as my DB server. It's not that far away, but I do notice if I try from home over the VPN then it's all much slower, even though it's the same distance (and it's not my home internet that's the problem).
  • I was testing the full call, so my API calls another (also running in the same instance in dev) which also connects to to the DB to get the initial data set. But that is the same in all three cases.

YMMV.

That said, the temporary table option was much slower. As in double so slow. I was getting 14-15 seconds for option 1, 15-16 for option 2 and 30 for option 3.

I'll try them again from the same network as the DB server and check if that changes things when I get the chance.

Angular.js How to change an elements css class on click and to remove all others

Typically with Angular you would be outputting these spans using the ngRepeat directive and (like in your case) each item would have an id. I know this is not true for all situations but it is typical if requesting data from a backend - objects in an array tend to have unique identifiers.

You can use this id to facilitate the toggling of classes on items in your list (see plunkr or code below).

Using the objects id's can also eliminate the undesirable effect when the $index (described in other answers) is messed up due to sorting in Angular.

Example Plunkr: http://plnkr.co/edit/na0gUec6cdMABK9L6drV

(basically apply the .active-selection class if the person.id is equal to $scope.activeClass - which we set when the user clicks an item.

Hope this helps someone, I've found expressions in ng-class to be very useful!

HTML

<ul>
  <li ng-repeat="person in people" 
  data-ng-class="{'active-selection': person.id == activeClass}">
    <a data-ng-click="selectPerson(person.id)">
      {{person.name}}
    </a>
  </li>
</ul>

JS

app.controller('MainCtrl', function($scope) {
  $scope.people = [{
    id: "1",
    name: "John",
  }, {
    id: "2",
    name: "Lucy"
  }, {
    id: "3",
    name: "Mark"
  }, {
    id: "4",
    name: "Sam"
  }];

  $scope.selectPerson = function(id) {
    $scope.activeClass = id;
    console.log(id);
  };
});    

CSS:

.active-selection {
  background-color: #eee;
}

The declared package does not match the expected package ""

Solution 1 : One solution that worked for me when this error "The declared package does not match the expected package" occured for a project I checked-out from eclipse CVS :

1.Right click the project in the navigation bar and click 'delete'
2.Make sure 'Delete project contents on disk' option is NOT checked, and click OK.
3.Now after the project is deleted, go to File -> Import -> General -> Existing Projects into Workspace
4.Select your workspace from the directory listing and check the box next to your project name. Click 'Finish'

Solution 2 : Once again I got this error with the following message

Eclipse build errors - java.lang.Object cannot be resolved I had to follow another route mention here and the error went away.

In the mean time, the work around is to remove the JRE System Library from the project and then add it back again. Here are the steps:

  1. Go to properties of project with the build error (right click > Properties) View the "Libraries" tab in the "Build Path" section Find the "JRE System Library" in the list (if this is missing then this error message is not an eclipse bug but a mis-configured project)
  2. Remove the "JRE System Library"
  3. Hit "Add Library ...", Select "JRE System Library" and add the appropriate JRE for the project (eg. 'Workspace default JRE')
  4. Hit "Finish" in the library selection and "OK" in the project properties and then wait for the re-build of the project

Hopefully the error will be resolved ...

How to increment a pointer address and pointer's value?

checked the program and the results are as,

p++;    // use it then move to next int position
++p;    // move to next int and then use it
++*p;   // increments the value by 1 then use it 
++(*p); // increments the value by 1 then use it
++*(p); // increments the value by 1 then use it
*p++;   // use the value of p then moves to next position
(*p)++; // use the value of p then increment the value
*(p)++; // use the value of p then moves to next position
*++p;   // moves to the next int location then use that value
*(++p); // moves to next location then use that value

Apply style to only first level of td tags

I guess you could try

table tr td { color: red; }
table tr td table tr td { color: black; }

Or

body table tr td { color: red; }

where 'body' is a selector for your table's parent

But classes are most likely the right way to go here.

Get value from hidden field using jQuery

var x = $('#h_v').val();
alert(x);

How do I change db schema to dbo

Way to do it for an individual thing:

alter schema dbo transfer jonathan.MovieData

Make an HTTP request with android

I made this for a webservice to requerst on URL, using a Gson lib:

Client:

public EstabelecimentoList getListaEstabelecimentoPorPromocao(){

        EstabelecimentoList estabelecimentoList  = new EstabelecimentoList();
        try{
            URL url = new URL("http://" +  Conexao.getSERVIDOR()+ "/cardapio.online/rest/recursos/busca_estabelecimento_promocao_android");
            HttpURLConnection con = (HttpURLConnection) url.openConnection();

            if (con.getResponseCode() != 200) {
                    throw new RuntimeException("HTTP error code : "+ con.getResponseCode());
            }

            BufferedReader br = new BufferedReader(new InputStreamReader((con.getInputStream())));
            estabelecimentoList = new Gson().fromJson(br, EstabelecimentoList.class);
            con.disconnect();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return estabelecimentoList;
}

Setting state on componentDidMount()

The only reason that the linter complains about using setState({..}) in componentDidMount and componentDidUpdate is that when the component render the setState immediately causes the component to re-render. But the most important thing to note: using it inside these component's lifecycles is not an anti-pattern in React.

Please take a look at this issue. you will understand more about this topic. Thanks for reading my answer.

How to make join queries using Sequelize on Node.js

Model1.belongsTo(Model2, { as: 'alias' })

Model1.findAll({include: [{model: Model2  , as: 'alias'  }]},{raw: true}).success(onSuccess).error(onError);

What is setBounds and how do I use it?

here's a short paragraph from this article How to Make Frames (Main Windows) - The Java Tutorials - Oracle that explains what setBounds method does in addition to some other similar methods:

The pack method sizes the frame so that all its contents are at or above their preferred sizes. An alternative to pack is to establish a frame size explicitly by calling setSize or setBounds (which also sets the frame location). In general, using pack is preferable to calling setSize, since pack leaves the frame layout manager in charge of the frame size, and layout managers are good at adjusting to platform dependencies and other factors that affect component size.

the parameters of setBounds are (int x, int y, int width, int height) x and y are define the position/location and width and height define the size/dimension of the frame.

Convert Variable Name to String?

as long as it's a variable and not a second class, this here works for me:

def print_var_name(variable):
 for name in globals():
     if eval(name) == variable:
        print name
foo = 123
print_var_name(foo)
>>>foo

this happens for class members:

class xyz:
     def __init__(self):
         pass
member = xyz()
print_var_name(member)
>>>member

ans this for classes (as example):

abc = xyz
print_var_name(abc)
>>>abc
>>>xyz

So for classes it gives you the name AND the properteries

startForeground fail after upgrade to Android 8.1

The first answer is great only for those people who know kotlin, for those who still using java here I translate the first answer

 public Notification getNotification() {
        String channel;
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O)
            channel = createChannel();
        else {
            channel = "";
        }
        NotificationCompat.Builder mBuilder = new NotificationCompat.Builder(this, channel).setSmallIcon(android.R.drawable.ic_menu_mylocation).setContentTitle("snap map fake location");
        Notification notification = mBuilder
                .setPriority(PRIORITY_LOW)
                .setCategory(Notification.CATEGORY_SERVICE)
                .build();


        return notification;
    }

    @NonNull
    @TargetApi(26)
    private synchronized String createChannel() {
        NotificationManager mNotificationManager = (NotificationManager) this.getSystemService(Context.NOTIFICATION_SERVICE);

        String name = "snap map fake location ";
        int importance = NotificationManager.IMPORTANCE_LOW;

        NotificationChannel mChannel = new NotificationChannel("snap map channel", name, importance);

        mChannel.enableLights(true);
        mChannel.setLightColor(Color.BLUE);
        if (mNotificationManager != null) {
            mNotificationManager.createNotificationChannel(mChannel);
        } else {
            stopSelf();
        }
        return "snap map channel";
    } 

For android, P don't forget to include this permission

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

comparing elements of the same array in java

First things first, you need to loop to < a.length rather than a.length - 1. As this is strictly less than you need to include the upper bound.

So, to check all pairs of elements you can do:

for (int i = 0; i < a.length; i++) {
    for (int k = 0; k < a.length; k++) {
        if (a[i] != a[k]) {
            //do stuff
        }
    }
}

But this will compare, for example a[2] to a[3] and then a[3] to a[2]. Given that you are checking != this seems wasteful.

A better approach would be to compare each element i to the rest of the array:

for (int i = 0; i < a.length; i++) {
    for (int k = i + 1; k < a.length; k++) {
        if (a[i] != a[k]) {
            //do stuff
        }
    }
}

So if you have the indices [1...5] the comparison would go

  1. 1 -> 2
  2. 1 -> 3
  3. 1 -> 4
  4. 1 -> 5
  5. 2 -> 3
  6. 2 -> 4
  7. 2 -> 5
  8. 3 -> 4
  9. 3 -> 5
  10. 4 -> 5

So you see pairs aren't repeated. Think of a circle of people all needing to shake hands with each other.

Convert DateTime to TimeSpan

You can just use the TimeOfDay property of date time, which is TimeSpan type:

DateTime.TimeOfDay

This property has been around since .NET 1.1

More information: http://msdn.microsoft.com/en-us/library/system.datetime.timeofday(v=vs.110).aspx

Fragments within Fragments

.. you can cleanup your nested fragment in the parent fragment's destroyview method:

@Override
    public void onDestroyView() {

      try{
        FragmentTransaction transaction = getSupportFragmentManager()
                .beginTransaction();

        transaction.remove(nestedFragment);

        transaction.commit();
      }catch(Exception e){
      }

        super.onDestroyView();
    }

Updating MySQL primary key

If the primary key happens to be an auto_increment value, you have to remove the auto increment, then drop the primary key then re-add the auto-increment

ALTER TABLE `xx`
MODIFY `auto_increment_field` INT, 
DROP PRIMARY KEY, 
ADD PRIMARY KEY (new_primary_key);

then add back the auto increment

ALTER TABLE `xx` ADD INDEX `auto_increment_field` (auto_increment_field),
MODIFY `auto_increment_field` int auto_increment;

then set auto increment back to previous value

ALTER TABLE `xx` AUTO_INCREMENT = 5;

Can Mockito capture arguments of a method called multiple times?

Since Mockito 2.0 there's also possibility to use static method Matchers.argThat(ArgumentMatcher). With the help of Java 8 it is now much cleaner and more readable to write:

verify(mockBar).doSth(argThat((arg) -> arg.getSurname().equals("OneSurname")));
verify(mockBar).doSth(argThat((arg) -> arg.getSurname().equals("AnotherSurname")));

If you're tied to lower Java version there's also not-that-bad:

verify(mockBar).doSth(argThat(new ArgumentMatcher<Employee>() {
        @Override
        public boolean matches(Object emp) {
            return ((Employee) emp).getSurname().equals("SomeSurname");
        }
    }));

Of course none of those can verify order of calls - for which you should use InOrder :

InOrder inOrder = inOrder(mockBar);

inOrder.verify(mockBar).doSth(argThat((arg) -> arg.getSurname().equals("FirstSurname")));
inOrder.verify(mockBar).doSth(argThat((arg) -> arg.getSurname().equals("SecondSurname")));

Please take a look at mockito-java8 project which makes possible to make calls such as:

verify(mockBar).doSth(assertArg(arg -> assertThat(arg.getSurname()).isEqualTo("Surname")));

Can I hide the HTML5 number input’s spin box?

Not what you asked for, but I do this because of a focus bug in WebKit with spinboxes:

// temporary fix for focus bug with webkit input type=number ui
if (navigator.userAgent.indexOf("AppleWebKit") > -1 && navigator.userAgent.indexOf("Mobile") == -1)
{
    var els = document.querySelectorAll("input[type=number]");
    for (var el in els)
        el.type = "text";
}

It might give you an idea to help with what you need.

Which version of Python do I have installed?

For bash scripts this would be the easiest way:

# In the form major.minor.micro e.g. '3.6.8'
# The second part excludes the 'Python ' prefix 
PYTHON_VERSION=`python3 --version | awk '{print $2}'`
echo "python3 version: ${PYTHON_VERSION}"
python3 version: 3.6.8

And if you just need the major.minor version (e.g. 3.6) you can either use the above and then pick the first 3 characters:

PYTHON_VERSION=`python3 --version | awk '{print $2}'`
echo "python3 major.minor: ${PYTHON_VERSION:0:3}"
python3 major.minor: 3.6

or

PYTHON_VERSION=`python3 -c 'import sys; print(str(sys.version_info[0])+"."+str(sys.version_info[1]))'`
echo "python3 major.minor: ${PYTHON_VERSION}"
python3 major.minor: 3.6

Creating default object from empty value in PHP?

Simply,

    $res = (object)array("success"=>false); // $res->success = bool(false);

Or you could instantiate classes with:

    $res = (object)array(); // object(stdClass) -> recommended

    $res = (object)[];      // object(stdClass) -> works too

    $res = new \stdClass(); // object(stdClass) -> old method

and fill values with:

    $res->success = !!0;     // bool(false)

    $res->success = false;   // bool(false)

    $res->success = (bool)0; // bool(false)

More infos: https://www.php.net/manual/en/language.types.object.php#language.types.object.casting

Using Chrome, how to find to which events are bound to an element

Edit: in lieu of my own answer, this one is quite excellent: How to debug JavaScript/jQuery event bindings with Firebug (or similar tool)

Google Chromes developer tools has a search function built into the scripts section

If you are unfamiliar with this tool: (just in case)

  • right click anywhere on a page (in chrome)
  • click 'Inspect Element'
  • click the 'Scripts' tab
  • Search bar in the top right

Doing a quick search for the #ID should take you to the binding function eventually.

Ex: searching for #foo would take you to

$('#foo').click(function(){ alert('bar'); })

enter image description here

HTML.ActionLink vs Url.Action in ASP.NET Razor

@HTML.ActionLink generates a HTML anchor tag. While @Url.Action generates a URL for you. You can easily understand it by;

// 1. <a href="/ControllerName/ActionMethod">Item Definition</a>
@HTML.ActionLink("Item Definition", "ActionMethod", "ControllerName")

// 2. /ControllerName/ActionMethod
@Url.Action("ActionMethod", "ControllerName")

// 3. <a href="/ControllerName/ActionMethod">Item Definition</a>
<a href="@Url.Action("ActionMethod", "ControllerName")"> Item Definition</a>

Both of these approaches are different and it totally depends upon your need.

Get class list for element with jQuery

var classList = $(element).attr('class').split(/\s+/);
$(classList).each(function(index){

     //do something

});

`col-xs-*` not working in Bootstrap 4

I just wondered, why col-xs-6 did not work for me but then I found the answer in the Bootstrap 4 documentation. The class prefix for extra small devices is now col- while in the previous versions it was col-xs.

https://getbootstrap.com/docs/4.1/layout/grid/#grid-options

Bootstrap 4 dropped all col-xs-* classes, so use col-* instead. For example col-xs-6 replaced by col-6.

Why are my CSS3 media queries not working on mobile devices?

i used bootstrap in a press site but it does not worked on IE8, i used css3-mediaqueries.js javascript but still not working. if you want your media query to work with this javascript file add screen to your media query line in css

here is an example :

<meta name="viewport" content="width=device-width" />


<style>
     @media screen and (max-width:900px) {}
     @media screen and (min-width:900px) and (max-width:1200px) {}
     @media screen and (min-width:1200px) {}
</style>

<link rel="stylesheet" type="text/css" href="bootstrap.min.css">
<script type="text/javascript" src="css3-mediaqueries.js"></script>

css Link line as simple as above line.

Most efficient way to check for DBNull and then assign to a variable?

I personally favour this syntax, which uses the explicit IsDbNull method exposed by IDataRecord, and caches the column index to avoid a duplicate string lookup.

Expanded for readability, it goes something like:

int columnIndex = row.GetOrdinal("Foo");
string foo; // the variable we're assigning based on the column value.
if (row.IsDBNull(columnIndex)) {
  foo = String.Empty; // or whatever
} else { 
  foo = row.GetString(columnIndex);
}

Rewritten to fit on a single line for compactness in DAL code - note that in this example we're assigning int bar = -1 if row["Bar"] is null.

int i; // can be reused for every field.
string foo  = (row.IsDBNull(i  = row.GetOrdinal("Foo")) ? null : row.GetString(i));
int bar = (row.IsDbNull(i = row.GetOrdinal("Bar")) ? -1 : row.GetInt32(i));

The inline assignment can be confusing if you don't know it's there, but it keeps the entire operation on one line, which I think enhances readability when you're populating properties from multiple columns in one block of code.

How to check if a String contains another String in a case insensitive manner in Java?

There is a simple concise way, using regex flag (case insensitive {i}):

 String s1 = "hello abc efg";
 String s2 = "ABC";
 s1.matches(".*(?i)"+s2+".*");

/*
 * .*  denotes every character except line break
 * (?i) denotes case insensitivity flag enabled for s2 (String)
 * */

Is the LIKE operator case-sensitive with MSSQL Server?

Try running,

SELECT SERVERPROPERTY('COLLATION')

Then find out if your collation is case sensitive or not.

How can I change the default credentials used to connect to Visual Studio Online (TFSPreview) when loading Visual Studio up?

You need to remove TFS credentials from Windows Vault to clear and force to ask new TFS credentials in Visual Studio

  1. Go to Control Panel (Start -> Control Panel).

  2. Click User Accounts ( or User Accounts and Family Safety->User Accounts in Windows 7 Machine)

  3. Click Credential Manager (or Manage your credentials)

  4. In Credential Manager page, you can see the two type of credentials

       i. Windows Credentials
       ii. Generic Credentials
    

5.Click on two credentials modify link, click the link Remove from vault to remove stored TFS credentials.

Now, When you login into Visual Studio you will be asked to give credentials to connect TFS.

Note: Don't forgot to uncheck the option Remember my credentials to force to ask credentials for every TFS connections.

Oracle SQL - REGEXP_LIKE contains characters other than a-z or A-Z

Something like

select *
  from foo
 where regexp_like( col1, '[^[:alpha:]]' ) ;

should work

SQL> create table foo( col1 varchar2(100) );

Table created.

SQL> insert into foo values( 'abc' );

1 row created.

SQL> insert into foo values( 'abc123' );

1 row created.

SQL> insert into foo values( 'def' );

1 row created.

SQL> select *
  2    from foo
  3   where regexp_like( col1, '[^[:alpha:]]' ) ;

COL1
--------------------------------------------------------------------------------
abc123

updating table rows in postgres using subquery

@Mayur "4.2 [Using query with complex JOIN]" with Common Table Expressions (CTEs) did the trick for me.

WITH cte AS (
SELECT e.id, e.postcode
FROM employees e
LEFT JOIN locations lc ON lc.postcode=cte.postcode
WHERE e.id=1
)
UPDATE employee_location SET lat=lc.lat, longitude=lc.longi
FROM cte
WHERE employee_location.id=cte.id;

Hope this helps... :D

Using PowerShell to write a file in UTF-8 without the BOM

For PowerShell 5.1, enable this setting:

Control Panel, Region, Administrative, Change system locale, Use Unicode UTF-8 for worldwide language support

Then enter this into PowerShell:

$PSDefaultParameterValues['*:Encoding'] = 'Default'

Alternatively, you can upgrade to PowerShell 6 or higher.

https://github.com/PowerShell/PowerShell

Pandas Merge - How to avoid duplicating columns

You can work out the columns that are only in one DataFrame and use this to select a subset of columns in the merge.

cols_to_use = df2.columns.difference(df.columns)

Then perform the merge (note this is an index object but it has a handy tolist() method).

dfNew = merge(df, df2[cols_to_use], left_index=True, right_index=True, how='outer')

This will avoid any columns clashing in the merge.

How to convert a char array to a string?

The string class has a constructor that takes a NULL-terminated C-string:

char arr[ ] = "This is a test";

string str(arr);


//  You can also assign directly to a string.
str = "This is another string";

// or
str = arr;

How to set dialog to show in full screen?

try

Dialog dialog=new Dialog(this,android.R.style.Theme_Black_NoTitleBar_Fullscreen)

When using Trusted_Connection=true and SQL Server authentication, will this affect performance?

This will probably have some performance costs when creating the connection but as connections are pooled, they are created only once and then reused, so it won't make any difference to your application. But as always: measure it.


UPDATE:

There are two authentication modes:

  1. Windows Authentication mode (corresponding to a trusted connection). Clients need to be members of a domain.
  2. SQL Server Authentication mode. Clients are sending username/password at each connection

accepting HTTPS connections with self-signed certificates

This is problem resulting from lack of SNI(Server Name Identification) support inA,ndroid 2.x. I was struggling with this problem for a week until I came across the following question, which not only gives a good background of the problem but also provides a working and effective solution devoid of any security holes.

'No peer certificate' error in Android 2.3 but NOT in 4

Mockito. Verify method arguments

Verify(a).aFunc(eq(b))

In pseudocode:

When in the instance a - a function named aFunc is called.

Verify this call got an argument which is equal to b.

How to validate phone number using PHP?

Here's how I find valid 10-digit US phone numbers. At this point I'm assuming the user wants my content so the numbers themselves are trusted. I'm using in an app that ultimately sends an SMS message so I just want the raw numbers no matter what. Formatting can always be added later

//eliminate every char except 0-9
$justNums = preg_replace("/[^0-9]/", '', $string);

//eliminate leading 1 if its there
if (strlen($justNums) == 11) $justNums = preg_replace("/^1/", '',$justNums);

//if we have 10 digits left, it's probably valid.
if (strlen($justNums) == 10) $isPhoneNum = true;

Edit: I ended up having to port this to Java, if anyone's interested. It runs on every keystroke so I tried to keep it fairly light:

boolean isPhoneNum = false;
if (str.length() >= 10 && str.length() <= 14 ) { 
  //14: (###) ###-####
  //eliminate every char except 0-9
  str = str.replaceAll("[^0-9]", "");

  //remove leading 1 if it's there
  if (str.length() == 11) str = str.replaceAll("^1", "");

  isPhoneNum = str.length() == 10;
}
Log.d("ISPHONENUM", String.valueOf(isPhoneNum));

How to change the window title of a MATLAB plotting figure?

First you must create an empty figure with the following command.

figure('name','Title of the window here');

By doing this, the newly created figure becomes you active figure. Immediately after calling a plot() command, it will print your plotting onto this figure. So your window will have a title.

This is the code you must use:

figure('name','Title of the window here');

hold on

x = [0; 0.2; 0.4; 0.6; 0.8; 1; 1.2; 1.4; 1.6; 1.8; 2; 2.2; 2.4; 2.6; 2.8; 3; 3.2; 3.4; 3.6; 3.8; 4; 4.2; 4.4; 4.6; 4.8; 5; 5.2; 5.4; 5.6; 5.8; 6; 6.2; 6.4; 6.6; 6.8; 7; 7.2; 7.4; 7.6; 7.8; 8; 8.2; 8.4; 8.6; 8.8; 9; 9.2; 9.4; 9.6; 9.8; 10; 10.2; 10.4; 10.6; 10.8; 11; 11.2; 11.4; 11.6; 11.8; 12; 12.2; 12.4; 12.6; 12.8; 13; 13.2; 13.4; 13.6; 13.8; 14; 14.2; 14.4; 14.6; 14.8; 15; 15.2; 15.4; 15.6; 15.8; 16; 16.2; 16.4; 16.6; 16.8; 17; 17.2; 17.4; 17.6; 17.8; 18; 18.2; 18.4; 18.6; 18.8];
y = [0; 0.198669; 0.389418; 0.564642; 0.717356; 0.841471; 0.932039; 0.98545; 0.999574; 0.973848; 0.909297; 0.808496; 0.675463; 0.515501; 0.334988; 0.14112; -0.0583741; -0.255541; -0.44252; -0.611858; -0.756802; -0.871576; -0.951602; -0.993691; -0.996165; -0.958924; -0.883455; -0.772764; -0.631267; -0.464602; -0.279415; -0.0830894; 0.116549; 0.311541; 0.494113; 0.656987; 0.793668; 0.898708; 0.96792; 0.998543; 0.989358; 0.940731; 0.854599; 0.734397; 0.584917; 0.412118; 0.22289; 0.0247754; -0.174327; -0.366479; -0.544021; -0.699875; -0.827826; -0.922775; -0.980936; -0.99999; -0.979178; -0.919329; -0.822829; -0.693525; -0.536573; -0.358229; -0.165604; 0.033623; 0.23151; 0.420167; 0.592074; 0.740376; 0.859162; 0.943696; 0.990607; 0.998027; 0.965658; 0.894791; 0.788252; 0.650288; 0.486399; 0.303118; 0.107754; -0.0919069; -0.287903; -0.472422; -0.638107; -0.778352; -0.887567; -0.961397; -0.9969; -0.992659; -0.948844; -0.867202; -0.750987; -0.604833; -0.434566; -0.246974; -0.0495356];
plot(x, y, '--b');

x = [0; 0.2; 0.4; 0.6; 0.8; 1; 1.2; 1.4; 1.6; 1.8; 2; 2.2; 2.4; 2.6; 2.8; 3; 3.2; 3.4; 3.6; 3.8; 4; 4.2; 4.4; 4.6; 4.8; 5; 5.2; 5.4; 5.6; 5.8; 6; 6.2; 6.4; 6.6; 6.8; 7; 7.2; 7.4; 7.6; 7.8; 8; 8.2; 8.4; 8.6; 8.8; 9; 9.2; 9.4; 9.6; 9.8; 10; 10.2; 10.4; 10.6; 10.8; 11; 11.2; 11.4; 11.6; 11.8; 12; 12.2; 12.4; 12.6; 12.8; 13; 13.2; 13.4; 13.6; 13.8; 14; 14.2; 14.4; 14.6; 14.8; 15; 15.2; 15.4; 15.6; 15.8; 16; 16.2; 16.4; 16.6; 16.8; 17; 17.2; 17.4; 17.6; 17.8; 18; 18.2; 18.4; 18.6; 18.8];
y = [-1; -0.980133; -0.921324; -0.825918; -0.697718; -0.541836; -0.364485; -0.172736; 0.0257666; 0.223109; 0.411423; 0.583203; 0.731599; 0.850695; 0.935744; 0.983355; 0.991629; 0.960238; 0.890432; 0.784994; 0.648128; 0.48529; 0.302972; 0.108443; -0.0905427; -0.286052; -0.470289; -0.635911; -0.776314; -0.885901; -0.960303; -0.996554; -0.993208; -0.950399; -0.869833; -0.754723; -0.609658; -0.44042; -0.253757; -0.057111; 0.141679; 0.334688; 0.514221; 0.673121; 0.805052; 0.904756; 0.968256; 0.993023; 0.978068; 0.923987; 0.832937; 0.708548; 0.555778; 0.380717; 0.190346; -0.00774649; -0.205663; -0.395514; -0.56973; -0.721365; -0.844375; -0.933855; -0.986238; -0.999436; -0.972923; -0.907755; -0.806531; -0.673287; -0.513333; -0.333047; -0.139617; 0.0592467; 0.255615; 0.44166; 0.609964; 0.753818; 0.867487; 0.946439; 0.987526; 0.989111; 0.95113; 0.875097; 0.764044; 0.622398; 0.455806; 0.27091; 0.0750802; -0.123876; -0.318026; -0.499631; -0.66145; -0.797032; -0.900972; -0.969126; -0.998776];
plot(x, y, '-r');

hold off

title('My plot title');
xlabel('My x-axis title');
ylabel('My y-axis title');

Difference between "move" and "li" in MIPS assembly language

The move instruction copies a value from one register to another. The li instruction loads a specific numeric value into that register.

For the specific case of zero, you can use either the constant zero or the zero register to get that:

move $s0, $zero
li   $s0, 0

There's no register that generates a value other than zero, though, so you'd have to use li if you wanted some other number, like:

li $s0, 12345678

How do I POST urlencoded form data with $http without jQuery?

I think you need to do is to transform your data from object not to JSON string, but to url params.

From Ben Nadel's blog.

By default, the $http service will transform the outgoing request by serializing the data as JSON and then posting it with the content- type, "application/json". When we want to post the value as a FORM post, we need to change the serialization algorithm and post the data with the content-type, "application/x-www-form-urlencoded".

Example from here.

$http({
    method: 'POST',
    url: url,
    headers: {'Content-Type': 'application/x-www-form-urlencoded'},
    transformRequest: function(obj) {
        var str = [];
        for(var p in obj)
        str.push(encodeURIComponent(p) + "=" + encodeURIComponent(obj[p]));
        return str.join("&");
    },
    data: {username: $scope.userName, password: $scope.password}
}).then(function () {});

UPDATE

To use new services added with AngularJS V1.4, see

How to select a single child element using jQuery?

No. Every jQuery function returns a jQuery object, and that is how it works. This is a crucial part of jQuery's magic.

If you want to access the underlying element, you have three options...

  1. Do not use jQuery
  2. Use [0] to reference it
  3. Extend jQuery to do what you want...

    $.fn.child = function(s) {
        return $(this).children(s)[0];
    }
    

Execute a command in command prompt using excel VBA

The S parameter does not do anything on its own.

/S      Modifies the treatment of string after /C or /K (see below) 
/C      Carries out the command specified by string and then terminates  
/K      Carries out the command specified by string but remains  

Try something like this instead

Call Shell("cmd.exe /S /K" & "perl a.pl c:\temp", vbNormalFocus)

You may not even need to add "cmd.exe" to this command unless you want a command window to open up when this is run. Shell should execute the command on its own.

Shell("perl a.pl c:\temp")



-Edit-
To wait for the command to finish you will have to do something like @Nate Hekman shows in his answer here

Dim wsh As Object
Set wsh = VBA.CreateObject("WScript.Shell")
Dim waitOnReturn As Boolean: waitOnReturn = True
Dim windowStyle As Integer: windowStyle = 1

wsh.Run "cmd.exe /S /C perl a.pl c:\temp", windowStyle, waitOnReturn

Java finished with non-zero exit value 2 - Android Gradle

If You have already updated your SDK and You also using google-play-services then you need to take care of the dependency because there are some kind of conflics with :

Follow the below : compile 'com.google.android.gms:play-services:+' Replace by compile 'com.google.android.gms:play-services:6.5.87'

Note: Here '6.5.87' is the google-play-service version. I hope it will help..

Convert text into number in MySQL query

SELECT *, CAST(SUBSTRING_INDEX(field, '-', -1) AS UNSIGNED) as num FROM tableName ORDER BY num;

Populate XDocument from String

You can use XDocument.Parse(string) instead of Load(string).

Detect when an image fails to load in Javascript

jQuery + CSS for img

With jQuery this is working for me :

$('img').error(function() {
    $(this).attr('src', '/no-img.png').addClass('no-img');
});

And I can use this picture everywhere on my website regardless of the size of it with the following CSS3 property :

img.no-img {
    object-fit: cover;
    object-position: 50% 50%;
}

TIP 1 : use a square image of at least 800 x 800 pixels.

TIP 2 : for use with portrait of people, use object-position: 20% 50%;

CSS only for background-img

For missing background images, I also added the following on each background-image declaration :

background-image: url('path-to-image.png'), url('no-img.png');

NOTE : not working for transparent images.

Apache server side

Another solution is to detect missing image with Apache before to send to browser and remplace it by the default no-img.png content.

RewriteCond %{REQUEST_FILENAME} !-f
RewriteCond %{REQUEST_URI} /images/.*\.(gif|jpg|jpeg|png)$
RewriteRule .* /images/no-img.png [L,R=307]