Programs & Examples On #Django filters

cursor.fetchall() vs list(cursor) in Python

cursor.fetchall() and list(cursor) are essentially the same. The different option is to not retrieve a list, and instead just loop over the bare cursor object:

for result in cursor:

This can be more efficient if the result set is large, as it doesn't have to fetch the entire result set and keep it all in memory; it can just incrementally get each item (or batch them in smaller batches).

how to overcome ERROR 1045 (28000): Access denied for user 'ODBC'@'localhost' (using password: NO) permanently

i entered in Mysql Workbench and i changed the password. It seem the password was expired. it works!

how to use JSON.stringify and json_decode() properly

I don't how this works, but it worked.

$post_data = json_decode(json_encode($_POST['request_key']));

horizontal line and right way to code it in html, css

I'd go for semantic markup, use an <hr/>.

Unless it's just a border what you want, then you can use a combination of padding, border and margin, to get the desired bound.

Passive Link in Angular 2 - <a href=""> equivalent

In my case deleting href attribute solve problem as long there is a click function assign to a.

Using an Alias in a WHERE clause

It's possible to effectively define a variable that can be used in both the SELECT, WHERE and other clauses.

A subquery doesn't necessarily allow for appropriate binding to the referenced table columns, however OUTER APPLY does.

SELECT A.identifier
     , A.name
     , vars.MONTH_NO
     , TO_NUMBER(TO_CHAR(B.last_update_date, 'YYYYMM')) as UPD_DATE
FROM table_a A
     , table_b B ON A.identifier = B.identifier
OUTER APPLY (
   SELECT
        -- variables
        MONTH_NO = TO_NUMBER(DECODE( A.month_no
                     , 1, 200803 
                     , 2, 200804 
                     , 3, 200805 
                     , 4, 200806 
                     , 5, 200807 
                     , 6, 200808 
                     , 7, 200809 
                     , 8, 200810 
                     , 9, 200811 
                     , 10, 200812 
                     , 11, 200701 
                     , 12, 200702
                     , NULL))
) vars
WHERE vars.MONTH_NO > UPD_DATE

Kudos to Syed Mehroz Alam.

importing go files in same folder

Any number of files in a directory are a single package; symbols declared in one file are available to the others without any imports or qualifiers. All of the files do need the same package foo declaration at the top (or you'll get an error from go build).

You do need GOPATH set to the directory where your pkg, src, and bin directories reside. This is just a matter of preference, but it's common to have a single workspace for all your apps (sometimes $HOME), not one per app.

Normally a Github path would be github.com/username/reponame (not just github.com/xxxx). So if you want to have main and another package, you may end up doing something under workspace/src like

github.com/
  username/
    reponame/
      main.go   // package main, importing "github.com/username/reponame/b"
      b/
        b.go    // package b

Note you always import with the full github.com/... path: relative imports aren't allowed in a workspace. If you get tired of typing paths, use goimports. If you were getting by with go run, it's time to switch to go build: run deals poorly with multiple-file mains and I didn't bother to test but heard (from Dave Cheney here) go run doesn't rebuild dirty dependencies.

Sounds like you've at least tried to set GOPATH to the right thing, so if you're still stuck, maybe include exactly how you set the environment variable (the command, etc.) and what command you ran and what error happened. Here are instructions on how to set it (and make the setting persistent) under Linux/UNIX and here is the Go team's advice on workspace setup. Maybe neither helps, but take a look and at least point to which part confuses you if you're confused.

Generating random integer from a range

If your compiler supports C++0x and using it is an option for you, then the new standard <random> header is likely to meet your needs. It has a high quality uniform_int_distribution which will accept minimum and maximum bounds (inclusive as you need), and you can choose among various random number generators to plug into that distribution.

Here is code that generates a million random ints uniformly distributed in [-57, 365]. I've used the new std <chrono> facilities to time it as you mentioned performance is a major concern for you.

#include <iostream>
#include <random>
#include <chrono>

int main()
{
    typedef std::chrono::high_resolution_clock Clock;
    typedef std::chrono::duration<double> sec;
    Clock::time_point t0 = Clock::now();
    const int N = 10000000;
    typedef std::minstd_rand G;
    G g;
    typedef std::uniform_int_distribution<> D;
    D d(-57, 365);
    int c = 0;
    for (int i = 0; i < N; ++i) 
        c += d(g);
    Clock::time_point t1 = Clock::now();
    std::cout << N/sec(t1-t0).count() << " random numbers per second.\n";
    return c;
}

For me (2.8 GHz Intel Core i5) this prints out:

2.10268e+07 random numbers per second.

You can seed the generator by passing in an int to its constructor:

    G g(seed);

If you later find that int doesn't cover the range you need for your distribution, this can be remedied by changing the uniform_int_distribution like so (e.g. to long long):

    typedef std::uniform_int_distribution<long long> D;

If you later find that the minstd_rand isn't a high enough quality generator, that can also easily be swapped out. E.g.:

    typedef std::mt19937 G;  // Now using mersenne_twister_engine

Having separate control over the random number generator, and the random distribution can be quite liberating.

I've also computed (not shown) the first 4 "moments" of this distribution (using minstd_rand) and compared them to the theoretical values in an attempt to quantify the quality of the distribution:

min = -57
max = 365
mean = 154.131
x_mean = 154
var = 14931.9
x_var = 14910.7
skew = -0.00197375
x_skew = 0
kurtosis = -1.20129
x_kurtosis = -1.20001

(The x_ prefix refers to "expected")

Percentage Height HTML 5/CSS

bobince's answer will let you know in which cases "height: XX%;" will or won't work.

If you want to create an element with a set ratio (height: % of it's own width), the best way to do that is by effectively setting the height using padding-bottom. Example for square:

<div class="square-container">
  <div class="square-content">
    <!-- put your content in here -->
  </div>
</div>

.square-container {  /* any display: block; element */
  position: relative;
  height: 0;
  padding-bottom: 100%; /* of parent width */
}
.square-content {
  position: absolute;
  left: 0;
  top: 0;
  height: 100%;
  width: 100%;
}

The square container will just be made of padding, and the content will expand to fill the container. Long article from 2009 on this subject: http://alistapart.com/article/creating-intrinsic-ratios-for-video

Can't specify the 'async' modifier on the 'Main' method of a console app

Haven't needed this much yet, but when I've used console application for Quick tests and required async I've just solved it like this:

class Program
{
    static void Main(string[] args)
    {
        MainAsync(args).Wait();
    }

    static async Task MainAsync(string[] args)
    {
        // Code here
    }
}

How to make JavaScript execute after page load?

Comparison

In below snippet I collect choosen methods and show their sequence. Remarks

  • the document.onload (X) is not supported by any modern browser (event is never fired)
  • if you use <body onload="bodyOnLoad()"> (F) and at the same time window.onload (E) then only first one will be executed (because it override second one)
  • event handler given in <body onload="..."> (F) is wrapped by additional onload function
  • document.onreadystatechange (D) not override document .addEventListener('readystatechange'...) (C) probably cecasue onXYZevent-like methods are independent than addEventListener queues (which allows add multiple listeners). Probably nothing happens between execution this two handlers.
  • all scripts write their timestamp in console - but scripts which also have access to div write their timestamps also in body (click "Full Page" link after script execution to see it).
  • solutions readystatechange (C,D) are executed multiple times by browser but for different document states:
    • loading - the document is loading (no fired in snippet)
    • interactive - the document is parsed, fired before DOMContentLoaded
    • complete - the document and resources are loaded, fired before body/window onload

_x000D_
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <script>_x000D_
    // solution A_x000D_
    console.log(`[timestamp: ${Date.now()}] A: Head script`);_x000D_
    _x000D_
    // solution B_x000D_
    document.addEventListener("DOMContentLoaded", () => {_x000D_
      print(`[timestamp: ${Date.now()}] B: DOMContentLoaded`);_x000D_
    });_x000D_
_x000D_
    // solution C_x000D_
    document.addEventListener('readystatechange', () => {_x000D_
      print(`[timestamp: ${Date.now()}] C: ReadyState: ${document.readyState}`);_x000D_
    });_x000D_
   _x000D_
    // solution D_x000D_
    document.onreadystatechange = s=> {print(`[timestamp: ${Date.now()}] D: document.onreadystatechange ReadyState: ${document.readyState}`)};_x000D_
    _x000D_
    // solution E (never executed)_x000D_
    window.onload = () => {_x000D_
      print(`E: <body onload="..."> override this handler`);_x000D_
    };_x000D_
_x000D_
    // solution F_x000D_
    function bodyOnLoad() {_x000D_
      print(`[timestamp: ${Date.now()}] F: <body onload='...'>`);      _x000D_
      infoAboutOnLoad(); // additional info_x000D_
    }_x000D_
    _x000D_
    // solution X_x000D_
    document.onload = () => {print(`document.onload is never fired`)};_x000D_
_x000D_
_x000D_
_x000D_
    // HELPERS_x000D_
_x000D_
    function print(txt) { _x000D_
      console.log(txt);_x000D_
      if(mydiv) mydiv.innerHTML += txt.replace('<','&lt;').replace('>','&gt;') + '<br>';_x000D_
    }_x000D_
    _x000D_
    function infoAboutOnLoad() {_x000D_
      console.log("window.onload (after  override):", (''+document.body.onload).replace(/\s+/g,' '));_x000D_
      console.log(`body.onload==window.onload --> ${document.body.onload==window.onload}`);_x000D_
    }_x000D_
            _x000D_
    console.log("window.onload (before override):", (''+document.body.onload).replace(/\s+/g,' '));_x000D_
_x000D_
  </script>_x000D_
</head>_x000D_
_x000D_
<body onload="bodyOnLoad()">_x000D_
  <div id="mydiv"></div>_x000D_
_x000D_
  <!-- this script must te at the bottom of <body> -->_x000D_
  <script>_x000D_
    // solution G_x000D_
    print(`[timestamp: ${Date.now()}] G: <body> bottom script`);_x000D_
  </script>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

VBA Subscript out of range - error 9

Suggest the following simplification: capture return value from Workbooks.Add instead of subscripting Windows() afterward, as follows:

Set wkb = Workbooks.Add
wkb.SaveAs ...

wkb.Activate ' instead of Windows(expression).Activate


General Philosophy Advice:

Avoid use Excel's built-ins: ActiveWorkbook, ActiveSheet, and Selection: capture return values, and, favor qualified expressions instead.

Use the built-ins only once and only in outermost macros(subs) and capture at macro start, e.g.

Set wkb = ActiveWorkbook
Set wks = ActiveSheet
Set sel = Selection

During and within macros do not rely on these built-in names, instead capture return values, e.g.

Set wkb = Workbooks.Add 'instead of Workbooks.Add without return value capture
wkb.Activate 'instead of Activeworkbook.Activate

Also, try to use qualified expressions, e.g.

wkb.Sheets("Sheet3").Name = "foo" ' instead of Sheets("Sheet3").Name = "foo"

or

Set newWks = wkb.Sheets.Add
newWks.Name = "bar" 'instead of ActiveSheet.Name = "bar"

Use qualified expressions, e.g.

newWks.Name = "bar" 'instead of `xyz.Select` followed by Selection.Name = "bar" 

These methods will work better in general, give less confusing results, will be more robust when refactoring (e.g. moving lines of code around within and between methods) and, will work better across versions of Excel. Selection, for example, changes differently during macro execution from one version of Excel to another.

Also please note that you'll likely find that you don't need to .Activate nearly as much when using more qualified expressions. (This can mean the for the user the screen will flicker less.) Thus the whole line Windows(expression).Activate could simply be eliminated instead of even being replaced by wkb.Activate.

(Also note: I think the .Select statements you show are not contributing and can be omitted.)

(I think that Excel's macro recorder is responsible for promoting this more fragile style of programming using ActiveSheet, ActiveWorkbook, Selection, and Select so much; this style leaves a lot of room for improvement.)

What is the relative performance difference of if/else versus switch statement in Java?

A good explanation at the link below:
https://www.geeksforgeeks.org/switch-vs-else/

Test(c++17)
1 - If grouped
2 - If sequential
3 - Goto Array
4 - Switch Case - Jump Table
https://onlinegdb.com/Su7HNEBeG

Numpy isnan() fails on an array of floats (from pandas dataframe apply)

A great substitute for np.isnan() and pd.isnull() is

for i in range(0,a.shape[0]):
    if(a[i]!=a[i]):
       //do something here
       //a[i] is nan

since only nan is not equal to itself.

Hashing with SHA1 Algorithm in C#

public string Hash(byte [] temp)
{
    using (SHA1Managed sha1 = new SHA1Managed())
    {
        var hash = sha1.ComputeHash(temp);
        return Convert.ToBase64String(hash);
    }
}

EDIT:

You could also specify the encoding when converting the byte array to string as follows:

return System.Text.Encoding.UTF8.GetString(hash);

or

return System.Text.Encoding.Unicode.GetString(hash);

How to change the author and committer name and e-mail of multiple commits in Git?

I would like to contribute with a modification of @Rognon answer. This answer is just another alternative in case the selected answer or others don't work for you (in my particular issue that was the case):

Objective: You will fix one or more authors with a correct one in the ALL the history, and you will get a clean history without duplicates. This method works by replacing 'master' branch with a 'clean' branch (its not using merge/rebase)

NOTE: Anyone using the "master" repository may need to checkout it again (after performing these steps) before pushing, as merge may fail.

We will use a new branch named "clean" to perform the operations (assuming you want to fix "master"):

git checkout -b clean

(be sure you are in the "clean" branch: git branch)

Modify the following script (replacing the email addresses and names). Note that this script expects two wrong emails/authors (as example), so if you only need to fix a single author, you can remove the second part of the condition or leave it like that (as it will be ignored as it won't match).

Execute the script.

#/bin/bash

git filter-branch --force --commit-filter '
        if [ "$GIT_COMMITTER_EMAIL" = "[email protected]" -o "$GIT_COMMITTER_EMAIL" = "[email protected]" ];
        then
                export GIT_COMMITTER_NAME="John Doe";
                export GIT_AUTHOR_NAME="John Doe";
                export GIT_COMMITTER_EMAIL="[email protected]";
                export GIT_AUTHOR_EMAIL="[email protected]";
        fi;
        git commit-tree "$@"
' --tag-name-filter cat -- --all

It has to report: Ref 'refs/heads/clean' was rewritten. If it reports "unchanged", maybe the email(s) entered in the script is wrong.

Confirm the history has been corrected with: git log

If you are using github/gitlab (recommended = safe):

  1. create the "clean" branch in remote:

git push --set-upstream origin clean

  1. set "clean" branch as default branch
  2. remove "master" (be sure everything is as expected before doing this).
  3. Create a new branch "master" based in "clean" branch.
  4. After confirming all is good, you can remove "clean" branch now (alternative you can just rename it).

If are not using github/gitlab or you prefer doing it by command:

  1. Delete the master branch from local:

git branch -d master

  1. Rename the branch:

git branch -m clean master

  1. Push it (be sure you "master" is unprotected)

git push --force origin master

Virtual member call in a constructor

Another interesting thing I found is that the ReSharper error can be 'satisfied' by doing something like below which is dumb to me. However, as mentioned by many earlier, it still is not a good idea to call virtual properties/methods in constructor.

public class ConfigManager
{
   public virtual int MyPropOne { get; private set; }
   public virtual string MyPropTwo { get; private set; }

   public ConfigManager()
   {
    Setup();
   }

   private void Setup()
   {
    MyPropOne = 1;
    MyPropTwo = "test";
   }
}

Best practice when adding whitespace in JSX

I have been trying to think of a good convention to use when placing text next to components on different lines, and found a couple good options:

<p>
    Hello {
        <span>World</span>
    }!
</p>

or

<p>
    Hello {}
    <span>World</span>
    {} again!
</p>

Each of these produces clean html without additional &nbsp; or other extraneous markup. It creates fewer text nodes than using {' '}, and allows using of html entities where {' hello &amp; goodbye '} does not.

How to correctly get image from 'Resources' folder in NetBeans

For me it worked like I had images in icons folder under src and I wrote below code.

new ImageIcon(getClass().getResource("/icons/rsz_measurment_01.png"));

What is the difference between encode/decode?

There are a few encodings that can be used to de-/encode from str to str or from unicode to unicode. For example base64, hex or even rot13. They are listed in the codecs module.

Edit:

The decode message on a unicode string can undo the corresponding encode operation:

In [1]: u'0a'.decode('hex')
Out[1]: '\n'

The returned type is str instead of unicode which is unfortunate in my opinion. But when you are not doing a proper en-/decode between str and unicode this looks like a mess anyway.

Creating default object from empty value in PHP?

You may need to check if variable declared and has correct type.

if (!isset($res) || !is_object($res)) {
    $res = new \stdClass();
    // With php7 you also can create an object in several ways.
    // Object that implements some interface.
    $res = new class implements MyInterface {};
    // Object that extends some object.
    $res = new class extends MyClass {};
} 

$res->success = true;

See PHP anonymous classes.

How to print strings with line breaks in java

OK, finally I found a good solution for my bill printing task and it is working properly for me.

This class provides the print service

public class PrinterService {

    public PrintService getCheckPrintService(String printerName) {
        PrintService ps = null;
        DocFlavor doc_flavor = DocFlavor.STRING.TEXT_PLAIN;
        PrintRequestAttributeSet attr_set =
                new HashPrintRequestAttributeSet();

        attr_set.add(new Copies(1));           
        attr_set.add(Sides.ONE_SIDED);
        PrintService[] service = PrintServiceLookup.lookupPrintServices(doc_flavor, attr_set);

        for (int i = 0; i < service.length; i++) {
            System.out.println(service[i].getName());
            if (service[i].getName().equals(printerName)) {
                ps = service[i];
            }
        }
        return ps;
    }
}

This class demonstrates the bill printing task,

public class HelloWorldPrinter implements Printable {

    @Override
    public int print(Graphics graphics, PageFormat pageFormat, int pageIndex) throws PrinterException {
        if (pageIndex > 0) { /* We have only one page, and 'page' is zero-based */
            return NO_SUCH_PAGE;
        }

        Graphics2D g2d = (Graphics2D) graphics;
        g2d.translate(pageFormat.getImageableX(), pageFormat.getImageableY());

        //the String to print in multiple lines
        //writing a semicolon (;) at the end of each sentence
        String mText = "SHOP MA;"
                + "Pannampitiya;"
                + "----------------------------;"
                + "09-10-2012 harsha  no: 001 ;"
                + "No  Item  Qty  Price  Amount ;"
                + "----------------------------;"
                + "1 Bread 1 50.00  50.00 ;"
                + "----------------------------;";

        //Prepare the rendering
        //split the String by the semicolon character
        String[] bill = mText.split(";");
        int y = 15;
        Font f = new Font(Font.SANS_SERIF, Font.PLAIN, 8);
        graphics.setFont(f);
        //draw each String in a separate line
        for (int i = 0; i < bill.length; i++) {
            graphics.drawString(bill[i], 5, y);
            y = y + 15;
        }

        /* tell the caller that this page is part of the printed document */
        return PAGE_EXISTS;
    }

    public void pp() throws PrinterException {
        PrinterService ps = new PrinterService();
        //get the printer service by printer name
        PrintService pss = ps.getCheckPrintService("Deskjet-1000-J110-series-2");

        PrinterJob job = PrinterJob.getPrinterJob();
        job.setPrintService(pss);
        job.setPrintable(this);

        try {
            job.print();
        } catch (PrinterException ex) {
            ex.printStackTrace();
        }

    }

    public static void main(String[] args) {
        HelloWorldPrinter hwp = new HelloWorldPrinter();
        try {
            hwp.pp();
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}

How to use foreach with a hash reference?

So, with Perl 5.20, the new answer is:

foreach my $key (keys $ad_grp_ref->%*) {

(which has the advantage of transparently working with more complicated expressions:

foreach my $key (keys $ad_grp_obj[3]->get_ref()->%*) {

etc.)

See perlref for the full documentation.

Note: in Perl version 5.20 and 5.22, this syntax is considered experimental, so you need

use feature 'postderef';
no warnings 'experimental::postderef';

at the top of any file that uses it. Perl 5.24 and later don't require any pragmas for this feature.

Latest jQuery version on Google's CDN

Here's an updated link.

There are updated now and then, just keep checking for the latest version.

Using an image caption in Markdown Jekyll

Andrew's @andrew-wei answer works great. You can also chain a few together, depending on what you are trying to do. This, for example, gets you an image with alt, title and caption with a line break and bold and italics in different parts of the caption:

img + br + strong {margin-top: 5px; margin-bottom: 7px; font-style:italic; font-size: 12px; }
img + br + strong + em {margin-top: 5px; margin-bottom: 7px; font-size: 12px; font-style:italic;}

With the following <img> markdown:

![description](https://img.jpg "description")
***Image:*** *description*

Groovy method with optional parameters

You can use arguments with default values.

def someMethod(def mandatory,def optional=null){}

if argument "optional" not exist, it turns to "null".

Copying files from server to local computer using SSH

Your question is a bit confusing, but I am assuming - you are first doing 'ssh' to find out which files or rather specifically directories are there and then again on your local computer, you are trying to scp 'all' files in that directory to local path. you should simply do scp -r.

So here in your case it'd be something like

local> scp -r [email protected]:/path/to/dir local/path 

If youare using some other executable that provides 'scp like functionality', refer to it's manual for recursively copying files.

Differences between hard real-time, soft real-time, and firm real-time?

Hard Real-Time

The hard real-time definition considers any missed deadline to be a system failure. This scheduling is used extensively in mission critical systems where failure to conform to timing constraints results in a loss of life or property.

Examples:

  • Air France Flight 447 crashed into the ocean after a sensor malfunction caused a series of system errors. The pilots stalled the aircraft while responding to outdated instrument readings. All 12 crew and 216 passengers were killed.

  • Mars Pathfinder spacecraft was nearly lost when a priority inversion caused system restarts. A higher priority task was not completed on time due to being blocked by a lower priority task. The problem was corrected and the spacecraft landed successfully.

  • An Inkjet printer has a print head with control software for depositing the correct amount of ink onto a specific part of the paper. If a deadline is missed then the print job is ruined.


Firm Real-Time

The firm real-time definition allows for infrequently missed deadlines. In these applications the system can survive task failures so long as they are adequately spaced, however the value of the task's completion drops to zero or becomes impossible.

Examples:

  • Manufacturing systems with robot assembly lines where missing a deadline results in improperly assembling a part. As long as ruined parts are infrequent enough to be caught by quality control and not too costly, then production continues.

  • A digital cable set-top box decodes time stamps for when frames must appear on the screen. Since the frames are time order sensitive a missed deadline causes jitter, diminishing quality of service. If the missed frame later becomes available it will only cause more jitter to display it, so it's useless. The viewer can still enjoy the program if jitter doesn't occur too often.


Soft Real-Time

The soft real-time definition allows for frequently missed deadlines, and as long as tasks are timely executed their results continue to have value. Completed tasks may have increasing value up to the deadline and decreasing value past it.

Examples:

  • Weather stations have many sensors for reading temperature, humidity, wind speed, etc. The readings should be taken and transmitted at regular intervals, however the sensors are not synchronized. Even though a sensor reading may be early or late compared with the others it can still be relevant as long as it is close enough.

  • A video game console runs software for a game engine. There are many resources that must be shared between its tasks. At the same time tasks need to be completed according to the schedule for the game to play correctly. As long as tasks are being completely relatively on time the game will be enjoyable, and if not it may only lag a little.


Siewert: Real-Time Embedded Systems and Components.
Liu & Layland: Scheduling Algorithms for Multiprogramming in a Hard Real-Time Environment.
Marchand & Silly-Chetto: Dynamic Scheduling of Soft Aperiodic Tasks and Periodic Tasks with Skips.

[ :Unexpected operator in shell programming

you can use case/esac instead of if/else

case "$choose" in
  [yY]) echo "Yes" && exit;;
  [nN]) echo "No" && exit;;
  * ) echo "wrong input" && exit;;
esac

How can I clear the terminal in Visual Studio Code?

To clear Terminal in VS Code simply press Ctrl + Shift + P key together this will open a command palette and type command Terminal: Clear. Also you will go to View in taskbar upper left corner of vs code and open Command pallete.

This will clear the terminal easily & work for any directory you have open in your terminal. This is for Windows, also try if it works for Mac.

This is command is work in all VS code versions include latest version 1.52.1

dotnet ef not found in .NET Core 3

For me, The problem was solved after I close Visual Studio and Open it again

How to load/reference a file as a File instance from the classpath

I find this one-line code as most efficient and useful:

File file = new File(ClassLoader.getSystemResource("com/path/to/file.txt").getFile());

Works like a charm.

How to export a Vagrant virtual machine to transfer it

My hard drive in my Mac was making beeping noises in the middle of a project so I decided to install a SSD. I needed to move my project from one disk to another. A few things to consider:

  • I'm vagrant w/ virtualbox on a Mac
  • I'm using git

This is what worked for me:

1.) Copy your ~/.vagrant.d directory to your new machine.
2.) Copy your ~/VirtualBox\ VMs directory to your new machine. 
3.) In VirtualBox add the machines one by one using **Machine** >> **Add**
4.) Run `vagrant box list` to see if vagrant acknowledges your machines. 
5.) `git clone my_project`
6.) `vagrant up`

I had a few problems with VB Guest additions.

enter image description here

I fixed them with this solution.

Xcode project not showing list of simulators

Try This, It worked like a charm! for me,

Follow below step

1) Clean Derived Data as show below,

 rm -rf ~/Library/Developer/Xcode/DerivedData/

OR

 Xcode---> Preferences--->Location--->Derived Data

Derived Data

2) In Deployment Info change Deployment Target

It's equal to or less then the SDK version of Xcode

enter image description here

3) Quit Xcode

enter image description here

4) Reopen Xcode you will see list of simulators

enter image description here

Hope this answer will help for someone.

What does `unsigned` in MySQL mean and when to use it?

MySQL says:

All integer types can have an optional (nonstandard) attribute UNSIGNED. Unsigned type can be used to permit only nonnegative numbers in a column or when you need a larger upper numeric range for the column. For example, if an INT column is UNSIGNED, the size of the column's range is the same but its endpoints shift from -2147483648 and 2147483647 up to 0 and 4294967295.

When do I use it ?

Ask yourself this question: Will this field ever contain a negative value?
If the answer is no, then you want an UNSIGNED data type.

A common mistake is to use a primary key that is an auto-increment INT starting at zero, yet the type is SIGNED, in that case you’ll never touch any of the negative numbers and you are reducing the range of possible id's to half.

How to align two divs side by side using the float, clear, and overflow elements with a fixed position div/

Try this:

<div id="wrapper">
    <div class="float left">left</div>
    <div class="float right">right</div>
</div>

#wrapper {
   width:500px; 
   height:300px; 
   position:relative;
}

.float {
   background-color:black; 
   height:300px; 
   margin:0; 
   padding:0; 
   color:white;
}

.left {
   background-color:blue; 
   position:fixed; 
   width:400px;
}

.right {
   float:right; 
   width:100px;
}

jsFiddle: http://jsfiddle.net/khA4m

Change the fill color of a cell based on a selection from a Drop Down List in an adjacent cell

this is the easiest way: Make list
Select list
right click: Define Name (e.g. ItemStatus)
select a cell where the list should appear (copy paste can be done later, so not location critical)
Data > Data Validation
Allow: Select List
Source: =ItemStatus (don't forget the = sign)
click Ok
dropdown appears in the cell you selected
Home > Conditional Formatting
Manage Rules
New Rule
etc.

Parsing JSON in Excel VBA

Another Regex based JSON parser (decode only)

Private Enum JsonStep
    jsonString
    jsonNumber
    jsonTrue
    jsonFalse
    jsonNull
    jsonOpeningBrace
    jsonClosingBrace
    jsonOpeningBracket
    jsonClosingBracket
    jsonComma
    jsonColon
End Enum

Private regexp As Object

Private Function JsonStepName(ByVal json_step As JsonStep) As String
    Select Case json_step
        Case jsonString: JsonStepName = "'STRING'"
        Case jsonNumber: JsonStepName = "'NUMBER'"
        Case jsonTrue: JsonStepName = "true"
        Case jsonFalse: JsonStepName = "false"
        Case jsonNull: JsonStepName = "null"
        Case jsonOpeningBrace: JsonStepName = "'{'"
        Case jsonClosingBrace: JsonStepName = "'}'"
        Case jsonOpeningBracket: JsonStepName = "'['"
        Case jsonClosingBracket: JsonStepName = "']'"
        Case jsonComma: JsonStepName = "','"
        Case jsonColon: JsonStepName = "':'"
    End Select
End Function

Private Function Unescape(ByVal str As String) As String
    Dim match As Object

    str = Replace$(str, "\""", """")
    str = Replace$(str, "\\", "\")
    str = Replace$(str, "\/", "/")
    str = Replace$(str, "\b", vbBack)
    str = Replace$(str, "\f", vbFormFeed)
    str = Replace$(str, "\n", vbCrLf)
    str = Replace$(str, "\r", vbCr)
    str = Replace$(str, "\t", vbTab)
    With regexp
        .Global = True
        .IgnoreCase = False
        .MultiLine = False
        .Pattern = "\\u([0-9a-fA-F]{4})"
        For Each match In .Execute(str)
            str = Replace$(str, match.value, ChrW$(Val("&H" + match.SubMatches(0))), match.FirstIndex + 1, 1)
        Next match
    End With
    Unescape = str
End Function

Private Function ParseStep(ByVal str As String, _
                           ByRef index As Long, _
                           ByRef value As Variant, _
                           ByVal json_step As JsonStep, _
                           ByVal expected As Boolean) As Boolean
    Dim match As Object

    With regexp
        .Global = False
        .IgnoreCase = False
        .MultiLine = False
        Select Case json_step
            'Case jsonString: .Pattern = "^\s*""(([^\\""]+|\\[""\\/bfnrt]|\\u[0-9a-fA-F]{4})*)""\s*"
            Case jsonString: .Pattern = "^\s*""([^\\""]+|([^\\""]+|\\[""\\/bfnrt]|\\u[0-9a-fA-F]{4})*)""\s*"
            Case jsonNumber: .Pattern = "^\s*(-?(0|[1-9]\d*)(\.\d+)?([eE][-+]?\d+)?)\s*"
            Case jsonTrue: .Pattern = "^\s*(true)\s*"
            Case jsonFalse: .Pattern = "^\s*(false)\s*"
            Case jsonNull: .Pattern = "^\s*(null)\s*"
            Case jsonOpeningBrace: .Pattern = "^\s*(\{)\s*"
            Case jsonClosingBrace: .Pattern = "^\s*(\})\s*"
            Case jsonOpeningBracket: .Pattern = "^\s*(\[)\s*"
            Case jsonClosingBracket: .Pattern = "^\s*(\])\s*"
            Case jsonComma: .Pattern = "^\s*(\,)\s*"
            Case jsonColon: .Pattern = "^\s*(:)\s*"
        End Select
        Set match = .Execute(Mid$(str, index))
    End With
    If match.Count > 0 Then
        index = index + match(0).Length
        Select Case json_step
            Case jsonString
                If match(0).SubMatches(1) = Empty Then
                    value = match(0).SubMatches(0)
                Else
                    value = Unescape(match(0).SubMatches(0))
                End If
            Case jsonNumber: value = Val(match(0).SubMatches(0))
            Case jsonTrue: value = True
            Case jsonFalse: value = False
            Case jsonNull: value = Null
            Case Else: value = Empty
        End Select
        ParseStep = True
    ElseIf expected Then
        Err.Raise 10001, "ParseJson", "Expecting " & JsonStepName(json_step) & " at char " & index & "."
    End If
End Function

Private Function ParseValue(ByRef str As String, _
                            ByRef index As Long, _
                            ByRef value As Variant, _
                            ByVal expected As Boolean) As Boolean
    ParseValue = True
    If ParseStep(str, index, value, jsonString, False) Then Exit Function
    If ParseStep(str, index, value, jsonNumber, False) Then Exit Function
    If ParseObject(str, index, value, False) Then Exit Function
    If ParseArray(str, index, value, False) Then Exit Function
    If ParseStep(str, index, value, jsonTrue, False) Then Exit Function
    If ParseStep(str, index, value, jsonFalse, False) Then Exit Function
    If ParseStep(str, index, value, jsonNull, False) Then Exit Function
    ParseValue = False
    If expected Then
        Err.Raise 10001, "ParseJson", "Expecting " & JsonStepName(jsonString) & ", " & JsonStepName(jsonNumber) & ", " & JsonStepName(jsonTrue) & ", " & JsonStepName(jsonFalse) & ", " & JsonStepName(jsonNull) & ", " & JsonStepName(jsonOpeningBrace) & ", or " & JsonStepName(jsonOpeningBracket) & " at char " & index & "."
    End If
End Function

Private Function ParseObject(ByRef str As String, _
                             ByRef index As Long, _
                             ByRef obj As Variant, _
                             ByVal expected As Boolean) As Boolean
    Dim key As Variant
    Dim value As Variant

    ParseObject = ParseStep(str, index, Empty, jsonOpeningBrace, expected)
    If ParseObject Then
        Set obj = CreateObject("Scripting.Dictionary")
        If ParseStep(str, index, Empty, jsonClosingBrace, False) Then Exit Function
        Do
            If ParseStep(str, index, key, jsonString, True) Then
                If ParseStep(str, index, Empty, jsonColon, True) Then
                    If ParseValue(str, index, value, True) Then
                        If IsObject(value) Then
                            Set obj.Item(key) = value
                        Else
                            obj.Item(key) = value
                        End If
                    End If
                End If
            End If
        Loop While ParseStep(str, index, Empty, jsonComma, False)
        ParseObject = ParseStep(str, index, Empty, jsonClosingBrace, True)
    End If
End Function

Private Function ParseArray(ByRef str As String, _
                            ByRef index As Long, _
                            ByRef arr As Variant, _
                            ByVal expected As Boolean) As Boolean
    Dim key As Variant
    Dim value As Variant

    ParseArray = ParseStep(str, index, Empty, jsonOpeningBracket, expected)
    If ParseArray Then
        Set arr = New Collection
        If ParseStep(str, index, Empty, jsonClosingBracket, False) Then Exit Function
        Do
            If ParseValue(str, index, value, True) Then
                arr.Add value
            End If
        Loop While ParseStep(str, index, Empty, jsonComma, False)
        ParseArray = ParseStep(str, index, Empty, jsonClosingBracket, True)
    End If
End Function

Public Function ParseJson(ByVal str As String) As Object
    If regexp Is Nothing Then
        Set regexp = CreateObject("VBScript.RegExp")
    End If
    If ParseObject(str, 1, ParseJson, False) Then Exit Function
    If ParseArray(str, 1, ParseJson, False) Then Exit Function
    Err.Raise 10001, "ParseJson", "Expecting " & JsonStepName(jsonOpeningBrace) & " or " & JsonStepName(jsonOpeningBracket) & "."
End Function

Rails DB Migration - How To Drop a Table?

if anybody is looking for how to do it in SQL.

type rails dbconsole from terminal

enter password

In console do

USE db_name;

DROP TABLE table_name;

exit

Please dont forget to remove the migration file and table structure from schema

Get all parameters from JSP page

localhost:8080/esccapp/tst/submit.jsp?key=datr&key2=datr2&key3=datr3

    <%@page import="java.util.Enumeration"%>

    <%
    Enumeration in = request.getParameterNames();
    while(in.hasMoreElements()) {
     String paramName = in.nextElement().toString();
     out.println(paramName + " = " + request.getParameter(paramName)+"<br>");
    }
    %>

    key = datr
    key2 = datr2
    key3 = datr3

Pip Install not installing into correct directory?

This is what worked for me on Windows. The cause being multiple python installations

  1. update path with correct python
  2. uninstall pip using python -m pip uninstall pip setuptools
  3. restart windows didn't work until a restart

Chart.js v2 hide dataset labels

Replace options with this snippet, will fix for Vanilla JavaScript Developers

_x000D_
_x000D_
options: {
            title: {
                text: 'Hello',
                display: true
            },
            scales: {
                xAxes: [{
                    ticks: {
                        display: false
                    }
                }]
            },
            legend: {
                display: false
            }
        }
_x000D_
_x000D_
_x000D_

Control flow in T-SQL SP using IF..ELSE IF - are there other ways?

Nope IF is the way to go, what is the problem you have with using it?

BTW your example won't ever get to the third block of code as it and the second block are exactly alike.

Identifier is undefined

From the update 2 and after narrowing down the problem scope, we can easily find that there is a brace missing at the end of the function addWord. The compiler will never explicitly identify such a syntax error. instead, it will assume that the missing function definition located in some other object file. The linker will complain about it and hence directly will be categorized under one of the broad the error phrases which is identifier is undefined. Reasonably, because with the current syntax the next function definition (in this case is ac_search) will be included under the addWord scope. Hence, it is not a global function anymore. And that is why compiler will not see this function outside addWord and will throw this error message stating that there is no such a function. A very good elaboration about the compiler and the linker can be found in this article

WRONGTYPE Operation against a key holding the wrong kind of value php

Redis supports 5 data types. You need to know what type of value that a key maps to, as for each data type, the command to retrieve it is different.

Here are the commands to retrieve key value:

  • if value is of type string -> GET <key>
  • if value is of type hash -> HGETALL <key>
  • if value is of type lists -> lrange <key> <start> <end>
  • if value is of type sets -> smembers <key>
  • if value is of type sorted sets -> ZRANGEBYSCORE <key> <min> <max>

Use the TYPE command to check the type of value a key is mapping to:

  • type <key>

How to check a not-defined variable in JavaScript

I've often done:

function doSomething(variable)
{
    var undef;

    if(variable === undef)
    {
         alert('Hey moron, define this bad boy.');
    }
}

Expression must be a modifiable lvalue

The assignment operator has lower precedence than &&, so your condition is equivalent to:

if ((match == 0 && k) = m)

But the left-hand side of this is an rvalue, namely the boolean resulting from the evaluation of the sub­expression match == 0 && k, so you cannot assign to it.

By contrast, comparison has higher precedence, so match == 0 && k == m is equivalent to:

if ((match == 0) && (k == m))

Int to byte array

Most of the answers here are either 'UnSafe" or not LittleEndian safe. BitConverter is not LittleEndian safe. So building on an example in here (see the post by PZahra) I made a LittleEndian safe version simply by reading the byte array in reverse when BitConverter.IsLittleEndian == true

void Main(){    
    Console.WriteLine(BitConverter.IsLittleEndian); 
    byte[] bytes = BitConverter.GetBytes(0xdcbaabcdfffe1608);
    //Console.WriteLine(bytes); 
    string hexStr = ByteArrayToHex(bytes);
    Console.WriteLine(hexStr);
}

public static string ByteArrayToHex(byte[] data) 
{ 
   char[] c = new char[data.Length * 2]; 
   byte b; 
  if(BitConverter.IsLittleEndian)
  {
        //read the byte array in reverse
        for (int y = data.Length -1, x = 0; y >= 0; --y, ++x) 
        { 
            b = ((byte)(data[y] >> 4)); 
            c[x] = (char)(b > 9 ? b + 0x37 : b + 0x30); 
            b = ((byte)(data[y] & 0xF)); 
            c[++x] = (char)(b > 9 ? b + 0x37 : b + 0x30); 
        }               
    }
    else
    {
        for (int y = 0, x = 0; y < data.Length; ++y, ++x) 
        { 
            b = ((byte)(data[y] >> 4)); 
            c[x] = (char)(b > 9 ? b + 0x37 : b + 0x30); 
            b = ((byte)(data[y] & 0xF)); 
            c[++x] = (char)(b > 9 ? b + 0x37 : b + 0x30); 
        }
    }
    return String.Concat("0x",new string(c));
}

It returns this:

True
0xDCBAABCDFFFE1608

which is the exact hex that went into the byte array.

What languages are Windows, Mac OS X and Linux written in?

You're right MacOSX has Objective-C in the core.

Windows C++

Linux C

About the scripting languages, no, they pretty much high level.

How to execute a shell script on a remote server using Ansible?

You can use template module to copy if script exists on local machine to remote machine and execute it.

 - name: Copy script from local to remote machine
   hosts: remote_machine
   tasks:
    - name: Copy  script to remote_machine
      template: src=script.sh.2 dest=<remote_machine path>/script.sh mode=755
    - name: Execute script on remote_machine
      script: sh <remote_machine path>/script.sh

When should I use h:outputLink instead of h:commandLink?

I also see that the page loading (performance) takes a long time on using h:commandLink than h:link. h:link is faster compared to h:commandLink

Check the current number of connections to MongoDb

db.serverStatus() gives no of connections opend and avail but not shows the connections from which client. For more info you can use this command sudo lsof | grep mongod | grep TCP. I need it when i did replication and primary node have many client connection greater than secondary.

$ sudo lsof | grep mongod | grep TCP
mongod    5733             Al    6u     IPv4 0x08761278       0t0       TCP *:28017 (LISTEN)
mongod    5733             Al    7u     IPv4 0x07c7eb98       0t0       TCP *:27017 (LISTEN)
mongod    5733             Al    9u     IPv4 0x08761688       0t0       TCP 192.168.1.103:27017->192.168.1.103:64752 (ESTABLISHED)
mongod    5733             Al   12u     IPv4 0x08761a98       0t0       TCP 192.168.1.103:27017->192.168.1.103:64754 (ESTABLISHED)
mongod    5733             Al   13u     IPv4 0x095fa748       0t0       TCP 192.168.1.103:27017->192.168.1.103:64770 (ESTABLISHED)
mongod    5733             Al   14u     IPv4 0x095f86c8       0t0       TCP 192.168.1.103:27017->192.168.1.103:64775 (ESTABLISHED)
mongod    5733             Al   17u     IPv4 0x08764748       0t0       TCP 192.168.1.103:27017->192.168.1.103:64777 (ESTABLISHED)

This shows that I currently have five connections open to the MongoDB port (27017) on my computer. In my case I'm connecting to MongoDB from a Scalatra server, and I'm using the MongoDB Casbah driver, but you'll see the same lsof TCP connections regardless of the client used (as long as they're connecting using TCP/IP).

What values for checked and selected are false?

No value is considered false, only the absence of the attribute. There are plenty of invalid values though, and some implementations might consider certain invalid values as false.

HTML5 spec

http://www.w3.org/TR/html5/forms.html#attr-input-checked :

The disabled content attribute is a boolean attribute.

http://www.w3.org/TR/html5/infrastructure.html#boolean-attributes :

The presence of a boolean attribute on an element represents the true value, and the absence of the attribute represents the false value.

If the attribute is present, its value must either be the empty string or a value that is an ASCII case-insensitive match for the attribute's canonical name, with no leading or trailing whitespace.

Conclusion

The following are valid, equivalent and true:

<input type="checkbox" checked />
<input type="checkbox" checked="" />
<input type="checkbox" checked="checked" />
<input type="checkbox" checked="ChEcKeD" />

The following are invalid:

<input type="checkbox" checked="0" />
<input type="checkbox" checked="1" />
<input type="checkbox" checked="false" />
<input type="checkbox" checked="true" />

The absence of the attribute is the only valid syntax for false:

<input type="checkbox" />

Recommendation

If you care about writing valid XHTML, use checked="checked", since <input checked> is invalid and other alternatives are less readable. Else, just use <input checked> as it is shorter.

How to disable HTML button using JavaScript?

Try the following:

document.getElementById("id").setAttribute("disabled", "disabled");

Docker - Cannot remove dead container

Try running the following commands. It always works for me.

# docker volume rm $(docker volume ls -qf dangling=true)
# docker rm $(docker ps -q -f 'status=exited')

After execution of the above commands, restart docker by,

# service docker restart

Pycharm: run only part of my Python file

You can select a code snippet and use right click menu to choose the action "Execute Selection in console".

How to use SQL Select statement with IF EXISTS sub query?

You can also use ISNULL and a select statement to get this result

SELECT
Table1.ID,
ISNULL((SELECT 'TRUE' FROM TABLE2 WHERE TABLE2.ID = TABEL1.ID),'FALSE') AS columName,
etc
FROM TABLE1

Clear android application user data

Hello UdayaLakmal,

public class MyApplication extends Application {
    private static MyApplication instance;

    @Override
    public void onCreate() {
        super.onCreate();
        instance = this;
    }

    public static MyApplication getInstance(){
        return instance;
    }

    public void clearApplicationData() {
        File cache = getCacheDir();
        File appDir = new File(cache.getParent());
        if(appDir.exists()){
            String[] children = appDir.list();
            for(String s : children){
                if(!s.equals("lib")){
                    deleteDir(new File(appDir, s));
                    Log.i("TAG", "File /data/data/APP_PACKAGE/" + s +" DELETED");
                }
            }
        }
    }

    public static boolean deleteDir(File dir) {
        if (dir != null && dir.isDirectory()) {
            String[] children = dir.list();
            for (int i = 0; i < children.length; i++) {
                boolean success = deleteDir(new File(dir, children[i]));
                if (!success) {
                    return false;
                }
            }
        }

        return dir.delete();
    }
}

Please check this and let me know...

You can download code from here

ssh: The authenticity of host 'hostname' can't be established

This warning is issued due the security features, do not disable this feature.

It's just displayed once.

If it still appears after second connection, the problem is probably in writing to the known_hosts file. In this case you'll also get the following message:

Failed to add the host to the list of known hosts 

You may fix it by changing owner of changing the permissions of the file to be writable by your user.

sudo chown -v $USER ~/.ssh/known_hosts

How do you convert an entire directory with ffmpeg?

And on Windows:

FOR /F "tokens=*" %G IN ('dir /b *.flac') DO ffmpeg -i "%G" -acodec mp3 "%~nG.mp3"

How to call multiple JavaScript functions in onclick event?

onclick="doSomething();doSomethingElse();"

But really, you're better off not using onclick at all and attaching the event handler to the DOM node through your Javascript code. This is known as unobtrusive javascript.

Fixing Xcode 9 issue: "iPhone is busy: Preparing debugger support for iPhone"

rebooted iPhone, closed all other open applications and unlocked phone worked

Load CSV data into MySQL in Python

Fastest way is to use MySQL bulk loader by "load data infile" statement. It is the fastest way by far than any way you can come up with in Python. If you have to use Python, you can call statement "load data infile" from Python itself.

Java Try Catch Finally blocks without Catch

If any of the code in the try block can throw a checked exception, it has to appear in the throws clause of the method signature. If an unchecked exception is thrown, it's bubbled out of the method.

The finally block is always executed, whether an exception is thrown or not.

How to run Pip commands from CMD

Firstly make sure that you have installed python 2.7 or higher

Open Command Prompt as administrator and change directory to python and then change directory to Scripts by typing cd Scripts then type pip.exe and now you can install modules Step by Step:

  • Open Cmd

  • type in "cd \" and then enter

  • type in "cd python2.7" and then enter

Note that my python version is 2.7 so my directory is that so use your python folder here...

  • type in "cd Scripts" and enter

  • Now enter this "pip.exe"

  • Now it prompts you to install modules

Map to String in Java

Use Object#toString().

String string = map.toString();

That's after all also what System.out.println(object) does under the hoods. The format for maps is described in AbstractMap#toString().

Returns a string representation of this map. The string representation consists of a list of key-value mappings in the order returned by the map's entrySet view's iterator, enclosed in braces ("{}"). Adjacent mappings are separated by the characters ", " (comma and space). Each key-value mapping is rendered as the key followed by an equals sign ("=") followed by the associated value. Keys and values are converted to strings as by String.valueOf(Object).

Google Apps Script to open a URL

You can build a small UI that does the job like this :

function test(){
showURL("http://www.google.com")
}
//
function showURL(href){
  var app = UiApp.createApplication().setHeight(50).setWidth(200);
  app.setTitle("Show URL");
  var link = app.createAnchor('open ', href).setId("link");
  app.add(link);  
  var doc = SpreadsheetApp.getActive();
  doc.show(app);
  }

If you want to 'show' the URL, just change this line like this :

  var link = app.createAnchor(href, href).setId("link");

EDIT : link to a demo spreadsheet in read only because too many people keep writing unwanted things on it (just make a copy to use instead).

EDIT : UiApp was deprecated by Google on 11th Dec 2014, this method could break at any time and needs updating to use HTML service instead!

EDIT : below is an implementation using html service.

function testNew(){
  showAnchor('Stackoverflow','http://stackoverflow.com/questions/tagged/google-apps-script');
}

function showAnchor(name,url) {
  var html = '<html><body><a href="'+url+'" target="blank" onclick="google.script.host.close()">'+name+'</a></body></html>';
  var ui = HtmlService.createHtmlOutput(html)
  SpreadsheetApp.getUi().showModelessDialog(ui,"demo");
}

Splitting strings using a delimiter in python

So, your input is 'dan|warrior|54' and you want "warrior". You do this like so:

>>> dan = 'dan|warrior|54'
>>> dan.split('|')[1]
"warrior"

Flutter plugin not installed error;. When running flutter doctor

The issue is just that "flutter doctor" is not able to read behind the scene that everything is fine and up to date. This issue is temporary (till next patch or update) and can be avoided as it won't affect anywhere in the development process.

This is a frequently occurring issue when we are updating a newer version of Flutter. Recently also upon updating to Flutter 1.22.1(Stable), it throws a "Plugins Not installed" error, while they are installed and up to date. Uninstalling and reinstalling will also not work as Android Studio will again pick the same version to install.

Is there a developers api for craigslist.org

Good news everybody! Craigslist has actually released a bulk posting api now!

Enjoy

How to use the new Material Design Icon themes: Outlined, Rounded, Two-Tone and Sharp?

I ended up using IcoMoon app to create a custom font using only the new themed icons I required for a recent web app build. It's not perfect but you can mimic the existing Google Font functionality pretty nicely with a little bit of setup. Here's a writeup:

https://medium.com/@leemartin/how-to-use-material-icon-outlined-rounded-two-tone-and-sharp-themes-92276f2415d2

If someone is feeling daring, they could convert the entire theme using IcoMoon. Hell, IcoMoon probably has an internal process that would make it easy since they already have the original Material Icons set in their library.

Anyway, this isn't a perfect solution, but it worked for me.

How npm start runs a server on port 8000

If you will look at package.json file.

you will see something like this

 "start": "http-server -a localhost -p 8000"

This tells start a http-server at address of localhost on port 8000

http-server is a node-module.

Update:- Including comment by @Usman, ideally it should be present in your package.json but if it's not present you can include it in scripts section.

How to run a task when variable is undefined in ansible?

Strictly stated you must check all of the following: defined, not empty AND not None.

For "normal" variables it makes a difference if defined and set or not set. See foo and bar in the example below. Both are defined but only foo is set.

On the other side registered variables are set to the result of the running command and vary from module to module. They are mostly json structures. You probably must check the subelement you're interested in. See xyz and xyz.msg in the example below:

cat > test.yml <<EOF
- hosts: 127.0.0.1

  vars:
    foo: ""          # foo is defined and foo == '' and foo != None
    bar:             # bar is defined and bar != '' and bar == None

  tasks:

  - debug:
      msg : ""
    register: xyz    # xyz is defined and xyz != '' and xyz != None
                     # xyz.msg is defined and xyz.msg == '' and xyz.msg != None

  - debug:
      msg: "foo is defined and foo == '' and foo != None"
    when: foo is defined and foo == '' and foo != None

  - debug:
      msg: "bar is defined and bar != '' and bar == None"
    when: bar is defined and bar != '' and bar == None

  - debug:
      msg: "xyz is defined and xyz != '' and xyz != None"
    when: xyz is defined and xyz != '' and xyz != None
  - debug:
      msg: "{{ xyz }}"

  - debug:
      msg: "xyz.msg is defined and xyz.msg == '' and xyz.msg != None"
    when: xyz.msg is defined and xyz.msg == '' and xyz.msg != None
  - debug:
      msg: "{{ xyz.msg }}"
EOF
ansible-playbook -v test.yml

Simplest way to throw an error/exception with a custom message in Swift 2?

Throwing code should make clear whether the error message is appropriate for display to end users or is only intended for developer debugging. To indicate a description is displayable to the user, I use a struct DisplayableError that implements the LocalizedError protocol.

struct DisplayableError: Error, LocalizedError {
    let errorDescription: String?

    init(_ description: String) {
        errorDescription = description
    }
}

Usage for throwing:

throw DisplayableError("Out of pixie dust.")

Usage for display:

let messageToDisplay = error.localizedDescription

Python speed testing - Time Difference - milliseconds

Since Python 2.7 there's the timedelta.total_seconds() method. So, to get the elapsed milliseconds:

>>> import datetime
>>> a = datetime.datetime.now()
>>> b = datetime.datetime.now()
>>> delta = b - a
>>> print delta
0:00:05.077263
>>> int(delta.total_seconds() * 1000) # milliseconds
5077

Java constant examples (Create a java file having only constants)

This question is old. But I would like to mention an other approach. Using Enums for declaring constant values. Based on the answer of Nandkumar Tekale, the Enum can be used as below:

Enum:

public enum Planck {
    REDUCED();
    public static final double PLANCK_CONSTANT = 6.62606896e-34;
    public static final double PI = 3.14159;
    public final double REDUCED_PLANCK_CONSTANT;

    Planck() {
        this.REDUCED_PLANCK_CONSTANT = PLANCK_CONSTANT / (2 * PI);
    }

    public double getValue() {
        return REDUCED_PLANCK_CONSTANT;
    }
}

Client class:

public class PlanckClient {

    public static void main(String[] args) {
        System.out.println(getReducedPlanckConstant());
        // or using Enum itself as below:
        System.out.println(Planck.REDUCED.getValue());
    }

    public static double getReducedPlanckConstant() {
        return Planck.PLANCK_CONSTANT / (2 * Planck.PI);
    }

}

Reference : The usage of Enums for declaring constant fields is suggested by Joshua Bloch in his Effective Java book.

Embed an External Page Without an Iframe?

Question is good, but the answer is : it depends on that.

If the other webpage doesn't contain any form or text, for example you can use the CURL method to pickup the exact content and after then showing on your page. YOu can do it without using an iframe.

But, if the page what you want to embed contains for example a form it will not work correctly , because the form handling is on that site.

Gradient borders

Webkit supports gradients in borders, and now accepts the gradient in the Mozilla format.

Firefox claims to support gradients in two ways:

  1. Using border-image with border-image-source
  2. Using border-right-colors (right/left/top/bottom)

IE9 has no support.

MySQL: What's the difference between float and double?

FLOAT stores floating point numbers with accuracy up to eight places and has four bytes while DOUBLE stores floating point numbers with accuracy upto 18 places and has eight bytes.

Select rows with same id but different value in another column

Select A.ARIDNR,A.LIEFNR
from Table A
join Table B
on A.ARIDNR = B.ARIDNR
and A.LIEFNR<> B.LIEFNR
group by A.ARIDNR,A.LIEFNR

Android check internet connection

Use this code to check the internet connection

ConnectivityManager connectivityManager = (ConnectivityManager) ctx
                .getSystemService(Context.CONNECTIVITY_SERVICE);
        if ((connectivityManager
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE) != null && connectivityManager
                .getNetworkInfo(ConnectivityManager.TYPE_MOBILE).getState() == NetworkInfo.State.CONNECTED)
                || (connectivityManager
                        .getNetworkInfo(ConnectivityManager.TYPE_WIFI) != null && connectivityManager
                        .getNetworkInfo(ConnectivityManager.TYPE_WIFI)
                        .getState() == NetworkInfo.State.CONNECTED)) {
            return true;
        } else {
            return false;
        }

Display DateTime value in dd/mm/yyyy format in Asp.NET MVC

I know this is an older question, but for reference, a really simple way for formatting dates without any data annotations or any other settings is as follows:

@Html.TextBoxFor(m => m.StartDate, new { @Value = Model.StartDate.ToString("dd-MMM-yyyy") })

The above format can of course be changed to whatever.

Git says local branch is behind remote branch, but it's not

To diagnose it, follow this answer.

But to fix it, knowing you are the only one changing it, do:
1 - backup your project (I did only the files on git, ./src folder)
2 - git pull
3 - restore you backup over the many "messed" files (with merge indicators)

I tried git pull -s recursive -X ours but didnt work the way I wanted, it could be an option tho, but backup first!!!

Make sure the differences/changes (at git gui) are none. This is my case, there is nothing to merge at all, but github keeps saying I should merge...

What is the difference between UTF-8 and Unicode?

This article explains all the details http://kunststube.net/encoding/

WRITING TO BUFFER

if you write to a 4 byte buffer, symbol ? with UTF8 encoding, your binary will look like this:

00000000 11100011 10000001 10000010

if you write to a 4 byte buffer, symbol ? with UTF16 encoding, your binary will look like this:

00000000 00000000 00110000 01000010

As you can see, depending on what language you would use in your content this will effect your memory accordingly.

e.g. For this particular symbol: ? UTF16 encoding is more efficient since we have 2 spare bytes to use for the next symbol. But it doesn't mean that you must use UTF16 for Japan alphabet.

READING FROM BUFFER

Now if you want to read the above bytes, you have to know in what encoding it was written to and decode it back correctly.

e.g. If you decode this : 00000000 11100011 10000001 10000010 into UTF16 encoding, you will end up with ? not ?

Note: Encoding and Unicode are two different things. Unicode is the big (table) with each symbol mapped to a unique code point. e.g. ? symbol (letter) has a (code point): 30 42 (hex). Encoding on the other hand, is an algorithm that converts symbols to more appropriate way, when storing to hardware.

30 42 (hex) - > UTF8 encoding - > E3 81 82 (hex), which is above result in binary.

30 42 (hex) - > UTF16 encoding - > 30 42 (hex), which is above result in binary.

enter image description here

How to extract the nth word and count word occurrences in a MySQL string?

The field's value is:

 "- DE-HEB 20% - DTopTen 1.2%"
SELECT ....
SUBSTRING_INDEX(SUBSTRING_INDEX(DesctosAplicados, 'DE-HEB ',  -1), '-', 1) DE-HEB ,
SUBSTRING_INDEX(SUBSTRING_INDEX(DesctosAplicados, 'DTopTen ',  -1), '-', 1) DTopTen ,

FROM TABLA 

Result is:

  DE-HEB       DTopTEn
    20%          1.2%

Bold words in a string of strings.xml in Android

In Kotlin I have created an extension function for the Context. It takes a @StringRes and optionally you can provide parameters as well.

fun Context.fromHtmlWithParams(@StringRes stringRes: Int, parameter : String? = null) : Spanned {

    val stringText = if (parameter.isNullOrEmpty()) {
                    this.getString(stringRes)
                } else {
                    this.getString(stringRes, parameter)
                }

    return Html.fromHtml(stringText, Html.FROM_HTML_MODE_LEGACY)

}

Usage

tv_directors.text = context?.fromHtmlWithParams(R.string.directors, movie.Director)

Disabling browser caching for all browsers from ASP.NET

For what it's worth, I just had to handle this in my ASP.NET MVC 3 application. Here is the code block I used in the Global.asax file to handle this for all requests.

    protected void Application_BeginRequest()
    {
        //NOTE: Stopping IE from being a caching whore
        HttpContext.Current.Response.Cache.SetAllowResponseInBrowserHistory(false);
        HttpContext.Current.Response.Cache.SetCacheability(HttpCacheability.NoCache);
        HttpContext.Current.Response.Cache.SetNoStore();
        Response.Cache.SetExpires(DateTime.Now);
        Response.Cache.SetValidUntilExpires(true);
    }

How do you force a CIFS connection to unmount

umount -f -t cifs -l /mnt &

Be careful of &, let umount run in background. umount will detach filesystem first, so you will find nothing abount /mnt. If you run df command, then it will umount /mnt forcibly.

How to serialize an Object into a list of URL query parameters?

You can use jQuery's param method:

_x000D_
_x000D_
var obj = {_x000D_
  param1: 'something',_x000D_
  param2: 'somethingelse',_x000D_
  param3: 'another'_x000D_
}_x000D_
obj['param4'] = 'yetanother';_x000D_
var str = jQuery.param(obj);_x000D_
alert(str);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

How can I make PHP display the error instead of giving me 500 Internal Server Error

Check the error_reporting, display_errors and display_startup_errors settings in your php.ini file. They should be set to E_ALL and "On" respectively (though you should not use display_errors on a production server, so disable this and use log_errors instead if/when you deploy it). You can also change these settings (except display_startup_errors) at the very beginning of your script to set them at runtime (though you may not catch all errors this way):

error_reporting(E_ALL);
ini_set('display_errors', 'On');

After that, restart server.

How to Execute stored procedure from SQL Plus?

You have two options, a PL/SQL block or SQL*Plus bind variables:

var z number

execute  my_stored_proc (-1,2,0.01,:z)

print z

Fragment pressing back button

You can use this .. Worked for me..

It seems as though fragment [3] is not removed from the view when back is pressed so you have to do it manually!

First of all, dont use replace() but instead use remove and add separately. It seems as though replace() doesnt work properly.

The next part to this is overriding the onKeyDown method and remove the current fragment every time the back button is pressed.

 @Override
 public boolean onKeyDown(int keyCode, KeyEvent event)
 {
 if (keyCode == KeyEvent.KEYCODE_BACK)
 {
    if (getSupportFragmentManager().getBackStackEntryCount() == 0)
    {
        this.finish();
        return false;
    }
    else
    {
        getSupportFragmentManager().popBackStack();
        removeCurrentFragment();

        return false;
    }



 }

  return super.onKeyDown(keyCode, event);
 }


public void removeCurrentFragment()
{
FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();

Fragment currentFrag =  getSupportFragmentManager().findFragmentById(R.id.f_id);
}

Replace substring with another substring C++

Generalizing on rotmax's answer, here is a full solution to search & replace all instances in a string. If both substrings are of different size, the substring is replaced using string::erase and string::insert., otherwise the faster string::replace is used.

void FindReplace(string& line, string& oldString, string& newString) {
  const size_t oldSize = oldString.length();

  // do nothing if line is shorter than the string to find
  if( oldSize > line.length() ) return;

  const size_t newSize = newString.length();
  for( size_t pos = 0; ; pos += newSize ) {
    // Locate the substring to replace
    pos = line.find( oldString, pos );
    if( pos == string::npos ) return;
    if( oldSize == newSize ) {
      // if they're same size, use std::string::replace
      line.replace( pos, oldSize, newString );
    } else {
      // if not same size, replace by erasing and inserting
      line.erase( pos, oldSize );
      line.insert( pos, newString );
    }
  }
}

Generate Controller and Model

See all Available Controller : You can do PHP artisan list to view all commands

For help: PHP artisan help make:controller

php artisan make:controller MyControllerName

enter image description here

How to change the color of a button?

You can change the value in the XML like this:

<Button
    android:background="#FFFFFF"
     ../>

Here, you can add any other color, from the resources or hex.

Similarly, you can also change these values form the code like this:

demoButton.setBackgroundColor(Color.WHITE);

Another easy way is to make a drawable, customize the corners and shape according to your preference and set the background color and stroke of the drawable. For eg.

button_background.xml

<?xml version="1.0" encoding="UTF-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">
    <stroke android:width="2dp" android:color="#ff207d94" />
    <corners android:radius="5dp" />
    <solid android:color="#FFFFFF" />
</shape>

And then set this shape as the background of your button.

<Button
    android:background="@drawable/button_background.xml"
     ../>

Hope this helps, good luck!

Comprehensive methods of viewing memory usage on Solaris

The command free is nice. Takes a short while to understand the "+/- buffers/cache", but the idea is that cache and buffers doesn't really count when evaluating "free", as it can be dumped right away. Therefore, to see how much free (and used) memory you have, you need to remove the cache/buffer usage - which is conveniently done for you.

Should URL be case sensitive?

According to W3's "HTML and URLs" they should:

There may be URLs, or parts of URLs, where case doesn't matter, but identifying these may not be easy. Users should always consider that URLs are case-sensitive.

Swap two items in List<T>

Check the answer from Marc from C#: Good/best implementation of Swap method.

public static void Swap<T>(IList<T> list, int indexA, int indexB)
{
    T tmp = list[indexA];
    list[indexA] = list[indexB];
    list[indexB] = tmp;
}

which can be linq-i-fied like

public static IList<T> Swap<T>(this IList<T> list, int indexA, int indexB)
{
    T tmp = list[indexA];
    list[indexA] = list[indexB];
    list[indexB] = tmp;
    return list;
}

var lst = new List<int>() { 8, 3, 2, 4 };
lst = lst.Swap(1, 2);

Is it possible to read the value of a annotation in java?

For the few people asking for a generic method, this should help you (5 years later :p).

For my below example, I'm pulling the RequestMapping URL value from methods that have the RequestMapping annotation. To adapt this for fields, just change the

for (Method method: clazz.getMethods())

to

for (Field field: clazz.getFields())

And swap usage of RequestMapping for whatever annotation you are looking to read. But make sure that the annotation has @Retention(RetentionPolicy.RUNTIME).

public static String getRequestMappingUrl(final Class<?> clazz, final String methodName)
{
    // Only continue if the method name is not empty.
    if ((methodName != null) && (methodName.trim().length() > 0))
    {
        RequestMapping tmpRequestMapping;
        String[] tmpValues;

        // Loop over all methods in the class.
        for (Method method: clazz.getMethods())
        {
            // If the current method name matches the expected method name, then keep going.
            if (methodName.equalsIgnoreCase(method.getName()))
            {
                // Try to extract the RequestMapping annotation from the current method.
                tmpRequestMapping = method.getAnnotation(RequestMapping.class);

                // Only continue if the current method has the RequestMapping annotation.
                if (tmpRequestMapping != null)
                {
                    // Extract the values from the RequestMapping annotation.
                    tmpValues = tmpRequestMapping.value();

                    // Only continue if there are values.
                    if ((tmpValues != null) && (tmpValues.length > 0))
                    {
                        // Return the 1st value.
                        return tmpValues[0];
                    }
                }
            }
        }
    }

    // Since no value was returned, log it and return an empty string.
    logger.error("Failed to find RequestMapping annotation value for method: " + methodName);

    return "";
}

XAMPP - Apache could not start - Attempting to start Apache service

I had the same issue.Just click on services button.Then find apache and right cick > properties > set startup type as Automatic/ Manual. Now close apache and try again.It will work!

enter image description here

jQuery: Uncheck other checkbox on one checked

Try this

 $(function() { 
  $('input[type="checkbox"]').bind('click',function() {
    $('input[type="checkbox"]').not(this).prop("checked", false);
  });
});

Two decimal places using printf( )

What you want is %.2f, not 2%f.

Also, you might want to replace your %d with a %f ;)

#include <cstdio>
int main()
{
printf("When this number: %f is assigned to 2 dp, it will be: %.2f ", 94.9456, 94.9456);
return 0;
}

This will output:

When this number: 94.945600 is assigned to 2 dp, it will be: 94.95

See here for a full description of the printf formatting options: printf

Using Intent in an Android application to show another activity

Use this code:

Intent intent=new Intent(context,SecondActivty.class);
startActivity(intent);
finish();

context: refer to current activity context,

please make sure that you have added activity in android manifest file.

Following code for adding activity in android manifest file

<Activity name=".SecondActivity">
</Activity>

Parse time of format hh:mm:ss

A bit verbose, but it's the standard way of parsing and formatting dates in Java:

DateFormat formatter = new SimpleDateFormat("HH:mm:ss");
try {
  Date dt = formatter.parse("08:19:12");
  Calendar cal = Calendar.getInstance();
  cal.setTime(dt);
  int hour = cal.get(Calendar.HOUR);
  int minute = cal.get(Calendar.MINUTE);
  int second = cal.get(Calendar.SECOND);
} catch (ParseException e) {
  // This can happen if you are trying to parse an invalid date, e.g., 25:19:12.
  // Here, you should log the error and decide what to do next
  e.printStackTrace();
}

How to call a javaScript Function in jsp on page load without using <body onload="disableView()">

Either use window.onload this way

<script>
    window.onload = function() {
        // ...
    }
</script>

or alternatively

<script>
    window.onload = functionName;
</script>

(yes, without the parentheses)


Or just put the script at the very bottom of page, right before </body>. At that point, all HTML DOM elements are ready to be accessed by document functions.

<body>
    ...

    <script>
        functionName();
    </script>
</body>

mcrypt is deprecated, what is the alternative?

I am using this on PHP 7.2.x, it's working fine for me:

public function make_hash($userStr){
        try{
            /** 
             * Used and tested on PHP 7.2x, Salt has been removed manually, it is now added by PHP 
             */
             return password_hash($userStr, PASSWORD_BCRYPT);
            }catch(Exception $exc){
                $this->tempVar = $exc->getMessage();
                return false;
            }
        }

and then authenticate the hash with the following function:

public function varify_user($userStr,$hash){
        try{
            if (password_verify($userStr, $hash)) {
                 return true;
                }
            else {
                return false;
                }
            }catch(Exception $exc){
                $this->tempVar = $exc->getMessage();
                return false;
            }
        }

Example:

  //create hash from user string

 $user_password = $obj->make_hash2($user_key);

and to authenticate this hash use the following code:

if($obj->varify_user($key, $user_key)){
      //this is correct, you can proceed with  
    }

That's all.

How to get a list of sub-folders and their files, ordered by folder-names

Hej man, why are you using this ?

dir /s/b/o:gn > f.txt (wrong one)

Don't you know what is that 'g' in '/o' ??

Check this out: http://www.computerhope.com/dirhlp.htm or dir /? for dir help

You should be using this instead:

dir /s/b/o:n > f.txt (right one)

changing textbox border colour using javascript

You may try

document.getElementById('name').style.borderColor='#e52213';
document.getElementById('name').style.border='solid';

postgresql COUNT(DISTINCT ...) very slow

I was also searching same answer, because at some point of time I needed total_count with distinct values along with limit/offset.

Because it's little tricky to do- To get total count with distinct values along with limit/offset. Usually it's hard to get total count with limit/offset. Finally I got the way to do -

SELECT DISTINCT COUNT(*) OVER() as total_count, * FROM table_name limit 2 offset 0;

Query performance is also high.

Is there a way to add/remove several classes in one single instruction with classList?

I liked @rich.kelly's answer, but I wanted to use the same nomenclature as classList.add() (comma seperated strings), so a slight deviation.

DOMTokenList.prototype.addMany = DOMTokenList.prototype.addMany || function() {
  for (var i = 0; i < arguments.length; i++) {
    this.add(arguments[i]);
  }
}
DOMTokenList.prototype.removeMany = DOMTokenList.prototype.removeMany || function() {
  for (var i = 0; i < arguments.length; i++) {
    this.remove(arguments[i]);
  }
}

So you can then use:

document.body.classList.addMany('class-one','class-two','class-three');

I need to test all browsers, but this worked for Chrome.
Should we be checking for something more specific than the existence of DOMTokenList.prototype.addMany? What exactly causes classList.add() to fail in IE11?

How to avoid scientific notation for large numbers in JavaScript?

The question of the post was avoiding e notation numbers and having the number as a plain number.

Therefore, if all is needed is to convert e (scientific) notation numbers to plain numbers (including in the case of fractional numbers) without loss of accuracy, then it is essential to avoid the use of the Math object and other javascript number methods so that rounding does not occur when large numbers and large fractions are handled (which always happens due to the internal storage in binary format).

The following function converts e (scientific) notation numbers to plain numbers (including fractions) handling both large numbers and large fractions without loss of accuracy as it does not use the built-in math and number functions to handle or manipulate the number.

The function also handles normal numbers, so that a number that is suspected to become in an 'e' notation can be passed to the function for fixing.

The function should work with different locale decimal points.

94 test cases are provided.

For large e-notation numbers pass the number as a string.

Examples:

eToNumber("123456789123456789.111122223333444455556666777788889999e+50");
// output:
"12345678912345678911112222333344445555666677778888999900000000000000"
eToNumber("123.456123456789123456895e-80");
// output:
"0.00000000000000000000000000000000000000000000000000000000000000000000000000000123456123456789123456895"
eToNumber("123456789123456789.111122223333444455556666777788889999e-50");
// output:
"0.00000000000000000000000000000000123456789123456789111122223333444455556666777788889999"

Valid e-notation numbers in Javascript include the following:

123e1   ==> 1230
123E1   ==> 1230
123e+1  ==> 1230
123.e+1 ==> 1230
123e-1  ==> 12.3
0.1e-1  ==> 0.01
.1e-1   ==> 0.01
-123e1  ==> -1230

_x000D_
_x000D_
/******************************************************************
 * Converts e-Notation Numbers to Plain Numbers
 ******************************************************************
 * @function eToNumber(number)
 * @version  1.00
 * @param   {e nottation Number} valid Number in exponent format.
 *          pass number as a string for very large 'e' numbers or with large fractions
 *          (none 'e' number returned as is).
 * @return  {string}  a decimal number string.
 * @author  Mohsen Alyafei
 * @date    17 Jan 2020
 * Note: No check is made for NaN or undefined input numbers.
 *
 *****************************************************************/
function eToNumber(num) {
  let sign = "";
  (num += "").charAt(0) == "-" && (num = num.substring(1), sign = "-");
  let arr = num.split(/[e]/ig);
  if (arr.length < 2) return sign + num;
  let dot = (.1).toLocaleString().substr(1, 1), n = arr[0], exp = +arr[1];
  let w = (n = n.replace(/^0+/, '')).replace(dot, ''),
    pos = n.split(dot)[1] ? n.indexOf(dot) + exp : w.length + exp,
    L = pos - w.length, s = "" + BigInt(w);
  w = exp >= 0 ? (L >= 0 ? s + "0".repeat(L) : r()) : (pos <= 0 ? "0" + dot + "0".repeat(Math.abs(pos)) + s : r());
  if (!+w) w = 0; return sign + w;
  function r() {return w.replace(new RegExp(`^(.{${pos}})(.)`), `$1${dot}$2`)}
}
//*****************************************************************

//================================================
//             Test Cases
//================================================
let r = 0; // test tracker
r |= test(1, "123456789123456789.111122223333444455556666777788889999e+50", "12345678912345678911112222333344445555666677778888999900000000000000");
r |= test(2, "123456789123456789.111122223333444455556666777788889999e-50", "0.00000000000000000000000000000000123456789123456789111122223333444455556666777788889999");
r |= test(3, "123456789e3", "123456789000");
r |= test(4, "123456789e1", "1234567890");
r |= test(5, "1.123e3", "1123");
r |= test(6, "12.123e3", "12123");
r |= test(7, "1.1234e1", "11.234");
r |= test(8, "1.1234e4", "11234");
r |= test(9, "1.1234e5", "112340");
r |= test(10, "123e+0", "123");
r |= test(11, "123E0", "123");
// //============================
r |= test(12, "123e-1", "12.3");
r |= test(13, "123e-2", "1.23");
r |= test(14, "123e-3", "0.123");
r |= test(15, "123e-4", "0.0123");
r |= test(16, "123e-2", "1.23");
r |= test(17, "12345.678e-1", "1234.5678");
r |= test(18, "12345.678e-5", "0.12345678");
r |= test(19, "12345.678e-6", "0.012345678");
r |= test(20, "123.4e-2", "1.234");
r |= test(21, "123.4e-3", "0.1234");
r |= test(22, "123.4e-4", "0.01234");
r |= test(23, "-123e+0", "-123");
r |= test(24, "123e1", "1230");
r |= test(25, "123e3", "123000");
r |= test(26, -1e33, "-1000000000000000000000000000000000");
r |= test(27, "123e+3", "123000");
r |= test(28, "123E+7", "1230000000");
r |= test(29, "-123.456e+1", "-1234.56");
r |= test(30, "-1.0e+1", "-10");
r |= test(31, "-1.e+1", "-10");
r |= test(32, "-1e+1", "-10");
r |= test(34, "-0", "-0");
r |= test(37, "0e0", "0");
r |= test(38, "123.456e+4", "1234560");
r |= test(39, "123E-0", "123");
r |= test(40, "123.456e+50", "12345600000000000000000000000000000000000000000000000");

r |= test(41, "123e-0", "123");
r |= test(42, "123e-1", "12.3");
r |= test(43, "123e-3", "0.123");
r |= test(44, "123.456E-1", "12.3456");
r |= test(45, "123.456123456789123456895e-80", "0.00000000000000000000000000000000000000000000000000000000000000000000000000000123456123456789123456895");
r |= test(46, "-123.456e-50", "-0.00000000000000000000000000000000000000000000000123456");

r |= test(47, "-0e+1", "-0");
r |= test(48, "0e+1", "0");
r |= test(49, "0.1e+1", "1");
r |= test(50, "-0.01e+1", "-0.1");
r |= test(51, "0.01e+1", "0.1");
r |= test(52, "-123e-7", "-0.0000123");
r |= test(53, "123.456e-4", "0.0123456");

r |= test(54, "1.e-5", "0.00001"); // handle missing base fractional part
r |= test(55, ".123e3", "123"); // handle missing base whole part

// The Electron's Mass:
r |= test(56, "9.10938356e-31", "0.000000000000000000000000000000910938356");
// The Earth's Mass:
r |= test(57, "5.9724e+24", "5972400000000000000000000");
// Planck constant:
r |= test(58, "6.62607015e-34", "0.000000000000000000000000000000000662607015");

r |= test(59, "0.000e3", "0");
r |= test(60, "0.000000000000000e3", "0");
r |= test(61, "-0.0001e+9", "-100000");
r |= test(62, "-0.0e1", "-0");
r |= test(63, "-0.0000e1", "-0");


r |= test(64, "1.2000e0", "1.2000");
r |= test(65, "1.2000e-0", "1.2000");
r |= test(66, "1.2000e+0", "1.2000");
r |= test(67, "1.2000e+10", "12000000000");
r |= test(68, "1.12356789445566771234e2", "112.356789445566771234");

// ------------- testing for Non e-Notation Numbers -------------
r |= test(69, "12345.7898", "12345.7898") // no exponent
r |= test(70, 12345.7898, "12345.7898") // no exponent
r |= test(71, 0.00000000000001, "0.00000000000001") // from 1e-14
r |= test(72, 0.0000000000001, "0.0000000000001") // from 1e-13
r |= test(73, 0.000000000001, "0.000000000001") // from 1e-12
r |= test(74, 0.00000000001, "0.00000000001") // from 1e-11
r |= test(75, 0.0000000001, "0.0000000001") // from 1e-10
r |= test(76, 0.000000001, "0.000000001") // from 1e-9
r |= test(77, 0.00000001, "0.00000001") // from 1e-8
r |= test(78, 0.0000001, "0.0000001") // from 1e-7
r |= test(79, 1e-7, "0.0000001") // from 1e-7
r |= test(80, -0.0000001, "-0.0000001") // from 1e-7
r |= test(81, 0.0000005, "0.0000005") // from 1e-7
r |= test(82, 0.1000005, "0.1000005") // from 1e-7
r |= test(83, 1e-6, "0.000001") // from 1e-6

r |= test(84, 0.000001, "0.000001"); // from 1e-6
r |= test(85, 0.00001, "0.00001"); // from 1e-5
r |= test(86, 0.0001, "0.0001"); // from 1e-4
r |= test(87, 0.001, "0.001"); // from 1e-3
r |= test(88, 0.01, "0.01"); // from 1e-2
r |= test(89, 0.1, "0.1") // from 1e-1
r |= test(90, -0.0000000000000345, "-0.0000000000000345"); // from -3.45e-14
r |= test(91, -0, "0");
r |= test(92, "-0", "-0");
r |= test(93,2e64,"20000000000000000000000000000000000000000000000000000000000000000");
r |= test(94,"2830869077153280552556547081187254342445169156730","2830869077153280552556547081187254342445169156730");

if (r == 0) console.log("All 94 tests passed.");

//================================================
//             Test function
//================================================
function test(testNumber, n1, should) {
  let result = eToNumber(n1);
  if (result !== should) {
    console.log(`Test ${testNumber} Failed. Output: ${result}\n             Should be: ${should}`);
    return 1;
  }
}
_x000D_
_x000D_
_x000D_

Remove duplicate rows in MySQL

Delete duplicate rows using DELETE JOIN statement MySQL provides you with the DELETE JOIN statement that you can use to remove duplicate rows quickly.

The following statement deletes duplicate rows and keeps the highest id:

DELETE t1 FROM contacts t1
    INNER JOIN
contacts t2 WHERE
t1.id < t2.id AND t1.email = t2.email;

Pass connection string to code-first DbContext

When using an EF model, I have a connection string in each project that consumes the EF model. For example, I have an EF EDMX model in a separate class library. I have one connection string in my web (mvc) project so that it can access the EF db.

I also have another unit test project for testing the repositories. In order for the repositories to access the EF db, the test project's app.config file has the same connection string.

DB connections should be configured, not coded, IMO.

What is the logic behind the "using" keyword in C++?

In C++11, the using keyword when used for type alias is identical to typedef.

7.1.3.2

A typedef-name can also be introduced by an alias-declaration. The identifier following the using keyword becomes a typedef-name and the optional attribute-specifier-seq following the identifier appertains to that typedef-name. It has the same semantics as if it were introduced by the typedef specifier. In particular, it does not define a new type and it shall not appear in the type-id.

Bjarne Stroustrup provides a practical example:

typedef void (*PFD)(double);    // C style typedef to make `PFD` a pointer to a function returning void and accepting double
using PF = void (*)(double);    // `using`-based equivalent of the typedef above
using P = [](double)->void; // using plus suffix return type, syntax error
using P = auto(double)->void // Fixed thanks to DyP

Pre-C++11, the using keyword can bring member functions into scope. In C++11, you can now do this for constructors (another Bjarne Stroustrup example):

class Derived : public Base { 
public: 
    using Base::f;    // lift Base's f into Derived's scope -- works in C++98
    void f(char);     // provide a new f 
    void f(int);      // prefer this f to Base::f(int) 

    using Base::Base; // lift Base constructors Derived's scope -- C++11 only
    Derived(char);    // provide a new constructor 
    Derived(int);     // prefer this constructor to Base::Base(int) 
    // ...
}; 

Ben Voight provides a pretty good reason behind the rationale of not introducing a new keyword or new syntax. The standard wants to avoid breaking old code as much as possible. This is why in proposal documents you will see sections like Impact on the Standard, Design decisions, and how they might affect older code. There are situations when a proposal seems like a really good idea but might not have traction because it would be too difficult to implement, too confusing, or would contradict old code.


Here is an old paper from 2003 n1449. The rationale seems to be related to templates. Warning: there may be typos due to copying over from PDF.

First let’s consider a toy example:

template <typename T>
class MyAlloc {/*...*/};

template <typename T, class A>
class MyVector {/*...*/};

template <typename T>

struct Vec {
typedef MyVector<T, MyAlloc<T> > type;
};
Vec<int>::type p; // sample usage

The fundamental problem with this idiom, and the main motivating fact for this proposal, is that the idiom causes the template parameters to appear in non-deducible context. That is, it will not be possible to call the function foo below without explicitly specifying template arguments.

template <typename T> void foo (Vec<T>::type&);

So, the syntax is somewhat ugly. We would rather avoid the nested ::type We’d prefer something like the following:

template <typename T>
using Vec = MyVector<T, MyAlloc<T> >; //defined in section 2 below
Vec<int> p; // sample usage

Note that we specifically avoid the term “typedef template” and introduce the new syntax involving the pair “using” and “=” to help avoid confusion: we are not defining any types here, we are introducing a synonym (i.e. alias) for an abstraction of a type-id (i.e. type expression) involving template parameters. If the template parameters are used in deducible contexts in the type expression then whenever the template alias is used to form a template-id, the values of the corresponding template parameters can be deduced – more on this will follow. In any case, it is now possible to write generic functions which operate on Vec<T> in deducible context, and the syntax is improved as well. For example we could rewrite foo as:

template <typename T> void foo (Vec<T>&);

We underscore here that one of the primary reasons for proposing template aliases was so that argument deduction and the call to foo(p) will succeed.


The follow-up paper n1489 explains why using instead of using typedef:

It has been suggested to (re)use the keyword typedef — as done in the paper [4] — to introduce template aliases:

template<class T> 
    typedef std::vector<T, MyAllocator<T> > Vec;

That notation has the advantage of using a keyword already known to introduce a type alias. However, it also displays several disavantages among which the confusion of using a keyword known to introduce an alias for a type-name in a context where the alias does not designate a type, but a template; Vec is not an alias for a type, and should not be taken for a typedef-name. The name Vec is a name for the family std::vector< [bullet] , MyAllocator< [bullet] > > – where the bullet is a placeholder for a type-name. Consequently we do not propose the “typedef” syntax. On the other hand the sentence

template<class T>
    using Vec = std::vector<T, MyAllocator<T> >;

can be read/interpreted as: from now on, I’ll be using Vec<T> as a synonym for std::vector<T, MyAllocator<T> >. With that reading, the new syntax for aliasing seems reasonably logical.

I think the important distinction is made here, aliases instead of types. Another quote from the same document:

An alias-declaration is a declaration, and not a definition. An alias- declaration introduces a name into a declarative region as an alias for the type designated by the right-hand-side of the declaration. The core of this proposal concerns itself with type name aliases, but the notation can obviously be generalized to provide alternate spellings of namespace-aliasing or naming set of overloaded functions (see ? 2.3 for further discussion). [My note: That section discusses what that syntax can look like and reasons why it isn't part of the proposal.] It may be noted that the grammar production alias-declaration is acceptable anywhere a typedef declaration or a namespace-alias-definition is acceptable.

Summary, for the role of using:

  • template aliases (or template typedefs, the former is preferred namewise)
  • namespace aliases (i.e., namespace PO = boost::program_options and using PO = ... equivalent)
  • the document says A typedef declaration can be viewed as a special case of non-template alias-declaration. It's an aesthetic change, and is considered identical in this case.
  • bringing something into scope (for example, namespace std into the global scope), member functions, inheriting constructors

It cannot be used for:

int i;
using r = i; // compile-error

Instead do:

using r = decltype(i);

Naming a set of overloads.

// bring cos into scope
using std::cos;

// invalid syntax
using std::cos(double);

// not allowed, instead use Bjarne Stroustrup function pointer alias example
using test = std::cos(double);

Is div inside list allowed?

If I recall correctly, a div inside a li used to be invalid.

@Flower @Superstringcheese Div should semantically define a section of a document, but it has already practically lost this role. Span should however contain text.

Go to Matching Brace in Visual Studio?

On Spanish (Spain) keyboard with VS2012 is Ctrl + ¡ as stated by @Keith but if you use Ctrl + ¿ (typed as Ctrl + Shift + ¡) then goes to Matching Brace plus selects all the code within the two braces and then you can't go again to the other brace.

T-sql - determine if value is integer

Sometimes you don't get to design the database, you just have to work with what you are given. In my case it's a database located on a computer that I only have read access to which has been around since 2008.

I need to select from a column in a poorly designed database which is a varchar with numbers 1-100 but sometimes a random string. I used the following to get around it (although I wish I could have re designed the entire database).

SELECT A from TABLE where isnumeric(A)=1

How do I use method overloading in Python?

I write my answer in Python 2.7:

In Python, method overloading is not possible; if you really want access the same function with different features, I suggest you to go for method overriding.

class Base(): # Base class
    '''def add(self,a,b):
        s=a+b
        print s'''

    def add(self,a,b,c):
        self.a=a
        self.b=b
        self.c=c

        sum =a+b+c
        print sum

class Derived(Base): # Derived class
    def add(self,a,b): # overriding method
        sum=a+b
        print sum



add_fun_1=Base() #instance creation for Base class
add_fun_2=Derived()#instance creation for Derived class

add_fun_1.add(4,2,5) # function with 3 arguments
add_fun_2.add(4,2)   # function with 2 arguments

Xcode Project vs. Xcode Workspace - Differences

When I used CocoaPods to develop iOS projects, there is a .xcworkspace file, you need to open the project with .xcworkspace file related with CocoaPods.

Files preview

But when you Show Package Contents with .xcworkspace file, you will find the contents.xcworkspacedata file.

Package contents

<?xml version="1.0" encoding="UTF-8"?>
<Workspace
   version = "1.0">
   <FileRef
      location = "group:BluetoothColorLamp24G.xcodeproj">
   </FileRef>
   <FileRef
      location = "group:Pods/Pods.xcodeproj">
   </FileRef>
</Workspace>

pay attention to this line:

location = "group:BluetoothColorLamp24G.xcodeproj"

The .xcworkspace file has reference with the .xcodeproj file.

Development Environment:

macOS 10.14
Xcode 10.1

How do I reverse a C++ vector?

There's a function std::reverse in the algorithm header for this purpose.

#include <vector>
#include <algorithm>

int main() {
  std::vector<int> a;
  std::reverse(a.begin(), a.end());
  return 0;
}

How to use `subprocess` command with pipes

After Python 3.5 you can also use:

    import subprocess

    f = open('test.txt', 'w')
    process = subprocess.run(['ls', '-la'], stdout=subprocess.PIPE, universal_newlines=True)
    f.write(process.stdout)
    f.close()

The execution of the command is blocking and the output will be in process.stdout.

node.js execute system command synchronously

Native Node.js solution is:

const {execSync} = require('child_process');

const result = execSync('node -v'); //  this do the trick 

Just be aware that some commands returns Buffer instead of string. And if you need string just add encoding to execSync options:

const result = execSync('git rev-parse HEAD', {encoding: 'utf8'});

... and it is also good to have timeout on sync exec:

const result = execSync('git rev-parse HEAD', {encoding: 'utf8', timeout: 10000});

Active Menu Highlight CSS

You should refer to the current element and not all elements matching your selector.

$("#mainMenu td").click(function() {
$(this).css('background-color', '#EDEDED');

});

I´d also recommend you to use CSS classes instead of setting the CSS properties this way.

That would be something like;

$("#mainMenu td").click(function() {
$(this).addClass('selected');

});

together with;

#mainMenu td.selected {

background-color: #EDEDED; }

LINK : fatal error LNK1561: entry point must be defined ERROR IN VC++

Main was missing in the entry point configuration. enter image description here

How to convert current date into string in java?

// On the form: dow mon dd hh:mm:ss zzz yyyy
new Date().toString();

Show spinner GIF during an $http request in AngularJS?

You can try something like this as well:

Create directive :

myApp.directive('loader', function () {
    return {
        restrict: 'A',
        scope: {cond: '=loader'},
        template: '<span ng-if="isLoading()" class="soft"><span class="fa fa-refresh fa-spin"></span></span>',
        link: function (scope) {
            scope.isLoading = function() {
                var ret = scope.cond === true || (
                        scope.cond &&
                        scope.cond.$$state &&
                        angular.isDefined(scope.cond.$$state.status) &&
                        scope.cond.$$state.status === 0
                    );
                return ret;
            }
        }
    };
}); 

Then you add something like this to mainCtrl

    // Return TRUE if some request is LOADING, else return FALSE
    $scope.isLoading = function() {
        return $http.pendingRequests.length > 0;
    };

And HTML can looks like this:

<div class="buttons loader">
    <span class="icon" loader="isLoading()"></span>
</div>

CSS Margin: 0 is not setting to 0

After reading this and troubleshooting the same issues, I agree that it is related to headings (h1 for sure, havent played with any others), also browser styles adding margins and paddings with clever rules that are hard to find and over-ride.

I have adapted a technique used to apply the box-sizing property properly to margins and paddings. the original article for box-sizing is located at CSS-Tricks :

html {
margin: 0;
padding: 0;
}
*, *:before, *:after {
margin: inherit;
padding: inherit;
}

So far it is exactly the trick for not using complex resets and makes applying a design much easier for myself anyways. Hope it helps.

Elasticsearch difference between MUST and SHOULD bool query

As said in the documentation:

Must: The clause (query) must appear in matching documents.

Should: The clause (query) should appear in the matching document. In a boolean query with no must clauses, one or more should clauses must match a document. The minimum number of should clauses to match can be set using the minimum_should_match parameter.

In other words, results will have to be matched by all the queries present in the must clause ( or match at least one of the should clauses if there is no must clause.

Since you want your results to satisfy all the queries, you should use must.


You can indeed use filters inside a boolean query.

How to print / echo environment variables?

This works too, with the semi-colon.

NAME=sam; echo $NAME

How to pass variable as a parameter in Execute SQL Task SSIS?

In your Execute SQL Task, make sure SQLSourceType is set to Direct Input, then your SQL Statement is the name of the stored proc, with questionmarks for each paramter of the proc, like so:

enter image description here

Click the parameter mapping in the left column and add each paramter from your stored proc and map it to your SSIS variable:

enter image description here

Now when this task runs it will pass the SSIS variables to the stored proc.

ERROR 1045 (28000): Access denied for user 'root'@'localhost' (using password: NO)

Your problem is here:

2013-11-14 17:57:20 5180 [ERROR] InnoDB: .\ibdata1 can't be opened in read-write mode

There's some problem with the ibdata1 file - maybe the permissions have changed on it? Perhaps some other process has it open. Does it even exist?

Fix this and possibly everything else will fall into place.

How to decode a Base64 string?

There are no PowerShell-native commands for Base64 conversion - yet (as of PowerShell [Core] 7.1), but adding dedicated cmdlets has been suggested.
For now, direct use of .NET is needed.

Important:

  • Base64 encoding is an encoding of binary data using bytes whose values are constrained to a well-defined 64-character subrange of the ASCII character set representing printable characters, devised at a time when sending arbitrary bytes was problematic, especially with the high bit set (byte values > 0x7f).

  • Therefore, you must always specify explicitly what character encoding the Base64 bytes do / should represent.

Ergo:

  • on converting TO Base64, you must first obtain a byte representation of the string you're trying to encode using the character encoding the consumer of the Base64 string expects.

  • on converting FROM Base64, you must interpret the resultant array of bytes as a string using the same encoding that was used to create the Base64 representation.

Examples:

Note:

  • The following examples convert to and from UTF-8 encoded strings:

  • To convert to and from UTF-16LE ("Unicode") instead, substitute [Text.Encoding]::Unicode for [Text.Encoding]::UTF8

Convert TO Base64:

PS> [Convert]::ToBase64String([Text.Encoding]::UTF8.GetBytes('Motörhead'))
TW90w7ZyaGVhZA==

Convert FROM Base64:

PS> [Text.Encoding]::Utf8.GetString([Convert]::FromBase64String('TW90w7ZyaGVhZA=='))
Motörhead

how to change the dist-folder path in angular-cli after 'ng build'

Another option would be to set the webroot path to the angular cli dist folder. In your Program.cs when configuring the WebHostBuilder just say

.UseWebRoot(Directory.GetCurrentDirectory() + "\\Frontend\\dist")

or whatever the path to your dist dir is.

java.lang.ClassNotFoundException: org.springframework.boot.SpringApplication Maven

The answer to the above question is "none of the above". When you download new STS it won't support the old Spring Boot parent version. Just update parent version with latest comes with STS it will work.

<parent>
    <groupId>org.springframework.boot</groupId>
    <artifactId>spring-boot-starter-parent</artifactId>
    <version>1.5.8.RELEASE</version>
    <relativePath/> <!-- lookup parent from repository -->
</parent>

If you have problem getting the latest, just create a new Spring Starter Project. Go to File->New->Spring Start Project and create a demo project you will get the latest parent version, change your version with that all will work. I do this every time I change STS.

How to check empty object in angular 2 template using *ngIf

This worked for me:

Check the length property and use ? to avoid undefined errors.

So your example would be:

<div class="comeBack_up" *ngIf="previous_info?.length">

UPDATE

The length property only exists on arrays. Since the question was about objects, use Object.getOwnPropertyNames(obj) to get an array of properties from the object. The example becomes:

<div class="comeBack_up" *ngIf="previous_info  && Object.getOwnPropertyNames(previous_info).length > 0">

The previous_info && is added to check if the object exists. If it evaluates to true the next statement checks if the object has at least on proporty. It does not check whether the property has a value.

SQL/mysql - Select distinct/UNIQUE but return all columns?

Found this elsewhere here but this is a simple solution that works:

 WITH cte AS /* Declaring a new table named 'cte' to be a clone of your table */
 (SELECT *, ROW_NUMBER() OVER (PARTITION BY id ORDER BY val1 DESC) AS rn
 FROM MyTable /* Selecting only unique values based on the "id" field */
 )
 SELECT * /* Here you can specify several columns to retrieve */
 FROM cte
 WHERE rn = 1

Copy a table from one database to another in Postgres

I tried some of the solutions here and they were really helpful. In my experience best solution is to use psql command line, but sometimes i don't feel like using psql command line. So here is another solution for pgAdminIII

create table table1 as(
 select t1.* 
 from dblink(
   'dbname=dbSource user=user1 password=passwordUser1',
   'select * from table1'  
  ) as t1(
    fieldName1 as bigserial,
    fieldName2 as text,
    fieldName3 as double precision 
  )
 )

The problem with this method is that the name of the fields and their types of the table you want to copy must be written.

Execute and get the output of a shell command in node.js

You can use the util library that comes with nodejs to get a promise from the exec command and can use that output as you need. Use restructuring to store the stdout and stderr in variables.

_x000D_
_x000D_
const util = require('util');
const exec = util.promisify(require('child_process').exec);

async function lsExample() {
  const {
    stdout,
    stderr
  } = await exec('ls');
  console.log('stdout:', stdout);
  console.error('stderr:', stderr);
}
lsExample();
_x000D_
_x000D_
_x000D_

Scala Doubles, and Precision

A bit strange but nice. I use String and not BigDecimal

def round(x: Double)(p: Int): Double = {
    var A = x.toString().split('.')
    (A(0) + "." + A(1).substring(0, if (p > A(1).length()) A(1).length() else p)).toDouble
}

SQL ORDER BY multiple columns

The results are ordered by the first column, then the second, and so on for as many columns as the ORDER BY clause includes. If you want any results sorted in descending order, your ORDER BY clause must use the DESC keyword directly after the name or the number of the relevant column.

Check out this Example

SELECT first_name, last_name, hire_date, salary 
FROM employee 
ORDER BY hire_date DESC,last_name ASC;

It will order in succession. Order the Hire_Date first, then LAST_NAME it by Hire_Date .

__init__() missing 1 required positional argument

The problem is with, you

def __init__(self, data):

when you create object from DHT class you should pass parameter the data should be dict type, like

data={'one':1,'two':2,'three':3}
dhtObj=DHT(data)

But in your code youshould to change is

data={'one':1,'two':2,'three':3}
if __name__ == '__main__': DHT(data).showData()

Or

if __name__ == '__main__': DHT({'one':1,'two':2,'three':3}).showData()

Builder Pattern in Effective Java

The Builder class should be static. I don't have time right now to actually test the code beyond that, but if it doesn't work let me know and I'll take another look.

failed to lazily initialize a collection of role

Try swich fetchType from LAZY to EAGER

...
@OneToMany(fetch=FetchType.EAGER)
private Set<NodeValue> nodeValues;
...

But in this case your app will fetch data from DB anyway. If this query very hard - this may impact on performance. More here: https://docs.oracle.com/javaee/6/api/javax/persistence/FetchType.html

==> 73

window.location.href not working

The browser is still submitting the form after your code runs.

Add return false; to the handler to prevent that.

How to play CSS3 transitions in a loop?

CSS transitions only animate from one set of styles to another; what you're looking for is CSS animations.

You need to define the animation keyframes and apply it to the element:

@keyframes changewidth {
  from {
    width: 100px;
  }

  to {
    width: 300px;
  }
}

div {
  animation-duration: 0.1s;
  animation-name: changewidth;
  animation-iteration-count: infinite;
  animation-direction: alternate;
}

Check out the link above to figure out how to customize it to your liking, and you'll have to add browser prefixes.

How many times a substring occurs

How about a one-liner with a list comprehension? Technically its 93 characters long, spare me PEP-8 purism. The regex.findall answer is the most readable if its a high level piece of code. If you're building something low level and don't want dependencies, this one is pretty lean and mean. I'm giving the overlapping answer. Obviously just use count like the highest score answer if there isn't overlap.

def count_substring(string, sub_string):
    return len([i for i in range(len(string)) if string[i:i+len(sub_string)] == sub_string])

How to create a listbox in HTML without allowing multiple selection?

Just use the size attribute:

<select name="sometext" size="5">
  <option>text1</option>
  <option>text2</option>
  <option>text3</option>
  <option>text4</option>
  <option>text5</option>
</select>

To clarify, adding the size attribute did not remove the multiple selection.

The single selection works because you removed the multiple="multiple" attribute.

Adding the size="5" attribute is still a good idea, it means that at least 5 lines must be displayed. See the full reference here

PHP Array to CSV

It worked for me.

 $f=fopen('php://memory','w');
 $header=array("asdf ","asdf","asd","Calasdflee","Start Time","End Time" );      
 fputcsv($f,$header);
 fputcsv($f,$header);
 fputcsv($f,$header); 
 fseek($f,0);
 header('content-type:text/csv'); 
 header('Content-Disposition: attachment; filename="' . $filename . '";');
 fpassthru($f);```

Pass array to where in Codeigniter Active Record

$this->db->where_in('id', ['20','15','22','42','86']);

Reference: where_in

Angular 2 filter/search list

You have to manually filter result based on change of input each time by keeping listener over input event. While doing manually filtering make sure you should maintain two copy of variable, one would be original collection copy & second would be filteredCollection copy. The advantage for going this way could save your couple of unnecessary filtering on change detection cycle. You may see a more code, but this would be more performance friendly.

Markup - HTML Template

<md-input #myInput placeholder="Item name..." [(ngModel)]="name" (input)="filterItem(myInput.value)"></md-input>

<div *ngFor="let item of filteredItems">
   {{item.name}}
</div>

Code

assignCopy(){
   this.filteredItems = Object.assign([], this.items);
}
filterItem(value){
   if(!value){
       this.assignCopy();
   } // when nothing has typed
   this.filteredItems = Object.assign([], this.items).filter(
      item => item.name.toLowerCase().indexOf(value.toLowerCase()) > -1
   )
}
this.assignCopy();//when you fetch collection from server.

VBA error 1004 - select method of range class failed

Removing the range select before the copy worked for me. Thanks for the posts.

Error : ORA-01704: string literal too long

What are you using when operate with CLOB?

In all events you can do it with PL/SQL

DECLARE
  str varchar2(32767);
BEGIN
  str := 'Very-very-...-very-very-very-very-very-very long string value';
  update t1 set col1 = str;
END;
/

Proof link on SQLFiddle

word-wrap break-word does not work in this example

Mozilla Firefox solution

Add:

display: inline-block;

to the style of your td.

Webkit based browsers (Google Chrome, Safari, ...) solution

Add:

display: inline-block;
word-break: break-word;

to the style of your td.

Note: Mind that, as for now, break-word is not part of the standard specification for webkit; therefore, you might be interested in employing the break-all instead. This alternative value provides a undoubtedly drastic solution; however, it conforms to the standard.

Opera solution

Add:

display: inline-block;
word-break: break-word;

to the style of your td.

The previous paragraph applies to Opera in a similar way.

How do I use boolean variables in Perl?

The most complete, concise definition of false I've come across is:

Anything that stringifies to the empty string or the string 0 is false. Everything else is true.

Therefore, the following values are false:

  • The empty string
  • Numerical value zero
  • An undefined value
  • An object with an overloaded boolean operator that evaluates one of the above.
  • A magical variable that evaluates to one of the above on fetch.

Keep in mind that an empty list literal evaluates to an undefined value in scalar context, so it evaluates to something false.


A note on "true zeroes"

While numbers that stringify to 0 are false, strings that numify to zero aren't necessarily. The only false strings are 0 and the empty string. Any other string, even if it numifies to zero, is true.

The following are strings that are true as a boolean and zero as a number:

  • Without a warning:
    • "0.0"
    • "0E0"
    • "00"
    • "+0"
    • "-0"
    • " 0"
    • "0\n"
    • ".0"
    • "0."
    • "0 but true"
    • "\t00"
    • "\n0e1"
    • "+0.e-9"
  • With a warning:
    • Any string for which Scalar::Util::looks_like_number returns false. (e.g. "abc")

ASP.NET MVC 404 Error Handling

The response from Marco is the BEST solution. I needed to control my error handling, and I mean really CONTROL it. Of course, I have extended the solution a little and created a full error management system that manages everything. I have also read about this solution in other blogs and it seems very acceptable by most of the advanced developers.

Here is the final code that I am using:

protected void Application_EndRequest()
    {
        if (Context.Response.StatusCode == 404)
        {
            var exception = Server.GetLastError();
            var httpException = exception as HttpException;
            Response.Clear();
            Server.ClearError();
            var routeData = new RouteData();
            routeData.Values["controller"] = "ErrorManager";
            routeData.Values["action"] = "Fire404Error";
            routeData.Values["exception"] = exception;
            Response.StatusCode = 500;

            if (httpException != null)
            {
                Response.StatusCode = httpException.GetHttpCode();
                switch (Response.StatusCode)
                {
                    case 404:
                        routeData.Values["action"] = "Fire404Error";
                        break;
                }
            }
            // Avoid IIS7 getting in the middle
            Response.TrySkipIisCustomErrors = true;
            IController errormanagerController = new ErrorManagerController();
            HttpContextWrapper wrapper = new HttpContextWrapper(Context);
            var rc = new RequestContext(wrapper, routeData);
            errormanagerController.Execute(rc);
        }
    }

and inside my ErrorManagerController :

        public void Fire404Error(HttpException exception)
    {
        //you can place any other error handling code here
        throw new PageNotFoundException("page or resource");
    }

Now, in my Action, I am throwing a Custom Exception that I have created. And my Controller is inheriting from a custom Controller Based class that I have created. The Custom Base Controller was created to override error handling. Here is my custom Base Controller class:

public class MyBasePageController : Controller
{
    protected override void OnException(ExceptionContext filterContext)
    {
        filterContext.GetType();
        filterContext.ExceptionHandled = true;
        this.View("ErrorManager", filterContext).ExecuteResult(this.ControllerContext);
        base.OnException(filterContext);
    }
}

The "ErrorManager" in the above code is just a view that is using a Model based on ExceptionContext

My solution works perfectly and I am able to handle ANY error on my website and display different messages based on ANY exception type.

Using find command in bash script

Welcome to bash. It's an old, dark and mysterious thing, capable of great magic. :-)

The option you're asking about is for the find command though, not for bash. From your command line, you can man find to see the options.

The one you're looking for is -o for "or":

  list="$(find /home/user/Desktop -name '*.bmp' -o -name '*.txt')"

That said ... Don't do this. Storage like this may work for simple filenames, but as soon as you have to deal with special characters, like spaces and newlines, all bets are off. See ParsingLs for details.

$ touch 'one.txt' 'two three.txt' 'foo.bmp'
$ list="$(find . -name \*.txt -o -name \*.bmp -type f)"
$ for file in $list; do if [ ! -f "$file" ]; then echo "MISSING: $file"; fi; done
MISSING: ./two
MISSING: three.txt

Pathname expansion (globbing) provides a much better/safer way to keep track of files. Then you can also use bash arrays:

$ a=( *.txt *.bmp )
$ declare -p a
declare -a a=([0]="one.txt" [1]="two three.txt" [2]="foo.bmp")
$ for file in "${a[@]}"; do ls -l "$file"; done
-rw-r--r--  1 ghoti  staff  0 24 May 16:27 one.txt
-rw-r--r--  1 ghoti  staff  0 24 May 16:27 two three.txt
-rw-r--r--  1 ghoti  staff  0 24 May 16:27 foo.bmp

The Bash FAQ has lots of other excellent tips about programming in bash.

Saving awk output to variable

as noted earlier, setting bash variables does not allow whitespace between the variable name on the LHS, and the variable value on the RHS, of the '=' sign.

awk can do everything and avoid the "awk"ward extra 'grep'. The use of awk's printf is to not add an unnecessary "\n" in the string which would give perl-ish matcher programs conniptions. The variable/parameter expansion for your case in bash doesn't have that issue, so either of these work:

variable=$(ps -ef | awk '/port 10 \-/ {print $12}')

variable=`ps -ef | awk '/port 10 \-/ {print $12}'`

The '-' int the awk record matching pattern removes the need to remove awk itself from the search results.

ERROR 1452: Cannot add or update a child row: a foreign key constraint fails

I am having the same issue here is my scenario

i put empty('') where value is NULL now this '' value does not match with the parent table's id

here is things need to check , all value with presented in parent table otherwise remove data from parent table then try enter image description here

enter image description here enter image description here

How do I get PHP errors to display?

If you have Xdebug installed you can override every setting by setting:

xdebug.force_display_errors = 1;
xdebug.force_error_reporting = -1;

force_display_errors

Type: int, Default value: 0, Introduced in Xdebug >= 2.3 If this setting is set to 1 then errors will always be displayed, no matter what the setting of PHP's display_errors is.

force_error_reporting

Type: int, Default value: 0, Introduced in Xdebug >= 2.3 This setting is a bitmask, like error_reporting. This bitmask will be logically ORed with the bitmask represented by error_reporting to dermine which errors should be displayed. This setting can only be made in php.ini and allows you to force certain errors from being shown no matter what an application does with ini_set().

Warning: Cannot modify header information - headers already sent by ERROR

Check the document encoding.

I had this same problem. I develop on Windows XP using Notepad++ and WampServer to run Apache locally and all was fine. After uploading to hosting provider that uses Apache on Unix I got this error. I had no extra PHP tags or white-space from extra lines after the closing tag.

For me this was caused by the encoding of the text documents. I used the "Convert to UTF-8 without BOM" option in Notepad++(under Encoding tab) and reloaded to the web server. Problem fixed, no code/editing changes required.

CSS position absolute full width problem

I have similar situation. In my case, it doesn't have a parent with position:relative. Just paste my solution here for those that might need.

position: fixed;
left: 0;
right: 0;

Private pages for a private Github repo

This is finally possible for GitHub Enterprise Cloud customers: Access control for GitHub Pages.

To enable access control on Pages, navigate to your repository settings, and click the dropdown menu to toggle between public and private visibility for your site.

enter image description here

How to compile or convert sass / scss to css with node-sass (no Ruby)?

I picked node-sass implementer for libsass because it is based on node.js.

Installing node-sass

  • (Prerequisite) If you don't have npm, install Node.js first.
  • $ npm install -g node-sass installs node-sass globally -g.

This will hopefully install all you need, if not read libsass at the bottom.

How to use node-sass from Command line and npm scripts

General format:

$ node-sass [options] <input.scss> [output.css]
$ cat <input.scss> | node-sass > output.css

Examples:

  1. $ node-sass my-styles.scss my-styles.css compiles a single file manually.
  2. $ node-sass my-sass-folder/ -o my-css-folder/ compiles all the files in a folder manually.
  3. $ node-sass -w sass/ -o css/ compiles all the files in a folder automatically whenever the source file(s) are modified. -w adds a watch for changes to the file(s).

More usefull options like 'compression' @ here. Command line is good for a quick solution, however, you can use task runners like Grunt.js or Gulp.js to automate the build process.

You can also add the above examples to npm scripts. To properly use npm scripts as an alternative to gulp read this comprehensive article @ css-tricks.com especially read about grouping tasks.

  • If there is no package.json file in your project directory running $ npm init will create one. Use it with -y to skip the questions.
  • Add "sass": "node-sass -w sass/ -o css/" to scripts in package.json file. It should look something like this:
"scripts": {
    "test" : "bla bla bla",
    "sass": "node-sass -w sass/ -o css/"
 }
  • $ npm run sass will compile your files.

How to use with gulp

  • $ npm install -g gulp installs Gulp globally.
  • If there is no package.json file in your project directory running $ npm init will create one. Use it with -y to skip the questions.
  • $ npm install --save-dev gulp installs Gulp locally. --save-dev adds gulp to devDependencies in package.json.
  • $ npm install gulp-sass --save-dev installs gulp-sass locally.
  • Setup gulp for your project by creating a gulpfile.js file in your project root folder with this content:
'use strict';
var gulp = require('gulp');

A basic example to transpile

Add this code to your gulpfile.js:

var gulp = require('gulp');
var sass = require('gulp-sass');
gulp.task('sass', function () {
  gulp.src('./sass/**/*.scss')
    .pipe(sass().on('error', sass.logError))
    .pipe(gulp.dest('./css'));
});

$ gulp sass runs the above task which compiles .scss file(s) in the sass folder and generates .css file(s) in the css folder.

To make life easier, let's add a watch so we don't have to compile it manually. Add this code to your gulpfile.js:

gulp.task('sass:watch', function () {
  gulp.watch('./sass/**/*.scss', ['sass']);
});

All is set now! Just run the watch task:

$ gulp sass:watch

How to use with Node.js

As the name of node-sass implies, you can write your own node.js scripts for transpiling. If you are curious, check out node-sass project page.

What about libsass?

Libsass is a library that needs to be built by an implementer such as sassC or in our case node-sass. Node-sass contains a built version of libsass which it uses by default. If the build file doesn't work on your machine, it tries to build libsass for your machine. This process requires Python 2.7.x (3.x doesn't work as of today). In addition:

LibSass requires GCC 4.6+ or Clang/LLVM. If your OS is older, this version may not compile. On Windows, you need MinGW with GCC 4.6+ or VS 2013 Update 4+. It is also possible to build LibSass with Clang/LLVM on Windows.

JavaScript code for getting the selected value from a combo box

I use this

var e = document.getElementById('ticket_category_clone').value;

Notice that you don't need the '#' character in javascript.

    function check () {

    var str = document.getElementById('ticket_category_clone').value;

      if (str==="Hardware")
      {
        SPICEWORKS.utils.addStyle('#ticket_c_hardware_clone{display: none !important;}');
      }

    }

SPICEWORKS.app.helpdesk.ready(check);?

C#: Converting byte array to string and printing out to console

For some fun with linq and string interpolation:

public string ByteArrayToString(byte[] bytes)
{
    if ( bytes == null ) return "null";
    string joinedBytes = string.Join(", ", bytes.Select(b => b.ToString()));
    return $"new byte[] {{ {joinedBytes} }}";
}

Test cases:

byte[] bytes = { 1, 2, 3, 4 };
ByteArrayToString( bytes ) .Dump();
ByteArrayToString(null).Dump();
ByteArrayToString(new byte[] {} ) .Dump();

Output:

new byte[] { 1, 2, 3, 4 }
null
new byte[] {  }

How do I move an existing Git submodule within a Git repository?

The most modern answer, taken from Valloric's comment above:

  1. Upgrade to Git 1.9.3 (or 2.18 if the submodule contains nested submodules)
  2. git mv old/submod new/submod
  3. Afterwards the .gitmodules and the submodule directory are already staged for a commit (you can verify this with git status.)
  4. Commit the changes with git commitand you're good to go!

Done!

How do I reflect over the members of dynamic object?

Requires Newtonsoft Json.Net

A little late, but I came up with this. It gives you just the keys and then you can use those on the dynamic:

public List<string> GetPropertyKeysForDynamic(dynamic dynamicToGetPropertiesFor)
{
    JObject attributesAsJObject = dynamicToGetPropertiesFor;
    Dictionary<string, object> values = attributesAsJObject.ToObject<Dictionary<string, object>>();
    List<string> toReturn = new List<string>();
    foreach (string key in values.Keys)
    {
        toReturn.Add(key);                
    }
    return toReturn;
}

Then you simply foreach like this:

foreach(string propertyName in GetPropertyKeysForDynamic(dynamicToGetPropertiesFor))
{
    dynamic/object/string propertyValue = dynamicToGetPropertiesFor[propertyName];
    // And
    dynamicToGetPropertiesFor[propertyName] = "Your Value"; // Or an object value
}

Choosing to get the value as a string or some other object, or do another dynamic and use the lookup again.

Truncate (not round) decimal places in SQL Server

Actually whatever the third parameter is, 0 or 1 or 2, it will not round your value.

CAST(ROUND(10.0055,2,0) AS NUMERIC(10,2))

Custom Listview Adapter with filter Android

If you want to achieve filtering with custom model class in kotlin then you can implement below code.

Step 1: Add SearchView in your xml file and then in your activity or fragment implement SearchView.OnQueryTextListener

class SearchActivity : AppCompatActivity(),SearchView.OnQueryTextListener {


    lateinit var sectionModelArrayList: ArrayList<CategorySectionModel>
    lateinit var filteredArrayList: ArrayList<CategorySectionModel>

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_category_updated)
        searchView.setOnQueryTextListener(this)
    }


    //Called this method with you own data to populate the recycler view.
    private fun parseJson() {
        rv_category_list.layoutManager = LinearLayoutManager(this, RecyclerView.VERTICAL, false)
        adapter = CategoryLabelAdapter(sectionModelArrayList, this)
        rv_category_list.adapter = adapter
    }

    override fun onQueryTextSubmit(query: String?): Boolean {
        return false
    }

    override fun onQueryTextChange(newText: String?): Boolean {
        adapter.filter!!.filter(newText.toString())
        return false
    }

My model class CategorySectionModel looks like

class CategorySectionModel(val categoryLabel: String, val categoryItemList: ArrayList<CategoryItem>)

Now we have to work on adapter class and there you need to implement Filterable interface and override getFilter() method like below

class CategoryLabelAdapter(internal var data: ArrayList<CategorySectionModel>?, internal var activity: Context) : RecyclerView.Adapter<CategoryLabelAdapter.ViewHolder>(), Filterable {
    val originalList = data
    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        val v = LayoutInflater.from(parent.context).inflate(R.layout.item_category_name, parent, false)
        return ViewHolder(v)
    }

    override fun getItemCount(): Int {
        return data!!.size
    }

    override fun onBindViewHolder(holder: ViewHolder, position: Int) {
        data?.get(position)?.let { holder.bindItem(it) }
    }


    class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {
        @SuppressLint("SetTextI18n")
        fun bindItem(data: CategorySectionModel) {
            itemView.tv_category_name.text = data.categoryLabel
        }
    }

    override fun getFilter(): Filter? {
        return object : Filter() {
            override fun performFiltering(constraint: CharSequence): FilterResults {
                val results = FilterResults()
                if (constraint.isEmpty()) {
                    //no filter implemented we return full list
                    results.values = data
                    results.count = data!!.size
                } else {
                    //Here we perform filtering operation
                    val list: ArrayList<CategorySectionModel> = ArrayList()
                    for (p in data!!) {
                        if (p.categoryLabel.toUpperCase().startsWith(constraint.toString().toUpperCase())) list.add(p)
                    }
                    results.values = list
                    results.count = list.size
                }
                return results
            }

            override fun publishResults(constraint: CharSequence, results: FilterResults) {
                // Now we have to inform the adapter about the new list filtered
                if (results.count == 0 || constraint == "") {
                    data = originalList
                    notifyDataSetChanged()
                } else {
                    data = results.values as ArrayList<CategorySectionModel>?
                    notifyDataSetChanged()
                }
            }
        }
    }
}

How do I check if an element is really visible with JavaScript?

You can use the clientHeight or clientWidth properties

function isViewable(element){
  return (element.clientHeight > 0);
}

Check image width and height before upload with Javascript

You can do the steps for previewing the image without showing it which is supported on all browsers. Following js code shows you how to check the width and height :

var file = e.target.files[0];
if (/\.(jpe?g|png|gif)$/i.test(file.name)) {
    var reader = new FileReader();
    reader.addEventListener("load", function () {
        var image = new Image();
        image.src = this.result as string;
        image.addEventListener('load', function () {
            console.log(`height: ${this.height}, width: ${this.width}`);
        });
                
    }, false);
            
    reader.readAsDataURL(file);
}

Based on Mozilla docs:

The readAsDataURL method is used to read the contents of the specified Blob or File. When the read operation is finished, the readyState becomes DONE, and the loadend is triggered. At that time, the result attribute contains the data as a data: URL representing the file's data as a base64 encoded string.

And the browser compatibility is listed too.

Finding the number of days between two dates

Object oriented style:

$datetime1 = new DateTime('2009-10-11');
$datetime2 = new DateTime('2009-10-13');
$interval = $datetime1->diff($datetime2);
echo $interval->format('%R%a days');

Procedural style:

$datetime1 = date_create('2009-10-11');
$datetime2 = date_create('2009-10-13');
$interval = date_diff($datetime1, $datetime2);
echo $interval->format('%R%a days');

How can I take a screenshot with Selenium WebDriver?

Python

You can capture the image from windows using the Python web driver. Use the code below which page need to capture the screenshot.

driver.save_screenshot('c:\foldername\filename.extension(png, jpeg)')

What is the PHP syntax to check "is not null" or an empty string?

Use empty(). It checks for both empty strings and null.

if (!empty($_POST['user'])) {
  // do stuff
}

From the manual:

The following things are considered to be empty:

"" (an empty string)  
0 (0 as an integer)  
0.0 (0 as a float)  
"0" (0 as a string)    
NULL  
FALSE  
array() (an empty array)  
var $var; (a variable declared, but without a value in a class)  

Importing CommonCrypto in a Swift framework

I found a GitHub project that successfully uses CommonCrypto in a Swift framework: SHA256-Swift. Also, this article about the same problem with sqlite3 was useful.

Based on the above, the steps are:

1) Create a CommonCrypto directory inside the project directory. Within, create a module.map file. The module map will allow us to use the CommonCrypto library as a module within Swift. Its contents are:

module CommonCrypto [system] {
    header "/Applications/Xcode.app/Contents/Developer/Platforms/iPhoneSimulator.platform/Developer/SDKs/iPhoneSimulator8.0.sdk/usr/include/CommonCrypto/CommonCrypto.h"
    link "CommonCrypto"
    export *
}

2) In Build Settings, within Swift Compiler - Search Paths, add the CommonCrypto directory to Import Paths (SWIFT_INCLUDE_PATHS).

Build Settings

3) Finally, import CommonCrypto inside your Swift files as any other modules. For example:

import CommonCrypto

extension String {

    func hnk_MD5String() -> String {
        if let data = self.dataUsingEncoding(NSUTF8StringEncoding)
        {
            let result = NSMutableData(length: Int(CC_MD5_DIGEST_LENGTH))
            let resultBytes = UnsafeMutablePointer<CUnsignedChar>(result.mutableBytes)
            CC_MD5(data.bytes, CC_LONG(data.length), resultBytes)
            let resultEnumerator = UnsafeBufferPointer<CUnsignedChar>(start: resultBytes, length: result.length)
            let MD5 = NSMutableString()
            for c in resultEnumerator {
                MD5.appendFormat("%02x", c)
            }
            return MD5
        }
        return ""
    }
}

Limitations

Using the custom framework in another project fails at compile time with the error missing required module 'CommonCrypto'. This is because the CommonCrypto module does not appear to be included with the custom framework. A workaround is to repeat step 2 (setting Import Paths) in the project that uses the framework.

The module map is not platform independent (it currently points to a specific platform, the iOS 8 Simulator). I don't know how to make the header path relative to the current platform.

Updates for iOS 8 <= We should remove the line link "CommonCrypto", to get the successful compilation.

UPDATE / EDIT

I kept getting the following build error:

ld: library not found for -lCommonCrypto for architecture x86_64 clang: error: linker command failed with exit code 1 (use -v to see invocation)

Unless I removed the line link "CommonCrypto" from the module.map file I created. Once I removed this line it built ok.

Creating a thumbnail from an uploaded image

I know this is an old question, but I stumbled upon the same problem and tried to use the function given in Alex's answer.

But the quality in the jpeg result was too low. So I changed the function a little bit to become more usable in my project and changed the "imagecopyresized" to "imagecopyresampled" (according to this recomendation).

If you are having questions about how to use this function, then try taking a look at the well documented version here.

function createThumbnail($filepath, $thumbpath, $thumbnail_width, $thumbnail_height, $background=false) {
    list($original_width, $original_height, $original_type) = getimagesize($filepath);
    if ($original_width > $original_height) {
        $new_width = $thumbnail_width;
        $new_height = intval($original_height * $new_width / $original_width);
    } else {
        $new_height = $thumbnail_height;
        $new_width = intval($original_width * $new_height / $original_height);
    }
    $dest_x = intval(($thumbnail_width - $new_width) / 2);
    $dest_y = intval(($thumbnail_height - $new_height) / 2);

    if ($original_type === 1) {
        $imgt = "ImageGIF";
        $imgcreatefrom = "ImageCreateFromGIF";
    } else if ($original_type === 2) {
        $imgt = "ImageJPEG";
        $imgcreatefrom = "ImageCreateFromJPEG";
    } else if ($original_type === 3) {
        $imgt = "ImagePNG";
        $imgcreatefrom = "ImageCreateFromPNG";
    } else {
        return false;
    }

    $old_image = $imgcreatefrom($filepath);
    $new_image = imagecreatetruecolor($thumbnail_width, $thumbnail_height); // creates new image, but with a black background

    // figuring out the color for the background
    if(is_array($background) && count($background) === 3) {
      list($red, $green, $blue) = $background;
      $color = imagecolorallocate($new_image, $red, $green, $blue);
      imagefill($new_image, 0, 0, $color);
    // apply transparent background only if is a png image
    } else if($background === 'transparent' && $original_type === 3) {
      imagesavealpha($new_image, TRUE);
      $color = imagecolorallocatealpha($new_image, 0, 0, 0, 127);
      imagefill($new_image, 0, 0, $color);
    }

    imagecopyresampled($new_image, $old_image, $dest_x, $dest_y, 0, 0, $new_width, $new_height, $original_width, $original_height);
    $imgt($new_image, $thumbpath);
    return file_exists($thumbpath);
}

How do I test if a variable is a number in Bash?

A clear answer has already been given by @charles Dufy and others. A pure bash solution would be using the following :

string="-12,345"
if [[ "$string" =~ ^-?[0-9]+[.,]?[0-9]*$ ]]
then
    echo $string is a number
else
    echo $string is not a number
fi

Although for real numbers it is not mandatory to have a number before the radix point.

To provide a more thorough support of floating numbers and scientific notation (many programs in C/Fortran or else will export float this way), a useful addition to this line would be the following :

string="1.2345E-67"
if [[ "$string" =~ ^-?[0-9]*[.,]?[0-9]*[eE]?-?[0-9]+$ ]]
then
    echo $string is a number
else
    echo $string is not a number
fi

Thus leading to a way to differentiate types of number, if you are looking for any specific type :

string="-12,345"
if [[ "$string" =~ ^-?[0-9]+$ ]]
then
    echo $string is an integer
elif [[ "$string" =~ ^-?[0-9]*[.,]?[0-9]*$ ]]
then
    echo $string is a float
elif [[ "$string" =~ ^-?[0-9]*[.,]?[0-9]*[eE]-?[0-9]+$ ]]
then
    echo $string is a scientific number
else
    echo $string is not a number
fi

Note: We could list the syntactical requirements for decimal and scientific notation, one being to allow comma as radix point, as well as ".". We would then assert that there must be only one such radix point. There can be two +/- signs in an [Ee] float. I have learned a few more rules from Aulu's work, and tested against bad strings such as '' '-' '-E-1' '0-0'. Here are my regex/substring/expr tools that seem to be holding up:

parse_num() {
 local r=`expr "$1" : '.*\([.,]\)' 2>/dev/null | tr -d '\n'` 
 nat='^[+-]?[0-9]+[.,]?$' \
 dot="${1%[.,]*}${r}${1##*[.,]}" \
 float='^[\+\-]?([.,0-9]+[Ee]?[-+]?|)[0-9]+$'
 [[ "$1" == $dot ]] && [[ "$1" =~ $float ]] || [[ "$1" =~ $nat ]]
} # usage: parse_num -123.456

Call an angular function inside html

Yep, just add parenthesis (calling the function). Make sure the function is in scope and actually returns something.

<ul class="ui-listview ui-radiobutton" ng-repeat="meter in meters">
  <li class = "ui-divider">
    {{ meter.DESCRIPTION }}
    {{ htmlgeneration() }}
  </li>
</ul>

Some projects cannot be imported because they already exist in the workspace error in Eclipse

Another way I just found!

MOVE the project to some other folder and then import and if required copy to workspace

How to execute .sql file using powershell?

Here is a function that I have in my PowerShell profile for loading SQL snapins:

function Load-SQL-Server-Snap-Ins
{
    try 
    {
        $sqlpsreg="HKLM:\SOFTWARE\Microsoft\PowerShell\1\ShellIds\Microsoft.SqlServer.Management.PowerShell.sqlps"

        if (!(Test-Path $sqlpsreg -ErrorAction "SilentlyContinue"))
        {
            throw "SQL Server Powershell is not installed yet (part of SQLServer installation)."
        }

        $item = Get-ItemProperty $sqlpsreg
        $sqlpsPath = [System.IO.Path]::GetDirectoryName($item.Path)

        $assemblyList = @(
            "Microsoft.SqlServer.Smo",
            "Microsoft.SqlServer.SmoExtended",
            "Microsoft.SqlServer.Dmf",
            "Microsoft.SqlServer.WmiEnum",
            "Microsoft.SqlServer.SqlWmiManagement",
            "Microsoft.SqlServer.ConnectionInfo ",
            "Microsoft.SqlServer.Management.RegisteredServers",
            "Microsoft.SqlServer.Management.Sdk.Sfc",
            "Microsoft.SqlServer.SqlEnum",
            "Microsoft.SqlServer.RegSvrEnum",
            "Microsoft.SqlServer.ServiceBrokerEnum",
            "Microsoft.SqlServer.ConnectionInfoExtended",
            "Microsoft.SqlServer.Management.Collector",
            "Microsoft.SqlServer.Management.CollectorEnum"
        )

        foreach ($assembly in $assemblyList)
        { 
            $assembly = [System.Reflection.Assembly]::LoadWithPartialName($assembly) 
            if ($assembly -eq $null)
                { Write-Host "`t`t($MyInvocation.InvocationName): Could not load $assembly" }
        }

        Set-Variable -scope Global -name SqlServerMaximumChildItems -Value 0
        Set-Variable -scope Global -name SqlServerConnectionTimeout -Value 30
        Set-Variable -scope Global -name SqlServerIncludeSystemObjects -Value $false
        Set-Variable -scope Global -name SqlServerMaximumTabCompletion -Value 1000

        Push-Location

         if ((Get-PSSnapin -Name SqlServerProviderSnapin100 -ErrorAction SilentlyContinue) -eq $null) 
        { 
            cd $sqlpsPath

            Add-PsSnapin SqlServerProviderSnapin100 -ErrorAction Stop
            Add-PsSnapin SqlServerCmdletSnapin100 -ErrorAction Stop
            Update-TypeData -PrependPath SQLProvider.Types.ps1xml
            Update-FormatData -PrependPath SQLProvider.Format.ps1xml
        }
    } 

    catch 
    {
        Write-Host "`t`t$($MyInvocation.InvocationName): $_" 
    }

    finally
    {
        Pop-Location
    }
}

How to determine previous page URL in Angular?

Angular 8 & rxjs 6 in 2019 version

I would like to share the solution based on others great solutions.

First make a service to listen for routes changes and save the last previous route in a Behavior Subject, then provide this service in the main app.component in constructor then use this service to get the previous route you want when ever you want.

use case: you want to redirect the user to an advertise page then auto redirect him/her to where he did came from so you need the last previous route to do so.

// service : route-events.service.ts

import { Injectable } from '@angular/core';
import { Router, RoutesRecognized } from '@angular/router';
import { BehaviorSubject } from 'rxjs';
import { filter, pairwise } from 'rxjs/operators';
import { Location } from '@angular/common';

@Injectable()
export class RouteEventsService {

    // save the previous route
  public previousRoutePath = new BehaviorSubject<string>('');

  constructor(
    private router: Router,
    private location: Location
  ) {

    // ..initial prvious route will be the current path for now
    this.previousRoutePath.next(this.location.path());


    // on every route change take the two events of two routes changed(using pairwise)
    // and save the old one in a behavious subject to access it in another component
    // we can use if another component like intro-advertise need the previous route
    // because he need to redirect the user to where he did came from.
    this.router.events.pipe(
      filter(e => e instanceof RoutesRecognized),
      pairwise(),
        )
    .subscribe((event: any[]) => {
        this.previousRoutePath.next(event[0].urlAfterRedirects);
    });

  }
}

provide the service in app.module

  providers: [
    ....
    RouteEventsService,
    ....
  ]

Inject it in app.component

  constructor(
    private routeEventsService: RouteEventsService
  )

finally use the saved previous route in the component you want

  onSkipHandler(){
    // navigate the user to where he did came from
    this.router.navigate([this.routeEventsService.previousRoutePath.value]);
  }

MongoDB: How to query for records where field is null or not set?

Seems you can just do single line:

{ "sent_at": null }

"Parameter not valid" exception loading System.Drawing.Image

Which line is throwing the exception? The new MemoryStream(...)? or the Image.FromStream(...)? And what is the byteArrayIn? Is it a byte[]? I only ask because of the comment "And none of value in it is not greater than 255" - which of course is automatic for a byte[].

As a more obvious question: does the binary actually contain an image in a sensible format?

For example, the following (although not great code) works fine:

    byte[] data = File.ReadAllBytes(@"d:\extn.png"); // not a good idea...
    MemoryStream ms = new MemoryStream(data);
    Image img = Image.FromStream(ms);
    Console.WriteLine(img.Width);
    Console.WriteLine(img.Height);

what is an illegal reflective access

Apart from an understanding of the accesses amongst modules and their respective packages. I believe the crux of it lies in the Module System#Relaxed-strong-encapsulation and I would just cherry-pick the relevant parts of it to try and answer the question.

What defines an illegal reflective access and what circumstances trigger the warning?

To aid in the migration to Java-9, the strong encapsulation of the modules could be relaxed.

  • An implementation may provide static access, i.e. by compiled bytecode.

  • May provide a means to invoke its run-time system with one or more packages of one or more of its modules open to code in all unnamed modules, i.e. to code on the classpath. If the run-time system is invoked in this way, and if by doing so some invocations of the reflection APIs succeed where otherwise they would have failed.

In such cases, you've actually ended up making a reflective access which is "illegal" since in a pure modular world you were not meant to do such accesses.

How it all hangs together and what triggers the warning in what scenario?

This relaxation of the encapsulation is controlled at runtime by a new launcher option --illegal-access which by default in Java9 equals permit. The permit mode ensures

The first reflective-access operation to any such package causes a warning to be issued, but no warnings are issued after that point. This single warning describes how to enable further warnings. This warning cannot be suppressed.

The modes are configurable with values debug(message as well as stacktrace for every such access), warn(message for each such access), and deny(disables such operations).


Few things to debug and fix on applications would be:-

  • Run it with --illegal-access=deny to get to know about and avoid opening packages from one module to another without a module declaration including such a directive(opens) or explicit use of --add-opens VM arg.
  • Static references from compiled code to JDK-internal APIs could be identified using the jdeps tool with the --jdk-internals option

The warning message issued when an illegal reflective-access operation is detected has the following form:

WARNING: Illegal reflective access by $PERPETRATOR to $VICTIM

where:

$PERPETRATOR is the fully-qualified name of the type containing the code that invoked the reflective operation in question plus the code source (i.e., JAR-file path), if available, and

$VICTIM is a string that describes the member being accessed, including the fully-qualified name of the enclosing type

Questions for such a sample warning: = JDK9: An illegal reflective access operation has occurred. org.python.core.PySystemState

Last and an important note, while trying to ensure that you do not face such warnings and are future safe, all you need to do is ensure your modules are not making those illegal reflective accesses. :)

How to search for string in an array

You could use the following without the wrapper function, but it provides a nicer API:

Function IsInArray(ByVal findString as String, ByVal arrayToSearch as Variant) as Boolean
  IsInArray = UBound(Filter(arrayToSearch,findString)) >= 0
End Function

The Filter function has the following signature:

Filter(sourceArray, stringToMatch, [Include As Boolean = True], [Compare as VbCompareMethod = vbBinaryCompare])

What is href="#" and why is it used?

Unfortunately, the most common use of <a href="#"> is by lazy programmers who want clickable non-hyperlink javascript-coded elements that behave like anchors, but they can't be arsed to add cursor: pointer; or :hover styles to a class for their non-hyperlink elements, and are additionally too lazy to set href to javascript:void(0);.

The problem with this is that one <a href="#" onclick="some_function();"> or another inevitably ends up with a javascript error, and an anchor with an onclick javascript error always ends up following its href. Normally this ends up being an annoying jump to the top of the page, but in the case of sites using <base>, <a href="#"> is handled as <a href="[base href]/#">, resulting in an unexpected navigation. If any logable errors are being generated, you won't see them in the latter case unless you enable persistent logs.

If an anchor element is used as a non-anchor it should have its href set to javascript:void(0); for the sake of graceful degradation.

I just wasted two days debugging a random unexpected page redirect that should have simply refreshed the page, and finally tracked it down to a function raising the click event of an <a href="#">. Replacing the # with javascript:void(0); fixed it.

The first thing I'm doing Monday is purging the project of all instances of <a href="#">.

matplotlib: colorbars and its text labels

import matplotlib.pyplot as plt
import numpy as np
from matplotlib.colors import ListedColormap

#discrete color scheme
cMap = ListedColormap(['white', 'green', 'blue','red'])

#data
np.random.seed(42)
data = np.random.rand(4, 4)
fig, ax = plt.subplots()
heatmap = ax.pcolor(data, cmap=cMap)

#legend
cbar = plt.colorbar(heatmap)

cbar.ax.get_yaxis().set_ticks([])
for j, lab in enumerate(['$0$','$1$','$2$','$>3$']):
    cbar.ax.text(.5, (2 * j + 1) / 8.0, lab, ha='center', va='center')
cbar.ax.get_yaxis().labelpad = 15
cbar.ax.set_ylabel('# of contacts', rotation=270)


# put the major ticks at the middle of each cell
ax.set_xticks(np.arange(data.shape[1]) + 0.5, minor=False)
ax.set_yticks(np.arange(data.shape[0]) + 0.5, minor=False)
ax.invert_yaxis()

#labels
column_labels = list('ABCD')
row_labels = list('WXYZ')
ax.set_xticklabels(column_labels, minor=False)
ax.set_yticklabels(row_labels, minor=False)

plt.show()

You were very close. Once you have a reference to the color bar axis, you can do what ever you want to it, including putting text labels in the middle. You might want to play with the formatting to make it more visible.

demo

With CSS, how do I make an image span the full width of the page as a background image?

Background images, ideally, are always done with CSS. All other images are done with html. This will span the whole background of your site.

body {
  background: url('../images/cat.ong');
  background-size: cover;
  background-position: center;
  background-attachment: fixed;
}

Changing position of the Dialog on screen android

I used this code to show the dialog at the bottom of the screen:

Dialog dlg = <code to create custom dialog>;

Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();

wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);

This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about


private void showPictureialog() {
    final Dialog dialog = new Dialog(this,
            android.R.style.Theme_Translucent_NoTitleBar);

    // Setting dialogview
    Window window = dialog.getWindow();
    window.setGravity(Gravity.CENTER);

    window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    dialog.setTitle(null);
    dialog.setContentView(R.layout.selectpic_dialog);
    dialog.setCancelable(true);

    dialog.show();
}

you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment

AngularJS accessing DOM elements inside directive template

You could write a directive for this, which simply assigns the (jqLite) element to the scope using an attribute-given name.

Here is the directive:

app.directive("ngScopeElement", function () {
  var directiveDefinitionObject = {

    restrict: "A",

    compile: function compile(tElement, tAttrs, transclude) {
      return {
          pre: function preLink(scope, iElement, iAttrs, controller) {
            scope[iAttrs.ngScopeElement] = iElement;
          }
        };
    }
  };

  return directiveDefinitionObject;
});

Usage:

app.directive("myDirective", function() {
    return {
        template: '<div><ul ng-scope-element="list"><li ng-repeat="item in items"></ul></div>',
        link: function(scope, element, attrs) {
            scope.list[0] // scope.list is the jqlite element, 
                          // scope.list[0] is the native dom element
        }
    }
});

Some remarks:

  • Due to the compile and link order for nested directives you can only access scope.list from myDirectives postLink-Function, which you are very likely using anyway
  • ngScopeElement uses a preLink-function, so that directives nested within the element having ng-scope-element can already access scope.list
  • not sure how this behaves performance-wise

Accessing localhost of PC from USB connected Android mobile device

I did this on a windows computer and it worked perfectly!

Turn on USB Tethering in your mobile. Type ipconfig in the command prompt in your computer and find the ipv4 for "ethernet adapter local area connection x" (mostly the first one) Now go to your mobile browser, type that ipv4 with the port number of your web application. eg:- 192.168.40.142:1342

It worked with those simple steps!

Should you choose the MONEY or DECIMAL(x,y) datatypes in SQL Server?

As a counter point to the general thrust of the other answers. See The Many Benefits of Money…Data Type! in SQLCAT's Guide to Relational Engine

Specifically I would point out the following

Working on customer implementations, we found some interesting performance numbers concerning the money data type. For example, when Analysis Services was set to the currency data type (from double) to match the SQL Server money data type, there was a 13% improvement in processing speed (rows/sec). To get faster performance within SQL Server Integration Services (SSIS) to load 1.18 TB in under thirty minutes, as noted in SSIS 2008 - world record ETL performance, it was observed that changing the four decimal(9,2) columns with a size of 5 bytes in the TPC-H LINEITEM table to money (8 bytes) improved bulk inserting speed by 20% ... The reason for the performance improvement is because of SQL Server’s Tabular Data Stream (TDS) protocol, which has the key design principle to transfer data in compact binary form and as close as possible to the internal storage format of SQL Server. Empirically, this was observed during the SSIS 2008 - world record ETL performance test using Kernrate; the protocol dropped significantly when the data type was switched to money from decimal. This makes the transfer of data as efficient as possible. A complex data type needs additional parsing and CPU cycles to handle than a fixed-width type.

So the answer to the question is "it depends". You need to be more careful with certain arithmetical operations to preserve precision but you may find that performance considerations make this worthwhile.

Hidden property of a button in HTML

It also works without jQuery if you do the following changes:

  1. Add type="button" to the edit button in order not to trigger submission of the form.

  2. Change the name of your function from change() to anything else.

  3. Don't use hidden="hidden", use CSS instead: style="display: none;".

The following code works for me:

<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<link rel="STYLESHEET" type="text/css" href="dba_style/buttons.css" />
<title>Untitled Document</title>
</head>
<script type="text/javascript">
function do_change(){
document.getElementById("save").style.display = "block";
document.getElementById("change").style.display = "block";
document.getElementById("cancel").style.display = "block";
}
</script>
<body>
<form name="form1" method="post" action="">
<div class="buttons">

<button type="button" class="regular" name="edit" id="edit" onclick="do_change(); return false;">
    <img src="dba_images/textfield_key.png" alt=""/>
    Edit
</button>

<button type="submit" class="positive" name="save" id="save" style="display:none;">
    <img src="dba_images/apply2.png" alt=""/>
    Save
</button>

<button class="regular" name="change" id="change" style="display:none;">
    <img src="dba_images/textfield_key.png" alt=""/>
    change
</button>

    <button class="negative" name="cancel" id="cancel" style="display:none;">
        <img src="dba_images/cross.png" alt=""/>
        Cancel
    </button>
</div>
</form>
</body>
</html>

How to manage exceptions thrown in filters in Spring?

It's strange because @ControllerAdvice should works, are you catching the correct Exception?

@ControllerAdvice
public class GlobalDefaultExceptionHandler {

    @ResponseBody
    @ExceptionHandler(value = DataAccessException.class)
    public String defaultErrorHandler(HttpServletResponse response, DataAccessException e) throws Exception {
       response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
       //Json return
    }
}

Also try to catch this exception in CorsFilter and send 500 error, something like this

@ExceptionHandler(DataAccessException.class)
@ResponseBody
public String handleDataException(DataAccessException ex, HttpServletResponse response) {
    response.setStatus(HttpStatus.INTERNAL_SERVER_ERROR.value());
    //Json return
}

Determine if a cell (value) is used in any formula

Have you tried Tools > Formula Auditing?

How do I show a console output/window in a forms application?

This worked for me, to pipe the output to a file. Call the console with

cmd /c "C:\path\to\your\application.exe" > myfile.txt

Add this code to your application.

    [DllImport("kernel32.dll")]
    static extern bool AttachConsole(UInt32 dwProcessId);
    [DllImport("kernel32.dll")]
    private static extern bool GetFileInformationByHandle(
        SafeFileHandle hFile,
        out BY_HANDLE_FILE_INFORMATION lpFileInformation
        );
    [DllImport("kernel32.dll")]
    private static extern SafeFileHandle GetStdHandle(UInt32 nStdHandle);
    [DllImport("kernel32.dll")]
    private static extern bool SetStdHandle(UInt32 nStdHandle, SafeFileHandle hHandle);
    [DllImport("kernel32.dll")]
    private static extern bool DuplicateHandle(
        IntPtr hSourceProcessHandle,
        SafeFileHandle hSourceHandle,
        IntPtr hTargetProcessHandle,
        out SafeFileHandle lpTargetHandle,
        UInt32 dwDesiredAccess,
        Boolean bInheritHandle,
        UInt32 dwOptions
        );
    private const UInt32 ATTACH_PARENT_PROCESS = 0xFFFFFFFF;
    private const UInt32 STD_OUTPUT_HANDLE = 0xFFFFFFF5;
    private const UInt32 STD_ERROR_HANDLE = 0xFFFFFFF4;
    private const UInt32 DUPLICATE_SAME_ACCESS = 2;
    struct BY_HANDLE_FILE_INFORMATION
    {
        public UInt32 FileAttributes;
        public System.Runtime.InteropServices.ComTypes.FILETIME CreationTime;
        public System.Runtime.InteropServices.ComTypes.FILETIME LastAccessTime;
        public System.Runtime.InteropServices.ComTypes.FILETIME LastWriteTime;
        public UInt32 VolumeSerialNumber;
        public UInt32 FileSizeHigh;
        public UInt32 FileSizeLow;
        public UInt32 NumberOfLinks;
        public UInt32 FileIndexHigh;
        public UInt32 FileIndexLow;
    }
    static void InitConsoleHandles()
    {
        SafeFileHandle hStdOut, hStdErr, hStdOutDup, hStdErrDup;
        BY_HANDLE_FILE_INFORMATION bhfi;
        hStdOut = GetStdHandle(STD_OUTPUT_HANDLE);
        hStdErr = GetStdHandle(STD_ERROR_HANDLE);
        // Get current process handle
        IntPtr hProcess = Process.GetCurrentProcess().Handle;
        // Duplicate Stdout handle to save initial value
        DuplicateHandle(hProcess, hStdOut, hProcess, out hStdOutDup,
        0, true, DUPLICATE_SAME_ACCESS);
        // Duplicate Stderr handle to save initial value
        DuplicateHandle(hProcess, hStdErr, hProcess, out hStdErrDup,
        0, true, DUPLICATE_SAME_ACCESS);
        // Attach to console window – this may modify the standard handles
        AttachConsole(ATTACH_PARENT_PROCESS);
        // Adjust the standard handles
        if (GetFileInformationByHandle(GetStdHandle(STD_OUTPUT_HANDLE), out bhfi))
        {
            SetStdHandle(STD_OUTPUT_HANDLE, hStdOutDup);
        }
        else
        {
            SetStdHandle(STD_OUTPUT_HANDLE, hStdOut);
        }
        if (GetFileInformationByHandle(GetStdHandle(STD_ERROR_HANDLE), out bhfi))
        {
            SetStdHandle(STD_ERROR_HANDLE, hStdErrDup);
        }
        else
        {
            SetStdHandle(STD_ERROR_HANDLE, hStdErr);
        }
    }

    /// <summary>
    /// The main entry point for the application.
    /// </summary>
    [STAThread]
    static void Main(string[] args)
    {
        // initialize console handles
        InitConsoleHandles();

        if (args.Length != 0)
        {

            if (args[0].Equals("waitfordebugger"))
            {
                MessageBox.Show("Attach the debugger now");
            }
            if (args[0].Equals("version"))
            {
#if DEBUG
                String typeOfBuild = "d";
#else
                String typeOfBuild = "r";
#endif
                String output = typeOfBuild + Assembly.GetExecutingAssembly()
                    .GetName().Version.ToString();
                //Just for the fun of it
                Console.Write(output);
                Console.Beep(4000, 100);
                Console.Beep(2000, 100);
                Console.Beep(1000, 100);
                Console.Beep(8000, 100);
                return;
            }
        }
    }

I found this code here: http://www.csharp411.com/console-output-from-winforms-application/ I thought is was worthy to post it here as well.

An unhandled exception of type 'System.TypeInitializationException' occurred in EntityFramework.dll

Check that right version is referenced in your project. E.g. the dll it is complaining about, could be from an older version and that's why there could be a version mismatch.

typescript - cloning object

For a simple clone of the hole object's content, I simply stringify and parse the instance :

let cloneObject = JSON.parse(JSON.stringify(objectToClone))

Whereas I change data in objectToClone tree, there is no change in cloneObject. That was my requierement.

Hope it help

python: how to send mail with TO, CC and BCC?

The distinction between TO, CC and BCC occurs only in the text headers. At the SMTP level, everybody is a recipient.

TO - There is a TO: header with this recipient's address

CC - There is a CC: header with this recipient's address

BCC - This recipient isn't mentioned in the headers at all, but is still a recipient.

If you have

TO: [email protected]
CC: [email protected]
BCC: [email protected]

You have three recipients. The headers in the email body will include only the TO: and CC:

Downloading video from YouTube

Gonna give another answer, since the libraries mentioned haven't been actively developed anymore.

Consider using YoutubeExplode. It has a very rich and consistent API and allows you to do a lot of other things with youtube videos beside downloading them.