Programs & Examples On #Termination

How to stop/terminate a python script from running?

  • To stop a python script just press Ctrl + C.
  • Inside a script with exit(), you can do it.
  • You can do it in an interactive script with just exit.
  • You can use pkill -f name-of-the-python-script.

How to terminate a Python script

from sys import exit
exit()

As a parameter you can pass an exit code, which will be returned to OS. Default is 0.

Force browser to refresh css, javascript, etc

I have decided that since browsers do not check for new versions of css and js files, I rename my css and js directories whenever I make a change. I use css1 to css9 and js1 to js9 as the directory names. When I get to 9, I next start over at 1. It is a pain, but it works perfectly every time. It is ridiculous to have to tell users to type .

Pick images of root folder from sub-folder

The relative reference would be

<img src="../images/logo.png">

If you know the location relative to the root of the server, that may be simplest approach for an app with a complex nested directory hierarchy - it would be the same from all folders.

For example, if your directory tree depicted in your question is relative to the root of the server, then index.html and sub_folder/sub.html would both use:

<img src="/images/logo.png">

If the images folder is instead in the root of an application like foo below the server root (e.g. http://www.example.com/foo), then index.html (http://www.example.com/foo/index.html) e.g and sub_folder/sub.html (http://www.example.com/foo/sub_folder/sub.html) both use:

<img src="/foo/images/logo.png">

How is a tag different from a branch in Git? Which should I use, here?

Tags can be either signed or unsigned; branches are never signed.

Signed tags can never move because they are cryptographically bound (with a signature) to a particular commit. Unsigned tags are not bound and it is possible to move them (but moving tags is not a normal use case).

Branches can not only move to a different commit but are expected to do so. You should use a branch for your local development project. It doesn't quite make sense to commit work to a Git repository "on a tag".

Is it possible to remove inline styles with jQuery?

In case the display is the only parameter from your style, you can run this command in order to remove all style:

$('#element').attr('style','');

Means that if your element looked like this before:

<input id="element" style="display: block;">

Now your element will look like this:

<input id="element" style="">

How to free memory in Java?

*"I personally rely on nulling variables as a placeholder for future proper deletion. For example, I take the time to nullify all elements of an array before actually deleting (making null) the array itself."

This is unnecessary. The way the Java GC works is it finds objects that have no reference to them, so if I have an Object x with a reference (=variable) a that points to it, the GC won't delete it, because there is a reference to that object:

a -> x

If you null a than this happens:

a -> null
     x

So now x doesn't have a reference pointing to it and will be deleted. The same thing happens when you set a to reference to a different object than x.

So if you have an array arr that references to objects x, y and z and a variable a that references to the array it looks like that:

a -> arr -> x
         -> y
         -> z

If you null a than this happens:

a -> null
     arr -> x
         -> y
         -> z

So the GC finds arr as having no reference set to it and deletes it, which gives you this structure:

a -> null
     x
     y
     z

Now the GC finds x, y and z and deletes them aswell. Nulling each reference in the array won't make anything better, it will just use up CPU time and space in the code (that said, it won't hurt further than that. The GC will still be able to perform the way it should).

How to check which PHP extensions have been enabled/disabled in Ubuntu Linux 12.04 LTS?

Perhaps the easiest way to see which extensions are (compiled and) loaded (not in cli) is to have a server run the following:

<?php
$ext = get_loaded_extensions();
asort($ext);
foreach ($ext as $ref) {
    echo $ref . "\n";
}

PHP cli does not necessarily have the same extensions loaded.

Run ssh and immediately execute command

You can use the LocalCommand command-line option if the PermitLocalCommand option is enabled:

ssh username@hostname -o LocalCommand="tmux list-sessions"

For more details about the available options, see the ssh_config man page.

if statement in ng-click

Don't put any Condition Expression in Template.

Do it at the Controller.

Template:

<input ng-click="check(profileForm.$valid)" name="submit" 
       id="submit" value="Save" class="submit" type="submit">

Controller:

$scope.check = function(value) {
    if (value) {
       updateMyProfile();
    }
}

Convert array to string in NodeJS

In node, you can just say

console.log(aa)

and it will format it as it should.

If you need to use the resulting string you should use

JSON.stringify(aa)

How to remove folders with a certain name

This command works for me. It does its work recursively

find . -name "node_modules" -type d -prune -exec rm -rf '{}' +

. - current folder

"node_modules" - folder name

convert an enum to another type of enum

I know that's an old question and have a lot of answers, However I find that using a switch statement as in the accepted answer is somewhat cumbersome, so here are my 2 cents:

My personal favorite method is to use a dictionary, where the key is the source enum and the value is the target enum - so in the case presented on the question my code would look like this:

var genderTranslator = new Dictionary<TheirGender, MyGender>();
genderTranslator.Add(TheirGender.Male, MyGender.Male);
genderTranslator.Add(TheirGender.Female, MyGender.Female);
genderTranslator.Add(TheirGender.Unknown, MyGender.Unknown);

// translate their to mine    
var myValue = genderTranslator[TheirValue];

// translate mine to their
var TheirValue = genderTranslator .FirstOrDefault(x => x.Value == myValue).Key;;

Of course, this can be wrapped in a static class and be used as an extension methods:

public static class EnumTranslator
{

    private static Dictionary<TheirGender, MyGender> GenderTranslator = InitializeGenderTranslator();

    private static Dictionary<TheirGender, MyGender> InitializeGenderTranslator()
    {
        var translator = new Dictionary<TheirGender, MyGender>();
        translator.Add(TheirGender.Male, MyGender.Male);
        translator.Add(TheirGender.Female, MyGender.Female);
        translator.Add(TheirGender.Unknown, MyGender.Unknown);
        return translator;
    }

    public static MyGender Translate(this TheirGender theirValue)
    {
        return GenderTranslator[theirValue];
    }

    public static TheirGender Translate(this MyGender myValue)
    {
        return GenderTranslator.FirstOrDefault(x => x.Value == myValue).Key;
    }

}

Directory.GetFiles of certain extension

I would have done using just single line like

List<string> imageFiles = Directory.GetFiles(dir, "*.*", SearchOption.AllDirectories)
      .Where(file => new string[] { ".jpg", ".gif", ".png" }
      .Contains(Path.GetExtension(file)))
      .ToList();

iterating through Enumeration of hastable keys throws NoSuchElementException error

You're calling nextElement twice in the loop. You should call it only once, else it moves ahead twice:

while(e.hasMoreElements()){
    String s = e.nextElement();
    System.out.println(s);
}

Creating a fixed sidebar alongside a centered Bootstrap 3 grid

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

HTML

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

CSS

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

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

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

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

@media (max-width:767px) {

    #wrapper {
      padding-left: 0;
    }

    #sidebar-wrapper {
      left: 0;
    }

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

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

}

JSFIDDLE

Django upgrading to 1.9 error "AppRegistryNotReady: Apps aren't loaded yet."

As others have said this can be caused when you've not installed an app that is listed in INSTALLED_APPS.

In my case, manage.py was attempting to log the exception, which led to an attempt to render it which failed due to the app not being initialized yet. By commenting out the except clause in manage.py the exception was displayed without special rendering, avoiding the confusing error.

# Temporarily commenting out the log statement.
#try:
    execute_from_command_line(sys.argv)
#except Exception as e:
#    log.error('Admin Command Error: %s', ' '.join(sys.argv), exc_info=sys.exc_info())
#    raise e

HttpServletRequest - how to obtain the referring URL?

As all have mentioned it is

request.getHeader("referer");

I would like to add some more details about security aspect of referer header in contrast with accepted answer. In Open Web Application Security Project(OWASP) cheat sheets, under Cross-Site Request Forgery (CSRF) Prevention Cheat Sheet it mentions about importance of referer header.

More importantly for this recommended Same Origin check, a number of HTTP request headers can't be set by JavaScript because they are on the 'forbidden' headers list. Only the browsers themselves can set values for these headers, making them more trustworthy because not even an XSS vulnerability can be used to modify them.

The Source Origin check recommended here relies on three of these protected headers: Origin, Referer, and Host, making it a pretty strong CSRF defense all on its own.

You can refer Forbidden header list here. User agent(ie:browser) has the full control over these headers not the user.

How can I get all a form's values that would be submitted without submitting

Thanks Chris. That's what I was looking for. However, note that the method is serialize(). And there is another method serializeArray() that looks very useful that I may use. Thanks for pointing me in the right direction.

var queryString = $('#frmAdvancedSearch').serialize();
alert(queryString);

var fieldValuePairs = $('#frmAdvancedSearch').serializeArray();
$.each(fieldValuePairs, function(index, fieldValuePair) {
    alert("Item " + index + " is [" + fieldValuePair.name + "," + fieldValuePair.value + "]");
});

How to create a dump with Oracle PL/SQL Developer?

EXP (export) and IMP (import) are the two tools you need. It's is better to try to run these on the command line and on the same machine.

It can be run from remote, you just need to setup you TNSNAMES.ORA correctly and install all the developer tools with the same version as the database. Without knowing the error message you are experiencing then I can't help you to get exp/imp to work.

The command to export a single user:

exp userid=dba/dbapassword OWNER=username DIRECT=Y FILE=filename.dmp

This will create the export dump file.

To import the dump file into a different user schema, first create the newuser in SQLPLUS:

SQL> create user newuser identified by 'password' quota unlimited users;

Then import the data:

imp userid=dba/dbapassword FILE=filename.dmp FROMUSER=username TOUSER=newusername

If there is a lot of data then investigate increasing the BUFFERS or look into expdp/impdp

Most common errors for exp and imp are setup. Check your PATH includes $ORACLE_HOME/bin, check $ORACLE_HOME is set correctly and check $ORACLE_SID is set

How to asynchronously call a method in Java

There is also nice library for Async-Await created by EA: https://github.com/electronicarts/ea-async

From their Readme:

With EA Async

import static com.ea.async.Async.await;
import static java.util.concurrent.CompletableFuture.completedFuture;

public class Store
{
    public CompletableFuture<Boolean> buyItem(String itemTypeId, int cost)
    {
        if(!await(bank.decrement(cost))) {
            return completedFuture(false);
        }
        await(inventory.giveItem(itemTypeId));
        return completedFuture(true);
    }
}

Without EA Async

import static java.util.concurrent.CompletableFuture.completedFuture;

public class Store
{
    public CompletableFuture<Boolean> buyItem(String itemTypeId, int cost)
    {
        return bank.decrement(cost)
            .thenCompose(result -> {
                if(!result) {
                    return completedFuture(false);
                }
                return inventory.giveItem(itemTypeId).thenApply(res -> true);
            });
    }
}

Get first and last date of current month with JavaScript or jQuery

I fixed it with Datejs

This is alerting the first day:

var fd = Date.today().clearTime().moveToFirstDayOfMonth();
var firstday = fd.toString("MM/dd/yyyy");
alert(firstday);

This is for the last day:

var ld = Date.today().clearTime().moveToLastDayOfMonth();
var lastday = ld.toString("MM/dd/yyyy");
alert(lastday);

Pass Model To Controller using Jquery/Ajax

Looks like your IndexPartial action method has an argument which is a complex object. If you are passing a a lot of data (complex object), It might be a good idea to convert your action method to a HttpPost action method and use jQuery post to post data to that. GET has limitation on the query string value.

[HttpPost]
public PartialViewResult IndexPartial(DashboardViewModel m)
{
   //May be you want to pass the posted model to the parial view?
   return PartialView("_IndexPartial");
}

Your script should be

var url = "@Url.Action("IndexPartial","YourControllerName")";

var model = { Name :"Shyju", Location:"Detroit"};

$.post(url, model, function(res){
   //res contains the markup returned by the partial view
   //You probably want to set that to some Div.
   $("#SomeDivToShowTheResult").html(res);
});

Assuming Name and Location are properties of your DashboardViewModel class and SomeDivToShowTheResult is the id of a div in your page where you want to load the content coming from the partialview.

Sending complex objects?

You can build more complex object in js if you want. Model binding will work as long as your structure matches with the viewmodel class

var model = { Name :"Shyju", 
              Location:"Detroit", 
              Interests : ["Code","Coffee","Stackoverflow"]
            };

$.ajax({
    type: "POST",
    data: JSON.stringify(model),
    url: url,
    contentType: "application/json"
}).done(function (res) {
    $("#SomeDivToShowTheResult").html(res);
});

For the above js model to be transformed to your method parameter, Your View Model should be like this.

public class DashboardViewModel
{
  public string Name {set;get;}
  public string Location {set;get;}
  public List<string> Interests {set;get;}
}

And in your action method, specify [FromBody]

[HttpPost]
public PartialViewResult IndexPartial([FromBody] DashboardViewModel m)
{
    return PartialView("_IndexPartial",m);
}

Why would $_FILES be empty when uploading files to PHP?

Do not trust the temp folder location provided by sys_get_temp_dir if you're in a shared hosting environment.

Here is one more thing to check that has not yet been mentioned...

I assumed, naturally, that the folder where my PHP script stored temporary file uploads was /tmp. This belief was reinforced by the fact that echo sys_get_temp_dir() . PHP_EOL; returns/tmp. Also, echo ini_get('upload_tmp_dir'); returns nothing.

To verify that the uploaded file does in fact briefly appear in my /tmp folder, I added a sleep(30); statement to my script (as suggested here) and navigated to my /tmp folder in cPanel File Manager to locate the file. However, no matter what, the uploaded file was nowhere to be found there.

I spent hours trying to determine the reason for this, and implemented every suggestion that's been offered here.

Finally, after searching my website files for the query tmp, I discovered that my site contained other folders named tmp in different directories. I realized that my PHP script was actually writing the uploaded files to .cagefs/tmp. (The "Show Hidden Files" setting must be enabled in cPanel in order to view this folder.)

So, why does the sys_get_temp_dir function return inaccurate info?

Here's an explanation from the PHP.net webpage for sys_get_temp_dir (i.e., the top comment):

If running on a Linux system where systemd has PrivateTmp=true (which is the default on CentOS 7 and perhaps other newer distros), this function will simply return "/tmp", not the true, much longer, somewhat dynamic path.

This SO post delves into the issue, as well:

Could not load file or assembly 'System.Web.Http 4.0.0 after update from 2012 to 2013

<dependentAssembly>
    <assemblyIdentity name="System.Web.Http" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>
<dependentAssembly>
    <assemblyIdentity name="System.Net.Http.Formatting" publicKeyToken="31bf3856ad364e35" culture="neutral" />
    <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>

How do I set <table> border width with CSS?

The default border-style is none, so you must specify that as well as the width and the colour.

You can use the border shorthand property to set all three values in one go.

Also, the border attribute describes the border for the table and the cells. CSS is much more flexible so it only describes the border of the elements you are selecting. You need to select the cells too in order to get the same effect.

table, th, td {
    border: solid black 1px;
}

See also border properties and tables in CSS.

Only allow Numbers in input Tag without Javascript

Of course, you can't fully rely on the client-side (javascript) validation, but that's not a reason to avoid it completely. With or without it, you have to do the server-side validation anyway (since the client can disable javascript). And that's just what you're left with, due to your non-javascript solution constraint.

So, after a submit, if the field value doesn't pass the server-side validation, the client should end up on the very same page, with additional error message specifying the requested value format. You also should provide the value format information beforehands, e.g. as a tool-tip hint (title attribute).

There's most certainly no passive client-side validation mechanism existing in HTML 4 / XHTML.

On the other hand, in HTML 5 you have two options:

  • input of type number:

    <input type="number" min="xxx" max="yyy" title="Format: 3 digits" />
    

    – only validates the range – if user enters a non-number, an empty value is submitted
    – the field visual is enhanced with increment / decrement controls (browser dependent)

  • the pattern attribute:

    <input type="text" pattern="[0-9]{3}" title="Format: 3 digits" />
    <input type="text" pattern="\d{3}" title="Format: 3 digits" />
    

    – this gives you a full contorl over the format (anything you can specify by regular expression)
    – no visual difference / enhancement

But here you still rely on browser capabilities, so do a server-side validation in either case.

android.content.Context.getPackageName()' on a null object reference

You solve the issue with a try/ catch. This crash happens when user close the app before the start intent.

try
{
    Intent mIntent = new Intent(getActivity(),MusicHome.class);
    mIntent.putExtra("SigninFragment.user_details", bundle);
    startActivity(mIntent);
}
catch (Exception e) {
    e.printStackTrace();
}

Declaring array of objects

Use array.push() to add an item to the end of the array.

var sample = new Array();
sample.push(new Object());

To do this n times use a for loop.

var n = 100;
var sample = new Array();
for (var i = 0; i < n; i++)
    sample.push(new Object());

Note that you can also substitute new Array() with [] and new Object() with {} so it becomes:

var n = 100;
var sample = [];
for (var i = 0; i < n; i++)
    sample.push({});

Switch to another branch without changing the workspace files

Simplest way to do is as follows:

git fetch && git checkout <branch_name>

Getting the textarea value of a ckeditor textarea with javascript

var campaignTitle= CKEDITOR.instances['CampaignTitle'].getData();

How to avoid the "Windows Defender SmartScreen prevented an unrecognized app from starting warning"

After clicking on Properties of any installer(.exe) which block your application to install (Windows Defender SmartScreen prevented an unrecognized app ) for that issue i found one solution

  1. Right click on installer(.exe)
  2. Select properties option.
  3. Click on checkbox to check Unblock at the bottom of Properties.

This solution work for Heroku CLI (heroku-x64) installer(.exe)

XAMPP MySQL password setting (Can not enter in PHPMYADMIN)

MySQL multiple instances present on Ubuntu.

step 1 : if it's listed as installed, you got it. Else you need to get it.

sudo ps -A | grep mysql

step 2 : remove the one MySQL

sudo apt-get remove mysql

sudo service mysql restart

step 3 : restart lamp

sudo /opt/lampp/lampp restart

How to generate xsd from wsdl

You can use SoapUI: http://www.soapui.org/ This is a generally handy program. Make a new project, connect to the WSDL link, then right click on the project and say "Show interface viewer". Under "Schemas" on the left you can see the XSD.

SoapUI can do many things though!

how can I check if a file exists?

Start with this:

Set fso = CreateObject("Scripting.FileSystemObject")
If (fso.FileExists(path)) Then
   msg = path & " exists."
Else
   msg = path & " doesn't exist."
End If

Taken from the documentation.

What is the meaning of ImagePullBackOff status on a Kubernetes pod?

You can specify also imagePullPolicy: Never in the container's spec:

containers:
- name: nginx
  imagePullPolicy: Never
  image: custom-nginx
  ports:
  - containerPort: 80

How to start IDLE (Python editor) without using the shortcut on Windows Vista?

I got a shortcut for Idle (Python GUI).

  • Click on Window icon at the bottom left or use Window Key (only Python 2), you will see Idle (Python GUI) icon
  • Right click on the icon then more
  • Open File Location
  • A new window will appears, and you will see the shortcut of Idle (Python GUI)
  • Right click, hold down and pull out to desktop to create a shortcut of Python GUI on desktop.

javascript Unable to get property 'value' of undefined or null reference

You can't access element like you did (document.frm_new_user_request). You have to use the function getElementById:

document.getElementById("frm_new_user_request")

So getting a value from an input could look like this:

var value = document.getElementById("frm_new_user_request").value

Also you can use some JavaScript framework, e.g. jQuery, which simplifies operations with DOM (Document Object Model) and also hides differences between various browsers from you.

Getting a value from an input using jQuery would look like this:

  • input with ID "element": var value = $("#element).value
  • input with class "element": var value = $(".element).value

Compare 2 arrays which returns difference

I know this is an old question, but I thought I would share this little trick.

var diff = $(old_array).not(new_array).get();

diff now contains what was in old_array that is not in new_array

Run an exe from C# code

Example:

Process process = Process.Start(@"Data\myApp.exe");
int id = process.Id;
Process tempProc = Process.GetProcessById(id);
this.Visible = false;
tempProc.WaitForExit();
this.Visible = true;

Pythonic way to print list items

To display each content, I use:

mylist = ['foo', 'bar']
indexval = 0
for i in range(len(mylist)):     
    print(mylist[indexval])
    indexval += 1

Example of using in a function:

def showAll(listname, startat):
   indexval = startat
   try:
      for i in range(len(mylist)):
         print(mylist[indexval])
         indexval = indexval + 1
   except IndexError:
      print('That index value you gave is out of range.')

Hope I helped.

PHP date() with timezone?

It should like this:

date_default_timezone_set('America/New_York');

Is there a way to perform "if" in python's lambda

note you can use several else...if statements in your lambda definition:

f = lambda x: 1 if x>0 else 0 if x ==0 else -1

Creating default object from empty value in PHP?

This message has been E_STRICT for PHP <= 5.3. Since PHP 5.4, it was unluckilly changed to E_WARNING. Since E_WARNING messages are useful, you don't want to disable them completely.

To get rid of this warning, you must use this code:

if (!isset($res)) 
    $res = new stdClass();

$res->success = false;

This is fully equivalent replacement. It assures exactly the same thing which PHP is silently doing - unfortunatelly with warning now - implicit object creation. You should always check if the object already exists, unless you are absolutely sure that it doesn't. The code provided by Michael is no good in general, because in some contexts the object might sometimes be already defined at the same place in code, depending on circumstances.

Starting a node.js server

Run cmd and then run node server.js. In your example, you are trying to use the REPL to run your command, which is not going to work. The ellipsis is node.js expecting more tokens before closing the current scope (you can type code in and run it on the fly here)

Move a view up only when the keyboard covers an input field

Here is My 2 cents:

Have you tried: https://github.com/hackiftekhar/IQKeyboardManager

Extremely easy to install Swift or Objective-C.

Here how it works:

IQKeyboardManager (Swift):- IQKeyboardManagerSwift is available through CocoaPods, to install it simply add the following line to your Podfile: (#236)

pod 'IQKeyboardManagerSwift'

In AppDelegate.swift, just import IQKeyboardManagerSwift framework and enable IQKeyboardManager.

import IQKeyboardManagerSwift

@UIApplicationMain
class AppDelegate: UIResponder, UIApplicationDelegate {

    var window: UIWindow?

    func application(application: UIApplication, didFinishLaunchingWithOptions launchOptions: [NSObject: AnyObject]?) -> Bool {

    IQKeyboardManager.sharedManager().enable = true
    // For Swift 4, use this instead
    // IQKeyboardManager.shared.enable = true


    return true
    }
}

And that is all. Easy!

A variable modified inside a while loop is not remembered

echo -e $lines | while read line 
    ...
done

The while loop is executed in a subshell. So any changes you do to the variable will not be available once the subshell exits.

Instead you can use a here string to re-write the while loop to be in the main shell process; only echo -e $lines will run in a subshell:

while read line
do
    if [[ "$line" == "second line" ]]
    then
        foo=2
        echo "Variable \$foo updated to $foo inside if inside while loop"
    fi
    echo "Value of \$foo in while loop body: $foo"
done <<< "$(echo -e "$lines")"

You can get rid of the rather ugly echo in the here-string above by expanding the backslash sequences immediately when assigning lines. The $'...' form of quoting can be used there:

lines=$'first line\nsecond line\nthird line'
while read line; do
    ...
done <<< "$lines"

When to use in vs ref vs out

Still feel the need for a good summary, this is what I came up with.

Summary,

When we are inside the function, this is how we specify the variable data access control,

in = R

out = must W before R

ref = R+W


Explanation,

in

Function may only READ that variable.

out

Variable must not be initialised first because,
function MUST WRITE to it before READ.

ref

Function may READ/WRITE to that variable.


Why is it named as such?

Focusing on where data gets modified,

in

Data must only be set before entering (in) function.

out

Data must only be set before leaving (out) function.

ref

Data must be set before entering (in) function.
Data may be set before leaving (out) function.

How to check if all of the following items are in a list?

What if your lists contain duplicates like this:

v1 = ['s', 'h', 'e', 'e', 'p']
v2 = ['s', 's', 'h']

Sets do not contain duplicates. So, the following line returns True.

set(v2).issubset(v1)

To count for duplicates, you can use the code:

v1 = sorted(v1)
v2 = sorted(v2)


def is_subseq(v2, v1):
    """Check whether v2 is a subsequence of v1."""
    it = iter(v1)
    return all(c in it for c in v2) 

So, the following line returns False.

is_subseq(v2, v1)

Difference between Return and Break statements

You won't be able to exit only from an if condition using either return or break.

return is used when you need to return from a method after its execution is finished when you don't want to execute the rest of the method code. So if you use return, then you will not only return from your if condition, but also from the whole method.

Consider the following method:

public void myMethod()
{
    int i = 10;

    if(i==10)
        return;

    System.out.println("This will never be printed");
}

Here, using return causes to stop the execution of the whole method after line 3 and execution goes back to its caller.

break is used to break out from a loop or a switch statement. Consider this example -

int i;

for(int j=0; j<10; j++)
{
    for(i=0; i<10; i++)
    {
        if(i==0)
            break;        // This break will cause the loop (innermost) to stop just after one iteration;
    }

    if(j==0)
        break;    // and then this break will cause the outermost loop to stop.
}

switch(i)
{
    case 0: break;    // This break will cause execution to skip executing the second case statement

    case 1: System.out.println("This will also never be printed");
}

This type of break statement is known as unlabeled break statement. There is another form of break, which is called labeled break. Consider this example -

int[][] arrayOfInts = { { 32, 87, 3, 589 },
                            { 12, 1076, 2000, 8 },
                            { 622, 127, 77, 955 }
                          };
int searchfor = 12;

int i;
int j = 0;
boolean foundIt = false;

search:
    for (i = 0; i < arrayOfInts.length; i++)
    {
        for (j = 0; j < arrayOfInts[i].length; j++)
        {
            if (arrayOfInts[i][j] == searchfor)
            {
                foundIt = true;
                break search;
            }
        }
    }

This example uses nested for loops to search for a value in a two-dimensional array. When the value is found, a labeled break terminates the outer for loop (labeled "search").

You can learn more abour break and return statements from JavaDoc.

How to compile a Perl script to a Windows executable with Strawberry Perl?

  :: short answer :
  :: perl -MCPAN -e "install PAR::Packer" 
  pp -o <<DesiredExeName>>.exe <<MyFancyPerlScript>> 

  :: long answer - create the following cmd , adjust vars to your taste ...
  :: next_line_is_templatized
  :: file:compile-morphus.1.2.3.dev.ysg.cmd v1.0.0
  :: disable the echo
  @echo off

  :: this is part of the name of the file - not used
  set _Action=run

  :: the name of the Product next_line_is_templatized
  set _ProductName=morphus

  :: the version of the current Product next_line_is_templatized
  set _ProductVersion=1.2.3

  :: could be dev , test , dev , prod next_line_is_templatized
  set _ProductType=dev

  :: who owns this Product / environment next_line_is_templatized
  set _ProductOwner=ysg

  :: identifies an instance of the tool ( new instance for this version could be created by simply changing the owner )   
  set _EnvironmentName=%_ProductName%.%_ProductVersion%.%_ProductType%.%_ProductOwner%

  :: go the run dir
  cd %~dp0

  :: do 4 times going up
  for /L %%i in (1,1,5) do pushd ..

  :: The BaseDir is 4 dirs up than the run dir
  set _ProductBaseDir=%CD%
  :: debug echo BEFORE _ProductBaseDir is %_ProductBaseDir%
  :: remove the trailing \

  IF %_ProductBaseDir:~-1%==\ SET _ProductBaseDir=%_ProductBaseDir:~0,-1%
  :: debug echo AFTER _ProductBaseDir is %_ProductBaseDir%
  :: debug pause


  :: The version directory of the Product 
  set _ProductVersionDir=%_ProductBaseDir%\%_ProductName%\%_EnvironmentName%

  :: the dir under which all the perl scripts are placed
  set _ProductVersionPerlDir=%_ProductVersionDir%\sfw\perl

  :: The Perl script performing all the tasks
  set _PerlScript=%_ProductVersionPerlDir%\%_Action%_%_ProductName%.pl

  :: where the log events are stored 
  set _RunLog=%_ProductVersionDir%\data\log\compile-%_ProductName%.cmd.log

  :: define a favorite editor 
  set _MyEditor=textpad

  ECHO Check the variables 
  set _
  :: debug PAUSE
  :: truncate the run log
  echo date is %date% time is %time% > %_RunLog%


  :: uncomment this to debug all the vars 
  :: debug set  >> %_RunLog%

  :: for each perl pm and or pl file to check syntax and with output to logs
  for /f %%i in ('dir %_ProductVersionPerlDir%\*.pl /s /b /a-d' ) do echo %%i >> %_RunLog%&perl -wc %%i | tee -a  %_RunLog% 2>&1


  :: for each perl pm and or pl file to check syntax and with output to logs
  for /f %%i in ('dir %_ProductVersionPerlDir%\*.pm /s /b /a-d' ) do echo %%i >> %_RunLog%&perl -wc %%i | tee -a  %_RunLog% 2>&1

  :: now open the run log
  cmd /c start /max %_MyEditor% %_RunLog%


  :: this is the call without debugging
  :: old 
  echo CFPoint1  OK The run cmd script %0 is executed >> %_RunLog%
  echo CFPoint2  OK  compile the exe file  STDOUT and STDERR  to a single _RunLog file >> %_RunLog%
  cd %_ProductVersionPerlDir%

  pp -o %_Action%_%_ProductName%.exe %_PerlScript% | tee -a %_RunLog% 2>&1 

  :: open the run log
  cmd /c start /max %_MyEditor% %_RunLog%

  :: uncomment this line to wait for 5 seconds
  :: ping localhost -n 5

  :: uncomment this line to see what is happening 
  :: PAUSE

  ::
  :::::::
  :: Purpose: 
  :: To compile every *.pl file into *.exe file under a folder 
  :::::::
  :: Requirements : 
  :: perl , pp , win gnu utils tee 
  :: perl -MCPAN -e "install PAR::Packer" 
  :: text editor supporting <<textEditor>> <<FileNameToOpen>> cmd call syntax
  :::::::
  :: VersionHistory
  :: 1.0.0 --- 2012-06-23 12:05:45 --- ysg --- Initial creation from run_morphus.cmd
  :::::::
  :: eof file:compile-morphus.1.2.3.dev.ysg.cmd v1.0.0

Setting max-height for table cell contents

We finally found an answer of sorts. First, the problem: the table always sizes itself around the content, rather than forcing the content to fit in the table. That limits your options.

We did it by setting the content div to display:none, letting the table size itself, and then in javascript setting the height and width of the content div to the inner height and width of the enclosing td tag. Show the content div. Repeat the process when the window is resized.

What is the native keyword in Java for?

Java native method provides a mechanism for Java code to call OS native code, either due to functional or performance reasons.

Example:

606  public native int availableProcessors();
617  public native long freeMemory();
630  public native long totalMemory();
641  public native long maxMemory();
664  public native void gc();

In the corresponding Runtime.class file in OpenJDK, located in JAVA_HOME/jmods/java.base.jmod/classes/java/lang/Runtime.class, contains these methods and tagged them with ACC_NATIVE (0x0100), and these methods do not contain the Code attribute, which means these method do not have any actual coding logic in the Runtime.class file:

  • Method 13 availableProcessors: tagged as native and no Code attribute
  • Method 14 freeMemory: tagged as native and no Code attribute
  • Method 15 totalMemory: tagged as native and no Code attribute
  • Method 16 maxMemory: tagged as native and no Code attribute
  • Method 17 gc: tagged as native and no Code attribute

enter image description here

The in fact coding logic is in the corresponding Runtime.c file:

42  #include "java_lang_Runtime.h"
43
44  JNIEXPORT jlong JNICALL
45  Java_java_lang_Runtime_freeMemory(JNIEnv *env, jobject this)
46  {
47      return JVM_FreeMemory();
48  }
49
50  JNIEXPORT jlong JNICALL
51  Java_java_lang_Runtime_totalMemory(JNIEnv *env, jobject this)
52  {
53      return JVM_TotalMemory();
54  }
55
56  JNIEXPORT jlong JNICALL
57  Java_java_lang_Runtime_maxMemory(JNIEnv *env, jobject this)
58  {
59      return JVM_MaxMemory();
60  }
61
62  JNIEXPORT void JNICALL
63  Java_java_lang_Runtime_gc(JNIEnv *env, jobject this)
64  {
65      JVM_GC();
66  }
67  
68  JNIEXPORT jint JNICALL
69  Java_java_lang_Runtime_availableProcessors(JNIEnv *env, jobject this)
70  {
71      return JVM_ActiveProcessorCount();
72  }

And these C coding is compiled into the libjava.so (Linux) or libjava.dll (Windows) file, located at JAVA_HOME/jmods/java.base.jmod/lib/libjava.so:

enter image description here

enter image description here

Reference

Get text of the selected option with jQuery

You could actually put the value = to the text and then do

$j(document).ready(function(){
    $j("select#select_2").change(function(){
        val = $j("#select_2 option:selected").html();
        alert(val);
    });
});

Or what I did on a similar case was

<select name="options[2]" id="select_2" onChange="JavascriptMethod()">
  with you're options here
</select>

With this second option you should have a undefined. Give me feedback if it worked :)

Patrick

The process cannot access the file because it is being used by another process (File is created but contains nothing)

using (var fs = new FileStream(filePath, FileMode.Append, FileAccess.Write, FileShare.ReadWrite))
using (var sw = new StreamWriter(fs))
{
    sw.WriteLine(message);
}

Extract names of objects from list

Making a small tweak to the inside function and using lapply on an index instead of the actual list itself gets this doing what you want

x <- c("yes", "no", "maybe", "no", "no", "yes")
y <- c("red", "blue", "green", "green", "orange")
list.xy <- list(x=x, y=y)

WORD.C <- function(WORDS){
  require(wordcloud)

  L2 <- lapply(WORDS, function(x) as.data.frame(table(x), stringsAsFactors = FALSE))

  # Takes a dataframe and the text you want to display
  FUN <- function(X, text){
    windows() 
    wordcloud(X[, 1], X[, 2], min.freq=1)
    mtext(text, 3, padj=-4.5, col="red")  #what I'm trying that isn't working
  }

  # Now creates the sequence 1,...,length(L2)
  # Loops over that and then create an anonymous function
  # to send in the information you want to use.
  lapply(seq_along(L2), function(i){FUN(L2[[i]], names(L2)[i])})

  # Since you asked about loops
  # you could use i in seq_along(L2) 
  # instead of 1:length(L2) if you wanted to
  #for(i in 1:length(L2)){
  #  FUN(L2[[i]], names(L2)[i])
  #}
}

WORD.C(list.xy)

On linux SUSE or RedHat, how do I load Python 2.7

If you need pip and setup tool , please install openssl and opessl-devl before making python2.7

 yum install openssl-devel

Then follow https://stackoverflow.com/a/4149444/429476

Then https://pypi.python.org/pypi/setuptools

wget https://bootstrap.pypa.io/ez_setup.py
python2.7 ez_setup.py

Then to install pip

wget https://bootstrap.pypa.io/get-pip.py
python2.7 get-pip.py

Then to install other packages pip2.7 install package_name

Changing fonts in ggplot2

Another option is to use showtext package which supports more types of fonts (TrueType, OpenType, Type 1, web fonts, etc.) and more graphics devices, and avoids using external software such as Ghostscript.

# install.packages('showtext', dependencies = TRUE)
library(showtext)

Import some Google Fonts

# https://fonts.google.com/featured/Superfamilies
font_add_google("Montserrat", "Montserrat")
font_add_google("Roboto", "Roboto")

Load font from the current search path into showtext

# Check the current search path for fonts
font_paths()    
#> [1] "C:\\Windows\\Fonts"

# List available font files in the search path
font_files()    
#>   [1] "AcadEref.ttf"                                
#>   [2] "AGENCYB.TTF"                           
#> [428] "pala.ttf"                                    
#> [429] "palab.ttf"                                   
#> [430] "palabi.ttf"                                  
#> [431] "palai.ttf"

# syntax: font_add(family = "<family_name>", regular = "/path/to/font/file")
font_add("Palatino", "pala.ttf")

font_families()
#> [1] "sans"         "serif"        "mono"         "wqy-microhei"
#> [5] "Montserrat"   "Roboto"       "Palatino"

## automatically use showtext for new devices
showtext_auto() 

Plot: need to open Windows graphics device as showtext does not work well with RStudio built-in graphics device

# https://github.com/yixuan/showtext/issues/7
# https://journal.r-project.org/archive/2015-1/qiu.pdf
# `x11()` on Linux, or `quartz()` on Mac OS
windows()

myFont1 <- "Montserrat"
myFont2 <- "Roboto"
myFont3 <- "Palatino"

library(ggplot2)

a <- ggplot(mtcars, aes(x = wt, y = mpg)) + 
  geom_point() +
  ggtitle("Fuel Efficiency of 32 Cars") +
  xlab("Weight (x1000 lb)") + ylab("Miles per Gallon") +
  theme(text = element_text(size = 16, family = myFont1)) +
  annotate("text", 4, 30, label = 'Palatino Linotype',
           family = myFont3, size = 10) +
  annotate("text", 1, 11, label = 'Roboto', hjust = 0,
           family = myFont2, size = 10) 

## On-screen device
print(a) 

## Save to PNG 
ggsave("plot_showtext.png", plot = a, 
       type = 'cairo',
       width = 6, height = 6, dpi = 150)  

## Save to PDF
ggsave("plot_showtext.pdf", plot = a, 
       device = cairo_pdf,
       width = 6, height = 6, dpi = 150)  

## turn showtext off if no longer needed
showtext_auto(FALSE) 

Edit: another workaround to use showtext in RStudio. Run the following code at the beginning of the R session (source)

trace(grDevices::png, exit = quote({
    showtext::showtext_begin()
}), print = FALSE)

Edit 2: Starting from version 0.9, showtext can work well with the RStudio graphics device (RStudioGD). Simply call showtext_auto() in the RStudio session and then the plots will be displayed correctly.

Kotlin - How to correctly concatenate a String

Similar to @Rhusfer answer I wrote this. In case you have a group of EditTexts and want to concatenate their values, you can write:

listOf(edit_1, edit_2, edit_3, edit_4).joinToString(separator = "") { it.text.toString() }

If you want to concatenate Map, use this:

map.entries.joinToString(separator = ", ")

To concatenate Bundle, use

bundle.keySet().joinToString(", ") { key -> "$key=${bundle[key]}" }

It sorts keys in alphabetical order.

Example:

val map: MutableMap<String, Any> = mutableMapOf("price" to 20.5)
map += "arrange" to 0
map += "title" to "Night cream"
println(map.entries.joinToString(separator = ", "))

// price=20.5, arrange=0, title=Night cream

val bundle = bundleOf("price" to 20.5)
bundle.putAll(bundleOf("arrange" to 0))
bundle.putAll(bundleOf("title" to "Night cream"))
val bundleString =
    bundle.keySet().joinToString(", ") { key -> "$key=${bundle[key]}" }
println(bundleString)

// arrange=0, price=20.5, title=Night cream

How to update Ruby to 1.9.x on Mac?

As previously mentioned, the bundler version may be too high for your version of rails.

I ran into the same problem using Rails 3.0.1 which requires Bundler v1.0.0 - v1.0.22

Check your bundler version using: gem list bundler

If your bundler version is not within the appropriate range, I found this solution to work: rvm @global do gem uninstall bundler

Note: rvm is required for this solution... another case for why you should be using rvm in the first place.

Swift days between two NSDates

Update for Swift 3 iOS 10 Beta 4

func daysBetweenDates(startDate: Date, endDate: Date) -> Int {
    let calendar = Calendar.current
    let components = calendar.dateComponents([Calendar.Component.day], from: startDate, to: endDate)
    return components.day!
}

What is the purpose of XSD files?

An XSD is a formal contract that specifies how an XML document can be formed. It is often used to validate an XML document, or to generate code from.

Ping with timestamp on Windows CLI

Try this instead:

ping -c2 -s16 sntdn | awk '{print NR " | " strftime("%Y-%m-%d_%H:%M:%S") " | " $0  }'

Check if it suits you

link with target="_blank" does not open in new tab in Chrome

Because JavaScript is handling the click event. When you click, the following code is called:

el.addEvent('click', function(e){
    if(obj.options.onOpen){
        new Event(e).stop();
        if(obj.options.open == i){
            obj.options.open = null;
            obj.options.onClose(this.href, i);
        }else{
            obj.options.open = i;
            obj.options.onOpen(this.href, i);
        }   
    }       
})

The onOpen manually changes the location.

Edit: Regarding your comment... If you can modify ImageMenu.js, you could update the script which calls onClose to pass the a element object (this, rather than this.href)

obj.options.onClose(this, i);

Then update your ImageMenu instance, with the following onOpen change:

window.addEvent('domready', function(){
    var myMenu = new ImageMenu($$('#imageMenu a'), {
        openWidth: 310,
        border: 2,
        onOpen: function(e, i) {
            if (e.target === '_blank') {
                window.open(e.href);    
            } else {
                location = e.href;
            }
        }
    });
});

This would check for the target property of the element to see if it's _blank, and then call window.open, if found.

If you'd prefer not to modify ImageMenu.js, another option would be to modify your links to identify them in your onOpen handler. Say something like:

<a href="http://www.foracure.org.au/#_b=1" target="_blank" style="width: 105px;"></a>

Then, update your onOpen call to:

onOpen: function(e, i) {
    if (e.indexOf('_b=1') > -1) {
        window.open(e);   
    } else {
        location = e;
    }
}

The only downside to this is the user sees the hash on hover.

Finally, if the number of links that you plan to open in a new window are low, you could create a map and check against that. Something like:

var linksThatOpenInANewWindow = {
    'http://www.foracure.org.au': 1
};

onOpen: function(e, i) {
    if (linksThatOpenInANewWindow[e] === 1) {
        window.open(e);   
    } else {
        location = e
    }
}

The only downside is maintenance, depending on the number of links.

Others have suggested modifying the link (using # or javascript:) and adding an inline event handler (onclick) - I don't recommend that at all as it breaks links when JS is disabled/not supported.

Converting any string into camel case

This function by pass cammelcase such these tests

  • Foo Bar
  • --foo-bar--
  • __FOO_BAR__-
  • foo123Bar
  • foo_Bar

_x000D_
_x000D_
function toCamelCase(str)
{
  var arr= str.match(/[a-z]+|\d+/gi);
  return arr.map((m,i)=>{
    let low = m.toLowerCase();
    if (i!=0){
      low = low.split('').map((s,k)=>k==0?s.toUpperCase():s).join``
    }
    return low;
  }).join``;
}
console.log(toCamelCase('Foo      Bar'));
console.log(toCamelCase('--foo-bar--'));
console.log(toCamelCase('__FOO_BAR__-'));
console.log(toCamelCase('foo123Bar'));
console.log(toCamelCase('foo_Bar'));

console.log(toCamelCase('EquipmentClass name'));
console.log(toCamelCase('Equipment className'));
console.log(toCamelCase('equipment class name'));
console.log(toCamelCase('Equipment Class Name'));
_x000D_
_x000D_
_x000D_

Filter Java Stream to 1 and only 1 element

For the sake of completeness, here is the ‘one-liner’ corresponding to @prunge’s excellent answer:

User user1 = users.stream()
        .filter(user -> user.getId() == 1)
        .reduce((a, b) -> {
            throw new IllegalStateException("Multiple elements: " + a + ", " + b);
        })
        .get();

This obtains the sole matching element from the stream, throwing

  • NoSuchElementException in case the stream is empty, or
  • IllegalStateException in case the stream contains more than one matching element.

A variation of this approach avoids throwing an exception early and instead represents the result as an Optional containing either the sole element, or nothing (empty) if there are zero or multiple elements:

Optional<User> user1 = users.stream()
        .filter(user -> user.getId() == 1)
        .collect(Collectors.reducing((a, b) -> null));

How can I sort a std::map first by value, then by key?

You can use std::set instead of std::map.

You can store both key and value in std::pair and the type of container will look like this:

std::set< std::pair<int, std::string> > items;

std::set will sort it's values both by original keys and values that were stored in std::map.

Java Error: illegal start of expression

Methods can only declare local variables. That is why the compiler reports an error when you try to declare it as public.

In the case of local variables you can not use any kind of accessor (public, protected or private).

You should also know what the static keyword means. In method checkYourself, you use the Integer array locations.

The static keyword distinct the elements that are accessible with object creation. Therefore they are not part of the object itself.

public class Test { //Capitalized name for classes are used in Java
   private final init[] locations; //key final mean that, is must be assigned before object is constructed and can not be changed later. 

   public Test(int[] locations) {
      this.locations = locations;//To access to class member, when method argument has the same name use `this` key word. 
   }

   public boolean checkYourSelf(int value) { //This method is accessed only from a object.
      for(int location : locations) {
         if(location == value) {
            return true; //When you use key word return insied of loop you exit from it. In this case you exit also from whole method.
         }
      }
      return false; //Method should be simple and perform one task. So you can get more flexibility. 
   }
   public static int[] locations = {1,2,3};//This is static array that is not part of object, but can be used in it. 

   public static void main(String[] args) { //This is declaration of public method that is not part of create object. It can be accessed from every place.
      Test test = new Test(Test.locations); //We declare variable test, and create new instance (object) of class Test.  
      String result;
      if(test.checkYourSelf(2)) {//We moved outside the string
        result = "Hurray";        
      } else {
        result = "Try again"
      }
      System.out.println(result); //We have only one place where write is done. Easy to change in future.
   } 
}

write multiple lines in a file in python

variable=10
f=open("fileName.txt","w+") # file name and mode
for x in range(0,10):
    f.writelines('your text')
    f.writelines('if you want to add variable data'+str(variable))
    # to add data you only add String data so you want to type cast variable  
    f.writelines("\n")

PHP foreach change original array values

Use &:

foreach($arr as &$value) {
    $value = $newVal;
}

& passes a value of the array as a reference and does not create a new instance of the variable. Thus if you change the reference the original value will change.

PHP documentation for Passing by Reference

Edit 2018

This answer seems to be favored by a lot of people on the internet, which is why I decided to add more information and words of caution.
While pass by reference in foreach (or functions) is a clean and short solution, for many beginners this might be a dangerous pitfall.

  1. Loops in PHP don't have their own scope. - @Mark Amery

    This could be a serious problem when the variables are being reused in the same scope. Another SO question nicely illustrates why that might be a problem.

  2. As foreach relies on the internal array pointer in PHP 5, changing it within the loop may lead to unexpected behavior. - PHP docs for foreach.

    Unsetting a record or changing the hash value (the key) during the iteration on the same loop could lead to potentially unexpected behaviors in PHP < 7. The issue gets even more complicated when the array itself is a reference.

  3. Foreach performance.
    In general, PHP prefers pass by value due to the copy-on-write feature. It means that internally PHP will not create duplicate data unless the copy of it needs to be changed. It is debatable whether pass by reference in foreach would offer a performance improvement. As it is always the case, you need to test your specific scenario and determine which option uses less memory and CPU time. For more information see the SO post linked below by NikiC.

  4. Code readability.
    Creating references in PHP is something that quickly gets out of hand. If you are a novice and don't have full control of what you are doing, it is best to stay away from references. For more information about & operator take a look at this guide: Reference — What does this symbol mean in PHP?
    For those who want to learn more about this part of PHP language: PHP References Explained

A very nice technical explanation by @NikiC of the internal logic of PHP foreach loops:
How does PHP 'foreach' actually work?

Simulate a click on 'a' element using javascript/jquery

Try to use document.createEvent described here https://developer.mozilla.org/en-US/docs/Web/API/document.createEvent

The code for function that simulates click should look something like this:

function simulateClick() {
  var evt = document.createEvent("MouseEvents");
  evt.initMouseEvent("click", true, true, window,
    0, 0, 0, 0, 0, false, false, false, false, 0, null);
  var a = document.getElementById("gift-close"); 
  a.dispatchEvent(evt);      
}

batch script - run command on each file in directory

I am doing similar thing to compile all the c files in a directory.
for iterating files in different directory try this.

set codedirectory=C:\Users\code
for /r  %codedirectory% %%i in (*.c) do 
( some GCC commands )

How to change MenuItem icon in ActionBar programmatically

to use in onMenuItemClick(MenuItem item) just do invalidateOptionsMenu(); item.setIcon(ContextCompat.getDrawable(this, R.drawable.ic_baseline_play_circle_outline_24px));

How to handle screen orientation change when progress dialog and background thread active?

I came up with a rock-solid solution for these issues that conforms with the 'Android Way' of things. I have all my long-running operations using the IntentService pattern.

That is, my activities broadcast intents, the IntentService does the work, saves the data in the DB and then broadcasts sticky intents. The sticky part is important, such that even if the Activity was paused during during the time after the user initiated the work and misses the real time broadcast from the IntentService we can still respond and pick up the data from the calling Activity. ProgressDialogs can work with this pattern quite nicely with onSaveInstanceState().

Basically, you need to save a flag that you have a progress dialog running in the saved instance bundle. Do not save the progress dialog object because this will leak the entire Activity. To have a persistent handle to the progress dialog, I store it as a weak reference in the application object. On orientation change or anything else that causes the Activity to pause (phone call, user hits home etc.) and then resume, I dismiss the old dialog and recreate a new dialog in the newly created Activity.

For indefinite progress dialogs this is easy. For progress bar style, you have to put the last known progress in the bundle and whatever information you're using locally in the activity to keep track of the progress. On restoring the progress, you'll use this information to re-spawn the progress bar in the same state as before and then update based on the current state of things.

So to summarize, putting long-running tasks into an IntentService coupled with judicious use of onSaveInstanceState() allows you to efficiently keep track of dialogs and restore then across the Activity life-cycle events. Relevant bits of Activity code are below. You'll also need logic in your BroadcastReceiver to handle Sticky intents appropriately, but that is beyond the scope of this.

public void doSignIn(View view) {
    waiting=true;
    AppClass app=(AppClass) getApplication();
    String logingon=getString(R.string.signon);
    app.Dialog=new WeakReference<ProgressDialog>(ProgressDialog.show(AddAccount.this, "", logingon, true));
    ...
}

@Override
protected void onSaveInstanceState(Bundle saveState) {
    super.onSaveInstanceState(saveState);
    saveState.putBoolean("waiting",waiting);
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if(savedInstanceState!=null) {
        restoreProgress(savedInstanceState);    
    }
    ...
}

private void restoreProgress(Bundle savedInstanceState) {
    waiting=savedInstanceState.getBoolean("waiting");
    if (waiting) {
        AppClass app=(AppClass) getApplication();
        ProgressDialog refresher=(ProgressDialog) app.Dialog.get();
        refresher.dismiss();
        String logingon=getString(R.string.signon);
        app.Dialog=new WeakReference<ProgressDialog>(ProgressDialog.show(AddAccount.this, "", logingon, true));
    }
}

How to upload, display and save images using node.js and express

First of all, you should make an HTML form containing a file input element. You also need to set the form's enctype attribute to multipart/form-data:

<form method="post" enctype="multipart/form-data" action="/upload">
    <input type="file" name="file">
    <input type="submit" value="Submit">
</form>

Assuming the form is defined in index.html stored in a directory named public relative to where your script is located, you can serve it this way:

const http = require("http");
const path = require("path");
const fs = require("fs");

const express = require("express");

const app = express();
const httpServer = http.createServer(app);

const PORT = process.env.PORT || 3000;

httpServer.listen(PORT, () => {
  console.log(`Server is listening on port ${PORT}`);
});

// put the HTML file containing your form in a directory named "public" (relative to where this script is located)
app.get("/", express.static(path.join(__dirname, "./public")));

Once that's done, users will be able to upload files to your server via that form. But to reassemble the uploaded file in your application, you'll need to parse the request body (as multipart form data).

In Express 3.x you could use express.bodyParser middleware to handle multipart forms but as of Express 4.x, there's no body parser bundled with the framework. Luckily, you can choose from one of the many available multipart/form-data parsers out there. Here, I'll be using multer:

You need to define a route to handle form posts:

const multer = require("multer");

const handleError = (err, res) => {
  res
    .status(500)
    .contentType("text/plain")
    .end("Oops! Something went wrong!");
};

const upload = multer({
  dest: "/path/to/temporary/directory/to/store/uploaded/files"
  // you might also want to set some limits: https://github.com/expressjs/multer#limits
});


app.post(
  "/upload",
  upload.single("file" /* name attribute of <file> element in your form */),
  (req, res) => {
    const tempPath = req.file.path;
    const targetPath = path.join(__dirname, "./uploads/image.png");

    if (path.extname(req.file.originalname).toLowerCase() === ".png") {
      fs.rename(tempPath, targetPath, err => {
        if (err) return handleError(err, res);

        res
          .status(200)
          .contentType("text/plain")
          .end("File uploaded!");
      });
    } else {
      fs.unlink(tempPath, err => {
        if (err) return handleError(err, res);

        res
          .status(403)
          .contentType("text/plain")
          .end("Only .png files are allowed!");
      });
    }
  }
);

In the example above, .png files posted to /upload will be saved to uploaded directory relative to where the script is located.

In order to show the uploaded image, assuming you already have an HTML page containing an img element:

<img src="/image.png" />

you can define another route in your express app and use res.sendFile to serve the stored image:

app.get("/image.png", (req, res) => {
  res.sendFile(path.join(__dirname, "./uploads/image.png"));
});

How can I set the value of a DropDownList using jQuery?

//Html Format of the dropdown list.

<select id="MyDropDownList">
<option value=test1 selected>test1</option>
<option value=test2>test2</option>
<option value=test3>test3</option>
<option value=test4>test4</option>

// If you want to change the selected Item to test2 using javascript. Try this one. // set the next option u want to select

var NewOprionValue = "Test2"

        var RemoveSelected = $("#MyDropDownList")[0].innerHTML.replace('selected', '');
        var ChangeSelected = RemoveSelected.replace(NewOption, NewOption + 'selected>');
        $('#MyDropDownList').html(ChangeSelected);

How to do a "Save As" in vba code, saving my current Excel workbook with datestamp?

I successfully use the following method in one file,

But come up with exactly the same error again... Only the last line come up with error

Newpath = Mid(ThisWorkbook.FullName, 1, _
 Len(ThisWorkbook.FullName) - Len(ThisWorkbook.Name)) & "\" & "ABC - " & Format(Date, "dd-mm-yyyy") & ".xlsm"
ThisWorkbook.SaveAs (Newpath)

How to sum columns in a dataTable?

I doubt that this is what you want but your question is a little bit vague

Dim totalCount As Int32 = DataTable1.Columns.Count * DataTable1.Rows.Count

If all your columns are numeric-columns you might want this:

You could use DataTable.Compute to Sum all values in the column.

 Dim totalCount As Double
 For Each col As DataColumn In DataTable1.Columns
     totalCount += Double.Parse(DataTable1.Compute(String.Format("SUM({0})", col.ColumnName), Nothing).ToString)
 Next

After you've edited your question and added more informations, this should work:

 Dim totalRow = DataTable1.NewRow
 For Each col As DataColumn In DataTable1.Columns
     totalRow(col.ColumnName) = Double.Parse(DataTable1.Compute("SUM(" & col.ColumnName & ")", Nothing).ToString)
 Next
 DataTable1.Rows.Add(totalRow)

How to use readline() method in Java?

Use BufferedReader and InputStreamReader classes.

BufferedReader buffer=new BufferedReader(new InputStreamReader(System.in));
String line=buffer.readLine();

Or use java.util.Scanner class methods.

Scanner scan=new Scanner(System.in);

How do I programmatically set device orientation in iOS 7?

I was in a similar problem than you. I need to lock device orientation for some screens (like Login) and allow rotation in others.

After a few changes and following some answers below I did it by:

  • Enabling all the orientations in the Project's Info.plist.

enter image description here

  • Disabling orientation in those ViewControllers where I need the device not to rotate, like in the Login screen in my case. I needed to override shouldAutorotate method in this VC:

-(BOOL)shouldAutorotate{ return NO; }

Hope this will work for you.

How to delete and update a record in Hive

Delete has been recently added in Hive version 0.14 Deletes can only be performed on tables that support ACID Below is the link from Apache .

https://cwiki.apache.org/confluence/display/Hive/LanguageManual+DML#LanguageManualDML-Delete

How do you do Impersonation in .NET?

Here is some good overview of .NET impersonation concepts.

Basically you will be leveraging these classes that are out of the box in the .NET framework:

The code can often get lengthy though and that is why you see many examples like the one you reference that try to simplify the process.

Java Interfaces/Implementation naming convention

I've seen answers here that suggest that if you only have one implementation then you don't need an interface. This flies in the face of the Depencency Injection/Inversion of Control principle (don't call us, we'll call you!).

So yes, there are situations in which you wish to simplify your code and make it easily testable by relying on injected interface implementations (which may also be proxied - your code doesn't know!). Even if you only have two implementations - one a Mock for testing, and one that gets injected into the actual production code - this doesn't make having an interface superfluous. A well documented interface establishes a contract, which can also be maintained by a strict mock implementation for testing.

in fact, you can establish tests that have mocks implement the most strict interface contract (throwing exceptions for arguments that shouldn't be null, etc) and catch errors in testing, using a more efficient implementation in production code (not checking arguments that should not be null for being null since the mock threw exceptions in your tests and you know that the arguments aren't null due to fixing the code after these tests, for example).

Dependency Injection/IOC can be hard to grasp for a newcomer, but once you understand its potential you'll want to use it all over the place and you'll find yourself making interfaces all the time - even if there will only be one (actual production) implementation.

For this one implementation (you can infer, and you'd be correct, that I believe the mocks for testing should be called Mock(InterfaceName)), I prefer the name Default(InterfaceName). If a more specific implementation comes along, it can be named appropriately. This also avoids the Impl suffix that I particularly dislike (if it's not an abstract class, OF COURSE it is an "impl"!).

I also prefer "Base(InterfaceName)" as opposed to "Abstract(InterfaceName)" because there are some situations in which you want your base class to become instantiable later, but now you're stuck with the name "Abstract(InterfaceName)", and this forces you to rename the class, possibly causing a little minor confusion - but if it was always Base(InterfaceName), removing the abstract modifier doesn't change what the class was.

How to post data using HttpClient?

Try to use this:

using (var handler = new HttpClientHandler() { CookieContainer = new CookieContainer() })
{
    using (var client = new HttpClient(handler) { BaseAddress = new Uri("site.com") })
    {
        //add parameters on request
        var body = new List<KeyValuePair<string, string>>
        {
            new KeyValuePair<string, string>("test", "test"),
            new KeyValuePair<string, string>("test1", "test1")
        };

        HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Post, "site.com");

        client.DefaultRequestHeaders.Accept.Add(new MediaTypeWithQualityHeaderValue("application/x-www-form-urlencoded; charset=UTF-8"));
        client.DefaultRequestHeaders.Add("Upgrade-Insecure-Requests", "1");
        client.DefaultRequestHeaders.Add("X-Requested-With", "XMLHttpRequest");
        client.DefaultRequestHeaders.Add("X-MicrosoftAjax", "Delta=true");
        //client.DefaultRequestHeaders.Add("Accept", "*/*");

        client.Timeout = TimeSpan.FromMilliseconds(10000);

        var res = await client.PostAsync("", new FormUrlEncodedContent(body));

        if (res.IsSuccessStatusCode)
        {
            var exec = await res.Content.ReadAsStringAsync();
            Console.WriteLine(exec);
        }                    
    }
}

How can I set the background color of <option> in a <select> element?

I had this problem too. I found setting the appearance to none helped.

.class {
    appearance:none;
    -moz-appearance:none;
    -webkit-appearance:none;

    background-color: red;
}

Git add all files modified, deleted, and untracked?

Try

git add -u

The "u" option stands for update. This will update the repo and actually delete files from the repo that you have deleted in your local copy.

git add -u [filename]

to stage a delete to just one file. Once pushed, the file will no longer be in the repo.

Alternatively,

git add -A .

is equivalent to

git add .

git add -u .

Note the extra '.' on git add -A and git add -u


Warning: Starting with git 2.0 (mid 2013), this will always stage files on the whole working tree.
If you want to stage files under the current path of your working tree, you need to use:

git add -A .

Also see: Difference of git add -A and git add .

How to get box-shadow on left & right sides only

NOTE: I suggest checking out @Hamish's answer below; it doesn't involve the imperfect "masking" in the solution described here.


You can get close with multiple box-shadows; one for each side

box-shadow: 12px 0 15px -4px rgba(31, 73, 125, 0.8), -12px 0 8px -4px rgba(31, 73, 125, 0.8);

http://jsfiddle.net/YJDdp/

Edit

Add 2 more box-shadows for the top and bottom up front to mask out the that bleeds through.

box-shadow: 0 9px 0px 0px white, 0 -9px 0px 0px white, 12px 0 15px -4px rgba(31, 73, 125, 0.8), -12px 0 15px -4px rgba(31, 73, 125, 0.8);

http://jsfiddle.net/LE6Lz/

How to concatenate and minify multiple CSS and JavaScript files with Grunt.js (0.3.x)

You don't need to add the concat package, you can do this via cssmin like this:

cssmin : {
      options: {
            keepSpecialComments: 0
      },
      minify : {
            expand : true,
            cwd : '/library/css',
            src : ['*.css', '!*.min.css'],
            dest : '/library/css',
            ext : '.min.css'
      },
      combine : {
        files: {
            '/library/css/app.combined.min.css': ['/library/css/main.min.css', '/library/css/font-awesome.min.css']
        }
      }
    }

And for js, use uglify like this:

uglify: {
      my_target: {
        files: {
            '/library/js/app.combined.min.js' : ['/app.js', '/controllers/*.js']
        }
      }
    }

extract date only from given timestamp in oracle sql

This is exactly what TO_DATE() is for: to convert timestamp to date.

Just use TO_DATE(sysdate) instead of TO_CHAR(sysdate, 'YYYY/MM/DD-HH24-MI-SS-SSSSS').

SQLFiddle demo

UPDATE:

Per your update, your cdate column is not real DATE or TIMESTAMP type, but VARCHAR2. It is not very good idea to use string types to keep dates. It is very inconvenient and slow to search, compare and do all other kinds of math on dates.

You should convert your cdate VARCHAR2 field into real TIMESTAMP. Assuming there are no other users for this field except for your code, you can convert cdate to timestamp as follows:

BEGIN TRANSACTION;
-- add new temp field tdate:
ALTER TABLE mytable ADD tdate TIMESTAMP;
-- save cdate to tdate while converting it:
UPDATE mytable SET tdate = to_date(cdate, 'YYYY-MM-DD HH24:MI:SS');

-- you may want to check contents of tdate before next step!!!

-- drop old field
ALTER TABLE mytable DROP COLUMN cdate;
-- rename tdate to cdate:
ALTER TABLE mytable RENAME COLUMN tdate TO cdate;
COMMIT;

SQLFiddle Demo

Installation error: INSTALL_FAILED_OLDER_SDK

Received the same error , the problem was difference in the version of Android SDK which AVD was using and the version in AndroidManifest file. I could solve it by correcting the

android:minSdkVersion="16"

to match with AVD.

Redirecting exec output to a buffer or file

After forking, use dup2(2) to duplicate the file's FD into stdout's FD, then exec.

Can I call an overloaded constructor from another constructor of the same class in C#?

In C# it is not possible to call another constructor from inside the method body. You can call a base constructor this way: foo(args):base() as pointed out yourself. You can also call another constructor in the same class: foo(args):this().

When you want to do something before calling a base constructor, it seems the construction of the base is class is dependant of some external things. If so, you should through arguments of the base constructor, not by setting properties of the base class or something like that

Difference between "Complete binary tree", "strict binary tree","full binary Tree"?

There is a difference between a STRICT and FULL BINARY TREE.

1) FULL BINARY TREE: A binary tree of height h that contains exactly (2^h)-1 elements is called a full binary tree. (Ref: Pg 427, Data Structures, Algorithms and Applications in C++ [University Press], Second Edition by Sartaj Sahni).

or in other words

In a FULL BINARY TREE each node has exactly 0 or 2 children and all leaf nodes are on the same level.

For Example: The following is a FULL BINARY TREE:

          18
       /      \   
     15       30    
    /  \     /   \   
  40    50  100  40 

2) STRICT BINARY TREE: Each node has exactly 0 or 2 children.

For example: The following is a STRICT BINARY TREE:

         18
       /     \   
     15       30    
    /  \          
  40    50

I think there's no confusion in the definition of a Complete Binary Tree, still for the completeness of the post I would like to tell what a Complete Binary Tree is.

3) COMPLETE BINARY TREE: A Binary Tree is complete Binary Tree if all levels are completely filled except possibly the last level and the last level has all keys as left as possible.

For Example: The following is a COMPLETE BINARY TREE:

           18
       /       \  
     15         30  
    /  \        /  \
  40    50    100   40
 /  \   /
8   7  9 

Note: The following is also a Complete Binary Tree:

         18
       /     \   
     15       30    
    /  \     /   \   
  40    50  100  40 

@RequestBody and @ResponseBody annotations in Spring

There is a whole Section in the docs called 16.3.3.4 Mapping the request body with the @RequestBody annotation. And one called 16.3.3.5 Mapping the response body with the @ResponseBody annotation. I suggest you consult those sections. Also relevant: @RequestBody javadocs, @ResponseBody javadocs

Usage examples would be something like this:

Using a JavaScript-library like JQuery, you would post a JSON-Object like this:

{ "firstName" : "Elmer", "lastName" : "Fudd" }

Your controller method would look like this:

// controller
@ResponseBody @RequestMapping("/description")
public Description getDescription(@RequestBody UserStats stats){
    return new Description(stats.getFirstName() + " " + stats.getLastname() + " hates wacky wabbits");
}

// domain / value objects
public class UserStats{
    private String firstName;
    private String lastName;
    // + getters, setters
}
public class Description{
    private String description;
    // + getters, setters, constructor
}

Now if you have Jackson on your classpath (and have an <mvc:annotation-driven> setup), Spring would convert the incoming JSON to a UserStats object from the post body (because you added the @RequestBody annotation) and it would serialize the returned object to JSON (because you added the @ResponseBody annotation). So the Browser / Client would see this JSON result:

{ "description" : "Elmer Fudd hates wacky wabbits" }

See this previous answer of mine for a complete working example: https://stackoverflow.com/a/5908632/342852

Note: RequestBody / ResponseBody is of course not limited to JSON, both can handle multiple formats, including plain text and XML, but JSON is probably the most used format.


Update

Ever since Spring 4.x, you usually won't use @ResponseBody on method level, but rather @RestController on class level, with the same effect.

Here is a quote from the official Spring MVC documentation:

@RestController is a composed annotation that is itself meta-annotated with @Controller and @ResponseBody to indicate a controller whose every method inherits the type-level @ResponseBody annotation and, therefore, writes directly to the response body versus view resolution and rendering with an HTML template.

Selecting multiple columns in a Pandas dataframe

You can use Pandas.

I create the DataFrame:

import pandas as pd
df = pd.DataFrame([[1, 2,5], [5,4, 5], [7,7, 8], [7,6,9]],
                  index=['Jane', 'Peter','Alex','Ann'],
                  columns=['Test_1', 'Test_2', 'Test_3'])

The DataFrame:

       Test_1  Test_2  Test_3
Jane        1       2       5
Peter       5       4       5
Alex        7       7       8
Ann         7       6       9

To select one or more columns by name:

df[['Test_1', 'Test_3']]

       Test_1  Test_3
Jane        1       5
Peter       5       5
Alex        7       8
Ann         7       9

You can also use:

df.Test_2

And you get column Test_2:

Jane     2
Peter    4
Alex     7
Ann      6

You can also select columns and rows from these rows using .loc(). This is called "slicing". Notice that I take from column Test_1 to Test_3:

df.loc[:, 'Test_1':'Test_3']

The "Slice" is:

       Test_1  Test_2  Test_3
Jane        1       2       5
Peter       5       4       5
Alex        7       7       8
Ann         7       6       9

And if you just want Peter and Ann from columns Test_1 and Test_3:

df.loc[['Peter', 'Ann'], ['Test_1', 'Test_3']]

You get:

       Test_1  Test_3
Peter       5       5
Ann         7       9

Comparison of Android Web Service and Networking libraries: OKHTTP, Retrofit and Volley

Retrofit 1.9.0 vs. RoboSpice

I am using both in my app.

Robospice works faster than Retrofit whenever I parse the nested JSON class. Because Spice Manger will do everything for you. In Retrofit you need to create GsonConverter and deserialize it.

I created two fragments in the same activity and called the same time with two same kind of URLs.

09-23 20:12:32.830  16002-16002/com.urbanpro.seeker E/RETROFIT?   RestAdapter Init
09-23 20:12:32.833  16002-16002/com.urbanpro.seeker E/RETROFIT? calling the method
09-23 20:12:32.837  16002-16002/com.urbanpro.seeker E/ROBOSPICE? initialzig spice manager
09-23 20:12:32.860  16002-16002/com.urbanpro.seeker E/ROBOSPICE? Executing the method
09-23 20:12:33.537  16002-16002/com.urbanpro.seeker E/ROBOSPICE? on SUcceess
09-23 20:12:33.553  16002-16002/com.urbanpro.seeker E/ROBOSPICE? gettting the all contents
09-23 20:12:33.601  16002-21819/com.urbanpro.seeker E/RETROFIT? deseriazation starts
09-23 20:12:33.603  16002-21819/com.urbanpro.seeker E/RETROFIT? deseriazation ends

How do I include a newline character in a string in Delphi?

Here's an even shorter approach:

my_string := 'Hello,'#13#10' world!';

Use string in switch case in java

Learn to use else.

Since value will never be equal to two unequal strings at once, there are only 5 possible outcomes -- one for each value you care about, plus one for "none of the above". But because your code doesn't eliminate the tests that can't pass, it has 16 "possible" paths (2 ^ the number of tests), of which most will never be followed.

With else, the only paths that exist are the 5 that can actually happen.

String value = some methodx;
if ("apple".equals(value )) {
    method1;
}
else if ("carrot".equals(value )) {
    method2;
}
else if ("mango".equals(value )) {
    method3;
}
else if ("orance".equals(value )) {
    method4;
}

Or start using JDK 7, which includes the ability to use strings in a switch statement. Course, Java will just compile the switch into an if/else like construct anyway...

How to store standard error in a variable

In zsh:

{ . ./useless.sh > /dev/tty } 2>&1 | read ERROR
$ echo $ERROR
( your message )

Subprocess check_output returned non-zero exit status 1

The command yum that you launch was executed properly. It returns a non zero status which means that an error occured during the processing of the command. You probably want to add some argument to your yum command to fix that.

Your code could show this error this way:

import subprocess
try:
    subprocess.check_output("dir /f",shell=True,stderr=subprocess.STDOUT)
except subprocess.CalledProcessError as e:
    raise RuntimeError("command '{}' return with error (code {}): {}".format(e.cmd, e.returncode, e.output))

Using success/error/finally/catch with Promises in AngularJS

Forget about using success and error method.

Both methods have been deprecated in angular 1.4. Basically, the reason behind the deprecation is that they are not chainable-friendly, so to speak.

With the following example, I'll try to demonstrate what I mean about success and error being not chainable-friendly. Suppose we call an API that returns a user object with an address:

User object:

{name: 'Igor', address: 'San Francisco'}

Call to the API:

$http.get('/user')
    .success(function (user) {
        return user.address;   <---  
    })                            |  // you might expect that 'obj' is equal to the
    .then(function (obj) {   ------  // address of the user, but it is NOT

        console.log(obj); // -> {name: 'Igor', address: 'San Francisco'}
    });
};

What happened?

Because success and error return the original promise, i.e. the one returned by $http.get, the object passed to the callback of the then is the whole user object, that is to say the same input to the preceding success callback.

If we had chained two then, this would have been less confusing:

$http.get('/user')
    .then(function (user) {
        return user.address;  
    })
    .then(function (obj) {  
        console.log(obj); // -> 'San Francisco'
    });
};

Java Class that implements Map and keeps insertion order?

I don't know if it is opensource, but after a little googling, I found this implementation of Map using ArrayList. It seems to be pre-1.5 Java, so you might want to genericize it, which should be easy. Note that this implementation has O(N) access, but this shouldn't be a problem if you don't add hundreds of widgets to your JPanel, which you shouldn't anyway.

How to convert the system date format to dd/mm/yy in SQL Server 2008 R2?

   SELECT CONVERT(varchar(11),getdate(),101)  -- mm/dd/yyyy

   SELECT CONVERT(varchar(11),getdate(),103)  -- dd/mm/yyyy

Check this . I am assuming D30.SPGD30_TRACKED_ADJUSTMENT_X is of datetime datatype .
That is why i am using CAST() function to make it as an character expression because CHARINDEX() works on character expression.
Also I think there is no need of OR condition.

select case when CHARINDEX('-',cast(D30.SPGD30_TRACKED_ADJUSTMENT_X as varchar )) > 0 

then 'Score Calculation - '+CONVERT(VARCHAR(11), D30.SPGD30_TRACKED_ADJUSTMENT_X, 103)
end

EDIT:

select case when CHARINDEX('-',D30.SPGD30_TRACKED_ADJUSTMENT_X) > 0 
then 'Score Calculation - '+
CONVERT( VARCHAR(11), CAST(D30.SPGD30_TRACKED_ADJUSTMENT_X as DATETIME) , 103)
end

See this link for conversion to other date formats: https://www.w3schools.com/sql/func_sqlserver_convert.asp

SQL Error: ORA-00936: missing expression

You didn't use FROM expression for a table

SELECT DISTINCT Description, Date as treatmentDate
**FROM <A TABLE>**
WHERE doothey.Patient P, doothey.Account A, doothey.AccountLine AL, doothey.Item.I
AND P.PatientID = A.PatientID
AND A.AccountNo = AL.AccountNo
AND AL.ItemNo = I.ItemNo
AND (p.FamilyName = 'Stange' AND p.GivenName = 'Jessie');

Get everything after and before certain character in SQL Server

Below query gives you data before '-' Ex- W12345A-4S

SELECT SUBSTRING(Column_Name,0, CHARINDEX('-',Column_Name))  as 'new_name'
from [abc].

Output - W12345A

How to make a checkbox checked with jQuery?

$('#test').prop('checked', true);

Note only in jQuery 1.6+

Automatically add all files in a folder to a target using CMake?

The answer by Kleist certainly works, but there is an important caveat:

When you write a Makefile manually, you might generate a SRCS variable using a function to select all .cpp and .h files. If a source file is later added, re-running make will include it.

However, CMake (with a command like file(GLOB ...)) will explicitly generate a file list and place it in the auto-generated Makefile. If you have a new source file, you will need to re-generate the Makefile by re-running cmake.

edit: No need to remove the Makefile.

jQuery get specific option tag text

You can get selected option text by using function .text();

you can call the function like this :

jQuery("select option:selected").text();

Detect whether there is an Internet connection available on Android

The getActiveNetworkInfo() method of ConnectivityManager returns a NetworkInfo instance representing the first connected network interface it can find or null if none if the interfaces are connected. Checking if this method returns null should be enough to tell if an internet connection is available.

private boolean isNetworkAvailable() {
     ConnectivityManager connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
     NetworkInfo activeNetworkInfo = connectivityManager.getActiveNetworkInfo();
     return activeNetworkInfo != null; 
}

You will also need:

in your android manifest.

Edit:

Note that having an active network interface doesn't guarantee that a particular networked service is available. Networks issues, server downtime, low signal, captive portals, content filters and the like can all prevent your app from reaching a server. For instance you can't tell for sure if your app can reach Twitter until you receive a valid response from the Twitter service.

getActiveNetworkInfo() shouldn't never give null. I don't know what they were thinking when they came up with that. It should give you an object always.

Scala: write string to file in one statement

os-lib is the best modern way to write to a file, as mentioned here.

Here's how to write "hello" to the file.txt file.

os.write(os.pwd/"file.txt", "hello")

os-lib hides the Java ugliness and complexity (it uses the Java libs under the hood, so it's just as performant). See here for more info about using the lib.

How to target the href to div

if you use

angularjs

you have just to write the right css in order to frame you div html code

<div 
style="height:51px;width:111px;margin-left:203px;" 
ng-click="nextDetail()">
</div>


JS Code(in your controller):

$scope.nextDetail = function()
{
....
}

What is the difference between Numpy's array() and asarray() functions?

The difference can be demonstrated by this example:

  1. generate a matrix

    >>> A = numpy.matrix(numpy.ones((3,3)))
    >>> A
    matrix([[ 1.,  1.,  1.],
            [ 1.,  1.,  1.],
            [ 1.,  1.,  1.]])
    
  2. use numpy.array to modify A. Doesn't work because you are modifying a copy

    >>> numpy.array(A)[2]=2
    >>> A
    matrix([[ 1.,  1.,  1.],
            [ 1.,  1.,  1.],
            [ 1.,  1.,  1.]])
    
  3. use numpy.asarray to modify A. It worked because you are modifying A itself

    >>> numpy.asarray(A)[2]=2
    >>> A
    matrix([[ 1.,  1.,  1.],
            [ 1.,  1.,  1.],
            [ 2.,  2.,  2.]])
    

Hope this helps!

How to redirect Valgrind's output to a file?

By default, Valgrind writes its output to stderr. So you need to do something like:

valgrind a.out > log.txt 2>&1

Alternatively, you can tell Valgrind to write somewhere else; see http://valgrind.org/docs/manual/manual-core.html#manual-core.comment (but I've never tried this).

Eliminating NAs from a ggplot

Just an update to the answer of @rafa.pereira. Since ggplot2 is part of tidyverse, it makes sense to use the convenient tidyverse functions to get rid of NAs.

library(tidyverse)
airquality %>% 
        drop_na(Ozone) %>%
        ggplot(aes(x = Ozone))+
        geom_bar(stat="bin")

Note that you can also use drop_na() without columns specification; then all the rows with NAs in any column will be removed.

How do I hide the status bar in a Swift iOS app?

Update for iOS 10 / Swift 3.0

No longer a function, now a property...

override var prefersStatusBarHidden: Bool {
    return true
}

Declaration of Methods should be Compatible with Parent Methods in PHP

if you wanna keep OOP form without turning any error off, you can also:

class A
{
    public function foo() {
        ;
    }
}
class B extends A
{
    /*instead of : 
    public function foo($a, $b, $c) {*/
    public function foo() {
        list($a, $b, $c) = func_get_args();
        // ...

    }
}

VBA EXCEL Multiple Nested FOR Loops that Set two variable for expression

I can't get to your google docs file at the moment but there are some issues with your code that I will try to address while answering

Sub stituterangersNEW()
Dim t As Range
Dim x As Range
Dim dify As Boolean
Dim difx As Boolean
Dim time2 As Date
Dim time1 As Date

    'You said time1 doesn't change, so I left it in a singe cell.
    'If that is not correct, you will have to play with this some more.
    time1 = Range("A6").Value

    'Looping through each of our output cells.
    For Each t In Range("B7:E9") 'Change these to match your real ranges.

        'Looping through each departure date/time.
        '(Only one row in your example. This can be adjusted if needed.)
        For Each x In Range("B2:E2") 'Change these to match your real ranges.
            'Check to see if our dep time corresponds to
            'the matching column in our output
            If t.Column = x.Column Then
                'If it does, then check to see what our time value is
                If x > 0 Then
                    time2 = x.Value
                    'Apply the change to the output cell.
                    t.Value = time1 - time2
                    'Exit out of this loop and move to the next output cell.
                    Exit For
                End If
            End If
            'If the columns don't match, or the x value is not a time
            'then we'll move to the next dep time (x)
        Next x
    Next t

End Sub

EDIT

I changed you worksheet to play with (see above for the new Sub). This probably does not suite your needs directly, but hopefully it will demonstrate the conept behind what I think you want to do. Please keep in mind that this code does not follow all the coding best preactices I would recommend (e.g. validating the time is actually a TIME and not some random other data type).

     A                      B                   C                   D                  E
1    LOAD_NUMBER            1                   2                   3                  4
2    DEPARTURE_TIME_DATE    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 19:30    11/12/2011 20:00                
4    Dry_Refrig 7585.1  0   10099.8 16700
6    1/4/2012 19:30

Using the sub I got this output:

    A           B             C             D             E
7   Friday      1272:00:00    1272:00:00    1272:00:00    1271:30:00
8   Saturday    1272:00:00    1272:00:00    1272:00:00    1271:30:00
9   Thursday    1272:00:00    1272:00:00    1272:00:00    1271:30:00

scp copy directory to another server with private key auth

Putty doesn't use openssh key files - there is a utility in putty suite to convert them.

edit: it is called puttygen

Take a char input from the Scanner

You should get the String using scanner.next() and invoke String.charAt(0) method on the returned String.
Exmple :

    import java.util.Scanner;

    public class InputC{


            public static void main(String[] args) {
                // TODO Auto-generated method stub
                   // Declare the object and initialize with
                   // predefined standard input object
                    Scanner scanner = new Scanner(System.in);
                    System.out.println("Enter a character: ");
                    // Character input
                    char c = scanner.next().charAt(0);
                    // Print the read value
                    System.out.println("You have entered: "+c);
            }


        }

output

Enter a character: 
a
You have entered: a

gpg decryption fails with no secret key error

I got the same error when trying to decrypt the key from a different user account via su - <otherUser>. (Like jayhendren suggests in his answer)

In my case, this happened because there would normally start a graphical pinentry prompt so I could enter the password to decrypt the key, but the su -ed to user had no access to the (graphical) X-Window-System that was currently running.

The solution was to simply issue in that same console (as the user under which the X Server was currently running):

xhost +local:

Which gives other local users access to the currently running (local) X-Server. After that, the pinentry prompt appeared, I could enter the password to decrypt the key and it worked...

Of course you can also forward X over ssh connections. For this look into ssh's -X parameter (client side) and X11Forwarding yes (server side).

What are the use cases for selecting CHAR over VARCHAR in SQL?

The general rule is to pick CHAR if all rows will have close to the same length. Pick VARCHAR (or NVARCHAR) when the length varies significantly. CHAR may also be a bit faster because all the rows are of the same length.

It varies by DB implementation, but generally, VARCHAR (or NVARCHAR) uses one or two more bytes of storage (for length or termination) in addition to the actual data. So (assuming you are using a one-byte character set) storing the word "FooBar"

  • CHAR(6) = 6 bytes (no overhead)
  • VARCHAR(100) = 8 bytes (2 bytes of overhead)
  • CHAR(10) = 10 bytes (4 bytes of waste)

The bottom line is CHAR can be faster and more space-efficient for data of relatively the same length (within two characters length difference).

Note: Microsoft SQL has 2 bytes of overhead for a VARCHAR. This may vary from DB to DB, but generally, there is at least 1 byte of overhead needed to indicate length or EOL on a VARCHAR.

As was pointed out by Gaven in the comments: Things change when it comes to multi-byte characters sets, and is a is case where VARCHAR becomes a much better choice.

A note about the declared length of the VARCHAR: Because it stores the length of the actual content, then you don't waste unused length. So storing 6 characters in VARCHAR(6), VARCHAR(100), or VARCHAR(MAX) uses the same amount of storage. Read more about the differences when using VARCHAR(MAX). You declare a maximum size in VARCHAR to limit how much is stored.

In the comments AlwaysLearning pointed out that the Microsoft Transact-SQL docs seem to say the opposite. I would suggest that is an error or at least the docs are unclear.

Android Webview - Completely Clear the Cache

context.deleteDatabase("webview.db");
context.deleteDatabase("webviewCache.db")

Did the trick

Count number of 1's in binary representation

There's only one way I can think of to accomplish this task in O(1)... that is to 'cheat' and use a physical device (with linear or even parallel programming I think the limit is O(log(k)) where k represents the number of bytes of the number).

However you could very easily imagine a physical device that connects each bit an to output line with a 0/1 voltage. Then you could just electronically read of the total voltage on a 'summation' line in O(1). It would be quite easy to make this basic idea more elegant with some basic circuit elements to produce the output in whatever form you want (e.g. a binary encoded output), but the essential idea is the same and the electronic circuit would produce the correct output state in fixed time.

I imagine there are also possible quantum computing possibilities, but if we're allowed to do that, I would think a simple electronic circuit is the easier solution.

Is SMTP based on TCP or UDP?

In theory SMTP can be handled by either TCP, UDP, or some 3rd party protocol.

As defined in RFC 821, RFC 2821, and RFC 5321:

SMTP is independent of the particular transmission subsystem and requires only a reliable ordered data stream channel.

In addition, the Internet Assigned Numbers Authority has allocated port 25 for both TCP and UDP for use by SMTP.

In practice however, most if not all organizations and applications only choose to implement the TCP protocol. For example, in Microsoft's port listing port 25 is only listed for TCP and not UDP.


The big difference between TCP and UDP that makes TCP ideal here is that TCP checks to make sure that every packet is received and re-sends them if they are not whereas UDP will simply send packets and not check for receipt. This makes UDP ideal for things like streaming video where every single packet isn't as important as keeping a continuous flow of packets from the server to the client.

Considering SMTP, it makes more sense to use TCP over UDP. SMTP is a mail transport protocol, and in mail every single packet is important. If you lose several packets in the middle of the message the recipient might not even receive the message and if they do they might be missing key information. This makes TCP more appropriate because it ensures that every packet is delivered.

Matplotlib - global legend and title aside subplots

suptitle seems the way to go, but for what it's worth, the figure has a transFigure property that you can use:

fig=figure(1)
text(0.5, 0.95, 'test', transform=fig.transFigure, horizontalalignment='center')

How to create a connection string in asp.net c#

Demo :

<connectionStrings>
<add name="myConnectionString" connectionString="server=localhost;database=myDb;uid=myUser;password=myPass;" />
</connectionStrings>

Based on your question:

<connectionStrings>
    <add name="itmall" connectionString="Data Source=.\SQLEXPRESS;AttachDbFilename=D:\19-02\ABCC\App_Data\abcc.mdf;Integrated Security=True;User Instance=True" />
    </connectionStrings>

Refer links:

http://www.connectionstrings.com/store-connection-string-in-webconfig/

Retrive connection string from web.config file:

write the below code in your file where you want;

string connstring=ConfigurationManager.ConnectionStrings["itmall"].ConnectionString;

SqlConnection con = new SqlConnection(connstring);

or you can go in your way like

SqlConnection con = new SqlConnection(ConfigurationManager.ConnectionStrings["itmall"].ConnectionString);

Note:

The "name" which you gave in web.config file and name which you used in connection string must be same(like "itmall" in this solution.)

Powershell Invoke-WebRequest Fails with SSL/TLS Secure Channel

If, like me, none of the above quite works, it might be worth also specifically trying a lower TLS version alone. I had tried both of the following, but didn't seem to solve my problem:

[Net.ServicePointManager]::SecurityProtocol = "tls12, tls11, tls"
[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls12 -bor [Net.SecurityProtocolType]::Tls11 -bor [Net.SecurityProtocolType]::Tls

In the end, it was only when I targetted TLS 1.0 (specifically remove 1.1 and 1.2 in the code) that it worked:

[Net.ServicePointManager]::SecurityProtocol = [Net.SecurityProtocolType]::Tls

The local server (that this was being attempted on) is fine with TLS 1.2, although the remote server (which was previously "confirmed" as fine for TLS 1.2 by a 3rd party) seems not to be.

Hope this helps someone.

Show tables, describe tables equivalent in redshift

You can use - desc / to see the view/table definition in Redshift. I have been using Workbench/J as a SQL client for Redshift and it gives the definition in the Messages tab adjacent to Result tab.

Is a DIV inside a TD a bad idea?

I have faced the problem by placing a <div> inside <td>.

I was unable to identify the div using document.getElementById() if i place that inside td. But outside, it was working fine.

Regex - how to match everything except a particular pattern

If you want to match a word A in a string and not to match a word B. For example: If you have a text:

1. I have a two pets - dog and a cat
2. I have a pet - dog

If you want to search for lines of text that HAVE a dog for a pet and DOESN'T have cat you can use this regular expression:

^(?=.*?\bdog\b)((?!cat).)*$

It will find only second line:

2. I have a pet - dog

Replace HTML Table with Divs

Please be aware that although tables are discouraged as a primary means of page layout, they still have their place. Tables can and should be used when and where appropriate and until some of the more popular browsers (ahem, IE, ahem) become more standards compliant, tables are sometimes the best route to a solution.

HTTP client timeout and server timeout

According to https://bugzilla.mozilla.org/show_bug.cgi?id=592284, the pref network.http.connection-retry-timeout controls the amount of time in ms (Milliseconds !) to wait for success on the initial connection before beginning the second one. Setting it to 0 disables the parallel connection.

Check if option is selected with jQuery, if not select a default

$("#select_box_id").children()[1].selected

This is another way of checking an option is selected or not in jquery. This will return Boolean (True or False).

[1] is index of select box option

Query error with ambiguous column name in SQL

This happens because there are fields with the same name in more than one table, in the query, because of the joins, so you should reference the fields differently, giving names (aliases) to the tables.

How to stop (and restart) the Rails Server?

I had to restart the rails application on the production so I looked for an another answer. I have found it below:

http://wiki.ocssolutions.com/Restarting_a_Rails_Application_Using_Passenger

Retrieving the COM class factory for component with CLSID {XXXX} failed due to the following error: 80040154

It sounds like your service was built against 'Any CPU', causing you errors on 64-bit where you are using COM components. You need to build it for x86.

The website is probably running as a 32-bit process which is why it can use the component. Building your solution against x86 will force your service to run as 32-bit.

Regex to match words of a certain length

^\w{0,10}$ # allows words of up to 10 characters.
^\w{5,}$   # allows words of more than 4 characters.
^\w{5,10}$ # allows words of between 5 and 10 characters.

How do I get the name of a Ruby class?

You want to call .name on the object's class:

result.class.name

How to use background thread in swift?

Since the OP question has already been answered above I just want to add some speed considerations:

I don't recommend running tasks with the .background thread priority especially on the iPhone X where the task seems to be allocated on the low power cores.

Here is some real data from a computationally intensive function that reads from an XML file (with buffering) and performs data interpolation:

Device name / .background / .utility / .default / .userInitiated / .userInteractive

  1. iPhone X: 18.7s / 6.3s / 1.8s / 1.8s / 1.8s
  2. iPhone 7: 4.6s / 3.1s / 3.0s / 2.8s / 2.6s
  3. iPhone 5s: 7.3s / 6.1s / 4.0s / 4.0s / 3.8s

Note that the data set is not the same for all devices. It's the biggest on the iPhone X and the smallest on the iPhone 5s.

Can we update primary key values of a table?

It is commonly agreed that primary keys should be immutable (or as stable as possible since immutability can not be enforced in the DB). While there is nothing that will prevent you from updating a primary key (except integrity constraint), it may not be a good idea:

From a performance point of view:

  • You will need to update all foreign keys that reference the updated key. A single update can lead to the update of potentially lots of tables/rows.
  • If the foreign keys are unindexed (!!) you will have to maintain a lock on the children table to ensure integrity. Oracle will only hold the lock for a short time but still, this is scary.
  • If your foreign keys are indexed (as they should be), the update will lead to the update of the index (delete+insert in the index structure), this is generally more expensive than the actual update of the base table.
  • In ORGANIZATION INDEX tables (in other RDBMS, see clustered primary key), the rows are physically sorted by the primary key. A logical update will result in a physical delete+insert (more expensive)

Other considerations:

  • If this key is referenced in any external system (application cache, another DB, export...), the reference will be broken upon update.
  • additionaly, some RDBMS don't support CASCADE UPDATE, in particular Oracle.

In conclusion, during design, it is generally safer to use a surrogate key in lieu of a natural primary key that is supposed not to change -- but may eventually need to be updated because of changed requirements or even data entry error.

If you absolutely have to update a primary key with children table, see this post by Tom Kyte for a solution.

How to compare 2 files fast using .NET?

The only thing that might make a checksum comparison slightly faster than a byte-by-byte comparison is the fact that you are reading one file at a time, somewhat reducing the seek time for the disk head. That slight gain may however very well be eaten up by the added time of calculating the hash.

Also, a checksum comparison of course only has any chance of being faster if the files are identical. If they are not, a byte-by-byte comparison would end at the first difference, making it a lot faster.

You should also consider that a hash code comparison only tells you that it's very likely that the files are identical. To be 100% certain you need to do a byte-by-byte comparison.

If the hash code for example is 32 bits, you are about 99.99999998% certain that the files are identical if the hash codes match. That is close to 100%, but if you truly need 100% certainty, that's not it.

Tomcat starts but home page cannot open with url http://localhost:8080

The problems may happen because of memory issue. java.lang.OutOfMemoryError: Java heap space

please verify the logfile, any issues related to hardware(memory).

How to extract a substring using regex

Assuming you want the part between single quotes, use this regular expression with a Matcher:

"'(.*?)'"

Example:

String mydata = "some string with 'the data i want' inside";
Pattern pattern = Pattern.compile("'(.*?)'");
Matcher matcher = pattern.matcher(mydata);
if (matcher.find())
{
    System.out.println(matcher.group(1));
}

Result:

the data i want

Handling very large numbers in Python

python supports arbitrarily large integers naturally:

example:

>>> 10**1000
10000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000000

You could even get, for example of a huge integer value, fib(4000000).

But still it does not (for now) supports an arbitrarily large float !!

If you need one big, large, float then check up on the decimal Module. There are examples of use on these foruns: OverflowError: (34, 'Result too large')

Another reference: http://docs.python.org/2/library/decimal.html

You can even using the gmpy module if you need a speed-up (which is likely to be of your interest): Handling big numbers in code

Another reference: https://code.google.com/p/gmpy/

OnChange event handler for radio button (INPUT type="radio") doesn't work as one value

Store the previous checked radio in a variable:
http://jsfiddle.net/dsbonev/C5S4B/

HTML

<input type="radio" name="myRadios" value="1" /> 1
<input type="radio" name="myRadios" value="2" /> 2
<input type="radio" name="myRadios" value="3" /> 3
<input type="radio" name="myRadios" value="4" /> 4
<input type="radio" name="myRadios" value="5" /> 5

JS

var changeHandler = (function initChangeHandler() {
    var previousCheckedRadio = null;

    var result = function (event) {
        var currentCheckedRadio = event.target;
        var name = currentCheckedRadio.name;

        if (name !== 'myRadios') return;

        //using radio elements previousCheckedRadio and currentCheckedRadio

        //storing radio element for using in future 'change' event handler
        previousCheckedRadio = currentCheckedRadio;
    };

    return result;
})();

document.addEventListener('change', changeHandler, false);

JS EXAMPLE CODE

var changeHandler = (function initChangeHandler() {
    var previousCheckedRadio = null;

    function logInfo(info) {
        if (!console || !console.log) return;

        console.log(info);
    }

    function logPrevious(element) {
        if (!element) return;

        var message = element.value + ' was unchecked';

        logInfo(message);
    }

    function logCurrent(element) {
        if (!element) return;

        var message = element.value + ' is checked';

        logInfo(message);
    }

    var result = function (event) {
        var currentCheckedRadio = event.target;
        var name = currentCheckedRadio.name;

        if (name !== 'myRadios') return;

        logPrevious(previousCheckedRadio);
        logCurrent(currentCheckedRadio);

        previousCheckedRadio = currentCheckedRadio;
    };

    return result;
})();

document.addEventListener('change', changeHandler, false);

Best way to test for a variable's existence in PHP; isset() is clearly broken

I think the only full solution is to report notices with

error_reporting(E_ALL); // Enables E_NOTICE

But you will have to fix all the notices generated by undefined variables, constants, array keys, class properties amongst others. Once you have done that you won't have to worry about the difference between null and not declared variables, and the ambiguity dissappears.

Enabling notice reporting might not be a good alternative in all situations, but there are good reasons to enable it:

Why should I fix E_NOTICE errors?

In my case was more than a year working in a proyect without it, but was used to be careful about declaring variables, so it was fast to transition.

Generic deep diff between two objects

I took the answer above by @sbgoran and modified it for my case same as the question needed, to treat arrays as sets (i.e. order is not important for diff)

const deepDiffMapper = function () {
return {
  VALUE_CREATED: "created",
  VALUE_UPDATED: "updated",
  VALUE_DELETED: "deleted",
  VALUE_UNCHANGED: "unchanged",
  map: function(obj1: any, obj2: any) {
    if (this.isFunction(obj1) || this.isFunction(obj2)) {
      throw "Invalid argument. Function given, object expected.";
    }
    if (this.isValue(obj1) || this.isValue(obj2)) {
      return {
        type: this.compareValues(obj1, obj2),
        data: obj2 === undefined ? obj1 : obj2
      };
    }

    if (this.isArray(obj1) || this.isArray(obj2)) {
      return {
        type: this.compareArrays(obj1, obj2),
        data: this.getArrayDiffData(obj1, obj2)
      };
    }

    const diff: any = {};
    for (const key in obj1) {

      if (this.isFunction(obj1[key])) {
        continue;
      }

      let value2 = undefined;
      if (obj2[key] !== undefined) {
        value2 = obj2[key];
      }

      diff[key] = this.map(obj1[key], value2);
    }
    for (const key in obj2) {
      if (this.isFunction(obj2[key]) || diff[key] !== undefined) {
        continue;
      }

      diff[key] = this.map(undefined, obj2[key]);
    }

    return diff;

  },

  getArrayDiffData: function(arr1: Array<any>, arr2: Array<any>) {
    const set1 = new Set(arr1);
    const set2 = new Set(arr2);

    if (arr1 === undefined || arr2 === undefined) {
       return arr1 === undefined ? arr1 : arr2;
    }
    const deleted = [...arr1].filter(x => !set2.has(x));

    const added = [...arr2].filter(x => !set1.has(x));

    return {
      added, deleted
    };

  },

  compareArrays: function(arr1: Array<any>, arr2: Array<any>) {
    const set1 = new Set(arr1);
    const set2 = new Set(arr2);
    if (_.isEqual(_.sortBy(arr1), _.sortBy(arr2))) {
      return this.VALUE_UNCHANGED;
    }
    if (arr1 === undefined) {
      return this.VALUE_CREATED;
    }
    if (arr2 === undefined) {
      return this.VALUE_DELETED;
    }
    return this.VALUE_UPDATED;
  },
  compareValues: function (value1: any, value2: any) {
    if (value1 === value2) {
      return this.VALUE_UNCHANGED;
    }
    if (this.isDate(value1) && this.isDate(value2) && value1.getTime() === value2.getTime()) {
      return this.VALUE_UNCHANGED;
    }
    if (value1 === undefined) {
      return this.VALUE_CREATED;
    }
    if (value2 === undefined) {
      return this.VALUE_DELETED;
    }
    return this.VALUE_UPDATED;
  },
  isFunction: function (x: any) {
    return Object.prototype.toString.call(x) === "[object Function]";
  },
  isArray: function (x: any) {
    return Object.prototype.toString.call(x) === "[object Array]";
  },
  isDate: function (x: any) {
    return Object.prototype.toString.call(x) === "[object Date]";
  },
  isObject: function (x: any) {
    return Object.prototype.toString.call(x) === "[object Object]";
  },
  isValue: function (x: any) {
    return !this.isObject(x) && !this.isArray(x);
  }
 };
}();

How can I make directory writable?

chmod 777 <directory>

this not change all ,just one file

chmod -R a+w <directory>

this ok

Programmatically obtain the phone number of the Android phone

Sometimes, below code returns null or blank string.

TelephonyManager tMgr = (TelephonyManager)mAppContext.getSystemService(Context.TELEPHONY_SERVICE);
String mPhoneNumber = tMgr.getLine1Number();

With below permission

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

There is another way you will be able to get your phone number, I haven't tested this on multiple devices but above code is not working every time.

Try below code:

String main_data[] = {"data1", "is_primary", "data3", "data2", "data1", "is_primary", "photo_uri", "mimetype"};
Object object = getContentResolver().query(Uri.withAppendedPath(android.provider.ContactsContract.Profile.CONTENT_URI, "data"),
        main_data, "mimetype=?",
        new String[]{"vnd.android.cursor.item/phone_v2"},
        "is_primary DESC");
if (object != null) {
    do {
        if (!((Cursor) (object)).moveToNext())
            break;
        // This is the phoneNumber
        String s1 = ((Cursor) (object)).getString(4);
    } while (true);
    ((Cursor) (object)).close();
}

You will need to add these two permissions.

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

Hope this helps, Thanks!

javascript convert int to float

JavaScript only has a Number type that stores floating point values.

There is no int.

Edit:

If you want to format the number as a string with two digits after the decimal point use:

(4).toFixed(2)

SQL grouping by month and year

If you want to stay having the field in datetime datatype, try using this:

SELECT DATEADD(MONTH, DATEDIFF(MONTH, 0, o.[date]), 0) AS Mjesec, SUM(marketingExpense) AS SumaMarketing, SUM(revenue) AS SumaZarada 
FROM [Order] o
WHERE (idCustomer = 1) AND (o.[date] BETWEEN '2001-11-3' AND '2011-11-3')
GROUP BY DATEADD(MONTH, DATEDIFF(MONTH, 0, o.[date]), 0)

It it also easy to change to group by hours, days, weeks, years...
I hope it is of use to someone,

Regards!

Byte[] to InputStream or OutputStream

output = new ByteArrayOutputStream();
...
input = new ByteArrayInputStream( output.toByteArray() )

How to compile for Windows on Linux with gcc/g++?

From: https://fedoraproject.org/wiki/MinGW/Tutorial

As of Fedora 17 it is possible to easily build (cross-compile) binaries for the win32 and win64 targets. This is realized using the mingw-w64 toolchain: http://mingw-w64.sf.net/. Using this toolchain allows you to build binaries for the following programming languages: C, C++, Objective-C, Objective-C++ and Fortran.

"Tips and tricks for using the Windows cross-compiler": https://fedoraproject.org/wiki/MinGW/Tips

java.lang.RuntimeException: Failure delivering result ResultInfo{who=null, request=1888, result=0, data=null} to activity

I had this error message show up for me because I was using the network on the main thread and new versions of Android have a "strict" policy to prevent that. To get around it just throw whatever network connection call into an AsyncTask.

Example:

    AsyncTask<CognitoCachingCredentialsProvider, Integer, Void> task = new AsyncTask<CognitoCachingCredentialsProvider, Integer, Void>() {

        @Override
        protected Void doInBackground(CognitoCachingCredentialsProvider... params) {
            AWSSessionCredentials creds = credentialsProvider.getCredentials();
            String id = credentialsProvider.getCachedIdentityId();
            credentialsProvider.refresh();
            Log.d("wooohoo", String.format("id=%s, token=%s", id, creds.getSessionToken()));
            return null;
        }
    };

    task.execute(credentialsProvider);

How to get the squared symbol (²) to display in a string

No need to get too complicated. If all you need is ² then use the unicode representation.

http://en.wikipedia.org/wiki/Unicode_subscripts_and_superscripts

(which is how I assume you got the ² to appear in your question. )

Prevent users from submitting a form by hitting Enter

Not putting a submit button could do. Just put a script to the input (type=button) or add eventListener if you want it to submit the data in the form.

Rather use this

<input type="button">

than using this

<input type="submit">

How to check if a column exists in Pandas

This will work:

if 'A' in df:

But for clarity, I'd probably write it as:

if 'A' in df.columns:

How to increase the max connections in postgres?

Adding to Winnie's great answer,

If anyone is not able to find the postgresql.conf file location in your setup, you can always ask the postgres itself.

SHOW config_file;

For me changing the max_connections alone made the trick.

Create session factory in Hibernate 4

The method buildSessionFactory is deprecated from the Hibernate 4 release and it is replaced with the new API. If you are using the Hibernate 4.3.0 and above, your code has to be:

Configuration configuration = new Configuration().configure();

StandardServiceRegistryBuilder builder = new StandardServiceRegistryBuilder()
        .applySettings(configuration.getProperties());

SessionFactory factory = configuration.buildSessionFactory(builder.build());

python date of the previous month

datetime and the datetime.timedelta classes are your friend.

  1. find today.
  2. use that to find the first day of this month.
  3. use timedelta to backup a single day, to the last day of the previous month.
  4. print the YYYYMM string you're looking for.

Like this:

 import datetime
 today = datetime.date.today()
 first = today.replace(day=1)
 lastMonth = first - datetime.timedelta(days=1)
 print(lastMonth.strftime("%Y%m"))

201202 is printed.

Disable vertical sync for glxgears

For intel drivers, there is also this method

Disable Vertical Synchronization (VSYNC)

The intel-driver uses Triple Buffering for vertical synchronization, this allows for full performance and avoids tearing. To turn vertical synchronization off (e.g. for benchmarking) use this .drirc in your home directory:

<device screen="0" driver="dri2">
    <application name="Default">
        <option name="vblank_mode" value="0"/>
    </application>
</device>

How to use the curl command in PowerShell?

Use splatting.

$CurlArgument = '-u', '[email protected]:yyyy',
                '-X', 'POST',
                'https://xxx.bitbucket.org/1.0/repositories/abcd/efg/pull-requests/2229/comments',
                '--data', 'content=success'
$CURLEXE = 'C:\Program Files\Git\mingw64\bin\curl.exe'
& $CURLEXE @CurlArgument

Check if a div does NOT exist with javascript

That works with :

 var element = document.getElementById('myElem');
 if (typeof (element) != undefined && typeof (element) != null && typeof (element) != 'undefined') {
     console.log('element exists');
 }
 else{
     console.log('element NOT exists');
 }

Sorting a vector in descending order

According to my machine, sorting a long long vector of [1..3000000] using the first method takes around 4 seconds, while using the second takes about twice the time. That says something, obviously, but I don't understand why either. Just think this would be helpful.

Same thing reported here.

As said by Xeo, with -O3 they use about the same time to finish.

center aligning a fixed position div

From the post above, I think the best way is

  1. Have a fixed div with width: 100%
  2. Inside the div, make a new static div with margin-left: auto and margin-right: auto, or for table make it align="center".
  3. Tadaaaah, you have centered your fixed div now

Hope this will help.

Spring @Autowired and @Qualifier

You can use @Qualifier along with @Autowired. In fact spring will ask you explicitly select the bean if ambiguous bean type are found, in which case you should provide the qualifier

For Example in following case it is necessary provide a qualifier

@Component
@Qualifier("staff") 
public Staff implements Person {}

@Component
@Qualifier("employee") 
public Manager implements Person {}


@Component
public Payroll {

    private Person person;

    @Autowired
    public Payroll(@Qualifier("employee") Person person){
          this.person = person;
    }

}

EDIT:

In Lombok 1.18.4 it is finally possible to avoid the boilerplate on constructor injection when you have @Qualifier, so now it is possible to do the following:

@Component
@Qualifier("staff") 
public Staff implements Person {}

@Component
@Qualifier("employee") 
public Manager implements Person {}


@Component
@RequiredArgsConstructor
public Payroll {
   @Qualifier("employee") private final Person person;
}

provided you are using the new lombok.config rule copyableAnnotations (by placing the following in lombok.config in the root of your project):

# Copy the Qualifier annotation from the instance variables to the constructor
# see https://github.com/rzwitserloot/lombok/issues/745
lombok.copyableAnnotations += org.springframework.beans.factory.annotation.Qualifier

This was recently introduced in latest lombok 1.18.4.

NOTE

If you are using field or setter injection then you have to place the @Autowired and @Qualifier on top of the field or setter function like below(any one of them will work)

public Payroll {
   @Autowired @Qualifier("employee") private final Person person;
}

or

public Payroll {
   private final Person person;
   @Autowired
   @Qualifier("employee")
   public void setPerson(Person person) {
     this.person = person;
   } 
}

If you are using constructor injection then the annotations should be placed on constructor, else the code would not work. Use it like below -

public Payroll {

    private Person person;

    @Autowired
    public Payroll(@Qualifier("employee") Person person){
          this.person = person;
    }

}

Shell command to tar directory excluding certain files/folders

Check it out

tar cvpzf zip_folder.tgz . --exclude=./public --exclude=./tmp --exclude=./log --exclude=fileName

Is it possible to have a multi-line comments in R?

if(FALSE) {
...
}

precludes multiple lines from being executed. However, these lines still have to be syntactically correct, i.e., can't be comments in the proper sense. Still helpful for some cases though.

How to find out client ID of component for ajax update/render? Cannot find component with expression "foo" referenced from "bar"

Try change update="insTable:display" to update="display". I believe you cannot prefix the id with the form ID like that.

Ruby: character to ascii from a string

The c variable already contains the char code!

"string".each_byte do |c|
    puts c
end

yields

115
116
114
105
110
103

Android fastboot waiting for devices

The shortest answer is first run the fastboot command (in my ubuntu case i.e. ./fastboot-linux oem unlock) (here i'm using ubuntu 12.04 and rooting nexus4) then power on your device in fastboot mode (in nexus 4 by pressing vol-down-key and power button)

The entitlements specified...profile. (0xE8008016). Error iOS 4.2

If you have the certificate for Apple IOS Developer, there is no need to set value for key:"Code Signing Entitlements". Build Settings -> Code Signing Entitlements -> delete any value there.

Split page vertically using CSS

I guess your elements on the page messes up because you don't clear out your floats, check this out

Demo

HTML

<div class="wrap">
    <div class="floatleft"></div>
    <div class="floatright"></div>
    <div style="clear: both;"></div>
</div>

CSS

.wrap {
    width: 100%;
}

.floatleft {
    float:left; 
    width: 80%;
    background-color: #ff0000;
    height: 400px;
}

.floatright {
float: right;
    background-color: #00ff00;
    height: 400px;
    width: 20%;
}

Fill formula down till last row in column

It's a one liner actually. No need to use .Autofill

Range("M3:M" & LastRow).Formula = "=G3&"",""&L3"

Compression/Decompression string with C#

For those who still getting The magic number in GZip header is not correct. Make sure you are passing in a GZip stream. ERROR and if your string was zipped using php you'll need to do something like:

       public static string decodeDecompress(string originalReceivedSrc) {
        byte[] bytes = Convert.FromBase64String(originalReceivedSrc);

        using (var mem = new MemoryStream()) {
            //the trick is here
            mem.Write(new byte[] { 0x1f, 0x8b, 0x08, 0x00, 0x00, 0x00, 0x00, 0x00 }, 0, 8);
            mem.Write(bytes, 0, bytes.Length);

            mem.Position = 0;

            using (var gzip = new GZipStream(mem, CompressionMode.Decompress))
            using (var reader = new StreamReader(gzip)) {
                return reader.ReadToEnd();
                }
            }
        }

Javascript add leading zeroes to date

Another option, using a built-in function to do the padding (but resulting in quite long code!):

myDateString = myDate.getDate().toLocaleString('en-US', {minimumIntegerDigits: 2})
  + '/' + (myDate.getMonth()+1).toLocaleString('en-US', {minimumIntegerDigits: 2})
  + '/' + myDate.getFullYear();

// '12/06/2017'

And another, manipulating strings with regular expressions:

var myDateString = myDate.toISOString().replace(/T.*/, '').replace(/-/g, '/');

// '2017/06/12'

But be aware that one will show the year at the start and the day at the end.

Ruby: Calling class method from instance

Similar your question, you could use:

class Truck
  def default_make
    # Do something
  end

  def initialize
    super
    self.default_make
  end
end

What is a simple command line program or script to backup SQL server databases?

I use ExpressMaint.

To backup all user databases I do for example:

C:\>ExpressMaint.exe -S (local)\sqlexpress -D ALL_USER -T DB -BU HOURS -BV 1 -B c:\backupdir\ -DS

Writing image to local server

Cleanest way of saving image locally using request:

const request = require('request');
request('http://link/to/your/image/file.png').pipe(fs.createWriteStream('fileName.png'))

If you need to add authentication token in headers do this:

const request = require('request');
request({
        url: 'http://link/to/your/image/file.png',
        headers: {
            "X-Token-Auth": TOKEN,
        }
    }).pipe(fs.createWriteStream('filename.png'))                    

Using colors with printf

I use this c code for printing coloured shell output. The code is based on this post.

//General Formatting
#define GEN_FORMAT_RESET                "0"
#define GEN_FORMAT_BRIGHT               "1"
#define GEN_FORMAT_DIM                  "2"
#define GEN_FORMAT_UNDERSCORE           "3"
#define GEN_FORMAT_BLINK                "4"
#define GEN_FORMAT_REVERSE              "5"
#define GEN_FORMAT_HIDDEN               "6"

//Foreground Colors
#define FOREGROUND_COL_BLACK            "30"
#define FOREGROUND_COL_RED              "31"
#define FOREGROUND_COL_GREEN            "32"
#define FOREGROUND_COL_YELLOW           "33"
#define FOREGROUND_COL_BLUE             "34"
#define FOREGROUND_COL_MAGENTA          "35"
#define FOREGROUND_COL_CYAN             "36"
#define FOREGROUND_COL_WHITE            "37"

//Background Colors
#define BACKGROUND_COL_BLACK            "40"
#define BACKGROUND_COL_RED              "41"
#define BACKGROUND_COL_GREEN            "42"
#define BACKGROUND_COL_YELLOW           "43"
#define BACKGROUND_COL_BLUE             "44"
#define BACKGROUND_COL_MAGENTA          "45"
#define BACKGROUND_COL_CYAN             "46"
#define BACKGROUND_COL_WHITE            "47"

#define SHELL_COLOR_ESCAPE_SEQ(X) "\x1b["X"m"
#define SHELL_FORMAT_RESET  ANSI_COLOR_ESCAPE_SEQ(GEN_FORMAT_RESET)

int main(int argc, char* argv[])
{
    //The long way
    fputs(SHELL_COLOR_ESCAPE_SEQ(GEN_FORMAT_DIM";"FOREGROUND_COL_YELLOW), stdout);
    fputs("Text in gold\n", stdout);
    fputs(SHELL_FORMAT_RESET, stdout);
    fputs("Text in default color\n", stdout);

    //The short way
    fputs(SHELL_COLOR_ESCAPE_SEQ(GEN_FORMAT_DIM";"FOREGROUND_COL_YELLOW)"Text in gold\n"SHELL_FORMAT_RESET"Text in default color\n", stdout);

    return 0;
}

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

If your package name on Google-services.json file is okay, Go to gradle.properties file. Then change your APPLICATION_ID="com.yourpackage.name"

HorizontalScrollView within ScrollView Touch Handling

This finally became a part of support v4 library, NestedScrollView. So, no longer local hacks is needed for most of cases I'd guess.

Is there a way to remove unused imports and declarations from Angular 2+?

There are already so many good answers on this thread! I am going to post this to help anybody trying to do this automatically! To automatically remove unused imports for the whole project this article was really helpful to me.

In the article the author explains it like this:

Make a stand alone tslint file that has the following in it:

{
  "extends": ["tslint-etc"],
  "rules": {
    "no-unused-declaration": true
  }
}

Then run the following command to fix the imports:

 tslint --config tslint-imports.json --fix --project .

Consider fixing any other errors it throws. (I did)

Then check the project works by building it:

ng build

or

ng build name_of_project --configuration=production 

End: If it builds correctly, you have successfully removed imports automatically!

NOTE: This only removes unnecessary imports. It does not provide the other features that VS Code does when using one of the commands previously mentioned.

Removing duplicates from a String in Java

 String input = "abbcccaabbddeessacccbbddefgaabbccddeeffggadscsda";
    String output ="";

    for (int i= 0; i<input.length();i++) {
        if (!output.contains(input.substring(i, i+1))) 
            output = output+ input.substring(i, i+1);

    }


        System.out.println(output);

jQuery: select an element's class and id at the same time?

You can do:

$("#country.save")...

OR

$("a#country.save")...

OR

$("a.save#country")...

as you prefer.

So yes you can specify a selector that has to match ID and class (and potentially tag name and anything else you want to throw in).

How to change the datetime format in pandas

You can use dt.strftime if you need to convert datetime to other formats (but note that then dtype of column will be object (string)):

import pandas as pd

df = pd.DataFrame({'DOB': {0: '26/1/2016', 1: '26/1/2016'}})
print (df)
         DOB
0  26/1/2016 
1  26/1/2016

df['DOB'] = pd.to_datetime(df.DOB)
print (df)
         DOB
0 2016-01-26
1 2016-01-26

df['DOB1'] = df['DOB'].dt.strftime('%m/%d/%Y')
print (df)
         DOB        DOB1
0 2016-01-26  01/26/2016
1 2016-01-26  01/26/2016

How do I save JSON to local text file

Here is a solution on pure js. You can do it with html5 saveAs. For example this lib could be helpful: https://github.com/eligrey/FileSaver.js
Look at the demo: http://eligrey.com/demos/FileSaver.js/
P.S. There is no information about json save, but you can do it changing file type to "application/json" and format to .json

Getting the document object of an iframe

In my case, it was due to Same Origin policies. To explain it further, MDN states the following:

If the iframe and the iframe's parent document are Same Origin, returns a Document (that is, the active document in the inline frame's nested browsing context), else returns null.

adding multiple entries to a HashMap at once in one statement

    boolean x;
    for (x = false, 
        map.put("One", new Integer(1)), 
        map.put("Two", new Integer(2)),      
        map.put("Three", new Integer(3)); x;);

Ignoring the declaration of x (which is necessary to avoid an "unreachable statement" diagnostic), technically it's only one statement.

How do you dismiss the keyboard when editing a UITextField

If you connect the DidEndOnExit event of the text field to an action (IBAction) in InterfaceBuilder, it will be messaged when the user dismisses the keyboard (with the return key) and the sender will be a reference to the UITextField that fired the event.

For example:

-(IBAction)userDoneEnteringText:(id)sender
{
    UITextField theField = (UITextField*)sender;
    // do whatever you want with this text field
}

Then, in InterfaceBuilder, link the DidEndOnExit event of the text field to this action on your controller (or whatever you're using to link events from the UI). Whenever the user enters text and dismisses the text field, the controller will be sent this message.

Dump Mongo Collection into JSON format

Mongo includes a mongoexport utility (see docs) which can dump a collection. This utility uses the native libmongoclient and is likely the fastest method.

mongoexport -d <database> -c <collection_name>

Also helpful:

-o: write the output to file, otherwise standard output is used (docs)

--jsonArray: generates a valid json document, instead of one json object per line (docs)

--pretty: outputs formatted json (docs)

Error: Uncaught (in promise): Error: Cannot match any routes Angular 2

I am using angular 4 and faced the same issue apply, all possible solution but finally, this solve my problem

export class AppRoutingModule {
constructor(private router: Router) {
    this.router.errorHandler = (error: any) => {
        this.router.navigate(['404']); // or redirect to default route
    }
  }
}

Hope this will help you.

Rounding to two decimal places in Python 2.7?

You can use str.format(), too:

>>> print "financial return of outcome 1 = {:.2f}".format(1.23456)
financial return of outcome 1 = 1.23

How to copy a dictionary and only edit the copy

Python never implicitly copies objects. When you set dict2 = dict1, you are making them refer to the same exact dict object, so when you mutate it, all references to it keep referring to the object in its current state.

If you want to copy the dict (which is rare), you have to do so explicitly with

dict2 = dict(dict1)

or

dict2 = dict1.copy()

Swap two items in List<T>

If order matters, you should keep a property on the "T" objects in your list that denotes sequence. In order to swap them, just swap the value of that property, and then use that in the .Sort(comparison with sequence property)

How do I reference a local image in React?

The best way is to import the image first and then use it.

import React, { Component } from 'react';
import logo from '../logo.svg';
export default class Header extends Component {
  render() {
    return (
      <div className="row">
        <div className="logo">
          <img src={logo} width="100" height="50" />
        </div>
      </div>
    );
  }
}