Programs & Examples On #Taint checking

Add st, nd, rd and th (ordinal) suffix to a number

Strongly recommend the excellent date-fns library. Fast, modular, immutable, works with standard dates.

import * as DateFns from 'date-fns';

const ordinalInt = DateFns.format(someInt, 'do');

See date-fns docs: https://date-fns.org/v2.0.0-alpha.9/docs/format

Export/import jobs in Jenkins

The most easy way, with direct access to the machine is to copy the job folder from first jenkins to another one (you can exclude workspaces - workspace folder), because the whole job configuration is stored in the xml file on the disk.

Then in the new jenkins just reload configuration in the global settings (admin access is required) should be enough, if not, then you will need to restart Jenkins tool.

Another way can be to use plugins mentioned above this post.

edit: - in case you can probably also exclude modules folders

How to move (and overwrite) all files from one directory to another?

In linux shell, many commands accept multiple parameters and therefore could be used with wild cards. So, for example if you want to move all files from folder A to folder B, you write:

mv A/* B

If you want to move all files with a certain "look" to it, you could do like this:

mv A/*.txt B

Which copies all files that are blablabla.txt to folder B

Star (*) can substitute any number of characters or letters while ? can substitute one. For example if you have many files in the shape file_number.ext and you want to move only the ones that have two digit numbers, you could use a command like this:

mv A/file_??.ext B

Or more complicated examples:

mv A/fi*_??.e* B

For files that look like fi<-something->_<-two characters->.e<-something->

Unlike many commands in shell that require -R to (for example) copy or remove subfolders, mv does that itself.

Remember that mv overwrites without asking (unless the files being overwritten are read only or you don't have permission) so make sure you don't lose anything in the process.

For your future information, if you have subfolders that you want to copy, you could use the -R option, saying you want to do the command recursively. So it would look something like this:

cp A/* B -R

By the way, all I said works with rm (remove, delete) and cp (copy) too and beware, because once you delete, there is no turning back! Avoid commands like rm * -R unless you are sure what you are doing.

C# Double - ToString() formatting with two decimal places but no rounding

This is working for me

string prouctPrice = Convert.ToDecimal(String.Format("{0:0.00}", Convert.ToDecimal(yourString))).ToString();

Get enum values as List of String in Java 8

You could also do something as follow

public enum DAY {MON, TUES, WED, THU, FRI, SAT, SUN};
EnumSet.allOf(DAY.class).stream().map(e -> e.name()).collect(Collectors.toList())

or

EnumSet.allOf(DAY.class).stream().map(DAY::name).collect(Collectors.toList())

The main reason why I stumbled across this question is that I wanted to write a generic validator that validates whether a given string enum name is valid for a given enum type (Sharing in case anyone finds useful).

For the validation, I had to use Apache's EnumUtils library since the type of enum is not known at compile time.

@SuppressWarnings({ "unchecked", "rawtypes" })
public static void isValidEnumsValid(Class clazz, Set<String> enumNames) {
    Set<String> notAllowedNames = enumNames.stream()
            .filter(enumName -> !EnumUtils.isValidEnum(clazz, enumName))
            .collect(Collectors.toSet());

    if (notAllowedNames.size() > 0) {
        String validEnumNames = (String) EnumUtils.getEnumMap(clazz).keySet().stream()
            .collect(Collectors.joining(", "));

        throw new IllegalArgumentException("The requested values '" + notAllowedNames.stream()
                .collect(Collectors.joining(",")) + "' are not valid. Please select one more (case-sensitive) "
                + "of the following : " + validEnumNames);
    }
}

I was too lazy to write an enum annotation validator as shown in here https://stackoverflow.com/a/51109419/1225551

How to Install Windows Phone 8 SDK on Windows 7

You can install it by first extracting all the files from the ISO and then overwriting those files with the files from the ZIP. Then you can run the batch file as administrator to do the installation. Most of the packages install on windows 7, but I haven't tested yet how well they work.

Is it possible to use argsort in descending order?

An elegant way could be as follows -

ids = np.flip(np.argsort(avgDists))

This will give you indices of elements sorted in descending order. Now you can use regular slicing...

top_n = ids[:n]

How to get the last row of an Oracle a table

$sql = "INSERT INTO table_name( field1, field2 )  VALUES ('foo','bar') 
        RETURNING ID INTO :mylastid";
$stmt = oci_parse($db, $sql);
oci_bind_by_name($stmt, "mylastid", $last_id, 8, SQLT_INT);
oci_execute($stmt);

echo "last inserted id is:".$last_id;

Tip: you have to use your id column name in {your_id_col_name} below...

"RETURNING {your_id_col_name} INTO :mylastid"

How to configure heroku application DNS to Godaddy Domain?

I struggled a lot to resolve it Nothing seemed to work for me.

The steps I followed are mentioned here.

1 - Go to your App settings.

2 - Click on Add domain.

enter image description here

3 - A dialog will open & will ask you to enter the desired domain. (Please add it starting with www for instance - www.abcd.com )

enter image description here

4 - One added click on Next to move to the next dialog.

enter image description here

5 - After adding the domain you will get the DNS target, Now you need to navigate to GoDaddy and follow the following steps.

6 - Navigate to https://dcc.godaddy.com/domains & click on your domain.

7 - Once clicked you will navigate to https://dcc.godaddy.com/control/yourdomain/settings

8 - Scroll down to the bottom you will see Manage DNS.

enter image description here

9 - It will navigate you to DNS settings then add the entry similar to mentioned below and delete all other CNAME records. Here the value of points is your DNS target that you got in the 4th Step.

enter image description here

10 - Then after some time your site should be mapped to the Heroku app URL.

minimize app to system tray

I found this to accomplish the entire solution. The answer above fails to remove the window from the task bar.

private void ImportStatusForm_Resize(object sender, EventArgs e)
{
    if (this.WindowState == FormWindowState.Minimized)
    {
        notifyIcon.Visible = true;
        notifyIcon.ShowBalloonTip(3000);
        this.ShowInTaskbar = false;
    }
}

private void notifyIcon_MouseDoubleClick(object sender, MouseEventArgs e)
{
    this.WindowState = FormWindowState.Normal;
    this.ShowInTaskbar = true;
    notifyIcon.Visible = false;
}

Also it is good to set the following properties of the notify icon control using the forms designer.

this.notifyIcon.BalloonTipIcon = System.Windows.Forms.ToolTipIcon.Info; //Shows the info icon so the user doesn't think there is an error.
this.notifyIcon.BalloonTipText = "[Balloon Text when Minimized]";
this.notifyIcon.BalloonTipTitle = "[Balloon Title when Minimized]";
this.notifyIcon.Icon = ((System.Drawing.Icon)(resources.GetObject("notifyIcon.Icon"))); //The tray icon to use
this.notifyIcon.Text = "[Message shown when hovering over tray icon]";

Error: Registry key 'Software\JavaSoft\Java Runtime Environment'\CurrentVersion'?

I had Java 1.8 but had to downgrade to Java 1.6 for some reason. When I uninstalled java 1.8 and ran the command "Java -Version" from the command prompt, I got the error -

Error: Registry key 'Software\JavaSoft\Java Runtime Environment'\CurrentVersion'

has value '1.6', but '1.8' is required. Error: could not find java.dll Error: Could not find Java SE Runtime Environment.

Uninstalling 1.6 and then reinstalling 1.6 fixed the issue for me :-)

WARNING: Setting property 'source' to 'org.eclipse.jst.jee.server:appname' did not find a matching property

Despite this question being rather old, I had to deal with a similar warning and wanted to share what I found out.

First of all this is a warning and not an error. So there is no need to worry too much about it. Basically it means, that Tomcat does not know what to do with the source attribute from context.

This source attribute is set by Eclipse (or to be more specific the Eclipse Web Tools Platform) to the server.xml file of Tomcat to match the running application to a project in workspace.

Tomcat generates a warning for every unknown markup in the server.xml (i.e. the source attribute) and this is the source of the warning. You can safely ignore it.

How to convert WebResponse.GetResponseStream return into a string?

As @Heinzi mentioned the character set of the response should be used.

var encoding = response.CharacterSet == ""
    ? Encoding.UTF8
    : Encoding.GetEncoding(response.CharacterSet);

using (var stream = response.GetResponseStream())
{
    var reader = new StreamReader(stream, encoding);
    var responseString = reader.ReadToEnd();
}

Choice between vector::resize() and vector::reserve()

reserve when you do not want the objects to be initialized when reserved. also, you may prefer to logically differentiate and track its count versus its use count when you resize. so there is a behavioral difference in the interface - the vector will represent the same number of elements when reserved, and will be 100 elements larger when resized in your scenario.

Is there any better choice in this kind of scenario?

it depends entirely on your aims when fighting the default behavior. some people will favor customized allocators -- but we really need a better idea of what it is you are attempting to solve in your program to advise you well.

fwiw, many vector implementations will simply double the allocated element count when they must grow - are you trying to minimize peak allocation sizes or are you trying to reserve enough space for some lock free program or something else?

What is the difference between window, screen, and document in Javascript?

Window is the main JavaScript object root, aka the global object in a browser, also can be treated as the root of the document object model. You can access it as window

window.screen or just screen is a small information object about physical screen dimensions.

window.document or just document is the main object of the potentially visible (or better yet: rendered) document object model/DOM.

Since window is the global object you can reference any properties of it with just the property name - so you do not have to write down window. - it will be figured out by the runtime.

CSS set li indent

Also try:

ul {
  list-style-position: inside;
}

SQL Server table creation date query

SELECT create_date
FROM sys.tables
WHERE name='YourTableName'

Pro JavaScript programmer interview questions (with answers)

Ask them how they ensure their pages continue to be usable when the user has JavaScript turned off or JavaScript isn't available.

There's no One True Answer, but you're fishing for an answer talking about some strategies for Progressive Enhancement.

Progressive Enhancement consists of the following core principles:

  • basic content should be accessible to all browsers
  • basic functionality should be accessible to all browsers
  • sparse, semantic markup contains all content
  • enhanced layout is provided by externally linked CSS
  • enhanced behavior is provided by [[Unobtrusive JavaScript|unobtrusive]], externally linked JavaScript
  • end user browser preferences are respected

How to loop through all the files in a directory in c # .net?

You can have a look at this page showing Deep Folder Copy, it uses recursive means to iterate throught the files and has some really nice tips, like filtering techniques etc.

http://www.codeproject.com/Tips/512208/Folder-Directory-Deep-Copy-including-sub-directori

Set UIButton title UILabel font size programmatically

This way you can set the fontSize and can handle it in just one class.

1. Created an extension of UIButton and added following code:

- (void)awakeFromNib{

    [super awakeFromNib];

    [self setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [self.titleLabel setFont:[UIFont fontWithName:@"font" 
                                     size:self.titleLabel.font.pointSize]];
    [self setContentHorizontalAlignment:UIControlContentHorizontalAlignmentCenter];
}

2.1 Create UIButton inside Code

Now if you create a UIButton inside your code, #import the extension of yourUIButton` and create the Button.

2.2 Create Button in Interface Builder

If you create the UIButton inside the Interface Builder, select the UIButton, go to the Identity Inspector and add the created extension as class for the UIButton.

How to view the current heap size that an application is using?

You can Use the tool : Eclipse Memory Analyzer Tool http://www.eclipse.org/mat/ .

It is very useful.

Ruby class instance variable vs. class variable

While it may immediately seem useful to utilize class instance variables, since class instance variable are shared among subclasses and they can be referred to within both singleton and instance methods, there is a singificant drawback. They are shared and so subclasses can change the value of the class instance variable, and the base class will also be affected by the change, which is usually undesirable behavior:

class C
  @@c = 'c'
  def self.c_val
    @@c
  end
end

C.c_val
 => "c" 

class D < C
end

D.instance_eval do 
  def change_c_val
    @@c = 'd'
  end
end
 => :change_c_val 

D.change_c_val
(irb):12: warning: class variable access from toplevel
 => "d" 

C.c_val
 => "d" 

Rails introduces a handy method called class_attribute. As the name implies, it declares a class-level attribute whose value is inheritable by subclasses. The class_attribute value can be accessed in both singleton and instance methods, as is the case with the class instance variable. However, the huge benefit with class_attribute in Rails is subclasses can change their own value and it will not impact parent class.

class C
  class_attribute :c
  self.c = 'c'
end

 C.c
 => "c" 

class D < C
end

D.c = 'd'
 => "d" 

 C.c
 => "c" 

Horizontal scroll on overflow of table

Unless I grossly misunderstood your question, move overflow-x:scroll from .search-table to .search-table-outter.

http://jsfiddle.net/ZXnqM/4/

.search-table-outter {border:2px solid red; overflow-x:scroll;}
.search-table{table-layout: fixed; margin:40px auto 0px auto;   }

As far as I know you can't give scrollbars to tables themselves.

Asp.Net MVC with Drop Down List, and SelectListItem Assistance

You have a view model to which your view is strongly typed => use strongly typed helpers:

<%= Html.DropDownListFor(
    x => x.SelectedAccountId, 
    new SelectList(Model.Accounts, "Value", "Text")
) %>

Also notice that I use a SelectList for the second argument.

And in your controller action you were returning the view model passed as argument and not the one you constructed inside the action which had the Accounts property correctly setup so this could be problematic. I've cleaned it a bit:

public ActionResult AccountTransaction()
{
    var accounts = Services.AccountServices.GetAccounts(false);
    var viewModel = new AccountTransactionView
    {
        Accounts = accounts.Select(a => new SelectListItem
        {
            Text = a.Description,
            Value = a.AccountId.ToString()
        })
    };
    return View(viewModel);
}

PHP: How to send HTTP response code?

Add this line before any output of the body, in the event you aren't using output buffering.

header("HTTP/1.1 200 OK");

Replace the message portion ('OK') with the appropriate message, and the status code with your code as appropriate (404, 501, etc)

What does the variable $this mean in PHP?

$this is a reference to the calling object (usually the object to which the method belongs, but possibly another object, if the method is called statically from the context of a secondary object).

When and where to use GetType() or typeof()?

typeof is applied to a name of a type or generic type parameter known at compile time (given as identifier, not as string). GetType is called on an object at runtime. In both cases the result is an object of the type System.Type containing meta-information on a type.

Example where compile-time and run-time types are equal

string s = "hello";

Type t1 = typeof(string);
Type t2 = s.GetType();

t1 == t2 ==> true

Example where compile-time and run-time types are different

object obj = "hello";

Type t1 = typeof(object); // ==> object
Type t2 = obj.GetType();  // ==> string!

t1 == t2 ==> false

i.e., the compile time type (static type) of the variable obj is not the same as the runtime type of the object referenced by obj.


Testing types

If, however, you only want to know whether mycontrol is a TextBox then you can simply test

if (mycontrol is TextBox)

Note that this is not completely equivalent to

if (mycontrol.GetType() == typeof(TextBox))    

because mycontrol could have a type that is derived from TextBox. In that case the first comparison yields true and the second false! The first and easier variant is OK in most cases, since a control derived from TextBox inherits everything that TextBox has, probably adds more to it and is therefore assignment compatible to TextBox.

public class MySpecializedTextBox : TextBox
{
}

MySpecializedTextBox specialized = new MySpecializedTextBox();
if (specialized is TextBox)       ==> true

if (specialized.GetType() == typeof(TextBox))        ==> false

Casting

If you have the following test followed by a cast and T is nullable ...

if (obj is T) {
    T x = (T)obj; // The casting tests, whether obj is T again!
    ...
}

... you can change it to ...

T x = obj as T;
if (x != null) {
    ...
}

Testing whether a value is of a given type and casting (which involves this same test again) can both be time consuming for long inheritance chains. Using the as operator followed by a test for null is more performing.

Starting with C# 7.0 you can simplify the code by using pattern matching:

if (obj is T t) {
    // t is a variable of type T having a non-null value.
    ...
}

Btw.: this works for value types as well. Very handy for testing and unboxing. Note that you cannot test for nullable value types:

if (o is int? ni) ===> does NOT compile!

This is because either the value is null or it is an int. This works for int? o as well as for object o = new Nullable<int>(x);:

if (o is int i) ===> OK!

I like it, because it eliminates the need to access the Nullable<T>.Value property.

What is the Java ?: operator called and what does it do?

It's the conditional operator, and it's more than just a concise way of writing if statements.

Since it is an expression that returns a value it can be used as part of other expressions.

What is the best way to merge mp3 files?

I would use Winamp to do this. Create a playlist of files you want to merge into one, select Disk Writer output plugin, choose filename and you're done. The file you will get will be correct MP3 file and you can set bitrate etc.

Check if null Boolean is true results in exception

Boolean is the object wrapper class for the primitive boolean. This class, as any class, can indeed be null. For performance and memory reasons it is always best to use the primitive.

The wrapper classes in the Java API serve two primary purposes:

  1. To provide a mechanism to “wrap” primitive values in an object so that the primitives can be included in activities reserved for objects, like as being added to Collections, or returned from a method with an object return value.
  2. To provide an assortment of utility functions for primitives. Most of these functions are related to various conversions: converting primitives to and from String objects, and converting primitives and String objects to and from different bases (or radix), such as binary, octal, and hexadecimal.

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

Error:Execution failed for task ':app:transformClassesWithDexForDebug'

The solution that worked for me personally was:

in the build.gradle

defaultConfig {
        multiDexEnabled true
    }

 dexOptions {
        javaMaxHeapSize "4g"
    }

Avoiding "resource is out of sync with the filesystem"

A little hint. The message often appears during rename operation. The quick workaround for me is pressing Ctrl-Y (redo shortcut) after message confirmation. It works only if the renaming affects a single file.

Disable time in bootstrap date time picker

In my case, the option I used was:

var from = $("input.datepicker").datetimepicker({
  format:'Y-m-d',
  timepicker:false # <- HERE
});

I'm using this plugin https://xdsoft.net/jqplugins/datetimepicker/

How to activate "Share" button in android app?

Share Any File as below ( Kotlin ) :
first create a folder named xml in the res folder and create a new XML Resource File named provider_paths.xml and put the below code inside it :

<?xml version="1.0" encoding="utf-8"?>
<paths xmlns:android="http://schemas.android.com/apk/res/android">
    <files-path
        name="files"
        path="."/>

    <external-path
        name="external_files"
        path="."/>
</paths>

now go to the manifests folder and open the AndroidManifest.xml and then put the below code inside the <application> tag :

<provider
android:name="androidx.core.content.FileProvider"
android:authorities="${applicationId}.provider"
android:exported="false"
android:grantUriPermissions="true">
<meta-data
    android:name="android.support.FILE_PROVIDER_PATHS"
    android:resource="@xml/provider_paths" /> // provider_paths.xml file path in this example
</provider>

now you put the below code in the setOnLongClickListener :

share_btn.setOnClickListener {
    try {
        val file = File("pathOfFile")
        if(file.exists()) {
            val uri = FileProvider.getUriForFile(this, BuildConfig.APPLICATION_ID + ".provider", file)
            val intent = Intent(Intent.ACTION_SEND)
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
            intent.setType("*/*")
            intent.putExtra(Intent.EXTRA_STREAM, uri)
            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
            startActivity(intent)
        }
    } catch (e: java.lang.Exception) {
        e.printStackTrace()
        toast("Error")
    }
}

When to use %r instead of %s in Python?

The %s specifier converts the object using str(), and %r converts it using repr().

For some objects such as integers, they yield the same result, but repr() is special in that (for types where this is possible) it conventionally returns a result that is valid Python syntax, which could be used to unambiguously recreate the object it represents.

Here's an example, using a date:

>>> import datetime
>>> d = datetime.date.today()
>>> str(d)
'2011-05-14'
>>> repr(d)
'datetime.date(2011, 5, 14)'

Types for which repr() doesn't produce Python syntax include those that point to external resources such as a file, which you can't guarantee to recreate in a different context.

jQuery on window resize

function myResizeFunction() {
  ...
}

$(function() {
  $(window).resize(myResizeFunction).trigger('resize');
});

This will cause your resize handler to trigger on window resize and on document ready. Of course, you can attach your resize handler outside of the document ready handler if you want .trigger('resize') to run on page load instead.

UPDATE: Here's another option if you don't want to make use of any other third-party libraries.

This technique adds a specific class to your target element so you have the advantage of controlling the styling through CSS only (and avoiding inline styling).

It also ensures that the class is only added or removed when the actual threshold point is triggered and not on each and every resize. It will fire at one threshold point only: when the height changes from <= 818 to > 819 or vice versa and not multiple times within each region. It's not concerned with any change in width.

function myResizeFunction() {
  var $window = $(this),
      height = Math.ceil($window.height()),
      previousHeight = $window.data('previousHeight');

  if (height !== previousHeight) {
    if (height < 819)
      previousHeight >= 819 && $('.footer').removeClass('hgte819');
    else if (!previousHeight || previousHeight < 819)
      $('.footer').addClass('hgte819');

    $window.data('previousHeight', height);
  }
}

$(function() {
  $(window).on('resize.optionalNamespace', myResizeFunction).triggerHandler('resize.optionalNamespace');
});

As an example, you might have the following as some of your CSS rules:

.footer {
  bottom: auto;
  left: auto;
  position: static;
}

.footer.hgte819 {
  bottom: 3px;
  left: 0;
  position: absolute;
}

How to get .app file of a xcode application

Xcode 8.1

Product -> Archive Then export on the right hand side to somewhere on your drive.

Populating a dictionary using for loops (python)

>>> dict(zip(keys, values))
{0: 'Hi', 1: 'I', 2: 'am', 3: 'John'}

Error with multiple definitions of function

You have #include "fun.cpp" in mainfile.cpp so compiling with:

g++ -o hw1 mainfile.cpp

will work, however if you compile by linking these together like

g++ -g -std=c++11 -Wall -pedantic   -c -o fun.o fun.cpp
g++ -g -std=c++11 -Wall -pedantic   -c -o mainfile.o mainfile.cpp

As they mention above, adding #include "fun.hpp" will need to be done or it won't work. However, your case with the funct() function is slightly different than my problem.

I had this issue when doing a HW assignment and the autograder compiled by the lower bash recipe, yet locally it worked using the upper bash.

How to produce an csv output file from stored procedure in SQL Server

I have tried this and it is working fine for me:

sqlcmd -S servername -E -s~ -W -k1 -Q  "sql query here" > "\\file_path\file_name.csv"

What is the T-SQL syntax to connect to another SQL Server?

If I were to paraphrase the question - is it possible to pick server context for query execution in the DDL - the answer is no. Only database context can be programmatically chosen with USE. (having already preselected the server context externally)

Linked server and OPEN QUERY can give access to the DDL but require somewhat a rewrite of your code to encapsulate as a string - making it difficult to develop/debug.

Alternately you could resort to an external driver program to pickup SQL files to send to the remote server via OPEN QUERY. However in most cases you might as well have connected to the server directly in the 1st place to evaluate the DDL.

Importing .py files in Google Colab

Below are the steps that worked for me

  1. Mount your google drive in google colab

    from google.colab import drive drive.mount('/content/drive')

  2. Insert the directory

    import sys sys.path.insert(0,’/content/drive/My Drive/ColabNotebooks’)

  3. check the current directory path

    %cd drive/MyDrive/ColabNotebooks %pwd

  4. Import your module or file

    import my_module

  5. If you get the following error 'Name Null is not defined' then do the following

    5.1 Download my_module.ipynb from colab as my_module.py file (file->Download .py)

    5.2 Upload the *.py file to drive/MyDrive/ColabNotebooks in Google drive

    5.3 import my_module will work now

Reference: https://medium.com/analytics-vidhya/importing-your-own-python-module-or-python-file-into-colab-3e365f0a35ec

https://github.com/googlecolab/colabtools/issues/1358

Running SSH Agent when starting Git Bash on Windows

Simple two string solution from this answer:

For sh, bash, etc:

# ~/.profile
if ! pgrep -q -U `whoami` -x 'ssh-agent'; then ssh-agent -s > ~/.ssh-agent.sh; fi
. ~/.ssh-agent.sh

For csh, tcsh, etc:

# ~/.schrc
sh -c 'if ! pgrep -q -U `whoami` -x 'ssh-agent'; then ssh-agent -c > ~/.ssh-agent.tcsh; fi'
eval `cat ~/.ssh-agent.tcsh`

When would you use the Builder Pattern?

Below are some reasons arguing for the use of the pattern and example code in Java, but it is an implementation of the Builder Pattern covered by the Gang of Four in Design Patterns. The reasons you would use it in Java are also applicable to other programming languages as well.

As Joshua Bloch states in Effective Java, 2nd Edition:

The builder pattern is a good choice when designing classes whose constructors or static factories would have more than a handful of parameters.

We've all at some point encountered a class with a list of constructors where each addition adds a new option parameter:

Pizza(int size) { ... }        
Pizza(int size, boolean cheese) { ... }    
Pizza(int size, boolean cheese, boolean pepperoni) { ... }    
Pizza(int size, boolean cheese, boolean pepperoni, boolean bacon) { ... }

This is called the Telescoping Constructor Pattern. The problem with this pattern is that once constructors are 4 or 5 parameters long it becomes difficult to remember the required order of the parameters as well as what particular constructor you might want in a given situation.

One alternative you have to the Telescoping Constructor Pattern is the JavaBean Pattern where you call a constructor with the mandatory parameters and then call any optional setters after:

Pizza pizza = new Pizza(12);
pizza.setCheese(true);
pizza.setPepperoni(true);
pizza.setBacon(true);

The problem here is that because the object is created over several calls it may be in an inconsistent state partway through its construction. This also requires a lot of extra effort to ensure thread safety.

The better alternative is to use the Builder Pattern.

public class Pizza {
  private int size;
  private boolean cheese;
  private boolean pepperoni;
  private boolean bacon;

  public static class Builder {
    //required
    private final int size;

    //optional
    private boolean cheese = false;
    private boolean pepperoni = false;
    private boolean bacon = false;

    public Builder(int size) {
      this.size = size;
    }

    public Builder cheese(boolean value) {
      cheese = value;
      return this;
    }

    public Builder pepperoni(boolean value) {
      pepperoni = value;
      return this;
    }

    public Builder bacon(boolean value) {
      bacon = value;
      return this;
    }

    public Pizza build() {
      return new Pizza(this);
    }
  }

  private Pizza(Builder builder) {
    size = builder.size;
    cheese = builder.cheese;
    pepperoni = builder.pepperoni;
    bacon = builder.bacon;
  }
}

Note that Pizza is immutable and that parameter values are all in a single location. Because the Builder's setter methods return the Builder object they are able to be chained.

Pizza pizza = new Pizza.Builder(12)
                       .cheese(true)
                       .pepperoni(true)
                       .bacon(true)
                       .build();

This results in code that is easy to write and very easy to read and understand. In this example, the build method could be modified to check parameters after they have been copied from the builder to the Pizza object and throw an IllegalStateException if an invalid parameter value has been supplied. This pattern is flexible and it is easy to add more parameters to it in the future. It is really only useful if you are going to have more than 4 or 5 parameters for a constructor. That said, it might be worthwhile in the first place if you suspect you may be adding more parameters in the future.

I have borrowed heavily on this topic from the book Effective Java, 2nd Edition by Joshua Bloch. To learn more about this pattern and other effective Java practices I highly recommend it.

How do you post to an iframe?

This function creates a temporary form, then send data using jQuery :

function postToIframe(data,url,target){
    $('body').append('<form action="'+url+'" method="post" target="'+target+'" id="postToIframe"></form>');
    $.each(data,function(n,v){
        $('#postToIframe').append('<input type="hidden" name="'+n+'" value="'+v+'" />');
    });
    $('#postToIframe').submit().remove();
}

target is the 'name' attr of the target iFrame, and data is a JS object :

data={last_name:'Smith',first_name:'John'}

converting a javascript string to a html object

You cannot do it with just method, unless you use some javascript framework like jquery which supports it ..

string s = '<div id="myDiv"></div>'
var htmlObject = $(s); // jquery call

but still, it would not be found by the getElementById because for that to work the element must be in the DOM... just creating in the memory does not insert it in the dom.

You would need to use append or appendTo or after etc.. to put it in the dom first..

Of'course all these can be done through regular javascript but it would take more steps to accomplish the same thing... and the logic is the same in both cases..

How to get the date from jQuery UI datepicker

You can retrieve the date by using the getDate function:

$("#datepicker").datepicker( 'getDate' );

The value is returned as a JavaScript Date object.

If you want to use this value when the user selects a date, you can use the onSelect event:

$("#datepicker").datepicker({
   onSelect: function(dateText, inst) { 
      var dateAsString = dateText; //the first parameter of this function
      var dateAsObject = $(this).datepicker( 'getDate' ); //the getDate method
   }
});

The first parameter is in this case the selected Date as String. Use parseDate to convert it to a JS Date Object.

See http://docs.jquery.com/UI/Datepicker for the full jQuery UI DatePicker reference.

Correct MIME Type for favicon.ico?

I have noticed that when using type="image/vnd.microsoft.icon", the favicon fails to appear when the browser is not connected to the internet. But type="image/x-icon" works whether the browser can connect to the internet, or not. When developing, at times I am not connected to the internet.

How to auto-format code in Eclipse?

On Windows and Linux : Ctrl + Shift + F

On Mac : ? + ? + F

(Alternatively you can press Format in Main Menu > Source)

How to open every file in a folder

The code below reads for any text files available in the directory which contains the script we are running. Then it opens every text file and stores the words of the text line into a list. After store the words we print each word line by line

import os, fnmatch

listOfFiles = os.listdir('.')
pattern = "*.txt"
store = []
for entry in listOfFiles:
    if fnmatch.fnmatch(entry, pattern):
        _fileName = open(entry,"r")
        if _fileName.mode == "r":
            content = _fileName.read()
            contentList = content.split(" ")
            for i in contentList:
                if i != '\n' and i != "\r\n":
                    store.append(i)

for i in store:
    print(i)

Adding n hours to a date in Java?

You can do it with Joda DateTime API

DateTime date= new DateTime(dateObj);
date = date.plusHours(1);
dateObj = date.toDate();

log4j:WARN No appenders could be found for logger (running jar file, not web app)

put the folder which has the properties file for log in java build path source. You can add it by right clicking the project ----> build path -----> configure build path ------> add t

How to add /usr/local/bin in $PATH on Mac

Try placing $PATH at the end.

export PATH=/usr/local/git/bin:/usr/local/bin:$PATH

What is the use of DesiredCapabilities in Selenium WebDriver?

  1. It is a class in org.openqa.selenium.remote.DesiredCapabilities package.
  2. It gives facility to set the properties of browser. Such as to set BrowserName, Platform, Version of Browser.
  3. Mostly DesiredCapabilities class used when do we used Selenium Grid.
  4. We have to execute mutiple TestCases on multiple Systems with different browser with Different version and Different Operating System.

Example:

WebDriver driver;
String baseUrl , nodeUrl;
baseUrl = "https://www.facebook.com";
nodeUrl = "http://192.168.10.21:5568/wd/hub";

DesiredCapabilities capability = DesiredCapabilities.firefox();
capability.setBrowserName("firefox");
capability.setPlatform(Platform.WIN8_1);

driver = new RemoteWebDriver(new URL(nodeUrl),capability);
driver.manage().window().maximize();
driver.manage().timeouts().implicitlyWait(2, TimeUnit.MINUTES);

How to document Python code using Doxygen

In the end, you only have two options:

You generate your content using Doxygen, or you generate your content using Sphinx*.

  1. Doxygen: It is not the tool of choice for most Python projects. But if you have to deal with other related projects written in C or C++ it could make sense. For this you can improve the integration between Doxygen and Python using doxypypy.

  2. Sphinx: The defacto tool for documenting a Python project. You have three options here: manual, semi-automatic (stub generation) and fully automatic (Doxygen like).

    1. For manual API documentation you have Sphinx autodoc. This is great to write a user guide with embedded API generated elements.
    2. For semi-automatic you have Sphinx autosummary. You can either setup your build system to call sphinx-autogen or setup your Sphinx with the autosummary_generate config. You will require to setup a page with the autosummaries, and then manually edit the pages. You have options, but my experience with this approach is that it requires way too much configuration, and at the end even after creating new templates, I found bugs and the impossibility to determine exactly what was exposed as public API and what not. My opinion is this tool is good for stub generation that will require manual editing, and nothing more. Is like a shortcut to end up in manual.
    3. Fully automatic. This have been criticized many times and for long we didn't have a good fully automatic Python API generator integrated with Sphinx until AutoAPI came, which is a new kid in the block. This is by far the best for automatic API generation in Python (note: shameless self-promotion).

There are other options to note:

  • Breathe: this started as a very good idea, and makes sense when you work with several related project in other languages that use Doxygen. The idea is to use Doxygen XML output and feed it to Sphinx to generate your API. So, you can keep all the goodness of Doxygen and unify the documentation system in Sphinx. Awesome in theory. Now, in practice, the last time I checked the project wasn't ready for production.
  • pydoctor*: Very particular. Generates its own output. It has some basic integration with Sphinx, and some nice features.

How to add SHA-1 to android application

Try pasting this code in CMD:

keytool -list -v -alias androiddebugkey -keystore  %USERPROFILE%\.android\debug.keystore

Java multiline string

A simple option is to edit your java-code with an editor like SciTE (http://www.scintilla.org/SciTEDownload.html), which allows you to WRAP the text so that long strings are easily viewed and edited. If you need escape characters you just put them in. By flipping the wrap-option off you can check that your string indeed is still just a long single-line string. But of course, the compiler will tell you too if it isn't.

Whether Eclipse or NetBeans support text-wrapping in an editor I don't know, because they have so many options. But if not, that would be a good thing to add.

Laravel Update Query

You could use the Laravel query builder, but this is not the best way to do it.

Check Wader's answer below for the Eloquent way - which is better as it allows you to check that there is actually a user that matches the email address, and handle the error if there isn't.

DB::table('users')
        ->where('email', $userEmail)  // find your user by their email
        ->limit(1)  // optional - to ensure only one record is updated.
        ->update(array('member_type' => $plan));  // update the record in the DB. 

If you have multiple fields to update you can simply add more values to that array at the end.

The remote server returned an error: (407) Proxy Authentication Required

Check with your firewall expert. They open the firewall for PROD servers so there is no need to use the Proxy.

Thanks your tip helped me solve my problem:

Had to to set the Credentials in two locations to get past the 407 error:

HttpWebRequest webRequest = WebRequest.Create(uirTradeStream) as HttpWebRequest;
webRequest.Proxy = WebRequest.DefaultWebProxy;
webRequest.Credentials = new NetworkCredential("user", "password", "domain");
webRequest.Proxy.Credentials = new NetworkCredential("user", "password", "domain");

and voila!

Split (explode) pandas dataframe string entry to separate rows

Pandas >= 0.25

Series and DataFrame methods define a .explode() method that explodes lists into separate rows. See the docs section on Exploding a list-like column.

Since you have a list of comma separated strings, split the string on comma to get a list of elements, then call explode on that column.

df = pd.DataFrame({'var1': ['a,b,c', 'd,e,f'], 'var2': [1, 2]})
df
    var1  var2
0  a,b,c     1
1  d,e,f     2

df.assign(var1=df['var1'].str.split(',')).explode('var1')

  var1  var2
0    a     1
0    b     1
0    c     1
1    d     2
1    e     2
1    f     2

Note that explode only works on a single column (for now). To explode multiple columns at once, see below.

NaNs and empty lists get the treatment they deserve without you having to jump through hoops to get it right.

df = pd.DataFrame({'var1': ['d,e,f', '', np.nan], 'var2': [1, 2, 3]})
df
    var1  var2
0  d,e,f     1
1            2
2    NaN     3

df['var1'].str.split(',')

0    [d, e, f]
1           []
2          NaN

df.assign(var1=df['var1'].str.split(',')).explode('var1')

  var1  var2
0    d     1
0    e     1
0    f     1
1          2  # empty list entry becomes empty string after exploding 
2  NaN     3  # NaN left un-touched

This is a serious advantage over ravel/repeat -based solutions (which ignore empty lists completely, and choke on NaNs).


Exploding Multiple Columns

Note that explode only works on a single column at a time, but you can use apply to explode multiple column at once:

df = pd.DataFrame({'var1': ['a,b,c', 'd,e,f'], 
                   'var2': ['i,j,k', 'l,m,n'], 
                   'var3': [1, 2]})
df
    var1   var2  var3
0  a,b,c  i,j,k     1
1  d,e,f  l,m,n     2

(df.set_index(['var3']) 
   .apply(lambda col: col.str.split(',').explode())
   .reset_index()
   .reindex(df.columns, axis=1))

df
  var1 var2  var3
0    a    i     1
1    b    j     1
2    c    k     1
3    d    l     2
4    e    m     2
5    f    n     2

The idea is to set as the index, all the columns that should NOT be exploded, then explode the remaining columns via apply. This works well when the lists are equally sized.

UICollectionView - dynamic cell height?

I just ran into this problem on a UICollectionView and the way that i solved it similar to the answer above but in a pure UICollectionView way.

  1. Create a custom UICollectionViewCell that contains whatever you will be filling it with to make it dynamic. I created its own .xib for it as it seems like the easiest approach.

  2. Add constraints in that .xib that allow for the cell to be calculated from top to bottom. The re-sizing won't work if you haven't accounted for all of the height. Say you have a view on top, then a label underneath it, and another label underneath that. You would need to connect constraints to the top of the cell to the top of that view, then the bottom of the view to the top of the first label, bottom of first label to the top of the second label, and bottom of second label to bottom of cell.

  3. Load the .xib into the viewcontroller and register it with the collectionView on viewDidLoad

    let nib = UINib(nibName: CustomCellName, bundle: nil)
    self.collectionView!.registerNib(nib, forCellWithReuseIdentifier: "customCellID")`
    
  4. Load a second copy of that xib into the class and store it as a property so you can use it to determine the size of what that cell should be

    let sizingNibNew = NSBundle.mainBundle().loadNibNamed(CustomCellName, owner: CustomCellName.self, options: nil) as NSArray
    self.sizingNibNew = (sizingNibNew.objectAtIndex(0) as? CustomViewCell)!
    
  5. Implement the UICollectionViewFlowLayoutDelegate in your view controller. The method that matters is called sizeForItemAtIndexPath. Inside that method you will need to pull the data from the datasource that is associated with that cell from the indexPath. Then configure the sizingCell and call preferredLayoutSizeFittingSize. The method returns a CGSize which will consist of the width minus the content insets and the height that is returned from self.sizingCell.preferredLayoutSizeFittingSize(targetSize).

    override func collectionView(collectionView: UICollectionView, layout collectionViewLayout: UICollectionViewLayout, sizeForItemAtIndexPath indexPath: NSIndexPath) -> CGSize {
        guard let data = datasourceArray?[indexPath.item] else {
            return CGSizeZero
        }
        let sectionInset = self.collectionView?.collectionViewLayout.sectionInset
        let widthToSubtract = sectionInset!.left + sectionInset!.right
    
        let requiredWidth = collectionView.bounds.size.width
    
    
        let targetSize = CGSize(width: requiredWidth, height: 0)
    
        sizingNibNew.configureCell(data as! CustomCellData, delegate: self)
        let adequateSize = self.sizingNibNew.preferredLayoutSizeFittingSize(targetSize)
        return CGSize(width: (self.collectionView?.bounds.width)! - widthToSubtract, height: adequateSize.height)
     }
    
  6. In the class of the custom cell itself you will need to override awakeFromNib and tell the contentView that its size needs to be flexible

     override func awakeFromNib() {
        super.awakeFromNib()
        self.contentView.autoresizingMask = [UIViewAutoresizing.FlexibleHeight]
     }
    
  7. In the custom cell override layoutSubviews

     override func layoutSubviews() {
       self.layoutIfNeeded()
      }
    
  8. In the class of the custom cell implement preferredLayoutSizeFittingSize. This is where you will need to do any trickery on the items that are being laid out. If its a label you will need to tell it what its preferredMaxWidth should be.

    func preferredLayoutSizeFittingSize(_ targetSize: CGSize)-> CGSize {
    
        let originalFrame = self.frame
        let originalPreferredMaxLayoutWidth = self.label.preferredMaxLayoutWidth
    
    
        var frame = self.frame
        frame.size = targetSize
        self.frame = frame
    
        self.setNeedsLayout()
        self.layoutIfNeeded()
        self.label.preferredMaxLayoutWidth = self.questionLabel.bounds.size.width
    
    
        // calling this tells the cell to figure out a size for it based on the current items set
        let computedSize = self.systemLayoutSizeFittingSize(UILayoutFittingCompressedSize)
    
        let newSize = CGSize(width:targetSize.width, height:computedSize.height)
    
        self.frame = originalFrame
        self.questionLabel.preferredMaxLayoutWidth = originalPreferredMaxLayoutWidth
    
        return newSize
    }
    

All those steps should give you the correct sizes. If your getting 0 or other funky numbers than you haven't set up your constraints properly.

Trust Store vs Key Store - creating with keytool

In simplest terms :

Keystore is used to store your credential (server or client) while truststore is used to store others credential (Certificates from CA).

Keystore is needed when you are setting up server side on SSL, it is used to store server's identity certificate, which server will present to a client on the connection while trust store setup on client side must contain to make the connection work. If you browser to connect to any website over SSL it verifies certificate presented by server against its truststore.

SQL injection that gets around mysql_real_escape_string()

Well, there's nothing really that can pass through that, other than % wildcard. It could be dangerous if you were using LIKE statement as attacker could put just % as login if you don't filter that out, and would have to just bruteforce a password of any of your users. People often suggest using prepared statements to make it 100% safe, as data can't interfere with the query itself that way. But for such simple queries it probably would be more efficient to do something like $login = preg_replace('/[^a-zA-Z0-9_]/', '', $login);

rails generate model

The code is okay but you are in the wrong directory. You must run these commands inside your rails project-directory.

The normal way to get there from scratch is:

$ rails new PROJECT_NAME
$ cd PROJECT_NAME
$ rails generate model ad \
    name:string \ 
    description:text \
    price:decimal \
    seller_id:integer \
    email:string img_url:string

Check if checkbox is NOT checked on click - jQuery

Try this:

if(!$(this).is(':checked'))

demo

YouTube iframe embed - full screen

I found a solution that worked for me on this page thanks to someone named @orangecoat-ciallella

https://www.drupal.org/node/1807158

The "full screen" button was not working in my Chrome browser on Ubuntu.

I was using the media_youtube module for D6. In the iframe it was using a video URL of the pattern //www.youtube.com/v/videoidhere.

I used the theme preprocessing function to make it output > //www.youtube.com/embed/videoidhere and it immediately started allowing the fullscreen button to work.

In short, try changing the /v/ to /embed/ in the YouTube URL if you're having a problem.

Unable to verify leaf signature

You have to include the Intermediate certificate in your server. This solves the [Error: UNABLE_TO_VERIFY_LEAF_SIGNATURE]

What is the difference between `sorted(list)` vs `list.sort()`?

Note: Simplest difference between sort() and sorted() is: sort() doesn't return any value while, sorted() returns an iterable list.

sort() doesn't return any value.

The sort() method just sorts the elements of a given list in a specific order - Ascending or Descending without returning any value.

The syntax of sort() method is:

list.sort(key=..., reverse=...)

Alternatively, you can also use Python's in-built function sorted() for the same purpose. sorted function return sorted list

 list=sorted(list, key=..., reverse=...)

How can I trigger the click event of another element in ng-click using angularjs?

The solution, as pointed out by other answers, is to use

angular.element(element).trigger(event);

Here's an example of how I randomly select multiple select elements:

$scope.randomize = function(){
    var games = [].slice.call(document.querySelectorAll('.games select'));

    games.forEach(function(e){
        // Logically change the element (Angular won't know about this)
        e.selectedIndex = parseInt(Math.random() * 100, 10) < 50 ? 1 : 2;

        // Manually tell Angular that the DOM has changed
        angular.element(e).trigger('change');
    });
};

Is PowerShell ready to replace my Cygwin shell on Windows?

I have only recently started dabbling in PowerShell with any degree of seriousness. Although for the past seven years I've worked in an almost exclusively Windows-based environment, I come from a Unix background and find myself constantly trying to "Unix-fy" my interaction experience on Windows. It's frustrating to say the least.

It's only fair to compare PowerShell to something like Bash, tcsh, or zsh since utilities like grep, sed, awk, find, etc. are not, strictly speaking, part of the shell; they will always, however, be part of any Unix environment. That said, a PowerShell command like Select-String has a very similar function to grep and is bundled as a core module in PowerShell ... so the lines can be a little blurred.

I think the key thing is culture, and the fact that the respective tool-sets will embody their respective cultures:

  • Unix is a file-based, (in general, non Unicode) text-based culture. Configuration files are almost exclusively text files. Windows, on the other hand has always been far more structured in respect of configuration formats--configurations are generally kept in proprietary databases (e.g., the Windows registry) which require specialised tools for their management.
  • The Unix administrative (and, for many years, development) interface has traditionally been the command line and the virtual terminal. Windows started off as a GUI and administrative functions have only recently started moving away from being exclusively GUI-based. We can expect the Unix experience on the command line to be a richer, more mature one given the significant lead it has on PowerShell, and my experience matches this. On this, in my experience:

    • The Unix administrative experience is geared towards making things easy to do in a minimal amount of key strokes; this is probably as a result of the historical situation of having to administer a server over a slow 9600 baud dial-up connection. Now PowerShell does have aliases which go a long way to getting around the rather verbose Verb-Noun standard, but getting to know those aliases is a bit of a pain (anyone know of something better than: alias | where {$_.ResolvedCommandName -eq "<command>"}?).

      An example of the rich way in which history can be manipulated:

      iptables commands are often long-winded and repeating them with slight differences would be a pain if it weren't for just one of many neat features of history manipulation built into Bash, so inserting an iptables rule like the following:

      iptables -I camera-1-internet -s 192.168.0.50 -m state --state NEW -j ACCEPT

      a second time for another camera ("camera-2"), is just a case of issuing:

      !!:s/-1-/-2-/:s/50/51

      which means "perform the previous command, but substitute -1- with -2- and 50 with 51.

    • The Unix experience is optimised for touch-typists; one can pretty much do everything without leaving the "home" position. For example, in Bash, using the Emacs key bindings (yes, Bash also supports vi bindings), cycling through the history is done using Ctrl-P and Ctrl-N whilst moving to the start and end of a line is done using Ctrl-A and Ctrl-E respectively ... and it definitely doesn't end there. Try even the simplest of navigation in the PowerShell console without moving from the home position and you're in trouble.

    • Simple things like versatile paging (a la less) on Unix don't seem to be available out-of-the-box in PowerShell which is a little frustrating, and a rich editor experience doesn't exist either. Of course, one can always download third-party tools that will fill those gaps, but it sure would be nice if these things were just "there" like they are on pretty much any flavour of Unix.
  • The Windows culture, at least in terms of system API's is largely driven by the supporting frameworks, viz., COM and .NET, both of-which are highly structured and object-based. On the other hand, access to Unix APIs has traditionally been through a file interface (/dev and /proc) or (non-object-oriented) C-style library calls. It's no surprise then that the scripting experiences match their respective OS paradigms. PowerShell is by nature structured (everything is an object) and Bash-and-friends file-based. The structured API which is at the disposal of a PowerShell programmer is vast (essentially matching the vastness of the existing set of standard COM and .NET interfaces).

In short, although the scripting capabilities of PowerShell are arguably more powerful than Bash (especially when you consider the availability of the .NET BCL), the interactive experience is significantly weaker, particularly if you're coming at it from an entirely keyboard-driven, console-based perspective (as many Unix-heads are).

Get current time in milliseconds using C++ and Boost

// Get current date/time in milliseconds.
#include "boost/date_time/posix_time/posix_time.hpp"
namespace pt = boost::posix_time;

int main()
{
     pt::ptime current_date_microseconds = pt::microsec_clock::local_time();

    long milliseconds = current_date_microseconds.time_of_day().total_milliseconds();

    pt::time_duration current_time_milliseconds = pt::milliseconds(milliseconds);

    pt::ptime current_date_milliseconds(current_date_microseconds.date(), 
                                        current_time_milliseconds);

    std::cout << "Microseconds: " << current_date_microseconds 
              << " Milliseconds: " << current_date_milliseconds << std::endl;

    // Microseconds: 2013-Jul-12 13:37:51.699548 Milliseconds: 2013-Jul-12 13:37:51.699000
}

Excel VBA Code: Compile Error in x64 Version ('PtrSafe' attribute required)

I think all you need to do for your function is just add PtrSafe: i.e. the first line of your first function should look like this:

Private Declare PtrSafe Function swe_azalt Lib "swedll32.dll" ......

What's the best way to build a string of delimited items in Java?

With Java 5 variable args, so you don't have to stuff all your strings into a collection or array explicitly:

import junit.framework.Assert;
import org.junit.Test;

public class StringUtil
{
    public static String join(String delim, String... strings)
    {
        StringBuilder builder = new StringBuilder();

        if (strings != null)
        {
            for (String str : strings)
            {
                if (builder.length() > 0)
                {
                    builder.append(delim).append(" ");
                }
                builder.append(str);
            }
        }           
        return builder.toString();
    }
    @Test
    public void joinTest()
    {
        Assert.assertEquals("", StringUtil.join(",", null));
        Assert.assertEquals("", StringUtil.join(",", ""));
        Assert.assertEquals("", StringUtil.join(",", new String[0]));
        Assert.assertEquals("test", StringUtil.join(",", "test"));
        Assert.assertEquals("foo, bar", StringUtil.join(",", "foo", "bar"));
        Assert.assertEquals("foo, bar, x", StringUtil.join(",", "foo", "bar", "x"));
    }
}

How to make space between LinearLayout children?

You just need to wrap items with linear layouts which have layout_weight. To have items horizontally separated, use this

<LinearLayout
    ...
    ...
  <LinearLayout
      android:layout_width="0dp"
      android:layout_height="wrap_content"
      android:layout_weight="1"
      android:gravity="center">

      // your item

  </LinearLayout>
</LinearLayout>

How to remove list elements in a for loop in Python?

You are not permitted to remove elements from the list while iterating over it using a for loop.

The best way to rewrite the code depends on what it is you're trying to do.

For example, your code is equivalent to:

for item in a:
  print item
a[:] = []

Alternatively, you could use a while loop:

while a:
  print a.pop(0)

I'm trying to remove items if they match a condition. Then I go to next item.

You could copy every element that doesn't match the condition into a second list:

result = []
for item in a:
  if condition is False:
    result.append(item)
a = result

Alternatively, you could use filter or a list comprehension and assign the result back to a:

a = filter(lambda item:... , a)

or

a = [item for item in a if ...]

where ... stands for the condition that you need to check.

New Intent() starts new instance with Android: launchMode="singleTop"

Firstly, Stack structure can be examined. For the launch mode:singleTop
If an instance of the same activity is already on top of the task stack, then this instance will be reused to respond to the intent.

All activities are hold in the stack("first in last out") so if your current activity is at the top of stack and if you define it in the manifest.file as singleTop

android:name=".ActivityA"
android:launchMode="singleTop"

if you are in the ActivityA recreate the activity it will not enter onCreate will resume onNewIntent() and you can see by creating a notification Not:If you do not implement onNewIntent(Intent) you will not get new intent.

Intent activityMain = new Intent(ActivityA.this,
                        ActivityA.class);

                activityMain.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK
                        | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                startActivity(activityMain);




    @Override
        protected void onNewIntent(Intent intent) {

            super.onNewIntent(intent);

            notify("onNewIntent");
        }

        private void notify(String methodName) {

            String name = this.getClass().getName();
            String[] strings = name.split("\\.");

            Notification noti = new Notification.Builder(this)
                    .setContentTitle(methodName + "" + strings[strings.length - 1])
                    .setAutoCancel(true).setSmallIcon(R.drawable.ic_launcher)
                    .setContentText(name).build();
            NotificationManager notificationManager = (NotificationManager) getSystemService(NOTIFICATION_SERVICE);
            notificationManager.notify((int) System.currentTimeMillis(), noti);

        }

IF EXISTS in T-SQL

There's no need for "else" in this case:

IF EXISTS(SELECT *  FROM  table1  WHERE Name='John' ) return 1
return 0

Fetch: reject promise and catch the error if status is not OK?

For me, fny answers really got it all. since fetch is not throwing error, we need to throw/handle the error ourselves. Posting my solution with async/await. I think it's more strait forward and readable

Solution 1: Not throwing an error, handle the error ourselves

  async _fetch(request) {
    const fetchResult = await fetch(request); //Making the req
    const result = await fetchResult.json(); // parsing the response

    if (fetchResult.ok) {
      return result; // return success object
    }


    const responseError = {
      type: 'Error',
      message: result.message || 'Something went wrong',
      data: result.data || '',
      code: result.code || '',
    };

    const error = new Error();
    error.info = responseError;

    return (error);
  }

Here if we getting an error, we are building an error object, plain JS object and returning it, the con is that we need to handle it outside. How to use:

  const userSaved = await apiCall(data); // calling fetch
  if (userSaved instanceof Error) {
    debug.log('Failed saving user', userSaved); // handle error

    return;
  }
  debug.log('Success saving user', userSaved); // handle success

Solution 2: Throwing an error, using try/catch

async _fetch(request) {
    const fetchResult = await fetch(request);
    const result = await fetchResult.json();

    if (fetchResult.ok) {
      return result;
    }

    const responseError = {
      type: 'Error',
      message: result.message || 'Something went wrong',
      data: result.data || '',
      code: result.code || '',
    };

    let error = new Error();
    error = { ...error, ...responseError };
    throw (error);
  }

Here we are throwing and error that we created, since Error ctor approve only string, Im creating the plain Error js object, and the use will be:

  try {
    const userSaved = await apiCall(data); // calling fetch
    debug.log('Success saving user', userSaved); // handle success
  } catch (e) {
    debug.log('Failed saving user', userSaved); // handle error
  }

Solution 3: Using customer error

  async _fetch(request) {
    const fetchResult = await fetch(request);
    const result = await fetchResult.json();

    if (fetchResult.ok) {
      return result;
    }

    throw new ClassError(result.message, result.data, result.code);
  }

And:

class ClassError extends Error {

  constructor(message = 'Something went wrong', data = '', code = '') {
    super();
    this.message = message;
    this.data = data;
    this.code = code;
  }

}

Hope it helped.

How do I calculate the percentage of a number?

Divide $percentage by 100 and multiply to $totalWidth. Simple maths.

Call Class Method From Another Class

In Python function are first class citezens, so you can just assign it to a property like any other value. Here we are assigning the method of A's hello to a property on B. After __init__, hello will be attached to B as self.hello, which is actually a reference to A's hello:

class A:
    def hello(self, msg):
        print(f"Hello {msg}")
    
class B:
    hello = A.hello

print(A.hello)
print(B.hello)

b = B()
b.hello("good looking!")

Prints:

<function A.hello at 0x7fcce55b9e50>
<function A.hello at 0x7fcce55b9e50>
Hello good looking!

How to show Error & Warning Message Box in .NET/ How to Customize MessageBox

You should add namespace if you are not using it:

System.Windows.Forms.MessageBox.Show("Some text", "Some title", 
    System.Windows.Forms.MessageBoxButtons.OK, 
    System.Windows.Forms.MessageBoxIcon.Error);

Alternatively, you can add at the begining of your file:

using System.Windows.Forms

and then use (as stated in previous answers):

MessageBox.Show("Some text", "Some title", 
    MessageBoxButtons.OK, MessageBoxIcon.Error);

Android - Launcher Icon Size

No need for third party tools when Android Studio can generate icons for us.

  • File -> New -> Image Asset

  • Then choose Launcher Icons as the Asset Type:

  • Choose a High-res image for the Image file:

Android Generate Launcher Icons

  • Next -> Finish to generate icons

generate ic laucher icons

Finally update android:icon name field in AndroidManifest.xml if required.

Configure nginx with multiple locations with different root folders on subdomain

You need to use the alias directive for location /static:

server {

  index index.html;
  server_name test.example.com;

  root /web/test.example.com/www;

  location /static/ {
    alias /web/test.example.com/static/;
  }

}

The nginx wiki explains the difference between root and alias better than I can:

Note that it may look similar to the root directive at first sight, but the document root doesn't change, just the file system path used for the request. The location part of the request is dropped in the request Nginx issues.

Note that root and alias handle trailing slashes differently.

SQL - How to find the highest number in a column?

You can do

SELECT MAX(ID) FROM Customers;

"Mixed content blocked" when running an HTTP AJAX operation in an HTTPS page

For laravel 8 in local it was ok but in production I had the problem. To solve it I used POST method and removed a simple slash at final of url. I changed it from:

/my/url/

to:

/my/url

and it works.

I don't know the reason. Perhaps somebody could explain it.

How can I delete all Git branches which have been merged?

For Windows you can install Cygwin and remove all remote branches using following command:

git branch -r --merged | "C:\cygwin64\bin\grep.exe" -v master | "C:\cygwin64\bin\sed.exe" 's/origin\///' | "C:\cygwin64\bin\xargs.exe" -n 1 git push --delete origin

Launch a shell command with in a python script, wait for the termination and return to the script

this worked for me fine!

shell_command = "ls -l" subprocess.call(shell_command.split())

What is the most efficient/elegant way to parse a flat table into a tree?

Now that MySQL 8.0 supports recursive queries, we can say that all popular SQL databases support recursive queries in standard syntax.

WITH RECURSIVE MyTree AS (
    SELECT * FROM MyTable WHERE ParentId IS NULL
    UNION ALL
    SELECT m.* FROM MyTABLE AS m JOIN MyTree AS t ON m.ParentId = t.Id
)
SELECT * FROM MyTree;

I tested recursive queries in MySQL 8.0 in my presentation Recursive Query Throwdown in 2017.

Below is my original answer from 2008:


There are several ways to store tree-structured data in a relational database. What you show in your example uses two methods:

  • Adjacency List (the "parent" column) and
  • Path Enumeration (the dotted-numbers in your name column).

Another solution is called Nested Sets, and it can be stored in the same table too. Read "Trees and Hierarchies in SQL for Smarties" by Joe Celko for a lot more information on these designs.

I usually prefer a design called Closure Table (aka "Adjacency Relation") for storing tree-structured data. It requires another table, but then querying trees is pretty easy.

I cover Closure Table in my presentation Models for Hierarchical Data with SQL and PHP and in my book SQL Antipatterns: Avoiding the Pitfalls of Database Programming.

CREATE TABLE ClosureTable (
  ancestor_id   INT NOT NULL REFERENCES FlatTable(id),
  descendant_id INT NOT NULL REFERENCES FlatTable(id),
  PRIMARY KEY (ancestor_id, descendant_id)
);

Store all paths in the Closure Table, where there is a direct ancestry from one node to another. Include a row for each node to reference itself. For example, using the data set you showed in your question:

INSERT INTO ClosureTable (ancestor_id, descendant_id) VALUES
  (1,1), (1,2), (1,4), (1,6),
  (2,2), (2,4),
  (3,3), (3,5),
  (4,4),
  (5,5),
  (6,6);

Now you can get a tree starting at node 1 like this:

SELECT f.* 
FROM FlatTable f 
  JOIN ClosureTable a ON (f.id = a.descendant_id)
WHERE a.ancestor_id = 1;

The output (in MySQL client) looks like the following:

+----+
| id |
+----+
|  1 | 
|  2 | 
|  4 | 
|  6 | 
+----+

In other words, nodes 3 and 5 are excluded, because they're part of a separate hierarchy, not descending from node 1.


Re: comment from e-satis about immediate children (or immediate parent). You can add a "path_length" column to the ClosureTable to make it easier to query specifically for an immediate child or parent (or any other distance).

INSERT INTO ClosureTable (ancestor_id, descendant_id, path_length) VALUES
  (1,1,0), (1,2,1), (1,4,2), (1,6,1),
  (2,2,0), (2,4,1),
  (3,3,0), (3,5,1),
  (4,4,0),
  (5,5,0),
  (6,6,0);

Then you can add a term in your search for querying the immediate children of a given node. These are descendants whose path_length is 1.

SELECT f.* 
FROM FlatTable f 
  JOIN ClosureTable a ON (f.id = a.descendant_id)
WHERE a.ancestor_id = 1
  AND path_length = 1;

+----+
| id |
+----+
|  2 | 
|  6 | 
+----+

Re comment from @ashraf: "How about sorting the whole tree [by name]?"

Here's an example query to return all nodes that are descendants of node 1, join them to the FlatTable that contains other node attributes such as name, and sort by the name.

SELECT f.name
FROM FlatTable f 
JOIN ClosureTable a ON (f.id = a.descendant_id)
WHERE a.ancestor_id = 1
ORDER BY f.name;

Re comment from @Nate:

SELECT f.name, GROUP_CONCAT(b.ancestor_id order by b.path_length desc) AS breadcrumbs
FROM FlatTable f 
JOIN ClosureTable a ON (f.id = a.descendant_id) 
JOIN ClosureTable b ON (b.descendant_id = a.descendant_id) 
WHERE a.ancestor_id = 1 
GROUP BY a.descendant_id 
ORDER BY f.name

+------------+-------------+
| name       | breadcrumbs |
+------------+-------------+
| Node 1     | 1           |
| Node 1.1   | 1,2         |
| Node 1.1.1 | 1,2,4       |
| Node 1.2   | 1,6         |
+------------+-------------+

A user suggested an edit today. SO moderators approved the edit, but I am reversing it.

The edit suggested that the ORDER BY in the last query above should be ORDER BY b.path_length, f.name, presumably to make sure the ordering matches the hierarchy. But this doesn't work, because it would order "Node 1.1.1" after "Node 1.2".

If you want the ordering to match the hierarchy in a sensible way, that is possible, but not simply by ordering by the path length. For example, see my answer to MySQL Closure Table hierarchical database - How to pull information out in the correct order.

POST: sending a post request in a url itself

It is not possible to send POST parameters in the url in a starightforward manner. POST request in itself means sending information in the body.

I found a fairly simple way to do this. Use Postman by Google, which allows you to specify the content-type(a header field) as application/json and then provide name-value pairs as parameters.

You can find clear directions at [2020-09-04: broken link - see comment] http://docs.brightcove.com/en/video-cloud/player-management/guides/postman.html

Just use your url in the place of theirs.

Hope it helps

LINQ extension methods - Any() vs. Where() vs. Exists()

foreach (var item in model.Where(x => !model2.Any(y => y.ID == x.ID)).ToList())
{
enter code here
}

same work you also can do with Contains

secondly Where is give you new list of values. thirdly using Exist is not a good practice, you can achieve your target from Any and contains like

EmployeeDetail _E = Db.EmployeeDetails.where(x=>x.Id==1).FirstOrDefault();

Hope this will clear your confusion.

Can I override and overload static methods in Java?

It’s actually pretty simple to understand – Everything that is marked static belongs to the class only, for example static method cannot be inherited in the sub class because they belong to the class in which they have been declared. Refer static keyword.

The best answer i found of this question is:

http://www.geeksforgeeks.org/can-we-overload-or-override-static-methods-in-java/

Meaning of "[: too many arguments" error from if [] (square brackets)

Another scenario that you can get the [: too many arguments or [: a: binary operator expected errors is if you try to test for all arguments "$@"

if [ -z "$@" ]
then
    echo "Argument required."
fi

It works correctly if you call foo.sh or foo.sh arg1. But if you pass multiple args like foo.sh arg1 arg2, you will get errors. This is because it's being expanded to [ -z arg1 arg2 ], which is not a valid syntax.

The correct way to check for existence of arguments is [ "$#" -eq 0 ]. ($# is the number of arguments).

How to resolve ORA-011033: ORACLE initialization or shutdown in progress

I used a combination of the answers from rohancragg, Mukul Goel, and NullSoulException from above. However I had an additional error:

ORA-01157: cannot identify/lock data file string - see DBWR trace file

To which I found the answer here: http://nimishgarg.blogspot.com/2014/01/ora-01157-cannot-identifylock-data-file.html

Incase the above post gets deleted I am including the commands here as well.

C:\>sqlplus sys/sys as sysdba
SQL*Plus: Release 11.2.0.3.0 Production on Tue Apr 30 19:07:16 2013
Copyright (c) 1982, 2011, Oracle.  All rights reserved.
Connected to an idle instance.

SQL> startup
ORACLE instance started.
Total System Global Area  778387456 bytes
Fixed Size                  1384856 bytes
Variable Size             520097384 bytes
Database Buffers          251658240 bytes
Redo Buffers                5246976 bytes
Database mounted.
ORA-01157: cannot identify/lock data file 11 – see DBWR trace file
ORA-01110: data file 16: 'E:\oracle\app\nimish.garg\oradata\orcl\test_ts.dbf'

SQL> select NAME from v$datafile where file#=16;
NAME
--------------------------------------------------------------------------------
E:\ORACLE\APP\NIMISH.GARG\ORADATA\ORCL\TEST_TS.DBF

SQL> alter database datafile 16 OFFLINE DROP;
Database altered.

SQL> alter database open;
Database altered.

Thanks everyone you saved my day!

Fissh

Wait for shell command to complete

Either link the shell to an object, have the batch job terminate the shell object (exit) and have the VBA code continue once the shell object = Nothing?

Or have a look at this: Capture output value from a shell command in VBA?

How can you dynamically create variables via a while loop?

For free-dom:

import random

alphabet = tuple('abcdefghijklmnopqrstuvwxyz')

globkeys = globals().keys()
globkeys.append('globkeys') # because name 'globkeys' is now also in globals()

print 'globkeys==',globkeys
print
print "globals().keys()==",globals().keys()

for i in xrange(8):
    globals()[''.join(random.sample(alphabet,random.randint(3,26)))] = random.choice(alphabet)
del i

newnames = [ x for x in globals().keys() if x not in globkeys ]
print
print 'newnames==',newnames

print
print "globals().keys()==",globals().keys()

print
print '\n'.join(repr((u,globals()[u])) for u in newnames)

Result

globkeys== ['__builtins__', 'alphabet', 'random', '__package__', '__name__', '__doc__', 'globkeys']

globals().keys()== ['__builtins__', 'alphabet', 'random', '__package__', '__name__', 'globkeys', '__doc__']

newnames== ['fztkebyrdwcigsmulnoaph', 'umkfcvztleoij', 'kbutmzfgpcdqanrivwsxly', 'lxzmaysuornvdpjqfetbchgik', 'wznptbyermclfdghqxjvki', 'lwg', 'vsolxgkz', 'yobtlkqh']

globals().keys()== ['fztkebyrdwcigsmulnoaph', 'umkfcvztleoij', 'newnames', 'kbutmzfgpcdqanrivwsxly', '__builtins__', 'alphabet', 'random', 'lxzmaysuornvdpjqfetbchgik', '__package__', 'wznptbyermclfdghqxjvki', 'lwg', 'x', 'vsolxgkz', '__name__', 'globkeys', '__doc__', 'yobtlkqh']

('fztkebyrdwcigsmulnoaph', 't')
('umkfcvztleoij', 'p')
('kbutmzfgpcdqanrivwsxly', 'a')
('lxzmaysuornvdpjqfetbchgik', 'n')
('wznptbyermclfdghqxjvki', 't')
('lwg', 'j')
('vsolxgkz', 'w')
('yobtlkqh', 'c')

Another way:

import random

pool_of_names = []
for i in xrange(1000):
    v = 'LXM'+str(random.randrange(10,100000))
    if v not in globals():
        pool_of_names.append(v)

alphabet = 'abcdefghijklmnopqrstuvwxyz' 

print 'globals().keys()==',globals().keys()

print
for j in xrange(8):
    globals()[pool_of_names[j]] = random.choice(alphabet)
newnames = pool_of_names[0:j+1]

print
print 'globals().keys()==',globals().keys()

print
print '\n'.join(repr((u,globals()[u])) for u in newnames)

result:

globals().keys()== ['__builtins__', 'alphabet', 'random', '__package__', 'i', 'v', '__name__', '__doc__', 'pool_of_names']


globals().keys()== ['LXM7646', 'random', 'newnames', 'LXM95826', 'pool_of_names', 'LXM66380', 'alphabet', 'LXM84070', '__package__', 'LXM8644', '__doc__', 'LXM33579', '__builtins__', '__name__', 'LXM58418', 'i', 'j', 'LXM24703', 'v']

('LXM66380', 'v')
('LXM7646', 'a')
('LXM8644', 'm')
('LXM24703', 'r')
('LXM58418', 'g')
('LXM84070', 'c')
('LXM95826', 'e')
('LXM33579', 'j')

How do you get the length of a list in the JSF expression language?

After 7 years... the facelets solution still works fine for me as a jsf user

include the namespace as xmlns:fn="http://java.sun.com/jsp/jstl/functions"

and use the EL as #{fn:length(myBean.someList)} for example if using in jsf ui:fragment below example works fine

<ui:fragment rendered="#{fn:length(myBean.someList) gt 0}">
    <!-- Do something here-->
</ui:fragment>

Big-oh vs big-theta

I'm a mathematician and I have seen and needed big-O O(n), big-Theta T(n), and big-Omega O(n) notation time and again, and not just for complexity of algorithms. As people said, big-Theta is a two-sided bound. Strictly speaking, you should use it when you want to explain that that is how well an algorithm can do, and that either that algorithm can't do better or that no algorithm can do better. For instance, if you say "Sorting requires T(n(log n)) comparisons for worst-case input", then you're explaining that there is a sorting algorithm that uses O(n(log n)) comparisons for any input; and that for every sorting algorithm, there is an input that forces it to make O(n(log n)) comparisons.

Now, one narrow reason that people use O instead of O is to drop disclaimers about worst or average cases. If you say "sorting requires O(n(log n)) comparisons", then the statement still holds true for favorable input. Another narrow reason is that even if one algorithm to do X takes time T(f(n)), another algorithm might do better, so you can only say that the complexity of X itself is O(f(n)).

However, there is a broader reason that people informally use O. At a human level, it's a pain to always make two-sided statements when the converse side is "obvious" from context. Since I'm a mathematician, I would ideally always be careful to say "I will take an umbrella if and only if it rains" or "I can juggle 4 balls but not 5", instead of "I will take an umbrella if it rains" or "I can juggle 4 balls". But the other halves of such statements are often obviously intended or obviously not intended. It's just human nature to be sloppy about the obvious. It's confusing to split hairs.

Unfortunately, in a rigorous area such as math or theory of algorithms, it's also confusing not to split hairs. People will inevitably say O when they should have said O or T. Skipping details because they're "obvious" always leads to misunderstandings. There is no solution for that.

Pandas split DataFrame by column value

Using "groupby" and list comprehension:

Storing all the split dataframe in list variable and accessing each of the seprated dataframe by their index.

DF = pd.DataFrame({'chr':["chr3","chr3","chr7","chr6","chr1"],'pos':[10,20,30,40,50],})
ans = [pd.DataFrame(y) for x, y in DF.groupby('chr', as_index=False)]

accessing the separated DF like this:

ans[0]
ans[1]
ans[len(ans)-1] # this is the last separated DF

accessing the column value of the separated DF like this:

ansI_chr=ans[i].chr 

What is the minimum I have to do to create an RPM file?

As an application distributor, fpm sounds perfect for your needs. There is an example here which shows how to package an app from source. FPM can produce both deb files and RPM files.

Is it possible to "decompile" a Windows .exe? Or at least view the Assembly?

You may get some information viewing it in assembly, but I think the easiest thing to do is fire up a virtual machine and see what it does. Make sure you have no open shares or anything like that that it can jump through though ;)

How to check programmatically if an application is installed or not in Android?

Try this

This code is used to check weather your application with package name is installed or not if not then it will open playstore link of your app otherwise your installed app

String your_apppackagename="com.app.testing";
    PackageManager packageManager = getPackageManager();
    ApplicationInfo applicationInfo = null;
    try {
        applicationInfo = packageManager.getApplicationInfo(your_apppackagename, 0);
    } catch (PackageManager.NameNotFoundException e) {
        e.printStackTrace();
    }
    if (applicationInfo == null) {
        // not installed it will open your app directly on playstore
        startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse("https://play.google.com/store/apps/details?id=" + your_apppackagename)));
    } else {
        // Installed
        Intent LaunchIntent = packageManager.getLaunchIntentForPackage(your_apppackagename);
        startActivity( LaunchIntent );
    }

How to upgrade glibc from version 2.13 to 2.15 on Debian?

Your script contains errors as well, for example if you have dos2unix installed your install works but if you don't like I did then it will fail with dependency issues.

I found this by accident as I was making a script file of this to give to my friend who is new to Linux and because I made the scripts on windows I directed him to install it, at the time I did not have dos2unix installed thus I got errors.

here is a copy of the script I made for your solution but have dos2unix installed.

#!/bin/sh
echo "deb http://ftp.debian.org/debian sid main" >> /etc/apt/sources.list
apt-get update
apt-get -t sid install libc6 libc6-dev libc6-dbg
echo "Please remember to hash out sid main from your sources list. /etc/apt/sources.list"

this script has been tested on 3 machines with no errors.

How to get the file path from HTML input form in Firefox 3

This is an example that could work for you if what you need is not exactly the path, but a reference to the file working offline.

http://www.ab-d.fr/date/2008-07-12/

It is in french, but the code is javascript :)

This are the references the article points to: http://developer.mozilla.org/en/nsIDOMFile http://developer.mozilla.org/en/nsIDOMFileList

Uninstall Node.JS using Linux command line?

Best way to go around this is to do it right from the BEGINNING:

INSTALL BREW

#HERE IS HOW: PASTE IN TERMINAL

sudo apt-get install build-essential curl git m4 ruby texinfo libbz2-dev libcurl4-openssl-dev libexpat-dev libncurses-dev zlib1g-dev

ruby -e "$(curl -fsSL https://raw.githubusercontent.com/Homebrew/linuxbrew/go/install)"

Then at the end of your .bashrc file(In your home directory press Ctrl + H)

export PATH="$HOME/.linuxbrew/bin:$PATH"
export MANPATH="$HOME/.linuxbrew/share/man:$MANPATH"
export INFOPATH="$HOME/.linuxbrew/share/info:$INFOPATH"

Then restart terminal so the modification to .bashrc are reloaded

TO INSTALL NODE

brew install node

TO CHECK VERSION

node -v
npm -v

TO UPDATE NODE

brew update
brew upgrade node

TO UNINSTALL NODE

brew uninstall node

Replace last occurrence of a string in a string

A short version:

$NewString = substr_replace($String,$Replacement,strrpos($String,$Replace),strlen($Replace));

How to format a date using ng-model?

Here is very handy directive angular-datetime. You can use it like this:

<input type="text" datetime="yyyy-MM-dd HH:mm:ss" ng-model="myDate">

It also add mask to your input and perform validation.

Linux Command History with date and time

Try this:

> HISTTIMEFORMAT="%d/%m/%y %T "

> history

You can adjust the format to your liking, of course.

setting JAVA_HOME & CLASSPATH in CentOS 6

I had to change /etc/profile.d/java_env.sh to point to the new path and then logout/login.

keytool error Keystore was tampered with, or password was incorrect

For me I solved it by changing passwords from Arabic letter to English letter, but first I went to the folder and deleted the generated key then it works.

How to test an Internet connection with bash?

Pong doesn't mean web service on the server is running; it merely means that server is replying to ICMP echo. I would recommend using curl and check its return value.

How to parseInt in Angular.js

You cannot (at least at the moment) use parseInt inside angular expressions, as they're not evaluated directly. Quoting the doc:

Angular does not use JavaScript's eval() to evaluate expressions. Instead Angular's $parse service processes these expressions.

Angular expressions do not have access to global variables like window, document or location. This restriction is intentional. It prevents accidental access to the global state – a common source of subtle bugs.

So you can define a total() method in your controller, then use it in the expression:

// ... somewhere in controller
$scope.total = function() { 
  return parseInt($scope.num1) + parseInt($scope.num2) 
}

// ... in HTML
Total: {{ total() }}

Still, that seems to be rather bulky for a such a simple operation as adding the numbers. The alternative is converting the results with -0 op:

Total: {{num1-0 + (num2-0)|number}}

... but that'll obviously won't parseInt values, only cast them to Numbers (|number filter prevents showing null if this cast results in NaN). So choose the approach that suits your particular case.

fatal: This operation must be run in a work tree

You repository is bare, i.e. it does not have a working tree attached to it. You can clone it locally to create a working tree for it, or you could use one of several other options to tell Git where the working tree is, e.g. the --work-tree option for single commands, or the GIT_WORK_TREE environment variable. There is also the core.worktree configuration option but it will not work in a bare repository (check the man page for what it does).

# git --work-tree=/path/to/work/tree checkout master
# GIT_WORK_TREE=/path/to/work/tree git status

How to set Linux environment variables with Ansible

This is the best option. As said Michal Gasek (first answer), since the pull request was merged (https://github.com/ansible/ansible/pull/8651), we are able to set permanent environment variables easily by play level.

- hosts: all
  roles:
     - php
     - nginx
  environment:
    MY_ENV_VARIABLE: whatever_value

sed whole word search and replace

Use \b for word boundaries:

sed -i 's/\boldtext\b/newtext/g' <file>

How many files can I put in a directory?

I recall running a program that was creating a huge amount of files at the output. The files were sorted at 30000 per directory. I do not recall having any read problems when I had to reuse the produced output. It was on an 32-bit Ubuntu Linux laptop, and even Nautilus displayed the directory contents, albeit after a few seconds.

ext3 filesystem: Similar code on a 64-bit system dealt well with 64000 files per directory.

How can I align text directly beneath an image?

Your HTML:

<div class="img-with-text">
    <img src="yourimage.jpg" alt="sometext" />
    <p>Some text</p>
</div>

If you know the width of your image, your CSS:

.img-with-text {
    text-align: justify;
    width: [width of img];
}

.img-with-text img {
    display: block;
    margin: 0 auto;
}

Otherwise your text below the image will free-flow. To prevent this, just set a width to your container.

C# : 'is' keyword and checking for Not

You can do it this way:

object a = new StreamWriter("c:\\temp\\test.txt");

if (a is TextReader == false)
{
   Console.WriteLine("failed");
}

How to run Pip commands from CMD

Firstly make sure that you have installed python 2.7 or higher

Open Command Prompt as administrator and change directory to python and then change directory to Scripts by typing cd Scripts then type pip.exe and now you can install modules Step by Step:

  • Open Cmd

  • type in "cd \" and then enter

  • type in "cd python2.7" and then enter

Note that my python version is 2.7 so my directory is that so use your python folder here...

  • type in "cd Scripts" and enter

  • Now enter this "pip.exe"

  • Now it prompts you to install modules

Convert string to date in Swift

  • Convert the ISO8601 string to date

    let isoDate = "2016-04-14T10:44:00+0000"
    
    let dateFormatter = DateFormatter()
    dateFormatter.locale = Locale(identifier: "en_US_POSIX") // set locale to reliable US_POSIX
    dateFormatter.dateFormat = "yyyy-MM-dd'T'HH:mm:ssZ"
    let date = dateFormatter.date(from:isoDate)!
    
  • Get the date components for year, month, day and hour from the date

    let calendar = Calendar.current
    let components = calendar.dateComponents([.year, .month, .day, .hour], from: date)
    
  • Finally create a new Date object and strip minutes and seconds

    let finalDate = calendar.date(from:components)
    

Consider also the convenience formatter ISO8601DateFormatter introduced in iOS 10 / macOS 12:

let isoDate = "2016-04-14T10:44:00+0000"

let dateFormatter = ISO8601DateFormatter()
let date = dateFormatter.date(from:isoDate)!

RecyclerView - Get view at particular position

You can as well do this, this will help when you want to modify a view after clicking a recyclerview position item

@Override
public void onClick(View view, int position) {

            View v =  rv_notifications.getChildViewHolder(view).itemView;
            TextView content = v.findViewById(R.id.tv_content);
            content.setText("Helloo");

        }

How to execute IN() SQL queries with Spring's JDBCTemplate effectively?

You want a parameter source:

Set<Integer> ids = ...;

MapSqlParameterSource parameters = new MapSqlParameterSource();
parameters.addValue("ids", ids);

List<Foo> foo = getJdbcTemplate().query("SELECT * FROM foo WHERE a IN (:ids)",
     parameters, getRowMapper());

This only works if getJdbcTemplate() returns an instance of type NamedParameterJdbcTemplate

Is log(n!) = T(n·log(n))?

http://en.wikipedia.org/wiki/Stirling%27s_approximation Stirling approximation might help you. It is really helpful in dealing with problems on factorials related to huge numbers of the order of 10^10 and above.

enter image description here

Pandas: Return Hour from Datetime Column Directly

Since the quickest, shortest answer is in a comment (from Jeff) and has a typo, here it is corrected and in full:

sales['time_hour'] = pd.DatetimeIndex(sales['timestamp']).hour

Fastest way to iterate over all the chars in a String

Just for curiosity and to compare with Saint Hill's answer.

If you need to process heavy data you should not use JVM in client mode. Client mode is not made for optimizations.

Let's compare results of @Saint Hill benchmarks using a JVM in Client mode and Server mode.

Core2Quad Q6600 G0 @ 2.4GHz
JavaSE 1.7.0_40

See also: Real differences between "java -server" and "java -client"?


CLIENT MODE:

len =      2:    111k charAt(i),  105k cbuff[i],   62k new[i],   17k field access.   (chars/ms) 
len =      4:    285k charAt(i),  166k cbuff[i],  114k new[i],   43k field access.   (chars/ms) 
len =      6:    315k charAt(i),  230k cbuff[i],  162k new[i],   69k field access.   (chars/ms) 
len =      8:    333k charAt(i),  275k cbuff[i],  181k new[i],   85k field access.   (chars/ms) 
len =     12:    342k charAt(i),  342k cbuff[i],  222k new[i],  117k field access.   (chars/ms) 
len =     16:    363k charAt(i),  347k cbuff[i],  275k new[i],  152k field access.   (chars/ms) 
len =     20:    363k charAt(i),  392k cbuff[i],  289k new[i],  180k field access.   (chars/ms) 
len =     24:    375k charAt(i),  428k cbuff[i],  311k new[i],  205k field access.   (chars/ms) 
len =     28:    378k charAt(i),  474k cbuff[i],  341k new[i],  233k field access.   (chars/ms) 
len =     32:    376k charAt(i),  492k cbuff[i],  340k new[i],  251k field access.   (chars/ms) 
len =     64:    374k charAt(i),  551k cbuff[i],  374k new[i],  367k field access.   (chars/ms) 
len =    128:    385k charAt(i),  624k cbuff[i],  415k new[i],  509k field access.   (chars/ms) 
len =    256:    390k charAt(i),  675k cbuff[i],  436k new[i],  619k field access.   (chars/ms) 
len =    512:    394k charAt(i),  703k cbuff[i],  439k new[i],  695k field access.   (chars/ms) 
len =   1024:    395k charAt(i),  718k cbuff[i],  462k new[i],  742k field access.   (chars/ms) 
len =   2048:    396k charAt(i),  725k cbuff[i],  471k new[i],  767k field access.   (chars/ms) 
len =   4096:    396k charAt(i),  727k cbuff[i],  459k new[i],  780k field access.   (chars/ms) 
len =   8192:    397k charAt(i),  712k cbuff[i],  446k new[i],  772k field access.   (chars/ms) 

SERVER MODE:

len =      2:     86k charAt(i),   41k cbuff[i],   46k new[i],   80k field access.   (chars/ms) 
len =      4:    571k charAt(i),  250k cbuff[i],   97k new[i],  222k field access.   (chars/ms) 
len =      6:    666k charAt(i),  333k cbuff[i],  125k new[i],  315k field access.   (chars/ms) 
len =      8:    800k charAt(i),  400k cbuff[i],  181k new[i],  380k field access.   (chars/ms) 
len =     12:    800k charAt(i),  521k cbuff[i],  260k new[i],  545k field access.   (chars/ms) 
len =     16:    800k charAt(i),  592k cbuff[i],  296k new[i],  640k field access.   (chars/ms) 
len =     20:    800k charAt(i),  666k cbuff[i],  408k new[i],  800k field access.   (chars/ms) 
len =     24:    800k charAt(i),  705k cbuff[i],  452k new[i],  800k field access.   (chars/ms) 
len =     28:    777k charAt(i),  736k cbuff[i],  368k new[i],  933k field access.   (chars/ms) 
len =     32:    800k charAt(i),  780k cbuff[i],  571k new[i],  969k field access.   (chars/ms) 
len =     64:    800k charAt(i),  901k cbuff[i],  800k new[i],  1306k field access.   (chars/ms) 
len =    128:    1084k charAt(i),  888k cbuff[i],  633k new[i],  1620k field access.   (chars/ms) 
len =    256:    1122k charAt(i),  966k cbuff[i],  729k new[i],  1790k field access.   (chars/ms) 
len =    512:    1163k charAt(i),  1007k cbuff[i],  676k new[i],  1910k field access.   (chars/ms) 
len =   1024:    1179k charAt(i),  1027k cbuff[i],  698k new[i],  1954k field access.   (chars/ms) 
len =   2048:    1184k charAt(i),  1043k cbuff[i],  732k new[i],  2007k field access.   (chars/ms) 
len =   4096:    1188k charAt(i),  1049k cbuff[i],  742k new[i],  2031k field access.   (chars/ms) 
len =   8192:    1157k charAt(i),  1032k cbuff[i],  723k new[i],  2048k field access.   (chars/ms) 

CONCLUSION:

As you can see, server mode is much faster.

How many significant digits do floats and doubles have in java?

Floating point numbers are encoded using an exponential form, that is something like m * b ^ e, i.e. not like integers at all. The question you ask would be meaningful in the context of fixed point numbers. There are numerous fixed point arithmetic libraries available.

Regarding floating point arithmetic: The number of decimal digits depends on the presentation and the number system. For example there are periodic numbers (0.33333) which do not have a finite presentation in decimal but do have one in binary and vice versa.

Also it is worth mentioning that floating point numbers up to a certain point do have a difference larger than one, i.e. value + 1 yields value, since value + 1 can not be encoded using m * b ^ e, where m, b and e are fixed in length. The same happens for values smaller than 1, i.e. all the possible code points do not have the same distance.

Because of this there is no precision of exactly n digits like with fixed point numbers, since not every number with n decimal digits does have a IEEE encoding.

There is a nearly obligatory document which you should read then which explains floating point numbers: What every computer scientist should know about floating point arithmetic.

Maven:Failed to execute goal org.apache.maven.plugins:maven-resources-plugin:2.7:resources

in my case, it was a confilict with IntelliJ , I've resolved it by building the project from command line and it worked!

How to set the title of UIButton as left alignment?

Swift 5.1

self.btnPro.titleLabel?.textAlignment = .left

phpmyadmin #1045 Cannot log in to the MySQL server. after installing mysql command line client

After like three (3) hours of google..ing.This is the solution to the problem: First, I run this command;

$mysqladmin -u root -p[your root password here] version Which outputs:

    Copyright (c) 2000, 2016, Oracle and/or its affiliates. All rights reserved.

    Oracle is a registered trademark of Oracle Corporation and/or its
    affiliates. Other names may be trademarks of their respective
    owners.

    Server version      5.5.49-0ubuntu0.14.04.1
    Protocol version    10
    Connection      Localhost via UNIX socket
    UNIX socket     /var/run/mysqld/mysqld.sock
    Uptime:         1 hour 54 min 3 sec

Finally, I changed the connect_type parameter from tcp to socket and added the parameter socket in config.inc.php:

    $cfg['Servers'][$i]['host'] = 'localhost';
    $cfg['Servers'][$i]['connect_type'] = 'socket';
    $cfg['Servers'][$i]['socket'] = '/var/run/mysqld/mysqld.sock';

All credit goes to this person: This is the correct solution

jQuery - Call ajax every 10 seconds

This worked for me

setInterval(ajax_query, 10000);

function ajax_query(){
   //Call ajax here
}

Jquery to get the id of selected value from dropdown

First set a custom attribute into your option for example nameid (you can set non-standardized attribute of an HTML element, it's allowed):

'<option nameid= "' + n.id + "' value="' + i + '">' + n.names + '</option>'

then you can easily get attribute value using jquery .attr() :

$('option:selected').attr("nameid")

For Example:

<select id="jobSel" class="longcombo" onchange="GetNameId">
    <option nameid="32" value="1">test1</option>
    <option nameid="67" value="1">test2</option>
    <option nameid="45" value="1">test3</option>    
    </select>    

Jquery:

function GetNameId(){
   alert($('#jobSel option:selected').attr("nameid"));
}

How to upgrade R in ubuntu?

Since R is already installed, you should be able to upgrade it with this method. First of all, you may want to have the packages you installed in the previous version in the new one,so it is convenient to check this post. Then, follow the instructions from here

  1. Open the sources.list file:

     sudo nano /etc/apt/sources.list    
    
  2. Add a line with the source from where the packages will be retrieved. For example:

     deb https://cloud.r-project.org/bin/linux/ubuntu/ version/
    

    Replace https://cloud.r-project.org with whatever mirror you would like to use, and replace version/ with whatever version of Ubuntu you are using (eg, trusty/, xenial/, and so on). If you're getting a "Malformed line error", check to see if you have a space between /ubuntu/ and version/.

  3. Fetch the secure APT key:

     gpg --keyserver keyserver.ubuntu.com --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
    

or

    gpg --hkp://keyserver keyserver.ubuntu.com:80 --recv-key E298A3A825C0D65DFD57CBB651716619E084DAB9
  1. Add it to keyring:

     gpg -a --export E084DAB9 | sudo apt-key add -
    
  2. Update your sources and upgrade your installation:

     sudo apt-get update && sudo apt-get upgrade
    
  3. Install the new version

     sudo apt-get install r-base-dev
    
  4. Recover your old packages following the solution that best suits to you (see this). For instance, to recover all the packages (not only those from CRAN) the idea is:

-- copy the packages from R-oldversion/library to R-newversion/library, (do not overwrite a package if it already exists in the new version!).

-- Run the R command update.packages(checkBuilt=TRUE, ask=FALSE).

Getting date format m-d-Y H:i:s.u from milliseconds

echo date('m-d-Y H:i:s').substr(fmod(microtime(true), 1), 1);

example output:

02-06-2019 16:45:03.53811192512512

If you have a need to limit the number of decimal places then the below line (credit mgutt) would be a good alternative. (With the code below, the 6 limits the number of decimal places to 6.)

echo date('m-d-Y H:i:').sprintf('%09.6f', date('s')+fmod(microtime(true), 1));

example output:

02-11-2019 15:33:03.624493

Get loop count inside a Python FOR loop

Using zip function we can get both element and index.

countries = ['Pakistan','India','China','Russia','USA']

for index, element zip(range(0,countries),countries):

         print('Index : ',index)
         print(' Element : ', element,'\n')

output : Index : 0 Element : Pakistan ...

See also :

Python.org

Using LIMIT within GROUP BY to get N results per group?

The following post: sql: selcting top N record per group describes the complicated way of achieving this without subqueries.

It improves on other solutions offered here by:

  • Doing everything in a single query
  • Being able to properly utilize indexes
  • Avoiding subqueries, notoriously known to produce bad execution plans in MySQL

It is however not pretty. A good solution would be achievable were Window Functions (aka Analytic Functions) enabled in MySQL -- but they are not. The trick used in said post utilizes GROUP_CONCAT, which is sometimes described as "poor man's Window Functions for MySQL".

Vertically align text to top within a UILabel

If you are using autolayout, set the vertical contentHuggingPriority to 1000, either in code or IB. In IB you may then have to remove a height constraint by setting it's priority to 1 and then deleting it.

What does 'super' do in Python?

Doesn't all of this assume that the base class is a new-style class?

class A:
    def __init__(self):
        print("A.__init__()")

class B(A):
    def __init__(self):
        print("B.__init__()")
        super(B, self).__init__()

Will not work in Python 2. class A must be new-style, i.e: class A(object)

Why does integer division in C# return an integer and not a float?

Since you don't use any suffix, the literals 13 and 4 are interpreted as integer:

Manual:

If the literal has no suffix, it has the first of these types in which its value can be represented: int, uint, long, ulong.

Thus, since you declare 13 as integer, integer division will be performed:

Manual:

For an operation of the form x / y, binary operator overload resolution is applied to select a specific operator implementation. The operands are converted to the parameter types of the selected operator, and the type of the result is the return type of the operator.

The predefined division operators are listed below. The operators all compute the quotient of x and y.

Integer division:

int operator /(int x, int y);
uint operator /(uint x, uint y);
long operator /(long x, long y);
ulong operator /(ulong x, ulong y);

And so rounding down occurs:

The division rounds the result towards zero, and the absolute value of the result is the largest possible integer that is less than the absolute value of the quotient of the two operands. The result is zero or positive when the two operands have the same sign and zero or negative when the two operands have opposite signs.

If you do the following:

int x = 13f / 4f;

You'll receive a compiler error, since a floating-point division (the / operator of 13f) results in a float, which cannot be cast to int implicitly.

If you want the division to be a floating-point division, you'll have to make the result a float:

float x = 13 / 4;

Notice that you'll still divide integers, which will implicitly be cast to float: the result will be 3.0. To explicitly declare the operands as float, using the f suffix (13f, 4f).

Pods stuck in Terminating status

Force delete the pod:

kubectl delete pod --grace-period=0 --force --namespace <NAMESPACE> <PODNAME>

The --force flag is mandatory.

Creating dummy variables in pandas for python

Handling categorical features scikit-learn expects all features to be numeric. So how do we include a categorical feature in our model?

Ordered categories: transform them to sensible numeric values (example: small=1, medium=2, large=3) Unordered categories: use dummy encoding (0/1) What are the categorical features in our dataset?

Ordered categories: weather (already encoded with sensible numeric values) Unordered categories: season (needs dummy encoding), holiday (already dummy encoded), workingday (already dummy encoded) For season, we can't simply leave the encoding as 1 = spring, 2 = summer, 3 = fall, and 4 = winter, because that would imply an ordered relationship. Instead, we create multiple dummy variables:

# An utility function to create dummy variable
`def create_dummies( df, colname ):
col_dummies = pd.get_dummies(df[colname], prefix=colname)
col_dummies.drop(col_dummies.columns[0], axis=1, inplace=True)
df = pd.concat([df, col_dummies], axis=1)
df.drop( colname, axis = 1, inplace = True )
return df`

Git: How to update/checkout a single file from remote origin master?

Following code worked for me:

     git fetch
     git checkout <branch from which file needs to be fetched> <filepath> 

Powershell 2 copy-item which creates a folder if doesn't exist

Yes, add the -Force parameter.

copy-item $from $to -Recurse -Force

How can I dynamically switch web service addresses in .NET without a recompile?

If you are fetching the URL from a database you can manually assign it to the web service proxy class URL property. This should be done before calling the web method.

If you would like to use the config file, you can set the proxy classes URL behavior to dynamic.

Executing "SELECT ... WHERE ... IN ..." using MySQLdb

Have been trying every variation on João's solution to get an IN List query to work with Tornado's mysql wrapper, and was still getting the accursed "TypeError: not enough arguments for format string" error. Turns out adding "*" to the list var "*args" did the trick.

args=['A', 'C']
sql='SELECT fooid FROM foo WHERE bar IN (%s)'
in_p=', '.join(list(map(lambda x: '%s', args)))
sql = sql % in_p
db.query(sql, *args)

How to calculate the sentence similarity using word2vec model of gensim with python

Once you compute the sum of the two sets of word vectors, you should take the cosine between the vectors, not the diff. The cosine can be computed by taking the dot product of the two vectors normalized. Thus, the word count is not a factor.

Super-simple example of C# observer/observable with delegates

In this model, you have publishers who will do some logic and publish an "event."
Publishers will then send out their event only to subscribers who have subscribed to receive the specific event.

In C#, any object can publish a set of events to which other applications can subscribe.
When the publishing class raises an event, all the subscribed applications are notified.
The following figure shows this mechanism.

enter image description here

Simplest Example possible on Events and Delegates in C#:

code is self explanatory, Also I've added the comments to clear out the code.

  using System;

public class Publisher //main publisher class which will invoke methods of all subscriber classes
{
    public delegate void TickHandler(Publisher m, EventArgs e); //declaring a delegate
    public TickHandler Tick;     //creating an object of delegate
    public EventArgs e = null;   //set 2nd paramter empty
    public void Start()     //starting point of thread
    {
        while (true)
        {
            System.Threading.Thread.Sleep(300);
            if (Tick != null)   //check if delegate object points to any listener classes method
            {
                Tick(this, e);  //if it points i.e. not null then invoke that method!
            }
        }
    }
}

public class Subscriber1                //1st subscriber class
{
    public void Subscribe(Publisher m)  //get the object of pubisher class
    {
        m.Tick += HeardIt;              //attach listener class method to publisher class delegate object
    }
    private void HeardIt(Publisher m, EventArgs e)   //subscriber class method
    {
        System.Console.WriteLine("Heard It by Listener");
    }

}
public class Subscriber2                   //2nd subscriber class
{
    public void Subscribe2(Publisher m)    //get the object of pubisher class
    {
        m.Tick += HeardIt;               //attach listener class method to publisher class delegate object
    }
    private void HeardIt(Publisher m, EventArgs e)   //subscriber class method
    {
        System.Console.WriteLine("Heard It by Listener2");
    }

}

class Test
{
    static void Main()
    {
        Publisher m = new Publisher();      //create an object of publisher class which will later be passed on subscriber classes
        Subscriber1 l = new Subscriber1();  //create object of 1st subscriber class
        Subscriber2 l2 = new Subscriber2(); //create object of 2nd subscriber class
        l.Subscribe(m);     //we pass object of publisher class to access delegate of publisher class
        l2.Subscribe2(m);   //we pass object of publisher class to access delegate of publisher class

        m.Start();          //starting point of publisher class
    }
}

Output:

Heard It by Listener

Heard It by Listener2

Heard It by Listener

Heard It by Listener2

Heard It by Listener . . . (infinite times)

Windows 7 - Add Path

I founded the problem: Just insert the folder without the executable file.
so Instead of:

C:\Program Files (x86)\SumatraPDF\SumatraPDF.exe

you have to write this:

C:\Program Files (x86)\SumatraPDF\

Split function in oracle to comma separated values with automatic sequence

Use this 'Split' function:

CREATE OR REPLACE FUNCTION Split (p_str varchar2) return sys_refcursor is
v_res sys_refcursor;

begin
  open v_res for 
  WITH TAB AS 
  (SELECT p_str STR FROM DUAL)
  select substr(STR, instr(STR, ',', 1, lvl) + 1, instr(STR, ',', 1, lvl + 1) - instr(STR, ',', 1, lvl) - 1) name 
  from
    ( select ',' || STR || ',' as STR from TAB ),
    ( select level as lvl from dual connect by level <= 100 )
    where lvl <= length(STR) - length(replace(STR, ',')) - 1;

     return v_res;
   end;

You can't use this function in select statement like you described in question, but I hope you will find it still useful.

EDIT: Here are steps you need to do. 1. Create Object: create or replace type empy_type as object(value varchar2(512)) 2. Create Type: create or replace type t_empty_type as table of empy_type 3. Create Function:

CREATE OR REPLACE FUNCTION Split (p_str varchar2) return sms.t_empty_type is
v_emptype t_empty_type := t_empty_type();
v_cnt     number := 0;
v_res sys_refcursor;
v_value nvarchar2(128);
begin
  open v_res for
  WITH TAB AS
  (SELECT p_str STR FROM DUAL)
  select substr(STR, instr(STR, ',', 1, lvl) + 1, instr(STR, ',', 1, lvl +     1) - instr(STR, ',', 1, lvl) - 1) name
  from
    ( select ',' || STR || ',' as STR from TAB ),
    ( select level as lvl from dual connect by level <= 100 )
    where lvl <= length(STR) - length(replace(STR, ',')) - 1;


  loop
     fetch v_res into v_value;
      exit when v_res%NOTFOUND;
      v_emptype.extend;
      v_cnt := v_cnt + 1;
     v_emptype(v_cnt) := empty_type(v_value);
    end loop;
    close v_res;

    return v_emptype;
end;

Then just call like this:

SELECT * FROM (TABLE(split('a,b,c,d,g'))) 

How to get Printer Info in .NET?

As dowski suggested, you could use WMI to get printer properties. The following code displays all properties for a given printer name. Among them you will find: PrinterStatus, Comment, Location, DriverName, PortName, etc.

using System.Management;

...

string printerName = "YourPrinterName";
string query = string.Format("SELECT * from Win32_Printer WHERE Name LIKE '%{0}'", printerName);

using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
using (ManagementObjectCollection coll = searcher.Get())
{
    try
    {
        foreach (ManagementObject printer in coll)
        {
            foreach (PropertyData property in printer.Properties)
            {
                Console.WriteLine(string.Format("{0}: {1}", property.Name, property.Value));
            }
        }
    }
    catch (ManagementException ex)
    {
        Console.WriteLine(ex.Message);
    }
}

How can I get just the first row in a result set AFTER ordering?

In 12c, here's the new way:

select bla
  from bla
 where bla
 order by finaldate desc
 fetch first 1 rows only; 

How nice is that!

JOptionPane Input to int

Please note that Integer.parseInt throws an NumberFormatException if the passed string doesn't contain a parsable string.

Excel error HRESULT: 0x800A03EC while trying to get range with cell's name

I got the error with a space in a Sheet Name:

using (var range = _excelApp.Range["Sheet Name Had Space!$A$1"].WithComCleanup())

I fixed it by putting single quotes around Sheet Names with spaces:

using (var range = _excelApp.Range["'Sheet Name Had Space'!$A$1"].WithComCleanup())

Convert list to tuple in Python

You might have done something like this:

>>> tuple = 45, 34  # You used `tuple` as a variable here
>>> tuple
(45, 34)
>>> l = [4, 5, 6]
>>> tuple(l)   # Will try to invoke the variable `tuple` rather than tuple type.

Traceback (most recent call last):
  File "<pyshell#10>", line 1, in <module>
    tuple(l)
TypeError: 'tuple' object is not callable
>>>
>>> del tuple  # You can delete the object tuple created earlier to make it work
>>> tuple(l)
(4, 5, 6)

Here's the problem... Since you have used a tuple variable to hold a tuple (45, 34) earlier... So, now tuple is an object of type tuple now...

It is no more a type and hence, it is no more Callable.

Never use any built-in types as your variable name... You do have any other name to use. Use any arbitrary name for your variable instead...

'this' implicitly has type 'any' because it does not have a type annotation

The error is indeed fixed by inserting this with a type annotation as the first callback parameter. My attempt to do that was botched by simultaneously changing the callback into an arrow-function:

foo.on('error', (this: Foo, err: any) => { // DON'T DO THIS

It should've been this:

foo.on('error', function(this: Foo, err: any) {

or this:

foo.on('error', function(this: typeof foo, err: any) {

A GitHub issue was created to improve the compiler's error message and highlight the actual grammar error with this and arrow-functions.

Using "like" wildcard in prepared statement

Code it like this:

PreparedStatement pstmt = con.prepareStatement(
    "SELECT * FROM analysis WHERE notes like ?");
pstmt.setString(1, notes + "%");`

Make sure that you DO NOT include the quotes ' ' like below as they will cause an exception.

pstmt.setString(1,"'%"+ notes + "%'");

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

To add to the existing answers, you can avoid affecting the URL by overriding the link with JavaScript. This will still take you to the top of the page without JavaScript, but will append # to the URL.

<a href="#" onclick="document.body.scrollTop=0;document.documentElement.scrollTop=0;event.preventDefault()">Back to top</a>

Getting each individual digit from a whole integer

You use the modulo operator:

while(score)
{
    printf("%d\n", score % 10);
    score /= 10;
}

Note that this will give you the digits in reverse order (i.e. least significant digit first). If you want the most significant digit first, you'll have to store the digits in an array, then read them out in reverse order.

How to edit log message already committed in Subversion?

svnadmin setlog /path/to/repository -r revision_number --bypass-hooks message_file.txt

What is JNDI? What is its basic use? When is it used?

JNDI in layman's terms is basically an Interface for being able to get instances of internal/External resources such as

  javax.sql.DataSource, 
  javax.jms.Connection-Factory,
  javax.jms.QueueConnectionFactory,
  javax.jms.TopicConnectionFactory,
  javax.mail.Session, java.net.URL,
  javax.resource.cci.ConnectionFactory,

or any other type defined by a JCA resource adapter. It provides a syntax in being able to create access whether they are internal or external. i.e (comp/env in this instance means where component/environment, there are lots of other syntax):

jndiContext.lookup("java:comp/env/persistence/customerDB");

Change / Add syntax highlighting for a language in Sublime 2/3

Syntax highlighting is controlled by the theme you use, accessible through Preferences -> Color Scheme. Themes highlight different keywords, functions, variables, etc. through the use of scopes, which are defined by a series of regular expressions contained in a .tmLanguage file in a language's directory/package. For example, the JavaScript.tmLanguage file assigns the scopes source.js and variable.language.js to the this keyword. Since Sublime Text 3 is using the .sublime-package zip file format to store all the default settings it's not very straightforward to edit the individual files.

Unfortunately, not all themes contain all scopes, so you'll need to play around with different ones to find one that looks good, and gives you the highlighting you're looking for. There are a number of themes that are included with Sublime Text, and many more are available through Package Control, which I highly recommend installing if you haven't already. Make sure you follow the ST3 directions.

As it so happens, I've developed the Neon Color Scheme, available through Package Control, that you might want to take a look at. My main goal, besides trying to make a broad range of languages look as good as possible, was to identify as many different scopes as I could - many more than are included in the standard themes. While the JavaScript language definition isn't as thorough as Python's, for example, Neon still has a lot more diversity than some of the defaults like Monokai or Solarized.

jQuery highlighted with Neon Theme

I should note that I used @int3h's Better JavaScript language definition for this image instead of the one that ships with Sublime. It can be installed via Package Control.

UPDATE

Of late I've discovered another JavaScript replacement language definition - JavaScriptNext - ES6 Syntax. It has more scopes than the base JavaScript or even Better JavaScript. It looks like this on the same code:

JavaScriptNext

Also, since I originally wrote this answer, @skuroda has released PackageResourceViewer via Package Control. It allows you to seamlessly view, edit and/or extract parts of or entire .sublime-package packages. So, if you choose, you can directly edit the color schemes included with Sublime.

ANOTHER UPDATE

With the release of nearly all of the default packages on Github, changes have been coming fast and furiously. The old JS syntax has been completely rewritten to include the best parts of JavaScript Next ES6 Syntax, and now is as fully ES6-compatible as can be. A ton of other changes have been made to cover corner and edge cases, improve consistency, and just overall make it better. The new syntax has been included in the (at this time) latest dev build 3111.

If you'd like to use any of the new syntaxes with the current beta build 3103, simply clone the Github repo someplace and link the JavaScript (or whatever language(s) you want) into your Packages directory - find it on your system by selecting Preferences -> Browse Packages.... Then, simply do a git pull in the original repo directory from time to time to refresh any changes, and you can enjoy the latest and greatest! I should note that the repo uses the new .sublime-syntax format instead of the old .tmLanguage one, so they will not work with ST3 builds prior to 3084, or with ST2 (in both cases, you should have upgraded to the latest beta or dev build anyway).

I'm currently tweaking my Neon Color Scheme to handle all of the new scopes in the new JS syntax, but most should be covered already.

JS regex: replace all digits in string

find the numbers and then replaced with strings which specified. It is achieved by two methods

  1. Using a regular expression literal

  2. Using keyword RegExp object

Using a regular expression literal:

<script type="text/javascript">

var string = "my contact number is 9545554545. my age is 27.";
alert(string.replace(/\d+/g, "XXX"));

</script>

**Output:**my contact number is XXX. my age is XXX.

for more details:

http://www.infinetsoft.com/Post/How-to-replace-number-with-string-in-JavaScript/1156

Android: Background Image Size (in Pixel) which Support All Devices

My understanding is that if you use a View object (as supposed to eg. android:windowBackground) Android will automatically scale your image to the correct size. The problem is that too much scaling can result in artifacts (both during up and down scaling) and blurring. Due to various resolutions and aspects ratios on the market, it's impossible to create "perfect" fits for every screen, but you can do your best to make sure only a little bit of scaling has to be done, and thus mitigate the unwanted side effects. So what I would do is:

  • Keep to the 3:4:6:8:12:16 scaling ratio between the six generalized densities (ldpi, mdpi, hdpi, etc).
  • You should not include xxxhdpi elements for your UI elements, this resolution is meant for upscaling launcher icons only (so mipmap folder only) ... You should not use the xxxhdpi qualifier for UI elements other than the launcher icon. ... although eg. on the Samsung edge 7 calling getDisplayMetrics().density returns 4 (xxxhdpi), so perhaps this info is outdated.
  • Then look at the new phone models on the market, and find the representative ones. Assumming the new google pixel is a good representation of an android phone: It has a 1080 x 1920 resolution at 441 dpi, and a screen size of 4.4 x 2.5 inches. Then from the the android developer docs:

    • ldpi (low) ~120dpi
    • mdpi (medium) ~160dpi
    • hdpi (high) ~240dpi
    • xhdpi (extra-high) ~320dpi
    • xxhdpi (extra-extra-high) ~480dpi
    • xxxhdpi (extra-extra-extra-high) ~640dpi

    This corresponds to an xxhdpi screen. From here I could scale these 1080 x 1920 down by the (3:4:6:8:12) ratios above.

  • I could also acknowledge that downsampling is generally an easy way to scale and thus I might want slightly oversized bitmaps bundled in my apk (Note: higher memory consumption). Once more assuming that the width and height of the pixel screen is represetative, I would scale up the 1080x1920 by a factor of 480/441, leaving my maximum resolution background image at approx. 1200x2100, which should then be scaled by the 3:4:6:8:12.
  • Remember, you only need to provide density-specific drawables for bitmap files (.png, .jpg, or .gif) and Nine-Patch files (.9.png). If you use XML files to define drawable resources (eg. shapes), just put one copy in the default drawable directory.
  • If you ever have to accomodate really large or odd aspect ratios, create specific folders for these as well, using the flags for this, eg. sw, long, large, etc.
  • And no need to draw the background twice. Therefore set a style with <item name="android:windowBackground">@null</item>

Unsafe JavaScript attempt to access frame with URL

I found that using the XFBML version of the Facebook like button instead of the HTML5 version fixed this problem. Add the below code where you want the button to appear:

<div id="fb-root"></div>
<script>(function (d, s, id) {
    var js, fjs = d.getElementsByTagName(s)[0];
    if (d.getElementById(id)) return;
    js = d.createElement(s); js.id = id;
    js.src = "//connect.facebook.net/en_GB/all.js#xfbml=1";
    fjs.parentNode.insertBefore(js, fjs);
}(document, 'script', 'facebook-jssdk'));</script>

<fb:like send="true" layout="button_count" width="50" show_faces="false" font="arial"></fb:like>

Then add this to your HTML tag:

 xmlns:fb="http://ogp.me/ns/fb#"

How to update a value, given a key in a hashmap?

The simplified Java 8 way:

map.put(key, map.getOrDefault(key, 0) + 1);

This uses the method of HashMap that retrieves the value for a key, but if the key can't be retrieved it returns the specified default value (in this case a '0').

This is supported within core Java: HashMap<K,V> getOrDefault(Object key, V defaultValue)

Flatten an irregular list of lists

I modified the code of the accepted answer and added a keyword max_depth to only flatten up to a specified depth. max_depth=0 means, the list stays as it is. Maybe somebody can use it:

def flatten(l, __depth=0, max_depth=100):

    for el in l:

        if isinstance(el, collections.Iterable) and not isinstance(el, (str, bytes)):

            __depth += 1
            if __depth <= max_depth:
                yield from flatten(el, __depth=__depth, max_depth=max_depth)
            else:
                yield el
            __depth -= 1

        else:

            yield el

Some examples:

# A
l = []
depth = 5
for i in range(depth):
    el = i
    for j in range(i):
        el = [el]
    l.append(el)
# [0, [1], [[2]], [[[3]]], [[[[4]]]]]

for i in range(depth):
    print(list(flatten_gen(l, max_depth=i)))
# [0, [1], [[2]], [[[3]]], [[[[4]]]]]
# [0,  1,   [2],   [[3]],   [[[4]]]]
# [0,  1,    2,     [3],     [[4]]]
# [0,  1,    2,      3,       [4]]
# [0,  1,    2,      3,        4]


# B
l = [[1, 2], [3, 4, [5, 6, [7, [8, [9]]], 10], 12, [13]], 14, [15]]

for i in range(6):
    print(list(flatten_gen(l, max_depth=i)))
# [[1, 2], [3, 4, [5, 6, [7, [8, [9]]], 10], 12, [13]], 14, [15]]
# [ 1, 2,   3, 4, [5, 6, [7, [8, [9]]], 10], 12, [13],  14,  15]
# [ 1, 2,   3, 4,  5, 6, [7, [8, [9]]], 10,  12,  13,   14,  15]
# [ 1, 2,   3, 4,  5, 6,  7, [8, [9]],  10,  12,  13,   14,  15]
# [ 1, 2,   3, 4,  5, 6,  7,  8, [9],   10,  12,  13,   14,  15]
# [ 1, 2,   3, 4,  5, 6,  7,  8,  9,    10,  12,  13,   14,  15]

Redirect on Ajax Jquery Call

JQuery is looking for a json type result, but because the redirect is processed automatically, it will receive the generated html source of your login.htm page.

One idea is to let the the browser know that it should redirect by adding a redirect variable to to the resulting object and checking for it in JQuery:

$(document).ready(function(){ 
    jQuery.ajax({ 
        type: "GET", 
        url: "populateData.htm", 
        dataType:"json", 
        data:"userId=SampleUser", 
        success:function(response){ 
            if (response.redirect) {
                window.location.href = response.redirect;
            }
            else {
                // Process the expected results...
            }
        }, 
     error: function(xhr, textStatus, errorThrown) { 
            alert('Error!  Status = ' + xhr.status); 
         } 

    }); 
}); 

You could also add a Header Variable to your response and let your browser decide where to redirect. In Java, instead of redirecting, do response.setHeader("REQUIRES_AUTH", "1") and in JQuery you do on success(!):

//....
        success:function(response){ 
            if (response.getResponseHeader('REQUIRES_AUTH') === '1'){ 
                window.location.href = 'login.htm'; 
            }
            else {
                // Process the expected results...
            }
        }
//....

Hope that helps.

My answer is heavily inspired by this thread which shouldn't left any questions in case you still have some problems.

Function to close the window in Tkinter

def exit(self):
    self.frame.destroy()
exit_btn=Button(self.frame,text='Exit',command=self.exit,activebackground='grey',activeforeground='#AB78F1',bg='#58F0AB',highlightcolor='red',padx='10px',pady='3px')
exit_btn.place(relx=0.45,rely=0.35)

This worked for me to destroy my Tkinter frame on clicking the exit button.

How to swap two variables in JavaScript

Destructing assignment is the best way to solve your problem.

_x000D_
_x000D_
var a = 1;
var b = 2;

[a, b] = [b, a];

console.log("After swap a =", a, " and b =", b);
_x000D_
_x000D_
_x000D_

Convert js Array() to JSon object for use with JQuery .ajax

There is actuly a difference between array object and JSON object. Instead of creating array object and converting it into a json object(with JSON.stringify(arr)) you can do this:

var sels = //Here is your array of SELECTs
var json = { };

for(var i = 0, l = sels.length; i < l; i++) {
  json[sels[i].id] = sels[i].value;
}

There is no need of converting it into JSON because its already a json object. To view the same use json.toSource();

CSS white space at bottom of page despite having both min-height and height tag

I find it quite remarkable that out of 6 answers, none of them have mentioned the real source of the problem.

Collapsing margins on the last p inside #fw-footer is where that extra space is originating from.

A sensible fix would be to add overflow: hidden to #fw-footer (or simply add margin: 0 on the last p).

You could also just move the script inside that last p outside of the p, and then remove the p entirely; there's no need to wrap a script in a p. The first p (#fw-foottext) has margin: 0 applied, so the problem won't happen with that one.


As an aside, you've broken the fix I gave you in this question:

CSS3 gradient background with unwanted white space at bottom

You need html { height: 100% } and body { min-height: 100% }.

At the moment, you have html { height: auto } being applied, which does not work:

(This happens with a window taller than the content on the page)

Git error: src refspec master does not match any

The quick possible answer: When you first successfully clone an empty git repository, the origin has no master branch. So the first time you have a commit to push you must do:

git push origin master

Which will create this new master branch for you. Little things like this are very confusing with git.

If this didn't fix your issue then it's probably a gitolite-related issue:

Your conf file looks strange. There should have been an example conf file that came with your gitolite. Mine looks like this:

repo    phonegap                                                                                                                                                                           
    RW+     =   myusername otherusername                                                                                                                                               

repo    gitolite-admin                                                                                                                                                                         
    RW+     =   myusername                                                                                                                                                               

Please make sure you're setting your conf file correctly.

Gitolite actually replaces the gitolite user's account with a modified shell that doesn't accept interactive terminal sessions. You can see if gitolite is working by trying to ssh into your box using the gitolite user account. If it knows who you are it will say something like "Hi XYZ, you have access to the following repositories: X, Y, Z" and then close the connection. If it doesn't know you, it will just close the connection.

Lastly, after your first git push failed on your local machine you should never resort to creating the repo manually on the server. We need to know why your git push failed initially. You can cause yourself and gitolite more confusion when you don't use gitolite exclusively once you've set it up.

Double vs. BigDecimal?

If you write down a fractional value like 1 / 7 as decimal value you get

1/7 = 0.142857142857142857142857142857142857142857...

with an infinite sequence of 142857. Since you can only write a finite number of digits you will inevitably introduce a rounding (or truncation) error.

Numbers like 1/10 or 1/100 expressed as binary numbers with a fractional part also have an infinite number of digits after the decimal point:

1/10 = binary 0.0001100110011001100110011001100110...

Doubles store values as binary and therefore might introduce an error solely by converting a decimal number to a binary number, without even doing any arithmetic.

Decimal numbers (like BigDecimal), on the other hand, store each decimal digit as is (binary coded, but each decimal on its own). This means that a decimal type is not more precise than a binary floating point or fixed point type in a general sense (i.e. it cannot store 1/7 without loss of precision), but it is more accurate for numbers that have a finite number of decimal digits as is often the case for money calculations.

Java's BigDecimal has the additional advantage that it can have an arbitrary (but finite) number of digits on both sides of the decimal point, limited only by the available memory.

how to bind datatable to datagridview in c#

Try this:

    ServersTable.Columns.Clear();
    ServersTable.DataSource = SBind;

If you don't want to clear all the existing columns, you have to set DataPropertyName for each existing column like this:

for (int i = 0; i < ServersTable.ColumnCount; ++i) {
  DTable.Columns.Add(new DataColumn(ServersTable.Columns[i].Name));
  ServersTable.Columns[i].DataPropertyName = ServersTable.Columns[i].Name;
}

How to change btn color in Bootstrap

The simplest way is to:

  1. intercept every button state

  2. add !important to override the states

    .btn-primary:hover,
    .btn-primary:active,
    .btn-primary:visited,
    .btn-primary:focus {
      background-color: black !important;
      border-color: black !important;
    }

OR the more practical UI way is to make the hover state of the button darker than the original state. Just use the CSS snippet below:

.btn-primary {
  background-color: Blue !important;
  border-color: Blue !important;
}
.btn-primary:hover,
.btn-primary:active,
.btn-primary:visited,
.btn-primary:focus {
  background-color: DarkBlue !important;
  border-color: DarkBlue !important;
}

Create a new workspace in Eclipse

You can create multiple workspaces in Eclipse. You have to just specify the path of the workspace during Eclipse startup. You can even switch workspaces via File?Switch workspace.

You can then import project to your workspace, copy paste project to your new workspace folder, then

File?Import?Existing project in to workspace?select project.

JsonParseException : Illegal unquoted character ((CTRL-CHAR, code 10)

This can happen if you have a newline (or other control character) in a JSON string literal.

{"foo": "bar
baz"}

If you are the one producing the data, replace actual newlines with escaped ones "\\n" when creating your string literals.

{"foo": "bar\nbaz"}

Convert integer into its character equivalent, where 0 => a, 1 => b, etc

Assuming you want lower case letters:

var chr = String.fromCharCode(97 + n); // where n is 0, 1, 2 ...

97 is the ASCII code for lower case 'a'. If you want uppercase letters, replace 97 with 65 (uppercase 'A'). Note that if n > 25, you will get out of the range of letters.

Express.js: how to get remote client address

With could-flare, nginx and x-real-ip support

var user_ip;

    if(req.headers['cf-connecting-ip'] && req.headers['cf-connecting-ip'].split(', ').length) {
      let first = req.headers['cf-connecting-ip'].split(', ');
      user_ip = first[0];
    } else {
      let user_ip = req.headers['x-forwarded-for'] || req.headers['x-real-ip'] || req.connection.remoteAddress || req.socket.remoteAddress || req.connection.socket.remoteAddress;
    }

How to check the first character in a string in Bash or UNIX shell?

Consider the case statement as well which is compatible with most sh-based shells:

case $str in
/*)
    echo 1
    ;;
*)
    echo 0
    ;;
esac

How can I simulate a click to an anchor tag?

Here is a complete test case that simulates the click event, calls all handlers attached (however they have been attached), maintains the "target" attribute ("srcElement" in IE), bubbles like a normal event would, and emulates IE's recursion-prevention. Tested in FF 2, Chrome 2.0, Opera 9.10 and of course IE (6):

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<script>
function fakeClick(event, anchorObj) {
  if (anchorObj.click) {
    anchorObj.click()
  } else if(document.createEvent) {
    if(event.target !== anchorObj) {
      var evt = document.createEvent("MouseEvents"); 
      evt.initMouseEvent("click", true, true, window, 
          0, 0, 0, 0, 0, false, false, false, false, 0, null); 
      var allowDefault = anchorObj.dispatchEvent(evt);
      // you can check allowDefault for false to see if
      // any handler called evt.preventDefault().
      // Firefox will *not* redirect to anchorObj.href
      // for you. However every other browser will.
    }
  }
}
</script>
</head>
<body>

<div onclick="alert('Container clicked')">
  <a id="link" href="#" onclick="alert((event.target || event.srcElement).innerHTML)">Normal link</a>
</div>

<button type="button" onclick="fakeClick(event, document.getElementById('link'))">
  Fake Click on Normal Link
</button>

<br /><br />

<div onclick="alert('Container clicked')">
    <div onclick="fakeClick(event, this.getElementsByTagName('a')[0])"><a id="link2" href="#" onclick="alert('foo')">Embedded Link</a></div>
</div>

<button type="button" onclick="fakeClick(event, document.getElementById('link2'))">Fake Click on Embedded Link</button>

</body>
</html>

Demo here.

It avoids recursion in non-IE browsers by inspecting the event object that is initiating the simulated click, by inspecting the target attribute of the event (which remains unchanged during propagation).

Obviously IE does this internally holding a reference to its global event object. DOM level 2 defines no such global variable, so for that reason the simulator must pass in its local copy of event.

What is difference between mutable and immutable String in java

Case 1:

String str = "Good";
str = str + " Morning";

In the above code you create 3 String Objects.

  1. "Good" it goes into the String Pool.
  2. " Morning" it goes into the String Pool as well.
  3. "Good Morning" created by concatenating "Good" and " Morning". This guy goes on the Heap.

Note: Strings are always immutable. There is no, such thing as a mutable String. str is just a reference which eventually points to "Good Morning". You are actually, not working on 1 object. you have 3 distinct String Objects.


Case 2:

StringBuffer str = new StringBuffer("Good"); 
str.append(" Morning");

StringBuffer contains an array of characters. It is not same as a String. The above code adds characters to the existing array. Effectively, StringBuffer is mutable, its String representation isn't.

Rotate and translate

The reason is because you are using the transform property twice. Due to CSS rules with the cascade, the last declaration wins if they have the same specificity. As both transform declarations are in the same rule set, this is the case.

What it is doing is this:

  1. rotate the text 90 degrees. Ok.
  2. translate 50% by 50%. Ok, this is same property as step one, so do this step and ignore step 1.

See http://jsfiddle.net/Lx76Y/ and open it in the debugger to see the first declaration overwritten

As the translate is overwriting the rotate, you have to combine them in the same declaration instead: http://jsfiddle.net/Lx76Y/1/

To do this you use a space separated list of transforms:

#rotatedtext {
    transform-origin: left;
    transform: translate(50%, 50%) rotate(90deg) ;
}

Remember that they are specified in a chain, so the translate is applied first, then the rotate after that.

How to fix Python indentation

If you're using Vim, see :h retab.

                                                        *:ret* *:retab*
:[range]ret[ab][!] [new_tabstop]
                        Replace all sequences of white-space containing a
                        <Tab> with new strings of white-space using the new
                        tabstop value given.  If you do not specify a new
                        tabstop size or it is zero, Vim uses the current value
                        of 'tabstop'.
                        The current value of 'tabstop' is always used to
                        compute the width of existing tabs.
                        With !, Vim also replaces strings of only normal
                        spaces with tabs where appropriate.
                        With 'expandtab' on, Vim replaces all tabs with the
                        appropriate number of spaces.
                        This command sets 'tabstop' to the new value given,
                        and if performed on the whole file, which is default,
                        should not make any visible change.
                        Careful: This command modifies any <Tab> characters
                        inside of strings in a C program.  Use "\t" to avoid
                        this (that's a good habit anyway).
                        ":retab!" may also change a sequence of spaces by
                        <Tab> characters, which can mess up a printf().
                        {not in Vi}
                        Not available when |+ex_extra| feature was disabled at
                        compile time.

For example, if you simply type

:ret

all your tabs will be expanded into spaces.

You may want to

:se et  " shorthand for :set expandtab

to make sure that any new lines will not use literal tabs.


If you're not using Vim,

perl -i.bak -pe "s/\t/' 'x(8-pos()%8)/eg" file.py

will replace tabs with spaces, assuming tab stops every 8 characters, in file.py (with the original going to file.py.bak, just in case). Replace the 8s with 4s if your tab stops are every 4 spaces instead.

How to crop a CvMat in OpenCV?

You can easily crop a Mat using opencv funtions.

setMouseCallback("Original",mouse_call);

The mouse_callis given below:

 void mouse_call(int event,int x,int y,int,void*)
    {
        if(event==EVENT_LBUTTONDOWN)
        {
            leftDown=true;
            cor1.x=x;
            cor1.y=y;
           cout <<"Corner 1: "<<cor1<<endl;

        }
        if(event==EVENT_LBUTTONUP)
        {
            if(abs(x-cor1.x)>20&&abs(y-cor1.y)>20) //checking whether the region is too small
            {
                leftup=true;
                cor2.x=x;
                cor2.y=y;
                cout<<"Corner 2: "<<cor2<<endl;
            }
            else
            {
                cout<<"Select a region more than 20 pixels"<<endl;
            }
        }

        if(leftDown==true&&leftup==false) //when the left button is down
        {
            Point pt;
            pt.x=x;
            pt.y=y;
            Mat temp_img=img.clone();
            rectangle(temp_img,cor1,pt,Scalar(0,0,255)); //drawing a rectangle continuously
            imshow("Original",temp_img);

        }
        if(leftDown==true&&leftup==true) //when the selection is done
        {

            box.width=abs(cor1.x-cor2.x);
            box.height=abs(cor1.y-cor2.y);
            box.x=min(cor1.x,cor2.x);
            box.y=min(cor1.y,cor2.y);
            Mat crop(img,box);   //Selecting a ROI(region of interest) from the original pic
            namedWindow("Cropped Image");
            imshow("Cropped Image",crop); //showing the cropped image
            leftDown=false;
            leftup=false;

        }
    }

For details you can visit the link Cropping the Image using Mouse

Can constructors be async?

I use this easy trick.

public sealed partial class NamePage
{
  private readonly Task _initializingTask;

  public NamePage()
  {
    _initializingTask = Init();
  }

  private async Task Init()
  {
    /*
    Initialization that you need with await/async stuff allowed
    */
  }
}

MySQL Multiple Where Clause

select unique red24.image_id from 
( 
    select image_id from `list` where style_id = 24 and style_value = 'red' 
) red24
inner join 
( 
    select image_id from `list` where style_id = 25 and style_value = 'big' 
) big25
on red24.image_id = big25.image_id
inner join 
( 
    select image_id from `list` where style_id = 27 and style_value = 'round' 
) round27
on red24.image_id = round27.image_id

How can I verify if a Windows Service is running

Here you get all available services and their status in your local machine.

ServiceController[] services = ServiceController.GetServices();
foreach(ServiceController service in services)
{
    Console.WriteLine(service.ServiceName+"=="+ service.Status);
}

You can Compare your service with service.name property inside loop and you get status of your service. For details go with the http://msdn.microsoft.com/en-us/library/system.serviceprocess.servicecontroller.aspx also http://msdn.microsoft.com/en-us/library/microsoft.windows.design.servicemanager(v=vs.90).aspx

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

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

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

How to add an extra row to a pandas dataframe

Try this:

df.loc[len(df)]=['8/19/2014','Jun','Fly','98765'] 

Warning: this method works only if there are no "holes" in the index. For example, suppose you have a dataframe with three rows, with indices 0, 1, and 3 (for example, because you deleted row number 2). Then, len(df) = 3, so by the above command does not add a new row - it overrides row number 3.

How can I get Android Wifi Scan Results into a list?

In addition for the accepted answer you'll need the following permissions into your AndroidManifest to get it working:

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

Why is there an unexplainable gap between these inline-block div elements?

simply add a border: 2px solid #e60000; to your 2nd div tag CSS.

Definitely it works

#Div2Id {
    border: 2px solid #e60000; --> color is your preference
}

C# - Insert a variable number of spaces into a string? (Formatting an output file)

For this you probably want myString.PadRight(totalLength, charToInsert).

See String.PadRight Method (Int32) for more info.

What's the best way to store a group of constants that my program uses?

Another vote for using web.config or app.config. The config files are a good place for constants like connection strings, etc. I prefer not to have to look at the source to view or modify these types of things. A static class which reads these constants from a .config file might be a good compromise, as it will let your application access these resources as though they were defined in code, but still give you the flexibility of having them in an easily viewable/editable space.

How do I install jmeter on a Mac?

You have 2 options:

brew update to update homebrew packages

brew install jmeter to install jmeter

Read this blog to know how to map folders from standard jmeter to homebrew installed version.

  • Install using standard version which I would advise you to do. Steps are:

    1. Install Last compatible JDK version (7 or 8 as of JMeter 3.1).

    2. Download JMeter from here

    3. Unzip folder and run from the folder:

bin/jmeter

How to execute my SQL query in CodeIgniter

I can see what @Þaw mentioned :

$ENROLLEES = $this->load->database('ENROLLEES', TRUE);
$ACCOUNTS = $this->load->database('ACCOUNTS', TRUE);

CodeIgniter supports multiple databases. You need to keep both database reference in separate variable as you did above. So far you are right/correct.

Next you need to use them as below:

$ENROLLEES->query();
$ENROLLEES->result();

and

$ACCOUNTS->query();
$ACCOUNTS->result();

Instead of using

$this->db->query();
$this->db->result();

See this for reference: http://ellislab.com/codeigniter/user-guide/database/connecting.html