Programs & Examples On #Voice recognition

Voice Recognition means identification of the person talking and is frequently misapplied to mean "Speech Recognition" - identification of what is being said.

Android view layout_width - how to change programmatically?

Or simply:

view.getLayoutParams().width = 400;
view.requestLayout();

How to update specific key's value in an associative array in PHP?

foreach($data as $value)
{
    $value["transaction_date"] = date('d/m/Y',$value["transaction_date"]);
}
return $data;

What are the differences between Mustache.js and Handlebars.js?

I feel that one of the mentioned cons for "Handlebars" isnt' really valid anymore.

Handlebars.java now allows us to share the same template languages for both client and server which is a big win for large projects with 1000+ components that require serverside rendering for SEO

Take a look at https://github.com/jknack/handlebars.java

Visual Studio Code - Convert spaces to tabs

File -> Preferences -> Settings or just press Ctrl + , and search for spaces, then just deactivate this option:

enter image description here

I had to reopen the file so the changes would take effect.

string.split - by multiple character delimiter

Another option:

Replace the string delimiter with a single character, then split on that character.

string input = "abc][rfd][5][,][.";
string[] parts1 = input.Replace("][","-").Split('-');

How to force browser to download file?

You are setting the response headers after writing the contents of the file to the output stream. This is quite late in the response lifecycle to be setting headers. The correct sequence of operations should be to set the headers first, and then write the contents of the file to the servlet's outputstream.

Therefore, your method should be written as follows (this won't compile as it is a mere representation):

response.setContentType("application/force-download");
response.setContentLength((int)f.length());
        //response.setContentLength(-1);
response.setHeader("Content-Transfer-Encoding", "binary");
response.setHeader("Content-Disposition","attachment; filename=\"" + "xxx\"");//fileName);
...
...
File f= new File(fileName);

InputStream in = new FileInputStream(f);
BufferedInputStream bin = new BufferedInputStream(in);
DataInputStream din = new DataInputStream(bin);

while(din.available() > 0){
    out.print(din.readLine());
    out.print("\n");
}

The reason for the failure is that it is possible for the actual headers sent by the servlet would be different from what you are intending to send. After all, if the servlet container does not know what headers (which appear before the body in the HTTP response), then it may set appropriate headers to ensure that the response is valid; setting the headers after the file has been written is therefore futile and redundant as the container might have already set the headers. You could confirm this by looking at the network traffic using Wireshark or a HTTP debugging proxy like Fiddler or WebScarab.

You may also refer to the Java EE API documentation for ServletResponse.setContentType to understand this behavior:

Sets the content type of the response being sent to the client, if the response has not been committed yet. The given content type may include a character encoding specification, for example, text/html;charset=UTF-8. The response's character encoding is only set from the given content type if this method is called before getWriter is called.

This method may be called repeatedly to change content type and character encoding. This method has no effect if called after the response has been committed.

...

How to get index of an item in java.util.Set

After creating Set just convert it to List and get by index from List:

Set<String> stringsSet = new HashSet<>();
stringsSet.add("string1");
stringsSet.add("string2");

List<String> stringsList = new ArrayList<>(stringsSet);
stringsList.get(0); // "string1";
stringsList.get(1); // "string2";

Embed HTML5 YouTube video without iframe?

Here is a example of embedding without an iFrame:

_x000D_
_x000D_
<div style="width: 560px; height: 315px; float: none; clear: both; margin: 2px auto;">
  <embed
    src="https://www.youtube.com/embed/J---aiyznGQ?autohide=1&autoplay=1"
    wmode="transparent"
    type="video/mp4"
    width="100%" height="100%"
    allow="autoplay; encrypted-media; picture-in-picture"
    allowfullscreen
    title="Keyboard Cat"
  >
</div>
_x000D_
_x000D_
_x000D_

compare to regular iframe "embed" code from YouTube:

_x000D_
_x000D_
<iframe
  width="560"
  height="315"
  src="https://www.youtube.com/embed/J---aiyznGQ?autoplay=1"
  frameborder="0"
  allow="accelerometer; autoplay; encrypted-media; gyroscope; picture-in-picture"
  allowfullscreen>
</iframe>
_x000D_
_x000D_
_x000D_

and as far as HTML5 goes, use <object> tag like so (corrected):

_x000D_
_x000D_
<object
  style="width: 820px; height: 461.25px; float: none; clear: both; margin: 2px auto;"
  data="http://www.youtube.com/embed/J---aiyznGQ?autoplay=1">
</object>
_x000D_
_x000D_
_x000D_

creating custom tableview cells in swift

Uncheck "Size Classes" checkbox works for me as well, but you could also add the missing constraints in the interface builder. Just use the built-in function if you don't want to add the constraints on your own. Using constraints is - in my opinion - the better way because the layout is independent from the device (iPhone or iPad).

Fatal Error: Allowed Memory Size of 134217728 Bytes Exhausted (CodeIgniter + XML-RPC)

Changing the memory_limit by ini_set('memory_limit', '-1'); is not a proper solution. Please don't do that.

Your PHP code may have a memory leak somewhere and you are telling the server to just use all the memory that it wants. You wouldn't have fixed the problem at all. If you monitor your server, you will see that it is now probably using up most of the RAM and even swapping to disk.

You should probably try to track down the offending code in your code and fix it.

Convert blob URL to normal URL

another way to create a data url from blob url may be using canvas.

var canvas = document.createElement("canvas")
var context = canvas.getContext("2d")
context.drawImage(img, 0, 0) // i assume that img.src is your blob url
var dataurl = canvas.toDataURL("your prefer type", your prefer quality)

as what i saw in mdn, canvas.toDataURL is supported well by browsers. (except ie<9, always ie<9)

What is the meaning of single and double underscore before an object name?

Since so many people are referring to Raymond's talk, I'll just make it a little easier by writing down what he said:

The intention of the double underscores was not about privacy. The intention was to use it exactly like this

class Circle(object):

    def __init__(self, radius):
        self.radius = radius

    def area(self):
        p = self.__perimeter()
        r = p / math.pi / 2.0
        return math.pi * r ** 2.0

    def perimeter(self):
        return 2.0 * math.pi * self.radius

    __perimeter = perimeter  # local reference


class Tire(Circle):

    def perimeter(self):
        return Circle.perimeter(self) * 1.25

It's actually the opposite of privacy, it's all about freedom. It makes your subclasses free to override any one method without breaking the others.

Say you don't keep a local reference of perimeter in Circle. Now, a derived class Tire overrides the implementation of perimeter, without touching area. When you call Tire(5).area(), in theory it should still be using Circle.perimeter for computation, but in reality it's using Tire.perimeter, which is not the intended behavior. That's why we need a local reference in Circle.

But why __perimeter instead of _perimeter? Because _perimeter still gives derived class the chance to override:

class Tire(Circle):

    def perimeter(self):
        return Circle.perimeter(self) * 1.25

    _perimeter = perimeter

Double underscores has name mangling, so there's a very little chance that the local reference in parent class get override in derived class. thus "makes your subclasses free to override any one method without breaking the others".

If your class won't be inherited, or method overriding does not break anything, then you simply don't need __double_leading_underscore.

Displaying the Error Messages in Laravel after being Redirected from controller

Below input field I include additional view:

@include('input-errors', ['inputName' => 'inputName']) #For your case it would be 'email'

input-errors.blade.php

@foreach ($errors->get($inputName) as $message)
    <span class="input-error">{{ $message }}</span>
@endforeach

CSS - adds red color to the message.

.input-error {
    color: #ff5555;
}

How do you display code snippets in MS Word preserving format and syntax highlighting?

This is a bit indirect, but it works very nicely. Get LiveWriter and install this plugin:

http://lvildosola.blogspot.com/2007/02/code-snippet-plugin-for-windows-live.html

Insert your code using the plugin into a blog post. Select all and copy it to Word.

It looks great and can include line numbers. It also spans pages decently.

HTH

Colby Africa

PHPExcel auto size column width

For Spreedsheet + PHP 7, you must write instead of PHPExcel_Cell::columnIndexFromString, \PhpOffice\PhpSpreadsheet\Cell::columnIndexFromString. And at the loop is a mistake, there you must < not work with <=. Otherwise, he takes a column too much into the loop.

Java: recommended solution for deep cloning/copying an instance

For complicated objects and when performance is not significant i use gson to serialize the object to json text, then deserialize the text to get new object.

gson which based on reflection will works in most cases, except that transient fields will not be copied and objects with circular reference with cause StackOverflowError.

public static <ObjectType> ObjectType Copy(ObjectType AnObject, Class<ObjectType> ClassInfo)
{
    Gson gson = new GsonBuilder().create();
    String text = gson.toJson(AnObject);
    ObjectType newObject = gson.fromJson(text, ClassInfo);
    return newObject;
}
public static void main(String[] args)
{
    MyObject anObject ...
    MyObject copyObject = Copy(o, MyObject.class);

}

Add shadow to custom shape on Android

The following worked for me: Just save as custom_shape.xml.

<?xml version="1.0" encoding="utf-8"?>
<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

    <!-- "shadow" -->
    <item>
        <shape android:shape="rectangle" >
           <solid android:color="#000000"/>
           <corners android:radius="12dp" />
        </shape>
    </item>


    <item android:bottom="3px">
        <shape android:shape="rectangle"> 
            <solid android:color="#90ffffff"/>
            <corners android:radius="12dp" />
         </shape>
    </item>

</layer-list>

Elegant way to check for missing packages and install them?

This solution will take a character vector of package names and attempt to load them, or install them if loading fails. It relies on the return behaviour of require to do this because...

require returns (invisibly) a logical indicating whether the required package is available

Therefore we can simply see if we were able to load the required package and if not, install it with dependencies. So given a character vector of packages you wish to load...

foo <- function(x){
  for( i in x ){
    #  require returns TRUE invisibly if it was able to load package
    if( ! require( i , character.only = TRUE ) ){
      #  If package was not able to be loaded then re-install
      install.packages( i , dependencies = TRUE )
      #  Load package after installing
      require( i , character.only = TRUE )
    }
  }
}

#  Then try/install packages...
foo( c("ggplot2" , "reshape2" , "data.table" ) )

Cross browser JavaScript (not jQuery...) scroll to top animation

Another cross-browser approach based on above solution

function doScrollTo(to, duration) {
    var element = document.documentElement;

        var start = element.scrollTop,
        change = to - start,
        increment = 20,
        i = 0;

    var animateScroll = function(elapsedTime) {
        elapsedTime += increment;
        var position = easeInOut(elapsedTime, start, change, duration);
        if (i === 1 && window.scrollY === start) {
            element = document.body;
            start = element.scrollTop;
        }
        element.scrollTop = position;
        if (!i) i++;
        if (elapsedTime < duration) {
            setTimeout(function() {
                animateScroll(elapsedTime);
            }, increment);
        }
    };

    animateScroll(0);
}

The trick is to control the actual scroll change, and if it is zero, change the scroll element.

Virtualenv Command Not Found

I had the same problem for a long time. I solved it by running these two commands, first is to install second is to activate the env:

python3 -m pip install virtualenv
python3 -m virtualenv yourenvname

Note that I'm using python3, you can change it to just python if python3 fails. Thanks.

How do I rename the android package name?

If you want to rename full android package, this is the best way to do that:

  1. Mark as checked - Comapct Emty Middle Packages

  2. Right click on the packcage you want to change, and then Refactor->Rename->Rename all

You can find video tutorial on this link: https://www.youtube.com/watch?v=A-rITYZQj0A

What is a good way to handle exceptions when trying to read a file in python?

I guess I misunderstood what was being asked. Re-re-reading, it looks like Tim's answer is what you want. Let me just add this, however: if you want to catch an exception from open, then open has to be wrapped in a try. If the call to open is in the header of a with, then the with has to be in a try to catch the exception. There's no way around that.

So the answer is either: "Tim's way" or "No, you're doing it correctly.".


Previous unhelpful answer to which all the comments refer:

import os

if os.path.exists(fName):
   with open(fName, 'rb') as f:
       try:
           # do stuff
       except : # whatever reader errors you care about
           # handle error

How can I convert a DateTime to the number of seconds since 1970?

That's basically it. These are the methods I use to convert to and from Unix epoch time:

public static DateTime ConvertFromUnixTimestamp(double timestamp)
{
    DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
    return origin.AddSeconds(timestamp);
}

public static double ConvertToUnixTimestamp(DateTime date)
{
    DateTime origin = new DateTime(1970, 1, 1, 0, 0, 0, 0, DateTimeKind.Utc);
    TimeSpan diff = date.ToUniversalTime() - origin;
    return Math.Floor(diff.TotalSeconds);
}

Update: As of .Net Core 2.1 and .Net Standard 2.1 a DateTime equal to the Unix Epoch can be obtained from the static DateTime.UnixEpoch.

mailto link with HTML body

It's not quite what you want, but it's possible using modern javascript to create an EML file on the client and stream that to the user's file system, which should open a rich email containing HTML in their mail program, such as Outlook:

https://stackoverflow.com/a/27971771/8595398

Here's a jsfiddle of an email containing images and tables: https://jsfiddle.net/seanodotcom/yd1n8Lfh/

HTML

<!-- https://jsfiddle.net/seanodotcom/yd1n8Lfh -->
<textarea id="textbox" style="width: 300px; height: 600px;">
To: User <[email protected]>
Subject: Subject
X-Unsent: 1
Content-Type: text/html

<html>
<head>
<style>
    body, html, table {
        font-family: Calibri, Arial, sans-serif;
    }
    .pastdue { color: crimson; }
    table {
        border: 1px solid silver;
        padding: 6px;
    }
    thead {
        text-align: center;
        font-size: 1.2em;
        color: navy;
        background-color: silver;
        font-weight: bold;
    }
    tbody td {
        text-align: center;
    }
</style>
</head>
<body>
<table width=100%>
    <tr>
        <td><img src="http://www.laurell.com/images/logo/laurell_logo_storefront.jpg" width="200" height="57" alt=""></td>
        <td align="right"><h1><span class="pastdue">PAST DUE</span> INVOICE</h1></td>
    </tr>
</table>
<table width=100%>
    <thead>
        <th>Invoice #</th>
        <th>Days Overdue</th>
        <th>Amount Owed</th>
    </thead>
    <tbody>
    <tr>
        <td>OU812</td>
        <td>9</td>
        <td>$4395.00</td>
    </tr>
    <tr>
        <td>OU812</td>
        <td>9</td>
        <td>$4395.00</td>
    </tr>
    <tr>
        <td>OU812</td>
        <td>9</td>
        <td>$4395.00</td>
    </tr>
    </tbody>
</table>
</body>
</html>
</textarea> <br>
<button id="create">Create file</button><br><br>
<a download="message.eml" id="downloadlink" style="display: none">Download</a>

Javascript

(function () {
var textFile = null,
  makeTextFile = function (text) {
    var data = new Blob([text], {type: 'text/plain'});
    if (textFile !== null) {
      window.URL.revokeObjectURL(textFile);
    }
    textFile = window.URL.createObjectURL(data);
    return textFile;
  };

  var create = document.getElementById('create'),
    textbox = document.getElementById('textbox');
  create.addEventListener('click', function () {
    var link = document.getElementById('downloadlink');
    link.href = makeTextFile(textbox.value);
    link.style.display = 'block';
  }, false);
})();

Calling constructors in c++ without new

In append to JaredPar answer

1-usual ctor, 2nd-function-like-ctor with temporary object.

Compile this source somewhere here http://melpon.org/wandbox/ with different compilers

// turn off rvo for clang, gcc with '-fno-elide-constructors'

#include <stdio.h>
class Thing {
public:
    Thing(const char*){puts(__FUNCTION__ );}
    Thing(const Thing&){puts(__FUNCTION__ );}   
    ~Thing(){puts(__FUNCTION__);}
};
int main(int /*argc*/, const char** /*argv*/) {
    Thing myThing = Thing("asdf");
}

And you will see the result.

From ISO/IEC 14882 2003-10-15

8.5, part 12

Your 1st,2nd construction are called direct-initialization

12.1, part 13

A functional notation type conversion (5.2.3) can be used to create new objects of its type. [Note: The syntax looks like an explicit call of the constructor. ] ... An object created in this way is unnamed. [Note: 12.2 describes the lifetime of temporary objects. ] [Note: explicit constructor calls do not yield lvalues, see 3.10. ]


Where to read about RVO:

12 Special member functions / 12.8 Copying class objects/ Part 15

When certain criteria are met, an implementation is allowed to omit the copy construction of a class object, even if the copy constructor and/or destructor for the object have side effects.

Turn off it with compiler flag from comment to view such copy-behavior)

CSS how to make scrollable list

Another solution would be as below where the list is placed under a drop-down button.

  <button class="btn dropdown-toggle btn-primary btn-sm" data-toggle="dropdown"
    >Markets<span class="caret"></span></button>

    <ul class="dropdown-menu", style="height:40%; overflow:hidden; overflow-y:scroll;">
      {{ form.markets }}
    </ul>

How to redirect the output of a PowerShell to a file during its execution

If you want a straight redirect of all output to a file, try using *>>:

# You'll receive standard output for the first command, and an error from the second command.
mkdir c:\temp -force *>> c:\my.log ;
mkdir c:\temp *>> c:\my.log ;

Since this is a straight redirect to file, it won't output to the console (often helpful). If you desire the console output, combined all output with *&>1, and then pipe with Tee-Object:

mkdir c:\temp -force *>&1 | Tee-Object -Append -FilePath c:\my.log ;
mkdir c:\temp *>&1 | Tee-Object -Append -FilePath c:\my.log ;

# Shorter aliased version
mkdir c:\temp *>&1 | tee -Append c:\my.log ;

I believe these techniques are supported in PowerShell 3.0 or later; I'm testing on PowerShell 5.0.

What are sessions? How do they work?

Because HTTP is stateless, in order to associate a request to any other request, you need a way to store user data between HTTP requests.

Cookies or URL parameters ( for ex. like http://example.com/myPage?asd=lol&boo=no ) are both suitable ways to transport data between 2 or more request. However they are not good in case you don't want that data to be readable/editable on client side.

The solution is to store that data server side, give it an "id", and let the client only know (and pass back at every http request) that id. There you go, sessions implemented. Or you can use the client as a convenient remote storage, but you would encrypt the data and keep the secret server-side.

Of course there are other aspects to consider, like you don't want people to hijack other's sessions, you want sessions to not last forever but to expire, and so on.

In your specific example, the user id (could be username or another unique ID in your user database) is stored in the session data, server-side, after successful identification. Then for every HTTP request you get from the client, the session id (given by the client) will point you to the correct session data (stored by the server) that contains the authenticated user id - that way your code will know what user it is talking to.

How do I see active SQL Server connections?

Apart from sp_who, you can also use the "undocumented" sp_who2 system stored procedure which gives you more detailed information. See Difference between sp_who and sp_who2.

Python DNS module import error

ok to resolve this First install dns for python by cmd using pip install dnspython
(if you use conda first type activate and then you will go in base (in cmd) and then type above code) it will install it in anaconda site package ,copy the location of that site package folder from cmd, and open it . Now copy all dns folders and paste them in python site package folder. it will resolve it .

actually the thing is our code is not able to find the specified package in python\site package bcz it is in anaconda\site package. so you have to COPY IT (not cut).

How to generate keyboard events?

For both python3 and python2 you can use pyautogui (pip install pyautogui)

from pyautogui import press, typewrite, hotkey

press('a')
typewrite('quick brown fox')
hotkey('ctrl', 'w')

It's also crossplatform with Windows, OSX, and Ubuntu LTS.

Java - Check if JTextField is empty or not

Well, the code that renders the button enabled/disabled:

if(name.getText().equals("")) {
    loginbt.setEnabled(false);
}else {
    loginbt.setEnabled(true);
}

must be written in javax.swing.event.ChangeListener and attached to the field (see here). A change in field's value should trigger the listener to reevaluate the object state. What did you expect?

How do I clone a github project to run locally?

I use @Thiho answer but i get this error:

'git' is not recognized as an internal or external command

For solving that i use this steps:

I add the following paths to PATH:

  • C:\Program Files\Git\bin\

  • C:\Program Files\Git\cmd\

In windows 7:

  1. Right-click "Computer" on the Desktop or Start Menu.
  2. Select "Properties".
  3. On the very far left, click the "Advanced system settings" link.
  4. Click the "Environment Variables" button at the bottom.
  5. Double-click the "Path" entry under "System variables".
  6. At the end of "Variable value", insert a ; if there is not already one, and then C:\Program Files\Git\bin\;C:\Program Files\Git\cmd. Do not put a space between ; and the entry.

Finally close and re-open your console.

Python Matplotlib Y-Axis ticks on Right Side of Plot

Use ax.yaxis.tick_right()

for example:

from matplotlib import pyplot as plt

f = plt.figure()
ax = f.add_subplot(111)
ax.yaxis.tick_right()
plt.plot([2,3,4,5])
plt.show()

enter image description here

Checking if a textbox is empty in Javascript

function valid(id)
    {
        var textVal=document.getElementById(id).value;
        if (!textVal.match("Tryit") 
        {
            alert("Field says Tryit");
            return false;
        } 
        else 
        {
            return true;
        }
     }

Use this for expressing things

How can I programmatically freeze the top row of an Excel worksheet in Excel 2007 VBA?

Just hit the same problem... For some reason, the freezepanes command just caused crosshairs to appear in the centre of the screen. It turns oout I had switched ScreenUpdating off! Solved with the following code:

Application.ScreenUpdating = True
Cells(2, 1).Select
ActiveWindow.FreezePanes = True

Now it works fine.

Converting a sentence string to a string array of words in Java

Following is a code snippet which splits a sentense to word and give its count too.

 import java.util.HashMap;
 import java.util.Iterator;
 import java.util.Map;

 public class StringToword {
public static void main(String[] args) {
    String s="a a a A A";
    String[] splitedString=s.split(" ");
    Map m=new HashMap();
    int count=1;
    for(String s1 :splitedString){
         count=m.containsKey(s1)?count+1:1;
          m.put(s1, count);
        }
    Iterator<StringToword> itr=m.entrySet().iterator();
    while(itr.hasNext()){
        System.out.println(itr.next());         
    }
    }

}

Get img src with PHP

Use a HTML parser like DOMDocument and then evaluate the value you're looking for with DOMXpath:

$html = '<img id="12" border="0" src="/images/image.jpg"
         alt="Image" width="100" height="100" />';

$doc = new DOMDocument();
$doc->loadHTML($html);
$xpath = new DOMXPath($doc);
$src = $xpath->evaluate("string(//img/@src)"); # "/images/image.jpg"

Or for those who really need to save space:

$xpath = new DOMXPath(@DOMDocument::loadHTML($html));
$src = $xpath->evaluate("string(//img/@src)");

And for the one-liners out there:

$src = (string) reset(simplexml_import_dom(DOMDocument::loadHTML($html))->xpath("//img/@src"));

How to run Tensorflow on CPU

In some systems one have to specify:

import os
os.environ["CUDA_DEVICE_ORDER"]="PCI_BUS_ID"
os.environ["CUDA_VISIBLE_DEVICES"]=""  # or even "-1"

BEFORE importing tensorflow.

What do pty and tty mean?

A tty is a physical terminal-teletype port on a computer (usually a serial port).

The word teletype is a shorting of the telegraph typewriter, or teletypewriter device from the 1930s - itself an electromagnetic device which replaced the telegraph encoding machines of the 1830s and 1840s.

Teletypewriter
TTY - Teletypewriter 1930s

A pty is a pseudo-teletype port provided by a computer Operating System Kernel to connect software programs emulating terminals, such as ssh, xterm, or screen.

enter image description here
PTY - PseudoTeletype

A terminal is simply a computer's user interface that uses text for input and output.


OS Implementations

These use pseudo-teletype ports however, their naming and implementations have diverged a little.

Linux mounts a special file system devpts on /dev (the 's' presumably standing for serial) that creates a corresponding entry in /dev/pts for every new terminal window you open, e.g. /dev/pts/0


macOS/FreeBSD also use the /dev file structure however, they use a numbered TTY naming convention ttys for every new terminal window you open e.g. /dev/ttys002


Microsoft Windows still has the concept of an LPT port for Line Printer Terminals within it's Command Shell for output to a printer.

Setting Inheritance and Propagation flags with set-acl and powershell

Here's a table to help find the required flags for different permission combinations.

    +-----------------------------------------------------------------------------------------------------------------------------------------------------------+
    ¦             ¦ folder only ¦ folder, sub-folders and files ¦ folder and sub-folders ¦ folder and files ¦ sub-folders and files ¦ sub-folders ¦    files    ¦
    ¦-------------+-------------+-------------------------------+------------------------+------------------+-----------------------+-------------+-------------¦
    ¦ Propagation ¦ none        ¦ none                          ¦ none                   ¦ none             ¦ InheritOnly           ¦ InheritOnly ¦ InheritOnly ¦
    ¦ Inheritance ¦ none        ¦ Container|Object              ¦ Container              ¦ Object           ¦ Container|Object      ¦ Container   ¦ Object      ¦
    +-----------------------------------------------------------------------------------------------------------------------------------------------------------+

So, as David said, you'll want

InheritanceFlags.ContainerInherit | InheritanceFlags.ObjectInherit
PropagationFlags.None

Write applications in C or C++ for Android?

Native C/c++ Files libstdc++.* from your Ubuntu are x86 (or x86_64) binaries but Android devices and emulators are ARM. Of course, this will not work anyway, even if you'll set correct soname. This is very naive way which leads nowhere. Android has very limited support of C++ meaning there is no exceptions, standard C++ library (including STL) and RTTI. If you need such functionality, use my custom NDK distribution from

http://crystax.net/android/ndk.php - it support full C++ features listed above.

Why is there error: undefined reference to '__cxa_end_cleanup' link error. Android stlport

time. Because there is no link to libstdc + +. A. So wrong.

Because it uses some static library, it is necessary to link the full libstdc + +. A. Can

http://crystax.net/android/ndk.php here to download the package

sources \ cxx-stl \ gnu-libstdc + + \ libs \ armeabi directory.

Android on its own libstdc + + support is limited, it must be linked to a complete libstdc + +. A the job.

Add file in Android.mk LOCAL_LDFLAGS = $ (LOCAL_PATH) / libs / libcurl.a \

 $ (LOCAL_PATH) / libs / liblua.a \
 `$ (LOCAL_PATH) / libs / libstdc + +. A`  

And LOCAL_CPPFLAGS + =-lstdc + +-fexceptions can be compiled

How to get the path of src/test/resources directory in JUnit?

If it's a spring project, we can use the below code to get files from src/test/resource folder.

File file = ResourceUtils.getFile(this.getClass().getResource("/some_file.txt"));

Is there a good Valgrind substitute for Windows?

See the "Source Test Tools" link on the Software QA Testing and Test Tool Resources page for a list of similar tools.

I've used BoundsChecker,DevPartner Studio and Intel V-Tune in the past for profiling. I liked V-Tune the best; you could emulate various Intel chipsets and it would give you hints on how to optimize for that platform.

Simple http post example in Objective-C?

This is what I recently used, and it worked fine for me:

NSString *post = @"key1=val1&key2=val2";
NSData *postData = [post dataUsingEncoding:NSASCIIStringEncoding allowLossyConversion:YES];

NSString *postLength = [NSString stringWithFormat:@"%d", [postData length]];

NSMutableURLRequest *request = [[[NSMutableURLRequest alloc] init] autorelease];
[request setURL:[NSURL URLWithString:@"http://www.nowhere.com/sendFormHere.php"]];
[request setHTTPMethod:@"POST"];
[request setValue:postLength forHTTPHeaderField:@"Content-Length"];
[request setValue:@"application/x-www-form-urlencoded" forHTTPHeaderField:@"Content-Type"];
[request setHTTPBody:postData];

Originally taken from http://deusty.blogspot.com/2006/11/sending-http-get-and-post-from-cocoa.html, but that blog does not seem to exist anymore.

How do I change the background of a Frame in Tkinter?

The root of the problem is that you are unknowingly using the Frame class from the ttk package rather than from the tkinter package. The one from ttk does not support the background option.

This is the main reason why you shouldn't do global imports -- you can overwrite the definition of classes and commands.

I recommend doing imports like this:

import tkinter as tk
import ttk

Then you prefix the widgets with either tk or ttk :

f1 = tk.Frame(..., bg=..., fg=...)
f2 = ttk.Frame(..., style=...)

It then becomes instantly obvious which widget you are using, at the expense of just a tiny bit more typing. If you had done this, this error in your code would never have happened.

How to switch from POST to GET in PHP CURL

CURL request by default is GET, you don't have to set any options to make a GET CURL request.

How to colorize diff on the command line?

Use Vim:

diff /path/to/a /path/to/b | vim -R -

Or better still, VimDiff (or vim -d, which is shorter to type) will show differences between two, three or four files side-by-side.

Examples:

vim -d /path/to/[ab]

vimdiff file1 file2 file3 file4

Composer install error - requires ext_curl when it's actually enabled

I have Archlinux with php 7.2, which has Curl integrated, so no amount of configuration voodoo would make Composer see ext-curl, that PHP could see and work with happily. Work around is to use Composer with --ignore-platform-reqs.

eg composer update --ignore-platform-reqs

Reference = https://github.com/composer/composer/issues/1426

How to have the cp command create any necessary folders for copying a file to a destination

cp -Rvn /source/path/* /destination/path/
cp: /destination/path/any.zip: No such file or directory

It will create no existing paths in destination, if path have a source file inside. This dont create empty directories.

A moment ago i've seen xxxxxxxx: No such file or directory, because i run out of free space. without error message.

with ditto:

ditto -V /source/path/* /destination/path
ditto: /destination/path/any.zip: No space left on device

once freed space cp -Rvn /source/path/* /destination/path/ works as expected

How to copy Outlook mail message into excel using VBA or Macros

New introduction 2

In the previous version of macro "SaveEmailDetails" I used this statement to find Inbox:

Set FolderTgt = CreateObject("Outlook.Application"). _
              GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)

I have since installed a newer version of Outlook and I have discovered that it does not use the default Inbox. For each of my email accounts, it created a separate store (named for the email address) each with its own Inbox. None of those Inboxes is the default.

This macro, outputs the name of the store holding the default Inbox to the Immediate Window:

Sub DsplUsernameOfDefaultStore()

  Dim NS As Outlook.NameSpace
  Dim DefaultInboxFldr As MAPIFolder

  Set NS = CreateObject("Outlook.Application").GetNamespace("MAPI")
  Set DefaultInboxFldr = NS.GetDefaultFolder(olFolderInbox)

  Debug.Print DefaultInboxFldr.Parent.Name

End Sub

On my installation, this outputs: "Outlook Data File".

I have added an extra statement to macro "SaveEmailDetails" that shows how to access the Inbox of any store.

New introduction 1

A number of people have picked up the macro below, found it useful and have contacted me directly for further advice. Following these contacts I have made a few improvements to the macro so I have posted the revised version below. I have also added a pair of macros which together will return the MAPIFolder object for any folder with the Outlook hierarchy. These are useful if you wish to access other than a default folder.

The original text referenced one question by date which linked to an earlier question. The first question has been deleted so the link has been lost. That link was to Update excel sheet based on outlook mail (closed)

Original text

There are a surprising number of variations of the question: "How do I extract data from Outlook emails to Excel workbooks?" For example, two questions up on [outlook-vba] the same question was asked on 13 August. That question references a variation from December that I attempted to answer.

For the December question, I went overboard with a two part answer. The first part was a series of teaching macros that explored the Outlook folder structure and wrote data to text files or Excel workbooks. The second part discussed how to design the extraction process. For this question Siddarth has provided an excellent, succinct answer and then a follow-up to help with the next stage.

What the questioner of every variation appears unable to understand is that showing us what the data looks like on the screen does not tell us what the text or html body looks like. This answer is an attempt to get past that problem.

The macro below is more complicated than Siddarth’s but a lot simpler that those I included in my December answer. There is more that could be added but I think this is enough to start with.

The macro creates a new Excel workbook and outputs selected properties of every email in Inbox to create this worksheet:

Example of worksheet created by macro

Near the top of the macro there is a comment containing eight hashes (#). The statement below that comment must be changed because it identifies the folder in which the Excel workbook will be created.

All other comments containing hashes suggest amendments to adapt the macro to your requirements.

How are the emails from which data is to be extracted identified? Is it the sender, the subject, a string within the body or all of these? The comments provide some help in eliminating uninteresting emails. If I understand the question correctly, an interesting email will have Subject = "Task Completed".

The comments provide no help in extracting data from interesting emails but the worksheet shows both the text and html versions of the email body if they are present. My idea is that you can see what the macro will see and start designing the extraction process.

This is not shown in the screen image above but the macro outputs two versions on the text body. The first version is unchanged which means tab, carriage return, line feed are obeyed and any non-break spaces look like spaces. In the second version, I have replaced these codes with the strings [TB], [CR], [LF] and [NBSP] so they are visible. If my understanding is correct, I would expect to see the following within the second text body:

Activity[TAB]Count[CR][LF]Open[TAB]35[CR][LF]HCQA[TAB]42[CR][LF]HCQC[TAB]60[CR][LF]HAbst[TAB]50 45 5 2 2 1[CR][LF] and so on

Extracting the values from the original of this string should not be difficult.

I would try amending my macro to output the extracted values in addition to the email’s properties. Only when I have successfully achieved this change would I attempt to write the extracted data to an existing workbook. I would also move processed emails to a different folder. I have shown where these changes must be made but give no further help. I will respond to a supplementary question if you get to the point where you need this information.

Good luck.

Latest version of macro included within the original text

Option Explicit
Public Sub SaveEmailDetails()

  ' This macro creates a new Excel workbook and writes to it details
  ' of every email in the Inbox.

  ' Lines starting with hashes either MUST be changed before running the
  ' macro or suggest changes you might consider appropriate.

  Dim AttachCount As Long
  Dim AttachDtl() As String
  Dim ExcelWkBk As Excel.Workbook
  Dim FileName As String
  Dim FolderTgt As MAPIFolder
  Dim HtmlBody As String
  Dim InterestingItem As Boolean
  Dim InxAttach As Long
  Dim InxItemCrnt As Long
  Dim PathName As String
  Dim ReceivedTime As Date
  Dim RowCrnt As Long
  Dim SenderEmailAddress As String
  Dim SenderName As String
  Dim Subject As String
  Dim TextBody As String
  Dim xlApp As Excel.Application

  ' The Excel workbook will be created in this folder.
  ' ######## Replace "C:\DataArea\SO" with the name of a folder on your disc.
  PathName = "C:\DataArea\SO"

  ' This creates a unique filename.
  ' #### If you use a version of Excel 2003, change the extension to "xls".
  FileName = Format(Now(), "yymmdd hhmmss") & ".xlsx"

  ' Open own copy of Excel
  Set xlApp = Application.CreateObject("Excel.Application")
  With xlApp
    ' .Visible = True         ' This slows your macro but helps during debugging
    .ScreenUpdating = False ' Reduces flash and increases speed
    ' Create a new workbook
    ' #### If updating an existing workbook, replace with an
    ' #### Open workbook statement.
    Set ExcelWkBk = xlApp.Workbooks.Add
    With ExcelWkBk
      ' #### None of this code will be useful if you are adding
      ' #### to an existing workbook.  However, it demonstrates a
      ' #### variety of useful statements.
      .Worksheets("Sheet1").Name = "Inbox"    ' Rename first worksheet
      With .Worksheets("Inbox")
        ' Create header line
        With .Cells(1, "A")
          .Value = "Field"
          .Font.Bold = True
        End With
        With .Cells(1, "B")
          .Value = "Value"
          .Font.Bold = True
        End With
        .Columns("A").ColumnWidth = 18
        .Columns("B").ColumnWidth = 150
      End With
    End With
    RowCrnt = 2
  End With

  ' FolderTgt is the folder I am going to search.  This statement says
  ' I want to seach the Inbox.  The value "olFolderInbox" can be replaced
  ' to allow any of the standard folders to be searched.
  ' See FindSelectedFolder() for a routine that will search for any folder.
  Set FolderTgt = CreateObject("Outlook.Application"). _
              GetNamespace("MAPI").GetDefaultFolder(olFolderInbox)
  ' #### Use the following the access a non-default Inbox.
  ' #### Change "Xxxx" to name of one of your store you want to access.
  Set FolderTgt = Session.Folders("Xxxx").Folders("Inbox")

  ' This examines the emails in reverse order. I will explain why later.
  For InxItemCrnt = FolderTgt.Items.Count To 1 Step -1
    With FolderTgt.Items.Item(InxItemCrnt)
      ' A folder can contain several types of item: mail items, meeting items,
      ' contacts, etc.  I am only interested in mail items.
      If .Class = olMail Then
        ' Save selected properties to variables
        ReceivedTime = .ReceivedTime
        Subject = .Subject
        SenderName = .SenderName
        SenderEmailAddress = .SenderEmailAddress
        TextBody = .Body
        HtmlBody = .HtmlBody
        AttachCount = .Attachments.Count
        If AttachCount > 0 Then
          ReDim AttachDtl(1 To 7, 1 To AttachCount)
          For InxAttach = 1 To AttachCount
            ' There are four types of attachment:
            '  *   olByValue       1
            '  *   olByReference   4
            '  *   olEmbeddedItem  5
            '  *   olOLE           6
            Select Case .Attachments(InxAttach).Type
              Case olByValue
            AttachDtl(1, InxAttach) = "Val"
              Case olEmbeddeditem
            AttachDtl(1, InxAttach) = "Ebd"
              Case olByReference
            AttachDtl(1, InxAttach) = "Ref"
              Case olOLE
            AttachDtl(1, InxAttach) = "OLE"
              Case Else
            AttachDtl(1, InxAttach) = "Unk"
            End Select
            ' Not all types have all properties.  This code handles
            ' those missing properties of which I am aware.  However,
            ' I have never found an attachment of type Reference or OLE.
            ' Additional code may be required for them.
            Select Case .Attachments(InxAttach).Type
              Case olEmbeddeditem
                AttachDtl(2, InxAttach) = ""
              Case Else
                AttachDtl(2, InxAttach) = .Attachments(InxAttach).PathName
            End Select
            AttachDtl(3, InxAttach) = .Attachments(InxAttach).FileName
            AttachDtl(4, InxAttach) = .Attachments(InxAttach).DisplayName
            AttachDtl(5, InxAttach) = "--"
            ' I suspect Attachment had a parent property in early versions
            ' of Outlook. It is missing from Outlook 2016.
            On Error Resume Next
            AttachDtl(5, InxAttach) = .Attachments(InxAttach).Parent
            On Error GoTo 0
            AttachDtl(6, InxAttach) = .Attachments(InxAttach).Position
            ' Class 5 is attachment.  I have never seen an attachment with
            ' a different class and do not see the purpose of this property.
            ' The code will stop here if a different class is found.
            Debug.Assert .Attachments(InxAttach).Class = 5
            AttachDtl(7, InxAttach) = .Attachments(InxAttach).Class
          Next
        End If
        InterestingItem = True
      Else
        InterestingItem = False
      End If
    End With
    ' The most used properties of the email have been loaded to variables but
    ' there are many more properies.  Press F2.  Scroll down classes until
    ' you find MailItem.  Look through the members and note the name of
    ' any properties that look useful.  Look them up using VB Help.

    ' #### You need to add code here to eliminate uninteresting items.
    ' #### For example:
    'If SenderEmailAddress <> "[email protected]" Then
    '  InterestingItem = False
    'End If
    'If InStr(Subject, "Accounts payable") = 0 Then
    '  InterestingItem = False
    'End If
    'If AttachCount = 0 Then
    '  InterestingItem = False
    'End If

    ' #### If the item is still thought to be interesting I
    ' #### suggest extracting the required data to variables here.

    ' #### You should consider moving processed emails to another
    ' #### folder.  The emails are being processed in reverse order
    ' #### to allow this removal of an email from the Inbox without
    ' #### effecting the index numbers of unprocessed emails.

    If InterestingItem Then
      With ExcelWkBk
        With .Worksheets("Inbox")
          ' #### This code creates a dividing row and then
          ' #### outputs a property per row.  Again it demonstrates
          ' #### statements that are likely to be useful in the final
          ' #### version
          ' Create dividing row between emails
          .Rows(RowCrnt).RowHeight = 5
          .Range(.Cells(RowCrnt, "A"), .Cells(RowCrnt, "B")) _
                                      .Interior.Color = RGB(0, 255, 0)
          RowCrnt = RowCrnt + 1
          .Cells(RowCrnt, "A").Value = "Sender name"
          .Cells(RowCrnt, "B").Value = SenderName
          RowCrnt = RowCrnt + 1
          .Cells(RowCrnt, "A").Value = "Sender email address"
          .Cells(RowCrnt, "B").Value = SenderEmailAddress
          RowCrnt = RowCrnt + 1
          .Cells(RowCrnt, "A").Value = "Received time"
          With .Cells(RowCrnt, "B")
            .NumberFormat = "@"
            .Value = Format(ReceivedTime, "mmmm d, yyyy h:mm")
          End With
          RowCrnt = RowCrnt + 1
          .Cells(RowCrnt, "A").Value = "Subject"
          .Cells(RowCrnt, "B").Value = Subject
          RowCrnt = RowCrnt + 1
          If AttachCount > 0 Then
            .Cells(RowCrnt, "A").Value = "Attachments"
            .Cells(RowCrnt, "B").Value = "Inx|Type|Path name|File name|Display name|Parent|Position|Class"
            RowCrnt = RowCrnt + 1
            For InxAttach = 1 To AttachCount
              .Cells(RowCrnt, "B").Value = InxAttach & "|" & _
                                           AttachDtl(1, InxAttach) & "|" & _
                                           AttachDtl(2, InxAttach) & "|" & _
                                           AttachDtl(3, InxAttach) & "|" & _
                                           AttachDtl(4, InxAttach) & "|" & _
                                           AttachDtl(5, InxAttach) & "|" & _
                                           AttachDtl(6, InxAttach) & "|" & _
                                           AttachDtl(7, InxAttach)
              RowCrnt = RowCrnt + 1
            Next
          End If
          If TextBody <> "" Then

            ' ##### This code was in the original version of the macro
            ' ##### but I did not find it as useful as the other version of
            ' ##### the text body.  See below
            ' This outputs the text body with CR, LF and TB obeyed
            'With .Cells(RowCrnt, "A")
            '  .Value = "text body"
            '  .VerticalAlignment = xlTop
            'End With
            'With .Cells(RowCrnt, "B")
            '  ' The maximum size of a cell 32,767
            '  .Value = Mid(TextBody, 1, 32700)
            '  .WrapText = True
            'End With
            'RowCrnt = RowCrnt + 1

            ' This outputs the text body with NBSP, CR, LF and TB
            ' replaced by strings.
            With .Cells(RowCrnt, "A")
              .Value = "text body"
              .VerticalAlignment = xlTop
            End With
            TextBody = Replace(TextBody, Chr(160), "[NBSP]")
            TextBody = Replace(TextBody, vbCr, "[CR]")
            TextBody = Replace(TextBody, vbLf, "[LF]")
            TextBody = Replace(TextBody, vbTab, "[TB]")
            With .Cells(RowCrnt, "B")
              ' The maximum size of a cell 32,767
              .Value = Mid(TextBody, 1, 32700)
              .WrapText = True
            End With
            RowCrnt = RowCrnt + 1
          End If

          If HtmlBody <> "" Then

            ' ##### This code was in the original version of the macro
            ' ##### but I did not find it as useful as the other version of
            ' ##### the html body.  See below
            ' This outputs the html body with CR, LF and TB obeyed
            'With .Cells(RowCrnt, "A")
            '  .Value = "Html body"
            '  .VerticalAlignment = xlTop
            'End With
            'With .Cells(RowCrnt, "B")
            '  .Value = Mid(HtmlBody, 1, 32700)
            '  .WrapText = True
            'End With
            'RowCrnt = RowCrnt + 1

            ' This outputs the html body with NBSP, CR, LF and TB
            ' replaced by strings.
            With .Cells(RowCrnt, "A")
              .Value = "Html body"
              .VerticalAlignment = xlTop
            End With
            HtmlBody = Replace(HtmlBody, Chr(160), "[NBSP]")
            HtmlBody = Replace(HtmlBody, vbCr, "[CR]")
            HtmlBody = Replace(HtmlBody, vbLf, "[LF]")
            HtmlBody = Replace(HtmlBody, vbTab, "[TB]")
            With .Cells(RowCrnt, "B")
              .Value = Mid(HtmlBody, 1, 32700)
              .WrapText = True
            End With
            RowCrnt = RowCrnt + 1

          End If
        End With
      End With
    End If
  Next

  With xlApp
    With ExcelWkBk
      ' Write new workbook to disc
      If Right(PathName, 1) <> "\" Then
        PathName = PathName & "\"
      End If
      .SaveAs FileName:=PathName & FileName
      .Close
    End With
    .Quit   ' Close our copy of Excel
  End With

  Set xlApp = Nothing       ' Clear reference to Excel

End Sub

Macros not included in original post but which some users of above macro have found useful.

Public Sub FindSelectedFolder(ByRef FolderTgt As MAPIFolder, _
                              ByVal NameTgt As String, ByVal NameSep As String)

  ' This routine (and its sub-routine) locate a folder within the hierarchy and
  ' returns it as an object of type MAPIFolder

  ' NameTgt   The name of the required folder in the format:
  '              FolderName1 NameSep FolderName2 [ NameSep FolderName3 ] ...
  '           If NameSep is "|", an example value is "Personal Folders|Inbox"
  '           FolderName1 must be an outer folder name such as
  '           "Personal Folders". The outer folder names are typically the names
  '           of PST files.  FolderName2 must be the name of a folder within
  '           Folder1; in the example "Inbox".  FolderName2 is compulsory.  This
  '           routine cannot return a PST file; only a folder within a PST file.
  '           FolderName3, FolderName4 and so on are optional and allow a folder
  '           at any depth with the hierarchy to be specified.
  ' NameSep   A character or string used to separate the folder names within
  '           NameTgt.
  ' FolderTgt On exit, the required folder.  Set to Nothing if not found.

  ' This routine initialises the search and finds the top level folder.
  ' FindSelectedSubFolder() is used to find the target folder within the
  ' top level folder.

  Dim InxFolderCrnt As Long
  Dim NameChild As String
  Dim NameCrnt As String
  Dim Pos As Long
  Dim TopLvlFolderList As Folders

  Set FolderTgt = Nothing   ' Target folder not found

  Set TopLvlFolderList = _
          CreateObject("Outlook.Application").GetNamespace("MAPI").Folders

  ' Split NameTgt into the name of folder at current level
  ' and the name of its children
  Pos = InStr(NameTgt, NameSep)
  If Pos = 0 Then
    ' I need at least a level 2 name
    Exit Sub
  End If
  NameCrnt = Mid(NameTgt, 1, Pos - 1)
  NameChild = Mid(NameTgt, Pos + 1)

  ' Look for current name.  Drop through and return nothing if name not found.
  For InxFolderCrnt = 1 To TopLvlFolderList.Count
    If NameCrnt = TopLvlFolderList(InxFolderCrnt).Name Then
      ' Have found current name. Call FindSelectedSubFolder() to
      ' look for its children
      Call FindSelectedSubFolder(TopLvlFolderList.Item(InxFolderCrnt), _
                                            FolderTgt, NameChild, NameSep)
      Exit For
    End If
  Next

End Sub
Public Sub FindSelectedSubFolder(FolderCrnt As MAPIFolder, _
                      ByRef FolderTgt As MAPIFolder, _
                      ByVal NameTgt As String, ByVal NameSep As String)

  ' See FindSelectedFolder() for an introduction to the purpose of this routine.
  ' This routine finds all folders below the top level

  ' FolderCrnt The folder to be seached for the target folder.
  ' NameTgt    The NameTgt passed to FindSelectedFolder will be of the form:
  '               A|B|C|D|E
  '            A is the name of outer folder which represents a PST file.
  '            FindSelectedFolder() removes "A|" from NameTgt and calls this
  '            routine with FolderCrnt set to folder A to search for B.
  '            When this routine finds B, it calls itself with FolderCrnt set to
  '            folder B to search for C.  Calls are nested to whatever depth are
  '            necessary.
  ' NameSep    As for FindSelectedSubFolder
  ' FolderTgt  As for FindSelectedSubFolder

  Dim InxFolderCrnt As Long
  Dim NameChild As String
  Dim NameCrnt As String
  Dim Pos As Long

  ' Split NameTgt into the name of folder at current level
  ' and the name of its children
  Pos = InStr(NameTgt, NameSep)
  If Pos = 0 Then
    NameCrnt = NameTgt
    NameChild = ""
  Else
    NameCrnt = Mid(NameTgt, 1, Pos - 1)
    NameChild = Mid(NameTgt, Pos + 1)
  End If

  ' Look for current name.  Drop through and return nothing if name not found.
  For InxFolderCrnt = 1 To FolderCrnt.Folders.Count
    If NameCrnt = FolderCrnt.Folders(InxFolderCrnt).Name Then
      ' Have found current name.
      If NameChild = "" Then
        ' Have found target folder
        Set FolderTgt = FolderCrnt.Folders(InxFolderCrnt)
      Else
        'Recurse to look for children
        Call FindSelectedSubFolder(FolderCrnt.Folders(InxFolderCrnt), _
                                            FolderTgt, NameChild, NameSep)
      End If
      Exit For
    End If
  Next

  ' If NameCrnt not found, FolderTgt will be returned unchanged.  Since it is
  ' initialised to Nothing at the beginning, that will be the returned value.

End Sub

How to include CSS file in Symfony 2 and Twig?

And you can use %stylesheets% (assetic feature) tag:

{% stylesheets
    "@MainBundle/Resources/public/colorbox/colorbox.css"
    "%kerner.root_dir%/Resources/css/main.css"
%}
<link type="text/css" rel="stylesheet" media="all" href="{{ asset_url }}" />
{% endstylesheets %}

You can write path to css as parameter (%parameter_name%).

More about this variant: http://symfony.com/doc/current/cookbook/assetic/asset_management.html

Check whether variable is number or string in JavaScript

function IsNumeric(num) {
    return ((num >=0 || num < 0)&& (parseInt(num)==num) );
}

fatal error: mpi.h: No such file or directory #include <mpi.h>

Debian appears to include the following:

  • mpiCC.openmpi
  • mpic++.openmpi
  • mpicc.openmpi
  • mpicxx.openmpi
  • mpif77.openmpi
  • mpif90.openmpi

I'll test symlinks of each for mpic, etc., and see if that helps the likes of HDF5-openmpi enabled find mpi.h.

Take that back Debian includes symlinks via their alternatives system and it still cannot find the proper paths between HDF5 openmpi packages and mpi.h referenced in the H5public.h header.

elasticsearch bool query combine must with OR

This is how you can nest multiple bool queries in one outer bool query this using Kibana,

  • bool indicates we are using boolean
  • must is for AND
  • should is for OR
GET my_inedx/my_type/_search
{
  "query" : {
     "bool": {             //bool indicates we are using boolean operator
          "must" : [       //must is for **AND**
               {
                 "match" : {
                       "description" : "some text"  
                   }
               },
               {
                  "match" :{
                        "type" : "some Type"
                   }
               },
               {
                  "bool" : {          //here its a nested boolean query
                        "should" : [  //should is for **OR**
                               {
                                 "match" : {
                                     //ur query
                                }
                               },
                               { 
                                  "match" : {} 
                               }     
                             ]
                        }
               }
           ]
      }
  }
}

This is how you can nest a query in ES


There are more types in "bool" like,

  1. Filter
  2. must_not

Android: adb: Permission Denied

Run your cmd as administrator this will solve my issues. Thanks.

How to get the anchor from the URL using jQuery?

For current window, you can use this:

var hash = window.location.hash.substr(1);

To get the hash value of the main window, use this:

var hash = window.top.location.hash.substr(1);

If you have a string with an URL/hash, the easiest method is:

var url = 'https://www.stackoverflow.com/questions/123/abc#10076097';
var hash = url.split('#').pop();

If you're using jQuery, use this:

var hash = $(location).attr('hash');

How can I limit ngFor repeat to some number of items in Angular?

This seems simpler to me

<li *ngFor="let item of list | slice:0:10; let i=index" class="dropdown-item" (click)="onClick(item)">{{item.text}}</li>

Closer to your approach

<ng-container *ngFor="let item of list" let-i="index">
  <li class="dropdown-item" (click)="onClick(item)" *ngIf="i<11">{{item.text}}</li>
</ng-container>

Get value from a string after a special character

Here's a way:

<html>
    <head>
        <script src="jquery-1.4.2.min.js" type="text/javascript"></script>
        <script type="text/javascript">
            $(document).ready(function(){
                var value = $('input[type="hidden"]')[0].value;
                alert(value.split(/\?/)[1]);
            });
        </script>
    </head>
    <body>
        <input type="hidden" value="/TEST/Name?3" />
    </body>
</html>

Why call git branch --unset-upstream to fixup?

Actually torek told you already how to use the tools much better than I would be able to do. However, in this case I think it is important to point out something peculiar if you follow the guidelines at http://octopress.org/docs/deploying/github/. Namely, you will have multiple github repositories in your setup. First of all the one with all the source code for your website in say the directory $WEBSITE, and then the one with only the static generated files residing in $WEBSITE/_deploy. The funny thing of the setup is that there is a .gitignore file in the $WEBSITE directory so that this setup actually works.

Enough introduction. In this case the error might also come from the repository in _deploy.

cd _deploy

git branch -a
* master
remotes/origin/master
remotes/origin/source

In .git/config you will normally need to find something like this:

[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
[remote "origin"]
    url = [email protected]:yourname/yourname.github.io.git
    fetch = +refs/heads/*:refs/remotes/origin/*
[branch "master"]
    remote = origin
    merge = refs/heads/master

But in your case the branch master does not have a remote.

[core]
    repositoryformatversion = 0
    filemode = true
    bare = false
    logallrefupdates = true
[remote "origin"]
    url = [email protected]:yourname/yourname.github.io.git
    fetch = +refs/heads/*:refs/remotes/origin/*

Which you can solve by:

cd _deploy
git branch --set-upstream-to=origin/master

So, everything is as torek told you, but it might be important to point out that this very well might concern the _deploy directory rather than the root of your website.

PS: It might be worth to use a shell such as zsh with a git plugin to not be bitten by this thing in the future. It will immediately show that _deploy concerns a different repository.

PHP script to loop through all of the files in a directory?

You can also make use of FilesystemIterator. It requires even less code then DirectoryIterator, and automatically removes . and ...

// Let's traverse the images directory
$fileSystemIterator = new FilesystemIterator('images');

$entries = array();
foreach ($fileSystemIterator as $fileInfo){
    $entries[] = $fileInfo->getFilename();
}

var_dump($entries);

//OUTPUT
object(FilesystemIterator)[1]

array (size=14)
  0 => string 'aa[1].jpg' (length=9)
  1 => string 'Chrysanthemum.jpg' (length=17)
  2 => string 'Desert.jpg' (length=10)
  3 => string 'giphy_billclinton_sad.gif' (length=25)
  4 => string 'giphy_shut_your.gif' (length=19)
  5 => string 'Hydrangeas.jpg' (length=14)
  6 => string 'Jellyfish.jpg' (length=13)
  7 => string 'Koala.jpg' (length=9)
  8 => string 'Lighthouse.jpg' (length=14)
  9 => string 'Penguins.jpg' (length=12)
  10 => string 'pnggrad16rgb.png' (length=16)
  11 => string 'pnggrad16rgba.png' (length=17)
  12 => string 'pnggradHDrgba.png' (length=17)
  13 => string 'Tulips.jpg' (length=10)

Link: http://php.net/manual/en/class.filesystemiterator.php

How to create a density plot in matplotlib?

Option 1:

Use pandas dataframe plot (built on top of matplotlib):

import pandas as pd
data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8
pd.DataFrame(data).plot(kind='density') # or pd.Series()

enter image description here

Option 2:

Use distplot of seaborn:

import seaborn as sns
data = [1.5]*7 + [2.5]*2 + [3.5]*8 + [4.5]*3 + [5.5]*1 + [6.5]*8
sns.distplot(data, hist=False)

enter image description here

How to set ANDROID_HOME path in ubuntu?

In the console just type these :

export ANDROID_HOME=$HOME/Android/Sdk
export PATH=$PATH:$ANDROID_HOME/tools

If you want to make it permanent just add those lines in the ~/.bashrc file

Disable activity slide-in animation when launching new activity?

In order to avoid the black background when starting an activity already in the stack, I added overridePendingTransition(0,0) in onStart():

@Override
protected void onStart() {
    overridePendingTransition(0,0);
    super.onStart();

}

How to clear browsing history using JavaScript?

It's not possible to clear user history without plugins. And also it's not an issue at developer's perspective, it's the burden of the user to clear his history.

For information refer to How to clear browsers (IE, Firefox, Opera, Chrome) history using JavaScript or Java except from browser itself?

Reading and displaying data from a .txt file

In Java 8, you can read a whole file, simply with:

public String read(String file) throws IOException {
  return new String(Files.readAllBytes(Paths.get(file)));
}

or if its a Resource:

public String read(String file) throws IOException {
  URL url = Resources.getResource(file);
  return Resources.toString(url, Charsets.UTF_8);
}

Can't perform a React state update on an unmounted component

I had a similar issue thanks @ford04 helped me out.

However, another error occurred.

NB. I am using ReactJS hooks

ndex.js:1 Warning: Cannot update during an existing state transition (such as within `render`). Render methods should be a pure function of props and state.

What causes the error?

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

const History = useHistory()
if (true) {
  history.push('/new-route');
}
return (
  <>
    <render component />
  </>
)

This could not work because despite you are redirecting to new page all state and props are being manipulated on the dom or simply rendering to the previous page did not stop.

What solution I found

import {Redirect} from 'react-router-dom'

if (true) {
  return <redirect to="/new-route" />
}
return (
  <>
    <render component />
  </>
)

jQuery - What are differences between $(document).ready and $(window).load?

From the jQuery API Document

While JavaScript provides the load event for executing code when a page is rendered, this event does not get triggered until all assets such as images have been completely received. In most cases, the script can be run as soon as the DOM hierarchy has been fully constructed. The handler passed to .ready() is guaranteed to be executed after the DOM is ready, so this is usually the best place to attach all other event handlers and run other jQuery code. When using scripts that rely on the value of CSS style properties, it's important to reference external stylesheets or embed style elements before referencing the scripts.

In cases where code relies on loaded assets (for example, if the dimensions of an image are required), the code should be placed in a handler for the load event instead.


Answer to the second question -

No, they are identical as long as you are not using jQuery in no conflict mode.

Get selected value/text from Select on change

If you're googling this, and don't want the event listener to be an attribute, use:

_x000D_
_x000D_
document.getElementById('my-select').addEventListener('change', function() {_x000D_
  console.log('You selected: ', this.value);_x000D_
});
_x000D_
<select id="my-select">_x000D_
  <option value="1">One</option>_x000D_
  <option value="2">Two</option>_x000D_
  <option value="3">Three</option>_x000D_
</select>
_x000D_
_x000D_
_x000D_

move column in pandas dataframe

An alternative, more generic method;

from pandas import DataFrame


def move_columns(df: DataFrame, cols_to_move: list, new_index: int) -> DataFrame:
    """
    This method re-arranges the columns in a dataframe to place the desired columns at the desired index.
    ex Usage: df = move_columns(df, ['Rev'], 2)   
    :param df:
    :param cols_to_move: The names of the columns to move. They must be a list
    :param new_index: The 0-based location to place the columns.
    :return: Return a dataframe with the columns re-arranged
    """
    other = [c for c in df if c not in cols_to_move]
    start = other[0:new_index]
    end = other[new_index:]
    return df[start + cols_to_move + end]

Visual Studio Code - Target of URI doesn't exist 'package:flutter/material.dart'

I didn't think this was possible: I had to delete flutter folder and reinstall it from scratch!

Python RuntimeWarning: overflow encountered in long scalars

An easy way to overcome this problem is to use 64 bit type

list = numpy.array(list, dtype=numpy.float64)

Java file path in Linux

Looks like you are missing a leading slash. Perhaps try:

Scanner s = new Scanner(new File("/home/me/java/ex.txt"));

(as to where it looks for files by default, it is where the JVM is run from for relative paths like the one you have in your question)

How to style the parent element when hovering a child element?

I know it is an old question, but I just managed to do so without a pseudo child (but a pseudo wrapper).

If you set the parent to be with no pointer-events, and then a child div with pointer-events set to auto, it works:)
Note that <img> tag (for example) doesn't do the trick.
Also remember to set pointer-events to auto for other children which have their own event listener, or otherwise they will lose their click functionality.

_x000D_
_x000D_
div.parent {  _x000D_
    pointer-events: none;_x000D_
}_x000D_
_x000D_
div.child {_x000D_
    pointer-events: auto;_x000D_
}_x000D_
_x000D_
div.parent:hover {_x000D_
    background: yellow;_x000D_
}    
_x000D_
<div class="parent">_x000D_
  parent - you can hover over here and it won't trigger_x000D_
  <div class="child">hover over the child instead!</div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Edit:
As Shadow Wizard kindly noted: it's worth to mention this won't work for IE10 and below. (Old versions of FF and Chrome too, see here)

how to add picasso library in android studio

easiest way to add dependence

hope this help you or Ctrl + Alt + Shift + S => select Dependencies tab and find what you need ( see my image)

How to correct TypeError: Unicode-objects must be encoded before hashing?

The error already says what you have to do. MD5 operates on bytes, so you have to encode Unicode string into bytes, e.g. with line.encode('utf-8').

Meaning of numbers in "col-md-4"," col-xs-1", "col-lg-2" in Bootstrap

From Twitter Bootstrap documentation:

  • small grid (= 768px) = .col-sm-*,
  • medium grid (= 992px) = .col-md-*,
  • large grid (= 1200px) = .col-lg-*.

to Read More...

PHP cURL HTTP CODE return 0

check the curl_error after the curl_getinfo to find out the hidden errors.

if(curl_errno($ch)){   
    echo 'Curl error: ' . curl_error($ch);
}

Frequency table for a single variable

The answer provided by @DSM is simple and straightforward, but I thought I'd add my own input to this question. If you look at the code for pandas.value_counts, you'll see that there is a lot going on.

If you need to calculate the frequency of many series, this could take a while. A faster implementation would be to use numpy.unique with return_counts = True

Here is an example:

import pandas as pd
import numpy as np

my_series = pd.Series([1,2,2,3,3,3])

print(my_series.value_counts())
3    3
2    2
1    1
dtype: int64

Notice here that the item returned is a pandas.Series

In comparison, numpy.unique returns a tuple with two items, the unique values and the counts.

vals, counts = np.unique(my_series, return_counts=True)
print(vals, counts)
[1 2 3] [1 2 3]

You can then combine these into a dictionary:

results = dict(zip(vals, counts))
print(results)
{1: 1, 2: 2, 3: 3}

And then into a pandas.Series

print(pd.Series(results))
1    1
2    2
3    3
dtype: int64

Sending string via socket (python)

client.py

import socket

s = socket.socket()
s.connect(('127.0.0.1',12345))
while True:
    str = raw_input("S: ")
    s.send(str.encode());
    if(str == "Bye" or str == "bye"):
        break
    print "N:",s.recv(1024).decode()
s.close()

server.py

import socket

s = socket.socket()
port = 12345
s.bind(('', port))
s.listen(5)
c, addr = s.accept()
print "Socket Up and running with a connection from",addr
while True:
    rcvdData = c.recv(1024).decode()
    print "S:",rcvdData
    sendData = raw_input("N: ")
    c.send(sendData.encode())
    if(sendData == "Bye" or sendData == "bye"):
        break
c.close()

This should be the code for a small prototype for the chatting app you wanted. Run both of them in separate terminals but then just check for the ports.

How do I view cookies in Internet Explorer 11 using Developer Tools

I think I found what you are looking for since I was also looking for it.

You have to follow Pawel's steps and then go to the key that is "Cookie". This will open a submenu with all the cookies and it specifies their name, value, domain, etc...

enter image description here

Respectively the values are: Key, Value, Expiration Date, Domain, Path.

This shows all the keys for this domain.

So again to get there:

  1. Go to Network.
  2. Capture Traffic, green triangle.
  3. Go to Details.
  4. Go to the "Cookie" key that has a gibberish value. (_utmc=xxxxx;something=ajksdhfa) etc...

Get full path without filename from path that includes filename

I used this and it works well:

string[] filePaths = Directory.GetFiles(Path.GetDirectoryName(dialog.FileName));

foreach (string file in filePaths)
{   
    if (comboBox1.SelectedItem.ToString() == "")
    {
        if (file.Contains("c"))
        {
            comboBox2.Items.Add(Path.GetFileName(file));
        }
    }
}

What is the difference between Unidirectional and Bidirectional JPA and Hibernate associations?

In terms of coding, a bidirectional relationship is more complex to implement because the application is responsible for keeping both sides in synch according to JPA specification 5 (on page 42). Unfortunately the example given in the specification does not give more details, so it does not give an idea of the level of complexity.

When not using a second level cache it is usually not a problem to do not have the relationship methods correctly implemented because the instances get discarded at the end of the transaction.

When using second level cache, if anything gets corrupted because of wrongly implemented relationship handling methods, this means that other transactions will also see the corrupted elements (the second level cache is global).

A correctly implemented bi-directional relationship can make queries and the code simpler, but should not be used if it does not really make sense in terms of business logic.

How to add an item to an ArrayList in Kotlin?

For people just migrating from java, In Kotlin List is by default immutable and mutable version of Lists is called MutableList.

Hence if you have something like :

val list: List<String> = ArrayList()

In this case you will not get an add() method as list is immutable. Hence you will have to declare a MutableList as shown below :

val list: MutableList<String> = ArrayList()

Now you will see an add() method and you can add elements to any list.

<code> vs <pre> vs <samp> for inline and block code snippets

This works for me to display code in frontend:

<style>
.content{
    height:50vh;
    width: 100%;
    background: transparent;
    border: none;
    border-radius: 0;
    resize: none;
    outline: none;
}
.content:focus{
    border: none;
    -webkit-box-shadow: none;
    -moz-box-shadow: none;
    box-shadow: none;
}
</style>

<textarea class="content">
<div>my div</div><p>my paragraph</p>
</textarea>

View Live Demo: https://jsfiddle.net/bytxj50e/

Reload parent window from child window

You can reload parent window location using :

window.opener.location.href = window.opener.location.href;

Obtaining ExitCode using Start-Process and WaitForExit instead of -Wait

The '-Wait' option seemed to block for me even though my process had finished.

I tried Adrian's solution and it works. But I used Wait-Process instead of relying on a side effect of retrieving the process handle.

So:

$proc = Start-Process $msbuild -PassThru
Wait-Process -InputObject $proc

if ($proc.ExitCode -ne 0) {
    Write-Warning "$_ exited with status code $($proc.ExitCode)"
}

Using Vim's tabs like buffers

I use buffers like tabs, using the BufExplorer plugin and a few macros:

" CTRL+b opens the buffer list
map <C-b> <esc>:BufExplorer<cr>

" gz in command mode closes the current buffer
map gz :bdelete<cr>

" g[bB] in command mode switch to the next/prev. buffer
map gb :bnext<cr>
map gB :bprev<cr>

With BufExplorer you don't have a tab bar at the top, but on the other hand it saves space on your screen, plus you can have an infinite number of files/buffers open and the buffer list is searchable...

How to install pywin32 module in windows 7

I disagree with the accepted answer being "the easiest", particularly if you want to use virtualenv.

You can use the Unofficial Windows Binaries instead. Download the appropriate wheel from there, and install it with pip:

pip install pywin32-219-cp27-none-win32.whl

(Make sure you pick the one for the right version and bitness of Python).

You might be able to get the URL and install it via pip without downloading it first, but they're made it a bit harder to just grab the URL. Probably better to download it and host it somewhere yourself.

Change url query string value using jQuery

If you only need to modify the page num you can replace it:

var newUrl = location.href.replace("page="+currentPageNum, "page="+newPageNum);

Bulk Insert Correctly Quoted CSV File in SQL Server

There is another solution for this.

Consider the quotes as part of the fields delimiter, by editing the fmt file.

You can check this out for more information:

http://blogs.msdn.com/b/sqlserverfaq/archive/2010/02/04/how-to-remove-unwanted-quotation-marks-while-importing-a-data-file.aspx

An extract of the link above:

The only way to remove the quotation marks would be to modify the column delimiters specified during the import operation. The only drawback here is that if you inspect the data to be inserted, you will very quickly realize that the column delimiters are different for each column (Delimiters highlighted above).

So to specify different column delimiters for each column, you would need to use a format file if you plan to use Bulk Insert or BCP. If you generate a format file for the above table structure, it would be as follows:

9.0
3
1       SQLCHAR       0       5       "\t"     1     FName              SQL_Latin1_General_CP1_CI_AS
2       SQLCHAR       0       5       "\t"     2     LName              SQL_Latin1_General_CP1_CI_AS
3       SQLCHAR       0       50      "\r\n"   3     Company            SQL_Latin1_General_CP1_CI_AS

Modify the format file to represent the correct column delimiters for each column. The new format file to be used will look like this:

9.0
4
1       SQLCHAR       0       0     "\""      0     FIRST_QUOTE      SQL_Latin1_General_CP1_CI_AS
2       SQLCHAR       0       5     "\",\""   1     FNAME               SQL_Latin1_General_CP1_CI_AS
3       SQLCHAR       0       5     "\",\""   2     LNAME            SQL_Latin1_General_CP1_CI_AS
4       SQLCHAR       0       50    "\"\r\n"  3     COMPANY          SQL_Latin1_General_CP1_CI_AS

Android Use Done button on Keyboard to click button

Kotlin and Numeric keyboard

If you are using the numeric keyboard you have to dismiss the keyboard, it will be like:

editText.setOnEditorActionListener { v, actionId, event ->
  if (action == EditorInfo.IME_ACTION_DONE || action == EditorInfo.IME_ACTION_NEXT || action == EditorInfo.IME_ACTION_UNSPECIFIED) {
      //hide the keyboard
      val imm = context.getSystemService(Context.INPUT_METHOD_SERVICE) as InputMethodManager
      imm.hideSoftInputFromWindow(windowToken, 0)
      //Take action
      editValue.clearFocus()
      return true
  } else {
      return false
  }
}

Storing money in a decimal column - what precision and scale?

If you're going to be doing any sort of arithmetic operations in the DB (multiplying out billing rates and so on), you'll probably want a lot more precision than people here are suggesting, for the same reasons that you'd never want to use anything less than a double-precision floating point value in application code.

Can't get private key with openssl (no start line:pem_lib.c:703:Expecting: ANY PRIVATE KEY)

I ran into the 'Expecting: ANY PRIVATE KEY' error when using openssl on Windows (Ubuntu Bash and Git Bash had the same issue).

The cause of the problem was that I'd saved the key and certificate files in Notepad using UTF8. Resaving both files in ANSI format solved the problem.

How to detect a mobile device with JavaScript?

var isMobileDevice = navigator.userAgent.match(/iPad|iPhone|iPod/i) != null 
    || screen.width <= 480;

How to properly reference local resources in HTML?

  • A leading slash tells the browser to start at the root directory.
  • If you don't have the leading slash, you're referencing from the current directory.
  • If you add two dots before the leading slash, it means you're referencing the parent of the current directory.

Take the following folder structure

demo folder structure

notice:

  • the ROOT checkmark is green,
  • the second checkmark is orange,
  • the third checkmark is purple,
  • the forth checkmark is yellow

Now in the index.html.en file you'll want to put the following markup

<p>
    <span>src="check_mark.png"</span>
    <img src="check_mark.png" />
    <span>I'm purple because I'm referenced from this current directory</span>
</p>

<p>
    <span>src="/check_mark.png"</span>
    <img src="/check_mark.png" />
    <span>I'm green because I'm referenced from the ROOT directory</span>
</p>

<p>
    <span>src="subfolder/check_mark.png"</span>
    <img src="subfolder/check_mark.png" />
    <span>I'm yellow because I'm referenced from the child of this current directory</span>
</p>

<p>
    <span>src="/subfolder/check_mark.png"</span>
    <img src="/subfolder/check_mark.png" />
    <span>I'm orange because I'm referenced from the child of the ROOT directory</span>
</p>

<p>
    <span>src="../subfolder/check_mark.png"</span>
    <img src="../subfolder/check_mark.png" />
    <span>I'm purple because I'm referenced from the parent of this current directory</span>
</p>

<p>
    <span>src="subfolder/subfolder/check_mark.png"</span>
    <img src="subfolder/subfolder/check_mark.png" />
    <span>I'm [broken] because there is no subfolder two children down from this current directory</span>
</p>

<p>
    <span>src="/subfolder/subfolder/check_mark.png"</span>
    <img src="/subfolder/subfolder/check_mark.png" />
    <span>I'm purple because I'm referenced two children down from the ROOT directory</span>
</p>

Now if you load up the index.html.en file located in the second subfolder
http://example.com/subfolder/subfolder/

This will be your output

enter image description here

How to return a result from a VBA function

VBA functions treat the function name itself as a sort of variable. So instead of using a "return" statement, you would just say:

test = 1

Notice, though, that this does not break out of the function. Any code after this statement will also be executed. Thus, you can have many assignment statements that assign different values to test, and whatever the value is when you reach the end of the function will be the value returned.

Multiple axis line chart in excel

Taking the answer above as guidance;

I made an extra graph for "hours worked by month", then copy/special-pasted it as a 'linked picture' for use under my other graphs. in other words, I copy pasted my existing graphs over the linked picture made from my new graph with the new axis.. And because it is a linked picture it always updates.

Make it easy on yourself though, make sure you copy an existing graph to build your 'picture' graph - then delete the series or change the data source to what you need as an extra axis. That way you won't have to mess around resizing.

The results were not too bad considering what I wanted to achieve; basically a list of incident frequency bar graph, with a performance tread line, and then a solid 'backdrop' of hours worked.

Thanks to the guy above for the idea!

Using Node.js require vs. ES6 import/export

As of right now ES6 import, export is always compiled to CommonJS, so there is no benefit using one or other. Although usage of ES6 is recommended since it should be advantageous when native support from browsers released. The reason being, you can import partials from one file while with CommonJS you have to require all of the file.

ES6 → import, export default, export

CommonJS → require, module.exports, exports.foo

Below is common usage of those.

ES6 export default

// hello.js
function hello() {
  return 'hello'
}
export default hello

// app.js
import hello from './hello'
hello() // returns hello

ES6 export multiple and import multiple

// hello.js
function hello1() {
  return 'hello1'
}
function hello2() {
  return 'hello2'
}
export { hello1, hello2 }

// app.js
import { hello1, hello2 } from './hello'
hello1()  // returns hello1
hello2()  // returns hello2

CommonJS module.exports

// hello.js
function hello() {
  return 'hello'
}
module.exports = hello

// app.js
const hello = require('./hello')
hello()   // returns hello

CommonJS module.exports multiple

// hello.js
function hello1() {
  return 'hello1'
}
function hello2() {
  return 'hello2'
}
module.exports = {
  hello1,
  hello2
}

// app.js
const hello = require('./hello')
hello.hello1()   // returns hello1
hello.hello2()   // returns hello2

Disabled form inputs do not appear in the request

In addition to Tom Blodget's response, you may simply add @HtmlBeginForm as the form action, like this:

 <form id="form" method="post" action="@Html.BeginForm("action", "controller", FormMethod.Post, new { onsubmit = "this.querySelectorAll('input').forEach(i => i.disabled = false)" })"

Store boolean value in SQLite

using the Integer data type with values 0 and 1 is the fastest.

How to see local history changes in Visual Studio Code?

I think there is no out-of-the-box support for that in VS Code.

You can install a plugin to give you similar functionality. Eg.:

https://marketplace.visualstudio.com/items?itemName=micnil.vscode-checkpoints

Or the more famous:

https://marketplace.visualstudio.com/items?itemName=xyz.local-history

Some details may need to be configured: The VS Code search gets confused sometimes because of additional folders created by this type of plugins. You can configure it to ignore such folders or change their locations (adding such folders to your .gitignore file also solves this problem).

Send attachments with PHP Mail()?

You can try using the following code:

    $filename = 'myfile';
    $path = 'your path goes here';
    $file = $path . "/" . $filename;

    $mailto = '[email protected]';
    $subject = 'Subject';
    $message = 'My message';

    $content = file_get_contents($file);
    $content = chunk_split(base64_encode($content));

    // a random hash will be necessary to send mixed content
    $separator = md5(time());

    // carriage return type (RFC)
    $eol = "\r\n";

    // main header (multipart mandatory)
    $headers = "From: name <[email protected]>" . $eol;
    $headers .= "MIME-Version: 1.0" . $eol;
    $headers .= "Content-Type: multipart/mixed; boundary=\"" . $separator . "\"" . $eol;
    $headers .= "Content-Transfer-Encoding: 7bit" . $eol;
    $headers .= "This is a MIME encoded message." . $eol;

    // message
    $body = "--" . $separator . $eol;
    $body .= "Content-Type: text/plain; charset=\"iso-8859-1\"" . $eol;
    $body .= "Content-Transfer-Encoding: 8bit" . $eol;
    $body .= $message . $eol;

    // attachment
    $body .= "--" . $separator . $eol;
    $body .= "Content-Type: application/octet-stream; name=\"" . $filename . "\"" . $eol;
    $body .= "Content-Transfer-Encoding: base64" . $eol;
    $body .= "Content-Disposition: attachment" . $eol;
    $body .= $content . $eol;
    $body .= "--" . $separator . "--";

    //SEND Mail
    if (mail($mailto, $subject, $body, $headers)) {
        echo "mail send ... OK"; // or use booleans here
    } else {
        echo "mail send ... ERROR!";
        print_r( error_get_last() );
    }

Edit 14-June-2018

for more readability in some of email provider use

$body .= $eol . $message . $eol . $eol; and $body .= $eol . $content . $eol . $eol;

Return Type for jdbcTemplate.queryForList(sql, object, classType)

In order to map a the result set of query to a particular Java class you'll probably be best (assuming you're interested in using the object elsewhere) off with a RowMapper to convert the columns in the result set into an object instance.

See Section 12.2.1.1 of Data access with JDBC on how to use a row mapper.

In short, you'll need something like:

List<Conversation> actors = jdbcTemplate.query(
    SELECT_ALL_CONVERSATIONS_SQL_FULL,
    new Object[] {userId, dateFrom, dateTo},
    new RowMapper<Conversation>() {
        public Conversation mapRow(ResultSet rs, int rowNum) throws SQLException {
            Conversation c = new Conversation();
            c.setId(rs.getLong(1));
            c.setRoom(rs.getString(2));
            [...]
            return c;
        }
    });

JOptionPane Input to int

Please note that Integer.parseInt throws an NumberFormatException if the passed string doesn't contain a parsable string.

PHP JSON String, escape Double Quotes for JS output

Another way would be to encode the quotes using htmlspecialchars:

$json_array = array(
    'title' => 'Example string\'s with "special" characters'
);

$json_decode = htmlspecialchars(json_encode($json_array), ENT_QUOTES, 'UTF-8');

Seaborn plots not showing up

Plots created using seaborn need to be displayed like ordinary matplotlib plots. This can be done using the

plt.show()

function from matplotlib.

Originally I posted the solution to use the already imported matplotlib object from seaborn (sns.plt.show()) however this is considered to be a bad practice. Therefore, simply directly import the matplotlib.pyplot module and show your plots with

import matplotlib.pyplot as plt
plt.show()

If the IPython notebook is used the inline backend can be invoked to remove the necessity of calling show after each plot. The respective magic is

%matplotlib inline

Entity Framework and Connection Pooling

Below code helped my object to be refreshed with fresh database values. The Entry(object).Reload() command forces the object to recall database values

GM_MEMBERS member = DatabaseObjectContext.GM_MEMBERS.FirstOrDefault(p => p.Username == username && p.ApplicationName == this.ApplicationName);
DatabaseObjectContext.Entry(member).Reload();

Can't change table design in SQL Server 2008

Just go to the SQL Server Management Studio -> Tools -> Options -> Designer; and Uncheck the option "prevent saving changes that require table re-creation".

SyntaxError: missing ; before statement

Looks like you have an extra parenthesis.

The following portion is parsed as an assignment so the interpreter/compiler will look for a semi-colon or attempt to insert one if certain conditions are met.

foob_name = $this.attr('name').replace(/\[(\d+)\]/, function($0, $1) {
   return '[' + (+$1 + 1) + ']';
})

jQuery.post( ) .done( ) and success:

From the doc:

jqXHR.done(function( data, textStatus, jqXHR ) {});

An alternative construct to the success callback option, the .done() method replaces the deprecated jqXHR.success() method. Refer to deferred.done() for implementation details.

The point it is just an alternative for success callback option, and jqXHR.success() is deprecated.

Using isKindOfClass with Swift

You can combine the check and cast into one statement:

let touch = object.anyObject() as UITouch
if let picker = touch.view as? UIPickerView {
    ...
}

Then you can use picker within the if block.

HTML character codes for this ? or this ?

&#9650; is the Unicode black up-pointing triangle (?) while &#9660; is the black down-pointing triangle (?).

You can just plug the characters (copied from the web) into this site for a lookup.

Issue with parsing the content from json file with Jackson & message- JsonMappingException -Cannot deserialize as out of START_ARRAY token

Your JSON string is malformed: the type of center is an array of invalid objects. Replace [ and ] with { and } in the JSON string around longitude and latitude so they will be objects:

[
    {
        "name" : "New York",
        "number" : "732921",
        "center" : {
                "latitude" : 38.895111, 
                "longitude" : -77.036667
            }
    },
    {
        "name" : "San Francisco",
        "number" : "298732",
        "center" : {
                "latitude" : 37.783333, 
                "longitude" : -122.416667
            }
    }
]

Getting min and max Dates from a pandas dataframe

'Date' is your index so you want to do,

print (df.index.min())
print (df.index.max())

2014-03-13 00:00:00
2014-03-31 00:00:00

Javascript counting number of objects in object

In recent browsers you can use:

Object.keys(obj.Data).length

See MDN

For older browsers, use the for-in loop in Michael Geary's answer.

Limiting floats to two decimal points

You are running into the old problem with floating point numbers that not all numbers can be represented exactly. The command line is just showing you the full floating point form from memory.

With floating point representation, your rounded version is the same number. Since computers are binary, they store floating point numbers as an integer and then divide it by a power of two so 13.95 will be represented in a similar fashion to 125650429603636838/(2**53).

Double precision numbers have 53 bits (16 digits) of precision and regular floats have 24 bits (8 digits) of precision. The floating point type in Python uses double precision to store the values.

For example,

>>> 125650429603636838/(2**53)
13.949999999999999

>>> 234042163/(2**24)
13.949999988079071

>>> a = 13.946
>>> print(a)
13.946
>>> print("%.2f" % a)
13.95
>>> round(a,2)
13.949999999999999
>>> print("%.2f" % round(a, 2))
13.95
>>> print("{:.2f}".format(a))
13.95
>>> print("{:.2f}".format(round(a, 2)))
13.95
>>> print("{:.15f}".format(round(a, 2)))
13.949999999999999

If you are after only two decimal places (to display a currency value, for example), then you have a couple of better choices:

  1. Use integers and store values in cents, not dollars and then divide by 100 to convert to dollars.
  2. Or use a fixed point number like decimal.

How to list all files in a directory and its subdirectories in hadoop hdfs

Thanks Radu Adrian Moldovan for the suggestion.

Here is an implementation using queue:

private static List<String> listAllFilePath(Path hdfsFilePath, FileSystem fs)
throws FileNotFoundException, IOException {
  List<String> filePathList = new ArrayList<String>();
  Queue<Path> fileQueue = new LinkedList<Path>();
  fileQueue.add(hdfsFilePath);
  while (!fileQueue.isEmpty()) {
    Path filePath = fileQueue.remove();
    if (fs.isFile(filePath)) {
      filePathList.add(filePath.toString());
    } else {
      FileStatus[] fileStatus = fs.listStatus(filePath);
      for (FileStatus fileStat : fileStatus) {
        fileQueue.add(fileStat.getPath());
      }
    }
  }
  return filePathList;
}

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

Exclusive Or is defined as follows

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

Select a dummy column with a dummy value in SQL?

Try this:

select col1, col2, 'ABC' as col3 from Table1 where col1 = 0;

Link entire table row?

I think this might be the simplest solution:

<tr onclick="location.href='http://www.mywebsite.com'" style="cursor: pointer">
<td>...</td>
<td>...</td>
</tr>

The cursor CSS property sets the type of cursor, if any, to show when the mouse pointer is over an element.

The inline css defines that for that element the cursor will be formatted as a pointer, so you don't need the 'hover'.

Do I commit the package-lock.json file created by npm 5?

Committing package-lock.json to the source code version control means that the project will use a specific version of dependencies that may or may not match those defined in package.json. while the dependency has a specific version without any Caret (^) and Tilde (~) as you can see, that's mean the dependency will not be updated to the most recent version. and npm install will pick up the same version as well as we need it for our current version of Angular.

Note : package-lock.json highly recommended to commit it IF I added any Caret (^) and Tilde (~) to the dependency to be updated during the CI.

How do I repair an InnoDB table?

See this article: http://www.unilogica.com/mysql-innodb-recovery/ (It's in portuguese)

Are explained how to use innodb_force_recovery and innodb_file_per_table. I discovered this after need to recovery a crashed database with a single ibdata1.

Using innodb_file_per_table, all tables in InnoDB will create a separated table file, like MyISAM.

Finding the path of the program that will execute from the command line in Windows

Here's a little cmd script you can copy-n-paste into a file named something like where.cmd:

@echo off
rem - search for the given file in the directories specified by the path, and display the first match
rem
rem    The main ideas for this script were taken from Raymond Chen's blog:
rem
rem         http://blogs.msdn.com/b/oldnewthing/archive/2005/01/20/357225.asp
rem
rem
rem - it'll be nice to at some point extend this so it won't stop on the first match. That'll
rem     help diagnose situations with a conflict of some sort.
rem

setlocal

rem - search the current directory as well as those in the path
set PATHLIST=.;%PATH%
set EXTLIST=%PATHEXT%

if not "%EXTLIST%" == "" goto :extlist_ok
set EXTLIST=.COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH
:extlist_ok

rem - first look for the file as given (not adding extensions)
for %%i in (%1) do if NOT "%%~$PATHLIST:i"=="" echo %%~$PATHLIST:i

rem - now look for the file adding extensions from the EXTLIST
for %%e in (%EXTLIST%) do @for %%i in (%1%%e) do if NOT "%%~$PATHLIST:i"=="" echo %%~$PATHLIST:i

How to access share folder in virtualbox. Host Win7, Guest Fedora 16?

I just figured. You need to add a shared folder using VirtualBox before you access it with the guest.

Click "Device" in the menu bar--->Shared File--->add a directory and name it

then in the guest terminal, use:

sudo mount -t vboxsf myFileName ~/destination

Dont directly refer to the host directory

php implode (101) with quotes

If you want to avoid the fopen/fputcsv sub-systems here's a snippet that builds an escaped CSV string from an associative array....

$output = '';
foreach ($list as $row) {
  $output .= '"' . implode('", "', array_values($row)) . '"' . "\r\n";
}

Or from a list of objects...

foreach ($list as $obj) {
  $output .= '"' . implode('", "', array_values((array) $obj)) . '"' . "\r\n";
}

Then you can output the string as desired.

Filter Pyspark dataframe column with None value

Try to just use isNotNull function.

df.filter(df.dt_mvmt.isNotNull()).count()

Run all SQL files in a directory

The easiest way I found included the following steps (the only requirement is it to be in Win7+):

  • open the folder in Explorer
  • select all script files
  • press Shift
  • right click the selection and select "Copy as path"
  • go to SQL Server Management Studio
  • create a new query
  • Query Menu, "SQLCMD mode"
  • paste the list, then Ctrl+H, replace '"C:\' (or whatever the drive letter) with ':r "C:' (i.e. prefix the lines with ':r ')
  • run the query

It sounds long, but in reality is very fast.. (it sounds long as I described even the smallest steps)

How to configure XAMPP to send mail from localhost?

You have to configure SMTP on your server. You can use G Suite SMTP by Google for free:

<?php

$mail = new PHPMailer(true);

// Send mail using Gmail
if($send_using_gmail){
    $mail->IsSMTP(); // telling the class to use SMTP
    $mail->SMTPAuth = true; // enable SMTP authentication
    $mail->SMTPSecure = "ssl"; // sets the prefix to the servier
    $mail->Host = "smtp.gmail.com"; // sets GMAIL as the SMTP server
    $mail->Port = 465; // set the SMTP port for the GMAIL server
    $mail->Username = "[email protected]"; // GMAIL username
    $mail->Password = "your-gmail-password"; // GMAIL password
}

// Typical mail data
$mail->AddAddress($email, $name);
$mail->SetFrom($email_from, $name_from);
$mail->Subject = "My Subject";
$mail->Body = "Mail contents";

try{
    $mail->Send();
    echo "Success!";
} catch(Exception $e){
    // Something went bad
    echo "Fail :(";
}

?>

Read more about PHPMailer here.

Add php variable inside echo statement as href link address?

Basically like this,

<?php
$link = ""; // Link goes here!
print "<a href="'.$link.'">Link</a>";
?>

Permission denied (publickey,keyboard-interactive)

You need to change the sshd_config file in the remote server (probably in /etc/ssh/sshd_config).

Change

PasswordAuthentication no

to

PasswordAuthentication yes

And then restart the sshd daemon.

Error: Address already in use while binding socket with address but the port number is shown free by `netstat`

For AF_UNIX you can use call unlink (path); after close() socket in "server" app

How to convert OutputStream to InputStream?

As input and output streams are just start and end point, the solution is to temporary store data in byte array. So you must create intermediate ByteArrayOutputStream, from which you create byte[] that is used as input for new ByteArrayInputStream.

public void doTwoThingsWithStream(InputStream inStream, OutputStream outStream){ 
  //create temporary bayte array output stream
  ByteArrayOutputStream baos = new ByteArrayOutputStream();
  doFirstThing(inStream, baos);
  //create input stream from baos
  InputStream isFromFirstData = new ByteArrayInputStream(baos.toByteArray()); 
  doSecondThing(isFromFirstData, outStream);
}

Hope it helps.

Listing all extras of an Intent

If for debugging all you want is a string (sort of implied by the OP but not explicitly stated), simply use toString on the extras Bundle:

intent.getExtras().toString()

It returns a string such as:

Bundle[{key1=value1, key2=value2, key3=value3}]

Documentation: Bundle.toString() (it's unfortunately the default Object.toString() javadoc and as such quite useless here.)

Python pandas insert list into a cell

Quick work around

Simply enclose the list within a new list, as done for col2 in the data frame below. The reason it works is that python takes the outer list (of lists) and converts it into a column as if it were containing normal scalar items, which is lists in our case and not normal scalars.

mydict={'col1':[1,2,3],'col2':[[1, 4], [2, 5], [3, 6]]}
data=pd.DataFrame(mydict)
data


   col1     col2
0   1       [1, 4]
1   2       [2, 5]
2   3       [3, 6]

How do I iterate through lines in an external file with shell?

I know the purists will hate this method, but you can cat the file.

NAMES=`cat scripts/names.txt` #names from names.txt file
for NAME in $NAMES; do
   echo "$NAME"
done

How to split a string with angularJS

Thx guys, I finally found the solution, a really basic one.. In my controller I have

$scope.mySplit = function(string, nb) {
    var array = string.split(',');
    return array[nb];
}

and in my view

{{mySplit(string,0)}}

What characters can be used for up/down triangle (arrow without stem) for display in HTML?

There are literal arrowheads in the Spacing Modifier Letters block:

U+02C2  ?   &#706;  Modifier Letter Left  Arrowhead
U+02C3  ?   &#707;  Modifier Letter Right Arrowhead
U+02C4  ^   &#708;  Modifier Letter Up    Arrowhead
U+02C5  ?   &#709;  Modifier Letter Down  Arrowhead

Difference between Hive internal tables and external tables?

The best use case for an external table in the hive is when you want to create the table from a file either CSV or text

The program can’t start because MSVCR71.dll is missing from your computer. Try reinstalling the program to fix this program

MY SOLUTION!!!!!!! I fixed this problem when I was trying to install business objects. When the installer failed to register .dll's I inputted the MSVCR71.dll into both system32 and sysWOW64 then clicked retry. Installation finished. I did try adding this in before and after install but, install still failed.

How to empty a redis database?

With redis-cli:

FLUSHDB       - Removes data from your connection's CURRENT database.
FLUSHALL      - Removes data from ALL databases.

Redis Docs: FLUSHDB, FLUSHALL

How to autosize and right-align GridViewColumn data in WPF?

I created a function for updating GridView column headers for a list and call it whenever the window is re-sized or the listview updates it's layout.

public void correctColumnWidths()
{
    double remainingSpace = myList.ActualWidth;

    if (remainingSpace > 0)
    {
         for (int i = 0; i < (myList.View as GridView).Columns.Count; i++)
              if (i != 2)
                   remainingSpace -= (myList.View as GridView).Columns[i].ActualWidth;

          //Leave 15 px free for scrollbar
          remainingSpace -= 15;

          (myList.View as GridView).Columns[2].Width = remainingSpace;
    }
}

How to fetch the dropdown values from database and display in jsp

You can learn some tutorials for JSP page direct access database (mysql) here

Notes:

  • import sql tag library in jsp page

    <%@ taglib uri="http://java.sun.com/jsp/jstl/sql" prefix="sql"%>

  • then set datasource on page

    <sql:setDataSource var="ds" driver="com.mysql.jdbc.Driver" url="jdbc:mysql://<yourhost>/<yourdb>" user="<user>" password="<password>"/>
    
  • Now query what you want on page

    <sql:query dataSource="${ds}" var="result"> //ref  defined 'ds'
        SELECT * from <your-table>;
    </sql:query>
    
  • Finally you can populate dropdowns on page using c:forEach tag to iterate result rows in select element

    <c:forEach var="row" items="${result.rows}"> //ref set var 'result' <option value='<c:out value="${row.key}"/>'><c:out value="${row.value}"/</option> </c:forEach>

How to call a C# function from JavaScript?

.CS File    
    namespace Csharp
    {
      public void CsharpFunction()
      {
        //Code;
      }
    }

    JS code:
    function JSFunction() {
            <%#ProjectName.Csharp.CsharpFunction()%> ;
    }

Note :in JS Function when call your CS page function.... first name of project then name of name space of CS page then function name

How to check not in array element

Try with array_intersect method

$id = $access_data['Privilege']['id']; 

if(count(array_intersect($id,$user_access_arr)) == 0){

$this->Session->setFlash(__('Access Denied! You are not eligible to access this.'), 'flash_custom_success');
return $this->redirect(array('controller'=>'Dashboard','action'=>'index'));
}

How to make flexbox items the same size?

None of these answers solved my problem, which was that the items weren't the same width in my makeshift flexbox table when it was shrunk to a width too small.

The solution for me was simply to put overflow: hidden; on the flex-grow: 1; cells.

Another git process seems to be running in this repository

rm -f .git/index.lock didn't help, because I had a locked file that couldn't be deleted. So, index.lock also had been captured by some application.

In Windows I downloaded an alternative to Unlocker called Lock Hunter and deleted both files. Git captured them.

What is the meaning of "this" in Java?

In Swing its fairly common to write a class that implements ActionListener and add the current instance (ie 'this') as an ActionListener for components.

public class MyDialog extends JDialog implements ActionListener
{
    public MyDialog()
    {
        JButton myButton = new JButton("Hello");
        myButton.addActionListener(this);
    }

    public void actionPerformed(ActionEvent evt)
    {
        System.out.println("Hurdy Gurdy!");
    }

}

Add space between HTML elements only using CSS

span:not(:last-child) {
    margin-right: 10px;
}

What is the use of BindingResult interface in spring MVC?

Well its a sequential process. The Request first treat by FrontController and then moves towards our own customize controller with @Controller annotation.

but our controller method is binding bean using modelattribute and we are also performing few validations on bean values.

so instead of moving the request to our controller class, FrontController moves it towards one interceptor which creates the temp object of our bean and the validate the values. if validation successful then bind the temp obj values with our actual bean which is stored in @ModelAttribute otherwise if validation fails it does not bind and moves the resp towards error page or wherever u want.

enter image description here

Embedding Windows Media Player for all browsers

I have found something that Actually works in both FireFox and IE, on Elizabeth Castro's site (thanks to the link on this site) - I have tried all other versions here, but could not make them work in both the browsers

<object classid="CLSID:6BF52A52-394A-11d3-B153-00C04F79FAA6" 
  id="player" width="320" height="260">
  <param name="url" 
    value="http://www.sarahsnotecards.com/catalunyalive/fishstore.wmv" />
  <param name="src" 
    value="http://www.sarahsnotecards.com/catalunyalive/fishstore.wmv" />
  <param name="showcontrols" value="true" />
  <param name="autostart" value="true" />
  <!--[if !IE]>-->
  <object type="video/x-ms-wmv" 
    data="http://www.sarahsnotecards.com/catalunyalive/fishstore.wmv" 
    width="320" height="260">
    <param name="src" 
      value="http://www.sarahsnotecards.com/catalunyalive/fishstore.wmv" />
    <param name="autostart" value="true" />
    <param name="controller" value="true" />
  </object>
  <!--<![endif]-->
</object>

Check her site out: http://www.alistapart.com/articles/byebyeembed/ and the version with the classid in the initial object tag

With form validation: why onsubmit="return functionname()" instead of onsubmit="functionname()"?

HTML event handler code behaves like the body of a JavaScript function. Many languages such as C or Perl implicitly return the value of the last expression evaluated in the function body. JavaScript doesn't, it discards it and returns undefined unless you write an explicit returnEXPR.

How to decode JWT Token?

Using .net core jwt packages, the Claims are available:

[Route("api/[controller]")]
[ApiController]
[Authorize(Policy = "Bearer")]
public class AbstractController: ControllerBase
{
    protected string UserId()
    {
        var principal = HttpContext.User;
        if (principal?.Claims != null)
        {
            foreach (var claim in principal.Claims)
            {
               log.Debug($"CLAIM TYPE: {claim.Type}; CLAIM VALUE: {claim.Value}");
            }

        }
        return principal?.Claims?.SingleOrDefault(p => p.Type == "username")?.Value;
    }
}

How to permanently remove few commits from remote branch

Simplifying from pctroll's answer, similarly based on this blog post.

# look up the commit id in git log or on github, e.g. 42480f3, then do
git checkout master
git checkout your_branch
git revert 42480f3
# a text editor will open, close it with ctrl+x (editor dependent)
git push origin your_branch
# or replace origin with your remote

Return the characters after Nth character in a string

Alternately, you could do a Text to Columns with space as the delimiter.

Accessing a Dictionary.Keys Key through a numeric index

I think you can do something like this, the syntax might be wrong, havent used C# in a while To get the last item

Dictionary<string, int>.KeyCollection keys = mydict.keys;
string lastKey = keys.Last();

or use Max instead of Last to get the max value, I dont know which one fits your code better.

NSUserDefaults - How to tell if a key exists

I just went through this, and all of your answers helped me toward a good solution, for me. I resisted going the route suggested by, just because I found it hard to read and comprehend.

Here's what I did. I had a BOOL being carried around in a variable called "_talkative".

When I set my default (NSUserDefaults) object, I set it as an object, as I could then test to see if it was nil:

//converting BOOL to an object so we can check on nil
[defaults setObject:@(_talkative) forKey:@"talkative"];

Then when I went to see if it existed, I used:

if ([defaults objectForKey:@"talkative"]!=nil )
  {

Then I used the object as a BOOL:

if ([defaults boolForKey:@"talkative"]) {
 ...

This seems to work in my case. It just made more visual sense to me.

Android Calling JavaScript functions in WebView

Modification of @Ilya_Gazman answer

    private void callJavaScript(WebView view, String methodName, Object...params){
        StringBuilder stringBuilder = new StringBuilder();
        stringBuilder.append("javascript:try{");
        stringBuilder.append(methodName);
        stringBuilder.append("(");
        String separator = "";
        for (Object param : params) {               
            stringBuilder.append(separator);
            separator = ",";
            if(param instanceof String){
                stringBuilder.append("'");
            }
                stringBuilder.append(param.toString().replace("'", "\\'"));
            if(param instanceof String){
                stringBuilder.append("'");
            }

        }
        stringBuilder.append(")}catch(error){console.error(error.message);}");
        final String call = stringBuilder.toString();
        Log.i(TAG, "callJavaScript: call="+call);


        view.loadUrl(call);
    }

will correctly create JS calls e.g.

callJavaScript(mBrowser, "alert", "abc", "def");
//javascript:try{alert('abc','def')}catch(error){console.error(error.message);}
callJavaScript(mBrowser, "alert", 1, true, "abc");
//javascript:try{alert(1,true,'abc')}catch(error){console.error(error.message);}

Note that objects will not be passed correctly - but you can serialize them before passing as an argument.

Also I've changed where the error goes, I've diverted it to the console log which can be listened by:

    webView.setWebChromeClient(new CustomWebChromeClient());

and client

class CustomWebChromeClient extends WebChromeClient {
    private static final String TAG = "CustomWebChromeClient";

    @Override
    public boolean onConsoleMessage(ConsoleMessage cm) {
        Log.d(TAG, String.format("%s @ %d: %s", cm.message(),
                cm.lineNumber(), cm.sourceId()));
        return true;
    }
}

Yes or No confirm box using jQuery

You can reuse your confirm:

    function doConfirm(body, $_nombrefuncion)
    {   var param = undefined;
        var $confirm = $("<div id='confirm' class='hide'></div>").dialog({
            autoOpen: false,
            buttons: {
                Yes: function() {
                param = true;
                $_nombrefuncion(param);
                $(this).dialog('close');
            },
                No: function() {
                param = false;
                $_nombrefuncion(param);
                $(this).dialog('close');
            }
                                    }
        });
        $confirm.html("<h3>"+body+"<h3>");
        $confirm.dialog('open');                                     
    };

// for this form just u must change or create a new function for to reuse the confirm
    function resultadoconfirmresetVTyBFD(param){
        $fecha = $("#asigfecha").val();
        if(param ==true){
              // DO THE CONFIRM
        }
    }

//Now just u must call the function doConfirm
    doConfirm('body message',resultadoconfirmresetVTyBFD);

'POCO' definition

"Plain Old C# Object"

Just a normal class, no attributes describing infrastructure concerns or other responsibilities that your domain objects shouldn't have.

EDIT - as other answers have stated, it is technically "Plain Old CLR Object" but I, like David Arno comments, prefer "Plain Old Class Object" to avoid ties to specific languages or technologies.

TO CLARIFY: In other words, they don’t derive from some special base class, nor do they return any special types for their properties.

See below for an example of each.

Example of a POCO:

public class Person
{
    public string Name { get; set; }

    public int Age { get; set; }
}

Example of something that isn’t a POCO:

public class PersonComponent : System.ComponentModel.Component
{
    [DesignerSerializationVisibility(DesignerSerializationVisibility.Hidden)]
    public string Name { get; set; }

    public int Age { get; set; }
}

The example above both inherits from a special class to give it additional behavior as well as uses a custom attribute to change behavior… the same properties exist on both classes, but one is not just a plain old object anymore.

HTTP 400 (bad request) for logical error, not malformed request syntax

Status 422 (RFC 4918, Section 11.2) comes to mind:

The 422 (Unprocessable Entity) status code means the server understands the content type of the request entity (hence a 415(Unsupported Media Type) status code is inappropriate), and the syntax of the request entity is correct (thus a 400 (Bad Request) status code is inappropriate) but was unable to process the contained instructions. For example, this error condition may occur if an XML request body contains well-formed (i.e., syntactically correct), but semantically erroneous, XML instructions.

How can I use Async with ForEach?

List<T>.ForEach doesn't play particularly well with async (neither does LINQ-to-objects, for the same reasons).

In this case, I recommend projecting each element into an asynchronous operation, and you can then (asynchronously) wait for them all to complete.

using (DataContext db = new DataLayer.DataContext())
{
    var tasks = db.Groups.ToList().Select(i => GetAdminsFromGroupAsync(i.Gid));
    var results = await Task.WhenAll(tasks);
}

The benefits of this approach over giving an async delegate to ForEach are:

  1. Error handling is more proper. Exceptions from async void cannot be caught with catch; this approach will propagate exceptions at the await Task.WhenAll line, allowing natural exception handling.
  2. You know that the tasks are complete at the end of this method, since it does an await Task.WhenAll. If you use async void, you cannot easily tell when the operations have completed.
  3. This approach has a natural syntax for retrieving the results. GetAdminsFromGroupAsync sounds like it's an operation that produces a result (the admins), and such code is more natural if such operations can return their results rather than setting a value as a side effect.

Creating default object from empty value in PHP?

  1. First think you should create object $res = new \stdClass();

  2. then assign object with key and value thay $res->success = false;

Laravel Eloquent - Get one Row

Try with it

$color = \App\Color::take(1)->first();

submit the form using ajax

You can add an onclick function to your submit button, but you won't be able to submit your function by pressing enter. For my part, I use this:

<form action="" method="post" onsubmit="your_ajax_function(); return false;">
    Your Name <br/>
    <input type="text" name="name" id="name" />
    <br/>
    <input type="submit" id="submit" value="Submit" />
</form>

Hope it helps.

Creating watermark using html and css

Other solutions are great but they didn't take care of the fact that watermark shouldn't get selected on selection from the mouse. This fiddle takes care or that: https://jsfiddle.net/MiKr13/d1r4o0jg/9/

This will be better option for pdf or static html.

CSS:

#watermark {
  opacity: 0.2;
  font-size: 52px;
  color: 'black';
  background: '#ccc';
  position: absolute;
  cursor: default;
  user-select: none;
  -webkit-user-select: none;
  -khtml-user-select: none;
  -moz-user-select: none;
  -ms-user-select: none;
  right: 5px;
  bottom: 5px;
}

PHP Warning: Division by zero

try this

if(isset($itemCost) != '' && isset($itemQty) != '')
{
    $diffPricePercent = (($actual * 100) / $itemCost) / $itemQty;
}
else
{
    echo "either of itemCost or itemQty are null";
}

What's the difference between StaticResource and DynamicResource in WPF?

A StaticResource will be resolved and assigned to the property during the loading of the XAML which occurs before the application is actually run. It will only be assigned once and any changes to resource dictionary ignored.

A DynamicResource assigns an Expression object to the property during loading but does not actually lookup the resource until runtime when the Expression object is asked for the value. This defers looking up the resource until it is needed at runtime. A good example would be a forward reference to a resource defined later on in the XAML. Another example is a resource that will not even exist until runtime. It will update the target if the source resource dictionary is changed.

Generating random strings with T-SQL

This worked for me: I needed to generate just three random alphanumeric characters for an ID, but it could work for any length up to 15 or so.

declare @DesiredLength as int = 3;
select substring(replace(newID(),'-',''),cast(RAND()*(31-@DesiredLength) as int),@DesiredLength);

How to merge two files line by line in Bash

Check

man paste

possible followed by some command like untabify or tabs2spaces

ModuleNotFoundError: No module named 'sklearn'

install these ==>> pip install -U scikit-learn scipy matplotlib if still getting the same error then , make sure that your imoprted statment should be correct. i made the mistike while writing ensemble so ,(check spelling) its should be >>> from sklearn.ensemble import RandomForestClassifier

How can I generate random alphanumeric strings?

After reviewing the other answers and considering CodeInChaos' comments, along with CodeInChaos still biased (although less) answer, I thought a final ultimate cut and paste solution was needed. So while updating my answer I decided to go all out.

For an up to date version of this code, please visit the new Hg repository on Bitbucket: https://bitbucket.org/merarischroeder/secureswiftrandom. I recommend you copy and paste the code from: https://bitbucket.org/merarischroeder/secureswiftrandom/src/6c14b874f34a3f6576b0213379ecdf0ffc7496ea/Code/Alivate.SolidSwiftRandom/SolidSwiftRandom.cs?at=default&fileviewer=file-view-default (make sure you click the Raw button to make it easier to copy and make sure you have the latest version, I think this link goes to a specific version of the code, not the latest).

Updated notes:

  1. Relating to some other answers - If you know the length of the output, you don't need a StringBuilder, and when using ToCharArray, this creates and fills the array (you don't need to create an empty array first)
  2. Relating to some other answers - You should use NextBytes, rather than getting one at a time for performance
  3. Technically you could pin the byte array for faster access.. it's usually worth it when your iterating more than 6-8 times over a byte array. (Not done here)
  4. Use of RNGCryptoServiceProvider for best randomness
  5. Use of caching of a 1MB buffer of random data - benchmarking shows cached single bytes access speed is ~1000x faster - taking 9ms over 1MB vs 989ms for uncached.
  6. Optimised rejection of bias zone within my new class.

End solution to question:

static char[] charSet =  "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".ToCharArray();
static int byteSize = 256; //Labelling convenience
static int biasZone = byteSize - (byteSize % charSet.Length);
public string GenerateRandomString(int Length) //Configurable output string length
{
    byte[] rBytes = new byte[Length]; //Do as much before and after lock as possible
    char[] rName = new char[Length];
    SecureFastRandom.GetNextBytesMax(rBytes, biasZone);
    for (var i = 0; i < Length; i++)
    {
        rName[i] = charSet[rBytes[i] % charSet.Length];
    }
    return new string(rName);
}

But you need my new (untested) class:

/// <summary>
/// My benchmarking showed that for RNGCryptoServiceProvider:
/// 1. There is negligable benefit of sharing RNGCryptoServiceProvider object reference 
/// 2. Initial GetBytes takes 2ms, and an initial read of 1MB takes 3ms (starting to rise, but still negligable)
/// 2. Cached is ~1000x faster for single byte at a time - taking 9ms over 1MB vs 989ms for uncached
/// </summary>
class SecureFastRandom
{
    static byte[] byteCache = new byte[1000000]; //My benchmark showed that an initial read takes 2ms, and an initial read of this size takes 3ms (starting to raise)
    static int lastPosition = 0;
    static int remaining = 0;

    /// <summary>
    /// Static direct uncached access to the RNGCryptoServiceProvider GetBytes function
    /// </summary>
    /// <param name="buffer"></param>
    public static void DirectGetBytes(byte[] buffer)
    {
        using (var r = new RNGCryptoServiceProvider())
        {
            r.GetBytes(buffer);
        }
    }

    /// <summary>
    /// Main expected method to be called by user. Underlying random data is cached from RNGCryptoServiceProvider for best performance
    /// </summary>
    /// <param name="buffer"></param>
    public static void GetBytes(byte[] buffer)
    {
        if (buffer.Length > byteCache.Length)
        {
            DirectGetBytes(buffer);
            return;
        }

        lock (byteCache)
        {
            if (buffer.Length > remaining)
            {
                DirectGetBytes(byteCache);
                lastPosition = 0;
                remaining = byteCache.Length;
            }

            Buffer.BlockCopy(byteCache, lastPosition, buffer, 0, buffer.Length);
            lastPosition += buffer.Length;
            remaining -= buffer.Length;
        }
    }

    /// <summary>
    /// Return a single byte from the cache of random data.
    /// </summary>
    /// <returns></returns>
    public static byte GetByte()
    {
        lock (byteCache)
        {
            return UnsafeGetByte();
        }
    }

    /// <summary>
    /// Shared with public GetByte and GetBytesWithMax, and not locked to reduce lock/unlocking in loops. Must be called within lock of byteCache.
    /// </summary>
    /// <returns></returns>
    static byte UnsafeGetByte()
    {
        if (1 > remaining)
        {
            DirectGetBytes(byteCache);
            lastPosition = 0;
            remaining = byteCache.Length;
        }

        lastPosition++;
        remaining--;
        return byteCache[lastPosition - 1];
    }

    /// <summary>
    /// Rejects bytes which are equal to or greater than max. This is useful for ensuring there is no bias when you are modulating with a non power of 2 number.
    /// </summary>
    /// <param name="buffer"></param>
    /// <param name="max"></param>
    public static void GetBytesWithMax(byte[] buffer, byte max)
    {
        if (buffer.Length > byteCache.Length / 2) //No point caching for larger sizes
        {
            DirectGetBytes(buffer);

            lock (byteCache)
            {
                UnsafeCheckBytesMax(buffer, max);
            }
        }
        else
        {
            lock (byteCache)
            {
                if (buffer.Length > remaining) //Recache if not enough remaining, discarding remaining - too much work to join two blocks
                    DirectGetBytes(byteCache);

                Buffer.BlockCopy(byteCache, lastPosition, buffer, 0, buffer.Length);
                lastPosition += buffer.Length;
                remaining -= buffer.Length;

                UnsafeCheckBytesMax(buffer, max);
            }
        }
    }

    /// <summary>
    /// Checks buffer for bytes equal and above max. Must be called within lock of byteCache.
    /// </summary>
    /// <param name="buffer"></param>
    /// <param name="max"></param>
    static void UnsafeCheckBytesMax(byte[] buffer, byte max)
    {
        for (int i = 0; i < buffer.Length; i++)
        {
            while (buffer[i] >= max)
                buffer[i] = UnsafeGetByte(); //Replace all bytes which are equal or above max
        }
    }
}

For history - my older solution for this answer, used Random object:

    private static char[] charSet =
      "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ0123456789".ToCharArray();

    static rGen = new Random(); //Must share, because the clock seed only has Ticks (~10ms) resolution, yet lock has only 20-50ns delay.
    static int byteSize = 256; //Labelling convenience
    static int biasZone = byteSize - (byteSize % charSet.Length);
    static bool SlightlyMoreSecurityNeeded = true; //Configuration - needs to be true, if more security is desired and if charSet.Length is not divisible by 2^X.
    public string GenerateRandomString(int Length) //Configurable output string length
    {
      byte[] rBytes = new byte[Length]; //Do as much before and after lock as possible
      char[] rName = new char[Length];
      lock (rGen) //~20-50ns
      {
          rGen.NextBytes(rBytes);

          for (int i = 0; i < Length; i++)
          {
              while (SlightlyMoreSecurityNeeded && rBytes[i] >= biasZone) //Secure against 1/5 increased bias of index[0-7] values against others. Note: Must exclude where it == biasZone (that is >=), otherwise there's still a bias on index 0.
                  rBytes[i] = rGen.NextByte();
              rName[i] = charSet[rBytes[i] % charSet.Length];
          }
      }
      return new string(rName);
    }

Performance:

  1. SecureFastRandom - First single run = ~9-33ms. Imperceptible. Ongoing: 5ms (sometimes it goes up to 13ms) over 10,000 iterations, With a single average iteration= 1.5 microseconds.. Note: Requires generally 2, but occasionally up to 8 cache refreshes - depends on how many single bytes exceed the bias zone
  2. Random - First single run = ~0-1ms. Imperceptible. Ongoing: 5ms over 10,000 iterations. With a single average iteration= .5 microseconds.. About the same speed.

Also check out:

These links are another approach. Buffering could be added to this new code base, but most important was exploring different approaches to removing bias, and benchmarking the speeds and pros/cons.

Remote Linux server to remote linux server dir copy. How?

scp will do the job, but there is one wrinkle: the connection to the second remote destination will use the configuration on the first remote destination, so if you use .ssh/config on the local environment, and you expect rsa and dsa keys to work, you have to forward your agent to the first remote host.

How to convert this var string to URL in Swift

In swift 3 use:

let url = URL(string: "Whatever url you have(eg: https://google.com)")

How to edit HTML input value colour?

You can add color in the style rule of your input: color:#ccc;

"Fatal error: Cannot redeclare <function>"

I don't like function_exists('fun_name') because it relies on the function name being turned into a string, plus, you have to name it twice. Could easily break with refactoring.

Declare your function as a lambda expression (I haven't seen this solution mentioned):

$generate_salt = function()
{
    ...
};

And use thusly:

$salt = $generate_salt();

Then, at re-execution of said PHP code, the function simply overwrites the previous declaration.

"The file "MyApp.app" couldn't be opened because you don't have permission to view it" when running app in Xcode 6 Beta 4

I tried all of the listed answers and none of them was useful. The problem was due to existence of an another plist file linked from a submodule via cocoapods. Luckily this was my own module, so I just deleted this plist from the submodule project and reinstalled pods.

solution

Later on I understood that the key of the problem was in the name of that second plist: simply info.plist. You may rename the file and relink it via a sources section of a submodule

That second plist file had a unique name, so Xcode was not supposed to become frustrated. Even my target settings pointed on a main plist, not on a info.plist. Looks like Xcode takes special consideraions about that name

The bug reproduced in Xcode 6.4 and Xcode 7.0

tmux status bar configuration

Do C-b, :show which will show you all your current settings. /green, nnn will find you which properties have been set to green, the default. Do C-b, :set window-status-bg cyan and the bottom bar should change colour.

List available colours for tmux

You can tell more easily by the titles and the colours as they're actually set in your live session :show, than by searching through the man page, in my opinion. It is a very well-written man page when you have the time though.

If you don't like one of your changes and you can't remember how it was originally set, you can open do a new tmux session. To change settings for good edit ~/.tmux.conf with a line like set window-status-bg -g cyan. Here's mine: https://gist.github.com/9083598

How can I get a web site's favicon?

Using jquery

var favicon = $("link[rel='shortcut icon']").attr("href") ||
              $("link[rel='icon']").attr("href") || "";

Dynamically Dimensioning A VBA Array?

You can also look into using the Collection Object. This usually works better than an array for custom objects, since it dynamically sizes and has methods for:

  • Add
  • Count
  • Remove
  • Item(index)

Plus its normally easier to loop through a collection too since you can use the for...each structure very easily with a collection.

Two inline-block, width 50% elements wrap to second line

You can remove the whitespaces via css using white-space so you can keep your pretty HTML layout. Don't forget to set the white-space back to normal again if you want your text to wrap inside the columns.

Tested in IE9, Chrome 18, FF 12

.container { white-space: nowrap; }
.column { display: inline-block; width: 50%; white-space: normal; }

<div class="container">
  <div class="column">text that can wrap</div>
  <div class="column">text that can wrap</div>
</div>

Change the value in app.config file dynamically

This code works for me:

    Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); 
    config.AppSettings.Settings["test"].Value = "blah";       
    config.Save(ConfigurationSaveMode.Modified);
    ConfigurationManager.RefreshSection("appSettings");

Note: it doesn't update the solution item 'app.config', but the '.exe.config' one in the bin/ folder if you run it with F5.

How do I remove duplicates from a C# array?

List<String> myStringList = new List<string>();
foreach (string s in myStringArray)
{
    if (!myStringList.Contains(s))
    {
        myStringList.Add(s);
    }
}

This is O(n^2), which won't matter for a short list which is going to be stuffed into a combo, but could be rapidly be a problem on a big collection.

Error: No toolchains found in the NDK toolchains folder for ABI with prefix: llvm

To continue with your older gradle version, we can use below solution:

Notice the file android-ndk-r17-beta2/toolchains/mips64el-linux-android- 4.9/prebuilt/darwin-x86_64/NOTICE-MIPS64. The content of the file is below.

This mips64el-linux-android-4.9 directory exists to make the NDK compatible with the Android SDK's Gradle plugin, version 3.0.1 and earlier, which expects the NDK to have a MIPS64 toolchain directory.

So, i can say, using Android SDK's Gradle plugin above 3.0.1, or create even a directory marked with 'mipsel' and 'mips64el', can both resolve the problem. The latter method is below.

cd "path-to-ndk"

OS_=$(uname -s | tr [A-Z] [a-z])
mkdir -p toolchains/mipsel-linux-android-4.9/prebuilt/${OS_}-x86_64
touch toolchains/mipsel-linux-android-4.9/prebuilt/${OS_}-x86_64/NOTICE-MIPS
mkdir -p toolchains/mips64el-linux-android-4.9/prebuilt/${OS_}-x86_64
touch toolchains/mips64el-linux-android-4.9/prebuilt/${OS_}-x86_64/NOTICE-MIPS64

Got the solutions from here

jQuery lose focus event

Use blur event to call your function when element loses focus :

$('#filter').blur(function() {
  $('#options').hide();
});

How can I display my windows user name in excel spread sheet using macros?

Range("A1").value = Environ("Username")

This is better than Application.Username, which doesn't always supply the Windows username. Thanks to Kyle for pointing this out.

  • Application Username is the name of the User set in Excel > Tools > Options
  • Environ("Username") is the name you registered for Windows; see Control Panel >System

ASP.NET Core Web API Authentication

I have implemented BasicAuthenticationHandler for basic authentication so you can use it with standart attributes Authorize and AllowAnonymous.

public class BasicAuthenticationHandler : AuthenticationHandler<BasicAuthenticationOptions>
{
    protected override Task<AuthenticateResult> HandleAuthenticateAsync()
    {
        var authHeader = (string)this.Request.Headers["Authorization"];

        if (!string.IsNullOrEmpty(authHeader) && authHeader.StartsWith("basic", StringComparison.OrdinalIgnoreCase))
        {
            //Extract credentials
            string encodedUsernamePassword = authHeader.Substring("Basic ".Length).Trim();
            Encoding encoding = Encoding.GetEncoding("iso-8859-1");
            string usernamePassword = encoding.GetString(Convert.FromBase64String(encodedUsernamePassword));

            int seperatorIndex = usernamePassword.IndexOf(':', StringComparison.OrdinalIgnoreCase);

            var username = usernamePassword.Substring(0, seperatorIndex);
            var password = usernamePassword.Substring(seperatorIndex + 1);

            //you also can use this.Context.Authentication here
            if (username == "test" && password == "test")
            {
                var user = new GenericPrincipal(new GenericIdentity("User"), null);
                var ticket = new AuthenticationTicket(user, new AuthenticationProperties(), Options.AuthenticationScheme);
                return Task.FromResult(AuthenticateResult.Success(ticket));
            }
            else
            {
                return Task.FromResult(AuthenticateResult.Fail("No valid user."));
            }
        }

        this.Response.Headers["WWW-Authenticate"]= "Basic realm=\"yourawesomesite.net\"";
        return Task.FromResult(AuthenticateResult.Fail("No credentials."));
    }
}

public class BasicAuthenticationMiddleware : AuthenticationMiddleware<BasicAuthenticationOptions>
{
    public BasicAuthenticationMiddleware(
       RequestDelegate next,
       IOptions<BasicAuthenticationOptions> options,
       ILoggerFactory loggerFactory,
       UrlEncoder encoder)
       : base(next, options, loggerFactory, encoder)
    {
    }

    protected override AuthenticationHandler<BasicAuthenticationOptions> CreateHandler()
    {
        return new BasicAuthenticationHandler();
    }
}

public class BasicAuthenticationOptions : AuthenticationOptions
{
    public BasicAuthenticationOptions()
    {
        AuthenticationScheme = "Basic";
        AutomaticAuthenticate = true;
    }
}

Registration at Startup.cs - app.UseMiddleware<BasicAuthenticationMiddleware>();. With this code, you can restrict any controller with standart attribute Autorize:

[Authorize(ActiveAuthenticationSchemes = "Basic")]
[Route("api/[controller]")]
public class ValuesController : Controller

and use attribute AllowAnonymous if you apply authorize filter on application level.

How to make Git "forget" about a file that was tracked but is now in .gitignore?

I liked JonBrave's answer but I have messy enough working directories that commit -a scares me a bit, so here's what I've done:

git config --global alias.exclude-ignored '!git ls-files -z --ignored --exclude-standard | xargs -0 git rm -r --cached && git ls-files -z --ignored --exclude-standard | xargs -0 git stage && git stage .gitignore && git commit -m "new gitignore and remove ignored files from index"'

breaking it down:

git ls-files -z --ignored --exclude-standard | xargs -0 git rm -r --cached 
git ls-files -z --ignored --exclude-standard | xargs -0 git stage 
git stage .gitignore 
git commit -m "new gitignore and remove ignored files from index"
  • remove ignored files from index
  • stage .gitignore and the files you just removed
  • commit

What is the difference between String and StringBuffer in Java?

Performance wise StringBuffer is much better than String ; because whenever you apply concatenation on String Object then new String object are created on each concatenation.

Principal Rule : String are immutable(Non Modifiable) and StringBuffer are mutable(Modifiable)

Here is the programmatic experiment where you get the performance difference

public class Test {

  public static int LOOP_ITERATION= 100000;

  public static void stringTest(){
    long startTime = System.currentTimeMillis();
    String string = "This";
    for(int i=0;i<LOOP_ITERATION;i++){
        string = string+"Yasir";
    }

    long endTime = System.currentTimeMillis();
    System.out.println(endTime - startTime);    
  }

  public static void stringBufferTest(){
    long startTime = System.currentTimeMillis();
    StringBuffer stringBuffer = new StringBuffer("This");
    for(int i=0;i<LOOP_ITERATION;i++){
        stringBuffer.append("Yasir");
    }

    long endTime = System.currentTimeMillis();
    System.out.println(endTime - startTime);
  }

  public static void main(String []args){
    stringTest()
    stringBufferTest(); 
  }
 }

Output of String are in my machine 14800

Output of StringBuffer are in my machine 14

How do I extract Month and Year in a MySQL date and compare them?

You may want to check out the mySQL docs in regard to the date functions. http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html

There is a YEAR() function just as there is a MONTH() function. If you're doing a comparison though is there a reason to chop up the date? Are you truly interested in ignoring day based differences and if so is this how you want to do it?

Stop fixed position at footer

I've made some changes to the second most popular answer as i found this worked better for me. The changes use window.innerHeight as it is more dynamic than adding your own height for the nav (above used + 570). this allows the code to work on mobile, tablet and desktop dynamicly.

$(window).scroll(() => {
            //Distance from top fo document to top of footer
            topOfFooter = $('#footer').position().top;
             // Distance user has scrolled from top + windows inner height
             scrollDistanceFromTopOfDoc = $(document).scrollTop() + window.innerHeight;
             // Difference between the two.
             scrollDistanceFromTopOfFooter = scrollDistanceFromTopOfDoc - topOfFooter; 
            // If user has scrolled further than footer,
              if (scrollDistanceFromTopOfDoc > topOfFooter) {
                // add margin-bottom so button stays above footer.
                $('#floating-button').css('margin-bottom',  0 + scrollDistanceFromTopOfFooter);
              } else  {
                // remove margin-bottom so button goes back to the bottom of the page
                $('#floating-button').css('margin-bottom', 0);
              }
            });

JavaScript - populate drop down list with array

You'll first get the dropdown element from the DOM, then loop through the array, and add each element as a new option in the dropdown like this:

// Get dropdown element from DOM
var dropdown = document.getElementById("selectNumber");

// Loop through the array
for (var i = 0; i < myArray.length; ++i) {
    // Append the element to the end of Array list
    dropdown[dropdown.length] = new Option(myArray[i], myArray[i]);
}?

See JSFiddle for a live demo: http://jsfiddle.net/nExgJ/

This assumes that you're not using JQuery, and you only have the basic DOM API to work with.

Counting how many times a certain char appears in a string before any other char appears

One approach you could take is the following method:

// Counts how many of a certain character occurs in the given string
public static int CharCountInString(char chr, string str)
{
    return str.Split(chr).Length-1;
}

As per the parameters this method returns the count of a specific character within a specific string.

This method works by splitting the string into an array by the specified character and then returning the length of that array -1.

PHP removing a character in a string

While a regexp would suit here just fine, I'll present you with an alternative method. It might be a tad faster than the equivalent regexp, but life's all about choices (...or something).

$length = strlen($urlString);
for ($i=0; $i<$length; i++) {
  if ($urlString[$i] === '?') {
    $urlString[$i+1] = '';
    break;
  }
}

Weird, I know.

Making an API call in Python with an API that requires a bearer token

The token has to be placed in an Authorization header according to the following format:

Authorization: Bearer [Token_Value]

Code below:

import urllib2
import json

def get_auth_token():
    """
    get an auth token
    """
    req=urllib2.Request("https://xforce-api.mybluemix.net/auth/anonymousToken")
    response=urllib2.urlopen(req)
    html=response.read()
    json_obj=json.loads(html)
    token_string=json_obj["token"].encode("ascii","ignore")
    return token_string

def get_response_json_object(url, auth_token):
    """
    returns json object with info
    """
    auth_token=get_auth_token()
    req=urllib2.Request(url, None, {"Authorization": "Bearer %s" %auth_token})
    response=urllib2.urlopen(req)
    html=response.read()
    json_obj=json.loads(html)
    return json_obj

How to use 'cp' command to exclude a specific directory?

cp -rv `ls -A | grep -vE "dirToExclude|targetDir"` targetDir

Edit: forgot to exclude the target path as well (otherwise it would recursively copy).

Git: See my last commit

Another way to list only the files is to use:
git diff-tree --no-commit-id --name-only -r HEAD^..HEAD
Or you can use any two commit IDs