Programs & Examples On #Full outer join

A full outer join combines the effect of applying both left and right outer joins.

SQL Server: What is the difference between CROSS JOIN and FULL OUTER JOIN?

I'd like to add one important aspect to other answers, which actually explained this topic to me in the best way:

If 2 joined tables contain M and N rows, then cross join will always produce (M x N) rows, but full outer join will produce from MAX(M,N) to (M + N) rows (depending on how many rows actually match "on" predicate).

EDIT:

From logical query processing perspective, CROSS JOIN does indeed always produce M x N rows. What happens with FULL OUTER JOIN is that both left and right tables are "preserved", as if both LEFT and RIGHT join happened. So rows, not satisfying ON predicate, from both left and right tables are added to the result set.

LINQ - Full Outer Join

I like sehe's answer, but it does not use deferred execution (the input sequences are eagerly enumerated by the calls to ToLookup). So after looking at the .NET sources for LINQ-to-objects, I came up with this:

public static class LinqExtensions
{
    public static IEnumerable<TResult> FullOuterJoin<TLeft, TRight, TKey, TResult>(
        this IEnumerable<TLeft> left,
        IEnumerable<TRight> right,
        Func<TLeft, TKey> leftKeySelector,
        Func<TRight, TKey> rightKeySelector,
        Func<TLeft, TRight, TKey, TResult> resultSelector,
        IEqualityComparer<TKey> comparator = null,
        TLeft defaultLeft = default(TLeft),
        TRight defaultRight = default(TRight))
    {
        if (left == null) throw new ArgumentNullException("left");
        if (right == null) throw new ArgumentNullException("right");
        if (leftKeySelector == null) throw new ArgumentNullException("leftKeySelector");
        if (rightKeySelector == null) throw new ArgumentNullException("rightKeySelector");
        if (resultSelector == null) throw new ArgumentNullException("resultSelector");

        comparator = comparator ?? EqualityComparer<TKey>.Default;
        return FullOuterJoinIterator(left, right, leftKeySelector, rightKeySelector, resultSelector, comparator, defaultLeft, defaultRight);
    }

    internal static IEnumerable<TResult> FullOuterJoinIterator<TLeft, TRight, TKey, TResult>(
        this IEnumerable<TLeft> left,
        IEnumerable<TRight> right,
        Func<TLeft, TKey> leftKeySelector,
        Func<TRight, TKey> rightKeySelector,
        Func<TLeft, TRight, TKey, TResult> resultSelector,
        IEqualityComparer<TKey> comparator,
        TLeft defaultLeft,
        TRight defaultRight)
    {
        var leftLookup = left.ToLookup(leftKeySelector, comparator);
        var rightLookup = right.ToLookup(rightKeySelector, comparator);
        var keys = leftLookup.Select(g => g.Key).Union(rightLookup.Select(g => g.Key), comparator);

        foreach (var key in keys)
            foreach (var leftValue in leftLookup[key].DefaultIfEmpty(defaultLeft))
                foreach (var rightValue in rightLookup[key].DefaultIfEmpty(defaultRight))
                    yield return resultSelector(leftValue, rightValue, key);
    }
}

This implementation has the following important properties:

  • Deferred execution, input sequences will not be enumerated before the output sequence is enumerated.
  • Only enumerates the input sequences once each.
  • Preserves order of input sequences, in the sense that it will yield tuples in the order of the left sequence and then the right (for the keys not present in left sequence).

These properties are important, because they are what someone new to FullOuterJoin but experienced with LINQ will expect.

How to do a FULL OUTER JOIN in MySQL?

what'd you say about Cross join solution?

SELECT t1.*, t2.*
FROM table1 t1
INNER JOIN table2 t2 
ON 1=1;

javac error: Class names are only accepted if annotation processing is explicitly requested

I learned that you also can get this error by storing the source file in a folder named Java

How to read from input until newline is found using scanf()?

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

int main(void)
{
  int i = 0;
  char *a = (char *) malloc(sizeof(char) * 1024);
  while (1) {
    scanf("%c", &a[i]);
    if (a[i] == '\n') {
      break;
    }
    else {
      i++;
    }
  }
  a[i] = '\0';
  i = 0;
  printf("\n");
  while (a[i] != '\0') {
    printf("%c", a[i]);
    i++;
  }
  free(a);
  getch();
  return 0;
}

More Pythonic Way to Run a Process X Times

If you are after the side effects that happen within the loop, I'd personally go for the range() approach.

If you care about the result of whatever functions you call within the loop, I'd go for a list comprehension or map approach. Something like this:

def f(n):
    return n * n

results = [f(i) for i in range(50)]
# or using map:
results = map(f, range(50))

Select rows where column is null

for some reasons IS NULL may not work with some column data type i was in need to get all the employees that their English full name is missing ,I've used :

**SELECT emp_id ,Full_Name_Ar,Full_Name_En from employees where Full_Name_En = ' ' or Full_Name_En is null **

Embed an External Page Without an Iframe?

What about something like this?

<?php
$URL = "http://example.com";
$base = '<base href="'.$URL.'">';
$host = preg_replace('/^[^\/]+\/\//', '', $URL);
$tarray = explode('/', $host);
$host = array_shift($tarray);
$URI = '/' . implode('/', $tarray);
$content = '';
$fp = @fsockopen($host, 80, $errno, $errstr, 30);
if(!$fp) { echo "Unable to open socked: $errstr ($errno)\n"; exit; } 
fwrite($fp,"GET $URI HTTP/1.0\r\n");
fwrite($fp,"Host: $host\r\n");
if( isset($_SERVER["HTTP_USER_AGENT"]) ) { fwrite($fp,'User-Agent: '.$_SERVER

["HTTP_USER_AGENT"]."\r\n"); }
fwrite($fp,"Connection: Close\r\n");
fwrite($fp,"\r\n");
while (!feof($fp)) { $content .= fgets($fp, 128); }
fclose($fp);
if( strpos($content,"\r\n") > 0 ) { $eolchar = "\r\n"; }
else { $eolchar = "\n"; }
$eolpos = strpos($content,"$eolchar$eolchar");
$content = substr($content,($eolpos + strlen("$eolchar$eolchar")));
if( preg_match('/<head\s*>/i',$content) ) { echo( preg_replace('/<head\s*>/i','<head>'.

$base,$content,1) ); }
else { echo( preg_replace('/<([a-z])([^>]+)>/i',"<\\1\\2>".$base,$content,1) ); }
?>

java.io.FileNotFoundException: (Access is denied)

You cannot open and read a directory, use the isFile() and isDirectory() methods to distinguish between files and folders. You can get the contents of folders using the list() and listFiles() methods (for filenames and Files respectively) you can also specify a filter that selects a subset of files listed.

OOP vs Functional Programming vs Procedural

In order to answer your question, we need two elements:

  1. Understanding of the characteristics of different architecture styles/patterns.
  2. Understanding of the characteristics of different programming paradigms.

A list of software architecture styles/pattern is shown on the software architecture article on Wikipeida. And you can research on them easily on the web.

In short and general, Procedural is good for a model that follows a procedure, OOP is good for design, and Functional is good for high level programming.

I think you should try reading the history on each paradigm and see why people create it and you can understand them easily.

After understanding them both, you can link the items of architecture styles/patterns to programming paradigms.

Where is svn.exe in my machine?

TortoiseSVN 1.7 has an option for installing the command line tools.

It isn't checked by default, but you can run the installer again and select it. It will also automatically update your PATH environment variable.

Remove secure warnings (_CRT_SECURE_NO_WARNINGS) from projects by default in Visual Studio

Mark all the desired projects in solution explorer.

Press Alt-F7 or right click in solution explorer and select "Properties"

Configurations:All Configurations

Click on the Preprocessor Definitions line to invoke its editor

Choose Edit...

Copy "_CRT_SECURE_NO_WARNINGS" into the Preprocessor Definitions white box on the top.

enter image description here

Mock MVC - Add Request Parameter to test

If anyone came to this question looking for ways to add multiple parameters at the same time (my case), you can use .params with a MultivalueMap instead of adding each .param :

LinkedMultiValueMap<String, String> requestParams = new LinkedMultiValueMap<>()
requestParams.add("id", "1");
requestParams.add("name", "john");
requestParams.add("age", "30");

mockMvc.perform(get("my/endpoint").params(requestParams)).andExpect(status().isOk())

What's the difference between __PRETTY_FUNCTION__, __FUNCTION__, __func__?

__func__ is documented in the C++0x standard at section 8.4.1. In this case it's a predefined function local variable of the form:

static const char __func__[] = "function-name ";

where "function name" is implementation specfic. This means that whenever you declare a function, the compiler will add this variable implicitly to your function. The same is true of __FUNCTION__ and __PRETTY_FUNCTION__. Despite their uppercasing, they aren't macros. Although __func__ is an addition to C++0x

g++ -std=c++98 ....

will still compile code using __func__.

__PRETTY_FUNCTION__ and __FUNCTION__ are documented here http://gcc.gnu.org/onlinedocs/gcc-4.5.1/gcc/Function-Names.html#Function-Names. __FUNCTION__ is just another name for __func__. __PRETTY_FUNCTION__ is the same as __func__ in C but in C++ it contains the type signature as well.

HTML form with two submit buttons and two "target" attributes

On each of your buttons you could have the following;

<input type="button" name="newWin" onclick="frmSubmitSameWin();">
<input type="button" name="SameWin" onclick="frmSubmitNewWin();">

Then have a few small js functions;

<script type="text/javascript">
function frmSubmitSameWin() {
form.target = '';
form.submit();
}


function frmSubmitNewWin() {
form.target = '_blank';
form.submit();
}
</script>

That should do the trick.

Detecting Back Button/Hash Change in URL

The answers here are all quite old.

In the HTML5 world, you should the use onpopstate event.

window.onpopstate = function(event)
{
    alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
};

Or:

window.addEventListener('popstate', function(event)
{
    alert("location: " + document.location + ", state: " + JSON.stringify(event.state));
});

The latter snippet allows multiple event handlers to exist, whereas the former will replace any existing handler which may cause hard-to-find bugs.

Deleting Row in SQLite in Android

Works great!

public void deleteNewMelk(String melkCode) {
    getWritableDatabase().delete(your_table, your_column +"=?", new String[]{melkCode});
}

How to make unicode string with python3

As a workaround, I've been using this:

# Fix Python 2.x.
try:
    UNICODE_EXISTS = bool(type(unicode))
except NameError:
    unicode = lambda s: str(s)

Stop Excel from automatically converting certain text values to dates

In Excel 2010 open a new sheet. On the Data ribbon click "Get External Data From Text". Select your CSV file then click "Open". Click "Next". Uncheck "Tab", place a check mark next to "Comma", then click "Next". Click anywhere on the first column. While holding the shift key drag the slider across until you can click in the last column, then release the shift key. Click the "text" radio button then click "Finish"

All columns will be imported as text, just as they were in the CSV file.

cpp / c++ get pointer value or depointerize pointer

To get the value of a pointer, just de-reference the pointer.

int *ptr;
int value;
*ptr = 9;

value = *ptr;

value is now 9.

I suggest you read more about pointers, this is their base functionality.

How to delete from a table where ID is in a list of IDs?

delete from t
where id in (1, 4, 6, 7)

How to decrypt hash stored by bcrypt

You simply can't.

bcrypt uses salting, of different rounds, I use 10 usually.

bcrypt.hash(req.body.password,10,function(error,response){ }

This 10 is salting random string into your password.

Powershell script does not run via Scheduled Tasks

I have another solution for this problem that might apply to some of you.

After I created my power shell (xyz.ps1) script, I opened it in notepad for subsequent editing. Hence Windows made an association between my xyz.ps1 file with notepad.exe and Scheduler was trying to run my power shell script (xyz.ps1) with notepad.exe in the background instead of executing it in Powershell. I found this problem by paying close attention to "Display all running tasks" section in the scheduler, which showed that notepad.exe was being used to run the xyz.ps1 script. To verify this, I right clicked on my xyz.ps1 file in windows explorer, went to "Properties", and it showed Notepad against the "Opens With" section. Then I changed the "Opens With" to %SystemRoot%\SysWOW64\WindowsPowerShell\v1.0\powershell.exe. This did the trick. Now the scheduler would execute my xyz.ps1 using powershell.exe and gave me the desired results.

To locate your powershell.exe, refer to this article: https://www.powershelladmin.com/wiki/PowerShell_Executables_File_System_Locations

Angular CLI SASS options

Angular CLI version 9 (used to create Angular 9 projects) now picks up style from schematics instead of styleext. Use the command like this:
ng config schematics.@schematics/angular:component.style scss
and the resulting angular.json shall look like this

"schematics": {
   "@schematics/angular:component": {
      "style": "scss"
    }
  }

Other possible solutions & explanations:

To create a new project with angular CLI with sass support, try this:

ng new My_New_Project --style=scss 

You can also use --style=sass & if you don't know the difference, read this short & easy article and if you still don't know, just go with scss & keep learning.

If you have an angular 5 project, use this command to update the config for your project.

ng set defaults.styleExt scss

For Latest Versions

For Angular 6 to set new style on existing project with CLI:

ng config schematics.@schematics/angular:component.styleext scss

Or Directly into angular.json:

"schematics": {
      "@schematics/angular:component": {
      "styleext": "scss"
    }
}

CMD (command prompt) can't go to the desktop

You need to use the change directory command 'cd' to change directory

cd C:\Users\MyName\Desktop

you can use cd \d to change the drive as well.

link for additional resources http://ss64.com/nt/cd.html

Copy an entire worksheet to a new worksheet in Excel 2010

If anyone has, like I do, an Estimating workbook with a default number of visible pricing sheets, a Summary and a larger number of hidden and 'protected' worksheets full of sensitive data but may need to create additional visible worksheets to arrive at a proper price, I have variant of the above responses that creates the said visible worksheets based on a protected hidden "Master". I have used the code provided by @/jean-fran%c3%a7ois-corbett and @thanos-a in combination with simple VBA as shown below.

Sub sbInsertWorksheetAfter()

    'This adds a new visible worksheet after the last visible worksheet

    ThisWorkbook.Sheets.Add After:=Worksheets(Worksheets.Count)

    'This copies the content of the HIDDEN "Master" worksheet to the new VISIBLE ActiveSheet just created

    ThisWorkbook.Sheets("Master").Cells.Copy _
        Destination:=ActiveSheet.Cells

    'This gives the the new ActiveSheet a default name

    With ActiveSheet
        .Name = Sheet12.Name & " copied"
    End With

    'This changes the name of the ActiveSheet to the user's preference

    Dim sheetname As String

    With ActiveSheet
        sheetname = InputBox("Enter name of this Worksheet")
        .Name = sheetname
    End With

End Sub

How to remove certain characters from a string in C++?

For those of you that prefer a more concise, easier to read lambda coding style...

This example removes all non-alphanumeric and white space characters from a wide string. You can mix it up with any of the other ctype.h helper functions to remove complex-looking character-based tests.

(I'm not sure how these functions would handle CJK languages, so walk softly there.)

    // Boring C loops: 'for(int i=0;i<str.size();i++)' 
    // Boring C++ eqivalent: 'for(iterator iter=c.begin; iter != c.end; ++iter)'

See if you don't find this easier to understand than noisy C/C++ for/iterator loops:

TSTRING label = _T("1.   Replen & Move  RPMV");
TSTRING newLabel = label;
set<TCHAR> badChars; // Use ispunct, isalpha, isdigit, et.al. (lambda version, with capture list parameter(s) example; handiest thing since sliced bread)
for_each(label.begin(), label.end(), [&badChars](TCHAR n){
    if (!isalpha(n) && !isdigit(n))
        badChars.insert(n);
});

for_each(badChars.begin(), badChars.end(), [&newLabel](TCHAR n){
    newLabel.erase(std::remove(newLabel.begin(), newLabel.end(), n), newLabel.end());
});

newLabel results after running this code: "1ReplenMoveRPMV"

This is just academic, since it would clearly be more precise, concise and efficient to combine the 'if' logic from lambda0 (first for_each) into the single lambda1 (second for_each), if you have already established which characters are the "badChars".

Remove stubborn underline from link

None of the answers worked for me. In my case there was a standard

a:-webkit-any-link {
text-decoration: underline;

in my code. Basically whatever link it is, the text color goes blue, and the link stays whatever it is.

So I added the code at the end of the header like this:

<head>
  </style>
    a:-webkit-any-link {
      text-decoration: none;
    }
  </style>
</head>

and problem is no more.

blur() vs. onblur()

I guess it's just because the onblur event is called as a result of the input losing focus, there isn't a blur action associated with an input, like there is a click action associated with a button

Python check if list items are integers?

Try this:

mynewlist = [s for s in mylist if s.isdigit()]

From the docs:

str.isdigit()

Return true if all characters in the string are digits and there is at least one character, false otherwise.

For 8-bit strings, this method is locale-dependent.


As noted in the comments, isdigit() returning True does not necessarily indicate that the string can be parsed as an int via the int() function, and it returning False does not necessarily indicate that it cannot be. Nevertheless, the approach above should work in your case.

How create table only using <div> tag and Css

Use the correct doc type; it will solve the problem. Add the below line to the top of your HTML file:

<!DOCTYPE HTML PUBLIC "-//W3C//DTD HTML 4.01//EN" "http://www.w3.org/TR/html4/strict.dtd">

Accessing session from TWIG template

{{app.session}} refers to the Session object and not the $_SESSION array. I don't think the $_SESSION array is accessible unless you explicitly pass it to every Twig template or if you do an extension that makes it available.

Symfony2 is object-oriented, so you should use the Session object to set session attributes and not rely on the array. The Session object will abstract this stuff away from you so it is easier to, say, store the session in a database because storing the session variable is hidden from you.

So, set your attribute in the session and retrieve the value in your twig template by using the Session object.

// In a controller
$session = $this->get('session');
$session->set('filter', array(
    'accounts' => 'value',
));

// In Twig
{% set filter = app.session.get('filter') %}
{% set account-filter = filter['accounts'] %}

Hope this helps.

Regards,
Matt

Why shouldn't I use mysql_* functions in PHP?

This answer is written to show just how trivial it is to bypass poorly written PHP user-validation code, how (and using what) these attacks work and how to replace the old MySQL functions with a secure prepared statement - and basically, why StackOverflow users (probably with a lot of rep) are barking at new users asking questions to improve their code.

First off, please feel free to create this test mysql database (I have called mine prep):

mysql> create table users(
    -> id int(2) primary key auto_increment,
    -> userid tinytext,
    -> pass tinytext);
Query OK, 0 rows affected (0.05 sec)

mysql> insert into users values(null, 'Fluffeh', 'mypass');
Query OK, 1 row affected (0.04 sec)

mysql> create user 'prepared'@'localhost' identified by 'example';
Query OK, 0 rows affected (0.01 sec)

mysql> grant all privileges on prep.* to 'prepared'@'localhost' with grant option;
Query OK, 0 rows affected (0.00 sec)

With that done, we can move to our PHP code.

Lets assume the following script is the verification process for an admin on a website (simplified but working if you copy and use it for testing):

<?php 

    if(!empty($_POST['user']))
    {
        $user=$_POST['user'];
    }   
    else
    {
        $user='bob';
    }
    if(!empty($_POST['pass']))
    {
        $pass=$_POST['pass'];
    }
    else
    {
        $pass='bob';
    }

    $database='prep';
    $link=mysql_connect('localhost', 'prepared', 'example');
    mysql_select_db($database) or die( "Unable to select database");

    $sql="select id, userid, pass from users where userid='$user' and pass='$pass'";
    //echo $sql."<br><br>";
    $result=mysql_query($sql);
    $isAdmin=false;
    while ($row = mysql_fetch_assoc($result)) {
        echo "My id is ".$row['id']." and my username is ".$row['userid']." and lastly, my password is ".$row['pass']."<br>";
        $isAdmin=true;
        // We have correctly matched the Username and Password
        // Lets give this person full access
    }
    if($isAdmin)
    {
        echo "The check passed. We have a verified admin!<br>";
    }
    else
    {
        echo "You could not be verified. Please try again...<br>";
    }
    mysql_close($link);

?>

<form name="exploited" method='post'>
    User: <input type='text' name='user'><br>
    Pass: <input type='text' name='pass'><br>
    <input type='submit'>
</form>

Seems legit enough at first glance.

The user has to enter a login and password, right?

Brilliant, not enter in the following:

user: bob
pass: somePass

and submit it.

The output is as follows:

You could not be verified. Please try again...

Super! Working as expected, now lets try the actual username and password:

user: Fluffeh
pass: mypass

Amazing! Hi-fives all round, the code correctly verified an admin. It's perfect!

Well, not really. Lets say the user is a clever little person. Lets say the person is me.

Enter in the following:

user: bob
pass: n' or 1=1 or 'm=m

And the output is:

The check passed. We have a verified admin!

Congrats, you just allowed me to enter your super-protected admins only section with me entering a false username and a false password. Seriously, if you don't believe me, create the database with the code I provided, and run this PHP code - which at glance REALLY does seem to verify the username and password rather nicely.

So, in answer, THAT IS WHY YOU ARE BEING YELLED AT.

So, lets have a look at what went wrong, and why I just got into your super-admin-only-bat-cave. I took a guess and assumed that you weren't being careful with your inputs and simply passed them to the database directly. I constructed the input in a way tht would CHANGE the query that you were actually running. So, what was it supposed to be, and what did it end up being?

select id, userid, pass from users where userid='$user' and pass='$pass'

That's the query, but when we replace the variables with the actual inputs that we used, we get the following:

select id, userid, pass from users where userid='bob' and pass='n' or 1=1 or 'm=m'

See how I constructed my "password" so that it would first close the single quote around the password, then introduce a completely new comparison? Then just for safety, I added another "string" so that the single quote would get closed as expected in the code we originally had.

However, this isn't about folks yelling at you now, this is about showing you how to make your code more secure.

Okay, so what went wrong, and how can we fix it?

This is a classic SQL injection attack. One of the simplest for that matter. On the scale of attack vectors, this is a toddler attacking a tank - and winning.

So, how do we protect your sacred admin section and make it nice and secure? The first thing to do will be to stop using those really old and deprecated mysql_* functions. I know, you followed a tutorial you found online and it works, but it's old, it's outdated and in the space of a few minutes, I have just broken past it without so much as breaking a sweat.

Now, you have the better options of using mysqli_ or PDO. I am personally a big fan of PDO, so I will be using PDO in the rest of this answer. There are pro's and con's, but personally I find that the pro's far outweigh the con's. It's portable across multiple database engines - whether you are using MySQL or Oracle or just about bloody anything - just by changing the connection string, it has all the fancy features we want to use and it is nice and clean. I like clean.

Now, lets have a look at that code again, this time written using a PDO object:

<?php 

    if(!empty($_POST['user']))
    {
        $user=$_POST['user'];
    }   
    else
    {
        $user='bob';
    }
    if(!empty($_POST['pass']))
    {
        $pass=$_POST['pass'];
    }
    else
    {
        $pass='bob';
    }
    $isAdmin=false;

    $database='prep';
    $pdo=new PDO ('mysql:host=localhost;dbname=prep', 'prepared', 'example');
    $sql="select id, userid, pass from users where userid=:user and pass=:password";
    $myPDO = $pdo->prepare($sql, array(PDO::ATTR_CURSOR => PDO::CURSOR_FWDONLY));
    if($myPDO->execute(array(':user' => $user, ':password' => $pass)))
    {
        while($row=$myPDO->fetch(PDO::FETCH_ASSOC))
        {
            echo "My id is ".$row['id']." and my username is ".$row['userid']." and lastly, my password is ".$row['pass']."<br>";
            $isAdmin=true;
            // We have correctly matched the Username and Password
            // Lets give this person full access
        }
    }

    if($isAdmin)
    {
        echo "The check passed. We have a verified admin!<br>";
    }
    else
    {
        echo "You could not be verified. Please try again...<br>";
    }

?>

<form name="exploited" method='post'>
    User: <input type='text' name='user'><br>
    Pass: <input type='text' name='pass'><br>
    <input type='submit'>
</form>

The major differences are that there are no more mysql_* functions. It's all done via a PDO object, secondly, it is using a prepared statement. Now, what's a prepred statement you ask? It's a way to tell the database ahead of running a query, what the query is that we are going to run. In this case, we tell the database: "Hi, I am going to run a select statement wanting id, userid and pass from the table users where the userid is a variable and the pass is also a variable.".

Then, in the execute statement, we pass the database an array with all the variables that it now expects.

The results are fantastic. Lets try those username and password combinations from before again:

user: bob
pass: somePass

User wasn't verified. Awesome.

How about:

user: Fluffeh
pass: mypass

Oh, I just got a little excited, it worked: The check passed. We have a verified admin!

Now, lets try the data that a clever chap would enter to try to get past our little verification system:

user: bob
pass: n' or 1=1 or 'm=m

This time, we get the following:

You could not be verified. Please try again...

This is why you are being yelled at when posting questions - it's because people can see that your code can be bypassed wihout even trying. Please, do use this question and answer to improve your code, to make it more secure and to use functions that are current.

Lastly, this isn't to say that this is PERFECT code. There are many more things that you could do to improve it, use hashed passwords for example, ensure that when you store sensetive information in the database, you don't store it in plain text, have multiple levels of verification - but really, if you just change your old injection prone code to this, you will be WELL along the way to writing good code - and the fact that you have gotten this far and are still reading gives me a sense of hope that you will not only implement this type of code when writing your websites and applications, but that you might go out and research those other things I just mentioned - and more. Write the best code you can, not the most basic code that barely functions.

Better way to generate array of all letters in the alphabet

Here are a few alternatives based on tom thomas' answer.

Character Array:

        char[] list = IntStream.concat(
                IntStream.rangeClosed('0', '9'),
                IntStream.rangeClosed('A', 'Z')
        ).mapToObj(c -> (char) c+"").collect(Collectors.joining()).toCharArray();

String Array:

Note: Won't work correctly if your delimiter is one of the values, too.

        String[] list = IntStream.concat(
                IntStream.rangeClosed('0', '9'),
                IntStream.rangeClosed('A', 'Z')
        ).mapToObj(c -> (char) c+",").collect(Collectors.joining()).split(",");

String List:

Note: Won't work correctly if your delimiter is one of the values, too.

        List<String> list = Arrays.asList(IntStream.concat(
                IntStream.rangeClosed('0', '9'),
                IntStream.rangeClosed('A', 'Z')
        ).mapToObj(c -> (char) c+",").collect(Collectors.joining()).split(","));

Hide a EditText & make it visible by clicking a menu

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.waist2height); {
        final EditText edit = (EditText)findViewById(R.id.editText);          
        final RadioButton rb1 = (RadioButton) findViewById(R.id.radioCM);
        final RadioButton rb2 = (RadioButton) findViewById(R.id.radioFT);                       
        if(rb1.isChecked()){    
            edit.setVisibility(View.VISIBLE);              
        }
        else if(rb2.isChecked()){               
            edit.setVisibility(View.INVISIBLE);
        }
}

How to add a border to a widget in Flutter?

You can use Container to contain your widget:

Container(
  decoration: BoxDecoration(
    border: Border.all(
    color: Color(0xff000000),
    width: 1,
  )),
  child: Text()
),

C++, how to declare a struct in a header file

C++, how to declare a struct in a header file:

Put this in a file called main.cpp:

#include <cstdlib>
#include <iostream>
#include "student.h"

using namespace std;    //Watchout for clashes between std and other libraries

int main(int argc, char** argv) {
    struct Student s1;
    s1.firstName = "fred"; s1.lastName = "flintstone";
    cout << s1.firstName << " " << s1.lastName << endl;
    return 0;
}

put this in a file named student.h

#ifndef STUDENT_H
#define STUDENT_H

#include<string>
struct Student {
    std::string lastName, firstName;
};

#endif

Compile it and run it, it should produce this output:

s1.firstName = "fred";

Protip:

You should not place a using namespace std; directive in the C++ header file because you may cause silent name clashes between different libraries. To remedy this, use the fully qualified name: std::string foobarstring; instead of including the std namespace with string foobarstring;.

Is there a method that tells my program to quit?

See sys.exit. That function will quit your program with the given exit status.

How to return a 200 HTTP Status Code from ASP.NET MVC 3 controller

    [HttpPost]
    public JsonResult ContactAdd(ContactViewModel contactViewModel)
    {
        if (ModelState.IsValid)
        {
            var job = new Job { Contact = new Contact() };

            Mapper.Map(contactViewModel, job);
            Mapper.Map(contactViewModel, job.Contact);

            _db.Jobs.Add(job);

            _db.SaveChanges();

            //you do not even need this line of code,200 is the default for ASP.NET MVC as long as no exceptions were thrown
            //Response.StatusCode = (int)HttpStatusCode.OK;

            return Json(new { jobId = job.JobId });
        }
        else
        {
            Response.StatusCode = (int)HttpStatusCode.BadRequest;
            return Json(new { jobId = -1 });
        }
    }

How to sort an array of objects in Java?

public class Student implements Comparable<Student> {

    private int sid;
    private String sname;

    public Student(int sid, String sname) {
        super();
        this.sid = sid;
        this.sname = sname;
    }

    public int getSid() {
        return sid;
    }

    public void setSid(int sid) {
        this.sid = sid;
    }

    public String getSname() {
        return sname;
    }

    public void setSname(String sname) {
        this.sname = sname;
    }

    @Override
    public String toString() {
        return "Student [sid=" + sid + ", sname=" + sname + "]";
    }

    public int compareTo(Student o) {
        if (this.getSname().compareTo(o.getSname()) > 1) {
            return toString().compareTo(o.getSname());
        } else if (this.getSname().compareTo(o.getSname()) < 1) {
            return toString().compareTo(o.getSname());
        }
        return 0;
    }

}

Sprintf equivalent in Java

Strings are immutable types. You cannot modify them, only return new string instances.

Because of that, formatting with an instance method makes little sense, as it would have to be called like:

String formatted = "%s: %s".format(key, value);

The original Java authors (and .NET authors) decided that a static method made more sense in this situation, as you are not modifying the target, but instead calling a format method and passing in an input string.

Here is an example of why format() would be dumb as an instance method. In .NET (and probably in Java), Replace() is an instance method.

You can do this:

 "I Like Wine".Replace("Wine","Beer");

However, nothing happens, because strings are immutable. Replace() tries to return a new string, but it is assigned to nothing.

This causes lots of common rookie mistakes like:

inputText.Replace(" ", "%20");

Again, nothing happens, instead you have to do:

inputText = inputText.Replace(" ","%20");

Now, if you understand that strings are immutable, that makes perfect sense. If you don't, then you are just confused. The proper place for Replace() would be where format() is, as a static method of String:

 inputText = String.Replace(inputText, " ", "%20");

Now there is no question as to what's going on.

The real question is, why did the authors of these frameworks decide that one should be an instance method, and the other static? In my opinion, both are more elegantly expressed as static methods.

Regardless of your opinion, the truth is that you are less prone to make a mistake using the static version, and the code is easier to understand (No Hidden Gotchas).

Of course there are some methods that are perfect as instance methods, take String.Length()

int length = "123".Length();

In this situation, it's obvious we are not trying to modify "123", we are just inspecting it, and returning its length. This is a perfect candidate for an instance method.

My simple rules for Instance Methods on Immutable Objects:

  • If you need to return a new instance of the same type, use a static method.
  • Otherwise, use an instance method.

JS strings "+" vs concat method

There was a time when adding strings into an array and finalising the string by using join was the fastest/best method. These days browsers have highly optimised string routines and it is recommended that + and += methods are fastest/best

How to convert string to integer in UNIX

The standard solution:

 expr $d1 - $d2

You can also do:

echo $(( d1 - d2 ))

but beware that this will treat 07 as an octal number! (so 07 is the same as 7, but 010 is different than 10).

ERROR: Google Maps API error: MissingKeyMapError

As per Google recent announcement, usage of the Google Maps APIs now requires a key. If you are using the Google Maps API on localhost or your domain was not active prior to June 22nd, 2016, it will require a key going forward. Please see the Google Maps APIs documentation to get a key and add it to your application.

Create a copy of a table within the same database DB2

CREATE TABLE NEW_TABLENAME LIKE OLD_TABLENAME;

Works for DB2 V 9.7

how to kill the tty in unix

I had the same problem today. I had NO remaining processes, but the remaining finger entry of user "xxx", which prevent me the deletion of this user using "userdel xxx".

Error message was: userdel: account `xxx' is currently in use.

It looked like a crashed terminal session. So I rebooted, but the issue remained.

last xxx
xxx      pts/5        10.1.2.3     Fri Feb  7 10:25 - crash  (01:27)

So I (re)moved the /var/run/utmp file:

mv /var/run/utmp /var/run/utmp.save ; touch /var/run/utmp

This cleared all finger entries. Unfortunately in this way even the current running sessions will be cleared. If this is an issue for you, you have to reboot, after you (re)moved the utmp file.

However in my case this was the solution. Afterwards I was able to successfully delete the user, using "userdel xxx".

How can I do an asc and desc sort using underscore.js?

Underscore Mixins

Extending on @emil_lundberg's answer, you can also write a "mixin" if you're using Underscore to make a custom function for sorting if it's a kind of sorting you might repeat in an application somewhere.

For example, maybe you have a controller or view sorting results with sort order of "ASC" or "DESC", and you want to toggle between that sort, you could do something like this:

Mixin.js

_.mixin({
    sortByOrder: function(stooges, prop, order) {
      if (String(order) === "desc") {
          return _.sortBy(stooges, prop).reverse();
      } else if (String(order) === "asc") {
          return _.sortBy(stooges, prop);
      } else {
          return stooges;
      }
    }
})

Usage Example

var sort_order = "asc";
var stooges = [
  {name: 'moe', age: 40}, 
  {name: 'larry', age: 50}, 
  {name: 'curly', age: 60},
  {name: 'July', age: 35},
  {name: 'mel', age: 38}
 ];

_.mixin({
    sortByOrder: function(stooges, prop, order) {
    if (String(order) === "desc") {
        return _.sortBy(stooges, prop).reverse();
    } else if (String(order) === "asc") {
        return _.sortBy(stooges, prop);
    } else {
        return stooges;
    }
  }
})


// find elements
var banner = $("#banner-message");
var sort_name_btn = $("button.sort-name");
var sort_age_btn = $("button.sort-age");

function showSortedResults(results, sort_order, prop) {
    banner.empty();
    banner.append("<p>Sorting: " + prop + ', ' + sort_order + "</p><hr>")
  _.each(results, function(r) {
    banner.append('<li>' + r.name + ' is '+ r.age + ' years old.</li>');
  }) 
}

// handle click and add class
sort_name_btn.on("click", function() {
  sort_order = (sort_order === "asc") ? "desc" : "asc"; 
    var sortedResults = _.sortByOrder(stooges, 'name', sort_order);
  showSortedResults(sortedResults, sort_order, 'name');
})

sort_age_btn.on('click', function() {
    sort_order = (sort_order === "asc") ? "desc" : "asc"; 
    var sortedResults = _.sortByOrder(stooges, 'age', sort_order);
  showSortedResults(sortedResults, sort_order, 'age');
})

Here's a JSFiddle demonstrating this: JSFiddle for SortBy Mixin

Attach Authorization header for all axios requests

The point is to set the token on the interceptors for each request

import axios from "axios";
    
const httpClient = axios.create({
    baseURL: "http://youradress",
    // baseURL: process.env.APP_API_BASE_URL,
});

httpClient.interceptors.request.use(function (config) {
    const token = localStorage.getItem('token');
    config.headers.Authorization =  token ? `Bearer ${token}` : '';
    return config;
});

Cannot read configuration file due to insufficient permissions

  1. Go to IIS, (sites)
  2. Right click on project inside the sites.enter image description here

and click on edit permission.

  1. Go to security.

  2. click on edit button.

  3. click add button. type COMPUTER_NAME\IIS_USERS

    or

  4. click advance.

  5. click find now button.

    and there is option to choose. choose IIS_USERS and click ok...ok....ok .

jQuery date/time picker

By far the nicest and simplest DateTime picker option is http://trentrichardson.com/examples/timepicker/.

It is an extension of the jQuery UI Datepicker so it will support the same themes as well it works very much the same way, similar syntax, etc. This should be packaged with the jQuery UI imo.

How do I get the App version and build number using Swift?

if let version = Bundle.main.infoDictionary?["CFBundleShortVersionString"] as? String {
            self.lblAppVersionValue.text = version
        }

Sql Query to list all views in an SQL Server 2005 database

SELECT SCHEMA_NAME(schema_id) AS schema_name
,name AS view_name
,OBJECTPROPERTYEX(OBJECT_ID,'IsIndexed') AS IsIndexed
,OBJECTPROPERTYEX(OBJECT_ID,'IsIndexable') AS IsIndexable
FROM sys.views

How can I return pivot table output in MySQL?

This basically is a pivot table.

A nice tutorial on how to achieve this can be found here: http://www.artfulsoftware.com/infotree/qrytip.php?id=78

I advise reading this post and adapt this solution to your needs.

Update

After the link above is currently not available any longer I feel obliged to provide some additional information for all of you searching for mysql pivot answers in here. It really had a vast amount of information, and I won't put everything from there in here (even more since I just don't want to copy their vast knowledge), but I'll give some advice on how to deal with pivot tables the sql way generally with the example from peku who asked the question in the first place.

Maybe the link comes back soon, I'll keep an eye out for it.

The spreadsheet way...

Many people just use a tool like MSExcel, OpenOffice or other spreadsheet-tools for this purpose. This is a valid solution, just copy the data over there and use the tools the GUI offer to solve this.

But... this wasn't the question, and it might even lead to some disadvantages, like how to get the data into the spreadsheet, problematic scaling and so on.

The SQL way...

Given his table looks something like this:

CREATE TABLE `test_pivot` (
  `pid` bigint(20) NOT NULL AUTO_INCREMENT,
  `company_name` varchar(32) DEFAULT NULL,
  `action` varchar(16) DEFAULT NULL,
  `pagecount` bigint(20) DEFAULT NULL,
  PRIMARY KEY (`pid`)
) ENGINE=MyISAM;

Now look into his/her desired table:

company_name    EMAIL   PRINT 1 pages   PRINT 2 pages   PRINT 3 pages
-------------------------------------------------------------
CompanyA        0       0               1               3
CompanyB        1       1               2               0

The rows (EMAIL, PRINT x pages) resemble conditions. The main grouping is by company_name.

In order to set up the conditions this rather shouts for using the CASE-statement. In order to group by something, well, use ... GROUP BY.

The basic SQL providing this pivot can look something like this:

SELECT  P.`company_name`,
    COUNT(
        CASE 
            WHEN P.`action`='EMAIL' 
            THEN 1 
            ELSE NULL 
        END
    ) AS 'EMAIL',
    COUNT(
        CASE 
            WHEN P.`action`='PRINT' AND P.`pagecount` = '1' 
            THEN P.`pagecount` 
            ELSE NULL 
        END
    ) AS 'PRINT 1 pages',
    COUNT(
        CASE 
            WHEN P.`action`='PRINT' AND P.`pagecount` = '2' 
            THEN P.`pagecount` 
            ELSE NULL 
        END
    ) AS 'PRINT 2 pages',
    COUNT(
        CASE 
            WHEN P.`action`='PRINT' AND P.`pagecount` = '3' 
            THEN P.`pagecount` 
            ELSE NULL 
        END
    ) AS 'PRINT 3 pages'
FROM    test_pivot P
GROUP BY P.`company_name`;

This should provide the desired result very fast. The major downside for this approach, the more rows you want in your pivot table, the more conditions you need to define in your SQL statement.

This can be dealt with, too, therefore people tend to use prepared statements, routines, counters and such.

Some additional links about this topic:

The operation cannot be completed because the DbContext has been disposed error

You need to remember that IQueryable queries are not actually executed against the data store until you enumerate them.

using (var dataContext = new dataContext())
{

This line of code doesn't actually do anything other than build the SQL statement

    users = dataContext.Users.Where(x => x.AccountID == accountId && x.IsAdmin == false);

.Any() is an operation that enumerates the IQueryable, so the SQL is sent to the data source (through dataContext), and then the .Any() operations is executed against it

    if(users.Any() == false)
    {
        return null;
    }
}

Your "problem" line is reusing the sql built above, and then doing an additional operation (.Select()), which just adds to the query. If you left it here, no exception, except your problem line

return users.Select(x => x.ToInfo()).ToList(); // this line is the problem

calls .ToList(), which enumerates the IQueryable, which causes the SQL to be sent to the datasource through the dataContext that was used in the original LINQ query. Since this dataContext has been disposed, it is no longer valid, and .ToList() throws an exception.

That is the "why it doesn't work". The fix is to move this line of code inside the scope of your dataContext.

How to use it properly is another question with a few arguably correct answers that depend on your application (Forms vs. ASP.net vs. MVC, etc.). The pattern that this implements is the Unit of Work pattern. There is almost no cost to creating a new context object, so the general rule is to create one, do your work, and then dispose of it. In web apps, some people will create a Context per request.

PHP parse/syntax errors; and how to solve them

Unexpected T_LNUMBER

The token T_LNUMBER refers to a "long" / number.

  1. Invalid variable names

    In PHP, and most other programming languages, variables cannot start with a number. The first character must be alphabetic or an underscore.

    $1   // Bad
    $_1  // Good
    

    *

    • Quite often comes up for using preg_replace-placeholders "$1" in PHP context:

      #                         ?            ?  ?
      preg_replace("/#(\w+)/e",  strtopupper($1) )
      

      Where the callback should have been quoted. (Now the /e regex flag has been deprecated. But it's sometimes still misused in preg_replace_callback functions.)

    • The same identifier constraint applies to object properties, btw.

             ?
      $json->0->value
      
    • While the tokenizer/parser does not allow a literal $1 as variable name, one could use ${1} or ${"1"}. Which is a syntactic workaround for non-standard identifiers. (It's best to think of it as a local scope lookup. But generally: prefer plain arrays for such cases!)

    • Amusingly, but very much not recommended, PHPs parser allows Unicode-identifiers; such that $? would be valid. (Unlike a literal 1).

  2. Stray array entry

    An unexpected long can also occur for array declarations - when missing , commas:

    #            ? ?
    $xy = array(1 2 3);
    

    Or likewise function calls and declarations, and other constructs:

    • func(1, 2 3);
    • function xy($z 2);
    • for ($i=2 3<$z)

    So usually there's one of ; or , missing for separating lists or expressions.

  3. Misquoted HTML

    And again, misquoted strings are a frequent source of stray numbers:

    #                 ? ?          
    echo "<td colspan="3">something bad</td>";
    

    Such cases should be treated more or less like Unexpected T_STRING errors.

  4. Other identifiers

    Neither functions, classes, nor namespaces can be named beginning with a number either:

             ?
    function 123shop() {
    

    Pretty much the same as for variable names.

Getting scroll bar width using JavaScript

If you use jquery.ui, try this code:

$.position.scrollbarWidth()

set environment variable in python script

bash:

LD_LIBRARY_PATH=my_path
sqsub -np $1 /path/to/executable

Similar, in Python:

import os
import subprocess
import sys

os.environ['LD_LIBRARY_PATH'] = "my_path" # visible in this process + all children
subprocess.check_call(['sqsub', '-np', sys.argv[1], '/path/to/executable'],
                      env=dict(os.environ, SQSUB_VAR="visible in this subprocess"))

Get Client Machine Name in PHP

PHP Manual says:

gethostname (PHP >= 5.3.0) gethostname — Gets the host name

Look:

<?php
echo gethostname(); // may output e.g,: sandie
// Or, an option that also works before PHP 5.3
echo php_uname('n'); // may output e.g,: sandie
?>

http://php.net/manual/en/function.gethostname.php

Enjoy

How can I export tables to Excel from a webpage

This code is IE only so it is only useful in situations where you know all of your users will be using IE (like, for example, in some corporate environments.)

<script Language="javascript">
function ExportHTMLTableToExcel()
{
   var thisTable = document.getElementById("tbl").innerHTML;
   window.clipboardData.setData("Text", thisTable);
   var objExcel = new ActiveXObject ("Excel.Application");
   objExcel.visible = true;

   var objWorkbook = objExcel.Workbooks.Add;
   var objWorksheet = objWorkbook.Worksheets(1);
   objWorksheet.Paste;
}
</script>

Convert char array to a int number in C

It's not what the question asks but I used @Rich Drummond 's answer for a char array read in from stdin which is null terminated.

char *buff;
size_t buff_size = 100;
int choice;
do{
    buff = (char *)malloc(buff_size *sizeof(char));
    getline(&buff, &buff_size, stdin);
    choice = atoi(buff);
    free(buff);
                    
}while((choice<1)&&(choice>9));

JavaScript - Get Browser Height

There's a simpler way than a whole bunch of if statements. Use the or (||) operator.

function getBrowserDimensions() {
  return {
    width: (window.innerWidth || document.documentElement.clientWidth || document.body.clientWidth),
    height: (window.innerHeight || document.documentElement.clientHeight || document.body.clientHeight)
  };
}

var browser_dims = getBrowserDimensions();

alert("Width = " + browser_dims.width + "\nHeight = " + browser_dims.height);

Undefined reference to sqrt (or other mathematical functions)

I suppose you have imported math.h with #include <math.h>

So the only other reason I can see is a missing linking information. You must link your code with the -lm option.

If you're simply trying to compile one file with gcc, just add -lm to your command line, otherwise, give some informations about your building process.

Asp.net MVC ModelState.Clear

Update:

  • This is not a bug.
  • Please stop returning View() from a POST action. Use PRG instead and redirect to a GET if the action is a success.
  • If you are returning a View() from a POST action, do it for form validation, and do it the way MVC is designed using the built in helpers. If you do it this way then you shouldn't need to use .Clear()
  • If you're using this action to return ajax for a SPA, use a web api controller and forget about ModelState since you shouldn't be using it anyway.

Old answer:

ModelState in MVC is used primarily to describe the state of a model object largely with relation to whether that object is valid or not. This tutorial should explain a lot.

Generally you should not need to clear the ModelState as it is maintained by the MVC engine for you. Clearing it manually might cause undesired results when trying to adhere to MVC validation best practises.

It seems that you are trying to set a default value for the title. This should be done when the model object is instantiated (domain layer somewhere or in the object itself - parameterless ctor), on the get action such that it goes down to the page the 1st time or completely on the client (via ajax or something) so that it appears as if the user entered it and it comes back with the posted forms collection. Some how your approach of adding this value on the receiving of a forms collection (in the POST action // Edit) is causing this bizarre behaviour that might result in a .Clear() appearing to work for you. Trust me - you don't want to be using the clear. Try one of the other ideas.

How to sort Counter by value? - python

A rather nice addition to @MartijnPieters answer is to get back a dictionary sorted by occurrence since Collections.most_common only returns a tuple. I often couple this with a json output for handy log files:

from collections import Counter, OrderedDict

x = Counter({'a':5, 'b':3, 'c':7})
y = OrderedDict(x.most_common())

With the output:

OrderedDict([('c', 7), ('a', 5), ('b', 3)])
{
  "c": 7, 
  "a": 5, 
  "b": 3
}

Class constants in python

Since Horse is a subclass of Animal, you can just change

print(Animal.SIZES[1])

with

print(self.SIZES[1])

Still, you need to remember that SIZES[1] means "big", so probably you could improve your code by doing something like:

class Animal:
    SIZE_HUGE="Huge"
    SIZE_BIG="Big"
    SIZE_MEDIUM="Medium"
    SIZE_SMALL="Small"

class Horse(Animal):
    def printSize(self):
        print(self.SIZE_BIG)

Alternatively, you could create intermediate classes: HugeAnimal, BigAnimal, and so on. That would be especially helpful if each animal class will contain different logic.

unsigned APK can not be installed

You can test the unsigned-apk only on Emulator. And as its step of application deployment and distribution, you should read this article atleast once, i suggest: http://developer.android.com/guide/publishing/app-signing.html.

For your question, you can find the below line in above article:

All applications must be signed. The system will not install an application that is not signed.

so you have to have signed-apk before the distribution of your application.

To generate Signed-apk of your application, there is a simple wizard procedure, click on File -> Export -> Android -> Export Android application.

enter image description here

iterrows pandas get next rows value

a combination of answers gave me a very fast running time. using the shift method to create new column of next row values, then using the row_iterator function as @alisdt did, but here i changed it from iterrows to itertuples which is 100 times faster.

my script is for iterating dataframe of duplications in different length and add one second for each duplication so they all be unique.

# create new column with shifted values from the departure time column
df['next_column_value'] = df['column_value'].shift(1)
# create row iterator that can 'save' the next row without running for loop
row_iterator = df.itertuples()
# jump to the next row using the row iterator
last = next(row_iterator)
# because pandas does not support items alteration i need to save it as an object
t = last[your_column_num]
# run and update the time duplications with one more second each
for row in row_iterator:
    if row.column_value == row.next_column_value:
         t = t + add_sec
         df_result.at[row.Index, 'column_name'] = t
    else:
         # here i resetting the 'last' and 't' values
         last = row
         t = last[your_column_num]

Hope it will help.

Server http:/localhost:8080 requires a user name and a password. The server says: XDB

Add username and password in application propreties files.

When adding spring security every http query must be authentified by login and password.

See Screenshot

npm install won't install devDependencies

I have the same issue because I set the NODE_ENV=production while building Docker. Then I add one more npm install --only=dev. Everything works fine. I need the devDependencies for building TypeSciprt modules

RUN npm install
RUN npm install --only=dev

Understanding esModuleInterop in tsconfig file

in your tsconfig you have to add: "esModuleInterop": true - it should help.

Tomcat 8 throwing - org.apache.catalina.webresources.Cache.getResource Unable to add the resource

This isn’t a solution in the sense that it doesn’t resolve the conditions which cause the message to appear in the logs, but the message can be suppressed by appending the following to conf/logging.properties:

org.apache.catalina.webresources.Cache.level = SEVERE

This filters out the “Unable to add the resource” logs, which are at level WARNING.

In my view a WARNING is not necessarily an error that needs to be addressed, but rather can be ignored if desired.

How to convert object to Dictionary<TKey, TValue> in C#?

The above answers are all cool. I found it easy to json serialize the object and deserialize as a dictionary.

var json = JsonConvert.SerializeObject(obj);
var dictionary = JsonConvert.DeserializeObject<Dictionary<string, string>>(json);

I don't know how performance is effected but this is much easier to read. You could also wrap it inside a function.

public static Dictionary<string, TValue> ToDictionary<TValue>(object obj)
{       
    var json = JsonConvert.SerializeObject(obj);
    var dictionary = JsonConvert.DeserializeObject<Dictionary<string, TValue>>(json);   
    return dictionary;
}

Use like so:

var obj = new { foo = 12345, boo = true };
var dictionary = ToDictionary<string>(obj);

Assets file project.assets.json not found. Run a NuGet package restore

In visual studio 2017 please do following steps:

1) select Tool=>Options=>NuGet Package Manager=> Package Sources then uncheck Microsoft Visual Studio Offline Packages Option. enter image description here

2) now open Tool=>NuGet Package Maneger=>Package Manager Console. 3) execute command in PM>dotnet restore.

Hope its working...

WebView and Cookies on Android

CookieManager.getInstance().setAcceptCookie(true); Normally it should work if your webview is already initialized

or try this:

CookieSyncManager.createInstance(this);
CookieManager cookieManager = CookieManager.getInstance();
cookieManager.removeAllCookie();
cookieManager.setAcceptCookie(true);

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

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

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

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

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

then

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

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

How to split (chunk) a Ruby array into parts of X elements?

Take a look at Enumerable#each_slice:

foo.each_slice(3).to_a
#=> [["1", "2", "3"], ["4", "5", "6"], ["7", "8", "9"], ["10"]]

How to add to an existing hash in Ruby

x = {:ca => "Canada", :us => "United States"}
x[:de] = "Germany"
p x

How to update two tables in one statement in SQL Server 2005?

You can write update statement for one table and then a trigger on first table update, which update second table

ECMAScript 6 class destructor

You have to manually "destruct" objects in JS. Creating a destroy function is common in JS. In other languages this might be called free, release, dispose, close, etc. In my experience though it tends to be destroy which will unhook internal references, events and possibly propagates destroy calls to child objects as well.

WeakMaps are largely useless as they cannot be iterated and this probably wont be available until ECMA 7 if at all. All WeakMaps let you do is have invisible properties detached from the object itself except for lookup by the object reference and GC so that they don't disturb it. This can be useful for caching, extending and dealing with plurality but it doesn't really help with memory management for observables and observers. WeakSet is a subset of WeakMap (like a WeakMap with a default value of boolean true).

There are various arguments on whether to use various implementations of weak references for this or destructors. Both have potential problems and destructors are more limited.

Destructors are actually potentially useless for observers/listeners as well because typically the listener will hold references to the observer either directly or indirectly. A destructor only really works in a proxy fashion without weak references. If your Observer is really just a proxy taking something else's Listeners and putting them on an observable then it can do something there but this sort of thing is rarely useful. Destructors are more for IO related things or doing things outside of the scope of containment (IE, linking up two instances that it created).

The specific case that I started looking into this for is because I have class A instance that takes class B in the constructor, then creates class C instance which listens to B. I always keep the B instance around somewhere high above. A I sometimes throw away, create new ones, create many, etc. In this situation a Destructor would actually work for me but with a nasty side effect that in the parent if I passed the C instance around but removed all A references then the C and B binding would be broken (C has the ground removed from beneath it).

In JS having no automatic solution is painful but I don't think it's easily solvable. Consider these classes (pseudo):

function Filter(stream) {
    stream.on('data', function() {
        this.emit('data', data.toString().replace('somenoise', '')); // Pretend chunks/multibyte are not a problem.
    });
}
Filter.prototype.__proto__ = EventEmitter.prototype;
function View(df, stream) {
    df.on('data', function(data) {
        stream.write(data.toUpper()); // Shout.
    });
}

On a side note, it's hard to make things work without anonymous/unique functions which will be covered later.

In a normal case instantiation would be as so (pseudo):

var df = new Filter(stdin),
    v1 = new View(df, stdout),
    v2 = new View(df, stderr);

To GC these normally you would set them to null but it wont work because they've created a tree with stdin at the root. This is basically what event systems do. You give a parent to a child, the child adds itself to the parent and then may or may not maintain a reference to the parent. A tree is a simple example but in reality you may also find yourself with complex graphs albeit rarely.

In this case, Filter adds a reference to itself to stdin in the form of an anonymous function which indirectly references Filter by scope. Scope references are something to be aware of and that can be quite complex. A powerful GC can do some interesting things to carve away at items in scope variables but that's another topic. What is critical to understand is that when you create an anonymous function and add it to something as a listener to ab observable, the observable will maintain a reference to the function and anything the function references in the scopes above it (that it was defined in) will also be maintained. The views do the same but after the execution of their constructors the children do not maintain a reference to their parents.

If I set any or all of the vars declared above to null it isn't going to make a difference to anything (similarly when it finished that "main" scope). They will still be active and pipe data from stdin to stdout and stderr.

If I set them all to null it would be impossible to have them removed or GCed without clearing out the events on stdin or setting stdin to null (assuming it can be freed like this). You basically have a memory leak that way with in effect orphaned objects if the rest of the code needs stdin and has other important events on it prohibiting you from doing the aforementioned.

To get rid of df, v1 and v2 I need to call a destroy method on each of them. In terms of implementation this means that both the Filter and View methods need to keep the reference to the anonymous listener function they create as well as the observable and pass that to removeListener.

On a side note, alternatively you can have an obserable that returns an index to keep track of listeners so that you can add prototyped functions which at least to my understanding should be much better on performance and memory. You still have to keep track of the returned identifier though and pass your object to ensure that the listener is bound to it when called.

A destroy function adds several pains. First is that I would have to call it and free the reference:

df.destroy();
v1.destroy();
v2.destroy();
df = v1 = v2 = null;

This is a minor annoyance as it's a bit more code but that is not the real problem. When I hand these references around to many objects. In this case when exactly do you call destroy? You cannot simply hand these off to other objects. You'll end up with chains of destroys and manual implementation of tracking either through program flow or some other means. You can't fire and forget.

An example of this kind of problem is if I decide that View will also call destroy on df when it is destroyed. If v2 is still around destroying df will break it so destroy cannot simply be relayed to df. Instead when v1 takes df to use it, it would need to then tell df it is used which would raise some counter or similar to df. df's destroy function would decrease than counter and only actually destroy if it is 0. This sort of thing adds a lot of complexity and adds a lot that can go wrong the most obvious of which is destroying something while there is still a reference around somewhere that will be used and circular references (at this point it's no longer a case of managing a counter but a map of referencing objects). When you're thinking of implementing your own reference counters, MM and so on in JS then it's probably deficient.

If WeakSets were iterable, this could be used:

function Observable() {
    this.events = {open: new WeakSet(), close: new WeakSet()};
}
Observable.prototype.on = function(type, f) {
    this.events[type].add(f);
};
Observable.prototype.emit = function(type, ...args) {
    this.events[type].forEach(f => f(...args));
};
Observable.prototype.off = function(type, f) {
    this.events[type].delete(f);
};

In this case the owning class must also keep a token reference to f otherwise it will go poof.

If Observable were used instead of EventListener then memory management would be automatic in regards to the event listeners.

Instead of calling destroy on each object this would be enough to fully remove them:

df = v1 = v2 = null;

If you didn't set df to null it would still exist but v1 and v2 would automatically be unhooked.

There are two problems with this approach however.

Problem one is that it adds a new complexity. Sometimes people do not actually want this behaviour. I could create a very large chain of objects linked to each other by events rather than containment (references in constructor scopes or object properties). Eventually a tree and I would only have to pass around the root and worry about that. Freeing the root would conveniently free the entire thing. Both behaviours depending on coding style, etc are useful and when creating reusable objects it's going to be hard to either know what people want, what they have done, what you have done and a pain to work around what has been done. If I use Observable instead of EventListener then either df will need to reference v1 and v2 or I'll have to pass them all if I want to transfer ownership of the reference to something else out of scope. A weak reference like thing would mitigate the problem a little by transferring control from Observable to an observer but would not solve it entirely (and needs check on every emit or event on itself). This problem can be fixed I suppose if the behaviour only applies to isolated graphs which would complicate the GC severely and would not apply to cases where there are references outside the graph that are in practice noops (only consume CPU cycles, no changes made).

Problem two is that either it is unpredictable in certain cases or forces the JS engine to traverse the GC graph for those objects on demand which can have a horrific performance impact (although if it is clever it can avoid doing it per member by doing it per WeakMap loop instead). The GC may never run if memory usage does not reach a certain threshold and the object with its events wont be removed. If I set v1 to null it may still relay to stdout forever. Even if it does get GCed this will be arbitrary, it may continue to relay to stdout for any amount of time (1 lines, 10 lines, 2.5 lines, etc).

The reason WeakMap gets away with not caring about the GC when non-iterable is that to access an object you have to have a reference to it anyway so either it hasn't been GCed or hasn't been added to the map.

I am not sure what I think about this kind of thing. You're sort of breaking memory management to fix it with the iterable WeakMap approach. Problem two can also exist for destructors as well.

All of this invokes several levels of hell so I would suggest to try to work around it with good program design, good practices, avoiding certain things, etc. It can be frustrating in JS however because of how flexible it is in certain aspects and because it is more naturally asynchronous and event based with heavy inversion of control.

There is one other solution that is fairly elegant but again still has some potentially serious hangups. If you have a class that extends an observable class you can override the event functions. Add your events to other observables only when events are added to yourself. When all events are removed from you then remove your events from children. You can also make a class to extend your observable class to do this for you. Such a class could provide hooks for empty and non-empty so in a since you would be Observing yourself. This approach isn't bad but also has hangups. There is a complexity increase as well as performance decrease. You'll have to keep a reference to object you observe. Critically, it also will not work for leaves but at least the intermediates will self destruct if you destroy the leaf. It's like chaining destroy but hidden behind calls that you already have to chain. A large performance problem is with this however is that you may have to reinitialise internal data from the Observable everytime your class becomes active. If this process takes a very long time then you might be in trouble.

If you could iterate WeakMap then you could perhaps combine things (switch to Weak when no events, Strong when events) but all that is really doing is putting the performance problem on someone else.

There are also immediate annoyances with iterable WeakMap when it comes to behaviour. I mentioned briefly before about functions having scope references and carving. If I instantiate a child that in the constructor that hooks the listener 'console.log(param)' to parent and fails to persist the parent then when I remove all references to the child it could be freed entirely as the anonymous function added to the parent references nothing from within the child. This leaves the question of what to do about parent.weakmap.add(child, (param) => console.log(param)). To my knowledge the key is weak but not the value so weakmap.add(object, object) is persistent. This is something I need to reevaluate though. To me that looks like a memory leak if I dispose all other object references but I suspect in reality it manages that basically by seeing it as a circular reference. Either the anonymous function maintains an implicit reference to objects resulting from parent scopes for consistency wasting a lot of memory or you have behaviour varying based on circumstances which is hard to predict or manage. I think the former is actually impossible. In the latter case if I have a method on a class that simply takes an object and adds console.log it would be freed when I clear the references to the class even if I returned the function and maintained a reference. To be fair this particular scenario is rarely needed legitimately but eventually someone will find an angle and will be asking for a HalfWeakMap which is iterable (free on key and value refs released) but that is unpredictable as well (obj = null magically ending IO, f = null magically ending IO, both doable at incredible distances).

Replace input type=file by an image

Actually it can be done in pure css and it's pretty easy...

HTML Code

<label class="filebutton">
Browse For File!
<span><input type="file" id="myfile" name="myfile"></span>
</label>

CSS Styles

label.filebutton {
    width:120px;
    height:40px;
    overflow:hidden;
    position:relative;
    background-color:#ccc;
}

label span input {
    z-index: 999;
    line-height: 0;
    font-size: 50px;
    position: absolute;
    top: -2px;
    left: -700px;
    opacity: 0;
    filter: alpha(opacity = 0);
    -ms-filter: "alpha(opacity=0)";
    cursor: pointer;
    _cursor: hand;
    margin: 0;
    padding:0;
}

The idea is to position the input absolutely inside your label. set the font size of the input to something large, which will increase the size of the "browse" button. It then takes some trial and error using the negative left / top properties to position the input browse button behind your label.

When positioning the button, set the alpha to 1. When you've finished set it back to 0 (so you can see what you're doing!)

Make sure you test across browsers because they'll all render the input button a slightly different size.

Change the background color of a pop-up dialog

Only update your import.

import android.app.AlertDialog;

to

import android.support.v7.app.AlertDialog;

It will be fixed.

Callback to a Fragment from a DialogFragment

Maybe a bit late, but may help other people with the same question like I did.

You can use setTargetFragment on Dialog before showing, and in dialog you can call getTargetFragment to get the reference.

WP -- Get posts by category?

You can use 'category_name' in parameters. http://codex.wordpress.org/Template_Tags/get_posts

Note: The category_name parameter needs to be a string, in this case, the category name.

POST an array from an HTML form without javascript

You can also post multiple inputs with the same name and have them save into an array by adding empty square brackets to the input name like this:

<input type="text" name="comment[]" value="comment1"/>
<input type="text" name="comment[]" value="comment2"/>
<input type="text" name="comment[]" value="comment3"/>
<input type="text" name="comment[]" value="comment4"/>

If you use php:

print_r($_POST['comment']) 

you will get this:

Array ( [0] => 'comment1' [1] => 'comment2' [2] => 'comment3' [3] => 'comment4' )

EOL conversion in notepad ++

In Notepad++, use replace all with regular expression. This has advantage over conversion command in menu that you can operate on entire folder w/o having to open each file or drag n drop (on several hundred files it will noticeably become slower) plus you can also set filename wildcard filter.

(\r?\n)|(\r\n?)

to

\n

This will match every possible line ending pattern (single \r, \n or \r\n) back to \n. (Or \r\n if you are converting to windows-style)

To operate on multiple files, either:

  • Use "Replace All in all opened document" in "Replace" tab. You will have to drag and drop all files into Notepad++ first. It's good that you will have control over which file to operate on but can be slow if there several hundreds or thousands files.
  • "Replace in files" in "Find in files" tab, by file filter of you choice, e.g., *.cpp *.cs under one specified directory.

How to fix IndexError: invalid index to scalar variable

You are trying to index into a scalar (non-iterable) value:

[y[1] for y in y_test]
#  ^ this is the problem

When you call [y for y in test] you are iterating over the values already, so you get a single value in y.

Your code is the same as trying to do the following:

y_test = [1, 2, 3]
y = y_test[0] # y = 1
print(y[0]) # this line will fail

I'm not sure what you're trying to get into your results array, but you need to get rid of [y[1] for y in y_test].

If you want to append each y in y_test to results, you'll need to expand your list comprehension out further to something like this:

[results.append(..., y) for y in y_test]

Or just use a for loop:

for y in y_test:
    results.append(..., y)

How to debug on a real device (using Eclipse/ADT)

in devices which has Android 4.3 and above you should follow these steps:

How to enable Developer Options:

Launch Settings menu.
Find the open the ‘About Device’ menu.
Scroll down to ‘Build Number’.
Next, tap on the ‘build number’ section seven times.
After the seventh tap you will be told that you are now a developer.
Go back to Settings menu and the Developer Options menu will now be displayed.

In order to enable the USB Debugging you will simply need to open Developer Options, scroll down and tick the box that says ‘USB Debugging’. That’s it.

Error 5 : Access Denied when starting windows service

For me - the folder from which the service was to run, and the files in it, were encrypted using the Windows "Encrypt" option. Removing that and - voila!

What is the apply function in Scala?

1 - Treat functions as objects.

2 - The apply method is similar to __call __ in Python, which allows you to use an instance of a given class as a function.

Java: set timeout on a certain block of code?

I can suggest two options.

  1. Within the method, assuming it is looping and not waiting for an external event, add a local field and test the time each time around the loop.

    void method() {
        long endTimeMillis = System.currentTimeMillis() + 10000;
        while (true) {
            // method logic
            if (System.currentTimeMillis() > endTimeMillis) {
                // do some clean-up
                return;
            }
        }
    }
    
  2. Run the method in a thread, and have the caller count to 10 seconds.

    Thread thread = new Thread(new Runnable() {
            @Override
            public void run() {
                method();
            }
    });
    thread.start();
    long endTimeMillis = System.currentTimeMillis() + 10000;
    while (thread.isAlive()) {
        if (System.currentTimeMillis() > endTimeMillis) {
            // set an error flag
            break;
        }
        try {
            Thread.sleep(500);
        }
        catch (InterruptedException t) {}
    }
    

The drawback to this approach is that method() cannot return a value directly, it must update an instance field to return its value.

Pass command parameter to method in ViewModel in WPF?

"ViewModel" implies MVVM. If you're doing MVVM you shouldn't be passing views into your view models. Typically you do something like this in your XAML:

<Button Content="Edit" 
        Command="{Binding EditCommand}"
        CommandParameter="{Binding ViewModelItem}" >

And then this in your view model:

private ViewModelItemType _ViewModelItem;
public ViewModelItemType ViewModelItem
{
    get
    {
        return this._ViewModelItem;
    }
    set
    {
        this._ViewModelItem = value;
        RaisePropertyChanged(() => this.ViewModelItem);
    }
}

public ICommand EditCommand { get { return new RelayCommand<ViewModelItemType>(OnEdit); } }
private void OnEdit(ViewModelItemType itemToEdit)
{
    ... do something here...
}

Obviously this is just to illustrate the point, if you only had one property to edit called ViewModelItem then you wouldn't need to pass it in as a command parameter.

Definitive way to trigger keypress events with jQuery

The real answer has to include keyCode:

var e = jQuery.Event("keydown");
e.which = 50; // # Some key code value
e.keyCode = 50
$("input").trigger(e);

Even though jQuery's website says that which and keyCode are normalized they are very badly mistaken. It's always safest to do the standard cross-browser checks for e.which and e.keyCode and in this case just define both.

Property 'catch' does not exist on type 'Observable<any>'

In angular 8:

//for catch:
import { catchError } from 'rxjs/operators';

//for throw:
import { Observable, throwError } from 'rxjs';

//and code should be written like this.

getEmployees(): Observable<IEmployee[]> {
    return this.http.get<IEmployee[]>(this.url).pipe(catchError(this.erroHandler));
  }

  erroHandler(error: HttpErrorResponse) {
    return throwError(error.message || 'server Error');
  }

How to manually install an artifact in Maven 2?

You need to indicate the groupId, the artifactId and the version for your artifact:

mvn install:install-file \
  -DgroupId=javax.transaction \
  -DartifactId=jta \
  -Dpackaging=jar \
  -Dversion=1.0.1B \
  -Dfile=jta-1.0.1B.jar \
  -DgeneratePom=true

Slicing of a NumPy 2d array, or how do I extract an mxm submatrix from an nxn array (n>m)?

With numpy, you can pass a slice for each component of the index - so, your x[0:2,0:2] example above works.

If you just want to evenly skip columns or rows, you can pass slices with three components (i.e. start, stop, step).

Again, for your example above:

>>> x[1:4:2, 1:4:2]
array([[ 5,  7],
       [13, 15]])

Which is basically: slice in the first dimension, with start at index 1, stop when index is equal or greater than 4, and add 2 to the index in each pass. The same for the second dimension. Again: this only works for constant steps.

The syntax you got to do something quite different internally - what x[[1,3]][:,[1,3]] actually does is create a new array including only rows 1 and 3 from the original array (done with the x[[1,3]] part), and then re-slice that - creating a third array - including only columns 1 and 3 of the previous array.

Column standard deviation R

The general idea is to sweep the function across. You have many options, one is apply():

R> set.seed(42)
R> M <- matrix(rnorm(40),ncol=4)
R> apply(M, 2, sd)
[1] 0.835449 1.630584 1.156058 1.115269
R> 

How to schedule a task to run when shutting down windows

The Group Policy editor is not mentioned in the post above. I have used GPedit quite a few times to perform a task on bootup or shutdown. Here are Microsoft's instructions on how to access and maneuver GPedit.

How To Use the Group Policy Editor to Manage Local Computer Policy in Windows XP

How to getElementByClass instead of GetElementById with JavaScript?

The getElementsByClassName method is now natively supported by the most recent versions of Firefox, Safari, Chrome, IE and Opera, you could make a function to check if a native implementation is available, otherwise use the Dustin Diaz method:

function getElementsByClassName(node,classname) {
  if (node.getElementsByClassName) { // use native implementation if available
    return node.getElementsByClassName(classname);
  } else {
    return (function getElementsByClass(searchClass,node) {
        if ( node == null )
          node = document;
        var classElements = [],
            els = node.getElementsByTagName("*"),
            elsLen = els.length,
            pattern = new RegExp("(^|\\s)"+searchClass+"(\\s|$)"), i, j;

        for (i = 0, j = 0; i < elsLen; i++) {
          if ( pattern.test(els[i].className) ) {
              classElements[j] = els[i];
              j++;
          }
        }
        return classElements;
    })(classname, node);
  }
}

Usage:

function toggle_visibility(className) {
   var elements = getElementsByClassName(document, className),
       n = elements.length;
   for (var i = 0; i < n; i++) {
     var e = elements[i];

     if(e.style.display == 'block') {
       e.style.display = 'none';
     } else {
       e.style.display = 'block';
     }
  }
}

Ruby objects and JSON serialization (without Rails)

To get the build in classes (like Array and Hash) to support as_json and to_json, you need to require 'json/add/core' (see the readme for details)

What causes: "Notice: Uninitialized string offset" to appear?

Check out the contents of your array with

echo '<pre>' . print_r( $arr, TRUE ) . '</pre>';

How to see data from .RData file?

If you have a lot of variables in your Rdata file and don't want them to clutter your global environment, create a new environment and load all of the data to this new environment.

load(file.path("C:/Users/isfar.RData"), isfar_env <- new.env() )

# Access individual variables in the RData file using '$' operator
isfar_env$var_name 

# List all of the variable names in RData:
ls(isfar_env)

How do I get a Cron like scheduler in Python?

There isn't a "pure python" way to do this because some other process would have to launch python in order to run your solution. Every platform will have one or twenty different ways to launch processes and monitor their progress. On unix platforms, cron is the old standard. On Mac OS X there is also launchd, which combines cron-like launching with watchdog functionality that can keep your process alive if that's what you want. Once python is running, then you can use the sched module to schedule tasks.

angularjs directive call function specified in attribute and pass an argument to it

You can create a directive that executes a function call with params by using the attrName: "&" to reference the expression in the outer scope.

We want to replace the ng-click directive with ng-click-x:

<button ng-click-x="add(a,b)">Add</button>

If we had this scope:

$scope.a = 2;
$scope.b = 2;

$scope.add = function (a, b) {
  $scope.result = parseFloat(a) + parseFloat(b);
}

We could write our directive like so:

angular.module("ng-click-x", [])

.directive('ngClickX', [function () {

  return {

    scope: {

      // Reference the outer scope
      fn: "&ngClickX",

    },

    restrict: "A",

    link: function(scope, elem) {

      function callFn () {
        scope.$apply(scope.fn());
      }

      elem[0].addEventListener('click', callFn);
    }
  };
}]);

Here is a live demo: http://plnkr.co/edit/4QOGLD?p=info

Setting custom UITableViewCells height

in a custom UITableViewCell -controller add this

-(void)layoutSubviews {  

    CGRect newCellSubViewsFrame = CGRectMake(0, 0, self.frame.size.width, self.frame.size.height);
    CGRect newCellViewFrame = CGRectMake(self.frame.origin.x, self.frame.origin.y, self.frame.size.width, self.frame.size.height);

    self.contentView.frame = self.contentView.bounds = self.backgroundView.frame = self.accessoryView.frame = newCellSubViewsFrame;
    self.frame = newCellViewFrame;

    [super layoutSubviews];
}

In the UITableView -controller add this

- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return [indexPath row] * 1.5; // your dynamic height...
}

What is unexpected T_VARIABLE in PHP?

It could be some other line as well. PHP is not always that exact.

Probably you are just missing a semicolon on previous line.

How to reproduce this error, put this in a file called a.php:

<?php
  $a = 5
  $b = 7;        // Error happens here.
  print $b;
?>

Run it:

eric@dev ~ $ php a.php

PHP Parse error:  syntax error, unexpected T_VARIABLE in
/home/el/code/a.php on line 3

Explanation:

The PHP parser converts your program to a series of tokens. A T_VARIABLE is a Token of type VARIABLE. When the parser processes tokens, it tries to make sense of them, and throws errors if it receives a variable where none is allowed.

In the simple case above with variable $b, the parser tried to process this:

$a = 5 $b = 7;

The PHP parser looks at the $b after the 5 and says "that is unexpected".

Make columns of equal width in <table>

I think that this will do the trick:

table{
    table-layout: fixed;
    width: 300px;
}

C# How can I check if a URL exists/is valid?

Web servers respond with a HTTP status code indicating the outcome of the request e.g. 200 (sometimes 202) means success, 404 - not found etc (see here). Assuming the server address part of the URL is correct and you are not getting a socket timeout, the exception is most likely telling you the HTTP status code was other than 200. I would suggest checking the class of the exception and seeing if the exception carries the HTTP status code.

IIRC - The call in question throws a WebException or a descendant. Check the class name to see which one and wrap the call in a try block to trap the condition.

How to redirect single url in nginx?

If you need to duplicate more than a few redirects, you might consider using a map:

# map is outside of server block
map $uri $redirect_uri {
    ~^/issue1/?$    http://example.com/shop/issues/custom_isse_name1;
    ~^/issue2/?$    http://example.com/shop/issues/custom_isse_name2;
    ~^/issue3/?$    http://example.com/shop/issues/custom_isse_name3;
    # ... or put these in an included file
}

location / {
    try_files $uri $uri/ @redirect-map;
}

location @redirect-map {
    if ($redirect_uri) {  # redirect if the variable is defined
        return 301 $redirect_uri;
    }
}

NVIDIA NVML Driver/library version mismatch

If you've recently updated, a reboot might solve this problem.

how to write value into cell with vba code without auto type conversion?

Indeed, just as commented by Tim Williams, the way to make it work is pre-formatting as text. Thus, to do it all via VBA, just do that:

Cells(1, 1).NumberFormat = "@"
Cells(1, 1).Value = "1234,56"

How to change default install location for pip

According to pip documentation at

http://pip.readthedocs.org/en/stable/user_guide/#configuration

You will need to specify the default install location within a pip.ini file, which, also according to the website above is usually located as follows

On Unix and Mac OS X the configuration file is: $HOME/.pip/pip.conf

On Windows, the configuration file is: %HOME%\pip\pip.ini

The %HOME% is located in C:\Users\Bob on windows assuming your name is Bob

On linux the $HOME directory can be located by using cd ~

You may have to create the pip.ini file when you find your pip directory. Within your pip.ini or pip.config you will then need to put (assuming your on windows) something like

[global]
target=C:\Users\Bob\Desktop

Except that you would replace C:\Users\Bob\Desktop with whatever path you desire. If you are on Linux you would replace it with something like /usr/local/your/path

After saving the command would then be

pip install pandas

However, the program you install might assume it will be installed in a certain directory and might not work as a result of being installed elsewhere.

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

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

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

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

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

How to use the DropDownList's SelectedIndexChanged event

I think this is the culprit:

cmd = new SqlCommand(query, con);

DataTable dt = Select(query);

cmd.ExecuteNonQuery();

ddtype.DataSource = dt;

I don't know what that code is supposed to do, but it looks like you want to create an SqlDataReader for that, as explained here and all over the web if you search for "SqlCommand DropDownList DataSource":

cmd = new SqlCommand(query, con);
ddtype.DataSource = cmd.ExecuteReader();

Or you can create a DataTable as explained here:

cmd = new SqlCommand(query, con);

SqlDataAdapter listQueryAdapter = new SqlDataAdapter(cmd);
DataTable listTable = new DataTable();
listQueryAdapter.Fill(listTable);

ddtype.DataSource = listTable;

How to find the 'sizeof' (a pointer pointing to an array)?

 #define array_size 10

 struct {
     int16 size;
     int16 array[array_size];
     int16 property1[(array_size/16)+1]
     int16 property2[(array_size/16)+1]
 } array1 = {array_size, 0, 1, 2, 3, 4, 5, 6, 7, 8, 9};

 #undef array_size

array_size is passing to the size variable:

#define array_size 30

struct {
    int16 size;
    int16 array[array_size];
    int16 property1[(array_size/16)+1]
    int16 property2[(array_size/16)+1]
} array2 = {array_size};

#undef array_size

Usage is:

void main() {

    int16 size = array1.size;
    for (int i=0; i!=size; i++) {

        array1.array[i] *= 2;
    }
}

Command-line svn for Windows?

TortoiseSVN contains a console svn client, but by default the corresponding option is not enabled during installation.

The svn.exe executable is not standalone and it depends on some other files in the distribution but this should not be a problem in most cases.

Once installed you might need to add the folder containing svn.exe to the system PATH as described here so that it is available in your console. To check if it was already added by the installer open a new console and type echo %PATH%. Use set on its own to see all environmental variables.

TortoiseSVN install wizard

Delete files older than 3 months old in a directory using .NET

For example: To go My folder project on source, i need to up two folder. I make this algorim to 2 days week and into four hour

public static void LimpiarArchivosViejos()
    {
        DayOfWeek today = DateTime.Today.DayOfWeek;
        int hora = DateTime.Now.Hour;
        if(today == DayOfWeek.Monday || today == DayOfWeek.Tuesday && hora < 12 && hora > 8)
        {
            CleanPdfOlds();
            CleanExcelsOlds();
        }

    }
    private static void CleanPdfOlds(){
        string[] files = Directory.GetFiles("../../Users/Maxi/Source/Repos/13-12-2017_config_pdfListados/ApplicaAccWeb/Uploads/Reports");
        foreach (string file in files)
        {
            FileInfo fi = new FileInfo(file);
            if (fi.CreationTime < DateTime.Now.AddDays(-7))
                fi.Delete();
        }
    }
    private static void CleanExcelsOlds()
    {
        string[] files2 = Directory.GetFiles("../../Users/Maxi/Source/Repos/13-12-2017_config_pdfListados/ApplicaAccWeb/Uploads/Excels");
        foreach (string file in files2)
        {
            FileInfo fi = new FileInfo(file);
            if (fi.CreationTime < DateTime.Now.AddDays(-7))
                fi.Delete();
        }
    }

How to convert a byte array to its numeric value (Java)?

Assuming the first byte is the least significant byte:

long value = 0;
for (int i = 0; i < by.length; i++)
{
   value += ((long) by[i] & 0xffL) << (8 * i);
}

Is the first byte the most significant, then it is a little bit different:

long value = 0;
for (int i = 0; i < by.length; i++)
{
   value = (value << 8) + (by[i] & 0xff);
}

Replace long with BigInteger, if you have more than 8 bytes.

Thanks to Aaron Digulla for the correction of my errors.

How to filter WooCommerce products by custom attribute

You can use the WooCommerce Layered Nav widget, which allows you to use different sets of attributes as filters for products. Here's the "official" description:

Shows a custom attribute in a widget which lets you narrow down the list of products when viewing product categories.

If you look into plugins/woocommerce/widgets/widget-layered_nav.php, you can see the way it operates with the attributes in order to set filters. The URL then looks like this:

http://yoursite.com/shop/?filtering=1&filter_min-kvadratura=181&filter_max-kvadratura=108&filter_obem-ohlajdane=111

... and the digits are actually the id-s of the different attribute values, that you want to set.

CSS transition with visibility not working

Visibility is an animatable property according to the spec, but transitions on visibility do not work gradually, as one might expect. Instead transitions on visibility delay hiding an element. On the other hand making an element visible works immediately. This is as it is defined by the spec (in the case of the default timing function) and as it is implemented in the browsers.

This also is a useful behavior, since in fact one can imagine various visual effects to hide an element. Fading out an element is just one kind of visual effect that is specified using opacity. Other visual effects might move away the element using e.g. the transform property, also see http://taccgl.org/blog/css-transition-visibility.html

It is often useful to combine the opacity transition with a visibility transition! Although opacity appears to do the right thing, fully transparent elements (with opacity:0) still receive mouse events. So e.g. links on an element that was faded out with an opacity transition alone, still respond to clicks (although not visible) and links behind the faded element do not work (although being visible through the faded element). See http://taccgl.org/blog/css-transition-opacity-for-fade-effects.html.

This strange behavior can be avoided by just using both transitions, the transition on visibility and the transition on opacity. Thereby the visibility property is used to disable mouse events for the element while opacity is used for the visual effect. However care must be taken not to hide the element while the visual effect is playing, which would otherwise not be visible. Here the special semantics of the visibility transition becomes handy. When hiding an element the element stays visible while playing the visual effect and is hidden afterwards. On the other hand when revealing an element, the visibility transition makes the element visible immediately, i.e. before playing the visual effect.

How can I easily view the contents of a datatable or dataview in the immediate window

and if you want this anywhere... to be a helper on DataTable this assumes you want to capture the output to Log4Net but the excellent starting example I worked against just dumps to the console... This one also has editable column width variable nMaxColWidth - ultimately I will pass that from whatever context...

public static class Helpers
    {
        private static ILog Log = Global.Log ?? LogManager.GetLogger("MyLogger");
        /// <summary>
        /// Dump contents of a DataTable to the log
        /// </summary>
        /// <param name="table"></param>
        public static void DebugTable(this DataTable table)
        {
            Log?.Debug("--- DebugTable(" + table.TableName + ") ---");
            var nRows = table.Rows.Count;
            var nCols = table.Columns.Count;
            var nMaxColWidth = 32;

            // Column Headers

            var sColFormat = @"{0,-" + nMaxColWidth + @"} | ";
            var sLogMessage = string.Empty;
            for (var i = 0; i < table.Columns.Count; i++)
            {
                sLogMessage = string.Concat(sLogMessage, string.Format(sColFormat, table.Columns[i].ToString()));
            }
            //Debug.Write(Environment.NewLine);
            Log?.Debug(sLogMessage);

            var sUnderScore = string.Empty;
            var sDashes = string.Empty;
            for (var j = 0; j <= nMaxColWidth; j++)
            {
                sDashes = sDashes + "-";
            }


            for (var i = 0; i < table.Columns.Count; i++)
            {
                sUnderScore = string.Concat(sUnderScore, sDashes + "|-");
            }

            sUnderScore = sUnderScore.TrimEnd('-');

            //Debug.Write(Environment.NewLine);
            Log?.Debug(sUnderScore);

            // Data
            for (var i = 0; i < nRows; i++)
            {
                DataRow row = table.Rows[i];
                //Debug.WriteLine("{0} {1} ", row[0], row[1]);
                sLogMessage = string.Empty;

                for (var j = 0; j < nCols; j++)
                {
                    string s = row[j].ToString();
                    if (s.Length > nMaxColWidth) s = s.Substring(0, nMaxColWidth - 3) + "...";
                    sLogMessage = string.Concat(sLogMessage, string.Format(sColFormat, s));
                }

                Log?.Debug(sLogMessage);
                //Debug.Write(Environment.NewLine);
            }           
            Log?.Debug(sUnderScore);
        }
}

LoDash: Get an array of values from an array of object properties

With pure JS:

var userIds = users.map( function(obj) { return obj.id; } );

How to align an input tag to the center without specifying the width?

To have text-align:center work you need to add that style to the #siteInfo div or wrap the input in a paragraph and add text-align:center to the paragraph.

How to use MapView in android using google map V2?

yes you can use MapView in v2... for further details you can get help from this

https://gist.github.com/joshdholtz/4522551


SomeFragment.java

public class SomeFragment extends Fragment implements OnMapReadyCallback{
 
    MapView mapView;
    GoogleMap map;
 
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v = inflater.inflate(R.layout.some_layout, container, false);
 
        // Gets the MapView from the XML layout and creates it
        mapView = (MapView) v.findViewById(R.id.mapview);
        mapView.onCreate(savedInstanceState);
 
    
        mapView.getMapAsync(this);
        
 
        return v;
    }
 
   @Override
   public void onMapReady(GoogleMap googleMap) {
       map = googleMap;
       map.getUiSettings().setMyLocationButtonEnabled(false);
       map.setMyLocationEnabled(true);
       /*
       //in old Api Needs to call MapsInitializer before doing any CameraUpdateFactory call
        try {
            MapsInitializer.initialize(this.getActivity());
        } catch (GooglePlayServicesNotAvailableException e) {
            e.printStackTrace();
        } 
       */
        
        // Updates the location and zoom of the MapView
        /*CameraUpdate cameraUpdate = CameraUpdateFactory.newLatLngZoom(new LatLng(43.1, -87.9), 10);
        map.animateCamera(cameraUpdate);*/
        map.moveCamera(CameraUpdateFactory.newLatLng(new LatLng(43.1, -87.9)));

    }

    @Override
    public void onResume() {
        mapView.onResume();
        super.onResume();
    }


    @Override
    public void onPause() {
        super.onPause();
        mapView.onPause();
    }
 
    @Override
    public void onDestroy() {
        super.onDestroy();
        mapView.onDestroy();
    }
 
    @Override
    public void onLowMemory() {
        super.onLowMemory();
        mapView.onLowMemory();
    }
 
}

AndroidManifest.xml

<manifest xmlns:android="http://schemas.android.com/apk/res/android"
    package="com.example"
    android:versionCode="1"
    android:versionName="1.0" >
    
    <uses-sdk
        android:minSdkVersion="8"
        android:targetSdkVersion="15" />
    
    <uses-permission android:name="android.permission.INTERNET"/>
    <uses-permission android:name="com.google.android.providers.gsf.permission.READ_GSERVICES"/>
    <uses-permission android:name="android.permission.ACCESS_COARSE_LOCATION"/>
    <uses-permission android:name="android.permission.ACCESS_FINE_LOCATION"/>
    
    <uses-feature
        android:glEsVersion="0x00020000"
        android:required="true"/>
    
    <permission
        android:name="com.example.permission.MAPS_RECEIVE"
        android:protectionLevel="signature"/>
    <uses-permission android:name="com.example.permission.MAPS_RECEIVE"/>
    
    <application
        android:icon="@drawable/ic_launcher"
        android:label="@string/app_name"
        android:theme="@style/AppTheme" >
        
        <meta-data
            android:name="com.google.android.maps.v2.API_KEY"
            android:value="your_key"/>
        
        <activity
            android:name=".HomeActivity"
            android:label="@string/app_name" >
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    
    </application>
 
</manifest>

some_layout.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
    
    <com.google.android.gms.maps.MapView android:id="@+id/mapview"
        android:layout_width="fill_parent" 
        android:layout_height="fill_parent" />
 
</LinearLayout>

Sort collection by multiple fields in Kotlin

Use sortedWith to sort a list with Comparator.

You can then construct a comparator using several ways:

  • compareBy, thenBy construct the comparator in a chain of calls:

    list.sortedWith(compareBy<Person> { it.age }.thenBy { it.name }.thenBy { it.address })
    
  • compareBy has an overload which takes multiple functions:

    list.sortedWith(compareBy({ it.age }, { it.name }, { it.address }))
    

What is the simplest way to convert array to vector?

Pointers can be used like any other iterators:

int x[3] = {1, 2, 3};
std::vector<int> v(x, x + 3);
test(v)

How do you check if a selector matches something in jQuery?

As the other commenters are suggesting the most efficient way to do it seems to be:

if ($(selector).length ) {
    // Do something
}

If you absolutely must have an exists() function - which will be slower- you can do:

jQuery.fn.exists = function(){return this.length>0;}

Then in your code you can use

if ($(selector).exists()) {
    // Do something
}

As answered here

How to override !important?

Override using JavaScript

$('.mytable td').attr('style', 'display: none !important');

Worked for me.

Where can I find the TypeScript version installed in Visual Studio?

Open a (normal, not the VS) command prompt or a PowerShell prompt.

tsc.exe -v tsc.cmd -v tsc -v

If you installed the same version of TypeScript for Visual Studio and using npm, the output from the above three commands should be the same.

If not, check your System PATH to see where in the path hierarchy and which typescript directory is listed. For PowerShell users, the easy way is: $env:path -split ';'

Be careful of having nothing or multiple TypeScript directories listed in your System PATH variable. As of June 9, 2017, my System PATH looked like this (just the top part, which is all that matters in this situation): ps>$env:path -split ';' C:\Windows\system32 C:\Windows C:\Windows\System32\Wbem C:\Windows\System32\WindowsPowerShell\v1.0\ C:\Program Files (x86)\Microsoft SDKs\TypeScript\2.3 C:\nodejs\ C:\Users\{username}\AppData\Roaming\npm

Notice that only the 2.3 directory is included in the PATH, not multiple versions.

Removing packages installed with go get

It's safe to just delete the source directory and compiled package file. Find the source directory under $GOPATH/src and the package file under $GOPATH/pkg/<architecture>, for example: $GOPATH/pkg/windows_amd64.

java how to use classes in other package?

Given your example, you need to add the following import in your main.main class:

import second.second;

Some bonus advice, make sure you titlecase your class names as that is a Java standard. So your example Main class will have the structure:

package main;  //lowercase package names
public class Main //titlecase class names
{
    //Main class content
}

How to use: while not in

If I understand the question correctly you are looking for something like this:

>>> s = "a1 c2 OR c3 AND"
>>> boolops = ["AND", "OR", "NOT"]
>>> if not any(boolop in s for boolop in boolops):
...     print "no boolean operator"
... 
>>> s = "test"
>>> if not any(boolop in s for boolop in boolops):
...     print "no boolean operator"
... 
no boolean operator
>>> 

Any way (or shortcut) to auto import the classes in IntelliJ IDEA like in Eclipse?

Not all at once. But you can press

Alt + Enter

People assume it only works when you are at the particular item. But it actually works for "next missing type". So if you keep pressing Alt + Enter, IDEA fixes one after another until all are fixed.

Java format yyyy-MM-dd'T'HH:mm:ss.SSSz to yyyy-mm-dd HH:mm:ss

I was trying to format the date string received from a JSON response e.g. 2016-03-09T04:50:00-0800 to yyyy-MM-dd. So here's what I tried and it worked and helped me assign the formatted date string a calendar widget.

String DATE_FORMAT_I = "yyyy-MM-dd'T'HH:mm:ss";
String DATE_FORMAT_O = "yyyy-MM-dd";


SimpleDateFormat formatInput = new SimpleDateFormat(DATE_FORMAT_I);
SimpleDateFormat formatOutput = new SimpleDateFormat(DATE_FORMAT_O);

Date date = formatInput.parse(member.getString("date"));
String dateString = formatOutput.format(date);

This worked. Thanks.

How can I clear the NuGet package cache using the command line?

Clearing the cache

With dotnet core cli

dotnet nuget locals all --clear

With Visual Studio 2017

  1. Go to menu Tools ? NuGet Package Manager ? Package Manager Settings.
  2. Click Clear All NuGet Cache(s):

visual studio NuGet Package Manager General settings screenshot

With the nuget cli

Download and install the NuGet command line tool.

nuget locals all -clear

With windows command line

del %LOCALAPPDATA%\NuGet\Cache\*.nupkg /q

(can be used in a .bat file)

With PowerShell

rm $env:LOCALAPPDATA\NuGet\Cache\*.nupkg

Or 'quiet' mode (without error messages):

rm $env:LOCALAPPDATA\NuGet\Cache\*.nupkg 2> $null

Cache location

Windows

%userprofile%\.nuget\packages

Linux

~/.nuget/

Build server

%windir%/ServiceProfiles/[account under build service runs]\AppData\Local\NuGet\Cache

Example:

C:\Windows\ServiceProfiles\NetworkService\AppData\Local\NuGet\Cache

This answer is a rollup of all the existing answers for your convenience

How to make a text box have rounded corners?

You could use CSS to do that, but it wouldn't be supported in IE8-. You can use some site like http://borderradius.com to come up with actual CSS you'd use, which would look something like this (again, depending on how many browsers you're trying to support):

-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;

How to use cookies in Python Requests

You can use a session object. It stores the cookies so you can make requests, and it handles the cookies for you

s = requests.Session() 
# all cookies received will be stored in the session object

s.post('http://www...',data=payload)
s.get('http://www...')

Docs: https://requests.readthedocs.io/en/master/user/advanced/#session-objects

You can also save the cookie data to an external file, and then reload them to keep session persistent without having to login every time you run the script:

How to save requests (python) cookies to a file?

Why does my JavaScript code receive a "No 'Access-Control-Allow-Origin' header is present on the requested resource" error, while Postman does not?

In the below investigation as API, I use http://example.com instead of http://myApiUrl/login from your question, because this first one working.

I assume that your page is on http://my-site.local:8088.

The reason why you see different results is that Postman:

  • set header Host=example.com (your API)
  • NOT set header Origin

This is similar to browsers' way of sending requests when the site and API has the same domain (browsers also set the header item Referer=http://my-site.local:8088, however I don't see it in Postman). When Origin header is not set, usually servers allow such requests by default.

Enter image description here

This is the standard way how Postman sends requests. But a browser sends requests differently when your site and API have different domains, and then CORS occurs and the browser automatically:

  • sets header Host=example.com (yours as API)
  • sets header Origin=http://my-site.local:8088 (your site)

(The header Referer has the same value as Origin). And now in Chrome's Console & Networks tab you will see:

Enter image description here

Enter image description here

When you have Host != Origin this is CORS, and when the server detects such a request, it usually blocks it by default.

Origin=null is set when you open HTML content from a local directory, and it sends a request. The same situation is when you send a request inside an <iframe>, like in the below snippet (but here the Host header is not set at all) - in general, everywhere the HTML specification says opaque origin, you can translate that to Origin=null. More information about this you can find here.

_x000D_
_x000D_
fetch('http://example.com/api', {method: 'POST'});
_x000D_
Look on chrome-console > network tab
_x000D_
_x000D_
_x000D_

If you do not use a simple CORS request, usually the browser automatically also sends an OPTIONS request before sending the main request - more information is here. The snippet below shows it:

_x000D_
_x000D_
fetch('http://example.com/api', {_x000D_
  method: 'POST',_x000D_
  headers: { 'Content-Type': 'application/json'}_x000D_
});
_x000D_
Look in chrome-console -> network tab to 'api' request._x000D_
This is the OPTIONS request (the server does not allow sending a POST request)
_x000D_
_x000D_
_x000D_

You can change the configuration of your server to allow CORS requests.

Here is an example configuration which turns on CORS on nginx (nginx.conf file) - be very careful with setting always/"$http_origin" for nginx and "*" for Apache - this will unblock CORS from any domain.

_x000D_
_x000D_
location ~ ^/index\.php(/|$) {_x000D_
   ..._x000D_
    add_header 'Access-Control-Allow-Origin' "$http_origin" always;_x000D_
    add_header 'Access-Control-Allow-Credentials' 'true' always;_x000D_
    if ($request_method = OPTIONS) {_x000D_
        add_header 'Access-Control-Allow-Origin' "$http_origin"; # DO NOT remove THIS LINES (doubled with outside 'if' above)_x000D_
        add_header 'Access-Control-Allow-Credentials' 'true';_x000D_
        add_header 'Access-Control-Max-Age' 1728000; # cache preflight value for 20 days_x000D_
        add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS';_x000D_
        add_header 'Access-Control-Allow-Headers' 'My-First-Header,My-Second-Header,Authorization,Content-Type,Accept,Origin';_x000D_
        add_header 'Content-Length' 0;_x000D_
        add_header 'Content-Type' 'text/plain charset=UTF-8';_x000D_
        return 204;_x000D_
    }_x000D_
}
_x000D_
_x000D_
_x000D_

Here is an example configuration which turns on CORS on Apache (.htaccess file)

_x000D_
_x000D_
# ------------------------------------------------------------------------------_x000D_
# | Cross-domain Ajax requests                                                 |_x000D_
# ------------------------------------------------------------------------------_x000D_
_x000D_
# Enable cross-origin Ajax requests._x000D_
# http://code.google.com/p/html5security/wiki/CrossOriginRequestSecurity_x000D_
# http://enable-cors.org/_x000D_
_x000D_
# <IfModule mod_headers.c>_x000D_
#    Header set Access-Control-Allow-Origin "*"_x000D_
# </IfModule>_x000D_
_x000D_
# Header set Header set Access-Control-Allow-Origin "*"_x000D_
# Header always set Access-Control-Allow-Credentials "true"_x000D_
_x000D_
Access-Control-Allow-Origin "http://your-page.com:80"_x000D_
Header always set Access-Control-Allow-Methods "POST, GET, OPTIONS, DELETE, PUT"_x000D_
Header always set Access-Control-Allow-Headers "My-First-Header,My-Second-Header,Authorization, content-type, csrf-token"
_x000D_
_x000D_
_x000D_

javascript setTimeout() not working

This line:

setTimeout(startTimer(), startInterval); 

You're invoking startTimer(). Instead, you need to pass it in as a function to be invoked, like so:

setTimeout(startTimer, startInterval);

Plot a line graph, error in xy.coords(x, y, xlabel, ylabel, log) : 'x' and 'y' lengths differ

plot(t) is in this case the same as

plot(t[[1]], t[[2]])

As the error message says, x and y differ in length and that is because you plot a list with length 4 against 1:

> length(t)
[1] 4
> length(1)
[1] 1

In your second example you plot a list with elements named x and y, both vectors of length 2, so plot plots these two vectors.

Edit:

If you want to plot lines use

plot(t, type="l")

CSS Progress Circle

Another pure css based solution that is based on two clipped rounded elements that i rotate to get to the right angle:

http://jsfiddle.net/maayan/byT76/

That's the basic css that enables it:

.clip1 {
    position:absolute;
    top:0;left:0;
    width:200px;
    height:200px;
    clip:rect(0px,200px,200px,100px);
}
.slice1 {
    position:absolute;
    width:200px;
    height:200px;
    clip:rect(0px,100px,200px,0px);
    -moz-border-radius:100px;
    -webkit-border-radius:100px; 
    border-radius:100px;
    background-color:#f7e5e1;
    border-color:#f7e5e1;
    -moz-transform:rotate(0);
    -webkit-transform:rotate(0);
    -o-transform:rotate(0);
    transform:rotate(0);
}

.clip2 
{
    position:absolute;
    top:0;left:0;
    width:200px;
    height:200px;
    clip:rect(0,100px,200px,0px);
}

.slice2
{
    position:absolute;
    width:200px;
    height:200px;
    clip:rect(0px,200px,200px,100px);
    -moz-border-radius:100px;
    -webkit-border-radius:100px; 
    border-radius:100px;
    background-color:#f7e5e1;
    border-color:#f7e5e1;
    -moz-transform:rotate(0);
    -webkit-transform:rotate(0);
    -o-transform:rotate(0);
    transform:rotate(0);
}

and the js rotates it as required.

quite easy to understand..

Hope it helps, Maayan

100% width table overflowing div container

Try adding

word-break: break-all 

to the CSS on your table element.

That will get the words in the table cells to break such that the table does not grow wider than its containing div, yet the table columns are still sized dynamically. jsfiddle demo.

Using LINQ to remove elements from a List<T>

To keep the code fluent (if code optimisation is not crucial) and you would need to do some further operations on the list:

authorsList = authorsList.Where(x => x.FirstName != "Bob").<do_some_further_Linq>;

or

authorsList = authorsList.Where(x => !setToRemove.Contains(x)).<do_some_further_Linq>;

Easiest way to change font and font size

Maybe something like this:

yourformName.YourLabel.Font = new Font("Arial", 24,FontStyle.Bold);

Or if you are in the same class as the form then simply do this:

YourLabel.Font = new Font("Arial", 24,FontStyle.Bold);

The constructor takes diffrent parameters (so pick your poison). Like this:

Font(Font, FontStyle)   
Font(FontFamily, Single)
Font(String, Single)
Font(FontFamily, Single, FontStyle)
Font(FontFamily, Single, GraphicsUnit)
Font(String, Single, FontStyle)
Font(String, Single, GraphicsUnit)
Font(FontFamily, Single, FontStyle, GraphicsUnit)
Font(String, Single, FontStyle, GraphicsUnit)
Font(FontFamily, Single, FontStyle, GraphicsUnit, Byte)
Font(String, Single, FontStyle, GraphicsUnit, Byte)
Font(FontFamily, Single, FontStyle, GraphicsUnit, Byte, Boolean)
Font(String, Single, FontStyle, GraphicsUnit, Byte, Boolean)

Reference here

C# Convert a Base64 -> byte[]

Try

byte[] incomingByteArray = receive...; // This is your Base64-encoded bute[]

byte[] decodedByteArray =Convert.FromBase64String (Encoding.ASCII.GetString (incomingByteArray)); 
// This work because all Base64-encoding is done with pure ASCII characters

What is the difference between ndarray and array in numpy?

numpy.array is a function that returns a numpy.ndarray. There is no object type numpy.array.

How to use shared memory with Linux in C

Here's a mmap example:

#include <sys/mman.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>

/*
 * pvtmMmapAlloc - creates a memory mapped file area.  
 * The return value is a page-aligned memory value, or NULL if there is a failure.
 * Here's the list of arguments:
 * @mmapFileName - the name of the memory mapped file
 * @size - the size of the memory mapped file (should be a multiple of the system page for best performance)
 * @create - determines whether or not the area should be created.
 */
void* pvtmMmapAlloc (char * mmapFileName, size_t size, char create)  
{      
  void * retv = NULL;                                                                                              
  if (create)                                                                                         
  {                                                                                                   
    mode_t origMask = umask(0);                                                                       
    int mmapFd = open(mmapFileName, O_CREAT|O_RDWR, 00666);                                           
    umask(origMask);                                                                                  
    if (mmapFd < 0)                                                                                   
    {                                                                                                 
      perror("open mmapFd failed");                                                                   
      return NULL;                                                                                    
    }                                                                                                 
    if ((ftruncate(mmapFd, size) == 0))               
    {                                                                                                 
      int result = lseek(mmapFd, size - 1, SEEK_SET);               
      if (result == -1)                                                                               
      {                                                                                               
        perror("lseek mmapFd failed");                                                                
        close(mmapFd);                                                                                
        return NULL;                                                                                  
      }                                                                                               

      /* Something needs to be written at the end of the file to                                      
       * have the file actually have the new size.                                                    
       * Just writing an empty string at the current file position will do.                           
       * Note:                                                                                        
       *  - The current position in the file is at the end of the stretched                           
       *    file due to the call to lseek().  
              *  - The current position in the file is at the end of the stretched                    
       *    file due to the call to lseek().                                                          
       *  - An empty string is actually a single '\0' character, so a zero-byte                       
       *    will be written at the last byte of the file.                                             
       */                                                                                             
      result = write(mmapFd, "", 1);                                                                  
      if (result != 1)                                                                                
      {                                                                                               
        perror("write mmapFd failed");                                                                
        close(mmapFd);                                                                                
        return NULL;                                                                                  
      }                                                                                               
      retv  =  mmap(NULL, size,   
                  PROT_READ | PROT_WRITE, MAP_SHARED, mmapFd, 0);                                     

      if (retv == MAP_FAILED || retv == NULL)                                                         
      {                                                                                               
        perror("mmap");                                                                               
        close(mmapFd);                                                                                
        return NULL;                                                                                  
      }                                                                                               
    }                                                                                                 
  }                                                                                                   
  else                                                                                                
  {                                                                                                   
    int mmapFd = open(mmapFileName, O_RDWR, 00666);                                                   
    if (mmapFd < 0)                                                                                   
    {                                                                                                 
      return NULL;                                                                                    
    }                                                                                                 
    int result = lseek(mmapFd, 0, SEEK_END);                                                          
    if (result == -1)                                                                                 
    {                                                                                                 
      perror("lseek mmapFd failed");                  
      close(mmapFd);                                                                                  
      return NULL;                                                                                    
    }                                                                                                 
    if (result == 0)                                                                                  
    {                                                                                                 
      perror("The file has 0 bytes");                           
      close(mmapFd);                                                                                  
      return NULL;                                                                                    
    }                                                                                              
    retv  =  mmap(NULL, size,     
                PROT_READ | PROT_WRITE, MAP_SHARED, mmapFd, 0);                                       

    if (retv == MAP_FAILED || retv == NULL)                                                           
    {                                                                                                 
      perror("mmap");                                                                                 
      close(mmapFd);                                                                                  
      return NULL;                                                                                    
    }                                                                                                 

    close(mmapFd);                                                                                    

  }                                                                                                   
  return retv;                                                                                        
}                                                                                                     

Can I set max_retries for requests.request?

It is the underlying urllib3 library that does the retrying. To set a different maximum retry count, use alternative transport adapters:

from requests.adapters import HTTPAdapter

s = requests.Session()
s.mount('http://stackoverflow.com', HTTPAdapter(max_retries=5))

The max_retries argument takes an integer or a Retry() object; the latter gives you fine-grained control over what kinds of failures are retried (an integer value is turned into a Retry() instance which only handles connection failures; errors after a connection is made are by default not handled as these could lead to side-effects).


Old answer, predating the release of requests 1.2.1:

The requests library doesn't really make this configurable, nor does it intend to (see this pull request). Currently (requests 1.1), the retries count is set to 0. If you really want to set it to a higher value, you'll have to set this globally:

import requests

requests.adapters.DEFAULT_RETRIES = 5

This constant is not documented; use it at your own peril as future releases could change how this is handled.

Update: and this did change; in version 1.2.1 the option to set the max_retries parameter on the HTTPAdapter() class was added, so that now you have to use alternative transport adapters, see above. The monkey-patch approach no longer works, unless you also patch the HTTPAdapter.__init__() defaults (very much not recommended).

When to use dynamic vs. static libraries

Static libraries are archives that contain the object code for the library, when linked into an application that code is compiled into the executable. Shared libraries are different in that they aren't compiled into the executable. Instead the dynamic linker searches some directories looking for the library(s) it needs, then loads that into memory. More then one executable can use the same shared library at the same time, thus reducing memory usage and executable size. However, there are then more files to distribute with the executable. You need to make sure that the library is installed onto the uses system somewhere where the linker can find it, static linking eliminates this problem but results in a larger executable file.

Split String by delimiter position using oracle SQL

You want to use regexp_substr() for this. This should work for your example:

select regexp_substr(val, '[^/]+/[^/]+', 1, 1) as part1,
       regexp_substr(val, '[^/]+$', 1, 1) as part2
from (select 'F/P/O' as val from dual) t

Here, by the way, is the SQL Fiddle.

Oops. I missed the part of the question where it says the last delimiter. For that, we can use regex_replace() for the first part:

select regexp_replace(val, '/[^/]+$', '', 1, 1) as part1,
       regexp_substr(val, '[^/]+$', 1, 1) as part2
from (select 'F/P/O' as val from dual) t

And here is this corresponding SQL Fiddle.

Standard deviation of a list

Since Python 3.4 / PEP450 there is a statistics module in the standard library, which has a method stdev for calculating the standard deviation of iterables like yours:

>>> A_rank = [0.8, 0.4, 1.2, 3.7, 2.6, 5.8]
>>> import statistics
>>> statistics.stdev(A_rank)
2.0634114147853952

Install gitk on Mac

If you already have git installed via homebrew, you can just do upgrade:

$ type -a git
/usr/bin/git
$ brew upgrade git
$ type -a git
/usr/local/bin/git

The one at local/bin will have gitk

How to force div to appear below not next to another?

Float the #list and #similar the right and add clear: right; to #similar

Like so:

#map { float:left; width:700px; height:500px; }
#list { float:right; width:200px; background:#eee; list-style:none; padding:0; }
#similar { float:right; width:200px; background:#000; clear:right; } 


<div id="map"></div>        
<ul id="list"></ul>
<div id="similar">this text should be below, not next to ul.</div>

You might need a wrapper(div) around all of them though that's the same width of the left and right element.

XAMPP permissions on Mac OS X?

Following the instructions from this page,

  1. Open the XAMPP control panel (cmd-space, then enter manager-osx.app).
  2. Select Manage Servers tab -> select Apache Web Server -> click Configure.
  3. Click Open Conf File. Provide credentials if asked.
  4. Change

    <IfModule unixd_module>
    #
    # If you wish httpd to run as a different user or group, you must run
    # httpd as root initially and it will switch.  
    #
    # User/Group: The name (or #number) of the user/group to run httpd as.
    # It is usually good practice to create a dedicated user and group for
    # running httpd, as with most system services.
    #
    User daemon
    Group daemon
    </IfModule>
    

    to

    <IfModule unixd_module>
    #
    # If you wish httpd to run as a different user or group, you must run
    # httpd as root initially and it will switch.  
    #
    # User/Group: The name (or #number) of the user/group to run httpd as.
    # It is usually good practice to create a dedicated user and group for
    # running httpd, as with most system services.
    #
    User your_username
    Group staff
    </IfModule>
    
  5. Save and close.

  6. Using the XAMPP control panel, restart Apache.
  7. Navigate to the document root of your server and make yourself the owner. The default is /Applications/XAMPP/xamppfiles/htdocs.

    $ cd your_document_root
    $ sudo chown -R your_username:staff .
    
  8. Navigate to the xamppfiles directory and change the permission for logs and temp directory.

    $ cd /Applications/XAMPP/xamppfiles
    $ sudo chown -R your_username:staff logs
    $ sudo chown -R your_username:staff temp
    
  9. To be able to use phpmyadmin you have to change the permissions for config.inc.php.

    $ cd /Applications/XAMPP/xamppfiles/phpmyadmin
    $ sudo chown your_username:staff config.inc.php
    

Python: How to keep repeating a program until a specific input is obtained?

This is a small program that will keep asking an input until required input is given.

we should keep the required number as a string, otherwise it may not work. input is taken as string by default

required_number = '18'

while True:
    number = input("Enter the number\n")
    if number == required_number:
        print ("GOT IT")
        break
    else:
        print ("Wrong number try again")

or you can use eval(input()) method

required_number = 18

while True:
    number = eval(input("Enter the number\n"))
    if number == required_number:
        print ("GOT IT")
        break
    else:
        print ("Wrong number try again")

JSON Parse File Path

var request = new XMLHttpRequest();
request.open("GET","<path_to_file>", false);
request.send(null);
var jsonData = JSON.parse(request.responseText);

This code worked for me.

Base 64 encode and decode example code

If you are using Kotlin than use like this

For Encode

val password = "Here Your String"
val data = password.toByteArray(charset("UTF-8"))
val base64 = Base64.encodeToString(data, Base64.DEFAULT)

For Decode

val datasd = Base64.decode(base64, Base64.DEFAULT)
val text = String(datasd, charset("UTF-8"))

Stream file using ASP.NET MVC FileContentResult in a browser with a name?

Actually, the absolutely easiest way is to do the following...

byte[] content = your_byte[];

FileContentResult result = new FileContentResult(content, "application/octet-stream") 
{
  FileDownloadName = "your_file_name"
};

return result;

Sequelize OR condition object

Seems there is another format now

where: {
    LastName: "Doe",
    $or: [
        {
            FirstName: 
            {
                $eq: "John"
            }
        }, 
        {
            FirstName: 
            {
                $eq: "Jane"
            }
        }, 
        {
            Age: 
            {
                $gt: 18
            }
        }
    ]
}

Will generate

WHERE LastName='Doe' AND (FirstName = 'John' OR FirstName = 'Jane' OR Age > 18)

See the doc: http://docs.sequelizejs.com/en/latest/docs/querying/#where

How to remove all listeners in an element?

Here's a function that is also based on cloneNode, but with an option to clone only the parent node and move all the children (to preserve their event listeners):

function recreateNode(el, withChildren) {
  if (withChildren) {
    el.parentNode.replaceChild(el.cloneNode(true), el);
  }
  else {
    var newEl = el.cloneNode(false);
    while (el.hasChildNodes()) newEl.appendChild(el.firstChild);
    el.parentNode.replaceChild(newEl, el);
  }
}

Remove event listeners on one element:

recreateNode(document.getElementById("btn"));

Remove event listeners on an element and all of its children:

recreateNode(document.getElementById("list"), true);

If you need to keep the object itself and therefore can't use cloneNode, then you have to wrap the addEventListener function and track the listener list by yourself, like in this answer.

The OLE DB provider "Microsoft.ACE.OLEDB.12.0" for linked server "(null)"

In the SQL Server, try these steps:

  1. Open one database.
  2. Click in the option Server Object.
  3. Click in Linked Servers.
  4. Click in Providers.
  5. Right click on Microsoft.ACE.OLEDB.12.0 and click Properties.
  6. Uncheck all the options and close.

Eclipse IDE: How to zoom in on text?

I've answered it here. How can I change font size in Eclipse for Java text editors?

For Eclipse Neon

To Increase Ctrl +

To reduce Ctrl - enter image description here

ASP.NET MVC: Custom Validation by DataAnnotation

Background:

Model validations are required for ensuring that the received data we receive is valid and correct so that we can do the further processing with this data. We can validate a model in an action method. The built-in validation attributes are Compare, Range, RegularExpression, Required, StringLength. However we may have scenarios wherein we required validation attributes other than the built-in ones.

Custom Validation Attributes

public class EmployeeModel 
{
    [Required]
    [UniqueEmailAddress]
    public string EmailAddress {get;set;}
    public string FirstName {get;set;}
    public string LastName {get;set;}
    public int OrganizationId {get;set;}
}

To create a custom validation attribute, you will have to derive this class from ValidationAttribute.

public class UniqueEmailAddress : ValidationAttribute
{
    private IEmployeeRepository _employeeRepository;
    [Inject]
    public IEmployeeRepository EmployeeRepository
    {
        get { return _employeeRepository; }
        set
        {
            _employeeRepository = value;
        }
    }
    protected override ValidationResult IsValid(object value,
                        ValidationContext validationContext)
    {
        var model = (EmployeeModel)validationContext.ObjectInstance;
        if(model.Field1 == null){
            return new ValidationResult("Field1 is null");
        }
        if(model.Field2 == null){
            return new ValidationResult("Field2 is null");
        }
        if(model.Field3 == null){
            return new ValidationResult("Field3 is null");
        }
        return ValidationResult.Success;
    }
}

Hope this helps. Cheers !

References

Checking if a date is valid in javascript

Try this:

var date = new Date();
console.log(date instanceof Date && !isNaN(date.valueOf()));

This should return true.

UPDATED: Added isNaN check to handle the case commented by Julian H. Lam

How to Pass Parameters to Activator.CreateInstance<T>()

Keep in mind though that passing arguments on Activator.CreateInstance has a significant performance difference versus parameterless creation.

There are better alternatives for dynamically creating objects using pre compiled lambda. Of course always performance is subjective and it clearly depends on each case if it's worth it or not.

Details about the issue on this article.

Graph is taken from the article and represents time taken in ms per 1000 calls.

Performance comparison

Merge two objects with ES6

Another aproach is:

let result = { ...item, location : { ...response } }

But Object spread isn't yet standardized.

May also be helpful: https://stackoverflow.com/a/32926019/5341953

Re-ordering columns in pandas dataframe based on column name

You can just do:

df[sorted(df.columns)]

Edit: Shorter is

df[sorted(df)]

How to read a HttpOnly cookie using JavaScript

Different Browsers enable different security measures when the HTTPOnly flag is set. For instance Opera and Safari do not prevent javascript from writing to the cookie. However, reading is always forbidden on the latest version of all major browsers.

But more importantly why do you want to read an HTTPOnly cookie? If you are a developer, just disable the flag and make sure you test your code for xss. I recommend that you avoid disabling this flag if at all possible. The HTTPOnly flag and "secure flag" (which forces the cookie to be sent over https) should always be set.

If you are an attacker, then you want to hijack a session. But there is an easy way to hijack a session despite the HTTPOnly flag. You can still ride on the session without knowing the session id. The MySpace Samy worm did just that. It used an XHR to read a CSRF token and then perform an authorized task. Therefore, the attacker could do almost anything that the logged user could do.

People have too much faith in the HTTPOnly flag, XSS can still be exploitable. You should setup barriers around sensitive features. Such as the change password filed should require the current password. An admin's ability to create a new account should require a captcha, which is a CSRF prevention technique that cannot be easily bypassed with an XHR.

$location / switching between html5 and hashbang mode / link rewriting

I wanted to be able to access my application with the HTML5 mode and a fixed token and then switch to the hashbang method (to keep the token so the user can refresh his page).

URL for accessing my app:

http://myapp.com/amazing_url?token=super_token

Then when the user loads the page:

http://myapp.com/amazing_url?token=super_token#/amazing_url

Then when the user navigates:

http://myapp.com/amazing_url?token=super_token#/another_url

With this I keep the token in the URL and keep the state when the user is browsing. I lost a bit of visibility of the URL, but there is no perfect way of doing it.

So don't enable the HTML5 mode and then add this controller:

.config ($stateProvider)->
    $stateProvider.state('home-loading', {
         url: '/',
         controller: 'homeController'
    })
.controller 'homeController', ($state, $location)->
    if window.location.pathname != '/'
        $location.url(window.location.pathname+window.location.search).replace()
    else
        $state.go('home', {}, { location: 'replace' })

Is there a minlength validation attribute in HTML5?

If desired to make this behavior, always show a small prefix on the input field or the user can't erase a prefix:

   // prefix="prefix_text"
   // If the user changes the prefix, restore the input with the prefix:
   if(document.getElementById('myInput').value.substring(0,prefix.length).localeCompare(prefix))
       document.getElementById('myInput').value = prefix;

Problem in running .net framework 4.0 website on iis 7.0

Try changing the AppPool Manged Pipeline Mode from "Integration" to "Classic".

How can I return camelCase JSON serialized by JSON.NET from ASP.NET MVC controller methods?

I think this is the simple answer you are looking for. It's from Shawn Wildermuth's blog:

// Add MVC services to the services container.
services.AddMvc()
  .AddJsonOptions(opts =>
  {
    opts.SerializerSettings.ContractResolver = new CamelCasePropertyNamesContractResolver();
  });

Link to Flask static files with url_for

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

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

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

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

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

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

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

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

Which will be converted to (using default settings):

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

Also look at url_for documentation.

Bulk load data conversion error (type mismatch or invalid character for the specified codepage) for row 1, column 4 (Year)

The above options works for Google big query file also. I exported a table data to goodle cloud storage and downloaded from there. While loading the same to sql server was facing this issue and could successfully load the file after specifying the row delimiter as

ROWTERMINATOR = '0x0a' 

Pay attention to header record as well and specify

FIRSTROW = 2

My final block for data file export from google bigquery looks like this.

BULK INSERT TABLENAME
        FROM 'C:\ETL\Data\BigQuery\In\FILENAME.csv'
        WITH
        (
         FIRSTROW = 2,
         FIELDTERMINATOR = ',',  --CSV field delimiter
         ROWTERMINATOR = '0x0a',--Files are generated with this row terminator in Google Bigquery
         TABLOCK
        )

How can I clear the Scanner buffer in Java?

You can't explicitly clear Scanner's buffer. Internally, it may clear the buffer after a token is read, but that's an implementation detail outside of the porgrammers' reach.

Ajax Success and Error function failure

 $.ajax({
         type:'POST',
         url: 'ajaxRequest.php',
         data:{
         userEmail : userEmail
         },
         success:function(data){
         if(data == "error"){
                $('#ShowError').show().text("Email dosen't Match ");
                $('#ShowSuccess').hide();
               }
               else{
                 $('#ShowSuccess').show().text(data);
                }
              }
            });

Jquery: how to sleep or delay?

If you can't use the delay method as Robert Harvey suggested, you can use setTimeout.

Eg.

setTimeout(function() {$("#test").animate({"top":"-=80px"})} , 1500); // delays 1.5 sec
setTimeout(function() {$("#test").animate({"opacity":"0"})} , 1500 + 1000); // delays 1 sec after the previous one

jQuery load first 3 elements, click "load more" to display next 5 elements

WARNING: size() was deprecated in jQuery 1.8 and removed in jQuery 3.0, use .length instead

Working Demo: http://jsfiddle.net/cse_tushar/6FzSb/

$(document).ready(function () {
    size_li = $("#myList li").size();
    x=3;
    $('#myList li:lt('+x+')').show();
    $('#loadMore').click(function () {
        x= (x+5 <= size_li) ? x+5 : size_li;
        $('#myList li:lt('+x+')').show();
    });
    $('#showLess').click(function () {
        x=(x-5<0) ? 3 : x-5;
        $('#myList li').not(':lt('+x+')').hide();
    });
});


New JS to show or hide load more and show less

$(document).ready(function () {
    size_li = $("#myList li").size();
    x=3;
    $('#myList li:lt('+x+')').show();
    $('#loadMore').click(function () {
        x= (x+5 <= size_li) ? x+5 : size_li;
        $('#myList li:lt('+x+')').show();
         $('#showLess').show();
        if(x == size_li){
            $('#loadMore').hide();
        }
    });
    $('#showLess').click(function () {
        x=(x-5<0) ? 3 : x-5;
        $('#myList li').not(':lt('+x+')').hide();
        $('#loadMore').show();
         $('#showLess').show();
        if(x == 3){
            $('#showLess').hide();
        }
    });
});

CSS

#showLess {
    color:red;
    cursor:pointer;
    display:none;
}

Working Demo: http://jsfiddle.net/cse_tushar/6FzSb/2/

Why is my CSS style not being applied?

In addition to the solutions posted above, having gone through the exact same problem, make sure you check your HTML. More specifically whether you've properly labelled your elements, as well as class and id selectors. You can do this either manually or through a validator (https://validator.w3.org/).

For me, I missed the equal sign next to the class (<div class someDiv> vs <div class = "someDiv">, hence why no CSS property was applied.

$_POST vs. $_SERVER['REQUEST_METHOD'] == 'POST'

They both work the same way, but $_POST should be used as it is cleaner. You can add isset() to it to check it exists.

How to use java.net.URLConnection to fire and handle HTTP requests?

Update

The new HTTP Client shipped with Java 9 but as part of an Incubator module named jdk.incubator.httpclient. Incubator modules are a means of putting non-final APIs in the hands of developers while the APIs progress towards either finalization or removal in a future release.

In Java 9, you can send a GET request like:

// GET
HttpResponse response = HttpRequest
    .create(new URI("http://www.stackoverflow.com"))
    .headers("Foo", "foovalue", "Bar", "barvalue")
    .GET()
    .response();

Then you can examine the returned HttpResponse:

int statusCode = response.statusCode();
String responseBody = response.body(HttpResponse.asString());

Since this new HTTP Client is in java.httpclient jdk.incubator.httpclient module, you should declare this dependency in your module-info.java file:

module com.foo.bar {
    requires jdk.incubator.httpclient;
}

Compiling C++11 with g++

If you want to keep the GNU compiler extensions, use -std=gnu++0x rather than -std=c++0x. Here's a quote from the man page:

The compiler can accept several base standards, such as c89 or c++98, and GNU dialects of those standards, such as gnu89 or gnu++98. By specifying a base standard, the compiler will accept all programs following that standard and those using GNU extensions that do not contradict it. For example, -std=c89 turns off certain features of GCC that are incompatible with ISO C90, such as the "asm" and "typeof" keywords, but not other GNU extensions that do not have a meaning in ISO C90, such as omitting the middle term of a "?:" expression. On the other hand, by specifying a GNU dialect of a standard, all features the compiler support are enabled, even when those features change the meaning of the base standard and some strict-conforming programs may be rejected. The particular standard is used by -pedantic to identify which features are GNU extensions given that version of the standard. For example-std=gnu89 -pedantic would warn about C++ style // comments, while -std=gnu99 -pedantic would not.

Select max value of each group

SELECT DISTINCT (t1.ProdId), t1.Quantity FROM Dummy t1 INNER JOIN
       (SELECT ProdId, MAX(Quantity) as MaxQuantity FROM Dummy GROUP BY ProdId) t2
    ON t1.ProdId = t2.ProdId
   AND t1.Quantity = t2.MaxQuantity
 ORDER BY t1.ProdId

this will give you the idea.

Sequence contains no matching element

From the MSDN library:

The First<TSource>(IEnumerable<TSource>) method throws an exception if source contains no elements. To instead return a default value when the source sequence is empty, use the FirstOrDefault method.

Chosen Jquery Plugin - getting selected values

$("#select-id").chosen().val()

Write a file on iOS

Try making

NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"MyFile"];

as

NSString *appFile = [documentsDirectory stringByAppendingPathComponent:@"MyFile.txt"];

Getting error "The package appears to be corrupt" while installing apk file

When you are releasing signed apk , please make sure you tick both v1 and v2 in signature versions

See below screenshot for more info Signed APK generation

Regex to check with starts with http://, https:// or ftp://

Unless there is some compelling reason to use a regex, I would just use String.startsWith:

bool matches = test.startsWith("http://")
            || test.startsWith("https://") 
            || test.startsWith("ftp://");

I wouldn't be surprised if this is faster, too.

WARNING in budgets, maximum exceeded for initial

What is Angular CLI Budgets? Budgets is one of the less known features of the Angular CLI. It’s a rather small but a very neat feature!

As applications grow in functionality, they also grow in size. Budgets is a feature in the Angular CLI which allows you to set budget thresholds in your configuration to ensure parts of your application stay within boundaries which you setOfficial Documentation

Or in other words, we can describe our Angular application as a set of compiled JavaScript files called bundles which are produced by the build process. Angular budgets allows us to configure expected sizes of these bundles. More so, we can configure thresholds for conditions when we want to receive a warning or even fail build with an error if the bundle size gets too out of control!

How To Define A Budget? Angular budgets are defined in the angular.json file. Budgets are defined per project which makes sense because every app in a workspace has different needs.

Thinking pragmatically, it only makes sense to define budgets for the production builds. Prod build creates bundles with “true size” after applying all optimizations like tree-shaking and code minimization.

Oops, a build error! The maximum bundle size was exceeded. This is a great signal that tells us that something went wrong…

  1. We might have experimented in our feature and didn’t clean up properly
  2. Our tooling can go wrong and perform a bad auto-import, or we pick bad item from the suggested list of imports
  3. We might import stuff from lazy modules in inappropriate locations
  4. Our new feature is just really big and doesn’t fit into existing budgets

First Approach: Are your files gzipped?

Generally speaking, gzipped file has only about 20% the size of the original file, which can drastically decrease the initial load time of your app. To check if you have gzipped your files, just open the network tab of developer console. In the “Response Headers”, if you should see “Content-Encoding: gzip”, you are good to go.

How to gzip? If you host your Angular app in most of the cloud platforms or CDN, you should not worry about this issue as they probably have handled this for you. However, if you have your own server (such as NodeJS + expressJS) serving your Angular app, definitely check if the files are gzipped. The following is an example to gzip your static assets in a NodeJS + expressJS app. You can hardly imagine this dead simple middleware “compression” would reduce your bundle size from 2.21MB to 495.13KB.

const compression = require('compression')
const express = require('express')
const app = express()
app.use(compression())

Second Approach:: Analyze your Angular bundle

If your bundle size does get too big you may want to analyze your bundle because you may have used an inappropriate large-sized third party package or you forgot to remove some package if you are not using it anymore. Webpack has an amazing feature to give us a visual idea of the composition of a webpack bundle.

enter image description here

It’s super easy to get this graph.

  1. npm install -g webpack-bundle-analyzer
  2. In your Angular app, run ng build --stats-json (don’t use flag --prod). By enabling --stats-json you will get an additional file stats.json
  3. Finally, run webpack-bundle-analyzer ./dist/stats.json and your browser will pop up the page at localhost:8888. Have fun with it.

ref 1: How Did Angular CLI Budgets Save My Day And How They Can Save Yours

ref 2: Optimize Angular bundle size in 4 steps

Is there "\n" equivalent in VBscript?

I think it's vbcrlf.

replace(s, vbcrlf, "<br />")

Inserting created_at data with Laravel

In my case, I wanted to unit test that users weren't able to verify their email addresses after 1 hour had passed, so I didn't want to do any of the other answers since they would also persist when not unit testing, so I ended up just manually updating the row after insert:

// Create new user
$user = factory(User::class)->create();

// Add an email verification token to the 
// email_verification_tokens table
$token = $user->generateNewEmailVerificationToken();

// Get the time 61 minutes ago
$created_at = (new Carbon())->subMinutes(61);

// Do the update
\DB::update(
    'UPDATE email_verification_tokens SET created_at = ?',
    [$created_at]
);

Note: For anything other than unit testing, I would look at the other answers here.

Execute combine multiple Linux commands in one line

cd /my_folder && rm *.jar && svn co path to repo && mvn compile package install

What is the best way to get the minimum or maximum value from an Array of numbers?

Algorithm MaxMin(first, last, max, min)

//This algorithm stores the highest and lowest element

//Values of the global array A in the global variables max and min

//tmax and tmin are temporary global variables

{
if (first==last) //Sub-array contains single element
 {
    max=A[first];
    min=A[first];
 }
 else if(first+1==last) //Sub-array contains two elements
  {
     if(A[first]<A[Last])
      {
      max=a[last];  //Second element is largest
      min=a[first]; //First element is smallest
      }
   else
   {
     max=a[first]; //First element is Largest 
     min=a[last];  //Second element is smallest
   }
}
else
 //sub-array contains more than two elements
{
 //Hence partition the sub-array into smaller sub-array 
 mid=(first+last)/2;
 //Recursively solve the sub-array
 MaxMin(first,mid,max,min);
 MaxMin(mid+1,last,tmax,tmin);
 if(max<tmax)
  {
     max=tmax;
  }
    if(min>tmin)
  {
   min=tmin;
  }
 }
}

Getting unique items from a list

Apart from the Distinct extension method of LINQ, you could use a HashSet<T> object that you initialise with your collection. This is most likely more efficient than the LINQ way, since it uses hash codes (GetHashCode) rather than an IEqualityComparer).

In fact, if it's appropiate for your situation, I would just use a HashSet for storing the items in the first place.

HTML set image on browser tab

It's called a Favicon, have a read.

<link rel="shortcut icon" href="http://www.example.com/myicon.ico"/>

You can use this neat tool to generate cross-browser compatible Favicons.

Android Studio cannot resolve R in imported project?

just clean project and then sync your project with gradle file.

Background color on input type=button :hover state sticks in IE

Try using the type attribute selector to find buttons (maybe this'll fix it too):

input[type=button]
{
  background-color: #E3E1B8; 
}

input[type=button]:hover
{
  background-color: #46000D
}

How to get HTML 5 input type="date" working in Firefox and/or IE 10

The type="date" is not an actual specification at this point. It is a concept Google came up with and is in their whatwg specifications (not official) and is only partially supported by Chrome.

http://caniuse.com/#search=date

I would not rely on this input type at this point. It would be nice to have, but I do not foresee this one actually making it. The #1 reason is it puts too much burden on the browser to determine the best UI for a somewhat complicated input. Think about it from a responsive perspective, how would any of the vendors know what will work best with your UI say at 400 pixels, 800 pixels and 1200 pixels wide?

Disable future dates after today in Jquery Ui Datepicker

//Disable future dates after current date

$("#datepicker").datepicker('setEndDate', new Date());

//Disable past dates after current date

$("#datepicker").datepicker('setEndDate', new Date());

Simple way to measure cell execution time in ipython notebook

I simply added %%time at the beginning of the cell and got the time. You may use the same on Jupyter Spark cluster/ Virtual environment using the same. Just add %%time at the top of the cell and you will get the output. On spark cluster using Jupyter, I added to the top of the cell and I got output like below:-

[1]  %%time
     import pandas as pd
     from pyspark.ml import Pipeline
     from pyspark.ml.classification import LogisticRegression
     import numpy as np
     .... code ....

Output :-

CPU times: user 59.8 s, sys: 4.97 s, total: 1min 4s
Wall time: 1min 18s

What's "tools:context" in Android layout files?

“tools:context” is one of the Design Attributes that can facilitate layout creation in XML in the development framework. This attribute is used to show the development framework what activity class is picked for implementing the layout. Using “tools:context”, Android Studio chooses the necessary theme for the preview automatically.

If you’d like to know more about some other attributes and useful tools for Android app development, take a look at this review: http://cases.azoft.com/4-must-know-tools-for-effective-android-development/

How to add google-play-services.jar project dependency so my project will run and present map

Some of the solutions described here did not work for me. Others did, however they produced warnings on runtime and javadoc was still not linked. After some experimenting, I managed to solve this. The steps are:

  1. Install the Google Play Services as recommended on Android Developers.

  2. Set up your project as recommended on Android Developers.

  3. If you followed 1. and 2., you should see two projects in your workspace: your project and google-play-services_lib project. Copy the docs folder which contains the javadoc from <android-sdk>/extras/google/google_play_services/ to libs folder of your project.

  4. Copy google-play-services.jar from <android-sdk>/extras/google/google_play_services/libproject/google-play-services_lib/libs to 'libs' folder of your project.

  5. In google-play-services_lib project, edit libs/google-play-services.jar.properties . The <path> in doc=<path> should point to the subfolder reference of the folder docs, which you created in step 3.

  6. In Eclipse, do Project > Clean. Done, javadoc is now linked.