Programs & Examples On #Custom tools

How to compare strings

In C++ the std::string class implements the comparison operators, so you can perform the comparison using == just as you would expect:

if (string == "add") { ... }

When used properly, operator overloading is an excellent C++ feature.

img src SVG changing the styles with CSS

If you are just switching the image between the real color and the black-and-white, you can set one selector as:

{filter:none;}

and another as:

{filter:grayscale(100%);}

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

I am having the same issue here is my scenario

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

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

enter image description here enter image description here

How to stop event bubbling on checkbox click

When using jQuery you do not need to call a stop function separate.

You can just return false in the event handler

This will stop the event and cancel bubbling..

Also see event.preventDefault() vs. return false

From the jQuery docs:

These handlers, therefore, may prevent the delegated handler from triggering by calling event.stopPropagation() or returning false.

How to declare Global Variables in Excel VBA to be visible across the Workbook

You can do the following to learn/test the concept:

  1. Open new Excel Workbook and in Excel VBA editor right-click on Modules->Insert->Module

  2. In newly added Module1 add the declaration; Public Global1 As String

  3. in Worksheet VBA Module Sheet1(Sheet1) put the code snippet:

Sub setMe()
      Global1 = "Hello"
End Sub
  1. in Worksheet VBA Module Sheet2(Sheet2) put the code snippet:
Sub showMe()
    Debug.Print (Global1)
End Sub
  1. Run in sequence Sub setMe() and then Sub showMe() to test the global visibility/accessibility of the var Global1

Hope this will help.

What is Type-safe?

To get a better understanding do watch the below video which demonstrates code in type safe language (C#) and NOT type safe language ( javascript).

http://www.youtube.com/watch?v=Rlw_njQhkxw

Now for the long text.

Type safety means preventing type errors. Type error occurs when data type of one type is assigned to other type UNKNOWINGLY and we get undesirable results.

For instance JavaScript is a NOT a type safe language. In the below code “num” is a numeric variable and “str” is string. Javascript allows me to do “num + str” , now GUESS will it do arithmetic or concatenation .

Now for the below code the results are “55” but the important point is the confusion created what kind of operation it will do.

This is happening because javascript is not a type safe language. Its allowing to set one type of data to the other type without restrictions.

<script>
var num = 5; // numeric
var str = "5"; // string
var z = num + str; // arthimetic or concat ????
alert(z); // displays  “55”
</script>

C# is a type safe language. It does not allow one data type to be assigned to other data type. The below code does not allow “+” operator on different data types.

enter image description here

How to connect to SQL Server database from JavaScript in the browser?

This would be really bad to do because sharing your connection string opens up your website to so many vulnerabilities that you can't simply patch up, you have to use a different method if you want it to be secure. Otherwise you are opening up to a huge audience to take advantage of your site.

A connection was successfully established with the server, but then an error occurred during the login process. (Error Number: 233)

I got that error message in code line containing SqlConnection.Open() running my .NET code as x64 application. Running as x86 causing no errors.

Solution was to deactivate the Force protocol encryption option for TCP/IP in %windir%\System32\cliconfg.exe

Force protocol encryption

Uninstalling Android ADT

I found a solution by myself after doing some research:

  • Go to Eclipse home folder.
  • Search for 'android' => In Windows 7 you can use search bar.
  • Delete all the file related to android, which is shown in the results.
  • Restart Eclipse.
  • Install the ADT plugin again and Restart plugin.

Now everything works fine.

Python Function to test ping

It looks like you want the return keyword

def check_ping():
    hostname = "taylor"
    response = os.system("ping -c 1 " + hostname)
    # and then check the response...
    if response == 0:
        pingstatus = "Network Active"
    else:
        pingstatus = "Network Error"

    return pingstatus

You need to capture/'receive' the return value of the function(pingstatus) in a variable with something like:

pingstatus = check_ping()

NOTE: ping -c is for Linux, for Windows use ping -n

Some info on python functions:

http://www.tutorialspoint.com/python/python_functions.htm

http://www.learnpython.org/en/Functions

It's probably worth going through a good introductory tutorial to Python, which will cover all the fundamentals. I recommend investigating Udacity.com and codeacademy.com

Java Spring - How to use classpath to specify a file location?

looks like you have maven project and so resources are in classpath by

go for

getClass().getResource("classpath:storedProcedures.sql")

Scope 'session' is not active for the current thread; IllegalStateException: No thread-bound request found

If anyone else stuck on same point, following solved my problem.

In web.xml

 <listener>
            <listener-class>
                    org.springframework.web.context.request.RequestContextListener 
            </listener-class>
  </listener>

In Session component

@Component
@Scope(value = "session",  proxyMode = ScopedProxyMode.TARGET_CLASS)

In pom.xml

    <dependency>
        <groupId>cglib</groupId>
        <artifactId>cglib</artifactId>
        <version>3.1</version>
    </dependency>

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.

Ignoring SSL certificate in Apache HttpClient 4.3

(I would have added a comment directly to vasekt's answer but I don't have enough reputation points (not sure the logic there)

Anyway... what I wanted to say is that even if you aren't explicitly creating/asking for a PoolingConnection, doesn't mean you aren't getting one.

I was going crazy trying to figure out why the original solution didn't work for me, but I ignored vasekt's answer as it "didn't apply to my case" - wrong!

I was staring at my stack-trace when low and behold I saw a PoolingConnection in the middle of it. Bang - I tired his addition and success!! (our demo is tomorrow and I was getting desperate) :-)

Data-frame Object has no Attribute

Check your DataFrame with data.columns

It should print something like this

Index([u'regiment', u'company',  u'name',u'postTestScore'], dtype='object')

Check for hidden white spaces..Then you can rename with

data = data.rename(columns={'Number ': 'Number'})

how to make label visible/invisible?

You can set display attribute as none to hide a label.

<label id="excel-data-div" style="display: none;"></label>

Get device information (such as product, model) from adb command

Why don't you try to grep the return of your command ? Something like :

adb devices -l | grep 123abc12

It should return only the line you want to.

Conversion of System.Array to List

Interestingly no one answers the question, OP isn't using a strongly typed int[] but an Array.

You have to cast the Array to what it actually is, an int[], then you can use ToList:

List<int> intList = ((int[])ints).ToList();

Note that Enumerable.ToList calls the list constructor that first checks if the argument can be casted to ICollection<T>(which an array implements), then it will use the more efficient ICollection<T>.CopyTo method instead of enumerating the sequence.

How to import local packages in go?

Local package is a annoying problem in go.

For some projects in our company we decide not use sub packages at all.

  • $ glide install
  • $ go get
  • $ go install

All work.

For some projects we use sub packages, and import local packages with full path:

import "xxxx.gitlab.xx/xxgroup/xxproject/xxsubpackage

But if we fork this project, then the subpackages still refer the original one.

How is the default max Java heap size determined?

Ernesto is right. According to the link he posted [1]:

Updated Client JVM heap configuration

In the Client JVM...

  • The default maximum heap size is half of the physical memory up to a physical memory size of 192 megabytes and otherwise one fourth of the physical memory up to a physical memory size of 1 gigabyte.

    For example, if your machine has 128 megabytes of physical memory, then the maximum heap size is 64 megabytes, and greater than or equal to 1 gigabyte of physical memory results in a maximum heap size of 256 megabytes.

  • The maximum heap size is not actually used by the JVM unless your program creates enough objects to require it. A much smaller amount, termed the initial heap size, is allocated during JVM initialization. ...

  • ...
  • Server JVM heap configuration ergonomics are now the same as the Client, except that the default maximum heap size for 32-bit JVMs is 1 gigabyte, corresponding to a physical memory size of 4 gigabytes, and for 64-bit JVMs is 32 gigabytes, corresponding to a physical memory size of 128 gigabytes.

[1] http://www.oracle.com/technetwork/java/javase/6u18-142093.html

Check if the file exists using VBA

Note your code contains Dir("thesentence") which should be Dir(thesentence).

Change your code to this

Sub test()

thesentence = InputBox("Type the filename with full extension", "Raw Data File")

Range("A1").Value = thesentence

If Dir(thesentence) <> "" Then
    MsgBox "File exists."
Else
    MsgBox "File doesn't exist."
End If

End Sub

How can I get input radio elements to horizontally align?

This also works like a charm

_x000D_
_x000D_
<form>_x000D_
    <label class="radio-inline">_x000D_
      <input type="radio" name="optradio" checked>Option 1_x000D_
    </label>_x000D_
    <label class="radio-inline">_x000D_
      <input type="radio" name="optradio">Option 2_x000D_
    </label>_x000D_
    <label class="radio-inline">_x000D_
      <input type="radio" name="optradio">Option 3_x000D_
    </label>_x000D_
  </form>
_x000D_
_x000D_
_x000D_

How to make a local variable (inside a function) global

Simply declare your variable outside any function:

globalValue = 1

def f(x):
    print(globalValue + x)

If you need to assign to the global from within the function, use the global statement:

def f(x):
    global globalValue
    print(globalValue + x)
    globalValue += 1

How can I convert a datetime object to milliseconds since epoch (unix time) in Python?

This other solution for covert datetime to unixtimestampmillis.

private static readonly DateTime UnixEpoch = new DateTime(1970, 1, 1, 0, 0, 0, DateTimeKind.Utc);

    public static long GetCurrentUnixTimestampMillis()
    {
        DateTime localDateTime, univDateTime;
        localDateTime = DateTime.Now;          
        univDateTime = localDateTime.ToUniversalTime();
        return (long)(univDateTime - UnixEpoch).TotalMilliseconds;
    } 

How to correctly dismiss a DialogFragment?

tl;dr: The correct way to close a DialogFragment is to use dismiss() directly on the DialogFragment.


Details: The documentation of DialogFragment states

Control of the dialog (deciding when to show, hide, dismiss it) should be done through the API here, not with direct calls on the dialog.

Thus, you should not use getDialog().dismiss(), since that would invoke dismiss() on the dialog. Instead, you should use the dismiss() method of the DialogFragment itself:

public void dismiss()

Dismiss the fragment and its dialog. If the fragment was added to the back stack, all back stack state up to and including this entry will be popped. Otherwise, a new transaction will be committed to remove the fragment.

As you can see, this takes care not only of closing the dialog but also of handling the fragment transactions involved in the process.

You only need to use onStop if you explicitly created any resources that require manual cleanup (closing files, closing cursors, etc.). Even then, I would override onStop of the DialogFragment rather than onStop of the underlying Dialog.

What do the python file extensions, .pyc .pyd .pyo stand for?

  1. .py: This is normally the input source code that you've written.
  2. .pyc: This is the compiled bytecode. If you import a module, python will build a *.pyc file that contains the bytecode to make importing it again later easier (and faster).
  3. .pyo: This was a file format used before Python 3.5 for *.pyc files that were created with optimizations (-O) flag. (see the note below)
  4. .pyd: This is basically a windows dll file. http://docs.python.org/faq/windows.html#is-a-pyd-file-the-same-as-a-dll

Also for some further discussion on .pyc vs .pyo, take a look at: http://www.network-theory.co.uk/docs/pytut/CompiledPythonfiles.html (I've copied the important part below)

  • When the Python interpreter is invoked with the -O flag, optimized code is generated and stored in ‘.pyo’ files. The optimizer currently doesn't help much; it only removes assert statements. When -O is used, all bytecode is optimized; .pyc files are ignored and .py files are compiled to optimized bytecode.
  • Passing two -O flags to the Python interpreter (-OO) will cause the bytecode compiler to perform optimizations that could in some rare cases result in malfunctioning programs. Currently only __doc__ strings are removed from the bytecode, resulting in more compact ‘.pyo’ files. Since some programs may rely on having these available, you should only use this option if you know what you're doing.
  • A program doesn't run any faster when it is read from a ‘.pyc’ or ‘.pyo’ file than when it is read from a ‘.py’ file; the only thing that's faster about ‘.pyc’ or ‘.pyo’ files is the speed with which they are loaded.
  • When a script is run by giving its name on the command line, the bytecode for the script is never written to a ‘.pyc’ or ‘.pyo’ file. Thus, the startup time of a script may be reduced by moving most of its code to a module and having a small bootstrap script that imports that module. It is also possible to name a ‘.pyc’ or ‘.pyo’ file directly on the command line.

Note:

On 2015-09-15 the Python 3.5 release implemented PEP-488 and eliminated .pyo files. This means that .pyc files represent both unoptimized and optimized bytecode.

Git: which is the default configured remote for branch?

You can do it more simply, guaranteeing that your .gitconfig is left in a meaningful state:

Using Git version v1.8.0 and above

git push -u hub master when pushing, or:
git branch -u hub/master

OR

(This will set the remote for the currently checked-out branch to hub/master)
git branch --set-upstream-to hub/master

OR

(This will set the remote for the branch named branch_name to hub/master)
git branch branch_name --set-upstream-to hub/master

If you're using v1.7.x or earlier

you must use --set-upstream:
git branch --set-upstream master hub/master

Pretty print in MongoDB shell as default

Got to the question but could not figure out how to print it from externally-loaded mongo. So:

This works is for console: and is prefered in console, but does not work in external mongo-loaded javascript:

db.quizes.find().pretty()

This works in external mongo-loaded javscript:

db.quizes.find().forEach(printjson)

Add a fragment to the URL without causing a redirect?

window.location.hash = 'whatever';

How to display .svg image using swift

My solution to show .svg in UIImageView from URL. You need to install SVGKit pod

Then just use it like this:

import SVGKit

 let svg = URL(string: "https://openclipart.org/download/181651/manhammock.svg")!
 let data = try? Data(contentsOf: svg)
 let receivedimage: SVGKImage = SVGKImage(data: data)
 imageview.image = receivedimage.uiImage

or you can use extension for async download

extension UIImageView {
func downloadedsvg(from url: URL, contentMode mode: UIView.ContentMode = .scaleAspectFit) {
    contentMode = mode
    URLSession.shared.dataTask(with: url) { data, response, error in
        guard
            let httpURLResponse = response as? HTTPURLResponse, httpURLResponse.statusCode == 200,
            let mimeType = response?.mimeType, mimeType.hasPrefix("image"),
            let data = data, error == nil,
            let receivedicon: SVGKImage = SVGKImage(data: data),
            let image = receivedicon.uiImage
            else { return }
        DispatchQueue.main.async() {
            self.image = image
        }
    }.resume()
}
}

How to use:

let svg = URL(string: "https://openclipart.org/download/181651/manhammock.svg")!

imageview.downloadedsvg(from: svg)

Can I access variables from another file?

One best way is by using window.INITIAL_STATE

<script src="/firstfile.js">
    // first.js
    window.__INITIAL_STATE__ = {
      back  : "#fff",
      front : "#888",
      side  : "#369"
    };
</script>
<script src="/secondfile.js">
    //second.js
    console.log(window.__INITIAL_STATE__)
    alert (window.__INITIAL_STATE__);
</script>

Can we cast a generic object to a custom object type in javascript?

This is not exactly an answer, rather sharing my findings, and hopefully getting some critical argument for/against it, as specifically I am not aware how efficient it is.

I recently had a need to do this for my project. I did this using Object.assign, more precisely it is done something like this:Object.assign(new Person(...), anObjectLikePerson).

Here is link to my JSFiddle, and also the main part of the code:

function Person(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;

  this.getFullName = function() {
    return this.lastName + ' ' + this.firstName;
  }
}

var persons = [{
  lastName: "Freeman",
  firstName: "Gordon"
}, {
  lastName: "Smith",
  firstName: "John"
}];

var stronglyTypedPersons = [];
for (var i = 0; i < persons.length; i++) {
  stronglyTypedPersons.push(Object.assign(new Person("", ""), persons[i]));
}

nodeJs callbacks simple example

var myCallback = function(data) {
  console.log('got data: '+data);
};

var usingItNow = function(callback) {
  callback('get it?');
};

Now open node or browser console and paste the above definitions.

Finally use it with this next line:

usingItNow(myCallback);

With Respect to the Node-Style Error Conventions

Costa asked what this would look like if we were to honor the node error callback conventions.

In this convention, the callback should expect to receive at least one argument, the first argument, as an error. Optionally we will have one or more additional arguments, depending on the context. In this case, the context is our above example.

Here I rewrite our example in this convention.

var myCallback = function(err, data) {
  if (err) throw err; // Check for the error and throw if it exists.
  console.log('got data: '+data); // Otherwise proceed as usual.
};

var usingItNow = function(callback) {
  callback(null, 'get it?'); // I dont want to throw an error, so I pass null for the error argument
};

If we want to simulate an error case, we can define usingItNow like this

var usingItNow = function(callback) {
  var myError = new Error('My custom error!');
  callback(myError, 'get it?'); // I send my error as the first argument.
};

The final usage is exactly the same as in above:

usingItNow(myCallback);

The only difference in behavior would be contingent on which version of usingItNow you've defined: the one that feeds a "truthy value" (an Error object) to the callback for the first argument, or the one that feeds it null for the error argument.

HTML/CSS Making a textbox with text that is grayed out, and disappears when I click to enter info, how?

The shortest way is to directly add the below code as additional attributes in the input type that you want to change.

onfocus="if(this.value=='Search')this.value=''" 
onblur="if(this.value=='')this.value='Search'"

Please note: Change the text "Search" to "go" or any other text to suit your requirements.

How to make Bootstrap carousel slider use mobile left/right swipe

Checked solution is not accurate, sometimes mouse-right-click triggers right-swipe. after trying different plugins for swipe i found an almost perfect one.

touchSwipe

i said "almost" because this plugin does not support future elements. so we would have to reinitialize the swipe call when the swipe content is changed by ajax or something. this plugin have lots of options to play with touch events like multi-finger-touch,pinch etc.

http://labs.rampinteractive.co.uk/touchSwipe/demos/index.html

solution 1 :

$("#myCarousel").swipe( {
            swipe:function(event, direction, distance, duration, fingerCount, fingerData) {

                if(direction=='left'){
                    $(this).carousel('next');
                }else if(direction=='right'){
                    $(this).carousel('prev');
                }

            }
        });

solution 2:(for future element case)

function addSwipeTo(selector){
            $(selector).swipe("destroy");
            $(selector).swipe( {
                swipe:function(event, direction, distance, duration, fingerCount, fingerData) {
                    if(direction=='left'){
                        $(this).carousel('next');
                    }else if(direction=='right'){
                        $(this).carousel('prev');
                    }
                }
            });
}
addSwipeTo("#myCarousel");

Swift - Split string over multiple lines

Multi-line strings are possible as of Swift 4.0, but there are some rules:

  1. You need to start and end your strings with three double quotes, """.
  2. Your string content should start on its own line.
  3. The terminating """ should also start on its own line.

Other than that, you're good to go! Here's an example:

let longString = """
When you write a string that spans multiple
lines make sure you start its content on a
line all of its own, and end it with three
quotes also on a line of their own.
Multi-line strings also let you write "quote marks"
freely inside your strings, which is great!
"""

See what's new in Swift 4 for more information.

Error Code: 2013. Lost connection to MySQL server during query

I got the same issue when loading a .csv file. Converted the file to .sql.

Using below command I manage to work around this issue.

mysql -u <user> -p -D <DB name> < file.sql

Hope this would help.

Javascript How to define multiple variables on a single line?

Specifically to what the OP has asked, if you want to initialize N variables with the same value (e.g. 0), you can use array destructuring and Array.fill to assign to the variables an array of N 0s:

_x000D_
_x000D_
let [a, b, c, d] = Array(4).fill(0);_x000D_
_x000D_
console.log(a, b, c, d);
_x000D_
_x000D_
_x000D_

How does GPS in a mobile phone work exactly?

There's 3 satellites at least that you must be able to receive from of the 24-32 out there, and they each broadcast a time from a synchronized atomic clock. The differences in those times that you receive at any one time tell you how long the broadcast took to reach you, and thus where you are in relation to the satellites. So, it sort of reads from something, but it doesn't connect to that thing. Note that this doesn't tell you your orientation, many GPSes fake that (and speed) by interpolating data points.

If you don't count the cost of the receiver, it's a free service. Apparently there's higher resolution services out there that are restricted to military use. Those are likely a fixed cost for a license to decrypt the signals along with a confidentiality agreement.

Now your device may support GPS tracking, in which case it might communicate, say via GPRS, to a database which will store the location the device has found itself to be at, so that multiple devices may be tracked. That would require some kind of connection.

Maps are either stored on the device or received over a connection. Navigation is computed based on those maps' databases. These likely are a licensed item with a cost associated, though if you use a service like Google Maps they have the license with NAVTEQ and others.

Executing multiple SQL queries in one statement with PHP

You can just add the word JOIN or add a ; after each line(as @pictchubbate said). Better this way because of readability and also you should not meddle DELETE with INSERT; it is easy to go south.

The last question is a matter of debate, but as far as I know yes you should close after a set of queries. This applies mostly to old plain mysql/php and not PDO, mysqli. Things get more complicated(and heated in debates) in these cases.

Finally, I would suggest either using PDO or some other method.

Local file access with JavaScript

If the user selects a file via <input type="file">, you can read and process that file using the File API.

Reading or writing arbitrary files is not allowed by design. It's a violation of the sandbox. From Wikipedia -> Javascript -> Security:

JavaScript and the DOM provide the potential for malicious authors to deliver scripts to run on a client computer via the web. Browser authors contain this risk using two restrictions. First, scripts run in a sandbox in which they can only perform web-related actions, not general-purpose programming tasks like creating files.

2016 UPDATE: Accessing the filesystem directly is possible via the Filesystem API, which is only supported by Chrome and Opera and may end up not being implemented by other browsers (with the exception of Edge). For details see Kevin's answer.

How do I search for files in Visual Studio Code?

Using Go to File... which is under the Go menu or using keyboard shortcut:

  • On Windows Ctrl+p or Ctrl+e
  • On macOS Cmd ?+p
  • On Linux Ctrl+p or Ctrl+e

Then type the file name.

Also be sure to checkout that you can set your own keybindings and that there are cheatsheets available for Windows, macOS and Linux.

Ruby, remove last N characters from a string?

Using regex:

str = 'string'
n = 2  #to remove last n characters

str[/\A.{#{str.size-n}}/] #=> "stri"

Iterating over ResultSet and adding its value in an ArrayList

Just for the fun, I'm offering an alternative solution using jOOQ and Java 8. Instead of using jOOQ, you could be using any other API that maps JDBC ResultSet to List, such as Spring JDBC or Apache DbUtils, or write your own ResultSetIterator:

jOOQ 3.8 or less

List<Object> list =
DSL.using(connection)
   .fetch("SELECT col1, col2, col3, ...")
   .stream()
   .flatMap(r -> Arrays.stream(r.intoArray()))
   .collect(Collectors.toList());

jOOQ 3.9

List<Object> list =
DSL.using(connection)
   .fetch("SELECT col1, col2, col3, ...")
   .stream()
   .flatMap(Record::intoStream)
   .collect(Collectors.toList());

(Disclaimer, I work for the company behind jOOQ)

retrieve data from db and display it in table in php .. see this code whats wrong with it?

Here is the solution total html with php and database connections

   <!doctype html>
    <html lang="en">
    <head>
      <meta charset="UTF-8">
      <title>database connections</title>
    </head>
    <body>
      <?php
      $username = "database-username";
      $password = "database-password";
      $host = "localhost";

      $connector = mysql_connect($host,$username,$password)
          or die("Unable to connect");
        echo "Connections are made successfully::";
      $selected = mysql_select_db("test_db", $connector)
        or die("Unable to connect");

      //execute the SQL query and return records
      $result = mysql_query("SELECT * FROM table_one ");
      ?>
      <table border="2" style= "background-color: #84ed86; color: #761a9b; margin: 0 auto;" >
      <thead>
        <tr>
          <th>Employee_id</th>
          <th>Employee_Name</th>
          <th>Employee_dob</th>
          <th>Employee_Adress</th>
          <th>Employee_dept</th>
          <td>Employee_salary</td>
        </tr>
      </thead>
      <tbody>
        <?php
          while( $row = mysql_fetch_assoc( $result ) ){
            echo
            "<tr>
              <td>{$row\['employee_id'\]}</td>
              <td>{$row\['employee_name'\]}</td>
              <td>{$row\['employee_dob'\]}</td>
              <td>{$row\['employee_addr'\]}</td>
              <td>{$row\['employee_dept'\]}</td>
              <td>{$row\['employee_sal'\]}</td> 
            </tr>\n";
          }
        ?>
      </tbody>
    </table>
     <?php mysql_close($connector); ?>
    </body>
    </html>

What does 'COLLATE SQL_Latin1_General_CP1_CI_AS' do?

The CP1 means 'Code Page 1' - technically this translates to code page 1252

Timing Delays in VBA

On Windows timer returns hundredths of a second... Most people just use seconds because on the Macintosh platform timer returns whole numbers.

Android Device Chooser -- device not showing up

One possible reason is to check Android SDK Manager and install Google USB Driver in Extras folder if you have not installed it.

How to properly make a http web GET request

Adding to the responses already given, this is a complete example hitting JSON PlaceHolder site.

using System;
using System.Net.Http;
using System.Threading.Tasks;
using Newtonsoft.Json;

namespace Publish
{
    class Program
    {
        static async Task Main(string[] args)
        {
            
            // Get Reqeust
            HttpClient req = new HttpClient();
            var content = await req.GetAsync("https://jsonplaceholder.typicode.com/users");
            Console.WriteLine(await content.Content.ReadAsStringAsync());

            // Post Request
            Post p = new Post("Some title", "Some body", "1");
            HttpContent payload = new StringContent(JsonConvert.SerializeObject(p));
            content = await req.PostAsync("https://jsonplaceholder.typicode.com/posts", payload);
            Console.WriteLine("--------------------------");
            Console.WriteLine(content.StatusCode);
            Console.WriteLine(await content.Content.ReadAsStringAsync());
        }
    }

    public struct Post {
        public string Title {get; set;}
        public string Body {get;set;}
        public string UserID {get; set;}

        public Post(string Title, string Body, string UserID){
            this.Title = Title;
            this.Body = Body;
            this.UserID = UserID;
        }
    }
}

Catching exceptions from Guzzle

I was catching GuzzleHttp\Exception\BadResponseException as @dado is suggesting. But one day I got GuzzleHttp\Exception\ConnectException when DNS for domain wasn't available. So my suggestion is - catch GuzzleHttp\Exception\ConnectException to be safe about DNS errors as well.

Get google map link with latitude/longitude

Keep it in iframe, dynamically bind data from object.

"https://www.google.com/maps/embed/v1/place?key=[APIKEY]%20&q=" + content..Latitude + ',' + content.Longitude;

References for longitude and Latitude.
https://developers.google.com/maps/documentation/embed/guide

Note:[APIKEY] will expire in 60days and regenerate key.

How can I find all of the distinct file extensions in a folder hierarchy?

Find everythin with a dot and show only the suffix.

find . -type f -name "*.*" | awk -F. '{print $NF}' | sort -u

if you know all suffix have 3 characters then

find . -type f -name "*.???" | awk -F. '{print $NF}' | sort -u

or with sed shows all suffixes with one to four characters. Change {1,4} to the range of characters you are expecting in the suffix.

find . -type f | sed -n 's/.*\.\(.\{1,4\}\)$/\1/p'| sort -u

ECMAScript 6 arrow function that returns an object

Issue:

When you do are doing:

p => {foo: "bar"}

JavaScript interpreter thinks you are opening a multi-statement code block, and in that block, you have to explicitly mention a return statement.

Solution:

If your arrow function expression has a single statement, then you can use the following syntax:

p => ({foo: "bar", attr2: "some value", "attr3": "syntax choices"})

But if you want to have multiple statements then you can use the following syntax:

p => {return {foo: "bar", attr2: "some value", "attr3": "syntax choices"}}

In above example, first set of curly braces opens a multi-statement code block, and the second set of curly braces is for dynamic objects. In multi-statement code block of arrow function, you have to explicitly use return statements

For more details, check Mozilla Docs for JS Arrow Function Expressions

Application Loader stuck at "Authenticating with the iTunes store" when uploading an iOS app

It might be a network issue. If you are running inside a virtual machine (e.g. VMWare or VirtualBox), try setting the network adapter mode from the default NAT to Bridged.

setting an environment variable in virtualenv

To activate virtualenv in env directory and export envinroment variables stored in .env use :

source env/bin/activate && set -a; source .env; set +a

Include .so library in apk in android studio

I've tried the solution presented in the accepted answer and it did not work for me. I wanted to share what DID work for me as it might help someone else. I've found this solution here.

Basically what you need to do is put your .so files inside a a folder named lib (Note: it is not libs and this is not a mistake). It should be in the same structure it should be in the APK file.

In my case it was:
Project:
|--lib:
|--|--armeabi:
|--|--|--.so files.

So I've made a lib folder and inside it an armeabi folder where I've inserted all the needed .so files. I then zipped the folder into a .zip (the structure inside the zip file is now lib/armeabi/*.so) I renamed the .zip file into armeabi.jar and added the line compile fileTree(dir: 'libs', include: '*.jar') into dependencies {} in the gradle's build file.

This solved my problem in a rather clean way.

How to create directory automatically on SD card

Don't forget to make sure that you have no special characters in your file/folder names. Happened to me with ":" when I was setting folder names using variable(s)

not allowed characters in file/folder names

" * / : < > ? \ |

U may find this code helpful in such a case.

The below code removes all ":" and replaces them with "-"

//actualFileName = "qwerty:asdfg:zxcvb" say...

    String[] tempFileNames;
    String tempFileName ="";
    String delimiter = ":";
    tempFileNames = actualFileName.split(delimiter);
    tempFileName = tempFileNames[0];
    for (int j = 1; j < tempFileNames.length; j++){
        tempFileName = tempFileName+" - "+tempFileNames[j];
    }
    File file = new File(Environment.getExternalStorageDirectory(), "/MyApp/"+ tempFileName+ "/");
    if (!file.exists()) {
        if (!file.mkdirs()) {
        Log.e("TravellerLog :: ", "Problem creating Image folder");
        }
    }

What exactly does the Access-Control-Allow-Credentials header do?

By default, CORS does not include cookies on cross-origin requests. This is different from other cross-origin techniques such as JSON-P. JSON-P always includes cookies with the request, and this behavior can lead to a class of vulnerabilities called cross-site request forgery, or CSRF.

In order to reduce the chance of CSRF vulnerabilities in CORS, CORS requires both the server and the client to acknowledge that it is ok to include cookies on requests. Doing this makes cookies an active decision, rather than something that happens passively without any control.

The client code must set the withCredentials property on the XMLHttpRequest to true in order to give permission.

However, this header alone is not enough. The server must respond with the Access-Control-Allow-Credentials header. Responding with this header to true means that the server allows cookies (or other user credentials) to be included on cross-origin requests.

You also need to make sure your browser isn't blocking third-party cookies if you want cross-origin credentialed requests to work.

Note that regardless of whether you are making same-origin or cross-origin requests, you need to protect your site from CSRF (especially if your request includes cookies).

How to create circular ProgressBar in android?

It's easy to create this yourself

In your layout include the following ProgressBar with a specific drawable (note you should get the width from dimensions instead). The max value is important here:

<ProgressBar
    android:id="@+id/progressBar"
    style="?android:attr/progressBarStyleHorizontal"
    android:layout_width="150dp"
    android:layout_height="150dp"
    android:layout_alignParentBottom="true"
    android:layout_centerHorizontal="true"
    android:max="500"
    android:progress="0"
    android:progressDrawable="@drawable/circular" />

Now create the drawable in your resources with the following shape. Play with the radius (you can use innerRadius instead of innerRadiusRatio) and thickness values.

circular (Pre Lollipop OR API Level < 21)

   <shape
        android:innerRadiusRatio="2.3"
        android:shape="ring"
        android:thickness="3.8sp" >
        <solid android:color="@color/yourColor" />
   </shape>

circular ( >= Lollipop OR API Level >= 21)

    <shape
        android:useLevel="true"
        android:innerRadiusRatio="2.3"
        android:shape="ring"
        android:thickness="3.8sp" >
        <solid android:color="@color/yourColor" />
     </shape>

useLevel is "false" by default in API Level 21 (Lollipop) .

Start Animation

Next in your code use an ObjectAnimator to animate the progress field of the ProgessBar of your layout.

ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
ObjectAnimator animation = ObjectAnimator.ofInt(progressBar, "progress", 0, 500); // see this max value coming back here, we animate towards that value
animation.setDuration(5000); // in milliseconds
animation.setInterpolator(new DecelerateInterpolator());
animation.start();

Stop Animation

progressBar.clearAnimation();

P.S. unlike examples above, it give smooth animation.

Add URL link in CSS Background Image?

Try wrapping the spans in an anchor tag and apply the background image to that.

HTML:

<div class="header">
    <a href="/">
        <span class="header-title">My gray sea design</span><br />
        <span class="header-title-two">A beautiful design</span>
    </a>
</div>

CSS:

.header {
    border-bottom:1px solid #eaeaea;
}

.header a {
    display: block;
    background-image: url("./images/embouchure.jpg");
    background-repeat: no-repeat;
    height:160px;
    padding-left:280px;
    padding-top:50px;
    width:470px;
    color: #eaeaea;
}

Question mark and colon in statement. What does it mean?

It is the ternary conditional operator.

If the condition in the parenthesis before the ? is true, it returns the value to the left of the :, otherwise the value to the right.

How to change to an older version of Node.js

Windows

Downgrade Node with Chocolately

Install Chocolatey. Then run:

choco install nodejs.install -version 6.3.0

Chocolatey has lots of Node versions available.

Downgrade NPM

npm install -g [email protected]

Disable a Button

The button can be Disabled in Swift 4 by the code

@IBAction func yourButtonMethodname(sender: UIButon) {
 yourButton.isEnabled = false 
}

Select records from NOW() -1 Day

You're almost there: it's NOW() - INTERVAL 1 DAY

Rotate camera in Three.js with mouse

take a look at the following examples

http://threejs.org/examples/#misc_controls_orbit

http://threejs.org/examples/#misc_controls_trackball

there are other examples for different mouse controls, but both of these allow the camera to rotate around a point and zoom in and out with the mouse wheel, the main difference is OrbitControls enforces the camera up direction, and TrackballControls allows the camera to rotate upside-down.

All you have to do is include the controls in your html document

<script src="js/OrbitControls.js"></script>

and include this line in your source

controls = new THREE.OrbitControls( camera, renderer.domElement );

How to force IE to reload javascript?

When you work with web page or javascript file you want it to be reloaded every time you change it. You can change settings in IE 8 so the browser will never cache.

Follow this simple steps.

  1. Select Tools-> Internet Options.
  2. In General tab click on Settings button in Browsing history section.
  3. Click on "Every time I visit the webpage" radio button.
  4. Click OK button.

Error "package android.support.v7.app does not exist"

For what it's worth:

I ran in to this issue when using Xamarin, even though I did have the Support packages installed, both the v4 and the v7 ones.

It was resolved for me by doing Build -> Clean All.

curl : (1) Protocol https not supported or disabled in libcurl

Specifying the protocol within the url might solve your problem.

I had a similar problem (while using curl php client) :

I was passing domain.com instead of sftp://domain.com which lead to this confusing error:

Protocol "http" not supported or disabled in libcurl, took 0 seconds.

I want to multiply two columns in a pandas DataFrame and add the result into a new column

For me, this is the clearest and most intuitive:

values = []
for action in ['Sell','Buy']:
    amounts = orders_df['Amounts'][orders_df['Action'==action]].values
    if action == 'Sell':
        prices = orders_df['Prices'][orders_df['Action'==action]].values
    else:
        prices = -1*orders_df['Prices'][orders_df['Action'==action]].values
    values += list(amounts*prices)  
orders_df['Values'] = values

The .values method returns a numpy array allowing you to easily multiply element-wise and then you can cumulatively generate a list by 'adding' to it.

What is the perfect counterpart in Python for "while not EOF"

In addition to @dawg's great answer, the equivalent solution using walrus operator (Python >= 3.8):

with open(filename, 'rb') as f:
    while buf := f.read(max_size):
        process(buf)

Calculating number of full months between two dates in SQL

DATEDIFF() is designed to return the number boundaries crossed between the two dates for the span specified. To get it to do what you want, you need to make an additional adjustment to account for when the dates cross a boundary but don't complete the full span.

How to export a table dataframe in PySpark to csv?

If you cannot use spark-csv, you can do the following:

df.rdd.map(lambda x: ",".join(map(str, x))).coalesce(1).saveAsTextFile("file.csv")

If you need to handle strings with linebreaks or comma that will not work. Use this:

import csv
import cStringIO

def row2csv(row):
    buffer = cStringIO.StringIO()
    writer = csv.writer(buffer)
    writer.writerow([str(s).encode("utf-8") for s in row])
    buffer.seek(0)
    return buffer.read().strip()

df.rdd.map(row2csv).coalesce(1).saveAsTextFile("file.csv")

Is there a list of screen resolutions for all Android based phones and tablets?

You can see a lot of screen sizes on this site.

Parsed list of screens:

From http://www.emirweb.com/ScreenDeviceStatistics.php

####################################################################################################
#    Filter out same-sized same-dp screens and width/height swap.
####################################################################################################
Size: 2560 x 1600 px (1280 x 800 dp) xhdpi
Size: 2048 x 1536 px (1024 x 768 dp) xhdpi
Size: 1920 x 1200 px (1442 x 901 dp) tvdpi
Size: 1920 x 1200 px (1280 x 800 dp) hdpi
Size: 1920 x 1200 px (960 x 600 dp) xhdpi
Size: 1920 x 1200 px (640 x 400 dp) xxhdpi
Size: 1920 x 1152 px (640 x 384 dp) xxhdpi
Size: 1920 x 1080 px (1920 x 1080 dp) mdpi
Size: 1920 x 1080 px (1280 x 720 dp) hdpi
Size: 1920 x 1080 px (960 x 540 dp) xhdpi
Size: 1920 x 1080 px (640 x 360 dp) xxhdpi
Size: 1600 x 1200 px (1066 x 800 dp) hdpi
Size: 1600 x 900 px (1600 x 900 dp) mdpi
Size: 1440 x 904 px (960 x 602 dp) hdpi
Size: 1366 x 768 px (1366 x 768 dp) mdpi
Size: 1360 x 768 px (1360 x 768 dp) mdpi
Size: 1280 x 960 px (640 x 480 dp) xhdpi
Size: 1280 x 800 px (1280 x 800 dp) mdpi
Size: 1280 x 800 px (961 x 600 dp) tvdpi
Size: 1280 x 800 px (853 x 533 dp) hdpi
Size: 1280 x 800 px (640 x 400 dp) xhdpi
Size: 1280 x 768 px (1280 x 768 dp) mdpi
Size: 1280 x 768 px (640 x 384 dp) xhdpi
Size: 1280 x 720 px (1280 x 720 dp) mdpi
Size: 1280 x 720 px (961 x 540 dp) tvdpi
Size: 1280 x 720 px (853 x 480 dp) hdpi
Size: 1280 x 720 px (640 x 360 dp) xhdpi
Size: 1279 x 720 px (639 x 360 dp) xhdpi
Size: 1152 x 720 px (1152 x 720 dp) mdpi
Size: 1080 x 607 px (720 x 404 dp) hdpi
Size: 1024 x 960 px (1024 x 960 dp) mdpi
Size: 1024 x 770 px (1024 x 770 dp) mdpi
Size: 1024 x 768 px (1365 x 1024 dp) ldpi
Size: 1024 x 768 px (1024 x 768 dp) mdpi
Size: 1024 x 768 px (512 x 384 dp) xhdpi
Size: 1024 x 600 px (1365 x 800 dp) ldpi
Size: 1024 x 600 px (1024 x 600 dp) mdpi
Size: 1024 x 600 px (682 x 400 dp) hdpi
Size: 960 x 640 px (480 x 320 dp) xhdpi
Size: 960 x 600 px (960 x 600 dp) ldpi
Size: 960 x 540 px (640 x 360 dp) hdpi
Size: 864 x 480 px (576 x 320 dp) hdpi
Size: 854 x 480 px (569 x 320 dp) hdpi
Size: 800 x 600 px (1066 x 800 dp) ldpi
Size: 800 x 480 px (1066 x 640 dp) ldpi
Size: 800 x 480 px (800 x 480 dp) mdpi
Size: 800 x 480 px (600 x 360 dp) tvdpi
Size: 800 x 480 px (533 x 320 dp) hdpi
Size: 800 x 480 px (266 x 160 dp) xxhdpi
Size: 768 x 576 px (768 x 576 dp) mdpi
Size: 640 x 480 px (640 x 480 dp) mdpi
Size: 640 x 360 px (426 x 240 dp) hdpi
Size: 480 x 320 px (480 x 320 dp) mdpi
Size: 480 x 320 px (320 x 213 dp) hdpi
Size: 432 x 240 px (576 x 320 dp) ldpi
Size: 400 x 240 px (533 x 320 dp) ldpi
Size: 320 x 240 px (426 x 320 dp) ldpi
Size: 280 x 280 px (186 x 186 dp) hdpi

####################################################################################################
#    Sorted by smallest width.
####################################################################################################
sw800dp:
Size: 1920 x 1080 px (1920 x 1080 dp) mdpi
Size: 1024 x 768 px (1365 x 1024 dp) ldpi
Size: 1024 x 960 px (1024 x 960 dp) mdpi
Size: 1920 x 1200 px (1442 x 901 dp) tvdpi
Size: 1600 x 900 px (1600 x 900 dp) mdpi
Size: 800 x 600 px (1066 x 800 dp) ldpi
Size: 1920 x 1200 px (1280 x 800 dp) hdpi
Size: 1024 x 600 px (1365 x 800 dp) ldpi
Size: 2560 x 1600 px (1280 x 800 dp) xhdpi
Size: 1280 x 800 px (1280 x 800 dp) mdpi
Size: 1600 x 1200 px (1066 x 800 dp) hdpi

sw720dp:
Size: 1024 x 770 px (1024 x 770 dp) mdpi
Size: 1366 x 768 px (1366 x 768 dp) mdpi
Size: 1280 x 768 px (1280 x 768 dp) mdpi
Size: 2048 x 1536 px (1024 x 768 dp) xhdpi
Size: 1360 x 768 px (1360 x 768 dp) mdpi
Size: 1024 x 768 px (1024 x 768 dp) mdpi
Size: 1152 x 720 px (1152 x 720 dp) mdpi
Size: 1280 x 720 px (1280 x 720 dp) mdpi
Size: 1920 x 1080 px (1280 x 720 dp) hdpi

sw600dp:
Size: 800 x 480 px (1066 x 640 dp) ldpi
Size: 1440 x 904 px (960 x 602 dp) hdpi
Size: 960 x 600 px (960 x 600 dp) ldpi
Size: 1280 x 800 px (961 x 600 dp) tvdpi
Size: 1024 x 600 px (1024 x 600 dp) mdpi
Size: 1920 x 1200 px (960 x 600 dp) xhdpi

sw480dp:
Size: 768 x 576 px (768 x 576 dp) mdpi
Size: 1920 x 1080 px (960 x 540 dp) xhdpi
Size: 1280 x 720 px (961 x 540 dp) tvdpi
Size: 1280 x 800 px (853 x 533 dp) hdpi
Size: 1280 x 720 px (853 x 480 dp) hdpi
Size: 800 x 480 px (800 x 480 dp) mdpi
Size: 1280 x 960 px (640 x 480 dp) xhdpi
Size: 640 x 480 px (640 x 480 dp) mdpi

sw320dp:
Size: 1080 x 607 px (720 x 404 dp) hdpi
Size: 1024 x 600 px (682 x 400 dp) hdpi
Size: 1280 x 800 px (640 x 400 dp) xhdpi
Size: 1920 x 1200 px (640 x 400 dp) xxhdpi
Size: 1280 x 768 px (640 x 384 dp) xhdpi
Size: 1024 x 768 px (512 x 384 dp) xhdpi
Size: 1920 x 1152 px (640 x 384 dp) xxhdpi
Size: 1279 x 720 px (639 x 360 dp) xhdpi
Size: 800 x 480 px (600 x 360 dp) tvdpi
Size: 960 x 540 px (640 x 360 dp) hdpi
Size: 1920 x 1080 px (640 x 360 dp) xxhdpi
Size: 1280 x 720 px (640 x 360 dp) xhdpi
Size: 432 x 240 px (576 x 320 dp) ldpi
Size: 800 x 480 px (533 x 320 dp) hdpi
Size: 960 x 640 px (480 x 320 dp) xhdpi
Size: 864 x 480 px (576 x 320 dp) hdpi
Size: 854 x 480 px (569 x 320 dp) hdpi
Size: 480 x 320 px (480 x 320 dp) mdpi
Size: 400 x 240 px (533 x 320 dp) ldpi
Size: 320 x 240 px (426 x 320 dp) ldpi

sw240dp:
Size: 640 x 360 px (426 x 240 dp) hdpi

lower:
Size: 480 x 320 px (320 x 213 dp) hdpi
Size: 280 x 280 px (186 x 186 dp) hdpi
Size: 800 x 480 px (266 x 160 dp) xxhdpi

####################################################################################################
#    Different size in px only.
####################################################################################################
2560 x 1600 px
2048 x 1536 px
1920 x 1200 px
1920 x 1152 px
1920 x 1080 px
1600 x 1200 px
1600 x 900 px
1440 x 904 px
1366 x 768 px
1360 x 768 px
1280 x 960 px
1280 x 800 px
1280 x 768 px
1280 x 720 px
1279 x 720 px
1152 x 720 px
1080 x 607 px
1024 x 960 px
1024 x 770 px
1024 x 768 px
1024 x 600 px
960 x 640 px
960 x 600 px
960 x 540 px
864 x 480 px
854 x 480 px
800 x 600 px
800 x 480 px
768 x 576 px
640 x 480 px
640 x 360 px
480 x 320 px
432 x 240 px
400 x 240 px
320 x 240 px
280 x 280 px

####################################################################################################
#    Different size in dp only.
####################################################################################################
1920 x 1080 dp
1600 x 900 dp
1442 x 901 dp
1366 x 768 dp
1365 x 1024 dp
1365 x 800 dp
1360 x 768 dp
1280 x 800 dp
1280 x 768 dp
1280 x 720 dp
1152 x 720 dp
1066 x 800 dp
1066 x 640 dp
1024 x 960 dp
1024 x 770 dp
1024 x 768 dp
1024 x 600 dp
961 x 600 dp
961 x 540 dp
960 x 602 dp
960 x 600 dp
960 x 540 dp
853 x 533 dp
853 x 480 dp
800 x 480 dp
768 x 576 dp
720 x 404 dp
682 x 400 dp
640 x 480 dp
640 x 400 dp
640 x 384 dp
640 x 360 dp
639 x 360 dp
600 x 360 dp
576 x 320 dp
569 x 320 dp
533 x 320 dp
512 x 384 dp
480 x 320 dp
426 x 320 dp
426 x 240 dp
320 x 213 dp
266 x 160 dp
186 x 186 dp

I drop a lot of same-sized same-dp screens, ignore height/width swap and include some sorting results.

What precisely does 'Run as administrator' do?

The Run as *Anything command saves you from logging out and logging in as the user for which you use the runas command for.

The reason programs ask for this elevated privilege started with Black Comb and the Panther folder. There is 0 access to the Kernel in windows unless through the Admin prompt and then it is only a virtual relation with the O/S kernel.

Hoorah!

Conditional formatting based on another cell's value

I've used an interesting conditional formatting in a recent file of mine and thought it would be useful to others too. So this answer is meant for completeness to the previous ones.

It should demonstrate what this amazing feature is capable of, and especially how the $ thing works.

Example table

Simple google sheets table

The color from D to G depend on the values in columns A, B and C. But the formula needs to check values that are fixed horizontally (user, start, end), and values that are fixed vertically (dates in row 1). That's where the dollar sign gets useful.

Solution

There are 2 users in the table, each with a defined color, respectively foo (blue) and bar (yellow).
We have to use the following conditional formatting rules, and apply both of them on the same range (D2:G3):

  1. =AND($A2="foo", D$1>=$B2, D$1<=$C2)
  2. =AND($A2="bar", D$1>=$B2, D$1<=$C2)

In English, the condition means:
User is name, and date of current cell is after start and before end

Notice how the only thing that changes between the 2 formulas, is the name of the user. This makes it really easy to reuse with many other users!

Explanations

Important: Variable rows and columns are relative to the start of the range. But fixed values are not affected.

It is easy to get confused with relative positions. In this example, if we had used the range D1:G3 instead of D2:G3, the color formatting would be shifted 1 row up.
To avoid that, remember that the value for variable rows and columns should correspond to the start of the containing range.

In this example, the range that contains colors is D2:G3, so the start is D2.

User, start, and end vary with rows
-> Fixed columns A B C, variable rows starting at 2: $A2, $B2, $C2

Dates vary with columns
-> Variable columns starting at D, fixed row 1: D$1

Remove item from list based on condition

If your collection type is a List<stuff>, then the best approach is probably the following:

prods.RemoveAll(s => s.ID == 1)

This only does one pass (iteration) over the list, so should be more efficient than other methods.

If your type is more generically an ICollection<T>, it might help to write a short extension method if you care about performance. If not, then you'd probably get away with using LINQ (calling Where or Single).

How to justify a single flexbox item (override justify-content)

For those situations where width of the items you do want to flex-end is known, you can set their flex to "0 0 ##px" and set the item you want to flex-start with flex:1

This will cause the pseudo flex-start item to fill the container, just format it to text-align:left or whatever.

Cannot ping AWS EC2 instance

A few years late but hopefully this will help someone else...

1) First make sure the EC2 instance has a public IP. If has a Public DNS or Public IP address (circled below) then you should be good. This will be the address you ping. AWS public DNS address

2) Next make sure the Amazon network rules allow Echo Requests. Go to the Security Group for the EC2.

  • right click, select inbound rules
  • A: select Add Rule
  • B: Select Custom ICMP Rule - IPv4
  • C: Select Echo Request
  • D: Select either Anywhere or My IP
  • E: Select Save

Add a Security Group ICMP Rule to allow Pings and Echos

3) Next, Windows firewall blocks inbound Echo requests by default. Allow Echo requests by creating a windows firewall exception...

  • Go to Start and type Windows Firewall with Advanced Security
  • Select inbound rules

Add a Windows Server ICMP Rule to allow Pings and Echos

4) Done! Hopefully you should now be able to ping your server.

Enable PHP Apache2

You have two ways to enable it.

First, you can set the absolute path of the php module file in your httpd.conf file like this:

LoadModule php5_module /path/to/mods-available/libphp5.so

Second, you can link the module file to the mods-enabled directory:

ln -s /path/to/mods-available/libphp5.so /path/to/mods-enabled/libphp5.so

TCPDF ERROR: Some data has already been output, can't send PDF file

Use ob_start(); at the beginning of your code.

How do I add a new class to an element dynamically?

Short answer no :)

But you could just use the same CSS for the hover like so:

a:hover, .hoverclass {
    background:red;
}

Maybe if you explain why you need the class added, there may be a better solution?

How to use string.substr() function?

As shown here, the second argument to substr is the length, not the ending position:

string substr ( size_t pos = 0, size_t n = npos ) const;

Generate substring

Returns a string object with its contents initialized to a substring of the current object. This substring is the character sequence that starts at character position pos and has a length of n characters.

Your line b = a.substr(i,i+1); will generate, for values of i:

substr(0,1) = 1
substr(1,2) = 23
substr(2,3) = 345
substr(3,4) = 45  (since your string stops there).

What you need is b = a.substr(i,2);

You should also be aware that your output will look funny for a number like 12045. You'll get 12 20 4 45 due to the fact that you're using atoi() on the string section and outputting that integer. You might want to try just outputing the string itself which will be two characters long:

b = a.substr(i,2);
cout << b << " ";

In fact, the entire thing could be more simply written as:

#include <iostream>
#include <string>
using namespace std;
int main(void) {
    string a;
    cin >> a;
    for (int i = 0; i < a.size() - 1; i++)
        cout << a.substr(i,2) << " ";
    cout << endl;
    return 0;
}

ES6 export default with multiple functions referring to each other

The export default {...} construction is just a shortcut for something like this:

const funcs = {
    foo() { console.log('foo') }, 
    bar() { console.log('bar') },
    baz() { foo(); bar() }
}

export default funcs

It must become obvious now that there are no foo, bar or baz functions in the module's scope. But there is an object named funcs (though in reality it has no name) that contains these functions as its properties and which will become the module's default export.

So, to fix your code, re-write it without using the shortcut and refer to foo and bar as properties of funcs:

const funcs = {
    foo() { console.log('foo') }, 
    bar() { console.log('bar') },
    baz() { funcs.foo(); funcs.bar() } // here is the fix
}

export default funcs

Another option is to use this keyword to refer to funcs object without having to declare it explicitly, as @pawel has pointed out.

Yet another option (and the one which I generally prefer) is to declare these functions in the module scope. This allows to refer to them directly:

function foo() { console.log('foo') }
function bar() { console.log('bar') }
function baz() { foo(); bar() }

export default {foo, bar, baz}

And if you want the convenience of default export and ability to import items individually, you can also export all functions individually:

// util.js

export function foo() { console.log('foo') }
export function bar() { console.log('bar') }
export function baz() { foo(); bar() }

export default {foo, bar, baz}

// a.js, using default export

import util from './util'
util.foo()

// b.js, using named exports

import {bar} from './util'
bar()

Or, as @loganfsmyth suggested, you can do without default export and just use import * as util from './util' to get all named exports in one object.

Best font for coding

I like Consolas a lot. This top-10 list is a good resource for others. It includes examples and descriptions.

Converting Chart.js canvas chart to image using .toDataUrl() results in blank image

You should use the Chartjs API function toBase64Image() instead and call it after the animation is complete. Therefore:

var pieChart, URI;

var options = {
    animation : {
        onComplete : function(){    
            URI = pieChart.toBase64Image();
        }
    }
};

var content = {
    type: 'pie', //whatever, not relevant for this example
    data: {
        datasets: dataset //whatever, not relevant for this example
    },
    options: options        
};    

pieChart = new Chart(pieChart, content);

Example

You can check this example and run it

_x000D_
_x000D_
var chart = new Chart(ctx, {_x000D_
   type: 'bar',_x000D_
   data: {_x000D_
      labels: ['Standing costs', 'Running costs'], // responsible for how many bars are gonna show on the chart_x000D_
      // create 12 datasets, since we have 12 items_x000D_
      // data[0] = labels[0] (data for first bar - 'Standing costs') | data[1] = labels[1] (data for second bar - 'Running costs')_x000D_
      // put 0, if there is no data for the particular bar_x000D_
      datasets: [{_x000D_
         label: 'Washing and cleaning',_x000D_
         data: [0, 8],_x000D_
         backgroundColor: '#22aa99'_x000D_
      }, {_x000D_
         label: 'Traffic tickets',_x000D_
         data: [0, 2],_x000D_
         backgroundColor: '#994499'_x000D_
      }, {_x000D_
         label: 'Tolls',_x000D_
         data: [0, 1],_x000D_
         backgroundColor: '#316395'_x000D_
      }, {_x000D_
         label: 'Parking',_x000D_
         data: [5, 2],_x000D_
         backgroundColor: '#b82e2e'_x000D_
      }, {_x000D_
         label: 'Car tax',_x000D_
         data: [0, 1],_x000D_
         backgroundColor: '#66aa00'_x000D_
      }, {_x000D_
         label: 'Repairs and improvements',_x000D_
         data: [0, 2],_x000D_
         backgroundColor: '#dd4477'_x000D_
      }, {_x000D_
         label: 'Maintenance',_x000D_
         data: [6, 1],_x000D_
         backgroundColor: '#0099c6'_x000D_
      }, {_x000D_
         label: 'Inspection',_x000D_
         data: [0, 2],_x000D_
         backgroundColor: '#990099'_x000D_
      }, {_x000D_
         label: 'Loan interest',_x000D_
         data: [0, 3],_x000D_
         backgroundColor: '#109618'_x000D_
      }, {_x000D_
         label: 'Depreciation of the vehicle',_x000D_
         data: [0, 2],_x000D_
         backgroundColor: '#109618'_x000D_
      }, {_x000D_
         label: 'Fuel',_x000D_
         data: [0, 1],_x000D_
         backgroundColor: '#dc3912'_x000D_
      }, {_x000D_
         label: 'Insurance and Breakdown cover',_x000D_
         data: [4, 0],_x000D_
         backgroundColor: '#3366cc'_x000D_
      }]_x000D_
   },_x000D_
   options: {_x000D_
      responsive: false,_x000D_
      legend: {_x000D_
         position: 'right' // place legend on the right side of chart_x000D_
      },_x000D_
      scales: {_x000D_
         xAxes: [{_x000D_
            stacked: true // this should be set to make the bars stacked_x000D_
         }],_x000D_
         yAxes: [{_x000D_
            stacked: true // this also.._x000D_
         }]_x000D_
      },_x000D_
      animation : {_x000D_
         onComplete : done_x000D_
      }      _x000D_
   }_x000D_
});_x000D_
_x000D_
function done(){_x000D_
    alert(chart.toBase64Image());_x000D_
}
_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.6.0/Chart.min.js"></script>_x000D_
<canvas id="ctx" width="700"></canvas>
_x000D_
_x000D_
_x000D_

What exactly does an #if 0 ..... #endif block do?

I'd like to add on for the #else case:

#if 0
   /* Code here will NOT be complied. */
#else
   /* Code will be compiled. */
#endif


#if 1
   /* Code will be complied. */
#else
   /* Code will NOT be compiled. */
#endif

ng-repeat: access key and value for each object in array of objects

In fact, your data is not well design. You'd better use something like :

$scope.steps = [
    {stepName: "companyName", isComplete: true},
    {stepName: "businessType", isComplete: true},
    {stepName: "physicalAddress", isComplete: true}
];

Then it is easy to do what you want :

<div ng-repeat="step in steps">
 Step {{step.stepName}} status : {{step.isComplet}}
</div>

Example: http://jsfiddle.net/rX7ba/

How to manually install a pypi module without pip/easy_install?

  1. Download the package
  2. unzip it if it is zipped
  3. cd into the directory containing setup.py
  4. If there are any installation instructions contained in documentation contianed herein, read and follow the instructions OTHERWISE
  5. type in python setup.py install

You may need administrator privileges for step 5. What you do here thus depends on your operating system. For example in Ubuntu you would say sudo python setup.py install

EDIT- thanks to kwatford (see first comment)

To bypass the need for administrator privileges during step 5 above you may be able to make use of the --user flag. In this way you can install the package only for the current user.

The docs say:

Files will be installed into subdirectories of site.USER_BASE (written as userbase hereafter). This scheme installs pure Python modules and extension modules in the same location (also known as site.USER_SITE). Here are the values for UNIX, including Mac OS X:

More details can be found here: http://docs.python.org/2.7/install/index.html

How to determine the encoding of text?

If you know the some content of the file you can try to decode it with several encoding and see which is missing. In general there is no way since a text file is a text file and those are stupid ;)

href image link download on click

If you are Using HTML5 you can add the attribute 'download' to your links.

<a href="/test.pdf" download>

http://www.w3schools.com/tags/att_a_download.asp

CodeIgniter - accessing $config variable in view

$this->config->item('config_var') did not work for my case.

I could only use the config_item('config_var'); to echo variables in the view

How do I UPDATE a row in a table or INSERT it if it doesn't exist?

Standard SQL provides the MERGE statement for this task. Not all DBMS support the MERGE statement.

How to compare dates in datetime fields in Postgresql?

@Nicolai is correct about casting and why the condition is false for any data. i guess you prefer the first form because you want to avoid date manipulation on the input string, correct? you don't need to be afraid:

SELECT *
FROM table
WHERE update_date >= '2013-05-03'::date
AND update_date < ('2013-05-03'::date + '1 day'::interval);

What are all the common ways to read a file in Ruby?

You can read the file all at once:

content = File.readlines 'file.txt'
content.each_with_index{|line, i| puts "#{i+1}: #{line}"}

When the file is large, or may be large, it is usually better to process it line-by-line:

File.foreach( 'file.txt' ) do |line|
  puts line
end

Sometimes you want access to the file handle though or control the reads yourself:

File.open( 'file.txt' ) do |f|
  loop do
    break if not line = f.gets
    puts "#{f.lineno}: #{line}"
  end
end

In case of binary files, you may specify a nil-separator and a block size, like so:

File.open('file.bin', 'rb') do |f|
  loop do
    break if not buf = f.gets(nil, 80)
    puts buf.unpack('H*')
  end
end

Finally you can do it without a block, for example when processing multiple files simultaneously. In that case the file must be explicitly closed (improved as per comment of @antinome):

begin
  f = File.open 'file.txt'
  while line = f.gets
    puts line
  end
ensure
  f.close
end

References: File API and the IO API.

How to convert column with dtype as object to string in Pandas Dataframe

Did you try assigning it back to the column?

df['column'] = df['column'].astype('str') 

Referring to this question, the pandas dataframe stores the pointers to the strings and hence it is of type 'object'. As per the docs ,You could try:

df['column_new'] = df['column'].str.split(',') 

Why is MySQL InnoDB insert so slow?

InnoDB has transaction support, you're not using explicit transactions so innoDB has to do a commit after each statement ("performs a log flush to disk for every insert").

Execute this command before your loop:

START TRANSACTION

and this after you loop

COMMIT

What is the HTML unicode character for a "tall" right chevron?

Use '›'

&rsaquo; -> single right angle quote. For single left angle quote, use &lsaquo;

Angular 2: Passing Data to Routes?

It changes in angular 2.1.0

In something.module.ts

import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { BlogComponent } from './blog.component';
import { AddComponent } from './add/add.component';
import { EditComponent } from './edit/edit.component';
import { RouterModule } from '@angular/router';
import { MaterialModule } from '@angular/material';
import { FormsModule } from '@angular/forms';
const routes = [
  {
    path: '',
    component: BlogComponent
  },
  {
    path: 'add',
    component: AddComponent
  },
  {
    path: 'edit/:id',
    component: EditComponent,
    data: {
      type: 'edit'
    }
  }

];
@NgModule({
  imports: [
    CommonModule,
    RouterModule.forChild(routes),
    MaterialModule.forRoot(),
    FormsModule
  ],
  declarations: [BlogComponent, EditComponent, AddComponent]
})
export class BlogModule { }

To get the data or params in edit component

import { Component, OnInit } from '@angular/core';
import { Router, ActivatedRoute, Params, Data } from '@angular/router';
@Component({
  selector: 'app-edit',
  templateUrl: './edit.component.html',
  styleUrls: ['./edit.component.css']
})
export class EditComponent implements OnInit {
  constructor(
    private route: ActivatedRoute,
    private router: Router

  ) { }
  ngOnInit() {

    this.route.snapshot.params['id'];
    this.route.snapshot.data['type'];

  }
}

How to create Python egg file

You are reading the wrong documentation. You want this: https://setuptools.readthedocs.io/en/latest/setuptools.html#develop-deploy-the-project-source-in-development-mode

  1. Creating setup.py is covered in the distutils documentation in Python's standard library documentation here. The main difference (for python eggs) is you import setup from setuptools, not distutils.

  2. Yep. That should be right.

  3. I don't think so. pyc files can be version and platform dependent. You might be able to open the egg (they should just be zip files) and delete .py files leaving .pyc files, but it wouldn't be recommended.

  4. I'm not sure. That might be “Development Mode”. Or are you looking for some “py2exe” or “py2app” mode?

How do I set a JLabel's background color?

For the Background, make sure you have imported java.awt.Color into your package.

In your main method, i.e. public static void main(String[] args), call the already imported method:

JLabel name_of_your_label=new JLabel("the title of your label");
name_of_your_label.setBackground(Color.the_color_you_wish);
name_of_your_label.setOpaque(true);

NB: Setting opaque will affect its visibility. Remember the case sensitivity in Java.

Python 2: AttributeError: 'list' object has no attribute 'strip'

strip() is a method for strings, you are calling it on a list, hence the error.

>>> 'strip' in dir(str)
True
>>> 'strip' in dir(list)
False

To do what you want, just do

>>> l = ['Facebook;Google+;MySpace', 'Apple;Android']
>>> l1 = [elem.strip().split(';') for elem in l]
>>> print l1
[['Facebook', 'Google+', 'MySpace'], ['Apple', 'Android']]

Since, you want the elements to be in a single list (and not a list of lists), you have two options.

  1. Create an empty list and append elements to it.
  2. Flatten the list.

To do the first, follow the code:

>>> l1 = []
>>> for elem in l:
        l1.extend(elem.strip().split(';'))  
>>> l1
['Facebook', 'Google+', 'MySpace', 'Apple', 'Android']

To do the second, use itertools.chain

>>> l1 = [elem.strip().split(';') for elem in l]
>>> print l1
[['Facebook', 'Google+', 'MySpace'], ['Apple', 'Android']]
>>> from itertools import chain
>>> list(chain(*l1))
['Facebook', 'Google+', 'MySpace', 'Apple', 'Android']

What is the equivalent of "none" in django templates?

You could try this:

{% if not profile.user.first_name.value %}
  <p> -- </p>
{% else %}
  {{ profile.user.first_name }} {{ profile.user.last_name }}
{% endif %}

This way, you're essentially checking to see if the form field first_name has any value associated with it. See {{ field.value }} in Looping over the form's fields in Django Documentation.

I'm using Django 3.0.

Running Command Line in Java

You can also watch the output like this:

final Process p = Runtime.getRuntime().exec("java -jar map.jar time.rel test.txt debug");

new Thread(new Runnable() {
    public void run() {
        BufferedReader input = new BufferedReader(new InputStreamReader(p.getInputStream()));
        String line = null;

        try {
            while ((line = input.readLine()) != null)
                System.out.println(line);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}).start();

p.waitFor();

And don't forget, if you are running a windows command, you need to put cmd /c in front of your command.

EDIT: And for bonus points, you can also use ProcessBuilder to pass input to a program:

String[] command = new String[] {
        "choice",
        "/C",
        "YN",
        "/M",
        "\"Press Y if you're cool\""
};
String inputLine = "Y";

ProcessBuilder pb = new ProcessBuilder(command);
pb.redirectErrorStream(true);
Process p = pb.start();
BufferedReader reader = new BufferedReader(new InputStreamReader(p.getInputStream()));
BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(p.getOutputStream()));

writer.write(inputLine);
writer.newLine();
writer.close();

String line;

while ((line = reader.readLine()) != null) {
    System.out.println(line);
}

This will run the windows command choice /C YN /M "Press Y if you're cool" and respond with a Y. So, the output will be:

Press Y if you're cool [Y,N]?Y

Docker command can't connect to Docker daemon

Perhaps this will help someone, as the error message is extremely unhelpful, and I had gone through all of the standard permission steps numerous times to no avail.

Docker occasionally leaves ghost environment variables in place that block access, despite your system otherwise being correctly set up. The following shell commands may make it accessible again, if you have had it running at one point and it just stopped cooperating after a reboot:

unset DOCKER_HOST
unset DOCKER_TLS_VERIFY
unset DOCKER_TLS_PATH
docker ps

I had a previously working docker install, and after rebooting my laptop it simply refused to work. Was correctly added to the docker user group, had the correct permissions on the socket, etc, but could still not run docker login, docker run ..., etc. This fixed it for me. Unfortunately I have to run this on each reboot. This is mentioned on a couple of github issues also as a workaround, although it seems like a bug that this is a persistent barrier to correct operation of Docker (note: I am on Arch Linux, not OSX, but this was the same issue for me).

How to cherry pick from 1 branch to another

When you cherry-pick, it creates a new commit with a new SHA. If you do:

git cherry-pick -x <sha>

then at least you'll get the commit message from the original commit appended to your new commit, along with the original SHA, which is very useful for tracking cherry-picks.

Error message 'Unable to load one or more of the requested types. Retrieve the LoaderExceptions property for more information.'

I had this issue while referencing a nuget package and later on using the remove option to delete it from my project. I had to clear the bin folder after battling with the issue for hours. To avoid this its advisable to use nuget to uninstall unwanted packages rather than the usual delete

Finding common rows (intersection) in two Pandas dataframes

My understanding is that this question is better answered over in this post.

But briefly, the answer to the OP with this method is simply:

s1 = pd.merge(df1, df2, how='inner', on=['user_id'])

Which gives s1 with 5 columns: user_id and the other two columns from each of df1 and df2.

TypeError("'bool' object is not iterable",) when trying to return a Boolean

Look at the traceback:

Traceback (most recent call last):
  File "C:\Python33\lib\site-packages\bottle.py", line 821, in _cast
    out = iter(out)
TypeError: 'bool' object is not iterable

Your code isn't iterating the value, but the code receiving it is.

The solution is: return an iterable. I suggest that you either convert the bool to a string (str(False)) or enclose it in a tuple ((False,)).

Always read the traceback: it's correct, and it's helpful.

How do I convert a column of text URLs into active hyperlinks in Excel?

You can insert the formula =HYPERLINK(<your_cell>,<your_cell>) to the adjacent cell and drag it along all the way to the bottom. This will give you a column with all the links. Now, you can select your original column by clicking on the header, right-click, and select Hide.

Cannot find firefox binary in PATH. Make sure firefox is installed

I didn't see the C# anwer to this question here. The trick is to set the BrowserExecutableLocation property on a FirefoxOptions instance, and pass that into the driver constructor:

        var opt = new FirefoxOptions
        {
            BrowserExecutableLocation = @"c:\program files\mozilla firefox\firefox.exe"
        };
        var driver = new FirefoxDriver(opt);

Metadata file '.dll' could not be found

My instance of the problem was caused by a common project that had a duplicate class name in it (under a different filename). It is strange that Visual Studio could not detect that and instead just blew up the build process.

In Maven how to exclude resources from the generated jar?

Another possibility is to use the Maven Shade Plugin, e.g. to exclude a logging properties file used only locally in your IDE:

<plugin>
    <groupId>org.apache.maven.plugins</groupId>
    <artifactId>maven-shade-plugin</artifactId>
    <version>${maven-shade-plugin-version}</version>
    <executions>
        <execution>
            <phase>package</phase>
            <goals>
                <goal>shade</goal>
            </goals>
            <configuration>
                <filters>
                    <filter>
                        <artifact>*:*</artifact>
                        <excludes>
                            <exclude>log4j2.xml</exclude>
                        </excludes>
                    </filter>
                </filters>
            </configuration>
        </execution>
    </executions>
</plugin>

This will however exclude the files from every artifact, so it might not be feasible in every situation.

Angular ngClass and click event for toggling class

This should work for you.

In .html:

<div class="my_class" (click)="clickEvent()"  
    [ngClass]="status ? 'success' : 'danger'">                
     Some content
</div>

In .ts:

status: boolean = false;
clickEvent(){
    this.status = !this.status;       
}

Bootstrap 3 Carousel Not Working

Well, Bootstrap Carousel has various parameters to control.

i.e.

Interval: Specifies the delay (in milliseconds) between each slide.

pause: Pauses the carousel from going through the next slide when the mouse pointer enters the carousel, and resumes the sliding when the mouse pointer leaves the carousel.

wrap: Specifies whether the carousel should go through all slides continuously, or stop at the last slide

For your reference:

enter image description here

Fore more details please click here...

Hope this will help you :)

Note: This is for the further help.. I mean how can you customise or change default behaviour once carousel is loaded.

Getting the application's directory from a WPF application

One method:

System.AppDomain.CurrentDomain.BaseDirectory

Another way to do it would be:

System.IO.Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName)

How to check if "Radiobutton" is checked?

If you need for espresso test the solutions is like this :

onView(withId(id)).check(matches(isChecked()));

Bye,

Add carriage return to a string

string s2 = s1.Replace(",", "," + Environment.NewLine);

Also, just from a performance perspective, here's how the three current solutions I've seen stack up over 100k iterations:

ReplaceWithConstant           - Ms: 328, Ticks: 810908
ReplaceWithEnvironmentNewLine - Ms: 310, Ticks: 766955 
SplitJoin                     - Ms: 483, Ticks: 1192545

ReplaceWithConstant:

string s2 = s1.Replace(",", ",\n");

ReplaceWithEnvironmentNewLine:

string s2 = s1.Replace(",", "," + Environment.NewLine);

SplitJoin:

string s2 = String.Join("," + Environment.NewLine, s1.Split(','));

ReplaceWithEnvironmentNewLine and ReplaceWithConstant are within the margin of error of each other, so there's functionally no difference.

Using Environment.NewLine should be preferred over "\n" for the sake readability and consistency similar to using String.Empty instead of "".

Can local storage ever be considered secure?

As an exploration of this topic, I have a presentation titled "Securing TodoMVC Using the Web Cryptography API" (video, code).

It uses the Web Cryptography API to store the todo list encrypted in localStorage by password protecting the application and using a password derived key for encryption. If you forget or lose the password, there is no recovery. (Disclaimer - it was a POC and not intended for production use.)

As the other answers state, this is still susceptible to XSS or malware installed on the client computer. However, any sensitive data would also be in memory when the data is stored on the server and the application is in use. I suggest that offline support may be the compelling use case.

In the end, encrypting localStorage probably only protects the data from attackers that have read only access to the system or its backups. It adds a small amount of defense in depth for OWASP Top 10 item A6-Sensitive Data Exposure, and allows you to answer "Is any of this data stored in clear text long term?" correctly.

Getting the last element of a split string array

var item = "one,two,three";
var lastItem = item.split(",").pop();
console.log(lastItem); // three

Return Bit Value as 1/0 and NOT True/False in SQL Server

This can be changed to 0/1 through using CASE WHEN like this example:

SELECT 
 CASE WHEN SchemaName.TableName.BitFieldName = 'true' THEN 1 ELSE 0 END AS 'bit Value' 
 FROM SchemaName.TableName

What is the use of ObservableCollection in .net?

One of the biggest uses is that you can bind UI components to one, and they'll respond appropriately if the collection's contents change. For example, if you bind a ListView's ItemsSource to one, the ListView's contents will automatically update if you modify the collection.

EDIT: Here's some sample code from MSDN: http://msdn.microsoft.com/en-us/library/ms748365.aspx

In C#, hooking the ListBox to the collection could be as easy as

listBox.ItemsSource = NameListData;

though if you haven't hooked the list up as a static resource and defined NameItemTemplate you may want to override PersonName's ToString(). For example:

public override ToString()
{
    return string.Format("{0} {1}", this.FirstName, this.LastName);
}

How do I run a file on localhost?

I'm not really sure what you mean, so I'll start simply:

If the file you're trying to "run" is static content, like HTML or even Javascript, you don't need to run it on "localhost"... you should just be able to open it from wherever it is on your machine in your browser.

If it is a piece of server-side code (ASP[.NET], php, whatever else, uou need to be running either a web server, or if you're using Visual Studio, start the development server for your application (F5 to debug, or CTRL+F5 to start without debugging).

If you're using a web server, you'll need to have a web site configured with the home directory set to the directory the file is in (or, just put the file in whatever home directory is configured).

If you're using Visual Studio, the file just needs to be in your project.

How do I dynamically change the content in an iframe using jquery?

If you just want to change where the iframe points to and not the actual content inside the iframe, you would just need to change the src attribute.

 $("#myiframe").attr("src", "newwebpage.html");

JWT (JSON Web Token) automatic prolongation of expiration

I solved this problem by adding a variable in the token data:

softexp - I set this to 5 mins (300 seconds)

I set expiresIn option to my desired time before the user will be forced to login again. Mine is set to 30 minutes. This must be greater than the value of softexp.

When my client side app sends request to the server API (where token is required, eg. customer list page), the server checks whether the token submitted is still valid or not based on its original expiration (expiresIn) value. If it's not valid, server will respond with a status particular for this error, eg. INVALID_TOKEN.

If the token is still valid based on expiredIn value, but it already exceeded the softexp value, the server will respond with a separate status for this error, eg. EXPIRED_TOKEN:

(Math.floor(Date.now() / 1000) > decoded.softexp)

On the client side, if it received EXPIRED_TOKEN response, it should renew the token automatically by sending a renewal request to the server. This is transparent to the user and automatically being taken care of the client app.

The renewal method in the server must check if the token is still valid:

jwt.verify(token, secret, (err, decoded) => {})

The server will refuse to renew tokens if it failed the above method.

Run multiple python scripts concurrently

You try the following ways to run the multiple python scripts:

  import os
  print "Starting script1"
  os.system("python script1.py arg1 arg2 arg3")
  print "script1 ended"
  print "Starting script2"
  os.system("python script2.py arg1 arg2 arg3")
  print "script2 ended"

Note: The execution of multiple scripts depends purely underlined operating system, and it won't be concurrent, I was new comer in Python when I answered it.

Update: I found a package: https://pypi.org/project/schedule/ Above package can be used to run multiple scripts and function, please check this and maybe on weekend will provide some example too.

i.e:

 import schedule
 import time
 import script1, script2

 def job():
     print("I'm working...")

 schedule.every(10).minutes.do(job)
 schedule.every().hour.do(job)
 schedule.every().day.at("10:30").do(job)
 schedule.every(5).to(10).days.do(job)
 schedule.every().monday.do(job)
 schedule.every().wednesday.at("13:15").do(job)

 while True:
     schedule.run_pending()
     time.sleep(1)

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

Even though, I have been using 400 to represent logical errors also, I have to say that returning 400 is wrong in this case because of the way the spec reads. Here is why i think so, the logical error could be that a relationship with another entity was failing or not satisfied and making changes to the other entity could cause the same exact to pass later. Like trying to (completely hypothetical) add an employee as a member of a department when that employee does not exist (logical error). Adding employee as member request could fail because employee does not exist. But the same exact request could pass after the employee has been added to the system.

Just my 2 cents ... We need lawyers & judges to interpret the language in the RFC these days :)

Thank You, Vish

How to reload apache configuration for a site without restarting apache?

Late answer here, but if you search /etc/init.d/apache2 for 'reload', you'll find something like this:

do_reload() {
        if apache_conftest; then
                if ! pidofproc -p $PIDFILE "$DAEMON" > /dev/null 2>&1 ; then
                        APACHE2_INIT_MESSAGE="Apache2 is not running"
                        return 2
                fi
                $APACHE2CTL graceful > /dev/null 2>&1
                return $?
        else
                APACHE2_INIT_MESSAGE="The apache2$DIR_SUFFIX configtest failed. Not doing anything."
                return 2
        fi
}

Basically, what the answers that suggest using init.d, systemctl, etc are invoking is a thin wrapper that says:

  • check the apache config
  • if it's good, run apachectl graceful (swallowing the output, and forwarding the exit code)

This suggests that @Aruman's answer is also correct, provided you are confident there are no errors in your configuration or have already run apachctl configtest manually.

The apache documentation also supplies the same command for a graceful restart (apachectl -k graceful), and some more color on the behavior thereof.

Open an html page in default browser with VBA?

If you want a more robust solution with ShellExecute that will open ANY file, folder or URL using the default OS associated program to do so, here is a function taken from http://access.mvps.org/access/api/api0018.htm:

'************ Code Start **********
' This code was originally written by Dev Ashish.
' It is not to be altered or distributed,
' except as part of an application.
' You are free to use it in any application,
' provided the copyright notice is left unchanged.
'
' Code Courtesy of
' Dev Ashish
'
Private Declare Function apiShellExecute Lib "shell32.dll" _
    Alias "ShellExecuteA" _
    (ByVal hwnd As Long, _
    ByVal lpOperation As String, _
    ByVal lpFile As String, _
    ByVal lpParameters As String, _
    ByVal lpDirectory As String, _
    ByVal nShowCmd As Long) _
    As Long

'***App Window Constants***
Public Const WIN_NORMAL = 1         'Open Normal
Public Const WIN_MAX = 3            'Open Maximized
Public Const WIN_MIN = 2            'Open Minimized

'***Error Codes***
Private Const ERROR_SUCCESS = 32&
Private Const ERROR_NO_ASSOC = 31&
Private Const ERROR_OUT_OF_MEM = 0&
Private Const ERROR_FILE_NOT_FOUND = 2&
Private Const ERROR_PATH_NOT_FOUND = 3&
Private Const ERROR_BAD_FORMAT = 11&

'***************Usage Examples***********************
'Open a folder:     ?fHandleFile("C:\TEMP\",WIN_NORMAL)
'Call Email app:    ?fHandleFile("mailto:[email protected]",WIN_NORMAL)
'Open URL:          ?fHandleFile("http://home.att.net/~dashish", WIN_NORMAL)
'Handle Unknown extensions (call Open With Dialog):
'                   ?fHandleFile("C:\TEMP\TestThis",Win_Normal)
'Start Access instance:
'                   ?fHandleFile("I:\mdbs\CodeNStuff.mdb", Win_NORMAL)
'****************************************************

Function fHandleFile(stFile As String, lShowHow As Long)
Dim lRet As Long, varTaskID As Variant
Dim stRet As String
    'First try ShellExecute
    lRet = apiShellExecute(hWndAccessApp, vbNullString, _
            stFile, vbNullString, vbNullString, lShowHow)

    If lRet > ERROR_SUCCESS Then
        stRet = vbNullString
        lRet = -1
    Else
        Select Case lRet
            Case ERROR_NO_ASSOC:
                'Try the OpenWith dialog
                varTaskID = Shell("rundll32.exe shell32.dll,OpenAs_RunDLL " _
                        & stFile, WIN_NORMAL)
                lRet = (varTaskID <> 0)
            Case ERROR_OUT_OF_MEM:
                stRet = "Error: Out of Memory/Resources. Couldn't Execute!"
            Case ERROR_FILE_NOT_FOUND:
                stRet = "Error: File not found.  Couldn't Execute!"
            Case ERROR_PATH_NOT_FOUND:
                stRet = "Error: Path not found. Couldn't Execute!"
            Case ERROR_BAD_FORMAT:
                stRet = "Error:  Bad File Format. Couldn't Execute!"
            Case Else:
        End Select
    End If
    fHandleFile = lRet & _
                IIf(stRet = "", vbNullString, ", " & stRet)
End Function
'************ Code End **********

Just put this into a separate module and call fHandleFile() with the right parameters.

PHP MySQL Google Chart JSON - Complete Example

Some might encounter this error either locally or on the server:

syntax error var data = new google.visualization.DataTable(<?=$jsonTable?>);

This means that their environment does not support short tags the solution is to use this instead:

<?php echo $jsonTable; ?>

And everything should work fine!

What is the difference between RTP or RTSP in a streaming server?

You are getting something wrong... RTSP is a realtime streaming protocol. Meaning, you can stream whatever you want in real time. So you can use it to stream LIVE content (no matter what it is, video, audio, text, presentation...). RTP is a transport protocol which is used to transport media data which is negotiated over RTSP.

You use RTSP to control media transmission over RTP. You use it to setup, play, pause, teardown the stream...

So, if you want your server to just start streaming when the URL is requested, you can implement some sort of RTP-only server. But if you want more control and if you are streaming live video, you must use RTSP, because it transmits SDP and other important decoding data.

Read the documents I linked here, they are a good starting point.

Lock screen orientation (Android)

inside the Android manifest file of your project, find the activity declaration of whose you want to fix the orientation and add the following piece of code ,

android:screenOrientation="landscape"

for landscape orientation and for portrait add the following code,

android:screenOrientation="portrait"

Read XML file using javascript

You can use below script for reading child of the above xml. It will work with IE and Mozila Firefox both.

<script type="text/javascript">

function readXml(xmlFile){

var xmlDoc;

if(typeof window.DOMParser != "undefined") {
    xmlhttp=new XMLHttpRequest();
    xmlhttp.open("GET",xmlFile,false);
    if (xmlhttp.overrideMimeType){
        xmlhttp.overrideMimeType('text/xml');
    }
    xmlhttp.send();
    xmlDoc=xmlhttp.responseXML;
}
else{
    xmlDoc = new ActiveXObject("Microsoft.XMLDOM");
    xmlDoc.async="false";
    xmlDoc.load(xmlFile);
}
var tagObj=xmlDoc.getElementsByTagName("marker");
var typeValue = tagObj[0].getElementsByTagName("type")[0].childNodes[0].nodeValue;
var titleValue = tagObj[0].getElementsByTagName("title")[0].childNodes[0].nodeValue;
}
</script>

Best way to define private methods for a class in Objective-C

There isn't really a "private method" in Objective-C, if the runtime can work out which implementation to use it will do it. But that's not to say that there aren't methods which aren't part of the documented interface. For those methods I think that a category is fine. Rather than putting the @interface at the top of the .m file like your point 2, I'd put it into its own .h file. A convention I follow (and have seen elsewhere, I think it's an Apple convention as Xcode now gives automatic support for it) is to name such a file after its class and category with a + separating them, so @interface GLObject (PrivateMethods) can be found in GLObject+PrivateMethods.h. The reason for providing the header file is so that you can import it in your unit test classes :-).

By the way, as far as implementing/defining methods near the end of the .m file is concerned, you can do that with a category by implementing the category at the bottom of the .m file:

@implementation GLObject(PrivateMethods)
- (void)secretFeature;
@end

or with a class extension (the thing you call an "empty category"), just define those methods last. Objective-C methods can be defined and used in any order in the implementation, so there's nothing to stop you putting the "private" methods at the end of the file.

Even with class extensions I will often create a separate header (GLObject+Extension.h) so that I can use those methods if required, mimicking "friend" or "protected" visibility.

Since this answer was originally written, the clang compiler has started doing two passes for Objective-C methods. This means you can avoid declaring your "private" methods completely, and whether they're above or below the calling site they'll be found by the compiler.

Android open pdf file

String dir="/Attendancesystem";

 public void displaypdf() {

        File file = null;
            file = new File(Environment.getExternalStorageDirectory()+dir+ "/sample.pdf");
        Toast.makeText(getApplicationContext(), file.toString() , Toast.LENGTH_LONG).show();
        if(file.exists()) {
            Intent target = new Intent(Intent.ACTION_VIEW);
            target.setDataAndType(Uri.fromFile(file), "application/pdf");
            target.setFlags(Intent.FLAG_ACTIVITY_NO_HISTORY);

            Intent intent = Intent.createChooser(target, "Open File");
            try {
                startActivity(intent);
            } catch (ActivityNotFoundException e) {
                // Instruct the user to install a PDF reader here, or something
            }
        }
        else
            Toast.makeText(getApplicationContext(), "File path is incorrect." , Toast.LENGTH_LONG).show();
    }

ActivityCompat.requestPermissions not showing dialog box

The above information is good, but setting targetSdkVersion to 23 (or higher) is critical for Android to interpret the <uses-permission> tag in the manifest as "I will ask in code" instead of "I demand upon installation." Lots of sources will tell you that you need the <uses-permission> tag, but no one says why and if you don't have that value set, you're going to be as confused as I was for hours on end.

Find what 2 numbers add to something and multiply to something

That's basically a set of 2 simultaneous equations:

x*y = a
X+y = b

(using the mathematical convention of x and y for the variables to solve and a and b for arbitrary constants).

But the solution involves a quadratic equation (because of the x*y), so depending on the actual values of a and b, there may not be a solution, or there may be multiple solutions.

Return value from nested function in Javascript

Just FYI, Geocoder is asynchronous so the accepted answer while logical doesn't really work in this instance. I would prefer to have an outside object that acts as your updater.

var updater = {};

function geoCodeCity(goocoord) { 
    var geocoder = new google.maps.Geocoder();
    geocoder.geocode({
        'latLng': goocoord
    }, function(results, status) {
        if (status == google.maps.GeocoderStatus.OK) {
            updater.currentLocation = results[1].formatted_address;
        } else {
            if (status == "ERROR") { 
                    console.log(status);
                }
        }
    });
};

How to convert Nonetype to int or string?

I've successfully used int(x or 0) for this type of error, so long as None should equate to 0 in the logic. Note that this will also resolve to 0 in other cases where testing x returns False. e.g. empty list, set, dictionary or zero length string. Sorry, Kindall already gave this answer.

Determining type of an object in ruby

I would say "Yes". As "Matz" had said something like this in one of his talks, "Ruby objects have no types." Not all of it but the part that he is trying to get across to us. Why would anyone have said "Everything is an Object" then? To add he said "Data has Types not objects".

So we might enjoy this.

https://www.youtube.com/watch?v=1l3U1X3z0CE

But Ruby doesn't care to much about the type of object just the class. We use classes not types. All data then has a class.

12345.class

'my string'.class

They may also have ancestors

Object.ancestors

They also have meta classes but I'll save you the details on that.

Once you know the class then you'll be able to lookup what methods you may use for it. That's where the "data type" is needed. If you really want to get into details the look up...

"The Ruby Object Model"

This is the term used for how Ruby handles objects. It's all internal so you don't really see much of this but it's nice to know. But that's another topic.

Yes! The class is the data type. Objects have classes and data has types. So if you know about data bases then you know there are only a finite set of types.

text blocks numbers

Swift error : signal SIGABRT how to solve it

If you run into this in Xcode 10 you will have to clean before build. Or, switch to the legacy build system. File -> Workspace Settings... -> Build System: Legacy Build System.

How to Correctly Check if a Process is running and Stop it

If you don't need to display exact result "running" / "not runnuning", you could simply:

ps notepad -ErrorAction SilentlyContinue | kill -PassThru

If the process was not running, you'll get no results. If it was running, you'll receive get-process output, and the process will be stopped.

Using LINQ to concatenate strings

Here is the combined Join/Linq approach I settled on after looking at the other answers and the issues addressed in a similar question (namely that Aggregate and Concatenate fail with 0 elements).

string Result = String.Join(",", split.Select(s => s.Name));

or (if s is not a string)

string Result = String.Join(",", split.Select(s => s.ToString()));

  • Simple
  • easy to read and understand
  • works for generic elements
  • allows using objects or object properties
  • handles the case of 0-length elements
  • could be used with additional Linq filtering
  • performs well (at least in my experience)
  • doesn't require (manual) creation of an additional object (e.g. StringBuilder) to implement

And of course Join takes care of the pesky final comma that sometimes sneaks into other approaches (for, foreach), which is why I was looking for a Linq solution in the first place.

Convert long/lat to pixel x/y on a given picture

The translation you are addressing has to do with Map Projection, which is how the spherical surface of our world is translated into a 2 dimensional rendering. There are multiple ways (projections) to render the world on a 2-D surface.

If your maps are using just a specific projection (Mercator being popular), you should be able to find the equations, some sample code, and/or some library (e.g. one Mercator solution - Convert Lat/Longs to X/Y Co-ordinates. If that doesn't do it, I'm sure you can find other samples - https://stackoverflow.com/search?q=mercator. If your images aren't map(s) using a Mercator projection, you'll need to determine what projection it does use to find the right translation equations.

If you are trying to support multiple map projections (you want to support many different maps that use different projections), then you definitely want to use a library like PROJ.4, but again I'm not sure what you'll find for Javascript or PHP.

React: Expected an assignment or function call and instead saw an expression

In my case the problem was the line with default instructions in switch block:

  handlePageChange = ({ btnType}) => {
    let { page } = this.state;
    switch (btnType) {
      case 'next':
        this.updatePage(page + 1);
        break;
      case 'prev':
        this.updatePage(page - 1);
        break;
      default: null;
    } 
  }

Instead of

default: null;

The line

default: ;

worked for me.

Always show vertical scrollbar in <select>

add:

overflow-y: scroll

in your css bud.

Select columns from result set of stored procedure

Here's a link to a pretty good document explaining all the different ways to solve your problem (although a lot of them can't be used since you can't modify the existing stored procedure.)

How to Share Data Between Stored Procedures

Gulzar's answer will work (it is documented in the link above) but it's going to be a hassle to write (you'll need to specify all 80 column names in your @tablevar(col1,...) statement. And in the future if a column is added to the schema or the output is changed it will need to be updated in your code or it will error out.

How to check db2 version

In z/OS while on version 10, use of CURRENT APPLICATION COMPATIBILITY is not allowed. You will have to resort to:

SELECT GETVARIABLE('SYSIBM.VERSION') AS VERSION,
       GETVARIABLE('SYSIBM.NEWFUN')  AS COMPATIBILITY
FROM SYSIBM.SYSDUMMY1;

Here is a link to all the variables available: https://www.ibm.com/support/knowledgecenter/SSEPEK_12.0.0/sqlref/src/tpc/db2z_refs2builtinsessionvars.html#db2z_refs2builtinsessionvars

Recursive search and replace in text files on Mac and Linux

A version that works on both Linux and Mac OS X (by adding the -e switch to sed):

export LC_CTYPE=C LANG=C
find . -name '*.txt' -print0 | xargs -0 sed -i -e 's/this/that/g'

How to close a thread from within?

If you want force stop your thread: thread._Thread_stop() For me works very good.

How to send string from one activity to another?

For those people who use Kotlin do this instead:

  1. Create a method with a parameter containing String Object.
  2. Navigate to another Activity

For Example,


// * The Method I Mentioned Above 
private fun parseTheValue(@NonNull valueYouWantToParse: String)
{
     val intent = Intent(this, AnotherActivity::class.java)
     intent.putExtra("value", valueYouWantToParse)
     intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
     startActivity(intent)
     this.finish()
}

Then just call parseTheValue("the String that you want to parse")

e.g,

val theValue: String
 parseTheValue(theValue)

then in the other activity,

val value: Bundle = intent.extras!!
// * enter the `name` from the `@param`
val str: String = value.getString("value").toString()

// * For testing
println(str)

Hope This Help, Happy Coding!

~ Kotlin Code Added By John Melody~

Android: failed to convert @drawable/picture into a drawable

If you have the naming conventions right, then just go to File -> Invalidate Caches / Restart..

And press Invalidate Caches / Restart..

This helped in my case.

C# winforms combobox dynamic autocomplete

Take 2. My answer below didn't get me all the way to the desired result, but it may still be useful to somebody. The auto-select feature of the ComboBox was causing me major pain. This one uses a TextBox sitting over the top of a ComboBox, allowing me to ignore whatever appears in the ComboBox itself and just respond to the selection changed event.

  1. Create Form
  2. Add ComboBox
    • Set desired size and location
    • Set DropDownStyle to DropDown
    • Set TabStop to false
    • Set DisplayMember to Value (I'm using a list of KeyValuePairs)
    • Set ValueMember to Key
  3. Add Panel
    • Set to same size as ComboBox
    • Cover ComboBox with the Panel (This accounts for the standard ComboBox being taller than the standard TextBox)
  4. Add TextBox
    • Place TextBox over the top of the Panel
    • Align bottom of the TextBox with the bottom of Panel/ComboBox

Code behind

public partial class TestForm : Form
{
    // Custom class for managing calls to an external address finder service
    private readonly AddressFinder _addressFinder;

    // Events for handling async calls to address finder service
    private readonly AddressSuggestionsUpdatedEventHandler _addressSuggestionsUpdated;
    private delegate void AddressSuggestionsUpdatedEventHandler(object sender, AddressSuggestionsUpdatedEventArgs e);

    public TestForm()
    {
        InitializeComponent();

        _addressFinder = new AddressFinder(new AddressFinderConfigurationProvider());
        _addressSuggestionsUpdated += AddressSuggestions_Updated;
    }

    private void textBox1_PreviewKeyDown(object sender, PreviewKeyDownEventArgs e)
    {
        if (e.KeyCode == Keys.Tab)
        {
            comboBox1_SelectionChangeCommitted(sender, e);
            comboBox1.DroppedDown = false;
        }
    }

    private void textBox1_KeyDown(object sender, KeyEventArgs e)
    {
        if (e.KeyCode == Keys.Up)
        {
            if (comboBox1.Items.Count > 0)
            {
                if (comboBox1.SelectedIndex > 0)
                {
                    comboBox1.SelectedIndex--;
                }
            }

            e.Handled = true;
        }
        else if (e.KeyCode == Keys.Down)
        {
            if (comboBox1.Items.Count > 0)
            {
                if (comboBox1.SelectedIndex < comboBox1.Items.Count - 1)
                {
                    comboBox1.SelectedIndex++;
                }
            }

            e.Handled = true;
        }
        else if (e.KeyCode == Keys.Enter)
        {
            comboBox1_SelectionChangeCommitted(sender, e);
            comboBox1.DroppedDown = false;

            textBox1.SelectionStart = textBox1.TextLength;

            e.Handled = true;
        }
    }

    private void textBox1_KeyPress(object sender, KeyPressEventArgs e)
    {
        if (e.KeyChar == '\r')  // Enter key
        {
            e.Handled = true;
            return;
        }

        if (char.IsControl(e.KeyChar) && e.KeyChar != '\b') // Backspace key
        {
            return;
        }

        if (textBox1.Text.Length > 1)
        {
            Task.Run(() => GetAddressSuggestions(textBox1.Text));
        }
    }

    private void comboBox1_SelectionChangeCommitted(object sender, EventArgs e)
    {
        if (comboBox1.Items.Count > 0 &&
            comboBox1.SelectedItem.IsNotNull() &&
            comboBox1.SelectedItem is KeyValuePair<string, string>)
        {
            var selectedItem = (KeyValuePair<string, string>)comboBox1.SelectedItem;

            textBox1.Text = selectedItem.Value;

            // Do Work with selectedItem
        }
    }

    private async Task GetAddressSuggestions(string searchString)
    {
        var addressSuggestions = await _addressFinder.CompleteAsync(searchString).ConfigureAwait(false);

        if (_addressSuggestionsUpdated.IsNotNull())
        {
            _addressSuggestionsUpdated.Invoke(this, new AddressSuggestionsUpdatedEventArgs(addressSuggestions));
        }
    }

    private void AddressSuggestions_Updated(object sender, AddressSuggestionsUpdatedEventArgs eventArgs)
    {
        try
        {
            ThreadingHelper.BeginUpdate(comboBox1);

            ThreadingHelper.ClearItems(comboBox1);

            if (eventArgs.AddressSuggestions.Count > 0)
            {
                foreach (var addressSuggestion in eventArgs.AddressSuggestions)
                {
                    var item = new KeyValuePair<string, string>(addressSuggestion.Key, addressSuggestion.Value.ToUpper());
                    ThreadingHelper.AddItem(comboBox1, item);
                }

                ThreadingHelper.SetDroppedDown(comboBox1, true);
                ThreadingHelper.SetVisible(comboBox1, true);
            }
            else
            {
                ThreadingHelper.SetDroppedDown(comboBox1, false);
            }
        }
        finally
        {
            ThreadingHelper.EndUpdate(comboBox1);
        }
    }

    private class AddressSuggestionsUpdatedEventArgs : EventArgs
    {
        public IList<KeyValuePair<string, string>> AddressSuggestions { get; }

        public AddressSuggestionsUpdatedEventArgs(IList<KeyValuePair<string, string>> addressSuggestions)
        {
            AddressSuggestions = addressSuggestions;
        }
    }
}

You may or may not have issues with setting the DroppedDown property of the ComboBox. I eventually just wrapped it up in a try block with an empty catch block. Not a great solution, but it works.

Please see my other answer below for info on ThreadingHelpers.

Enjoy.

Is true == 1 and false == 0 in JavaScript?

Try the strict equality comparison:

if(1 === true)
    document.write("oh!!! that's true");  //**this is not displayed**

The == operator does conversion from one type to another, the === operator doesn't.

.Net picking wrong referenced assembly version

This error was somewhat misleading - I was loading some DLLs that required x64 architecture to be specified. In the .csproj file:

<PropertyGroup Condition="'$(Configuration)|$(Platform)' == 'Release-ABC|AnyCPU'">
    <OutputPath>bin\Release-ABC</OutputPath>
    <PlatformTarget>x64</PlatformTarget>
</PropertyGroup>

A missing PlatformTarget caused this error.

How to run JUnit tests with Gradle?

If you want to add a sourceSet for testing in addition to all the existing ones, within a module regardless of the active flavor:

sourceSets {
    test {
        java.srcDirs += [
                'src/customDir/test/kotlin'
        ]
        print(java.srcDirs)   // Clean
    }
}

Pay attention to the operator += and if you want to run integration tests change test to androidTest.

GL

Parsing huge logfiles in Node.js - read in line-by-line

Apart from read the big file line by line, you also can read it chunk by chunk. For more refer to this article

var offset = 0;
var chunkSize = 2048;
var chunkBuffer = new Buffer(chunkSize);
var fp = fs.openSync('filepath', 'r');
var bytesRead = 0;
while(bytesRead = fs.readSync(fp, chunkBuffer, 0, chunkSize, offset)) {
    offset += bytesRead;
    var str = chunkBuffer.slice(0, bytesRead).toString();
    var arr = str.split('\n');

    if(bytesRead = chunkSize) {
        // the last item of the arr may be not a full line, leave it to the next chunk
        offset -= arr.pop().length;
    }
    lines.push(arr);
}
console.log(lines);

C99 stdint.h header and MS Visual Studio

Microsoft do not support C99 and haven't announced any plans to. I believe they intend to track C++ standards but consider C as effectively obsolete except as a subset of C++.

New projects in Visual Studio 2003 and later have the "Compile as C++ Code (/TP)" option set by default, so any .c files will be compiled as C++.

What is meaning of negative dbm in signal strength?

The power in dBm is the 10 times the logarithm of the ratio of actual Power/1 milliWatt.

dBm stands for "decibel milliwatts". It is a convenient way to measure power. The exact formula is

P(dBm) = 10 · log10( P(W) / 1mW ) 

where

P(dBm) = Power expressed in dBm   
P(W) = the absolute power measured in Watts   
mW = milliWatts   
log10 = log to base 10

From this formula, the power in dBm of 1 Watt is 30 dBm. Because the calculation is logarithmic, every increase of 3dBm is approximately equivalent to doubling the actual power of a signal.

There is a conversion calculator and a comparison table here. There is also a comparison table on the Wikipedia english page, but the value it gives for mobile networks is a bit off.

Your actual question was "does the - sign count?"

The answer is yes, it does.

-85 dBm is less powerful (smaller) than -60 dBm. To understand this, you need to look at negative numbers. Alternatively, think about your bank account. If you owe the bank 85 dollars/rands/euros/rupees (-85), you're poorer than if you only owe them 65 (-65), i.e. -85 is smaller than -65. Also, in temperature measurements, -85 is colder than -65 degrees.

Signal strengths for mobile networks are always negative dBm values, because the transmitted network is not strong enough to give positive dBm values.

How will this affect your location finding? I have no idea, because I don't know what technology you are using to estimate the location. The values you quoted correspond roughly to a 5 bar network in GSM, UMTS or LTE, so you shouldn't have be having any problems due to network strength.

Oracle database: How to read a BLOB?

What client do you use? .Net, Java, Ruby, SQLPLUS, SQL DEVELOPER? Where did you write that simple select statement?

And why do you want to read the content of the blob, a blob contains binary data so that data is unreadable. You should use a clob instead of a blob if you want to store text instead of binary content.

I suggest that you download SQL DEVELOPER: http://www.oracle.com/technetwork/developer-tools/sql-developer/overview/index.html . With SQL DEVELOPER you can see the content.

What is the best way to seed a database in Rails?

factory_bot sounds like it will do what you are trying to achieve. You can define all the common attributes in the default definition and then override them at creation time. You can also pass an id to the factory:

Factory.define :theme do |t|
  t.background_color '0x000000'
  t.title_text_color '0x000000',
  t.component_theme_color '0x000000'
  t.carrier_select_color '0x000000'
  t.label_text_color '0x000000',
  t.join_upper_gradient '0x000000'
  t.join_lower_gradient '0x000000'
  t.join_text_color '0x000000',
  t.cancel_link_color '0x000000'
  t.border_color '0x000000'
  t.carrier_text_color '0x000000'
  t.public true
end

Factory(:theme, :id => 1, :name => "Lite", :background_color => '0xC7FFD5')
Factory(:theme, :id => 2, :name => "Metallic", :background_color => '0xC7FFD5')
Factory(:theme, :id => 3, :name => "Blues", :background_color => '0x0060EC')

When used with faker it can populate a database really quickly with associations without having to mess about with Fixtures (yuck).

I have code like this in a rake task.

100.times do
    Factory(:company, :address => Factory(:address), :employees => [Factory(:employee)])
end

Get the Selected value from the Drop down box in PHP

Posting it from my project.

<select name="parent" id="parent"><option value="0">None</option>
<?php
 $select="select=selected";
 $allparent=mysql_query("select * from tbl_page_content where parent='0'");
 while($parent=mysql_fetch_array($allparent))
   {?>
   <option value="<?= $parent['id']; ?>" <?php if( $pageDetail['parent']==$parent['id'] ) { echo($select); }?>><?= $parent['name']; ?></option>
  <?php 
   }
  ?></select>

Difference between thread's context class loader and normal classloader

This does not answer the original question, but as the question is highly ranked and linked for any ContextClassLoader query, I think it is important to answer the related question of when the context class loader should be used. Short answer: never use the context class loader! But set it to getClass().getClassLoader() when you have to call a method that is missing a ClassLoader parameter.

When code from one class asks to load another class, the correct class loader to use is the same class loader as the caller class (i.e., getClass().getClassLoader()). This is the way things work 99.9% of the time because this is what the JVM does itself the first time you construct an instance of a new class, invoke a static method, or access a static field.

When you want to create a class using reflection (such as when deserializing or loading a configurable named class), the library that does the reflection should always ask the application which class loader to use, by receiving the ClassLoader as a parameter from the application. The application (which knows all the classes that need constructing) should pass it getClass().getClassLoader().

Any other way to obtain a class loader is incorrect. If a library uses hacks such as Thread.getContextClassLoader(), sun.misc.VM.latestUserDefinedLoader(), or sun.reflect.Reflection.getCallerClass() it is a bug caused by a deficiency in the API. Basically, Thread.getContextClassLoader() exists only because whoever designed the ObjectInputStream API forgot to accept the ClassLoader as a parameter, and this mistake has haunted the Java community to this day.

That said, many many JDK classes use one of a few hacks to guess some class loader to use. Some use the ContextClassLoader (which fails when you run different apps on a shared thread pool, or when you leave the ContextClassLoader null), some walk the stack (which fails when the direct caller of the class is itself a library), some use the system class loader (which is fine, as long as it is documented to only use classes in the CLASSPATH) or bootstrap class loader, and some use an unpredictable combination of the above techniques (which only makes things more confusing). This has resulted in much weeping and gnashing of teeth.

When using such an API, first, try to find an overload of the method that accepts the class loader as a parameter. If there is no sensible method, then try setting the ContextClassLoader before the API call (and resetting it afterwards):

ClassLoader originalClassLoader = Thread.currentThread().getContextClassLoader();
try {
    Thread.currentThread().setContextClassLoader(getClass().getClassLoader());
    // call some API that uses reflection without taking ClassLoader param
} finally {
    Thread.currentThread().setContextClassLoader(originalClassLoader);
}

Vue component event after render

updated() should be what you're looking for:

Called after a data change causes the virtual DOM to be re-rendered and patched.

The component’s DOM will have been updated when this hook is called, so you can perform DOM-dependent operations here.

Javascript Iframe innerHTML

Don't forget that you can not cross domains because of security.

So if this is the case, you should use JSON.

Check if input is integer type in C

I was having the same problem, finally figured out what to do:

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

int main ()
{
    int x;
    float check;
    reprocess:
    printf ("enter a integer number:");
    scanf ("%f", &check);
    x=check;
    if (x==check)
    printf("\nYour number is %d", x);
    else 
    {
         printf("\nThis is not an integer number, please insert an integer!\n\n");
         goto reprocess;
    }
    _getch();
    return 0;
}

Select 2 columns in one and combine them

Yes, you can combine columns easily enough such as concatenating character data:

select col1 | col 2 as bothcols from tbl ...

or adding (for example) numeric data:

select col1 + col2 as bothcols from tbl ...

In both those cases, you end up with a single column bothcols, which contains the combined data. You may have to coerce the data type if the columns are not compatible.

Console.log(); How to & Debugging javascript

Learn to use a javascript debugger. Venkman (for Firefox) or the Web Inspector (part of Chome & Safari) are excellent tools for debugging what's going on.

You can set breakpoints and interrogate the state of the machine as you're interacting with your script; step through parts of your code to make sure everything is working as planned, etc.

Here is an excellent write up from WebMonkey on JavaScript Debugging for Beginners. It's a great place to start.

How do you completely remove Ionic and Cordova installation from mac?

If you want to delete ionic and cordova at same time.Run this code in cmd

npm uninstall -g ionic cordova

How to see full absolute path of a symlink

realpath isn't available on all linux flavors, but readlink should be.

readlink -f symlinkName

The above should do the trick.

Alternatively, if you don't have either of the above installed, you can do the following if you have python 2.6 (or later) installed

python -c 'import os.path; print(os.path.realpath("symlinkName"))'

Check if ADODB connection is open

This is an old topic, but in case anyone else is still looking...

I was having trouble after an undock event. An open db connection saved in a global object would error, even after reconnecting to the network. This was due to the TCP connection being forcibly terminated by remote host. (Error -2147467259: TCP Provider: An existing connection was forcibly closed by the remote host.)

However, the error would only show up after the first transaction was attempted. Up to that point, neither Connection.State nor Connection.Version (per solutions above) would reveal any error.

So I wrote the small sub below to force the error - hope it's useful.

Performance testing on my setup (Access 2016, SQL Svr 2008R2) was approx 0.5ms per call.

Function adoIsConnected(adoCn As ADODB.Connection) As Boolean

    '----------------------------------------------------------------
    '#PURPOSE: Checks whether the supplied db connection is alive and
    '          hasn't had it's TCP connection forcibly closed by remote
    '          host, for example, as happens during an undock event
    '#RETURNS: True if the supplied db is connected and error-free, 
    '          False otherwise
    '#AUTHOR:  Belladonna
    '----------------------------------------------------------------

    Dim i As Long
    Dim cmd As New ADODB.Command

    'Set up SQL command to return 1
    cmd.CommandText = "SELECT 1"
    cmd.ActiveConnection = adoCn

    'Run a simple query, to test the connection
    On Error Resume Next
    i = cmd.Execute.Fields(0)
    On Error GoTo 0

    'Tidy up
    Set cmd = Nothing

    'If i is 1, connection is open
    If i = 1 Then
        adoIsConnected = True
    Else
        adoIsConnected = False
    End If

End Function

SQL injection that gets around mysql_real_escape_string()

Well, there's nothing really that can pass through that, other than % wildcard. It could be dangerous if you were using LIKE statement as attacker could put just % as login if you don't filter that out, and would have to just bruteforce a password of any of your users. People often suggest using prepared statements to make it 100% safe, as data can't interfere with the query itself that way. But for such simple queries it probably would be more efficient to do something like $login = preg_replace('/[^a-zA-Z0-9_]/', '', $login);

The specified DSN contains an architecture mismatch between the Driver and Application. JAVA

By default, the Command Prompt is connected to System32. Run a 64-bit command prompt, i.e., C:\WINDOWS\SYSWOW64\CMD.EXE. In that, compile and run your java application.

What is the most "pythonic" way to iterate over a list in chunks?

Since nobody's mentioned it yet here's a zip() solution:

>>> def chunker(iterable, chunksize):
...     return zip(*[iter(iterable)]*chunksize)

It works only if your sequence's length is always divisible by the chunk size or you don't care about a trailing chunk if it isn't.

Example:

>>> s = '1234567890'
>>> chunker(s, 3)
[('1', '2', '3'), ('4', '5', '6'), ('7', '8', '9')]
>>> chunker(s, 4)
[('1', '2', '3', '4'), ('5', '6', '7', '8')]
>>> chunker(s, 5)
[('1', '2', '3', '4', '5'), ('6', '7', '8', '9', '0')]

Or using itertools.izip to return an iterator instead of a list:

>>> from itertools import izip
>>> def chunker(iterable, chunksize):
...     return izip(*[iter(iterable)]*chunksize)

Padding can be fixed using @??O?????'s answer:

>>> from itertools import chain, izip, repeat
>>> def chunker(iterable, chunksize, fillvalue=None):
...     it   = chain(iterable, repeat(fillvalue, chunksize-1))
...     args = [it] * chunksize
...     return izip(*args)

GIT vs. Perforce- Two VCS will enter... one will leave

I have no experience with Git, but I have with Mercurial which is also a distributed VCS. It depends on the project really, but in our case a distributed VCS suited the project as basically eliminated frequent broken builds.

I think it depends on the project really, as some are better suited towards a client-server VCS, and others towads a distributed one.

Running Windows batch file commands asynchronously

You can use the start command to spawn background processes without launching new windows:

start /b foo.exe

The new process will not be interruptable with CTRL-C; you can kill it only with CTRL-BREAK (or by closing the window, or via Task Manager.)

How to add hyperlink in JLabel?

If <a href="link"> doesn't work, then:

  1. Create a JLabel and add a MouseListener (decorate the label to look like a hyperlink)
  2. Implement mouseClicked() event
  3. In the implementation of mouseClicked() event, perform your action

Have a look at java.awt.Desktop API for opening a link using the default browser (this API is available only from Java6).

Why is there extra padding at the top of my UITableView with style UITableViewStyleGrouped in iOS7

This code worked for me, The best answer for me that was written in objective-C at up-side so I converted it into Swift.

For Swift 4.0+

self.tableView.tableHeaderView = UIView(frame: CGRect(x: 0, y: 0, width: self.tableView.bounds.size.width, height: 0.01))

Just write this into viewDidLoad() and it will work like a charm.

Uppercase first letter of variable

The string to lower before Capitalizing the first letter.

(Both use Jquery syntax)

function CapitaliseFirstLetter(elementId) {
    var txt = $("#" + elementId).val().toLowerCase();
    $("#" + elementId).val(txt.replace(/^(.)|\s(.)/g, function($1) {
    return $1.toUpperCase(); }));
    }

In addition a function to Capitalise the WHOLE string:

function CapitaliseAllText(elementId) {
     var txt = $("#" + elementId).val();
     $("#" + elementId).val(txt.toUpperCase());
     }

Syntax to use on a textbox's click event:

onClick="CapitaliseFirstLetter('TextId'); return false"

copy from one database to another using oracle sql developer - connection failed

The copy command is a SQL*Plus command (not a SQL Developer command). If you have your tnsname entries setup for SID1 and SID2 (e.g. try a tnsping), you should be able to execute your command.

Another assumption is that table1 has the same columns as the message_table (and the columns have only the following data types: CHAR, DATE, LONG, NUMBER or VARCHAR2). Also, with an insert command, you would need to be concerned about primary keys (e.g. that you are not inserting duplicate records).

I tried a variation of your command as follows in SQL*Plus (with no errors):

copy from scott/tiger@db1 to scott/tiger@db2 create new_emp using select * from emp;

After I executed the above statement, I also truncate the new_emp table and executed this command:

copy from scott/tiger@db1 to scott/tiger@db2 insert new_emp using select * from emp;

With SQL Developer, you could do the following to perform a similar approach to copying objects:

  1. On the tool bar, select Tools>Database copy.

  2. Identify source and destination connections with the copy options you would like. enter image description here

  3. For object type, select table(s). enter image description here

  4. Specify the specific table(s) (e.g. table1). enter image description here

The copy command approach is old and its features are not being updated with the release of new data types. There are a number of more current approaches to this like Oracle's data pump (even for tables).

Array to Collection: Optimized code

You can try something like this:

List<String> list = new ArrayList<String>(Arrays.asList(array));

public ArrayList(Collection c)

Constructs a list containing the elements of the specified collection, in the order they are returned by the collection's iterator. The ArrayList instance has an initial capacity of 110% the size of the specified collection.

Taken from here

Load content of a div on another page

You just need to add a jquery selector after the url.

See: http://api.jquery.com/load/

Example straight from the API:

$('#result').load('ajax/test.html #container');

So what that does is it loads the #container element from the specified url.

Click event on select option element in chrome

I don't believe the click event is valid on options. It is valid, however, on select elements. Give this a try:

$("select#yourSelect").change(function(){
    process($(this).children(":selected").html());
});

MySQL direct INSERT INTO with WHERE clause

you can use UPDATE command.

UPDATE table_name SET name=@name, email=@email, phone=@phone WHERE client_id=@client_id

How to reshape data from long to wide format

Using reshape function:

reshape(dat1, idvar = "name", timevar = "numbers", direction = "wide")

How to dynamically build a JSON object with Python?

All previous answers are correct, here is one more and easy way to do it. For example, create a Dict data structure to serialize and deserialize an object

(Notice None is Null in python and I'm intentionally using this to demonstrate how you can store null and convert it to json null)

import json
print('serialization')
myDictObj = { "name":"John", "age":30, "car":None }
##convert object to json
serialized= json.dumps(myDictObj, sort_keys=True, indent=3)
print(serialized)
## now we are gonna convert json to object
deserialization=json.loads(serialized)
print(deserialization)

enter image description here

Android Studio - Emulator - eglSurfaceAttrib not implemented

Fix: Unlock your device before running it.

Hi Guys: Think I may have a fix for this:

Sounds ridiculous but try unlocking your Virtual Device; i.e. use your mouse to swipe and open. Your app should then work!!

Using gdb to single-step assembly code outside specified executable causes error "cannot find bounds of current function"

Instead of gdb, run gdbtui. Or run gdb with the -tui switch. Or press C-x C-a after entering gdb. Now you're in GDB's TUI mode.

Enter layout asm to make the upper window display assembly -- this will automatically follow your instruction pointer, although you can also change frames or scroll around while debugging. Press C-x s to enter SingleKey mode, where run continue up down finish etc. are abbreviated to a single key, allowing you to walk through your program very quickly.

   +---------------------------------------------------------------------------+
B+>|0x402670 <main>         push   %r15                                        |
   |0x402672 <main+2>       mov    %edi,%r15d                                  |
   |0x402675 <main+5>       push   %r14                                        |
   |0x402677 <main+7>       push   %r13                                        |
   |0x402679 <main+9>       mov    %rsi,%r13                                   |
   |0x40267c <main+12>      push   %r12                                        |
   |0x40267e <main+14>      push   %rbp                                        |
   |0x40267f <main+15>      push   %rbx                                        |
   |0x402680 <main+16>      sub    $0x438,%rsp                                 |
   |0x402687 <main+23>      mov    (%rsi),%rdi                                 |
   |0x40268a <main+26>      movq   $0x402a10,0x400(%rsp)                       |
   |0x402696 <main+38>      movq   $0x0,0x408(%rsp)                            |
   |0x4026a2 <main+50>      movq   $0x402510,0x410(%rsp)                       |
   +---------------------------------------------------------------------------+
child process 21518 In: main                            Line: ??   PC: 0x402670
(gdb) file /opt/j64-602/bin/jconsole
Reading symbols from /opt/j64-602/bin/jconsole...done.
(no debugging symbols found)...done.
(gdb) layout asm
(gdb) start
(gdb)

How to check the version of GitLab?

The easiest way is to paste the following command:

cat /opt/gitlab/version-manifest.txt | head -n 1

and there you get the version installed. :)

Spring Boot not serving static content

Unlike what the spring-boot states, to get my spring-boot jar to serve the content: I had to add specifically register my src/main/resources/static content through this config class:

@Configuration
public class StaticResourceConfiguration implements WebMvcConfigurer {

    private static final String[] CLASSPATH_RESOURCE_LOCATIONS = {
            "classpath:/META-INF/resources/", "classpath:/resources/",
            "classpath:/static/", "classpath:/public/" };

    @Override
    public void addResourceHandlers(ResourceHandlerRegistry registry) {
        registry.addResourceHandler("/**")
            .addResourceLocations(CLASSPATH_RESOURCE_LOCATIONS);
    }
}

In MySQL, can I copy one row to insert into the same table?

You could also try dumping the table, finding the insert command and editing it:

mysqldump -umyuser -p mydatabase --skip-extended-insert mytable > outfile.sql

The --skip-extended-insert gives you one insert command per row. You may then find the row in your favourite text editor, extract the command and alter the primary key to "default".

How to index characters in a Golang string?

You can also try typecasting it with string.

package main

import "fmt"

func main() {
    fmt.Println(string("Hello"[1]))
}

How to enable PHP short tags?

I'v Changed the short_open_tag Off to On on my aws centos 7 instance and php7(PHP 7.0.33 (cli) (built: Dec 6 2018 22:30:44) ( NTS )), but its not reflecting the php info page and the code. So I refer may docs and find a solution on my case. Add an extra line after the short_open_tag as asp_tags = On after that restart Apache It works on the code and I go the output correctly

php.ini file

engine = On

; This directive determines whether or not PHP will recognize code between
; <? and ?> tags as PHP source which should be processed as such. It is
; generally recommended that <?php and ?> should be used and that this feature
; should be disabled, as enabling it may result in issues when generating XML
; documents, however this remains supported for backward compatibility reasons.
; Note that this directive does not control the <?= shorthand tag, which can be
; used regardless of this directive. 
; Default Value: On   
; Development Value: Off     
; Production Value: Off  
; http://php.net/short-open-tag

short_open_tag = On

; Allow ASP-style <% %> tags   
; http://php.net/asp-tags
asp_tags = On

Difference between multitasking, multithreading and multiprocessing?

Multiprogramming - This term is used in the context of batch systems. You've got several programs in main memory concurrently. The CPU schedules a time for each one.

I.e. submitting multiple jobs and all of them are loaded into memory and executed according to a scheduling algorithm. Common batch system scheduling algorithms include: First-Come-First-Served, Shortest-Job-First, Shortest-Remaining-Time-Next.

Multitasking - This is basically multiprogramming in the context of a single-user interactive environment, in which the OS switches between several programs in main memory so as to give the illusion that several are running at once. Common scheduling algorithms used for multitasking are: Round-Robin, Priority Scheduling (multiple queues), Shortest-Process-Next.

Is it possible to execute multiple _addItem calls asynchronously using Google Analytics?

From the docs:

_trackTrans() Sends both the transaction and item data to the Google Analytics server. This method should be called after _trackPageview(), and used in conjunction with the _addItem() and addTrans() methods. It should be called after items and transaction elements have been set up.

So, according to the docs, the items get sent when you call trackTrans(). Until you do, you can add items, but the transaction will not be sent.

Edit: Further reading led me here:

http://www.analyticsmarket.com/blog/edit-ecommerce-data

Where it clearly says you can start another transaction with an existing ID. When you commit it, the new items you listed will be added to that transaction.

W3WP.EXE using 100% CPU - where to start?

It's not much of an answer, but you might need to go old school and capture an image snapshot of the IIS process and debug it. You might also want to check out Tess Ferrandez's blog - she is a kick a** microsoft escalation engineer and her blog focuses on debugging windows ASP.NET, but the blog is relevant to windows debugging in general. If you select the ASP.NET tag (which is what I've linked to) then you'll see several items that are similar.

How do I disable a Button in Flutter?

For a specific and limited number of widgets, wrapping them in a widget IgnorePointer does exactly this: when its ignoring property is set to true, the sub-widget (actually, the entire subtree) is not clickable.

IgnorePointer(
    ignoring: true, // or false
    child: RaisedButton(
        onPressed: _logInWithFacebook,
        child: Text("Facebook sign-in"),
        ),
),

Otherwise, if you intend to disable an entire subtree, look into AbsorbPointer().