Programs & Examples On #Logical operators

Simple logical operators in Bash

What you've written actually almost works (it would work if all the variables were numbers), but it's not an idiomatic way at all.

  • (…) parentheses indicate a subshell. What's inside them isn't an expression like in many other languages. It's a list of commands (just like outside parentheses). These commands are executed in a separate subprocess, so any redirection, assignment, etc. performed inside the parentheses has no effect outside the parentheses.
    • With a leading dollar sign, $(…) is a command substitution: there is a command inside the parentheses, and the output from the command is used as part of the command line (after extra expansions unless the substitution is between double quotes, but that's another story).
  • { … } braces are like parentheses in that they group commands, but they only influence parsing, not grouping. The program x=2; { x=4; }; echo $x prints 4, whereas x=2; (x=4); echo $x prints 2. (Also braces require spaces around them and a semicolon before closing, whereas parentheses don't. That's just a syntax quirk.)
    • With a leading dollar sign, ${VAR} is a parameter expansion, expanding to the value of a variable, with possible extra transformations.
  • ((…)) double parentheses surround an arithmetic instruction, that is, a computation on integers, with a syntax resembling other programming languages. This syntax is mostly used for assignments and in conditionals.
    • The same syntax is used in arithmetic expressions $((…)), which expand to the integer value of the expression.
  • [[ … ]] double brackets surround conditional expressions. Conditional expressions are mostly built on operators such as -n $variable to test if a variable is empty and -e $file to test if a file exists. There are also string equality operators: "$string1" == "$string2" (beware that the right-hand side is a pattern, e.g. [[ $foo == a* ]] tests if $foo starts with a while [[ $foo == "a*" ]] tests if $foo is exactly a*), and the familiar !, && and || operators for negation, conjunction and disjunction as well as parentheses for grouping. Note that you need a space around each operator (e.g. [[ "$x" == "$y" ]], not [[ "$x"=="$y" ]]), and a space or a character like ; both inside and outside the brackets (e.g. [[ -n $foo ]], not [[-n $foo]]).
  • [ … ] single brackets are an alternate form of conditional expressions with more quirks (but older and more portable). Don't write any for now; start worrying about them when you find scripts that contain them.

This is the idiomatic way to write your test in bash:

if [[ $varA == 1 && ($varB == "t1" || $varC == "t2") ]]; then

If you need portability to other shells, this would be the way (note the additional quoting and the separate sets of brackets around each individual test, and the use of the traditional = operator rather than the ksh/bash/zsh == variant):

if [ "$varA" = 1 ] && { [ "$varB" = "t1" ] || [ "$varC" = "t2" ]; }; then

Logical Operators, || or OR?

The difference between respectively || and OR and && and AND is operator precedence :

$bool = FALSE || TRUE;

  • interpreted as ($bool = (FALSE || TRUE))
  • value of $bool is TRUE

$bool = FALSE OR TRUE;

  • interpreted as (($bool = FALSE) OR TRUE)
  • value of $bool is FALSE

$bool = TRUE && FALSE;

  • interpreted as ($bool = (TRUE && FALSE))
  • value of $bool is FALSE

$bool = TRUE AND FALSE;

  • interpreted as (($bool = TRUE) AND FALSE)
  • value of $bool is TRUE

How do you get the logical xor of two variables in Python?

Exclusive Or is defined as follows

def xor( a, b ):
    return (a or b) and not (a and b)

SQL Logic Operator Precedence: And and Or

Query to show a 3-variable boolean expression truth table :

;WITH cteData AS
(SELECT 0 AS A, 0 AS B, 0 AS C
UNION ALL SELECT 0,0,1
UNION ALL SELECT 0,1,0
UNION ALL SELECT 0,1,1
UNION ALL SELECT 1,0,0
UNION ALL SELECT 1,0,1
UNION ALL SELECT 1,1,0
UNION ALL SELECT 1,1,1
)
SELECT cteData.*,
    CASE WHEN

(A=1) OR (B=1) AND (C=1)

    THEN 'True' ELSE 'False' END AS Result
FROM cteData

Results for (A=1) OR (B=1) AND (C=1) :

A   B   C   Result
0   0   0   False
0   0   1   False
0   1   0   False
0   1   1   True
1   0   0   True
1   0   1   True
1   1   0   True
1   1   1   True

Results for (A=1) OR ( (B=1) AND (C=1) ) are the same.

Results for ( (A=1) OR (B=1) ) AND (C=1) :

A   B   C   Result
0   0   0   False
0   0   1   False
0   1   0   False
0   1   1   True
1   0   0   False
1   0   1   True
1   1   0   False
1   1   1   True

Javascript logical "!==" operator?

!==

This is the strict not equal operator and only returns a value of true if both the operands are not equal and/or not of the same type. The following examples return a Boolean true:

a !== b
a !== "2"
4 !== '4' 

What's the difference between & and && in MATLAB?

The single ampersand & is the logical AND operator. The double ampersand && is again a logical AND operator that employs short-circuiting behaviour. Short-circuiting just means the second operand (right hand side) is evaluated only when the result is not fully determined by the first operand (left hand side)

A & B (A and B are evaluated)

A && B (B is only evaluated if A is true)

Boolean operators && and ||

The shorter ones are vectorized, meaning they can return a vector, like this:

((-2:2) >= 0) & ((-2:2) <= 0)
# [1] FALSE FALSE  TRUE FALSE FALSE

The longer form evaluates left to right examining only the first element of each vector, so the above gives

((-2:2) >= 0) && ((-2:2) <= 0)
# [1] FALSE

As the help page says, this makes the longer form "appropriate for programming control-flow and [is] typically preferred in if clauses."

So you want to use the long forms only when you are certain the vectors are length one.

You should be absolutely certain your vectors are only length 1, such as in cases where they are functions that return only length 1 booleans. You want to use the short forms if the vectors are length possibly >1. So if you're not absolutely sure, you should either check first, or use the short form and then use all and any to reduce it to length one for use in control flow statements, like if.

The functions all and any are often used on the result of a vectorized comparison to see if all or any of the comparisons are true, respectively. The results from these functions are sure to be length 1 so they are appropriate for use in if clauses, while the results from the vectorized comparison are not. (Though those results would be appropriate for use in ifelse.

One final difference: the && and || only evaluate as many terms as they need to (which seems to be what is meant by short-circuiting). For example, here's a comparison using an undefined value a; if it didn't short-circuit, as & and | don't, it would give an error.

a
# Error: object 'a' not found
TRUE || a
# [1] TRUE
FALSE && a
# [1] FALSE
TRUE | a
# Error: object 'a' not found
FALSE & a
# Error: object 'a' not found

Finally, see section 8.2.17 in The R Inferno, titled "and and andand".

Differences in boolean operators: & vs && and | vs ||

& and | provide the same outcome as the && and || operators. The difference is that they always evaluate both sides of the expression where as && and || stop evaluating if the first condition is enough to determine the outcome.

Java logical operator short-circuiting

Short circuiting means the second operator will not be checked if the first operator decides the final outcome.

E.g. Expression is: True || False

In case of ||, all we need is one of the side to be True. So if the left hand side is true, there is no point in checking the right hand side, and hence that will not be checked at all.

Similarly, False && True

In case of &&, we need both sides to be True. So if the left hand side is False, there is no point in checking the right hand side, the answer has to be False. And hence that will not be checked at all.

Logical operators ("and", "or") in DOS batch

OR is slightly tricky, but not overly so. Here is an example

set var1=%~1
set var2=%~2
::
set or_=
if "%var1%"=="Stack" set or_=true
if "%var2%"=="Overflow" set or_=true
if defined or_ echo Stack OR Overflow

Python's equivalent of && (logical-and) in an if-statement

Python uses and and or conditionals.

i.e.

if foo == 'abc' and bar == 'bac' or zoo == '123':
  # do something

Logical XOR operator in C++?

#if defined(__OBJC__)
    #define __bool BOOL
    #include <stdbool.h>
    #define __bool bool
#endif

static inline __bool xor(__bool a, __bool b)
{
    return (!a && b) || (a && !b);
}

It works as defined. The conditionals are to detect if you are using Objective-C, which is asking for BOOL instead of bool (the length is different!)

Is it good practice to use the xor operator for boolean checks?

str.contains("!=") ^ str.startsWith("not(")

looks better for me than

str.contains("!=") != str.startsWith("not(")

Route.get() requires callback functions but got a "object Undefined"

Make sure that

yourFile.js:

exports.yourFunction = function(a,b){
  //your code
}

matches

app.js

var express = require('express');
var app = express();
var yourModule = require('yourFile');
app.get('/your_path', yourModule.yourFunction);

For me, I ran into this issue when copy pasting a module into another module for testing, needed to change the exports. xxxx at the top of the file

Animate visibility modes, GONE and VISIBLE

You probably want to use an ExpandableListView, a special ListView that allows you to open and close groups.

How do you force a makefile to rebuild a target

This simple technique will allow the makefile to function normally when forcing is not desired. Create a new target called force at the end of your makefile. The force target will touch a file that your default target depends on. In the example below, I have added touch myprogram.cpp. I also added a recursive call to make. This will cause the default target to get made every time you type make force.

yourProgram: yourProgram.cpp
       g++ -o yourProgram yourProgram.cpp 

force:
       touch yourProgram.cpp
       make

Endless loop in C/C++

It is very subjective. I write this:

while(true) {} //in C++

Because its intent is very much clear and it is also readable: you look at it and you know infinite loop is intended.

One might say for(;;) is also clear. But I would argue that because of its convoluted syntax, this option requires extra knowledge to reach the conclusion that it is an infinite loop, hence it is relatively less clear. I would even say there are more number of programmers who don't know what for(;;) does (even if they know usual for loop), but almost all programmers who knows while loop would immediately figure out what while(true) does.

To me, writing for(;;) to mean infinite loop, is like writing while() to mean infinite loop — while the former works, the latter does NOT. In the former case, empty condition turns out to be true implicitly, but in the latter case, it is an error! I personally didn't like it.

Now while(1) is also there in the competition. I would ask: why while(1)? Why not while(2), while(3) or while(0.1)? Well, whatever you write, you actually mean while(true) — if so, then why not write it instead?

In C (if I ever write), I would probably write this:

while(1) {} //in C

While while(2), while(3) and while(0.1) would equally make sense. But just to be conformant with other C programmers, I would write while(1), because lots of C programmers write this and I find no reason to deviate from the norm.

JS. How to replace html element with another element/text, represented in string?

idTABLE.parentElement.innerHTML =  '<span>123 element</span> 456';

while this works, it's still recommended to use getElementById: Do DOM tree elements with ids become global variables?

replaceChild would work fine if you want to go to the trouble of building up your replacement, element by element, using document.createElement and appendChild, but I don't see the point.

WPF: simple TextBox data binding

Your Window is not implementing the necessary data binding notifications that the grid requires to use it as a data source, namely the INotifyPropertyChanged interface.

Your "Name2" string needs also to be a property and not a public variable, as data binding is for use with properties.

Implementing the necessary interfaces for using an object as a data source can be found here.

Entity Framework: There is already an open DataReader associated with this Command

In my case the issue had nothing to do with MARS connection string but with json serialization. After upgrading my project from NetCore2 to 3 i got this error.

More information can be found here

CodeIgniter Disallowed Key Characters

I had the same problem thanks to french specials characters. Here is my class in case anybody needs it. It has to be saved here : /application/core/MY_Input.php

(also this extension will report witch character is not allowed in the future)

class MY_Input extends CI_Input {

function __construct() { parent::__construct(); } /** * Clean Keys * * This is a helper function. To prevent malicious users * from trying to exploit keys we make sure that keys are * only named with alpha-numeric text and a few other items. * * @access private * @param string * @return string */ function _clean_input_keys($str) { if ( ! preg_match("/^[a-z0-9:_\/-àâçéèêëîôùû]+$/i", $str)) { exit('Disallowed Key Characters : '.$str); } // Clean UTF-8 if supported if (UTF8_ENABLED === TRUE) { $str = $this->uni->clean_string($str); } return $str; }

}

Read The Friendly Manual about core classes extension : http://ellislab.com/codeigniter/user-guide/general/core_classes.html

Android: How do I prevent the soft keyboard from pushing my view up?

In my case I needed the keyboard to stay hidden and just after the click of the button my layout needs to be adjusted, so I just added this command in the manifest and it got super right.

android:windowSoftInputMode="stateHidden|adjustResize"

Rerouting stdin and stdout from C

freopen solves the easy part. Keeping old stdin around is not hard if you haven't read anything and if you're willing to use POSIX system calls like dup or dup2. If you're started to read from it, all bets are off.

Maybe you can tell us the context in which this problem occurs?

I'd encourage you to stick to situations where you're willing to abandon old stdin and stdout and can therefore use freopen.

PSEXEC, access denied errors

I had a case where AV was quarantining Psexec - had to disable On-access scanning

Python initializing a list of lists

The problem is that they're all the same exact list in memory. When you use the [x]*n syntax, what you get is a list of n many x objects, but they're all references to the same object. They're not distinct instances, rather, just n references to the same instance.

To make a list of 3 different lists, do this:

x = [[] for i in range(3)]

This gives you 3 separate instances of [], which is what you want

[[]]*n is similar to

l = []
x = []
for i in range(n):
    x.append(l)

While [[] for i in range(3)] is similar to:

x = []
for i in range(n):
    x.append([])   # appending a new list!

In [20]: x = [[]] * 4

In [21]: [id(i) for i in x]
Out[21]: [164363948, 164363948, 164363948, 164363948] # same id()'s for each list,i.e same object


In [22]: x=[[] for i in range(4)]

In [23]: [id(i) for i in x]
Out[23]: [164382060, 164364140, 164363628, 164381292] #different id(), i.e unique objects this time

Set default value of an integer column SQLite

Use the SQLite keyword default

db.execSQL("CREATE TABLE " + DATABASE_TABLE + " (" 
    + KEY_ROWID + " INTEGER PRIMARY KEY AUTOINCREMENT, "
    + KEY_NAME + " TEXT NOT NULL, "
    + KEY_WORKED + " INTEGER, "
    + KEY_NOTE + " INTEGER DEFAULT 0);");

This link is useful: http://www.sqlite.org/lang_createtable.html

Method List in Visual Studio Code

Take a look at Show Functions plugin. It can list functions, symbols, bookmarks by configurable regular expressions. Regular expressions are a real saver, expecially when you're not using a mainstream language and when CodeOutline doesn't do the job. It's ugly to see a split window with these functions (CodeOutline seems to be better integrated) but at least there's something to use

Error: Java: invalid target release: 11 - IntelliJ IDEA

If you are in Springboot please check the java version in the pom.xml file

<properties>
   <java.version>11</java.version>
</properties>

If this version doesn't match with your default version(Java) of the computer, that error can be happen.

Python List vs. Array - when to use?

My understanding is that arrays are stored more efficiently (i.e. as contiguous blocks of memory vs. pointers to Python objects), but I am not aware of any performance benefit. Additionally, with arrays you must store primitives of the same type, whereas lists can store anything.

laravel collection to array

Try collect function in array like:

$comments_collection = collect($post->comments()->get()->toArray());

this methods can help you

toArray() with collect()

SQLSTATE[HY000] [1045] Access denied for user 'username'@'localhost' using CakePHP

Check Following Things

  • Make Sure You Have MySQL Server Running
  • Check connection with default credentials i.e. username : 'root' & password : '' [Blank Password]
  • Try login phpmyadmin with same credentials
  • Try to put 127.0.0.1 instead localhost or your lan IP would do too.
  • Make sure you are running MySql on 3306 and if you have configured make sure to state it while making a connection

MongoDB Show all contents from all collections

Step 1: See all your databases:

show dbs

Step 2: Select the database

use your_database_name

Step 3: Show the collections

show collections

This will list all the collections in your selected database.

Step 4: See all the data

db.collection_name.find() 

or

db.collection_name.find().pretty()

json: cannot unmarshal object into Go value of type

Here's a fixed version of it: http://play.golang.org/p/w2ZcOzGHKR

The biggest fix that was needed is when Unmarshalling an array, that property needs to be an array/slice in the struct as well.

For example:

{ "things": ["a", "b", "c"] }

Would Unmarshal into a:

type Item struct {
    Things []string
}

And not into:

type Item struct {
    Things string
}

The other thing to watch out for when Unmarshaling is that the types line up exactly. It will fail when Unmarshalling a JSON string representation of a number into an int or float field -- "1" needs to Unmarshal into a string, not into an int like we saw with ShippingAdditionalCost int

How do you extract IP addresses from files using a regex in a linux shell?

All of the previous answers have one or more problems. The accepted answer allows ip numbers like 999.999.999.999. The currently second most upvoted answer requires prefixing with 0 such as 127.000.000.001 or 008.008.008.008 instead of 127.0.0.1 or 8.8.8.8. Apama has it almost right, but that expression requires that the ipnumber is the only thing on the line, no leading or trailing space allowed, nor can it select ip's from the middle of a line.

I think the correct regex can be found on http://www.regextester.com/22

So if you want to extract all ip-adresses from a file use:

grep -Eo "(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])" file.txt

If you don't want duplicates use:

grep -Eo "(([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])\.){3}([0-9]|[1-9][0-9]|1[0-9]{2}|2[0-4][0-9]|25[0-5])" file.txt | sort | uniq

Please comment if there still are problems in this regex. It easy to find many wrong regex for this problem, I hope this one has no real issues.

Python: find position of element in array

For your first question, find the position of some value in a list x using index(), like so:

x.index(value)

For your second question, to check for multiple same values you should split your list into chunks and use the same logic from above. They say divide and conquer. It works. Try this:

value = 1 
x = [1,2,3,4,5,6,2,1,4,5,6]

chunk_a = x[:int(len(x)/2)] # get the first half of x 
chunk_b = x[int(len(x)/2):] # get the rest half of x

print(chunk_a.index(value))
print(chunk_b.index(value))

Hope that helps!

'ls' in CMD on Windows is not recognized

Use the command dir to list all the directories and files in a directory; ls is a unix command.

Node.js: how to consume SOAP XML web service

For those who are new to SOAP and want a quick explanation and guide, I strongly recommend this awesome medium article.

You can also use node-soap package, with this simple tutorial.

How to define a List bean in Spring?

You just remove id out of beans inside <list> tag. Like this:

<property name="listStaff">
  <list>
    <bean class="com.test.entity.Staff">
        <constructor-arg name="name" value = "Jonh"/>
        <constructor-arg name="age" value = "30"/>
    </bean>
    <bean class="com.test.entity.Staff">
        <constructor-arg name="name" value = "Jam"/>
        <constructor-arg name="age" value = "21"/>
    </bean>
  </list>
</property>

How to replace all dots in a string using JavaScript

Here's another implementation of replaceAll. Hope it helps someone.

    String.prototype.replaceAll = function (stringToFind, stringToReplace) {
        if (stringToFind === stringToReplace) return this;
        var temp = this;
        var index = temp.indexOf(stringToFind);
        while (index != -1) {
            temp = temp.replace(stringToFind, stringToReplace);
            index = temp.indexOf(stringToFind);
        }
        return temp;
    };

Then you can use it:

var myText = "My Name is George";
var newText = myText.replaceAll("George", "Michael");

Splitting a Java String by the pipe symbol using split("|")

the split() method takes a regular expression as an argument

How to interactively (visually) resolve conflicts in SourceTree / git

When the Resolve Conflicts->Content Menu are disabled, one may be on the Pending files list. We need to select the Conflicted files option from the drop down (top)

hope it helps

How to use comparison and ' if not' in python?

In this particular case the clearest solution is the S.Lott answer

But in some complex logical conditions I would prefer use some boolean algebra to get a clear solution.

Using De Morgan's law ¬(A^B) = ¬Av¬B

not (u0 <= u and u < u0+step)
(not u0 <= u) or (not u < u0+step)
u0 > u or u >= u0+step

then

if u0 > u or u >= u0+step:
    pass

... in this case the «clear» solution is not more clear :P

How to implement class constructor in Visual Basic?

Suppose your class is called MyStudent. Here's how you define your class constructor:

Public Class MyStudent
    Public StudentId As Integer

    'Here's the class constructor:
    Public Sub New(newStudentId As Integer)
        StudentId = newStudentId
    End Sub
End Class

Here's how you call it:

Dim student As New MyStudent(studentId)

Of course, your class constructor can contain as many or as few arguments as you need--even none, in which case you leave the parentheses empty. You can also have several constructors for the same class, all with different combinations of arguments. These are known as different "signatures" for your class constructor.

React Router with optional path parameter

As with regular parameters, declaring an optional parameter is just a matter of the path property of a Route; any parameter that ends with a question mark will be treated as optional:

<Route path="to/page/:pathParam?" component={MyPage}/>

How to use youtube-dl from a python program?

It's not difficult and actually documented:

import youtube_dl

ydl = youtube_dl.YoutubeDL({'outtmpl': '%(id)s.%(ext)s'})

with ydl:
    result = ydl.extract_info(
        'http://www.youtube.com/watch?v=BaW_jenozKc',
        download=False # We just want to extract the info
    )

if 'entries' in result:
    # Can be a playlist or a list of videos
    video = result['entries'][0]
else:
    # Just a video
    video = result

print(video)
video_url = video['url']
print(video_url)

How to test abstract class in Java with JUnit?

You could do something like this

public abstract MyAbstractClass {

    @Autowire
    private MyMock myMock;        

    protected String sayHello() {
            return myMock.getHello() + ", " + getName();
    }

    public abstract String getName();
}

// this is your JUnit test
public class MyAbstractClassTest extends MyAbstractClass {

    @Mock
    private MyMock myMock;

    @InjectMocks
    private MyAbstractClass thiz = this;

    private String myName = null;

    @Override
    public String getName() {
        return myName;
    }

    @Test
    public void testSayHello() {
        myName = "Johnny"
        when(myMock.getHello()).thenReturn("Hello");
        String result = sayHello();
        assertEquals("Hello, Johnny", result);
    }
}

How to read a large file line by line?

I would strongly recommend not using the default file loading as it is horrendously slow. You should look into the numpy functions and the IOpro functions (e.g. numpy.loadtxt()).

http://docs.scipy.org/doc/numpy/user/basics.io.genfromtxt.html

https://store.continuum.io/cshop/iopro/

Then you can break your pairwise operation into chunks:

import numpy as np
import math

lines_total = n    
similarity = np.zeros(n,n)
lines_per_chunk = m
n_chunks = math.ceil(float(n)/m)
for i in xrange(n_chunks):
    for j in xrange(n_chunks):
        chunk_i = (function of your choice to read lines i*lines_per_chunk to (i+1)*lines_per_chunk)
        chunk_j = (function of your choice to read lines j*lines_per_chunk to (j+1)*lines_per_chunk)
        similarity[i*lines_per_chunk:(i+1)*lines_per_chunk,
                   j*lines_per_chunk:(j+1)*lines_per_chunk] = fast_operation(chunk_i, chunk_j) 

It's almost always much faster to load data in chunks and then do matrix operations on it than to do it element by element!!

Difference between Fact table and Dimension table?

From my point of view,

  • Dimension table : Master Data
  • Fact table : Transactional Data

Multiple file upload in php

$property_images = $_FILES['property_images']['name'];
    if(!empty($property_images))
    {
        for($up=0;$up<count($property_images);$up++)
        {
            move_uploaded_file($_FILES['property_images']['tmp_name'][$up],'../images/property_images/'.$_FILES['property_images']['name'][$up]);
        }
    }

Hex transparency in colors

I always keep coming here to check for int/hex alpha value. So, end up creating a simple method in my java utils class. This method will convert the percentage to hex value and append to the color code string value.

 public static String setColorAlpha(int percentage, String colorCode){
    double decValue = ((double)percentage / 100) * 255;
    String rawHexColor = colorCode.replace("#","");
    StringBuilder str = new StringBuilder(rawHexColor);

    if(Integer.toHexString((int)decValue).length() == 1)
        str.insert(0, "#0" + Integer.toHexString((int)decValue));
    else
        str.insert(0, "#" + Integer.toHexString((int)decValue));
    return str.toString();
}

So, Utils.setColorAlpha(30, "#000000") will give you #4c000000

How can I stage and commit all files, including newly added files, using a single command?

Committing in git can be a multiple step process or one step depending on the situation.

  1. This situation is where you have multiple file updated and wants to commit:

    You have to add all the modified files before you commit anything.

    git add -A
    

    or

    git add --all
    
  2. After that you can use commit all the added files

    git commit
    

    with this you have to add the message for this commit.

How to subtract a day from a date?

Genial arrow module exists

import arrow
utc = arrow.utcnow()
utc_yesterday = utc.shift(days=-1)
print(utc, '\n', utc_yesterday)

output:

2017-04-06T11:17:34.431397+00:00 
 2017-04-05T11:17:34.431397+00:00

When are you supposed to use escape instead of encodeURI / encodeURIComponent?

Inspired by Johann's table, I've decided to extend the table. I wanted to see which ASCII characters get encoded.

screenshot of console.table

_x000D_
_x000D_
var ascii = " !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~";_x000D_
_x000D_
var encoded = [];_x000D_
_x000D_
ascii.split("").forEach(function (char) {_x000D_
    var obj = { char };_x000D_
    if (char != encodeURI(char))_x000D_
        obj.encodeURI = encodeURI(char);_x000D_
    if (char != encodeURIComponent(char))_x000D_
        obj.encodeURIComponent = encodeURIComponent(char);_x000D_
    if (obj.encodeURI || obj.encodeURIComponent)_x000D_
        encoded.push(obj);_x000D_
});_x000D_
_x000D_
console.table(encoded);
_x000D_
_x000D_
_x000D_

Table shows only the encoded characters. Empty cells mean that the original and the encoded characters are the same.


Just to be extra, I'm adding another table for urlencode() vs rawurlencode(). The only difference seems to be the encoding of space character.

screenshot of console.table

<script>
<?php
$ascii = str_split(" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~", 1);
$encoded = [];
foreach ($ascii as $char) {
    $obj = ["char" => $char];
    if ($char != urlencode($char))
        $obj["urlencode"] = urlencode($char);
    if ($char != rawurlencode($char))
        $obj["rawurlencode"] = rawurlencode($char);
    if (isset($obj["rawurlencode"]) || isset($obj["rawurlencode"]))
        $encoded[] = $obj;
}
echo "var encoded = " . json_encode($encoded) . ";";
?>
console.table(encoded);
</script>

How to resize a VirtualBox vmdk file

Use these simple steps to resize the vmdk

  1. Go to File -> Virtual Media Player

enter image description here

  1. Select vdi file and click properties

enter image description here

Here you can increase or decrease the vdi size.

jar not loaded. See Servlet Spec 2.3, section 9.7.2. Offending class: javax/servlet/Servlet.class

Remove servlet.jar from source web-inf/lib folder as it is available in tomcat lib folder then it works fine

NGINX: upstream timed out (110: Connection timed out) while reading response header from upstream

I think this error can happen for various reasons, but it can be specific to the module you're using. For example I saw this using the uwsgi module, so had to set "uwsgi_read_timeout".

Open a webpage in the default browser

This worked perfectly for me. Since this is for personal use, I used Firefox as my browser.

 Dim url As String
    url = "http://www.google.com"
    Process.Start("Firefox", url)

delete vs delete[] operators in C++

delete is used for one single pointer and delete[] is used for deleting an array through a pointer. This might help you to understand better.

Fastest way to convert string to integer in PHP

Run a test.

   string coerce:          7.42296099663
   string cast:            8.05654597282
   string fail coerce:     7.14159703255
   string fail cast:       7.87444186211

This was a test that ran each scenario 10,000,000 times. :-)

Co-ercion is 0 + "123"

Casting is (integer)"123"

I think Co-ercion is a tiny bit faster. Oh, and trying 0 + array('123') is a fatal error in PHP. You might want your code to check the type of the supplied value.

My test code is below.


function test_string_coerce($s) {
    return 0 + $s;
}

function test_string_cast($s) {
    return (integer)$s;
}

$iter = 10000000;

print "-- running each text $iter times.\n";

// string co-erce
$string_coerce = new Timer;
$string_coerce->Start();

print "String Coerce test\n";
for( $i = 0; $i < $iter ; $i++ ) {
    test_string_coerce('123');
}

$string_coerce->Stop();

// string cast
$string_cast = new Timer;
$string_cast->Start();

print "String Cast test\n";
for( $i = 0; $i < $iter ; $i++ ) {
    test_string_cast('123');
}

$string_cast->Stop();

// string co-erce fail.
$string_coerce_fail = new Timer;
$string_coerce_fail->Start();

print "String Coerce fail test\n";
for( $i = 0; $i < $iter ; $i++ ) {
    test_string_coerce('hello');
}

$string_coerce_fail->Stop();

// string cast fail
$string_cast_fail = new Timer;
$string_cast_fail->Start();

print "String Cast fail test\n";
for( $i = 0; $i < $iter ; $i++ ) {
    test_string_cast('hello');
}

$string_cast_fail->Stop();

// -----------------
print "\n";
print "string coerce:          ".$string_coerce->Elapsed()."\n";
print "string cast:            ".$string_cast->Elapsed()."\n";
print "string fail coerce:     ".$string_coerce_fail->Elapsed()."\n";
print "string fail cast:       ".$string_cast_fail->Elapsed()."\n";


class Timer {
    var $ticking = null;
    var $started_at = false;
    var $elapsed = 0;

    function Timer() {
        $this->ticking = null;
    }

    function Start() {
        $this->ticking = true;
        $this->started_at = microtime(TRUE);
    }

    function Stop() {
        if( $this->ticking )
            $this->elapsed = microtime(TRUE) - $this->started_at;
        $this->ticking = false;
    }

    function Elapsed() {
        switch( $this->ticking ) {
            case true: return "Still Running";
            case false: return $this->elapsed;
            case null: return "Not Started";
        }
    }
}

Do sessions really violate RESTfulness?

i think token must include all the needed information encoded inside it, which makes authentication by validating the token and decoding the info https://www.oauth.com/oauth2-servers/access-tokens/self-encoded-access-tokens/

Install a Windows service using a Windows command prompt?

Create a *.bat file beside of your windows service exe file for installing with the following context:

CLS
ECHO Installing My Windows Service 

START %windir%\Microsoft.NET\Framework\v4.0.30319\installutil.exe "%~d0%~p0\YourWindowsServiceExeName.exe"

Create a *.bat file beside of your windows service exe file for uninstalling with the following context:

CLS
ECHO Uninstalling My Windows Service 

START %windir%\Microsoft.NET\Framework\v4.0.30319\installutil.exe -u "%~d0%~p0\YourWindowsServiceExeName.exe"

Run each of bat file as Admin to install or uninstall your windows service.

Conda version pip install -r requirements.txt --target ./lib

You can always try this:

/home/user/anaconda3/bin/pip install -r requirements.txt

This simply uses the pip installed in the conda environment. If pip is not preinstalled in your environment you can always run the following command

conda install pip

Compile throws a "User-defined type not defined" error but does not go to the offending line of code

For the Scripting.Dictionary type, you can either use late binding (as already pointed out ) with:

Dim Dict as Object
Set Dict = CreateObject("Scripting.Dictionary")

Which works, but you don't get the code auto completion. Or you use early binding, but you need to make sure that VBA can find the Scripting.Dictionary type by adding the reference to the Microsoft Scripting Library via VBA-->Tools-->References--> "Microsoft Scripting Runtime". Then you can use:

Dim Dict as Scripting.Dictionary
Set Dict = New Scripting.Dictionary

... and auto completion will work.

Angular pass callback function to child component as @Input similar to AngularJS way

As an example, I am using a login modal window, where the modal window is the parent, the login form is the child and the login button calls back to the modal parent's close function.

The parent modal contains the function to close the modal. This parent passes the close function to the login child component.

import { Component} from '@angular/core';
import { LoginFormComponent } from './login-form.component'

@Component({
  selector: 'my-modal',
  template: `<modal #modal>
      <login-form (onClose)="onClose($event)" ></login-form>
    </modal>`
})
export class ParentModalComponent {
  modal: {...};

  onClose() {
    this.modal.close();
  }
}

After the child login component submits the login form, it closes the parent modal using the parent's callback function

import { Component, EventEmitter, Output } from '@angular/core';

@Component({
  selector: 'login-form',
  template: `<form (ngSubmit)="onSubmit()" #loginForm="ngForm">
      <button type="submit">Submit</button>
    </form>`
})
export class ChildLoginComponent {
  @Output() onClose = new EventEmitter();
  submitted = false;

  onSubmit() {
    this.onClose.emit();
    this.submitted = true;
  }
}

R - Concatenate two dataframes?

You may use rbind but in this case you need to have the same number of columns in both tables, so try the following:

b$b<-as.double(NA) #keeping numeric format is essential for further calculations
new<-rbind(a,b)

How do I create an Excel chart that pulls data from multiple sheets?

Use the Chart Wizard.

On Step 2 of 4, there is a tab labeled "Series". There are 3 fields and a list box on this tab. The list box shows the different series you are already including on the chart. Each series has both a "Name" field and a "Values" field that is specific to that series. The final field is the "Category (X) axis labels" field, which is common to all series.

Click on the "Add" button below the list box. This will add a blank series to your list box. Notice that the values for "Name" and for "Values" change when you highlight a series in the list box.

Select your new series.

There is an icon in each field on the right side. This icon allows you to select cells in the workbook to pull the data from. When you click it, the Wizard temporarily hides itself (except for the field you are working in) allowing you to interact with the workbook.

Select the appropriate sheet in the workbook and then select the fields with the data you want to show in the chart. The button on the right of the field can be clicked to unhide the wizard.

Hope that helps.

EDIT: The above applies to 2003 and before. For 2007, when the chart is selected, you should be able to do a similar action using the "Select Data" option on the "Design" tab of the ribbon. This opens up a dialog box listing the Series for the chart. You can select the series just as you could in Excel 2003, but you must use the "Add" and "Edit" buttons to define custom series.

How to create an Array with AngularJS's ng-model

First thing is first. You need to define $scope.telephone as an array in your controller before you can start using it in your view.

$scope.telephone = [];

To address the issue of ng-model not being recognised when you append a new input - for that to work you have to use the $compile Angular service.

From the Angular.js API reference on $compile:

Compiles an HTML string or DOM into a template and produces a template function, which can then be used to link scope and the template together.

// I'm using Angular syntax. Using jQuery will have the same effect
// Create input element
var input = angular.element('<div><input type="text" ng-model="telephone[' + $scope.inputCounter + ']"></div>');
// Compile the HTML and assign to scope
var compile = $compile(input)($scope);

Have a look on JSFiddle

How to prevent column break within an element?

This answer might only apply to certain circumstances; If you set a height to your elements, this will be obeyed by the column styling. There-by keeping anything that is contained within that height to a row.

I had a list, like the op, but it contained two elements, items and buttons to act upon those items. I treated it like a table <ul> - table, <li> - table-row, <div> - table-cell put the UL in a 4 column layout. The columns were sometimes being split between the item and it's buttons. The trick I used was to give the Div elements a line height to cover the buttons.

What is the best way to manage a user's session in React?

There is a React module called react-client-session that makes storing client side session data very easy. The git repo is here.

This is implemented in a similar way as the closure approach in my other answer, however it also supports persistence using 3 different persistence stores. The default store is memory(not persistent).

  1. Cookie
  2. localStorage
  3. sessionStorage

After installing, just set the desired store type where you mount the root component ...

import ReactSession from 'react-client-session';

ReactSession.setStoreType("localStorage");

... and set/get key value pairs from anywhere in your app:

import ReactSession from 'react-client-session';

ReactSession.set("username", "Bob");
ReactSession.get("username");  // Returns "Bob"

How do I configure HikariCP in my Spring Boot app in my application.properties files?

@Configuration
@ConfigurationProperties(prefix = "params.datasource")
public class JpaConfig extends HikariConfig {

    @Bean
    public DataSource dataSource() throws SQLException {
        return new HikariDataSource(this);
    }

}

application.yml

params:
  datasource:
    driverClassName: com.mysql.jdbc.Driver
    jdbcUrl: jdbc:mysql://localhost:3306/myDb
    username: login
    password: password
    maximumPoolSize: 5

UPDATED! Since version Spring Boot 1.3.0 :

  1. Just add HikariCP to dependencies
  2. Configure application.yml

application.yml

spring:
  datasource:
    type: com.zaxxer.hikari.HikariDataSource
    url: jdbc:h2:mem:TEST
    driver-class-name: org.h2.Driver
    username: username
    password: password
    hikari:
      idle-timeout: 10000

UPDATED! Since version Spring Boot 2.0.0 :

The default connection pool has changed from Tomcat to Hikari :)

Android Studio: Can't start Git

For the one using mac who installed Xcode7, you have to start Xcode and accept the license agreement for the android studio error to go away.

Executing a shell script from a PHP script

It's a simple problem. When you are running from terminal, you are running the php file from terminal as a privileged user. When you go to the php from your web browser, the php script is being run as the web server user which does not have permissions to execute files in your home directory. In Ubuntu, the www-data user is the apache web server user. If you're on ubuntu you would have to do the following: chown yourusername:www-data /home/testuser/testscript chmod g+x /home/testuser/testscript

what the above does is transfers user ownership of the file to you, and gives the webserver group ownership of it. the next command gives the group executable permission to the file. Now the next time you go ahead and do it from the browser, it should work.

Class vs. static method in JavaScript

Static method calls are made directly on the class and are not callable on instances of the class. Static methods are often used to create utility function

Pretty clear description

Taken Directly from mozilla.org

Foo needs to be bound to your class Then when you create a new instance you can call myNewInstance.foo() If you import your class you can call a static method

Comparing two java.util.Dates to see if they are in the same day

FOR ANDROID USERS:

You can use DateUtils.isToday(dateMilliseconds) to check whether the given date is current day or not.

API reference: https://developer.android.com/reference/android/text/format/DateUtils.html#isToday(long)

Autonumber value of last inserted row - MS Access / VBA

This is an adaptation from my code for you. I was inspired from developpez.com (Look in the page for : "Pour insérer des données, vaut-il mieux passer par un RecordSet ou par une requête de type INSERT ?"). They explain (with a little French). This way is much faster than the one upper. In the example, this way was 37 times faster. Try it.

Const tableName As String = "InvoiceNumbers"
Const columnIdName As String = "??"
Const columnDateName As String = "date"

Dim rsTable As DAO.recordSet
Dim recordId as long

Set rsTable = CurrentDb.OpenRecordset(tableName)
Call rsTable .AddNew
recordId = CLng(rsTable (columnIdName)) ' Save your Id in a variable
rsTable (columnDateName) = Now()        ' Store your data
rsTable .Update

recordSet.Close

LeCygne

How can I scale an image in a CSS sprite

Old post, but here's what I did using background-size:cover; (hat tip to @Ceylan Pamir)...

EXAMPLE USAGE
Horizontal circle flipper (hover on front side image, flips to back with different image).

EXAMPLE SPRITE
480px x 240px

EXAMPLE FINAL SIZE
Single image @ 120px x 120px

GENERIC CODE
.front {width:120px; height:120px; background:url(http://www.example.com/images/image_240x240.png); background-size:cover; background-repeat:no-repeat; background-position:0px 0px;}

.back {width:120px; height:120px; background:url(http://www.example.com/images/image_240x240.png); background-size:cover; background-repeat:no-repeat; background-position:-120px 0px;}

ABBREVIATED CASE FIDDLE
http://jsfiddle.net/zuhloobie/133esq63/2/

I do not understand how execlp() works in Linux

this prototype:

  int execlp(const char *file, const char *arg, ...);

Says that execlp ìs a variable argument function. It takes 2 const char *. The rest of the arguments, if any, are the additional arguments to hand over to program we want to run - also char * - all these are C strings (and the last argument must be a NULL pointer)

So, the file argument is the path name of an executable file to be executed. arg is the string we want to appear as argv[0] in the executable. By convention, argv[0] is just the file name of the executable, normally it's set to the same as file.

The ... are now the additional arguments to give to the executable.

Say you run this from a commandline/shell:

$ ls

That'd be execlp("ls", "ls", (char *)NULL); Or if you run

$ ls -l /

That'd be execlp("ls", "ls", "-l", "/", (char *)NULL);

So on to execlp("/bin/sh", ..., "ls -l /bin/??", ...);

Here you are going to the shell, /bin/sh , and you're giving the shell a command to execute. That command is "ls -l /bin/??". You can run that manually from a commandline/shell:

 $ ls -l /bin/??

Now, how do you run a shell and tell it to execute a command ? You open up the documentation/man page for your shell and read it.

What you want to run is:

$ /bin/sh -c "ls -l /bin/??"

This becomes

  execlp("/bin/sh","/bin/sh", "-c", "ls -l /bin/??", (char *)NULL);

Side note: The /bin/?? is doing pattern matching, this pattern matching is done by the shell, and it expands to all files under /bin/ with 2 characters. If you simply did

  execlp("ls","ls", "-l", "/bin/??", (char *)NULL);

Probably nothing would happen (unless there's a file actually named /bin/??) as there's no shell that interprets and expands /bin/??

Filter rows which contain a certain string

This answer similar to others, but using preferred stringr::str_detect and dplyr rownames_to_column.

library(tidyverse)

mtcars %>% 
  rownames_to_column("type") %>% 
  filter(stringr::str_detect(type, 'Toyota|Mazda') )

#>             type  mpg cyl  disp  hp drat    wt  qsec vs am gear carb
#> 1      Mazda RX4 21.0   6 160.0 110 3.90 2.620 16.46  0  1    4    4
#> 2  Mazda RX4 Wag 21.0   6 160.0 110 3.90 2.875 17.02  0  1    4    4
#> 3 Toyota Corolla 33.9   4  71.1  65 4.22 1.835 19.90  1  1    4    1
#> 4  Toyota Corona 21.5   4 120.1  97 3.70 2.465 20.01  1  0    3    1

Created on 2018-06-26 by the reprex package (v0.2.0).

Parsing PDF files (especially with tables) with PDFBox

How about printing to image and doing OCR on that?

Sounds terribly ineffective, but it's practically the very purpose of PDF to make text inaccessible, you gotta do what you gotta do.

What is an Android PendingIntent?

TAXI ANALOGY

Intent

Intents are typically used for starting Services. For example:

Intent intent = new Intent(CurrentClass.this, ServiceClass.class);
startService(intent);

This is like when you call for a taxi:

Myself = CurrentClass
Taxi Driver = ServiceClass

Pending Intent

You will need to use something like this:

Intent intent = new Intent(CurrentClass.this, ServiceClass.class);
PendingIntent pi = PendingIntent.getService(parameter, parameter, intent, parameter);
getDataFromThirdParty(parameter, parameter, pi, parameter);

Now this Third party will start the service acting on your behalf. A real life analogy is Uber or Lyft who are both taxi companies.

You send a request for a ride to Uber/Lyft. They will then go ahead and call one of their drivers on your behalf.

Therefore:

Uber/Lyft ------ ThirdParty which receives PendingIntent
Myself --------- Class calling PendingIntent
Taxi Driver ---- ServiceClass

What is the equivalent of bigint in C#?

Int64 maps directly to BigInt.

Source

Automatic creation date for Django model form objects?

You can use the auto_now and auto_now_add options for updated_at and created_at respectively.

class MyModel(models.Model):
    created_at = models.DateTimeField(auto_now_add=True)
    updated_at = models.DateTimeField(auto_now=True)

Format Float to n decimal places

Of note, use of DecimalFormat constructor is discouraged. The javadoc for this class states:

In general, do not call the DecimalFormat constructors directly, since the NumberFormat factory methods may return subclasses other than DecimalFormat.

https://docs.oracle.com/javase/8/docs/api/java/text/DecimalFormat.html

So what you need to do is (for instance):

NumberFormat formatter = NumberFormat.getInstance(Locale.US);
formatter.setMaximumFractionDigits(2);
formatter.setMinimumFractionDigits(2);
formatter.setRoundingMode(RoundingMode.HALF_UP); 
Float formatedFloat = new Float(formatter.format(floatValue));

Error Code: 1290. The MySQL server is running with the --secure-file-priv option so it cannot execute this statement

I had to set

C:\ProgramData\MySQL\MySQL Server 8.0/my.ini  secure-file-priv=""

When I commented line with secure-file-priv, secure-file-priv was null and I couldn't download data.

CodeIgniter 404 Page Not Found, but why?

I had the same issue after migrating to a new environment and it was simply that the server didn't run mod_rewrite

a quick sudo a2enmod rewrite then sudo systemctl restart apache2

and problem solved...

Thanks @fanis who pointed that out in his comment on the question.

Validate select box

I don't know how was the plugin the time the question was asked (2009), but I faced the same problem today and solved it this way:

  1. Give your select tag a name attribute. For example in this case

    <select name="myselect">

  2. Instead of working with the attribute value="default" in the tag option, disable the default option as suggested by Jeremy Visser or set value=""

    <option disabled="disabled">Choose...</option>

    or

    <option value="">Choose...</option>

  3. Set the plugin validation rule

    $( "#YOUR_FORM_ID" ).validate({ rules: { myselect: { required: true } } });

    or

    <select name="myselect" class="required">

Obs: redsquare's solution works only if you have just one select in your form. If you want his solution to work with more than one select add a name attribute to your select.

Hope it helps! :)

*.h or *.hpp for your class definitions

I've recently started using *.hpp for c++ headers.

The reason is that I use emacs as my primary editor and it enters automatically into c-mode when you load a *.h file and into c++-mode when you load a *.hpp file.

Apart that fact I see no good reasons for choosing *.h over *.hpp or vice-versa.

How can I get the list of files in a directory using C or C++?

Unfortunately the C++ standard does not define a standard way of working with files and folders in this way.

Since there is no cross platform way, the best cross platform way is to use a library such as the boost filesystem module.

Cross platform boost method:

The following function, given a directory path and a file name, recursively searches the directory and its sub-directories for the file name, returning a bool, and if successful, the path to the file that was found.

bool find_file(const path & dir_path,         // in this directory,
               const std::string & file_name, // search for this name,
               path & path_found)             // placing path here if found
{
    if (!exists(dir_path)) 
        return false;

    directory_iterator end_itr; // default construction yields past-the-end

    for (directory_iterator itr(dir_path); itr != end_itr; ++itr)
    {
        if (is_directory(itr->status()))
        {
            if (find_file(itr->path(), file_name, path_found)) 
                return true;
        }
        else if (itr->leaf() == file_name) // see below
        {
            path_found = itr->path();
            return true;
        }
    }
    return false;
}

Source from the boost page mentioned above.

For Unix/Linux based systems:

You can use opendir / readdir / closedir.

Sample code which searches a directory for entry ``name'' is:

len = strlen(name);
dirp = opendir(".");
while ((dp = readdir(dirp)) != NULL)
        if (dp->d_namlen == len && !strcmp(dp->d_name, name)) {
                (void)closedir(dirp);
                return FOUND;
        }
(void)closedir(dirp);
return NOT_FOUND;

Source code from the above man pages.

For a windows based systems:

You can use the Win32 API FindFirstFile / FindNextFile / FindClose functions.

The following C++ example shows you a minimal use of FindFirstFile.

#include <windows.h>
#include <tchar.h>
#include <stdio.h>

void _tmain(int argc, TCHAR *argv[])
{
   WIN32_FIND_DATA FindFileData;
   HANDLE hFind;

   if( argc != 2 )
   {
      _tprintf(TEXT("Usage: %s [target_file]\n"), argv[0]);
      return;
   }

   _tprintf (TEXT("Target file is %s\n"), argv[1]);
   hFind = FindFirstFile(argv[1], &FindFileData);
   if (hFind == INVALID_HANDLE_VALUE) 
   {
      printf ("FindFirstFile failed (%d)\n", GetLastError());
      return;
   } 
   else 
   {
      _tprintf (TEXT("The first file found is %s\n"), 
                FindFileData.cFileName);
      FindClose(hFind);
   }
}

Source code from the above msdn pages.

How to save the contents of a div as a image?

Do something like this:

A <div> with ID of #imageDIV, another one with ID #download and a hidden <div> with ID #previewImage.

Include the latest version of jquery, and jspdf.debug.js from the jspdf CDN

Then add this script:

var element = $("#imageDIV"); // global variable
var getCanvas; // global variable
$('document').ready(function(){
  html2canvas(element, {
    onrendered: function (canvas) {
      $("#previewImage").append(canvas);
      getCanvas = canvas;
    }
  });
});
$("#download").on('click', function () {
  var imgageData = getCanvas.toDataURL("image/png");
  // Now browser starts downloading it instead of just showing it
  var newData = imageData.replace(/^data:image\/png/, "data:application/octet-stream");
  $("#download").attr("download", "image.png").attr("href", newData);
});

The div will be saved as a PNG on clicking the #download

Multiple definition of ... linker error

Declarations of public functions go in header files, yes, but definitions are absolutely valid in headers as well! You may declare the definition as static (only 1 copy allowed for the entire program) if you are defining things in a header for utility functions that you don't want to have to define again in each c file. I.E. defining an enum and a static function to translate the enum to a string. Then you won't have to rewrite the enum to string translator for each .c file that includes the header. :)

104, 'Connection reset by peer' socket error, or When does closing a socket result in a RST rather than FIN?

I had the same issue however with doing an upload of a very large file using a python-requests client posting to a nginx+uwsgi backend.

What ended up being the cause was the the backend had a cap on the max file size for uploads lower than what the client was trying to send.

The error never showed up in our uwsgi logs since this limit was actually one imposed by nginx.

Upping the limit in nginx removed the error.

C# Iterating through an enum? (Indexing a System.Array)

You can cast that Array to different types of Arrays:

myEnum[] values = (myEnum[])Enum.GetValues(typeof(myEnum));

or if you want the integer values:

int[] values = (int[])Enum.GetValues(typeof(myEnum));

You can iterate those casted arrays of course :)

How to open port in Linux

First, you should disable selinux, edit file /etc/sysconfig/selinux so it looks like this:

SELINUX=disabled
SELINUXTYPE=targeted

Save file and restart system.

Then you can add the new rule to iptables:

iptables -A INPUT -m state --state NEW -p tcp --dport 8080 -j ACCEPT

and restart iptables with /etc/init.d/iptables restart

If it doesn't work you should check other network settings.

JavaScript seconds to time string with format hh:mm:ss

I dislike adding properties to standard datatypes in JavaScript, so I would recommend something like this:

/**
 * Format a duration in seconds to a human readable format using the notion
 * "h+:mm:ss", e.g. "4:40:78". Negative durations are preceeded by "-".
 *
 * @param t Duration in seconds
 * @return The formatted duration string
 */
var readableDuration = (function() {

    // Each unit is an object with a suffix s and divisor d
    var units = [
        {s: '', d: 1}, // Seconds
        {s: ':', d: 60}, // Minutes
        {s: ':', d: 60}, // Hours
    ];

    // Closure function
    return function(t) {
        t = parseInt(t); // In order to use modulus
        var trunc, n = Math.abs(t), i, out = []; // out: list of strings to concat
        for (i = 0; i < units.length; i++) {
            n = Math.floor(n / units[i].d); // Total number of this unit
            // Truncate e.g. 26h to 2h using modulus with next unit divisor
            if (i+1 < units.length) // Tweak substr with two digits
                trunc = ('00'+ n % units[i+1].d).substr(-2, 2); // …if not final unit
            else
                trunc = n;
            out.unshift(''+ trunc + units[i].s); // Output
        }
        (t < 0) ? out.unshift('-') : null; // Handle negative durations
        return out.join('');
    };
})();

Usage:

var str = readableDuration(3808); // "1:03:28"

I also created a more generally usable version. The main difference is that it accepts milliseconds (which is kind of the standard time unit in JS) and the output format uses spaces instead.

Returning Promises from Vuex actions

Actions

ADD_PRODUCT : (context,product) => {
  return Axios.post(uri, product).then((response) => {
    if (response.status === 'success') {  
      context.commit('SET_PRODUCT',response.data.data)
    }
    return response.data
  });
});

Component

this.$store.dispatch('ADD_PRODUCT',data).then((res) => {
  if (res.status === 'success') {
    // write your success actions here....
  } else {
     // write your error actions here...
  }
})

jQuery Multiple ID selectors

If you give each of these instances a class you can use

$('.yourClass').upload()

Apache 13 permission denied in user's home directory

Error:

[error] [client 127.0.0.1] (13)Permission denied: Could not open password file: /home/XXX/svn/svn_password

Info:

##SELinux Security Context File Labels
#httpd_sys_content_t  The type used by regular static web pages with .html and .htm extensions.
#httpd_sys_script_ro_t  Required for CGI scripts to read files and directories.
#httpd_sys_script_ra_t  Same as the httpd_sys_script_ro_t type but also allows appending data to files by the CGI script.
#httpd_sys_script_rw_t  Files with this type may be changed by a CGI script in any way, including deletion.
#httpd_sys_script_exec_t  The type required for the execution of CGI scripts 

Solution:

[root@localhost]# perror 13
OS error code  13:  Permission denied
[root@localhost]# chown apache.apache /home/XXX/svn/ -R
[root@localhost]# semanage fcontext -a -t httpd_sys_script_rw_t  "/home/XXX/svn(/.*)?"
[root@localhost]# restorecon -R -v /home/XXX/svn/
[root@localhost]# restorecon reset /home/XXX/svn/ context
[root@localhost]# ls -dZ /home/XXX/svn/
drwxr-xr-x. apache apache system_u:object_r:httpd_sys_rw_content_t:s0 /home/XXX/svn/
[root@localhost]# ls -dZ /home/XXX/svn/svn_password 
-rwxr-xr-x. apache apache system_u:object_r:httpd_sys_rw_content_t:s0 /home/XXX/svn/svn_password
[root@localhost]# 

Pass variable to function in jquery AJAX success callback

Try something like this (use this.url to get the url):

$.ajax({
    url: 'http://www.example.org',
    data: {'a':1,'b':2,'c':3},
    dataType: 'xml',
    complete : function(){
        alert(this.url)
    },
    success: function(xml){
    }
});

Taken from here

Drop all tables whose names begin with a certain string

CREATE PROCEDURE usp_GenerateDROP
    @Pattern AS varchar(255)
    ,@PrintQuery AS bit
    ,@ExecQuery AS bit
AS
BEGIN
    DECLARE @sql AS varchar(max)

    SELECT @sql = COALESCE(@sql, '') + 'DROP TABLE [' + TABLE_NAME + ']' + CHAR(13) + CHAR(10)
    FROM INFORMATION_SCHEMA.TABLES
    WHERE TABLE_NAME LIKE @Pattern

    IF @PrintQuery = 1 PRINT @sql
    IF @ExecQuery = 1 EXEC (@sql)
END

Android: adbd cannot run as root in production builds

You have to grant the Superuser right to the shell app (com.anroid.shell). In my case, I use Magisk to root my phone Nexsus 6P (Oreo 8.1). So I can grant Superuser right in the Magisk Manager app, whih is in the left upper option menu.

Determine whether an array contains a value

jQuery has a utility function for this:

$.inArray(value, array)

Returns index of value in array. Returns -1 if array does not contain value.

See also How do I check if an array includes an object in JavaScript?

tkinter: Open a new window with a button prompt

Here's the nearly shortest possible solution to your question. The solution works in python 3.x. For python 2.x change the import to Tkinter rather than tkinter (the difference being the capitalization):

import tkinter as tk
#import Tkinter as tk  # for python 2
    
def create_window():
    window = tk.Toplevel(root)

root = tk.Tk()
b = tk.Button(root, text="Create new window", command=create_window)
b.pack()

root.mainloop()

This is definitely not what I recommend as an example of good coding style, but it illustrates the basic concepts: a button with a command, and a function that creates a window.

How to use Bootstrap in an Angular project?

  1. npm install --save bootstrap
  2. go to -> angular-cli.json file, find styles properties and just add next sting: "../node_modules/bootstrap/dist/css/bootstrap.min.css", It might be looks like this:

    "styles": [
    "../node_modules/bootstrap/dist/css/bootstrap.min.css",
    "styles.css"
    ],
    

How to use a FolderBrowserDialog from a WPF application

And here's my final version.

public static class MyWpfExtensions
{
    public static System.Windows.Forms.IWin32Window GetIWin32Window(this System.Windows.Media.Visual visual)
    {
        var source = System.Windows.PresentationSource.FromVisual(visual) as System.Windows.Interop.HwndSource;
        System.Windows.Forms.IWin32Window win = new OldWindow(source.Handle);
        return win;
    }

    private class OldWindow : System.Windows.Forms.IWin32Window
    {
        private readonly System.IntPtr _handle;
        public OldWindow(System.IntPtr handle)
        {
            _handle = handle;
        }

        #region IWin32Window Members
        System.IntPtr System.Windows.Forms.IWin32Window.Handle
        {
            get { return _handle; }
        }
        #endregion
    }
}

And to actually use it:

var dlg = new FolderBrowserDialog();
System.Windows.Forms.DialogResult result = dlg.ShowDialog(this.GetIWin32Window());

Equivalent of Clean & build in Android Studio?

reed these links

http://tools.android.com/tech-docs/new-build-system/version-compatibility https://developer.android.com/studio/releases/gradle-plugin.html

in android studio version 2+, use this in gradle config

android{
..

compileOptions {
        sourceCompatibility JavaVersion.VERSION_1_7
        targetCompatibility JavaVersion.VERSION_1_7
        incremental = false;
}
...

}

after 3 days of search and test :(, this solve "rebuild for any run"

How to get current working directory in Java?

If you want the absolute path of the current source code, my suggestion is:

String internalPath = this.getClass().getName().replace(".", File.separator);
String externalPath = System.getProperty("user.dir")+File.separator+"src";
String workDir = externalPath+File.separator+internalPath.substring(0, internalPath.lastIndexOf(File.separator));

How to manually deploy artifacts in Nexus Repository Manager OSS 3

This isn't currently implemented in the UI in Nexus 3 (see https://issues.sonatype.org/browse/NEXUS-10121). You'll need to use curl or mvn deploy or some other option.

Remove a folder from git tracking

if file is committed and pushed to github then you should run

git rm --fileName

git ls-files to make sure that the file is removed or untracked

git commit -m "UntrackChanges"

git push

In a Dockerfile, How to update PATH environment variable?

Although the answer that Gunter posted was correct, it is not different than what I already had posted. The problem was not the ENV directive, but the subsequent instruction RUN export $PATH

There's no need to export the environment variables, once you have declared them via ENV in your Dockerfile.

As soon as the RUN export ... lines were removed, my image was built successfully

How to add,set and get Header in request of HttpClient?

You can use HttpPost, there are methods to add Header to the Request.

DefaultHttpClient httpclient = new DefaultHttpClient();
String url = "http://localhost";
HttpPost httpPost = new HttpPost(url);

httpPost.addHeader("header-name" , "header-value");

HttpResponse response = httpclient.execute(httpPost);

UIButton action in table view cell

Swift 4 & Swift 5:

You need to add target for that button.

myButton.addTarget(self, action: #selector(connected(sender:)), for: .touchUpInside)

And of course you need to set tag of that button since you are using it.

myButton.tag = indexPath.row

You can achieve this by subclassing UITableViewCell. Use it in interface builder, drop a button on that cell, connect it via outlet and there you go.

To get the tag in the connected function:

@objc func connected(sender: UIButton){
    let buttonTag = sender.tag
}

Counting unique values in a column in pandas dataframe like in Qlik?

you can use unique property by using len function

len(df['hID'].unique()) 5

How to auto-size an iFrame?

In IE 5.5+, you can use the contentWindow property:

iframe.height = iframe.contentWindow.document.scrollHeight;

In Netscape 6 (assuming firefox as well), contentDocument property:

iframe.height = iframe.contentDocument.scrollHeight

Styling Form with Label above Inputs

10 minutes ago i had the same problem of place label above input

then i got a small ugly resolution

<form>
    <h4><label for="male">Male</label></h4>
    <input type="radio" name="sex" id="male" value="male">
</form>

The disadvantage is that there is a big blank space between the label and input, of course you can adjust the css

Demo at: http://jsfiddle.net/bqkawjs5/

How to view .img files?

At first you should use file to identify the image:

file foo.img

Docker Repository Does Not Have a Release File on Running apt-get update on Ubuntu

This is what worked for me on LinuxMint 19.

curl -s https://yum.dockerproject.org/gpg | sudo apt-key add
apt-key fingerprint 58118E89F3A912897C070ADBF76221572C52609D
sudo add-apt-repository "deb https://apt.dockerproject.org/repo ubuntu-$(lsb_release -cs) main"
sudo apt-get update
sudo apt-get install docker-ce docker-ce-cli containerd.io

Apache default VirtualHost

I will say what worked for me, the others answers above didn't help to my case at all. I hope it can help someone.

Actually, I'm using Virtual host configuration (sites-available / sites-enabled) on EC2 Linux AMI with Apache/2.4.39 (Amazon). So, I have 1 ec2 instance to serve many sites (domains).

Considering that you already have Virtual Host installed and working. In my folder /etc/httpd/sites-available, I have some files with domain names (suffix .conf), for example: domain.com.conf. Create a new file like that.

sudo nano /etc/httpd/sites-available/domain.com.conf

<VirtualHost *:80>
    ServerName www.domain.com
    ServerAlias domain.com
    DocumentRoot /var/www/html/domain
</VirtualHost>

For each file.conf in sites-available, I create a symbolic link:

sudo ln -s /etc/httpd/sites-available/domain.com.conf /etc/httpd/sites-enabled/domain.com.conf

This is the default configuration, so, if access directly by IP of Server, you will be redirect to DocumentRoot of the first file (.conf) in sites-available folder, sorted by filename.

To have a default DocumentRoot folder when access by IP, you have to create a file named 0a.conf, then apache will serve this site because this new file will be the first in sites-available folder.

You must create a symbolic link:

sudo ln -s /etc/httpd/sites-available/0a.conf /etc/httpd/sites-enabled/0a.conf

To check serving order, use it:

sudo apachectl -S

Now, restart apache, and check out it.

Be happy =)

AngularJS is rendering <br> as text not as a newline

Why so complicated?

I solved my problem this way simply:

  <pre>{{existingCategory+thisCategory}}</pre>

It will make <br /> automatically if the string contains '\n' that contain when I was saving data from textarea.

Iterating through map in template

As Herman pointed out, you can get the index and element from each iteration.

{{range $index, $element := .}}{{$index}}
{{range $element}}{{.Value}}
{{end}}
{{end}}

Working example:

package main

import (
    "html/template"
    "os"
)

type EntetiesClass struct {
    Name string
    Value int32
}

// In the template, we use rangeStruct to turn our struct values
// into a slice we can iterate over
var htmlTemplate = `{{range $index, $element := .}}{{$index}}
{{range $element}}{{.Value}}
{{end}}
{{end}}`

func main() {
    data := map[string][]EntetiesClass{
        "Yoga": {{"Yoga", 15}, {"Yoga", 51}},
        "Pilates": {{"Pilates", 3}, {"Pilates", 6}, {"Pilates", 9}},
    }

    t := template.New("t")
    t, err := t.Parse(htmlTemplate)
    if err != nil {
        panic(err)
    }

    err = t.Execute(os.Stdout, data)
    if err != nil {
        panic(err)
    }

}

Output:

Pilates
3
6
9

Yoga
15
51

Playground: http://play.golang.org/p/4ISxcFKG7v

Zsh: Conda/Pip installs command not found

this solved it for me, and is sure to work add this to ~/.zshrc

export PATH=path_to_anaconda_bin:$PATH

the answer

How to set -source 1.7 in Android Studio and Gradle

Always use latest SDK version to build:

compileSdkVersion 23

It does not affect runtime behavior, but give you latest programming features.

How to draw a standard normal distribution in R

Something like this perhaps?

x<-rnorm(100000,mean=10, sd=2)
hist(x,breaks=150,xlim=c(0,20),freq=FALSE)
abline(v=10, lwd=5)
abline(v=c(4,6,8,12,14,16), lwd=3,lty=3)

Disable form autofill in Chrome without disabling autocomplete

A little late, but here's my fool proof solution useful for pages like the sign up/registration page where the user has to input a new password.

<form method="post">
    <input type="text" name="fname" id="firstname" x-autocompletetype="given-name" autocomplete="on">
    <input type="text" name="lname" id="lastname" x-autocompletetype="family-name" autocomplete="on">
    <input type="text" name="email" id="email" x-autocompletetype="email" autocomplete="on">
    <input type="password" name="password" id="password_fake" class="hidden" autocomplete="off" style="display: none;">
    <input type="password" name="password" id="password" autocomplete="off">
</form>

Chrome will detect two password inputs and will not auto fill the password fields. However, the field id="password_fake" one will be hidden via CSS. So the user will only see one password field.

I've also added some extra attributes "x-autocompletetype" which is a chrome experimental specific auto fill feature. From my example, chrome will autofill in the first name, last name and email address, and NOT the password field.

How To Show And Hide Input Fields Based On Radio Button Selection

Replace all instances of visibility style to display

display:none //to hide
display:block //to show

Here's updated jsfiddle: http://jsfiddle.net/QAaHP/16/

You can do it using Mootools or jQuery functions to slide up/down but if you don't need animation effect it's probably too much for what you need.

CSS display is a faster and simpler approach.

What is the use of the @Temporal annotation in Hibernate?

This annotation must be specified for persistent fields or properties of type java.util.Date and java.util.Calendar. It may only be specified for fields or properties of these types.

The Temporal annotation may be used in conjunction with the Basic annotation, the Id annotation, or the ElementCollection annotation (when the element collection value is of such a temporal type.

In plain Java APIs, the temporal precision of time is not defined. When dealing with temporal data, you might want to describe the expected precision in database. Temporal data can have DATE, TIME, or TIMESTAMP precision (i.e., the actual date, only the time, or both). Use the @Temporal annotation to fine tune that.

The temporal data is the data related to time. For example, in a content management system, the creation-date and last-updated date of an article are temporal data. In some cases, temporal data needs precision and you want to store precise date/time or both (TIMESTAMP) in database table.

The temporal precision is not specified in core Java APIs. @Temporal is a JPA annotation that converts back and forth between timestamp and java.util.Date. It also converts time-stamp into time. For example, in the snippet below, @Temporal(TemporalType.DATE) drops the time value and only preserves the date.

@Temporal(TemporalType.DATE)
private java.util.Date creationDate;

As per javadocs,

Annotation to declare an appropriate {@code TemporalType} on query method parameters. Note that this annotation can only be used on parameters of type {@link Date} with default TemporalType.DATE

[Information above collected from various sources]

LINQ: combining join and group by

I met the same problem as you.

I push two tables result into t1 object and group t1.

 from p in Products                         
  join bp in BaseProducts on p.BaseProductId equals bp.Id
  select new {
   p,
   bp
  } into t1
 group t1 by t1.p.SomeId into g
 select new ProductPriceMinMax { 
  SomeId = g.FirstOrDefault().p.SomeId, 
  CountryCode = g.FirstOrDefault().p.CountryCode, 
  MinPrice = g.Min(m => m.bp.Price), 
  MaxPrice = g.Max(m => m.bp.Price),
  BaseProductName = g.FirstOrDefault().bp.Name
};

Angular2 QuickStart npm start is not working correctly

I had a similar problem after copying the angular2-quickstart folder (including node_modules) to create the angular2-tour-of-heroes folder. This was wierd because the original was compiling fine but the copy was not...

npm run tsc

I was able to resolve the issue by deleting the node_modules folder and re-running npm install.

This was a surprise to me, so I did a diff between the 2 folders...

diff -rw angular2-quickstart/node_modules/ angular2-tour-of-heroes/node_modules/

there were a LOT of differences, a lot of 'where' diffs in the package.json files like this:-

diff -rw angular2-quickstart/node_modules/yargs/package.json angular2-tour-of-heroes/node_modules/yargs/package.json
5c5
<       "/Users/michael/Tutorials/angular2/angular2-quickstart/node_modules/lite-server"
---
>       "/Users/michael/Tutorials/angular2/angular2-tour-of-heroes/node_modules/lite-server"

...which kind of makes sense but there were also some like this:-

diff -rw angular2-quickstart/node_modules/utf-8-validate/build/gyp-mac-tool angular2-tour-of-heroes/node_modules/utf-8-validate/build/gyp-mac-tool
607c607,608
<       return {k: self._ExpandVariables(data[k], substitutions) for k in data}
---
>       return dict((k, self._ExpandVariables(data[k],
>                                             substitutions)) for k in data)

...which I don't understand at all.

Oh well, Hope this helps.

Best way to log POST data in Apache?

I would do it in the application, actually. It's still configurable at runtime, depending on your logger system, of course. For example, if you use Apache Log (log4j/cxx) you could configure a dedicated logger for such URLs and then configure it at runtime from an XML file.

SELECT * FROM in MySQLi

While you are switching, switch to PDO instead of mysqli, It helps you write database agnositc code and have better features for prepared statements.

http://www.php.net/pdo

Bindparam for PDO: http://se.php.net/manual/en/pdostatement.bindparam.php

$sth = $dbh->prepare("SELECT * FROM tablename WHERE field1 = :value1 && field2 = :value2");
$sth->bindParam(':value1', 'foo');
$sth->bindParam(':value2', 'bar');
$sth->execute();

or:

$sth = $dbh->prepare("SELECT * FROM tablename WHERE field1 = ? && field2 = ?");
$sth->bindParam(1, 'foo');
$sth->bindParam(2, 'bar');
$sth->execute();

or execute with the parameters as an array:

$sth = $dbh->prepare("SELECT * FROM tablename WHERE field1 = :value1 && field2 = :value2");
$sth->execute(array(':value1' => 'foo' , ':value2' => 'bar'));

It will be easier for you if you would like your application to be able to run on different databases in the future.

I also think you should invest some time in using some of the classes from Zend Framwework whilst working with PDO. Check out their Zend_Db and more specifically [Zend_Db_Factory][2]. You do not have to use all of the framework or convert your application to the MVC pattern, but using the framework and reading up on it is time well spent.

Programmatically Add CenterX/CenterY Constraints

Center in container

enter image description here

The code below does the same thing as centering in the Interface Builder.

override func viewDidLoad() {
    super.viewDidLoad()

    // set up the view
    let myView = UIView()
    myView.backgroundColor = UIColor.blue
    myView.translatesAutoresizingMaskIntoConstraints = false
    view.addSubview(myView)

    // Add code for one of the constraint methods below
    // ...
}

Method 1: Anchor Style

myView.centerXAnchor.constraint(equalTo: view.centerXAnchor).isActive = true
myView.centerYAnchor.constraint(equalTo: view.centerYAnchor).isActive = true

Method 2: NSLayoutConstraint Style

NSLayoutConstraint(item: myView, attribute: NSLayoutConstraint.Attribute.centerX, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerX, multiplier: 1, constant: 0).isActive = true
NSLayoutConstraint(item: myView, attribute: NSLayoutConstraint.Attribute.centerY, relatedBy: NSLayoutConstraint.Relation.equal, toItem: view, attribute: NSLayoutConstraint.Attribute.centerY, multiplier: 1, constant: 0).isActive = true

Notes

  • Anchor style is the preferred method over NSLayoutConstraint Style, however it is only available from iOS 9, so if you are supporting iOS 8 then you should still use NSLayoutConstraint Style.
  • You will also need to add length and width constraints.
  • My full answer is here.

How to bind bootstrap popover on dynamic elements

Try this HTML

<a href="#" data-toggle="popover" data-popover-target="#popover-content-1">Do Popover 1</a>
<a href="#" data-toggle="popover" data-popover-target="#popover-content-2">Do Popover</a>

<div id="popover-content-1" style="display: none">Content 1</div>
<div id="popover-content-2" style="display: none">Content 2</div>

jQuery:

$(function() {
  $('[data-toggle="popover"]').each(function(i, obj) {
    var popover_target = $(this).data('popover-target');
    $(this).popover({
        html: true,
        trigger: 'focus',
        placement: 'right',
        content: function(obj) {
            return $(popover_target).html();
        }
    });
  });
});

Converting string to byte array in C#

This work for me, after that I could convert put my picture in a bytea field in my database.

using (MemoryStream s = new MemoryStream(DirEntry.Properties["thumbnailphoto"].Value as byte[]))
{
    return s.ToArray();
}

What is the purpose of the return statement?

return should be used for recursive functions/methods or you want to use the returned value for later applications in your algorithm.

print should be used when you want to display a meaningful and desired output to the user and you don't want to clutter the screen with intermediate results that the user is not interested in, although they are helpful for debugging your code.

The following code shows how to use return and print properly:

def fact(x):
    if x < 2:
        return 1
    return x * fact(x - 1)

print(fact(5))

This explanation is true for all of the programming languages not just python.

What is class="mb-0" in Bootstrap 4?

m - for classes that set margin, like this :

  • mt - for classes that set margin-top
  • mb - for classes that set margin-bottom
  • ml - for classes that set margin-left
  • mr - for classes that set margin-right
  • mx - for classes that set both margin-left and margin-right
  • my - for classes that set both margin-top and margin-bottom

Where size is one of margin :

  • 0 - for classes that eliminate the margin by setting it to 0, like mt-0
  • 1 - (by default) for classes that set the margin to $spacer * .25, like mt-1
  • 2 - (by default) for classes that set the margin to $spacer * .5, like mt-2
  • 3 - (by default) for classes that set the margin to $spacer, like mt-3
  • 4 - (by default) for classes that set the margin to $spacer * 1.5, like mt-4
  • 5 - (by default) for classes that set the margin to $spacer * 3, like mt-5
  • auto - for classes that set the margin to auto, like mx-auto

Eclipse/Maven error: "No compiler is provided in this environment"

if someone is running Eclipse in Ubuntu and have this problem I have found the answer by following these steps:

  1. Eclipse->window->preference.
  2. Select installed JREs->Add
  3. Select standardVM.
  4. JRE home: press [Directory..] button.
  5. Choose your java (my problem was my eclipse was running with java8 and my VM were with java7), in my case java8 was installed in usr/local/jvm/java-8-oracle.
  6. Press finish.
  7. Then press installed JRES arrow so you can see the other options.
  8. Go to Execution Environment.
  9. Select JavaSE-1.6 on left and in the right (the compatible JRE) you have to choose the Java you have just installed( in my case java-8-oracle). you have to do this steps with JavaSE1.8.
  10. Click OK and restart Eclipse.

How to Deserialize JSON data?

If you use .Net 4.5 you can also use standard .Net json serializer:

using System.Runtime.Serialization.Json;
...    
Stream jsonSource = ...; // serializer will read data stream
var s = new DataContractJsonSerializer(typeof(string[][]));
var j = (string[][])s.ReadObject(jsonSource);

In .Net 4.5 and older you can use JavaScriptSerializer class:

using System.Web.Script.Serialization;
...
JavaScriptSerializer serializer = new JavaScriptSerializer();
string[][] list = serializer.Deserialize<string[][]>(json);

How to check for valid email address?

Email addresses are incredibly complicated. Here's a sample regex that will match every RFC822-valid address: http://www.ex-parrot.com/pdw/Mail-RFC822-Address.html

You'll notice that it's probably longer than the rest of your program. There are even whole modules for Perl with the purpose of validating email addresses. So you probably won't get anything that's 100% perfect as a regex while also being readable. Here's a sample recursive descent parser: http://cpansearch.perl.org/src/ABIGAIL/RFC-RFC822-Address-2009110702/lib/RFC/RFC822/Address.pm

but you'll need to decide whether you need perfect parsing or simple code.

How can I cast int to enum?

Just cast it:

MyEnum e = (MyEnum)3;

You can check if it's in range using Enum.IsDefined:

if (Enum.IsDefined(typeof(MyEnum), 3)) { ... }

Convert RGB values to Integer

if r, g, b = 3 integer values from 0 to 255 for each color

then

rgb = 65536 * r + 256 * g + b;

the single rgb value is the composite value of r,g,b combined for a total of 16777216 possible shades.

Console logging for react?

If you want to log inside JSX you can create a dummy component
which plugs where you wish to log:

_x000D_
_x000D_
const Console = prop => (
  console[Object.keys(prop)[0]](...Object.values(prop))
  ,null // ? React components must return something 
)

// Some component with JSX and a logger inside
const App = () => 
  <div>
    <p>imagine this is some component</p>
    <Console log='foo' />
    <p>imagine another component</p>
    <Console warn='bar' />
  </div>

// Render 
ReactDOM.render(
  <App />,
  document.getElementById("react")
)
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/16.8.4/umd/react.production.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react-dom/16.8.4/umd/react-dom.production.min.js"></script>
<div id="react"></div>
_x000D_
_x000D_
_x000D_

jQuery: Currency Format Number

Here is the cool regex style for digit grouping:

thenumber.toString().replace(/(\d)(?=(\d{3})+(?!\d))/g, "$1.");

Command to get latest Git commit hash from a branch

Use git ls-remote git://github.com/<user>/<project>.git. For example, my trac-backlog project gives:

:: git ls-remote git://github.com/jszakmeister/trac-backlog.git
5d6a3c973c254378738bdbc85d72f14aefa316a0    HEAD
4652257768acef90b9af560295b02d0ac6e7702c    refs/heads/0.1.x
35af07bc99c7527b84e11a8632bfb396823326f3    refs/heads/0.2.x
5d6a3c973c254378738bdbc85d72f14aefa316a0    refs/heads/master
520dcebff52506682d6822ade0188d4622eb41d1    refs/pull/11/head
6b2c1ed650a7ff693ecd8ab1cb5c124ba32866a2    refs/pull/11/merge
51088b60d66b68a565080eb56dbbc5f8c97c1400    refs/pull/12/head
127c468826c0c77e26a5da4d40ae3a61e00c0726    refs/pull/12/merge
2401b5537224fe4176f2a134ee93005a6263cf24    refs/pull/15/head
8aa9aedc0e3a0d43ddfeaf0b971d0ae3a23d57b3    refs/pull/15/merge
d96aed93c94f97d328fc57588e61a7ec52a05c69    refs/pull/7/head
f7c1e8dabdbeca9f9060de24da4560abc76e77cd    refs/pull/7/merge
aa8a935f084a6e1c66aa939b47b9a5567c4e25f5    refs/pull/8/head
cd258b82cc499d84165ea8d7a23faa46f0f2f125    refs/pull/8/merge
c10a73a8b0c1809fcb3a1f49bdc1a6487927483d    refs/tags/0.1.0
a39dad9a1268f7df256ba78f1166308563544af1    refs/tags/0.2.0
2d559cf785816afd69c3cb768413c4f6ca574708    refs/tags/0.2.1
434170523d5f8aad05dc5cf86c2a326908cf3f57    refs/tags/0.2.2
d2dfe40cb78ddc66e6865dcd2e76d6bc2291d44c    refs/tags/0.3.0
9db35263a15dcdfbc19ed0a1f7a9e29a40507070    refs/tags/0.3.0^{}

Just grep for the one you need and cut it out:

:: git ls-remote git://github.com/jszakmeister/trac-backlog.git | \
   grep refs/heads/master | cut -f 1
5d6a3c973c254378738bdbc85d72f14aefa316a0

Or, you can specify which refs you want on the command line and avoid the grep with:

:: git ls-remote git://github.com/jszakmeister/trac-backlog.git refs/heads/master | \
   cut -f 1
5d6a3c973c254378738bdbc85d72f14aefa316a0

Note: it doesn't have to be the git:// URL. It could be https:// or [email protected]: too.

Originally, this was geared towards finding out the latest commit of a remote branch (not just from your last fetch, but the actual latest commit in the branch on the remote repository). If you need the commit hash for something locally, the best answer is:

git rev-parse branch-name

It's fast, easy, and a single command. If you want the commit hash for the current branch, you can look at HEAD:

git rev-parse HEAD

How to serialize an object to XML without getting xmlns="..."?

Ahh... nevermind. It's always the search after the question is posed that yields the answer. My object that is being serialized is obj and has already been defined. Adding an XMLSerializerNamespace with a single empty namespace to the collection does the trick.

In VB like this:

Dim xs As New XmlSerializer(GetType(cEmploymentDetail))
Dim ns As New XmlSerializerNamespaces()
ns.Add("", "")

Dim settings As New XmlWriterSettings()
settings.OmitXmlDeclaration = True

Using ms As New MemoryStream(), _
    sw As XmlWriter = XmlWriter.Create(ms, settings), _
    sr As New StreamReader(ms)
xs.Serialize(sw, obj, ns)
ms.Position = 0
Console.WriteLine(sr.ReadToEnd())
End Using

in C# like this:

//Create our own namespaces for the output
XmlSerializerNamespaces ns = new XmlSerializerNamespaces();

//Add an empty namespace and empty value
ns.Add("", "");

//Create the serializer
XmlSerializer slz = new XmlSerializer(someType);

//Serialize the object with our own namespaces (notice the overload)
slz.Serialize(myXmlTextWriter, someObject, ns);

How do I add files and folders into GitHub repos?

Note that since early December 2012, you can create new files directly from GitHub:

Create new File

ProTip™: You can pre-fill the filename field using just the URL.
Typing ?filename=yournewfile.txt at the end of the URL will pre-fill the filename field with the name yournewfile.txt.

d

How do you know a variable type in java?

I learned from the Search Engine(My English is very bad , So code...) How to get variable's type? Up's :

String str = "test";
String type = str.getClass().getName();
value: type = java.lang.String

this method :

str.getClass().getSimpleName();
value:String

now example:

Object o = 1;
o.getClass().getSimpleName();
value:Integer

Checking if float is an integer

Keep in mind that most of the techniques here are valid presuming that round-off error due to prior calculations is not a factor. E.g. you could use roundf, like this:

float z = 1.0f;

if (roundf(z) == z) {
    printf("integer\n");
} else {
    printf("fraction\n");
}

The problem with this and other similar techniques (such as ceilf, casting to long, etc.) is that, while they work great for whole number constants, they will fail if the number is a result of a calculation that was subject to floating-point round-off error. For example:

float z = powf(powf(3.0f, 0.05f), 20.0f);

if (roundf(z) == z) {
    printf("integer\n");
} else {
    printf("fraction\n");
}

Prints "fraction", even though (31/20)20 should equal 3, because the actual calculation result ended up being 2.9999992847442626953125.

Any similar method, be it fmodf or whatever, is subject to this. In applications that perform complex or rounding-prone calculations, usually what you want to do is define some "tolerance" value for what constitutes a "whole number" (this goes for floating-point equality comparisons in general). We often call this tolerance epsilon. For example, lets say that we'll forgive the computer for up to +/- 0.00001 rounding error. Then, if we are testing z, we can choose an epsilon of 0.00001 and do:

if (fabsf(roundf(z) - z) <= 0.00001f) {
    printf("integer\n");
} else {
    printf("fraction\n");
}

You don't really want to use ceilf here because e.g. ceilf(1.0000001) is 2 not 1, and ceilf(-1.99999999) is -1 not -2.

You could use rintf in place of roundf if you prefer.

Choose a tolerance value that is appropriate for your application (and yes, sometimes zero tolerance is appropriate). For more information, check out this article on comparing floating-point numbers.

Spring configure @ResponseBody JSON format

For the folks who are using Java based Spring configuration:

@Configuration
@ComponentScan(basePackages = "com.domain.sample")
@EnableWebMvc
public class SpringConfig extends WebMvcConfigurerAdapter {
....

    @Override
    public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
        final MappingJackson2HttpMessageConverter converter = new MappingJackson2HttpMessageConverter();
        final ObjectMapper objectMapper = new ObjectMapper();
        objectMapper.setSerializationInclusion(JsonInclude.Include.NON_NULL);
        converter.setObjectMapper(objectMapper);
        converters.add(converter);
        super.configureMessageConverters(converters);
    }

....

}

I'm using MappingJackson2HttpMessageConverter - which is from fasterxml.

<dependency>
  <groupId>com.fasterxml.jackson.core</groupId>
  <artifactId>jackson-databind</artifactId>
  <version>2.3.1</version>
</dependency>

If you want to use codehaus-jackson mapper, instead use this one MappingJacksonHttpMessageConverter

 <dependency>
    <groupId>org.codehaus.jackson</groupId>
    <artifactId>jackson-mapper-asl</artifactId>
    <version>${codehaus.jackson.version}</version>
 </dependency>

Disable Button in Angular 2

I tried use [disabled]="!editmode" but it not work in my case.

This is my solution [disabled]="!editmode ? 'disabled': null" , I share for whom concern.

<button [disabled]="!editmode ? 'disabled': null" 
    (click)='loadChart()'>
            <div class="btn-primary">Load Chart</div>
    </button>

Stackbliz https://stackblitz.com/edit/angular-af55ep

MVC 5 Access Claims Identity User Data

You can also do this.

IEnumerable<Claim> claims = ClaimsPrincipal.Current.Claims;

Converting a JS object to an array using jQuery

Since ES5 Object.keys() returns an array containing the properties defined directly on an object (excluding properties defined in the prototype chain):

Object.keys(yourObject).map(function(key){ return yourObject[key] });

ES6 takes it one step further with arrow functions:

Object.keys(yourObject).map(key => yourObject[key]);

Easy way to turn JavaScript array into comma-separated list?

var arr = ["Pro1", "Pro2", "Pro3"];
console.log(arr.join());// Pro1,Pro2,Pro3
console.log(arr.join(', '));// Pro1, Pro2, Pro3

Link to Flask static files with url_for

You have by default the static endpoint for static files. Also Flask application has the following arguments:

static_url_path: can be used to specify a different path for the static files on the web. Defaults to the name of the static_folder folder.

static_folder: the folder with static files that should be served at static_url_path. Defaults to the 'static' folder in the root path of the application.

It means that the filename argument will take a relative path to your file in static_folder and convert it to a relative path combined with static_url_default:

url_for('static', filename='path/to/file')

will convert the file path from static_folder/path/to/file to the url path static_url_default/path/to/file.

So if you want to get files from the static/bootstrap folder you use this code:

<link rel="stylesheet" type="text/css" href="{{ url_for('static', filename='bootstrap/bootstrap.min.css') }}">

Which will be converted to (using default settings):

<link rel="stylesheet" type="text/css" href="static/bootstrap/bootstrap.min.css">

Also look at url_for documentation.

PostgreSQL CASE ... END with multiple conditions

This kind of code perhaps should work for You

SELECT
 *,
 CASE
  WHEN (pvc IS NULL OR pvc = '') AND (datepose < 1980) THEN '01'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose >= 1980) THEN '02'
  WHEN (pvc IS NULL OR pvc = '') AND (datepose IS NULL OR datepose = 0) THEN '03'
  ELSE '00'
 END AS modifiedpvc
FROM my_table;


 gid | datepose | pvc | modifiedpvc 
-----+----------+-----+-------------
   1 |     1961 | 01  | 00
   2 |     1949 |     | 01
   3 |     1990 | 02  | 00
   1 |     1981 |     | 02
   1 |          | 03  | 00
   1 |          |     | 03
(6 rows)

How to print out a variable in makefile

If you simply want some output, you want to use $(info) by itself. You can do that anywhere in a Makefile, and it will show when that line is evaluated:

$(info VAR="$(VAR)")

Will output VAR="<value of VAR>" whenever make processes that line. This behavior is very position dependent, so you must make sure that the $(info) expansion happens AFTER everything that could modify $(VAR) has already happened!

A more generic option is to create a special rule for printing the value of a variable. Generally speaking, rules are executed after variables are assigned, so this will show you the value that is actually being used. (Though, it is possible for a rule to change a variable.) Good formatting will help clarify what a variable is set to, and the $(flavor) function will tell you what kind of a variable something is. So in this rule:

print-% : ; $(info $* is a $(flavor $*) variable set to [$($*)]) @true
  • $* expands to the stem that the % pattern matched in the rule.
  • $($*) expands to the value of the variable whose name is given by by $*.
  • The [ and ] clearly delineate the variable expansion. You could also use " and " or similar.
  • $(flavor $*) tells you what kind of variable it is. NOTE: $(flavor) takes a variable name, and not its expansion. So if you say make print-LDFLAGS, you get $(flavor LDFLAGS), which is what you want.
  • $(info text) provides output. Make prints text on its stdout as a side-effect of the expansion. The expansion of $(info) though is empty. You can think of it like @echo, but importantly it doesn't use the shell, so you don't have to worry about shell quoting rules.
  • @true is there just to provide a command for the rule. Without that, make will also output print-blah is up to date. I feel @true makes it more clear that it's meant to be a no-op.

Running it, you get

$ make print-LDFLAGS
LDFLAGS is a recursive variable set to [-L/Users/...]

Python string class like StringBuilder in C#?

In case you are here looking for a fast string concatenation method in Python, then you do not need a special StringBuilder class. Simple concatenation works just as well without the performance penalty seen in C#.

resultString = ""

resultString += "Append 1"
resultString += "Append 2"

See Antoine-tran's answer for performance results

Create a map with clickable provinces/states using SVG, HTML/CSS, ImageMap

jQuery plugin for decorating image maps (highlights, select areas, tooltips):

http://www.outsharked.com/imagemapster/

Disclosure: I wrote it.

Is there any boolean type in Oracle databases?

Not at the SQL level and that's a pity There is one in PLSQL though

How do I enable Java in Microsoft Edge web browser?

Edge has dropped all support for plugins. This means that Java, ActiveX, Silverlight, and other plugins are no longer supported. For this reason Microsoft has included Internet Explorer 11, which does support these plugins, with non-mobile versions of Windows 10. If you are running Windows 10 and need plugin support Edge is not an option, but IE 11 is.

Storage permission error in Marshmallow

Add below code to your OnCreate() function in MainAcitivity, which will display pop up to ask for permission:

if (ActivityCompat.shouldShowRequestPermissionRationale(TestActivity.this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)){
}
else {
     ActivityCompat.requestPermissions(TestActivity.this,
                            new String[]{Manifest.permission.WRITE_EXTERNAL_STORAGE},
                            100);
}

CSS media query to target iPad and iPad only?

Well quite same question and there is also an answer =)

http://css-tricks.com/forums/discussion/12708/target-ipad-ipad-only./p1

@media only screen and (device-width: 768px) ...
@media only screen and (max-device-width: 1024px) ...

I can not test it currently so please test it =)

Also found some more:

http://perishablepress.com/press/2010/10/20/target-iphone-and-ipad-with-css3-media-queries/

Or you check the navigator with some javascript and generate / add a css file with javascript

How to do SELECT MAX in Django?

I've tested this for my project, it finds the max/min in O(n) time:

from django.db.models import Max

# Find the maximum value of the rating and then get the record with that rating. 
# Notice the double underscores in rating__max
max_rating = App.objects.aggregate(Max('rating'))['rating__max']
return App.objects.get(rating=max_rating)

This is guaranteed to get you one of the maximum elements efficiently, rather than sorting the whole table and getting the top (around O(n*logn)).

How to filter (key, value) with ng-repeat in AngularJs?

I made a bit more of a generic filter that I've used in multiple projects already:

  • object = the object that needs to be filtered
  • field = the field within that object that we'll filter on
  • filter = the value of the filter that needs to match the field

HTML:

<input ng-model="customerNameFilter" />
<div ng-repeat="(key, value) in filter(customers, 'customerName', customerNameFilter" >
   <p>Number: {{value.customerNo}}</p>
   <p>Name: {{value.customerName}}</p>
</div>

JS:

  $scope.filter = function(object, field, filter) {
    if (!object) return {};
    if (!filter) return object;

    var filteredObject = {};
    Object.keys(object).forEach(function(key) {
      if (object[key][field] === filter) {
        filteredObject[key] = object[key];
      }
    });

    return filteredObject;
  };

Template not provided using create-react-app

Clear your npm cache first then use yarn as follows:

  • npm cache clean --force
  • npm cache verify
  • yarn create react-app my-app

I hope this helps.

EDIT

...you might want to try the following after I have looked into this problem further:

  1. npm uninstall -g create-react-app
  2. yarn global remove create-react-app
  3. which create-react-app - If it returns something (e.g. /usr/local/bin/create-react-app), then do a rm -rf /usr/local/bin/create-react-app to delete manually.
  4. npm cache clean --force
  5. npm cache verify
  6. npx create-react-app@latest

These steps should remove globally installed create-react-app installs, you then manually remove the old directories linked to the old globally installed create-react-app scripts. It's then a good idea to clear your npm cache to ensure your not using any old cached versions of create-react-app. Lastly create a new reactjs app with the @latest option like so: npx create-react-app@latest. There has been much confusion on this issue where no template is created when using npx create-react-app, if you follow the steps I have stated above (1-6) then I hope you'll have success.

p.s.

If I wanted to then create a react app in a directory called client then I would type the following command into the terminal:

npx create-react-app@latest ./client

Good luck.

Accessing the logged-in user in a template

For symfony 2.6 and above we can use

{{ app.user.getFirstname() }}

as app.security global variable for Twig template has been deprecated and will be removed from 3.0

more info:

http://symfony.com/blog/new-in-symfony-2-6-security-component-improvements

and see the global variables in

http://symfony.com/doc/current/reference/twig_reference.html

Pygame mouse clicking detection

I was looking for the same answer to this question and after much head scratching this is the answer I came up with:

#Python 3.4.3 with Pygame
import pygame

pygame.init()
pygame.display.set_caption('Crash!')
window = pygame.display.set_mode((300, 300))


# Draw Once
Rectplace = pygame.draw.rect(window, (255, 0, 0),(100, 100, 100, 100))
pygame.display.update()
# Main Loop
while True:
    # Mouse position and button clicking.
    pos = pygame.mouse.get_pos()
    pressed1, pressed2, pressed3 = pygame.mouse.get_pressed()
    # Check if the rect collided with the mouse pos
    # and if the left mouse button was pressed.
    if Rectplace.collidepoint(pos) and pressed1:
        print("You have opened a chest!")
    # Quit pygame.
            for event in pygame.event.get():
        if event.type == pygame.QUIT:
            pygame.quit()
            quit(1)

Android studio takes too much memory

Open below mention path on your system and delete all your avd's (Virtual devices: Emulator)

C:\Users{Username}.android\avd

Note: - Deleting Emulator only from android studio will not delete all the spaces grab by their avd's. So delete all avd's from above given path and then create new emulator, if you needed.

How can I confirm a database is Oracle & what version it is using SQL?

There are different ways to check Oracle Database Version. Easiest way is to run the below SQL query to check Oracle Version.

SQL> SELECT * FROM PRODUCT_COMPONENT_VERSION;
SQL> SELECT * FROM v$version;

SQL Case Sensitive String Compare

You can define attribute as BINARY or use INSTR or STRCMP to perform your search.

File path for project files?

Path.Combine(AppDomain.CurrentDomain.BaseDirectory, @"JukeboxV2.0\JukeboxV2.0\Datos\ich will.mp3")

base directory + your filename

How to reset all checkboxes using jQuery or pure JS?

 $(":checkbox:checked").each(function () {

 this.click(); 
});

to unchecked checked box, turn your logic around to do opposite

Difference between git stash pop and git stash apply

git stash pop throws away the (topmost, by default) stash after applying it, whereas git stash apply leaves it in the stash list for possible later reuse (or you can then git stash drop it).

This happens unless there are conflicts after git stash pop, in which case it will not remove the stash, leaving it to behave exactly like git stash apply.

Another way to look at it: git stash pop is git stash apply && git stash drop.

Convert string to a variable name

assign is what you are looking for.

assign("x", 5)

x
[1] 5

but buyer beware.

See R FAQ 7.21 http://cran.r-project.org/doc/FAQ/R-FAQ.html#How-can-I-turn-a-string-into-a-variable_003f

How to do a SOAP wsdl web services call from the command line

For Windows users looking for a PowerShell alternative, here it is (using POST). I've split it up onto multiple lines for readability.

$url = 'https://sandbox.mediamind.com/Eyeblaster.MediaMind.API/V2/AuthenticationService.svc'
$headers = @{
    'Content-Type' = 'text/xml';
    'SOAPAction' = 'http://api.eyeblaster.com/IAuthenticationService/ClientLogin'
}
$envelope = @'
    <Envelope xmlns="http://schemas.xmlsoap.org/soap/envelope/">
        <Body>
            <yourEnvelopeContentsHere/>
        </Body>
    </Envelope>
'@     # <--- This line must not be indented

Invoke-WebRequest -Uri $url -Headers $headers -Method POST -Body $envelope

How do I size a UITextView to its content?

Not sure why people always over complicate things: here it is :

- (void)textViewDidChange:(UITextView *)textView{ CGRect frame = textView.frame;
CGFloat height = [self measureHeightOfUITextView:textView];
CGFloat insets = textView.textContainerInset.top + textView.textContainerInset.bottom;
height += insets;
frame.size.height = height;

if(frame.size.height > textView.frame.size.height){
    CGFloat diff = frame.size.height - textView.frame.size.height;
    textView.frame = CGRectMake(5, textView.frame.origin.y - diff, textView.frame.size.width, frame.size.height);
}
else if(frame.size.height < textView.frame.size.height){
    CGFloat diff = textView.frame.size.height - frame.size.height;
    textView.frame = CGRectMake(5, textView.frame.origin.y + diff, textView.frame.size.width, frame.size.height);
}
[textView setNeedsDisplay];
}

Laravel 5: Display HTML with Blade

For who using tinymce and markup within textarea:

{{ htmlspecialchars($text) }}

php date validation

Though checkdate is good, this seems much concise function to validate and also you can give formats. [Source]

function validateDate($date, $format = 'Y-m-d H:i:s') {
    $d = DateTime::createFromFormat($format, $date);
    return $d && $d->format($format) == $date;
}

function was copied from this answer or php.net


The extra ->format() is needed for cases where the date is invalid but createFromFormat still manages to create a DateTime object. For example:

// Gives "2016-11-10 ..." because Thursday falls on Nov 10
DateTime::createFromFormat('D M j Y', 'Thu Nov 9 2016');

// false, Nov 9 is a Wednesday
validateDate('Thu Nov 9 2016', 'D M j Y');

How to make google spreadsheet refresh itself every 1 minute?

I had a similar problem with crypto updates. A kludgy hack that gets around this is to include a '+ now() - now()' stunt at the end of the cell formula, with the setting as above to recalculate every minute. This worked for my price updates, but, definitely an ugly hack.

Execute curl command within a Python script

If you are not tweaking the curl command too much you can also go and call the curl command directly

import shlex
cmd = '''curl -X POST -d  '{"nw_src": "10.0.0.1/32", "nw_dst": "10.0.0.2/32", "nw_proto": "ICMP", "actions": "ALLOW", "priority": "10"}' http://localhost:8080/firewall/rules/0000000000000001'''
args = shlex.split(cmd)
process = subprocess.Popen(args, shell=False, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout, stderr = process.communicate()

Working copy locked error in tortoise svn while committing

I ran into this issue as well. For some I would like to point out that if it is locked CHECK WITH YOUR TEAM. Someone on the team might have some things locked because they are working on it (this allows developers to do work on things without others coming in and trying to work on the same content as well). If that is the case, releasing the lock and then updating has the potential to lose data for the developer who locked it.

With that in mind my concern was that the "clean up" option would possibly change my working copy or remove information from the Repo level of Subversion. That is not the case. The answer worked for me. Mine became locked when I clicked cancel during the middle of an update. I ended up pulling some of our branches and I did not need the stuff so I hit cancel. My working copy became locked. I could not find any documents that came up as "locked" when I used the command 'release lock'. This left me puzzled and upon some quick reading (and this thread) I attempted the 'clean up' command. After a clean up it resolved my issue and nothing was locked anymore.

source: http://tortoisesvn.net/docs/nightly/TortoiseSVN_en/tsvn-dug-locking.html

Send cookies with curl

.example.com TRUE / FALSE 1560211200 MY_VARIABLE MY_VALUE

The cookies file format apparently consists of a line per cookie and each line consists of the following seven tab-delimited fields:

  • domain - The domain that created AND that can read the variable.
  • flag - A TRUE/FALSE value indicating if all machines within a given domain can access the variable. This value is set automatically by the browser, depending on the value you set for domain.
  • path - The path within the domain that the variable is valid for.
  • secure - A TRUE/FALSE value indicating if a secure connection with the domain is needed to access the variable.
  • expiration - The UNIX time that the variable will expire on. UNIX time is defined as the number of seconds since Jan 1, 1970 00:00:00 GMT.
  • name - The name of the variable.
  • value - The value of the variable.

From http://www.cookiecentral.com/faq/#3.5

CSS performance relative to translateZ(0)

If you want implications, in some scenarios Google Chrome performance is horrible with hardware acceleration enabled. Oddly enough, changing the "trick" to -webkit-transform: rotateZ(360deg); worked just fine.

I don't believe we ever figured out why.

How to detect orientation change in layout in Android?

Use the onConfigurationChanged method of Activity. See the following code:

@Override
public void onConfigurationChanged(@NotNull Configuration newConfig) {
    super.onConfigurationChanged(newConfig);

    // Checks the orientation of the screen
    if (newConfig.orientation == Configuration.ORIENTATION_LANDSCAPE) {
        Toast.makeText(this, "landscape", Toast.LENGTH_SHORT).show();
    } else if (newConfig.orientation == Configuration.ORIENTATION_PORTRAIT){
        Toast.makeText(this, "portrait", Toast.LENGTH_SHORT).show();
    }
}

You also have to edit the appropriate element in your manifest file to include the android:configChanges Just see the code below:

<activity android:name=".MyActivity"
          android:configChanges="orientation|keyboardHidden"
          android:label="@string/app_name">

NOTE: with Android 3.2 (API level 13) or higher, the "screen size" also changes when the device switches between portrait and landscape orientation. Thus, if you want to prevent runtime restarts due to orientation change when developing for API level 13 or higher, you must declare android:configChanges="orientation|screenSize" for API level 13 or higher.

Hope this will help you... :)

Extract the first word of a string in a SQL Server query

Enhancement of Ben Brandt's answer to compensate even if the string starts with space by applying LTRIM(). Tried to edit his answer but rejected, so I am now posting it here separately.

DECLARE @test NVARCHAR(255)
SET @test = 'First Second'

SELECT SUBSTRING(LTRIM(@test),1,(CHARINDEX(' ',LTRIM(@test) + ' ')-1))

Ruby, remove last N characters from a string?

If the characters you want to remove are always the same characters, then consider chomp:

'abc123'.chomp('123')    # => "abc"

The advantages of chomp are: no counting, and the code more clearly communicates what it is doing.

With no arguments, chomp removes the DOS or Unix line ending, if either is present:

"abc\n".chomp      # => "abc"
"abc\r\n".chomp    # => "abc"

From the comments, there was a question of the speed of using #chomp versus using a range. Here is a benchmark comparing the two:

require 'benchmark'

S = 'asdfghjkl'
SL = S.length
T = 10_000
A = 1_000.times.map { |n| "#{n}#{S}" }

GC.disable

Benchmark.bmbm do |x|
  x.report('chomp') { T.times { A.each { |s| s.chomp(S) } } }
  x.report('range') { T.times { A.each { |s| s[0...-SL] } } }
end

Benchmark Results (using CRuby 2.13p242):

Rehearsal -----------------------------------------
chomp   1.540000   0.040000   1.580000 (  1.587908)
range   1.810000   0.200000   2.010000 (  2.011846)
-------------------------------- total: 3.590000sec

            user     system      total        real
chomp   1.550000   0.070000   1.620000 (  1.610362)
range   1.970000   0.170000   2.140000 (  2.146682)

So chomp is faster than using a range, by ~22%.

CREATE FILE encountered operating system error 5(failed to retrieve text for this error. Reason: 15105)

In my case I have got the error when trying to create a databae on a new drive. To overcome the problem I created a new folder in that drive and set the user properties Security to full control on it(It may be sufficient to set Modify ). Conclusion: SET the Drive/Folder Properties Security for users to "Modify".

Disable HttpClient logging

With:

  • Log2J 2 2.11.2
  • HttpClient 4.5.7 (elasticsearch 7.0.0 rest client)
  • Using properties file to configure

One can add:

logger.httpclient.name=org.apache.http
logger.httpclient.level=info

With 'httpclient' in the above example being a logical name you choose.

(Tested on Java 11 OpenFX application.)

Problems with jQuery getJSON using local files in Chrome

An additional way to get around the problem is by leveraging Flash Player's Local Only security sandbox and ExternalInterface methods. One can have JavaScript request a Flash application published using the Local Only security sandbox to load the file from the hard drive, and Flash can pass the data back to JavaScript via Flash's ExternalInterface class. I've tested this in Chrome, FF and IE9, and it works well. I'd be happy to share the code if anyone is interested.

EDIT: I've started a google code (ironic?) project for the implementation: http://code.google.com/p/flash-loader/

What is the meaning of git reset --hard origin/master?

In newer version of git (2.23+) you can use:

git switch -C master origin/master

-C is same as --force-create. Related Reference Docs

Querying a linked sql server

The accepted answer works for me.

Also, in MSSQLMS, you can browse the tree in the Object Explorer to the table you want to query.

[Server] -> Server Objects -> Linked Servers -> [Linked server] -> Catalogs -> [Database] -> [table]

then Right click, Script Table as, SELECT To, New Query Window

And the query will be generated for you with the right FROM, which you can use in your JOIN

Error loading the SDK when Eclipse starts

Feel tired deleting the android-wear related packages each time upgrading the sdk?

Try to make some changes to devices.xml as following, you can edit the files by hand, or use some batching tools like repl.

repl is written by me, add this line to sources.list and install:

echo 'http://deb.bodz.net/ unstable/' >>/etc/apt/sources.list
alias sagu='sudo apt-get update'
alias sagi='sudo apt-get install'
sagu
sagi repl

Then, remove those <d:skin> lines and replace ###dpi to hdpi or whatever.

repl -r --filter=devices.xml --mode=regexp -- '<d:skin>.*</d:skin>' '' .
repl -r --filter=devices.xml -- '280dpi' 'hdpi' .
repl -r --filter=devices.xml -- '360dpi' 'xhdpi' .

e.printStackTrace equivalent in python

import traceback
traceback.print_exc()

When doing this inside an except ...: block it will automatically use the current exception. See http://docs.python.org/library/traceback.html for more information.

Change width of select tag in Twitter Bootstrap

In bootstrap 3, it is recommended that you size inputs by wrapping them in col-**-# div tags. It seems that most things have 100% width, especially .form-control elements.

https://getbootstrap.com/docs/3.3/css/#forms-control-sizes

CSS:Defining Styles for input elements inside a div

When you say "called" I'm going to assume you mean an ID tag.

To make it cross-brower, I wouldn't suggest using the CSS3 [], although it is an option. This being said, give each of your textboxes a class like "tb" and the radio button "rb".

Then:

#divContainer .tb { width: 150px }
#divContainer .rb { width: 20px }

This assumes you are using the same classes elsewhere, if not, this will suffice:

.tb { width: 150px }
.rb { width: 20px }

As @David mentioned, to access anything within the division itself:

#divContainer [element] { ... }

Where [element] is whatever HTML element you need.

How to try convert a string to a Guid

new Guid(string)

You could also look at using a TypeConverter.

How do I add to the Windows PATH variable using setx? Having weird problems

This works perfectly:

for /f "usebackq tokens=2,*" %A in (`reg query HKCU\Environment /v PATH`) do set my_user_path=%B

setx PATH "C:\Python27;C:\Python27\Scripts;%my_user_path%"

The 1st command gets the USER environment variable 'PATH', into 'my_user_path' variable The 2nd line prepends the 'C:\Python27;C:\Python27\Scripts;' to the USER environment variable 'PATH'

Check If array is null or not in php

you can use

empty($result) 

to check if the main array is empty or not.

But since you have a SimpleXMLElement object, you need to query the object if it is empty or not. See http://www.php.net/manual/en/simplexmlelement.count.php

ex:

if (empty($result) || !isset($result['Tags'])) {
    return false;
}
if ( !($result['Tags'] instanceof SimpleXMLElement)) {
    return false;
}
return ($result['Tags']->count());

iOS 7 - Failing to instantiate default view controller

Projects created in Xcode 11 and above, simply changing the Main Interface file from the project settings won't be enough.

You have to manually edit the Info.plist file and set the storyboard name for the UISceneStoryboardFile as well.

Deserialize a json string to an object in python

In recent versions of python, you can use marshmallow-dataclass:

from marshmallow_dataclass import dataclass

@dataclass
class Payload
    action:str
    method:str
    data:str

Payload.Schema().load({"action":"print","method":"onData","data":"Madan Mohan"})

Web API Put Request generates an Http 405 Method Not Allowed error

Your client application and server application must be under same domain, for example :

client - localhost

server - localhost

and not :

client - localhost:21234

server - localhost

Registry Key '...' has value '1.7', but '1.6' is required. Java 1.7 is Installed and the Registry is Pointing to it

This happens when you somehow confused java itself. You are trying to run a java 6 VM where it found a JRE 7. It might show this problem even if you type in the command line just java or java -version in a misconfigured environment. The JAR is not the problem, except in the very unlikely case where the code in JAR is looking in the Windows Registry for that (which probably is not your case).

In my case, I had the java.exe, javaw.exe and javaws.exe from Java 6 in the Windows/System32 folder (don't know how it got to be there). The rest of the JDK and JRE where found in the PATH inside C:\Java\jdk_1.7.0\bin. Oops!

Python - TypeError: 'int' object is not iterable

Your problem is with this line:

number4 = list(cow[n])

It tries to take cow[n], which returns an integer, and make it a list. This doesn't work, as demonstrated below:

>>> a = 1
>>> list(a)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
TypeError: 'int' object is not iterable
>>>

Perhaps you meant to put cow[n] inside a list:

number4 = [cow[n]]

See a demonstration below:

>>> a = 1
>>> [a]
[1]
>>>

Also, I wanted to address two things:

  1. Your while-statement is missing a : at the end.
  2. It is considered very dangerous to use input like that, since it evaluates its input as real Python code. It would be better here to use raw_input and then convert the input to an integer with int.

To split up the digits and then add them like you want, I would first make the number a string. Then, since strings are iterable, you can use sum:

>>> a = 137
>>> a = str(a)
>>> # This way is more common and preferred
>>> sum(int(x) for x in a)
11
>>> # But this also works
>>> sum(map(int, a))
11
>>>

Command to open file with git

To open a file in Sublime Text,

Here is an example for opening a sample text file in Sublime Text editor

subl <filename>.txt

subl is previously created as an alias name,containing the directory file, using the "echo" command in Git Bash shell.

How to solve this java.lang.NoClassDefFoundError: org/apache/commons/io/output/DeferredFileOutputStream?

You will have to download file from here https://commons.apache.org/proper/commons-io/download_io.cgi and select https://prnt.sc/tk5ewt

Now, Next add this downloaded files into your project:

Right click to your project ->Build path->Configure BuidPath -> https://prnt.sc/tk5d93

How to execute a stored procedure within C# program

Calling Store Procedure in C#

    SqlCommand cmd = new SqlCommand("StoreProcedureName",con);
    cmd.CommandType=CommandType.StoredProcedure;
    cmd.Parameters.AddWithValue("@value",txtValue.Text);
    con.Open();
    int rowAffected=cmd.ExecuteNonQuery();
    con.Close();

How to delete a selected DataGridViewRow and update a connected database table?

private void buttonRemove_Click(object sender, EventArgs e)
{
    foreach (DataGridViewCell oneCell in dataGridView1.SelectedCells)
    {
        if (oneCell.Selected)
            dataGridView1.Rows.RemoveAt(oneCell.RowIndex);
    }
}

Removes rows which indexes are in selected cells. So, select any cells, and their corresponding rows will be removed.

APT command line interface-like yes/no input?

Python x.x

res = True
while res:
    res = input("Please confirm with y/yes...").lower(); res = res not in {'y','yes','Y','YES',''}

Where is HttpContent.ReadAsAsync?

I have the same problem, so I simply get JSON string and deserialize to my class:

HttpResponseMessage response = await client.GetAsync("Products");
//get data as Json string 
string data = await response.Content.ReadAsStringAsync();
//use JavaScriptSerializer from System.Web.Script.Serialization
JavaScriptSerializer JSserializer = new JavaScriptSerializer();
//deserialize to your class
products = JSserializer.Deserialize<List<Product>>(data);

How to merge a list of lists with same type of items to a single list of items?

Do you mean this?

var listOfList = new List<List<int>>() {
    new List<int>() { 1, 2 },
    new List<int>() { 3, 4 },
    new List<int>() { 5, 6 }
};
var list = new List<int> { 9, 9, 9 };
var result = list.Concat(listOfList.SelectMany(x => x));

foreach (var x in result) Console.WriteLine(x);

Results in: 9 9 9 1 2 3 4 5 6

Disable Enable Trigger SQL server for a table

I wanted to share something that helped me out. Idea credit goes to @Siavash and @Shahab Naseer.

I needed something where I could script disable and re enable of triggers for a particular table. I normally try and stay away from tiggers, but sometimes they could be good to use.

I took the script above and added a join to the sysobjects so I could filter by table name. This script will disable a trigger or triggers for a table.

select 'alter table '+ (select Schema_name(schema_id) from sys.objects o 
where o.object_id = parent_id) + '.'+object_name(parent_id) + ' ENABLE TRIGGER '+ t.Name as EnableScript,*
from sys.triggers t 
INNER JOIN dbo.sysobjects DS ON DS.id = t.parent_id 
where is_disabled = 0 AND DS.name = 'tblSubContact'

Getting all selected checkboxes in an array

On checking add the value for checkbox and on dechecking subtract the value

_x000D_
_x000D_
$('#myDiv').change(function() {_x000D_
  var values = 0.00;_x000D_
  {_x000D_
    $('#myDiv :checked').each(function() {_x000D_
      //if(values.indexOf($(this).val()) === -1){_x000D_
      values=values+parseFloat(($(this).val()));_x000D_
      // }_x000D_
    });_x000D_
    console.log( parseFloat(values));_x000D_
  }_x000D_
});
_x000D_
<div id="myDiv">_x000D_
  <input type="checkbox" name="type" value="4.00" />_x000D_
  <input type="checkbox" name="type" value="3.75" />_x000D_
  <input type="checkbox" name="type" value="1.25" />_x000D_
  <input type="checkbox" name="type" value="5.50" />_x000D_
</div>_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Showing alert in angularjs when user leaves a page

The other examples here work fine for the old versions of ui-router (>=0.3.x) but all state events, such as $stateChangeStart, are deprecated as of 1.0. The new ui-router 1.0 code uses the $transitions service. So you need to inject $transitions into your component then use the $transitions.onBefore method as the code below demonstrates.

$transitions.onBefore({}, function(transition) {
  return confirm("Are you sure you want to leave this page?");
});

This is just a super simple example. The $transitions service can accept more complicated responses such as promises. See the HookResult type for more information.

IOError: [Errno 32] Broken pipe: Python

I feel obliged to point out that the method using

signal(SIGPIPE, SIG_DFL) 

is indeed dangerous (as already suggested by David Bennet in the comments) and in my case led to platform-dependent funny business when combined with multiprocessing.Manager (because the standard library relies on BrokenPipeError being raised in several places). To make a long and painful story short, this is how I fixed it:

First, you need to catch the IOError (Python 2) or BrokenPipeError (Python 3). Depending on your program you can try to exit early at that point or just ignore the exception:

from errno import EPIPE

try:
    broken_pipe_exception = BrokenPipeError
except NameError:  # Python 2
    broken_pipe_exception = IOError

try:
    YOUR CODE GOES HERE
except broken_pipe_exception as exc:
    if broken_pipe_exception == IOError:
        if exc.errno != EPIPE:
            raise

However, this isn't enough. Python 3 may still print a message like this:

Exception ignored in: <_io.TextIOWrapper name='<stdout>' mode='w' encoding='UTF-8'>
BrokenPipeError: [Errno 32] Broken pipe

Unfortunately getting rid of that message is not straightforward, but I finally found http://bugs.python.org/issue11380 where Robert Collins suggests this workaround that I turned into a decorator you can wrap your main function with (yes, that's some crazy indentation):

from functools import wraps
from sys import exit, stderr, stdout
from traceback import print_exc


def suppress_broken_pipe_msg(f):
    @wraps(f)
    def wrapper(*args, **kwargs):
        try:
            return f(*args, **kwargs)
        except SystemExit:
            raise
        except:
            print_exc()
            exit(1)
        finally:
            try:
                stdout.flush()
            finally:
                try:
                    stdout.close()
                finally:
                    try:
                        stderr.flush()
                    finally:
                        stderr.close()
    return wrapper


@suppress_broken_pipe_msg
def main():
    YOUR CODE GOES HERE