Programs & Examples On #Pascalscript

Free scripting engine that allows you to use most of the Object Pascal language within Delphi or Free Pascal projects at runtime.

Oracle 'Partition By' and 'Row_Number' keyword

I know this is an old thread but PARTITION is the equiv of GROUP BY not ORDER BY. ORDER BY in this function is . . . ORDER BY. It's just a way to create uniqueness out of redundancy by adding a sequence number. Or you may eliminate the other redundant records by the WHERE clause when referencing the aliased column for the function. However, DISTINCT in the SELECT statement would probably accomplish the same thing in that regard.

What does `void 0` mean?

What does void 0 mean?

void[MDN] is a prefix keyword that takes one argument and always returns undefined.

Examples

void 0
void (0)
void "hello"
void (new Date())
//all will return undefined

What's the point of that?

It seems pretty useless, doesn't it? If it always returns undefined, what's wrong with just using undefined itself?

In a perfect world we would be able to safely just use undefined: it's much simpler and easier to understand than void 0. But in case you've never noticed before, this isn't a perfect world, especially when it comes to Javascript.

The problem with using undefined was that undefined is not a reserved word (it is actually a property of the global object [wtfjs]). That is, undefined is a permissible variable name, so you could assign a new value to it at your own caprice.

alert(undefined); //alerts "undefined"
var undefined = "new value";
alert(undefined) // alerts "new value"

Note: This is no longer a problem in any environment that supports ECMAScript 5 or newer (i.e. in practice everywhere but IE 8), which defines the undefined property of the global object as read-only (so it is only possible to shadow the variable in your own local scope). However, this information is still useful for backwards-compatibility purposes.

alert(window.hasOwnProperty('undefined')); // alerts "true"
alert(window.undefined); // alerts "undefined"
alert(undefined === window.undefined); // alerts "true"
var undefined = "new value";
alert(undefined); // alerts "new value"
alert(undefined === window.undefined); // alerts "false"

void, on the other hand, cannot be overidden. void 0 will always return undefined. undefined, on the other hand, can be whatever Mr. Javascript decides he wants it to be.

Why void 0, specifically?

Why should we use void 0? What's so special about 0? Couldn't we just as easily use 1, or 42, or 1000000 or "Hello, world!"?

And the answer is, yes, we could, and it would work just as well. The only benefit of passing in 0 instead of some other argument is that 0 is short and idiomatic.

Why is this still relevant?

Although undefined can generally be trusted in modern JavaScript environments, there is one trivial advantage of void 0: it's shorter. The difference is not enough to worry about when writing code but it can add up enough over large code bases that most code minifiers replace undefined with void 0 to reduce the number of bytes sent to the browser.

Link to the issue number on GitHub within a commit message

Just as addition to the other answers: If you don't even want to write the commit message with the issue number and happen to use Eclipse for development, then you can install the eGit and Mylyn plugins as well as the GitHub connector for Mylyn. Eclipse can then automatically track which issue you are working on and automatically fill the commit message, including the issue number as shown in all the other answers.

For more details about that setup see http://wiki.eclipse.org/EGit/GitHub/UserGuide

How to set password for Redis?

you can also use following command on client

cmd :: config set requirepass p@ss$12E45

above command will set p@ss$12E45 as a redis server password.

How to check if the given string is palindrome?

Another one from Delphi, which I think is a little more rigorous than the other Delphi example submitted. This can easily turn into a golfing match, but I've tried to make mine readable.

Edit0: I was curious about the performance characteristics, so I did a little test. On my machine, I ran this function against a 60 character string 50 million times, and it took 5 seconds.

function TForm1.IsPalindrome(txt: string): boolean;
var
  i, halfway, len : integer;
begin
  Result := True;
  len := Length(txt);

  {
  special cases:
  an empty string is *never* a palindrome
  a 1-character string is *always* a palindrome
  }
  case len of
    0 : Result := False;
    1 : Result := True;
    else begin
      halfway := Round((len/2) - (1/2));  //if odd, round down to get 1/2way pt

      //scan half of our string, make sure it is mirrored on the other half
      for i := 1 to halfway do begin
        if txt[i] <> txt[len-(i-1)] then begin
          Result := False;
          Break;
        end;  //if we found a non-mirrored character
      end;  //for 1st half of string
    end;  //else not a special case
  end;  //case
end;

And here is the same thing, in C#, except that I've left it with multiple exit points, which I don't like.

private bool IsPalindrome(string txt) {
  int len = txt.Length;

  /*
  Special cases:
  An empty string is *never* a palindrome
  A 1-character string is *always* a palindrome
  */    
  switch (len) {
    case 0: return false;
    case 1: return true;
  }  //switch
  int halfway = (len / 2);

  //scan half of our string, make sure it is mirrored on the other half
  for (int i = 0; i < halfway; ++i) {
    if (txt.Substring(i,1) != txt.Substring(len - i - 1,1)) {
      return false;
    }  //if
  }  //for
  return true;
}

Ruby capitalize every word first letter

Another option is to use a regex and gsub, which takes a block:

'one TWO three foUR'.gsub(/\w+/, &:capitalize)

How to remove list elements in a for loop in Python?

As other answers have said, the best way to do this involves making a new list - either iterate over a copy, or construct a list with only the elements you want and assign it back to the same variable. The difference between these depends on your use case, since they affect other variables for the original list differently (or, rather, the first affects them, the second doesn't).

If a copy isn't an option for some reason, you do have one other option that relies on an understanding of why modifying a list you're iterating breaks. List iteration works by keeping track of an index, incrementing it each time around the loop until it falls off the end of the list. So, if you remove at (or before) the current index, everything from that point until the end shifts one spot to the left. But the iterator doesn't know about this, and effectively skips the next element since it is now at the current index rather than the next one. However, removing things that are after the current index doesn't affect things.

This implies that if you iterate the list back to front, if you remove an item at the current index, everything to it's right shifts left - but that doesn't matter, since you've already dealt with all the elements to the right of the current position, and you're moving left - the next element to the left is unaffected by the change, and so the iterator gives you the element you expect.

TL;DR:

>>> a = list(range(5))
>>> for b in reversed(a):
    if b == 3:
        a.remove(b)
>>> a
[0, 1, 2, 4]

However, making a copy is usually better in terms of making your code easy to read. I only mention this possibility for sake of completeness.

Detect IE version (prior to v9) in JavaScript

This approach to detecting IE combines the strengths and avoids the weaknesses of jKey's answer using conditional comments and Owen's answer using user agents.

  • jKey's approach works up to version 9 and immune to user agent spoofing in IE 8 & 9.
  • Owen's approach can fail on IE 5 & 6 (reporting 7) and is susceptible to UA spoofing, but it can detect IE versions >= 10 (now also including 12, which postdates Owen's answer).

    // ----------------------------------------------------------
    // A short snippet for detecting versions of IE
    // ----------------------------------------------------------
    // If you're not in IE (or IE version is less than 5) then:
    //     ie === undefined
    // Thus, to detect IE:
    //     if (ie) {}
    // And to detect the version:
    //     ie === 6 // IE6
    //     ie > 7 // IE8, IE9 ...
    // ----------------------------------------------------------
    var ie = (function(){
        var v = 3,
            div = document.createElement('div'),
            all = div.getElementsByTagName('i');
    
        while (
            div.innerHTML = '<!--[if gt IE ' + (++v) + ']><i></i><![endif]-->',
            all[0]
        );
        if (v <= 4) { // Check for IE>9 using user agent
            var match = navigator.userAgent.match(/(?:MSIE |Trident\/.*; rv:|Edge\/)(\d+)/);
            v = match ? parseInt(match[1]) : undefined;
        }
        return v;
    }());
    

This can be used to set useful classes to your document containing the IE version:

    if (ie) {
        document.documentElement.className += ' ie' + ie;
        if (ie < 9)
            document.documentElement.className += ' ieLT9';
    }

Note that it detects the compatibility mode being used, if IE is in compatability mode. Also note that IE version is mostly useful for older versions (<10); higher versions are more standards-compliant and it's probably better to instead check for features using something like modernizr.js.

Launching an application (.EXE) from C#?

Here's a snippet of helpful code:

using System.Diagnostics;

// Prepare the process to run
ProcessStartInfo start = new ProcessStartInfo();
// Enter in the command line arguments, everything you would enter after the executable name itself
start.Arguments = arguments; 
// Enter the executable to run, including the complete path
start.FileName = ExeName;
// Do you want to show a console window?
start.WindowStyle = ProcessWindowStyle.Hidden;
start.CreateNoWindow = true;
int exitCode;


// Run the external process & wait for it to finish
using (Process proc = Process.Start(start))
{
     proc.WaitForExit();

     // Retrieve the app's exit code
     exitCode = proc.ExitCode;
}

There is much more you can do with these objects, you should read the documentation: ProcessStartInfo, Process.

Using getResources() in non-activity class

I am late but complete solution;: Example Class, Use Context like this :-

public class SingletonSampleClass {

    // Your cute context
    private Context context;
    private static SingletonSampleClass instance;

  // Pass as Constructor
    private SingletonSampleClass(Context context) {
        this.context = context;
    }

    public synchronized static SingletonSampleClass getInstance(Context context) {
        if (instance == null) instance = new SingletonSampleClass(context);
        return instance;
    }

//At end, don't forgot to relase memory
    public void onDestroy() {
       if(context != null) {
          context = null; 
       }
    }
}

Warning (Memory Leaks)

How to solve this?

Option 1: Instead of passing activity context i.e. this to the singleton class, you can pass applicationContext().

Option 2: If you really have to use activity context, then when the activity is destroyed, ensure that the context you passed to the singleton class is set to null.

Hope it helps..????

Ignore cells on Excel line graph

There are many cases in which gaps are desired in a chart.

I am currently trying to make a plot of flow rate in a heating system vs. the time of day. I have data for two months. I want to plot only vs. the time of day from 00:00 to 23:59, which causes lines to be drawn between 23:59 and 00:01 of the next day which extend across the chart and disturb the otherwise regular daily variation.

Using the NA() formula (in German NV()) causes Excel to ignore the cells, but instead the previous and following points are simply connected, which has the same problem with lines across the chart.

The only solution I have been able to find is to delete the formulas from the cells which should create the gaps.

Using an IF formula with "" as its value for the gaps makes Excel interpret the X-values as string labels (shudder) for the chart instead of numbers (and makes me swear about the people who wrote that requirement).

How can I copy a conditional formatting from one document to another?

If you want to copy conditional formatting to another document you can use the "Copy to..." feature for the worksheet (click the tab with the name of the worksheet at the bottom) and copy the worksheet to the other document.

Then you can just copy what you want from that worksheet and right-click select "Paste special" -> "Paste conditional formatting only", as described earlier.

Check if a value is in an array (C#)

Add necessary namespace

using System.Linq;

Then you can use linq Contains() method

string[] printer = {"jupiter", "neptune", "pangea", "mercury", "sonic"};
if(printer.Contains("jupiter"))
{
    Process.Start("BLAH BLAH CODE TO ADD PRINTER VIA WINDOWS EXEC"");
}

Hexadecimal value 0x00 is a invalid character

I also get the same error in an ASP.NET application when I saved some unicode data (Hindi) in the Web.config file and saved it with "Unicode" encoding.

It fixed the error for me when I saved the Web.config file with "UTF-8" encoding.

Store multiple values in single key in json

{
    "success": true,
    "data": {
        "BLR": {
            "origin": "JAI",
            "destination": "BLR",
            "price": 127,
            "transfers": 0,
            "airline": "LB",
            "flight_number": 655,
            "departure_at": "2017-06-03T18:20:00Z",
            "return_at": "2017-06-07T08:30:00Z",
            "expires_at": "2017-03-05T08:40:31Z"
        }
    }
};

Random integer in VB.NET

Dim rnd As Random = New Random
rnd.Next(n)

IEnumerable vs List - What to Use? How do they work?

In addition to all the answers posted above, here is my two cents. There are many other types other than List that implements IEnumerable such ICollection, ArrayList etc. So if we have IEnumerable as parameter of any method, we can pass any collection types to the function. Ie we can have method to operate on abstraction not any specific implementation.

Installing OpenCV 2.4.3 in Visual C++ 2010 Express

1. Installing OpenCV 2.4.3

First, get OpenCV 2.4.3 from sourceforge.net. Its a self-extracting so just double click to start the installation. Install it in a directory, say C:\.

OpenCV self-extractor

Wait until all files get extracted. It will create a new directory C:\opencv which contains OpenCV header files, libraries, code samples, etc.

Now you need to add the directory C:\opencv\build\x86\vc10\bin to your system PATH. This directory contains OpenCV DLLs required for running your code.

Open Control PanelSystemAdvanced system settingsAdvanced Tab → Environment variables...

enter image description here

On the System Variables section, select Path (1), Edit (2), and type C:\opencv\build\x86\vc10\bin; (3), then click Ok.

On some computers, you may need to restart your computer for the system to recognize the environment path variables.

This will completes the OpenCV 2.4.3 installation on your computer.


2. Create a new project and set up Visual C++

Open Visual C++ and select FileNewProject...Visual C++Empty Project. Give a name for your project (e.g: cvtest) and set the project location (e.g: c:\projects).

New project dialog

Click Ok. Visual C++ will create an empty project.

VC++ empty project

Make sure that "Debug" is selected in the solution configuration combobox. Right-click cvtest and select PropertiesVC++ Directories.

Project property dialog

Select Include Directories to add a new entry and type C:\opencv\build\include.

Include directories dialog

Click Ok to close the dialog.

Back to the Property dialog, select Library Directories to add a new entry and type C:\opencv\build\x86\vc10\lib.

Library directories dialog

Click Ok to close the dialog.

Back to the property dialog, select LinkerInputAdditional Dependencies to add new entries. On the popup dialog, type the files below:

opencv_calib3d243d.lib
opencv_contrib243d.lib
opencv_core243d.lib
opencv_features2d243d.lib
opencv_flann243d.lib
opencv_gpu243d.lib
opencv_haartraining_engined.lib
opencv_highgui243d.lib
opencv_imgproc243d.lib
opencv_legacy243d.lib
opencv_ml243d.lib
opencv_nonfree243d.lib
opencv_objdetect243d.lib
opencv_photo243d.lib
opencv_stitching243d.lib
opencv_ts243d.lib
opencv_video243d.lib
opencv_videostab243d.lib

Note that the filenames end with "d" (for "debug"). Also note that if you have installed another version of OpenCV (say 2.4.9) these filenames will end with 249d instead of 243d (opencv_core249d.lib..etc).

enter image description here

Click Ok to close the dialog. Click Ok on the project properties dialog to save all settings.

NOTE:

These steps will configure Visual C++ for the "Debug" solution. For "Release" solution (optional), you need to repeat adding the OpenCV directories and in Additional Dependencies section, use:

opencv_core243.lib
opencv_imgproc243.lib
...

instead of:

opencv_core243d.lib
opencv_imgproc243d.lib
...

You've done setting up Visual C++, now is the time to write the real code. Right click your project and select AddNew Item...Visual C++C++ File.

Add new source file

Name your file (e.g: loadimg.cpp) and click Ok. Type the code below in the editor:

#include <opencv2/highgui/highgui.hpp>
#include <iostream>

using namespace cv;
using namespace std;

int main()
{
    Mat im = imread("c:/full/path/to/lena.jpg");
    if (im.empty()) 
    {
        cout << "Cannot load image!" << endl;
        return -1;
    }
    imshow("Image", im);
    waitKey(0);
}

The code above will load c:\full\path\to\lena.jpg and display the image. You can use any image you like, just make sure the path to the image is correct.

Type F5 to compile the code, and it will display the image in a nice window.

First OpenCV program

And that is your first OpenCV program!


3. Where to go from here?

Now that your OpenCV environment is ready, what's next?

  1. Go to the samples dir → c:\opencv\samples\cpp.
  2. Read and compile some code.
  3. Write your own code.

How to stash my previous commit?

If you've not pushed either commit to your remote repository, you could use interactive rebasing to 'reorder' your commits and stash the (new) most recent commit's changes only.

Assuming you have the tip of your current branch (commit 111 in your example) checked out, execute the following:

git rebase -i HEAD~2

This will open your default editor, listing most recent 2 commits and provide you with some instructions. Be very cautious as to what you do here, as you are going to effectively 'rewrite' the history of your repository, and can potentially lose work if you aren't careful (make a backup of the whole repository first if necessary). I've estimated commit hashes/titles below for example

pick 222 commit to be stashed
pick 111 commit to be pushed to remote

# Rebase 111..222 onto 333
#
# Commands:
#  p, pick = use commit
#  r, reword = use commit, but edit the commit message
#  e, edit = use commit, but stop for amending
#  s, squash = use commit, but meld into previous commit
#  f, fixup = like "squash", but discard this commit's log message
#  x, exec = run command (the rest of the line) using shell
#
# These lines can be re-ordered; they are executed from top to bottom.
#
# If you remove a line here THAT COMMIT WILL BE LOST.
#
# However, if you remove everything, the rebase will be aborted.
#
# Note that empty commits are commented out

Reorder the two commits (they are listed oldest => newest) like this:

pick 111 commit to be pushed to remote
pick 222 commit to be stashed

Save and exit, at which point git will do some processing to rewrite the two commits you have changed. Assuming no issues, you should have reversed the order of your two changesets. This can be confirmed with git log --oneline -5 which will output newest-first.

At this point, you can simply do a soft-reset on the most recent commit, and stash your working changes:

git reset --soft HEAD~1
git stash

It's important to mention that this option is only really viable if you have not previously pushed any of these changes to your remote, otherwise it can cause issues for everyone using the repository.

Send POST parameters with MultipartFormData using Alamofire, in iOS Swift

Swift 3 / Alamofire 4.0 (Addendum to the accepted answer)

To append to multipartFormData in Swift 3 / Alamofire 4.0, use the following method of MultipartFormData:

public func append(_ data: Data, withName name: String) { /* ... */ }

And, to convert String to Data, the data(using:) method of String. E.g.,

multipartFormData.append("comment".data(using: .utf8)!, withName: "comment")

Replace single quotes in SQL Server

Try REPLACE(@strip,'''','')

SQL uses two quotes to represent one in a string.

How do I debug Windows services in Visual Studio?

I use a great Nuget package called ServiceProcess.Helpers.

And I quote...

It helps windows services debugging by creating a play/stop/pause UI when running with a debugger attached, but also allows the service to be installed and run by the windows server environment.

All this with one line of code.

http://windowsservicehelper.codeplex.com/

Once installed and wired in all you need to do is set your windows service project as the start-up project and click start on your debugger.

PHP Multiple Checkbox Array

Try this, by for Loop

<form method="post">
<?php
for ($i=1; $i <5 ; $i++) 
{ 
    echo'<input type="checkbox" value="'.$i.'" name="checkbox[]"/>';
} 
?>
<input type="submit" name="submit" class="form-control" value="Submit">  
</form>

<?php 
if(isset($_POST['submit']))
{
    $check=implode(", ", $_POST['checkbox']);
    print_r($check);
}     
?>

INSERT INTO a temp table, and have an IDENTITY field created, without first declaring the temp table?

IIRC, the INSERT INTO command uses the schema of the source table to create the temp table. That's part of the reason you can't just try to create a table with an additional column. Identity columns are internally tied to a SQL Server construct called a generator.

CronJob not running

I've found another reason for user's crontab not running: the hostname is not present on the hosts file:

user@ubuntu:~$ cat /etc/hostname
ubuntu

Now the hosts file:

user@ubuntu:~$ cat /etc/hosts
127.0.0.1 localhost

# The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts

This is on a Ubuntu 14.04.3 LTS, the way to fix it is adding the hostname to the hosts file so it resembles something like this:

user@ubuntu:~$ cat /etc/hosts
127.0.0.1 ubuntu localhost

# The following lines are desirable for IPv6 capable hosts
::1 ip6-localhost ip6-loopback
fe00::0 ip6-localnet
ff00::0 ip6-mcastprefix
ff02::1 ip6-allnodes
ff02::2 ip6-allrouters
ff02::3 ip6-allhosts

How to Insert BOOL Value to MySQL Database

TRUE and FALSE are keywords, and should not be quoted as strings:

INSERT INTO first VALUES (NULL, 'G22', TRUE);
INSERT INTO first VALUES (NULL, 'G23', FALSE);

By quoting them as strings, MySQL will then cast them to their integer equivalent (since booleans are really just a one-byte INT in MySQL), which translates into zero for any non-numeric string. Thus, you get 0 for both values in your table.

Non-numeric strings cast to zero:

mysql> SELECT CAST('TRUE' AS SIGNED), CAST('FALSE' AS SIGNED), CAST('12345' AS SIGNED);
+------------------------+-------------------------+-------------------------+
| CAST('TRUE' AS SIGNED) | CAST('FALSE' AS SIGNED) | CAST('12345' AS SIGNED) |
+------------------------+-------------------------+-------------------------+
|                      0 |                       0 |                   12345 |
+------------------------+-------------------------+-------------------------+

But the keywords return their corresponding INT representation:

mysql> SELECT TRUE, FALSE;
+------+-------+
| TRUE | FALSE |
+------+-------+
|    1 |     0 |
+------+-------+

Note also, that I have replaced your double-quotes with single quotes as are more standard SQL string enclosures. Finally, I have replaced your empty strings for id with NULL. The empty string may issue a warning.

Git and nasty "error: cannot lock existing info/refs fatal"

For me this worked:

git remote prune origin

Since this answer seems to help a lot of people, I dug a little bit into what actually happens here. What this will do is remove references to remote branches in the folder .git/refs/remotes/origin. So this will not affect your local branches and it will not change anything remote, but it will update the local references you have to remote branches. It seems in some cases these references can contain data Git cannot handle correctly.

Emulating a do-while loop in Bash

This implementation:

  • Has no code duplication
  • Doesn't require extra functions()
  • Doesn't depend on the return value of code in the "while" section of the loop:
do=true
while $do || conditions; do
  do=false
  # your code ...
done

It works with a read loop, too, skipping the first read:

do=true
while $do || read foo; do
  do=false

  # your code ...
  echo $foo
done

How to use regex with find command?

Judging from other answers, it seems this might be find's fault.

However you can do it this way instead:

find . * | grep -P "[a-f0-9\-]{36}\.jpg"

You might have to tweak the grep a bit and use different options depending on what you want but it works.

How do I print to the debug output window in a Win32 app?

To print to the real console, you need to make it visible by using the linker flag /SUBSYSTEM:CONSOLE. The extra console window is annoying, but for debugging purposes it's very valuable.

OutputDebugString prints to the debugger output when running inside the debugger.

MySQL Error: : 'Access denied for user 'root'@'localhost'

Okay, I know this is an old thread but if you reached this page via Google like I did and none of the above solutions worked, what turned out to be the error was 100% foolishness on my end. I didn't connect to the server. Once connected everything was smooth sailing.

In case it helps to know my setup, I'm using Sequel Pro and trying to connect to it with Node using the NPM package, mysql. I didn't think I needed to actually connect (other than run Sequel Pro) because I was doing that from my app already.

enter image description here

Usage of $broadcast(), $emit() And $on() in AngularJS

  • Broadcast: We can pass the value from parent to child (i.e parent -> child controller.)
  • Emit: we can pass the value from child to parent (i.e.child ->parent controller.)
  • On: catch the event dispatched by $broadcast or $emit.

Import/Index a JSON file into Elasticsearch

Adding to KenH's answer

$ curl -s -XPOST localhost:9200/_bulk --data-binary @requests

You can replace @requests with @complete_path_to_json_file

Note: @is important before the file path

Why is my toFixed() function not working?

You're not assigning the parsed float back to your value var:

value = parseFloat(value).toFixed(2);

should fix things up.

How can I replace a regex substring match in Javascript?

using str.replace(regex, $1);:

var str   = 'asd-0.testing';
var regex = /(asd-)\d(\.\w+)/;

if (str.match(regex)) {
    str = str.replace(regex, "$1" + "1" + "$2");
}

Edit: adaptation regarding the comment

ReferenceError: event is not defined error in Firefox

You're declaring (some of) your event handlers incorrectly:

$('.menuOption').click(function( event ){ // <---- "event" parameter here

    event.preventDefault();
    var categories = $(this).attr('rel');
    $('.pages').hide();
    $(categories).fadeIn();


});

You need "event" to be a parameter to the handlers. WebKit follows IE's old behavior of using a global symbol for "event", but Firefox doesn't. When you're using jQuery, that library normalizes the behavior and ensures that your event handlers are passed the event parameter.

edit — to clarify: you have to provide some parameter name; using event makes it clear what you intend, but you can call it e or cupcake or anything else.

Note also that the reason you probably should use the parameter passed in from jQuery instead of the "native" one (in Chrome and IE and Safari) is that that one (the parameter) is a jQuery wrapper around the native event object. The wrapper is what normalizes the event behavior across browsers. If you use the global version, you don't get that.

Codeigniter how to create PDF

Please click on this link it should work ..

http://www.php-guru.in/2013/html-to-pdf-conversion-in-codeigniter/

Or you can see below

There are number of PHP libraries on the web to convert HTML page to PDF file. They are easy to implement and deploy when you are working on any web application in core PHP. But when we try to integrate this libraries with any framework or template, then it becomes very tedious work if the framework which we are using does not have its own library to integrate it with any PDF library. The same situation came in front of me when there was one requirement to convert HTML page to PDF file and the framework I was using was codeigniter.

I searched on web and got number of PHP libraries to convert HTML page to PDF file. After lot of research and googling I decided to go with TCPDF PHP library to convert HTML page to PDF file for my requirement. I found TCPDf PHP library quite easy to integrate with codeigniter and stated working on it. After successfully completing my integration of codeigniter and TCPDF, I thought of sharing this script on web.

Now, let’s start with implimentation of the code.

Download the TCPDF library code, you can download it from TCPDF website http://www.tcpdf.org/.

Now create “tcpdf” folder in “application/helpers/” directory of your web application which is developed in codeigniter. Copy all TCPDF library files and paste it in “application/helpers/tcpdf/” directory. Update the configuration file “tcpdf_config.php” of TCPDF, which is located in “application/helpers/tcpdf/config” directory, do changes according to your applicatoin requirements. We can set logo, font, font size, with, height, header etc in the cofing file. Give read, write permissions to “cache” folder which is there in tcpdf folder. After defining your directory structure, updating configuration file and assigning permissions, here starts your actual coding part.

Create one PHP helper file in “application/helpers/” directory of codeigniter, say “pdf_helper.php”, then copy below given code and paste it in helper file

Helper: application/helpers/pdf_helper.php

function tcpdf()
{
    require_once('tcpdf/config/lang/eng.php');
    require_once('tcpdf/tcpdf.php');
}

Then in controller file call the above helper, suppose our controller file is “createpdf.php” and it has method as pdf(), so the method pdf() will load the “pdf_helper” helper and will also have any other code.

Controller: application/controllers/createpdf.php

function pdf()
{
    $this->load->helper('pdf_helper');
    /*
        ---- ---- ---- ----
        your code here
        ---- ---- ---- ----
    */
    $this->load->view('pdfreport', $data);
}

Now create one view file, say “pdfreport.php” in “application/views/” directory, which is also loaded in pdf() method in controller. So in view file we can directly call the tcpdf() function which we have defined in “pdf_helper” helper, which will load all required TCPDF classes, functions, variable etc. Then we can directly use the TCPDF example codes as it is in our current controller or view. Now in out current view “pdfreport” copy the given code below:

View: application/views/pdfreport.php

tcpdf();
$obj_pdf = new TCPDF('P', PDF_UNIT, PDF_PAGE_FORMAT, true, 'UTF-8', false);
$obj_pdf->SetCreator(PDF_CREATOR);
$title = "PDF Report";
$obj_pdf->SetTitle($title);
$obj_pdf->SetHeaderData(PDF_HEADER_LOGO, PDF_HEADER_LOGO_WIDTH, $title, PDF_HEADER_STRING);
$obj_pdf->setHeaderFont(Array(PDF_FONT_NAME_MAIN, '', PDF_FONT_SIZE_MAIN));
$obj_pdf->setFooterFont(Array(PDF_FONT_NAME_DATA, '', PDF_FONT_SIZE_DATA));
$obj_pdf->SetDefaultMonospacedFont('helvetica');
$obj_pdf->SetHeaderMargin(PDF_MARGIN_HEADER);
$obj_pdf->SetFooterMargin(PDF_MARGIN_FOOTER);
$obj_pdf->SetMargins(PDF_MARGIN_LEFT, PDF_MARGIN_TOP, PDF_MARGIN_RIGHT);
$obj_pdf->SetAutoPageBreak(TRUE, PDF_MARGIN_BOTTOM);
$obj_pdf->SetFont('helvetica', '', 9);
$obj_pdf->setFontSubsetting(false);
$obj_pdf->AddPage();
ob_start();
    // we can have any view part here like HTML, PHP etc
    $content = ob_get_contents();
ob_end_clean();
$obj_pdf->writeHTML($content, true, false, true, false, '');
$obj_pdf->Output('output.pdf', 'I');

Thus our HTML page will be converted to PDF using TCPDF in CodeIgniter. We can also embed images,css,modifications in PDF file by using TCPDF library.

Is it possible to run selenium (Firefox) web driver without a GUI?

What you're looking for is a .

Yes, it's possible to run Selenium on Firefox headlessly. Here is a post you can follow.

Here is the summary steps to set up Xvfb

#install Xvfb
sudo apt-get install xvfb

#set display number to :99
Xvfb :99 -ac &
export DISPLAY=:99    

#you are now having an X display by Xvfb

How to make the webpack dev server run on port 80 and on 0.0.0.0 to make it publicly accessible?

In package.json change the "start" value as follows

Note: Run $sudo npm start, You need to use sudo to run react scripts on port 80

enter image description here

Call one constructor from another

Here is an example that calls another constructor, then checks on the property it has set.

    public SomeClass(int i)
    {
        I = i;
    }

    public SomeClass(SomeOtherClass soc)
        : this(soc.J)
    {
        if (I==0)
        {
            I = DoSomethingHere();
        }
    }

Direct method from SQL command text to DataSet

public DataSet GetDataSet(string ConnectionString, string SQL)
{
    SqlConnection conn = new SqlConnection(ConnectionString);
    SqlDataAdapter da = new SqlDataAdapter();
    SqlCommand cmd = conn.CreateCommand();
    cmd.CommandText = SQL;
    da.SelectCommand = cmd;
    DataSet ds = new DataSet();

    ///conn.Open();
    da.Fill(ds);
    ///conn.Close();

    return ds;
}

Shortcut to Apply a Formula to an Entire Column in Excel

Select a range of cells (the entire column in this case), type in your formula, and hold down Ctrl while you press Enter. This places the formula in all selected cells.

How do I launch a Git Bash window with particular working directory using a script?

Let yet add up to the answer from @Drew Noakes:

Target:

"C:\Program Files\Git\git-bash.exe" --cd=C:\GitRepo

The cd param should be one of the options how to specify the working directory.

Also notice, that I have not any --login param there: Instead, I use another extra app, dedicated just for SSH keys: Pageant (PuTTY authentication agent).

Start in:

C:\GitRepo

The same possible way, as @Drew Noakes mentioned/shown here sooner, I use it too.

Shortcut key:

Ctrl + Alt + B

Such shortcuts are another less known feature in Windows. But there is a restriction: To let the shortcut take effect, it must be placed somewhere on the User's subdirectory: The Desktop is fine.

If you do not want it visible, yet still activatable, place this .lnk file i.e. to the quick launch folder, as that dir is purposed for such shortcuts. (no matter whether displayed on the desktop) #76080 #3619355

"\Application Data\Microsoft\Internet Explorer\Quick Launch\"

How does a Java HashMap handle different objects with the same hash code?

Each Entry object represents key-value pair. Field next refers to other Entry object if a bucket has more than 1 Entry.

Sometimes it might happen that hashCodes for 2 different objects are the same. In this case 2 objects will be saved in one bucket and will be presented as LinkedList. The entry point is more recently added object. This object refers to other object with next field and so one. Last entry refers to null. When you create HashMap with default constructor

Array is gets created with size 16 and default 0.75 load balance.

enter image description here

(Source)

JS. How to replace html element with another element/text, represented in string?

Because you are talking about your replacement being anything, and also replacing in the middle of an element's children, it becomes more tricky than just inserting a singular element, or directly removing and appending:

function replaceTargetWith( targetID, html ){
  /// find our target
  var i, tmp, elm, last, target = document.getElementById(targetID);
  /// create a temporary div or tr (to support tds)
  tmp = document.createElement(html.indexOf('<td')!=-1?'tr':'div'));
  /// fill that div with our html, this generates our children
  tmp.innerHTML = html;
  /// step through the temporary div's children and insertBefore our target
  i = tmp.childNodes.length;
  /// the insertBefore method was more complicated than I first thought so I 
  /// have improved it. Have to be careful when dealing with child lists as  
  /// they are counted as live lists and so will update as and when you make
  /// changes. This is why it is best to work backwards when moving children 
  /// around, and why I'm assigning the elements I'm working with to `elm` 
  /// and `last`
  last = target;
  while(i--){
    target.parentNode.insertBefore((elm = tmp.childNodes[i]), last);
    last = elm;
  }
  /// remove the target.
  target.parentNode.removeChild(target);
}

example usage:

replaceTargetWith( 'idTABLE', 'I <b>can</b> be <div>anything</div>' );

demo:

By using the .innerHTML of our temporary div this will generate the TextNodes and Elements we need to insert without any hard work. But rather than insert the temporary div itself -- this would give us mark up that we don't want -- we can just scan and insert it's children.

...either that or look to using jQuery and it's replaceWith method.

jQuery('#idTABLE').replaceWith('<blink>Why this tag??</blink>');


update 2012/11/15

As a response to EL 2002's comment above:

It not always possible. For example, when createElement('div') and set its innerHTML as <td>123</td>, this div becomes <div>123</div> (js throws away inappropriate td tag)

The above problem obviously negates my solution as well - I have updated my code above accordingly (at least for the td issue). However for certain HTML this will occur no matter what you do. All user agents interpret HTML via their own parsing rules, but nearly all of them will attempt to auto-correct bad HTML. The only way to achieve exactly what you are talking about (in some of your examples) is to take the HTML out of the DOM entirely, and manipulate it as a string. This will be the only way to achieve a markup string with the following (jQuery will not get around this issue either):

<table><tr>123 text<td>END</td></tr></table>

If you then take this string an inject it into the DOM, depending on the browser you will get the following:

123 text<table><tr><td>END</td></tr></table>

<table><tr><td>END</td></tr></table>

The only question that remains is why you would want to achieve broken HTML in the first place? :)

How to add `style=display:"block"` to an element using jQuery?

Depending on the purpose of setting the display property, you might want to take a look at

$("#yourElementID").show()

and

$("#yourElementID").hide()

Capturing URL parameters in request.GET

These queries are currently done in two ways. If you want to access the query parameters (GET) you can query the following:

http://myserver:port/resource/?status=1
request.query_params.get('status', None) => 1

If you want to access the parameters passed by POST, you need to access this way:

request.data.get('role', None)

Accessing the dictionary (QueryDict) with 'get()', you can set a default value. In the cases above, if 'status' or 'role' are not informed, the values ??are None.

How to set the env variable for PHP?

You need to add the PHP directory to your path. On the command line (e.g. in a batch file), it would look like this:

SET PATH=%PATH%;C:\your\wamp\path\php

if in doubt, it's the directory containing the php.exe.

You can also pre-set the path in Windows' control panel. See here on how to do this in Windows 7 for example.

Be aware that if you call the PHP executable from an arbitrary directory, that directory will be the working directory. You may need to adjust your scripts so they use the proper directories for their file operations (if there are any).

Change the project theme in Android Studio?

Note : This answer is now out-of-date. This changes the theme in "preview" only as @imjohnking and @john-ktejik pointed out. As @Shahzeb mentioned, theme can modified in res>values>styles

Android Studio 0.8.2 provides a slightly easier way to change the theme. In the preview window, you can select the theme of "Holo.Light.DarkActionBar" by clicking on the theme combo box just above the phone.enter image description here

Or do a ctrl + click on the @style/AppTheme in the Android manifest file. It will open styles.xml file where you can change the parent attribute of the style tag.

  • Theme.Holo for a "dark" theme.
  • Theme.Holo.Light for a "light" theme.

When using the Support Library, you must instead use the Theme.AppCompat themes:

  • Theme.AppCompat for the "dark" theme.
  • Theme.AppCompat.Light for the "light" theme.
  • Theme.AppCompat.Light.DarkActionBar for the light theme with a dark action bar.

Source http://forums.udacity.com/questions/100200635/choosing-theme-in-android-studio-08x

input type=file show only button

So here's the best way to do this FOR ALL BROWSERS:

Forget CSS!

<p>Append Image:</p> 
<input type="button" id="clickImage" value="Add Image" />
<input type="file" name="images[]" id="images" multiple />

<script type="text/javascript" src="https://ajax.googleapis.com/ajax/libs/jquery/1.6.1/jquery.min.js" charset="utf-8"></script>

<script>
$('#images').hide();        
$('#clickImage').click( function() {    
    $('#images').trigger('click');  
});
</script>

What is the maximum float in Python?

If you are using numpy, you can use dtype 'float128' and get a max float of 10e+4931

>>> np.finfo(np.float128)
finfo(resolution=1e-18, min=-1.18973149536e+4932, max=1.18973149536e+4932, dtype=float128)

Access localhost from the internet

There are couple of good free service that let you do the same. Ideal for showing something quickly for testing:

Edits:

  • add ngrok service
  • add localhost.run service

c# search string in txt file

With LINQ, you could use the SkipWhile / TakeWhile methods, like this:

var importantLines = 
    File.ReadLines(pathToTextFile)
    .SkipWhile(line => !line.Contains("CustomerEN"))
    .TakeWhile(line => !line.Contains("CustomerCh"));

Configuration with name 'default' not found. Android Studio

For one, it doesn't do good to have more than one settings.gradle file -- it only looks at the top-level one.

When you get this "Configuration with name 'default' not found" error, it's really confusing, but what it means is that Gradle is looking for a module (or a build.gradle) file someplace, and it's not finding it. In your case, you have this in your settings.gradle file:

include ':libraries:Android-Bootstrap',':Android-Bootstrap'

which is making Gradle look for a library at FTPBackup/libraries/Android-Bootstrap. If you're on a case-sensitive filesystem (and you haven't mistyped Libraries in your question when you meant libraries), it may not find FTPBackup/Libraries/Android-Bootstrap because of the case difference. It's also looking for another library at FTPBackup/Android-Bootstrap, and it's definitely not going to find one because that directory isn't there.

This should work:

include ':Libraries:Android-Bootstrap'

You need the same case-sensitive spec in your dependencies block:

compile project (':Libraries:Android-Bootstrap')

How do you disable the unused variable warnings coming out of gcc in 3rd party code I do not wish to edit?

Sometimes you just need to suppress only some warnings and you want to keep other warnings, just to be safe. In your code, you can suppress the warnings for variables and even formal parameters by using GCC's unused attribute. Lets say you have this code snippet:

void func(unsigned number, const int version)
{
  unsigned tmp;
  std::cout << number << std::endl;
}

There might be a situation, when you need to use this function as a handler - which (imho) is quite common in C++ Boost library. Then you need the second formal parameter version, so the function's signature is the same as the template the handler requires, otherwise the compilation would fail. But you don't really need it in the function itself either...

The solution how to mark variable or the formal parameter to be excluded from warnings is this:

void func(unsigned number, const int version __attribute__((unused)))
{
  unsigned tmp __attribute__((unused));
  std::cout << number << std::endl;
}

GCC has many other parameters, you can check them in the man pages. This also works for the C programs, not only C++, and I think it can be used in almost every function, not just handlers. Go ahead and try it! ;)

P.S.: Lately I used this to suppress warnings of Boosts' serialization in template like this:

template <typename Archive>
void serialize(Archive &ar, const unsigned int version __attribute__((unused)))

EDIT: Apparently, I didn't answer your question as you needed, drak0sha done it better. It's because I mainly followed the title of the question, my bad. Hopefully, this might help other people, who get here because of that title... :)

How to find tags with only certain attributes - BeautifulSoup

if you want to only search with attribute name with any value

from bs4 import BeautifulSoup
import re

soup= BeautifulSoup(html.text,'lxml')
results = soup.findAll("td", {"valign" : re.compile(r".*")})

as per Steve Lorimer better to pass True instead of regex

results = soup.findAll("td", {"valign" : True})

Artisan, creating tables in database

in laravel 5 first we need to create migration and then run the migration

Step 1.

php artisan make:migration create_users_table --create=users

Step 2.

php artisan migrate

keytool error bash: keytool: command not found

In Windows 10, you need to add a double slash

./keytool -genkey -v -keystore c:\\Users\\USERNAME\\youralias.jks -storetype JKS -keyalg RSA -keysize 2048 -validity 10000 -alias youralias

Dialog throwing "Unable to add window — token null is not for an application” with getApplication() as context

Here is how I resolved same error for my application:
Adding the following line after creating the dialog:

dialog.getWindow().setType(WindowManager.LayoutParams.TYPE_SYSTEM_DIALOG);  

You will not need to acquire a context. This is particularly useful if you are popping up another dialog over current popped up dialog. Or when it's not convenient to get a context.

Hope this can help you with your app development.

David

How can I create a table with borders in Android?

The stroke doubles up on the middel sections, I used this layer list drawable:

<layer-list xmlns:android="http://schemas.android.com/apk/res/android" >

 <item android:top="0dp" android:left="0dp" android:bottom="0dp" android:right="0dp">

     <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
       <solid android:color="@color/grey" />
    </shape>
</item>

<item android:top="1dp" android:left="1dp" android:bottom="1dp" android:right="1dp">

    <shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle">
      <solid android:color="@color/lightgrey" />
    </shape>
 </item>
</layer-list>

Creating files and directories via Python

import os

path = chap_name

if not os.path.exists(path):
    os.makedirs(path)

filename = img_alt + '.jpg'
with open(os.path.join(path, filename), 'wb') as temp_file:
    temp_file.write(buff)

Key point is to use os.makedirs in place of os.mkdir. It is recursive, i.e. it generates all intermediate directories. See http://docs.python.org/library/os.html

Open the file in binary mode as you are storing binary (jpeg) data.

In response to Edit 2, if img_alt sometimes has '/' in it:

img_alt = os.path.basename(img_alt)

How to do this using jQuery - document.getElementById("selectlist").value

"Equivalent" is the word here

While...

$('#selectlist').val();

...is equivalent to...

document.getElementById("selectlist").value

...it's worth noting that...

$('#selectlist')

...although 'equivalent' is not the same as...

document.getElementById("selectlist")

...as the former returns a jQuery object, not a DOM object.

To get the DOM object(s) from the jQuery one, use the following:

$('#selectlist').get(); //get all DOM objects in the jQuery collection
$('#selectlist').get(0); //get the DOM object in the jQuery collection at index 0
$('#selectlist')[0]; //get the DOM objects in the jQuery collection at index 0

Difference between variable declaration syntaxes in Javascript (including global variables)?

Keeping it simple :

a = 0

The code above gives a global scope variable

var a = 0;

This code will give a variable to be used in the current scope, and under it

window.a = 0;

This generally is same as the global variable.

Get all variables sent with POST?

The variable $_POST is automatically populated.

Try var_dump($_POST); to see the contents.

You can access individual values like this: echo $_POST["name"];

This, of course, assumes your form is using the typical form encoding (i.e. enctype=”multipart/form-data”

If your post data is in another format (e.g. JSON or XML, you can do something like this:

$post = file_get_contents('php://input');

and $post will contain the raw data.

Assuming you're using the standard $_POST variable, you can test if a checkbox is checked like this:

if(isset($_POST['myCheckbox']) && $_POST['myCheckbox'] == 'Yes')
{
     ...
}

If you have an array of checkboxes (e.g.

<form action="myscript.php" method="post">
  <input type="checkbox" name="myCheckbox[]" value="A" />val1<br />
  <input type="checkbox" name="myCheckbox[]" value="B" />val2<br />
  <input type="checkbox" name="myCheckbox[]" value="C" />val3<br />
  <input type="checkbox" name="myCheckbox[]" value="D" />val4<br />
  <input type="checkbox" name="myCheckbox[]" value="E" />val5
  <input type="submit" name="Submit" value="Submit" />
</form>

Using [ ] in the checkbox name indicates that the selected values will be accessed by PHP script as an array. In this case $_POST['myCheckbox'] won't return a single string but will return an array consisting of all the values of the checkboxes that were checked.

For instance, if I checked all the boxes, $_POST['myCheckbox'] would be an array consisting of: {A, B, C, D, E}. Here's an example of how to retrieve the array of values and display them:

  $myboxes = $_POST['myCheckbox'];
  if(empty($myboxes))
  {
    echo("You didn't select any boxes.");
  }
  else
  {
    $i = count($myboxes);
    echo("You selected $i box(es): <br>");
    for($j = 0; $j < $i; $j++)
    {
      echo $myboxes[$j] . "<br>";
    }
  }

Determining if a number is prime

If you are lazy, and have a lot of RAM, create a sieve of Eratosthenes which is practically a giant array from which you kicked all numbers that are not prime. From then on every prime "probability" test will be super quick. The upper limit for this solution for fast results is the amount of you RAM. The upper limit for this solution for superslow results is your hard disk's capacity.

check if jquery has been loaded, then load it if false

Old post but I made an good solution what is tested on serval places.

https://github.com/CreativForm/Load-jQuery-if-it-is-not-already-loaded

CODE:

(function(url, position, callback){
    // default values
    url = url || 'https://ajax.googleapis.com/ajax/libs/jquery/3.3.1/jquery.min.js';
    position = position || 0;

    // Check is jQuery exists
    if (!window.jQuery) {
        // Initialize <head>
        var head = document.getElementsByTagName('head')[0];
        // Create <script> element
        var script = document.createElement("script");
        // Append URL
        script.src = url;
        // Append type
        script.type = 'text/javascript';
        // Append script to <head>
        head.appendChild(script);
        // Move script on proper position
        head.insertBefore(script,head.childNodes[position]);

        script.onload = function(){
            if(typeof callback == 'function') {
                callback(jQuery);
            }
        };
    } else {
        if(typeof callback == 'function') {
            callback(jQuery);
        }
    }
}('https://ajax.googleapis.com/ajax/libs/jquery/1.12.4/jquery.min.js', 5, function($){ 
    console.log($);
}));

At GitHub is better explanation but generaly this function you can add anywhere in your HTML code and you will initialize jquery if is not already loaded.

Column calculated from another column?

If it is a selection, you can do it as:

SELECT id, value, (value/2) AS calculated FROM mytable

Else, you can also first alter the table to add the missing column and then do an UPDATE query to compute the values for the new column as:

UPDATE mytable SET calculated = value/2;

If it must be automatic, and your MySQL version allows it, you can try with triggers

How to create a directory and give permission in single command

Just to expand on and improve some of the above answers:

First, I'll check the mkdir man page for GNU Coreutils 8.26 -- it gives us this information about the option '-m' and '-p' (can also be given as --mode=MODE and --parents, respectively):

...set[s] file mode (as in chmod), not a=rwx - umask

...no error if existing, make parent directories as needed

The statements are vague and unclear in my opinion. But basically, it says that you can make the directory with permissions specified by "chmod numeric notation" (octals) or you can go "the other way" and use a/your umask.

Side note: I say "the other way" since the umask value is actually exactly what it sounds like -- a mask, hiding/removing permissions rather than "granting" them as with chmod's numeric octal notation.

You can execute the shell-builtin command umask to see what your 3-digit umask is; for me, it's 022. This means that when I execute mkdir yodirectory in a given folder (say, mahome) and stat it, I'll get some output resembling this:

               755                   richard:richard         /mahome/yodirectory
 #          permissions                 user:group      what I just made (yodirectory),
 # (owner,group,others--in that order)                 where I made it (i.e. in mahome)
 # 

Now, to add just a tiny bit more about those octal permissions. When you make a directory, "your system" take your default directory perms' [which applies for new directories (its value should 777)] and slaps on yo(u)mask, effectively hiding some of those perms'. My umask is 022--now if we "subtract" 022 from 777 (technically subtracting is an oversimplification and not always correct - we are actually turning off perms or masking them)...we get 755 as stated (or "statted") earlier.

We can omit the '0' in front of the 3-digit octal (so they don't have to be 4 digits) since in our case we didn't want (or rather didn't mention) any sticky bits, setuids or setgids (you might want to look into those, btw, they might be useful since you are going 777). So in other words, 0777 implies (or is equivalent to) 777 (but 777 isn't necessarily equivalent to 0777--since 777 only specifies the permissions, not the setuids, setgids, etc.)

Now, to apply this to your question in a broader sense--you have (already) got a few options. All the answers above work (at least according to my coreutils). But you may (or are pretty likely to) run into problems with the above solutions when you want to create subdirectories (nested directories) with 777 permissions all at once. Specifically, if I do the following in mahome with a umask of 022:

mkdir -m 777 -p yodirectory/yostuff/mastuffinyostuff
# OR (you can swap 777 for 0777 if you so desire, outcome will be the same)
install -d -m 777 -p yodirectory/yostuff/mastuffinyostuff

I will get perms 755 for both yodirectory and yostuff, with only 777 perms for mastuffinyostuff. So it appears that the umask is all that's slapped on yodirectory and yostuff...to get around this we can use a subshell:

( umask 000 && mkdir -p yodirectory/yostuff/mastuffinyostuff )

and that's it. 777 perms for yostuff, mastuffinyostuff, and yodirectory.

How to check if keras tensorflow backend is GPU or CPU version?

Also you can check using Keras backend function:

from keras import backend as K
K.tensorflow_backend._get_available_gpus()

I test this on Keras (2.1.1)

How to use range-based for() loop with std::map?

If you only want to see the keys/values from your map and like using boost, you can use the boost adaptors with the range based loops:

for (const auto& value : myMap | boost::adaptors::map_values)
{
    std::cout << value << std::endl;
}

there is an equivalent boost::adaptors::key_values

http://www.boost.org/doc/libs/1_51_0/libs/range/doc/html/range/reference/adaptors/reference/map_values.html

How do you serve a file for download with AngularJS or Javascript?

Would just like to add that in case it doesn't download the file because of unsafe:blob:null... when you hover over the download button, you have to sanitize it. For instance,

var app = angular.module('app', []);

app.config(function($compileProvider){

$compileProvider.aHrefSanitizationWhitelist(/^\s*(|blob|):/);

php function mail() isn't working

I think you are not configured properly,

if you are using XAMPP then you can easily send mail from localhost.

for example you can configure C:\xampp\php\php.ini and c:\xampp\sendmail\sendmail.ini for gmail to send mail.

in C:\xampp\php\php.ini find extension=php_openssl.dll and remove the semicolon from the beginning of that line to make SSL working for gmail for localhost.

in php.ini file find [mail function] and change

SMTP=smtp.gmail.com
smtp_port=587
sendmail_from = [email protected]
sendmail_path = "C:\xampp\sendmail\sendmail.exe -t"

(use the above send mail path only and it will work)

Now Open C:\xampp\sendmail\sendmail.ini. Replace all the existing code in sendmail.ini with following code

[sendmail]

smtp_server=smtp.gmail.com
smtp_port=587
error_logfile=error.log
debug_logfile=debug.log
[email protected]
auth_password=my-gmail-password
[email protected]

Now you have done!! create php file with mail function and send mail from localhost.

Update

First, make sure you PHP installation has SSL support (look for an "openssl" section in the output from phpinfo()).

You can set the following settings in your PHP.ini:

ini_set("SMTP","ssl://smtp.gmail.com");
ini_set("smtp_port","465");

Rails - controller action name to string

mikej's answer was very precise and helpful, but the the thing i also wanted to know was how to get current method name in rails.

found out it's possible with self.current_method

easily found at http://www.ruby-forum.com/topic/75258

Linux shell script for database backup

As a DBA, You must schedule the backup of MySQL Database in case of any issues so that you can recover your databases from the current backup.

Here, we are using mysqldump to take the backup of mysql databases and the same you can put into the script.

[orahow@oradbdb DB_Backup]$ cat .backup_script.sh

#!/bin/bash
# Database credentials
user="root"
password="1Loginxx"
db_name="orahowdb"
v_cnt=0
logfile_path=/DB_Backup
touch "$logfile_path/orahowdb_backup.log"
# Other options
backup_path="/DB_Backup"
date=$(date +"%d-%b-%Y-%H-%M-%p")
# Set default file permissions

Continue Reading .... MySQL Backup

How to use java.Set

The first thing you need to study is the java.util.Set API.

Here's a small example of how to use its methods:

    Set<Integer> numbers = new TreeSet<Integer>();

    numbers.add(2);
    numbers.add(5);

    System.out.println(numbers); // "[2, 5]"
    System.out.println(numbers.contains(7)); // "false"

    System.out.println(numbers.add(5)); // "false"
    System.out.println(numbers.size()); // "2"

    int sum = 0;
    for (int n : numbers) {
        sum += n;
    }
    System.out.println("Sum = " + sum); // "Sum = 7"

    numbers.addAll(Arrays.asList(1,2,3,4,5));
    System.out.println(numbers); // "[1, 2, 3, 4, 5]"

    numbers.removeAll(Arrays.asList(4,5,6,7));
    System.out.println(numbers); // "[1, 2, 3]"

    numbers.retainAll(Arrays.asList(2,3,4,5));
    System.out.println(numbers); // "[2, 3]"

Once you're familiar with the API, you can use it to contain more interesting objects. If you haven't familiarized yourself with the equals and hashCode contract, already, now is a good time to start.

In a nutshell:

  • @Override both or none; never just one. (very important, because it must satisfied property: a.equals(b) == true --> a.hashCode() == b.hashCode()
    • Be careful with writing boolean equals(Thing other) instead; this is not a proper @Override.
  • For non-null references x, y, z, equals must be:
    • reflexive: x.equals(x).
    • symmetric: x.equals(y) if and only if y.equals(x)
    • transitive: if x.equals(y) && y.equals(z), then x.equals(z)
    • consistent: x.equals(y) must not change unless the objects have mutated
    • x.equals(null) == false
  • The general contract for hashCode is:
    • consistent: return the same number unless mutation happened
    • consistent with equals: if x.equals(y), then x.hashCode() == y.hashCode()
      • strictly speaking, object inequality does not require hash code inequality
      • but hash code inequality necessarily requires object inequality
  • What counts as mutation should be consistent between equals and hashCode.

Next, you may want to impose an ordering of your objects. You can do this by making your type implements Comparable, or by providing a separate Comparator.

Having either makes it easy to sort your objects (Arrays.sort, Collections.sort(List)). It also allows you to use SortedSet, such as TreeSet.


Further readings on stackoverflow:

How to split a delimited string in Ruby and convert it to an array?

For String Integer without space as String

arr = "12345"

arr.split('')

output: ["1","2","3","4","5"]

For String Integer with space as String

arr = "1 2 3 4 5"

arr.split(' ')

output: ["1","2","3","4","5"]

For String Integer without space as Integer

arr = "12345"

arr.split('').map(&:to_i)

output: [1,2,3,4,5]

For String

arr = "abc"

arr.split('')

output: ["a","b","c"]

Explanation:

  1. arr -> string which you're going to perform any action.
  2. split() -> is an method, which split the input and store it as array.
  3. '' or ' ' or ',' -> is an value, which is needed to be removed from given string.

Module AppRegistry is not registered callable module (calling runApplication)

One of the libraries has not been linked. To check, just comment out in the package.json one by one the latest libraries added.

yarn remove libraryName.

Then run the app with xcode and puf !

What is the best way to call a script from another script?

I prefer runpy:

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

import runpy

runpy.run_path(path_name='script-01.py')
runpy.run_path(path_name='script-02.py')
runpy.run_path(path_name='script-03.py')

ParseError: not well-formed (invalid token) using cElementTree

See this answer to another question and the according part of the XML spec.

The backspace U+0008 is an invalid character in XML documents. It must be represented as escaped entity &#8; and cannot occur plainly.

If you need to process this XML snippet, you must replace \x08 in s before feeding it into an XML parser.

Vertically align text within a div

Try this:

HTML

<div><span>Text</span></div>

CSS

div {
    height: 100px;
}

span {
    height: 100px;
    display: table-cell;
    vertical-align: middle;
}

Is bool a native C type?

No, there is no bool in ISO C90.

Here's a list of keywords in standard C (not C99):

  • auto
  • break
  • case
  • char
  • const
  • continue
  • default
  • do
  • double
  • else
  • enum
  • extern
  • float
  • for
  • goto
  • if
  • int
  • long
  • register
  • return
  • short
  • signed
  • static
  • struct
  • switch
  • typedef
  • union
  • unsigned
  • void
  • volatile
  • while

Here's an article discussing some other differences with C as used in the kernel and the standard: http://www.ibm.com/developerworks/linux/library/l-gcc-hacks/index.html

How to get response body using HttpURLConnection, when code other than 2xx is returned?

Wrong method was used for errors, here is the working code:

BufferedReader br = null;
if (100 <= conn.getResponseCode() && conn.getResponseCode() <= 399) {
    br = new BufferedReader(new InputStreamReader(conn.getInputStream()));
} else {
    br = new BufferedReader(new InputStreamReader(conn.getErrorStream()));
}

Find Active Tab using jQuery and Twitter Bootstrap

Here is the answer for those of you who need a Boostrap 3 solution.

In bootstrap 3 use 'shown.bs.tab' instead of 'shown' in the next line

// tab
$('#rowTab a:first').tab('show');

$('a[data-toggle="tab"]').on('shown.bs.tab', function (e) {
//show selected tab / active
 console.log ( $(e.target).attr('id') );
});

How do I read a text file of about 2 GB?

Instead of loading / reading the complete file, you could use a tool to split the text file in smaller chunks. If you're using Linux, you could just use the split command (see this stackoverflow thread). For Windows, there are several tools available like HJSplit (see this superuser thread).

how to create a cookie and add to http response from inside my service layer?

To add a new cookie, use HttpServletResponse.addCookie(Cookie). The Cookie is pretty much a key value pair taking a name and value as strings on construction.

List of standard lengths for database fields

I wanted to find the same and the UK Government Data Standards mentioned in the accepted answer sounded ideal. However none of these seemed to exist any more - after an extended search I found it in an archive here: http://webarchive.nationalarchives.gov.uk/+/http://www.cabinetoffice.gov.uk/govtalk/schemasstandards/e-gif/datastandards.aspx. Need to download the zip, extract it and then open default.htm in the html folder.

What exactly is Apache Camel?

Assume you create an ecommerce company like Amazon, and you want to only focus on strategy/choice of products to sell. unlike amazon delivery fleet, instead of yourself handling moving of goods from sellers to warehouse, making changes to it in warehouse like packaging and sending it out to other city and customers. You hire a company that does all this and just give them info of all your warehouse locations, vehicle types, delivery locations and a list of when to do what. Then they handle that by themselves, that would be Apache Camel. They take care of moving things from one end to other, once you handover stuff to them, so that you are free to focus on other things.

Jquery find nearest matching element

Get the .column parent of the this element, get its previous sibling, then find any input there:

$(this).closest(".column").prev().find("input:first").val();

Demo: http://jsfiddle.net/aWhtP/

How to check SQL Server version

Simply use

SELECT @@VERSION

Sample output

Microsoft SQL Server 2012 - 11.0.2100.60 (X64) 
Feb 10 2012 19:39:15 
Copyright (c) Microsoft Corporation
Express Edition (64-bit) on Windows NT 6.2 <X64> (Build 9200: )

Source: How to check sql server version? (Various ways explained)

How to get the GL library/headers?

In Visual Studio :

//OpenGL
#pragma comment(lib, "opengl32")
#pragma comment(lib, "glu32")
#include <gl/gl.h>
#include <gl/glu.h>

Headers are in the SDK : C:\Program Files\Microsoft SDKs\Windows\v7.0A\Include\gl

Powershell Get-ChildItem most recent file in directory

Yes I think this would be quicker.

Get-ChildItem $folder | Sort-Object -Descending -Property LastWriteTime -Top 1 

Change Color of Fonts in DIV (CSS)

Your first CSS selector—social.h2—is looking for the "social" element in the "h2", class, e.g.:

<social class="h2">

Class selectors are proceeded with a dot (.). Also, use a space () to indicate that one element is inside of another. To find an <h2> descendant of an element in the social class, try something like:

.social h2 {
  color: pink;
  font-size: 14px;
}

To get a better understanding of CSS selectors and how they are used to reference your HTML, I suggest going through the interactive HTML and CSS tutorials from CodeAcademy. I hope that this helps point you in the right direction.

git status shows modifications, git checkout -- <file> doesn't remove them

Another solution that may work for people, since none of the text options worked for me:

  1. Replace the content of .gitattributes with a single line: * binary. This tells git to treat every file as a binary file that it can't do anything with.
  2. Check that message for the offending files is gone; if it's not you can git checkout -- <files> to restore them to the repository version
  3. git checkout -- .gitattributes to restore the .gitattributes file to its initial state
  4. Check that the files are still not marked as changed.

Simple two column html layout without using tables

a few small changes to make it responsive

<style type="text/css">
#wrap {
    width: 100%;
    margin: 0 auto;
    display: table;
}
#left_col {
   float:left;
   width:50%;
}
#right_col {
   float:right;
   width:50%;
}
@media only screen and (max-width: 480px){
    #left_col {
       width:100%;
    }
    #right_col {
       width:100%;
    }
}
</style>

<div id="wrap">
    <div id="left_col">
        ...
    </div>
    <div id="right_col">
        ...
    </div>
</div>

How do you explicitly set a new property on `window` in TypeScript?

The accepted answer is what I used to use, but with TypeScript 0.9.* it no longer works. The new definition of the Window interface seems to completely replace the built-in definition, instead of augmenting it.

I have taken to doing this instead:

interface MyWindow extends Window {
    myFunction(): void;
}

declare var window: MyWindow;

UPDATE: With TypeScript 0.9.5 the accepted answer is working again.

Sort Pandas Dataframe by Date

sort method has been deprecated and replaced with sort_values. After converting to datetime object using df['Date']=pd.to_datetime(df['Date'])

df.sort_values(by=['Date'])

Note: to sort in-place and/or in a descending order (the most recent first):

df.sort_values(by=['Date'], inplace=True, ascending=False)

Using ls to list directories and their total sizes

If you want more control over the size that you want to list the directories over, you can use the threshold (-t) switch as in:

$ du -ht 1000000000 | sort --reverse

du - disk usage
h - human readable format
t - threshold size

Here, we want to list all directories which are greater than 1GB in size.

$ du -ht 1G | sort --reverse

Explanation:

Units that are described in wiki follows:

K, M, G, T, P, E, Z, Y (powers of 1024) or
KB, MB, GB, TB, PB, EB, ZB, YB (powers of 1000).

python: changing row index of pandas data frame

you can do

followers_df.index = range(20)

Static variables in C++

A static variable declared in a header file outside of the class would be file-scoped in every .c file which includes the header. That means separate copy of a variable with same name is accessible in each of the .c files where you include the header file.

A static class variable on the other hand is class-scoped and the same static variable is available to every compilation unit that includes the header containing the class with static variable.

Using Font Awesome icon for bullet points, with a single list item element

The new fontawesome (version 4.0.3) makes this really easy to do. We simply use the following classes:

<ul class="fa-ul">
  <li><i class="fa-li fa fa-check-square"></i>List icons (like these)</li>
  <li><i class="fa-li fa fa-check-square"></i>can be used</li>
  <li><i class="fa-li fa fa-spinner fa-spin"></i>to replace</li>
  <li><i class="fa-li fa fa-square"></i>default bullets in lists</li>
</ul>

As per this (new) url: http://fontawesome.io/examples/#list

ImportError: No module named Crypto.Cipher

Worked for me (Ubuntu 17.10)

Removing venv and creating it again with python v3.6

pip3 install PyJWT
sudo apt-get install build-essential libgmp3-dev python3-dev
pip3 install cryptography
pip3 install pycryptodome
pip3 install pycryptodomex

Pycrypto is deprecated, had problems with it, used Pycryptodome

INSTALL_FAILED_DUPLICATE_PERMISSION... C2D_MESSAGE

See this link it said that it will work when they are signed by the same key. The release key and the debug key are not the same.

So do it:

buildTypes {
        release {
            minifyEnabled true
            signingConfig signingConfigs.release//signing by the same key
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-android.txt'

        }
        debug {
            applicationIdSuffix ".debug"
            debuggable true
            signingConfig signingConfigs.release//signing by the same key
        }

    }

 signingConfigs {
        release {
            storeFile file("***\\key_.jks")
            storePassword "key_***"
            keyAlias "key_***"
            keyPassword "key_"***"
        }


}

jQuery - Add active class and remove active from other element on click

Try this

$(document).ready(function() {
$(".tab").click(function () {
    $(".tab").removeClass("active");
    // $(".tab").addClass("active"); // instead of this do the below 
    $(this).addClass("active");   
});
});

when you are using $(".tab").addClass("active");, it targets all the elements with class name .tab. Instead when you use this it looks for the element which has an event, in your case the element which is clicked.

Hope this helps you.

Delete file from internal storage

This is an old topic, but I will add my experience, maybe someone finds this helpful

>     2019-11-12 20:05:50.178 27764-27764/com.strba.myapplicationx I/File: /storage/emulated/0/Android/data/com.strba.myapplicationx/files/Readings/JPEG_20191112_200550_4444350520538787768.jpg//file when it was created

2019-11-12 20:05:58.801 27764-27764/com.strba.myapplicationx I/File: content://com.strba.myapplicationx.fileprovider/my_images/JPEG_20191112_200550_4444350520538787768.jpg //same file when trying to delete it

solution1:

              Uri uriDelete=Uri.parse (adapter.getNoteAt (viewHolder.getAdapterPosition ()).getImageuri ());//getter getImageuri on my object from adapter that returns String with content uri

here I initialize Content resolver and delete it with a passed parameter of that URI

            ContentResolver contentResolver = getContentResolver ();
            contentResolver.delete (uriDelete,null ,null );

solution2(my first solution-from head in this time I do know that ): content resolver exists...

              String path = "/storage/emulated/0/Android/data/com.strba.myapplicationx/files/Readings/" +
                    adapter.getNoteAt (viewHolder.getAdapterPosition ()).getImageuri ().substring (58);

            File file = new File (path);
            if (file != null) {
                file.delete ();
            }

Hope that this will be helpful to someone happy coding

How do I grep recursively?

To find name of files with path recursively containing the particular string use below command for UNIX:

find . | xargs grep "searched-string"

for Linux:

grep -r "searched-string" .

find a file on UNIX server

find . -type f -name file_name

find a file on LINUX server

find . -name file_name

How to load all the images from one of my folder into my web page, using Jquery/Javascript

Using Chrome, searching for the images files in links (as proposed previously) didn't work as it is generating something like:

(...) i18nTemplate.process(document, loadTimeData);
</script>
<script>start("current directory...")</script>
<script>addRow("..","..",1,"170 B","10/2/15, 8:32:45 PM");</script>
<script>addRow("fotos-interessantes-11.jpg","fotos-interessantes-> 11.jpg",false,"","");</script>

Maybe the most reliable way is to do something like this:

_x000D_
_x000D_
var folder = "img/";_x000D_
_x000D_
$.ajax({_x000D_
    url : folder,_x000D_
    success: function (data) {_x000D_
        var patt1 = /"([^"]*\.(jpe?g|png|gif))"/gi;     // extract "*.jpeg" or "*.jpg" or "*.png" or "*.gif"_x000D_
        var result = data.match(patt1);_x000D_
        result = result.map(function(el) { return el.replace(/"/g, ""); });     // remove double quotes (") surrounding filename+extension // TODO: do this at regex!_x000D_
_x000D_
        var uniqueNames = [];                               // this array will help to remove duplicate images_x000D_
        $.each(result, function(i, el){_x000D_
            var el_url_encoded = encodeURIComponent(el);    // avoid images with same name but converted to URL encoded_x000D_
            console.log("under analysis: " + el);_x000D_
            if($.inArray(el, uniqueNames) === -1  &&  $.inArray(el_url_encoded, uniqueNames) === -1){_x000D_
                console.log("adding " + el_url_encoded);_x000D_
                uniqueNames.push(el_url_encoded);_x000D_
                $("#slider").append( "<img src='" + el_url_encoded +"' alt=''>" );      // finaly add to HTML_x000D_
            } else{   console.log(el_url_encoded + " already in!"); }_x000D_
        });_x000D_
    },_x000D_
    error: function(xhr, textStatus, err) {_x000D_
       alert('Error: here we go...');_x000D_
       alert(textStatus);_x000D_
       alert(err);_x000D_
       alert("readyState: "+xhr.readyState+"\n xhrStatus: "+xhr.status);_x000D_
       alert("responseText: "+xhr.responseText);_x000D_
   }_x000D_
});
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
_x000D_
_x000D_
_x000D_

Change Select List Option background colour on hover

Select / Option elements are rendered by the OS, not HTML. You cannot change the style for these elements.

How to set page content to the middle of screen?

Solution for the code you posted:

.center{
    position:absolute;
    width:780px;
    height:650px;
    left:50%;
    top:50%;
    margin-left:-390px;
    margin-top:-325px;
}

<table class="center" width="780" border="0" align="center" cellspacing="2" bordercolor="#000000" bgcolor="#FFCC66">
      <tr>
        <td>
        <table width="100%" border="0">
      <tr>
        <td>
        <table width="100%" border="0">
        <tr>
            <td width="150"><img src="images/banners/BAX Company.jpg" width="149" height="130" /></td>
            <td width="150"><img src="images/banners/BAX Location.jpg" width="149" height="130" /></td>
            <td width="300"><img src="images/banners/Closet.jpg" width="300" height="130" /></td>
            <td width="150"><img src="images/banners/BAX Company.jpg" width="149" height="130" /></td>
            <td width="150"><img src="images/banners/BAX Location.jpg" width="149" height="130" /></td>        
        </tr>
        </table>
        </td>
      </tr>
      <tr>
        <td>
        <table width="100%" border="0">
        <tr>
            <td width="150"><img src="images/banners/BAX Company.jpg" width="149" height="130" /></td>
            <td width="150"><img src="images/banners/BAX Location.jpg" width="149" height="130" /></td>
            <td width="300"><img src="images/banners/Closet.jpg" width="300" height="130" /></td>
            <td width="150"><img src="images/banners/BAX Company.jpg" width="149" height="130" /></td>
            <td width="150"><img src="images/banners/BAX Location.jpg" width="149" height="130" /></td>        
        </tr>
        </table>
        </td>
      </tr>
</table>

--

How this works?

Example: http://jsfiddle.net/953Yj/

<div class="center">
    Lorem ipsum
</div>

.center{
    position:absolute;
    height: X px;
    width: Y px;
    left:50%;
    top:50%;
    margin-top:- X/2 px;
    margin-left:- Y/2 px;
}
  • X would your your height.
  • Y would be your width.

To position the div vertically and horizontally, divide X and Y by 2.

How to set default vim colorscheme

Copy downloaded color schemes to ~/.vim/colors/Your_Color_Scheme.

Then write

colo Your_Color_Scheme

or

colorscheme Your_Color_Scheme

into your ~/.vimrc.

See this link for holokai

How do you create an asynchronous method in C#?

If you didn't want to use async/await inside your method, but still "decorate" it so as to be able to use the await keyword from outside, TaskCompletionSource.cs:

public static Task<T> RunAsync<T>(Func<T> function)
{ 
    if (function == null) throw new ArgumentNullException(“function”); 
    var tcs = new TaskCompletionSource<T>(); 
    ThreadPool.QueueUserWorkItem(_ =>          
    { 
        try 
        {  
           T result = function(); 
           tcs.SetResult(result);  
        } 
        catch(Exception exc) { tcs.SetException(exc); } 
   }); 
   return tcs.Task; 
}

From here and here

To support such a paradigm with Tasks, we need a way to retain the Task façade and the ability to refer to an arbitrary asynchronous operation as a Task, but to control the lifetime of that Task according to the rules of the underlying infrastructure that’s providing the asynchrony, and to do so in a manner that doesn’t cost significantly. This is the purpose of TaskCompletionSource.

I saw it's also used in the .NET source, e.g. WebClient.cs:

    [HostProtection(ExternalThreading = true)]
    [ComVisible(false)]
    public Task<string> UploadStringTaskAsync(Uri address, string method, string data)
    {
        // Create the task to be returned
        var tcs = new TaskCompletionSource<string>(address);

        // Setup the callback event handler
        UploadStringCompletedEventHandler handler = null;
        handler = (sender, e) => HandleCompletion(tcs, e, (args) => args.Result, handler, (webClient, completion) => webClient.UploadStringCompleted -= completion);
        this.UploadStringCompleted += handler;

        // Start the async operation.
        try { this.UploadStringAsync(address, method, data, tcs); }
        catch
        {
            this.UploadStringCompleted -= handler;
            throw;
        }

        // Return the task that represents the async operation
        return tcs.Task;
    }

Finally, I also found the following useful:

I get asked this question all the time. The implication is that there must be some thread somewhere that’s blocking on the I/O call to the external resource. So, asynchronous code frees up the request thread, but only at the expense of another thread elsewhere in the system, right? No, not at all.

To understand why asynchronous requests scale, I’ll trace a (simplified) example of an asynchronous I/O call. Let’s say a request needs to write to a file. The request thread calls the asynchronous write method. WriteAsync is implemented by the Base Class Library (BCL), and uses completion ports for its asynchronous I/O. So, the WriteAsync call is passed down to the OS as an asynchronous file write. The OS then communicates with the driver stack, passing along the data to write in an I/O request packet (IRP).

This is where things get interesting: If a device driver can’t handle an IRP immediately, it must handle it asynchronously. So, the driver tells the disk to start writing and returns a “pending” response to the OS. The OS passes that “pending” response to the BCL, and the BCL returns an incomplete task to the request-handling code. The request-handling code awaits the task, which returns an incomplete task from that method and so on. Finally, the request-handling code ends up returning an incomplete task to ASP.NET, and the request thread is freed to return to the thread pool.

Introduction to Async/Await on ASP.NET

If the target is to improve scalability (rather than responsiveness), it all relies on the existence of an external I/O that provides the opportunity to do that.

How to debug Google Apps Script (aka where does Logger.log log to?)

I am having the same problem, I found the below on the web somewhere....

Event handlers in Docs are a little tricky though. Because docs can handle multiple simultaneous edits by multiple users, the event handlers are handled server-side. The major issue with this structure is that when an event trigger script fails, it fails on the server. If you want to see the debug info you'll need to setup an explicit trigger under the triggers menu that emails you the debug info when the event fails or else it will fail silently.

How do you rename a MongoDB database?

The above process is slow,you can use below method but you need to move collection by collection to another db.

use admin
db.runCommand({renameCollection: "[db_old_name].[collection_name]", to: "[db_new_name].[collection_name]"})

OnChange event handler for radio button (INPUT type="radio") doesn't work as one value

For some reason, the best answer does not works for me.

I improved best answer by use

    var overlayType_radio = document.querySelectorAll('input[type=radio][name="radio_overlaytype"]');

Original best answer use:

      var rad = document.myForm.myRadios;

The others keep the same, finally it works for me.

var overlayType_radio = document.querySelectorAll('input[type=radio][name="radio_overlaytype"]');
                              console.log('overlayType_radio', overlayType_radio)

                              var prev = null;
                              for (var i = 0; i < overlayType_radio.length; i++) {
                                  overlayType_radio[i].addEventListener('change', function() {
                                      (prev) ? console.log('radio prev value',prev.value): null;
                                      if (this !== prev) {
                                          prev = this;
                                      }
                                      console.log('radio now value ', this.value)
                                  });
                              }

html is:

<div id='overlay-div'>
                        <fieldset>
                                <legend> Overlay Type </legend>
                                
                                <p>
                                    <label>
                                      <input class='with-gap' id='overlayType_image' value='overlayType_image' name='radio_overlaytype' type='radio' checked/>
                                      <span>Image</span> 
                                    </label>
                                </p>

                                <p>
                                  <label>
                                    <input class='with-gap' id='overlayType_tiled_image' value='overlayType_tiled_image' name='radio_overlaytype' type='radio' disabled/>
                                    <span> Tiled Image</span>   
                                </p>

                                <p>
                                  <label>
                                    <input class='with-gap' id='overlayType_coordinated_tile' value='overlayType_coordinated_tile' name='radio_overlaytype' type='radio'  disabled/>
                                    <span> Coordinated Tile</span>  
                                </p>

                                <p>
                                  <label>
                                    <input class='with-gap' id='overlayType_none' value='overlayType_none' name='radio_overlaytype' type='radio'/>
                                    <span> None </span>            
                                  </p>

                                  
                          </fieldset>
                       </div>

_x000D_
_x000D_
 var overlayType_radio = document.querySelectorAll('input[type=radio][name="radio_overlaytype"]');
                                  console.log('overlayType_radio', overlayType_radio)

                                  var prev = null;
                                  for (var i = 0; i < overlayType_radio.length; i++) {
                                      overlayType_radio[i].addEventListener('change', function() {
                                          (prev) ? console.log('radio prev value',prev.value): null;
                                          if (this !== prev) {
                                              prev = this;
                                          }
                                          console.log('radio now value ', this.value)
                                      });
                                  }
_x000D_
<div id='overlay-div'>
                            <fieldset>
                                    <legend> Overlay Type </legend>
                                    
                                    <p>
                                        <label>
                                          <input class='with-gap' id='overlayType_image' value='overlayType_image' name='radio_overlaytype' type='radio' checked/>
                                          <span>Image</span> 
                                        </label>
                                    </p>

                                    <p>
                                      <label>
                                        <input class='with-gap' id='overlayType_tiled_image' value='overlayType_tiled_image' name='radio_overlaytype' type='radio' />
                                        <span> Tiled Image</span>   
                                    </p>

                                    <p>
                                      <label>
                                        <input class='with-gap' id='overlayType_coordinated_tile' value='overlayType_coordinated_tile' name='radio_overlaytype' type='radio'  />
                                        <span> Coordinated Tile</span>  
                                    </p>

                                    <p>
                                      <label>
                                        <input class='with-gap' id='overlayType_none' value='overlayType_none' name='radio_overlaytype' type='radio'/>
                                        <span> None </span>            
                                      </p>

                                      
                              </fieldset>
                           </div>
_x000D_
_x000D_
_x000D_

jsfiddle click here

https://jsfiddle.net/hoogw/jetmkn02/1/

Is there a way to link someone to a YouTube Video in HD 1080p quality?

To link to a YouTube video so it plays in HD by default, use the following URL:

https://www.youtube.com/v/VIDEOID?version=3&vq=hd1080

Change VIDEOID to the YouTube video ID that you want to link to. When someone follows the link, it will display the highest-resolution available (up to 1080p) in full-screen mode. Unfortunately, vq=hd1080 does not work on the normal YouTube site (with comments and related videos).

PHP - remove <img> tag from string

I would suggest using the strip_tags method.

How to change checkbox's border style in CSS?

I suggest using "outline" instead of "border". For example: outline: 1px solid #1e5180.

How do I increase the capacity of the Eclipse output console?

Under Window > Preferences, go to the Run/Debug > Console section, then you should see an option "Limit console output." You can uncheck this or change the number in the "Console buffer size (characters)" text box below.

(This is in Galileo, Helios CDT, Kepler, Juno, Luna, Mars, Neon, Oxygen and 2018-09)

The type initializer for 'MyClass' threw an exception

I ran into the same problem, when I was using a static methods in a Util class, just like you had used CSMessageUtility.CSDetails.

The problem was that during the static initialization of the class (using the static constructor), the framework also initialize the the static variables (fields) in the class. I had a static variable that attempts to read values from app.config, and app.config was missing the respective settings, thus resulting in an un-handled exception. This resulted in getting the

"Object reference not set to an instance of an object."

as the inner exception.

PopupWindow $BadTokenException: Unable to add window -- token null is not valid

Try to show the pop like below

findViewById(R.id.main_layout).post(new Runnable() {
        public void run() {
            mPopupWindow.showAtLocation(findViewById(R.id.main_layout), Gravity.CENTER, 0, 0);
            Button close = (Button) customView.findViewById(R.id.btn_ok);
            close.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    mPopupWindow.dismiss();
                    doOtherStuff();
                }
            });
        }
    });

How to join two sets in one line without using "|"

You can use union method for sets: set.union(other_set)

Note that it returns a new set i.e it doesn't modify itself.

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

You don't want regular expressions here.

s = "144,1231693144,26959535291011309493156476344723991336010898738574164086137773096960,26959535291011309493156476344723991336010898738574164086137773096960,1.00,4295032833,1563,2747941 288,1231823695,26959535291011309493156476344723991336010898738574164086137773096960,26959535291011309493156476344723991336010898738574164086137773096960,1.00,4295032833,909,4725008"

print s.split(',')

Gives you:

['144', '1231693144', '26959535291011309493156476344723991336010898738574164086137773096960', '26959535291011309493156476344723991336010898738574164086137773096960', '1.00
', '4295032833', '1563', '2747941 288', '1231823695', '26959535291011309493156476344723991336010898738574164086137773096960', '26959535291011309493156476344723991336010898
738574164086137773096960', '1.00', '4295032833', '909', '4725008']

How to add a custom button to the toolbar that calls a JavaScript function?

I am in the process of developing a number of custom Plugins for CKEditor and here's my survival pack of bookmarks:

For your purpose, I would recommend look at one of the plugins in the _source/plugins directory, for example the "print" button. Adding a simple Javascript function is quite easy to achieve. You should be able to duplicate the print plugin (take the directory from _source into the actual plugins/ directory, worry about minification later), rename it, rename every mention of "print" within it, give the button a proper name you use later in your toolbar setup to include the button, and add your function.

How to properly exit a C# application?

In this case, the most proper way to exit the application in to override onExit() method in App.xaml.cs:

protected override void OnExit(ExitEventArgs e) {
    base.OnExit(e); 
}

Cannot use special principal dbo: Error 15405

Fix: Cannot use the special principal ‘sa’. Microsoft SQL Server, Error: 15405

When importing a database in your SQL instance you would find yourself with Cannot use the special principal 'sa'. Microsoft SQL Server, Error: 15405 popping out when setting the sa user as the DBO of the database. To fix this, Open SQL Management Studio and Click New Query. Type:

USE mydatabase
exec sp_changedbowner 'sa', 'true'

Close the new query and after viewing the security of the sa, you will find that that sa is the DBO of the database. (14444)

Source: http://www.noelpulis.com/fix-cannot-use-the-special-principal-sa-microsoft-sql-server-error-15405/

How do I declare and initialize an array in Java?

The following shows the declaration of an array, but the array is not initialized:

 int[] myIntArray = new int[3];

The following shows the declaration as well as initialization of the array:

int[] myIntArray = {1,2,3};

Now, the following also shows the declaration as well as initialization of the array:

int[] myIntArray = new int[]{1,2,3};

But this third one shows the property of anonymous array-object creation which is pointed by a reference variable "myIntArray", so if we write just "new int[]{1,2,3};" then this is how anonymous array-object can be created.

If we just write:

int[] myIntArray;

this is not declaration of array, but the following statement makes the above declaration complete:

myIntArray=new int[3];

Bulk Insert to Oracle using .NET

A really fast way to solve this problem is to make a database link from the Oracle database to the MySQL database. You can create database links to non-Oracle databases. After you have created the database link you can retrieve your data from the MySQL database with a ... create table mydata as select * from ... statement. This is called heterogeneous connectivity. This way you don't have to do anything in your .net application to move the data.

Another way is to use ODP.NET. In ODP.NET you can use the OracleBulkCopy-class.

But I don't think that inserting 160k records in an Oracle table with System.Data.OracleClient should take 25 minutes. I think you commit too many times. And do you bind your values to the insert statement with parameters or do you concatenate your values. Binding is much faster.

JavaScript for...in vs for

I have seen problems with the "for each" using objects and prototype and arrays

my understanding is that the for each is for properties of objects and NOT arrays

How to run .sh on Windows Command Prompt?

On Windows 10 Anniversary Update, it's even easier to run shell commands in/with bash on ubuntu on windows

I was trying to set my region for my x-wrt r7000 netgear router, I found the following worked for me, using bash on ubuntu on windows, you do have to enable subsystem found in windows features, and dev mode on

ssh [email protected] < /mnt/c/ccode-eu.sh

Check if a radio button is checked jquery

First of all, have only one id="test"

Secondly, try this:

if ($('[name="test"]').is(':checked'))

What is an attribute in Java?

Attributes are also data members and properties of a class. They are Variables declared inside class.

Vue JS mounted()

You can also move mounted out of the Vue instance and make it a function in the top-level scope. This is also a useful trick for server side rendering in Vue.

function init() {
  // Use `this` normally
}

new Vue({
  methods:{
    init
  },
  mounted(){
    init.call(this)
  }
})

Calling a function on bootstrap modal open

if somebody still has a problem the only thing working perfectly for me by useing (loaded.bs.modal) :

 $('#editModal').on('loaded.bs.modal', function () {
       console.log('edit modal loaded');

       $('.datepicker').datepicker({
            dateFormat: 'yy-mm-dd',
            clearBtn: true,
            rtl: false,
            todayHighlight: true,
            toggleActive: true,
            changeYear: true,
            changeMonth: true
        });
});

Error message 'java.net.SocketException: socket failed: EACCES (Permission denied)'

Uninstalling the app on device and then reinstalling fixed it for me.

Tried all the other options, nothing. Finally found this post. This is after adding permission (below) and cleaning build.

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

How to display the value of the bar on each bar with pyplot.barh()?

Check this link Matplotlib Gallery This is how I used the code snippet of autolabel.

    def autolabel(rects):
    """Attach a text label above each bar in *rects*, displaying its height."""
    for rect in rects:
        height = rect.get_height()
        ax.annotate('{}'.format(height),
                    xy=(rect.get_x() + rect.get_width() / 2, height),
                    xytext=(0, 3),  # 3 points vertical offset
                    textcoords="offset points",
                    ha='center', va='bottom')
        
temp = df_launch.groupby(['yr_mt','year','month'])['subs_trend'].agg(subs_count='sum').sort_values(['year','month']).reset_index()
_, ax = plt.subplots(1,1, figsize=(30,10))
bar = ax.bar(height=temp['subs_count'],x=temp['yr_mt'] ,color ='g')
autolabel(bar)

ax.set_title('Monthly Change in Subscribers from Launch Date')
ax.set_ylabel('Subscriber Count Change')
ax.set_xlabel('Time')
plt.show()

How to comment multiple lines with space or indent

Pressing Ctrl+K+C or Ctrl+E+C After selecting the lines you want to comment will not give space after slashes. you can use multiline select to provide space as suggested by Habib

Perhaps, you can use /* before the lines you want to comment and after */ in that case you might not need to provide spaces.

/*
  First Line to Comment
  Second Line to Comment
  Third Line to Comment      
*/

How to bind 'touchstart' and 'click' events but not respond to both?

Here's a simple way to do it:

// A very simple fast click implementation
$thing.on('click touchstart', function(e) {
  if (!$(document).data('trigger')) $(document).data('trigger', e.type);
  if (e.type===$(document).data('trigger')) {
    // Do your stuff here
  }
});

You basically save the first event type that is triggered to the 'trigger' property in jQuery's data object that is attached to the root document, and only execute when the event type is equal to the value in 'trigger'. On touch devices, the event chain would likely be 'touchstart' followed by 'click'; however, the 'click' handler won't be executed because "click" doesn't match the initial event type saved in 'trigger' ("touchstart").

The assumption, and I do believe it's a safe one, is that your smartphone won't spontaneously change from a touch device to a mouse device or else the tap won't ever register because the 'trigger' event type is only saved once per page load and "click" would never match "touchstart".

Here's a codepen you can play around with (try tapping on the button on a touch device -- there should be no click delay): http://codepen.io/thdoan/pen/xVVrOZ

I also implemented this as a simple jQuery plugin that also supports jQuery's descendants filtering by passing a selector string:

// A very simple fast click plugin
// Syntax: .fastClick([selector,] handler)
$.fn.fastClick = function(arg1, arg2) {
  var selector, handler;
  switch (typeof arg1) {
    case 'function':
      selector = null;
      handler = arg1;
      break;
    case 'string':
      selector = arg1;
      if (typeof arg2==='function') handler = arg2;
      else return;
      break;
    default:
      return;
  }
  this.on('click touchstart', selector, function(e) {
    if (!$(document).data('trigger')) $(document).data('trigger', e.type);
    if (e.type===$(document).data('trigger')) handler.apply(this, arguments);
  });
};

Codepen: http://codepen.io/thdoan/pen/GZrBdo/

XPath OR operator for different nodes

If you want to select only one of two nodes with union operator, you can use this solution: (//bookstore/book/title | //bookstore/city/zipcode/title)[1]

When are static variables initialized?

Starting with the code from the other question:

class MyClass {
  private static MyClass myClass = new MyClass();
  private static final Object obj = new Object();
  public MyClass() {
    System.out.println(obj); // will print null once
  }
}

A reference to this class will start initialization. First, the class will be marked as initialized. Then the first static field will be initialized with a new instance of MyClass(). Note that myClass is immediately given a reference to a blank MyClass instance. The space is there, but all values are null. The constructor is now executed and prints obj, which is null.

Now back to initializing the class: obj is made a reference to a new real object, and we're done.

If this was set off by a statement like: MyClass mc = new MyClass(); space for a new MyClass instance is again allocated (and the reference placed in mc). The constructor is again executed and again prints obj, which now is not null.

The real trick here is that when you use new, as in WhatEverItIs weii = new WhatEverItIs( p1, p2 ); weii is immediately given a reference to a bit of nulled memory. The JVM will then go on to initialize values and run the constructor. But if you somehow reference weii before it does so--by referencing it from another thread or or by referencing from the class initialization, for instance--you are looking at a class instance filled with null values.

PHP: Convert any string to UTF-8 without knowing the original character set, or at least try

In motherland Russia we have 4 popular encodings, so your question is in great demand here.

Only by char codes of symbols you can not detect encoding, because code pages intersect. Some codepages in different languages have even full intersection. So, we need another approach.

The only way to work with unknown encodings is working with probabilities. So, we do not want to answer the question "what is encoding of this text?", we are trying to understand "what is most likely encoding of this text?".

One guy here in popular Russian tech blog invented this approach:

Build the probability range of char codes in every encoding you want to support. You can build it using some big texts in your language (e.g. some fiction, use Shakespeare for english and Tolstoy for russian, lol ). You will get smth like this:

    encoding_1:
    190 => 0.095249209893009,
    222 => 0.095249209893009,
    ...
    encoding_2:
    239 => 0.095249209893009,
    207 => 0.095249209893009,
    ...
    encoding_N:
    charcode => probabilty

Next. You take text in unknown encoding and for every encoding in your "probability dictionary" you search for frequency of every symbol in unknown-encoded text. Sum probabilities of symbols. Encoding with bigger rating is likely the winner. Better results for bigger texts.

If you are interested, I can gladly help you with this task. We can greatly increase the accuracy by building two-charcodes probabilty list.

Btw. mb_detect_encoding certanly does not work. Yes, at all. Please, take a look of mb_detect_encoding source code in "ext/mbstring/libmbfl/mbfl/mbfl_ident.c".

Solving SharePoint Server 2010 - 503. The service is unavailable, After installation

Thanks for sharing this. It helped a lot. The one difference in my applicationHost.config was

            <add name="SharePoint14Module" image="C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\isapi\owssvr.dll" preCondition="appPoolName=SharePoint Central Administration v4,bitness64;SharePoint - 80" />

Note the multiple semicolon seperated entries. This is probably because I have a single box install of SPS.

How can I parse a YAML file from a Linux shell script?

My use case may or may not be quite the same as what this original post was asking, but it's definitely similar.

I need to pull in some YAML as bash variables. The YAML will never be more than one level deep.

YAML looks like so:

KEY:                value
ANOTHER_KEY:        another_value
OH_MY_SO_MANY_KEYS: yet_another_value
LAST_KEY:           last_value

Output like-a dis:

KEY="value"
ANOTHER_KEY="another_value"
OH_MY_SO_MANY_KEYS="yet_another_value"
LAST_KEY="last_value"

I achieved the output with this line:

sed -e 's/:[^:\/\/]/="/g;s/$/"/g;s/ *=/=/g' file.yaml > file.sh
  • s/:[^:\/\/]/="/g finds : and replaces it with =", while ignoring :// (for URLs)
  • s/$/"/g appends " to the end of each line
  • s/ *=/=/g removes all spaces before =

Django: Redirect to previous page after login

I linked to the login form by passing the current page as a GET parameter and then used 'next' to redirect to that page. Thanks!

Accessing a Dictionary.Keys Key through a numeric index

A Dictionary is a Hash Table, so you have no idea the order of insertion!

If you want to know the last inserted key I would suggest extending the Dictionary to include a LastKeyInserted value.

E.g.:

public MyDictionary<K, T> : IDictionary<K, T>
{
    private IDictionary<K, T> _InnerDictionary;

    public K LastInsertedKey { get; set; }

    public MyDictionary()
    {
        _InnerDictionary = new Dictionary<K, T>();
    }

    #region Implementation of IDictionary

    public void Add(KeyValuePair<K, T> item)
    {
        _InnerDictionary.Add(item);
        LastInsertedKey = item.Key;

    }

    public void Add(K key, T value)
    {
        _InnerDictionary.Add(key, value);
        LastInsertedKey = key;
    }

    .... rest of IDictionary methods

    #endregion

}

You will run into problems however when you use .Remove() so to overcome this you will have to keep an ordered list of the keys inserted.

Ruby on Rails: how to render a string as HTML?

If you're on rails which utilizes Erubis — the coolest way to do it is

<%== @str >

Note the double equal sign. See related question on SO for more info.

Error 1022 - Can't write; duplicate key in table

I also encountered that problem.Check if database name already exist in Mysql,and rename the old one.

OpenCV - DLL missing, but it's not?

you can find the opencv_core248 and other dlls in opencv\build\x86\vc12\bin folder. Just copy the dlls you require into system32 folder. And your app should start working in a flash ! Hope it helps.

Uncaught TypeError: .indexOf is not a function

I was getting e.data.indexOf is not a function error, after debugging it, I found that it was actually a TypeError, which meant, indexOf() being a function is applicable to strings, so I typecasted the data like the following and then used the indexOf() method to make it work

e.data.toString().indexOf('<stringToBeMatchedToPosition>')

Not sure if my answer was accurate to the question, but yes shared my opinion as i faced a similar kind of situation.

Make var_dump look pretty

I wrote a function (debug_display) which can print, arrays, objects, and file info in pretty way.

<?php
function debug_display($var,$show = false) {
    if($show) { $dis = 'block'; }else { $dis = 'none'; }
    ob_start();
    echo '<div style="display:'.$dis.';text-align:left; direction:ltr;"><b>Idea Debug Method : </b>
        <pre>';
    if(is_bool($var)) {
        echo $var === TRUE ? 'Boolean(TRUE)' : 'Boolean(FALSE)';
    }else {
        if(FALSE == empty($var) && $var !== NULL && $var != '0') {
            if(is_array($var)) {
                echo "Number of Indexes: " . count($var) . "\n";
                print_r($var);
            } elseif(is_object($var)) {
                print_r($var);
            } elseif(@is_file($var)){
                $stat = stat($var);
                $perm = substr(sprintf('%o',$stat['mode']), -4);
                $accesstime = gmdate('Y/m/d H:i:s', $stat['atime']);
                $modification = gmdate('Y/m/d H:i:s', $stat['mtime']);
                $change = gmdate('Y/m/d H:i:s', $stat['ctime']);
                echo "
    file path : $var
    file size : {$stat['size']} Byte
    device number : {$stat['dev']}
    permission : {$perm}
    last access time was : {$accesstime}
    last modified time was : {$modification}
    last change time was : {$change}
    ";
            }elseif(is_string($var)) {
                print_r(htmlentities(str_replace("\t", '  ', $var)));
            }  else {
                print_r($var);
            }
        }else {
            echo 'Undefined';
        }
    }
    echo '</pre>
    </div>';
    $output = ob_get_contents();
    ob_end_clean();
    echo $output;
    unset($output);
}

Uninstall mongoDB from ubuntu

I suggest the following to make sure everything is uninstalled:

sudo apt-get purge mongodb mongodb-clients mongodb-server mongodb-dev

sudo apt-get purge mongodb-10gen

sudo apt-get autoremove

This should also remove your config from

 /etc/mongodb.conf.

If you want to clean up completely and you might also want to remove the data directory

/var/lib/mongodb

Oracle SQL, concatenate multiple columns + add text

The Oracle/PLSQL CONCAT function allows to concatenate two strings together.

CONCAT( string1, string2 )

string1

The first string to concatenate.

string2

The second string to concatenate.

E.g.

SELECT 'I like ' || type_column_name || ' cake with ' || 
icing_column_name || ' and a ' fruit_column_name || '.' 
AS Cake FROM table;

Powershell send-mailmessage - email to multiple recipients

$recipients = "Marcel <[email protected]>, Marcelt <[email protected]>"

is type of string you need pass to send-mailmessage a string[] type (an array):

[string[]]$recipients = "Marcel <[email protected]>", "Marcelt <[email protected]>"

I think that not casting to string[] do the job for the coercing rules of powershell:

$recipients = "Marcel <[email protected]>", "Marcelt <[email protected]>"

is object[] type but can do the same job.

Throwing multiple exceptions in a method of an interface in java

You can declare as many Exceptions as you want for your interface method. But the class you gave in your question is invalid. It should read

public class MyClass implements MyInterface {
  public void find(int x) throws A_Exception, B_Exception{
    ----
    ----
    ---
  }
}

Then an interface would look like this

public interface MyInterface {
  void find(int x) throws A_Exception, B_Exception;
}

Run cron job only if it isn't already running

With lockrun you don't need to write a wrapper script for your cron job. http://www.unixwiz.net/tools/lockrun.html

'Class' does not contain a definition for 'Method'

I had the same issue when working in a solution with multiple projects that share code. Turned out that I forgot to update the DLL in the folder of the 2nd project.

My suggestion is to take a good look at the 'project' column in the Error list window and make sure that project also uses the right DLL.

PHP session handling errors

Go to your PHP.ini file or find PHP.ini EZConfig on your Cpanel and set your session.save_path to the full path leading to the tmp file, i.e: /home/cpanelusername/tmp

How to detect the screen resolution with JavaScript?

If you want to detect screen resolution, you might want to checkout the plugin res. It allows you to do the following:

var res = require('res')
res.dppx() // 1
res.dpi() // 96
res.dpcm() // 37.79527559055118

Here are some great resolution takeaways from Ryan Van Etten, the plugin's author:

  • 2 unit sets exist and differ at a fixed scale: device units and CSS units.
  • Resolution is calculated as the number of dots that can fit along a particular CSS length.
  • Unit conversion: 1?in = 2.54?cm = 96?px = 72?pt
  • CSS has relative and absolute lengths. In normal zoom: 1?em = 16?px
  • dppx is equivalent to device-pixel-ratio.
  • devicePixelRatio definition differs by platform.
  • Media queries can target min-resolution. Use with care for speed.

Here's the source code for res, as of today:

!function(root, name, make) {
  if (typeof module != 'undefined' && module.exports) module.exports = make()
  else root[name] = make()
}(this, 'res', function() {

  var one = {dpi: 96, dpcm: 96 / 2.54}

  function ie() {
    return Math.sqrt(screen.deviceXDPI * screen.deviceYDPI) / one.dpi
  }

  function dppx() {
    // devicePixelRatio: Webkit (Chrome/Android/Safari), Opera (Presto 2.8+), FF 18+
    return typeof window == 'undefined' ? 0 : +window.devicePixelRatio || ie() || 0
  }

  function dpcm() {
    return dppx() * one.dpcm
  }

  function dpi() {
    return dppx() * one.dpi
  }

  return {'dppx': dppx, 'dpi': dpi, 'dpcm': dpcm}
});

How to convert integer to char in C?

 void main ()
 {
    int temp,integer,count=0,i,cnd=0;
    char ascii[10]={0};
    printf("enter a number");
    scanf("%d",&integer);


     if(integer>>31)
     {
     /*CONVERTING 2's complement value to normal value*/    
     integer=~integer+1;    
     for(temp=integer;temp!=0;temp/=10,count++);    
     ascii[0]=0x2D;
     count++;
     cnd=1;
     }
     else
     for(temp=integer;temp!=0;temp/=10,count++);    
     for(i=count-1,temp=integer;i>=cnd;i--)
     {

        ascii[i]=(temp%10)+0x30;
        temp/=10;
     }
    printf("\n count =%d ascii=%s ",count,ascii);

 }

In PHP, how can I add an object element to an array?

Do you really need an object? What about:

$myArray[] = array("name" => "my name");

Just use a two-dimensional array.

Output (var_dump):

array(1) {
  [0]=>
  array(1) {
    ["name"]=>
    string(7) "my name"
  }
}

You could access your last entry like this:

echo $myArray[count($myArray) - 1]["name"];

Access-control-allow-origin with multiple domains

For IIS 7.5+ and Rewrite 2.0 you can use:

<system.webServer>
   <httpProtocol>
     <customHeaders>
         <add name="Access-Control-Allow-Headers" value="Origin, X-Requested-With, Content-Type, Accept" />
         <add name="Access-Control-Allow-Methods" value="POST,GET,OPTIONS,PUT,DELETE" />
     </customHeaders>
   </httpProtocol>
        <rewrite>            
            <outboundRules>
                <clear />                
                <rule name="AddCrossDomainHeader">
                    <match serverVariable="RESPONSE_Access_Control_Allow_Origin" pattern=".*" />
                    <conditions logicalGrouping="MatchAll" trackAllCaptures="true">
                        <add input="{HTTP_ORIGIN}" pattern="(http(s)?://((.+\.)?domain1\.com|(.+\.)?domain2\.com|(.+\.)?domain3\.com))" />
                    </conditions>
                    <action type="Rewrite" value="{C:0}" />
                </rule>           
            </outboundRules>
        </rewrite>
 </system.webServer>

Explaining the server variable RESPONSE_Access_Control_Allow_Origin portion:
In Rewrite you can use any string after RESPONSE_ and it will create the Response Header using the rest of the word as the header name (in this case Access-Control-Allow-Origin). Rewrite uses underscores "_" instead of dashes "-" (rewrite converts them to dashes)

Explaining the server variable HTTP_ORIGIN :
Similarly, in Rewrite you can grab any Request Header using HTTP_ as the prefix. Same rules with the dashes (use underscores "_" instead of dashes "-").

VBA using ubound on a multidimensional array

[This is a late answer addressing the title of the question (since that is what people would encounter when searching) rather than the specifics of OP's question which has already been answered adequately]

Ubound is a bit fragile in that it provides no way to know how many dimensions an array has. You can use error trapping to determine the full layout of an array. The following returns a collection of arrays, one for each dimension. The count property can be used to determine the number of dimensions and their lower and upper bounds can be extracted as needed:

Function Bounds(A As Variant) As Collection
    Dim C As New Collection
    Dim v As Variant, i As Long

    On Error GoTo exit_function
    i = 1
    Do While True
        v = Array(LBound(A, i), UBound(A, i))
        C.Add v
        i = i + 1
    Loop
exit_function:
    Set Bounds = C
End Function

Used like this:

Sub test()
    Dim i As Long
    Dim A(1 To 10, 1 To 5, 4 To 10) As Integer
    Dim B(1 To 5) As Variant
    Dim C As Variant
    Dim sizes As Collection

    Set sizes = Bounds(A)
    Debug.Print "A has " & sizes.Count & " dimensions:"
    For i = 1 To sizes.Count
        Debug.Print sizes(i)(0) & " to " & sizes(i)(1)
    Next i

    Set sizes = Bounds(B)
    Debug.Print vbCrLf & "B has " & sizes.Count & " dimensions:"
    For i = 1 To sizes.Count
        Debug.Print sizes(i)(0) & " to " & sizes(i)(1)
    Next i

    Set sizes = Bounds(C)
    Debug.Print vbCrLf & "C has " & sizes.Count & " dimensions:"
    For i = 1 To sizes.Count
        Debug.Print sizes(i)(0) & " to " & sizes(i)(1)
    Next i
End Sub

Output:

A has 3 dimensions:
1 to 10
1 to 5
4 to 10

B has 1 dimensions:
1 to 5

C has 0 dimensions:

What is &amp used for

That's a great example. When &current is parsed into a text node it is converted to ¤t. When parsed into an attribute value, it is parsed as &current.

If you want &current in a text node, you should write &amp;current in your markup.

The gory details are in the HTML5 parsing spec - Named Character Reference State

SFTP Libraries for .NET

I've been using Chilkat's native SFTP library ( http://www.chilkatsoft.com/ssh-sftp-component.asp ) for a couple of months now and it's working great. Been using it in a nightly job to download large files and do private key authentication. Only problem that I had was getting the 64bit version to work on windows server 2008, I needed to install vcredist_x64.exe ( http://www.microsoft.com/download/en/details.aspx?id=14632 ) on my server.

Meaning of "[: too many arguments" error from if [] (square brackets)

If your $VARIABLE is a string containing spaces or other special characters, and single square brackets are used (which is a shortcut for the test command), then the string may be split out into multiple words. Each of these is treated as a separate argument.

So that one variable is split out into many arguments:

VARIABLE=$(/some/command);  
# returns "hello world"

if [ $VARIABLE == 0 ]; then
  # fails as if you wrote:
  # if [ hello world == 0 ]
fi 

The same will be true for any function call that puts down a string containing spaces or other special characters.


Easy fix

Wrap the variable output in double quotes, forcing it to stay as one string (therefore one argument). For example,

VARIABLE=$(/some/command);
if [ "$VARIABLE" == 0 ]; then
  # some action
fi 

Simple as that. But skip to "Also beware..." below if you also can't guarantee your variable won't be an empty string, or a string that contains nothing but whitespace.


Or, an alternate fix is to use double square brackets (which is a shortcut for the new test command).

This exists only in bash (and apparently korn and zsh) however, and so may not be compatible with default shells called by /bin/sh etc.

This means on some systems, it might work from the console but not when called elsewhere, like from cron, depending on how everything is configured.

It would look like this:

VARIABLE=$(/some/command);
if [[ $VARIABLE == 0 ]]; then
  # some action
fi 

If your command contains double square brackets like this and you get errors in logs but it works from the console, try swapping out the [[ for an alternative suggested here, or, ensure that whatever runs your script uses a shell that supports [[ aka new test.


Also beware of the [: unary operator expected error

If you're seeing the "too many arguments" error, chances are you're getting a string from a function with unpredictable output. If it's also possible to get an empty string (or all whitespace string), this would be treated as zero arguments even with the above "quick fix", and would fail with [: unary operator expected

It's the same 'gotcha' if you're used to other languages - you don't expect the contents of a variable to be effectively printed into the code like this before it is evaluated.

Here's an example that prevents both the [: too many arguments and the [: unary operator expected errors: replacing the output with a default value if it is empty (in this example, 0), with double quotes wrapped around the whole thing:

VARIABLE=$(/some/command);
if [ "${VARIABLE:-0}" == 0 ]; then
  # some action
fi 

(here, the action will happen if $VARIABLE is 0, or empty. Naturally, you should change the 0 (the default value) to a different default value if different behaviour is wanted)


Final note: Since [ is a shortcut for test, all the above is also true for the error test: too many arguments (and also test: unary operator expected)

WHERE IS NULL, IS NOT NULL or NO WHERE clause depending on SQL Server parameter value

An other way of CASE:

SELECT *  
FROM MyTable
WHERE 1 = CASE WHEN @myParm = value1 AND MyColumn IS NULL     THEN 1 
               WHEN @myParm = value2 AND MyColumn IS NOT NULL THEN 1 
               WHEN @myParm = value3                          THEN 1 
          END

Hiding a button in Javascript

visibility=hidden

is very useful, but it will still take up space on the page. You can also use

display=none

because that will not only hide the object, but make it so that it doesn't take up space until it is displayed. (Also keep in mind that display's opposite is "block," not "visible")

Path.Combine absolute with relative path strings

Be careful with Backslashes, don't forget them (neither use twice:)

string relativePath = "..\\bling.txt";
string baseDirectory = "C:\\blah\\";
//OR:
//string relativePath = "\\..\\bling.txt";
//string baseDirectory = "C:\\blah";
//THEN
string absolutePath = Path.GetFullPath(baseDirectory + relativePath);

Using any() and all() to check if a list contains one set of values or another

Generally speaking:

all and any are functions that take some iterable and return True, if

  • in the case of all(), no values in the iterable are falsy;
  • in the case of any(), at least one value is truthy.

A value x is falsy iff bool(x) == False. A value x is truthy iff bool(x) == True.

Any non-booleans in the iterable will be fine — bool(x) will coerce any x according to these rules: 0, 0.0, None, [], (), [], set(), and other empty collections will yield False, anything else True. The docstring for bool uses the terms 'true'/'false' for 'truthy'/'falsy', and True/False for the concrete boolean values.


In your specific code samples:

You misunderstood a little bit how these functions work. Hence, the following does something completely not what you thought:

if any(foobars) == big_foobar:

...because any(foobars) would first be evaluated to either True or False, and then that boolean value would be compared to big_foobar, which generally always gives you False (unless big_foobar coincidentally happened to be the same boolean value).

Note: the iterable can be a list, but it can also be a generator/generator expression (˜ lazily evaluated/generated list) or any other iterator.

What you want instead is:

if any(x == big_foobar for x in foobars):

which basically first constructs an iterable that yields a sequence of booleans—for each item in foobars, it compares the item to big_foobar and emits the resulting boolean into the resulting sequence:

tmp = (x == big_foobar for x in foobars)

then any walks over all items in tmp and returns True as soon as it finds the first truthy element. It's as if you did the following:

In [1]: foobars = ['big', 'small', 'medium', 'nice', 'ugly']                                        

In [2]: big_foobar = 'big'                                                                          

In [3]: any(['big' == big_foobar, 'small' == big_foobar, 'medium' == big_foobar, 'nice' == big_foobar, 'ugly' == big_foobar])        
Out[3]: True

Note: As DSM pointed out, any(x == y for x in xs) is equivalent to y in xs but the latter is more readable, quicker to write and runs faster.

Some examples:

In [1]: any(x > 5 for x in range(4))
Out[1]: False

In [2]: all(isinstance(x, int) for x in range(10))
Out[2]: True

In [3]: any(x == 'Erik' for x in ['Erik', 'John', 'Jane', 'Jim'])
Out[3]: True

In [4]: all([True, True, True, False, True])
Out[4]: False

See also: http://docs.python.org/2/library/functions.html#all

How to make JQuery-AJAX request synchronous

From jQuery.ajax()

async Boolean
Default: true
By default, all requests are sent asynchronously (i.e. this is set to true by default). If you need synchronous requests, set this option to false.

So in your request, you must do async: false instead of async: "false".

Update:

The return value of ajaxSubmit is not the return value of the success: function(){...}. ajaxSubmit returns no value at all, which is equivalent to undefined, which in turn evaluates to true.

And that is the reason, why the form is always submitted and is independent of sending the request synchronous or not.

If you want to submit the form only, when the response is "Successful", you must return false from ajaxSubmit and then submit the form in the success function, as @halilb already suggested.

Something along these lines should work

function ajaxSubmit() {
    var password = $.trim($('#employee_password').val());
    $.ajax({
        type: "POST",
        url: "checkpass.php",
        data: "password="+password,
        success: function(response) {
            if(response == "Successful")
            {
                $('form').removeAttr('onsubmit'); // prevent endless loop
                $('form').submit();
            }
        }
    });

    return false;
}

if variable contains

if (code.indexOf("ST1")>=0) { location = "stoke central"; }

Getting Gradle dependencies in IntelliJ IDEA using Gradle build

You either need to import the project as a Gradle project from within Idea. When you add a dependency you need to open the Gradle window and perform a refresh.

Alternatively generate the project files from gradle with this:

build.gradle:

apply plugin: 'idea'

And then run:

$ gradle idea

If you modify the dependencies you will need to rerun the above again.

Importing data from a JSON file into R

jsonlite will import the JSON into a data frame. It can optionally flatten nested objects. Nested arrays will be data frames.

> library(jsonlite)
> winners <- fromJSON("winners.json", flatten=TRUE)
> colnames(winners)
[1] "winner" "votes" "startPrice" "lastVote.timestamp" "lastVote.user.name" "lastVote.user.user_id"
> winners[,c("winner","startPrice","lastVote.user.name")]
    winner startPrice lastVote.user.name
1 68694999          0              Lamur
> winners[,c("votes")]
[[1]]
                            ts user.name user.user_id
1 Thu Mar 25 03:13:01 UTC 2010     Lamur     68694999
2 Thu Mar 25 03:13:08 UTC 2010     Lamur     68694999

How do I execute a program from Python? os.system fails due to spaces in path

At least in Windows 7 and Python 3.1, os.system in Windows wants the command line double-quoted if there are spaces in path to the command. For example:

  TheCommand = '\"\"C:\\Temp\\a b c\\Notepad.exe\"\"'
  os.system(TheCommand)

A real-world example that was stumping me was cloning a drive in VirtualBox. The subprocess.call solution above didn't work because of some access rights issue, but when I double-quoted the command, os.system became happy:

  TheCommand = '\"\"C:\\Program Files\\Sun\\VirtualBox\\VBoxManage.exe\" ' \
                 + ' clonehd \"' + OrigFile + '\" \"' + NewFile + '\"\"'
  os.system(TheCommand)

update to python 3.7 using anaconda

This can be installed via conda with the command conda install -c anaconda python=3.7 as per https://anaconda.org/anaconda/python.

Though not all packages support 3.7 yet, running conda update --all may resolve some dependency failures.

How to use global variable in node.js?

If your app is written in TypeScript, try

(global as any).logger = // ...

or

Object.assign(global, { logger: // ... })

However, I will do it only when React Native's __DEV__ in testing environment.

How to access custom attributes from event object in React?

You can access data attributes something like this

event.target.dataset.tag

What is the difference between Integer and int in Java?

An Integer is pretty much just a wrapper for the primitive type int. It allows you to use all the functions of the Integer class to make life a bit easier for you.

If you're new to Java, something you should learn to appreciate is the Java documentation. For example, anything you want to know about the Integer Class is documented in detail.

This is straight out of the documentation for the Integer class:

The Integer class wraps a value of the primitive type int in an object. An object of type Integer contains a single field whose type is int.

HTML Submit-button: Different value / button-text?

It's possible using the button element.

<button name="name" value="value" type="submit">Sök</button>

From the W3C page on button:

Buttons created with the BUTTON element function just like buttons created with the INPUT element, but they offer richer rendering possibilities: the BUTTON element may have content.

How do I adb pull ALL files of a folder present in SD Card

Please try with just giving the path from where you want to pull the files I just got the files from sdcard like

adb pull sdcard/

do NOT give * like to broaden the search or to filter out. ex: adb pull sdcard/*.txt --> this is invalid.

just give adb pull sdcard/

Match everything except for specified strings

I had the same question, the solutions proposed were almost working but they had some issue. In the end the regex I used is:

^(?!red|green|blue).*

I tested it in Javascript and .NET.

.* should't be placed inside the negative lookahead like this: ^(?!.*red|green|blue) or it would make the first element behave different from the rest (i.e. "anotherred" wouldn't be matched while "anothergreen" would)

How do I download/extract font from chrome developers tools?

If you are on a unixoid operating system and want to extract just a single file you can try the following. The structure of the chrome://cache pages is URL, parsed HTTP header, hex dump of the HTTP header and then hex dump of the payload.

To extract a file copy all payload lines from a Chrome cache page to the clipboard (starting at the second 00000000: ... line), paste them into a text editor and save them as a plain text file (e.g. file.txt). If the payload is a gzipped WOFF file use xxd -r file.txt > file.woff.gz to convert it back to a binary file and gunzip file.woff.gz for decompression.

You can then use woff2otf to convert WOFF files to the OTF format or woff2 to convert WOFF 2.0 files to the TTF format. For batch processing this workflow should obviously be scripted.

Add Text on Image using PIL

First install pillow

pip install pillow

Example

from PIL import Image, ImageDraw, ImageFont

image = Image.open('Focal.png')
width, height = image.size 

draw = ImageDraw.Draw(image)

text = 'https://devnote.in'
textwidth, textheight = draw.textsize(text)

margin = 10
x = width - textwidth - margin
y = height - textheight - margin

draw.text((x, y), text)

image.save('devnote.png')

# optional parameters like optimize and quality
image.save('optimized.png', optimize=True, quality=50)

XAMPP Port 80 in use by "Unable to open process" with PID 4

Your port 80 is being used by the system.

  1. In Windows “World Wide Publishing" Service is using this port and it's process is system which PID is 4 maximum time and stopping this service(“World Wide Publishing") will free the port 80 and you can connect Apache using this port. To stop the service go to the “Task manager –> Services tab”, right click the “World Wide Publishing Service” and stop.
  2. If you don't find there then Then go to "Run > services.msc" and again find there and right click the “World Wide Publishing Service” and stop.
  3. If you didn't find “World Wide Publishing Service” there then go to "Run>>resmon.exe>> Network Tab>>Listening Ports" and see which process is using port 80

enter image description here

And from "Overview>>CPU" just Right click on that process and click "End Process Tree". If that process is system that might be a critical issue.

Make a div into a link

Not sure if this is valid but it worked for me.

The code :

_x000D_
_x000D_
<div style='position:relative;background-color:#000000;width:600px;height:30px;border:solid;'>_x000D_
  <p style='display:inline;color:#ffffff;float:left;'> Whatever </p>     _x000D_
  <a style='position:absolute;top:0px;left:0px;width:100%;height:100%;display:inline;' href ='#'></a>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Javascript: getFullyear() is not a function

You are overwriting the start date object with the value of a DOM Element with an id of Startdate.

This should work:

var start = new Date(document.getElementById('Stardate').value);

var y = start.getFullYear();

Send a ping to each IP on a subnet

This is a modification of @david-rodríguez-dribeas answer above, which runs all the pings in parallel (much faster) and only shows the output for ip addresses which return the ping.

export COUNTER=1
while [ $COUNTER -lt 255 ]
do
    ping $1$COUNTER -c 1 -w 400 | grep -B 1 "Lost = 0" &
    COUNTER=$(( $COUNTER + 1 ))
done

Give all permissions to a user on a PostgreSQL database

In PostgreSQL 9.0+ you would do the following:

GRANT ALL PRIVILEGES ON ALL TABLES IN SCHEMA MY_SCHEMA TO MY_GROUP;
GRANT ALL PRIVILEGES ON ALL SEQUENCES IN SCHEMA MY_SCHEMA TO MY_GROUP;

If you want to enable this for newly created relations too, then set the default permissions:

ALTER DEFAULT PRIVILEGES IN SCHEMA MY_SCHEMA
  GRANT ALL PRIVILEGES ON TABLES TO MY_GROUP;
ALTER DEFAULT PRIVILEGES IN SCHEMA MY_SCHEMA
  GRANT ALL PRIVILEGES ON SEQUENCES TO MY_GROUP;

However, seeing that you use 8.1 you have to code it yourself:

CREATE FUNCTION grant_all_in_schema (schname name, grant_to name) RETURNS integer AS $$
DECLARE
  rel RECORD;
BEGIN
  FOR rel IN
    SELECT c.relname
    FROM pg_class c
    JOIN pg_namespace s ON c.namespace = s.oid
    WHERE s.nspname = schname
  LOOP
    EXECUTE 'GRANT ALL PRIVILEGES ON ' || quote_ident(schname) || '.' || rel.relname || ' TO ' || quote_ident(grant_to);
  END LOOP;
  RETURN 1;
END; $$ LANGUAGE plpgsql STRICT;
REVOKE ALL ON FUNCTION grant_all_in_schema(name, name) FROM PUBLIC;

This will set the privileges on all relations: tables, views, indexes, sequences, etc. If you want to restrict that, filter on pg_class.relkind. See the pg_class docs for details.

You should run this function as superuser and as regular as your application requires. An option would be to package this in a cron job that executes every day or every hour.

New lines inside paragraph in README.md

According to Github API two empty lines are a new paragraph (same as here in stackoverflow)

You can test it with http://prose.io

How can I make my string property nullable?

string type is a reference type, therefore it is nullable by default. You can only use Nullable<T> with value types.

public struct Nullable<T> where T : struct

Which means that whatever type is replaced for the generic parameter, it must be a value type.

How to set "style=display:none;" using jQuery's attr method?

Please try below code for it :

$('#msform').fadeOut(50);

$('#msform').fadeIn(50);

Laravel Migration table already exists, but I want to add new not the older

Answer is very straight forward :

First take a backup of folder bootstrap/cache.

Then delete all the files from bootstrap/cache folder .

Now run:

php artisan migrate 

Escape quotes in JavaScript

The problem is that HTML doesn't recognize the escape character. You could work around that by using the single quotes for the HTML attribute and the double quotes for the onclick.

<a href="#" onclick='DoEdit("Preliminary Assessment \"Mini\""); return false;'>edit</a>

How to write a foreach in SQL Server?

You seem to want to use a CURSOR. Though most of the times it's best to use a set based solution, there are some times where a CURSOR is the best solution. Without knowing more about your real problem, we can't help you more than that:

DECLARE @PractitionerId int

DECLARE MY_CURSOR CURSOR 
  LOCAL STATIC READ_ONLY FORWARD_ONLY
FOR 
SELECT DISTINCT PractitionerId 
FROM Practitioner

OPEN MY_CURSOR
FETCH NEXT FROM MY_CURSOR INTO @PractitionerId
WHILE @@FETCH_STATUS = 0
BEGIN 
    --Do something with Id here
    PRINT @PractitionerId
    FETCH NEXT FROM MY_CURSOR INTO @PractitionerId
END
CLOSE MY_CURSOR
DEALLOCATE MY_CURSOR

How to use a decimal range() step value?

Add auto-correction for the possibility of an incorrect sign on step:

def frange(start,step,stop):
    step *= 2*((stop>start)^(step<0))-1
    return [start+i*step for i in range(int((stop-start)/step))]

Getting the 'external' IP address in Java

If you are using JAVA based webapp and if you want to grab the client's (One who makes the request via a browser) external ip try deploying the app in a public domain and use request.getRemoteAddr() to read the external IP address.