Programs & Examples On #Smalltalk

Smalltalk is one of the oldest object-oriented programming languages. It pioneered many aspects modern developers take for granted: Virtual Machines (Smalltalk was an interpreted language) IDEs Pure object approach (no primitives or keywords at all) Closures (called Blocks) An image (i.e. non-file-based language) Advanced debugging techniques (halting programs on-the-fly, inspection, writing or modifying code on-the-fly)

Why are static variables considered evil?

No. Global states are not evil per se. But we have to see your code to see if you used it properly. It is quite possible that a newbie abuses global states; just like he would abuses every language feature.

Global states are absolute necessity. We cannot avoid global states. We cannot avoid reasoning about global states. - If we care to understand our application semantics.

People who try to get rid of global states for the sake of it, inevitably end up with a much more complex system - and the global states are still there, cleverly/idiotically disguised under many layers of indirections; and we still have to reason about global states, after unwrapping all the indirections.

Like the Spring people who lavishly declare global states in xml and think somehow it's superior.

@Jon Skeet if I create a new instance of an object now you have two things to reason about - the state within the object, and the state of the environment hosting the object.

What is the worst programming language you ever worked with?

Cold Fusion

I guess it's good for designers but as a programmer I always felt like one hand was tied behind my back.

How to add multiple font files for the same font?

As of CSS3, the spec has changed, allowing for only a single font-style. A comma-separated list (per CSS2) will be treated as if it were normal and override any earlier (default) entry. This will make fonts defined in this way appear italic permanently.

@font-face {
    font-family: "DejaVu Sans";
    src: url("fonts/DejaVuSans.ttf");
}
@font-face {
    font-family: "DejaVu Sans";
    src: url("fonts/DejaVuSans-Bold.ttf");
    font-weight: bold;
}
@font-face {
    font-family: "DejaVu Sans";
    src: url("fonts/DejaVuSans-Oblique.ttf");
    font-style: italic;
}
@font-face {
    font-family: "DejaVu Sans";
    src: url("fonts/DejaVuSans-BoldOblique.ttf");
    font-weight: bold;
    font-style: italic;
}
@font-face {
    font-family: "DejaVu Sans";
    src: url("fonts/DejaVuSans-Oblique.ttf");
    font-style: oblique;
}
@font-face {
    font-family: "DejaVu Sans";
    src: url("fonts/DejaVuSans-BoldOblique.ttf");
    font-weight: bold;
    font-style: oblique;
}

In most cases, italic will probably be sufficient and oblique rules won't be necessary if you take care to define whichever you will use and stick to it.

What is the purpose of the var keyword and when should I use it (or omit it)?

Without var - global variable.

Strongly recommended to ALWAYS use var statement, because init global variable in local context - is evil. But, if you need this dirty trick, you should write comment at start of page:

/* global: varname1, varname2... */

SQLite select where empty?

You can do this with the following:

int counter = 0;
String sql = "SELECT projectName,Owner " + "FROM Project WHERE Owner= ?";
PreparedStatement prep = conn.prepareStatement(sql);
prep.setString(1, "");
ResultSet rs = prep.executeQuery();
while (rs.next()) {
    counter++;
}
System.out.println(counter);

This will give you the no of rows where the column value is null or blank.

Creating a byte array from a stream

The one above is ok...but you will encounter data corruption when you send stuff over SMTP (if you need to). I've altered to something else that will help to correctly send byte for byte: '

using System;
using System.IO;

        private static byte[] ReadFully(string input)
        {
            FileStream sourceFile = new FileStream(input, FileMode.Open); //Open streamer
            BinaryReader binReader = new BinaryReader(sourceFile);
            byte[] output = new byte[sourceFile.Length]; //create byte array of size file
            for (long i = 0; i < sourceFile.Length; i++)
                output[i] = binReader.ReadByte(); //read until done
            sourceFile.Close(); //dispose streamer
            binReader.Close(); //dispose reader
            return output;
        }'

CentOS: Enabling GD Support in PHP Installation

With CentOS 6.5+ and PHP 5.5:

yum install php55u-gd
service httpd restart

If you get an error like: cannot map zero-fill pages: Cannot allocate memory in Unknown on line 0, it could be because you don't have a swap file. I suggest you take a look at the tutorial mentioned in this answer: https://stackoverflow.com/a/20275282/828366

Tutorial: https://www.digitalocean.com/community/articles/how-to-add-swap-on-centos-6

How to initialize an array's length in JavaScript?

The reason you shouldn't use new Array is demonstrated by this code:

var Array = function () {};

var x = new Array(4);

alert(x.length);  // undefined...

Some other code could mess with the Array variable. I know it's a bit far fetched that anyone would write such code, but still...

Also, as Felix King said, the interface is a little inconsistent, and could lead to some very difficult-to-track-down bugs.

If you wanted an array with length = x, filled with undefined (as new Array(x) would do), you could do this:

var x = 4;
var myArray = [];
myArray[x - 1] = undefined;

alert(myArray.length); // 4

convert strtotime to date time format in php

Here is exp.

$date_search_strtotime = strtotime(date("Y-m-d"));
echo 'Now strtotime date : '.$date_search_strtotime;
echo '<br>';
echo 'Now date from strtotime : '.date('Y-m-d',$date_search_strtotime);

How to create Android Facebook Key Hash?

    private fun generateKeyHash(): String? {try {
    val info =packageManager.getPackageInfo(packageName, PackageManager.GET_SIGNATURES)
    for (signature in info.signatures) {
        val md: MessageDigest = MessageDigest.getInstance("SHA")
        md.update(signature.toByteArray())
        return String(Base64.encode(md.digest(), 0))
    }
} catch (e: Exception) {
    Log.e("exception", e.toString())
}
    return "key hash not found"
}

Concatenation of strings in Lua

As other answers have said, the string concatenation operator in Lua is two dots.

Your simple example would be written like this:

filename = "checkbook"
filename = filename .. ".tmp"

However, there is a caveat to be aware of. Since strings in Lua are immutable, each concatenation creates a new string object and copies the data from the source strings to it. That makes successive concatenations to a single string have very poor performance.

The Lua idiom for this case is something like this:

function listvalues(s)
    local t = { }
    for k,v in ipairs(s) do
        t[#t+1] = tostring(v)
    end
    return table.concat(t,"\n")
end

By collecting the strings to be concatenated in an array t, the standard library routine table.concat can be used to concatenate them all up (along with a separator string between each pair) without unnecessary string copying.

Update: I just noticed that I originally wrote the code snippet above using pairs() instead of ipairs().

As originally written, the function listvalues() would indeed produce every value from the table passed in, but not in a stable or predictable order. On the other hand, it would include values who's keys were not positive integers in the span of 1 to #s. That is what pairs() does: it produces every single (key,value) pair stored in the table.

In most cases where you would be using something like listvaluas() you would be interested in preserving their order. So a call written as listvalues{13, 42, 17, 4} would produce a string containing those value in that order. However, pairs() won't do that, it will itemize them in some order that depends on the underlying implementation of the table data structure. It is known that the order not only depends on the keys, but also on the order in which the keys were inserted and other keys removed.

Of course ipairs() isn't a perfect answer either. It only enumerates those values of the table that form a "sequence". That is, those values who's keys form an unbroken block spanning from 1 to some upper bound, which is (usually) also the value returned by the # operator. (In many cases, the function ipairs() itself is better replaced by a simpler for loop that just counts from 1 to #s. This is the recommended practice in Lua 5.2 and in LuaJIT where the simpler for loop can be more efficiently implemented than the ipairs() iterator.)

If pairs() really is the right approach, then it is usually the case that you want to print both the key and the value. This reduces the concerns about order by making the data self-describing. Of course, since any Lua type (except nil and the floating point NaN) can be used as a key (and NaN can also be stored as a value) finding a string representation is left as an exercise for the student. And don't forget about trees and more complex structures of tables.

Fastest way to count number of occurrences in a Python list

a = ['1', '1', '1', '1', '1', '1', '2', '2', '2', '2', '7', '7', '7', '10', '10']
print a.count("1")

It's probably optimized heavily at the C level.

Edit: I randomly generated a large list.

In [8]: len(a)
Out[8]: 6339347

In [9]: %timeit a.count("1")
10 loops, best of 3: 86.4 ms per loop

Edit edit: This could be done with collections.Counter

a = Counter(your_list)
print a['1']

Using the same list in my last timing example

In [17]: %timeit Counter(a)['1']
1 loops, best of 3: 1.52 s per loop

My timing is simplistic and conditional on many different factors, but it gives you a good clue as to performance.

Here is some profiling

In [24]: profile.run("a.count('1')")
         3 function calls in 0.091 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    0.091    0.091 <string>:1(<module>)
        1    0.091    0.091    0.091    0.091 {method 'count' of 'list' objects}

        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Prof
iler' objects}



In [25]: profile.run("b = Counter(a); b['1']")
         6339356 function calls in 2.143 seconds

   Ordered by: standard name

   ncalls  tottime  percall  cumtime  percall filename:lineno(function)
        1    0.000    0.000    2.143    2.143 <string>:1(<module>)
        2    0.000    0.000    0.000    0.000 _weakrefset.py:68(__contains__)
        1    0.000    0.000    0.000    0.000 abc.py:128(__instancecheck__)
        1    0.000    0.000    2.143    2.143 collections.py:407(__init__)
        1    1.788    1.788    2.143    2.143 collections.py:470(update)
        1    0.000    0.000    0.000    0.000 {getattr}
        1    0.000    0.000    0.000    0.000 {isinstance}
        1    0.000    0.000    0.000    0.000 {method 'disable' of '_lsprof.Prof
iler' objects}
  6339347    0.356    0.000    0.356    0.000 {method 'get' of 'dict' objects}

When to catch java.lang.Error?

ideally we should never catch Error in our Java application as it is an abnormal condition. The application would be in abnormal state and could result in carshing or giving some seriously wrong result.

Substring in excel

kennytm's links are dead and he doesn't provide an example so here's how you do substrings:

=MID(text, start_num, char_num)

Let's say cell A1 is Hello.

=MID(A1, 2, 3) 

Would return

ell

Because it says to start at character 2, e, and to return 3 characters.

How to insert &nbsp; in XSLT

you can also use:

<xsl:value-of select="'&amp;nbsp'"/>

remember the amp after the & or you will get an error message

Change bootstrap navbar collapse breakpoint without using LESS

This worked for me Bootstrap3

@media (min-width: 768px) {
    .navbar-header {
          float: none;
      }
      .navbar-toggle {
          display: block;
      }
      .navbar-collapse {
          border-top: 1px solid transparent;
          box-shadow: inset 0 1px 0 rgba(255, 255, 255, 0.1);
      }
      .navbar-collapse.collapse {
          display: none!important;
      }
      .navbar-collapse.collapse.in {
          display: block!important;
      }
      .navbar-nav {
          float: none!important;
          margin: 7.5px -15px;
      }
      .navbar-nav>li {
          float: none;
      }
      .navbar-nav>li>a {
          padding-top: 10px;
          padding-bottom: 10px;
      }
}

Took a while to figure these two out:

.navbar-collapse.collapse {
   display: none!important;
}
.navbar-collapse.collapse.in {
   display: block!important;
}

Align image to left of text on same line - Twitter Bootstrap3

Use Nesting column

To nest your content with the default grid, add a new .row and set of .col-sm-* columns within an existing .col-sm-* column. Nested rows should include a set of columns that add up to 12 or fewer (it is not required that you use all 12 available columns).

enter image description here

_x000D_
_x000D_
<div class="row">_x000D_
  <div class="col-sm-9">_x000D_
    Level 1: .col-sm-9_x000D_
    <div class="row">_x000D_
      <div class="col-xs-8 col-sm-6">_x000D_
        Level 2: .col-xs-8 .col-sm-6_x000D_
      </div>_x000D_
      <div class="col-xs-4 col-sm-6">_x000D_
        Level 2: .col-xs-4 .col-sm-6_x000D_
      </div>_x000D_
    </div>_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Register 32 bit COM DLL to 64 bit Windows 7

For 32 bit DLLS in Windows 64 bit platforms:

  1. Copy whatever.dll to c:\windows\sysWOW64\
  2. Open a CMD prompt AS ADMINISTRATOR (very important)

In the CMD window:

  1. CD c:\windows\sysWOW64\
  2. regsvr32 whatever.dll

You will then be executing the 32-bit regsvr (c:\windows\sysWOW64\regsvr.exe) on a 32 bit dll

Get single row result with Doctrine NativeQuery

You can use $query->getSingleResult(), which will throw an exception if more than one result are found, or if no result is found. (see the related phpdoc here https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/AbstractQuery.php#L791)

There's also the less famous $query->getOneOrNullResult() which will throw an exception if more than one result are found, and return null if no result is found. (see the related phpdoc here https://github.com/doctrine/doctrine2/blob/master/lib/Doctrine/ORM/AbstractQuery.php#L752)

Android SDK manager won't open

The issue with mine was that I could run SDK manager through double clicking android.bat but not when I double click on the actual SDK manager application. I solved this issue by setting a new environmental variable:

ANDROID_HOME = C:\Development\adt-bundle-windows-x86_64-20130911\sdk\

restarted my pc and now I can double click on the application and run SDK Manager. Hope that helps :)

Initialize 2D array

You can follow what paxdiablo(on Dec '12) suggested for an automated, more versatile approach:

for (int row = 0; row < 3; row ++)
for (int col = 0; col < 3; col++)
    table[row][col] = (char) ('1' + row * 3 + col);

In terms of efficiency, it depends on the scale of your implementation. If it is to simply initialize a 2D array to values 0-9, it would be much easier to just define, declare and initialize within the same statement like this: private char[][] table = {{'1', '2', '3'}, {'4', '5', '6'}, {'7', '8', '9'}};

Or if you're planning to expand the algorithm, the previous code would prove more, efficient.

Converting Integer to String with comma for thousands

The other answers are correct, however double-check your locale before using "%,d":

Locale.setDefault(Locale.US);
int bigNumber = 35634646;
String formattedNumber = String.format("%,d", bigNumber);
System.out.println(formattedNumber);

Locale.setDefault(new Locale("pl", "PL"));
formattedNumber = String.format("%,d", bigNumber);
System.out.println(formattedNumber);

Result:

35,634,646
35 634 646

How can one see content of stack with GDB?

Use:

  • bt - backtrace: show stack functions and args
  • info frame - show stack start/end/args/locals pointers
  • x/100x $sp - show stack memory
(gdb) bt
#0  zzz () at zzz.c:96
#1  0xf7d39cba in yyy (arg=arg@entry=0x0) at yyy.c:542
#2  0xf7d3a4f6 in yyyinit () at yyy.c:590
#3  0x0804ac0c in gnninit () at gnn.c:374
#4  main (argc=1, argv=0xffffd5e4) at gnn.c:389

(gdb) info frame
Stack level 0, frame at 0xffeac770:
 eip = 0x8049047 in main (goo.c:291); saved eip 0xf7f1fea1
 source language c.
 Arglist at 0xffeac768, args: argc=1, argv=0xffffd5e4
 Locals at 0xffeac768, Previous frame's sp is 0xffeac770
 Saved registers:
  ebx at 0xffeac75c, ebp at 0xffeac768, esi at 0xffeac760, edi at 0xffeac764, eip at 0xffeac76c

(gdb) x/10x $sp
0xffeac63c: 0xf7d39cba  0xf7d3c0d8  0xf7d3c21b  0x00000001
0xffeac64c: 0xf78d133f  0xffeac6f4  0xf7a14450  0xffeac678
0xffeac65c: 0x00000000  0xf7d3790e

Convert string to Boolean in javascript

Unfortunately, I didn't find function something like Boolean.ParseBool('true') which returns true as Boolean type like in C#. So workaround is

var setActive = 'true'; 
setActive = setActive == "true";

if(setActive)
// statements
else
// statements.

Playing m3u8 Files with HTML Video Tag

In normally html5 video player will support mp4, WebM, 3gp and OGV format directly.

    <video controls>
      <source src=http://techslides.com/demos/sample-videos/small.webm type=video/webm>
      <source src=http://techslides.com/demos/sample-videos/small.ogv type=video/ogg>
      <source src=http://techslides.com/demos/sample-videos/small.mp4 type=video/mp4>
      <source src=http://techslides.com/demos/sample-videos/small.3gp type=video/3gp>
    </video>

We can add an external HLS js script in web application.

    <!DOCTYPE html>
    <html>
    <head>
    <meta charset=utf-8 />
    <title>Your title</title>
      
    
      <link href="https://unpkg.com/video.js/dist/video-js.css" rel="stylesheet">
      <script src="https://unpkg.com/video.js/dist/video.js"></script>
      <script src="https://unpkg.com/videojs-contrib-hls/dist/videojs-contrib-hls.js"></script>
       
    </head>
    <body>
      <video id="my_video_1" class="video-js vjs-fluid vjs-default-skin" controls preload="auto"
      data-setup='{}'>
        <source src="https://cdn3.wowza.com/1/ejBGVnFIOW9yNlZv/cithRSsv/hls/live/playlist.m3u8" type="application/x-mpegURL">
      </video>
      
    <script>
    var player = videojs('my_video_1');
    player.play();
    </script>
      
    </body>
    </html>

how to get the selected index of a drop down

$("select[name='CCards'] option:selected") should do the trick

See jQuery documentation for more detail: http://api.jquery.com/selected-selector/

UPDATE: if you need the index of the selected option, you need to use the .index() jquery method:

$("select[name='CCards'] option:selected").index()

Copy / Put text on the clipboard with FireFox, Safari and Chrome

I have to say that none of these solutions really work. I have tried the clipboard solution from the accepted answer, and it does not work with Flash Player 10. I have also tried ZeroClipboard, and I was very happy with it for awhile.

I'm currently using it on my own site (http://www.blogtrog.com), but I've been noticing weird bugs with it. The way ZeroClipboard works is that it puts an invisible flash object over the top of an element on your page. I've found that if my element moves (like when the user resizes the window and i have things right aligned), the ZeroClipboard flash object gets out of whack and is no longer covering the object. I suspect it's probably still sitting where it was originally. They have code that's supposed to stop that, or restick it to the element, but it doesn't seem to work well.

So... in the next version of BlogTrog, I guess I'll follow suit with all the other code highlighters I've seen out in the wild and remove my Copy to Clipboard button. :-(

(I noticed that dp.syntaxhiglighter's Copy to Clipboard is broken now also.)

MySQL: How to copy rows, but change a few fields?

If you have loads of columns in your table and don't want to type out each one you can do it using a temporary table, like;

SELECT *
INTO #Temp
FROM Table WHERE Event_ID = "120"
GO

UPDATE #TEMP
SET Column = "Changed"
GO

INSERT INTO Table
SELECT *
FROM #Temp

What is the difference between i++ and ++i?

If you have:

int i = 10;
int x = ++i;

then x will be 11.

But if you have:

int i = 10;
int x = i++;

then x will be 10.

Note as Eric points out, the increment occurs at the same time in both cases, but it's what value is given as the result that differs (thanks Eric!).

Generally, I like to use ++i unless there's a good reason not to. For example, when writing a loop, I like to use:

for (int i = 0; i < 10; ++i) {
}

Or, if I just need to increment a variable, I like to use:

++x;

Normally, one way or the other doesn't have much significance and comes down to coding style, but if you are using the operators inside other assignments (like in my original examples), it's important to be aware of potential side effects.

'Framework not found' in Xcode

Please after adding both framework also open each Bolts and Parse framework and add Parse and Bolts to the project then problem will be solve

Passing arguments to angularjs filters

Actually you can pass a parameter ( http://docs.angularjs.org/api/ng.filter:filter ) and don't need a custom function just for this. If you rewrite your HTML as below it'll work:

<div ng:app>
 <div ng-controller="HelloCntl">
 <ul>
    <li ng-repeat="friend in friends | filter:{name:'!Adam'}">
        <span>{{friend.name}}</span>
        <span>{{friend.phone}}</span>
    </li>
 </ul>
 </div>
</div>

http://jsfiddle.net/ZfGx4/59/

How to create a generic array?

checked :

public Constructor(Class<E> c, int length) {

    elements = (E[]) Array.newInstance(c, length);
}

or unchecked :

public Constructor(int s) {
    elements = new Object[s];
}

How to Delete Session Cookie?

This needs to be done on the server-side, where the cookie was issued.

How to send an object from one Android Activity to another using Intents?

I use Gson with its so powerful and simple api to send objects between activities,

Example

// This is the object to be sent, can be any object
public class AndroidPacket {

    public String CustomerName;

   //constructor
   public AndroidPacket(String cName){
       CustomerName = cName;
   }   
   // other fields ....


    // You can add those functions as LiveTemplate !
    public String toJson() {
        Gson gson = new Gson();
        return gson.toJson(this);
    }

    public static AndroidPacket fromJson(String json) {
        Gson gson = new Gson();
        return gson.fromJson(json, AndroidPacket.class);
    }
}

2 functions you add them to the objects that you want to send

Usage

Send Object From A to B

    // Convert the object to string using Gson
    AndroidPacket androidPacket = new AndroidPacket("Ahmad");
    String objAsJson = androidPacket.toJson();

    Intent intent = new Intent(A.this, B.class);
    intent.putExtra("my_obj", objAsJson);
    startActivity(intent);

Receive In B

@Override
protected void onCreate(Bundle savedInstanceState) {        
    Bundle bundle = getIntent().getExtras();
    String objAsJson = bundle.getString("my_obj");
    AndroidPacket androidPacket = AndroidPacket.fromJson(objAsJson);

    // Here you can use your Object
    Log.d("Gson", androidPacket.CustomerName);
}

I use it almost in every project i do and I have no performance issues.

Callback functions in Java

A method is not (yet) a first-class object in Java; you can't pass a function pointer as a callback. Instead, create an object (which usually implements an interface) that contains the method you need and pass that.

Proposals for closures in Java—which would provide the behavior you are looking for—have been made, but none will be included in the upcoming Java 7 release.

Creating Accordion Table with Bootstrap

This seems to be already asked before:

This might help:

Twitter Bootstrap Use collapse.js on table cells [Almost Done]

UPDATE:

Your fiddle wasn't loading jQuery, so anything worked.

<table class="table table-hover">
<thead>
  <tr>
    <th></th>
    <th></th>
    <th></th>
  </tr>
</thead>

<tbody>
    <tr data-toggle="collapse" data-target="#accordion" class="clickable">
        <td>Some Stuff</td>
        <td>Some more stuff</td>
        <td>And some more</td>
    </tr>
    <tr>
        <td colspan="3">
            <div id="accordion" class="collapse">Hidden by default</div>
        </td>
    </tr>
</tbody>
</table>

Try this one: http://jsfiddle.net/Nb7wy/2/

I also added colspan='2' to the details row. But it's essentially your fiddle with jQuery loaded (in frameworks in the left column)

Parse error: syntax error, unexpected [

Are you using php 5.4 on your local? the render line is using the new way of initializing arrays. Try replacing ["title" => "Welcome "] with array("title" => "Welcome ")

How to create a circle icon button in Flutter?

You can use InkWell to do that:

A rectangular area of a Material that responds to touch.

Below example demonstrate how to use InkWell. Notice: you don't need StatefulWidget to do that. I used it to change the state of the count.

Example:

import 'package:flutter/material.dart';

class SettingPage extends StatefulWidget {
  @override
  _SettingPageState createState() => new _SettingPageState();
}

class _SettingPageState extends State<SettingPage> {
  int _count = 0;
  @override
  Widget build(BuildContext context) {
    return new Scaffold(
      body: new Center(
        child: new InkWell(// this is the one you are looking for..........
        onTap: () => setState(() => _count++),
        child: new Container(
          //width: 50.0,
          //height: 50.0,
          padding: const EdgeInsets.all(20.0),//I used some padding without fixed width and height
          decoration: new BoxDecoration(
            shape: BoxShape.circle,// You can use like this way or like the below line
            //borderRadius: new BorderRadius.circular(30.0),
            color: Colors.green,
          ),
          child: new Text(_count.toString(), style: new TextStyle(color: Colors.white, fontSize: 50.0)),// You can add a Icon instead of text also, like below.
          //child: new Icon(Icons.arrow_forward, size: 50.0, color: Colors.black38)),
        ),//............
      ),
      ),
    );
  }
}

If you want to get benefit of splashColor, highlightColor, wrap InkWell widget using a Material widget with material type circle. And then remove decoration in Container widget.

Outcome:

enter image description here

How do I merge two dictionaries in a single expression (taking union of dictionaries)?

There will be a new option when Python 3.8 releases (scheduled for 20 October, 2019), thanks to PEP 572: Assignment Expressions. The new assignment expression operator := allows you to assign the result of the copy and still use it to call update, leaving the combined code a single expression, rather than two statements, changing:

newdict = dict1.copy()
newdict.update(dict2)

to:

(newdict := dict1.copy()).update(dict2)

while behaving identically in every way. If you must also return the resulting dict (you asked for an expression returning the dict; the above creates and assigns to newdict, but doesn't return it, so you couldn't use it to pass an argument to a function as is, a la myfunc((newdict := dict1.copy()).update(dict2))), then just add or newdict to the end (since update returns None, which is falsy, it will then evaluate and return newdict as the result of the expression):

(newdict := dict1.copy()).update(dict2) or newdict

Important caveat: In general, I'd discourage this approach in favor of:

newdict = {**dict1, **dict2}

The unpacking approach is clearer (to anyone who knows about generalized unpacking in the first place, which you should), doesn't require a name for the result at all (so it's much more concise when constructing a temporary that is immediately passed to a function or included in a list/tuple literal or the like), and is almost certainly faster as well, being (on CPython) roughly equivalent to:

newdict = {}
newdict.update(dict1)
newdict.update(dict2)

but done at the C layer, using the concrete dict API, so no dynamic method lookup/binding or function call dispatch overhead is involved (where (newdict := dict1.copy()).update(dict2) is unavoidably identical to the original two-liner in behavior, performing the work in discrete steps, with dynamic lookup/binding/invocation of methods.

It's also more extensible, as merging three dicts is obvious:

 newdict = {**dict1, **dict2, **dict3}

where using assignment expressions won't scale like that; the closest you could get would be:

 (newdict := dict1.copy()).update(dict2), newdict.update(dict3)

or without the temporary tuple of Nones, but with truthiness testing of each None result:

 (newdict := dict1.copy()).update(dict2) or newdict.update(dict3)

either of which is obviously much uglier, and includes further inefficiencies (either a wasted temporary tuple of Nones for comma separation, or pointless truthiness testing of each update's None return for or separation).

The only real advantage to the assignment expression approach occurs if:

  1. You have generic code that needs handle both sets and dicts (both of them support copy and update, so the code works roughly as you'd expect it to)
  2. You expect to receive arbitrary dict-like objects, not just dict itself, and must preserve the type and semantics of the left hand side (rather than ending up with a plain dict). While myspecialdict({**speciala, **specialb}) might work, it would involve an extra temporary dict, and if myspecialdict has features plain dict can't preserve (e.g. regular dicts now preserve order based on the first appearance of a key, and value based on the last appearance of a key; you might want one that preserves order based on the last appearance of a key so updating a value also moves it to the end), then the semantics would be wrong. Since the assignment expression version uses the named methods (which are presumably overloaded to behave appropriately), it never creates a dict at all (unless dict1 was already a dict), preserving the original type (and original type's semantics), all while avoiding any temporaries.

How can I make a CSS glass/blur effect work for an overlay?

Here's a solution that works with fixed backgrounds, if you have a fixed background and you have some overlayed elements and you need blured backgrounds for them, this solution works:

Image we have this simple HTML:

<body> <!-- or any wrapper -->
   <div class="content">Some Texts</div>
</body>

A fixed background for <body> or the wrapper element:

body {
  background-image: url(http://placeimg.com/640/360/any);
  background-size: cover;
  background-repeat: no-repeat;
  background-attachment: fixed;
}

And here for example we have a overlayed element with a white transparent background:

.content {
  background-color: rgba(255, 255, 255, 0.3);
  position: relative;
}

Now we need to use the exact same background image of our wrapper for our overlay elements too, i use it as a :before psuedo-class:

.content:before {
  content: '';
  position: absolute;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  z-index: -1;
  filter: blur(5px);
  background-image: url(http://placeimg.com/640/360/any);
  background-size: cover;
  background-repeat: no-repeat;
  background-attachment: fixed;
}

Since the fixed background works in a same way in both wrapper and overlayed elements, we have the background in exactly same scroll position of the overlayed element and we can simply blur it. Here's a working fiddle, tested in Firefox, Chrome, Opera and Edge: https://jsfiddle.net/0vL2rc4d/

NOTE: In firefox there's a bug that makes screen flicker when scrolling and there are fixed blurred backgrounds. if there's any fix, let me know

Should functions return null or an empty object?

To put what others have said in a pithier manner...

Exceptions are for Exceptional circumstances

If this method is pure data access layer, I would say that given some parameter that gets included in a select statement, it would expect that I may not find any rows from which to build an object, and therefore returning null would be acceptable as this is data access logic.

On the other hand, if I expected my parameter to reflect a primary key and I should only get one row back, if I got more than one back I would throw an exception. 0 is ok to return null, 2 is not.

Now, if I had some login code that checked against an LDAP provider then checked against a DB to get more details and I expected those should be in sync at all times, I might toss the exception then. As others said, it's business rules.

Now I'll say that is a general rule. There are times where you may want to break that. However, my experience and experiments with C# (lots of that) and Java(a bit of that) has taught me that it is much more expensive performance wise to deal with exceptions than to handle predictable issues via conditional logic. I'm talking to the tune of 2 or 3 orders of magnitude more expensive in some cases. So, if it's possible your code could end up in a loop, then I would advise returning null and testing for it.

How to reload page the page with pagination in Angular 2?

This should technically be achievable using window.location.reload():

HTML:

<button (click)="refresh()">Refresh</button>

TS:

refresh(): void {
    window.location.reload();
}

Update:

Here is a basic StackBlitz example showing the refresh in action. Notice the URL on "/hello" path is retained when window.location.reload() is executed.

How to recover Git objects damaged by hard disk failure?

Banengusk was putting me on the right track. For further reference, I want to post the steps I took to fix my repository corruption. I was lucky enough to find all needed objects either in older packs or in repository backups.

# Unpack last non-corrupted pack
$ mv .git/objects/pack .git/objects/pack.old
$ git unpack-objects -r < .git/objects/pack.old/pack-012066c998b2d171913aeb5bf0719fd4655fa7d0.pack
$ git log
fatal: bad object HEAD

$ cat .git/HEAD 
ref: refs/heads/master

$ ls .git/refs/heads/

$ cat .git/packed-refs 
# pack-refs with: peeled 
aa268a069add6d71e162c4e2455c1b690079c8c1 refs/heads/master

$ git fsck --full 
error: HEAD: invalid sha1 pointer aa268a069add6d71e162c4e2455c1b690079c8c1
error: refs/heads/master does not point to a valid object!
missing blob 75405ef0e6f66e48c1ff836786ff110efa33a919
missing blob 27c4611ffbc3c32712a395910a96052a3de67c9b
dangling tree 30473f109d87f4bcde612a2b9a204c3e322cb0dc

# Copy HEAD object from backup of repository
$ cp repobackup/.git/objects/aa/268a069add6d71e162c4e2455c1b690079c8c1 .git/objects/aa
# Now copy all missing objects from backup of repository and run "git fsck --full" afterwards
# Repeat until git fsck --full only reports dangling objects

# Now garbage collect repo
$ git gc
warning: reflog of 'HEAD' references pruned commits
warning: reflog of 'refs/heads/master' references pruned commits
Counting objects: 3992, done.
Delta compression using 2 threads.
fatal: object bf1c4953c0ea4a045bf0975a916b53d247e7ca94 inconsistent object length (6093 vs 415232)
error: failed to run repack

# Check reflogs...
$ git reflog

# ...then clean
$ git reflog expire --expire=0 --all

# Now garbage collect again
$ git gc       
Counting objects: 3992, done.
Delta compression using 2 threads.
Compressing objects: 100% (3970/3970), done.
Writing objects: 100% (3992/3992), done.
Total 3992 (delta 2060), reused 0 (delta 0)
Removing duplicate objects: 100% (256/256), done.
# Done!

No == operator found while comparing structs in C++

C++20 introduced default comparisons, aka the "spaceship" operator<=>, which allows you to request compiler-generated </<=/==/!=/>=/ and/or > operators with the obvious/naive(?) implementation...

auto operator<=>(const MyClass&) const = default;

...but you can customise that for more complicated situations (discussed below). See here for the language proposal, which contains justifications and discussion. This answer remains relevant for C++17 and earlier, and for insight in to when you should customise the implementation of operator<=>....

It may seem a bit unhelpful of C++ not to have already Standardised this earlier, but often structs/classes have some data members to exclude from comparison (e.g. counters, cached results, container capacity, last operation success/error code, cursors), as well as decisions to make about myriad things including but not limited to:

  • which fields to compare first, e.g. comparing a particular int member might eliminate 99% of unequal objects very quickly, while a map<string,string> member might often have identical entries and be relatively expensive to compare - if the values are loaded at runtime, the programmer may have insights the compiler can't possibly
  • in comparing strings: case sensitivity, equivalence of whitespace and separators, escaping conventions...
  • precision when comparing floats/doubles
  • whether NaN floating point values should be considered equal
  • comparing pointers or pointed-to-data (and if the latter, how to know how whether the pointers are to arrays and of how many objects/bytes needing comparison)
  • whether order matters when comparing unsorted containers (e.g. vector, list), and if so whether it's ok to sort them in-place before comparing vs. using extra memory to sort temporaries each time a comparison is done
  • how many array elements currently hold valid values that should be compared (is there a size somewhere or a sentinel?)
  • which member of a union to compare
  • normalisation: for example, date types may allow out-of-range day-of-month or month-of-year, or a rational/fraction object may have 6/8ths while another has 3/4ers, which for performance reasons they correct lazily with a separate normalisation step; you may have to decide whether to trigger a normalisation before comparison
  • what to do when weak pointers aren't valid
  • how to handle members and bases that don't implement operator== themselves (but might have compare() or operator< or str() or getters...)
  • what locks must be taken while reading/comparing data that other threads may want to update

So, it's kind of nice to have an error until you've explicitly thought about what comparison should mean for your specific structure, rather than letting it compile but not give you a meaningful result at run-time.

All that said, it'd be good if C++ let you say bool operator==() const = default; when you'd decided a "naive" member-by-member == test was ok. Same for !=. Given multiple members/bases, "default" <, <=, >, and >= implementations seem hopeless though - cascading on the basis of order of declaration's possible but very unlikely to be what's wanted, given conflicting imperatives for member ordering (bases being necessarily before members, grouping by accessibility, construction/destruction before dependent use). To be more widely useful, C++ would need a new data member/base annotation system to guide choices - that would be a great thing to have in the Standard though, ideally coupled with AST-based user-defined code generation... I expect it'll happen one day.

Typical implementation of equality operators

A plausible implementation

It's likely that a reasonable and efficient implementation would be:

inline bool operator==(const MyStruct1& lhs, const MyStruct1& rhs)
{
    return lhs.my_struct2 == rhs.my_struct2 &&
           lhs.an_int     == rhs.an_int;
}

Note that this needs an operator== for MyStruct2 too.

Implications of this implementation, and alternatives, are discussed under the heading Discussion of specifics of your MyStruct1 below.

A consistent approach to ==, <, > <= etc

It's easy to leverage std::tuple's comparison operators to compare your own class instances - just use std::tie to create tuples of references to fields in the desired order of comparison. Generalising my example from here:

inline bool operator==(const MyStruct1& lhs, const MyStruct1& rhs)
{
    return std::tie(lhs.my_struct2, lhs.an_int) ==
           std::tie(rhs.my_struct2, rhs.an_int);
}

inline bool operator<(const MyStruct1& lhs, const MyStruct1& rhs)
{
    return std::tie(lhs.my_struct2, lhs.an_int) <
           std::tie(rhs.my_struct2, rhs.an_int);
}

// ...etc...

When you "own" (i.e. can edit, a factor with corporate and 3rd party libs) the class you want to compare, and especially with C++14's preparedness to deduce function return type from the return statement, it's often nicer to add a "tie" member function to the class you want to be able to compare:

auto tie() const { return std::tie(my_struct1, an_int); }

Then the comparisons above simplify to:

inline bool operator==(const MyStruct1& lhs, const MyStruct1& rhs)
{
    return lhs.tie() == rhs.tie();
}

If you want a fuller set of comparison operators, I suggest boost operators (search for less_than_comparable). If it's unsuitable for some reason, you may or may not like the idea of support macros (online):

#define TIED_OP(STRUCT, OP, GET_FIELDS) \
    inline bool operator OP(const STRUCT& lhs, const STRUCT& rhs) \
    { \
        return std::tie(GET_FIELDS(lhs)) OP std::tie(GET_FIELDS(rhs)); \
    }

#define TIED_COMPARISONS(STRUCT, GET_FIELDS) \
    TIED_OP(STRUCT, ==, GET_FIELDS) \
    TIED_OP(STRUCT, !=, GET_FIELDS) \
    TIED_OP(STRUCT, <, GET_FIELDS) \
    TIED_OP(STRUCT, <=, GET_FIELDS) \
    TIED_OP(STRUCT, >=, GET_FIELDS) \
    TIED_OP(STRUCT, >, GET_FIELDS)

...that can then be used a la...

#define MY_STRUCT_FIELDS(X) X.my_struct2, X.an_int
TIED_COMPARISONS(MyStruct1, MY_STRUCT_FIELDS)

(C++14 member-tie version here)

Discussion of specifics of your MyStruct1

There are implications to the choice to provide a free-standing versus member operator==()...

Freestanding implementation

You have an interesting decision to make. As your class can be implicitly constructed from a MyStruct2, a free-standing / non-member bool operator==(const MyStruct2& lhs, const MyStruct2& rhs) function would support...

my_MyStruct2 == my_MyStruct1

...by first creating a temporary MyStruct1 from my_myStruct2, then doing the comparison. This would definitely leave MyStruct1::an_int set to the constructor's default parameter value of -1. Depending on whether you include an_int comparison in the implementation of your operator==, a MyStruct1 might or might not compare equal to a MyStruct2 that itself compares equal to the MyStruct1's my_struct_2 member! Further, creating a temporary MyStruct1 can be a very inefficient operation, as it involves copying the existing my_struct2 member to a temporary, only to throw it away after the comparison. (Of course, you could prevent this implicit construction of MyStruct1s for comparison by making that constructor explicit or removing the default value for an_int.)

Member implementation

If you want to avoid implicit construction of a MyStruct1 from a MyStruct2, make the comparison operator a member function:

struct MyStruct1
{
    ...
    bool operator==(const MyStruct1& rhs) const
    {
        return tie() == rhs.tie(); // or another approach as above
    }
};

Note the const keyword - only needed for the member implementation - advises the compiler that comparing objects doesn't modify them, so can be allowed on const objects.

Comparing the visible representations

Sometimes the easiest way to get the kind of comparison you want can be...

    return lhs.to_string() == rhs.to_string();

...which is often very expensive too - those strings painfully created just to be thrown away! For types with floating point values, comparing visible representations means the number of displayed digits determines the tolerance within which nearly-equal values are treated as equal during comparison.

How to delete and update a record in Hive

The CLI told you where is your mistake : delete WHAT? from student ...

Delete : How to delete/truncate tables from Hadoop-Hive?

Update : Update , SET option in Hive

Stop form from submitting , Using Jquery

use this too :

if(e.preventDefault) 
   e.preventDefault(); 
else 
   e.returnValue = false;

Becoz e.preventDefault() is not supported in IE( some versions ). In IE it is e.returnValue = false

How to to send mail using gmail in Laravel?

if you still could be able to send mail after setting all configs right and get forbidden or timeout errors you could set the allow less secure apps to access your account in gmail. you can follow how to here

Convert boolean to int in Java

boolean b = ....; 
int i = -("false".indexOf("" + b));

How to run two jQuery animations simultaneously?

That would run simultaneously yes. what if you wanted to run two animations on the same element simultaneously ?

$(function () {
    $('#first').animate({ width: '200px' }, 200);
    $('#first').animate({ marginTop: '50px' }, 200);
});

This ends up queuing the animations. to get to run them simultaneously you would use only one line.

$(function () {
    $('#first').animate({ width: '200px', marginTop:'50px' }, 200);
});

Is there any other way to run two different animation on the same element simultaneously ?

How to make g++ search for header files in a specific directory?

Headers included with #include <> will be searched in all default directories , but you can also add your own location in the search path with -I command line arg.

I saw your edit you could install your headers in default locations usually

 /usr/local/include
 libdir/gcc/target/version/include
 /usr/target/include
 /usr/include

Confirm with compiler docs though.

How do I pass data to Angular routed components?

use a shared service to store data with a custom index. then send that custom index with queryParam. this approach is more flexible.

// component-a : typeScript :
constructor( private DataCollector: DataCollectorService ) {}

ngOnInit() {
    this.DataCollector['someDataIndex'] = data;
}

// component-a : html :
<a routerLink="/target-page" 
   [queryParams]="{index: 'someDataIndex'}"></a>

.

// component-b : typeScript :
public data;

constructor( private DataCollector: DataCollectorService ) {}

ngOnInit() {
    this.route.queryParams.subscribe(
        (queryParams: Params) => {
            this.data = this.DataCollector[queryParams['index']];
        }
    );
}

How to load external webpage in WebView

Add Internet permission in AndroidManifest.xml

<uses-permission android:name="android.permission.INTERNET" />

In your Layout:

<?xml version="1.0" encoding="utf-8"?>
<WebView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/webView"
 />

In your Activity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    try {
        progressDialog = new ProgressDialog(this);
        url_Api = "https://docs.microsoft.com/en-us/learn";

        webView = this.findViewById(R.id.webView);

            progressDialog.setMessage(getString(R.string.connection_Wait));
            progressDialog.setIndeterminate(false);
            progressDialog.setCancelable(true);
            progressDialog.show();

            LoadUrlWebView( url_Api );
    }catch (Exception e){
        Log.w(TAG, "onCreate", e);
    }
}

private void LoadUrlWebView( String url_api ) {
    try {
        webView.setWebViewClient(new WebViewClient());
        webView.setWebChromeClient(new MyWebChromeClient( url_api ));
        webView.getSettings().setJavaScriptEnabled(true);
        webView.getSettings().setSupportZoom(true);
        webView.getSettings().setAllowContentAccess(true);
        webView.getSettings().setBuiltInZoomControls(true);
        webView.getSettings().setDisplayZoomControls(false);

        webView.loadUrl(url_api);
    } catch (Exception e) {
        Log.w(TAG, "setUpNavigationView", e);
    }
}

private class MyWebChromeClient extends WebChromeClient {
    private String urlAccount;

    public MyWebChromeClient( String urlAccount ) {
        this.urlAccount = urlAccount;
    }

    @Override
    public void onProgressChanged(WebView view, int newProgress) {
        try {
            //Tools.LogCat(context, "INSIDE MyWebChromeClient | onProgressChanged / newProgress1:" + newProgress);
            progressDialog.setMessage(newProgress + "% " + getString(R.string.connection_Wait));
            if (newProgress < 100 && !progressDialog.isShowing()) {
                if (progressDialog != null)
                    progressDialog.show();
            }
            if (newProgress == 100) {
                if (progressDialog != null)
                    progressDialog.dismiss();
            }
        }catch (Exception e){
            Log.w( "onProgressChanged", e);
        }
    }

    @Override
    public void onReceivedTitle(WebView view, String title) {
        super.onReceivedTitle(view, title);

        sharedPreferences = new Shared_Preferences( context );
        sharedPreferences.setPageWebView(view.getUrl());
    }

}

How do I execute a stored procedure in a SQL Agent job?

You just need to add this line to the window there:

exec (your stored proc name) (and possibly add parameters)

What is your stored proc called, and what parameters does it expect?

How to display and hide a div with CSS?

you can use any of the following five ways to hide element, depends upon your requirements.

Opacity

.hide {
  opacity: 0;
}

Visibility

.hide {
   visibility: hidden;
}

Display

.hide {
   display: none;
}

Position

.hide {
   position: absolute;
   top: -9999px;
   left: -9999px;
}

clip-path

.hide {
  clip-path: polygon(0px 0px,0px 0px,0px 0px,0px 0px);
}

To show use any of the following: opacity: 1; visibility: visible; display: block;

Source : https://www.sitepoint.com/five-ways-to-hide-elements-in-css/

html5: display video inside canvas

var canvas = document.getElementById('canvas');
var ctx    = canvas.getContext('2d');
var video  = document.getElementById('video');

video.addEventListener('play', function () {
    var $this = this; //cache
    (function loop() {
        if (!$this.paused && !$this.ended) {
            ctx.drawImage($this, 0, 0);
            setTimeout(loop, 1000 / 30); // drawing at 30fps
        }
    })();
}, 0);

I guess the above code is self Explanatory, If not drop a comment below, I will try to explain the above few lines of code

Edit :
here's an online example, just for you :)
Demo

_x000D_
_x000D_
var canvas = document.getElementById('canvas');_x000D_
var ctx = canvas.getContext('2d');_x000D_
var video = document.getElementById('video');_x000D_
_x000D_
// set canvas size = video size when known_x000D_
video.addEventListener('loadedmetadata', function() {_x000D_
  canvas.width = video.videoWidth;_x000D_
  canvas.height = video.videoHeight;_x000D_
});_x000D_
_x000D_
video.addEventListener('play', function() {_x000D_
  var $this = this; //cache_x000D_
  (function loop() {_x000D_
    if (!$this.paused && !$this.ended) {_x000D_
      ctx.drawImage($this, 0, 0);_x000D_
      setTimeout(loop, 1000 / 30); // drawing at 30fps_x000D_
    }_x000D_
  })();_x000D_
}, 0);
_x000D_
<div id="theater">_x000D_
  <video id="video" src="http://upload.wikimedia.org/wikipedia/commons/7/79/Big_Buck_Bunny_small.ogv" controls="false"></video>_x000D_
  <canvas id="canvas"></canvas>_x000D_
  <label>_x000D_
    <br />Try to play me :)</label>_x000D_
  <br />_x000D_
</div>
_x000D_
_x000D_
_x000D_

Set the text in a span

Use .text() instead, and change your selector:

$(".ui-datepicker-prev .ui-icon.ui-icon-circle-triangle-w").text('<<');

-- VIEW DEMO --

How to remove duplicate values from a multi-dimensional array in PHP

As people are saying array_unique() is very slow, here is a snippet I use for one level multidimensional array.

$serialized_array = array_map("serialize", $input);

foreach ($serialized_array as $key => $val) {
     $result[$val] = true;
}

$output = array_map("unserialize", (array_keys($result)));

Reference first user contributed note of array_unique() function page in php.net

How to close form

new WindowSettings();

You just closed a brand new instance of the form that wasn't visible in the first place.

You need to close the original instance of the form by accepting it as a constructor parameter and storing it in a field.

Form inline inside a form horizontal in twitter bootstrap?

Since bootstrap 4 use div class="form-row" in combination with div class="form-group col-X". X is the width you need. You will get nice inline columns. See fiddle.

<form class="form-horizontal" name="FORMNAME" method="post" action="ACTION" enctype="multipart/form-data">
    <div class="form-group">
        <label class="control-label col-sm-2" for="naam">Naam:&nbsp;*</label>
        <div class="col-sm-10">
            <input type="text" require class="form-control" id="naam" name="Naam" placeholder="Uw naam" value="{--NAAM--}" >
            <div id="naamx" class="form-error form-hidden">Wat is uw naam?</div>
        </div>
    </div>

    <div class="form-row">

        <div class="form-group col-5">
            <label class="control-label col-sm-4" for="telefoon">Telefoon:&nbsp;*</label>
            <div class="col-sm-12">
                <input type="tel" require class="form-control" id="telefoon" name="Telefoon" placeholder="Telefoon nummer" value="{--TELEFOON--}" >
                <div id="telefoonx" class="form-error form-hidden">Wat is uw telefoonnummer?</div>
            </div>
        </div>

        <div class="form-group col-5">
            <label class="control-label col-sm-4" for="email">E-mail: </label>
            <div class="col-sm-12">
                <input type="email" require class="form-control" id="email" name="E-mail" placeholder="E-mail adres" value="{--E-MAIL--}" >
                <div id="emailx" class="form-error form-hidden">Wat is uw e-mail adres?</div>
                    </div>
                </div>

        </div>

    <div class="form-group">
        <label class="control-label col-sm-2" for="titel">Titel:&nbsp;*</label>
        <div class="col-sm-10">
            <input type="text" require class="form-control" id="titel" name="Titel" placeholder="Titel van uw vraag of aanbod" value="{--TITEL--}" >
            <div id="titelx" class="form-error form-hidden">Wat is de titel van uw vraag of aanbod?</div>
        </div>
    </div>
<from>

Define: What is a HashSet?

From application perspective, if one needs only to avoid duplicates then HashSet is what you are looking for since it's Lookup, Insert and Remove complexities are O(1) - constant. What this means it does not matter how many elements HashSet has it will take same amount of time to check if there's such element or not, plus since you are inserting elements at O(1) too it makes it perfect for this sort of thing.

Java: String - add character n-times

public String appendNewStringToExisting(String exisitingString, String newString, int number) {
    StringBuilder builder = new StringBuilder(exisitingString);
    for(int iDx = 0; iDx < number; iDx++){
        builder.append(newString);
    }
    return builder.toString();
}

How do I make the text box bigger in HTML/CSS?

This will do it:

#signin input {
 background-color:#FFF;
 min-height:200px;

}

Configuring angularjs with eclipse IDE

Hi Guys if u are using angular plugin in eclipse that time is plugin is limited periods after that if u want to used this plugin then u pay it so i suggest to you used webstrome and visual code ide that are very easy and comfort to used so take care if u start and developed a angular app using eclipse

PHP file_get_contents() and setting request headers

Here is what worked for me (Dominic was just one line short).

$url = "";

$options = array(
  'http'=>array(
    'method'=>"GET",
    'header'=>"Accept-language: en\r\n" .
              "Cookie: foo=bar\r\n" .  // check function.stream-context-create on php.net
              "User-Agent: Mozilla/5.0 (iPad; U; CPU OS 3_2 like Mac OS X; en-us) AppleWebKit/531.21.10 (KHTML, like Gecko) Version/4.0.4 Mobile/7B334b Safari/531.21.102011-10-16 20:23:10\r\n" // i.e. An iPad 
  )
);

$context = stream_context_create($options);
$file = file_get_contents($url, false, $context);

Omitting the second expression when using the if-else shorthand

Technically, putting null or 0, or just some random value there works (since you are not using the return value). However, why are you using this construct instead of the if construct? It is less obvious what you are trying to do when you write code this way, as you may confuse people with the no-op (null in your case).

How to move up a directory with Terminal in OS X

For Mac Terminal

cd ..   # one up
cd ../  # two up
cd      # home directory 
cd /    # root directory
cd "yaya-13" # use quotes if the file name contains punctuation or spaces

Letter Count on a string

A simple way is as follows:

def count_letters(word, char):
    return word.count(char)

Or, there's another way count each element directly:

from collections import Counter
Counter('banana')

Of course, you can specify one element, e.g.

Counter('banana')['a']

Selenium C# WebDriver: Wait until element is present

You can find out something like this in C#.

This is what I used in JUnit - Selenium

WebDriverWait wait = new WebDriverWait(driver, 100);
WebElement element = wait.until(ExpectedConditions.elementToBeClickable(By.id("submit")));

Do import related packages.

Efficiently test if a port is open on Linux?

Based on Spencer Rathbun's answer, using bash:

true &>/dev/null </dev/tcp/127.0.0.1/$PORT && echo open || echo closed

JQuery $.each() JSON array object iteration

Assign the second variable for the $.each function() as well, makes it lot easier as it'll provide you the data (so you won't have to work with the indicies).

$.each(json, function(arrayID,group) {
            console.log('<a href="'+group.GROUP_ID+'">');
    $.each(group.EVENTS, function(eventID,eventData) {
            console.log('<p>'+eventData.SHORT_DESC+'</p>');
     });
});

Should print out everything you were trying in your question.

http://jsfiddle.net/niklasvh/hZsQS/

edit renamed the variables to make it bit easier to understand what is what.

position fixed is not working

We'll never convince people to leave IE6 if we keep striving to deliver quality websites to those users.

Only IE7+ understood "position: fixed".

https://developer.mozilla.org/en-US/docs/Web/CSS/position

So you're out of luck for IE6. To get the footer semi-sticky try this:

.main {
  min-height: 100%;
  margin-bottom: -60px;
}
.footer {
  height: 60px;
}

You could also use an iFrame maybe.

This will keep the footer from 'lifting off' from the bottom of the page. If you have more than one page of content then it will push down out of site.

On a philosophical note, I'd rather point IE6 users to http://browsehappy.com/ and spend the time I save hacking for IE6 on something else.

How to sort Map values by key in Java?

This code can sort a key-value map in both orders i.e. ascending and descending.

<K, V extends Comparable<V>> Map<K, V> sortByValues
     (final Map<K, V> map, int ascending)
{
     Comparator<K> valueComparator =  new Comparator<K>() {         
        private int ascending;
        public int compare(K k1, K k2) {
            int compare = map.get(k2).compareTo(map.get(k1));
            if (compare == 0) return 1;
            else return ascending*compare;
        }
        public Comparator<K> setParam(int ascending)
        {
            this.ascending = ascending;
            return this;
        }
    }.setParam(ascending);

    Map<K, V> sortedByValues = new TreeMap<K, V>(valueComparator);
    sortedByValues.putAll(map);
    return sortedByValues;
}

As an example:

Map<Integer,Double> recommWarrVals = new HashMap<Integer,Double>();
recommWarrVals = sortByValues(recommWarrVals, 1);  // Ascending order
recommWarrVals = sortByValues(recommWarrVals,-1);  // Descending order

What is the color code for transparency in CSS?

There are now 8-digit hex codes in CSS4 (CSS Color Module Level 4), the last two digit (or in case of the abbreviation, the last of the 4 digits) represents alpha, 00 meaning fully transparent and ff meaning fully opaque, 7f representing an opacity of 0.5 etc.

The format is '#rrggbbaa' or the shorthand, '#rgba'.

Support is lacking for MS browsers, they might be less cooperative or just slower than the other developers, either or both of which actually sealed IE's fate: https://caniuse.com/#feat=css-rrggbbaa

What REALLY happens when you don't free after malloc?

It depends on the scope of the project that you're working on. In the context of your question, and I mean just your question, then it doesn't matter.

For a further explanation (optional), some scenarios I have noticed from this whole discussion is as follow:

(1) - If you're working in an embedded environment where you cannot rely on the main OS' to reclaim the memory for you, then you should free them since memory leaks can really crash the program if done unnoticed.

(2) - If you're working on a personal project where you won't disclose it to anyone else, then you can skip it (assuming you're using it on the main OS') or include it for "best practices" sake.

(3) - If you're working on a project and plan to have it open source, then you need to do more research into your audience and figure out if freeing the memory would be the better choice.

(4) - If you have a large library and your audience consisted of only the main OS', then you don't need to free it as their OS' will help them to do so. In the meantime, by not freeing, your libraries/program may help to make the overall performance snappier since the program does not have to close every data structure, prolonging the shutdown time (imagine a very slow excruciating wait to shut down your computer before leaving the house...)

I can go on and on specifying which course to take, but it ultimately depends on what you want to achieve with your program. Freeing memory is considered good practice in some cases and not so much in some so it ultimately depends on the specific situation you're in and asking the right questions at the right time. Good luck!

What's the difference between "&nbsp;" and " "?

The entity &nbsp; produces a non-breaking space, which is used when you don't want an automatic line break at that position. The regular space has the character code 32, while the non-breaking space has the character code 160.

For example when you display numbers with space as thousands separator: 1 234 567, then you use non-breaking spaces so that the number can't be split on separate lines. If you display currency and there is a space between the amount and the currency: 42 SEK, then you use a non-breaking space so that you don't get the amount on one line and the currency on the next.

What __init__ and self do in Python?

Basically, you need to use the 'self' keyword when using a variable in multiple functions within the same class. As for init, it's used to setup default values incase no other functions from within that class are called.

std::wstring VS std::string

I frequently use std::string to hold utf-8 characters without any problems at all. I heartily recommend doing this when interfacing with API's which use utf-8 as the native string type as well.

For example, I use utf-8 when interfacing my code with the Tcl interpreter.

The major caveat is the length of the std::string, is no longer the number of characters in the string.

Bootstrap Modal Backdrop Remaining

After perform action just trigger the close button.

Example

$('.close').click();

'router-outlet' is not a known element

This issue was with me also. Simple trick for it.

 @NgModule({
  imports: [
   .....       
  ],
 declarations: [
  ......
 ],

 providers: [...],
 bootstrap: [...]
 })

use it as in above order.first imports then declarations.It worked for me.

How to set cookie value with AJAX request?

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

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

What is lexical scope?

Lets try the shortest possible definition:

Lexical Scoping defines how variable names are resolved in nested functions: inner functions contain the scope of parent functions even if the parent function has returned.

That is all there is to it!

UICollectionView auto scroll to cell at IndexPath

As an alternative to mentioned above. Call after data load:

Swift

collectionView.reloadData()
collectionView.layoutIfNeeded()
collectionView.selectItem(at: indexPath, animated: true, scrollPosition: .right)

Saving a Numpy array as an image

Assuming you want a grayscale image:

im = Image.new('L', (width, height))
im.putdata(an_array.flatten().tolist())
im.save("image.tiff")

How do I view 'git diff' output with my preferred diff tool/ viewer?

If you're not one for the command line then if you install tortoise git you can right click on a file to get a tortoisegit submenu with the "Diff later" option.

When you select this on the first file you can then right click on the second file, go to the tortoisegit submenu and select "Diff with ==yourfilehere==" This will give the tortoisegitmerge gui for the result.

Can jQuery read/write cookies to a browser?

To answer your question, yes. The other have answered that part, but it also seems like you're asking if that's the best way to do it.

It would probably depend on what you are doing. Typically you would have a user click what items they want to buy (ordering for example). Then they would hit a buy or checkout button. Then the form would send off to a page and process the result. You could do all of that with a cookie but I would find it to be more difficult.

You may want to consider posting your second question in another topic.

send Content-Type: application/json post with node.js

Since the request module that other answers use has been deprecated, may I suggest switching to node-fetch:

const fetch = require("node-fetch")

const url = "https://www.googleapis.com/urlshortener/v1/url"
const payload = { longUrl: "http://www.google.com/" }

const res = await fetch(url, {
  method: "post",
  body: JSON.stringify(payload),
  headers: { "Content-Type": "application/json" },
})

const { id } = await res.json()

Getting "unixtime" in Java

Java 8 added a new API for working with dates and times. With Java 8 you can use

import java.time.Instant
...
long unixTimestamp = Instant.now().getEpochSecond();

Instant.now() returns an Instant that represents the current system time. With getEpochSecond() you get the epoch seconds (unix time) from the Instant.

How to move an element into another element?

Ever tried plain JavaScript... destination.appendChild(source); ?

_x000D_
_x000D_
onclick = function(){ destination.appendChild(source); }
_x000D_
div{ margin: .1em; } _x000D_
#destination{ border: solid 1px red; }_x000D_
#source {border: solid 1px gray; }
_x000D_
<!DOCTYPE html>_x000D_
<html>_x000D_
_x000D_
 <body>_x000D_
_x000D_
  <div id="destination">_x000D_
   ###_x000D_
  </div>_x000D_
  <div id="source">_x000D_
   ***_x000D_
  </div>_x000D_
_x000D_
 </body>_x000D_
</html>
_x000D_
_x000D_
_x000D_

Search for one value in any column of any table inside a database

All third=party tools mentioned below are 100% free.

I’ve used ApexSQL Search with good success for searching both objects and data in tables. It comes with several other features such as relationship diagrams and such…

I was a bit slow on large (40GB TFS Database) databases though…

enter image description here

Apart from this there is also SSMS Tools pack that offers a lot of other features that are quite useful even though these are not directly related to searching text.

How can I store and retrieve images from a MySQL database using PHP?

First you create a MySQL table to store images, like for example:

create table testblob (
    image_id        tinyint(3)  not null default '0',
    image_type      varchar(25) not null default '',
    image           blob        not null,
    image_size      varchar(25) not null default '',
    image_ctgy      varchar(25) not null default '',
    image_name      varchar(50) not null default ''
);

Then you can write an image to the database like:

/***
 * All of the below MySQL_ commands can be easily
 * translated to MySQLi_ with the additions as commented
 ***/ 
$imgData = file_get_contents($filename);
$size = getimagesize($filename);
mysql_connect("localhost", "$username", "$password");
mysql_select_db ("$dbname");
// mysqli 
// $link = mysqli_connect("localhost", $username, $password,$dbname); 
$sql = sprintf("INSERT INTO testblob
    (image_type, image, image_size, image_name)
    VALUES
    ('%s', '%s', '%d', '%s')",
    /***
     * For all mysqli_ functions below, the syntax is:
     * mysqli_whartever($link, $functionContents); 
     ***/
    mysql_real_escape_string($size['mime']),
    mysql_real_escape_string($imgData),
    $size[3],
    mysql_real_escape_string($_FILES['userfile']['name'])
    );
mysql_query($sql);

You can display an image from the database in a web page with:

$link = mysql_connect("localhost", "username", "password");
mysql_select_db("testblob");
$sql = "SELECT image FROM testblob WHERE image_id=0";
$result = mysql_query("$sql");
header("Content-type: image/jpeg");
echo mysql_result($result, 0);
mysql_close($link);

Powershell v3 Invoke-WebRequest HTTPS error

I tried searching for documentation on the EM7 OpenSource REST API. No luck so far.

http://blog.sciencelogic.com/sciencelogic-em7-the-next-generation/05/2011

There's a lot of talk about OpenSource REST API, but no link to the actual API or any documentation. Maybe I was impatient.

Here are few things you can try out

$a = Invoke-RestMethod -Uri https://IPADDRESS/resource -Credential $cred -certificate $cert 
$a.Results | ConvertFrom-Json

Try this to see if you can filter out the columns that you are getting from the API

$a.Results | ft

or, you can try using this also

$b = Invoke-WebRequest -Uri https://IPADDRESS/resource -Credential $cred -certificate $cert 
$b.Content | ConvertFrom-Json

Curl Style Headers

$b.Headers

I tested the IRM / IWR with the twitter JSON api.

$a = Invoke-RestMethod http://search.twitter.com/search.json?q=PowerShell 

Hope this helps.

NuGet auto package restore does not work with MSBuild

Sometimes this occurs when you have the folder of the package you are trying to restore inside the "packages" folder (i.e. "Packages/EntityFramework.6.0.0/") but the "DLLs" are not inside it (most of the version control systems automatically ignore ".dll" files). This occurs because before NuGet tries to restore each package it checks if the folders already exist, so if it exists, NuGet assumes that the "dll" is inside it. So if this is the problem for you just delete the folder that NuGet will restore it correctly.

How to remove duplicate white spaces in string using Java?

If you want to get rid of all leading and trailing extraneous whitespace then you want to do something like this:

// \\A = Start of input boundary
// \\z = End of input boundary 
string = string.replaceAll("\\A\\s+(.*?)\\s+\\z", "$1");

Then you can remove the duplicates using the other strategies listed here:

string = string.replaceAll("\\s+"," ");

How to set the margin or padding as percentage of height of parent container?

The fix is that yes, vertical padding and margin are relative to width, but top and bottom aren't.

So just place a div inside another, and in the inner div, use something like top:50% (remember position matters if it still doesn't work)

TypeError: '<=' not supported between instances of 'str' and 'int'

When you use the input function it automatically turns it into a string. You need to go:

vote = int(input('Enter the name of the player you wish to vote for'))

which turns the input into a int type value

SSIS expression: convert date to string

Something simpler than what @Milen proposed but it gives YYYY-MM-DD instead of the DD-MM-YYYY you wanted :

SUBSTRING((DT_STR,30, 1252) GETDATE(), 1, 10)

Expression builder screen:

enter image description here

Convert date from 'Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)' to 'YYYY-MM-DD' in javascript

You can parse the date using the Date constructor, then spit out the individual time components:

_x000D_
_x000D_
function convert(str) {_x000D_
  var date = new Date(str),_x000D_
    mnth = ("0" + (date.getMonth() + 1)).slice(-2),_x000D_
    day = ("0" + date.getDate()).slice(-2);_x000D_
  return [date.getFullYear(), mnth, day].join("-");_x000D_
}_x000D_
_x000D_
console.log(convert("Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)"))_x000D_
//-> "2011-06-08"
_x000D_
_x000D_
_x000D_

As you can see from the result though, this will parse the date into the local time zone. If you want to keep the date based on the original time zone, the easiest approach is to split the string and extract the parts you need:

_x000D_
_x000D_
function convert(str) {_x000D_
  var mnths = {_x000D_
      Jan: "01",_x000D_
      Feb: "02",_x000D_
      Mar: "03",_x000D_
      Apr: "04",_x000D_
      May: "05",_x000D_
      Jun: "06",_x000D_
      Jul: "07",_x000D_
      Aug: "08",_x000D_
      Sep: "09",_x000D_
      Oct: "10",_x000D_
      Nov: "11",_x000D_
      Dec: "12"_x000D_
    },_x000D_
    date = str.split(" ");_x000D_
_x000D_
  return [date[3], mnths[date[1]], date[2]].join("-");_x000D_
}_x000D_
_x000D_
console.log(convert("Thu Jun 09 2011 00:00:00 GMT+0530 (India Standard Time)"))_x000D_
//-> "2011-06-09"
_x000D_
_x000D_
_x000D_

Convert list of ASCII codes to string (byte array) in Python

struct.pack('B' * len(integers), *integers)

*sequence means "unpack sequence" - or rather, "when calling f(..., *args ,...), let args = sequence".

Post request with Wget?

Wget currently only supports x-www-form-urlencoded data. --post-file is not for transmitting files as form attachments, it expects data with the form: key=value&otherkey=example.

--post-data and --post-file work the same way: the only difference is that --post-data allows you to specify the data in the command line, while --post-file allows you to specify the path of the file that contain the data to send.

Here's the documentation:

 --post-data=string
       --post-file=file
           Use POST as the method for all HTTP requests and send the specified data
           in the request body.  --post-data sends string as data, whereas
           --post-file sends the contents of file.  Other than that, they work in
           exactly the same way. In particular, they both expect content of the
           form "key1=value1&key2=value2", with percent-encoding for special
           characters; the only difference is that one expects its content as a
           command-line parameter and the other accepts its content from a file. In
           particular, --post-file is not for transmitting files as form
           attachments: those must appear as "key=value" data (with appropriate
           percent-coding) just like everything else. Wget does not currently
           support "multipart/form-data" for transmitting POST data; only
           "application/x-www-form-urlencoded". Only one of --post-data and
           --post-file should be specified.

Regarding your authentication token, it should either be provided in the header, in the path of the url, or in the data itself. This must be indicated somewhere in the documentation of the service you use. In a POST request, as in a GET request, you must specify the data using keys and values. This way the server will be able to receive multiple information with specific names. It's similar with variables.

Hence, you can't just send a magic token to the server, you also need to specify the name of the key. If the key is "token", then it should be token=YOUR_TOKEN.

wget --post-data 'user=foo&password=bar' http://example.com/auth.php

Also, you should consider using curl if you can because it is easier to send files using it. There are many examples on the Internet for that.

Is there any advantage of using map over unordered_map in case of trivial keys?

Don't forget that map keeps its elements ordered. If you can't give that up, obviously you can't use unordered_map.

Something else to keep in mind is that unordered_map generally uses more memory. map just has a few house-keeping pointers, and memory for each object. Contrarily, unordered_map has a big array (these can get quite big in some implementations), and then additional memory for each object. If you need to be memory-aware, map should prove better, because it lacks the large array.

So, if you need pure lookup-retrieval, I'd say unordered_map is the way to go. But there are always trade-offs, and if you can't afford them, then you can't use it.

Just from personal experience, I found an enormous improvement in performance (measured, of course) when using unordered_map instead of map in a main entity look-up table.

On the other hand, I found it was much slower at repeatedly inserting and removing elements. It's great for a relatively static collection of elements, but if you're doing tons of insertions and deletions the hashing + bucketing seems to add up. (Note, this was over many iterations.)

Error: EACCES: permission denied, access '/usr/local/lib/node_modules'

change your file permissions .. like this

first check who owns the directory

ls -la /usr/local/lib/node_modules

it is denying access because the node_module folder is owned by root

drwxr-xr-x   3 root    wheel  102 Jun 24 23:24 node_modules

so this needs to be changed by changing root to your user but first run command below to check your current user How do I get the name of the active user via the command line in OS X?

id -un

OR

whoami

then change owner

sudo chown -R [owner]:[owner] /usr/local/lib/node_modules

OR

sudo chown -R ownerName: /usr/local/lib/node_modules

OR

sudo chown -R $USER /usr/local/lib/node_modules

Even though JRE 8 is installed on my MAC -" No Java Runtime present,requesting to install " gets displayed in terminal

I have Mojave 10.14.6 and the only thing that did work for me was:

  • setting JAVA_HOME to the following:
export JAVA_HOME=/Library/Internet\ Plug-Ins/JavaAppletPlugin.plugin/Contents/Home
  • source .bash_profile (or wherever you keep your vars, in my case .zshrc)

Hope it helps! You can now type java --version and it should work

Gson library in Android Studio

There is no need of adding JAR to your project by yourself, just add dependency in build.gradle (Module lavel). ALSO always try to use the upgraded version, as of now is

dependencies {
  implementation 'com.google.code.gson:gson:2.8.5'
}

As every incremental version has some bugs fixes or up-gradations as mentioned here

Read from file in eclipse

Sometimes, even when the file is in the right directory, there is still the "file not found" exception. One thing you could do is to drop the text file inside eclipse, where your classes are, on the left side. It is going to ask you if you want to copy, click yes. Sometimes it helps.

Exchange Powershell - How to invoke Exchange 2010 module from inside script?

You can do this:

add-pssnapin Microsoft.Exchange.Management.PowerShell.E2010

and most of it will work (although MS support will tell you that doing this is not supported because it bypasses RBAC).

I've seen issues with some cmdlets (specifically enable/disable UMmailbox) not working with just the snapin loaded.

In Exchange 2010, they basically don't support using Powershell outside of the the implicit remoting environment of an actual EMS shell.

How to call Base Class's __init__ method from the child class?

You could use super(ChildClass, self).__init__()

class BaseClass(object):
    def __init__(self, *args, **kwargs):
        pass

class ChildClass(BaseClass):
    def __init__(self, *args, **kwargs):
        super(ChildClass, self).__init__(*args, **kwargs)

Your indentation is incorrect, here's the modified code:

class Car(object):
    condition = "new"

    def __init__(self, model, color, mpg):
        self.model = model
        self.color = color
        self.mpg   = mpg

class ElectricCar(Car):
    def __init__(self, battery_type, model, color, mpg):
        self.battery_type=battery_type
        super(ElectricCar, self).__init__(model, color, mpg)

car = ElectricCar('battery', 'ford', 'golden', 10)
print car.__dict__

Here's the output:

{'color': 'golden', 'mpg': 10, 'model': 'ford', 'battery_type': 'battery'}

percentage of two int?

One of them has to be a float going in. One possible way of ensuring that is:

float percent = (float) n/v * 100;

Otherwise, you're doing integer division, which truncates the numbers. Also, you should be using double unless there's a good reason for the float.

The next issue you'll run into is that some of your percentages might look like 24.9999999999999% instead of 25%. This is due to precision loss in floating point representation. You'll have to decide how to deal with that, too. Options include a DecimalFormat to "fix" the formatting or BigDecimal to represent exact values.

javascript push multidimensional array

In JavaScript, the type of key/value store you are attempting to use is an object literal, rather than an array. You are mistakenly creating a composite array object, which happens to have other properties based on the key names you provided, but the array portion contains no elements.

Instead, declare valueToPush as an object and push that onto cookie_value_add:

// Create valueToPush as an object {} rather than an array []
var valueToPush = {};

// Add the properties to your object
// Note, you could also use the valueToPush["productID"] syntax you had
// above, but this is a more object-like syntax
valueToPush.productID = productID;
valueToPush.itemColorTitle = itemColorTitle;
valueToPush.itemColorPath = itemColorPath;

cookie_value_add.push(valueToPush);

// View the structure of cookie_value_add
console.dir(cookie_value_add);

Close Android Application

The answer depends on what you mean by "close app". In android's terms its either about an "activity", or a group of activities in a temporal/ancestral order called "task".

End activity: just call finish()

End task:

  1. clear activity task-stack
  2. navigate to root activity
  3. then call finish on it.

This will end the entire "task"

Windows Scipy Install: No Lapack/Blas Resources Found

The following link should solve all problems with Windows and SciPy; just choose the appropriate download. I was able to pip install the package with no problems. Every other solution I have tried gave me big headaches.

Source: http://www.lfd.uci.edu/~gohlke/pythonlibs/#scipy

Command:

 pip install [Local File Location]\[Your specific file such as scipy-0.16.0-cp27-none-win_amd64.whl]

This assumes you have installed the following already:

  1. Install Visual Studio 2015/2013 with Python Tools
    (Is integrated into the setup options on install of 2015)

  2. Install Visual Studio C++ Compiler for Python
    Source: http://www.microsoft.com/en-us/download/details.aspx?id=44266
    File Name: VCForPython27.msi

  3. Install Python Version of choice
    Source: python.org
    File Name (e.g.): python-2.7.10.amd64.msi

How to decrypt the password generated by wordpress

You will not be able to retrieve a plain text password from wordpress.

Wordpress use a 1 way encryption to store the passwords using a variation of md5. There is no way to reverse this.

See this article for more info http://wordpress.org/support/topic/how-is-the-user-password-encrypted-wp_hash_password

Change fill color on vector asset in Android Studio

As said in other answers, don't edit the vector drawable directly, instead you can tint in java code, like that:

    mWrappedDrawable = mDrawable.mutate();
    mWrappedDrawable = DrawableCompat.wrap(mWrappedDrawable);
    DrawableCompat.setTint(mWrappedDrawable, mColor);
    DrawableCompat.setTintMode(mWrappedDrawable, PorterDuff.Mode.SRC_IN);

And for the sake of simplicity, I have created a helper class:

import android.content.Context;
import android.graphics.PorterDuff;
import android.graphics.drawable.Drawable;
import android.os.Build;
import android.support.annotation.ColorRes;
import android.support.annotation.DrawableRes;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.support.v4.graphics.drawable.DrawableCompat;
import android.view.MenuItem;
import android.view.View;
import android.widget.ImageView;

/**
 * {@link Drawable} helper class.
 *
 * @author Filipe Bezerra
 * @version 18/01/2016
 * @since 18/01/2016
 */
public class DrawableHelper {
    @NonNull Context mContext;
    @ColorRes private int mColor;
    private Drawable mDrawable;
    private Drawable mWrappedDrawable;

    public DrawableHelper(@NonNull Context context) {
        mContext = context;
    }

    public static DrawableHelper withContext(@NonNull Context context) {
        return new DrawableHelper(context);
    }

    public DrawableHelper withDrawable(@DrawableRes int drawableRes) {
        mDrawable = ContextCompat.getDrawable(mContext, drawableRes);
        return this;
    }

    public DrawableHelper withDrawable(@NonNull Drawable drawable) {
        mDrawable = drawable;
        return this;
    }

    public DrawableHelper withColor(@ColorRes int colorRes) {
        mColor = ContextCompat.getColor(mContext, colorRes);
        return this;
    }

    public DrawableHelper tint() {
        if (mDrawable == null) {
            throw new NullPointerException("É preciso informar o recurso drawable pelo método withDrawable()");
        }

        if (mColor == 0) {
            throw new IllegalStateException("É necessário informar a cor a ser definida pelo método withColor()");
        }

        mWrappedDrawable = mDrawable.mutate();
        mWrappedDrawable = DrawableCompat.wrap(mWrappedDrawable);
        DrawableCompat.setTint(mWrappedDrawable, mColor);
        DrawableCompat.setTintMode(mWrappedDrawable, PorterDuff.Mode.SRC_IN);

        return this;
    }

    @SuppressWarnings("deprecation")
    public void applyToBackground(@NonNull View view) {
        if (mWrappedDrawable == null) {
            throw new NullPointerException("É preciso chamar o método tint()");
        }

        if(Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
            view.setBackground(mWrappedDrawable);
        } else {
            view.setBackgroundDrawable(mWrappedDrawable);
        }
    }

    public void applyTo(@NonNull ImageView imageView) {
        if (mWrappedDrawable == null) {
            throw new NullPointerException("É preciso chamar o método tint()");
        }

        imageView.setImageDrawable(mWrappedDrawable);
    }

    public void applyTo(@NonNull MenuItem menuItem) {
        if (mWrappedDrawable == null) {
            throw new NullPointerException("É preciso chamar o método tint()");
        }

        menuItem.setIcon(mWrappedDrawable);
    }

    public Drawable get() {
        if (mWrappedDrawable == null) {
            throw new NullPointerException("É preciso chamar o método tint()");
        }

        return mWrappedDrawable;
    }
}

To use just do the following:

    DrawableHelper
            .withContext(this)
            .withColor(R.color.white)
            .withDrawable(R.drawable.ic_search_24dp)
            .tint()
            .applyTo(mSearchItem);

Or:

    final Drawable drawable = DrawableHelper
            .withContext(this)
            .withColor(R.color.white)
            .withDrawable(R.drawable.ic_search_24dp)
            .tint()
            .get();

    actionBar.setHomeAsUpIndicator(drawable);

Using Docker-Compose, how to execute multiple commands

Use a tool such as wait-for-it or dockerize. These are small wrapper scripts which you can include in your application’s image. Or write your own wrapper script to perform a more application-specific commands. according to: https://docs.docker.com/compose/startup-order/

Static nested class in Java, why?

Well, for one thing, non-static inner classes have an extra, hidden field that points to the instance of the outer class. So if the Entry class weren't static, then besides having access that it doesn't need, it would carry around four pointers instead of three.

As a rule, I would say, if you define a class that's basically there to act as a collection of data members, like a "struct" in C, consider making it static.

How to kill all processes with a given partial name?

Also you can use killall -r my_pattern. -r Interpret process name pattern as an extended regular expression.

killall -r my_pattern

How to launch an application from a browser?

The correct method is to register your custom URL Protocol in windows registry as follows:

[HKEY_CLASSES_ROOT\customurl]
@="Description here"
"URL Protocol"=""

[HKEY_CLASSES_ROOT\customurl\shell]

[HKEY_CLASSES_ROOT\customurl\shell\open]

[HKEY_CLASSES_ROOT\customurl\shell\open\command]
@="\"C:\\Path To Your EXE\\ExeName.exe\" \"%1\""

Once the above keys and values are added, from the web page, just call "customurl:\\parameter1=xxx&parameter2=xxx" . You will receive the entire url as the argument in exe, which you need to process inside your exe. Change 'customurl' with the text of your choice.

How to auto-reload files in Node.js?

I am working on making a rather tiny node "thing" that is able to load/unload modules at-will (so, i.e. you could be able to restart part of your application without bringing the whole app down). I am incorporating a (very stupid) dependency management, so that if you want to stop a module, all the modules that depends on that will be stopped too.

So far so good, but then I stumbled into the issue of how to reload a module. Apparently, one could just remove the module from the "require" cache and have the job done. Since I'm not keen to change directly the node source code, I came up with a very hacky-hack that is: search in the stack trace the last call to the "require" function, grab a reference to it's "cache" field and..well, delete the reference to the node:

    var args = arguments
    while(!args['1'] || !args['1'].cache) {
        args = args.callee.caller.arguments
    }
    var cache = args['1'].cache
    util.log('remove cache ' + moduleFullpathAndExt)
    delete( cache[ moduleFullpathAndExt ] )

Even easier, actually:

var deleteCache = function(moduleFullpathAndExt) {
  delete( require.cache[ moduleFullpathAndExt ] )
}

Apparently, this works just fine. I have absolutely no idea of what that arguments["1"] means, but it's doing its job. I believe that the node guys will implement a reload facility someday, so I guess that for now this solution is acceptable too. (btw. my "thing" will be here: https://github.com/cheng81/wirez , go there in a couple of weeks and you should see what I'm talking about)

Sum all values in every column of a data.frame in R

We can use dplyr to select only numeric columns and purr to get sum for all columns. (can be used to get what ever value for all columns, such as mean, min, max, etc. )

library("dplyr")
library("purrr")

people %>%
    select_if(is.numeric) %>%
    map_dbl(sum)

Or another easy way by only using dplyr

library("dplyr")
people %>%
    summarize_if(is.numeric, sum, na.rm=TRUE)

How to list only top level directories in Python?

Just to add that using os.listdir() does not "take a lot of processing vs very simple os.walk().next()[1]". This is because os.walk() uses os.listdir() internally. In fact if you test them together:

>>>> import timeit
>>>> timeit.timeit("os.walk('.').next()[1]", "import os", number=10000)
1.1215229034423828
>>>> timeit.timeit("[ name for name in os.listdir('.') if os.path.isdir(os.path.join('.', name)) ]", "import os", number=10000)
1.0592019557952881

The filtering of os.listdir() is very slightly faster.

Running MSBuild fails to read SDKToolsPath

I encountered a similar issue just recently on our build server.

I copied the 7.0A folder (C:\Program Files\Microsoft SDKs\Windows\7.0A) from my computer (which has VS2010 installed) on it to the build server in the same location.

After create the following registry key: HKEY_LOCAL_MACHINE\SOFTWARE\Microsoft\Microsoft SDKs\Windows\v7.0A. Set InstallationFolder to C:\Program Files\Microsoft SDKs\Windows\7.0A.

You can also reference the registry on your machine with VS2010 already installed on it if you are confused about what to do with the registry on the build server.

How do I extract the contents of an rpm?

The "DECOMPRESSION" test fails on CygWin, one of the most potentiaally useful platforms for it, due to the "grep" check for "xz" being case sensitive. The result of the "COMPRESSION:" check is:

COMPRESSION='/dev/stdin: XZ compressed data'

Simply replacing 'grep -q' with 'grep -q -i' everywhere seems to resolve the issue well.

I've done a few updates, particularly adding some comments and using "case" instead of stacked "if" statements, and included that fix below

#!/bin/sh
#
# rpm2cpio.sh - extract 'cpio' contents of RPM
#
# Typical usage: rpm2cpio.sh rpmname | cpio -idmv
#

if [ "$# -ne 1" ]; then
    echo "Usage: $0 file.rpm" 1>&2
    exit 1
fi

rpm="$1"
if [ -e "$rpm" ]; then
    echo "Error: missing $rpm"
fi


leadsize=96
o=`expr $leadsize + 8`
set `od -j $o -N 8 -t u1 $rpm`
il=`expr 256 \* \( 256 \* \( 256 \* $2 + $3 \) + $4 \) + $5`
dl=`expr 256 \* \( 256 \* \( 256 \* $6 + $7 \) + $8 \) + $9`
# echo "sig il: $il dl: $dl"

sigsize=`expr 8 + 16 \* $il + $dl`
o=`expr $o + $sigsize + \( 8 - \( $sigsize \% 8 \) \) \% 8 + 8`
set `od -j $o -N 8 -t u1 $rpm`
il=`expr 256 \* \( 256 \* \( 256 \* $2 + $3 \) + $4 \) + $5`
dl=`expr 256 \* \( 256 \* \( 256 \* $6 + $7 \) + $8 \) + $9`
# echo "hdr il: $il dl: $dl"

hdrsize=`expr 8 + 16 \* $il + $dl`
o=`expr $o + $hdrsize`
EXTRACTOR="dd if=$rpm ibs=$o skip=1"

COMPRESSION=`($EXTRACTOR |file -) 2>/dev/null`
DECOMPRESSOR="cat"

case $COMPRESSION in
    *gzip*|*GZIP*)
        DECOMPRESSOR=gunzip
        ;;
    *bzip2*|*BZIP2*)
        DECOMPRESSOR=bunzip2
        ;;
    *xz*|*XZ*)
        DECOMPRESSOR=unxz
        ;;
    *cpio*|*cpio*)
        ;;
    *)
        # Most versions of file don't support LZMA, therefore we assume
        # anything not detected is LZMA
        DECOMPRESSOR="`which unlzma 2>/dev/null`"
        case "$DECOMPRESSOR" in
            /*)
                DECOMPRESSOR="$DECOMPRESSOR"
                ;;
            *)
                DECOMPRESSOR=`which lzmash 2>/dev/null`
                case "$DECOMPRESSOR" in
                    /* )
                        DECOMPRESSOR="lzmash -d -c"
                        ;;
                    *  )
                        echo "Warning: DECOMPRESSOR not found, assuming 'cat'" 1>&2
                        ;;
                esac
                ;;
        esac
esac

$EXTRACTOR 2>/dev/null | $DECOMPRESSOR

What does the regex \S mean in JavaScript?

The \s metacharacter matches whitespace characters.

How to do relative imports in Python?

"Guido views running scripts within a package as an anti-pattern" (rejected PEP-3122)

I have spent so much time trying to find a solution, reading related posts here on Stack Overflow and saying to myself "there must be a better way!". Looks like there is not.

design a stack such that getMinimum( ) should be O(1)

I used a different kind of stack. Here is the implementation.

//
//  main.cpp
//  Eighth
//
//  Created by chaitanya on 4/11/13.
//  Copyright (c) 2013 cbilgika. All rights reserved.
//

#include <iostream>
#include <limits>
using namespace std;
struct stack
{
    int num;
    int minnum;
}a[100];

void push(int n,int m,int &top)
{

    top++;
    if (top>=100) {
        cout<<"Stack Full";
        cout<<endl;
    }
    else{
        a[top].num = n;
        a[top].minnum = m;
    }


}

void pop(int &top)
{
    if (top<0) {
        cout<<"Stack Empty";
        cout<<endl;
    }
    else{
       top--; 
    }


}
void print(int &top)
{
    cout<<"Stack: "<<endl;
    for (int j = 0; j<=top ; j++) {
        cout<<"("<<a[j].num<<","<<a[j].minnum<<")"<<endl;
    }
}


void get_min(int &top)
{
    if (top < 0)
    {
        cout<<"Empty Stack";
    }
    else{
        cout<<"Minimum element is: "<<a[top].minnum;
    }
    cout<<endl;
}

int main()
{

    int top = -1,min = numeric_limits<int>::min(),num;
    cout<<"Enter the list to push (-1 to stop): ";
    cin>>num;
    while (num!=-1) {
        if (top == -1) {
            min = num;
            push(num, min, top);
        }
        else{
            if (num < min) {
                min = num;
            }
            push(num, min, top);
        }
        cin>>num;
    }
    print(top);
    get_min(top);
    return 0;
}

Output:

Enter the list to push (-1 to stop): 5
1
4
6
2
-1
Stack: 
(5,5)
(1,1)
(4,1)
(6,1)
(2,1)
Minimum element is: 1

Try it. I think it answers the question. The second element of every pair gives the minimum value seen when that element was inserted.

How can I convert the "arguments" object to an array in JavaScript?

Lodash:

var args = _.toArray(arguments);

in action:

(function(){ console.log(_.toArray(arguments).splice(1)); })(1, 2, 3)

produces:

[2,3]

Best way to move files between S3 buckets?

For me the following command just worked:

aws s3 mv s3://bucket/data s3://bucket/old_data --recursive

Detecting Windows or Linux?

You can use "system.properties.os", for example:

public class GetOs {

  public static void main (String[] args) {
    String s = 
      "name: " + System.getProperty ("os.name");
    s += ", version: " + System.getProperty ("os.version");
    s += ", arch: " + System.getProperty ("os.arch");
    System.out.println ("OS=" + s);
  }
}

// EXAMPLE OUTPUT: OS=name: Windows 7, version: 6.1, arch: amd64

Here are more details:

How to make a JSONP request from Javascript without JQuery?

I wrote a library to handle this, as simply as possible. No need to make it external, its just one function. Unlike some other options, this script cleans up after itself, and is generalized for making further requests at runtime.

https://github.com/Fresheyeball/micro-jsonp

function jsonp(url, key, callback) {

    var appendParam = function(url, key, param){
            return url
                + (url.indexOf("?") > 0 ? "&" : "?")
                + key + "=" + param;
        },

        createScript = function(url, callback){
            var doc = document,
                head = doc.head,
                script = doc.createElement("script");

            script
            .setAttribute("src", url);

            head
            .appendChild(script);

            callback(function(){
                setTimeout(function(){
                    head
                    .removeChild(script);
                }, 0);
            });
        },

        q =
            "q" + Math.round(Math.random() * Date.now());

    createScript(
        appendParam(url, key, q), function(remove){
            window[q] =
                function(json){
                    window[q] = undefined;
                    remove();
                    callback(json);
                };
        });
}

Limiting floats to two decimal points

orig_float = 232569 / 16000.0

14.5355625

short_float = float("{:.2f}".format(orig_float)) 

14.54

How to tell if tensorflow is using gpu acceleration from inside python shell?

UPDATE FOR TENSORFLOW >= 2.1.

The recommended way in which to check if TensorFlow is using GPU is the following:

tf.config.list_physical_devices('GPU') 

As of TensorFlow 2.1, tf.test.gpu_device_name() has been deprecated in favour of the aforementioned.

Then, in the terminal you can use nvidia-smi to check how much GPU memory has been alloted; at the same time, using watch -n K nvidia-smi would tell you for example every K seconds how much memory you are using (you may want to use K = 1 for real-time)

If you have multiple GPUs and you want to use multiple networks, each one on a separated GPU, you can use:

 with tf.device('/GPU:0'):
      neural_network_1 = initialize_network_1()
 with tf.device('/GPU:1'):
      neural_network_2 = initialize_network_2()

How to add spacing between UITableViewCell

I override this function is subclass of UITableViewCell, and it works OK for me

override func layoutSubviews() {
      super.layoutSubviews()
      //set the values for top,left,bottom,right margins
      let margins = UIEdgeInsets(top: 5, left: 8, bottom: 5, right: 8)
      contentView.frame = contentView.frame.inset(by: margins)
      contentView.layer.cornerRadius = 8
}

Calling constructors in c++ without new

I assume with the second line you actually mean:

Thing *thing = new Thing("uiae");

which would be the standard way of creating new dynamic objects (necessary for dynamic binding and polymorphism) and storing their address to a pointer. Your code does what JaredPar described, namely creating two objects (one passed a const char*, the other passed a const Thing&), and then calling the destructor (~Thing()) on the first object (the const char* one).

By contrast, this:

Thing thing("uiae");

creates a static object which is destroyed automatically upon exiting the current scope.

How to remove carriage return and newline from a variable in shell script

for a pure shell solution without calling external program:

NL=$'\n'    # define a variable to reference 'newline'

testVar=${testVar%$NL}    # removes trailing 'NL' from string

how to open .mat file without using MATLAB?

A .mat-file is a compressed binary file. It is not possible to open it with a text editor (except you have a special plugin as Dennis Jaheruddin says). Otherwise you will have to convert it into a text file (csv for example) with a script. This could be done by python for example: Read .mat files in Python.

Fetch API request timeout?

Edit 1

As pointed out in comments, the code in the original answer keeps running the timer even after the promise is resolved/rejected.

The code below fixes that issue.

function timeout(ms, promise) {
  return new Promise((resolve, reject) => {
    const timer = setTimeout(() => {
      reject(new Error('TIMEOUT'))
    }, ms)

    promise
      .then(value => {
        clearTimeout(timer)
        resolve(value)
      })
      .catch(reason => {
        clearTimeout(timer)
        reject(reason)
      })
  })
}


Original answer

It doesn't have a specified default; the specification doesn't discuss timeouts at all.

You can implement your own timeout wrapper for promises in general:

// Rough implementation. Untested.
function timeout(ms, promise) {
  return new Promise(function(resolve, reject) {
    setTimeout(function() {
      reject(new Error("timeout"))
    }, ms)
    promise.then(resolve, reject)
  })
}

timeout(1000, fetch('/hello')).then(function(response) {
  // process response
}).catch(function(error) {
  // might be a timeout error
})

As described in https://github.com/github/fetch/issues/175 Comment by https://github.com/mislav

Create Log File in Powershell

function WriteLog
{
    Param ([string]$LogString)
    $LogFile = "C:\$(gc env:computername).log"
    $DateTime = "[{0:MM/dd/yy} {0:HH:mm:ss}]" -f (Get-Date)
    $LogMessage = "$Datetime $LogString"
    Add-content $LogFile -value $LogMessage
}

WriteLog "This is my log message"

ObservableCollection not noticing when Item in it changes (even with INotifyPropertyChanged)

The ContentList's Set method will not get called when you change a value inside the collection, instead you should be looking out for the CollectionChanged event firing.

public class CollectionViewModel : ViewModelBase
{          
    public ObservableCollection<EntityViewModel> ContentList
    {
        get { return _contentList; }
    }

    public CollectionViewModel()
    {
         _contentList = new ObservableCollection<EntityViewModel>();
         _contentList.CollectionChanged += ContentCollectionChanged;
    }

    public void ContentCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        //This will get called when the collection is changed
    }
}

Okay, that's twice today I've been bitten by the MSDN documentation being wrong. In the link I gave you it says:

Occurs when an item is added, removed, changed, moved, or the entire list is refreshed.

But it actually doesn't fire when an item is changed. I guess you'll need a more bruteforce method then:

public class CollectionViewModel : ViewModelBase
{          
    public ObservableCollection<EntityViewModel> ContentList
    {
        get { return _contentList; }
    }

    public CollectionViewModel()
    {
         _contentList = new ObservableCollection<EntityViewModel>();
         _contentList.CollectionChanged += ContentCollectionChanged;
    }

    public void ContentCollectionChanged(object sender, NotifyCollectionChangedEventArgs e)
    {
        if (e.Action == NotifyCollectionChangedAction.Remove)
        {
            foreach(EntityViewModel item in e.OldItems)
            {
                //Removed items
                item.PropertyChanged -= EntityViewModelPropertyChanged;
            }
        }
        else if (e.Action == NotifyCollectionChangedAction.Add)
        {
            foreach(EntityViewModel item in e.NewItems)
            {
                //Added items
                item.PropertyChanged += EntityViewModelPropertyChanged;
            }     
        }       
    }

    public void EntityViewModelPropertyChanged(object sender, PropertyChangedEventArgs e)
    {
        //This will get called when the property of an object inside the collection changes
    }
}

If you are going to need this a lot you may want to subclass your own ObservableCollection that triggers the CollectionChanged event when a member triggers its PropertyChanged event automatically (like it says it should in the documentation...)

What is %timeit in python?

This is known as a line magic in iPython. They are unique in that their arguments only extend to the end of the current line, and magics themselves are really structured for command line development. timeit is used to time the execution of code.

If you wanted to see all of the magics you can use, you could simply type:

%lsmagic

to get a list of both line magics and cell magics.

Some further magic information from documentation here:

IPython has a system of commands we call magics that provide effectively a mini command language that is orthogonal to the syntax of Python and is extensible by the user with new commands. Magics are meant to be typed interactively, so they use command-line conventions, such as using whitespace for separating arguments, dashes for options and other conventions typical of a command-line environment.

Depending on whether you are in line or cell mode, there are two different ways to use %timeit. Your question illustrates the first way:

In [1]: %timeit range(100)

vs.

In [1]: %%timeit 
      : x = range(100)
      :

Two models in one view in ASP MVC 3

Create a parent view model that contains both models.

public class MainPageModel{
    public Model1 Model1{get; set;}
    public Model2 Model2{get; set;}
}

This way you can add additional models at a later date with very minimum effort.

How to get Bitmap from an Uri?

private void uriToBitmap(Uri selectedFileUri) {
    try {
        ParcelFileDescriptor parcelFileDescriptor =
                getContentResolver().openFileDescriptor(selectedFileUri, "r");
        FileDescriptor fileDescriptor = parcelFileDescriptor.getFileDescriptor();
        Bitmap image = BitmapFactory.decodeFileDescriptor(fileDescriptor);

        parcelFileDescriptor.close();
    } catch (IOException e) {
        e.printStackTrace();
    }
}

how do I insert a column at a specific column index in pandas?

You could try to extract columns as list, massage this as you want, and reindex your dataframe:

>>> cols = df.columns.tolist()
>>> cols = [cols[-1]]+cols[:-1] # or whatever change you need
>>> df.reindex(columns=cols)

   n  l  v
0  0  a  1
1  0  b  2
2  0  c  1
3  0  d  2

EDIT: this can be done in one line ; however, this looks a bit ugly. Maybe some cleaner proposal may come...

>>> df.reindex(columns=['n']+df.columns[:-1].tolist())

   n  l  v
0  0  a  1
1  0  b  2
2  0  c  1
3  0  d  2

How do I pass options to the Selenium Chrome driver using Python?

Found the chrome Options class in the Selenium source code.

Usage to create a Chrome driver instance:

from selenium import webdriver
from selenium.webdriver.chrome.options import Options
chrome_options = Options()
chrome_options.add_argument("--disable-extensions")
driver = webdriver.Chrome(chrome_options=chrome_options)

nginx: [emerg] "server" directive is not allowed here

That is not an nginx configuration file. It is part of an nginx configuration file.

The nginx configuration file (usually called nginx.conf) will look like:

events {
    ...
}
http {
    ...
    server {
        ...
    }
}

The server block is enclosed within an http block.

Often the configuration is distributed across multiple files, by using the include directives to pull in additional fragments (for example from the sites-enabled directory).

Use sudo nginx -t to test the complete configuration file, which starts at nginx.conf and pulls in additional fragments using the include directive. See this document for more.

Use tab to indent in textarea

There is a library on Github for tab support in your textareas by wjbryant: Tab Override

This is how it works:

// get all the textarea elements on the page
var textareas = document.getElementsByTagName('textarea');

// enable Tab Override for all textareas
tabOverride.set(textareas);

Problems with a PHP shell script: "Could not open input file"

I know its stupid but in my case i was outside of my project folder i didn't have spark file.

In PHP, how do you change the key of an array element?

best way is using reference, and not using unset (which make another step to clean memory)

$tab = ['two' => [] ];

solution:

$tab['newname'] = & $tab['two'];

you have one original and one reference with new name.

or if you don't want have two names in one value is good make another tab and foreach on reference

foreach($tab as $key=> & $value) {
    if($key=='two') { 
        $newtab["newname"] = & $tab[$key];
     } else {
        $newtab[$key] = & $tab[$key];
     }
}

Iterration is better on keys than clone all array, and cleaning old array if you have long data like 100 rows +++ etc..

What exactly is nullptr?

How is it a keyword and an instance of a type?

This isn't surprising. Both true and false are keywords and as literals they have a type ( bool ). nullptr is a pointer literal of type std::nullptr_t, and it's a prvalue (you cannot take the address of it using &).

  • 4.10 about pointer conversion says that a prvalue of type std::nullptr_t is a null pointer constant, and that an integral null pointer constant can be converted to std::nullptr_t. The opposite direction is not allowed. This allows overloading a function for both pointers and integers, and passing nullptr to select the pointer version. Passing NULL or 0 would confusingly select the int version.

  • A cast of nullptr_t to an integral type needs a reinterpret_cast, and has the same semantics as a cast of (void*)0 to an integral type (mapping implementation defined). A reinterpret_cast cannot convert nullptr_t to any pointer type. Rely on the implicit conversion if possible or use static_cast.

  • The Standard requires that sizeof(nullptr_t) be sizeof(void*).

Date formatting in WPF datagrid

If your bound property is DateTime, then all you need is

Binding={Property, StringFormat=d}

How can I account for period (AM/PM) using strftime?

format = '%Y-%m-%d %H:%M %p'

The format is using %H instead of %I. Since %H is the "24-hour" format, it's likely just discarding the %p information. It works just fine if you change the %H to %I.

LINQ Orderby Descending Query

I think this first failed because you are ordering value which is null. If Delivery is a foreign key associated table then you should include this table first, example below:

var itemList = from t in ctn.Items.Include(x=>x.Delivery)
                    where !t.Items && t.DeliverySelection
                    orderby t.Delivery.SubmissionDate descending
                    select t;

Can you run GUI applications in a Docker container?

The other solutions should work, but here is a solution for docker-compose.

To fix that error, you need to pass $DISPLAY and .X11-unix to docker, as well as grant the user who started docker access to xhost.

Within docker-compose.yml file:

version: '2'
services:
    node:
        build: .
        container_name: node
        environment:
            - DISPLAY
        volumes:
            - /tmp/.X11-unix:/tmp/.X11-unix

In terminal or script:

  • xhost +si:localuser:$USER
  • xhost +local:docker
  • export DISPLAY=$DISPLAY
  • docker-compose up

Angular 5 - Copy to clipboard

The best way to do this in Angular and keep the code simple is to use this project.

https://www.npmjs.com/package/ngx-clipboard

    <fa-icon icon="copy" ngbTooltip="Copy to Clipboard" aria-hidden="true" 
    ngxClipboard [cbContent]="target value here" 
    (cbOnSuccess)="copied($event)"></fa-icon>

A non well formed numeric value encountered

Because you are passing a string as the second argument to the date function, which should be an integer.

string date ( string $format [, int $timestamp = time() ] )

Try strtotime which will Parse about any English textual datetime description into a Unix timestamp (integer):

date("d", strtotime($_GET['start_date']));

SQL selecting rows by most recent date with two unique columns

select to.chargeid,t0.po,i.chargetype from invoice i
inner join
(select chargeid,max(servicemonth)po from invoice 
group by chargeid)t0
on i.chargeid=t0.chargeid

The above query will work if the distinct charge id has different chargetype combinations.Hope this simple query helps with little performance time into consideration...

Install a .NET windows service without InstallUtil.exe

Process QProc = new Process();
QProc.StartInfo.FileName = "cmd";
QProc.StartInfo.Arguments ="/c InstallUtil "+ "\""+ filefullPath +"\"";
QProc.StartInfo.WorkingDirectory = Environment.GetEnvironmentVariable("windir") + @"\Microsoft.NET\Framework\v2.0.50727\";
QProc.StartInfo.UseShellExecute = false;
// QProc.StartInfo.CreateNoWindow = true;
QProc.StartInfo.RedirectStandardOutput = true;
QProc.Start();
// QProc.WaitForExit();
QProc.Close();

How do I pass a variable to the layout using Laravel' Blade templating?

just try this simple method: in controller:-

 public function index()
   {
        $data = array(
            'title' => 'Home',
            'otherData' => 'Data Here'
        );
        return view('front.landing')->with($data);
   }

And in you layout (app.blade.php) :

<title>{{ $title }} - {{ config('app.name') }} </title>

Thats all.

Uploading file using POST request in Node.js

An undocumented feature of the formData field that request implements is the ability to pass options to the form-data module it uses:

request({
  url: 'http://example.com',
  method: 'POST',
  formData: {
    'regularField': 'someValue',
    'regularFile': someFileStream,
    'customBufferFile': {
      value: fileBufferData,
      options: {
        filename: 'myfile.bin'
      }
    }
  }
}, handleResponse);

This is useful if you need to avoid calling requestObj.form() but need to upload a buffer as a file. The form-data module also accepts contentType (the MIME type) and knownLength options.

This change was added in October 2014 (so 2 months after this question was asked), so it should be safe to use now (in 2017+). This equates to version v2.46.0 or above of request.

How can I get the named parameters from a URL using Flask?

Template Code

<table>
     <tr>
      <th style="min-width: 70px;">Sl No.</th>
      <th style="min-width: 350px;">Description</th>
      <th style="min-width: 100px;">Date</th>
      <th style="min-width: 50px;">Time</th>
      <th style="min-width: 50px;">Status</th>
      <th style="min-width: 50px;">Action</th>
      </tr>
      {% set count = [0] %}
      {% for val in data['todos']%}
      {% if count.append(count.pop() + 1) %}{% endif %}
      <tr>
      <td>{{count[0]}}</td>
      <td>{{val['description']}}</td>
      <td>{{val['date']}}</td>
      <td>{{val['time']}}</td>
      <td>{{val['status']}}</td>
      <td>
        <a class="fa fa-edit" href="#" style=" color: rgb(32, 252, 43);" ></a>
        <a class="fa fa-trash-alt" href="http://localhost:5000/delete?todoid={{val['_id']}}" onmouseout="this.style.color=' rgb(248, 153, 153)'" onmouseover="this.style.color='rgb(241, 74, 74)'" style="padding-left:8%; color: rgb(248, 153, 153);"></a>
      </td>
     </tr>
     {% endfor %}
    </table>

Route code

@app.route('/delete', methods=["GET"])
def deleteTodo():
id = request.args.get('todoid')
print(id)

PHP Header redirect not working

Look carefully at your includes - perhaps you have a blank line after a closing ?> ?

This will cause some literal whitespace to be sent as output, preventing you from making subsequent header calls.

Note that it is legal to leave the close ?> off the include file, which is a useful idiom for avoiding this problem.

(EDIT: looking at your header, you need to avoid doing any HTML output if you want to output headers, or use output buffering to capture it).

Finally, as the PHP manual page for header points out, you should really use full URLs to redirect:

Note: HTTP/1.1 requires an absolute URI as argument to Location: including the scheme, hostname and absolute path, but some clients accept relative URIs. You can usually use $_SERVER['HTTP_HOST'], $_SERVER['PHP_SELF'] and dirname() to make an absolute URI from a relative one yourself:

List attributes of an object

dir(instance)
# or (same value)
instance.__dir__()
# or
instance.__dict__

Then you can test what type is with type() or if is a method with callable().

Android Studio: Application Installation Failed

I solved the issue by simply deleting my whole /build folder and rebuilding (menu Build > rebuild project).

Android studio: emulator is running but not showing up in Run App "choose a running device"

  1. start device from genymotion button (have to install genymotion before and setup genymotion folder location on settings)
  2. run application
  3. choose genymotion running device

.htaccess rewrite subdomain to directory

Redirect subdomain directory:

RewriteCond %{HTTP_HOST} ^([^.]+)\.(archive\.example\.com)$ [NC]
RewriteRule ^ http://%2/%1%{REQUEST_URI} [L,R=301]

How can I insert binary file data into a binary SQL field using a simple insert statement?

If you mean using a literal, you simply have to create a binary string:

insert into Files (FileId, FileData) values (1, 0x010203040506)

And you will have a record with a six byte value for the FileData field.


You indicate in the comments that you want to just specify the file name, which you can't do with SQL Server 2000 (or any other version that I am aware of).

You would need a CLR stored procedure to do this in SQL Server 2005/2008 or an extended stored procedure (but I'd avoid that at all costs unless you have to) which takes the filename and then inserts the data (or returns the byte string, but that can possibly be quite long).


In regards to the question of only being able to get data from a SP/query, I would say the answer is yes, because if you give SQL Server the ability to read files from the file system, what do you do when you aren't connected through Windows Authentication, what user is used to determine the rights? If you are running the service as an admin (God forbid) then you can have an elevation of rights which shouldn't be allowed.

Has been blocked by CORS policy: Response to preflight request doesn’t pass access control check

Angular and Django Rest Framework.

I encountered similar error while making post request to my DRF api. It happened that all I was missing was trailing slash for endpoint.

Redirecting to URL in Flask

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

import os
from flask import Flask, redirect, url_for

app = Flask(__name__)

@app.route('/')
def hello():
    return redirect(url_for('foo'))

@app.route('/foo')
def foo():
    return 'Hello Foo!'

if __name__ == '__main__':
    # Bind to PORT if defined, otherwise default to 5000.
    port = int(os.environ.get('PORT', 5000))
    app.run(host='0.0.0.0', port=port)

Take a look at the example in the documentation.

Mail multipart/alternative vs multipart/mixed

Here is the best: Multipart/mixed mime message with attachments and inline images

And image: https://www.qcode.co.uk/images/mime-nesting-structure.png

From: [email protected]
To: to@@qcode.co.uk
Subject: Example Email
MIME-Version: 1.0
Content-Type: multipart/mixed; boundary="MixedBoundaryString"

--MixedBoundaryString
Content-Type: multipart/related; boundary="RelatedBoundaryString"

--RelatedBoundaryString
Content-Type: multipart/alternative; boundary="AlternativeBoundaryString"

--AlternativeBoundaryString
Content-Type: text/plain;charset="utf-8"
Content-Transfer-Encoding: quoted-printable

This is the plain text part of the email.

--AlternativeBoundaryString
Content-Type: text/html;charset="utf-8"
Content-Transfer-Encoding: quoted-printable

<html>
  <body>=0D
    <img src=3D=22cid:masthead.png=40qcode.co.uk=22 width 800 height=3D80=
 =5C>=0D
    <p>This is the html part of the email.</p>=0D
    <img src=3D=22cid:logo.png=40qcode.co.uk=22 width 200 height=3D60 =5C=
>=0D
  </body>=0D
</html>=0D

--AlternativeBoundaryString--

--RelatedBoundaryString
Content-Type: image/jpgeg;name="logo.png"
Content-Transfer-Encoding: base64
Content-Disposition: inline;filename="logo.png"
Content-ID: <[email protected]>

amtsb2hiaXVvbHJueXZzNXQ2XHVmdGd5d2VoYmFmaGpremxidTh2b2hydHVqd255aHVpbnRyZnhu
dWkgb2l1b3NydGhpdXRvZ2hqdWlyb2h5dWd0aXJlaHN1aWhndXNpaHhidnVqZmtkeG5qaG5iZ3Vy
...
...
a25qbW9nNXRwbF0nemVycHpvemlnc3k5aDZqcm9wdHo7amlodDhpOTA4N3U5Nnkwb2tqMm9sd3An
LGZ2cDBbZWRzcm85eWo1Zmtsc2xrZ3g=

--RelatedBoundaryString
Content-Type: image/jpgeg;name="masthead.png"
Content-Transfer-Encoding: base64
Content-Disposition: inline;filename="masthead.png"
Content-ID: <[email protected]>

aXR4ZGh5Yjd1OHk3MzQ4eXFndzhpYW9wO2tibHB6c2tqOTgwNXE0aW9qYWJ6aXBqOTBpcjl2MC1t
dGlmOTA0cW05dGkwbWk0OXQwYVttaXZvcnBhXGtsbGo7emt2c2pkZnI7Z2lwb2F1amdpNTh1NDlh
...
...
eXN6dWdoeXhiNzhuZzdnaHQ3eW9zemlqb2FqZWt0cmZ1eXZnamhka3JmdDg3aXV2dWd5aGVidXdz
dhyuhehe76YTGSFGA=

--RelatedBoundaryString--

--MixedBoundaryString
Content-Type: application/pdf;name="Invoice_1.pdf"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;filename="Invoice_1.pdf"

aGZqZGtsZ3poZHVpeWZoemd2dXNoamRibngganZodWpyYWRuIHVqO0hmSjtyRVVPIEZSO05SVURF
SEx1aWhudWpoZ3h1XGh1c2loZWRma25kamlsXHpodXZpZmhkcnVsaGpnZmtsaGVqZ2xod2plZmdq
...
...
a2psajY1ZWxqanNveHV5ZXJ3NTQzYXRnZnJhZXdhcmV0eXRia2xhanNueXVpNjRvNWllc3l1c2lw
dWg4NTA0

--MixedBoundaryString
Content-Type: application/pdf;name="SpecialOffer.pdf"
Content-Transfer-Encoding: base64
Content-Disposition: attachment;filename="SpecialOffer.pdf"

aXBvY21odWl0dnI1dWk4OXdzNHU5NTgwcDN3YTt1OTQwc3U4NTk1dTg0dTV5OGlncHE1dW4zOTgw
cS0zNHU4NTk0eWI4OTcwdjg5MHE4cHV0O3BvYTt6dWI7dWlvenZ1em9pdW51dDlvdTg5YnE4N3Z3
...
...
OTViOHk5cDV3dTh5bnB3dWZ2OHQ5dTh2cHVpO2p2Ymd1eTg5MGg3ajY4bjZ2ODl1ZGlvcjQ1amts
dfnhgjdfihn=

--MixedBoundaryString--

.

Schema multipart/related/alternative

Header
|From: email
|To: email
|MIME-Version: 1.0
|Content-Type: multipart/mixed; boundary="boundary1";
Message body
|multipart/mixed --boundary1
|--boundary1
|   multipart/related --boundary2
|   |--boundary2
|   |   multipart/alternative --boundary3
|   |   |--boundary3
|   |   |text/plain
|   |   |--boundary3
|   |   |text/html
|   |   |--boundary3--
|   |--boundary2    
|   |Inline image
|   |--boundary2    
|   |Inline image
|   |--boundary2--
|--boundary1    
|Attachment1
|--boundary1
|Attachment2
|--boundary1
|Attachment3
|--boundary1--
|
.

A Windows equivalent of the Unix tail command

Try Windows Services for UNIX. Provides shells, awk, sed, etc. as well as tail.

Update -: Unfortunately, as of 2019 this system is no longer available on the Microsoft Download Center.

Expected BEGIN_ARRAY but was BEGIN_OBJECT at line 1 column 2

You state in the comments that the returned JSON is this:

{ 
  "dstOffset" : 3600, 
  "rawOffset" : 36000, 
  "status" : "OK", 
  "timeZoneId" : "Australia/Hobart", 
  "timeZoneName" : "Australian Eastern Daylight Time" 
}

You're telling Gson that you have an array of Post objects:

List<Post> postsList = Arrays.asList(gson.fromJson(reader,
                    Post[].class));

You don't. The JSON represents exactly one Post object, and Gson is telling you that.

Change your code to be:

Post post = gson.fromJson(reader, Post.class);

Opening a SQL Server .bak file (Not restoring!)

The only workable solution is to restore the .bak file. The contents and the structure of those files are not documented and therefore, there's really no way (other than an awful hack) to get this to work - definitely not worth your time and the effort!

The only tool I'm aware of that can make sense of .bak files without restoring them is Red-Gate SQL Compare Professional (and the accompanying SQL Data Compare) which allow you to compare your database structure against the contents of a .bak file. Red-Gate tools are absolutely marvelous - highly recommended and well worth every penny they cost!

And I just checked their web site - it does seem that you can indeed restore a single table from out of a .bak file with SQL Compare Pro ! :-)

PNG transparency issue in IE8

PNG transparency pr?bl?m in IE8

Dan's solution worked for me. I was trying to fade a div with a background image. Caveats: you cannot fade the div directly, instead fade a wrapper image. Also, add the following filters to apply a background image:

-ms-filter: "progid:DXImageTransform.Microsoft.gradient(startColorstr=#00FFFFFF,endColorstr=#00FFFFFF)progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',sizingMethod='image',src='assets/img/bgSmall.png')"; /* IE8 */   
filter: progid:DXImageTransform.Microsoft.gradient(startColorstr=#00FFFFFF,endColorstr=#00FFFFFF)progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled='true',sizingMethod='image',src='assets/img/bgSmall.png');   /* IE6 & 7 */      

Please note that the paths in the src attributes of the filters are absolute, and not relative to the css sheet.

I also added:

background: transparent\9;

This causes IE to ignore my earlier declaration of the actual background image for the other browsers.

Thanks Dan!!!

Trim whitespace from a String

Using a regex

#include <regex>
#include <string>

string trim(string s) {
    regex e("^\\s+|\\s+$");   // remove leading and trailing spaces
    return regex_replace(s, e, "");
}

Credit to: https://www.regular-expressions.info/examples.html for the regex

Command /usr/bin/codesign failed with exit code 1

If you're using phonegap/cordova:

I got this when building from Cordova but the solution for me was much simpler. A permissions issue.

Just set the files to correct permissions

chmod -R 774 ./projectfolder

And then set ownership

chown -R youraccname:staff ./projectfolder 

How to check if the docker engine and a docker container are running?

If the underlying goal is "How can I start a container when Docker starts?"

We can use Docker's restart policy

To add a restart policy to an existing container:

Docker: Add a restart policy to a container that was already created

Example:

docker update --restart=always <container>

Java: How to convert List to Map

Short and sweet.

Using Java 8 you can do following :

Map<Key, Value> result= results
                       .stream()
                       .collect(Collectors.toMap(Value::getName,Function.identity()));

Value can be any object you use.

Selecting text in an element (akin to highlighting with your mouse)

here is another simple solution to get the selected the text in the form of string, you can use this string easily to append a div element child into your code:

var text = '';

if (window.getSelection) {
    text = window.getSelection();

} else if (document.getSelection) {
    text = document.getSelection();

} else if (document.selection) {
    text = document.selection.createRange().text;
}

text = text.toString();

Avoiding "resource is out of sync with the filesystem"

You can enable this in Window - Preferences - General - Workspace - Refresh Automatically (called Refresh using native hooks or polling in newer builds)

Eclipse Preferences "Refresh using native hooks or polling" - Screenshot

The only reason I can think why this isn't enabled by default is performance related.

For example, refreshing source folders automatically might trigger a build of the workspace. Perhaps some people want more control over this.

There is also an article on the Eclipse site regarding auto refresh.

Basically, there is no external trigger that notifies Eclipse of files changed outside the workspace. Rather a background thread is used by Eclipse to monitor file changes that can possibly lead to performance issues with large workspaces.

Declare Variable for a Query String

DECLARE @theDate DATETIME
SET @theDate = '2010-01-01'

Then change your query to use this logic:

AND 
(
    tblWO.OrderDate > DATEADD(MILLISECOND, -1, @theDate) 
    AND tblWO.OrderDate < DATEADD(DAY, 1, @theDate)
)

Open multiple Projects/Folders in Visual Studio Code

Not sure why the simplest solution is not mentioned. You can simply do File>New Window and open the other project in the new window.

How to select a drop-down menu value with Selenium using Python?

firstly you need to import the Select class and then you need to create the instance of Select class. After creating the instance of Select class, you can perform select methods on that instance to select the options from dropdown list. Here is the code

from selenium.webdriver.support.select import Select

select_fr = Select(driver.find_element_by_id("fruits01"))
select_fr.select_by_index(0)

How to lowercase a pandas dataframe string column if it has missing values?

Use apply function,

Xlower = df['x'].apply(lambda x: x.upper()).head(10) 

How to vertically align an image inside a div

Background image solution

I removed the image element altogether and set it as background of the div with a class of .frame

http://jsfiddle.net/URVKa/2/

This at least works fine on Internet Explorer 8, Firefox 6 and Chrome  13.

I checked, and this solution will not work to shrink images larger than 25 pixels height. There is a property called background-size which does set the size of the element, but it is CSS 3 which would conflict with Internet Explorer 7 requirements.

I would advice you to either redo your browser priorities and design for the best available browsers, or get some server-side code to resize the images if you'd want to use this solution.

How do I clear a C++ array?

std::fill(a.begin(),a.end(),0);

How to tag an older commit in Git?

The answer by @Phrogz is great, but doesn't work on Windows. Here's how to tag an old commit with the commit's original date using Powershell:

git checkout 9fceb02
$env:GIT_COMMITTER_DATE = git show --format=%aD | Select -First 1
git tag v1.2
git checkout master

Return value of x = os.system(..)

os.system() returns the (encoded) process exit value. 0 means success:

On Unix, the return value is the exit status of the process encoded in the format specified for wait(). Note that POSIX does not specify the meaning of the return value of the C system() function, so the return value of the Python function is system-dependent.

The output you see is written to stdout, so your console or terminal, and not returned to the Python caller.

If you wanted to capture stdout, use subprocess.check_output() instead:

x = subprocess.check_output(['whoami'])

Mismatched anonymous define() module

I was also seeing the same error on browser console for a project based out of require.js. As stated under MISMATCHED ANONYMOUS DEFINE() MODULES at https://requirejs.org/docs/errors.html, this error has multiple causes, the interesting one in my case being: If the problem is the use of loader plugins or anonymous modules but the RequireJS optimizer is not used for file bundling, use the RequireJS optimizer. As it turns out, Google Closure compiler was getting used to merge/minify the Javascript code during build. Solution was to remove the Google closure compiler, and instead use require.js's optimizer (r.js) to merge the js files.

How to install PostgreSQL's pg gem on Ubuntu?

Simple solution for ubuntu users...

First uninstall all postgres packages, then run these commads...

sudo apt-get install postgresql
sudo apt-get install postgresql-client libpq5 libpq-dev

# for rvm (single user)
mv ~/.rvm/usr/lib ~/.rvm/usr/lib_rvm 

# for rvm (multi-user)
mv /usr/local/rvm/usr/lib /usr/local/rvm/usr/lib_rvm

gem install pg  --   --with-pg-lib=/usr/lib

Then run 'bundle install'. Every thing will be fine. Have a good day!

How do I calculate percentiles with python/numpy?

for a series: used describe functions

suppose you have df with following columns sales and id. you want to calculate percentiles for sales then it works like this,

df['sales'].describe(percentiles = [0.0,0.1,0.2,0.3,0.4,0.5,0.6,0.7,0.8,0.9,1])

0.0: .0: minimum
1: maximum 
0.1 : 10th percentile and so on

Rendering HTML inside textarea

Since you only said render, yes you can. You could do something along the lines of this:

_x000D_
_x000D_
function render(){_x000D_
 var inp     = document.getElementById("box");_x000D_
 var data = `_x000D_
<svg xmlns="http://www.w3.org/2000/svg" width="${inp.offsetWidth}" height="${inp.offsetHeight}">_x000D_
<foreignObject width="100%" height="100%">_x000D_
<div xmlns="http://www.w3.org/1999/xhtml" _x000D_
style="font-family:monospace;font-style: normal; font-variant: normal; font-size:13.3px;padding:2px;;">_x000D_
${inp.value} <i style="color:red">cant touch this</i>_x000D_
</div>_x000D_
</foreignObject>_x000D_
</svg>`;_x000D_
 var blob = new Blob( [data], {type:'image/svg+xml'} );_x000D_
 var url=URL.createObjectURL(blob);_x000D_
 inp.style.backgroundImage="url("+URL.createObjectURL(blob)+")";_x000D_
 }_x000D_
 onload=function(){_x000D_
  render();_x000D_
  ro = new ResizeObserver(render);_x000D_
 ro.observe(document.getElementById("box"));_x000D_
 }
_x000D_
#box{_x000D_
  color:transparent;_x000D_
  caret-color: black;_x000D_
  font-style: normal;/*must be same as in the svg for caret to align*/_x000D_
  font-variant: normal; _x000D_
  font-size:13.3px;_x000D_
  padding:2px;_x000D_
  font-family:monospace;_x000D_
}
_x000D_
<textarea id="box" oninput="render()">you can edit me!</textarea>
_x000D_
_x000D_
_x000D_ This makes it so that a textarea will render html! Besides the flashing when resizing, inability to directly use classes and having to make sure that the div in the svg has the same format as the textarea for the caret to align correctly, it's works!

What is the backslash character (\\)?

\ is used for escape sequences in programming languages.

\n prints a newline
\\ prints a backslash
\" prints "
\t prints a tabulator
\b moves the cursor one back

Using Mockito with multiple calls to the same method with the same arguments

You can do that using the thenAnswer method (when chaining with when):

when(someMock.someMethod()).thenAnswer(new Answer() {
    private int count = 0;

    public Object answer(InvocationOnMock invocation) {
        if (count++ == 1)
            return 1;

        return 2;
    }
});

Or using the equivalent, static doAnswer method:

doAnswer(new Answer() {
    private int count = 0;

    public Object answer(InvocationOnMock invocation) {
        if (count++ == 1)
            return 1;

        return 2;
    }
}).when(someMock).someMethod();

How to set a value for a span using jQuery

Syntax:

$(selector).text() returns the text content.

$(selector).text(content) sets the text content.

$(selector).text(function(index, curContent)) sets text content using a function.

kaynak: https://www.geeksforgeeks.org/jquery-change-the-text-of-a-span-element/

localhost refused to connect Error in visual studio

Like Donny V. this happened to me in VS2017 using .net core 2.0.

When the project first launched, VS displayed a dialog, offering to create an SSL Cert for localhost - but I didn't want to use SSL, so I stopped running and went into Project Properties and disabled SSL (a checkbox that can be cleared). After doing that I kept getting the issue described.

After trying many things what actually resolved the issue for me was editing the launchSettings.json file located under [ProjectName]/Properties - it's accessible from Solution Explorer.

When the editing was complete, the contents looked like this (where 12345 is a Port Number, and where MyNETCoreApp is the name of the project).

{
    "iisSettings": {
        "windowsAuthentication": false,
        "anonymousAuthentication": true,
        "iisExpress": {
            "applicationUrl": "http://localhost:12345/"
        }
    },
    "profiles": {
        "IIS Express": {
            "commandName": "IISExpress",
            "launchBrowser": true,
            "launchUrl": "http://localhost:12345/",
            "environmentVariables": {
                "ASPNETCORE_ENVIRONMENT": "Development"
            }
        },
        "MyNETCoreApp": {
            "commandName": "Project",
            "launchBrowser": true,
            "environmentVariables": {
                "ASPNETCORE_ENVIRONMENT": "Development"
            },
            "applicationUrl": "http://localhost:12345/"
        }
    }
}

The edits I made were:

  • Updated the Port Numbers so they were all the same number
  • Removed a key:value of ssl:0 in one spot
  • Updated all https:// instances to be http://

How to keep two folders automatically synchronized?

You can use inotifywait (with the modify,create,delete,move flags enabled) and rsync.

while inotifywait -r -e modify,create,delete,move /directory; do
    rsync -avz /directory /target
done

If you don't have inotifywait on your system, run sudo apt-get install inotify-tools

SSL certificate rejected trying to access GitHub over HTTPS behind firewall

I wanted Git to use the updated certificate bundle without replacing the one my entire system uses. Here's how to have Git use a specific file in my home directory:

mkdir ~/certs
curl https://curl.haxx.se/ca/cacert.pem -o ~/certs/cacert.pem

Now update .gitconfig to use this for peer verification:

[http]
sslCAinfo = /home/radium/certs/cacert.pem

Note I'm using an absolute path. Git does no path expansion here, so you can't use ~ without an ugly kludge. Alternatively, you can skip the config file and set the path via the environment variable GIT_SSL_CAINFO instead.

To troubleshoot this, set GIT_CURL_VERBOSE=1. The path of the CA file Git is using will be shown on lines starting with "CAfile:" in the output.

Edited to change from http to https.

Download a specific tag with Git

git clone --branch my_abc http://git.abc.net/git/abc.git

Will clone the repo and leave you on the tag you are interested in.

Documentation for 1.8.0 of git clone states.

--branch can also take tags and detaches the HEAD at that commit in the resulting repository.

How to change the font size and color of x-axis and y-axis label in a scatterplot with plot function in R?

To track down the correct parameters you need to go first to ?plot.default, which refers you to ?par and ?axis:

plot(1, 1 ,xlab="x axis", ylab="y axis",  pch=19,
           col.lab="red", cex.lab=1.5,    #  for the xlab and ylab
           col="green")                   #  for the points

Show hidden div on ng-click within ng-repeat

Use ng-show and toggle the value of a show scope variable in the ng-click handler.

Here is a working example: http://jsfiddle.net/pvtpenguin/wD7gR/1/

<ul class="procedures">
    <li ng-repeat="procedure in procedures">
        <h4><a href="#" ng-click="show = !show">{{procedure.definition}}</a></h4>
         <div class="procedure-details" ng-show="show">
            <p>Number of patient discharges: {{procedure.discharges}}</p>
            <p>Average amount covered by Medicare: {{procedure.covered}}</p>
            <p>Average total payments: {{procedure.payments}}</p>
         </div>
    </li>
</ul>

How to change the port of Tomcat from 8080 to 80?

Running the command below worked with. Tried changing server.xml and the conf file but both didn't work.

/sbin/iptables -A INPUT -i eth0 -p tcp --dport 80 -j ACCEPT

/sbin/iptables -A INPUT -i eth0 -p tcp --dport 8080 -j ACCEPT

/sbin/iptables -A PREROUTING -t nat -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080

How to create a testflight invitation code?

after you add the user for testing. the user should get an email. open that email by your iOS device, then click "Start testing" it will bring you to testFlight to download the app directly. If you open that email via computer, and then click "Start testing" it will show you another page which have the instruction of how to install the app. and that invitation code is on the last line. those All upper case letters is the code.

Finding what branch a Git commit came from

git branch --contains <ref> is the most obvious "porcelain" command to do this. If you want to do something similar with only "plumbing" commands:

COMMIT=$(git rev-parse <ref>) # expands hash if needed
for BRANCH in $(git for-each-ref --format "%(refname)" refs/heads); do
  if $(git rev-list $BRANCH | fgrep -q $COMMIT); then
    echo $BRANCH
  fi
done

(crosspost from this SO answer)