Programs & Examples On #Newsletter

A email or document containing a one or more news stories that will be distributed to a group of subscribers.

How do I remove link underlining in my HTML email?

It wholly depends on the email client whether it wants to display the underline under the link or not. As of now, the styles in the body are only supported by:

  • Outlook 2007/10/13 +
  • Outlook 2000/03
  • Apple iPhone/iPad
  • Outlook.com
  • Apple Mail 4
  • Yahoo! Mail Beta

http://www.campaignmonitor.com/css/

standard size for html newsletter template

Ideally the email content should be about 550px wide to fit within most email clients preview window. If you know for sure your target market can view bigger then you can design bigger. Loads of email examples over on http://www.beautiful-email-newsletters.com/

How make background image on newsletter in outlook?

You can use the code below :

<!--[if gte mso 9]>
<v:rect xmlns:v="urn:schemas-microsoft-com:vml" fill="true" stroke="false" 
style="width: 700px; height: 460px;">
<v:fill type="tile" src="images/feature-background-01.png" color="#333333" />   
<v:textbox inset="0,0,0,0">                                 
<![endif]-->

Note: Include this code above the table for which the background image is needed. Also, add the closing tag mentioned below, after the closing tag of the table.

<!--[if gte mso 9]>
      </v:textbox>
      </v:rect>
<![endif]-->

AJAX Mailchimp signup form integration

Based on gbinflames' answer, I kept the POST and URL, so that the form would continue to work for those with JS off.

<form class="myform" action="http://XXXXXXXXXlist-manage2.com/subscribe/post" method="POST">
  <input type="hidden" name="u" value="XXXXXXXXXXXXXXXX">
  <input type="hidden" name="id" value="XXXXXXXXX">
  <input class="input" type="text" value="" name="MERGE1" placeholder="First Name" required>
  <input type="submit" value="Send" name="submit" id="mc-embedded-subscribe">
</form>

Then, using jQuery's .submit() changed the type, and URL to handle JSON repsonses.

$('.myform').submit(function(e) {
  var $this = $(this);
  $.ajax({
      type: "GET", // GET & url for json slightly different
      url: "http://XXXXXXXX.list-manage2.com/subscribe/post-json?c=?",
      data: $this.serialize(),
      dataType    : 'json',
      contentType: "application/json; charset=utf-8",
      error       : function(err) { alert("Could not connect to the registration server."); },
      success     : function(data) {
          if (data.result != "success") {
              // Something went wrong, parse data.msg string and display message
          } else {
              // It worked, so hide form and display thank-you message.
          }
      }
  });
  return false;
});

C# equivalent of C++ map<string,double>

Roughly:-

var accounts = new Dictionary<string, double>();

// Initialise to zero...

accounts["Fred"] = 0;
accounts["George"] = 0;
accounts["Fred"] = 0;

// Add cash.
accounts["Fred"] += 4.56;
accounts["George"] += 1.00;
accounts["Fred"] += 1.00;

Console.WriteLine("Fred owes me ${0}", accounts["Fred"]);

Return a 2d array from a function

The function returns a static 2D array

const int N = 6;
int (*(MakeGridOfCounts)())[N] {
 static int cGrid[N][N] = {{0, }, {0, }, {0, }, {0, }, {0, }, {0, }};
 return cGrid;
}

int main() {
int (*arr)[N];
arr = MakeGridOfCounts();
}

You need to make the array static since it will be having a block scope, when the function call ends, the array will be created and destroyed. Static scope variables last till the end of program.

How to avoid HTTP error 429 (Too Many Requests) python

I've found out a nice workaround to IP blocking when scraping sites. It lets you run a Scraper indefinitely by running it from Google App Engine and redeploying it automatically when you get a 429.

Check out this article

How to compare dates in Java?

This method worked for me:

 public static String daysBetween(String day1, String day2) {
    String daysBetween = "";
    SimpleDateFormat myFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    try {
        Date date1 = myFormat.parse(day1);
        Date date2 = myFormat.parse(day2);
        long diff = date2.getTime() - date1.getTime();
        daysBetween = ""+(TimeUnit.DAYS.convert(diff, TimeUnit.MILLISECONDS));
    } catch (ParseException e) {
        e.printStackTrace();
    }
    return daysBetween;
}

Change a Git remote HEAD to point to something besides master

You can create a detached master branch using only porcelain Git commands:

git init
touch GO_AWAY
git add GO_AWAY
git commit -m "GO AWAY - this branch is detached from reality"

That gives us a master branch with a rude message (you may want to be more polite). Now we create our "real" branch (let's call it trunk in honour of SVN) and divorce it from master:

git checkout -b trunk
git rm GO_AWAY
git commit --amend --allow-empty -m "initial commit on detached trunk"

Hey, presto! gitk --all will show master and trunk with no link between them.

The "magic" here is that --amend causes git commit to create a new commit with the same parent as the current HEAD, then make HEAD point to it. But the current HEAD doesn't have a parent as it's the initial commit in the repository, so the new HEAD doesn't get one either, making them detached from each other.

The old HEAD commit doesn't get deleted by git-gc because refs/heads/master still points to it.

The --allow-empty flag is only needed because we're committing an empty tree. If there were some git add's after the git rm then it wouldn't be necessary.

In truth, you can create a detached branch at any time by branching the initial commit in the repository, deleting its tree, adding your detached tree, then doing git commit --amend.

I know this doesn't answer the question of how to modify the default branch on the remote repository, but it gives a clean answer on how to create a detached branch.

How to check if a text field is empty or not in swift

Swift 4.2

You can use a general function for your every textField just add the following function in your base controller

// White space validation.
func checkTextFieldIsNotEmpty(text:String) -> Bool
{
    if (text.trimmingCharacters(in: .whitespaces).isEmpty)
    {
        return false

    }else{
        return true
    }
}

How to count duplicate rows in pandas dataframe?

ran into this problem today and wanted to include NaNs so I replace them temporarily with "" (empty string). Please comment if you do not understand something :). This solution assumes that "" is not a relevant value for you. It should also work with numerical data (I have tested it sucessfully but not extensively) since pandas will infer the data type again after replacing "" with np.nan.

import pandas as pd

# create test data
df = pd.DataFrame({'test':['foo','bar',None,None,'foo'],
                  'test2':['bar',None,None,None,'bar'],
                  'test3':[None, 'foo','bar',None,None]})

# fill null values with '' to not lose them during groupby
# groupby all columns and calculate the length of the resulting groups
# rename the series obtained with groupby to "group_count"
# reset the index to get a DataFrame
# replace '' with np.nan (this reverts our first operation)
# sort DataFrame by "group_count" descending
df = (df.fillna('')\
      .groupby(df.columns.tolist()).apply(len)\
      .rename('group_count')\
      .reset_index()\
      .replace('',np.nan)\
      .sort_values(by = ['group_count'], ascending = False))
df
  test test2 test3  group_count
3  foo   bar   NaN            2
0  NaN   NaN   NaN            1
1  NaN   NaN   bar            1
2  bar   NaN   foo            1

How do I install the ext-curl extension with PHP 7?

I tried the above solutions but it didn't work for me, just incase there any other person in the same shoes, this is what I did. I updated apt-get with the following command

sudo add-apt-repository ppa:ondrej/php

this i installed with php curl for the version of php that i was using, mine was

sudo apt-get install php7.1-curl

TypeError: Object of type 'bytes' is not JSON serializable

I was dealing with this issue today, and I knew that I had something encoded as a bytes object that I was trying to serialize as json with json.dump(my_json_object, write_to_file.json). my_json_object in this case was a very large json object that I had created, so I had several dicts, lists, and strings to look at to find what was still in bytes format.

The way I ended up solving it: the write_to_file.json will have everything up to the bytes object that is causing the issue.

In my particular case this was a line obtained through

for line in text:
    json_object['line'] = line.strip()

I solved by first finding this error with the help of the write_to_file.json, then by correcting it to:

for line in text:
    json_object['line'] = line.strip().decode()

Virtual network interface in Mac OS X

The loopback adapter is always up.

ifconfig lo0 alias 172.16.123.1 will add an alias IP 172.16.123.1 to the loopback adapter

ifconfig lo0 -alias 172.16.123.1 will remove it

php is null or empty?

This is not a bug but PHP normal behavior. It happens because the == operator in PHP doesn't check for type.

'' == null == 0 == false

If you want also to check if the values have the same type, use === instead. To study in deep this difference, please read the official documentation.

Call js-function using JQuery timer

try jQueryTimers, they have great functionality for polling

http://plugins.jquery.com/project/timers

How do you read CSS rule values with JavaScript?

//works in IE, not sure about other browsers...

alert(classes[x].style.cssText);

What's the valid way to include an image with no src?

Use a truly blank, valid and highly compatible SVG, based on this article:

src="data:image/svg+xml;charset=utf8,%3Csvg%20xmlns='http://www.w3.org/2000/svg'%3E%3C/svg%3E"

It will default in size to 300x150px as any SVG does, but you can work with that in your img element default styles, as you would possibly need in any case in the practical implementation.

File uploading with Express 4.0: req.files undefined

Please use below code

app.use(fileUpload());

Landscape printing from HTML

You can try the following:

@page {
    size: auto
}

Why can't DateTime.ParseExact() parse "9/1/2009" using "M/d/yyyy"

Try :

Configure in web config file

<system.web> <globalization culture="ja-JP" uiCulture="zh-HK" /> </system.web>

eg: DateTime dt = DateTime.ParseExact("08/21/2013", "MM/dd/yyyy", null);

ref url : http://support.microsoft.com/kb/306162/

How to check whether a string is Base64 encoded or not

This snippet may be useful when you know the length of the original content (e.g. a checksum). It checks that encoded form has the correct length.

public static boolean isValidBase64( final int initialLength, final String string ) {
  final int padding ;
  final String regexEnd ;
  switch( ( initialLength ) % 3 ) {
    case 1 :
      padding = 2 ;
      regexEnd = "==" ;
      break ;
    case 2 :
      padding = 1 ;
      regexEnd = "=" ;
      break ;
    default :
      padding = 0 ;
      regexEnd = "" ;
  }
  final int encodedLength = ( ( ( initialLength / 3 ) + ( padding > 0 ? 1 : 0 ) ) * 4 ) ;
  final String regex = "[a-zA-Z0-9/\\+]{" + ( encodedLength - padding ) + "}" + regexEnd ;
  return Pattern.compile( regex ).matcher( string ).matches() ;
}

Is there a way to override class variables in Java?

You can create a getter and then override that getter. It's particularly useful if the variable you are overriding is a sub-class of itself. Imagine your super class has an Object member but in your sub-class this is now more defined to be an Integer.

class Dad
{
        private static final String me = "dad";

        protected String getMe() {
            return me;
        }

        public void printMe()
        {
                System.out.println(getMe());
        }
}

class Son extends Dad
{
        private static final String me = "son";

        @Override
        protected String getMe() {
            return me;
        }
}

public void doIt()
{
        new Son().printMe(); //Prints "son"
}

Spring boot - Not a managed type

You either missed @Entity on class definition or you have explicit component scan path and this path does not contain your class

SQL join on multiple columns in same tables

You want to join on condition 1 AND condition 2, so simply use the AND keyword as below

ON a.userid = b.sourceid AND a.listid = b.destinationid;

Algorithm/Data Structure Design Interview Questions

Graphs are tough, because most non-trivial graph problems tend to require a decent amount of actual code to implement, if more than a sketch of an algorithm is required. A lot of it tends to come down to whether or not the candidate knows the shortest path and graph traversal algorithms, is familiar with cycle types and detection, and whether they know the complexity bounds. I think a lot of questions about this stuff comes down to trivia more than on the spot creative thinking ability.

I think problems related to trees tend to cover most of the difficulties of graph questions, but without as much code complexity.

I like the Project Euler problem that asks to find the most expensive path down a tree (16/67); common ancestor is a good warm up, but a lot of people have seen it. Asking somebody to design a tree class, perform traversals, and then figure out from which traversals they could rebuild a tree also gives some insight into data structure and algorithm implementation. The Stern-Brocot programming challenge is also interesting and quick to develop on a board (http://online-judge.uva.es/p/v100/10077.html).

How do I pass multiple attributes into an Angular.js attribute directive?

If you "require" 'exampleDirective' from another directive + your logic is in 'exampleDirective's' controller (let's say 'exampleCtrl'):

app.directive('exampleDirective', function () {
    return {
        restrict: 'A',
        scope: false,
        bindToController: {
            myCallback: '&exampleFunction'
        },
        controller: 'exampleCtrl',
        controllerAs: 'vm'
    };
});
app.controller('exampleCtrl', function () {
    var vm = this;
    vm.myCallback();
});

Question mark and colon in statement. What does it mean?

It means if "OperationURL[1]" evaluates to "GET" then return "GetRequestSignature()" else return "". I'm guessing "GetRequestSignature()" here returns a string. The syntax CONDITION ? A : B basically stands for an if-else where A is returned when CONDITION is true and B is returned when CONDITION is false.

Override devise registrations controller

Very simple methods Just go to the terminal and the type following

rails g devise:controllers users //This will create devise controllers in controllers/users folder

Next to use custom views

rails g devise:views users //This will create devise views in views/users folder

now in your route.rb file

devise_for :users, controllers: {
           :sessions => "users/sessions",
           :registrations => "users/registrations" }

You can add other controllers too. This will make devise to use controllers in users folder and views in users folder.

Now you can customize your views as your desire and add your logic to controllers in controllers/users folder. Enjoy !

Log4j2 configuration - No log4j2 configuration file found

Eclipse will never see a file until you force a refresh of the IDE. Its a feature! So you can put the file all over the project and Eclipse will ignore it completely and throw these errors. Hit refresh in Eclipse project view and then it works.

You don't have permission to access / on this server

Right click your www folder and click on properties. Navigate to permissions and change all to read and write then click on "Apply permission to enclosed files" and your are done!! Maybe its too late but this will definitely help some other person

What causes and what are the differences between NoClassDefFoundError and ClassNotFoundException?

A ClassNotFoundException is thrown when the reported class is not found by the ClassLoader. This typically means that the class is missing from the CLASSPATH. It could also mean that the class in question is trying to be loaded from another class which was loaded in a parent classloader and hence the class from the child classloader is not visible. This is sometimes the case when working in more complex environments like an App Server (WebSphere is infamous for such classloader issues).

People often tend to confuse java.lang.NoClassDefFoundError with java.lang.ClassNotFoundException however there's an important distinction. For example an exception (an error really since java.lang.NoClassDefFoundError is a subclass of java.lang.Error) like

java.lang.NoClassDefFoundError:
org/apache/activemq/ActiveMQConnectionFactory

does not mean that the ActiveMQConnectionFactory class is not in the CLASSPATH. Infact its quite the opposite. It means that the class ActiveMQConnectionFactory was found by the ClassLoader however when trying to load the class, it ran into an error reading the class definition. This typically happens when the class in question has static blocks or members which use a Class that's not found by the ClassLoader. So to find the culprit, view the source of the class in question (ActiveMQConnectionFactory in this case) and look for code using static blocks or static members. If you don't have access the the source, then simply decompile it using JAD.

On examining the code, say you find a line of code like below, make sure that the class SomeClass in in your CLASSPATH.

private static SomeClass foo = new SomeClass();

Tip : To find out which jar a class belongs to, you can use the web site jarFinder . This allows you to specify a class name using wildcards and it searches for the class in its database of jars. jarhoo allows you to do the same thing but its no longer free to use.

If you would like to locate the which jar a class belongs to in a local path, you can use a utility like jarscan ( http://www.inetfeedback.com/jarscan/ ). You just specify the class you'd like to locate and the root directory path where you'd like it to start searching for the class in jars and zip files.

In Oracle, is it possible to INSERT or UPDATE a record through a view?

There are two times when you can update a record through a view:

  1. If the view has no joins or procedure calls and selects data from a single underlying table.
  2. If the view has an INSTEAD OF INSERT trigger associated with the view.

Generally, you should not rely on being able to perform an insert to a view unless you have specifically written an INSTEAD OF trigger for it. Be aware, there are also INSTEAD OF UPDATE triggers that can be written as well to help perform updates.

How can I get the current directory name in Javascript?

complete URL

If you want the complete URL e.g. http://website/basedirectory/workingdirectory/ use:

var location = window.location.href;
var directoryPath = location.substring(0, location.lastIndexOf("/")+1);

local path

If you want the local path without domain e.g. /basedirectory/workingdirectory/ use:

var location = window.location.pathname;
var directoryPath = location.substring(0, location.lastIndexOf("/")+1);

In case you don't need the slash at the end, remove the +1 after location.lastIndexOf("/")+1.

directory name

If you only want the current directory name, where the script is running in, e.g. workingdirectory use:

var location = window.location.pathname;
var path = location.substring(0, location.lastIndexOf("/"));
var directoryName = path.substring(path.lastIndexOf("/")+1);

Windows equivalent of OS X Keychain?

The "traditional" Windows equivalent would be the Protected Storage subsystem, used by IE (pre IE 7), Outlook Express, and a few other programs. I believe it's encrypted with your login password, which prevents some offline attacks, but once you're logged in, any program that wants to can read it. (See, for example, NirSoft's Protected Storage PassView.)

Windows also provides the CryptoAPI and Data Protection API that might help. Again, though, I don't think that Windows does anything to prevent processes running under the same account from seeing each other's passwords.

It looks like the book Mechanics of User Identification and Authentication provides more details on all of these.

Eclipse (via its Secure Storage feature) implements something like this, if you're interested in seeing how other software does it.

How to use and style new AlertDialog from appCompat 22.1 and above

When creating the AlertDialog you can set a theme to use.

Example - Creating the Dialog

AlertDialog.Builder builder = new AlertDialog.Builder(this, R.style.MyAlertDialogStyle);
builder.setTitle("AppCompatDialog");
builder.setMessage("Lorem ipsum dolor...");
builder.setPositiveButton("OK", null);
builder.setNegativeButton("Cancel", null);
builder.show();

styles.xml - Custom style

<style name="MyAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
    <!-- Used for the buttons -->
    <item name="colorAccent">#FFC107</item>
    <!-- Used for the title and text -->
    <item name="android:textColorPrimary">#FFFFFF</item>
    <!-- Used for the background -->
    <item name="android:background">#4CAF50</item>
</style>

Result

styled alertdialog

Edit

In order to change the Appearance of the Title, you can do the following. First add a new style:

<style name="MyTitleTextStyle">
    <item name="android:textColor">#FFEB3B</item>
    <item name="android:textAppearance">@style/TextAppearance.AppCompat.Title</item>
</style>

afterwards simply reference this style in your MyAlertDialogStyle:

<style name="MyAlertDialogStyle" parent="Theme.AppCompat.Light.Dialog.Alert">
    ...
    <item name="android:windowTitleStyle">@style/MyTitleTextStyle</item>
</style>

This way you can define a different textColor for the message via android:textColorPrimary and a different for the title via the style.

Static way to get 'Context' in Android?

Do this:

In the Android Manifest file, declare the following.

<application android:name="com.xyz.MyApplication">

</application>

Then write the class:

public class MyApplication extends Application {

    private static Context context;

    public void onCreate() {
        super.onCreate();
        MyApplication.context = getApplicationContext();
    }

    public static Context getAppContext() {
        return MyApplication.context;
    }
}

Now everywhere call MyApplication.getAppContext() to get your application context statically.

Split string with delimiters in C

Two issues surrounding this question are memory management and thread safety. As you can see from the numerous posts, this isn't an easy task to accomplish seamlessly in C. I desired a solution that is:

  • Thread safe. (strtok is not thread safe)
  • Does not employ malloc or any of it's derivatives (to avoid memory management issues)
  • Checks array bounds on the individual fields (to avoid segment faults on unknown data)
  • Works with multi-byte field separators (utf-8)
  • ignores extra fields in the input
  • provides soft error routine for invalid field lengths

The solution I came up meets all of these criteria. It's probably a little more work to setup than some other solutions posted here, but I think that in practice, the extra work is worth it in order to avoid the common pitfalls of other solutions.

#include <stdio.h>
#include <string.h>

struct splitFieldType {
    char *field;
    int   maxLength;
};

typedef struct splitFieldType splitField;

int strsplit(splitField *fields, int expected, const char *input, const char *fieldSeparator, void (*softError)(int fieldNumber,int expected,int actual))  {
    int i;
    int fieldSeparatorLen=strlen(fieldSeparator);
    const char *tNext, *tLast=input;

    for (i=0; i<expected && (tNext=strstr(tLast, fieldSeparator))!=NULL; ++i) {
        int len=tNext-tLast;
        if (len>=fields[i].maxLength) {
            softError(i,fields[i].maxLength-1,len);
            len=fields[i].maxLength-1;
        }
        fields[i].field[len]=0;
        strncpy(fields[i].field,tLast,len);
        tLast=tNext+fieldSeparatorLen;
    }
    if (i<expected) {
        if (strlen(tLast)>fields[i].maxLength) {
            softError(i,fields[i].maxLength,strlen(tLast));
        } else {
            strcpy(fields[i].field,tLast);
        }
        return i+1;
    } else {
        return i;
    }
}


void monthSplitSoftError(int fieldNumber, int expected, int actual) {
    fprintf(stderr,"monthSplit: input field #%d is %d bytes, expected %d bytes\n",fieldNumber+1,actual,expected);
}


int main() {
  const char *fieldSeparator=",";
  const char *input="JAN,FEB,MAR,APRI,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC,FOO,BAR";

  struct monthFieldsType {
    char field1[4];
    char field2[4];
    char field3[4];
    char field4[4];
    char field5[4];
    char field6[4];
    char field7[4];
    char field8[4];
    char field9[4];
    char field10[4];
    char field11[4];
    char field12[4];
  } monthFields;

  splitField inputFields[12] = {
    {monthFields.field1,  sizeof(monthFields.field1)},
    {monthFields.field2,  sizeof(monthFields.field2)},
    {monthFields.field3,  sizeof(monthFields.field3)},
    {monthFields.field4,  sizeof(monthFields.field4)},
    {monthFields.field5,  sizeof(monthFields.field5)},
    {monthFields.field6,  sizeof(monthFields.field6)},
    {monthFields.field7,  sizeof(monthFields.field7)},
    {monthFields.field8,  sizeof(monthFields.field8)},
    {monthFields.field9,  sizeof(monthFields.field9)},
    {monthFields.field10, sizeof(monthFields.field10)},
    {monthFields.field11, sizeof(monthFields.field11)},
    {monthFields.field12, sizeof(monthFields.field12)}
  };

  int expected=sizeof(inputFields)/sizeof(splitField);

  printf("input data: %s\n", input);
  printf("expecting %d fields\n",expected);

  int ct=strsplit(inputFields, expected, input, fieldSeparator, monthSplitSoftError);

  if (ct!=expected) {
    printf("string split %d fields, expected %d\n", ct,expected);
  }

  for (int i=0;i<expected;++i) {
    printf("field %d: %s\n",i+1,inputFields[i].field);
  }

  printf("\n");
  printf("Direct structure access, field 10: %s", monthFields.field10);
}

Below is an example compile and output. Note that in my example, I purposefully spelled out "APRIL" so that you can see how the soft error works.

$ gcc strsplitExample.c && ./a.out
input data: JAN,FEB,MAR,APRIL,MAY,JUN,JUL,AUG,SEP,OCT,NOV,DEC,FOO,BAR
expecting 12 fields
monthSplit: input field #4 is 5 bytes, expected 3 bytes
field 1: JAN
field 2: FEB
field 3: MAR
field 4: APR
field 5: MAY
field 6: JUN
field 7: JUL
field 8: AUG
field 9: SEP
field 10: OCT
field 11: NOV
field 12: DEC

Direct structure access, field 10: OCT

Enjoy!

Vector erase iterator

for( ; it != res.end();)
{
    it = res.erase(it);
}

or, more general:

for( ; it != res.end();)
{
    if (smth)
        it = res.erase(it);
    else
        ++it;
}

Unable to merge dex

For our project, we accidentally added same jar two times with different name. Removing one of them solved the issue.

How to get a complete list of object's methods and attributes?

Only to supplement:

  1. dir() is the most powerful/fundamental tool. (Most recommended)
  2. Solutions other than dir() merely provide their way of dealing the output of dir().

    Listing 2nd level attributes or not, it is important to do the sifting by yourself, because sometimes you may want to sift out internal vars with leading underscores __, but sometimes you may well need the __doc__ doc-string.

  3. __dir__() and dir() returns identical content.
  4. __dict__ and dir() are different. __dict__ returns incomplete content.
  5. IMPORTANT: __dir__() can be sometimes overwritten with a function, value or type, by the author for whatever purpose.

    Here is an example:

    \\...\\torchfun.py in traverse(self, mod, search_attributes)
    445             if prefix in traversed_mod_names:
    446                 continue
    447             names = dir(m)
    448             for name in names:
    449                 obj = getattr(m,name)
    

    TypeError: descriptor __dir__ of 'object' object needs an argument

    The author of PyTorch modified the __dir__() method to something that requires an argument. This modification makes dir() fail.

  6. If you want a reliable scheme to traverse all attributes of an object, do remember that every pythonic standard can be overridden and may not hold, and every convention may be unreliable.

How to sort a list of objects based on an attribute of the objects?

from operator import attrgetter
ut.sort(key = attrgetter('count'), reverse = True)

How do I use regular expressions in bash scripts?

It was changed between 3.1 and 3.2:

This is a terse description of the new features added to bash-3.2 since the release of bash-3.1.

Quoting the string argument to the [[ command's =~ operator now forces string matching, as with the other pattern-matching operators.

So use it without the quotes thus:

i="test"
if [[ $i =~ 200[78] ]] ; then
    echo "OK"
else
    echo "not OK"
fi

matplotlib: colorbars and its text labels

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap

#discrete color scheme
cMap = ListedColormap(['white', 'green', 'blue','red'])

#data
np.random.seed(42)
data = np.random.rand(4, 4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=cMap)

#legend
cbar = plt.colorbar(heatmap)

cbar.ax.get_yaxis().set_ticks([])
for j, lab in enumerate(['$0$','$1$','$2$','$>3$']):
    cbar.ax.text(.5, (2 * j + 1) / 8.0, lab, ha='center', va='center')
cbar.ax.get_yaxis().labelpad = 15
cbar.ax.set_ylabel('# of contacts', rotation=270)


# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False)
ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False)
ax.invert_yaxis()

#labels
column_labels = list('ABCD')
row_labels = list('WXYZ')
ax.set_xticklabels(column_labels, minor=False)
ax.set_yticklabels(row_labels, minor=False)

plt.show()

You were very close. Once you have a reference to the color bar axis, you can do what ever you want to it, including putting text labels in the middle. You might want to play with the formatting to make it more visible.

demo

How to use EditText onTextChanged event when I press the number?

put the logic in

afterTextChanged(Editable s) {
    string str = s.toString()
    // use the string str
}

documentation on TextWatcher

Sum values in a column based on date

Use a column to let each date be shown as month number; another column for day number:

      A      B       C         D
   -----  ----- ----------- --------
1     8      6    8/6/2010   12.70
2     8      7    8/7/2010   10.50
3     8      7    8/7/2010    7.10
4     8      9    8/9/2010   10.50
5     8     10   8/10/2010   15.00

The formula for A1 is =Month(C1)

The formula for B1 is =Day(C1)

For Month sums, put the month number next to each month:

      E      F         G     
   -----  ----- -------------  
1     7    July   $1,000,010 
2     8     Aug   $1,200,300 

The formula for G1 is =SumIf($A$1:$A$100, E1, $D$1:$D$100). This is a portable formula; just copy it down.

Total for the day will be be a bit more complicated, but you can probably see how to do it.

Sorting a Data Table

After setting the sort expression on the DefaultView (table.DefaultView.Sort = "Town ASC, Cutomer ASC" ) you should loop over the table using the DefaultView not the DataTable instance itself

foreach(DataRowView r in table.DefaultView)
{
    //... here you get the rows in sorted order
    Console.WriteLine(r["Town"].ToString());
}

Using the Select method of the DataTable instead, produces an array of DataRow. This array is sorted as from your request, not the DataTable

DataRow[] rowList = table.Select("", "Town ASC, Cutomer ASC");
foreach(DataRow r in rowList)
{
    Console.WriteLine(r["Town"].ToString());
}

Amazon S3 upload file and get URL

a bit old but still for anyone stumbling upon this in the future:

you can do it with one line assuming you already wrote the CredentialProvider and the AmazonS3Client.

it will look like this:

 String ImageURL = String.valueOf(s3.getUrl(
                                  ConstantsAWS3.BUCKET_NAME, //The S3 Bucket To Upload To
                                  file.getName())); //The key for the uploaded object

and if you didn't wrote the CredentialProvider and the AmazonS3Client then just add them before getting the URL like this:

  CognitoCachingCredentialsProvider credentialsProvider = new CognitoCachingCredentialsProvider(
        getApplicationContext(),
        "POOL_ID", // Identity pool ID
        Regions.US_EAST_1 // Region
);

Formatting code in Notepad++

Here is a list of the available shortcuts in Notepad++.

In case your desired functionality is not available, you are able to define own macros and assign them to a custom shortcut (i am not used to use macros).

UPDATE: I will post the shortcuts here in case the link gets invalid:

Shortcut    Command

Ctrl-C  Copy
Ctrl-X  Cut
Ctrl-V  Paste
Ctrl-Z  Undo
Ctrl-Y  Redo
Ctrl-A  Select All
Ctrl-F  Launch Find Dialog
Ctrl-H  Launch Find / Replace Dialog
Ctrl-D  Duplicate Current Line
Ctrl-L  Delete Current Line
Ctrl-T  Switch the current line position with the previous line position
F3  Find Next
Shft-F3 Find Previous
Ctrl-Shft-F Find in Files
Ctrl-F3 Find (volatil) Next
Ctrl-Shft-F3    Find (volatil) Previous
Ctrl-Shft-I Incremental Search
Ctrl-S  Save File
Ctrl-Alt-S  Save As
Ctrl-Shft-S Save All
Ctrl-O  Open File
Ctrl-N  New File
Ctrl-F2 Toggle Bookmark
F2  Go To Next Bookmark 
Shft-F2 Go To Previous Bookmark
Ctrl-G  Launch GoToLine Dialog
Ctrl-W  Close Current Document
Alt-Shft-Arrow keys or Alt + Left mouse click   Column Mode Select
F5  Launch Run Dialog
Ctrl-Space  Launch CallTip ListBox
Alt-Space   Launch Word Completion ListBox
Tab (selection of several lines)    Insert Tabulation or Space (Indent)
Shft-Tab (selection of several lines)   Remove Tabulation or Space (outdent)
Ctrl-(Keypad-/Keypad+) or Ctrl + mouse wheel butto  Zoom in (+ or up) and Zoom out (- or down)
Ctrl-Keypad/    Restore the original size from zoom 
F11 Toggle Full Screen Mode
Ctrl-Tab    Next Document
Ctrl-Shft-Tab   Previous Document
Ctrl-Shft-Up    Move Current Line Up
Ctrl-Shft-Down  Move Current Line Down
Ctrl-Alt-F  Collapse the Current Level
Ctrl-Alt-Shft-F Uncollapse the Current Level
Alt-0   Fold All
Alt-(1~8)   Collapse the Level (1~8)
Alt-Shft-0  Unfold All
Alt-Shft-(1~8)  Uncollapse the Level (1~8)
Ctrl-BackSpace  Delete to start of word
Ctrl-Delete Delete to end of word
Ctrl-Shft-BackSpace Delete to start of line
Ctrl-Shft-Delete    Delete to end of line
Ctrl-U  Convert to lower case
Ctrl-Shft-U Convert to UPPER CASE
Ctrl-B  Go to matching brace
Ctrl-Shft-R Start to record /Stop recording the macro
Ctrl-Shft-P Play recorded macro
Ctrl-Q  Block comment/uncomment
Ctrl-Shft-Q Stream comment
Ctrl-Shft-T Copy current line to clipboard
Ctrl-P  Print
Alt-F4  Exit
Ctrl-I  Split Lines
Ctrl-J  Join Lines
Ctrl-Alt-R  Text Direction RTL
Ctrl-Alt-L  Text Direction LT
F1  About

plot is not defined

If you want to use a function form a package or module in python you have to import and reference them. For example normally you do the following to draw 5 points( [1,5],[2,4],[3,3],[4,2],[5,1]) in the space:

import matplotlib.pyplot
matplotlib.pyplot.plot([1,2,3,4,5],[5,4,3,2,1],"bx")
matplotlib.pyplot.show()

In your solution

from matplotlib import*

This imports the package matplotlib and "plot is not defined" means there is no plot function in matplotlib you can access directly, but instead if you import as

from matplotlib.pyplot import *
plot([1,2,3,4,5],[5,4,3,2,1],"bx")
show()

Now you can use any function in matplotlib.pyplot without referencing them with matplotlib.pyplot.

I would recommend you to name imports you have, in this case you can prevent disambiguation and future problems with the same function names. The last and clean version of above example looks like:

import matplotlib.pyplot as plt
plt.plot([1,2,3,4,5],[5,4,3,2,1],"bx")
plt.show()

Bootstrap Align Image with text

You have two choices, either correct your markup so that it uses correct elements and utilizes the Bootstrap grid system:

_x000D_
_x000D_
@import url('http://getbootstrap.com/dist/css/bootstrap.css');
_x000D_
<div class="container">_x000D_
     <h1>About Me</h1>_x000D_
    <div class="row">_x000D_
        <div class="col-md-4">_x000D_
            <div class="imgAbt">_x000D_
                <img width="220" height="220" src="img/me.jpg" />_x000D_
            </div>_x000D_
        </div>_x000D_
        <div class="col-md-8">_x000D_
            <p>Lots of text here...With the four tiers of grids available you're bound to run into issues where, at certain breakpoints, your columns don't clear quite right as one is taller than the other. To fix that, use a combination of a .clearfix and o</p>_x000D_
        </div>_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Or, if you wish the text to closely wrap the image, change your markup to:

_x000D_
_x000D_
@import url('http://getbootstrap.com/dist/css/bootstrap.css');
_x000D_
<div class="container">_x000D_
    <h1>About Me</h1>_x000D_
    <div class="row">_x000D_
        <div class="col-md-12">_x000D_
            <img style='float:left;width:200px;height:200px; margin-right:10px;' src="img/me.jpg" />_x000D_
            <p>Lots of text here...With the four tiers of grids available you're bound to run into issues where, at certain breakpoints, your columns don't clear quite right as one is taller than the other. To fix that, use a combination of a .clearfix and o</p>_x000D_
        </div>_x000D_
    </div>
_x000D_
_x000D_
_x000D_

What is the difference between Sublime text and Github's Atom

Atom is still in beta (v0.123 as I'm writing this) but it's moving fast. Way faster than Sublime. New builds are released on a weekly basis, sometimes even few of them in the same week. In its short life span, it had more releases than Sublime which takes months to release a new feature or a bug fix. Here's an updated take on things looking back on the path Atom has taken since the launch of the beta:

  1. Sublime has better performance than Atom. Simply because it's written in C++. Atom on the other hand is a web based desktop app built on top of Chromium, and while they take performance close to heart, it will be really hard or even impossible to reach the same speed and responsiveness. Last July Atom began using React and it gave it a nice performance boost but you can still feel the difference. Apart from that, if Atom’s performance issues will not push users away - Sublime better speed up the release cycle, brush up its small UX tweaks, and consider letting in more contributors because this is where Atom is winning.

  2. Atom's package ecosystem is also growing really fast, it might not be as big as Sublime's at the moment but I have a feeling that with GitHub at it's back it will keep growing even faster. It probably has the majority of IDE like plug-ins you can think of. A major difference right now is that it can't handle files bigger than 2MB so it's something to keep in mind.

  3. The one thing you'll notice first is that the Sublime minimap is gone! Other than that, the first impression is that Atom looks almost the same as Sublime. I wrote a more in depth comparison about it in this blog post.

  4. No easy straightforward way to port your Sublime configurations, packages and such as far as I know.

Is there a free GUI management tool for Oracle Database Express?

you can always use the web based management tool that comes with oracle express db.. have tried using it? you can access it through http://host:port/apex if i remember correctly...

Alternative solutions are Oracle SQL Developer, TOAD etc...

The difference between the Runnable and Callable interfaces in Java

Let us look at where one would use Runnable and Callable.

Runnable and Callable both run on a different thread than the calling thread. But Callable can return a value and Runnable cannot. So where does this really apply.

Runnable : If you have a fire and forget task then use Runnable. Put your code inside a Runnable and when the run() method is called, you can perform your task. The calling thread really does not care when you perform your task.

Callable : If you are trying to retrieve a value from a task, then use Callable. Now callable on its own will not do the job. You will need a Future that you wrap around your Callable and get your values on future.get (). Here the calling thread will be blocked till the Future comes back with results which in turn is waiting for Callable's call() method to execute.

So think about an interface to a target class where you have both Runnable and Callable wrapped methods defined. The calling class will randomly call your interface methods not knowing which is Runnable and which is Callable. The Runnable methods will execute asynchronously, till a Callable method is called. Here the calling class's thread will block since you are retrieving values from your target class.

NOTE : Inside your target class you can make the calls to Callable and Runnable on a single thread executor, making this mechanism similar to a serial dispatch queue. So as long as the caller calls your Runnable wrapped methods the calling thread will execute really fast without blocking. As soon as it calls a Callable wrapped in Future method it will have to block till all the other queued items are executed. Only then the method will return with values. This is a synchronization mechanism.

Automatically start forever (node) on system restart

I would suggest using crontab. It's easy to use.

How to

  1. To start editing run the following replacing the "testuser" with your desired runtime user for the node process. If you choose a different user other than yourself, you will have to run this with sudo.

    $ crontab -u testuser -e
    
  2. If you have never done this before, it will ask you which editor you wish to edit with. I like vim, but will recommend nano for ease of use.

  3. Once in the editor add the following line:

    @reboot /usr/local/bin/forever start /your/path/to/your/app.js
    
  4. Save the file. You should get some feedback that the cron has been installed.

  5. For further confirmation of the installation of the cron, execute the following (again replacing "testuser" with your target username) to list the currently installed crons:

    $ crontab -u testuser -l 
    

Note that in my opinion, you should always use full paths when executing binaries in cron. Also, if the path to your forever script is not correct, run which forever to get the full path.

Given that forever calls node, you may also want to provide the full path to node:

@reboot /usr/local/bin/forever start -c /usr/local/bin/node /your/path/to/your/app.js

Further Reading

Find the number of downloads for a particular app in apple appstore

I think developers can do this for their own apps via iTunes Connect but this doesn't help you if you are looking for stats on other peoples apps.

148Apps also have some aggregate AppStore metrics on their web site that could be useful to you but, again, doesn't really give a low-level breakdown of numbers.

You could also scrape some stats from the RSS feeds generated by the iTunes Store RSS Generator but, again, this just gets currently popular apps rather than actual download numbers.

What is a regex to match ONLY an empty string?

Try looking here: https://docs.python.org/2/library/re.html

I ran into the same problem you had though. I could only build a regex that would match only the empty string and also "\n". Try trimming/replacing the newline characters in the string with another character first.

I was using http://pythex.org/ and trying weird regexes like these:

()

(?:)

^$

^(?:^\n){0}$

and so on.

Remove Array Value By index in jquery

Your syntax is incorrect, you should either specify a hash:

hash = {abc: true, def: true, ghi: true};

Or an array:

arr = ['abc','def','ghi'];

You can effectively remove an item from a hash by simply setting it to null:

hash['def'] = null;
hash.def = null;

Or removing it entirely:

delete hash.def;

To remove an item from an array you have to iterate through each item and find the one you want (there may be duplicates). You could use array searching and splicing methods:

arr.splice(arr.indexOf("def"), 1);

This finds the first index of "def" and then removes it from the array with splice. However I would recommend .filter() because it gives you more control:

arr.filter(function(item) { return item !== 'def'; });

This will create a new array with only elements that are not 'def'.

It is important to note that arr.filter() will return a new array, while arr.splice will modify the original array and return the removed elements. These can both be useful, depending on what you want to do with the items.

Including a .js file within a .js file

I basically do like this, create new element and attach that to <head>

var x = document.createElement('script');
x.src = 'http://example.com/test.js';
document.getElementsByTagName("head")[0].appendChild(x);

You may also use onload event to each script you attach, but please test it out, I am not so sure it works cross-browser or not.

x.onload=callback_function;

SQL Server Service not available in service list after installation of SQL Server Management Studio

You need to start the SQL Server manually. Press

windows + R

type

sqlservermanager12.msc

right click ->Start

Service configuration does not display SQL Server?

App.settings - the Angular way?

I figured out how to do this with InjectionTokens (see example below), and if your project was built using the Angular CLI you can use the environment files found in /environments for static application wide settings like an API endpoint, but depending on your project's requirements you will most likely end up using both since environment files are just object literals, while an injectable configuration using InjectionToken's can use the environment variables and since it's a class can have logic applied to configure it based on other factors in the application, such as initial http request data, subdomain, etc.

Injection Tokens Example

/app/app-config.module.ts

import { NgModule, InjectionToken } from '@angular/core';
import { environment } from '../environments/environment';

export let APP_CONFIG = new InjectionToken<AppConfig>('app.config');

export class AppConfig {
  apiEndpoint: string;
}

export const APP_DI_CONFIG: AppConfig = {
  apiEndpoint: environment.apiEndpoint
};

@NgModule({
  providers: [{
    provide: APP_CONFIG,
    useValue: APP_DI_CONFIG
  }]
})
export class AppConfigModule { }

/app/app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';

import { AppConfigModule } from './app-config.module';

@NgModule({
  declarations: [
    // ...
  ],
  imports: [
    // ...
    AppConfigModule
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

Now you can just DI it into any component, service, etc:

/app/core/auth.service.ts

import { Injectable, Inject } from '@angular/core';
import { Http, Response } from '@angular/http';
import { Router } from '@angular/router';
import { Observable } from 'rxjs/Observable';
import 'rxjs/add/operator/map';
import 'rxjs/add/operator/catch';
import 'rxjs/add/observable/throw';

import { APP_CONFIG, AppConfig } from '../app-config.module';
import { AuthHttp } from 'angular2-jwt';

@Injectable()
export class AuthService {

  constructor(
    private http: Http,
    private router: Router,
    private authHttp: AuthHttp,
    @Inject(APP_CONFIG) private config: AppConfig
  ) { }

  /**
   * Logs a user into the application.
   * @param payload
   */
  public login(payload: { username: string, password: string }) {
    return this.http
      .post(`${this.config.apiEndpoint}/login`, payload)
      .map((response: Response) => {
        const token = response.json().token;
        sessionStorage.setItem('token', token); // TODO: can this be done else where? interceptor
        return this.handleResponse(response); // TODO:  unset token shouldn't return the token to login
      })
      .catch(this.handleError);
  }

  // ...
}

You can then also type check the config using the exported AppConfig.

What is the use of <<<EOD in PHP?

That is not HTML, but PHP. It is called the HEREDOC string method, and is an alternative to using quotes for writing multiline strings.

The HTML in your example will be:

    <tr>
      <td>TEST</td>
    </tr>

Read the PHP documentation that explains it.

How to get the input from the Tkinter Text Widget?

Here is how I did it with python 3.5.2:

from tkinter import *
root=Tk()
def retrieve_input():
    inputValue=textBox.get("1.0","end-1c")
    print(inputValue)

textBox=Text(root, height=2, width=10)
textBox.pack()
buttonCommit=Button(root, height=1, width=10, text="Commit", 
                    command=lambda: retrieve_input())
#command=lambda: retrieve_input() >>> just means do this when i press the button
buttonCommit.pack()

mainloop()

with that, when i typed "blah blah" in the text widget and pressed the button, whatever i typed got printed out. So i think that is the answer for storing user input from Text widget to variable.

How can I add a volume to an existing Docker container?

I've successfully mount /home/<user-name> folder of my host to the /mnt folder of the existing (not running) container. You can do it in the following way:

  1. Open configuration file corresponding to the stopped container, which can be found at /var/lib/docker/containers/99d...1fb/config.v2.json (may be config.json for older versions of docker).

  2. Find MountPoints section, which was empty in my case: "MountPoints":{}. Next replace the contents with something like this (you can copy proper contents from another container with proper settings):

"MountPoints":{"/mnt":{"Source":"/home/<user-name>","Destination":"/mnt","RW":true,"Name":"","Driver":"","Type":"bind","Propagation":"rprivate","Spec":{"Type":"bind","Source":"/home/<user-name>","Target":"/mnt"},"SkipMountpointCreation":false}}

or the same (formatted):

  "MountPoints": {
    "/mnt": {
      "Source": "/home/<user-name>",
      "Destination": "/mnt",
      "RW": true,
      "Name": "",
      "Driver": "",
      "Type": "bind",
      "Propagation": "rprivate",
      "Spec": {
        "Type": "bind",
        "Source": "/home/<user-name>",
        "Target": "/mnt"
      },
      "SkipMountpointCreation": false
    }
  }
  1. Restart the docker service: service docker restart

This works for me with Ubuntu 18.04.1 and Docker 18.09.0

What are alternatives to document.write?

Just dropping a note here to say that, although using document.write is highly frowned upon due to performance concerns (synchronous DOM injection and evaluation), there is also no actual 1:1 alternative if you are using document.write to inject script tags on demand.

There are a lot of great ways to avoid having to do this (e.g. script loaders like RequireJS that manage your dependency chains) but they are more invasive and so are best used throughout the site/application.

How to delete Tkinter widgets from a window?

You simply use the destroy() method to delete the specified widgets like this:

lbl = tk.Label(....)

btn = tk.Button(....., command=lambda: lbl.destroy())

Using this you can completely destroy the specific widgets.

How to store a command in a variable in a shell script?

var=$(echo "asdf")
echo $var
# => asdf

Using this method, the command is immediately evaluated and it's return value is stored.

stored_date=$(date)
echo $stored_date
# => Thu Jan 15 10:57:16 EST 2015
# (wait a few seconds)
echo $stored_date
# => Thu Jan 15 10:57:16 EST 2015

Same with backtick

stored_date=`date`
echo $stored_date
# => Thu Jan 15 11:02:19 EST 2015
# (wait a few seconds)
echo $stored_date
# => Thu Jan 15 11:02:19 EST 2015

Using eval in the $(...) will not make it evaluated later

stored_date=$(eval "date")
echo $stored_date
# => Thu Jan 15 11:05:30 EST 2015
# (wait a few seconds)
echo $stored_date
# => Thu Jan 15 11:05:30 EST 2015

Using eval, it is evaluated when eval is used

stored_date="date" # < storing the command itself
echo $(eval "$stored_date")
# => Thu Jan 15 11:07:05 EST 2015
# (wait a few seconds)
echo $(eval "$stored_date")
# => Thu Jan 15 11:07:16 EST 2015
#                     ^^ Time changed

In the above example, if you need to run a command with arguments, put them in the string you are storing

stored_date="date -u"
# ...

For bash scripts this is rarely relevant, but one last note. Be careful with eval. Eval only strings you control, never strings coming from an untrusted user or built from untrusted user input.

  • Thanks to @CharlesDuffy for reminding me to quote the command!

Can I have a video with transparent background using HTML5 video tag?

Mp4 files can be playable with transparent background using seeThrou Js library. All you need to combine actual video and alpha channel in the single video. Also make sure to keep video height dimension below 1400 px as some of the old iphone devices wont play videos with dimension more than 2000. This is pretty useful in safari desktop and mobile devices which doesnt support webm at this time.

more details can be found in the below link https://github.com/m90/seeThru

How do I find the size of a struct?

If you want to manually count it, the size of a struct is just the size of each of its data members after accounting for alignment. There's no magic overhead bytes for a struct.

Redirect to external URI from ASP.NET MVC controller

If you're talking about ASP.NET MVC then you should have a controller method that returns the following:

return Redirect("http://www.google.com");

Otherwise we need more info on the error you're getting in the redirect. I'd step through to make sure the url isn't empty.

Calling an executable program using awk

From the AWK man page:

system(cmd)
              executes cmd and returns its exit status

The GNU AWK manual also has a section that, in part, describes the system function and provides an example:

system("date | mail -s 'awk run done' root")

GROUP_CONCAT ORDER BY

You can use SEPARATOR and ORDER BY inside the GROUP_CONCAT function in this way:

SELECT li.client_id, group_concat(li.percentage ORDER BY li.views ASC SEPARATOR ',') 
AS views, group_concat(li.percentage ORDER BY li.percentage ASC SEPARATOR ',') FROM li
GROUP BY client_id;

How do I update a GitHub forked repository?

rm -rf oldrepository
git clone ...

There may be subtler options, but it is the only way that I have any confidence that my local repository is the same as upstream.

AngularJs $http.post() does not send data

To build on @felipe-miosso's answer:

  1. Download it as an AngularJS module from here,
  2. Install it
  3. Add it to your application:

    var app = angular.module('my_app', [ ... , 'httpPostFix']);
    

AngularJS performs an OPTIONS HTTP request for a cross-origin resource

OPTIONS request are by no means an AngularJS bug, this is how Cross-Origin Resource Sharing standard mandates browsers to behave. Please refer to this document: https://developer.mozilla.org/en-US/docs/HTTP_access_control, where in the "Overview" section it says:

The Cross-Origin Resource Sharing standard works by adding new HTTP headers that allow servers to describe the set of origins that are permitted to read that information using a web browser. Additionally, for HTTP request methods that can cause side-effects on user data (in particular; for HTTP methods other than GET, or for POST usage with certain MIME types). The specification mandates that browsers "preflight" the request, soliciting supported methods from the server with an HTTP OPTIONS request header, and then, upon "approval" from the server, sending the actual request with the actual HTTP request method. Servers can also notify clients whether "credentials" (including Cookies and HTTP Authentication data) should be sent with requests.

It is very hard to provide a generic solution that would work for all the WWW servers as setup will vary depending on the server itself and HTTP verbs that you intend to support. I would encourage you to get over this excellent article (http://www.html5rocks.com/en/tutorials/cors/) that has much more details on the exact headers that needs to be sent by a server.

Convert character to ASCII numeric value in java

just a different approach

    String s = "admin";
    byte[] bytes = s.getBytes("US-ASCII");

bytes[0] will represent ascii of a.. and thus the other characters in the whole array.

Eclipse error: "Editor does not contain a main type"

Did you import the packages for the file reading stuff.

import java.io.BufferedReader;
import java.io.FileInputStream;
import java.io.InputStreamReader;

also here

cfiltering(numberOfUsers, numberOfMovies);

Are you trying to create an object or calling a method?

also another thing:

user_movie_matrix[userNo][movieNo]=rating;

you are assigning a value to a member of an instance as if it was a static variable also remove the Th in

private int user_movie_matrix[][];Th

Hope this helps.

Add text at the end of each line

  1. You can also achieve this using the backreference technique

    sed -i.bak 's/\(.*\)/\1:80/' foo.txt
    
  2. You can also use with awk like this

    awk '{print $0":80"}' foo.txt > tmp && mv tmp foo.txt
    

Fatal error: Can't open and lock privilege tables: Table 'mysql.host' doesn't exist

mysql_install_db –-user=mysql --ldata=/var/lib/mysql

Worked for me in Centos 7

Uncaught TypeError: undefined is not a function on loading jquery-min.js

I had this problem recently with the jQuery Validation plug-in, using Squishit, also getting the js error:

"undefined is not a function"

I fixed it by changing the reference to the unminified jquery.validate.js file, rather than jquery.validate.min.js.

@MvcHtmlString.Create(
    @SquishIt.Framework.Bundle.JavaScript()
        .Add("~/Scripts/Libraries/jquery-1.8.2.min.js")
        .Add("~/Scripts/Libraries/jquery-ui-1.9.1.custom.min.js")
        .Add("~/Scripts/Libraries/jquery.unobtrusive-ajax.min.js")
        .Add("~/Scripts/Libraries/jquery.validate.js")
        .Add("~/Scripts/Libraries/jquery.validate.unobtrusive.js")
         ... more files

I think that the minified version of certain files, when further compressed using Squishit, for example, might in some cases not deal with missing semi-colons and the like, as @Dustin suggests, so you might have to experiment with which files you can doubly compress, and which you just leave to Squishit or whatever you're bundling with.

Webpack.config how to just copy the index.html to the dist folder

I also found it easy and generic enough to put my index.html file in dist/ directory and add <script src='main.js'></script> to index.html to include my bundled webpack files. main.js seems to be default output name of our bundle if no other specified in webpack's conf file. I guess it's not good and long-term solution, but I hope it can help to understand how webpack works.

What's the difference between nohup and ampersand

There are many cases when small differences between environments can bite you. This is one into which I have ran recently. What is the difference between these two commands?

1 ~ $ nohup myprocess.out &
2 ~ $ myprocess.out &

The answer is the same as usual - it depends.

nohup catches the hangup signal while the ampersand does not.

What is the hangup signal?

SIGHUP - hangup detected on controlling terminal or death of controlling process (value: 1).

Normally, when running a command using & and exiting the shell afterwards, the shell will terminate the sub-command with the hangup signal (like kill -SIGHUP $PID). This can be prevented using nohup, as it catches the signal and ignores it so that it never reaches the actual application.

Fine, but like in this case there are always ‘buts’. There is no difference between these launching methods when the shell is configured in a way where it does not send SIGHUP at all.

In case you are using bash, you can use the command specified below to find out whether your shell sends SIGHUP to its child processes or not:

~ $ shopt | grep hupon

And moreover - there are cases where nohup does not work. For example, when the process you start reconnects the NOHUP signal (it is done inside, on the application code level).

In the described case, lack of differences bit me when inside a custom service launching script there was a call to a second script which sets up and launches the proper application without a nohup command.

On one Linux environment everything worked smoothly, on a second one the application quit as soon as the second script exited (detecting that case, of course took me much more time then you might think :stuck_out_tongue:).

After adding nohup as a launching method to second script, application keeps running even if the scripts will exit and this behavior became consistent on both environments.

Pass Array Parameter in SqlCommand

Since there is a method on

SqlCommand.Parameters.AddWithValue(parameterName, value)

it might be more convenient to create a method accepting a parameter (name) to replace and a list of values. It is not on the Parameters level (like AddWithValue) but on command itself so it's better to call it AddParametersWithValues and not just AddWithValues:

query:

SELECT * from TableA WHERE Age IN (@age)

usage:

sqlCommand.AddParametersWithValues("@age", 1, 2, 3);

the extension method:

public static class SqlCommandExtensions
{
    public static void AddParametersWithValues<T>(this SqlCommand cmd,  string parameterName, params T[] values)
    {
        var parameterNames = new List<string>();
        for(int i = 0; i < values.Count(); i++)
        {
            var paramName = @"@param" + i;
            cmd.Parameters.AddWithValue(paramName, values.ElementAt(i));
            parameterNames.Add(paramName);
        }

        cmd.CommandText = cmd.CommandText.Replace(parameterName, string.Join(",", parameterNames));
    }
}

Place a button right aligned

If the button is the only element on the block:

_x000D_
_x000D_
.border {_x000D_
  border: 2px blue dashed;_x000D_
}_x000D_
_x000D_
.mr-0 {_x000D_
  margin-right: 0;_x000D_
}_x000D_
.ml-auto {_x000D_
  margin-left:auto;_x000D_
}_x000D_
.d-block {_x000D_
  display:block;_x000D_
}
_x000D_
<p class="border">_x000D_
  <input type="button" class="d-block mr-0 ml-auto" value="The Button">_x000D_
</p>
_x000D_
_x000D_
_x000D_

If there are other elements on the block:

_x000D_
_x000D_
.border {_x000D_
  border: 2px indigo dashed;_x000D_
}_x000D_
_x000D_
.d-table {_x000D_
  display:table;_x000D_
}_x000D_
_x000D_
.d-table-cell {_x000D_
  display:table-cell;_x000D_
}_x000D_
_x000D_
.w-100 {_x000D_
  width: 100%;_x000D_
}_x000D_
_x000D_
.tar {_x000D_
  text-align: right;_x000D_
}
_x000D_
<div class="border d-table w-100">_x000D_
  <p class="d-table-cell">The paragraph.....lorem ipsum...etc.</p>_x000D_
  <div class="d-table-cell tar">_x000D_
    <button >The Button</button>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

With flex-box:

_x000D_
_x000D_
.flex-box {_x000D_
  display:flex;_x000D_
  justify-content:space-between;_x000D_
  outline: 2px dashed blue;_x000D_
}_x000D_
_x000D_
.flex-box-2 {_x000D_
  display:flex;_x000D_
  justify-content: flex-end;_x000D_
  outline: 2px deeppink dashed;_x000D_
}
_x000D_
<h1>Button with Text</h1>_x000D_
<div class="flex-box">_x000D_
<p>Once upon a time in a ...</p>_x000D_
<button>Read More...</button>_x000D_
</div>_x000D_
_x000D_
<h1>Only Button</h1>_x000D_
<div class="flex-box-2">_x000D_
  <button>The Button</button>_x000D_
</div>_x000D_
_x000D_
<h1>Multiple Buttons</h1>_x000D_
<div class="flex-box-2">_x000D_
  <button>Button 1</button>_x000D_
  <button>Button 2</button>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Good Luck...

Prevent cell numbers from incrementing in a formula in Excel

In Excel 2013 and resent versions, you can use F2 and F4 to speed things up when you want to toggle the lock.

About the keys:

  • F2 - With a cell selected, it places the cell in formula edit mode.
  • F4 - Toggles the cell reference lock (the $ signs).

  • Example scenario with 'A4'.

    • Pressing F4 will convert 'A4' into '$A$4'
    • Pressing F4 again converts '$A$4' into 'A$4'
    • Pressing F4 again converts 'A$4' into '$A4'
    • Pressing F4 again converts '$A4' back to the original 'A4'

How To:

  • In Excel, select a cell with a formula and hit F2 to enter formula edit mode. You can also perform these next steps directly in the Formula bar. (Issue with F2 ? Double check that 'F Lock' is on)

    • If the formula has one cell reference;
      • Hit F4 as needed and the single cell reference will toggle.
    • If the forumla has more than one cell reference, hitting F4 (without highlighting anything) will toggle the last cell reference in the formula.
    • If the formula has more than one cell reference and you want to change them all;
      • You can use your mouse to highlight the entire formula or you can use the following keyboard shortcuts;
      • Hit End key (If needed. Cursor is at end by default)
      • Hit Ctrl + Shift + Home keys to highlight the entire formula
      • Hit F4 as needed
    • If the formula has more than one cell reference and you only want to edit specific ones;
      • Highlight the specific values with your mouse or keyboard ( Shift and arrow keys) and then hit F4 as needed.

Notes:

  • These notes are based on my observations while I was looking into this for one of my own projects.
  • It only works on one cell formula at a time.
  • Hitting F4 without selecting anything will update the locking on the last cell reference in the formula.
  • Hitting F4 when you have mixed locking in the formula will convert everything to the same thing. Example two different cell references like '$A4' and 'A$4' will both become 'A4'. This is nice because it can prevent a lot of second guessing and cleanup.
  • Ctrl+A does not work in the formula editor but you can hit the End key and then Ctrl + Shift + Home to highlight the entire formula. Hitting Home and then Ctrl + Shift + End.
  • OS and Hardware manufactures have many different keyboard bindings for the Function (F Lock) keys so F2 and F4 may do different things. As an example, some users may have to hold down you 'F Lock' key on some laptops.
  • 'DrStrangepork' commented about F4 actually closes Excel which can be true but it depends on what you last selected. Excel changes the behavior of F4 depending on the current state of Excel. If you have the cell selected and are in formula edit mode (F2), F4 will toggle cell reference locking as Alexandre had originally suggested. While playing with this, I've had F4 do at least 5 different things. I view F4 in Excel as an all purpose function key that behaves something like this; "As an Excel user, given my last action, automate or repeat logical next step for me".

`IF` statement with 3 possible answers each based on 3 different ranges

You need to use the AND function for the multiple conditions:

=IF(AND(A2>=75, A2<=79),0.255,IF(AND(A2>=80, X2<=84),0.327,IF(A2>=85,0.559,0)))

int array to string

string result = arr.Aggregate("", (s, i) => s + i.ToString());

(Disclaimer: If you have a lot of digits (hundreds, at least) and you care about performance, I suggest eschewing this method and using a StringBuilder, as in JaredPar's answer.)

How to remove last n characters from every element in the R vector

Here's a way with gsub:

cs <- c("foo_bar","bar_foo","apple","beer")
gsub('.{3}$', '', cs)
# [1] "foo_" "bar_" "ap"   "b"

Relational Database Design Patterns?

After many years of database development I can say there are some no goes and some question that you should answer before you begin:

questions:

  • Do you want use in the future another DBMS? If yes then does not use to special SQL stuff of the current DBMS. Remove logic in your application.

Does not use:

  • white spaces in table names and column names
  • Non Ascii characters in table and column names
  • binding to a specific lower case or upper case. And never use 2 tables or columns that differ only with lower case and upper case.
  • does not use SQL keywords for tables or columns names like "FROM", "BETWEEN", "DELETE", etc

recomendations:

  • Use NVARCHAR or equivalents for unicode support then you have no problems with codepages.
  • Give every column a unique name. This make it easer on join to select the column. It is very difficult if every table has a column "ID" or "Name" or "Description". Use XyzID and AbcID.
  • Use a resource bundle or equals for complex SQL expressions. It make it easer to switch to another DBMS.
  • Does not cast hard on any data type. Another DBMS can not have this data type. FOr example Oracle daes not have a SMALLINT only a number.

I hope this is a good starting point.

how to check if List<T> element contains an item with a Particular Property Value

bool contains = pricePublicList.Any(p => p.Size == 200);

2 ways for "ClearContents" on VBA Excel, but 1 work fine. Why?

For numerical addressing of cells try to enable S1O1 checkbox in MS Excel settings. It is the second tab from top (i.e. Formulas), somewhere mid-page in my Hungarian version.

If enabled, it handles VBA addressing in both styles, i.e. Range("A1:B10") and Range(Cells(1, 1), Cells(10, 2)). I assume it handles Range("A1:B10") style only, if not enabled.

Good luck!

(Note, that Range("A1:B10") represents a 2x10 square, while Range(Cells(1, 1), Cells(10, 2)) represents 10x2. Using column numbers instead of letters will not affect the order of addresing.)

Returning value from Thread

Using Future described in above answers does the job, but a bit less significantly as f.get(), blocks the thread until it gets the result, which violates concurrency.

Best solution is to use Guava's ListenableFuture. An example :

    ListenableFuture<Void> future = MoreExecutors.listeningDecorator(Executors.newFixedThreadPool(1, new NamedThreadFactory).submit(new Callable<Void>()
    {
        @Override
        public Void call() throws Exception
        {
            someBackgroundTask();
        }
    });
    Futures.addCallback(future, new FutureCallback<Long>()
    {
        @Override
        public void onSuccess(Long result)
        {
            doSomething();
        }

        @Override
        public void onFailure(Throwable t)
        {

        }
    };

div inside php echo

You can do the following:

echo '<div class="my_class">';
echo ($cart->count_product > 0) ? $cart->count_product : '';
echo '</div>';

If you want to have it inside your statement, do this:

if($cart->count_product > 0) 
{
    echo '<div class="my_class">'.$cart->count_product.'</div>';
}

You don't need the else statement, since you're only going to output the above when it's truthy anyway.

SQL DROP TABLE foreign key constraint

No, this will not drop your table if there are indeed foreign keys referencing it.

To get all foreign key relationships referencing your table, you could use this SQL (if you're on SQL Server 2005 and up):

SELECT * 
FROM sys.foreign_keys
WHERE referenced_object_id = object_id('Student')

and if there are any, with this statement here, you could create SQL statements to actually drop those FK relations:

SELECT 
    'ALTER TABLE [' +  OBJECT_SCHEMA_NAME(parent_object_id) +
    '].[' + OBJECT_NAME(parent_object_id) + 
    '] DROP CONSTRAINT [' + name + ']'
FROM sys.foreign_keys
WHERE referenced_object_id = object_id('Student')

How to list files inside a folder with SQL Server

I hunted around for ages to find a decent easy solution to this and in the end found some ridiculously complicated CLR solutions so decided to write my own simple VB one. Simply create a new VB CLR project from the Database tab under Installed Templates, and then add a new SQL CLR VB User Defined Function. I renamed it to CLRGetFilesInDir.vb. Here's the code inside it...

Imports System
Imports System.Data
Imports System.Data.Sql
Imports System.Data.SqlTypes
Imports Microsoft.SqlServer.Server
Imports System.IO
-----------------------------------------------------------------------------
Public Class CLRFilesInDir
-----------------------------------------------------------------------------
<SqlFunction(FillRowMethodName:="FillRowFiles", IsDeterministic:=True, IsPrecise:=True, TableDefinition:="FilePath nvarchar(4000)")> _
Public Shared Function GetFiles(PathName As SqlString, Pattern As SqlString) As IEnumerable
    Dim FileNames As String()

    Try
    FileNames = Directory.GetFiles(PathName, Pattern, SearchOption.TopDirectoryOnly)
    Catch
        FileNames = Nothing
    End Try

    Return FileNames

End Function
-----------------------------------------------------------------------------
Public Shared Sub FillRowFiles(ByVal obj As Object, ByRef Val As SqlString)
    Val = CType(obj, String).ToString
End Sub

End Class

I also changed the Assembly Name in the Project Properties window to CLRExcelFiles, and the Default Namespace to CLRGetExcelFiles.

NOTE: Set the target framework to 3.5 if you are using anything less that SQL Server 2012.

Compile the project and then copy the CLRExcelFiles.dll from \bin\release to somewhere like C:\temp on the SQL Server machine, not your own.

In SSMS:-

CREATE ASSEMBLY <your assembly name in here - anything you like>
FROM 'C:\temp\CLRExcelFiles.dll';

CREATE FUNCTION dbo.fnGetFiles
(
@PathName NVARCHAR(MAX),
@Pattern NVARCHAR(MAX)
)
RETURNS TABLE (Val NVARCHAR(100))
AS
EXTERNAL NAME <your assembly name>."CLRGetExcelFiles.CLRFilesInDir".GetFiles;
GO

then call it

SELECT * FROM dbo.fnGetFiles('\\<SERVERNAME>\<$SHARE>\<folder>\' , '*.xls')

NOTE: Even though I changed the Permission Level to EXTERNAL_ACCESS on the SQLCLR tab under Project Properties, I still needed to run this every time I (re)created it.

ALTER ASSEMBLY [CLRFilesInDirAssembly] 
WITH PERMISSION_SET = EXTERNAL_ACCESS 
GO

and wullah! that should work.

How to get the dimensions of a tensor (in TensorFlow) at graph construction time?

A function to access the values:

def shape(tensor):
    s = tensor.get_shape()
    return tuple([s[i].value for i in range(0, len(s))])

Example:

batch_size, num_feats = shape(logits)

Trigger a Travis-CI rebuild without pushing a commit?

Log in to Travis and go to the build page. You will see a "Restart Build" button on the top-right corner, next to the gear icon:

screengrab

Note: you need to have write access to the linked GitHub repo for this to work.

jQuery datepicker, onSelect won't work

$('.date-picker').datepicker({
                    autoclose : true,
                    todayHighlight : true,
                    clearBtn: true,
                    format: 'yyyy-mm-dd', 
                    onSelect: function(value, date) { 
                         alert(123);
                    },
                    todayBtn: "linked",
                    startView: 0, maxViewMode: 0,minViewMode:0

                    }).on('changeDate',function(ev){
                    //this is right events ,trust me
                    }
});

Force drop mysql bypassing foreign key constraint

Since you are not interested in keeping any data, drop the entire database and create a new one.

calling java methods in javascript code

When it is on server side, use web services - maybe RESTful with JSON.

  • create a web service (for example with Tomcat)
  • call its URL from JavaScript (for example with JQuery or dojo)

When Java code is in applet you can use JavaScript bridge. The bridge between the Java and JavaScript programming languages, known informally as LiveConnect, is implemented in Java plugin. Formerly Mozilla-specific LiveConnect functionality, such as the ability to call static Java methods, instantiate new Java objects and reference third-party packages from JavaScript, is now available in all browsers.

Below is example from documentation. Look at methodReturningString.

Java code:

public class MethodInvocation extends Applet {
    public void noArgMethod() { ... }
    public void someMethod(String arg) { ... }
    public void someMethod(int arg) { ... }
    public int  methodReturningInt() { return 5; }
    public String methodReturningString() { return "Hello"; }
    public OtherClass methodReturningObject() { return new OtherClass(); }
}

public class OtherClass {
    public void anotherMethod();
}

Web page and JavaScript code:

<applet id="app"
        archive="examples.jar"
        code="MethodInvocation" ...>
</applet>
<script language="javascript">
    app.noArgMethod();
    app.someMethod("Hello");
    app.someMethod(5);
    var five = app.methodReturningInt();
    var hello = app.methodReturningString();
    app.methodReturningObject().anotherMethod();
</script>

angularjs make a simple countdown

You should use $scope.$apply() when you execute an angular expression from outside of the angular framework.

function countController($scope){
    $scope.countDown = 10;    
    var timer = setInterval(function(){
        $scope.countDown--;
        $scope.$apply();
        console.log($scope.countDown);
    }, 1000);  
}

http://jsfiddle.net/andreev_artem/48Fm2/

How to concatenate two strings to build a complete path

#!/bin/bash

read -p "Enter a directory: " BASEPATH

SUBFOLD1=${BASEPATH%%/}/subFold1
SUBFOLD2=${BASEPATH%%/}/subFold2

echo "I will create $SUBFOLD1 and $SUBFOLD2"

# mkdir -p $SUBFOLD1
# mkdir -p $SUBFOLD2

And if you want to use readline so you get completion and all that, add a -e to the call to read:

read -e -p "Enter a directory: " BASEPATH

How do you get the Git repository's name in some Git repository?

If you want the whole GitHub repository name ('full name') - user/repository, and you want to do it in with Ruby...

git remote show origin -n | ruby -ne 'puts /^\s*Fetch.*:(.*).git/.match($_)[1] rescue nil'

How to format numbers by prepending 0 to single-digit numbers?

My Example like this

         var n =9;
         var checkval=('00'+n).slice(-2);
         console.log(checkval)

and the output is 09

line breaks in a textarea

This works on me.

 str_replace(array("\r", "\n"), '&#10;', $textareavalue);

Find UNC path of a network drive?

This question has been answered already, but since there is a more convenient way to get the UNC path and some more I recommend using Path Copy, which is free and you can practically get any path you want with one click:

https://pathcopycopy.github.io/

Here is a screenshot demonstrating how it works. The latest version has more options and definitely UNC Path too:

enter image description here

Android Studio Image Asset Launcher Icon Background Color

To make background transparent, set shape as None. See the image below:

enter image description here

EDIT:

For Android Studio 3.0, you can set it from Legacy Tab

enter image description here

Access images inside public folder in laravel

In my case it worked perfectly

<img style="border-radius: 50%;height: 50px;width: 80px;"  src="<?php echo asset("storage/TeacherImages/{$teacher->profilePic}")?>">

this is used to display image from folder i hope this will help someone looking for this type of code

Java string split with "." (dot)

You need to escape the dot if you want to split on a literal dot:

String extensionRemoved = filename.split("\\.")[0];

Otherwise you are splitting on the regex ., which means "any character".
Note the double backslash needed to create a single backslash in the regex.


You're getting an ArrayIndexOutOfBoundsException because your input string is just a dot, ie ".", which is an edge case that produces an empty array when split on dot; split(regex) removes all trailing blanks from the result, but since splitting a dot on a dot leaves only two blanks, after trailing blanks are removed you're left with an empty array.

To avoid getting an ArrayIndexOutOfBoundsException for this edge case, use the overloaded version of split(regex, limit), which has a second parameter that is the size limit for the resulting array. When limit is negative, the behaviour of removing trailing blanks from the resulting array is disabled:

".".split("\\.", -1) // returns an array of two blanks, ie ["", ""]

ie, when filename is just a dot ".", calling filename.split("\\.", -1)[0] will return a blank, but calling filename.split("\\.")[0] will throw an ArrayIndexOutOfBoundsException.

Fix CSS hover on iPhone/iPad/iPod

  1. Assigning an event listener to the target element seems to work. (Works with 'click', at least.) CSS hover on ios works only if an event listener is assigned

  2. Wrapping the target element in an a[href=trivial] also seems to work. https://stackoverflow.com/a/28792519/1378390

A related note/diagram on mobile Safari's algorithm for handling clicks and other events is here: Is it possible to force ignore the :hover pseudoclass for iPhone/iPad users?

How do I create a WPF Rounded Corner container?

I know that this isn't an answer to the initial question ... but you often want to clip the inner content of that rounded corner border you just created.

Chris Cavanagh has come up with an excellent way to do just this.

I have tried a couple different approaches to this ... and I think this one rocks.

Here is the xaml below:

<Page
    xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
    xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
    Background="Black"
>
    <!-- Rounded yellow border -->
    <Border
        HorizontalAlignment="Center"
        VerticalAlignment="Center"
        BorderBrush="Yellow"
        BorderThickness="3"
        CornerRadius="10"
        Padding="2"
    >
        <Grid>
            <!-- Rounded mask (stretches to fill Grid) -->
            <Border
                Name="mask"
                Background="White"
                CornerRadius="7"
            />

            <!-- Main content container -->
            <StackPanel>
                <!-- Use a VisualBrush of 'mask' as the opacity mask -->
                <StackPanel.OpacityMask>
                    <VisualBrush Visual="{Binding ElementName=mask}"/>
                </StackPanel.OpacityMask>

                <!-- Any content -->
                <Image Source="http://chriscavanagh.files.wordpress.com/2006/12/chriss-blog-banner.jpg"/>
                <Rectangle
                    Height="50"
                    Fill="Red"/>
                <Rectangle
                    Height="50"
                    Fill="White"/>
                <Rectangle
                    Height="50"
                    Fill="Blue"/>
            </StackPanel>
        </Grid>
    </Border>
</Page>

INSERT INTO from two different server database

USE [mydb1]

SELECT *
INTO mytable1
FROM OPENDATASOURCE (
        'SQLNCLI'
        ,'Data Source=XXX.XX.XX.XXX;Initial Catalog=mydb2;User ID=XXX;Password=XXXX'
        ).[mydb2].dbo.mytable2
    /*  steps - 
            1-  [mydb1] means our opend connection database 
            2-  mytable1 means create copy table in mydb1 database where we want insert record
            3-  XXX.XX.XX.XXX - another server name.
            4-  mydb2 another server database.
            5-  write User id and Password of another server credential
            6-  mytable2 is another server table where u fetch record from it. */

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

Removing all non-numeric characters from string in Python

Many right answers but in case you want it in a float, directly, without using regex:

x= '$123.45M'

float(''.join(c for c in x if (c.isdigit() or c =='.'))

123.45

You can change the point for a comma depending on your needs.

change for this if you know your number is an integer

x='$1123'    
int(''.join(c for c in x if c.isdigit())

1123

contenteditable change events

Here's what worked for me:

   var clicked = {} 
   $("[contenteditable='true']").each(function(){       
        var id = $(this).attr("id");
        $(this).bind('focus', function() {
            // store the original value of element first time it gets focus
            if(!(id in clicked)){
                clicked[id] = $(this).html()
            }
        });
   });

   // then once the user clicks on save
   $("#save").click(function(){
            for(var id in clicked){
                var original = clicked[id];
                var current = $("#"+id).html();
                // check if value changed
                if(original != current) save(id,current);
            }
   });

How to SUM parts of a column which have same text value in different column in the same row

A PivotTable might suit, though I am not quite certain of the layout of your data:

SO19669814 example

The bold numbers (one of each pair of duplicates) need not be shown as the field does not have to be subtotalled eg:

SO19669814 second example

Reload child component when variables on parent component changes. Angular2

You can use @input with ngOnChanges, to see the changes when it happened.

reference: https://angular.io/api/core/OnChanges

(or)

If you want to pass data between multiple component or routes then go with Rxjs way.

Service.ts

import { Injectable } from '@angular/core';
import { Observable, Subject } from 'rxjs';

@Injectable({ providedIn: 'root' })
export class MessageService {
  private subject = new Subject<any>();

  sendMessage(message: string) {
    this.subject.next({ text: message });
  }

  clearMessages() {
    this.subject.next();
  }

  getMessage(): Observable<any> {
    return this.subject.asObservable();
  }
}

Component.ts

import { Component, OnDestroy } from '@angular/core';
import { Subscription } from 'rxjs';

import { MessageService } from './_services/index';

@Component({
  selector: 'app',
  templateUrl: 'app.component.html'
})

export class AppComponent implements OnDestroy {
  messages: any[] = [];
  subscription: Subscription;

  constructor(private messageService: MessageService) {
    // subscribe to home component messages
    this.subscription = this.messageService.getMessage().subscribe(message => {
      if (message) {
        this.messages.push(message);
      } else {
        // clear messages when empty message received
        this.messages = [];
      }
    });
  }

  ngOnDestroy() {
    // unsubscribe to ensure no memory leaks
    this.subscription.unsubscribe();
  }
}

Reference: http://jasonwatmore.com/post/2019/02/07/angular-7-communicating-between-components-with-observable-subject

Check whether a value is a number in JavaScript or jQuery

function isNumber(n) {
  return !isNaN(parseFloat(n)) && isFinite(n);
}

Why is textarea filled with mysterious white spaces?

Well, everything between <textarea> and </textarea> is used as the default value for your textarea box. There is some whitespace in your example there. Try to eliminate all of that.

Merge Two Lists in R

Here are two options, the first:

both <- list(first, second)
n <- unique(unlist(lapply(both, names)))
names(n) <- n
lapply(n, function(ni) unlist(lapply(both, `[[`, ni)))

and the second, which works only if they have the same structure:

apply(cbind(first, second),1,function(x) unname(unlist(x)))

Both give the desired result.

Generate a UUID on iOS from Swift

Each time the same will be generated:

if let uuid = UIDevice.current.identifierForVendor?.uuidString {
    print(uuid)
}

Each time a new one will be generated:

let uuid = UUID().uuidString
print(uuid)

JavaScript open in a new window, not tab

I may be wrong, but from what I understand, this is controlled by the user's browser preferences, and I do not believe that this can be overridden.

Failed to load resource: net::ERR_FILE_NOT_FOUND loading json.js

I got the same error using:

<link rel="stylesheet" href="//fonts.googleapis.com/css?family=Source+Sans+Pro:400,400i,700,700i,900,900i" type="text/css" media="all">

But once I added https: in the beginning of the href the error disappeared.

<link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:400,400i,700,700i,900,900i" type="text/css" media="all">

how do I loop through a line from a csv file in powershell

A slightly other way of iterating through each column of each line of a CSV-file would be

$path = "d:\scratch\export.csv"
$csv = Import-Csv -path $path

foreach($line in $csv)
{ 
    $properties = $line | Get-Member -MemberType Properties
    for($i=0; $i -lt $properties.Count;$i++)
    {
        $column = $properties[$i]
        $columnvalue = $line | Select -ExpandProperty $column.Name

        # doSomething $column.Name $columnvalue 
        # doSomething $i $columnvalue 
    }
} 

so you have the choice: you can use either $column.Name to get the name of the column, or $i to get the number of the column

multiple ways of calling parent method in php

There are three scenarios (that I can think of) where you would call a method in a subclass where the method exits in the parent class:

  1. Method is not overwritten by subclass, only exists in parent.

    This is the same as your example, and generally it's better to use $this -> get_species(); You are right that in this case the two are effectively the same, but the method has been inherited by the subclass, so there is no reason to differentiate. By using $this you stay consistent between inherited methods and locally declared methods.

  2. Method is overwritten by the subclass and has totally unique logic from the parent.

    In this case, you would obviously want to use $this -> get_species(); because you don't want the parent's version of the method executed. Again, by consistently using $this, you don't need to worry about the distinction between this case and the first.

  3. Method extends parent class, adding on to what the parent method achieves.

    In this case, you still want to use `$this -> get_species(); when calling the method from other methods of the subclass. The one place you will call the parent method would be from the method that is overwriting the parent method. Example:

    abstract class Animal {
    
        function get_species() {
    
            echo "I am an animal.";
    
        }
    
     }
    
     class Dog extends Animal {
    
         function __construct(){
    
             $this->get_species();
         }
    
         function get_species(){
    
             parent::get_species();
             echo "More specifically, I am a dog.";
         }
    }
    

The only scenario I can imagine where you would need to call the parent method directly outside of the overriding method would be if they did two different things and you knew you needed the parent's version of the method, not the local. This shouldn't be the case, but if it did present itself, the clean way to approach this would be to create a new method with a name like get_parentSpecies() where all it does is call the parent method:

function get_parentSpecies(){

     parent::get_species();
}

Again, this keeps everything nice and consistent, allowing for changes/modifications to the local method rather than relying on the parent method.

Update statement using with clause

The WITH syntax appears to be valid in an inline view, e.g.

UPDATE (WITH comp AS ...
        SELECT SomeColumn, ComputedValue FROM t INNER JOIN comp ...)
   SET SomeColumn=ComputedValue;

But in the quick tests I did this always failed with ORA-01732: data manipulation operation not legal on this view, although it succeeded if I rewrote to eliminate the WITH clause. So the refactoring may interfere with Oracle's ability to guarantee key-preservation.

You should be able to use a MERGE, though. Using the simple example you've posted this doesn't even require a WITH clause:

MERGE INTO mytable t
USING (select *, 42 as ComputedValue from mytable where id = 1) comp
ON (t.id = comp.id)
WHEN MATCHED THEN UPDATE SET SomeColumn=ComputedValue;

But I understand you have a more complex subquery you want to factor out. I think that you will be able to make the subquery in the USING clause arbitrarily complex, incorporating multiple WITH clauses.

How do I parse JSON from a Java HTTPResponse?

Jackson appears to support some amount of JSON parsing straight from an InputStream. My understanding is that it runs on Android and is fairly quick. On the other hand, it is an extra JAR to include with your app, increasing download and on-flash size.

Including non-Python files with setup.py

I wanted to post a comment to one of the questions but I don't enough reputation to do that >.>

Here's what worked for me (came up with it after referring the docs):

package_data={
    'mypkg': ['../*.txt']
},

include_package_data: False

The last line was, strangely enough, also crucial for me (you can also omit this keyword argument - it works the same).

What this does is it copies all text files in your top-level or root directory (one level up from the package mypkg you want to distribute).

Hope this helps!

Inline elements shifting when made bold on hover

_x000D_
_x000D_
li {_x000D_
    display: inline-block;_x000D_
    font-size: 0;_x000D_
}_x000D_
li a {_x000D_
    display:inline-block;_x000D_
    text-align:center;_x000D_
    font: normal 16px Arial;_x000D_
    text-transform: uppercase;_x000D_
}_x000D_
a:hover {_x000D_
    font-weight:bold;_x000D_
}_x000D_
a::before {_x000D_
    display: block;_x000D_
    content: attr(title);_x000D_
    font-weight: bold;_x000D_
    height: 0;_x000D_
    overflow: hidden;_x000D_
    visibility: hidden;_x000D_
}
_x000D_
<ul>_x000D_
    <li><a href="#" title="height">height</a></li>_x000D_
    <li><a href="#" title="icon">icon</a></li>_x000D_
    <li><a href="#" title="left">left</a></li>_x000D_
    <li><a href="#" title="letter-spacing">letter-spacing</a></li>_x000D_
    <li><a href="#" title="line-height">line-height</a></li>_x000D_
</ul>
_x000D_
_x000D_
_x000D_

Check the working example on JSfiddle. The idea is to reserve space for bolded (or any :hover state styles) content in :before pseudo element and using title tag as a source for content.

MySQL case sensitive query

Whilst the listed answer is correct, may I suggest that if your column is to hold case sensitive strings you read the documentation and alter your table definition accordingly.

In my case this amounted to defining my column as:

`tag` varchar(255) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL DEFAULT ''

This is in my opinion preferential to adjusting your queries.

Karma: Running a single test file from command line

Even though --files is no longer supported, you can use an env variable to provide a list of files:

// karma.conf.js
function getSpecs(specList) {
  if (specList) {
    return specList.split(',')
  } else {
    return ['**/*_spec.js'] // whatever your default glob is
  }
}

module.exports = function(config) {
  config.set({
    //...
    files: ['app.js'].concat(getSpecs(process.env.KARMA_SPECS))
  });
});

Then in CLI:

$ env KARMA_SPECS="spec1.js,spec2.js" karma start karma.conf.js --single-run

How to deal with SettingWithCopyWarning in Pandas

In general the point of the SettingWithCopyWarning is to show users (and especially new users) that they may be operating on a copy and not the original as they think. There are false positives (IOW if you know what you are doing it could be ok). One possibility is simply to turn off the (by default warn) warning as @Garrett suggest.

Here is another option:

In [1]: df = DataFrame(np.random.randn(5, 2), columns=list('AB'))

In [2]: dfa = df.ix[:, [1, 0]]

In [3]: dfa.is_copy
Out[3]: True

In [4]: dfa['A'] /= 2
/usr/local/bin/ipython:1: SettingWithCopyWarning: A value is trying to be set on a copy of a slice from a DataFrame.
Try using .loc[row_index,col_indexer] = value instead
  #!/usr/local/bin/python

You can set the is_copy flag to False, which will effectively turn off the check, for that object:

In [5]: dfa.is_copy = False

In [6]: dfa['A'] /= 2

If you explicitly copy then no further warning will happen:

In [7]: dfa = df.ix[:, [1, 0]].copy()

In [8]: dfa['A'] /= 2

The code the OP is showing above, while legitimate, and probably something I do as well, is technically a case for this warning, and not a false positive. Another way to not have the warning would be to do the selection operation via reindex, e.g.

quote_df = quote_df.reindex(columns=['STK', ...])

Or,

quote_df = quote_df.reindex(['STK', ...], axis=1)  # v.0.21

How to convert DateTime? to DateTime

You can use a simple cast:

DateTime dtValue = (DateTime) dtNullAbleSource;

As Leandro Tupone said, you have to check if the var is null before

Check if a record exists in the database

sda = new SqlCeDataAdapter("SELECT COUNT(regNumber) AS i FROM  tblAttendance",con);
sda.Fill(dt);

string i = dt.Rows[0]["i"].ToString();
int bar = Convert.ToInt32(i);

if (bar >= 1){

    dt.Clear();
    MetroFramework.MetroMessageBox.Show(this, "something");
}
else if(bar <= 0) {

    dt.Clear();
    MetroFramework.MetroMessageBox.Show(this, "empty");
}

Storing SHA1 hash values in MySQL

So the length is between 10 16-bit chars, and 40 hex digits.

In any case decide the format you are going to store, and make the field a fixed size based on that format. That way you won't have any wasted space.

What do Push and Pop mean for Stacks?

after all these good examples adam shankman still can't make sense of it. I think you should open up some code and try it. The second you try a myStack.Push(1) and myStack.Pop(1) you really should get the picture. But by the looks of it, even that will be a challenge for you!

Get property value from string using reflection

public static TValue GetFieldValue<TValue>(this object instance, string name)
{
    var type = instance.GetType(); 
    var field = type.GetFields(BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance).FirstOrDefault(e => typeof(TValue).IsAssignableFrom(e.FieldType) && e.Name == name);
    return (TValue)field?.GetValue(instance);
}

public static TValue GetPropertyValue<TValue>(this object instance, string name)
{
    var type = instance.GetType();
    var field = type.GetProperties(BindingFlags.NonPublic | BindingFlags.Static | BindingFlags.Instance).FirstOrDefault(e => typeof(TValue).IsAssignableFrom(e.PropertyType) && e.Name == name);
    return (TValue)field?.GetValue(instance);
}

mysqli_fetch_assoc() expects parameter 1 to be mysqli_result, boolean given

Mysqli makes use of object oriented programming. Try using this approach instead:

function dbCon() {
        if($mysqli = new mysqli('$hostname','$username','$password','$databasename')) return $mysqli; else return false;
}

if(!dbCon())
exit("<script language='javascript'>alert('Unable to connect to database')</script>");
else $con=dbCon();

if (isset($_GET['part'])){
    $partid = $_GET['part'];
    $sql = "SELECT * 
        FROM $usertable 
        WHERE PartNumber = $partid";

    $result=$con->query($sql_query);
    $row = $result->fetch_assoc();

    $partnumber = $partid;
    $nsn = $row["NSN"];
    $description = $row["Description"];
    $quantity = $row["Quantity"];
    $condition = $row["Conditio"];
}

Let me know if you have any questions, I could not test this code so you might need to tripple check it!

Test file upload using HTTP PUT method

In my opinion the best tool for such testing is curl. Its --upload-file option uploads a file by PUT, which is exactly what you want (and it can do much more, like modifying HTTP headers, in case you need it):

curl http://myservice --upload-file file.txt

Use getElementById on HTMLElement instead of HTMLDocument

I would use XMLHTTP request to retrieve page content as much faster. Then it is easy enough to use querySelectorAll to apply a CSS class selector to grab by class name. Then you access the child elements by tag name and index.

Option Explicit
Public Sub GetInfo()
    Dim sResponse As String, html As HTMLDocument, elements As Object, i As Long

    With CreateObject("MSXML2.XMLHTTP")
        .Open "GET", "https://www.hsbc.com/about-hsbc/leadership", False
        .setRequestHeader "If-Modified-Since", "Sat, 1 Jan 2000 00:00:00 GMT"
        .send
        sResponse = StrConv(.responseBody, vbUnicode)
    End With
    Set html = New HTMLDocument
    With html
        .body.innerHTML = sResponse
        Set elements = .querySelectorAll(".profile-col1")
        For i = 0 To elements.Length - 1
            Debug.Print String(20, Chr$(61))
            Debug.Print elements.item(i).getElementsByTagName("a")(0).innerText
            Debug.Print elements.item(i).getElementsByTagName("p")(0).innerText
            Debug.Print elements.item(i).getElementsByTagName("p")(1).innerText
        Next
    End With
End Sub

References:

VBE > Tools > References > Microsoft HTML Object Library

Is it possible to hide/encode/encrypt php source code and let others have the system?

You could just split the frontend and backend. The frontend is hosted on the customers server with an API that makes calls to the backend on your server. This keeps all of the proprietary code proprietary and forces users to sign up / pay for subscriptions.

"’" showing on page instead of " ' "

You have a mismatch in your character encoding; your string is encoded in one encoding (UTF-8) and whatever is interpreting this page is using another (say ASCII).

Always specify your encoding in your http headers and make sure this matches your framework's definition of encoding.

Sample http header:

Content-Type    text/html; charset=utf-8

Setting encoding in asp.net

<configuration>
  <system.web>
    <globalization
      fileEncoding="utf-8"
      requestEncoding="utf-8"
      responseEncoding="utf-8"
      culture="en-US"
      uiCulture="de-DE"
    />
  </system.web>
</configuration>

Setting encoding in jsp

Sort an Array by keys based on another Array?

function sortArrayByArray(array $toSort, array $sortByValuesAsKeys)
{
    $commonKeysInOrder = array_intersect_key(array_flip($sortByValuesAsKeys), $toSort);
    $commonKeysWithValue = array_intersect_key($toSort, $commonKeysInOrder);
    $sorted = array_merge($commonKeysInOrder, $commonKeysWithValue);
    return $sorted;
}

Is it possible to insert multiple rows at a time in an SQLite database?

update

As BrianCampbell points out here, SQLite 3.7.11 and above now supports the simpler syntax of the original post. However, the approach shown is still appropriate if you want maximum compatibility across legacy databases.

original answer

If I had privileges, I would bump river's reply: You can insert multiple rows in SQLite, you just need different syntax. To make it perfectly clear, the OPs MySQL example:

INSERT INTO 'tablename' ('column1', 'column2') VALUES
  ('data1', 'data2'),
  ('data1', 'data2'),
  ('data1', 'data2'),
  ('data1', 'data2');

This can be recast into SQLite as:

     INSERT INTO 'tablename'
          SELECT 'data1' AS 'column1', 'data2' AS 'column2'
UNION ALL SELECT 'data1', 'data2'
UNION ALL SELECT 'data1', 'data2'
UNION ALL SELECT 'data1', 'data2'

a note on performance

I originally used this technique to efficiently load large datasets from Ruby on Rails. However, as Jaime Cook points out, it's not clear this is any faster wrapping individual INSERTs within a single transaction:

BEGIN TRANSACTION;
INSERT INTO 'tablename' table VALUES ('data1', 'data2');
INSERT INTO 'tablename' table VALUES ('data3', 'data4');
...
COMMIT;

If efficiency is your goal, you should try this first.

a note on UNION vs UNION ALL

As several people commented, if you use UNION ALL (as shown above), all rows will be inserted, so in this case, you'd get four rows of data1, data2. If you omit the ALL, then duplicate rows will be eliminated (and the operation will presumably be a bit slower). We're using UNION ALL since it more closely matches the semantics of the original post.

in closing

P.S.: Please +1 river's reply, as it presented the solution first.

How to preSelect an html dropdown list with php?

I use inline if's

($_POST['category'] == $data['id'] ? 'selected="selected"' : false)

How to check if an object is a list or tuple (but not string)?

Try this for readability and best practices:

Python2

import types
if isinstance(lst, types.ListType) or isinstance(lst, types.TupleType):
    # Do something

Python3

import typing
if isinstance(lst, typing.List) or isinstance(lst, typing.Tuple):
    # Do something

Hope it helps.

MYSQL Sum Query with IF Condition

How about this?

SUM(IF(PaymentType = "credit card", totalamount, 0)) AS CreditCardTotal

How to downgrade tensorflow, multiple versions possible?

I discovered the joy of anaconda: https://www.continuum.io/downloads

C:> conda create -n tensorflow1.1 python=3.5
C:> activate tensorflow1.1
(tensorflow1.1) 
C:> pip install --ignore-installed --upgrade https://storage.googleapis.com/tensorflow/windows/gpu/tensorflow_gpu-1.1.0-cp35-cp35m-win_amd64.whl

voila, a virtual environment is created.

How to simulate POST request?

It would be helpful if you provided more information - e.g. what OS your using, what you want to accomplish, etc. But, generally speaking cURL is a very powerful command-line tool I frequently use (in linux) for imitating HTML requests:

For example:

curl --data "post1=value1&post2=value2&etc=valetc" http://host/resource

OR, for a RESTful API:

curl -X POST -d @file http://host/resource

You can check out more information here-> http://curl.haxx.se/


EDITs:

OK. So basically you're looking to stress test your REST server? Then cURL really isn't helpful unless you want to write your own load-testing program, even then sockets would be the way to go. I would suggest you check out Gatling. The Gatling documentation explains how to set up the tool, and from there your can run all kinds of GET, POST, PUT and DELETE requests.

Unfortunately, short of writing your own program - i.e. spawning a whole bunch of threads and inundating your REST server with different types of requests - you really have to rely on a stress/load-testing toolkit. Just using a REST client to send requests isn't going to put much stress on your server.


More EDITs

So in order to simulate a post request on a socket, you basically have to build the initial socket connection with the server. I am not a C# guy, so I can't tell you exactly how to do that; I'm sure there are 1001 C# socket tutorials on the web. With most RESTful APIs you usually need to provide a URI to tell the server what to do. For example, let's say your API manages a library, and you are using a POST request to tell the server to update information about a book with an id of '34'. Your URI might be

http://localhost/library/book/34

Therefore, you should open a connection to localhost on port 80 (or 8080, or whatever port your server is on), and pass along an HTML request header. Going with the library example above, your request header might look as follows:

POST library/book/34 HTTP/1.0\r\n
X-Requested-With: XMLHttpRequest\r\n
Content-Type: text/html\r\n
Referer: localhost\r\n
Content-length: 36\r\n\r\n
title=Learning+REST&author=Some+Name

From here, the server should shoot back a response header, followed by whatever the API is programed to tell the client - usually something to say the POST succeeded or failed. To stress test your API, you should essentially do this over and over again by creating a threaded process.

Also, if you are posting JSON data, you will have to alter your header and content accordingly. Frankly, if you are looking to do this quick and clean, I would suggest using python (or perl) which has several libraries for creating POST, PUT, GET and DELETE request, as well as POSTing and PUTing JSON data. Otherwise, you might end up doing more programming than stress testing. Hope this helps!

How can I add an empty directory to a Git repository?

As described in other answers, Git is unable to represent empty directories in its staging area. (See the Git FAQ.) However, if, for your purposes, a directory is empty enough if it contains a .gitignore file only, then you can create .gitignore files in empty directories only via:

find . -type d -empty -exec touch {}/.gitignore \;

ToggleClass animate jQuery?

You should look at the toggle function found on jQuery. This will allow you to specify an easing method to define how the toggle works.

slideToggle will only slide up and down, not left/right if that's what you are looking for.

If you need the class to be toggled as well you can deifine that in the toggle function with a:

$(this).closest('article').toggle('slow', function() {
    $(this).toggleClass('expanded');
});

How to find files recursively by file type and copy them to a directory while in ssh?

Paul Dardeau answer is perfect, the only thing is, what if all the files inside those folders are not PDF files and you want to grab it all no matter the extension. Well just change it to

find . -name "*.*" -type f -exec cp {} ./pdfsfolder \;

Just to sum up!

Merge development branch with master

It would be great if you can use the Git Flow workflow. It can merge develop branch into master easily.

What you want to do is just follow the git-flow instruction mentioned here:

STEPS:

  • setup the git-flow project
  • create branches and merge everything to develop
  • run the command git flow release start <version_number>
  • then provide a meaningful message for the release
  • run the command git flow release finish <version_number>
  • it will merge everything into master and change the branch to master.
  • run the command git push to publish the changes to the remote master.

For more information, visit the page - http://danielkummer.github.io/git-flow-cheatsheet/

Open window in JavaScript with HTML inserted

You can also create an "example.html" page which has your desired html and give that page's url as parameter to window.open

var url = '/example.html';
var myWindow = window.open(url, "", "width=800,height=600");

Laravel 5.2 not reading env file

From the official Laravel 5.2 Upgrade Notes:

If you are using the config:cache command during deployment, you must make sure that you are only calling the env function from within your configuration files, and not from anywhere else in your application.

If you are calling env from within your application, it is strongly recommended you add proper configuration values to your configuration files and call env from that location instead, allowing you to convert your env calls to config calls.

Reference: https://laravel.com/docs/5.2/upgrade#upgrade-5.2.0

mysql Foreign key constraint is incorrectly formed error

I had the same issue with Symfony 2.8.

I didn't get it at first, because there were no similar problems with int length of foreign keys etc.

Finally I had to do the following in the project folder. (A server restart didn't help!)

app/console doctrine:cache:clear-metadata app/console doctrine:cache:clear-query app/console doctrine:cache:clear-result

Asynchronous vs synchronous execution, what does it really mean?

Use an example of instructions for making a breakfast

  1. Pour a cup of coffee.
  2. Heat up a pan, then fry two eggs.
  3. Fry three slices of bacon.
  4. Toast two pieces of bread.
  5. Add butter and jam to the toast.
  6. Pour a glass of orange juice.

If you have experience cooking, you'd execute those instructions asynchronously. you'd start warming the pan for eggs, then start the bacon. You'd put the bread in the toaster, then start the eggs. At each step of the process, you'd start a task, then turn your attention to tasks that are ready for your attention.

Cooking breakfast is a good example of asynchronous work that isn't parallel. One person (or thread) can handle all these tasks. Continuing the breakfast analogy, one person can make breakfast asynchronously by starting the next task before the first completes. The cooking progresses whether or not someone is watching it. As soon as you start warming the pan for the eggs, you can begin frying the bacon. Once the bacon starts, you can put the bread into the toaster.

For a parallel algorithm, you'd need multiple cooks (or threads). One would make the eggs, one the bacon, and so on. Each one would be focused on just that one task. Each cook (or thread) would be blocked synchronously waiting for bacon to be ready to flip, or the toast to pop.

Reference from Asynchronous programming concepts

Create a simple Login page using eclipse and mysql

use this code it is working

// index.jsp or login.jsp

<%@ page language="java" contentType="text/html; charset=ISO-8859-1"
    pageEncoding="ISO-8859-1"%>
<!DOCTYPE html PUBLIC "-//W3C//DTD HTML 4.01 Transitional//EN" "http://www.w3.org/TR/html4/loose.dtd">
<html>
<head>
<meta http-equiv="Content-Type" content="text/html; charset=ISO-8859-1">
<title>Insert title here</title>
</head>
<body>

<form action="login" method="post">
Username : <input type="text" name="username"><br>
Password : <input type="password" name="pass"><br>
<input type="submit"><br>
</form>

</body>
</html>

// authentication servlet class

    import java.io.IOException;
    import java.io.PrintWriter;
    import java.sql.Connection;
    import java.sql.DriverManager;
    import java.sql.SQLException;
    import java.sql.Statement;

    import javax.servlet.ServletException;
    import javax.servlet.http.HttpServlet;
    import javax.servlet.http.HttpServletRequest;
    import javax.servlet.http.HttpServletResponse;

    public class auth extends HttpServlet {
        private static final long serialVersionUID = 1L;

        public auth() {
            super();
        }
        protected void doGet(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {

        }

        protected void doPost(HttpServletRequest request,
                HttpServletResponse response) throws ServletException, IOException {

            try {
                Class.forName("com.mysql.jdbc.Driver");
            } catch (ClassNotFoundException e) {
                e.printStackTrace();
            }

            String username = request.getParameter("username");
            String pass = request.getParameter("pass");

            String sql = "select * from reg where username='" + username + "'";
            Connection conn = null;

            try {
                conn = DriverManager.getConnection("jdbc:mysql://localhost/Exam",
                        "root", "");
                Statement s = conn.createStatement();

                java.sql.ResultSet rs = s.executeQuery(sql);
                String un = null;
                String pw = null;
                String name = null;

            /* Need to put some condition in case the above query does not return any row, else code will throw Null Pointer exception */   

            PrintWriter prwr1 = response.getWriter();               
            if(!rs.isBeforeFirst()){
                prwr1.write("<h1> No Such User in Database<h1>");
            } else {

/* Conditions to be executed after at least one row is returned by query execution */ 
                while (rs.next()) {
                    un = rs.getString("username");
                    pw = rs.getString("password");
                    name = rs.getString("name");
                }

                PrintWriter pww = response.getWriter();

                if (un.equalsIgnoreCase(username) && pw.equals(pass)) {
                                // use this or create request dispatcher 
                    response.setContentType("text/html");
                    pww.write("<h1>Welcome, " + name + "</h1>");
                } else {
                    pww.write("wrong username or password\n");
                }
              }

            } catch (SQLException e) {
                e.printStackTrace();
            }

        }

    }

PHP order array by date?

I recommend using DateTime objects instead of strings, because you cannot easily compare strings, which is required for sorting. You also get additional advantages for working with dates.

Once you have the DateTime objects, sorting is quite easy:

usort($array, function($a, $b) {
  return ($a['date'] < $b['date']) ? -1 : 1;
});

How do I subscribe to all topics of a MQTT broker

Use the wildcard "#" but beware that at some point you will have to somehow understand the data passing through the bus!

Difference between innerText, innerHTML and value?

The only difference between innerText and innerHTML is that innerText insert string as it is into the element, while innerHTML run it as html content.

_x000D_
_x000D_
const ourstring = 'My name is <b class="name">Satish chandra Gupta</b>.';_x000D_
document.getElementById('innertext').innerText = ourstring;_x000D_
document.getElementById('innerhtml').innerHTML = ourstring;
_x000D_
.name{_x000D_
color:red;_x000D_
}
_x000D_
<h3>Inner text below. It inject string as it is into the element.</h3>_x000D_
<div id="innertext"></div>_x000D_
<br />_x000D_
<h3>Inner html below. It renders the string into the element and treat as part of html document.</h3>_x000D_
<div id="innerhtml"></div>
_x000D_
_x000D_
_x000D_

Convert Current date to integer

Try This

Calendar currentDay= Calendar.getInstance();
int currDate= currentDay.get(Calendar.DATE);
int currMonth= currentDay.get(Calendar.MONTH);
int currYear= currentDay.get(Calendar.YEAR);
System.out.println(currDate + "-" +  currMonth + "-" + currYear);

an alternative way using LocalDate.

LocalDate today = LocalDate.now();
int currentDate= today.getDayOfMonth();
int currentMonth= today.getMonthValue();
int currentYear= today.getYear()

How to bundle an Angular app for production

Angular 2 with Webpack (without CLI setup)

1- The tutorial by the Angular2 team

The Angular2 team published a tutorial for using Webpack

I created and placed the files from the tutorial in a small GitHub seed project. So you can quickly try the workflow.

Instructions:

  • npm install

  • npm start. For development. This will create a virtual "dist" folder that will be livereloaded at your localhost address.

  • npm run build. For production. "This will create a physical "dist" folder version than can be sent to a webserver. The dist folder is 7.8MB but only 234KB is actually required to load the page in a web browser.

2 - A Webkit starter kit

This Webpack Starter Kit offers some more testing features than the above tutorial and seem quite popular.

Switch statement: must default be the last case?

It's valid and very useful in some cases.

Consider the following code:

switch(poll(fds, 1, 1000000)){
   default:
    // here goes the normal case : some events occured
   break;
   case 0:
    // here goes the timeout case
   break;
   case -1:
     // some error occurred, you have to check errno
}

The point is that the above code is more readable and efficient than cascaded if. You could put default at the end, but it is pointless as it will focus your attention on error cases instead of normal cases (which here is the default case).

Actually, it's not such a good example, in poll you know how many events may occur at most. My real point is that there are cases with a defined set of input values where there are 'exceptions' and normal cases. If it's better to put exceptions or normal cases at front is a matter of choice.

In software field I think of another very usual case: recursions with some terminal values. If you can express it using a switch, default will be the usual value that contains recursive call and distinguished elements (individual cases) the terminal values. There is usually no need to focus on terminal values.

Another reason is that the order of the cases may change the compiled code behavior, and that matters for performances. Most compilers will generate compiled assembly code in the same order as the code appears in the switch. That makes the first case very different from the others: all cases except the first one will involve a jump and that will empty processor pipelines. You may understand it like branch predictor defaulting to running the first appearing case in the switch. If a case if much more common that the others then you have very good reasons to put it as the first case.

Reading comments it's the specific reason why the original poster asked that question after reading Intel compiler Branch Loop reorganisation about code optimisation.

Then it will become some arbitration between code readability and code performance. Probably better to put a comment to explain to future reader why a case appears first.

Catch Ctrl-C in C

Addendum regarding UN*X platforms.

According to the signal(2) man page on GNU/Linux, the behavior of signal is not as portable as behavior of sigaction:

The behavior of signal() varies across UNIX versions, and has also varied historically across different versions of Linux. Avoid its use: use sigaction(2) instead.

On System V, system did not block delivery of further instances of the signal and delivery of a signal would reset the handler to the default one. In BSD the semantics changed.

The following variation of previous answer by Dirk Eddelbuettel uses sigaction instead of signal:

#include <signal.h>
#include <stdlib.h>

static bool keepRunning = true;

void intHandler(int) {
    keepRunning = false;
}

int main(int argc, char *argv[]) {
    struct sigaction act;
    act.sa_handler = intHandler;
    sigaction(SIGINT, &act, NULL);

    while (keepRunning) {
        // main loop
    }
}

How to write new line character to a file in Java

In EDIT 2:

while((line = bufferedReader.readLine()) != null)
{
  sb.append(line); //append the lines to the string
  sb.append('\n'); //append new line
} //end while

you are reading the text file, and appending a newline to it. Don't append newline, which will not show a newline in some simple-minded Windows editors like Notepad. Instead append the OS-specific line separator string using:

sb.append(System.lineSeparator()); (for Java 1.7 and 1.8) or sb.append(System.getProperty("line.separator")); (Java 1.6 and below)

Alternatively, later you can use String.replaceAll() to replace "\n" in the string built in the StringBuffer with the OS-specific newline character:

String updatedText = text.replaceAll("\n", System.lineSeparator())

but it would be more efficient to append it while you are building the string, than append '\n' and replace it later.

Finally, as a developer, if you are using notepad for viewing or editing files, you should drop it, as there are far more capable tools like Notepad++, or your favorite Java IDE.

SOAP-ERROR: Parsing WSDL: Couldn't load from <URL>

I got the same error

Could not connect to the Magento WebService API: SOAP-ERROR: Parsing WSDL: Couldn't load from 'example.com/api/soap/?wsdl' : failed to load external entity "example.com/api/soap/?wsdl"

and my issue resolved once I update my Magento Root URL to

example.com/index.php/api/soap/?wsdl

Yes, I was missing index.php that causes the error.

Remove duplicate elements from array in Ruby

You can remove the duplicate elements with the uniq method:

array.uniq  # => [1, 2, 4, 5, 6, 7, 8]

What might also be useful to know is that uniq takes a block, so if you have a have an array of keys:

["bucket1:file1", "bucket2:file1", "bucket3:file2", "bucket4:file2"]

and you want to know what the unique files are, you can find it out with:

a.uniq { |f| f[/\d+$/] }.map { |p| p.split(':').last }

Best implementation for Key Value Pair Data Structure?

@Jay Mooney: A generic Dictionary class in .NET is actually a hash table, just with fixed types.

The code you've shown shouldn't convince anyone to use Hashtable instead of Dictionary, since both code pieces can be used for both types.

For hashtable:

foreach(object key in h.keys)
{
     string keyAsString = key.ToString(); // btw, this is unnecessary
     string valAsString = h[key].ToString();

     System.Diagnostics.Debug.WriteLine(keyAsString + " " + valAsString);
}

For dictionary:

foreach(string key in d.keys)
{
     string valAsString = d[key].ToString();

     System.Diagnostics.Debug.WriteLine(key + " " + valAsString);
}

And just the same for the other one with KeyValuePair, just use the non-generic version for Hashtable, and the generic version for Dictionary.

So it's just as easy both ways, but Hashtable uses Object for both key and value, which means you will box all value types, and you don't have type safety, and Dictionary uses generic types and is thus better.

How to extend a class in python?

Another way to extend (specifically meaning, add new methods, not change existing ones) classes, even built-in ones, is to use a preprocessor that adds the ability to extend out of/above the scope of Python itself, converting the extension to normal Python syntax before Python actually gets to see it.

I've done this to extend Python 2's str() class, for instance. str() is a particularly interesting target because of the implicit linkage to quoted data such as 'this' and 'that'.

Here's some extending code, where the only added non-Python syntax is the extend:testDottedQuad bit:

extend:testDottedQuad
def testDottedQuad(strObject):
    if not isinstance(strObject, basestring): return False
    listStrings = strObject.split('.')
    if len(listStrings) != 4: return False
    for strNum in listStrings:
        try:    val = int(strNum)
        except: return False
        if val < 0: return False
        if val > 255: return False
    return True

After which I can write in the code fed to the preprocessor:

if '192.168.1.100'.testDottedQuad():
    doSomething()

dq = '216.126.621.5'
if not dq.testDottedQuad():
    throwWarning();

dqt = ''.join(['127','.','0','.','0','.','1']).testDottedQuad()
if dqt:
    print 'well, that was fun'

The preprocessor eats that, spits out normal Python without monkeypatching, and Python does what I intended it to do.

Just as a c preprocessor adds functionality to c, so too can a Python preprocessor add functionality to Python.

My preprocessor implementation is too large for a stack overflow answer, but for those who might be interested, it is here on GitHub.

Detect when an HTML5 video finishes

Here is a full example, I hope it helps =).

<!DOCTYPE html> 
<html> 
<body> 

<video id="myVideo" controls="controls">
  <source src="your_video_file.mp4" type="video/mp4">
  <source src="your_video_file.mp4" type="video/ogg">
  Your browser does not support HTML5 video.
</video>

<script type='text/javascript'>
    document.getElementById('myVideo').addEventListener('ended',myHandler,false);
    function myHandler(e) {
        if(!e) { e = window.event; }
        alert("Video Finished");
    }
</script>
</body> 
</html>

gem install: Failed to build gem native extension (can't find header files)

For anyone reading this in 2015: if you happened to install the package ruby2.0, you need to install the matching ruby2.0-dev to get the appropriate Ruby headers. The same goes for ruby2.1 and ruby2.2, etc. For example:

$ sudo apt-get install ruby2.2-dev

How to delete last character in a string in C#?

I would just not add it in the first place:

 var sb = new StringBuilder();

 bool first = true;
 foreach (var foo in items) {
    if (first)
        first = false;
    else
        sb.Append('&');

    // for example:
    var escapedValue = System.Web.HttpUtility.UrlEncode(foo);

    sb.Append(key).Append('=').Append(escapedValue);
 }

 var s = sb.ToString();

How to format a number as percentage in R?

Here's my solution for defining a new function (mostly so I can play around with Curry and Compose :-) ):

library(roxygen)
printpct <- Compose(function(x) x*100, Curry(sprintf,fmt="%1.2f%%"))

What is difference between Implicit wait and Explicit wait in Selenium WebDriver?

My Thought,

Implicit Wait : If wait is set, it will wait for specified amount of time for each findElement/findElements call. It will throw an exception if action is not complete.

Explicit Wait : If wait is set, it will wait and move on to next step when the provided condition becomes true else it will throw an exception after waiting for specified time. Explicit wait is applicable only once wherever specified.

Size of character ('a') in C/C++

As Paul stated, it's because 'a' is an int in C but a char in C++.

I cover that specific difference between C and C++ in something I wrote a few years ago, at: http://david.tribble.com/text/cdiffs.htm

jQuery - Illegal invocation

Also this is a cause too: If you built a jQuery collection (via .map() or something similar) then you shouldn't use this collection in .ajax()'s data. Because it's still a jQuery object, not plain JavaScript Array. You should use .get() at the and to get plain js array and should use it on the data setting on .ajax().

How to check model string property for null in a razor view

Try this first, you may be passing a Null Model:

@if (Model != null && !String.IsNullOrEmpty(Model.ImageName))
{
    <label for="Image">Change picture</label>
}
else
{ 
    <label for="Image">Add picture</label>
}

Otherise, you can make it even neater with some ternary fun! - but that will still error if your model is Null.

<label for="Image">@(String.IsNullOrEmpty(Model.ImageName) ? "Add" : "Change") picture</label>

Merge (Concat) Multiple JSONObjects in Java

I used string to concatenate new object to an existing object.


private static void concatJSON() throws IOException, InterruptedException {

    JSONParser parser = new JSONParser();
    Object obj = parser.parse(new FileReader(new File(Main.class.getResource("/file/user.json").toURI())));


    JSONObject jsonObj = (JSONObject) obj; //usernameJsonObj

    String [] values = {"0.9" , Date.from(Calendar.getInstance().toInstant()).toLocaleString()},
            innermost = {"Accomplished", "LatestDate"}, 
            inner = {"Lesson1", "Lesson2", "Lesson3", "Lesson4"};
    String in = "Jayvee Villa";

    JSONObject jo1 = new JSONObject();
    for (int i = 0; i < innermost.length; i++)
        jo1.put(innermost[i], values[i]);

    JSONObject jo2 = new JSONObject();
    for (int i = 0; i < inner.length; i++)
        jo2.put(inner[i], jo1);

    JSONObject jo3 = new JSONObject();
    jo3.put(in, jo2);

    String merger = jsonObj.toString().substring(0, jsonObj.toString().length()-1) + "," +jo3.toString().substring(1);

    System.out.println(merger);
    FileWriter pr = new FileWriter(file);
    pr.write(merger);
    pr.flush();
    pr.close();
}

master branch and 'origin/master' have diverged, how to 'undiverge' branches'?

I had this and am mystified as to what has caused it, even after reading the above responses. My solution was to do

git reset --hard origin/master

Then that just resets my (local) copy of master (which I assume is screwed up) to the correct point, as represented by (remote) origin/master.

WARNING: You will lose all changes not yet pushed to origin/master.

You must enable the openssl extension to download files via https

make sure you have correct path to extension folder

extension_dir = "ext"

by default it is commented with ; character

Should I add the Visual Studio .suo and .user files to source control?

These files contain user preference configurations that are in general specific to your machine, so it's better not to put it in SCM. Also, VS will change it almost every time you execute it, so it will always be marked by the SCM as 'changed'. I don't include either, I'm in a project using VS for 2 years and had no problems doing that. The only minor annoyance is that the debug parameters (execution path, deployment target, etc.) are stored in one of those files (don't know which), so if you have a standard for them you won't be able to 'publish' it via SCM for other developers to have the entire development environment 'ready to use'.

AJAX Mailchimp signup form integration

Use jquery.ajaxchimp plugin to achieve that. It's dead easy!

<form method="post" action="YOUR_SUBSCRIBE_URL_HERE">
  <input type="text" name="EMAIL" placeholder="e-mail address" />
  <input type="submit" name="subscribe" value="subscribe!" />        
  <p class="result"></p>
</form>

JavaScript:

$(function() {
  $('form').ajaxChimp({
    callback: function(response) {
      $('form .result').text(response.msg);
    }
  });
})

Using grep to search for hex strings in a file

There's also a pretty handy tool called binwalk, written in python, which provides for binary pattern matching (and quite a lot more besides). Here's how you would search for a binary string, which outputs the offset in decimal and hex (from the docs):

$ binwalk -R "\x00\x01\x02\x03\x04" firmware.bin
DECIMAL     HEX         DESCRIPTION
--------------------------------------------------------------------------
377654      0x5C336     Raw string signature

"Failed to load platform plugin "xcb" " while launching qt5 app on linux without qt installed

So, I spent about a day trying to figure out what was the issue; tried all the proposed solutions, but none of that worked like installing xcb libs or exporting Qt plugins folder. The solution that suggested to use QT_DEBUG_PLUGINS=1 to debug the issue didn't provide me a direct insight like in the answer - instead I was getting something about unresolved symbols within Qt5Core.

That gave me a hint, though: what if it's trying to use different files from different Qt installations? On my machine I had standard version installed in /home/username/Qt/ and some local builds within my project that I compiled by myself (I have other custom built kits as well in other locations). Whenever I tried to use any of the kits (installed by Qt maintenance tool or built by myself), I would get an "xcb error".

The solution was simple: provide the Qt path through CMAKE_PREFIX_PATH and not though Qt5_DIR as I did, and it solved the problem. Example:

cmake .. -DCMAKE_PREFIX_PATH=/home/username/Qt/5.11.1/gcc_64

List comprehension on a nested list?

Yes you can do the following.

[[float(y) for y in x] for x in l]

Find duplicate records in MongoDB

db.getCollection('orders').aggregate([  
    {$group: { 
            _id: {name: "$name"},
            uniqueIds: {$addToSet: "$_id"},
            count: {$sum: 1}
        } 
    },
    {$match: { 
        count: {"$gt": 1}
        }
    }
])

First Group Query the group according to the fields.

Then we check the unique Id and count it, If count is greater then 1 then the field is duplicate in the entire collection so that thing is to be handle by $match query.

composer laravel create project

I also had same problem then I found this on there documentation page

So if you want to create a project by name of test_laravel in directory /Applications/MAMP/htdocs/ then what you need to do is

go to your project parent directory

cd /Applications/MAMP/htdocs

and fire this command

composer create-project laravel/laravel test_laravel --prefer-dist

that's it, this is really easy and it also creates Application Key automatically for you

How do I cancel an HTTP fetch() request?

This works in browser and nodejs Live browser demo

const cpFetch= require('cp-fetch');
const url= 'https://run.mocky.io/v3/753aa609-65ae-4109-8f83-9cfe365290f0?mocky-delay=3s';
 
const chain = cpFetch(url, {timeout: 10000})
    .then(response => response.json())
    .then(data => console.log(`Done: `, data), err => console.log(`Error: `, err))
 
setTimeout(()=> chain.cancel(), 1000); // abort the request after 1000ms 

Change New Google Recaptcha (v2) Width

It's been late, but just want to help others if still facing an issue. I found nice JS solution here : https://github.com/google/recaptcha/issues/61#issuecomment-376484690


Here is JavaScript code using jQuery to do so:

$(document).ready(function () {        
    var width = $('.g-recaptcha').parent().width();
    if (width < 302) {
        var scale = width / 302;
        $('.g-recaptcha').css('transform', 'scale(' + scale + ')');
        $('.g-recaptcha').css('-webkit-transform', 'scale(' + scale + ')');
        $('.g-recaptcha').css('transform-origin', '0 0');
        $('.g-recaptcha').css('-webkit-transform-origin', '0 0');
    }
}); 

IMP Note : It will support All Devices, above and bellow 320px width as well.

creating a new list with subset of list using index in python

The following definition might be more efficient than the first solution proposed

def new_list_from_intervals(original_list, *intervals):
    n = sum(j - i for i, j in intervals)
    new_list = [None] * n
    index = 0
    for i, j in intervals :
        for k in range(i, j) :
            new_list[index] = original_list[k]
            index += 1

    return new_list

then you can use it like below

new_list = new_list_from_intervals(original_list, (0,2), (4,5), (6, len(original_list)))

How to include a font .ttf using CSS?

Did you try format?

@font-face {
  font-family: 'The name of the Font Family Here';
  src: URL('font.ttf') format('truetype');
}

Read this article: http://css-tricks.com/snippets/css/using-font-face/

Also, might depend on browser as well.

T-SQL: Using a CASE in an UPDATE statement to update certain columns depending on a condition

You can't use a condition to change the structure of your query, just the data involved. You could do this:

update table set
    columnx = (case when condition then 25 else columnx end),
    columny = (case when condition then columny else 25 end)

This is semantically the same, but just bear in mind that both columns will always be updated. This probably won't cause you any problems, but if you have a high transactional volume, then this could cause concurrency issues.

The only way to do specifically what you're asking is to use dynamic SQL. This is, however, something I'd encourage you to stay away from. The solution above will almost certainly be sufficient for what you're after.

Powershell's Get-date: How to get Yesterday at 22:00 in a variable?

When I was to get yesterday with just the date in the format Year/Month/Day I use:

$Variable = Get-Date((get-date ).AddDays(-1))  -Format "yyyy-MM-dd"

How can I format date by locale in Java?

Joda-Time

Using the Joda-Time 2.4 library. The DateTimeFormat class is a factory of DateTimeFormatter formatters. That class offers a forStyle method to access formatters appropriate to a Locale.

DateTimeFormatter formatter = DateTimeFormat.forStyle( "MM" ).withLocale( Java.util.Locale.CANADA_FRENCH );
String output = formatter.print( DateTime.now( DateTimeZone.forID( "America/Montreal" ) ) );

The argument with two letters specifies a format for the date portion and the time portion. Specify a character of 'S' for short style, 'M' for medium, 'L' for long, and 'F' for full. A date or time may be ommitted by specifying a style character '-' HYPHEN.

Note that we specified both a Locale and a time zone. Some people confuse the two.

  • A time zone is an offset from UTC and a set of rules for Daylight Saving Time and other anomalies along with their historical changes.
  • A Locale is a human language such as Français, plus a country code such as Canada that represents cultural practices including formatting of date-time strings.

We need all those pieces to properly generate a string representation of a date-time value.

Can Google Chrome open local links?

You can't link to file:/// from an HTML document that is not itself a file:/// for security reasons.

Linux: Which process is causing "device busy" when doing umount?

lsof and fuser didn't give me anything either.

After a process of renaming all possible directories to .old and rebooting the system every time after I made changes I found one particular directory (relating to postfix) that was responsible.

It turned out that I had once made a symlink from /var/spool/postfix to /disk2/pers/mail/postfix/varspool in order to minimise disk writes on an SDCARD-based root filesystem (Sheeva Plug).

With this symlink, even after stopping the postfix and dovecot services (both ps aux as well as netstat -tuanp didn't show anything related) I was not able to unmount /disk2/pers.

When I removed the symlink and updated the postfix and dovecot config files to point directly to the new dirs on /disk2/pers/ I was able to successfully stop the services and unmount the directory.

Next time I will look more closely at the output of:

ls -lR /var | grep ^l | grep disk2

The above command will recursively list all symbolic links in a directory tree (here starting at /var) and filter out those names that point to a specific target mount point (here disk2).

Multiple Errors Installing Visual Studio 2015 Community Edition

As described from other answers, but with steps:

1- go to control panel -> uninstall programs -> uninstall all Microsoft C++ ((year)) Redistributable

2- delete those files if they still exist manually:

  • c:\windows\System32\vcruntime140.dll
  • c:\windows\SysWOW64\vcruntime140.dll

3- download and install: https://www.microsoft.com/en-us/download/details.aspx?id=48145

after that rerun the installation of Visual Studio, and hope that error won't show again.

How to remove focus from single editText

i had a similar problem with the editText, which gained focus since the activity was started. this problem i fixed easily like this:

you add this piece of code into the layout that contains the editText in xml:

    android:id="@+id/linearlayout" 
    android:focusableInTouchMode="true"

dont forget the android:id, without it i've got an error.

the other problem i had with the editText is that once it gain the first focus, the focus never disappeared. this is a piece of my code in java, it has an editText and a button that captures the text in the editText:

    editText=(EditText) findViewById(R.id.et1);
    tvhome= (TextView)findViewById(R.id.tv_home);
    etBtn= (Button) findViewById(R.id.btn_homeadd);
    etBtn.setOnClickListener(new View.OnClickListener() 
    {   
        @Override
        public void onClick(View v)
        {
            tvhome.setText( editText.getText().toString() );

            //** this code is for hiding the keyboard after pressing the button
            View view = Settings.this.getCurrentFocus();
            if (view != null) 
            {  
                InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
            }
            //**

            editText.getText().clear();//clears the text
            editText.setFocusable(false);//disables the focus of the editText 
            Log.i("onCreate().Button.onClickListener()", "et.isfocused= "+editText.isFocused());
        }
    });
    editText.setOnClickListener(new View.OnClickListener() 
    {
        @Override
        public void onClick(View v) 
        {
            if(v.getId() == R.id.et1)
            {
                v.setFocusableInTouchMode(true);// when the editText is clicked it will gain focus again

                //** this code is for enabling the keyboard at the first click on the editText
                if(v.isFocused())//the code is optional, because at the second click the keyboard shows by itself
                {
                    InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.showSoftInput(v, InputMethodManager.SHOW_IMPLICIT);
                }
                //**

                Log.i("onCreate().EditText.onClickListener()", "et.isfocused= "+v.isFocused());
            }
            else
                Log.i("onCreate().EditText.onClickListener()", "the listener did'nt consume the event");
        }
    });

hope it will help to some of you!

What does "request for member '*******' in something not a structure or union" mean?

You are trying to access a member of a structure, but in something that is not a structure. For example:

struct {
    int a;
    int b;
} foo;
int fum;
fum.d = 5;