Programs & Examples On #Training data

Parameter "stratify" from method "train_test_split" (scikit Learn)

Try running this code, it "just works":

from sklearn import cross_validation, datasets 

iris = datasets.load_iris()

X = iris.data[:,:2]
y = iris.target

x_train, x_test, y_train, y_test = cross_validation.train_test_split(X,y,train_size=.8, stratify=y)

y_test

array([0, 0, 0, 0, 2, 2, 1, 0, 1, 2, 2, 0, 0, 1, 0, 1, 1, 2, 1, 2, 0, 2, 2,
       1, 2, 1, 1, 0, 2, 1])

Inserting a Python datetime.datetime object into MySQL

when iserting into t-sql

this fails:

select CONVERT(datetime,'2019-09-13 09:04:35.823312',21)

this works:

select CONVERT(datetime,'2019-09-13 09:04:35.823',21)

easy way:

regexp = re.compile(r'\.(\d{6})')
def to_splunk_iso(dt):
    """Converts the datetime object to Splunk isoformat string."""
    # 6-digits string.
    microseconds = regexp.search(dt).group(1)
    return regexp.sub('.%d' % round(float(microseconds) / 1000), dt)

Meaning of "487 Request Terminated"

The 487 Response indicates that the previous request was terminated by user/application action. The most common occurrence is when the CANCEL happens as explained above. But it is also not limited to CANCEL. There are other cases where such responses can be relevant. So it depends on where you are seeing this behavior and whether its a user or application action that caused it.

15.1.2 UAS Behavior==> BYE Handling in RFC 3261

The UAS MUST still respond to any pending requests received for that dialog. It is RECOMMENDED that a 487 (Request Terminated) response be generated to those pending requests.

How to allocate aligned memory only using the standard library?

usage of memalign, Aligned-Memory-Blocks might be a good solution for the problem.

Styling Password Fields in CSS

The best I can find is to set input[type="password"] {font:small-caption;font-size:16px}

Demo:

_x000D_
_x000D_
input {_x000D_
  font: small-caption;_x000D_
  font-size: 16px;_x000D_
}
_x000D_
<input type="password">
_x000D_
_x000D_
_x000D_

Catch error if iframe src fails to load . Error :-"Refused to display 'http://www.google.co.in/' in a frame.."

I have the same problem, chrome can't fire onerror when iframe src load error.

but in my case, I just need make a cross domain http request, so I use script src/onload/onerror instead of iframe. it's working well.

AngularJS - difference between pristine/dirty and touched/untouched

This is a late answer but hope this might help.

Scenario 1: You visited the site for first time and did not touch any field. The state of form is

ng-untouched and ng-pristine

Scenario 2: You are currently entering the values in a particular field in the form. Then the state is

ng-untouched and ng-dirty

Scenario 3: You are done with entering the values in the field and moved to next field

ng-touched and ng-dirty

Scenario 4: Say a form has a phone number field . You have entered the number but you have actually entered 9 digits but there are 10 digits required for a phone number.Then the state is ng-invalid

In short:

ng-untouched:When the form field has not been visited yet

ng-touched: When the form field is visited AND the field has lost focus

ng-pristine: The form field value is not changed

ng-dirty: The form field value is changed

ng-valid : When all validations of form fields are successful

ng-invalid: When all validations of form fields are not successful

Drop all data in a pandas dataframe

This code make clean dataframe:

df = pd.DataFrame({'a':[1,2], 'b':[3,4]})
#clean
df = pd.DataFrame()

SEVERE: ContainerBase.addChild: start:org.apache.catalina.LifecycleException: Failed to start error

What caused this error in my case was having two @GET methods with the same path in a single resource. Changing the @Path of one of the methods solved it for me.

Using python's mock patch.object to change the return value of a method called within another method

This can be done with something like this:

# foo.py
class Foo:
    def method_1():
        results = uses_some_other_method()


# testing.py
from mock import patch

@patch('Foo.uses_some_other_method', return_value="specific_value"):
def test_some_other_method(mock_some_other_method):
    foo = Foo()
    the_value = foo.method_1()
    assert the_value == "specific_value"

Here's a source that you can read: Patching in the wrong place

How do I change the title of the "back" button on a Navigation Bar

Here's another way to do it.

In your parent view controller, implement the following method:

- (void) setBackBarButtonItemTitle:(NSString *)newTitle {
  self.navigationItem.backBarButtonItem.title = newTitle;
}

In your child view controller, when you want to change the title, this will work:

NSArray *viewControllerArray = [self.navigationController viewControllers];
int parentViewControllerIndex = [viewControllerArray count] - 2;
[[viewControllerArray objectAtIndex:parentViewControllerIndex] setBackBarButtonItemTitle:@"New Title"];

I was never able to get the parentViewController property to work:

[(ParentViewController *)(self.navigationController.parentViewController) setBackBarButtonItemTitle:@"New Title"];

I don't know if that's a bug or I'm not using it properly. But grabbing the second-to-last view controller in the viewControllers array points to the parent view controller, and I can call parent methods correctly with that reference.

How to copy directories with spaces in the name

robocopy "C:\Users\Angie\My Documents" "C:\test-backup\My Documents" /B /E /R:0 /CREATE /NP /TEE /XJ /LOG+:"CompleteBackupLog.txt"
robocopy "C:\Users\Angie\My Music" "C:\test-backup\My Music" /B /E /R:0 /CREATE /NP /TEE /XJ /LOG+:"CompleteBackupLog.txt"
robocopy "C:\Users\Angie\My Pictures" "C:\test-backup\My Pictures" /B /E /R:0 /CREATE /NP /TEE /XJ /LOG+:"CompleteBackupLog.txt"

Unable to locate an executable at "/usr/bin/java/bin/java" (-1)

In MacOS Catalina, run

sudo nano ~/.bash_profile

In bash_profile, add:

export JAVA_HOME=$(/usr/libexec/java_home)
source ~/.bash_profile

Verify by running java --version

Convert python datetime to epoch with strftime

I had serious issues with Timezones and such. The way Python handles all that happen to be pretty confusing (to me). Things seem to be working fine using the calendar module (see links 1, 2, 3 and 4).

>>> import datetime
>>> import calendar
>>> aprilFirst=datetime.datetime(2012, 04, 01, 0, 0)
>>> calendar.timegm(aprilFirst.timetuple())
1333238400

How to format LocalDate to string?

SimpleDateFormat will not work if he is starting with LocalDate which is new in Java 8. From what I can see, you will have to use DateTimeFormatter, http://docs.oracle.com/javase/8/docs/api/java/time/format/DateTimeFormatter.html.

LocalDate localDate = LocalDate.now();//For reference
DateTimeFormatter formatter = DateTimeFormatter.ofPattern("dd LLLL yyyy");
String formattedString = localDate.format(formatter);

That should print 05 May 1988. To get the period after the day and before the month, you might have to use "dd'.LLLL yyyy"

How to split csv whose columns may contain ,

It is a tricky matter to parse .csv files when the .csv file could be either comma separated strings, comma separated quoted strings, or a chaotic combination of the two. The solution I came up with allows for any of the three possibilities.

I created a method, ParseCsvRow() which returns an array from a csv string. I first deal with double quotes in the string by splitting the string on double quotes into an array called quotesArray. Quoted string .csv files are only valid if there is an even number of double quotes. Double quotes in a column value should be replaced with a pair of double quotes (This is Excel's approach). As long as the .csv file meets these requirements, you can expect the delimiter commas to appear only outside of pairs of double quotes. Commas inside of pairs of double quotes are part of the column value and should be ignored when splitting the .csv into an array.

My method will test for commas outside of double quote pairs by looking only at even indexes of the quotesArray. It also removes double quotes from the start and end of column values.

    public static string[] ParseCsvRow(string csvrow)
    {
        const string obscureCharacter = "?";
        if (csvrow.Contains(obscureCharacter)) throw new Exception("Error: csv row may not contain the " + obscureCharacter + " character");

        var unicodeSeparatedString = "";

        var quotesArray = csvrow.Split('"');  // Split string on double quote character
        if (quotesArray.Length > 1)
        {
            for (var i = 0; i < quotesArray.Length; i++)
            {
                // CSV must use double quotes to represent a quote inside a quoted cell
                // Quotes must be paired up
                // Test if a comma lays outside a pair of quotes.  If so, replace the comma with an obscure unicode character
                if (Math.Round(Math.Round((decimal) i/2)*2) == i)
                {
                    var s = quotesArray[i].Trim();
                    switch (s)
                    {
                        case ",":
                            quotesArray[i] = obscureCharacter;  // Change quoted comma seperated string to quoted "obscure character" seperated string
                            break;
                    }
                }
                // Build string and Replace quotes where quotes were expected.
                unicodeSeparatedString += (i > 0 ? "\"" : "") + quotesArray[i].Trim();
            }
        }
        else
        {
            // String does not have any pairs of double quotes.  It should be safe to just replace the commas with the obscure character
            unicodeSeparatedString = csvrow.Replace(",", obscureCharacter);
        }

        var csvRowArray = unicodeSeparatedString.Split(obscureCharacter[0]); 

        for (var i = 0; i < csvRowArray.Length; i++)
        {
            var s = csvRowArray[i].Trim();
            if (s.StartsWith("\"") && s.EndsWith("\""))
            {
                csvRowArray[i] = s.Length > 2 ? s.Substring(1, s.Length - 2) : "";  // Remove start and end quotes.
            }
        }

        return csvRowArray;
    }

One downside of my approach is the way I temporarily replace delimiter commas with an obscure unicode character. This character needs to be so obscure, it would never show up in your .csv file. You may want to put more handling around this.

MessageBodyWriter not found for media type=application/json

To overcome this issue try the following. Worked for me.

Add following dependency in the pom.xml

<dependency>
  <groupId>org.glassfish.jersey.media</groupId>
  <artifactId>jersey-media-json-jackson</artifactId>
  <version>2.25</version>
</dependency>

And make sure Model class contains no arg constructor

 public Student()
    {
    }

Running python script inside ipython

from within the directory of "my_script.py" you can simply do:

%run ./my_script.py

Pretty-Print JSON in Java

You can use Gson like below

Gson gson = new GsonBuilder().setPrettyPrinting().create();
String jsonString = gson.toJson(object);

From the post JSON pretty print using Gson

Alternatively, You can use Jackson like below

ObjectMapper mapper = new ObjectMapper();
String perttyStr = mapper.writerWithDefaultPrettyPrinter().writeValueAsString(object);

From the post Pretty print JSON in Java (Jackson)

Hope this help!

How to subtract hours from a date in Oracle so it affects the day also

date - n will subtract n days form given date. In order to subtract hrs you need to convert it into day buy dividing it with 24. In your case it should be to_char(sysdate - (2 + 2/24), 'MM-DD-YYYY HH24'). This will subract 2 days and 2 hrs from sysdate.

Switch case with conditions

You should not use switch for this scenario. This is the proper approach:

var cnt = $("#div1 p").length;

alert(cnt);

if (cnt >= 10 && cnt <= 20)
{
   alert('10');
}
else if (cnt >= 21 && cnt <= 30)
{
   alert('21');
}
else if (cnt >= 31 && cnt <= 40)
{
   alert('31');
}
else 
{
   alert('>41');
}

How can I convert a string to upper- or lower-case with XSLT?

In XSLT 1.0 the upper-case() and lower-case() functions are not available. If you're using a 1.0 stylesheet the common method of case conversion is translate():

<xsl:variable name="lowercase" select="'abcdefghijklmnopqrstuvwxyz'" />
<xsl:variable name="uppercase" select="'ABCDEFGHIJKLMNOPQRSTUVWXYZ'" />


<xsl:template match="/">
  <xsl:value-of select="translate(doc, $lowercase, $uppercase)" />
</xsl:template>

What do 3 dots next to a parameter type mean in Java?

Just think of it as the keyword params in C#, if you are coming from that background :)

Check for a substring in a string in Oracle without LIKE

You can do it this way using INSTR:

SELECT * FROM users WHERE INSTR(LOWER(last_name), 'z') > 0;

INSTR returns zero if the substring is not in the string.

Out of interest, why don't you want to use like?

Edit: I took the liberty of making the search case insensitive so you don't miss Bob Zebidee. :-)

How to sort a dataframe by multiple column(s)

I learned about order with the following example which then confused me for a long time:

set.seed(1234)

ID        = 1:10
Age       = round(rnorm(10, 50, 1))
diag      = c("Depression", "Bipolar")
Diagnosis = sample(diag, 10, replace=TRUE)

data = data.frame(ID, Age, Diagnosis)

databyAge = data[order(Age),]
databyAge

The only reason this example works is because order is sorting by the vector Age, not by the column named Age in the data frame data.

To see this create an identical data frame using read.table with slightly different column names and without making use of any of the above vectors:

my.data <- read.table(text = '

  id age  diagnosis
   1  49 Depression
   2  50 Depression
   3  51 Depression
   4  48 Depression
   5  50 Depression
   6  51    Bipolar
   7  49    Bipolar
   8  49    Bipolar
   9  49    Bipolar
  10  49 Depression

', header = TRUE)

The above line structure for order no longer works because there is no vector named age:

databyage = my.data[order(age),]

The following line works because order sorts on the column age in my.data.

databyage = my.data[order(my.data$age),]

I thought this was worth posting given how confused I was by this example for so long. If this post is not deemed appropriate for the thread I can remove it.

EDIT: May 13, 2014

Below is a generalized way of sorting a data frame by every column without specifying column names. The code below shows how to sort from left to right or by right to left. This works if every column is numeric. I have not tried with a character column added.

I found the do.call code a month or two ago in an old post on a different site, but only after extensive and difficult searching. I am not sure I could relocate that post now. The present thread is the first hit for ordering a data.frame in R. So, I thought my expanded version of that original do.call code might be useful.

set.seed(1234)

v1  <- c(0,0,0,0, 0,0,0,0, 1,1,1,1, 1,1,1,1)
v2  <- c(0,0,0,0, 1,1,1,1, 0,0,0,0, 1,1,1,1)
v3  <- c(0,0,1,1, 0,0,1,1, 0,0,1,1, 0,0,1,1)
v4  <- c(0,1,0,1, 0,1,0,1, 0,1,0,1, 0,1,0,1)

df.1 <- data.frame(v1, v2, v3, v4) 
df.1

rdf.1 <- df.1[sample(nrow(df.1), nrow(df.1), replace = FALSE),]
rdf.1

order.rdf.1 <- rdf.1[do.call(order, as.list(rdf.1)),]
order.rdf.1

order.rdf.2 <- rdf.1[do.call(order, rev(as.list(rdf.1))),]
order.rdf.2

rdf.3 <- data.frame(rdf.1$v2, rdf.1$v4, rdf.1$v3, rdf.1$v1) 
rdf.3

order.rdf.3 <- rdf.1[do.call(order, as.list(rdf.3)),]
order.rdf.3

pros and cons between os.path.exists vs os.path.isdir

os.path.isdir() checks if the path exists and is a directory and returns TRUE for the case.

Similarly, os.path.isfile() checks if the path exists and is a file and returns TRUE for the case.

And, os.path.exists() checks if the path exists and doesn’t care if the path points to a file or a directory and returns TRUE in either of the cases.

How to change Android version and code version number?

Go in the build.gradle and set the version code and name inside the defaultConfig element

defaultConfig {
    minSdkVersion 9
    targetSdkVersion 19
    versionCode 1
    versionName "1.0"
}

screenshot

npm WARN package.json: No repository field

To avoid warnings like:

npm WARN [email protected] No repository field.

You must define repository in your project package.json. In the case when you are developing with no publishing to the repository you can set "private": true in package.json

Example:

{
  "name": "test.loc",
  "version": "1.0.0",
  "private": true,
  ...
  "license": "ISC"
}

NPM documentation about this: https://docs.npmjs.com/files/package.json

How to do integer division in javascript (Getting division answer in int not float)?

var answer = Math.floor(x)

I sincerely hope this will help future searchers when googling for this common question.

Laravel - Session store not set on request

It's not on the laravel documentation, I have been an hour to achieve this:

My session didn't persist until i used the "save" method...

$request->session()->put('lang','en_EN');
$request->session()->save();

Escape a string for a sed replace pattern

The only three literal characters which are treated specially in the replace clause are / (to close the clause), \ (to escape characters, backreference, &c.), and & (to include the match in the replacement). Therefore, all you need to do is escape those three characters:

sed "s/KEYWORD/$(echo $REPLACE | sed -e 's/\\/\\\\/g; s/\//\\\//g; s/&/\\\&/g')/g"

Example:

$ export REPLACE="'\"|\\/><&!"
$ echo fooKEYWORDbar | sed "s/KEYWORD/$(echo $REPLACE | sed -e 's/\\/\\\\/g; s/\//\\\//g; s/&/\\\&/g')/g"
foo'"|\/><&!bar

How do you read CSS rule values with JavaScript?

Here is code to iterate through all rules in a page:

_x000D_
_x000D_
function iterateCSS(f) {_x000D_
  for (const styleSheet of window.document.styleSheets) {_x000D_
    const classes = styleSheet.rules || styleSheet.cssRules;_x000D_
    if (!classes) continue;_x000D_
_x000D_
    for (const cssRule of classes) {_x000D_
      if (cssRule.type !== 1 || !cssRule.style) continue;_x000D_
      const selector = cssRule.selectorText, style=cssRule.style;_x000D_
      if (!selector || !style.cssText) continue;_x000D_
      for (let i=0; i<style.length; i++) {_x000D_
        const propertyName=style.item(i);_x000D_
        if (f(selector, propertyName, style.getPropertyValue(propertyName), style.getPropertyPriority(propertyName), cssRule)===false) return;_x000D_
      }_x000D_
    }_x000D_
  }_x000D_
}_x000D_
_x000D_
iterateCSS( (selector, propertyName, propertyValue, propertyPriority, cssRule) => {_x000D_
  console.log(selector+' { '+propertyName+': '+propertyValue+(propertyPriority==='important' ? ' !important' : '')+' }');_x000D_
});
_x000D_
_x000D_
_x000D_

First Or Create

An update:

As of Laravel 5.3 doing this in a single step is possible; the firstOrCreate method now accepts an optional second array as an argument.

The first array argument is the array on which the fields/values are matched, and the second array is the additional fields to use in the creation of the model if no match is found via matching the fields/values in the first array:

See documentation

Get/pick an image from Android's built-in Gallery app programmatically

basis with the above code, I reflected the code like below, may be it's more suitable:

public String getPath(Uri uri) {
    String selectedImagePath;
    //1:MEDIA GALLERY --- query from MediaStore.Images.Media.DATA
    String[] projection = { MediaStore.Images.Media.DATA };
    Cursor cursor = managedQuery(uri, projection, null, null, null);
    if(cursor != null){
        int column_index = cursor.getColumnIndexOrThrow(MediaStore.Images.Media.DATA);
        cursor.moveToFirst();
        selectedImagePath = cursor.getString(column_index);
    }else{
        selectedImagePath = null;
    }

    if(selectedImagePath == null){
        //2:OI FILE Manager --- call method: uri.getPath()
        selectedImagePath = uri.getPath();
    }
    return selectedImagePath;
}

bash: pip: command not found

Not sure why this wasnt mentioned before, but the only thing that worked for me (on my NVIDIA Xavier) was:

sudo apt-get install python3-pip

(or sudo apt-get install python-pip for python 2)

Create a string and append text to it

Concatenate with & operator

Dim str as String  'no need to create a string instance
str = "Hello " & "World"

You can concate with the + operator as well but you can get yourself into trouble when trying to concatenate numbers.


Concatenate with String.Concat()

str = String.Concat("Hello ", "World")

Useful when concatenating array of strings


StringBuilder.Append()

When concatenating large amounts of strings use StringBuilder, it will result in much better performance.

    Dim sb as new System.Text.StringBuilder()
    str = sb.Append("Hello").Append(" ").Append("World").ToString()

Strings in .NET are immutable, resulting in a new String object being instantiated for every concatenation as well a garbage collection thereof.

How do I remove all .pyc files from a project?

full recursive

ll **/**/*.pyc
rm **/**/*.pyc

Get the year from specified date php

<?php
list($year) = explode("-", "2068-06-15");
echo $year;
?>

Add padding to HTML text input field

You can provide padding to an input like this:

HTML:

<input type=text id=firstname />

CSS:

input {
    width: 250px;
    padding: 5px;
}

however I would also add:

input {
    width: 250px;
    padding: 5px;
    -webkit-box-sizing: border-box; /* Safari/Chrome, other WebKit */
    -moz-box-sizing: border-box;    /* Firefox, other Gecko */
    box-sizing: border-box;         /* Opera/IE 8+ */
}

Box sizing makes the input width stay at 250px rather than increase to 260px due to the padding.

For reference.

The EntityManager is closed

This is how I solved the Doctrine "The EntityManager is closed." issue. Basically each time there's an exception (i.e. duplicate key) or not providing data for a mandatory column will cause Doctrine to close the Entity Manager. If you still want to interact with the database you have to reset the Entity Manger by calling the resetManager() method as mentioned by JGrinon.

In my application I was running multiple RabbitMQ consumers that were all doing the same thing: checking if an entity was there in the database, if yes return it, if not create it and then return it. In the few milliseconds between checking if that entity already existed and creating it another consumer happened to do the same and created the missing entity making the other consumer incur in a duplicate key exception (race condition).

This led to a software design problem. Basically what I was trying to do was creating all the entities in one transaction. This may feel natural to most but was definitely conceptually wrong in my case. Consider the following problem: I had to store a football Match entity which had these dependencies.

  • a group (e.g. Group A, Group B...)
  • a round (e.g. Semi-finals...)
  • a venue (i.e. stadium where the match is taking place)
  • a match status (e.g. half time, full time)
  • the two teams playing the match
  • the match itself

Now, why the venue creation should be in the same transaction as the match? It could be that I've just received a new venue that it's not in my database so I have to create it first. But it could also be that that venue may host another match so another consumer will probably try to create it as well at the same time. So what I had to do was create all the dependencies first in separate transactions making sure I was resetting the entity manager in a duplicate key exception. I'd say that all the entities in there beside the match could be defined as "shared" because they could potentially be part of other transactions in other consumers. Something that is not "shared" in there is the match itself that won't likely be created by two consumers at the same time. So in the last transaction I expect to see just the match and the relation between the two teams and the match.

All of this also led to another issue. If you reset the Entity Manager, all the objects that you've retrieved before resetting are for Doctrine totally new. So Doctrine won't try to run an UPDATE on them but an INSERT! So make sure you create all your dependencies in logically correct transactions and then retrieve all your objects back from the database before setting them to the target entity. Consider the following code as an example:

$group = $this->createGroupIfDoesNotExist($groupData);

$match->setGroup($group); // this is NOT OK!

$venue = $this->createVenueIfDoesNotExist($venueData);

$round = $this->createRoundIfDoesNotExist($roundData);

/**
 * If the venue creation generates a duplicate key exception
 * we are forced to reset the entity manager in order to proceed
 * with the round creation and so we'll loose the group reference.
 * Meaning that Doctrine will try to persist the group as new even
 * if it's already there in the database.
 */

So this is how I think it should be done.

$group = $this->createGroupIfDoesNotExist($groupData); // first transaction, reset if duplicated
$venue = $this->createVenueIfDoesNotExist($venueData); // second transaction, reset if duplicated
$round = $this->createRoundIfDoesNotExist($roundData); // third transaction, reset if duplicated

// we fetch all the entities back directly from the database
$group = $this->getGroup($groupData);
$venue = $this->getVenue($venueData);
$round = $this->getGroup($roundData);

// we finally set them now that no exceptions are going to happen
$match->setGroup($group);
$match->setVenue($venue);
$match->setRound($round);

// match and teams relation...
$matchTeamHome = new MatchTeam();
$matchTeamHome->setMatch($match);
$matchTeamHome->setTeam($teamHome);

$matchTeamAway = new MatchTeam();
$matchTeamAway->setMatch($match);
$matchTeamAway->setTeam($teamAway);

$match->addMatchTeam($matchTeamHome);
$match->addMatchTeam($matchTeamAway);

// last transaction!
$em->persist($match);
$em->persist($matchTeamHome);
$em->persist($matchTeamAway);
$em->flush();

I hope it helps :)

regular expression for DOT

You should use contains not matches

if(nom.contains("."))
    System.out.println("OK");
else
    System.out.println("Bad");

How do I open workbook programmatically as read-only?

Does this work?

Workbooks.Open Filename:=filepath, ReadOnly:=True

Or, as pointed out in a comment, to keep a reference to the opened workbook:

Dim book As Workbook
Set book = Workbooks.Open(Filename:=filepath, ReadOnly:=True)

How can I get Maven to stop attempting to check for updates for artifacts from a certain group from maven-central-repo?

The updatePolicy tag didn't work for me. However Rich Seller mentioned that snapshots should be disabled anyways so I looked further and noticed that the extra repository that I added to my settings.xml was causing the problem actually. Adding the snapshots section to this repository in my settings.xml did the trick!

<repository>
    <id>jboss</id>
    <name>JBoss Repository</name>
    <url>http://repository.jboss.com/maven2</url>
    <snapshots>
        <enabled>false</enabled>
    </snapshots>
</repository>

Import-Module : The specified module 'activedirectory' was not loaded because no valid module file was found in any module directory

You can install the Active Directory snap-in with Powershell on Windows Server 2012 using the following command:

Install-windowsfeature -name AD-Domain-Services –IncludeManagementTools

This helped me when I had problems with the Features screen due to AppFabric and Windows Update errors.

can we use xpath with BeautifulSoup?

Nope, BeautifulSoup, by itself, does not support XPath expressions.

An alternative library, lxml, does support XPath 1.0. It has a BeautifulSoup compatible mode where it'll try and parse broken HTML the way Soup does. However, the default lxml HTML parser does just as good a job of parsing broken HTML, and I believe is faster.

Once you've parsed your document into an lxml tree, you can use the .xpath() method to search for elements.

try:
    # Python 2
    from urllib2 import urlopen
except ImportError:
    from urllib.request import urlopen
from lxml import etree

url =  "http://www.example.com/servlet/av/ResultTemplate=AVResult.html"
response = urlopen(url)
htmlparser = etree.HTMLParser()
tree = etree.parse(response, htmlparser)
tree.xpath(xpathselector)

There is also a dedicated lxml.html() module with additional functionality.

Note that in the above example I passed the response object directly to lxml, as having the parser read directly from the stream is more efficient than reading the response into a large string first. To do the same with the requests library, you want to set stream=True and pass in the response.raw object after enabling transparent transport decompression:

import lxml.html
import requests

url =  "http://www.example.com/servlet/av/ResultTemplate=AVResult.html"
response = requests.get(url, stream=True)
response.raw.decode_content = True
tree = lxml.html.parse(response.raw)

Of possible interest to you is the CSS Selector support; the CSSSelector class translates CSS statements into XPath expressions, making your search for td.empformbody that much easier:

from lxml.cssselect import CSSSelector

td_empformbody = CSSSelector('td.empformbody')
for elem in td_empformbody(tree):
    # Do something with these table cells.

Coming full circle: BeautifulSoup itself does have very complete CSS selector support:

for cell in soup.select('table#foobar td.empformbody'):
    # Do something with these table cells.

What does HTTP/1.1 302 mean exactly?

In the term of SEO , 301 and 302 both are good it is depend on situation,

If only one version can be returned (i.e., the other redirects to it), that’s great! This behavior is beneficial because it reduces duplicate content. In the particular case of redirects to trailing slash URLs, our search results will likely show the version of the URL with the 200 response code (most often the trailing slash URL) -- regardless of whether the redirect was a 301 or 302.

Carry Flag, Auxiliary Flag and Overflow Flag in Assembly

Carry Flag is a flag set when:

a) two unsigned numbers were added and the result is larger than "capacity" of register where it is saved. Ex: we wanna add two 8 bit numbers and save result in 8 bit register. In your example: 255 + 9 = 264 which is more that 8 bit register can store. So the value "8" will be saved there (264 & 255 = 8) and CF flag will be set.

b) two unsigned numbers were subtracted and we subtracted the bigger one from the smaller one. Ex: 1-2 will give you 255 in result and CF flag will be set.

Auxiliary Flag is used as CF but when working with BCD. So AF will be set when we have overflow or underflow on in BCD calculations. For example: considering 8 bit ALU unit, Auxiliary flag is set when there is carry from 3rd bit to 4th bit i.e. carry from lower nibble to higher nibble. (Wiki link)

Overflow Flag is used as CF but when we work on signed numbers. Ex we wanna add two 8 bit signed numbers: 127 + 2. the result is 129 but it is too much for 8bit signed number, so OF will be set. Similar when the result is too small like -128 - 1 = -129 which is out of scope for 8 bit signed numbers.

You can read more about flags on wikipedia

How to export table data in MySql Workbench to csv?

U can use mysql dump or query to export data to csv file

SELECT *
INTO OUTFILE '/tmp/products.csv'
FIELDS TERMINATED BY ','
ENCLOSED BY '"'
ESCAPED BY '\\'
LINES TERMINATED BY '\n'
FROM products

How do I resolve "Run-time error '429': ActiveX component can't create object"?

You say it works once you install the VB6 IDE so the problem is likely to be that the components you are trying to use depend on the VB6 runtime being installed.

The VB6 runtime isn't installed on Windows by default.

Installing the IDE is one way to get the runtime. For non-developer machines, a "redistributable" installer package from Microsoft should be used instead.

Here is one VB6 runtime installer from Microsoft. I'm not sure if it will be the right version for your components:

http://www.microsoft.com/downloads/en/details.aspx?FamilyID=7b9ba261-7a9c-43e7-9117-f673077ffb3c

How to use a filter in a controller?

function ngController($scope,$filter){
    $scope.name = "aaaa";
    $scope.age = "32";

     $scope.result = function(){
        return $filter('lowercase')($scope.name);
    };
}

The controller method 2nd argument name should be "$filter" then only the filter functionality will work with this example. In this example i have used the "lowercase" Filter.

error: expected class-name before ‘{’ token

I got the same error with a different problem,

I used namespaces in my headers and forgot the closing bracket and got this cryptic error instead.

What to gitignore from the .idea folder?

I just want to present a more recent alternative. There is an online tool that generates .gitignore files based on operating systems, IDEs and programming languages that you might be using.

gitignore.io


EDIT Disclaimer: Do not copy this file, copy the file generated by the website instead, they do a good job on keeping it updated. This is just an example.

The file generated for IntelliJ contains the following

# Created by https://www.gitignore.io/api/intellij

### Intellij ###
# Covers JetBrains IDEs: IntelliJ, RubyMine, PhpStorm, AppCode, PyCharm, CLion, Android Studio and Webstorm
# Reference: https://intellij-support.jetbrains.com/hc/en-us/articles/206544839

# User-specific stuff:
.idea/workspace.xml
.idea/tasks.xml
.idea/dictionaries
.idea/vcs.xml
.idea/jsLibraryMappings.xml

# Sensitive or high-churn files:
.idea/dataSources.ids
.idea/dataSources.xml
.idea/dataSources.local.xml
.idea/sqlDataSources.xml
.idea/dynamic.xml
.idea/uiDesigner.xml

# Gradle:
.idea/gradle.xml
.idea/libraries

# Mongo Explorer plugin:
.idea/mongoSettings.xml

## File-based project format:
*.iws

## Plugin-specific files:

# IntelliJ
/out/

# mpeltonen/sbt-idea plugin
.idea_modules/

# JIRA plugin
atlassian-ide-plugin.xml

# Crashlytics plugin (for Android Studio and IntelliJ)
com_crashlytics_export_strings.xml
crashlytics.properties
crashlytics-build.properties
fabric.properties

### Intellij Patch ###
# Comment Reason: https://github.com/joeblau/gitignore.io/issues/186#issuecomment-215987721

# *.iml
# modules.xml

Making a drop down list using swift?

Using UIPickerview is the right way to go to implement it according to Apple's Human Interface Guidelines

If you select drop down in mobile safari it will show UIPickerview to let the use choose drop down items.

Alternatively

you can use UIPopoverController till iOS 9 as its deprecated but its better to stick with UIModalPresentationPopover of view you want o show as well

you can use UIActionsheet to show the items but it's better to use UIAlertViewController and choose UIActionSheetstyle to show as the former is deprecated in latest versions

Is a new line = \n OR \r\n?

\n is used for Unix systems (including Linux, and OSX).

\r\n is mainly used on Windows.

\r is used on really old Macs.

PHP_EOL constant is used instead of these characters for portability between platforms.

How to find length of digits in an integer?

Without conversion to string

import math
digits = int(math.log10(n))+1

To also handle zero and negative numbers

import math
if n > 0:
    digits = int(math.log10(n))+1
elif n == 0:
    digits = 1
else:
    digits = int(math.log10(-n))+2 # +1 if you don't count the '-' 

You'd probably want to put that in a function :)

Here are some benchmarks. The len(str()) is already behind for even quite small numbers

timeit math.log10(2**8)
1000000 loops, best of 3: 746 ns per loop
timeit len(str(2**8))
1000000 loops, best of 3: 1.1 µs per loop

timeit math.log10(2**100)
1000000 loops, best of 3: 775 ns per loop
 timeit len(str(2**100))
100000 loops, best of 3: 3.2 µs per loop

timeit math.log10(2**10000)
1000000 loops, best of 3: 844 ns per loop
timeit len(str(2**10000))
100 loops, best of 3: 10.3 ms per loop

Fatal error: "No Target Architecture" in Visual Studio

Another cause of this can be including a header that depends on windows.h, before including windows.h.

In my case I included xinput.h before windows.h and got this error. Swapping the order solved the problem.

How to re-create database for Entity Framework?

While this question is premised by not caring about the data, sometimes maintenance of the data is essential.

If so, I wrote a list of steps on how to recover from Entity Framework nightmare when the database already has tables with the same name here: How to recover from Entity Framework nightmare - database already has tables with the same name

Apparently... a moderator saw fit to delete my post so I'll paste it here:

How to recover from Entity Framework nightmare - database already has tables with the same name

Description: If you're like us when your team is new to EF, you'll end up in a state where you either can't create a new local database or you can't apply updates to your production database. You want to get back to a clean EF environment and then stick to basics, but you can't. If you get it working for production, you can't create a local db, and if you get it working for local, your production server gets out of sync. And finally, you don't want to delete any production server data.

Symptom: Can't run Update-Database because it's trying to run the creation script and the database already has tables with the same name.

Error Message: System.Data.SqlClient.SqlException (0x80131904): There is already an object named '' in the database.

Problem Background: EF understands where the current database is at compared to where the code is at based on a table in the database called dbo.__MigrationHistory. When it looks at the Migration Scripts, it tries to reconsile where it was last at with the scripts. If it can't, it just tries to apply them in order. This means, it goes back to the initial creation script and if you look at the very first part in the UP command, it'll be the CreeateTable for the table that the error was occurring on.

To understand this in more detail, I'd recommend watching both videos referenced here: https://msdn.microsoft.com/en-us/library/dn481501(v=vs.113).aspx

Solution: What we need to do is to trick EF into thinking that the current database is up to date while not applying these CreateTable commands. At the same time, we still want those commands to exist so we can create new local databases.

Step 1: Production DB clean First, make a backup of your production db. In SSMS, Right-Click on the database, Select "Tasks > Export Data-tier application..." and follow the prompts. Open your production database and delete/drop the dbo.__MigrationHistory table.

Step 2: Local environment clean Open your migrations folder and delete it. I'm assuming you can get this all back from git if necessary.

Step 3: Recreate Initial In the Package Manager, run "Enable-Migrations" (EF will prompt you to use -ContextTypeName if you have multiple contexts). Run "Add-Migration Initial -verbose". This will Create the initial script to create the database from scratch based on the current code. If you had any seed operations in the previous Configuration.cs, then copy that across.

Step 4: Trick EF At this point, if we ran Update-Database, we'd be getting the original error. So, we need to trick EF into thinking that it's up to date, without running these commands. So, go into the Up method in the Initial migration you just created and comment it all out.

Step 5: Update-Database With no code to execute on the Up process, EF will create the dbo.__MigrationHistory table with the correct entry to say that it ran this script correctly. Go and check it out if you like. Now, uncomment that code and save. You can run Update-Database again if you want to check that EF thinks its up to date. It won't run the Up step with all of the CreateTable commands because it thinks it's already done this.

Step 6: Confirm EF is ACTUALLY up to date If you had code that hadn't yet had migrations applied to it, this is what I did...

Run "Add-Migration MissingMigrations" This will create practically an empty script. Because the code was there already, there was actually the correct commands to create these tables in the initial migration script, so I just cut the CreateTable and equivalent drop commands into the Up and Down methods.

Now, run Update-Database again and watch it execute your new migration script, creating the appropriate tables in the database.

Step 7: Re-confirm and commit. Build, test, run. Ensure that everything is running then commit the changes.

Step 8: Let the rest of your team know how to proceed. When the next person updates, EF won't know what hit it given that the scripts it had run before don't exist. But, assuming that local databases can be blown away and re-created, this is all good. They will need to drop their local database and add create it from EF again. If they had local changes and pending migrations, I'd recommend they create their DB again on master, switch to their feature branch and re-create those migration scripts from scratch.

Are the PUT, DELETE, HEAD, etc methods available in most web browsers?

I believe those comments refer specifically to the browsers, i.e., clicking links and submitting forms, not XMLHttpRequest. XMLHttpRequest is just a custom client that you wrote in JavaScript that uses the browser as a runtime.

UPDATE: To clarify, I did not mean (though I did write) that you wrote XMLHttpRequest; I meant that you wrote the code that uses XMLHttpRequest. The browsers do not natively support XMLHttpRequest. XMLHttpRequest comes from the JavaScript runtime, which may be hosted by a browser, although it isn't required to be (see Rhino). That's why people say browsers don't support PUT and DELETE—because it's actually JavaScript that is supporting them.

Nested or Inner Class in PHP

As per Xenon's comment to Anil Özselgin's answer, anonymous classes have been implemented in PHP 7.0, which is as close to nested classes as you'll get right now. Here are the relevant RFCs:

Nested Classes (status: withdrawn)

Anonymous Classes (status: implemented in PHP 7.0)

An example to the original post, this is what your code would look like:

<?php
    public class User {
        public $userid;
        public $username;
        private $password;

        public $profile;
        public $history;

        public function __construct() {
            $this->profile = new class {
                // Some code here for user profile
            }

            $this->history = new class {
                // Some code here for user history
            }
        }
    }
?>

This, though, comes with a very nasty caveat. If you use an IDE such as PHPStorm or NetBeans, and then add a method like this to the User class:

public function foo() {
  $this->profile->...
}

...bye bye auto-completion. This is the case even if you code to interfaces (the I in SOLID), using a pattern like this:

<?php
    public class User {
        public $profile;

        public function __construct() {
            $this->profile = new class implements UserProfileInterface {
                // Some code here for user profile
            }
        }
    }
?>

Unless your only calls to $this->profile are from the __construct() method (or whatever method $this->profile is defined in) then you won't get any sort of type hinting. Your property is essentially "hidden" to your IDE, making life very hard if you rely on your IDE for auto-completion, code smell sniffing, and refactoring.

Hide/encrypt password in bash file to stop accidentally seeing it

Although this is not a built in Unix solution, I've implemented a solution for this using a shell script that can be included in whatever shell script you are using. This is usable on POSIX compliant setups. (sh, bash, ksh, zsh) The full description is available in the github repo -> https://github.com/plyint/encpass.sh. This solution will auto-generate a key for your script and store the key and your password (or other secrets) in a hidden directory under your user (i.e. ~/.encpass).

In your script you just need to source encpass.sh and then call the get_secret method. For example:

#!/bin/sh
. encpass.sh
password=$(get_secret)

Pasted below is lite version of the code for encpass.sh(you can get the full version over on github) for easier visibility:

 #!/bin/sh
 ################################################################################
 # Copyright (c) 2020 Plyint, LLC <[email protected]>. All Rights Reserved.
 # This file is licensed under the MIT License (MIT). 
 # Please see LICENSE.txt for more information.
 # 
 # DESCRIPTION: 
 # This script allows a user to encrypt a password (or any other secret) at 
 # runtime and then use it, decrypted, within a script.  This prevents shoulder 
 # surfing passwords and avoids storing the password in plain text, which could 
 # inadvertently be sent to or discovered by an individual at a later date.
 #
 # This script generates an AES 256 bit symmetric key for each script (or user-
 # defined bucket) that stores secrets.  This key will then be used to encrypt 
 # all secrets for that script or bucket.  encpass.sh sets up a directory 
 # (.encpass) under the user's home directory where keys and secrets will be 
 # stored.
 #
 # For further details, see README.md or run "./encpass ?" from the command line.
 #
 ################################################################################

 encpass_checks() {
    [ -n "$ENCPASS_CHECKS" ] && return

    if [ -z "$ENCPASS_HOME_DIR" ]; then
        ENCPASS_HOME_DIR="$HOME/.encpass"
    fi
    [ ! -d "$ENCPASS_HOME_DIR" ] && mkdir -m 700 "$ENCPASS_HOME_DIR"

    if [ -f "$ENCPASS_HOME_DIR/.extension" ]; then
        # Extension enabled, load it...
        ENCPASS_EXTENSION="$(cat "$ENCPASS_HOME_DIR/.extension")"
        ENCPASS_EXT_FILE="encpass-$ENCPASS_EXTENSION.sh"
        if [ -f "./extensions/$ENCPASS_EXTENSION/$ENCPASS_EXT_FILE" ]; then
            # shellcheck source=/dev/null
          . "./extensions/$ENCPASS_EXTENSION/$ENCPASS_EXT_FILE"
        elif [ ! -z "$(command -v encpass-"$ENCPASS_EXTENSION".sh)" ]; then 
            # shellcheck source=/dev/null
            . "$(command -v encpass-$ENCPASS_EXTENSION.sh)"
        else
            encpass_die "Error: Extension $ENCPASS_EXTENSION could not be found."
        fi

        # Extension specific checks, mandatory function for extensions
        encpass_"${ENCPASS_EXTENSION}"_checks
    else
        # Use default OpenSSL implementation
        if [ ! -x "$(command -v openssl)" ]; then
            echo "Error: OpenSSL is not installed or not accessible in the current path." \
                "Please install it and try again." >&2
            exit 1
        fi

        [ ! -d "$ENCPASS_HOME_DIR/keys" ] && mkdir -m 700 "$ENCPASS_HOME_DIR/keys"
        [ ! -d "$ENCPASS_HOME_DIR/secrets" ] && mkdir -m 700 "$ENCPASS_HOME_DIR/secrets"
        [ ! -d "$ENCPASS_HOME_DIR/exports" ] && mkdir -m 700 "$ENCPASS_HOME_DIR/exports"

    fi

   ENCPASS_CHECKS=1
 }

 # Checks if the enabled extension has implented the passed function and if so calls it
 encpass_ext_func() {
   [ ! -z "$ENCPASS_EXTENSION" ] && ENCPASS_EXT_FUNC="$(command -v "encpass_${ENCPASS_EXTENSION}_$1")" || return
    [ ! -z "$ENCPASS_EXT_FUNC" ] && shift && $ENCPASS_EXT_FUNC "$@" 
 }

 # Initializations performed when the script is included by another script
 encpass_include_init() {
    encpass_ext_func "include_init" "$@"
    [ ! -z "$ENCPASS_EXT_FUNC" ] && return

    if [ -n "$1" ] && [ -n "$2" ]; then
        ENCPASS_BUCKET=$1
        ENCPASS_SECRET_NAME=$2
    elif [ -n "$1" ]; then
        if [ -z "$ENCPASS_BUCKET" ]; then
          ENCPASS_BUCKET=$(basename "$0")
        fi
        ENCPASS_SECRET_NAME=$1
    else
        ENCPASS_BUCKET=$(basename "$0")
        ENCPASS_SECRET_NAME="password"
    fi
 }

 encpass_generate_private_key() {
    ENCPASS_KEY_DIR="$ENCPASS_HOME_DIR/keys/$ENCPASS_BUCKET"

    [ ! -d "$ENCPASS_KEY_DIR" ] && mkdir -m 700 "$ENCPASS_KEY_DIR"

    if [ ! -f "$ENCPASS_KEY_DIR/private.key" ]; then
        (umask 0377 && printf "%s" "$(openssl rand -hex 32)" >"$ENCPASS_KEY_DIR/private.key")
    fi
 }

 encpass_set_private_key_abs_name() {
    ENCPASS_PRIVATE_KEY_ABS_NAME="$ENCPASS_HOME_DIR/keys/$ENCPASS_BUCKET/private.key"
    [ ! -n "$1" ] && [ ! -f "$ENCPASS_PRIVATE_KEY_ABS_NAME" ] && encpass_generate_private_key
 }

 encpass_set_secret_abs_name() {
    ENCPASS_SECRET_ABS_NAME="$ENCPASS_HOME_DIR/secrets/$ENCPASS_BUCKET/$ENCPASS_SECRET_NAME.enc"
    [ ! -n "$1" ] && [ ! -f "$ENCPASS_SECRET_ABS_NAME" ] && set_secret
 }

 encpass_rmfifo() {
    trap - EXIT
    kill "$1" 2>/dev/null
    rm -f "$2"
 }

 encpass_mkfifo() {
    fifo="$ENCPASS_HOME_DIR/$1.$$"
    mkfifo -m 600 "$fifo" || encpass_die "Error: unable to create named pipe"
    printf '%s\n' "$fifo"
 }

 get_secret() {
    encpass_checks
    encpass_ext_func "get_secret" "$@"; [ ! -z "$ENCPASS_EXT_FUNC" ] && return

    [ "$(basename "$0")" != "encpass.sh" ] && encpass_include_init "$1" "$2"

    encpass_set_private_key_abs_name
    encpass_set_secret_abs_name
    encpass_decrypt_secret "$@"
 }

 set_secret() {
    encpass_checks

    encpass_ext_func "set_secret" "$@"; [ ! -z "$ENCPASS_EXT_FUNC" ] && return

    if [ "$1" != "reuse" ] || { [ -z "$ENCPASS_SECRET_INPUT" ] && [ -z "$ENCPASS_CSECRET_INPUT" ]; }; then
        echo "Enter $ENCPASS_SECRET_NAME:" >&2
        stty -echo
        read -r ENCPASS_SECRET_INPUT
        stty echo
        echo "Confirm $ENCPASS_SECRET_NAME:" >&2
        stty -echo
        read -r ENCPASS_CSECRET_INPUT
        stty echo

        # Use named pipe to securely pass secret to openssl
        fifo="$(encpass_mkfifo set_secret_fifo)"
    fi

    if [ "$ENCPASS_SECRET_INPUT" = "$ENCPASS_CSECRET_INPUT" ]; then
        encpass_set_private_key_abs_name
        ENCPASS_SECRET_DIR="$ENCPASS_HOME_DIR/secrets/$ENCPASS_BUCKET"

        [ ! -d "$ENCPASS_SECRET_DIR" ] && mkdir -m 700 "$ENCPASS_SECRET_DIR"

        # Generate IV and create secret file
        printf "%s" "$(openssl rand -hex 16)" > "$ENCPASS_SECRET_DIR/$ENCPASS_SECRET_NAME.enc"
        ENCPASS_OPENSSL_IV="$(cat "$ENCPASS_SECRET_DIR/$ENCPASS_SECRET_NAME.enc")"

        echo "$ENCPASS_SECRET_INPUT" > "$fifo" &
        # Allow expansion now so PID is set
        # shellcheck disable=SC2064
        trap "encpass_rmfifo $! $fifo" EXIT HUP TERM INT TSTP

        # Append encrypted secret to IV in the secret file
        openssl enc -aes-256-cbc -e -a -iv "$ENCPASS_OPENSSL_IV" \
            -K "$(cat "$ENCPASS_HOME_DIR/keys/$ENCPASS_BUCKET/private.key")" \
            -in "$fifo" 1>> "$ENCPASS_SECRET_DIR/$ENCPASS_SECRET_NAME.enc"
    else
        encpass_die "Error: secrets do not match.  Please try again."
    fi
 }

 encpass_decrypt_secret() {
    encpass_ext_func "decrypt_secret" "$@"; [ ! -z "$ENCPASS_EXT_FUNC" ] && return

    if [ -f "$ENCPASS_PRIVATE_KEY_ABS_NAME" ]; then
        ENCPASS_DECRYPT_RESULT="$(dd if="$ENCPASS_SECRET_ABS_NAME" ibs=1 skip=32 2> /dev/null | openssl enc -aes-256-cbc \
            -d -a -iv "$(head -c 32 "$ENCPASS_SECRET_ABS_NAME")" -K "$(cat "$ENCPASS_PRIVATE_KEY_ABS_NAME")" 2> /dev/null)"
        if [ ! -z "$ENCPASS_DECRYPT_RESULT" ]; then
            echo "$ENCPASS_DECRYPT_RESULT"
        else
            # If a failed unlock command occurred and the user tries to show the secret
            # Present either a locked or failed decrypt error.
            if [ -f "$ENCPASS_HOME_DIR/keys/$ENCPASS_BUCKET/private.lock" ]; then 
            echo "**Locked**"
            else
                # The locked file wasn't present as expected.  Let's display a failure
            echo "Error: Failed to decrypt"
            fi
        fi
    elif [ -f "$ENCPASS_HOME_DIR/keys/$ENCPASS_BUCKET/private.lock" ]; then
        echo "**Locked**"
    else
        echo "Error: Unable to decrypt. The key file \"$ENCPASS_PRIVATE_KEY_ABS_NAME\" is not present."
    fi
 }

 encpass_die() {
   echo "$@" >&2
   exit 1
 }
 #LITE

What are 'get' and 'set' in Swift?

You should look at Computed Properties

In your code sample, perimeter is a property not backed up by a class variable, instead its value is computed using the get method and stored via the set method - usually referred to as getter and setter.

When you use that property like this:

var cp = myClass.perimeter

you are invoking the code contained in the get code block, and when you use it like this:

myClass.perimeter = 5.0

you are invoking the code contained in the set code block, where newValue is automatically filled with the value provided at the right of the assignment operator.

Computed properties can be readwrite if both a getter and a setter are specified, or readonly if the getter only is specified.

Android Studio update -Error:Could not run build action using Gradle distribution

I had same issue when first start Android Studio in Window 10, with java jdk 1.8.0_66. The solution that worked is:

Step 1: Close Android Studio

Step 2: Delete Folder C:\Users\Anna\.gradle (Anna is my username)

Step 3: Open Android Studio as Administrator

Step 4: If you are currently in an opened project, close current project by select File > Close Project.

Step 5: Now you seeing this Quick Start GUI: Android Studio Quick Start

Select Open an existing Android Studio project, navigate to your project folder and select it.

Wait for gradle to build again (it would download all the dependency in your build.gradle for every module in your project)

If it has not worked till now, you could restart your computer. Do step 1 again.

This happens sometime when I changed Android Studio version or recently upgrade Window. Hope that helps !

What exactly is a Maven Snapshot and why do we need it?

The three others answers provide you a good vision of what a -SNAPSHOT version is. I just wanted to add some information regarding the behavior of Maven when it finds a SNAPSHOT dependency.

When you build an application, Maven will search for dependencies in the local repository. If a stable version is not found there, it will search the remote repositories (defined in settings.xml or pom.xml) to retrieve this dependency. Then, it will copy it into the local repository, to make it available for the next builds.

For example, a foo-1.0.jar library is considered as a stable version, and if Maven finds it in the local repository, it will use this one for the current build.

Now, if you need a foo-1.0-SNAPSHOT.jar library, Maven will know that this version is not stable and is subject to changes. That's why Maven will try to find a newer version in the remote repositories, even if a version of this library is found on the local repository. However, this check is made only once per day. That means that if you have a foo-1.0-20110506.110000-1.jar (i.e. this library has been generated on 2011/05/06 at 11:00:00) in your local repository, and if you run the Maven build again the same day, Maven will not check the repositories for a newer version.

Maven provides you a way to change this update policy in your repository definition:

<repository>
    <id>foo-repository</id>
    <url>...</url>
    <snapshots>
        <enabled>true</enabled>
        <updatePolicy>XXX</updatePolicy>
    </snapshots>
</repository>

where XXX can be:

  • always: Maven will check for a newer version on every build;
  • daily, the default value;
  • interval:XXX: an interval in minutes (XXX)
  • never: Maven will never try to retrieve another version. It will do that only if it doesn't exist locally. With the configuration, SNAPSHOT version will be handled as the stable libraries.

(model of the settings.xml can be found here)

Removing element from array in component state

Here is a way to remove the element from the array in the state using ES6 spread syntax.

onRemovePerson: (index) => {
  const data = this.state.data;
  this.setState({ 
    data: [...data.slice(0,index), ...data.slice(index+1)]
  });
}

LINQ Orderby Descending Query

You need to choose a Property to sort by and pass it as a lambda expression to OrderByDescending

like:

.OrderByDescending(x => x.Delivery.SubmissionDate);

Really, though the first version of your LINQ statement should work. Is t.Delivery.SubmissionDate actually populated with valid dates?

ASP.NET MVC JsonResult Date Format

I have been working on a solution to this issue as none of the above answers really helped me. I am working with the jquery week calendar and needed my dates to have time zone information on the server and locally on the page. After quite a bit of digging around, I figured out a solution that may help others.

I am using asp.net 3.5, vs 2008, asp.net MVC 2, and jquery week calendar,

First, I am using a library written by Steven Levithan that helps with dealing with dates on the client side, Steven Levithan's date library. The isoUtcDateTime format is perfect for what I needed. In my jquery AJAX call I use the format function provided with the library with the isoUtcDateTime format and when the ajax call hits my action method, the datetime Kind is set to local and reflects the server time.

When I send dates to my page via AJAX, I send them as text strings by formatting the dates using "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'zzzz". This format is easily converted client side using

var myDate = new Date(myReceivedDate);

Here is my complete solution minus Steve Levithan's source, which you can download:

Controller:

public class HomeController : Controller
{
    public const string DATE_FORMAT = "ddd, dd MMM yyyy HH':'mm':'ss 'GMT'zzzz";

    public ActionResult Index()
    {
        ViewData["Message"] = "Welcome to ASP.NET MVC!";

        return View();
    }

    public ActionResult About()
    {
        return View();
    }


    public JsonResult GetData()
    {
        DateTime myDate = DateTime.Now.ToLocalTime();

        return new JsonResult { Data = new { myDate = myDate.ToString(DATE_FORMAT) } };
    }

    public JsonResult ReceiveData(DateTime myDate)
    {
        return new JsonResult { Data = new { myDate = myDate.ToString(DATE_FORMAT) } };
    }
}

Javascript:

<script type="text/javascript">

function getData() {
    $.ajax({
        url: "/Home/GetData",
        type: "POST",
        cache: "false",
        dataType: "json",
        success: function(data) {
            alert(data.myDate);
            var newDate = cleanDate(data.myDate);
            alert(newDate);
            sendData(newDate);
        }
    });
} 

function cleanDate(d) {
    if (typeof d == 'string') {
        return new Date(d) || Date.parse(d) || new Date(parseInt(d));
    }
    if (typeof d == 'number') {
        return new Date(d);
    }
    return d;
}

function sendData(newDate) {
    $.ajax({
        url: "/Home/ReceiveData",
        type: "POST",
        cache: "false",
        dataType: "json",
        data:
        {
            myDate: newDate.format("isoUtcDateTime")
        },
        success: function(data) {
            alert(data.myDate);
            var newDate = cleanDate(data.myDate);
            alert(newDate);
        }
    });
}

// bind myButton click event to call getData
$(document).ready(function() {
    $('input#myButton').bind('click', getData);
});
</script>

I hope this quick example helps out others in the same situation I was in. At this time it seems to work very well with the Microsoft JSON Serialization and keeps my dates correct across timezones.

How to mock location on device?

The solution mentioned by icyerasor and provided by Pedro at http://pedroassuncao.com/blog/2009/11/12/android-location-provider-mock/ worked very well for me. However, it does not offer support for properly starting, stopping and restarting the mock GPS provider.

I have changed his code a bit and rewritten the class to be an AsyncTask instead of a Thread. This allows us to communicate with the UI Thread, so we can restart the provider at the point where we were when we stopped it. This comes in handy when the screen orientation changes.

The code, along with a sample project for Eclipse, can be found on GitHub: https://github.com/paulhoux/Android-MockProviderGPS

All credit should go to Pedro for doing most of the hard work.

Byte and char conversion in Java

A character in Java is a Unicode code-unit which is treated as an unsigned number. So if you perform c = (char)b the value you get is 2^16 - 56 or 65536 - 56.

Or more precisely, the byte is first converted to a signed integer with the value 0xFFFFFFC8 using sign extension in a widening conversion. This in turn is then narrowed down to 0xFFC8 when casting to a char, which translates to the positive number 65480.

From the language specification:

5.1.4. Widening and Narrowing Primitive Conversion

First, the byte is converted to an int via widening primitive conversion (§5.1.2), and then the resulting int is converted to a char by narrowing primitive conversion (§5.1.3).


To get the right point use char c = (char) (b & 0xFF) which first converts the byte value of b to the positive integer 200 by using a mask, zeroing the top 24 bits after conversion: 0xFFFFFFC8 becomes 0x000000C8 or the positive number 200 in decimals.


Above is a direct explanation of what happens during conversion between the byte, int and char primitive types.

If you want to encode/decode characters from bytes, use Charset, CharsetEncoder, CharsetDecoder or one of the convenience methods such as new String(byte[] bytes, Charset charset) or String#toBytes(Charset charset). You can get the character set (such as UTF-8 or Windows-1252) from StandardCharsets.

How to do a SQL NOT NULL with a DateTime?

erm it does work? I've just tested it?

/****** Object:  Table [dbo].[DateTest]    Script Date: 09/26/2008 10:44:21 ******/
SET ANSI_NULLS ON
GO
SET QUOTED_IDENTIFIER ON
GO
CREATE TABLE [dbo].[DateTest](
    [Date1] [datetime] NULL,
    [Date2] [datetime] NOT NULL
) ON [PRIMARY]

GO
Insert into DateTest (Date1,Date2) VALUES (NULL,'1-Jan-2008')
Insert into DateTest (Date1,Date2) VALUES ('1-Jan-2008','1-Jan-2008')
Go
SELECT * FROM DateTest WHERE Date1 is not NULL
GO
SELECT * FROM DateTest WHERE Date2 is not NULL

How to programmatically disable page scrolling with jQuery

If you just want to disable scrolling with keyboard navigation, you can override keydown event.

$(document).on('keydown', function(e){
    e.preventDefault();
    e.stopPropagation();
});

clear javascript console in Google Chrome

There's always the good ol' trick:

console.log("\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n\n");

or a shorter variation of the above:

console.log('\n'.repeat('25'));

Not the most elegant solution, I know :) ... but works.

For me, I usually just print a long "-----" separator line to help make the logs easier to read.

Separators for Navigation

For those using Sass, I have written a mixin for this purpose:

@mixin addSeparator($element, $separator, $padding) {
    #{$element+'+'+$element}:before {
        content: $separator;
        padding: 0 $padding;
    }
}

Example:

@include addSeparator('li', '|', 1em);

Which will give you this:

li+li:before {
  content: "|";
  padding: 0 1em;
}

Can I safely delete contents of Xcode Derived data folder?

The content of 'Derived Data' is generated during Build-time. You can delete it safely. Follow below steps for deleting 'Derived Data' :

  1. Select Xcode -> Preferences..

Step 1

  1. This will open pop-up window. Select 'Locations' tab. In Locations sub-tab you can see 'Derived Data' Click on arrow icon next to path.

Step 2

  1. This will open-up folder containing 'Derived Data' Right click and Delete folder.

Step 3

How to get the employees with their managers

(SELECT ename FROM EMP WHERE empno = mgr)

There are no records in EMP that meet this criteria.

You need to self-join to get this relation.

SELECT e.ename AS Employee, e.empno, m.ename AS Manager, m.empno
FROM EMP AS e LEFT OUTER JOIN EMP AS m
ON e.mgr =m.empno;

EDIT:

The answer you selected will not list your president because it's an inner join. I'm thinking you'll be back when you discover your output isn't what your (I suspect) homework assignment required. Here's the actual test case:

> select * from emp;

 empno | ename |    job    | deptno | mgr  
-------+-------+-----------+--------+------
  7839 | king  | president |     10 |     
  7698 | blake | manager   |     30 | 7839
(2 rows)

> SELECT e.ename employee, e.empno, m.ename manager, m.empno
FROM emp AS e LEFT OUTER JOIN emp AS m
ON e.mgr =m.empno;

 employee | empno | manager | empno 
----------+-------+---------+-------
 king     |  7839 |         |      
 blake    |  7698 | king    |  7839
(2 rows)

The difference is that an outer join returns all the rows. An inner join will produce the following:

> SELECT e.ename, e.empno, m.ename as manager, e.mgr
FROM emp e, emp m
WHERE e.mgr = m.empno;

 ename | empno | manager | mgr  
-------+-------+---------+------
 blake |  7698 | king    | 7839
(1 row)

How to substring in jquery

var name = "nameGorge";
name.match(/[A-Z].*/)[0]

Formatting a field using ToText in a Crystal Reports formula field

I think you are looking for ToText(CCur(@Price}/{ValuationReport.YestPrice}*100-100))

You can use CCur to convert numbers or string to Curency formats. CCur(number) or CCur(string)


I think this may be what you are looking for,

Replace (ToText(CCur({field})),"$" , "") that will give the parentheses for negative numbers

It is a little hacky, but I'm not sure CR is very kind in the ways of formatting

Extracting an attribute value with beautifulsoup

Here is an example for how to extract the href attrbiutes of all a tags:

import requests as rq 
from bs4 import BeautifulSoup as bs

url = "http://www.cde.ca.gov/ds/sp/ai/"
page = rq.get(url)
html = bs(page.text, 'lxml')

hrefs = html.find_all("a")
all_hrefs = []
for href in hrefs:
    # print(href.get("href"))
    links = href.get("href")
    all_hrefs.append(links)

print(all_hrefs)

Select 50 items from list at random to write to file

Say your list has 100 elements and you want to pick 50 of them in a random way. Here are the steps to follow:

  1. Import the libraries
  2. Create the seed for random number generator, I have put it at 2
  3. Prepare a list of numbers from which to pick up in a random way
  4. Make the random choices from the numbers list

Code:

from random import seed
from random import choice

seed(2)
numbers = [i for i in range(100)]

print(numbers)

for _ in range(50):
    selection = choice(numbers)
    print(selection)

Add and Remove Views in Android Dynamically?

Hi You can try this way by adding relative layout and than add textview in that.

LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
            (LayoutParams.WRAP_CONTENT), (LayoutParams.WRAP_CONTENT));

RelativeLayout relative = new RelativeLayout(getApplicationContext());
relative.setLayoutParams(lp);

TextView tv = new TextView(getApplicationContext());
tv.setLayoutParams(lp);

EditText edittv = new EditText(getApplicationContext());
edittv.setLayoutParams(lp);

relative.addView(tv);
relative.addView(edittv);

replace NULL with Blank value or Zero in sql server

Try This

SELECT Title  from #Movies
    SELECT CASE WHEN Title = '' THEN 'No Title' ELSE Title END AS Titile from #Movies

OR

SELECT [Id], [CategoryId], ISNULL(nullif(Title,''),'No data') as Title, [Director], [DateReleased] FROM #Movies

How to create a self-signed certificate with OpenSSL

As of 2021, the following command serves all your needs, including SAN:

openssl req -x509 -newkey rsa:4096 -sha256 -days 3650 -nodes \
  -keyout example.key -out example.crt -extensions san -config \
  <(echo "[req]"; 
    echo distinguished_name=req; 
    echo "[san]"; 
    echo subjectAltName=DNS:example.com,DNS:www.example.net,IP:10.0.0.1
    ) \
  -subj "/CN=example.com"

In OpenSSL = 1.1.1, this can be shortened to:

openssl req -x509 -newkey rsa:4096 -sha256 -days 3650 -nodes \
  -keyout example.key -out example.crt -subj "/CN=example.com" \
  -addext "subjectAltName=DNS:example.com,DNS:www.example.net,IP:10.0.0.1"

It creates a certificate that is

  • valid for the (sub)domains example.com and www.example.net (SAN),
  • also valid for the IP address 10.0.0.1 (SAN),
  • relatively strong (as of 2021) and
  • valid for 3650 days (~10 years).

It creates the following files:

  • Private key: example.key
  • Certificate: example.crt

All information is provided at the command line. There is no interactive input that annoys you. There are no config files you have to mess around with. All necessary steps are executed by a single OpenSSL invocation: from private key generation up to the self-signed certificate.

Remark #1: Crypto parameters

Since the certificate is self-signed and needs to be accepted by users manually, it doesn't make sense to use a short expiration or weak cryptography.

In the future, you might want to use more than 4096 bits for the RSA key and a hash algorithm stronger than sha256, but as of 2021 these are sane values. They are sufficiently strong while being supported by all modern browsers.

Remark #2: Parameter "-nodes"

Theoretically you could leave out the -nodes parameter (which means "no DES encryption"), in which case example.key would be encrypted with a password. However, this is almost never useful for a server installation, because you would either have to store the password on the server as well, or you'd have to enter it manually on each reboot.

Remark #3: See also

Set div height equal to screen size

try this

$(document).ready(function(){
    $('#content').height($(window).height());
});

Convert JS date time to MySQL datetime

For arbitrary date string,

// Your default date object  
var starttime = new Date();
// Get the iso time (GMT 0 == UTC 0)
var isotime = new Date((new Date(starttime)).toISOString() );
// getTime() is the unix time value, in milliseconds.
// getTimezoneOffset() is UTC time and local time in minutes.
// 60000 = 60*1000 converts getTimezoneOffset() from minutes to milliseconds. 
var fixedtime = new Date(isotime.getTime()-(starttime.getTimezoneOffset()*60000));
// toISOString() is always 24 characters long: YYYY-MM-DDTHH:mm:ss.sssZ.
// .slice(0, 19) removes the last 5 chars, ".sssZ",which is (UTC offset).
// .replace('T', ' ') removes the pad between the date and time.
var formatedMysqlString = fixedtime.toISOString().slice(0, 19).replace('T', ' ');
console.log( formatedMysqlString );

Or a single line solution,

var formatedMysqlString = (new Date ((new Date((new Date(new Date())).toISOString() )).getTime() - ((new Date()).getTimezoneOffset()*60000))).toISOString().slice(0, 19).replace('T', ' ');
console.log( formatedMysqlString );

This solution also works for Node.js when using Timestamp in mysql.

@Gajus Kuizinas's first answer seems to modify mozilla's toISOString prototype

Multiple arguments to function called by pthread_create()?

I have the same question as the original poster, Michael.

However I have tried to apply the answers submitted for the original code without success

After some trial and error, here is my version of the code that works (or at least works for me!). And if you look closely, you will note that it is different to the earlier solutions posted.

#include <stdio.h>
#include <stdlib.h>
#include <pthread.h>

struct arg_struct
{
   int arg1;
   int arg2;
} *args;

void *print_the_arguments(void *arguments)
{
   struct arg_struct *args = arguments;
   printf("Thread\n");
   printf("%d\n", args->arg1);
   printf("%d\n", args->arg2);
   pthread_exit(NULL);
   return NULL;
}

int main()
{
   pthread_t some_thread;
   args = malloc(sizeof(struct arg_struct) * 1);

   args->arg1 = 5;
   args->arg2 = 7;

   printf("Before\n");
   printf("%d\n", args->arg1);
   printf("%d\n", args->arg2);
   printf("\n");


   if (pthread_create(&some_thread, NULL, &print_the_arguments, args) != 0)
   {
      printf("Uh-oh!\n");
      return -1;
   }

   return pthread_join(some_thread, NULL); /* Wait until thread is finished */
}

Where does Console.WriteLine go in ASP.NET?

If you look at the Console class in .NET Reflector, you'll find that if a process doesn't have an associated console, Console.Out and Console.Error are backed by Stream.Null (wrapped inside a TextWriter), which is a dummy implementation of Stream that basically ignores all input, and gives no output.

So it is conceptually equivalent to /dev/null, but the implementation is more streamlined: there's no actual I/O taking place with the null device.

Also, apart from calling SetOut, there is no way to configure the default.

Update 2020-11-02: As this answer is still gathering votes in 2020, it should probably be noted that under ASP.NET Core, there usually is a console attached. You can configure the ASP.NET Core IIS Module to redirect all stdout and stderr output to a log file via the stdoutLogEnabled and stdoutLogFile settings:

<system.webServer>
  <aspNetCore processPath="dotnet"
              arguments=".\MyApp.dll"
              hostingModel="inprocess"
              stdoutLogEnabled="true"
              stdoutLogFile=".\logs\stdout" />
<system.webServer>

Spring Security exclude url patterns in security annotation configurartion

Where are you configuring your authenticated URL pattern(s)? I only see one uri in your code.

Do you have multiple configure(HttpSecurity) methods or just one? It looks like you need all your URIs in the one method.

I have a site which requires authentication to access everything so I want to protect /*. However in order to authenticate I obviously want to not protect /login. I also have static assets I'd like to allow access to (so I can make the login page pretty) and a healthcheck page that shouldn't require auth.

In addition I have a resource, /admin, which requires higher privledges than the rest of the site.

The following is working for me.

@Override
protected void configure(HttpSecurity http) throws Exception {

    http.authorizeRequests()
        .antMatchers("/login**").permitAll()
        .antMatchers("/healthcheck**").permitAll()
        .antMatchers("/static/**").permitAll()
        .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")
        .antMatchers("/**").access("hasRole('ROLE_USER')")
        .and()
            .formLogin().loginPage("/login").failureUrl("/login?error")
                .usernameParameter("username").passwordParameter("password")
        .and()
            .logout().logoutSuccessUrl("/login?logout")
        .and()
            .exceptionHandling().accessDeniedPage("/403")
        .and()
            .csrf();

}

NOTE: This is a first match wins so you may need to play with the order. For example, I originally had /** first:

        .antMatchers("/**").access("hasRole('ROLE_USER')")
        .antMatchers("/login**").permitAll()
        .antMatchers("/healthcheck**").permitAll()

Which caused the site to continually redirect all requests for /login back to /login. Likewise I had /admin/** last:

        .antMatchers("/**").access("hasRole('ROLE_USER')")
        .antMatchers("/admin/**").access("hasRole('ROLE_ADMIN')")

Which resulted in my unprivledged test user "guest" having access to the admin interface (yikes!)

Pause in Python

On Windows 10 insert at beggining this:

#!/usr/bin/env python
# -*- coding: utf-8 -*-

Strange, but it works for me! (Together with input() at the end, of course)

How to show uncommitted changes in Git and some Git diffs in detail

You have already staged the changes (presumably by running git add), so in order to get their diff, you need to run:

git diff --cached

(A plain git diff will only show unstaged changes.)

For example: Example git diff cached use

JQuery: dynamic height() with window resize()

The cleanest solution - also purely CSS - would be using calc and vh.

The middle div's heigh will be calculated thusly:

#middle-div { 
height: calc(100vh - 46px); 
}

That is, 100% of the viewport height minus the 2*23px. This will ensure that the page loads properly and is dynamic(demo here).

Also remember to use box-sizing, so the paddings and borders don't make the divs outfill the viewport.

Resize an Array while keeping current elements in Java?

It is not possible to change the Array Size. But you can copy the element of one array into another array by creating an Array of bigger size.

It is recommended to create Array of double size if Array is full and Reduce Array to halve if Array is one-half full

public class ResizingArrayStack1 {
    private String[] s;
    private int size = 0;
    private int index = 0;

    public void ResizingArrayStack1(int size) {
        this.size = size;
        s = new String[size];
    }


    public void push(String element) {
        if (index == s.length) {
            resize(2 * s.length);
        }
        s[index] = element;
        index++;
    }

    private void resize(int capacity) {
        String[] copy = new String[capacity];
        for (int i = 0; i < s.length; i++) {
            copy[i] = s[i];
            s = copy;
        }
    }

    public static void main(String[] args) {
        ResizingArrayStack1 rs = new ResizingArrayStack1();
        rs.push("a");
        rs.push("b");
        rs.push("c");
        rs.push("d");
    }
}

Postgres - Transpose Rows to Columns

Use crosstab() from the tablefunc module.

SELECT * FROM crosstab(
   $$SELECT user_id, user_name, rn, email_address
     FROM  (
        SELECT u.user_id, u.user_name, e.email_address
             , row_number() OVER (PARTITION BY u.user_id
                            ORDER BY e.creation_date DESC NULLS LAST) AS rn
        FROM   usr u
        LEFT   JOIN email_tbl e USING (user_id)
        ) sub
     WHERE  rn < 4
     ORDER  BY user_id
   $$
  , 'VALUES (1),(2),(3)'
   ) AS t (user_id int, user_name text, email1 text, email2 text, email3 text);

I used dollar-quoting for the first parameter, which has no special meaning. It's just convenient if you have to escape single quotes in the query string which is a common case:

Detailed explanation and instructions here:

And in particular, for "extra columns":

The special difficulties here are:

  • The lack of key names.
    -> We substitute with row_number() in a subquery.

  • The varying number of emails.
    -> We limit to a max. of three in the outer SELECT
    and use crosstab() with two parameters, providing a list of possible keys.

Pay attention to NULLS LAST in the ORDER BY.

Select query to get data from SQL Server

According to MSDN

http://msdn.microsoft.com/ru-ru/library/system.data.sqlclient.sqlcommand.executenonquery(v=vs.110).aspx

result is the number of lines affected, and since your query is select no lines are affected (i.e. inserted, deleted or updated) anyhow.

If you want to return a single row of the query, use ExecuteScalar() instead of ExecuteNonQuery():

  int result = (int) (command.ExecuteScalar());

However, if you expect many rows to be returned, ExecuteReader() is the only option:

  using (SqlDataReader reader = command.ExecuteReader()) {
    while (reader.Read()) {
      int result = reader.GetInt32(0);

      ...
    }
  }

Use nginx to serve static files from subdirectories of a given directory

It should work, however http://nginx.org/en/docs/http/ngx_http_core_module.html#alias says:

When location matches the last part of the directive’s value: it is better to use the root directive instead:

which would yield:

server {
  listen        8080;
  server_name   www.mysite.com mysite.com;
  error_log     /home/www-data/logs/nginx_www.error.log;
  error_page    404    /404.html;

  location /public/doc/ {
    autoindex on;
    root  /home/www-data/mysite;
  } 

  location = /404.html {
    root /home/www-data/mysite/static/html;
  }       
}

Change text color with Javascript?

use ONLY

function init() { 
    about = document.getElementById("about");
    about.style.color = 'blue';
}

.innerHTML() sets or gets the HTML syntax describing the element's descendants., All you need is an object here.

Demo

List files committed for a revision

From remote repo:

svn log -v -r 42 --stop-on-copy --non-interactive --no-auth-cache --username USERNAME --password PASSWORD http://repourl/projectname/

Converting String to Cstring in C++

string name;
char *c_string;

getline(cin, name);

c_string = new char[name.length()];

for (int index = 0; index < name.length(); index++){
    c_string[index] = name[index];
}
c_string[name.length()] = '\0';//add the null terminator at the end of
                              // the char array

I know this is not the predefined method but thought it may be useful to someone nevertheless.

How to check if a string in Python is in ASCII?

def is_ascii(s):
    return all(ord(c) < 128 for c in s)

How to get whole and decimal part of a number?

$n = 1.25;
$whole = floor($n);      // 1
$fraction = $n - $whole; // .25

Then compare against 1/4, 1/2, 3/4, etc.


In cases of negative numbers, use this:

function NumberBreakdown($number, $returnUnsigned = false)
{
  $negative = 1;
  if ($number < 0)
  {
    $negative = -1;
    $number *= -1;
  }

  if ($returnUnsigned){
    return array(
      floor($number),
      ($number - floor($number))
    );
  }

  return array(
    floor($number) * $negative,
    ($number - floor($number)) * $negative
  );
}

The $returnUnsigned stops it from making -1.25 in to -1 & -0.25

How to change package name of Android Project in Eclipse?

As usual, by pressing F2 on the package name, you can rename or change the package name, and also by right-clicking and then select Rename option, you can change or rename the package name.

When you press F2, it will show you the dialog box as:

Alt text

In this dialog, don't forget to check the "Update references" checkbox because by making "check" to this check-box, it will make changes to all the references of the package which are referred by other components of project.

Should I use px or rem value units in my CSS?

Half (but only half) snarky answer (the other half is bitter disdain of the reality of bureaucracy):

Use vh

Everything is always sized to browser window.

Always allow scroll down, but disable horizontal scroll.

Set body width to be a static 50vh, and never code css that floats or breaks out of the parent div. (If they try to mock up something that looks like it does, clever use of a background gif can throw them off track.) And style only using tables so everything is held rigidly into place as expected. Include a javascript function to undo any ctrl+/- activity the user may do.

Users will hate you, because the site doesn't flow differently based on what they're using (such as text being too small to read on phones). Your coworkers will hate you because nobody in their right mind does this and it will likely break their work (though not yours). Your programming professors will hate you because this is not a good idea. Your UX designer will hate you because it will reveal the corners they cut in designing UX mock-ups that they have to do in order to meet deadlines.

Nearly everyone will hate you, except the people who tell you to make things match the mock-up and to do so quickly. Those people, however (which generally include the project managers), will be ecstatic by your accuracy and fast turn around time. And everyone knows their opinion is the only one that matters to your paycheck.

Gulp error: The following tasks did not complete: Did you forget to signal async completion?

Here you go: No synchronous tasks.

No synchronous tasks

Synchronous tasks are no longer supported. They often led to subtle mistakes that were hard to debug, like forgetting to return your streams from a task.

When you see the Did you forget to signal async completion? warning, none of the techniques mentioned above were used. You'll need to use the error-first callback or return a stream, promise, event emitter, child process, or observable to resolve the issue.

Using async/await

When not using any of the previous options, you can define your task as an async function, which wraps your task in a promise. This allows you to work with promises synchronously using await and use other synchronous code.

const fs = require('fs');

async function asyncAwaitTask() {
  const { version } = fs.readFileSync('package.json');
  console.log(version);
  await Promise.resolve('some result');
}

exports.default = asyncAwaitTask;

Hide div if screen is smaller than a certain width

The problem I was having is my css media queries and my IF statement in Jquery clashing. They were both set to 700px but one would think it's hit 700px before the other.

To get around this I created a empty Div right at the top of my HTML(outside my main container)

<div id="max-width"></div>

In css I set this div to display none

 #max-width {
        display: none;
    }

In my JS created a function

var hasSwitched = function () {
    var maxWidth = parseInt($('#max-width').css('max-width'), 10);
    return !isNaN(maxWidth);
};

So in my IF statement instead of saying if (hasSwitched<700) perform the following code, I did the following

if (!hasSwitched()) { Your code

}

else{ your code

}

By doing this CSS tells Jquery when it's hit 700px. So css and jquery are both synchronized... rather than having a couple of pixels difference. Do give this a try peeps it shall definitely not disappoint.

To get this same logic working for IE8 I used the Respond.js plugin(which also definitely works) It lets you use media queries for IE8. Only thing that wasn't supported was the viewport width and viewport height... hence my reason to try get my css and JS working together. Hope this helps you guys

Statistics: combinations in Python

If you want an exact result, use sympy.binomial. It seems to be the fastest method, hands down.

x = 1000000
y = 234050

%timeit scipy.misc.comb(x, y, exact=True)
1 loops, best of 3: 1min 27s per loop

%timeit gmpy.comb(x, y)
1 loops, best of 3: 1.97 s per loop

%timeit int(sympy.binomial(x, y))
100000 loops, best of 3: 5.06 µs per loop

How to send multiple data fields via Ajax?

Try this:

$(document).ready(function() {
  $("#btnSubmit").click(function() {
    var status = $("#activitymessage").val();
    var name = "Ronny";
    $.ajax({
      type: "POST",
      url: "ajax/activity_save.php",
      data: {'status': status, 'name': name},
        success: function(msg) {...

What is the 'realtime' process priority setting for?

It basically is higher/greater in everything else. A keyboard is less of a priority than the real time process. This means the process will be taken into account faster then keyboard and if it can't handle that, then your keyboard is slowed.

Access index of the parent ng-repeat from child ng-repeat

My example code was correct and the issue was something else in my actual code. Still, I know it was difficult to find examples of this so I'm answering it in case someone else is looking.

<div ng-repeat="f in foos">
  <div>
    <div ng-repeat="b in foos.bars">
      <a ng-click="addSomething($parent.$index)">Add Something</a>
    </div>
  </div>
</div>

Input type number "only numeric value" validation

Using directive it becomes easy and can be used throughout the application

HTML

<input type="text" placeholder="Enter value" numbersOnly>

As .keyCode() and .which() are deprecated, codes are checked using .key() Referred from

Directive:

@Directive({
   selector: "[numbersOnly]"
})

export class NumbersOnlyDirective {
  @Input() numbersOnly:boolean;

  navigationKeys: Array<string> = ['Backspace']; //Add keys as per requirement
  
  constructor(private _el: ElementRef) { }

  @HostListener('keydown', ['$event']) onKeyDown(e: KeyboardEvent) {
    
    if (
      // Allow: Delete, Backspace, Tab, Escape, Enter, etc
      this.navigationKeys.indexOf(e.key) > -1 || 
      (e.key === 'a' && e.ctrlKey === true) || // Allow: Ctrl+A
      (e.key === 'c' && e.ctrlKey === true) || // Allow: Ctrl+C
      (e.key === 'v' && e.ctrlKey === true) || // Allow: Ctrl+V
      (e.key === 'x' && e.ctrlKey === true) || // Allow: Ctrl+X
      (e.key === 'a' && e.metaKey === true) || // Cmd+A (Mac)
      (e.key === 'c' && e.metaKey === true) || // Cmd+C (Mac)
      (e.key === 'v' && e.metaKey === true) || // Cmd+V (Mac)
      (e.key === 'x' && e.metaKey === true) // Cmd+X (Mac)
    ) {
        return;  // let it happen, don't do anything
    }
    // Ensure that it is a number and stop the keypress
    if (e.key === ' ' || isNaN(Number(e.key))) {
      e.preventDefault();
    }
  }
}

Parsing ISO 8601 date in Javascript

Maybe, you can use moment.js which in my opinion is the best JavaScript library for parsing, formatting and working with dates client-side. You could use something like:

_x000D_
_x000D_
var momentDate = moment('1890-09-30T23:59:59+01:16:20', 'YYYY-MM-DDTHH:mm:ss+-HH:mm:ss');_x000D_
var jsDate = momentDate.toDate();_x000D_
_x000D_
// Now, you can run any JavaScript Date method_x000D_
_x000D_
jsDate.toLocaleString();
_x000D_
_x000D_
_x000D_

The advantage of using a library like moment.js is that your code will work perfectly even in legacy browsers like IE 8+.

Here is the documenation about parsing methods: https://momentjs.com/docs/#/parsing/

How can I read the client's machine/computer name from the browser?

<html>
<body onload = "load()">
<script>
  function load(){ 

     try {
       var ax = new ActiveXObject("WScript.Network");
       alert('User: ' + ax.UserName );
       alert('Computer: ' + ax.ComputerName);
     }
     catch (e) {
       document.write('Permission to access computer name is denied' + '<br />');
     } 
  }
</script>
</body>
</html>

"Sources directory is already netbeans project" error when opening a project from existing sources

  1. copy an existing netbeans project folder in to your new project and manually edit the xml project name.

  2. reinstall netbeans

  3. copy/move all files/folders (except nbproject/ folder) to a new folder for your project, with a new name.

ImportError: No module named dateutil.parser

None of the solutions worked for me. If you are using PIP do:

pip install pycrypto==2.6.1

Jquery selector input[type=text]')

Using a normal css selector:

$('.sys input[type=text], .sys select').each(function() {...})

If you don't like the repetition:

$('.sys').find('input[type=text],select').each(function() {...})

Or more concisely, pass in the context argument:

$('input[type=text],select', '.sys').each(function() {...})

Note: Internally jQuery will convert the above to find() equivalent

http://api.jquery.com/jQuery/

Internally, selector context is implemented with the .find() method, so $('span', this) is equivalent to $(this).find('span').

I personally find the first alternative to be the most readable :), your take though

String to object in JS

This simple way...

var string = "{firstName:'name1', lastName:'last1'}";
eval('var obj='+string);
alert(obj.firstName);

output

name1

Convert Mat to Array/Vector in OpenCV

Here is another possible solution assuming matrix have one column( you can reshape original Mat to one column Mat via reshape):

Mat matrix= Mat::zeros(20, 1, CV_32FC1);
vector<float> vec;
matrix.col(0).copyTo(vec);

What is output buffering?

Output buffering is used by PHP to improve performance and to perform a few tricks.

  • You can have PHP store all output into a buffer and output all of it at once improving network performance.

  • You can access the buffer content without sending it back to browser in certain situations.

Consider this example:

<?php
    ob_start( );
    phpinfo( );
    $output = ob_get_clean( );
?>

The above example captures the output into a variable instead of sending it to the browser. output_buffering is turned off by default.

  • You can use output buffering in situations when you want to modify headers after sending content.

Consider this example:

<?php
    ob_start( );
    echo "Hello World";
    if ( $some_error )
    {
        header( "Location: error.php" );
        exit( 0 );
    }
?>

How to declare a Fixed length Array in TypeScript

Actually, You can achieve this with current typescript:

type Grow<T, A extends Array<T>> = ((x: T, ...xs: A) => void) extends ((...a: infer X) => void) ? X : never;
type GrowToSize<T, A extends Array<T>, N extends number> = { 0: A, 1: GrowToSize<T, Grow<T, A>, N> }[A['length'] extends N ? 0 : 1];

export type FixedArray<T, N extends number> = GrowToSize<T, [], N>;

Examples:

// OK
const fixedArr3: FixedArray<string, 3> = ['a', 'b', 'c'];

// Error:
// Type '[string, string, string]' is not assignable to type '[string, string]'.
//   Types of property 'length' are incompatible.
//     Type '3' is not assignable to type '2'.ts(2322)
const fixedArr2: FixedArray<string, 2> = ['a', 'b', 'c'];

// Error:
// Property '3' is missing in type '[string, string, string]' but required in type 
// '[string, string, string, string]'.ts(2741)
const fixedArr4: FixedArray<string, 4> = ['a', 'b', 'c'];

EDIT (after a long time)

This should handle bigger sizes (as basically it grows array exponentially until we get to closest power of two):

type Shift<A extends Array<any>> = ((...args: A) => void) extends ((...args: [A[0], ...infer R]) => void) ? R : never;

type GrowExpRev<A extends Array<any>, N extends number, P extends Array<Array<any>>> = A['length'] extends N ? A : {
  0: GrowExpRev<[...A, ...P[0]], N, P>,
  1: GrowExpRev<A, N, Shift<P>>
}[[...A, ...P[0]][N] extends undefined ? 0 : 1];

type GrowExp<A extends Array<any>, N extends number, P extends Array<Array<any>>> = A['length'] extends N ? A : {
  0: GrowExp<[...A, ...A], N, [A, ...P]>,
  1: GrowExpRev<A, N, P>
}[[...A, ...A][N] extends undefined ? 0 : 1];

export type FixedSizeArray<T, N extends number> = N extends 0 ? [] : N extends 1 ? [T] : GrowExp<[T, T], N, [[T]]>;

Need to remove href values when printing in Chrome

To hide Page url .

use media="print" in style tage example :

<style type="text/css" media="print">
            @page {
                size: auto;   /* auto is the initial value */
                margin: 0;  /* this affects the margin in the printer settings */
            }
            @page { size: portrait; }
</style>

If you want to remove links :

@media print {
   a[href]:after {
      visibility: hidden !important;
   }
}

Significance of ios_base::sync_with_stdio(false); cin.tie(NULL);

It's just common stuff for making cin input work faster.

For a quick explanation: the first line turns off buffer synchronization between the cin stream and C-style stdio tools (like scanf or gets) — so cin works faster, but you can't use it simultaneously with stdio tools.

The second line unties cin from cout — by default the cout buffer flushes each time when you read something from cin. And that may be slow when you repeatedly read something small then write something small many times. So the line turns off this synchronization (by literally tying cin to null instead of cout).

Case statement in MySQL

Try to use IF(condition, value1, value2)

SELECT ID, HEADING, 
IF(action_type='Income',action_amount,0) as Income,
IF(action_type='Expense',action_amount,0) as Expense

Force HTML5 youtube video

I tried using the iframe embed code and the HTML5 player appeared, however, for some reason the iframe was completely breaking my site.

I messed around with the old object embed code and it works perfectly fine. So if you're having problems with the iframe here's the code i used:

<object width="640" height="360">
<param name="movie" value="http://www.youtube.com/embed/VIDEO_ID?html5=1&amp;rel=0&amp;hl=en_US&amp;version=3"/>
<param name="allowFullScreen" value="true"/>
<param name="allowscriptaccess" value="always"/>
<embed width="640" height="360" src="http://www.youtube.com/embed/VIDEO_ID?html5=1&amp;rel=0&amp;hl=en_US&amp;version=3" class="youtube-player" type="text/html" allowscriptaccess="always" allowfullscreen="true"/>
</object>

hope this is useful for someone

How to cut an entire line in vim and paste it?

dd in command mode (after pressing escape) will cut the line, p in command mode will paste.

Update:

For a bonus, d and then a movement will cut the equivalent of that movement, so dw will cut a word, d<down-arrow> will cut this line and the line below, d50w will cut 50 words.

yy is copy line, and works like dd.

D cuts from cursor to end of line.

If you've used v (visual mode), you should try V (visual line mode) and <ctrl>v (visual block mode).

Dynamically create and submit form

Try with this code -
It is a totally dynamic solution:

    var form = $(document.createElement('form'));
    $(form).attr("action", "reserves.php");
    $(form).attr("method", "POST");

    var input = $("<input>").attr("type", "hidden").attr("name", "mydata").val("bla");
    $(form).append($(input));
    $(form).submit();

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

If your data has the names grouped as shown then you can use this formula in D2 copied down to get a total against the last entry for each name

=IF((A2=A3)*(B2=B3),"",SUM(C$2:C2)-SUM(D$1:D1))

See screenshot

enter image description here

Finding the median of an unsorted array

The quick select algorithm can find the k-th smallest element of an array in linear (O(n)) running time. Here is an implementation in python:

import random

def partition(L, v):
    smaller = []
    bigger = []
    for val in L:
        if val < v: smaller += [val]
        if val > v: bigger += [val]
    return (smaller, [v], bigger)

def top_k(L, k):
    v = L[random.randrange(len(L))]
    (left, middle, right) = partition(L, v)
    # middle used below (in place of [v]) for clarity
    if len(left) == k:   return left
    if len(left)+1 == k: return left + middle
    if len(left) > k:    return top_k(left, k)
    return left + middle + top_k(right, k - len(left) - len(middle))

def median(L):
    n = len(L)
    l = top_k(L, n / 2 + 1)
    return max(l)

Plotting multiple lines, in different colors, with pandas dataframe

You could use groupby to split the DataFrame into subgroups according to the color:

for key, grp in df.groupby(['color']):

import numpy as np
import pandas as pd
import matplotlib.pyplot as plt

df = pd.read_table('data', sep='\s+')
fig, ax = plt.subplots()

for key, grp in df.groupby(['color']):
    ax = grp.plot(ax=ax, kind='line', x='x', y='y', c=key, label=key)

plt.legend(loc='best')
plt.show()

yields enter image description here

What does MissingManifestResourceException mean and how to fix it?

I had the with a newly created F# project. The solution was to uncheck "Use standard resource names" in the project properties -> Application -> Resources / Specify how application resources will be managed. If you do not see the checkbox then update your Visual Studio! I have 15.6.7 installed. In 15.3.2 this checkbox is not there.

Using :: in C++

One use for the 'Unary Scope Resolution Operator' or 'Colon Colon Operator' is for local and global variable selection of identical names:

    #include <iostream>
    using namespace std;
    
    int variable = 20;
    
    int main()
    {
    float variable = 30;
    
    cout << "This is local to the main function: " << variable << endl;
    cout << "This is global to the main function: " << ::variable << endl;
    
    return 0;
    }

The resulting output would be:

This is local to the main function: 30

This is global to the main function: 20

Other uses could be: Defining a function from outside of a class, to access a static variable within a class or to use multiple inheritance.

Create a asmx web service in C# using visual studio 2013

on the web site box, you have selected .NETFramework 4.5 and it doesn show, so click there and choose the 3.5...i hope it helps.

Function overloading in Javascript - Best practices

I like @AntouanK's approach. I often find myself offering a function with different numbers o parameters and different types. Sometimes they don't follow a order. I use to map looking the types of parameters:

findUDPServers: function(socketProperties, success, error) {
    var fqnMap = [];

    fqnMap['undefined'] = fqnMap['function'] = function(success, error) {
        var socketProperties = {name:'HELLO_SERVER'};

        this.searchServers(socketProperties, success, error);
    };

    fqnMap['object'] = function(socketProperties, success, error) {
        var _socketProperties = _.merge({name:'HELLO_SERVER'}, socketProperties || {});

        this.searchServers(_socketProperties, success, error);
    };

    fqnMap[typeof arguments[0]].apply(this, arguments);
}

Python script to copy text to clipboard

To use native Python directories, use:

import subprocess

def copy2clip(txt):
    cmd='echo '+txt.strip()+'|clip'
    return subprocess.check_call(cmd, shell=True)

on Mac, instead:

import subprocess

def copy2clip(txt):
    cmd='echo '+txt.strip()+'|pbcopy'
    return subprocess.check_call(cmd, shell=True)

Then use:

copy2clip('This is on my clipboard!')

to call the function.

How to enter special characters like "&" in oracle database?

For special character set, you need to check UNICODE Charts. After choose your character, you can use sql statement below,

SELECT COMPOSE('do' || UNISTR('\0304' || 'TTTT')) FROM dual;

--

doTTTT

Apple Mach-O Linker Error when compiling for device

This error can also be occurred if you have imported two different versions of same library ,in this case just remove the older version and keep only one version and Magic will work for you.

AttributeError: 'str' object has no attribute 'strftime'

You should use datetime object, not str.

>>> from datetime import datetime
>>> cr_date = datetime(2013, 10, 31, 18, 23, 29, 227)
>>> cr_date.strftime('%m/%d/%Y')
'10/31/2013'

To get the datetime object from the string, use datetime.datetime.strptime:

>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f')
datetime.datetime(2013, 10, 31, 18, 23, 29, 227)
>>> datetime.strptime(cr_date, '%Y-%m-%d %H:%M:%S.%f').strftime('%m/%d/%Y')
'10/31/2013'

How can I specify a display?

Please do NOT try to set $DISPLAY manually when connecting over SSH.
If you connect via SSH -X and $DISPLAY stays empty, this usually means that no encrypted channel could be established.

Most likely you are missing the package xauth or xorg-x11-xauth. Try to install it on the remote machine using:

sudo apt-get install xauth

or

sudo apt-get install xorg-x11-xauth

After that end and restart your SSH connection. Don't forget to use SSH -X so that X Window output is forwarded to your local machine.

Now try echo $DISPLAYagain to see if $DISPLAY has been set automatically by the SSH demon. It should show you a line with an IP address and a port.

How to delete a column from a table in MySQL

If you are running MySQL 5.6 onwards, you can make this operation online, allowing other sessions to read and write to your table while the operation is been performed:

ALTER TABLE tbl_Country DROP COLUMN IsDeleted, ALGORITHM=INPLACE, LOCK=NONE;

Initializing IEnumerable<string> In C#

You can create a static method that will return desired IEnumerable like this :

public static IEnumerable<T> CreateEnumerable<T>(params T[] values) =>
    values;
//And then use it
IEnumerable<string> myStrings = CreateEnumerable("first item", "second item");//etc..

Alternatively just do :

IEnumerable<string> myStrings = new []{ "first item", "second item"};

How to Identify port number of SQL server

You can also use this query

USE MASTER GO xp_readerrorlog 0, 1, N'Server is listening on' GO

Source : sqlauthority blog

How to tell CRAN to install package dependencies automatically?

Another possibility is to select the Install Dependencies checkbox In the R package installer, on the bottom right:

enter image description here

How to get date representing the first day of a month?

i think normally converts string to MM/DD/YY HH:mm:ss, you would need to use 08/01/2010 00:00:00

Sorry, misunderstood the question, looking to see if you can change the order for strings.

This may be what you want:

declare @test as date

select @test = CONVERT(date, '01/08/2010 00:00:00', 103)
select convert(varchar(15), @test, 106)

How to add a border just on the top side of a UIView

I came up with a solution using Swift 4.1 that uses AutoLayout and UIViews so that it will resize with the view.

It is based off @AdamWaite 's answer but solves the issue for table view cells where the cells are reused. If the previous border is not removed before adding a new one, then the reused cell will contain multiple borders.

This is solved by creating a dummy BorderView class and searching the subview's for the borders and removing them.

This code uses SnapKit for constraints and CocoaLumberjack for debugging. If you are not using these, then it should be fairly straightforward to convert

class BorderView: UIView {
}

extension UIView {
    private func addSidedBorder(toEdge edge: UIRectEdge, withColor color: UIColor, inset: CGFloat, thickness: CGFloat) {
        let border = BorderView(frame: .zero)
        border.backgroundColor = color
        addSubview(border)

        border.snp.makeConstraints { make in
            switch edge {
            case .top:
                make.top.equalToSuperview()
                make.height.equalTo(thickness)
                make.left.right.equalToSuperview().inset(inset)

            case .left:
                make.left.equalToSuperview()
                make.width.equalTo(thickness)
                make.top.bottom.equalToSuperview().inset(inset)

            case .bottom:
                make.bottom.equalToSuperview()
                make.height.equalTo(thickness)
                make.left.right.equalToSuperview().inset(inset)

            case .right:
                make.right.equalToSuperview()
                make.width.equalTo(thickness)
                make.top.bottom.equalToSuperview().inset(inset)

            default:
                DDLogWarn("Invalid sided border given in ExtendedUIView, border not added correctly")
            }
        }
    }

    func addBorder(toEdge edge: UIRectEdge, withColor color: UIColor = .black, inset: CGFloat = 0.0, thickness: CGFloat = 1.0) {
        // Remove existing borders from view and readd them
        for view in subviews {
            if view is BorderView {
                view.removeFromSuperview()
            }
        }

        if edge.contains(.all) {
            addSidedBorder(toEdge: .top, withColor: color, inset: inset, thickness: thickness)
            addSidedBorder(toEdge: .left, withColor: color, inset: inset, thickness: thickness)
            addSidedBorder(toEdge: .bottom, withColor: color, inset: inset, thickness: thickness)
            addSidedBorder(toEdge: .right, withColor: color, inset: inset, thickness: thickness)
        } else {
            if edge.contains(.top) {
                addSidedBorder(toEdge: .top, withColor: color, inset: inset, thickness: thickness)
            }

            if edge.contains(.left) {
                addSidedBorder(toEdge: .left, withColor: color, inset: inset, thickness: thickness)
            }

            if edge.contains(.bottom) {
                addSidedBorder(toEdge: .bottom, withColor: color, inset: inset, thickness: thickness)
            }

            if edge.contains(.right) {
                addSidedBorder(toEdge: .right, withColor: color, inset: inset, thickness: thickness)
            }
        }
    }
}

Add this code and then within a class that subclasses UIView, call:

view.addBorder(toEdge: [.left, .right], withColor: .red, inset: 0.0, thickness: 1.0)

Sorting data based on second column of a file

Use sort.

sort ... -k 2,2 ...

Plotting multiple curves same graph and same scale

My solution is to use ggplot2. It takes care of these types of things automatically. The biggest thing is to arrange the data appropriately.

y1 <- c(100, 200, 300, 400, 500)
y2 <- c(1, 2, 3, 4, 5)
x <- c(1, 2, 3, 4, 5)
df <- data.frame(x=rep(x,2), y=c(y1, y2), class=c(rep("y1", 5), rep("y2", 5)))

Then use ggplot2 to plot it

library(ggplot2)
ggplot(df, aes(x=x, y=y, color=class)) + geom_point()

This is saying plot the data in df, and separate the points by class.

The plot generated isenter image description here

Get an object attribute

To access field or method of an object use dot .:

user = User()
print user.fullName

If a name of the field will be defined at run time, use buildin getattr function:

field_name = "fullName"
print getattr(user, field_name) # prints content of user.fullName

Count unique values with pandas per groups

df.domain.value_counts()

>>> df.domain.value_counts()

vk.com          5

twitter.com     2

google.com      1

facebook.com    1

Name: domain, dtype: int64

jQuery - Trigger event when an element is removed from the DOM

I'm not sure there is an event handle for this, so you would have to keep a copy of the DOM and compare to the existing DOM in some kind of polling loop - which could be quite nasty. Firebug does this though - if you inspect the HTML and run some DOM-changes, it highlights the changes in yellow in the Firebug console for a short time.

Alternatively, you could create a remove function...

var removeElements = function(selector) {
    var elems = jQuery(selector);

    // Your code to notify the removal of the element here...
    alert(elems.length + " elements removed");

    jQuery(selector).remove();
};

// Sample usage
removeElements("#some-element");
removeElements("p");
removeElements(".myclass");

std::enable_if to conditionally compile a member function

From this post:

Default template arguments are not part of the signature of a template

But one can do something like this:

#include <iostream>

struct Foo {
    template < class T,
               class std::enable_if < !std::is_integral<T>::value, int >::type = 0 >
    void f(const T& value)
    {
        std::cout << "Not int" << std::endl;
    }

    template<class T,
             class std::enable_if<std::is_integral<T>::value, int>::type = 0>
    void f(const T& value)
    {
        std::cout << "Int" << std::endl;
    }
};

int main()
{
    Foo foo;
    foo.f(1);
    foo.f(1.1);

    // Output:
    // Int
    // Not int
}

How do I extract a substring from a string until the second space is encountered?

A straightforward approach would be the following:

string[] tokens = str.Split(' ');
string retVal = tokens[0] + " " + tokens[1];

When should an IllegalArgumentException be thrown?

Any API should check the validity of the every parameter of any public method before executing it:

void setPercentage(int pct, AnObject object) {
    if( pct < 0 || pct > 100) {
        throw new IllegalArgumentException("pct has an invalid value");
    }
    if (object == null) {
        throw new IllegalArgumentException("object is null");
    }
}

They represent 99.9% of the times errors in the application because it is asking for impossible operations so in the end they are bugs that should crash the application (so it is a non recoverable error).

In this case and following the approach of fail fast you should let the application finish to avoid corrupting the application state.

How to run ~/.bash_profile in mac terminal

As @kojiro said, you don't want to "run" this file. Source it as he says. It should get "sourced" at startup. Sourcing just means running every line in the file, including the one you want to get run. If you want to make sure a folder is in a certain path environment variable (as it seems you want from one of your comments on another solution), execute

$ echo $PATH

At the command line. If you want to check that your ~/.bash_profile is being sourced, either at startup as it should be, or when you source it manually, enter the following line into your ~/.bash_profile file:

$ echo "Hello I'm running stuff in the ~/.bash_profile!"

Verify if file exists or not in C#

These answers all assume the file you are checking is on the server side. Unfortunately, there is no cast iron way to ensure that a file exists on the client side (e.g. if you are uploading the resume). Sure, you can do it in Javascript but you are still not going to be 100% sure on the server side.

The best way to handle this, in my opinion, is to assume that the user will actually select an appropriate file for upload, and then do whatever work you need to do to ensure the uploaded file is what you expect (hint - assume the user is trying to poison your system in every possible way with his/her input)

Unable to launch the IIS Express Web server, Failed to register URL, Access is denied

If you're having this after installing Visual Studio 2015 and you can see Error messages in System event log such as this: Unable to bind to the underlying transport for [::]:{your_port}. . The IP Listen-Only list may contain a reference ... then you might be missing a registry entry.

Run this under administrative command prompt: netsh http add iplisten ipaddress=:: to fix it.

I found the solution described in detail here

JavaScript Chart.js - Custom data formatting to display on tooltip

This is what my final options section looks like for chart.js version 2.8.0.

        options: {
        legend: {
            display: false //Have this or else legend will display as undefined
        },
        scales: {
            //This will show money for y-axis labels with format of $xx.xx
            yAxes: [{
              ticks: {
                beginAtZero: true,
                callback: function(value) {
                    return (new Intl.NumberFormat('en-US', {
                        style: 'currency',
                        currency: 'USD',
                    })).format(value);
                }
              }
            }]
        },
        //This will show money in tooltip with format of $xx.xx
        tooltips: {
            callbacks: {
                label: function (tooltipItem) {
                    return (new Intl.NumberFormat('en-US', {
                        style: 'currency',
                        currency: 'USD',
                    })).format(tooltipItem.value);
                }
            }
        }
    }

I wanted to show money values for both the y-axis and the tooltip values that show up when you hover over them. This works to show $49.99 and values with zero cents (ex: $50.00)

Java Does Not Equal (!=) Not Working?

Please use !statusCheck.equals("success") instead of !=.

Here are more details.

Exception: Serialization of 'Closure' is not allowed

Direct Closure serialisation is not allowed by PHP. But you can use powefull class like PHP Super Closure : https://github.com/jeremeamia/super_closure

This class is really simple to use and is bundled into the laravel framework for the queue manager.

From the github documentation :

$helloWorld = new SerializableClosure(function ($name = 'World') use ($greeting) {
    echo "{$greeting}, {$name}!\n";
});

$serialized = serialize($helloWorld);

Inserting values into tables Oracle SQL

You can insert into a table from a SELECT.

INSERT INTO
  Employee (emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager)
SELECT
  001,
  'John Doe',
  '1 River Walk, Green Street',
  (SELECT id FROM state WHERE name = 'New York'),
  (SELECT id FROM positions WHERE name = 'Sales Executive'),
  (SELECT id FROM manager WHERE name = 'Barry Green')
FROM
  dual

Or, similarly...

INSERT INTO
  Employee (emp_id, emp_name, emp_address, emp_state, emp_position, emp_manager)
SELECT
  001,
  'John Doe',
  '1 River Walk, Green Street',
  state.id,
  positions.id,
  manager.id
FROM
  state
CROSS JOIN
  positions
CROSS JOIN
  manager
WHERE
      state.name     = 'New York'
  AND positions.name = 'Sales Executive'
  AND manager.name   = 'Barry Green'

Though this one does assume that all the look-ups exist. If, for example, there is no position name 'Sales Executive', nothing would get inserted with this version.

How to configure multi-module Maven + Sonar + JaCoCo to give merged coverage report?

You can call a ant task called merge on maven, to put all coverage files (*.exec) together in the same file.

If you are run unit tests use the phase prepare-package, if you run integration test so use post-integration-test.

This site has an example to how call jacoco ant task in maven project

You can use this merged file on sonar.

What is the iPhone 4 user-agent?

iOS 4.3.2's User Agent, which came out this week, is:

Mozilla/5.0 (iPhone; U; CPU iPhone OS 4_3_2 like Mac OS X; en-us) AppleWebKit/533.17.9 (KHTML, like Gecko) Version/5.0.2 Mobile/8H7 Safari/6533.18.5

Embed a PowerPoint presentation into HTML

I spent a while looking into this and pretty much all of the freeware and shareware on the web sucked. This included software to directly convert the .ppt file to Flash or some sort of video format and also software to record your desktop screen. Software was clunky, and the quality was poor.

The solution we eventually came up with is a little bit manual, but it gave by far the best quality results:

  1. Export the .ppt file into some sort of image format (.bmp, .jpeg, .png, .tif) - it writes out one file per slide
  2. Import all the slide image files into Google Picasa and use them to create a video. You can add in some nice simple transitions (it hasn't got some of the horrific .ppt one's, but who cares) and it dumps out a WMV file of your specified resolution.

Saving out as .wmv isn't perfect, but I'm sure it's probably quite straightforward to convert that to some other format or Flash. We were looking to get them up on YouTube and this did the trick.

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

I also encountered this question, I solved it through adding two conditions one is:

resultCode != null

the other is:

resultCode != RESULT_CANCELED

How to find the serial port number on Mac OS X?

mac os x don't use com numbers. you have to use something like 'ser:devicename' , 9600

Reload parent window from child window

window.parent.opener.location.reload();

worked for me.

push_back vs emplace_back

One more example for lists:

// constructs the elements in place.                                                
emplace_back("element");

// creates a new object and then copies (or moves) that object.
push_back(ExplicitDataType{"element"});

How to make a .NET Windows Service start right after the installation?

The easiest solution is found here install-windows-service-without-installutil-exe by @Hoàng Long

@echo OFF
echo Stopping old service version...
net stop "[YOUR SERVICE NAME]"
echo Uninstalling old service version...
sc delete "[YOUR SERVICE NAME]"

echo Installing service...
rem DO NOT remove the space after "binpath="!
sc create "[YOUR SERVICE NAME]" binpath= "[PATH_TO_YOUR_SERVICE_EXE]" start= auto
echo Starting server complete
pause

check if file exists in php

  1. The function expects a string.

  2. file_exists() does not work properly with HTTP URLs.

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

First, JavaScript's switch is no faster than if/else (and sometimes much slower).

Second, the only way to use switch with multiple variables is to combine them into one primitive (string, number, etc) value:

var stateA = "foo";
var stateB = "bar";
switch (stateA + "-" + stateB) {
    case "foo-bar": ...
    ...
}

But, personally, I would rather see a set of if/else statements.

Edit: When all the values are integers, it appears that switch can out-perform if/else in Chrome. See the comments.

matplotlib: how to change data points color based on some variable

This is what matplotlib.pyplot.scatter is for.

As a quick example:

import matplotlib.pyplot as plt
import numpy as np

# Generate data...
t = np.linspace(0, 2 * np.pi, 20)
x = np.sin(t)
y = np.cos(t)

plt.scatter(t,x,c=y)
plt.show()

enter image description here

Adding List<t>.add() another list

List<T>.Add adds a single element. Instead, use List<T>.AddRange to add multiple values.

Additionally, List<T>.AddRange takes an IEnumerable<T>, so you don't need to convert tripDetails into a List<TripDetails>, you can pass it directly, e.g.:

tripDetailsCollection.AddRange(tripDetails);

How to remove "disabled" attribute using jQuery?

for removing the disabled properties

 $('#inputDisabled').removeAttr('Disabled');

for adding the disabled properties

 $('#inputDisabled').attr('disabled', 'disabled' );

Why am I getting a NoClassDefFoundError in Java?

This is the best solution I found so far.

Suppose we have a package called org.mypackage containing the classes:

  • HelloWorld (main class)
  • SupportClass
  • UtilClass

and the files defining this package are stored physically under the directory D:\myprogram (on Windows) or /home/user/myprogram (on Linux).

The file structure will look like this: enter image description here

When we invoke Java, we specify the name of the application to run: org.mypackage.HelloWorld. However we must also tell Java where to look for the files and directories defining our package. So to launch the program, we have to use the following command: enter image description here

TypeError: unhashable type: 'dict'

You're trying to use a dict as a key to another dict or in a set. That does not work because the keys have to be hashable. As a general rule, only immutable objects (strings, integers, floats, frozensets, tuples of immutables) are hashable (though exceptions are possible). So this does not work:

>>> dict_key = {"a": "b"}
>>> some_dict[dict_key] = True
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'

To use a dict as a key you need to turn it into something that may be hashed first. If the dict you wish to use as key consists of only immutable values, you can create a hashable representation of it like this:

>>> key = frozenset(dict_key.items())

Now you may use key as a key in a dict or set:

>>> some_dict[key] = True
>>> some_dict
{frozenset([('a', 'b')]): True}

Of course you need to repeat the exercise whenever you want to look up something using a dict:

>>> some_dict[dict_key]                     # Doesn't work
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: unhashable type: 'dict'
>>> some_dict[frozenset(dict_key.items())]  # Works
True

If the dict you wish to use as key has values that are themselves dicts and/or lists, you need to recursively "freeze" the prospective key. Here's a starting point:

def freeze(d):
    if isinstance(d, dict):
        return frozenset((key, freeze(value)) for key, value in d.items())
    elif isinstance(d, list):
        return tuple(freeze(value) for value in d)
    return d

Convert int to string?

None of the answers mentioned that the ToString() method can be applied to integer expressions

Debug.Assert((1000*1000).ToString()=="1000000");

even to integer literals

Debug.Assert(256.ToString("X")=="100");

Although integer literals like this are often considered to be bad coding style (magic numbers) there may be cases where this feature is useful...

DLL load failed error when importing cv2

this happens because the compiler or the interpreter is finding more than one package of the file, delete all the number of same package you have and then keep only one and then try to install. It serves

Bootstrap 4 datapicker.js not included

You can use this and then you can add just a class form from bootstrap. (does not matter which version)

<div class="form-group">
 <label >Begin voorverkoop periode</label>
 <input type="date" name="bday" max="3000-12-31" 
        min="1000-01-01" class="form-control">
</div>
<div class="form-group">
 <label >Einde voorverkoop periode</label>
 <input type="date" name="bday" min="1000-01-01"
        max="3000-12-31" class="form-control">
</div>

How to test for $null array in PowerShell

if($foo -eq $null) { "yes" } else { "no" }

help about_comparison_operators 

displays help and includes this text:

All comparison operators except the containment operators (-contains, -notcontains) and type operators (-is, -isnot) return a Boolean value when the input to the operator (the value on the left side of the operator) is a single value (a scalar). When the input is a collection of values, the containment operators and the type operators return any matching values. If there are no matches in a collection, these operators do not return anything. The containment operators and type operators always return a Boolean value.

How to create a inner border for a box in html?

Please have a look

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
    <html xmlns="http://www.w3.org/1999/xhtml">
    <head>
    <meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
    <title>Untitled Document</title>
    <style>
    .box{ width:500px; height:200px; background:#000; border:2px solid #ccc;}
        .inner-border {
            border: 20px solid black;
            box-shadow: inset 0px 0px 0px 10px red;
            box-sizing: border-box; /* Include padding and border in element's width and height */
        }
        /* CSS3 solution only for rectangular shape */
        .inner-outline {
            outline: 10px solid red;
            outline-offset: -30px;
        }
    </style>
    </head>

    <body>
    <div class="box inner-border inner-outline"></div>
    </body>
    </html>

How to test web service using command line curl

In addition to existing answers it is often desired to format the REST output (typically JSON and XML lacks indentation). Try this:

$ curl https://api.twitter.com/1/help/configuration.xml  | xmllint --format -
$ curl https://api.twitter.com/1/help/configuration.json | python -mjson.tool

Tested on Ubuntu 11.0.4/11.10.

Another issue is the desired content type. Twitter uses .xml/.json extension, but more idiomatic REST would require Accept header:

$ curl -H "Accept: application/json"

Simulator or Emulator? What is the difference?

Simulator is something more broader than Emulator and it seems like the duality of this terms is overthought in the posts above.

Emulator

People decided to use a new word emulation in the "computer world" when they started replacing some hardware parts of the existing system in straightforward manner - imitating their behaviour and relying on the computational nature to be sure to not break something and leave everything in the equivalent state. So we have emulated the piece of this! (and the whole still works as before)

Emulator usually used in narrow sense in digital area as replacement and virtualization - presenting in digital form as a piece of software - of something known and existed before (virtual chips, circuit boards, electronic devices). So when the world became more digital and brought the emulator word to the masses, the masses added uncertainty to it (or additional reasons).

Simulator

First of all, I saw many comments about emulators do or replace something real but simulators not.

BUT flight simulator is used for a real thing - it trains pilots, gives them skill up and knowledge and it replaces expensive real planes and saves much of money. And we cannot just say a plane-emulator because we have inner feeling that this is much more than that, so we call it simulator :) Plane simulator could contain emulated radar or transponder that is true.

Contra-statements that simulators are used for analysis and study (and emulators for something real), but that analysis and study not less a real thing than emulated GSM boards (even more in the informational age we live in). Analysis adds a value to the business, cuts costs or points out to profits not less than the replaced (emulated) hardware.

Simulator is similar to modelling of something that we can't obtain for some reason (cost, technology, physical impossibility). It is usually simulated for something new or intangible or complex or not properly known to us like market, weather, combustion, user. So here comes the flight, black hole, stock exchange, simulations.

So finally:

  1. Simulator is broader than Emulator
  2. Simulator tends to imitate/model more global processes/things in general with ability to narrow the imitation down (e.g. capacitor simulator with presets representing some known models)
  3. Emulator tends to imitate certain hardware devices with certain specification, known characteristics and properties (e.g. SNES emulator, Intel 8087 or Roland TB-303)

As for words origin

All came from Latin and mean:

  • emulate is "to be equal" (looks like more aggressive and straightforward - rivalry)
  • simulate is "to be similar" (looks like more sly and tricky - imitation)

Applications are expected to have a root view controller at the end of application launch

Validate your STORYBOARD file... If you are using IB to 'wire' code to your UI.. and just happen to delete the UI element ... and then realize, oh you need to delete the reference in the code (in my case a UIButton called AbortButton)... then moments later the app won't launch...

The issue is in the 'storyboard' file. Open it in an xml editor and look for orphaned 'relationships', of connectors which point places where they should not...

eg:

<relationships> <relationship kind="outlet" name="AbortButton" candidateClass="UIButton"/>

did NOT exist in my code anymore... (yet i still had a 'connector' linked up in the storyboard file)..

Also i had (somehow and invalid connector from a UIImageView or a ToolBar to my main UIViewController.view object)... don't think it liked that either...

bottom line - one doesn't have to manually 'code the controller' back into existence... the STORYBOARD file is whacked. I fixed mine, and bingo worked perfect again..

and BTW, as a text coder.. i am growing very fond of IB... kicks butt over MS Visual Studio's IDE...

How to express a One-To-Many relationship in Django

While rolling stone's answer is good, straightforward and functional, I think there are two things it does not solve.

  1. If OP wanted to enforce a phone number cannot belong to both a Dude and a Business
  2. The inescapable feeling of sadness as a result of defining the relationship on the PhoneNumber model and not on the Dude/Business models. When extra terrestrials come to Earth, and we want to add an Alien model, we need to modify the PhoneNumber (assuming the ETs have phone numbers) instead of simply adding a "phone_numbers" field to the Alien model.

Introduce the content types framework, which exposes some objects that allow us to create a "generic foreign key" on the PhoneNumber model. Then, we can define the reverse relationship on Dude and Business

from django.contrib.contenttypes.fields import GenericForeignKey, GenericRelation
from django.contrib.contenttypes.models import ContentType
from django.db import models

class PhoneNumber(models.Model):
    number = models.CharField()

    content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE)
    object_id = models.PositiveIntegerField()
    owner = GenericForeignKey()

class Dude(models.Model):
    numbers = GenericRelation(PhoneNumber)

class Business(models.Model):
    numbers = GenericRelation(PhoneNumber)

See the docs for details, and perhaps check out this article for a quick tutorial.

Also, here is an article that argues against the use of Generic FKs.

What does enumerate() mean?

I am assuming that you know how to iterate over elements in some list:

for el in my_list:
    # do something

Now sometimes not only you need to iterate over the elements, but also you need the index for each iteration. One way to do it is:

i = 0
for el in my_list:
    # do somethings, and use value of "i" somehow
    i += 1

However, a nicer way is to user the function "enumerate". What enumerate does is that it receives a list, and it returns a list-like object (an iterable that you can iterate over) but each element of this new list itself contains 2 elements: the index and the value from that original input list: So if you have

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

Then the command enumerate(arr) returns something like:

[(0,'a'), (1,'b'), (2,'c')]

Now If you iterate over a list (or an iterable) where each element itself has 2 sub-elements, you can capture both of those sub-elements in the for loop like below:

for index, value in enumerate(arr):
    print(index,value)

which would print out the sub-elements of the output of enumerate.

And in general you can basically "unpack" multiple items from list into multiple variables like below:

idx,value = (2,'c')
print(idx)
print(value)

which would print

2
c

This is the kind of assignment happening in each iteration of that loop with enumerate(arr) as iterable.

UIImage: Resize, then Crop

This question seems to have been put to rest, but in my quest for a solution that I could more easily understand (and written in Swift), I arrived at this (also posted to: How to crop the UIImage?)


I wanted to be able to crop from a region based on an aspect ratio, and scale to a size based on a outer bounding extent. Here is my variation:

import AVFoundation
import ImageIO

class Image {

    class func crop(image:UIImage, crop source:CGRect, aspect:CGSize, outputExtent:CGSize) -> UIImage {

        let sourceRect = AVMakeRectWithAspectRatioInsideRect(aspect, source)
        let targetRect = AVMakeRectWithAspectRatioInsideRect(aspect, CGRect(origin: CGPointZero, size: outputExtent))

        let opaque = true, deviceScale:CGFloat = 0.0 // use scale of device's main screen
        UIGraphicsBeginImageContextWithOptions(targetRect.size, opaque, deviceScale)

        let scale = max(
            targetRect.size.width / sourceRect.size.width,
            targetRect.size.height / sourceRect.size.height)

        let drawRect = CGRect(origin: -sourceRect.origin * scale, size: image.size * scale)
        image.drawInRect(drawRect)

        let scaledImage = UIGraphicsGetImageFromCurrentImageContext()
        UIGraphicsEndImageContext()

        return scaledImage
    }
}

There are a couple things that I found confusing, the separate concerns of cropping and resizing. Cropping is handled with the origin of the rect that you pass to drawInRect, and scaling is handled by the size portion. In my case, I needed to relate the size of the cropping rect on the source, to my output rect of the same aspect ratio. The scale factor is then output / input, and this needs to be applied to the drawRect (passed to drawInRect).

One caveat is that this approach effectively assumes that the image you are drawing is larger than the image context. I have not tested this, but I think you can use this code to handle cropping / zooming, but explicitly defining the scale parameter to be the aforementioned scale parameter. By default, UIKit applies a multiplier based on the screen resolution.

Finally, it should be noted that this UIKit approach is higher level than CoreGraphics / Quartz and Core Image approaches, and seems to handle image orientation issues. It is also worth mentioning that it is pretty fast, second to ImageIO, according to this post here: http://nshipster.com/image-resizing/

jQuery click / toggle between two functions

Micro jQuery Plugin

If you want your own chainable clickToggle jQuery Method you can do it like:

_x000D_
_x000D_
jQuery.fn.clickToggle = function(a, b) {_x000D_
  return this.on("click", function(ev) { [b, a][this.$_io ^= 1].call(this, ev) })_x000D_
};_x000D_
_x000D_
// TEST:_x000D_
$('button').clickToggle(function(ev) {_x000D_
  $(this).text("B"); _x000D_
}, function(ev) {_x000D_
  $(this).text("A");_x000D_
});
_x000D_
<button>A</button>_x000D_
<button>A</button>_x000D_
<button>A</button>_x000D_
_x000D_
<script src="//code.jquery.com/jquery-3.3.1.min.js"></script>
_x000D_
_x000D_
_x000D_


Simple Functions Toggler

LIVE DEMO

function a(){ console.log('a'); }
function b(){ console.log('b'); }

$("selector").click(function() { 
  return (this.tog = !this.tog) ? a() : b();
});

If you want it even shorter (why would one, right?!) you can use the Bitwise XOR *Docs operator like:
DEMO

  return (this.tog^=1) ? a() : b();

That's all.
The trick is to set to the this Object a boolean property tog, and toggle it using negation (tog = !tog)
and put the needed function calls in a Conditional Operator ?:




In OP's example (even with multiple elements) could look like:

function a(el){ $(el).animate({width: 260}, 1500); }
function b(el){ $(el).animate({width: 30}, 1500);  }

$("selector").click(function() {
  var el = this;
  return (el.t = !el.t) ? a(el) : b(el);
}); 

ALSO: You can also store-toggle like:
DEMO:

$("selector").click(function() {
  $(this).animate({width: (this.tog ^= 1) ? 260 : 30 });
}); 

but it was not the OP's exact request for he's looking for a way to have two separate operations / functions


Using Array.prototype.reverse:

Note: this will not store the current Toggle state but just inverse our functions positions in Array (It has it's uses...)

You simply store your a,b functions inside an array, onclick you simply reverse the array order and execute the array[1] function:

LIVE DEMO

function a(){ console.log("a"); }
function b(){ console.log("b"); }
var ab = [a,b];

$("selector").click(function(){
  ab.reverse()[1](); // Reverse and Execute! // >> "a","b","a","b"...
});

SOME MASHUP!

jQuery DEMO
JavaScript DEMO

Create a nice function toggleAB() that will contain your two functions, put them in Array, and at the end of the array you simply execute the function [0 // 1] respectively depending on the tog property that's passed to the function from the this reference:

function toggleAB(){
  var el = this; // `this` is the "button" Element Obj reference`
  return [
    function() { console.log("b"); },
    function() { console.log("a"); }
  ][el.tog^=1]();
}

$("selector").click( toggleAB );

Android Overriding onBackPressed()

Yes. Only override it in that one Activity with

@Override
public void onBackPressed()
{
     // code here to show dialog
     super.onBackPressed();  // optional depending on your needs
}

don't put this code in any other Activity

In Python how should I test if a variable is None, True or False

I would like to stress that, even if there are situations where if expr : isn't sufficient because one wants to make sure expr is True and not just different from 0/None/whatever, is is to be prefered from == for the same reason S.Lott mentionned for avoiding == None.

It is indeed slightly more efficient and, cherry on the cake, more human readable.

In [1]: %timeit (1 == 1) == True
38.1 ns ± 0.116 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

In [2]: %timeit (1 == 1) is True
33.7 ns ± 0.141 ns per loop (mean ± std. dev. of 7 runs, 10000000 loops each)

Get jQuery version from inspecting the jQuery object

FYI, for the cases where your page is loading with other javascript libraries like mootools that are conflicting with the $ symbol, you can use jQuery instead.

For instance, jQuery.fn.jquery or jQuery().jquery would work just fine:

screen shot for checking jQuery version

Jquery: Checking to see if div contains text, then action

Ayman is right but, you can use it like that as well :

if( $("#field > div.field-item").text().indexOf('someText') >= 0) {
        $("#somediv").addClass("thisClass");
    }

Where should I put the log4j.properties file?

Your standard project setup will have a project structure something like:

src/main/java
src/main/resources

You place log4j.properties inside the resources folder, you can create the resources folder if one does not exist

Javascript get the text value of a column from a particular row of an html table

in case if your table has tbody

let tbl = document.getElementById("tbl").getElementsByTagName('tbody')[0];
console.log(tbl.rows[0].cells[0].innerHTML)

How to disable keypad popup when on edittext?

In a Android app I was building, I had three EditTexts in a LinearLayout arranged horizontally. I had to prevent the soft keyboard from appearing when the fragment loaded. In addition to setting focusable and focusableInTouchMode to true on the LinearLayout, I had to set descendantFocusability to blocksDescendants. In onCreate, I called requestFocus on the LinearLayout. This prevented the keyboard from appearing when the fragment is created.

Layout -

    <LinearLayout
       android:id="@+id/text_selector_container"
       android:layout_width="match_parent"
       android:layout_height="wrap_content"
       android:weightSum="3"
       android:orientation="horizontal"
       android:focusable="true"
       android:focusableInTouchMode="true"
       android:descendantFocusability="blocksDescendants"
       android:background="@color/black">

       <!-- EditText widgets -->

    </LinearLayout>

In onCreate - mTextSelectorContainer.requestFocus();

java.lang.OutOfMemoryError: GC overhead limit exceeded

For this use below code in your app gradle file under android closure.

dexOptions { javaMaxHeapSize "4g" }

How to change column width in DataGridView?

In my Visual Studio 2019 it worked only after I set the AutoSizeColumnsMode property to None.

How to clear the canvas for redrawing

function clear(context, color)
{
    var tmp = context.fillStyle;
    context.fillStyle = color;
    context.fillRect(0, 0, context.canvas.width, context.canvas.height);
    context.fillStyle = tmp;
}

set gvim font in .vimrc file

Ubuntu 14.04 LTS

:/$ cd etc/vim/
:/etc/vim$ sudo gvim gvimrc

After if - endif block, type

set guifont=Neep\ 10

save the file (:wq!). Here "Neep" (your choice) is the font style and "10" is respect size of the font. Then build the font - cache again.

:/etc/vim$ fc-cache -f -v

Your desired font will set to gvim.

What is the difference between single and double quotes in SQL?

The difference lies in their usage. The single quotes are mostly used to refer a string in WHERE, HAVING and also in some built-in SQL functions like CONCAT, STRPOS, POSITION etc.

When you want to use an alias that has space in between then you can use double quotes to refer to that alias.

For example

(select account_id,count(*) "count of" from orders group by 1)sub 

Here is a subquery from an orders table having account_id as Foreign key that I am aggregating to know how many orders each account placed. Here I have given one column any random name as "count of" for sake of purpose.

Now let's write an outer query to display the rows where "count of" is greater than 20.

select "count of" from 
(select account_id,count(*) "count of" from orders group by 1)sub where "count of" >20;

You can apply the same case to Common Table expressions also.

Is it possible to send an array with the Postman Chrome extension?

in headers set

content-type : application/x-www-form-urlencoded

In body select option

x-www-form-urlencoded

and insert data as json array

user_ids : ["1234", "5678"]

Center Contents of Bootstrap row container

With Bootstrap 4, there is a css class specifically for this. The below will center row content:

<div class="row justify-content-center">
  ...inner divs and content...
</div>

See: https://v4-alpha.getbootstrap.com/layout/grid/#horizontal-alignment, for more information.

saving a file (from stream) to disk using c#

For file Type you can rely on FileExtentions and for writing it to disk you can use BinaryWriter. or a FileStream.

Example (Assuming you already have a stream):

FileStream fileStream = File.Create(fileFullPath, (int)stream.Length);
// Initialize the bytes array with the stream length and then fill it with data
byte[] bytesInStream = new byte[stream.Length];
stream.Read(bytesInStream, 0, bytesInStream.Length);    
// Use write method to write to the file specified above
fileStream.Write(bytesInStream, 0, bytesInStream.Length);
//Close the filestream
fileStream.Close();