Programs & Examples On #Syntax

Syntax refers to the actual language elements and symbols themselves. Questions should be tagged as syntax when the question specifically and almost completely relates to syntax alone. This tag should be used with a specific language tag

How to escape single quotes within single quoted strings

shell_escape () {
    printf '%s' "'${1//\'/\'\\\'\'}'"
}

Implementation explanation:

  • double quotes so we can easily output wrapping single quotes and use the ${...} syntax

  • bash's search and replace looks like: ${varname//search/replacement}

  • we're replacing ' with '\''

  • '\'' encodes a single ' like so:

    1. ' ends the single quoting

    2. \' encodes a ' (the backslash is needed because we're not inside quotes)

    3. ' starts up single quoting again

    4. bash automatically concatenates strings with no white space between

  • there's a \ before every \ and ' because that's the escaping rules for ${...//.../...} .

string="That's "'#@$*&^`(@#'
echo "original: $string"
echo "encoded:  $(shell_escape "$string")"
echo "expanded: $(bash -c "echo $(shell_escape "$string")")"

P.S. Always encode to single quoted strings because they are way simpler than double quoted strings.

What does map(&:name) mean in Ruby?

It's shorthand for tags.map { |tag| tag.name }.join(' ')

What's the syntax to import a class in a default package in Java?

You can't import classes from the default package. You should avoid using the default package except for very small example programs.

From the Java language specification:

It is a compile time error to import a type from the unnamed package.

In c# what does 'where T : class' mean?

It is called a type parameter constraint. Effectively it constraints what type T can be.

The type argument must be a reference type; this applies also to any class, interface, delegate, or array type.

Constraints on Type Parameters (C# Programming Guide)

Is there a difference between `continue` and `pass` in a for loop in python?

x = [1,2,3,4] 
for i in x:
    if i==2:
         pass  #Pass actually does nothing. It continues to execute statements below it.
         print "This statement is from pass."
for i in x:
    if i==2:
         continue #Continue gets back to top of the loop.And statements below continue are executed.
         print "This statement is from continue."

The output is

>>> This statement is from pass.

Again, let run same code with minor changes.

x = [1,2,3,4]
for i in x:
    if i==2:
       pass  #Pass actually does nothing. It continues to execute statements below it.
    print "This statement is from pass."
for i in x:
    if i==2:
        continue #Continue gets back to top of the loop.And statements below continue are executed.
    print "This statement is from continue."

The output is -

>>> This statement is from pass.
This statement is from pass.
This statement is from pass.
This statement is from pass.
This statement is from continue.
This statement is from continue.
This statement is from continue.

Pass doesn't do anything. Computation is unaffected. But continue gets back to top of the loop to procced with next computation.

Is there a difference between x++ and ++x in java?

Yes.

public class IncrementTest extends TestCase {

    public void testPreIncrement() throws Exception {
        int i = 0;
        int j = i++;
        assertEquals(0, j);
        assertEquals(1, i);
    }

    public void testPostIncrement() throws Exception {
        int i = 0;
        int j = ++i;
        assertEquals(1, j);
        assertEquals(1, i);
    }
}

JavaScript error (Uncaught SyntaxError: Unexpected end of input)

In my case, it ended up being a simple double quote issue in my bookmarklet, remember only use single quotes on bookmarklets. Just in case this helps someone.

Python def function: How do you specify the end of the function?

It uses indentation

 def func():
     funcbody
     if cond: 
         ifbody
     outofif

 outof_func 

How to replace multiple patterns at once with sed?

I always use multiple statements with "-e"

$ sed -e 's:AND:\n&:g' -e 's:GROUP BY:\n&:g' -e 's:UNION:\n&:g' -e 's:FROM:\n&:g' file > readable.sql

This will append a '\n' before all AND's, GROUP BY's, UNION's and FROM's, whereas '&' means the matched string and '\n&' means you want to replace the matched string with an '\n' before the 'matched'

Arrow operator (->) usage in C

The -> operator makes the code more readable than the * operator in some situations.

Such as: (quoted from the EDK II project)

typedef
EFI_STATUS
(EFIAPI *EFI_BLOCK_READ)(
  IN EFI_BLOCK_IO_PROTOCOL          *This,
  IN UINT32                         MediaId,
  IN EFI_LBA                        Lba,
  IN UINTN                          BufferSize,
  OUT VOID                          *Buffer
  );


struct _EFI_BLOCK_IO_PROTOCOL {
  ///
  /// The revision to which the block IO interface adheres. All future
  /// revisions must be backwards compatible. If a future version is not
  /// back wards compatible, it is not the same GUID.
  ///
  UINT64              Revision;
  ///
  /// Pointer to the EFI_BLOCK_IO_MEDIA data for this device.
  ///
  EFI_BLOCK_IO_MEDIA  *Media;

  EFI_BLOCK_RESET     Reset;
  EFI_BLOCK_READ      ReadBlocks;
  EFI_BLOCK_WRITE     WriteBlocks;
  EFI_BLOCK_FLUSH     FlushBlocks;

};

The _EFI_BLOCK_IO_PROTOCOL struct contains 4 function pointer members.

Suppose you have a variable struct _EFI_BLOCK_IO_PROTOCOL * pStruct, and you want to use the good old * operator to call it's member function pointer. You will end up with code like this:

(*pStruct).ReadBlocks(...arguments...)

But with the -> operator, you can write like this:

pStruct->ReadBlocks(...arguments...).

Which looks better?

What is the difference between . (dot) and $ (dollar sign)?

One application that is useful and took me some time to figure out from the very short description at learn you a haskell: Since:

f $ x = f x

and parenthesizing the right hand side of an expression containing an infix operator converts it to a prefix function, one can write ($ 3) (4+) analogous to (++", world") "hello".

Why would anyone do this? For lists of functions, for example. Both:

map (++", world") ["hello","goodbye"]`

and:

map ($ 3) [(4+),(3*)]

are shorter than map (\x -> x ++ ", world") ... or map (\f -> f 3) .... Obviously, the latter variants would be more readable for most people.

c++ array assignment of multiple values

const static int newvals[] = {34,2,4,5,6};

std::copy(newvals, newvals+sizeof(newvals)/sizeof(newvals[0]), array);

What is this weird colon-member (" : ") syntax in the constructor?

The other already explained to you that the syntax that you observe is called "constructor initializer list". This syntax lets you to custom-initialize base subobjects and member subobjects of the class (as opposed to allowing them to default-initialize or to remain uninitialized).

I just want to note that the syntax that, as you said, "looks like a constructor call", is not necessarily a constructor call. In C++ language the () syntax is just one standard form of initialization syntax. It is interpreted differently for different types. For class types with user-defined constructor it means one thing (it is indeed a constructor call), for class types without user-defined constructor it means another thing (so called value initialization ) for empty ()) and for non-class types it again means something different (since non-class types have no constructors).

In your case the data member has type int. int is not a class type, so it has no constructor. For type int this syntax means simply "initialize bar with the value of num" and that's it. It is done just like that, directly, no constructors involved, since, once again, int is not a class type of therefore it can't have any constructors.

passing object by reference in C++

What seems to be confusing you is the fact that functions that are declared to be pass-by-reference (using the &) aren't called using actual addresses, i.e. &a.

The simple answer is that declaring a function as pass-by-reference:

void foo(int& x);

is all we need. It's then passed by reference automatically.

You now call this function like so:

int y = 5;
foo(y);

and y will be passed by reference.

You could also do it like this (but why would you? The mantra is: Use references when possible, pointers when needed) :

#include <iostream>
using namespace std;

class CDummy {
public:
    int isitme (CDummy* param);
};


int CDummy::isitme (CDummy* param)
{
    if (param == this) return true;
    else return false;
}

int main () {
    CDummy a;
    CDummy* b = &a;             // assigning address of a to b
    if ( b->isitme(&a) )        // Called with &a (address of a) instead of a
        cout << "yes, &a is b";
    return 0;
}

Output:

yes, &a is b

Are (non-void) self-closing tags valid in HTML5?

In practice, using self-closing tags in HTML should work just like you'd expect. But if you are concerned about writing valid HTML5, you should understand how the use of such tags behaves within the two different two syntax forms you can use. HTML5 defines both an HTML syntax and an XHTML syntax, which are similar but not identical. Which one is used depends on the media type sent by the web server.

More than likely, your pages are being served as text/html, which follows the more lenient HTML syntax. In these cases, HTML5 allows certain start tags to have an optional / before it's terminating >. In these cases, the / is optional and ignored, so <hr> and <hr /> are identical. The HTML spec calls these "void elements", and gives a list of valid ones. Strictly speaking, the optional / is only valid within the start tags of these void elements; for example, <br /> and <hr /> are valid HTML5, but <p /> is not.

The HTML5 spec makes a clear distinction between what is correct for HTML authors and for web browser developers, with the second group being required to accept all kinds of invalid "legacy" syntax. In this case, it means that HTML5-compliant browsers will accept illegal self-closed tags, like <p />, and render them as you probably expect. But for an author, that page would not be valid HTML5. (More importantly, the DOM tree you get from using this kind of illegal syntax can be seriously screwed up; self-closed <span /> tags, for example, tend to mess things up a lot).

(In the unusual case that your server knows how to send XHTML files as an XML MIME type, the page needs to conform to the XHTML DTD and XML syntax. That means self-closing tags are required for those elements defined as such.)

Null check in an enhanced for loop

I have modified the above answer, so you don't need to cast from Object

public static <T> List<T> safeClient( List<T> other ) {
            return other == null ? Collections.EMPTY_LIST : other;
}

and then simply call the List by

for (MyOwnObject ownObject : safeClient(someList)) {
    // do whatever
}

Explaination: MyOwnObject: If List<Integer> then MyOwnObject will be Integer in this case.

How do I remove javascript validation from my eclipse project?

Go to Windows->Preferences->Validation.

There would be a list of validators with checkbox options for Manual & Build, go and individually disable the javascript validator there.

If you select the Suspend All Validators checkbox on the top it doesn't necessarily take affect.

How do you express binary literals in Python?

0 in the start here specifies that the base is 8 (not 10), which is pretty easy to see:

>>> int('010101', 0)
4161

If you don't start with a 0, then python assumes the number is base 10.

>>> int('10101', 0)
10101

How do you say not equal to in Ruby?

Yes. In Ruby the not equal to operator is:

!=

You can get a full list of ruby operators here: https://www.tutorialspoint.com/ruby/ruby_operators.htm.

var functionName = function() {} vs function functionName() {}

An illustration of when to prefer the first method to the second one is when you need to avoid overriding a function's previous definitions.

With

if (condition){
    function myfunction(){
        // Some code
    }
}

, this definition of myfunction will override any previous definition, since it will be done at parse-time.

While

if (condition){
    var myfunction = function (){
        // Some code
    }
}

does the correct job of defining myfunction only when condition is met.

Putting a simple if-then-else statement on one line

count = 0 if count == N else N+1

- the ternary operator. Although I'd say your solution is more readable than this.

Syntax of for-loop in SQL Server

While Loop example in T-SQL which list current month's beginning to end date.

DECLARE @Today DATE= GETDATE() ,
@StartOfMonth DATE ,
@EndOfMonth DATE;

DECLARE @DateList TABLE ( DateLabel VARCHAR(10) );
SET @EndOfMonth = EOMONTH(GETDATE());
SET @StartOfMonth = DATEFROMPARTS(YEAR(@Today), MONTH(@Today), 1);

WHILE @StartOfMonth <= @EndOfMonth
BEGIN
    INSERT  INTO @DateList
    VALUES  ( @StartOfMonth );
    SET @StartOfMonth = DATEADD(DAY, 1, @StartOfMonth);
END;

SELECT  DateLabel
FROM    @DateList;  

SQL Server - Case Statement

Like so

DECLARE @t INT=1

SELECT CASE
            WHEN @t>0 THEN
                CASE
                    WHEN @t=1 THEN 'one'
                    ELSE 'not one'
                END
            ELSE 'less than one'
        END

EDIT: After looking more at the question, I think the best option is to create a function that calculates the value. That way, if you end up having multiple places where the calculation needs done, you only have one point to maintain the logic.

Ternary operator (?:) in Bash

Here are some options:

1- Use if then else in one line, it is possible.

if [[ "$2" == "raiz" ]] || [[ "$2" == '.' ]]; then pasta=''; else pasta="$2"; fi

2- Write a function like this:

 # Once upon a time, there was an 'iif' function in MS VB ...

function iif(){
  # Echoes $2 if 1,banana,true,etc and $3 if false,null,0,''
  case $1 in ''|false|FALSE|null|NULL|0) echo $3;;*) echo $2;;esac
}

use inside script like this

result=`iif "$expr" 'yes' 'no'`

# or even interpolating:
result=`iif "$expr" "positive" "negative, because $1 is not true"` 

3- Inspired in the case answer, a more flexible and one line use is:

 case "$expr" in ''|false|FALSE|null|NULL|0) echo "no...$expr";;*) echo "yep $expr";;esac

 # Expression can be something like:     
   expr=`expr "$var1" '>' "$var2"`

What is the C# Using block and why should I use it?

From MSDN:

C#, through the .NET Framework common language runtime (CLR), automatically releases the memory used to store objects that are no longer required. The release of memory is non-deterministic; memory is released whenever the CLR decides to perform garbage collection. However, it is usually best to release limited resources such as file handles and network connections as quickly as possible.

The using statement allows the programmer to specify when objects that use resources should release them. The object provided to the using statement must implement the IDisposable interface. This interface provides the Dispose method, which should release the object's resources.

In other words, the using statement tells .NET to release the object specified in the using block once it is no longer needed.

Why does the program give "illegal start of type" error?

You have a misplaced closing brace before the return statement.

Prolog "or" operator, query

Just another viewpoint. Performing an "or" in Prolog can also be done with the "disjunct" operator or semi-colon:

registered(X, Y) :-
    X = ct101; X = ct102; X = ct103.

For a fuller explanation:

Predicate control in Prolog

Unexpected token }

You have endless loop in place:

function save() {
    var filename = id('filename').value;
    var name = id('name').value;
    var text = id('text').value;
    save(filename, name, text);
}

No idea what you're trying to accomplish with that endless loop but first of all get rid of it and see if things are working.

Why is NULL undeclared?

Do use NULL. It is just #defined as 0 anyway and it is very useful to semantically distinguish it from the integer 0.

There are problems with using 0 (and hence NULL). For example:

void f(int);
void f(void*);

f(0); // Ambiguous. Calls f(int).

The next version of C++ (C++0x) includes nullptr to fix this.

f(nullptr); // Calls f(void*).

Putting an if-elif-else statement on one line?

No, it's not possible (at least not with arbitrary statements), nor is it desirable. Fitting everything on one line would most likely violate PEP-8 where it is mandated that lines should not exceed 80 characters in length.

It's also against the Zen of Python: "Readability counts". (Type import this at the Python prompt to read the whole thing).

You can use a ternary expression in Python, but only for expressions, not for statements:

>>> a = "Hello" if foo() else "Goodbye"

Edit:

Your revised question now shows that the three statements are identical except for the value being assigned. In that case, a chained ternary operator does work, but I still think that it's less readable:

>>> i=100
>>> a = 1 if i<100 else 2 if i>100 else 0
>>> a
0
>>> i=101
>>> a = 1 if i<100 else 2 if i>100 else 0
>>> a
2
>>> i=99
>>> a = 1 if i<100 else 2 if i>100 else 0
>>> a
1

Why does ++[[]][+[]]+[+[]] return the string "10"?

  1. Unary plus given string converts to number
  2. Increment operator given string converts and increments by 1
  3. [] == ''. Empty String
  4. +'' or +[] evaluates 0.

    ++[[]][+[]]+[+[]] = 10 
    ++[''][0] + [0] : First part is gives zeroth element of the array which is empty string 
    1+0 
    10
    

C# Syntax - Split String into Array by Comma, Convert To Generic List, and Reverse Order

The problem is that you're calling List<T>.Reverse() which returns void.

You could either do:

List<string> names = "Tom,Scott,Bob".Split(',').ToList<string>();
names.Reverse();

or:

IList<string> names = "Tom,Scott,Bob".Split(',').Reverse().ToList<string>();

The latter is more expensive, as reversing an arbitrary IEnumerable<T> involves buffering all of the data and then yielding it all - whereas List<T> can do all the reversing "in-place". (The difference here is that it's calling the Enumerable.Reverse<T>() extension method, instead of the List<T>.Reverse() instance method.)

More efficient yet, you could use:

string[] namesArray = "Tom,Scott,Bob".Split(',');
List<string> namesList = new List<string>(namesArray.Length);
namesList.AddRange(namesArray);
namesList.Reverse();

This avoids creating any buffers of an inappropriate size - at the cost of taking four statements where one will do... As ever, weigh up readability against performance in the real use case.

JQuery .hasClass for multiple values in an if statement

Try this:

if ($('html').hasClass('class1 class2')) {

// do stuff 

}

How to concatenate string variables in Bash

Safer way:

a="AAAAAAAAAAAA"
b="BBBBBBBBBBBB"
c="CCCCCCCCCCCC"
d="DD DD"
s="${a}${b}${c}${d}"
echo "$s"
AAAAAAAAAAAABBBBBBBBBBBBCCCCCCCCCCCCDD DD

Strings containing spaces can become part of command, use "$XXX" and "${XXX}" to avoid these errors.

Plus take a look at other answer about +=

What does print(... sep='', '\t' ) mean?

The sep='\t' can be use in many forms, for example if you want to read tab separated value: Example: I have a dataset tsv = tab separated value NOT comma separated value df = pd.read_csv('gapminder.tsv'). when you try to read this, it will give you an error because you have tab separated value not csv. so you need to give read csv a different parameter called sep='\t'.

Now you can read: df = pd.read_csv('gapminder.tsv, sep='\t'), with this you can read the it.

Printing variables in Python 3.4

The syntax has changed in that print is now a function. This means that the % formatting needs to be done inside the parenthesis:1

print("%d. %s appears %d times." % (i, key, wordBank[key]))

However, since you are using Python 3.x., you should actually be using the newer str.format method:

print("{}. {} appears {} times.".format(i, key, wordBank[key]))

Though % formatting is not officially deprecated (yet), it is discouraged in favor of str.format and will most likely be removed from the language in a coming version (Python 4 maybe?).


1Just a minor note: %d is the format specifier for integers, not %s.

Single quotes vs. double quotes in C or C++

Double quotes are for string literals, e.g.:

char str[] = "Hello world";

Single quotes are for single character literals, e.g.:

char c = 'x';

EDIT As David stated in another answer, the type of a character literal is int.

C# binary literals

If you look at the language feature implementation status of the .NET Compiler Platform ("Roslyn") you can clearly see that in C# 6.0 this is a planned feature, so in the next release we can do it in the usual way.

Binary literal status

Awk if else issues

Try the code

awk '{s=($3==0)?"-":$3/$4; print s}'

Effects of the extern keyword on C functions

The extern keyword takes on different forms depending on the environment. If a declaration is available, the extern keyword takes the linkage as that specified earlier in the translation unit. In the absence of any such declaration, extern specifies external linkage.

static int g();
extern int g(); /* g has internal linkage */

extern int j(); /* j has tentative external linkage */

extern int h();
static int h(); /* error */

Here are the relevant paragraphs from the C99 draft (n1256):

6.2.2 Linkages of identifiers

[...]

4 For an identifier declared with the storage-class specifier extern in a scope in which a prior declaration of that identifier is visible,23) if the prior declaration specifies internal or external linkage, the linkage of the identifier at the later declaration is the same as the linkage specified at the prior declaration. If no prior declaration is visible, or if the prior declaration specifies no linkage, then the identifier has external linkage.

5 If the declaration of an identifier for a function has no storage-class specifier, its linkage is determined exactly as if it were declared with the storage-class specifier extern. If the declaration of an identifier for an object has file scope and no storage-class specifier, its linkage is external.

What Does This Mean in PHP -> or =>

-> is used to call a method, or access a property, on the object of a class

=> is used to assign values to the keys of an array

E.g.:

    $ages = array("Peter"=>32, "Quagmire"=>30, "Joe"=>34, 1=>2); 

And since PHP 7.4+ the operator => is used too for the added arrow functions, a more concise syntax for anonymous functions.

Insert into ... values ( SELECT ... FROM ... )

Just use parenthesis for SELECT clause into INSERT. For example like this :

INSERT INTO Table1 (col1, col2, your_desired_value_from_select_clause, col3)
VALUES (
   'col1_value', 
   'col2_value',
   (SELECT col_Table2 FROM Table2 WHERE IdTable2 = 'your_satisfied_value_for_col_Table2_selected'),
   'col3_value'
);

Is there a goto statement in Java?

An example of how to use "continue" labels in Java is:

public class Label {
    public static void main(String[] args) {
        int temp = 0;
        out: // label
        for (int i = 0; i < 3; ++i) {
            System.out.println("I am here");
            for (int j = 0; j < 20; ++j) {
                if(temp==0) {
                    System.out.println("j: " + j);
                    if (j == 1) {
                        temp = j;
                        continue out; // goto label "out"
                    }
                }
            }
        }
        System.out.println("temp = " + temp);
    }
}

Results:

I am here // i=0
j: 0
j: 1
I am here // i=1
I am here // i=2
temp = 1

1064 error in CREATE TABLE ... TYPE=MYISAM

Try the below query

CREATE TABLE card_types (
  card_type_id int(11) NOT NULL auto_increment,
  name varchar(50) NOT NULL default '',
  PRIMARY KEY  (card_type_id),
) ENGINE = MyISAM ;

How to make "if not true condition"?

try

if ! grep -q sysa /etc/passwd ; then

grep returns true if it finds the search target, and false if it doesn't.

So NOT false == true.

if evaluation in shells are designed to be very flexible, and many times doesn't require chains of commands (as you have written).

Also, looking at your code as is, your use of the $( ... ) form of cmd-substitution is to be commended, but think about what is coming out of the process. Try echo $(cat /etc/passwd | grep "sysa") to see what I mean. You can take that further by using the -c (count) option to grep and then do if ! [ $(grep -c "sysa" /etc/passwd) -eq 0 ] ; then which works but is rather old school.

BUT, you could use the newest shell features (arithmetic evaluation) like

if ! (( $(grep -c "sysa" /etc/passwd) == 0 )) ; then ...`

which also gives you the benefit of using the c-lang based comparison operators, ==,<,>,>=,<=,% and maybe a few others.

In this case, per a comment by Orwellophile, the arithmetic evaluation can be pared down even further, like

if ! (( $(grep -c "sysa" /etc/passwd) )) ; then ....

OR

if (( ! $(grep -c "sysa" /etc/passwd) )) ; then ....

Finally, there is an award called the Useless Use of Cat (UUOC). :-) Some people will jump up and down and cry gothca! I'll just say that grep can take a file name on its cmd-line, so why invoke extra processes and pipe constructions when you don't have to? ;-)

I hope this helps.

IndentationError: unexpected indent error

While the indentation errors are obvious in the StackOverflow page, they may not be in your editor. You have a mix of different indentation types here, 1, 4 and 8 spaces. You should always use four spaces for indentation, as per PEP8. You should also avoid mixing tabs and spaces.

I also recommend that you try to run your script using the '-tt' command-line option to determine when you accidentally mix tabs and spaces. Of course any decent editor will be able to highlight tabs versus spaces (such as Vim's 'list' option).

What does operator "dot" (.) mean?

There is a whole page in the MATLAB documentation dedicated to this topic: Array vs. Matrix Operations. The gist of it is below:

MATLAB® has two different types of arithmetic operations: array operations and matrix operations. You can use these arithmetic operations to perform numeric computations, for example, adding two numbers, raising the elements of an array to a given power, or multiplying two matrices.

Matrix operations follow the rules of linear algebra. By contrast, array operations execute element by element operations and support multidimensional arrays. The period character (.) distinguishes the array operations from the matrix operations. However, since the matrix and array operations are the same for addition and subtraction, the character pairs .+ and .- are unnecessary.

What does "while True" mean in Python?

In this context, I suppose it could be interpreted as

do
...
while cmd  != 'e' 

how to reference a YAML "setting" from elsewhere in the same YAML file?

I have wrote my own library on Python to expand variables being loaded from directories with a hierarchy like:

/root
 |
 +- /proj1
     |
     +- config.yaml
     |
     +- /proj2
         |
         +- config.yaml
         |
         ... and so on ...

The key difference here is that the expansion must be applied only after all the config.yaml files is loaded, where the variables from the next file can override the variables from the previous, so the pseudocode should look like this:

env = YamlEnv()
env.load('/root/proj1/config.yaml')
env.load('/root/proj1/proj2/config.yaml')
...
env.expand()

As an additional option the xonsh script can export the resulting variables into environment variables (see the yaml_update_global_vars function).

The scripts:

https://sourceforge.net/p/contools/contools/HEAD/tree/trunk/Scripts/Tools/cmdoplib.yaml.py https://sourceforge.net/p/contools/contools/HEAD/tree/trunk/Scripts/Tools/cmdoplib.yaml.xsh

Pros:

  • simple, does not support recursion and nested variables
  • can replace an undefined variable to a placeholder (${MYUNDEFINEDVAR} -> *$/{MYUNDEFINEDVAR})
  • can expand a reference from environment variable (${env:MYVAR})
  • can replace all \\ to / in a path variable (${env:MYVAR:path})

Cons:

  • does not support nested variables, so can not expand values in nested dictionaries (something like ${MYSCOPE.MYVAR} is not implemented)
  • does not detect expansion recursion, including recursion after a placeholder put

jquery variable syntax

self and $self aren't the same. The former is the object pointed to by "this" and the latter a jQuery object whose "scope" is the object pointed to by "this". Similarly, $body isn't the body DOM element but the jQuery object whose scope is the body element.

Double quotes within php script echo

You need to escape ", so it won't be interpreted as end of string. Use \ to escape it:

echo "<script>$('#edit_errors').html('<h3><em><font color=\"red\">Please Correct Errors Before Proceeding</font></em></h3>')</script>";

Read more: strings and escape sequences

How do I perform a GROUP BY on an aliased column in MS-SQL Server?

You pass the expression you want to group by rather than the alias

SELECT       LastName + ', ' + FirstName AS 'FullName'
FROM         customers
GROUP BY      LastName + ', ' + FirstName

How do I select an element that has a certain class?

h2.myClass refers to all h2 with class="myClass".

.myClass h2 refers to all h2 that are children of (i.e. nested in) elements with class="myClass".

If you want the h2 in your HTML to appear blue, change the CSS to the following:

.myClass h2 {
    color: blue;
}

If you want to be able to reference that h2 by a class rather than its tag, you should leave the CSS as it is and give the h2 a class in the HTML:

<h2 class="myClass">This header should be BLUE to match the element.class selector</h2>

How do I iterate over a range of numbers defined by variables in Bash?

Replace {} with (( )):

tmpstart=0;
tmpend=4;

for (( i=$tmpstart; i<=$tmpend; i++ )) ; do 
echo $i ;
done

Yields:

0
1
2
3
4

How to break out of a loop from inside a switch?

AFAIK there is no "double break" or similar construct in C++. The closest would be a goto - which, while it has a bad connotation to its name, exists in the language for a reason - as long as it's used carefully and sparingly, it's a viable option.

Java generics - why is "extends T" allowed but not "implements T"?

There is no semantic difference in the generic constraint language between whether a class 'implements' or 'extends'. The constraint possibilities are 'extends' and 'super' - that is, is this class to operate with assignable to that other one (extends), or is this class assignable from that one (super).

How do I break a string in YAML over multiple lines?

None of the above solutions worked for me, in a YAML file within a Jekyll project. After trying many options, I realized that an HTML injection with <br> might do as well, since in the end everything is rendered to HTML:

name: | In a village of La Mancha <br> whose name I don't <br> want to remember.

At least it works for me. No idea on the problems associated to this approach.

Accessing dict keys like an attribute?

Just to add some variety to the answer, sci-kit learn has this implemented as a Bunch:

class Bunch(dict):                                                              
    """ Scikit Learn's container object                                         

    Dictionary-like object that exposes its keys as attributes.                 
    >>> b = Bunch(a=1, b=2)                                                     
    >>> b['b']                                                                  
    2                                                                           
    >>> b.b                                                                     
    2                                                                           
    >>> b.c = 6                                                                 
    >>> b['c']                                                                  
    6                                                                           
    """                                                                         

    def __init__(self, **kwargs):                                               
        super(Bunch, self).__init__(kwargs)                                     

    def __setattr__(self, key, value):                                          
        self[key] = value                                                       

    def __dir__(self):                                                          
        return self.keys()                                                      

    def __getattr__(self, key):                                                 
        try:                                                                    
            return self[key]                                                    
        except KeyError:                                                        
            raise AttributeError(key)                                           

    def __setstate__(self, state):                                              
        pass                       

All you need is to get the setattr and getattr methods - the getattr checks for dict keys and the moves on to checking for actual attributes. The setstaet is a fix for fix for pickling/unpickling "bunches" - if inerested check https://github.com/scikit-learn/scikit-learn/issues/6196

What does '&' do in a C++ declaration?

string * and string& differ in a couple of ways. First of all, the pointer points to the address location of the data. The reference points to the data. If you had the following function:

int foo(string *param1);

You would have to check in the function declaration to make sure that param1 pointed to a valid location. Comparatively:

int foo(string &param1);

Here, it is the caller's responsibility to make sure the pointed to data is valid. You can't pass a "NULL" value, for example, int he second function above.

With regards to your second question, about the method return values being a reference, consider the following three functions:

string &foo();
string *foo();
string foo();

In the first case, you would be returning a reference to the data. If your function declaration looked like this:

string &foo()
{
    string localString = "Hello!";
    return localString;
}

You would probably get some compiler errors, since you are returning a reference to a string that was initialized in the stack for that function. On the function return, that data location is no longer valid. Typically, you would want to return a reference to a class member or something like that.

The second function above returns a pointer in actual memory, so it would stay the same. You would have to check for NULL-pointers, though.

Finally, in the third case, the data returned would be copied into the return value for the caller. So if your function was like this:

string foo()
{
    string localString = "Hello!";
    return localString;
}

You'd be okay, since the string "Hello" would be copied into the return value for that function, accessible in the caller's memory space.

Else clause on Python while statement

Else is executed if while loop did not break.

I kinda like to think of it with a 'runner' metaphor.

The "else" is like crossing the finish line, irrelevant of whether you started at the beginning or end of the track. "else" is only not executed if you break somewhere in between.

runner_at = 0 # or 10 makes no difference, if unlucky_sector is not 0-10
unlucky_sector = 6
while runner_at < 10:
    print("Runner at: ", runner_at)
    if runner_at == unlucky_sector:
        print("Runner fell and broke his foot. Will not reach finish.")
        break
    runner_at += 1
else:
    print("Runner has finished the race!") # Not executed if runner broke his foot.

Main use cases is using this breaking out of nested loops or if you want to run some statements only if loop didn't break somewhere (think of breaking being an unusual situation).

For example, the following is a mechanism on how to break out of an inner loop without using variables or try/catch:

for i in [1,2,3]:
    for j in ['a', 'unlucky', 'c']:
        print(i, j)
        if j == 'unlucky':
            break
    else: 
        continue  # Only executed if inner loop didn't break.
    break         # This is only reached if inner loop 'breaked' out since continue didn't run. 

print("Finished")
# 1 a
# 1 b
# Finished

Java "?" Operator for checking null - What is it? (Not Ternary!)

I'm not sure this would even work; if, say, the person reference was null, what would the runtime replace it with? A new Person? That would require the Person to have some default initialization that you'd expect in this case. You may avoid null reference exceptions but you'd still get unpredictable behavior if you didn't plan for these types of setups.

The ?? operator in C# might be best termed the "coalesce" operator; you can chain several expressions and it will return the first that isn't null. Unfortunately, Java doesn't have it. I think the best you could do is use the ternary operator to perform null checks and evaluate an alternative to the entire expression if any member in the chain is null:

return person == null ? "" 
    : person.getName() == null ? "" 
        : person.getName().getGivenName();

You could also use try-catch:

try
{
   return person.getName().getGivenName();
}
catch(NullReferenceException)
{
   return "";
}

What does += mean in Python?

FYI: it looks like you might have an infinite loop in your example...

if cnt > 0 and len(aStr) > 1:
    while cnt > 0:                  
        aStr = aStr[1:]+aStr[0]
        cnt += 1
  • a condition of entering the loop is that cnt is greater than 0
  • the loop continues to run as long as cnt is greater than 0
  • each iteration of the loop increments cnt by 1

The net result is that cnt will always be greater than 0 and the loop will never exit.

Update Query with INNER JOIN between tables in 2 different databases on 1 server

It is explained here http://erabhinavrana.blogspot.in/2014/01/how-to-execute-update-query-by-applying.html

It also has other useful code snippets which are commonly used.

update <dbname of 1st table>.<table name of 1st table> A INNER JOIN <dbname of 2nd table>.<table name of 2nd table> RA ON A.<field name of table 1>=RA.<field name of table 2> SET A.<field name of table 1 to be updated>=RA.<field name of table 2 to set value in table 1>

Replace data in <> with your appropriate values.

That's It. source:

http://www.dynamic-coders.com/how-to-update-two-different-tables-in-different-databases-on-same-server

In Ruby, how do I skip a loop in a .each loop, similar to 'continue'

next - it's like return, but for blocks! (So you can use this in any proc/lambda too.)

That means you can also say next n to "return" n from the block. For instance:

puts [1, 2, 3].map do |e|
  next 42 if e == 2
  e
end.inject(&:+)

This will yield 46.

Note that return always returns from the closest def, and never a block; if there's no surrounding def, returning is an error.

Using return from within a block intentionally can be confusing. For instance:

def my_fun
  [1, 2, 3].map do |e|
    return "Hello." if e == 2
    e
  end
end

my_fun will result in "Hello.", not [1, "Hello.", 2], because the return keyword pertains to the outer def, not the inner block.

How to normalize a 2-dimensional numpy array in python less verbose?

You could use built-in numpy function: np.linalg.norm(a, axis = 1, keepdims = True)

What's the difference between 'int?' and 'int' in C#?

int? is shorthand for Nullable<int>.

This may be the post you were looking for.

What is the difference between '/' and '//' when used for division?

The double slash, //, is floor division:

>>> 7//3
2

What does the question mark and the colon (?: ternary operator) mean in objective-c?

This is part of C, so it's not Objective-C specific. Here's a translation into an if statement:

if (inPseudoEditMode)
    label.frame = kLabelIndentedRec;
else
    label.frame = kLabelRect;

Concatenate two string literals

In case 1, because of order of operations you get:

(hello + ", world") + "!" which resolves to hello + "!" and finally to hello

In case 2, as James noted, you get:

("Hello" + ", world") + exclam which is the concat of 2 string literals.

Hope it's clear :)

What is the result of % in Python?

Somewhat off topic, the % is also used in string formatting operations like %= to substitute values into a string:

>>> x = 'abc_%(key)s_'
>>> x %= {'key':'value'}
>>> x 
'abc_value_'

Again, off topic, but it seems to be a little documented feature which took me awhile to track down, and I thought it was related to Pythons modulo calculation for which this SO page ranks highly.

How do I pass multiple parameters into a function in PowerShell?

If you don't know (or care) how many arguments you will be passing to the function, you could also use a very simple approach like;

Code:

function FunctionName()
{
    Write-Host $args
}

That would print out all arguments. For example:

FunctionName a b c 1 2 3

Output

a b c 1 2 3

I find this particularly useful when creating functions that use external commands that could have many different (and optional) parameters, but relies on said command to provide feedback on syntax errors, etc.

Here is a another real-world example (creating a function to the tracert command, which I hate having to remember the truncated name);

Code:

Function traceroute
{
    Start-Process -FilePath "$env:systemroot\system32\tracert.exe" -ArgumentList $args -NoNewWindow
}

Single vs Double quotes (' vs ")

I use " as a top-tier and ' as a second tier, as I imagine most people do. For example

<a href="#" onclick="alert('Clicked!');">Click Me!</a>

In that example, you must use both, it is unavoidable.

Why is list initialization (using curly braces) better than the alternatives?

Basically copying and pasting from Bjarne Stroustrup's "The C++ Programming Language 4th Edition":

List initialization does not allow narrowing (§iso.8.5.4). That is:

  • An integer cannot be converted to another integer that cannot hold its value. For example, char to int is allowed, but not int to char.
  • A floating-point value cannot be converted to another floating-point type that cannot hold its value. For example, float to double is allowed, but not double to float.
  • A floating-point value cannot be converted to an integer type.
  • An integer value cannot be converted to a floating-point type.

Example:

void fun(double val, int val2) {

    int x2 = val;    // if val == 7.9, x2 becomes 7 (bad)

    char c2 = val2;  // if val2 == 1025, c2 becomes 1 (bad)

    int x3 {val};    // error: possible truncation (good)

    char c3 {val2};  // error: possible narrowing (good)

    char c4 {24};    // OK: 24 can be represented exactly as a char (good)

    char c5 {264};   // error (assuming 8-bit chars): 264 cannot be 
                     // represented as a char (good)

    int x4 {2.0};    // error: no double to int value conversion (good)

}

The only situation where = is preferred over {} is when using auto keyword to get the type determined by the initializer.

Example:

auto z1 {99};   // z1 is an int
auto z2 = {99}; // z2 is std::initializer_list<int>
auto z3 = 99;   // z3 is an int

Conclusion

Prefer {} initialization over alternatives unless you have a strong reason not to.

Check file uploaded is in csv format

There are a lot of possible MIME types for CSV files, depending on the user's OS and browser version.

This is how I currently validate the MIME types of my CSV files:

$csv_mimetypes = array(
    'text/csv',
    'text/plain',
    'application/csv',
    'text/comma-separated-values',
    'application/excel',
    'application/vnd.ms-excel',
    'application/vnd.msexcel',
    'text/anytext',
    'application/octet-stream',
    'application/txt',
);

if (in_array($_FILES['upload']['type'], $csv_mimetypes)) {
    // possible CSV file
    // could also check for file content at this point
}

Difference between if () { } and if () : endif;

I think that it's particularly clearer when you're using a mix of ifs, fors and foreaches in view scripts:

<?php if ( $this->hasIterable ): ?>
    <h2>Iterable</h2>
    <ul>
    <?php foreach ( $this->iterable as $key => $val ):?>
        <?php for ( $i = 0; $i <= $val; $i++ ): ?>
        <li><?php echo $key ?></li>
        <?php endfor; ?>
    <?php endforeach; ?>
    </ul>
<?php elseif ( $this->hasScalar ): ?>
    <h2>Scalar</h2>
    <?php for ( $i = 0; $i <= $this->scalar; $i++ ): ?>
    <p>Foo = Bar</p>
    <?php endfor; ?>
<?php else: ?>
    <h2>Other</h2>
    <?php if ( $this->otherVal === true ): ?>
    <p>Spam</p>
    <?php else: ?>  
    <p>Eggs</p>  
    <?php endif; ?>
<?php endif; ?>

as opposed to:

<?php if ( $this->hasIterable ){ ?>
    <h2>Iterable</h2>
    <ul>
    <?php foreach ( $this->iterable as $key => $val ){?>
        <?php for ( $i = 0; $i <= $val; $i++ ){ ?>
        <li><?php echo $key ?></li>
        <?php } ?>
    <?php } ?>
    </ul>
<?php } elseif ( $this->hasScalar ){ ?>
    <h2>Scalar</h2>
    <?php for ( $i = 0; $i <= $this->scalar; $i++ ){ ?>
    <p>Foo = Bar</p>
    <?php } ?>
<?php } else { ?>
    <h2>Other</h2>
    <?php if ( $this->otherVal === true ){ ?>
    <p>Spam</p>
    <?php } else { ?>  
    <p>Eggs</p>  
    <?php } ?>
<?php } ?>

This is especially useful for long control statements where you might not be able to see the top declaration from the bottom brace.

How to throw an exception in C?

As mentioned in numerous threads, the "standard" way of doing this is using setjmp/longjmp. I posted yet another such solution to https://github.com/psevon/exceptions-and-raii-in-c This is to my knowledge the only solution that relies on automatic cleanup of allocated resources. It implements unique and shared smartpointers, and allows intermediate functions to let exceptions pass through without catching and still have their locally allocated resources cleaned up properly.

JavaScript property access: dot notation vs. brackets?

Generally speaking, they do the same job.
Nevertheless, the bracket notation gives you the opportunity to do stuff that you can't do with dot notation, like

var x = elem["foo[]"]; // can't do elem.foo[];

This can be extended to any property containing special characters.

-bash: syntax error near unexpected token `newline'

The characters '<', and '>', are to indicate a place-holder, you should remove them to read:

php /usr/local/solusvm/scripts/pass.php --type=admin --comm=change --username=ADMINUSERNAME

What does @@variable mean in Ruby?

@ and @@ in modules also work differently when a class extends or includes that module.

So given

module A
    @a = 'module'
    @@a = 'module'

    def get1
        @a          
    end     

    def get2
        @@a         
    end     

    def set1(a) 
        @a = a      
    end     

    def set2(a) 
        @@a = a     
    end     

    def self.set1(a)
        @a = a      
    end     

    def self.set2(a)
        @@a = a     
    end     
end 

Then you get the outputs below shown as comments

class X
    extend A

    puts get1.inspect # nil
    puts get2.inspect # "module"

    @a = 'class' 
    @@a = 'class' 

    puts get1.inspect # "class"
    puts get2.inspect # "module"

    set1('set')
    set2('set')

    puts get1.inspect # "set" 
    puts get2.inspect # "set" 

    A.set1('sset')
    A.set2('sset')

    puts get1.inspect # "set" 
    puts get2.inspect # "sset"
end 

class Y
    include A

    def doit
        puts get1.inspect # nil
        puts get2.inspect # "module"

        @a = 'class'
        @@a = 'class'

        puts get1.inspect # "class"
        puts get2.inspect # "class"

        set1('set')
        set2('set')

        puts get1.inspect # "set"
        puts get2.inspect # "set"

        A.set1('sset')
        A.set2('sset')

        puts get1.inspect # "set"
        puts get2.inspect # "sset"
    end
end

Y.new.doit

So use @@ in modules for variables you want common to all their uses, and use @ in modules for variables you want separate for every use context.

YAML: Do I need quotes for strings in YAML?

I had this concern when working on a Rails application with Docker.

My most preferred approach is to generally not use quotes. This includes not using quotes for:

  • variables like ${RAILS_ENV}
  • values separated by a colon (:) like postgres-log:/var/log/postgresql
  • other strings values

I, however, use double-quotes for integer values that need to be converted to strings like:

  • docker-compose version like version: "3.8"
  • port numbers like "8080:8080"

However, for special cases like booleans, floats, integers, and other cases, where using double-quotes for the entry values could be interpreted as strings, please do not use double-quotes.

Here's a sample docker-compose.yml file to explain this concept:

version: "3"

services:
  traefik:
    image: traefik:v2.2.1
    command:
      - --api.insecure=true # Don't do that in production
      - --providers.docker=true
      - --providers.docker.exposedbydefault=false
      - --entrypoints.web.address=:80
    ports:
      - "80:80"
      - "8080:8080"
    volumes:
      - /var/run/docker.sock:/var/run/docker.sock:ro

That's all.

I hope this helps

How can I fix MySQL error #1064?

For my case, I was trying to execute procedure code in MySQL, and due to some issue with server in which Server can't figure out where to end the statement I was getting Error Code 1064. So I wrapped the procedure with custom DELIMITER and it worked fine.

For example, Before it was:

DROP PROCEDURE IF EXISTS getStats;
CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
BEGIN
    /*Procedure Code Here*/
END;

After putting DELIMITER it was like this:

DROP PROCEDURE IF EXISTS getStats;
DELIMITER $$
CREATE PROCEDURE `getStats` (param_id INT, param_offset INT, param_startDate datetime, param_endDate datetime)
BEGIN
    /*Procedure Code Here*/
END;
$$
DELIMITER ;

How can I do a line break (line continuation) in Python?

If you want to break your line because of a long literal string, you can break that string into pieces:

long_string = "a very long string"
print("a very long string")

will be replaced by

long_string = (
  "a "
  "very "
  "long "
  "string"
)
print(
  "a "
  "very "
  "long "
  "string"
)

Output for both print statements:

a very long string

Notice the parenthesis in the affectation.

Notice also that breaking literal strings into pieces allows to use the literal prefix only on parts of the string and mix the delimiters:

s = (
  '''2+2='''
  f"{2+2}"
)

Python: One Try Multiple Except

Yes, it is possible.

try:
   ...
except FirstException:
   handle_first_one()

except SecondException:
   handle_second_one()

except (ThirdException, FourthException, FifthException) as e:
   handle_either_of_3rd_4th_or_5th()

except Exception:
   handle_all_other_exceptions()

See: http://docs.python.org/tutorial/errors.html

The "as" keyword is used to assign the error to a variable so that the error can be investigated more thoroughly later on in the code. Also note that the parentheses for the triple exception case are needed in python 3. This page has more info: Catch multiple exceptions in one line (except block)

Why avoid increment ("++") and decrement ("--") operators in JavaScript?

The "pre" and "post" nature of increment and decrement operators can tend to be confusing for those who are not familiar with them; that's one way in which they can be tricky.

What does the star operator mean, in a function call?

In a function call the single star turns a list into seperate arguments (e.g. zip(*x) is the same as zip(x1,x2,x3) if x=[x1,x2,x3]) and the double star turns a dictionary into seperate keyword arguments (e.g. f(**k) is the same as f(x=my_x, y=my_y) if k = {'x':my_x, 'y':my_y}.

In a function definition it's the other way around: the single star turns an arbitrary number of arguments into a list, and the double start turns an arbitrary number of keyword arguments into a dictionary. E.g. def foo(*x) means "foo takes an arbitrary number of arguments and they will be accessible through the list x (i.e. if the user calls foo(1,2,3), x will be [1,2,3])" and def bar(**k) means "bar takes an arbitrary number of keyword arguments and they will be accessible through the dictionary k (i.e. if the user calls bar(x=42, y=23), k will be {'x': 42, 'y': 23})".

No Multiline Lambda in Python: Why not?

This is generally very ugly (but sometimes the alternatives are even more ugly), so a workaround is to make a braces expression:

lambda: (
    doFoo('abc'),
    doBar(123),
    doBaz())

It won't accept any assignments though, so you'll have to prepare data beforehand. The place I found this useful is the PySide wrapper, where you sometimes have short callbacks. Writing additional member functions would be even more ugly. Normally you won't need this.

Example:

pushButtonShowDialog.clicked.connect(
    lambda: (
    field1.clear(),
    spinBox1.setValue(0),
    diag.show())

Difference between single and double quotes in Bash

There is a clear distinction between the usage of ' ' and " ".

When ' ' is used around anything, there is no "transformation or translation" done. It is printed as it is.

With " ", whatever it surrounds, is "translated or transformed" into its value.

By translation/ transformation I mean the following: Anything within the single quotes will not be "translated" to their values. They will be taken as they are inside quotes. Example: a=23, then echo '$a' will produce $a on standard output. Whereas echo "$a" will produce 23 on standard output.

Is double square brackets [[ ]] preferable over single square brackets [ ] in Bash?

[[ ]] has more features - I suggest you take a look at the Advanced Bash Scripting Guide for more info, specifically the extended test command section in Chapter 7. Tests.

Incidentally, as the guide notes, [[ ]] was introduced in ksh88 (the 1988 version of the Korn shell).

C++ array initialization

You can declare the array in C++ in these type of ways. If you know the array size then you should declare the array for: integer: int myArray[array_size]; Double: double myArray[array_size]; Char and string : char myStringArray[array_size]; The difference between char and string is as follows

char myCharArray[6]={'a','b','c','d','e','f'};
char myStringArray[6]="abcdef";

If you don't know the size of array then you should leave the array blank like following.

integer: int myArray[array_size];

Double: double myArray[array_size];

What does 'wb' mean in this code, using Python?

The wb indicates that the file is opened for writing in binary mode.

When writing in binary mode, Python makes no changes to data as it is written to the file. In text mode (when the b is excluded as in just w or when you specify text mode with wt), however, Python will encode the text based on the default text encoding. Additionally, Python will convert line endings (\n) to whatever the platform-specific line ending is, which would corrupt a binary file like an exe or png file.

Text mode should therefore be used when writing text files (whether using plain text or a text-based format like CSV), while binary mode must be used when writing non-text files like images.

References:

https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-files https://docs.python.org/3/library/functions.html#open

C# Syntax - Example of a Lambda Expression - ForEach() over Generic List

public void Each<T>(IEnumerable<T> items, Action<T> action)
{
    foreach (var item in items)
        action(item);
}

... and call it thusly:

Each(myList, i => Console.WriteLine(i));

What is the meaning of prepended double colon "::"?

:: is the scope resolution operator. It's used to specify the scope of something.

For example, :: alone is the global scope, outside all other namespaces.

some::thing can be interpreted in any of the following ways:

  • some is a namespace (in the global scope, or an outer scope than the current one) and thing is a type, a function, an object or a nested namespace;
  • some is a class available in the current scope and thing is a member object, function or type of the some class;
  • in a class member function, some can be a base type of the current type (or the current type itself) and thing is then one member of this class, a type, function or object.

You can also have nested scope, as in some::thing::bad. Here each name could be a type, an object or a namespace. In addition, the last one, bad, could also be a function. The others could not, since functions can't expose anything within their internal scope.

So, back to your example, ::thing can be only something in the global scope: a type, a function, an object or a namespace.

The way you use it suggests (used in a pointer declaration) that it's a type in the global scope.

I hope this answer is complete and correct enough to help you understand scope resolution.

Get Insert Statement for existing row in MySQL

Within MySQL work bench perform the following:

  1. Click Server > Data Export

  2. In the Object Selection Tab select the desired schema.

  3. Next, select the desired tables using the list box to the right of the schema.

  4. Select a file location to export the script.

  5. Click Finish.

  6. Navigate to the newly created file and copy the insert statements.

How do I compare a value to a backslash?

If message.value[] is string:

if message.value[0] in ('/', '\'):
    do_stuff()

If it not str

SQL Case Expression Syntax?

Here are the CASE statement examples from the PostgreSQL docs (Postgres follows the SQL standard here):

SELECT a,
   CASE WHEN a=1 THEN 'one'
        WHEN a=2 THEN 'two'
        ELSE 'other'
   END
FROM test;

or

SELECT a,
   CASE a WHEN 1 THEN 'one'
          WHEN 2 THEN 'two'
          ELSE 'other'
   END
FROM test;

Obviously the second form is cleaner when you are just checking one field against a list of possible values. The first form allows more complicated expressions.

PHP syntax question: What does the question mark and colon mean?

This is the PHP ternary operator (also known as a conditional operator) - if first operand evaluates true, evaluate as second operand, else evaluate as third operand.

Think of it as an "if" statement you can use in expressions. Can be very useful in making concise assignments that depend on some condition, e.g.

$param = isset($_GET['param']) ? $_GET['param'] : 'default';

There's also a shorthand version of this (in PHP 5.3 onwards). You can leave out the middle operand. The operator will evaluate as the first operand if it true, and the third operand otherwise. For example:

$result = $x ?: 'default';

It is worth mentioning that the above code when using i.e. $_GET or $_POST variable will throw undefined index notice and to prevent that we need to use a longer version, with isset or a null coalescing operator which is introduced in PHP7:

$param = $_GET['param'] ?? 'default';

LaTeX package for syntax highlighting of code in various languages

LGrind does this. It's a mature LaTeX package that's been around since adam was a cowboy and has support for many programming languages.

Can someone explain __all__ in Python?

__all__ affects how from foo import * works.

Code that is inside a module body (but not in the body of a function or class) may use an asterisk (*) in a from statement:

from foo import *

The * requests that all attributes of module foo (except those beginning with underscores) be bound as global variables in the importing module. When foo has an attribute __all__, the attribute's value is the list of the names that are bound by this type of from statement.

If foo is a package and its __init__.py defines a list named __all__, it is taken to be the list of submodule names that should be imported when from foo import * is encountered. If __all__ is not defined, the statement from foo import * imports whatever names are defined in the package. This includes any names defined (and submodules explicitly loaded) by __init__.py.

Note that __all__ doesn't have to be a list. As per the documentation on the import statement, if defined, __all__ must be a sequence of strings which are names defined or imported by the module. So you may as well use a tuple to save some memory and CPU cycles. Just don't forget a comma in case the module defines a single public name:

__all__ = ('some_name',)

See also Why is “import *” bad?

Inner text shadow with CSS

Try this example for inset text shadow. Here's the HTML

<h1 class="inset-text-shadow">Inset text shadow trick</h1>

and the CSS

body {
    background: #f8f8f8;
}
h1 {
    font-family: Helvetica, Arial, sans-serif;
    font-weight: bold;
    font-size: 6em;
    line-height: 1em;
}
.inset-text-shadow {
    /* Shadows are visible under slightly transparent text color */
    color: rgba(0,0,0,0.6);
    text-shadow: 2px 8px 6px rgba(0,0,0,0.2), 0px -5px 35px rgba(255,255,255,0.3);

}

Demo on Jsfiddle

HTML SELECT - Change selected option by VALUE using JavaScript

You can select the value using javascript:

document.getElementById('sel').value = 'bike';

DEMO

How to append output to the end of a text file

I would use printf instead of echo because it's more reliable and processes formatting such as new line \n properly.

This example produces an output similar to echo in previous examples:

printf "hello world"  >> read.txt   
cat read.txt
hello world

However if you were to replace printf with echo in this example, echo would treat \n as a string, thus ignoring the intent

printf "hello\nworld"  >> read.txt   
cat read.txt
hello
world

Finding the id of a parent div using Jquery

Try this:

$("button").click(function () {
    $(this).parents("div:first").html(...);
});

How to support different screen size in android

Beginning with Android 3.2 (API level 13), size groups (folders small, normal, large, xlarge) are deprecated in favor of a new technique for managing screen sizes based on the available screen width.



There are different resource configurations that you can specify based on the space available for your layout:

1) Smallest Width - The fundamental size of a screen, as indicated by the shortest dimension of the available screen area.

Qualifier Value: sw'dp value'dp

Eg. res/sw600dp/layout.xml -> will be used for all screen sizes bigger or equal to 600dp. This does not take the device orientation into account.


2) Available Screen Width - Specifies a minimum available width in dp units at which the resources should be used.

Qualifier Value: w'dp value'dp

Eg. res/w600dp/layout.xml -> will be used for all screens, which width is greater than or equal to 600dp.


3) Available Screen Height - Specifies a minimum screen height in dp units at which the resources should be used.

Qualifier Value: h'dp value'dp

Eg. res/h600dp/layout.xml -> will be used for all screens, which height is greater than or equal to 600dp.



So at the end your folder structure might look like this:

res/layout/layout.xml -> for handsets (smaller than 600dp available width)
res/layout-sw600dp/layout.xml -> for 7” tablets (600dp wide and bigger)
res/layout-sw720dp/layout.xml -> for 10” tablets (720dp wide and bigger)


For more information please read the official documentation:
https://developer.android.com/guide/practices/screens_support.html#DeclaringTabletLayouts

What is the difference between YAML and JSON?

If you don't need any features which YAML has and JSON doesn't, I would prefer JSON because it is very simple and is widely supported (has a lot of libraries in many languages). YAML is more complex and has less support. I don't think the parsing speed or memory use will be very much different, and maybe not a big part of your program's performance.

Unicode via CSS :before

The code points used in icon font tricks are usually Private Use code points, which means that they have no generally defined meaning and should not be used in open information interchange, only by private agreement between interested parties. However, Private Use code points can be represented as any other Unicode value, e.g. in CSS using a notation like \f066, as others have answered. You can even enter the code point as such, if your document is UTF-8 encoded and you know how to type an arbitrary Unicode value by its number in your authoring environment (but of course it would normally be displayed using a symbol for an unknown character).

However, this is not the normal way of using icon fonts. Normally you use a CSS file provided with the font and use constructs like <span class="icon-resize-small">foo</span>. The CSS code will then take care of inserting the symbol at the start of the element, and you don’t need to know the code point number.

ASP.NET MVC: What is the correct way to redirect to pages/actions in MVC?

RedirectToAction("actionName", "controllerName");

It has other overloads as well, please check up!

Also, If you are new and you are not using T4MVC, then I would recommend you to use it!

It gives you intellisence for actions,Controllers,views etc (no more magic strings)

How can I split this comma-delimited string in Python?

How about a list?

mystring.split(",")

It might help if you could explain what kind of info we are looking at. Maybe some background info also?

EDIT:

I had a thought you might want the info in groups of two?

then try:

re.split(r"\d*,\d*", mystring)

and also if you want them into tuples

[(pair[0], pair[1]) for match in re.split(r"\d*,\d*", mystring) for pair in match.split(",")]

in a more readable form:

mylist = []
for match in re.split(r"\d*,\d*", mystring):
    for pair in match.split(",")
        mylist.append((pair[0], pair[1]))

Webdriver findElements By xpath

The XPath turns into this:

Get me all of the div elements that have an id equal to container.

As for getting the first etc, you have two options.

Turn it into a .findElement() - this will just return the first one for you anyway.

or

To explicitly do this in XPath, you'd be looking at:

(//div[@id='container'])[1]

for the first one, for the second etc:

(//div[@id='container'])[2]

Then XPath has a special indexer, called last, which would (you guessed it) get you the last element found:

(//div[@id='container'])[last()]

Worth mentioning that XPath indexers will start from 1 not 0 like they do in most programming languages.

As for getting the parent 'node', well, you can use parent:

//div[@id='container']/parent::*

That would get the div's direct parent.

You could then go further and say I want the first *div* with an id of container, and I want his parent:

(//div[@id='container'])[1]/parent::*

Hope that helps!

How to run a Runnable thread in Android at defined intervals?

Kotlin

private lateinit var runnable: Runnable
override fun onCreate(savedInstanceState: Bundle?) {
    val handler = Handler()
    runnable = Runnable {
        // do your work
        handler.postDelayed(runnable, 2000)
    }
    handler.postDelayed(runnable, 2000)
}

Java

Runnable runnable;
Handler handler;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    handler = new Handler();
    runnable = new Runnable() {
        @Override
        public void run() {
            // do your work
            handler.postDelayed(this, 1000);
        }
    };
    handler.postDelayed(runnable, 1000);
}

When to use IList and when to use List

There are two rules I follow:

  • Accept the most basic type that will work
  • Return the richest type your user will need

So when writing a function or method that takes a collection, write it not to take a List, but an IList<T>, an ICollection<T>, or IEnumerable<T>. The generic interfaces will still work even for heterogenous lists because System.Object can be a T too. Doing this will save you headache if you decide to use a Stack or some other data structure further down the road. If all you need to do in the function is foreach through it, IEnumerable<T> is really all you should be asking for.

On the other hand, when returning an object out of a function, you want to give the user the richest possible set of operations without them having to cast around. So in that case, if it's a List<T> internally, return a copy as a List<T>.

Auto-expanding layout with Qt-Designer

Set the horizontalPolicy & VerticalPolicy for the controls/widgets to "Preferred".

How to check if an excel cell is empty using Apache POI?

Try below code:

String empty = "-";
if (row.getCell(3) == null || row.getCell(3).getCellType() == Cell.CELL_TYPE_BLANK) {
    upld.setValue(empty);
} else {
    upld.setValue(row.getCell(3).getStringCellValue());
}

Allowing Untrusted SSL Certificates with HttpClient

I found an example online which seems to work well:

First you create a new ICertificatePolicy

using System.Security.Cryptography.X509Certificates;
using System.Net;

public class MyPolicy : ICertificatePolicy
{
  public bool CheckValidationResult(ServicePoint srvPoint, X509Certificate certificate, WebRequest request, 
int certificateProblem)
  {
    //Return True to force the certificate to be accepted.
    return true;
  }
}

Then just use this prior to sending your http request like so:

System.Net.ServicePointManager.CertificatePolicy = new MyPolicy();

http://www.terminally-incoherent.com/blog/2008/05/05/send-a-https-post-request-with-c/

CSS: 100% font size - 100% of what?

As to my understanding it help your content adjust with different values of font family and font sizes.Thus making your content scalable. As to the issue of inhering font size we can always override by giving a specific font size for the element.

Getting XML Node text value with Java DOM

I use a very old java. Jdk 1.4.08 and I had the same issue. The Node class for me did not had the getTextContent() method. I had to use Node.getFirstChild().getNodeValue() instead of Node.getNodeValue() to get the value of the node. This fixed for me.

How to let an ASMX file output JSON

From WebService returns XML even when ResponseFormat set to JSON:

Make sure that the request is a POST request, not a GET. Scott Guthrie has a post explaining why.

Though it's written specifically for jQuery, this may also be useful to you:
Using jQuery to Consume ASP.NET JSON Web Services

How to close the command line window after running a batch file?

If you only need to execute only one command all by itself and no wait needed, you should try "cmd /c", this works for me!

cmd /c start iexplore "http://your/url.html"

cmd /c means executing a command and then exit.

You can learn the functions of your switches by typing in your command prompt

anycmd /?

Format number to always show 2 decimal places

Extend Math object with precision method

_x000D_
_x000D_
Object.defineProperty(Math, 'precision',{_x000D_
   value: function (value,precision,type){_x000D_
             var v = parseFloat(value),_x000D_
                 p = Math.max(precision,0)||0,_x000D_
                 t = type||'round';_x000D_
              return (Math[t](v*Math.pow(10,p))/Math.pow(10,p)).toFixed(p);_x000D_
          }_x000D_
    });_x000D_
_x000D_
console.log(_x000D_
    Math.precision(3.1,3), // round 3 digits _x000D_
    Math.precision(0.12345,2,'ceil'), // ceil 2 digits_x000D_
    Math.precision(1.1) // integer part_x000D_
)
_x000D_
_x000D_
_x000D_

how to get date of yesterday using php?

try this

        $tz    = new DateTimeZone('Your Time Zone');
        $date  = new DateTime($today,$tz);
        $interval = new DateInterval('P1D');
        $date->sub($interval); 

        echo $date->format('d.m.y');

        ?>           

Postman addon's like in firefox

I liked PostMan, it was the main reason why I kept using Chrome, now I'm good with HttpRequester

https://addons.mozilla.org/En-us/firefox/addon/httprequester/?src=search

Wait until page is loaded with Selenium WebDriver for Python

The webdriver will wait for a page to load by default via .get() method.

As you may be looking for some specific element as @user227215 said, you should use WebDriverWait to wait for an element located in your page:

from selenium import webdriver
from selenium.webdriver.support.ui import WebDriverWait
from selenium.webdriver.support import expected_conditions as EC
from selenium.webdriver.common.by import By
from selenium.common.exceptions import TimeoutException

browser = webdriver.Firefox()
browser.get("url")
delay = 3 # seconds
try:
    myElem = WebDriverWait(browser, delay).until(EC.presence_of_element_located((By.ID, 'IdOfMyElement')))
    print "Page is ready!"
except TimeoutException:
    print "Loading took too much time!"

I have used it for checking alerts. You can use any other type methods to find the locator.

EDIT 1:

I should mention that the webdriver will wait for a page to load by default. It does not wait for loading inside frames or for ajax requests. It means when you use .get('url'), your browser will wait until the page is completely loaded and then go to the next command in the code. But when you are posting an ajax request, webdriver does not wait and it's your responsibility to wait an appropriate amount of time for the page or a part of page to load; so there is a module named expected_conditions.

C++ vector's insert & push_back difference

The functions have different purposes. vector::insert allows you to insert an object at a specified position in the vector, whereas vector::push_back will just stick the object on the end. See the following example:

using namespace std;
vector<int> v = {1, 3, 4};
v.insert(next(begin(v)), 2);
v.push_back(5);
// v now contains {1, 2, 3, 4, 5}

You can use insert to perform the same job as push_back with v.insert(v.end(), value).

Can I do a max(count(*)) in SQL?

create view sal as
select yr,count(*) as ct from
(select title,yr from movie m, actor a, casting c
where a.name='JOHN'
and a.id=c.actorid
and c.movieid=m.id)group by yr

-----VIEW CREATED-----

select yr from sal
where ct =(select max(ct) from sal)

YR 2013

How to install a python library manually

You need to install it in a directory in your home folder, and somehow manipulate the PYTHONPATH so that directory is included.

The best and easiest is to use virtualenv. But that requires installation, causing a catch 22. :) But check if virtualenv is installed. If it is installed you can do this:

$ cd /tmp
$ virtualenv foo
$ cd foo
$ ./bin/python

Then you can just run the installation as usual, with /tmp/foo/python setup.py install. (Obviously you need to make the virtual environment in your a folder in your home directory, not in /tmp/foo. ;) )

If there is no virtualenv, you can install your own local Python. But that may not be allowed either. Then you can install the package in a local directory for packages:

$ wget http://pypi.python.org/packages/source/s/six/six-1.0b1.tar.gz#md5=cbfcc64af1f27162a6a6b5510e262c9d
$ tar xvf six-1.0b1.tar.gz 
$ cd six-1.0b1/
$ pythonX.X setup.py   install --install-dir=/tmp/frotz

Now you need to add /tmp/frotz/pythonX.X/site-packages to your PYTHONPATH, and you should be up and running!

Fastest way to count exact number of rows in a very large table?

I got this script from another StackOverflow question/answer:

SELECT SUM(p.rows) FROM sys.partitions AS p
  INNER JOIN sys.tables AS t
  ON p.[object_id] = t.[object_id]
  INNER JOIN sys.schemas AS s
  ON s.[schema_id] = t.[schema_id]
  WHERE t.name = N'YourTableNameHere'
  AND s.name = N'dbo'
  AND p.index_id IN (0,1);

My table has 500 million records and the above returns in less than 1ms. Meanwhile,

SELECT COUNT(id) FROM MyTable

takes a full 39 minutes, 52 seconds!

They yield the exact same number of rows (in my case, exactly 519326012).

I do not know if that would always be the case.

How to replace a character by a newline in Vim

But if one has to substitute, then the following thing works:

:%s/\n/\r\|\-\r/g

In the above, every next line is substituted with next line, and then |- and again a new line. This is used in wiki tables.

If the text is as follows:

line1
line2
line3

It is changed to

line1
|-
line2
|-
line3

What's the best UI for entering date of birth?

Who don't you use the jQuery UI DatePicker?

It's configurable to suit pretty much any needs. The only downside is if you're including it with jQuery UI it has a somewhat large footprint..

Update

Some of the file sizes appear to have changed, so they are updated below. Keep in mind these numbers will only be correct for the time they were last updated. Things may have changed since then.

  • CSS theme - 23kb
  • jQuery UI - 71kb minified
  • DatePicker - 38kb
  • Plus a couple of images (next month/previous month, which I'm pretty sure are sprited)

But that's not too bad...

Highlight label if checkbox is checked

This is an example of using the :checked pseudo-class to make forms more accessible. The :checked pseudo-class can be used with hidden inputs and their visible labels to build interactive widgets, such as image galleries. I created the snipped for the people that wanna test.

_x000D_
_x000D_
input[type=checkbox] + label {_x000D_
  color: #ccc;_x000D_
  font-style: italic;_x000D_
} _x000D_
input[type=checkbox]:checked + label {_x000D_
  color: #f00;_x000D_
  font-style: normal;_x000D_
} 
_x000D_
<input type="checkbox" id="cb_name" name="cb_name"> _x000D_
<label for="cb_name">CSS is Awesome</label> 
_x000D_
_x000D_
_x000D_

Is there an equivalent to background-size: cover and contain for image elements?

Assuming you can arrange to have a container element you wish to fill, this appears to work, but feels a bit hackish. In essence, I just use min/max-width/height on a larger area and then scale that area back into the original dimensions.

_x000D_
_x000D_
.container {_x000D_
  width: 800px;_x000D_
  height: 300px;_x000D_
  border: 1px solid black;_x000D_
  overflow:hidden;_x000D_
  position:relative;_x000D_
}_x000D_
.container.contain img {_x000D_
  position: absolute;_x000D_
  left:-10000%; right: -10000%; _x000D_
  top: -10000%; bottom: -10000%;_x000D_
  margin: auto auto;_x000D_
  max-width: 10%;_x000D_
  max-height: 10%;_x000D_
  -webkit-transform:scale(10);_x000D_
  transform: scale(10);_x000D_
}_x000D_
.container.cover img {_x000D_
  position: absolute;_x000D_
  left:-10000%; right: -10000%; _x000D_
  top: -10000%; bottom: -10000%;_x000D_
  margin: auto auto;_x000D_
  min-width: 1000%;_x000D_
  min-height: 1000%;_x000D_
  -webkit-transform:scale(0.1);_x000D_
  transform: scale(0.1);_x000D_
}
_x000D_
<h1>contain</h1>_x000D_
  <div class="container contain">_x000D_
    <img _x000D_
       src="https://www.google.de/logos/doodles/2014/european-parliament-election-2014-day-4-5483168891142144-hp.jpg" _x000D_
       />_x000D_
    <!-- 366x200 -->_x000D_
  </div>_x000D_
  <h1>cover</h1>_x000D_
  <div class="container cover">_x000D_
    <img _x000D_
       src="https://www.google.de/logos/doodles/2014/european-parliament-election-2014-day-4-5483168891142144-hp.jpg" _x000D_
       />_x000D_
    <!-- 366x200 -->_x000D_
  </div>
_x000D_
_x000D_
_x000D_

How to JUnit test that two List<E> contain the same elements in the same order?

org.junit.Assert.assertEquals() and org.junit.Assert.assertArrayEquals() do the job.

To avoid next questions: If you want to ignore the order put all elements to set and then compare: Assert.assertEquals(new HashSet<String>(one), new HashSet<String>(two))

If however you just want to ignore duplicates but preserve the order wrap you list with LinkedHashSet.

Yet another tip. The trick Assert.assertEquals(new HashSet<String>(one), new HashSet<String>(two)) works fine until the comparison fails. In this case it shows you error message with to string representations of your sets that can be confusing because the order in set is almost not predictable (at least for complex objects). So, the trick I found is to wrap the collection with sorted set instead of HashSet. You can use TreeSet with custom comparator.

Reading from file using read() function

Read Byte by Byte and check that each byte against '\n' if it is not, then store it into buffer
if it is '\n' add '\0' to buffer and then use atoi()

You can read a single byte like this

char c;
read(fd,&c,1);

See read()

Password Protect a SQLite DB. Is it possible?

You can encrypt your SQLite database with the SEE addon. This way you prevent unauthorized access/modification.

Quoting SQLite documentation:

The SQLite Encryption Extension (SEE) is an enhanced version of SQLite that encrypts database files using 128-bit or 256-Bit AES to help prevent unauthorized access or modification. The entire database file is encrypted so that to an outside observer, the database file appears to contain white noise. There is nothing that identifies the file as an SQLite database.

You can find more info about this addon in this link.

Set initial value in datepicker with jquery?

Use setDate

.datepicker( "setDate" , date )

Sets the current date for the datepicker. The new date may be a Date object or a string in the current date format (e.g. '01/26/2009'), a number of days from today (e.g. +7) or a string of values and periods ('y' for years, 'm' for months, 'w' for weeks, 'd' for days, e.g. '+1m +7d'), or null to clear the selected date.

Why is setTimeout(fn, 0) sometimes useful?

setTimeout() buys you some time until the DOM elements are loaded, even if is set to 0.

Check this out: setTimeout

How to filter data in dataview

Eg:

Datatable newTable =  new DataTable();

            foreach(string s1 in list)
            {
                if (s1 != string.Empty) {
                    dvProducts.RowFilter = "(CODE like '" + serachText + "*') AND (CODE <> '" + s1 + "')";
                    foreach(DataRow dr in dvProducts.ToTable().Rows)
                    {
                       newTable.ImportRow(dr);
                    }
                }
            }
ListView1.DataSource = newTable;
ListView1.DataBind();

How can I commit a single file using SVN over a network?

strange that your command works, i thougth it would need a target directory. but it looks like it assumes current pwd as default.

cd myapp
svn ci page1.html

you can also just do svn ci in or on that folder and it will detect all changes automatically and give you a list of what will be checked in

man svn tells you the rest

Delete ActionLink with confirm dialog

You can also customize the by passing the delete item along with the message. In my case using MVC and Razor, so I could do this:

@Html.ActionLink("Delete", 
    "DeleteTag", new { id = t.IDTag }, 
    new { onclick = "return confirm('Do you really want to delete the tag " + @t.Tag + "?')" })

Why use the 'ref' keyword when passing an object?

With ref you can write:

static public void DoSomething(ref TestRef t)
{
    t = new TestRef();
}

And t will be changed after the method has completed.

Byte Array and Int conversion in Java

here is my implementation

public static byte[] intToByteArray(int a) {
    return BigInteger.valueOf(a).toByteArray();
}

public static int byteArrayToInt(byte[] b) {
    return new BigInteger(b).intValue();
}

Random number c++ in some range

float RandomFloat(float min, float max)
{
    float r = (float)rand() / (float)RAND_MAX;
    return min + r * (max - min);
}

HTML: Changing colors of specific words in a string of text

use spans. ex) <span style='color: #FF0000;'>January 30, 2011</span>

Failed to resolve: com.google.firebase:firebase-core:9.0.0

If all the above methods are not working then change implementation 'com.google.firebase:firebase-core:12.0.0' to implementation 'com.google.firebase:firebase-core:10.0.0' in your app level build.gradle file. This would surely work.

In WPF, what are the differences between the x:Name and Name attributes?

Name:

  1. can be used only for descendants of FrameworkElement and FrameworkContentElement;
  2. can be set from code-behind via SetValue() and property-like.

x:Name:

  1. can be used for almost all XAML elements;
  2. can NOT be set from code-behind via SetValue(); it can only be set using attribute syntax on objects because it is a directive.

Using both directives in XAML for one FrameworkElement or FrameworkContentElement will cause an exception: if the XAML is markup compiled, the exception will occur on the markup compile, otherwise it occurs on load.

Installing lxml module in python

For python 3 this worked for me

sudo apt-get install python3-lxml

Sample random rows in dataframe

Write one! Wrapping JC's answer gives me:

randomRows = function(df,n){
   return(df[sample(nrow(df),n),])
}

Now make it better by checking first if n<=nrow(df) and stopping with an error.

How do I make my ArrayList Thread-Safe? Another approach to problem in Java?

You can also use as Vector instead, as vectors are thread safe and arraylist are not. Though vectors are old but they can solve your purpose easily.

But you can make your Arraylist synchronized like code given this:

Collections.synchronizedList(new ArrayList(numberOfRaceCars())); 

Create a batch file to copy and rename file

type C:\temp\test.bat>C:\temp\test.log

Taking inputs with BufferedReader in Java

You can't read individual integers in a single line separately using BufferedReader as you do using Scannerclass. Although, you can do something like this in regard to your query :

import java.io.*;
class Test
{
   public static void main(String args[])throws IOException
    {
       BufferedReader br=new BufferedReader(new InputStreamReader(System.in));
       int t=Integer.parseInt(br.readLine());
       for(int i=0;i<t;i++)
       {
         String str=br.readLine();
         String num[]=br.readLine().split(" ");
         int num1=Integer.parseInt(num[0]);
         int num2=Integer.parseInt(num[1]);
         //rest of your code
       }
    }
}

I hope this will help you.

Simple working Example of json.net in VB.net

Imports Newtonsoft.Json.Linq

Dim json As JObject = JObject.Parse(Me.TextBox1.Text)
MsgBox(json.SelectToken("Venue").SelectToken("ID"))

CSS content property: is it possible to insert HTML instead of Text?

As almost noted in comments to @BoltClock's answer, in modern browsers, you can actually add some html markup to pseudo-elements using the (url()) in combination with svg's <foreignObject> element.

You can either specify an URL pointing to an actual svg file, or create it with a dataURI version (data:image/svg+xml; charset=utf8, + encodeURIComponent(yourSvgMarkup))

But note that it is mostly a hack and that there are a lot of limitations :

  • You can not load any external resources from this markup (no CSS, no images, no media etc.).
  • You can not execute script.
  • Since this won't be part of the DOM, the only way to alter it, is to pass the markup as a dataURI, and edit this dataURI in document.styleSheets. for this part, DOMParser and XMLSerializer may help.
  • While the same operation allows us to load url-encoded media in <img> tags, this won't work in pseudo-elements (at least as of today, I don't know if it is specified anywhere that it shouldn't, so it may be a not-yet implemented feature).

Now, a small demo of some html markup in a pseudo element :

_x000D_
_x000D_
/* _x000D_
**  original svg code :_x000D_
*_x000D_
*<svg width="200" height="60"_x000D_
*     xmlns="http://www.w3.org/2000/svg">_x000D_
*_x000D_
* <foreignObject width="100%" height="100%" x="0" y="0">_x000D_
* <div xmlns="http://www.w3.org/1999/xhtml" style="color: blue">_x000D_
*  I am <pre>HTML</pre>_x000D_
* </div>_x000D_
* </foreignObject>_x000D_
*</svg>_x000D_
*_x000D_
*/
_x000D_
#log::after {_x000D_
  content: url('data:image/svg+xml;%20charset=utf8,%20%3Csvg%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F2000%2Fsvg%22%20height%3D%2260%22%20width%3D%22200%22%3E%0A%0A%20%20%3CforeignObject%20y%3D%220%22%20x%3D%220%22%20height%3D%22100%25%22%20width%3D%22100%25%22%3E%0A%09%3Cdiv%20style%3D%22color%3A%20blue%22%20xmlns%3D%22http%3A%2F%2Fwww.w3.org%2F1999%2Fxhtml%22%3E%0A%09%09I%20am%20%3Cpre%3EHTML%3C%2Fpre%3E%0A%09%3C%2Fdiv%3E%0A%20%20%3C%2FforeignObject%3E%0A%3C%2Fsvg%3E');_x000D_
}
_x000D_
<p id="log">hi</p>
_x000D_
_x000D_
_x000D_

Two div blocks on same line

diplay:flex; is another alternative answer that you can add to all above answers which is supported in all modern browsers.

_x000D_
_x000D_
#block_container {_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
}
_x000D_
<div id="block_container">_x000D_
  <div id="bloc1">Copyright &copy; All Rights Reserved.</div>_x000D_
  <div id="bloc2"><img src="..."></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Aligning a float:left div to center?

Just wrap floated elements in a <div> and give it this CSS:

.wrapper {

display: table;
margin: auto;

}

GitHub Error Message - Permission denied (publickey)

I was having a similar problem to @Batman. However, because I was running this under /usr/local/src/projectname, running without sudo was not an option.

Just add the -E flag to preseve the environment (your ~/.ssh/ path).

$ sudo -E git clone git@your_repo

From man sudo:

-E, --preserve-env Indicates to the security policy that the user wishes to pre- serve their existing environment variables. The security policy may return an error if the user does not have permis- sion to preserve the environment.

Nginx upstream prematurely closed connection while reading response header from upstream, for large requests

You can increase the timeout in node like so.

app.post('/slow/request', function(req, res){ req.connection.setTimeout(100000); //100 seconds ... }

MySQL - Using If Then Else in MySQL UPDATE or SELECT Queries

Here's a query to update a table based on a comparison of another table. If record is not found in tableB, it will update the "active" value to "n". If it's found, will set the value to NULL

UPDATE tableA
LEFT JOIN tableB ON tableA.id = tableB.id
SET active = IF(tableB.id IS NULL, 'n', NULL)";

Hope this helps someone else.

Determining 32 vs 64 bit in C++

You could do this:

#if __WORDSIZE == 64
char *size = "64bits";
#else
char *size = "32bits";
#endif

git pull keeping local changes

There is a simple solution based on Git stash. Stash everything that you've changed, pull all the new stuff, apply your stash.

git stash
git pull
git stash pop

On stash pop there may be conflicts. In the case you describe there would in fact be a conflict for config.php. But, resolving the conflict is easy because you know that what you put in the stash is what you want. So do this:

git checkout --theirs -- config.php

jQuery Date Picker - disable past dates

set startDate attribute of datepicker, it works, below is the working code

$(function(){
$('#datepicker').datepicker({
    startDate: '-0m'
    //endDate: '+2d'
}).on('changeDate', function(ev){
    $('#sDate1').text($('#datepicker').data('date'));
    $('#datepicker').datepicker('hide');
});
})

Matrix Multiplication in pure Python?

This is incorrect initialization. You interchanged row with col!

C = [[0 for row in range(len(A))] for col in range(len(B[0]))]

Correct initialization would be

C = [[0 for col in range(len(B[0]))] for row in range(len(A))]

Also I would suggest using better naming conventions. Will help you a lot in debugging. For example:

def matrixmult (A, B):
    rows_A = len(A)
    cols_A = len(A[0])
    rows_B = len(B)
    cols_B = len(B[0])

    if cols_A != rows_B:
      print "Cannot multiply the two matrices. Incorrect dimensions."
      return

    # Create the result matrix
    # Dimensions would be rows_A x cols_B
    C = [[0 for row in range(cols_B)] for col in range(rows_A)]
    print C

    for i in range(rows_A):
        for j in range(cols_B):
            for k in range(cols_A):
                C[i][j] += A[i][k] * B[k][j]
    return C

You can do a lot more, but you get the idea...

com.apple.WebKit.WebContent drops 113 error: Could not find specified service

SWIFT

Well I did this in the following order and didn't get any error like Could not signal service com.apple.WebKit.WebContent: 113: Could not find specified service after that, following code might help you too.

webView = WKWebView(frame: self.view.frame)
self.view.addSubview(self.view.webView)
webView.navigationDelegate = self
webView.loadHTMLString(htmlString, baseURL: nil)

Do as order.

Thanks

How to efficiently change image attribute "src" from relative URL to absolute using jQuery?

The replace method in Javascript returns a value, and does not act upon the existing string object. See: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/String/replace

In your example, you will have to do

$(this).attr("src", $(this).attr("src").replace(...))

Wrapping a react-router Link in an html button

You can use useHistory hook since react-router v5.1.0.

The useHistory hook gives you access to the history instance that you may use to navigate.

import React from 'react'
import { useHistory } from 'react-router-dom'

export default function SomeComponent() {
  const { push } = useHistory()
  ...
  <button
    type="button"
    onClick={() => push('/some-link')}
  >
    Some link
  </button>
  ...
}

What is the difference between UNION and UNION ALL?

UNION removes duplicates, whereas UNION ALL does not.

In order to remove duplicates the result set must be sorted, and this may have an impact on the performance of the UNION, depending on the volume of data being sorted, and the settings of various RDBMS parameters ( For Oracle PGA_AGGREGATE_TARGET with WORKAREA_SIZE_POLICY=AUTO or SORT_AREA_SIZE and SOR_AREA_RETAINED_SIZE if WORKAREA_SIZE_POLICY=MANUAL ).

Basically, the sort is faster if it can be carried out in memory, but the same caveat about the volume of data applies.

Of course, if you need data returned without duplicates then you must use UNION, depending on the source of your data.

I would have commented on the first post to qualify the "is much less performant" comment, but have insufficient reputation (points) to do so.

How do I get time of a Python program's execution?

There is a timeit module which can be used to time the execution times of Python code.

It has detailed documentation and examples in Python documentation, 26.6. timeit — Measure execution time of small code snippets.

BeautifulSoup getText from between <p>, not picking up subsequent paragraphs

This works well for specific articles where the text is all wrapped in <p> tags. Since the web is an ugly place, it's not always the case.

Often, websites will have text scattered all over, wrapped in different types of tags (e.g. maybe in a <span> or a <div>, or an <li>).

To find all text nodes in the DOM, you can use soup.find_all(text=True).

This is going to return some undesired text, like the contents of <script> and <style> tags. You'll need to filter out the text contents of elements you don't want.

blacklist = [
  'style',
  'script',
  # other elements,
]

text_elements = [t for t in soup.find_all(text=True) if t.parent.name not in blacklist]

If you are working with a known set of tags, you can tag the opposite approach:

whitelist = [
  'p'
]

text_elements = [t for t in soup.find_all(text=True) if t.parent.name in whitelist]

I can pass a variable from a JSP scriptlet to JSTL but not from JSTL to a JSP scriptlet without an error

@skaffman nailed it down. They live each in its own context. However, I wouldn't consider using scriptlets as the solution. You'd like to avoid them. If all you want is to concatenate strings in EL and you discovered that the + operator fails for strings in EL (which is correct), then just do:

<c:out value="abc${test}" />

Or if abc is to obtained from another scoped variable named ${resp}, then do:

<c:out value="${resp}${test}" />

How can I get screen resolution in java?

int resolution =Toolkit.getDefaultToolkit().getScreenResolution();

System.out.println(resolution);

argparse module How to add option without any argument?

To create an option that needs no value, set the action [docs] of it to 'store_const', 'store_true' or 'store_false'.

Example:

parser.add_argument('-s', '--simulate', action='store_true')

How to customize an end time for a YouTube video?

Youtube doesn't provide any option for an end time, but there alternative sites that provide this, like Tubechop. Otherwise try writing a function that either pauses video/skips to next when your when your video has played its desired duration.

OR: using the Youtube Javascript player API, you could do something like this:

function onPlayerStateChange(evt) {
    if (evt.data == YT.PlayerState.PLAYING && !done) {
        setTimeout(stopVideo, 6000);
        done = true;
    }
}

Youtube API blog

Bootstrap navbar Active State not working

Bootstrap 4: navbar Active State working, just use .navbar-nav .nav-link classes

_x000D_
_x000D_
 $(function () {
  // this will get the full URL at the address bar
  var url = window.location.href;
  // passes on every "a" tag
  $(".navbar-nav .nav-link").each(function () {
    // checks if its the same on the address bar
    if (url == (this.href)) {
      $(this).closest("li").addClass("active");
      //for making parent of submenu active
      $(this).closest("li").parent().parent().addClass("active");
    }
  });
});
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/css/bootstrap.min.css" integrity="sha384-Gn5384xqQ1aoWXA+058RXPxPg6fy4IWvTNh0E263XmFcJlSAwiGgFAW/dAiS6JXm" crossorigin="anonymous">

<script src="https://code.jquery.com/jquery-3.2.1.slim.min.js" integrity="sha384-KJ3o2DKtIkvYIK3UENzmM7KCkRr/rE9/Qpg6aAZGJwFDMVNA/GpGFF93hXpG5KkN" crossorigin="anonymous"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.12.9/umd/popper.min.js" integrity="sha384-ApNbgh9B+Y1QKtv3Rn7W3mgPxhU9K/ScQsAP7hUibX39j7fakFPskvXusvfa0b4Q" crossorigin="anonymous"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/4.0.0/js/bootstrap.min.js" integrity="sha384-JZR6Spejh4U02d8jOt6vLEHfe/JQGiRRSQQxSfFWpi1MquVdAyjUar5+76PVCmYl" crossorigin="anonymous"></script>

<nav class="navbar navbar-expand-lg navbar-light bg-light">
  <a class="navbar-brand" href="#">Navbar</a>
  <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation">
    <span class="navbar-toggler-icon"></span>
  </button>

  <div class="collapse navbar-collapse" id="navbarSupportedContent">
    <ul class="navbar-nav mr-auto">
      <li class="nav-item">
        <a class="nav-link" href="#">Home</a>
      </li>
      <li class="nav-item">
        <a class="nav-link" href="#">Link</a>
      </li>
      <li class="nav-item dropdown">
        <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
          Dropdown
        </a>
        <div class="dropdown-menu" aria-labelledby="navbarDropdown">
          <a class="dropdown-item" href="#">Action</a>
          <a class="dropdown-item" href="#">Another action</a>
          <div class="dropdown-divider"></div>
          <a class="dropdown-item" href="#">Something else here</a>
        </div>
      </li>
      <li class="nav-item">


        <a class="nav-link" href="#">Other</a>
      </li>
    </ul>
    <form class="form-inline my-2 my-lg-0">
      <input class="form-control mr-sm-2" type="search" placeholder="Search" aria-label="Search">
      <button class="btn btn-outline-success my-2 my-sm-0" type="submit">Search</button>
    </form>
  </div>
</nav>
_x000D_
_x000D_
_x000D_

Error handling with try and catch in Laravel

You are inside a namespace so you should use \Exception to specify the global namespace:

try {

  $this->buildXMLHeader();

} catch (\Exception $e) {

    return $e->getMessage();
}

In your code you've used catch (Exception $e) so Exception is being searched in/as:

App\Services\PayUService\Exception

Since there is no Exception class inside App\Services\PayUService so it's not being triggered. Alternatively, you can use a use statement at the top of your class like use Exception; and then you can use catch (Exception $e).

How to reset Django admin password?

if you forget your admin then you need to create new user by using

python manage.py createsuperuser <username>

and for password there is CLI command changepassword for django to change user password

python manage.py changepassword <username>

OR

django-admin changepassword <username>

OR Run this code in Django env

from django.contrib.auth.models import User
u = User.objects.get(username='john')
u.set_password('new password')
u.save()

PHP unable to load php_curl.dll extension

Solution:

Step1: Uncomment the php_curl.dll from php.ini

Step2: Copy the following three files from php installed directory.i.e "C:\\php7".

libeay32.dll,
libssh2.dll,
ssleay32.dll

Step3: Paste the files under two place

httpd.conf's ServerRoot directive. i.e "C\Apache24"
apache bin directory. i.e "C\Apache24\bin"

Step4: Restart apache.

That's all. I solve the problem by this way.Hope it might work for you.

The solution is given here. https://abcofcomputing.blogspot.com/2017/06/php7-unable-to-load-phpcurldll.html

javac : command not found

This worked for me: sudo dnf install java-<version>-devel

Adding ASP.NET MVC5 Identity Authentication to an existing project

This is what I did to integrate Identity with an existing database.

  1. Create a sample MVC project with MVC template. This has all the code needed for Identity implementation - Startup.Auth.cs, IdentityConfig.cs, Account Controller code, Manage Controller, Models and related views.

  2. Install the necessary nuget packages for Identity and OWIN. You will get an idea by seeing the references in the sample Project and the answer by @Sam

  3. Copy all these code to your existing project. Please note don't forget to add the "DefaultConnection" connection string for Identity to map to your database. Please check the ApplicationDBContext class in IdentityModel.cs where you will find the reference to "DefaultConnection" connection string.

  4. This is the SQL script I ran on my existing database to create necessary tables:

    USE ["YourDatabse"]
    GO
    /****** Object:  Table [dbo].[AspNetRoles]    Script Date: 16-Aug-15 6:52:25 PM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[AspNetRoles](
    [Id] [nvarchar](128) NOT NULL,
    [Name] [nvarchar](256) NOT NULL,
    CONSTRAINT [PK_dbo.AspNetRoles] PRIMARY KEY CLUSTERED 
    (
      [Id] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    
    GO
    /****** Object:  Table [dbo].[AspNetUserClaims]    Script Date: 16-Aug-15 6:52:25 PM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[AspNetUserClaims](
       [Id] [int] IDENTITY(1,1) NOT NULL,
       [UserId] [nvarchar](128) NOT NULL,
       [ClaimType] [nvarchar](max) NULL,
       [ClaimValue] [nvarchar](max) NULL,
    CONSTRAINT [PK_dbo.AspNetUserClaims] PRIMARY KEY CLUSTERED 
    (
       [Id] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
    
    GO
    /****** Object:  Table [dbo].[AspNetUserLogins]    Script Date: 16-Aug-15 6:52:25 PM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[AspNetUserLogins](
        [LoginProvider] [nvarchar](128) NOT NULL,
        [ProviderKey] [nvarchar](128) NOT NULL,
        [UserId] [nvarchar](128) NOT NULL,
    CONSTRAINT [PK_dbo.AspNetUserLogins] PRIMARY KEY CLUSTERED 
    (
        [LoginProvider] ASC,
        [ProviderKey] ASC,
        [UserId] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    
    GO
    /****** Object:  Table [dbo].[AspNetUserRoles]    Script Date: 16-Aug-15 6:52:25 PM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[AspNetUserRoles](
       [UserId] [nvarchar](128) NOT NULL,
       [RoleId] [nvarchar](128) NOT NULL,
    CONSTRAINT [PK_dbo.AspNetUserRoles] PRIMARY KEY CLUSTERED 
    (
        [UserId] ASC,
        [RoleId] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY]
    
    GO
    /****** Object:  Table [dbo].[AspNetUsers]    Script Date: 16-Aug-15 6:52:25 PM ******/
    SET ANSI_NULLS ON
    GO
    SET QUOTED_IDENTIFIER ON
    GO
    CREATE TABLE [dbo].[AspNetUsers](
        [Id] [nvarchar](128) NOT NULL,
        [Email] [nvarchar](256) NULL,
        [EmailConfirmed] [bit] NOT NULL,
        [PasswordHash] [nvarchar](max) NULL,
        [SecurityStamp] [nvarchar](max) NULL,
        [PhoneNumber] [nvarchar](max) NULL,
        [PhoneNumberConfirmed] [bit] NOT NULL,
        [TwoFactorEnabled] [bit] NOT NULL,
        [LockoutEndDateUtc] [datetime] NULL,
        [LockoutEnabled] [bit] NOT NULL,
        [AccessFailedCount] [int] NOT NULL,
        [UserName] [nvarchar](256) NOT NULL,
    CONSTRAINT [PK_dbo.AspNetUsers] PRIMARY KEY CLUSTERED 
    (
        [Id] ASC
    )WITH (PAD_INDEX = OFF, STATISTICS_NORECOMPUTE = OFF, IGNORE_DUP_KEY = OFF, ALLOW_ROW_LOCKS = ON, ALLOW_PAGE_LOCKS = ON) ON [PRIMARY]
    ) ON [PRIMARY] TEXTIMAGE_ON [PRIMARY]
    
     GO
     ALTER TABLE [dbo].[AspNetUserClaims]  WITH CHECK ADD  CONSTRAINT [FK_dbo.AspNetUserClaims_dbo.AspNetUsers_UserId] FOREIGN KEY([UserId])
     REFERENCES [dbo].[AspNetUsers] ([Id])
     ON DELETE CASCADE
     GO
     ALTER TABLE [dbo].[AspNetUserClaims] CHECK CONSTRAINT [FK_dbo.AspNetUserClaims_dbo.AspNetUsers_UserId]
     GO
     ALTER TABLE [dbo].[AspNetUserLogins]  WITH CHECK ADD  CONSTRAINT [FK_dbo.AspNetUserLogins_dbo.AspNetUsers_UserId] FOREIGN KEY([UserId])
     REFERENCES [dbo].[AspNetUsers] ([Id])
     ON DELETE CASCADE
     GO
     ALTER TABLE [dbo].[AspNetUserLogins] CHECK CONSTRAINT [FK_dbo.AspNetUserLogins_dbo.AspNetUsers_UserId]
     GO
     ALTER TABLE [dbo].[AspNetUserRoles]  WITH CHECK ADD  CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetRoles_RoleId] FOREIGN KEY([RoleId])
     REFERENCES [dbo].[AspNetRoles] ([Id])
     ON DELETE CASCADE
     GO
     ALTER TABLE [dbo].[AspNetUserRoles] CHECK CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetRoles_RoleId]
     GO
     ALTER TABLE [dbo].[AspNetUserRoles]  WITH CHECK ADD  CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetUsers_UserId] FOREIGN KEY([UserId])
     REFERENCES [dbo].[AspNetUsers] ([Id])
     ON DELETE CASCADE
     GO
     ALTER TABLE [dbo].[AspNetUserRoles] CHECK CONSTRAINT [FK_dbo.AspNetUserRoles_dbo.AspNetUsers_UserId]
     GO
    
  5. Check and solve any remaining errors and you are done. Identity will handle the rest :)

What is an undefined reference/unresolved external symbol error and how do I fix it?

If all else fails, recompile.

I was recently able to get rid of an unresolved external error in Visual Studio 2012 just by recompiling the offending file. When I re-built, the error went away.

This usually happens when two (or more) libraries have a cyclic dependency. Library A attempts to use symbols in B.lib and library B attempts to use symbols from A.lib. Neither exist to start off with. When you attempt to compile A, the link step will fail because it can't find B.lib. A.lib will be generated, but no dll. You then compile B, which will succeed and generate B.lib. Re-compiling A will now work because B.lib is now found.

"The given path's format is not supported."

I am using the (limited) Expression builder for a Variable for use in a simple File System Task to make an archive of a file in SSIS.

This is my quick and dirty hack to remove the colons to stop the error: @[User::LocalFile] + "-" + REPLACE((DT_STR, 30, 1252) GETDATE(), ":", "-") + ".xml"

syntax error when using command line in python

In order to run scripts, you should write the "python test.py" command in the command prompt, and not within the python shell. also, the test.py file should be at the path you run from in the cli.

Git merge is not possible because I have unmerged files

It might be the Unmerged paths that cause

error: Merging is not possible because you have unmerged files.

If so, try:

git status

if it says

You have unmerged paths.

do as suggested: either resolve conflicts and then commit or abort the merge entirely with

git merge --abort

You might also see files listed under Unmerged paths, which you can resolve by doing

git rm <file>

Java collections maintaining insertion order

Depends on what you need the implementation to do well. Insertion order usually is not interesting so there is no need to maintain it so you can rearrange to get better performance.

For Maps it is usually HashMap and TreeMap that is used. By using hash codes, the entries can be put in small groups easy to search in. The TreeMap maintains a sorted order of the inserted entries at the cost of slower search, but easier to sort than a HashMap.

Deciding between HttpClient and WebClient

Unpopular opinion from 2020:

When it comes to ASP.NET apps I still prefer WebClient over HttpClient because:

  1. The modern implementation comes with async/awaitable task-based methods
  2. Has smaller memory footprint and 2x-5x faster (other answers already mention that)
  3. It's suggested to "reuse a single instance of HttpClient for the lifetime of your application". But ASP.NET has no "lifetime of application", only lifetime of a request.

bootstrap 4 row height

Use the sizing utility classes...

  • h-50 = height 50%
  • h-100 = height 100%

http://www.codeply.com/go/Y3nG0io2uE

 <div class="container">
        <div class="row">
            <div class="col-md-8 col-lg-6 B">
                <div class="card card-inverse card-primary">
                    <img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
                </div>
            </div>
            <div class="col-md-4 col-lg-3 G">
                <div class="row h-100">
                    <div class="col-md-6 col-lg-6 B h-50 pb-3">
                        <div class="card card-inverse card-success h-100">

                        </div>
                    </div>
                    <div class="col-md-6 col-lg-6 B h-50 pb-3">
                        <div class="card card-inverse bg-success h-100">

                        </div>
                    </div>
                    <div class="col-md-12 h-50">
                        <div class="card card-inverse bg-danger h-100">

                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>

Or, for an unknown number of child columns, use flexbox and the cols will fill height. See the d-flex flex-column on the row, and h-100 on the child cols.

<div class="container">
    <div class="row">
        <div class="col-md-8 col-lg-6 B">
            <div class="card card-inverse card-primary">
                <img src="http://lorempicsum.com/rio/800/500/4" class="img-fluid" alt="Responsive image">
            </div>
        </div>
        <div class="col-md-4 col-lg-3 G ">
            <div class="row d-flex flex-column h-100">
                <div class="col-md-6 col-lg-6 B h-100">
                    <div class="card bg-success h-100">

                    </div>
                </div>
                <div class="col-md-6 col-lg-6 B h-100">
                    <div class="card bg-success h-100">

                    </div>
                </div>
                <div class="col-md-12 h-100">
                    <div class="card bg-danger h-100">

                    </div>
                </div>
            </div>
        </div>
    </div>
</div>

https://www.codeply.com/go/tgzFAH8vaW

Any good, visual HTML5 Editor or IDE?

Since HTML5 is still in the works and doesn't have consistant support across any browsers yet, my guess is that it's going to be quite a while before you get a WYSIWYG HTML5 Editor.

In the mean time, get used to editting your markup by hand in a good text editor like Notepad++ or TextEdit.

Inline onclick JavaScript variable

<script>var myVar = 15;</script>
<input id="EditBanner" type="button" value="Edit Image" onclick="EditBanner(myVar);"/>

OnclientClick and OnClick is not working at the same time?

Vinay (above) gave an effective work-around. What's actually causing the button's OnClick event to not work following the OnClientClick event function is that MS has defined it where, once the button is disabled (in the function called by the OnClientClick event), the button "honors" this by not trying to complete the button's activity by calling the OnClick event's defined method.

I struggled several hours trying to figure this out. Once I removed the statement to disable the submit button (that was inside the OnClientClick function), the OnClick method was called with no further problem.

Microsoft, if you're listening, once the button is clicked it should complete it's assigned activity even if it is disabled part of the way through this activity. As long as it is not disabled when it is clicked, it should complete all assigned methods.

What are enums and why are they useful?

It is useful to know that enums are just like the other classes with Constant fields and a private constructor.

For example,

public enum Weekday
{
  MONDAY, TUESDAY, WEDNESDAY, THURSDAY, FRIDAY, SATURDAY, SUNDAY
} 

The compiler compiles it as follows;

class Weekday extends Enum
{
  public static final Weekday MONDAY  = new Weekday( "MONDAY",   0 );
  public static final Weekday TUESDAY = new Weekday( "TUESDAY ", 1 );
  public static final Weekday WEDNESDAY= new Weekday( "WEDNESDAY", 2 );
  public static final Weekday THURSDAY= new Weekday( "THURSDAY", 3 );
  public static final Weekday FRIDAY= new Weekday( "FRIDAY", 4 );
  public static final Weekday SATURDAY= new Weekday( "SATURDAY", 5 );
  public static final Weekday SUNDAY= new Weekday( "SUNDAY", 6 );

  private Weekday( String s, int i )
  {
    super( s, i );
  }

  // other methods...
}

How to set cookie value with AJAX request?

Basically, ajax request as well as synchronous request sends your document cookies automatically. So, you need to set your cookie to document, not to request. However, your request is cross-domain, and things became more complicated. Basing on this answer, additionally to set document cookie, you should allow its sending to cross-domain environment:

type: "GET",    
url: "http://example.com",
cache: false,
// NO setCookies option available, set cookie to document
//setCookies: "lkfh89asdhjahska7al446dfg5kgfbfgdhfdbfgcvbcbc dfskljvdfhpl",
crossDomain: true,
dataType: 'json',
xhrFields: {
    withCredentials: true
},
success: function (data) {
    alert(data);
});

How do I make UITableViewCell's ImageView a fixed size even when the image is smaller

The whole cell doesn't need to be remade. You could use the indentationLevel and indentationWidth property of tableViewCells to shift the content of your cell. Then you add your custom imageView to the left side of the cell.

How do I make calls to a REST API using C#?

Unrelated, I'm sure, but do wrap your IDisposable objects in using blocks to ensure proper disposal:

using System;
using System.Net;
using System.IO;

namespace ConsoleProgram
{
    public class Class1
    {
        private const string URL = "https://sub.domain.com/objects.json?api_key=123";
        private const string DATA = @"{""object"":{""name"":""Name""}}";

        static void Main(string[] args)
        {
            Class1.CreateObject();
        }

        private static void CreateObject()
        {
            HttpWebRequest request = (HttpWebRequest)WebRequest.Create(URL);
            request.Method = "POST";
            request.ContentType = "application/json";
            request.ContentLength = DATA.Length;
            using (Stream webStream = request.GetRequestStream())
            using (StreamWriter requestWriter = new StreamWriter(webStream, System.Text.Encoding.ASCII))
            {
                requestWriter.Write(DATA);
            }

            try
            {
                WebResponse webResponse = request.GetResponse();
                using (Stream webStream = webResponse.GetResponseStream() ?? Stream.Null)
                using (StreamReader responseReader = new StreamReader(webStream))
                {
                    string response = responseReader.ReadToEnd();
                    Console.Out.WriteLine(response);
                }
            }
            catch (Exception e)
            {
                Console.Out.WriteLine("-----------------");
                Console.Out.WriteLine(e.Message);
            }
        }
    }
}

If Else in LINQ

you should change like this:

private string getValue(float price)
{
    if(price >0)
        return "debit";
    return "credit";
}

//Get value like this
select new {p.PriceID, Type = getValue(p.Price)};

Decompile .smali files on an APK

For getting the practical view of converting .apk file into .java files just check out https://www.youtube.com/watch?v=-AX4NYE-9V8 video . you will get more benefited and understand clearly. It clearly demonstrates the steps you required if you are using mac OS.

The basic requirement for getting this done. 1. http://code.google.com/p/dex2jar/
2. http://jd.benow.ca/

Where can I find my Facebook application id and secret key?

It is under Account -> Application Settings, click on your application's profile, then go to Edit Application.

Could not connect to SMTP host: smtp.gmail.com, port: 465, response: -1

I have been experiencing this issue when debugging using NetBeans, even executing the actual jar file. Antivirus would block sending email. You should temporarily disable your antivirus during debugging or exclude NetBeans and the actual jar file from being scanned. In my case, I'm using Avast.

See this link on how to Exclude : How to Add File/Website Exception into avast! Antivirus 2014

It works for me.

How to detect browser using angularjs?

Browser sniffing should generally be avoided, feature detection is much better, but sometimes you have to do it. For instance in my case Windows 8 Tablets overlaps the browser window with a soft keyboard; Ridiculous I know, but sometimes you have to deal with reality.

So you would measure 'navigator.userAgent' as with regular JavaScript (Please don't sink into the habit of treating Angular as something distinct from JavaScript, use plain JavaScript if possible it will lead to less future refactoring).

However for testing you want to use injected objects rather than global ones. Since '$location' doesn't contain the userAgent the simple trick is to use '$window.location.userAgent'. You can now write tests that inject a $window stub with whatever userAgent you wan't to simulate.

I haven't used it for years, but Modernizr's a good source of code for checking features. https://github.com/Modernizr/Modernizr/issues/878#issuecomment-41448059

Node.js: get path from the request

req.protocol + '://' + req.get('host') + req.originalUrl

or

req.protocol + '://' + req.headers.host + req.originalUrl // I like this one as it survives from proxy server, getting the original host name

How can I represent an infinite number in Python?

Another, less convenient, way to do it is to use Decimal class:

from decimal import Decimal
pos_inf = Decimal('Infinity')
neg_inf = Decimal('-Infinity')

What is setContentView(R.layout.main)?

As per the documentation :

Set the activity content from a layout resource. The resource will be inflated, adding all top-level views to the activity.

Your Launcher activity in the manifest first gets called and it set the layout view as specified in respective java files setContentView(R.layout.main);. Now this activity uses setContentView(R.layout.main) to set xml layout to that activity which will actually render as the UI of your activity.

Can I load a UIImage from a URL?

Try this code, you can set loading image with it, so the users knows that your app is loading an image from url:

UIImageView *yourImageView = [[UIImageView alloc] initWithImage:[UIImage imageNamed:@"loading.png"]];
    [yourImageView setContentMode:UIViewContentModeScaleAspectFit];

    //Request image data from the URL:
    dispatch_async(dispatch_get_global_queue(DISPATCH_QUEUE_PRIORITY_DEFAULT, 0), ^{
        NSData *imgData = [NSData dataWithContentsOfURL:[NSURL URLWithString:@"http://yourdomain.com/yourimg.png"]];

        dispatch_async(dispatch_get_main_queue(), ^{
            if (imgData)
            {
                //Load the data into an UIImage:
                UIImage *image = [UIImage imageWithData:imgData];

                //Check if your image loaded successfully:
                if (image)
                {
                    yourImageView.image = image;
                }
                else
                {
                    //Failed to load the data into an UIImage:
                    yourImageView.image = [UIImage imageNamed:@"no-data-image.png"];
                }
            }
            else
            {
                //Failed to get the image data:
                yourImageView.image = [UIImage imageNamed:@"no-data-image.png"];
            }
        });
    });

Adding a column after another column within SQL

It depends on what database you are using. In MySQL, you would use the "ALTER TABLE" syntax. I don't remember exactly how, but it would go something like this if you wanted to add a column called 'newcol' that was a 200 character varchar:

ALTER TABLE example ADD newCol VARCHAR(200) AFTER otherCol;

What is the @Html.DisplayFor syntax for?

Html.DisplayFor() will render the DisplayTemplate that matches the property's type.

If it can't find any, I suppose it invokes .ToString().


If you don't know about display templates, they're partial views that can be put in a DisplayTemplates folder inside the view folder associated to a controller.


Example:

If you create a view named String.cshtml inside the DisplayTemplates folder of your views folder (e.g Home, or Shared) with the following code:

@model string

@if (string.IsNullOrEmpty(Model)) {
   <strong>Null string</strong>
}
else {
   @Model
}

Then @Html.DisplayFor(model => model.Title) (assuming that Title is a string) will use the template and display <strong>Null string</strong> if the string is null, or empty.

'NoneType' object is not subscriptable?

The print() function returns None. You are trying to index None. You can not, because 'NoneType' object is not subscriptable.

Put the [0] inside the brackets. Now you're printing everything, and not just the first term.

select2 onchange event only works once

My select2 element was not firing the onchange event as the drop down list offered only one value, making it impossible to change the value.

The value not having changed, no event was fired and the handler could not execute.

I then added another handler to clear the value, with the select2-open handler being executed before the onchange handler.

The source code now looks like:

el.on("select2-open", function(e) {
    $(this).val('');
});
el.on('change', function() {
    ...
});

The first handler clears the value, allowing the second handler to fire up even if selecting the same value.

how to count length of the JSON array element

First if the object you're dealing with is a string then you need to parse it then figure out the length of the keys :

obj = JSON.parse(jsonString);
shareInfoLen = Object.keys(obj.shareInfo[0]).length;

How to select date without time in SQL

In PLSQL you can use

to_char(SYSDATE,'dd/mm/yyyy')

How to enable scrolling of content inside a modal?

Actually for Bootstrap 3 you also need to override the .modal-open class on body.

    body.modal-open, 
    .modal-open 
    .navbar-fixed-top, 
    .modal-open 
    .navbar-fixed-bottom {
     margin-right: 15px; /*<-- to margin-right: 0px;*/
    }

Map a 2D array onto a 1D array

using row major example:

A(i,j) = a[i + j*ld]; // where ld is the leading dimension
                      // (commonly same as array dimension in i)

// matrix like notation using preprocessor hack, allows to hide indexing
#define A(i,j) A[(i) + (j)*ld]

double *A = ...;
size_t ld = ...;
A(i,j) = ...;
... = A(j,i);

How to import a class from default package

From the Java language spec:

It is a compile time error to import a type from the unnamed package.

You'll have to access the class via reflection or some other indirect method.

How to get File Created Date and Modified Date

You can do that using FileInfo class:

FileInfo fi = new FileInfo("path");
var created = fi.CreationTime;
var lastmodified = fi.LastWriteTime;

How do I use typedef and typedef enum in C?

typedef defines a new data type. So you can have:

typedef char* my_string;
typedef struct{
  int member1;
  int member2;
} my_struct;

So now you can declare variables with these new data types

my_string s;
my_struct x;

s = "welcome";
x.member1 = 10;

For enum, things are a bit different - consider the following examples:

enum Ranks {FIRST, SECOND};
int main()
{
   int data = 20;
   if (data == FIRST)
   {
      //do something
   }
}

using typedef enum creates an alias for a type:

typedef enum Ranks {FIRST, SECOND} Order;
int main()
{
   Order data = (Order)20;  // Must cast to defined type to prevent error

   if (data == FIRST)
   {
      //do something
   }
}

What is a Question Mark "?" and Colon ":" Operator Used for?

They are called the ternary operator since they are the only one in Java.

The difference to the if...else construct is, that they return something, and this something can be anything:

  int k = a > b ? 7 : 8; 
  String s = (foobar.isEmpty ()) ? "empty" : foobar.toString (); 

How do I write a SQL query for a specific date range and date time using SQL Server 2008?

You can try this:

SELECT * FROM MYTABLE WHERE DATE BETWEEN '03/10/2014 06:25:00' and '03/12/2010 6:25:00'

Trying to handle "back" navigation button action in iOS

The problem with didMoveToParentViewController it's that it gets called once the parent view is fully visible again so if you need to perform some tasks before that, it won't work.

And it doesn't work with the driven animation gesture. Using willMoveToParentViewController works better.

Objective-c

- (void)willMoveToParentViewController:(UIViewController *)parent{
    if (parent == NULL) {
        // ...
    }
}

Swift

override func willMoveToParentViewController(parent: UIViewController?) {
    if parent == nil {
        // ...  
    }
}

Do I need to compile the header files in a C program?

I think we do need preprocess(maybe NOT call the compile) the head file. Because from my understanding, during the compile stage, the head file should be included in c file. For example, in test.h we have

typedef enum{
    a,
    b,
    c
}test_t

and in test.c we have

void foo()
{
    test_t test;
    ...
}

during the compile, i think the compiler will put the code in head file and c file together and code in head file will be pre-processed and substitute the code in c file. Meanwhile, we'd better to define the include path in makefile.

Missing MVC template in Visual Studio 2015

I had the same issue with the MVC template not appearing in VS2015.

I checked Web Developer Tools when originally installing. It was still checked when trying to Modify the install. I tried unchecking and updating the install but next time I went back to Modify, it was still checked. And still no MVC template.

I got it working by uninstalling: Microsoft ASP.NET Web Frameworks and Tools 2015 via the Programs and Features windows and re-installing. Here's the link for those who don't have it.

How to split a string, but also keep the delimiters?

I had a look at the above answers and honestly none of them I find satisfactory. What you want to do is essentially mimic the Perl split functionality. Why Java doesn't allow this and have a join() method somewhere is beyond me but I digress. You don't even need a class for this really. Its just a function. Run this sample program:

Some of the earlier answers have excessive null-checking, which I recently wrote a response to a question here:

https://stackoverflow.com/users/18393/cletus

Anyway, the code:

public class Split {
    public static List<String> split(String s, String pattern) {
        assert s != null;
        assert pattern != null;
        return split(s, Pattern.compile(pattern));
    }

    public static List<String> split(String s, Pattern pattern) {
        assert s != null;
        assert pattern != null;
        Matcher m = pattern.matcher(s);
        List<String> ret = new ArrayList<String>();
        int start = 0;
        while (m.find()) {
            ret.add(s.substring(start, m.start()));
            ret.add(m.group());
            start = m.end();
        }
        ret.add(start >= s.length() ? "" : s.substring(start));
        return ret;
    }

    private static void testSplit(String s, String pattern) {
        System.out.printf("Splitting '%s' with pattern '%s'%n", s, pattern);
        List<String> tokens = split(s, pattern);
        System.out.printf("Found %d matches%n", tokens.size());
        int i = 0;
        for (String token : tokens) {
            System.out.printf("  %d/%d: '%s'%n", ++i, tokens.size(), token);
        }
        System.out.println();
    }

    public static void main(String args[]) {
        testSplit("abcdefghij", "z"); // "abcdefghij"
        testSplit("abcdefghij", "f"); // "abcde", "f", "ghi"
        testSplit("abcdefghij", "j"); // "abcdefghi", "j", ""
        testSplit("abcdefghij", "a"); // "", "a", "bcdefghij"
        testSplit("abcdefghij", "[bdfh]"); // "a", "b", "c", "d", "e", "f", "g", "h", "ij"
    }
}

How do I measure separate CPU core usage for a process?

dstat -C 0,1,2,3 

Will also give you the CPU usage of first 4 cores. Of course, if you have 32 cores then this command gets a little bit longer but useful if you only interested in few cores.

For example, if you only interested in core 3 and 7 then you could do

dstat -C 3,7

How to Run Terminal as Administrator on Mac Pro

Add sudo to your command line, like:

$ sudo firebase init

'Incomplete final line' warning when trying to read a .csv file into R

I received the same message. My fix included: I deleted all the additional sheets (tabs) in the .csv file, eliminated non-numeric characters, resaved the file as comma delimited and loaded in R v 2.15.0 using standard language:

filename<-read.csv("filename",header=TRUE)

As an additional safeguard, I closed the software and reopened before I loaded the csv.

How to add multiple jar files in classpath in linux

You use the -classpath argument. You can use either a relative or absolute path. What that means is you can use a path relative to your current directory, OR you can use an absolute path that starts at the root /.

Example:

bash$ java -classpath path/to/jar/file MyMainClass

In this example the main function is located in MyMainClass and would be included somewhere in the jar file.

For compiling you need to use javac

Example:

bash$ javac -classpath path/to/jar/file MyMainClass.java

You can also specify the classpath via the environment variable, follow this example:

bash$ export CLASSPATH="path/to/jar/file:path/tojar/file2"
bash$ javac MyMainClass.java

For any normally complex java project you should look for the ant script named build.xml

Where's javax.servlet?

The normal procedure with Eclipse and Java EE webapplications is to install a servlet container (Tomcat, Jetty, etc) or application server (Glassfish (which is bundled in the "Sun Java EE" download), JBoss AS, WebSphere, Weblogic, etc) and integrate it in Eclipse using a (builtin) plugin in the Servers view.

During the creation wizard of a new Dynamic Web Project, you can then pick the integrated server from the list. If you happen to have an existing Dynamic Web Project without a server or want to change the associated one, then you need to modify it in the Targeted Rutimes section of the project's properties.

Either way, Eclipse will automatically place the necessary server-specific libraries in the project's classpath (buildpath).

You should absolutely in no way extract and copy server-specific libraries into /WEB-INF/lib or even worse the JRE/lib yourself, to "fix" the compilation errors in Eclipse. It would make your webapplication tied to a specific server and thus completely unportable.

Code signing is required for product type Unit Test Bundle in SDK iOS 8.0

In my case the problem that I faced was:

CodeSign error: code signing is required for product type 'Unit Test Bundle' in SDK 'iOS 8.4'

Fortunatelly, the target did not implemented anything, so a quick solution is remove it.

enter image description here

What is the standard Python docstring format?

I suggest using Vladimir Keleshev's pep257 Python program to check your docstrings against PEP-257 and the Numpy Docstring Standard for describing parameters, returns, etc.

pep257 will report divergence you make from the standard and is called like pylint and pep8.

round up to 2 decimal places in java?

Go back to your code, and replace 100 by 100.00 and let me know if it works. However, if you want to be formal, try this:

import java.text.DecimalFormat;
DecimalFormat df=new DecimalFormat("0.00");
String formate = df.format(value); 
double finalValue = (Double)df.parse(formate) ;

How do you get a query string on Flask?

I came here looking for the query string, not how to get values from the query string.

request.query_string returns the URL parameters as raw byte string (Ref 1).

Example of using request.query_string:

from flask import Flask, request

app = Flask(__name__)

@app.route('/data', methods=['GET'])
def get_query_string():
    return request.query_string

if __name__ == '__main__':
    app.run(debug=True)

Output:

query parameters in Flask route

References:

  1. Official API documentation on query_string

Python - add PYTHONPATH during command line module run

 import sys
 sys.path.append('your certain directory')

Basically sys.path is a list with all the search paths for python modules. It is initialized by the interpreter. The content of PYTHONPATH is automatically added to the end of that list.

How to enter in a Docker container already running with a new TTY

I started powershell on a running microsoft/iis run as daemon using

docker exec -it <nameOfContainer> powershell

How to export data from Spark SQL to CSV

The error message suggests this is not a supported feature in the query language. But you can save a DataFrame in any format as usual through the RDD interface (df.rdd.saveAsTextFile). Or you can check out https://github.com/databricks/spark-csv.

How do I find the distance between two points?

dist = sqrt( (x2 - x1)**2 + (y2 - y1)**2 )

As others have pointed out, you can also use the equivalent built-in math.hypot():

dist = math.hypot(x2 - x1, y2 - y1)

What is the best workaround for the WCF client `using` block issue?

Given a choice between the solution advocated by IServiceOriented.com and the solution advocated by David Barret's blog, I prefer the simplicity offered by overriding the client's Dispose() method. This allows me to continue to use the using() statement as one would expect with a disposable object. However, as @Brian pointed out, this solution contains a race condition in that the State might not be faulted when it is checked but could be by the time Close() is called, in which case the CommunicationException still occurs.

So, to get around this, I've employed a solution that mixes the best of both worlds.

void IDisposable.Dispose()
{
    bool success = false;
    try 
    {
        if (State != CommunicationState.Faulted) 
        {
            Close();
            success = true;
        }
    } 
    finally 
    {
        if (!success) 
            Abort();
    }
}

How to have image and text side by side

You're already doing it correctly, it just that the <h4>Facebook</h4> tag is taking too much vertical margin. You can remove it by using the style margin:0px on the <h4> tag.

For your future convenience, you can put border (border:1px solid black) on your elements to see which part you actually get it wrong.

Convert list of ASCII codes to string (byte array) in Python

Shorter version of previous using map() function (works for python 2.7):

"".join(map(chr, myList))

Is there an upside down caret character?

I did subscript capital & bolded V. It works perfectly (although it takes some effort, if it needs to be done repetitively)

Syntax:

<sub><strong>v</strong></sub>

Output:
v

iTunes Connect: How to choose a good SKU?

Might be answer is late but look at Simple Information of SKU (Stock keeping unit) number is, it's an unique tracking number (an arbi­trary num­ber) that are used in appStore for your application. You can put what­ever you want in there as long as it is unique among your appli­ca­tions. Try to fol­low a pat­tern for the SKU Num­ber of your apps so that you will be able to bet­ter orga­nize them. I sug­gest a com­bi­na­tion of the cur­rent year + month + ID for your app. So if you’re devel­op­ing your first appli­ca­tion on september 1991 (oh,, yah it's my b'day's month and year :D ), you could put your SKU Num­ber as “19910901”. Here, I am just suggesting you for this pattern but you can take/choose any pattern which easy for you.

How to return a complex JSON response with Node.js?

I don't know if this is really any different, but rather than iterate over the query cursor, you could do something like this:

query.exec(function (err, results){
  if (err) res.writeHead(500, err.message)
  else if (!results.length) res.writeHead(404);
  else {
    res.writeHead(200, { 'Content-Type': 'application/json' });
    res.write(JSON.stringify(results.map(function (msg){ return {msgId: msg.fileName}; })));
  }
  res.end();
});

How to replace all occurrences of a character in string?

Imagine a large binary blob where all 0x00 bytes shall be replaced by "\1\x30" and all 0x01 bytes by "\1\x31" because the transport protocol allows no \0-bytes.

In cases where:

  • the replacing and the to-replaced string have different lengths,
  • there are many occurences of the to-replaced string within the source string and
  • the source string is large,

the provided solutions cannot be applied (because they replace only single characters) or have a performance problem, because they would call string::replace several times which generates copies of the size of the blob over and over. (I do not know the boost solution, maybe it is OK from that perspective)

This one walks along all occurrences in the source string and builds the new string piece by piece once:

void replaceAll(std::string& source, const std::string& from, const std::string& to)
{
    std::string newString;
    newString.reserve(source.length());  // avoids a few memory allocations

    std::string::size_type lastPos = 0;
    std::string::size_type findPos;

    while(std::string::npos != (findPos = source.find(from, lastPos)))
    {
        newString.append(source, lastPos, findPos - lastPos);
        newString += to;
        lastPos = findPos + from.length();
    }

    // Care for the rest after last occurrence
    newString += source.substr(lastPos);

    source.swap(newString);
}

remote rejected master -> master (pre-receive hook declined)

Mine finally worked somewhere along this road:

  1. Updating Git
  2. back to \my_first_rail_app\, type or run:
    • a. bundle install
    • b. bundle install --gemfile
    • c. bundle update
    • d. git add .
    • e. git commit -m "updates for heroku deployment"
    • f. git pust heroku master (still wont work with my case)
    • g. heroku buildpacks:set https://github.com/bundler/heroku-buildpack-bundler2

How to make a <button> in Bootstrap look like a normal link in nav-tabs?

I've tried all examples, posted here, but they do not work without extra CSS. Try this:

<a href="http://www.google.com"><button type="button" class="btn btn-success">Google</button></a>

Works perfectly without any extra CSS.

How to count the number of columns in a table using SQL?

select count(*) 
from user_tab_columns
where table_name='MYTABLE' --use upper case

Instead of uppercase you can use lower function. Ex: select count(*) from user_tab_columns where lower(table_name)='table_name';

JQuery html() vs. innerHTML

innerHTML is not standard and may not work in some browsers. I have used html() in all browsers with no problem.

Posting a File and Associated Data to a RESTful WebService preferably as JSON

I know this question is old, but in the last days I had searched whole web to solution this same question. I have grails REST webservices and iPhone Client that send pictures, title and description.

I don't know if my approach is the best, but is so easy and simple.

I take a picture using the UIImagePickerController and send to server the NSData using the header tags of request to send the picture's data.

NSMutableURLRequest *request = [[NSMutableURLRequest alloc] initWithURL:[NSURL URLWithString:@"myServerAddress"]];
[request setHTTPMethod:@"POST"];
[request setHTTPBody:UIImageJPEGRepresentation(picture, 0.5)];
[request setValue:@"image/jpeg" forHTTPHeaderField:@"Content-Type"];
[request setValue:@"myPhotoTitle" forHTTPHeaderField:@"Photo-Title"];
[request setValue:@"myPhotoDescription" forHTTPHeaderField:@"Photo-Description"];

NSURLResponse *response;

NSError *error;

[NSURLConnection sendSynchronousRequest:request returningResponse:&response error:&error];

At the server side, I receive the photo using the code:

InputStream is = request.inputStream

def receivedPhotoFile = (IOUtils.toByteArray(is))

def photo = new Photo()
photo.photoFile = receivedPhotoFile //photoFile is a transient attribute
photo.title = request.getHeader("Photo-Title")
photo.description = request.getHeader("Photo-Description")
photo.imageURL = "temp"    

if (photo.save()) {    

    File saveLocation = grailsAttributes.getApplicationContext().getResource(File.separator + "images").getFile()
    saveLocation.mkdirs()

    File tempFile = File.createTempFile("photo", ".jpg", saveLocation)

    photo.imageURL = saveLocation.getName() + "/" + tempFile.getName()

    tempFile.append(photo.photoFile);

} else {

    println("Error")

}

I don't know if I have problems in future, but now is working fine in production environment.

IF/ELSE Stored Procedure

Try this with SQL join statements

CREATE PROCEDURE [dbo].[deleteItem]
   @ItemId int = 0  
 AS
 Begin
 DECLARE @cnt int;

SET NOCOUNT ON
SELECT @cnt =COUNT(ttm.Id) 
    from ItemTransaction itr INNER JOIN ItemUnitMeasurement ium 
        ON itr.Id = ium.ItemTransactionId  INNER JOIN ItemMaster im 
        ON itr.ItemId = im.Id INNER JOIN TransactionTypeMaster ttm 
        ON itr.TransactionTypeMasterId = ttm.Id 
        where im.Id = @ItemId

if(@cnt = 1)
    Begin
    DECLARE @transactionType varchar(255);
    DECLARE @mesurementAmount float;
    DECLARE @itemTransactionId int;
    DECLARE @itemUnitMeasurementId int;

        SELECT @transactionType = ttm.TransactionType,  @mesurementAmount = ium.Amount, @itemTransactionId = itr.Id, @itemUnitMeasurementId = ium.Id
        from ItemTransaction itr INNER JOIN ItemUnitMeasurement ium 
            ON itr.Id = ium.ItemTransactionId INNER JOIN TransactionTypeMaster ttm 
            ON itr.TransactionTypeMasterId = ttm.Id 
            where itr.ItemId = @ItemId  
        if(@transactionType = 'Close' and @mesurementAmount = 0)
            Begin
                delete from ItemUnitMeasurement where Id = @itemUnitMeasurementId;

            End
        else
            Begin
                delete from ItemTransaction where Id = @itemTransactionId;
            End
    End
else
 Begin
    delete from ItemMaster where Id = @ItemId;
 End

END

Do something if screen width is less than 960 px

Use jQuery to get the width of the window.

if ($(window).width() < 960) {
   alert('Less than 960');
}
else {
   alert('More than 960');
}

How to edit a JavaScript alert box title?

Override the javascript window.alert() function.

window.alert = function(title, message){
    var myElementToShow = document.getElementById("someElementId");
    myElementToShow.innerHTML = title + "</br>" + message; 
}

With this you can create your own alert() function. Create a new 'cool' looking dialog (from some div elements).

Tested working in chrome and webkit, not sure of others.

git push rejected: error: failed to push some refs

'remote: error: denying non-fast-forward refs/heads/master (you should pull first)'

That message suggests that there is a hook on the server that is rejecting fast forward pushes. Yes, it is usually not recommended and is a good guard, but since you are the only person using it and you want to do the force push, contact the administrator of the repo to allow to do the non-fastforward push by temporarily removing the hook or giving you the permission in the hook to do so.

NHibernate.MappingException: No persister for: XYZ

Make sure you have called the CreateCriteria(typeof(DomainObjectType)) method on Session for the domain object which you intent to fetch from DB.

if statement in ng-click

Don't put any Condition Expression in Template.

Do it at the Controller.

Template:

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

Controller:

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

How to delete object from array inside foreach loop?

It looks like your syntax for unset is invalid, and the lack of reindexing might cause trouble in the future. See: the section on PHP arrays.

The correct syntax is shown above. Also keep in mind array-values for reindexing, so you don't ever index something you previously deleted.

How to make a HTTP request using Ruby on Rails?

I prefer httpclient over Net::HTTP.

client = HTTPClient.new
puts client.get_content('http://www.example.com/index.html')

HTTParty is a good choice if you're making a class that's a client for a service. It's a convenient mixin that gives you 90% of what you need. See how short the Google and Twitter clients are in the examples.

And to answer your second question: no, I wouldn't put this functionality in a controller--I'd use a model instead if possible to encapsulate the particulars (perhaps using HTTParty) and simply call it from the controller.

"query function not defined for Select2 undefined error"

It seems that your selector returns an undefined element (Therefore undefined error is returned)

In case the element really exists, you are calling select2 on an input element without supplying anything to select2, where it should fetch the data from. Typically, one calls .select2({data: [{id:"firstid", text:"firsttext"}]).

Can I get "&&" or "-and" to work in PowerShell?

I tried this sequence of commands in PowerShell:

First Test

PS C:\> $MyVar = "C:\MyTxt.txt"
PS C:\> ($MyVar -ne $null) -and (Get-Content $MyVar)
True

($MyVar -ne $null) returned true and (Get-Content $MyVar) also returned true.

Second Test

PS C:\> $MyVar = $null
PS C:\> ($MyVar -ne $null) -and (Get-Content $MyVar)
False

($MyVar -ne $null) returned false and so far I must assume the (Get-Content $MyVar) also returned false.

The third test proved the second condition was not even analyzed.

PS C:\> ($MyVar -ne $null) -and (Get-Content "C:\MyTxt.txt")
False

($MyVar -ne $null) returned false and proved the second condition (Get-Content "C:\MyTxt.txt") never ran, by returning false on the whole command.

phpMyAdmin + CentOS 6.0 - Forbidden

I tried all answers provided here: editing phpMyAdmin.conf, changing selinux context for phpmyadmin folder, disabling selinux... but I still got a 'Forbidden' from the web server.

I finally found what I was missing in Edouard Thiel post here :

$ yum install php

then restart httpd :

$ service httpd restart => for centos 6 hots

$ systemctl restart httpd => for centos 7 hosts

What has me amazed is why php is not installed as dependency for phpmyadmin in the first place.

Regards, Fred

WCF Service Client: The content type text/html; charset=utf-8 of the response message does not match the content type of the binding

If your are using both wshttpbinding along with https request, then i resolved it by using the below configuration change.

 <security mode="TransportWithMessageCredential">
                    <transport clientCredentialType="None" />
                    <message clientCredentialType="Certificate" />
                </security>

Debian 8 (Live-CD) what is the standard login and password?

I am using Debian 8 live off a USB. I was locked out of the system after 10 min of inactivity. The password that was required to log back in to the system for the user was:

login : Debian Live User
password : live

I hope this helps

Create directories using make file

OS independence is critical for me, so mkdir -p is not an option. I created this series of functions that use eval to create directory targets with the prerequisite on the parent directory. This has the benefit that make -j 2 will work without issue since the dependencies are correctly determined.

# convenience function for getting parent directory, will eventually return ./
#     $(call get_parent_dir,somewhere/on/earth/) -> somewhere/on/
get_parent_dir=$(dir $(patsubst %/,%,$1))

# function to create directory targets.
# All directories have order-only-prerequisites on their parent directories
# https://www.gnu.org/software/make/manual/html_node/Prerequisite-Types.html#Prerequisite-Types
TARGET_DIRS:=
define make_dirs_recursively
TARGET_DIRS+=$1
$1: | $(if $(subst ./,,$(call get_parent_dir,$1)),$(call get_parent_dir,$1))
    mkdir $1
endef

# function to recursively get all directories 
#     $(call get_all_dirs,things/and/places/) -> things/ things/and/ things/and/places/
#     $(call get_all_dirs,things/and/places) -> things/ things/and/
get_all_dirs=$(if $(subst ./,,$(dir $1)),$(call get_all_dirs,$(call get_parent_dir,$1)) $1)

# function to turn all targets into directories
#     $(call get_all_target_dirs,obj/a.o obj/three/b.o) -> obj/ obj/three/
get_all_target_dirs=$(sort $(foreach target,$1,$(call get_all_dirs,$(dir $(target)))))

# create target dirs
create_dirs=$(foreach dirname,$(call get_all_target_dirs,$1),$(eval $(call make_dirs_recursively,$(dirname))))

TARGETS := w/h/a/t/e/v/e/r/things.dat w/h/a/t/things.dat

all: $(TARGETS)

# this must be placed after your .DEFAULT_GOAL, or you can manually state what it is
# https://www.gnu.org/software/make/manual/html_node/Special-Variables.html
$(call create_dirs,$(TARGETS))

# $(TARGET_DIRS) needs to be an order-only-prerequisite
w/h/a/t/e/v/e/r/things.dat: w/h/a/t/things.dat | $(TARGET_DIRS)
    echo whatever happens > $@

w/h/a/t/things.dat: | $(TARGET_DIRS)
    echo whatever happens > $@

For example, running the above will create:

$ make
mkdir w/
mkdir w/h/
mkdir w/h/a/
mkdir w/h/a/t/
mkdir w/h/a/t/e/
mkdir w/h/a/t/e/v/
mkdir w/h/a/t/e/v/e/
mkdir w/h/a/t/e/v/e/r/
echo whatever happens > w/h/a/t/things.dat
echo whatever happens > w/h/a/t/e/v/e/r/things.dat

Why are empty catch blocks a bad idea?

If you dont know what to do in catch block, you can just log this exception, but dont leave it blank.

        try
        {
            string a = "125";
            int b = int.Parse(a);
        }
        catch (Exception ex)
        {
            Log.LogError(ex);
        }

How do I insert a JPEG image into a python Tkinter window?

from tkinter import *
from PIL import ImageTk, Image

window = Tk()
window.geometry("1000x300")

path = "1.jpg"

image = PhotoImage(Image.open(path))

panel = Label(window, image = image)

panel.pack()

window.mainloop()

Set background image according to screen resolution

Delete your "body background image code" then paste this code:

html { 
    background: url(../img/background.jpg) no-repeat center center fixed #000; 
    -webkit-background-size: cover;
    -moz-background-size: cover;
    -o-background-size: cover;
    background-size: cover;
}

JAVA_HOME is set to an invalid directory:

You need to set with only C:\Program Files\Java\jdk1.8.0_12.

And check with using new cmd. It will be updated

Simulate a button click in Jest

Using Jest, you can do it like this:

test('it calls start logout on button click', () => {
    const mockLogout = jest.fn();
    const wrapper = shallow(<Component startLogout={mockLogout}/>);
    wrapper.find('button').at(0).simulate('click');
    expect(mockLogout).toHaveBeenCalled();
});

How to: Install Plugin in Android Studio

2019: With Android Studio 3.4.2 started:

  1. Click on File -> Settings
  2. Find "Plugins" in the left pane of the popup window and click on it
  3. Click on the Gear in the upper right
  4. Click on "Install Plugin from Disk"
  5. Find your plugin from the file browser or drag and drop it from another window to go to it in the browse window, then click on it then click "OK"
  6. The browse window will close
  7. Click "OK" on the setting window
  8. Click "Restart" on the popup

How to check if an integer is within a range of numbers in PHP?

$ranges = [
    1 => [
        'min_range' => 0.01,
        'max_range' => 199.99
    ],
    2 => [
        'min_range' => 200.00,
    ],
];

   foreach( $ranges as $value => $range ){
        if( filter_var( $cartTotal, FILTER_VALIDATE_FLOAT, [ 'options' => $range ] ) ){
            return $value;
        }
    }

Cycles in an Undirected Graph

An undirected graph is acyclic (i.e., a forest) if a DFS yields no back edges. Since back edges are those edges (u, v) connecting a vertex u to an ancestor v in a depth-first tree, so no back edges means there are only tree edges, so there is no cycle. So we can simply run DFS. If find a back edge, there is a cycle. The complexity is O(V) instead of O(E + V). Since if there is a back edge, it must be found before seeing |V| distinct edges. This is because in a acyclic (undirected) forest, |E| = |V| + 1.

Numpy: Divide each row by a vector element

Adding to the answer of stackoverflowuser2010, in the general case you can just use

data = np.array([[1,1,1],[2,2,2],[3,3,3]])

vector = np.array([1,2,3])

data / vector.reshape(-1,1)

This will turn your vector into a column matrix/vector. Allowing you to do the elementwise operations as you wish. At least to me, this is the most intuitive way going about it and since (in most cases) numpy will just use a view of the same internal memory for the reshaping it's efficient too.

IsNumeric function in c#

To totally steal from Bill answer you can make an extension method and use some syntactic sugar to help you out.

Create a class file, StringExtensions.cs

Content:

public static class StringExt
{
    public static bool IsNumeric(this string text)
    {
        double test;
        return double.TryParse(text, out test);
    }
}

EDIT: This is for updated C# 7 syntax. Declaring out parameter in-line.

public static class StringExt
{
    public static bool IsNumeric(this string text) => double.TryParse(text, out _);

}

Call method like such:

var text = "I am not a number";
text.IsNumeric()  //<--- returns false

Unique Key constraints for multiple columns in Entity Framework

With Entity Framework 6.1, you can now do this:

[Index("IX_FirstAndSecond", 1, IsUnique = true)]
public int FirstColumn { get; set; }

[Index("IX_FirstAndSecond", 2, IsUnique = true)]
public int SecondColumn { get; set; }

The second parameter in the attribute is where you can specify the order of the columns in the index.
More information: MSDN

Linux: where are environment variables stored?

Type "set" and you will get a list of all the current variables. If you want something to persist put it in ~/.bashrc or ~/.bash_profile (if you're using bash)

Visual Studio debugging/loading very slow

I had execution perfomance troubles with debugging too and i tried very many options of debugger. In my case huge perfomance achieved when i change this options:

Tools - Options - Debugging - Output Window - (General output settings - All debug output) - OFF

Easy way to get a test file into JUnit

If you want to load a test resource file as a string with just few lines of code and without any extra dependencies, this does the trick:

public String loadResourceAsString(String fileName) throws IOException {
    Scanner scanner = new Scanner(getClass().getClassLoader().getResourceAsStream(fileName));
    String contents = scanner.useDelimiter("\\A").next();
    scanner.close();
    return contents;
}

"\\A" matches the start of input and there's only ever one. So this parses the entire file contents and returns it as a string. Best of all, it doesn't require any 3rd party libraries (like IOUTils).

Yii2 data provider default sorting

Or

       $dataProvider->setSort([
        'defaultOrder' => ['topic_order'=>SORT_DESC],
        'attributes' => [...

How to add 'ON DELETE CASCADE' in ALTER TABLE statement

Here is an handy solution! I'm using SQL Server 2008 R2.

As you want to modify the FK constraint by adding ON DELETE/UPDATE CASCADE, follow these steps:

NUMBER 1:

Right click on the constraint and click to Modify

enter image description here

NUMBER 2:

Choose your constraint on the left side (if there are more than one). Then on the right side, collapse "INSERT And UPDATE Specification" point and specify the actions on Delete Rule or Update Rule row to suit your need. After that, close the dialog box.

enter image description here

NUMBER 3:

The final step is to save theses modifications (of course!)

enter image description here

PS: It's saved me from a bunch of work as I want to modify a primary key referenced in another table.

EC2 Instance Cloning

There is no explicit Clone button. Basically what you do is create an image, or snapshot of an existing EC2 instance, and then spin up a new instance using that snapshot.

First create an image from an existing EC2 instance.

enter image description here


Check your snapshots list to see if the process is completed. This usually takes around 20 minutes depending on how large your instance drive is.

enter image description here


Then, you need to create a new instance and use that image as the AMI.

enter image description here

enter image description here

One line if-condition-assignment

you can use one of the following:

(falseVal, trueVal)[TEST]

TEST and trueVal or falseVal

The HTTP request is unauthorized with client authentication scheme 'Negotiate'. The authentication header received from the server was 'NTLM'

THE ANSWER: The problem was all of the posts for such an issue were related to older kerberos and IIS issues where proxy credentials or AllowNTLM properties were helping. My case was different. What I have discovered after hours of picking worms from the ground was that somewhat IIS installation did not include Negotiate provider under IIS Windows authentication providers list. So I had to add it and move up. My WCF service started to authenticate as expected. Here is the screenshot how it should look if you are using Windows authentication with Anonymous auth OFF.

You need to right click on Windows authentication and choose providers menu item.

enter image description here

Hope this helps to save some time.

How to format number of decimal places in wpf using style/template?

    void NumericTextBoxInput(object sender, TextCompositionEventArgs e)
    {
        TextBox txt = (TextBox)sender;
        var regex = new Regex(@"^[0-9]*(?:\.[0-9]{0,1})?$");
        string str = txt.Text + e.Text.ToString();
        int cntPrc = 0;
        if (str.Contains('.'))
        {
            string[] tokens = str.Split('.');
            if (tokens.Count() > 0)
            {
                string result = tokens[1];
                char[] prc = result.ToCharArray();
                cntPrc = prc.Count();
            }
        }
        if (regex.IsMatch(e.Text) && !(e.Text == "." && ((TextBox)sender).Text.Contains(e.Text)) && (cntPrc < 3))
        {
            e.Handled = false;
        }
        else
        {
            e.Handled = true;
        }
    }

How to view the assembly behind the code using Visual C++?

The earlier version of this answer (a "hack" for rextester.com) is mostly redundant now that http://gcc.godbolt.org/ provides CL 19 RC for ARM, x86, and x86-64 (targeting the Windows calling convention, unlike gcc, clang, and icc on that site).

The Godbolt compiler explorer is designed for nicely formatting compiler asm output, removing the "noise" of directives, so I'd highly recommend using it to look at asm for simple functions that take args and return a value (so they won't be optimized away).

For a while, CL was available on http://gcc.beta.godbolt.org/ but not the main site, but now it's on both.


To get MSVC asm output from the http://rextester.com/l/cpp_online_compiler_visual online compiler: Add /FAs to the command line options. Have your program find its own path and work out the path to the .asm and dump it. Or run a disassembler on the .exe.

e.g. http://rextester.com/OKI40941

#include <string>
#include <boost/filesystem.hpp>
#include <Windows.h>

using namespace std;

static string my_exe(void){
    char buf[MAX_PATH];
    DWORD tmp = GetModuleFileNameA( NULL, // self
                                  buf, MAX_PATH);
    return buf;
}

int main() {
    string dircmd = "dir ";
    boost::filesystem::path p( my_exe() );
    //boost::filesystem::path dir = p.parent_path();

    // transform c:\foo\bar\1234\a.exe 
    // into      c:\foo\bar\1234\1234.asm
    p.remove_filename();
    system ( (dircmd + p.string()).c_str() );

    auto subdir = p.end();      // pointing at one-past the end
    subdir--;                   // pointing at the last directory name
    p /= *subdir;               // append the last dir name as a filename
    p.replace_extension(".asm");
    system ( (string("type ") + p.string()).c_str() );
//    std::cout << "Hello, world!\n";
}

... code of functions you want to see the asm for goes here ...

type is the DOS version of cat. I didn't want to include more code that would make it harder to find the functions I wanted to see the asm for. (Although using std::string and boost run counter to those goals! Some C-style string manipulation that makes more assumptions about the string it's processing (and ignores max-length safety / allocation by using a big buffer) on the result of GetModuleFileNameA would be much less total machine code.)

IDK why, but cout << p.string() << endl only shows the basename (i.e. the filename, without the directories), even though printing its length shows it's not just the bare name. (Chromium48 on Ubuntu 15.10). There's probably some backslash-escape processing at some point in cout, or between the program's stdout and the web browser.

Error In PHP5 ..Unable to load dynamic library

Seems like you upgraded PHP to newer version and old .ini files are still pointing to old location.

The solution: find out where are modules located now

ls -l /usr/lib/php5

There should be a directory similar to old 20090626. In my case it is now 20131226

The .ini files giving you an error are located at /etc/php5/cli/conf.d/

Just edit those .ini files which module gives you an error. For example, in case the error is for mcrypt module:

sudo vi /etc/php5/cli/conf.d/20-mcrypt.ini

Change the line:

extension=/usr/lib/php5/20090626/mcrypt.so

to reflect the new path for .so file. In my case the correct path should be:

extension=/usr/lib/php5/20131226/mcrypt.so

That's it! The error is gone. Ofc you'd have to do it with each module giving you an error.

Static Classes In Java

Java has static methods that are associated with classes (e.g. java.lang.Math has only static methods), but the class itself is not static.

How can I INSERT data into two tables simultaneously in SQL Server?

Create table #temp1
(
 id int identity(1,1),
 name varchar(50),
 profession varchar(50)
)

Create table #temp2
(
 id int identity(1,1),
 name varchar(50),
 profession varchar(50)
)

-----main query ------

insert into #temp1(name,profession)

output inserted.name,inserted.profession into #temp2

select 'Shekhar','IT'

javascript return true or return false when and how to use it?

I think a lot of times when you see this code, it's from people who are in the habit of event handlers for forms, buttons, inputs, and things of that sort.

Basically, when you have something like:

<form onsubmit="return callSomeFunction();"></form>

or

<a href="#" onclick="return callSomeFunction();"></a>`

and callSomeFunction() returns true, then the form or a will submit, otherwise it won't.

Other more obvious general purposes for returning true or false as a result of a function are because they are expected to return a boolean.

How to escape strings in SQL Server using PHP?

addslashes() isn't fully adequate, but PHP's mssql package doesn't provide any decent alternative. The ugly but fully general solution is encoding the data as a hex bytestring, i.e.

$unpacked = unpack('H*hex', $data);
mssql_query('
    INSERT INTO sometable (somecolumn)
    VALUES (0x' . $unpacked['hex'] . ')
');

Abstracted, that would be:

function mssql_escape($data) {
    if(is_numeric($data))
        return $data;
    $unpacked = unpack('H*hex', $data);
    return '0x' . $unpacked['hex'];
}

mssql_query('
    INSERT INTO sometable (somecolumn)
    VALUES (' . mssql_escape($somevalue) . ')
');

mysql_error() equivalent is mssql_get_last_message().

How do I get the total number of unique pairs of a set in the database?

I was solving this algorithm and get stuck with the pairs part.

This explanation help me a lot https://betterexplained.com/articles/techniques-for-adding-the-numbers-1-to-100/

So to calculate the sum of series of numbers:

n(n+1)/2

But you need to calculate this

1 + 2 + ... + (n-1)

So in order to get this you can use

n(n+1)/2 - n

that is equal to

n(n-1)/2

SQL Query Multiple Columns Using Distinct on One Column Only

I suppose the easiest and the best solution is using OUTER APPLY. You only use one field with DISTINCT but to retrieve more data about that record, you utilize OUTER APPLY.

To test the solution, execute following query which firstly creates a temp table then retrieves data:

 DECLARE @tblFruit TABLE (tblFruit_ID int, tblFruit_FruitType varchar(10), tblFruit_FruitName varchar(50))
 SET NOCOUNT ON
 INSERT @tblFruit VALUES (1,'Citrus ','Orange')
 INSERT @tblFruit VALUES (2,'Citrus','Lime')
 INSERT @tblFruit VALUES (3,'Citrus','Lemon')
 INSERT @tblFruit VALUES (4,'Seed','Cherry')
 INSERT @tblFruit VALUES (5,'Seed','Banana')
   
SELECT DISTINCT (f.tblFruit_FruitType), outter_f.tblFruit_ID
FROM @tblFruit AS f
OUTER APPLY (
    SELECT TOP(1) *
    FROM @tblFruit AS inner_f
    WHERE inner_f.tblFruit_FruitType = f.tblFruit_FruitType
) AS outter_f

The result will be:

Citrus 1

Seed 4

How to change value of process.env.PORT in node.js?

use the below command to set the port number in node process while running node JS programme:

set PORT =3000 && node file_name.js

The set port can be accessed in the code as

process.env.PORT 

JavaScript: Global variables after Ajax requests

What you expect is the synchronous (blocking) type request.

var it_works = false;

jQuery.ajax({
  type: "POST",
  url: 'some_file.php',
  success: function (data) {
    it_works = true;
  }, 
  async: false // <- this turns it into synchronous
});?

// Execution is BLOCKED until request finishes.

// it_works is available
alert(it_works);

Requests are asynchronous (non-blocking) by default which means that the browser won't wait for them to be completed in order to continue its work. That's why your alert got wrong result.

Now, with jQuery.ajax you can optionally set the request to be synchronous, which means that the script will only continue to run after the request is finished.


The RECOMMENDED way, however, is to refactor your code so that the data would be passed to a callback function as soon as the request is finished. This is preferred because blocking execution means blocking the UI which is unacceptable. Do it this way:

$.post("some_file.php", '', function(data) {
    iDependOnMyParameter(data);
});

function iDependOnMyParameter(param) {
    // You should do your work here that depends on the result of the request!
    alert(param)
}

// All code here should be INDEPENDENT of the result of your AJAX request
// ...

Asynchronous programming is slightly more complicated because the consequence of making a request is encapsulated in a function instead of following the request statement. But the realtime behavior that the user experiences can be significantly better because they will not see a sluggish server or sluggish network cause the browser to act as though it had crashed. Synchronous programming is disrespectful and should not be employed in applications which are used by people.

Douglas Crockford (YUI Blog)

How to distinguish between left and right mouse click with jQuery

event.which === 1 ensures it's a left-click (when using jQuery).

But you should also think about modifier keys: ctrlcmdshiftalt

If you're only interested in catching simple, unmodified left-clicks, you can do something like this:

var isSimpleClick = function (event) {
  return !(
    event.which !== 1 || // not a left click
    event.metaKey ||     // "open link in new tab" (mac)
    event.ctrlKey ||     // "open link in new tab" (windows/linux)
    event.shiftKey ||    // "open link in new window"
    event.altKey         // "save link as"
  );
};

$('a').on('click', function (event) {
  if (isSimpleClick(event)) {
    event.preventDefault();
    // do something...
  }
});

Javascript receipt printing using POS Printer

You could try using https://www.printnode.com which is essentially exactly the service that you are looking for. You download and install a desktop client onto the users computer - https://www.printnode.com/download. You can then discover and print to any printers on that user's computer using their JSON API https://www.printnode.com/docs/api/curl/. They have lots of libs here: https://github.com/PrintNode/

pandas create new column based on values from other columns / apply a function of multiple columns, row-wise

Since this is the first Google result for 'pandas new column from others', here's a simple example:

import pandas as pd

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

# create an unattached column with an index
df.apply(lambda row: row.a + row.b, axis=1)
# 0    4
# 1    6

# do same but attach it to the dataframe
df['c'] = df.apply(lambda row: row.a + row.b, axis=1)
df
#    a  b  c
# 0  1  3  4
# 1  2  4  6

If you get the SettingWithCopyWarning you can do it this way also:

fn = lambda row: row.a + row.b # define a function for the new column
col = df.apply(fn, axis=1) # get column data with an index
df = df.assign(c=col.values) # assign values to column 'c'

Source: https://stackoverflow.com/a/12555510/243392

And if your column name includes spaces you can use syntax like this:

df = df.assign(**{'some column name': col.values})

And here's the documentation for apply, and assign.

Bloomberg BDH function with ISIN

The problem is that an isin does not identify the exchange, only an issuer.

Let's say your isin is US4592001014 (IBM), one way to do it would be:

  • get the ticker (in A1):

    =BDP("US4592001014 ISIN", "TICKER") => IBM
    
  • get a proper symbol (in A2)

    =BDP("US4592001014 ISIN", "PARSEKYABLE_DES") => IBM XX Equity
    

    where XX depends on your terminal settings, which you can check on CNDF <Go>.

  • get the main exchange composite ticker, or whatever suits your need (in A3):

    =BDP(A2,"EQY_PRIM_SECURITY_COMP_EXCH") => US
    
  • and finally:

    =BDP(A1&" "&A3&" Equity", "LAST_PRICE") => the last price of IBM US Equity
    

C# int to enum conversion

You don't need the inheritance. You can do:

(Foo)1 

it will work ;)

Why is quicksort better than mergesort?

Actually, QuickSort is O(n2). Its average case running time is O(nlog(n)), but its worst-case is O(n2), which occurs when you run it on a list that contains few unique items. Randomization takes O(n). Of course, this doesn't change its worst case, it just prevents a malicious user from making your sort take a long time.

QuickSort is more popular because it:

  1. Is in-place (MergeSort requires extra memory linear to number of elements to be sorted).
  2. Has a small hidden constant.

Test method is inconclusive: Test wasn't run. Error?

I know this question has /several/ answers to it, but I have yet another unique answer that I haven't seen as a way to resolve it. I'm hoping this helps someone else out there.

To use the Unit Test Sessions, one external dependency is the Microsoft.Net.Test.Sdk, at some point in the VS pipeline the xunit.runner.visualstudio stopped working correctly for the ReSharper Unit Test Session flavor of test runner. The following is how I ended up with this problem, and how I solved it.

My issue and answer arose from seeing the Inconclusive when converting some of my net451 libraries into netStandard 2.0 in order to allow my team to develop in Core or Framework. When I went into the newly finished netStandard2.0 libraries and started converting their old unit test projects into the new solutions, I ran into issues. You can't run Unit Tests in a net Standard project, so I chose to downshift to net472 for my unit testing projects.

At this point I'll note, .csproj files have gone through a change since .net Framework. In order to cleanly integrate with build packs for nupkg files and .net Standard libraries, you need to change your references to be handled with PackageReference instead of packages.config.

I had a few libraries coupled to Windows that couldn't be converted to netStandard, so when updating their dependencies to use the new netStandard libs, I realized that the dotnet pack command would fail if their .csproj files were in the old format. To fix that, not only did they need to be converted to PackageReference from packages.config, I had to manually update the .csproj files to the newer VS2017 format. This allowed those libraries to build into nuget packages cleanly as net472 libraries referencing netStandard2.0 dependencies.

There is a tool to convert the package organization behavior for you, it keeps the old .csproj style and uses the PackageReference in the .csproj. And due to the above I got in the habit of migrating the .csproj style to the VS2017 format manually.

So in summary, I was receiving the Inconclusive when I was using both PackageReference for my dependencies AND my Unit Testing Project .csproj file was in the VS2017 style.

I was able to solve this by deleting my project, recreating it exactly as it was in net472 and instead of converting it to the VS2017 .csproj format, I left it in the old format.

The old format, for whatever reason, allows my Test Session to complete.

I'm curious of few things:

  1. If a lot of the people with this issue were experiencing it in netCore versions where the .csproj files come in the new format by default.
  2. If people able to solve the issue by other means than my reproduceable problem/fix were on the netCore versions of .csproj and using netCore as their test project as well.
  3. If this solution will help any of the people that weren't able to fix it through rebuilds or deletion of vs/bin folders or additional entries in their .csproj files.

I don't know that this answer is the one true solution that ReSharper would need to fix it for everyone, but it is reproduceable for me, and solves my problem to leave the unit test project as the old version of .csproj file, at least when I have a net472 unit test project referencing netStandard2.0 libraries.

It should also be noted that VS2017 .csproj files deprecates the need for an AssemblyInfo.cs file in the Properties folder, which I'm not sure if that causes issues for the Unit Test Sessions as well.

How do I specify local .gem files in my Gemfile?

I found it easiest to run my own gem server using geminabox

See these simple instructions.

Partly JSON unmarshal into a map in Go

Here is an elegant way to do similar thing. But why do partly JSON unmarshal? That doesn't make sense.

  1. Create your structs for the Chat.
  2. Decode json to the Struct.
  3. Now you can access everything in Struct/Object easily.

Look below at the working code. Copy and paste it.

import (
   "bytes"
   "encoding/json" // Encoding and Decoding Package
   "fmt"
 )

var messeging = `{
"say":"Hello",
"sendMsg":{
    "user":"ANisus",
    "msg":"Trying to send a message"
   }
}`

type SendMsg struct {
   User string `json:"user"`
   Msg  string `json:"msg"`
}

 type Chat struct {
   Say     string   `json:"say"`
   SendMsg *SendMsg `json:"sendMsg"`
}

func main() {
  /** Clean way to solve Json Decoding in Go */
  /** Excellent solution */

   var chat Chat
   r := bytes.NewReader([]byte(messeging))
   chatErr := json.NewDecoder(r).Decode(&chat)
   errHandler(chatErr)
   fmt.Println(chat.Say)
   fmt.Println(chat.SendMsg.User)
   fmt.Println(chat.SendMsg.Msg)

}

 func errHandler(err error) {
   if err != nil {
     fmt.Println(err)
     return
   }
 }

Go playground

How can I order a List<string>?

ListaServizi.Sort();

Will do that for you. It's straightforward enough with a list of strings. You need to be a little cleverer if sorting objects.