Programs & Examples On #Nsrunalertpanel

How can I convert a dictionary into a list of tuples?

>>> a={ 'a': 1, 'b': 2, 'c': 3 }

>>> [(x,a[x]) for x in a.keys() ]
[('a', 1), ('c', 3), ('b', 2)]

>>> [(a[x],x) for x in a.keys() ]
[(1, 'a'), (3, 'c'), (2, 'b')]

jQuery: how to change title of document during .ready()?

I am using some nested layouts in Ruby on Rails, and in one of the layouts i have a need to read in a string from a div and set that as the title of the document.

The correct way to do this is on the server side.

In your layout, there at some point will be some code which puts the text in the div. Make this code also set some instance variable such as @page_title, and then in your outer layout have it do <%= @page_title || 'Default Title' %>

Is the Javascript date object always one day off?

You are using the ISO date string format which, according to this page, causes the date to be constructed using the UTC timezone:

Note: parsing of date strings with the Date constructor (and Date.parse, they are equivalent) is strongly discouraged due to browser differences and inconsistencies. Support for RFC 2822 format strings is by convention only. Support for ISO 8601 formats differs in that date-only strings (e.g. "1970-01-01") are treated as UTC, not local.

If you format the text differently, such as "Jan 01 1970", then (at least on my machine) it uses your local timezone.

How do I limit the number of decimals printed for a double?

Formatter class is also a good option. fmt.format("%.2f", variable); 2 here is showing how many decimals you want. You can change it to 4 for example. Don't forget to close the formatter.

 private static int nJars, nCartons, totalOunces, OuncesTolbs, lbs;

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

  public static void computeShippingCost()
  {
   System.out.print("Enter a number of jars: ");
   Scanner kboard = new Scanner (System.in);
   nJars = kboard.nextInt();
   int nCartons = (nJars + 11) / 12;
   int totalOunces = (nJars * 21) + (nCartons * 25);
   int lbs = totalOunces / 16;


   double shippingCost =  ((nCartons * 1.44) + (lbs + 1) * 0.96) + 3.0;

     Formatter fmt = new Formatter();
     fmt.format("%.2f", shippingCost);

   System.out.print("$" + fmt);

   fmt.close();

}

Angular2 RC6: '<component> is not a known element'

I received this error when I imported Module A into Module B, and then tried to use a component from Module A in Module B.

The solution is to declare that component in the exports array.

@NgModule({
  declarations: [
    MyComponent
  ],
  exports: [
    MyComponent
  ]
})
export class ModuleA {}
@NgModule({
  imports: [
    ModuleA
  ]
})
export class ModuleB {}

indexOf Case Sensitive?

@Test
public void testIndexofCaseSensitive() {
    TestCase.assertEquals(-1, "abcDef".indexOf("d") );
}

How to install mysql-connector via pip

First install setuptools

sudo pip install setuptools

Then install mysql-connector

sudo pip install mysql-connector

If using Python3, then replace pip by pip3

It is more efficient to use if-return-return or if-else-return?

This is a question of style (or preference) since the interpreter does not care. Personally I would try not to make the final statement of a function which returns a value at an indent level other than the function base. The else in example 1 obscures, if only slightly, where the end of the function is.

By preference I use:

return A+1 if (A > B) else A-1

As it obeys both the good convention of having a single return statement as the last statement in the function (as already mentioned) and the good functional programming paradigm of avoiding imperative style intermediate results.

For more complex functions I prefer to break the function into multiple sub-functions to avoid premature returns if possible. Otherwise I revert to using an imperative style variable called rval. I try not to use multiple return statements unless the function is trivial or the return statement before the end is as a result of an error. Returning prematurely highlights the fact that you cannot go on. For complex functions that are designed to branch off into multiple subfunctions I try to code them as case statements (driven by a dict for instance).

Some posters have mentioned speed of operation. Speed of Run-time is secondary for me since if you need speed of execution Python is not the best language to use. I use Python as its the efficiency of coding (i.e. writing error free code) that matters to me.

What is the difference between method overloading and overriding?

Method overriding is when a child class redefines the same method as a parent class, with the same parameters. For example, the standard Java class java.util.LinkedHashSet extends java.util.HashSet. The method add() is overridden in LinkedHashSet. If you have a variable that is of type HashSet, and you call its add() method, it will call the appropriate implementation of add(), based on whether it is a HashSet or a LinkedHashSet. This is called polymorphism.

Method overloading is defining several methods in the same class, that accept different numbers and types of parameters. In this case, the actual method called is decided at compile-time, based on the number and types of arguments. For instance, the method System.out.println() is overloaded, so that you can pass ints as well as Strings, and it will call a different version of the method.

css h1 - only as wide as the text

I recently solved this problem by using table-caption, though I cannot say if it is recommended. The other answers didn't seem to workout in my case.

h1 {
  display: table-caption;
}

How can I run an external command asynchronously from Python?

If you want to run many processes in parallel and then handle them when they yield results, you can use polling like in the following:

from subprocess import Popen, PIPE
import time

running_procs = [
    Popen(['/usr/bin/my_cmd', '-i %s' % path], stdout=PIPE, stderr=PIPE)
    for path in '/tmp/file0 /tmp/file1 /tmp/file2'.split()]

while running_procs:
    for proc in running_procs:
        retcode = proc.poll()
        if retcode is not None: # Process finished.
            running_procs.remove(proc)
            break
        else: # No process is done, wait a bit and check again.
            time.sleep(.1)
            continue

    # Here, `proc` has finished with return code `retcode`
    if retcode != 0:
        """Error handling."""
    handle_results(proc.stdout)

The control flow there is a little bit convoluted because I'm trying to make it small -- you can refactor to your taste. :-)

This has the advantage of servicing the early-finishing requests first. If you call communicate on the first running process and that turns out to run the longest, the other running processes will have been sitting there idle when you could have been handling their results.

jQuery .attr("disabled", "disabled") not working in Chrome

if you are removing all disabled attributes from input, then why not just do:

$("input").removeAttr('disabled');

Then after ajax success:

$("input[type='text']").attr('disabled', true);

Make sure you use remove the disabled attribute before submit, or it won't submit that data. If you need to submit it before changing, you need to use readonly instead.

What is the difference between x86 and x64

Oddly enough it was an Intel thing not a Microsoft thing. X86 referred to the Intel CPU series from the 8086 to the 80486. The Pentium series still use the same addressing system. The x64 refers to the I64 addressing system that Intel came out with later for the 64-bit CPUs. So Windows was just following Intel's architecture naming.

How do you do a ‘Pause’ with PowerShell 2.0?

You may want to use FlushInputBuffer to discard any characters mistakenly typed into the console, especially for long running operations, before using ReadKey:

Write-Host -NoNewLine 'Press any key to continue...'
$Host.UI.RawUI.FlushInputBuffer()
$Host.UI.RawUI.ReadKey('NoEcho,IncludeKeyDown') | Out-Null

When would you use the Builder Pattern?

The key difference between a builder and factory IMHO, is that a builder is useful when you need to do lots of things to build an object. For example imagine a DOM. You have to create plenty of nodes and attributes to get your final object. A factory is used when the factory can easily create the entire object within one method call.

One example of using a builder is a building an XML document, I've used this model when building HTML fragments for example I might have a Builder for building a specific type of table and it might have the following methods (parameters are not shown):

BuildOrderHeaderRow()
BuildLineItemSubHeaderRow()
BuildOrderRow()
BuildLineItemSubRow()

This builder would then spit out the HTML for me. This is much easier to read than walking through a large procedural method.

Check out Builder Pattern on Wikipedia.

Convert json data to a html table

You can use simple jQuery jPut plugin

http://plugins.jquery.com/jput/

<script>
$(document).ready(function(){

var json = [{"name": "name1","email":"[email protected]"},{"name": "name2","link":"[email protected]"}];
//while running this code the template will be appended in your div with json data
$("#tbody").jPut({
    jsonData:json,
    //ajax_url:"youfile.json",  if you want to call from a json file
    name:"tbody_template",
});

});
</script>   

<table jput="t_template">
 <tbody jput="tbody_template">
     <tr>
         <td>{{name}}</td>
         <td>{{email}}</td>
     </tr>
 </tbody>
</table>

<table>
 <tbody id="tbody">
 </tbody>
</table>

Capture keyboardinterrupt in Python without try-except

I tried the suggested solutions by everyone, but I had to improvise code myself to actually make it work. Following is my improvised code:

import signal
import sys
import time

def signal_handler(signal, frame):
    print('You pressed Ctrl+C!')
    print(signal) # Value is 2 for CTRL + C
    print(frame) # Where your execution of program is at moment - the Line Number
    sys.exit(0)

#Assign Handler Function
signal.signal(signal.SIGINT, signal_handler)

# Simple Time Loop of 5 Seconds
secondsCount = 5
print('Press Ctrl+C in next '+str(secondsCount))
timeLoopRun = True 
while timeLoopRun:  
    time.sleep(1)
    if secondsCount < 1:
        timeLoopRun = False
    print('Closing in '+ str(secondsCount)+ ' seconds')
    secondsCount = secondsCount - 1

How to do what head, tail, more, less, sed do in Powershell?

"-TotalCount" in this instance responds exactly like "-head". You have to use -TotalCount or -head to run the command like that. But -TotalCount is misleading - it does not work in ACTUALLY giving you ANY counts...

gc -TotalCount 25 C:\scripts\logs\robocopy_report.txt

The above script, tested in PS 5.1 is the SAME response as below...

gc -head 25 C:\scripts\logs\robocopy_report.txt

So then just use '-head 25" already!

How to solve "The specified service has been marked for deletion" error

Most probably deleting service fails because

protected override void OnStop()

throw error when stopping a service. wrapping things inside a try catch will prevent mark for deletion error

protected override void OnStop()
{
            try
            {
                //things to do
            }
            catch (Exception)
            {
            }

}

Which Ruby version am I really running?

The ruby version 1.8.7 seems to be your system ruby.

Normally you can choose the ruby version you'd like, if you are using rvm with following. Simple change into your directory in a new terminal and type in:

rvm use 2.0.0

You can find more details about rvm here: http://rvm.io Open the website and scroll down, you will see a few helpful links. "Setting up default rubies" for example could help you.

Update: To set the ruby as default:

rvm use 2.0.0 --default

How to put attributes via XElement

Add XAttribute in the constructor of the XElement, like

new XElement("Conn", new XAttribute("Server", comboBox1.Text));

You can also add multiple attributes or elements via the constructor

new XElement("Conn", new XAttribute("Server", comboBox1.Text), new XAttribute("Database", combobox2.Text));

or you can use the Add-Method of the XElement to add attributes

XElement element = new XElement("Conn");
XAttribute attribute = new XAttribute("Server", comboBox1.Text);
element.Add(attribute);

How can I know which radio button is selected via jQuery?

To retrieve all radio buttons values in JavaScript array use following jQuery code :

var values = jQuery('input:checkbox:checked.group1').map(function () {
    return this.value;
}).get();

Image is not showing in browser?

You need to import your image from the image folder. import name_of_image from '../imageFolder/name_of_image.jpg';

<img src={name_of_image} alt=''>

Please refer here. https://create-react-app.dev/docs/adding-images-fonts-and-files -

Recursively list files in Java

I would go with something like:

public void list(File file) {
    System.out.println(file.getName());
    File[] children = file.listFiles();
    for (File child : children) {
        list(child);
    }
}

The System.out.println is just there to indicate to do something with the file. there is no need to differentiate between files and directories, since a normal file will simply have zero children.

Create text file and fill it using bash

If you're wanting this as a script, the following Bash script should do what you want (plus tell you when the file already exists):

#!/bin/bash
if [ -e $1 ]; then
  echo "File $1 already exists!"
else
  echo >> $1
fi

If you don't want the "already exists" message, you can use:

#!/bin/bash
if [ ! -e $1 ]; then
  echo >> $1
fi

Edit about using:

Save whichever version with a name you like, let's say "create_file" (quotes mine, you don't want them in the file name). Then, to make the file executatble, at a command prompt do:

chmod u+x create_file

Put the file in a directory in your path, then use it with:

create_file NAME_OF_NEW_FILE

The $1 is a special shell variable which takes the first argument on the command line after the program name; i.e. $1 will pick up NAME_OF_NEW_FILE in the above usage example.

why numpy.ndarray is object is not callable in my simple for python loop

Sometimes, when a function name and a variable name to which the return of the function is stored are same, the error is shown. Just happened to me.

jquery how to use multiple ajax calls one after the end of the other

We can simply use

async: false 

This will do your need.

Rebasing a Git merge commit

There are two options here.

One is to do an interactive rebase and edit the merge commit, redo the merge manually and continue the rebase.

Another is to use the --rebase-merges option on git rebase, which is described as follows from the manual:

By default, a rebase will simply drop merge commits from the todo list, and put the rebased commits into a single, linear branch. With --rebase-merges, the rebase will instead try to preserve the branching structure within the commits that are to be rebased, by recreating the merge commits. Any resolved merge conflicts or manual amendments in these merge commits will have to be resolved/re-applied manually."

Oracle SqlDeveloper JDK path

For those who use Mac, edit this file:

/Applications/SQLDeveloper.app/Contents/MacOS/sqldeveloper.sh

Mine had:

export JAVA_HOME=`/usr/libexec/java_home -v 1.7`

and I changed it to 1.8 and it stopped complaining about java version.

How to connect to a remote MySQL database with Java?

in my.cnf file , please change the following

## Instead of skip-networking the default is now to listen only on ## localhost which is more compatible and is not less secure. ## bind-address = 127.0.0.1

setting an environment variable in virtualenv

Locally within an virtualenv there are two methods you could use to test this. The first is a tool which is installed via the Heroku toolbelt (https://toolbelt.heroku.com/). The tool is foreman. It will export all of your environment variables that are stored in a .env file locally and then run app processes within your Procfile.

The second way if you're looking for a lighter approach is to have a .env file locally then run:

export $(cat .env)

how to write javascript code inside php

Lately I've come across yet another way of putting JS code inside PHP code. It involves Heredoc PHP syntax. I hope it'll be helpful for someone.

<?php
$script = <<< JS

$(function() {
   // js code goes here
});

JS;
?>

After closing the heredoc construction the $script variable contains your JS code that can be used like this:

<script><?= $script ?></script>

The profit of using this way is that modern IDEs recognize JS code inside Heredoc and highlight it correctly unlike using strings. And you're still able to use PHP variables inside of JS code.

android pick images from gallery

You can use this method to pick image from gallery. Only images will be displayed.

public void pickImage() {
    Intent intent = new Intent(Intent.ACTION_PICK,
            MediaStore.Images.Media.INTERNAL_CONTENT_URI);
    intent.setType("image/*");
    intent.putExtra("crop", "true");
    intent.putExtra("scale", true);
    intent.putExtra("outputX", 256);
    intent.putExtra("outputY", 256);
    intent.putExtra("aspectX", 1);
    intent.putExtra("aspectY", 1);
    intent.putExtra("return-data", true);
    startActivityForResult(intent, 1);
}

and override onActivityResult as

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        if (resultCode != RESULT_OK) {
            return;
        }
        if (requestCode == 1) {
            final Bundle extras = data.getExtras();
            if (extras != null) {
                //Get image
                Bitmap newProfilePic = extras.getParcelable("data");
            }
        }
    }

How to print / echo environment variables?

On windows, you can print with this command in your CLI C:\Users\dir\env | more

You can view all environment variables set on your system with the env command. The list is long, so pipe the output through more to make it easier to read.

How to get the Facebook user id using the access token

The easiest way is

https://graph.facebook.com/me?fields=id&access_token="xxxxx"

then you will get json response which contains only userid.

List(of String) or Array or ArrayList

You can use IList(Of String) in the function :

Private Function getWriteBits() As IList(Of String)


Dim temp1 As String
Dim temp2 As Boolean
Dim temp3 As Boolean


'Pallet Destination Unique
Dim temp4 As Boolean
Dim temp5 As Boolean
Dim temp6 As Boolean

Dim lstWriteBits As Ilist = {temp1, temp2, temp3, temp4, temp5, temp6}

Return lstWriteBits
End Function

use list1.AddRange(list2) to add lists

Hope it helps.

Detect application heap size in Android

This returns max heap size in bytes:

Runtime.getRuntime().maxMemory()

I was using ActivityManager.getMemoryClass() but on CyanogenMod 7 (I didn't test it elsewhere) it returns wrong value if the user sets heap size manually.

How to convert std::string to LPCWSTR in C++ (Unicode)

LPCWSTR lpcwName=std::wstring(strname.begin(), strname.end()).c_str()

Filter by process/PID in Wireshark

If you want to follow an application that still has to be started then it's certainly possible:

  1. Install docker (see https://docs.docker.com/engine/installation/linux/docker-ce/ubuntu/)
  2. Open a terminal and run a tiny container: docker run -t -i ubuntu /bin/bash (change "ubuntu" to your favorite distro, this doesn't have to be the same as in your real system)
  3. Install your application in the container using the same way that you would install it in a real system.
  4. Start wireshark in your real system, go to capture > options . In the window that will open you'll see all your interfaces. Instead of choosing any, wlan0, eth0, ... choose the new virtual interface docker0 instead.
  5. Start capturing
  6. Start your application in the container

You might have some doubts about running your software in a container, so here are the answers to the questions you probably want to ask:

  • Will my application work inside a container ? Almost certainly yes, but you might need to learn a bit about docker to get it working
  • Won't my application run slow ? Negligible. If your program is something that runs heavy calculations for a week then it might now take a week and 3 seconds
  • What if my software or something else breaks in the container ? That's the nice thing about containers. Whatever is running inside can only break the current container and can't hurt the rest of the system.

Find OpenCV Version Installed on Ubuntu

1) Direct Answer: Try this:

   sudo updatedb
   locate OpenCVConfig.cmake

For me, I get:

   /home/pkarasev3/source/opencv/build/OpenCVConfig.cmake

To see the version, you can try:

   cat /home/pkarasev3/source/opencv/build/OpenCVConfig.cmake

giving

    ....
   SET(OpenCV_VERSION 2.3.1)
    ....

2) Better Answer:

"sudo make install" is your enemy, don't do that when you need to compile/update the library often and possibly debug step through it's internal functions. Notice how my config file is in a local build directory, not in /usr/something. You will avoid this confusion in the future, and can maintain several different versions even (debug and release, for example).

Edit: the reason this questions seems to arise often for OpenCV as opposed to other libraries is that it changes rather dramatically and fast between versions, and many of the operations are not so well-defined / well-constrained so you can't just rely on it to be a black-box like you do for something like libpng or libjpeg. Thus, better to not install it at all really, but just compile and link to the build folder.

WCF Error "This could be due to the fact that the server certificate is not configured properly with HTTP.SYS in the HTTPS case"

Rather than explicitly setting the security protocol, a better way is to set the web.config <compilation targetFramework="4.5"> or higher.

Call japplet from jframe

First of all, Applets are designed to be run from within the context of a browser (or applet viewer), they're not really designed to be added into other containers.

Technically, you can add a applet to a frame like any other component, but personally, I wouldn't. The applet is expecting a lot more information to be available to it in order to allow it to work fully.

Instead, I would move all of the "application" content to a separate component, like a JPanel for example and simply move this between the applet or frame as required...

ps- You can use f.setLocationRelativeTo(null) to center the window on the screen ;)

Updated

You need to go back to basics. Unless you absolutely must have one, avoid applets until you understand the basics of Swing, case in point...

Within the constructor of GalzyTable2 you are doing...

JApplet app = new JApplet(); add(app); app.init(); app.start(); 

...Why are you adding another applet to an applet??

Case in point...

Within the main method, you are trying to add the instance of JFrame to itself...

f.getContentPane().add(f, button2); 

Instead, create yourself a class that extends from something like JPanel, add your UI logical to this, using compound components if required.

Then, add this panel to whatever top level container you need.

Take the time to read through Creating a GUI with Swing

Updated with example

import java.awt.BorderLayout; import java.awt.Dimension; import java.awt.EventQueue; import java.awt.event.ActionEvent; import javax.swing.ImageIcon; import javax.swing.JButton; import javax.swing.JFrame; import javax.swing.JPanel; import javax.swing.JScrollPane; import javax.swing.JTable; import javax.swing.UIManager; import javax.swing.UnsupportedLookAndFeelException;  public class GalaxyTable2 extends JPanel {      private static final int PREF_W = 700;     private static final int PREF_H = 600;      String[] columnNames                     = {"Phone Name", "Brief Description", "Picture", "price",                         "Buy"};  // Create image icons     ImageIcon Image1 = new ImageIcon(                     getClass().getResource("s1.png"));     ImageIcon Image2 = new ImageIcon(                     getClass().getResource("s2.png"));     ImageIcon Image3 = new ImageIcon(                     getClass().getResource("s3.png"));     ImageIcon Image4 = new ImageIcon(                     getClass().getResource("s4.png"));     ImageIcon Image5 = new ImageIcon(                     getClass().getResource("note.png"));     ImageIcon Image6 = new ImageIcon(                     getClass().getResource("note2.png"));     ImageIcon Image7 = new ImageIcon(                     getClass().getResource("note3.png"));      Object[][] rowData = {         {"Galaxy S", "3G Support,CPU 1GHz",             Image1, 120, false},         {"Galaxy S II", "3G Support,CPU 1.2GHz",             Image2, 170, false},         {"Galaxy S III", "3G Support,CPU 1.4GHz",             Image3, 205, false},         {"Galaxy S4", "4G Support,CPU 1.6GHz",             Image4, 230, false},         {"Galaxy Note", "4G Support,CPU 1.4GHz",             Image5, 190, false},         {"Galaxy Note2 II", "4G Support,CPU 1.6GHz",             Image6, 190, false},         {"Galaxy Note 3", "4G Support,CPU 2.3GHz",             Image7, 260, false},};      MyTable ss = new MyTable(                     rowData, columnNames);      // Create a table     JTable jTable1 = new JTable(ss);      public GalaxyTable2() {         jTable1.setRowHeight(70);          add(new JScrollPane(jTable1),                         BorderLayout.CENTER);          JPanel buttons = new JPanel();          JButton button = new JButton("Home");         buttons.add(button);         JButton button2 = new JButton("Confirm");         buttons.add(button2);          add(buttons, BorderLayout.SOUTH);     }      @Override      public Dimension getPreferredSize() {         return new Dimension(PREF_W, PREF_H);     }      public void actionPerformed(ActionEvent e) {         new AMainFrame7().setVisible(true);     }      public static void main(String[] args) {          EventQueue.invokeLater(new Runnable() {             @Override             public void run() {                 try {                     UIManager.setLookAndFeel(UIManager.getSystemLookAndFeelClassName());                 } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {                     ex.printStackTrace();                 }                  JFrame frame = new JFrame("Testing");                 frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);                 frame.add(new GalaxyTable2());                 frame.pack();                 frame.setLocationRelativeTo(null);                 frame.setVisible(true);             }         });     } } 

You also seem to have a lack of understanding about how to use layout managers.

Take the time to read through Creating a GUI with Swing and Laying components out in a container

How to set the color of "placeholder" text?

#Try this:

input[type="text"],textarea[type="text"]::-webkit-input-placeholder {
    color:#f51;
}
input[type="text"],textarea[type="text"]:-moz-placeholder {
    color:#f51;
}
input[type="text"],textarea[type="text"]::-moz-placeholder {
    color:#f51;
}
input[type="text"],textarea[type="text"]:-ms-input-placeholder {
    color:#f51;
}

##Works very well for me.

Android, ListView IllegalStateException: "The content of the adapter has changed but ListView did not receive a notification"

Even I faced the same problem in my XMPP notification application, receivers message needs to be added back to list view (implemented with ArrayList). When I tried to add the receiver content through MessageListener (separate thread), application quits with above error. I solved this by adding the content to my arraylist & setListviewadapater through runOnUiThread method which is part of Activity class. This solved my problem.

Insert variable values in the middle of a string

String.Format("Hi We have these flights for you: {0}. Which one do you want",
                              flights);

EDIT: you can even save the "template" string separately (for instance you could store it in a configuration file and retrieve it from there), like this:

string flights = "Flight A, B,C,D";

string template = @"Hi We have these flights for you: {0}. Which one do you want";
Console.WriteLine(String.Format(template, flights));

EDIT2: whoops, sorry I see that @DanPuzey had already suggested something very similar to my EDIT (but somewhat better)

How can I make a ComboBox non-editable in .NET?

for winforms .NET change DropDownStyle to DropDownList from Combobox property

Browser detection in JavaScript?

Some times we need simple method to check if the browser is IE or not. This is how it could be:

 var isMSIE = (/trident/i).test(navigator.userAgent);

 if(isMSIE)
 {
  /* do something for ie */
 }
 else
 {
  /* do something else */
 }

or simplified siva's method:

 if(!!navigator.systemLanguage)
 {
  /* do something for ie */
 }
 else
 {
  /* do something else */
 }

MSIE v.11 check:

if( (/trident/i).test(navigator.userAgent) && (/rv:/i).test(navigator.userAgent) )
{
  /* do something for ie 11 */
}

other IE browsers contain MSIE string in their userAgent property and could be catched by it.

Merge 2 arrays of objects

You can leverage hash maps and Object.values to accomplish this in roughly O(3n) time. This looks like O(n^2), but the outer loop is just to iterate through the arrays to be merged.

function uniqueMerge(arrays) {
  const results = {};
  arrays.forEach((arr) => {
    arr.forEach(item => {
      results[item.name] = item;
    });
  });

  return Object.values(results);
}

enter image description here

Add Class to Object on Page Load

I would recommend using jQuery with this function:

$(document).ready(function(){
 $('#about').addClass('expand');
});

This will add the expand class to an element with id of about when the dom is ready on page load.

Android Fatal signal 11 (SIGSEGV) at 0x636f7d89 (code=1). How can it be tracked down?

For me, on Android Studio 4.1, what did the trick was good ole File > Invalidate Cache & Restart

No more Fatal Signals after that. I'm sure it had something to do with the profiler, but can't be certain. I just know restarting AS stopped the crashes on my emulator. enter image description here

DatabaseError: current transaction is aborted, commands ignored until end of transaction block?

I just had this error too but it was masking another more relevant error message where the code was trying to store a 125 characters string in a 100 characters column:

DatabaseError: value too long for type character varying(100)

I had to debug through the code for the above message to show up, otherwise it displays

DatabaseError: current transaction is aborted

Right way to convert data.frame to a numeric matrix, when df also contains strings?

I manually filled NAs by exporting the CSV then editing it and reimporting, as below.

Perhaps one of you experts might explain why this procedure worked so well (the first file had columns with data of types char, INT and num (floating point numbers)), which all became char type after STEP 1; but at the end of STEP 3 R correctly recognized the datatype of each column).

# STEP 1:
MainOptionFile <- read.csv("XLUopt_XLUstk_v3.csv",
                            header=T, stringsAsFactors=FALSE)
#... STEP 2:
TestFrame <- subset(MainOptionFile, str_locate(option_symbol,"120616P00034000") > 0)
write.csv(TestFrame, file = "TestFrame2.csv")
# ...
# STEP 3:
# I made various amendments to `TestFrame2.csv`, including replacing all missing data cells with appropriate numbers. I then read that amended data frame back into R as follows:    
XLU_34P_16Jun12 <- read.csv("TestFrame2_v2.csv",
                            header=T,stringsAsFactors=FALSE)

On arrival back in R, all columns had their correct measurement levels automatically recognized by R!

Variable is accessed within inner class. Needs to be declared final

If you don't want to make it final, you can always just make it a global variable.

How do I override nested NPM dependency versions?

You can use npm shrinkwrap functionality, in order to override any dependency or sub-dependency.

I've just done this in a grunt project of ours. We needed a newer version of connect, since 2.7.3. was causing trouble for us. So I created a file named npm-shrinkwrap.json:

{
  "dependencies": {
    "grunt-contrib-connect": {
      "version": "0.3.0",
      "from": "[email protected]",
      "dependencies": {
        "connect": {
          "version": "2.8.1",
          "from": "connect@~2.7.3"
        }
      }
    }
  }
}

npm should automatically pick it up while doing the install for the project.

(See: https://nodejs.org/en/blog/npm/managing-node-js-dependencies-with-shrinkwrap/)

Why would one use nested classes in C++?

One can implement a Builder pattern with nested class. Especially in C++, personally I find it semantically cleaner. For example:

class Product{
    public:
        class Builder;
}
class Product::Builder {
    // Builder Implementation
}

Rather than:

class Product {}
class ProductBuilder {}

Use bash to find first folder name that contains a string

for example:

dir1=$(find . -name \*foo\* -type d -maxdepth 1 -print | head -n1)
echo "$dir1"

or (For the better shell solution see Adrian Frühwirth's answer)

for dir1 in *
do
    [[ -d "$dir1" && "$dir1" =~ foo ]] && break
    dir1=        #fix based on comment
done
echo "$dir1"

or

dir1=$(find . -type d -maxdepth 1 -print | grep 'foo' | head -n1)
echo "$dir1"

Edited head -n1 based on @ hek2mgl comment

Next based on @chepner's comments

dir1=$(find . -type d -maxdepth 1 -print | grep -m1 'foo')

or

dir1=$(find . -name \*foo\* -type d -maxdepth 1 -print -quit)

Can I use return value of INSERT...RETURNING in another INSERT?

table_ex

id default nextval('table_id_seq'::regclass),

camp1 varchar

camp2 varchar

INSERT INTO table_ex(camp1,camp2) VALUES ('xxx','123') RETURNING id 

Apache: The requested URL / was not found on this server. Apache

Non-trivial reasons:

  • if your .htaccess is in DOS format, change it to UNIX format (in Notepad++, click Edit>Convert )
  • if your .htaccess is in UTF8 Without-BOM, make it WITH BOM.

Add new row to excel Table (VBA)

I had the same error message and after lots of trial and error found out that it was caused by an advanced filter which was set on the ListObject. After clearing the advanced filter .listrows.add worked fine again. To clear the filter I use this - no idea how one could clear the filter only for the specific listobject instead of the complete worksheet.

Worksheets("mysheet").ShowAllData

How to add a new audio (not mixing) into a video using ffmpeg?

If the input video has multiple audio tracks and you need to add one more then use the following command:

ffmpeg -i input_video_with_audio.avi -i new_audio.ac3 -map 0 -map 1 -codec copy output_video.avi

-map 0 means to copy (include) all streams from the first input file (input_video_with_audio.avi) and -map 1 means to include all streams (in this case one) from the second input file (new_audio.ac3).

How to check if a file is a valid image file?

One option is to use the filetype package.

Installation

python -m pip install filetype

Advantages

  1. Quick: Does its work by loading the first few bytes of your image (check on the magic number)
  2. Supports different mime type: Images, Videos, Fonts, Audio, Archives.

Example

filetype >= 1.0.7

import filetype

filename = "/path/to/file.jpg"

if filetype.is_image(filename):
    print(f"{filename} is a valid image...")
elif filetype.is_video(filename):
    print(f"{filename} is a valid video...")

filetype <= 1.0.6

import filetype

filename = "/path/to/file.jpg"

if filetype.image(filename):
    print(f"{filename} is a valid image...")
elif filetype.video(filename):
    print(f"{filename} is a valid video...")

Additional information on the official repo: https://github.com/h2non/filetype.py

Synchronous XMLHttpRequest warning and <script>

In my case if i append script tag like this :

var script = document.createElement('script');
script.src = 'url/test.js';
$('head').append($(script));

i get that warning but if i append script tag to head first then change src warning gone !

var script = document.createElement('script');
$('head').append($(script));
script.src = 'url/test.js';

works fine!!

escaping question mark in regex javascript

You should use double slash:

var regex = new RegExp("\\?", "g");

Why? because in JavaScript the \ is also used to escape characters in strings, so: "\?" becomes: "?"

And "\\?", becomes "\?"

Decompile Python 2.7 .pyc

In case anyone is still struggling with this, as I was all morning today, I have found a solution that works for me:

Uncompyle

Installation instructions:

git clone https://github.com/gstarnberger/uncompyle.git
cd uncompyle/
sudo ./setup.py install

Once the program is installed (note: it will be installed to your system-wide-accessible Python packages, so it should be in your $PATH), you can recover your Python files like so:

uncompyler.py thank_goodness_this_still_exists.pyc > recovered_file.py

The decompiler adds some noise mostly in the form of comments, however I've found it to be surprisingly clean and faithful to my original code. You will have to remove a little line of text beginning with +++ near the end of the recovered file to be able to run your code.

Arguments to main in C

For parsing command line arguments on posix systems, the standard is to use the getopt() family of library routines to handle command line arguments.

A good reference is the GNU getopt manual

How can I dynamically add items to a Java array?

Apache Commons has an ArrayUtils implementation to add an element at the end of the new array:

/** Copies the given array and adds the given element at the end of the new array. */
public static <T> T[] add(T[] array, T element)

How to close current tab in a browser window?

As far as I can tell, it no longer is possible in Chrome or FireFox. It may still be possible in IE (at least pre-Edge).

SQL Server IN vs. EXISTS Performance

Off the top of my head and not guaranteed to be correct: I believe the second will be faster in this case.

  1. In the first, the correlated subquery will likely cause the subquery to be run for each row.
  2. In the second example, the subquery should only run once, since not correlated.
  3. In the second example, the IN will short-circuit as soon as it finds a match.

change image opacity using javascript

First set the opacity explicitly in your HTML thus:

<div id="box" style="height:150px; width:150px; background-color:orange; margin:25px; opacity:1"></div>

otherwise it is 0 or null

this is then in my .js file

document.getElementById("fadeButton90").addEventListener("click", function(){
document.getElementById("box").style.opacity  =   document.getElementById("box").style.opacity*0.90; });

Fastest way to count exact number of rows in a very large table?

Maybe a bit late but this might help others for MSSQL

;WITH RecordCount AS (  SELECT      ROW_NUMBER() OVER (ORDER BY
COLUMN_NAME) AS [RowNumber]     FROM        TABLE_NAME )  SELECT
MAX(RowNumber) FROM RecordCount

Using SSH keys inside docker container

As eczajk already commented in Daniel van Flymen's answer it does not seem to be safe to remove the keys and use --squash, as they still will be visible in the history (docker history --no-trunc).

Instead with Docker 18.09, you can now use the "build secrets" feature. In my case I cloned a private git repo using my hosts SSH key with the following in my Dockerfile:

# syntax=docker/dockerfile:experimental

[...]

RUN --mount=type=ssh git clone [...]

[...]

To be able to use this, you need to enable the new BuildKit backend prior to running docker build:

export DOCKER_BUILDKIT=1

And you need to add the --ssh default parameter to docker build.

More info about this here: https://medium.com/@tonistiigi/build-secrets-and-ssh-forwarding-in-docker-18-09-ae8161d066

How to add a primary key to a MySQL table?

This code work in my mysql db:

ALTER TABLE `goods`
ADD COLUMN `id` INT NOT NULL AUTO_INCREMENT,
ADD PRIMARY KEY (`id`);

Ruby combining an array into one string

Use the Array#join method (the argument to join is what to insert between the strings - in this case a space):

@arr.join(" ")

get current date with 'yyyy-MM-dd' format in Angular 4

you can try doing this.


component.ts

currentDate = new Date();

component.html

{{currentDate | date:'yyyy-MM-dd'}}

Windows 7, 64 bit, DLL problems

This problem is related to missing the Visual Studio "redistributable package." It is not obvious which one is missing based on the dependency walk, but I would try the one that corresponds with your compiler version first and see if things run properly:

Visual Studio 2015

Visual Studio 2013

Visual Studio 2010

Visual Studio 2008

I ran into this problem because I am using the Visual Studio compilers, but not the full Visual Studio environment.


Going to dare to inject a new link here: The latest supported Visual C++ downloads. Stein Åsmul, 29.11.2018.

Move all files except one

A quick way would be to modify the tux filename so that your move command will not match.

For example:

mv Tux.png .Tux.png

mv * ~/somefolder

mv .Tux.png Tux.png

Can't connect to local MySQL server through socket homebrew

I had same problem. After trying all these methods without success I did the following:

tail -f the-mysql-or-maria-db-error-file.err

in another console:

brew services restart mariadb

I saw the following error:

"MAC HOMEBREW Crash recovery failed. Either correct the problem (if it's, for example, out of memory error) and restart, or delete tc log and start mysqld with"

So I changed the tc.log extesion to tc.log.txt and restart mariadb

brew services restart mariadb

and done!

current/duration time of html5 video?

This page might help you out. Everything you need to know about HTML5 video and audio

var video = document.createElement('video');
var curtime = video.currentTime;

If you already have the video element, .currentTime should work. If you need more details, that webpage should be able to help.

CSS: How can I set image size relative to parent height?

you can use flex box for it.. this will solve your problem

.image-parent 
{
     height:33px; 
     display:flex; 
}

Quick way to list all files in Amazon S3 bucket?

I'd recommend using boto. Then it's a quick couple of lines of python:

from boto.s3.connection import S3Connection

conn = S3Connection('access-key','secret-access-key')
bucket = conn.get_bucket('bucket')
for key in bucket.list():
    print key.name.encode('utf-8')

Save this as list.py, open a terminal, and then run:

$ python list.py > results.txt

How to get a function name as a string?

As an extension of @Demyn's answer, I created some utility functions which print the current function's name and current function's arguments:

import inspect
import logging
import traceback

def get_function_name():
    return traceback.extract_stack(None, 2)[0][2]

def get_function_parameters_and_values():
    frame = inspect.currentframe().f_back
    args, _, _, values = inspect.getargvalues(frame)
    return ([(i, values[i]) for i in args])

def my_func(a, b, c=None):
    logging.info('Running ' + get_function_name() + '(' + str(get_function_parameters_and_values()) +')')
    pass

logger = logging.getLogger()
handler = logging.StreamHandler()
formatter = logging.Formatter(
    '%(asctime)s [%(levelname)s] -> %(message)s')
handler.setFormatter(formatter)
logger.addHandler(handler)
logger.setLevel(logging.INFO)

my_func(1, 3) # 2016-03-25 17:16:06,927 [INFO] -> Running my_func([('a', 1), ('b', 3), ('c', None)])

How can I view a git log of just one user's commits?

This works for both git log and gitk - the 2 most common ways of viewing history.
You don't need to use the whole name:

git log --author="Jon"

will match a commit made by "Jonathan Smith"

git log --author=Jon

and

git log --author=Smith

would also work. The quotes are optional if you don't need any spaces.

Add --all if you intend to search all branches and not just the current commit's ancestors in your repo.

You can also easily match on multiple authors as regex is the underlying mechanism for this filter. So to list commits by Jonathan or Adam, you can do this:

git log --author="\(Adam\)\|\(Jon\)"

In order to exclude commits by a particular author or set of authors using regular expressions as noted in this question, you can use a negative lookahead in combination with the --perl-regexp switch:

git log --author='^(?!Adam|Jon).*$' --perl-regexp

Alternatively, you can exclude commits authored by Adam by using bash and piping:

git log --format='%H %an' | 
  grep -v Adam | 
  cut -d ' ' -f1 | 
  xargs -n1 git log -1

If you want to exclude commits commited (but not necessarily authored) by Adam, replace %an with %cn. More details about this are in my blog post here: http://dymitruk.com/blog/2012/07/18/filtering-by-author-name/

Permission denied for relation

Make sure you log into psql as the owner of the tables. to find out who own the tables use \dt

psql -h CONNECTION_STRING DBNAME -U OWNER_OF_THE_TABLES

then you can run the GRANTS

All com.android.support libraries must use the exact same version specification

Here is my flow to fix this warning

build.gradle

android {
    compileSdkVersion ... // must same version (ex: 26)
    ...
}

dependencies {
    ...
    compile 'any com.android.support... library'  // must same version (ex: 26.0.1)
    compile 'any com.android.support... library'  // must same version (ex: 26.0.1)

    ...
    compile ('a library B which don't use 'com.android.support...' OR use SAME version of 'com.android.support'){
         // do nothing 
    }

    ...
    compile ('a library C which use DIFFERENT 'com.android.support...' (ex:27.0.1) { 
        // By default, if use don't do anything here your app will choose the higher com.android.support... for whole project (in this case it is 27.0.1)

        // If you want to use 26.0.1 use
        exclude group: 'com.android.support', module: '...' (ex module: 'appcompat-v7') 
        exclude group: 'com.android.support', module: 'another module'
        ...

        // If you want to use 27.0.1 do 
        Upgrade `compileSdkVersion` and all 'com.android.support' to 27.0.1.
        (It may be a good solution because the best practice is always use latest `compileSdkVersion`.  
        However, use 26 or 27 is base on you for example higher library may have bug)
    }
}

To view/verify the dependencies of all library in your app
Open terminal and run ./gradlew app:dependencies

To view the dependencies of a specific library in your app follow tutorial here :- How to exclude dependencies of a particular dependency in Gradle

Hope it help

Get ID of element that called a function

For others unexpectedly getting the Window element, a common pitfall:

<a href="javascript:myfunction(this)">click here</a>

which actually scopes this to the Window object. Instead:

<a href="javascript:nop()" onclick="myfunction(this)">click here</a>

passes the a object as expected. (nop() is just any empty function.)

Drop-down menu that opens up/upward with pure css

Add bottom:100% to your #menu:hover ul li:hover ul rule

Demo 1

#menu:hover ul li:hover ul {
    position: absolute;
    margin-top: 1px;
    font: 10px;
    bottom: 100%; /* added this attribute */
}

Or better yet to prevent the submenus from having the same effect, just add this rule

Demo 2

#menu>ul>li:hover>ul { 
    bottom:100%;
}

Demo 3

source: http://jsfiddle.net/W5FWW/4/

And to get back the border you can add the following attribute

#menu>ul>li:hover>ul { 
    bottom:100%;
    border-bottom: 1px solid transparent
}

Component is not part of any NgModule or the module has not been imported into your module

In my case the imports of real routes in app.component.spec.ts were causing these error messages. Solution was to import RouterTestingModule instead.

import { TestBed, async } from '@angular/core/testing';
import { AppComponent } from './app.component';
import { RouterTestingModule } from '@angular/router/testing';

describe('AppComponent', () => {
  beforeEach(async(() => {
    TestBed.configureTestingModule({
      declarations: [
        AppComponent
      ],
      imports: [RouterTestingModule]
    }).compileComponents();
  }));

  it('should create the app', async(() => {
    const fixture = TestBed.createComponent(AppComponent);
    console.log(fixture);
    const app = fixture.debugElement.componentInstance;
    expect(app).toBeTruthy();
  }));

});

How do I calculate the normal vector of a line segment?

This question has been posted long time ago, but I found an alternative way to answer it. So I decided to share it here.
Firstly, one must know that: if two vectors are perpendicular, their dot product equals zero.
The normal vector (x',y') is perpendicular to the line connecting (x1,y1) and (x2,y2). This line has direction (x2-x1,y2-y1), or (dx,dy).
So,

(x',y').(dx,dy) = 0
x'.dx + y'.dy = 0

The are plenty of pairs (x',y') that satisfy the above equation. But the best pair that ALWAYS satisfies is either (dy,-dx) or (-dy,dx)

powershell - extract file name and extension

Check the BaseName and Extension properties of the FileInfo object.

How copy data from Excel to a table using Oracle SQL Developer

It's not exactly copy and paste but you can import data from Excel using Oracle SQL Developer.

Navigate to the table you want to import the data into and click on the Data tab.

After clicking on the data tab you should notice a drop down that says Actions... indicating the position of the Data tab and Actions... drop down

Click Actions... and select the bottom option Import Data...

Then just follow the wizard to select the correct sheet, and columns that you want to import.

EDIT : To view the data tab :

  1. Select the SCHEMA where your table is created.(Choose from the Connections tab on the left pane).
  2. Right click on the SCHEMA and choose SCHEMA BROWSER.
  3. Select your table from the list (by giving your schema).
  4. Now you will see the DATA tab.
  5. Click on Actions and Import Data...

String replacement in batch file

You can use the following little trick:

set word=table
set str="jump over the chair"
call set str=%%str:chair=%word%%%
echo %str%

The call there causes another layer of variable expansion, making it necessary to quote the original % signs but it all works out in the end.

Calling a particular PHP function on form submit

In the following line

<form method="post" action="display()">

the action should be the name of your script and you should call the function, Something like this

<form method="post" action="yourFileName.php">
    <input type="text" name="studentname">
    <input type="submit" value="click" name="submit"> <!-- assign a name for the button -->
</form>

<?php
function display()
{
    echo "hello ".$_POST["studentname"];
}
if(isset($_POST['submit']))
{
   display();
} 
?>

HTML - Change\Update page contents without refreshing\reloading the page

jQuery will do the job. You can use either jQuery.ajax function, which is general one for performing ajax calls, or its wrappers: jQuery.get, jQuery.post for getting/posting data. Its very easy to use, for example, check out this tutorial, which shows how to use jQuery with PHP.

How can I pass arguments to a batch file?

Yep, and just don't forget to use variables like %%1 when using if and for and the gang.

If you forget the double %, then you will be substituting in (possibly null) command line arguments and you will receive some pretty confusing error messages.

How to find the serial port number on Mac OS X?

I was able to screen using the device's name anyway so that wasn't the issue. I was actually just trying to find the port number, i.e. 5331, 5332 etc. I managed to find this by a trial and error process using an app called TCP2Serial from the app store on Mac OS X. It isn't free but that's fine as long as I know it works!

Worth the 99c :) http://itunes.apple.com/us/app/tcp2serial/id506186902?mt=12

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

Make sure you import csv file using Pandas

import pandas as pd

condition = pd.isnull(data[i][j])

How to convert OutputStream to InputStream?

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

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

Hope it helps.

Reference - What does this error mean in PHP?

Code doesn't run/what looks like parts of my PHP code are output

If you see no result from your PHP code whatsoever and/or you are seeing parts of your literal PHP source code output in the webpage, you can be pretty sure that your PHP isn't actually getting executed. If you use View Source in your browser, you're probably seeing the whole PHP source code file as is. Since PHP code is embedded in <?php ?> tags, the browser will try to interpret those as HTML tags and the result may look somewhat confused.

To actually run your PHP scripts, you need:

  • a web server which executes your script
  • to set the file extension to .php, otherwise the web server won't interpret it as such*
  • to access your .php file via the web server

* Unless you reconfigure it, everything can be configured.

This last one is particularly important. Just double clicking the file will likely open it in your browser using an address such as:

file://C:/path/to/my/file.php

This is completely bypassing any web server you may have running and the file is not getting interpreted. You need to visit the URL of the file on your web server, likely something like:

http://localhost/my/file.php

You may also want to check whether you're using short open tags <? instead of <?php and your PHP configuration has turned short open tags off.

Also see PHP code is not being executed, instead code shows on the page

How to make Python speak

Please note that this only work with python 2.x

You should try using the PyTTSx package since PyTTS is outdated. PyTTSx works with the lastest python version.

http://pypi.python.org/pypi/pyttsx/1.0 -> The package

Hope it helps

How to open local file on Jupyter?

Install jupyter. Open terminal. Go to folder where you file is (in terminal ie.cd path/to/folder). Run jupyter notebook. And voila: you have something like this:

enter image description here

Notice that to open a notebook in the folder, you can either click on it in the browser or go to address:

http://localhost:8888/notebooks/name_of_your_file.ipynb

How to update Pandas from Anaconda and is it possible to use eclipse with this last

Simply type conda update pandas in your preferred shell (on Windows, use cmd; if Anaconda is not added to your PATH use the Anaconda prompt). You can of course use Eclipse together with Anaconda, but you need to specify the Python-Path (the one in the Anaconda-Directory). See this document for a detailed instruction.

Is it possible in Java to access private fields via reflection

Yes it is possible.

You need to use the getDeclaredField method (instead of the getField method), with the name of your private field:

Field privateField = Test.class.getDeclaredField("str");

Additionally, you need to set this Field to be accessible, if you want to access a private field:

privateField.setAccessible(true);

Once that's done, you can use the get method on the Field instance, to access the value of the str field.

log4j logging hierarchy order

This table might be helpful for you:

Log Level

Going down the first column, you will see how the log works in each level. i.e for WARN, (FATAL, ERROR and WARN) will be visible. For OFF, nothing will be visible.

Iterate through string array in Java

As long as this question remains unsanswered the OP's problem and Java has evolved over the years, I have decided to put my own one.

Let's change for sake of clarity the input String array to have 5 unique items.

String[] elements = {"a", "b", "c", "d", "e"};

You want to access two siblings in the list with each iteration incremented by one index.

for (int i=0; i<elements.length-1; i++) {        // note the condition
    String left = elements[i];
    String right = elements[i+1];

    System.out.println(left + " " + right);      // prints 4 lines
}

Printing the pairs of left and right in four iterations result in the lines a b, b c, c d, d e in your console.

What can happen if the input string array has less than 2 elements? Nothing prints our as long as this for-loop extracts always two sibling nodes. With less than 2 elements the program doesn't enter to the loop itself.

As far as your snippet says you want to not discard the extracted values but add them an another variable, assuming outside the scope of the for-loop, you want to store them in either a list or an array. Let's say you want to concatenate the siblings with the + character.

List<String> list = new ArrayList<>();
String[] array = new String[elements.length-1];  // note the defined size

for (int i=0; i<elements.length-1; i++) {
    String left = elements[i];
    String right = elements[i+1];

    list.add(left + "+" + right);            // adds to the list
    array[i] = left + "+" + right;           // adds to the array
}

Printing the contents both of the list and the array (Arrays.toString(array)) results in:

[a+b, b+c, c+d, d+e]

Java 8

As of Java 8, you might be tempted to use the advantage of Stream API, however, it was made for procesing the individual elements from a source collection. There is no such method for processing 2 or more sibling nodes at once.

The only way is to use Stream API to process the indices instead and map them to the real value. As long as you start with a primitive Stream called IntStream you need to use IntStream::mapToObj method to get boxed Stream<T>:

String[] array = IntStream.range(0, elements.length-1)
    .mapToObj(i -> elements[i] + "+" + elements[i + 1])
    .toArray(String[]::new);                              // [a+b, b+c, c+d, d+e]

List<String> list = IntStream.range(0, elements.length-1)
    .mapToObj(i -> elements[i] + "+" + elements[i + 1])
    .collect(Collectors.toList());                        // [a+b, b+c, c+d, d+e]

Two onClick actions one button

<input type="button" value="..." onClick="fbLikeDump(); WriteCookie();" />

Rownum in postgresql

If you have a unique key, you may use COUNT(*) OVER ( ORDER BY unique_key ) as ROWNUM

SELECT t.*, count(*) OVER (ORDER BY k ) ROWNUM 
FROM yourtable t;

| k |     n | rownum |
|---|-------|--------|
| a | TEST1 |      1 |
| b | TEST2 |      2 |
| c | TEST2 |      3 |
| d | TEST4 |      4 |

DEMO

Location of sqlite database on the device

This is and old question, but answering may help others.

Default path where Android saves databases can not be accesed on non-rooted devices. So, the easiest way to access to database file (only for debugging environments) is to modify the constructor of the class:

public class MySQLiteOpenHelper extends SQLiteOpenHelper {
    MySQLiteOpenHelper(Context context) {
        super(context, "/mnt/sdcard/database_name.db", null, 0);
    }
}

Remember to change for production environments with these lines:

public class MySQLiteOpenHelper extends SQLiteOpenHelper {
    MySQLiteOpenHelper(Context context) {
        super(context, "database_name.db", null, 0);
    }
}

How to control border height?

Only using line-height

line-height: 10px;

enter image description here

How to correctly dismiss a DialogFragment?

Just call dismiss() from the fragment you want to dismiss.

imageView3.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            dismiss();
        }
    });

Git commit -a "untracked files"?

git commit -am "msg" is not same as git add file and git commit -m "msg"

If you have some files which were never added to git tracking you still need to do git add file

The “git commit -a” command is a shortcut to a two-step process. After you modify a file that is already known by the repo, you still have to tell the repo, “Hey! I want to add this to the staged files and eventually commit it to you.” That is done by issuing the “git add” command. “git commit -a” is staging the file and committing it in one step.

Source: "git commit -a" and "git add"

Create GUI using Eclipse (Java)

There are lot of GUI designers even like Eclipse plugins, just few of them could use both, Swing and SWT..

WindowBuilder Pro GUI Designer - eclipse marketplace

WindowBuilder Pro GUI Designer - Google code home page

and

Jigloo SWT/Swing GUI Builder - eclipse market place

Jigloo SWT/Swing GUI Builder - home page

The window builder is quite better tool..

But IMHO, GUIs created by those tools have really ugly and unmanageable code..

SQL update query using joins

UPDATE im
SET mf_item_number = gm.SKU --etc
FROM item_master im
JOIN group_master gm
    ON im.sku = gm.sku 
JOIN Manufacturer_Master mm
    ON gm.ManufacturerID = mm.ManufacturerID
WHERE im.mf_item_number like 'STA%' AND
      gm.manufacturerID = 34

To make it clear... The UPDATE clause can refer to an table alias specified in the FROM clause. So im in this case is valid

Generic example

UPDATE A
SET foo = B.bar
FROM TableA A
JOIN TableB B
    ON A.col1 = B.colx
WHERE ...

XPath with multiple conditions

question is not clear, but what i understand you need to select a catagory that has name attribute and should have child author with value specified , correct me if i am worng

here is a xpath

//category[@name='Required value'][./author[contains(.,'Required value')]]
e.g
//category[@name='Sport'][./author[contains(.,'James Small')]]

Get User's Current Location / Coordinates

import CoreLocation
import UIKit

class ViewController: UIViewController, CLLocationManagerDelegate {

    var locationManager: CLLocationManager!

    override func viewDidLoad() {
        super.viewDidLoad()
        locationManager = CLLocationManager()
        locationManager.delegate = self
        locationManager.requestWhenInUseAuthorization()
    } 

    func locationManager(_ manager: CLLocationManager, didChangeAuthorization status: CLAuthorizationStatus) {
        if status != .authorizedWhenInUse {return}
        locationManager.desiredAccuracy = kCLLocationAccuracyBest
        locationManager.startUpdatingLocation()
        let locValue: CLLocationCoordinate2D = manager.location!.coordinate
        print("locations = \(locValue.latitude) \(locValue.longitude)")
    }
}

Because the call to requestWhenInUseAuthorization is asynchronous, the app calls the locationManager function after the user has granted permission or rejected it. Therefore it is proper to place your location getting code inside that function given the user granted permission. This is the best tutorial on this I have found on it.

How to apply border radius in IE8 and below IE8 browsers?

HTML:

<div id="myElement">Rounded Corner Box</div>

CSS:

#myElement {
    background: #EEE;
    padding: 2em;
    -moz-border-radius: 1em;
    -webkit-border-radius: 1em;
    border-radius: 1em;
    behavior: url(PIE.htc);
    border: 1px solid red;

}

PIE.htc file can be downloaded from http://www.css3pie.com

Rollback transaction after @Test

In addition to adding @Transactional on @Test method, you also need to add @Rollback(false)

Why an interface can not implement another interface?

implements means implementation, when interface is meant to declare just to provide interface not for implementation.

A 100% abstract class is functionally equivalent to an interface but it can also have implementation if you wish (in this case it won't remain 100% abstract), so from the JVM's perspective they are different things.

Also the member variable in a 100% abstract class can have any access qualifier, where in an interface they are implicitly public static final.

How can I render inline JavaScript with Jade / Pug?

THIRD VERSION OF MY ANSWER:

Here's a multiple line example of inline Jade Javascript. I don't think you can write it without using a -. This is a flash message example that I use in a partial. Hope this helps!

-if(typeof(info) !== 'undefined')
  -if (info)
    - if(info.length){
      ul
        -info.forEach(function(info){
          li= info
      -})
  -}

Is the code you're trying to get to compile the code in your question?

If so, you don't need two things: first, you don't need to declare that it's Javascript/a script, you can just started coding after typing -; second, after you type -if you don't need to type the { or } either. That's what makes Jade pretty sweet.

--------------ORIGINAL ANSWER BELOW ---------------

Try prepending if with -:

-if(10 == 10)
  //do whatever you want here as long as it's indented two spaces from
   the `-` above

There are also tons of Jade examples at:

https://github.com/visionmedia/jade/blob/master/examples/

"for line in..." results in UnicodeDecodeError: 'utf-8' codec can't decode byte

If you are using Python 2, the following will be the solution:

import io
for line in io.open("u.item", encoding="ISO-8859-1"):
    # Do something

Because the encoding parameter doesn't work with open(), you will be getting the following error:

TypeError: 'encoding' is an invalid keyword argument for this function

Java path..Error of jvm.cfg

Resolved

I had similar issue, I tried different things but nothing worked. Then when I checked the installed programs. I could see two versions of java installed.

What I did is, just uninstall all java versions and freshly installed the required version. But this didn't seem to work when I checked in terminal. Then I had to reopen the terminal and run the command, then only it worked.

Note : Dont forget to reopen the terminal if you are testing via terminal.

Binding Button click to a method

You have various possibilies. The most simple and the most ugly is:

XAML

<Button Name="cmdCommand" Click="Button_Clicked" Content="Command"/> 

Code Behind

private void Button_Clicked(object sender, RoutedEventArgs e) { 
    FrameworkElement fe=sender as FrameworkElement;
    ((YourClass)fe.DataContext).DoYourCommand();     
} 

Another solution (better) is to provide a ICommand-property on your YourClass. This command will have already a reference to your YourClass-object and therefore can execute an action on this class.

XAML

<Button Name="cmdCommand" Command="{Binding YourICommandReturningProperty}" Content="Command"/>

Because during writing this answer, a lot of other answers were posted, I stop writing more. If you are interested in one of the ways I showed or if you think I have made a mistake, make a comment.

Customize UITableView header section

If you use default header view you can only change the text on it with

- (NSString *)tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section

For Swift:

override func tableView(tableView: UITableView, titleForHeaderInSection section: Int) -> String? {

If you want to customize the view you need to create a new one your self.

What is ModelState.IsValid valid for in ASP.NET MVC in NerdDinner?

ModelState.IsValid tells you if any model errors have been added to ModelState.

The default model binder will add some errors for basic type conversion issues (for example, passing a non-number for something which is an "int"). You can populate ModelState more fully based on whatever validation system you're using.

The sample DataAnnotations model binder will fill model state with validation errors taken from the DataAnnotations attributes on your model.

How do you implement a good profanity filter?

Beware of localization issues: what is a swearword in one language might be a perfectly normal word in another.

One current example of this: ebay uses a dictionary approach to filter "bad words" from feedback. If you try to enter the german translation of "this was a perfect transaction" ("das war eine perfekte Transaktion"), ebay will reject the feedback due to bad words.

Why? Because the german word for "was" is "war", and "war" is in ebay dictionary of "bad words".

So beware of localisation issues.

After installing with pip, "jupyter: command not found"

I compiled python3.7 from the source code, with the following command

./configure --prefix=/opt/python3.7.4 --with-ssl
make
make install

after pip3.7 install jupyter I found the executable is under /opt/python3.7.4/bin

check my answer here Missing sqlite3 after Python3 compile to get more detail comping python3.7 and pip under ubuntu14.04

How do I list all remote branches in Git 1.7+?

Using this command,

git log -r --oneline --no-merges --simplify-by-decoration --pretty=format:"%n %Cred CommitID %Creset: %h %n %Cred Remote Branch %Creset :%d %n %Cred Commit Message %Creset: %s %n"

CommitID       : 27385d919
Remote Branch  : (origin/ALPHA)
Commit Message :  New branch created

It lists all remote branches including commit messages and commit IDs that are referred to by remote branches.

Oracle 10g: Extract data (select) from XML (CLOB Type)

In case the XML store in the CLOB field in the database table. E.g for this XML:

<?xml version="1.0" encoding="UTF-8" standalone="yes"?>
<Awmds>
    <General_segment>
        <General_segment_id>
        <Customs_office_code>000</Customs_office_code>
    </General_segment_id>
</General_segment>
</Awmds>

This is the Extract Query:

SELECT EXTRACTVALUE (
    xmltype (T.CLOB_COLUMN_NAME),
    '/Awmds/General_segment/General_segment_id/Customs_office_code')
    AS Customs_office_code
FROM TABLE_NAME t;

SQLSTATE[HY093]: Invalid parameter number: parameter was not defined

I had the same error. My issue was using the wrong parameter name when binding.

Notice :tokenHash in the query, but :token_hash when binding. Fixing one or the other resolves the error in this instance.

// Prepare DB connection
$sql = 'INSERT INTO rememberedlogins (token_hash,user_id,expires_at)
        VALUES (:tokenHash,:user_id,:expires_at)';
$db = static::getDB();
$stmt = $db->prepare($sql);

// Bind values
$stmt->bindValue(':token_hash',$hashed_token,PDO::PARAM_STR);

Node.js setting up environment specific configs to be used with everyauth

This answer is not something new. It's similar to what @andy_t has mentioned. But I use the below pattern for two reasons.

  1. Clean implementation with No external npm dependencies

  2. Merge the default config settings with the environment based settings.

Javascript implementation

const settings = {
    _default: {
       timeout: 100
       baseUrl: "http://some.api/",
    },
    production: {
       baseUrl: "http://some.prod.api/",
    },
}
// If you are not using ECMAScript 2018 Standard
// https://stackoverflow.com/a/171256/1251350
module.exports = { ...settings._default, ...settings[process.env.NODE_ENV] }

I usually use typescript in my node project. Below is my actual implementation copy-pasted.

Typescript implementation

const settings: { default: ISettings, production: any } = {
    _default: {
        timeout: 100,
        baseUrl: "",
    },
    production: {
        baseUrl: "",
    },
}

export interface ISettings {
    baseUrl: string
}

export const config = ({ ...settings._default, ...settings[process.env.NODE_ENV] } as ISettings)

Purge or recreate a Ruby on Rails database

You can use db:reset - for run db:drop and db:setup or db:migrate:reset - which runs db:drop, db:create and db:migrate.

dependent at you want to use exist schema.rb

Laravel Eloquent LEFT JOIN WHERE NULL

This can be resolved by specifying the specific column names desired from the specific table like so:

$c = Customer::leftJoin('orders', function($join) {
      $join->on('customers.id', '=', 'orders.customer_id');
    })
    ->whereNull('orders.customer_id')
    ->first([
        'customers.id',
        'customers.first_name',
        'customers.last_name',
        'customers.email',
        'customers.phone',
        'customers.address1',
        'customers.address2',
        'customers.city',
        'customers.state',
        'customers.county',
        'customers.district',
        'customers.postal_code',
        'customers.country'
    ]);

Python read JSON file and modify

Set item using data['id'] = ....

import json

with open('data.json', 'r+') as f:
    data = json.load(f)
    data['id'] = 134 # <--- add `id` value.
    f.seek(0)        # <--- should reset file position to the beginning.
    json.dump(data, f, indent=4)
    f.truncate()     # remove remaining part

Awaiting multiple Tasks with different results

You can use Task.WhenAll as mentioned, or Task.WaitAll, depending on whether you want the thread to wait. Take a look at the link for an explanation of both.

WaitAll vs WhenAll

Batch script to install MSI

Here is the batch file which should work for you:

@echo off
Title HOST: Installing updates on %computername%
echo %computername%
set Server=\\SERVERNAME or PATH\msifolder

:select
cls
echo Select one of the following MSI install folders for installation task.
echo.
dir "%Server%" /AD /ON /B
echo.
set /P "MSI=Please enter the MSI folder to install: "
set "Package=%Server%\%MSI%\%MSI%.msi"

if not exist "%Package%" (
   echo.
   echo The entered folder/MSI file does not exist ^(typing mistake^).
   echo.
   setlocal EnableDelayedExpansion
   set /P "Retry=Try again [Y/N]: "
   if /I "!Retry!"=="Y" endlocal & goto select
   endlocal
   goto :EOF
)

echo.
echo Selected installation: %MSI%
echo.
echo.

:verify
echo Is This Correct?
echo.
echo.
echo    0: ABORT INSTALL
echo    1: YES
echo    2: NO, RE-SELECT
echo.
set /p "choice=Select YES, NO or ABORT? [0,1,2]: "
if [%choice%]==[0] goto :EOF
if [%choice%]==[1] goto yes
goto select

:yes
echo.
echo Running %MSI% installation ...
start "Install MSI" /wait "%SystemRoot%\system32\msiexec.exe" /i /quiet "%Package%"

The characters listed on last page output on entering in a command prompt window either help cmd or cmd /? have special meanings in batch files. Here are used parentheses and square brackets also in strings where those characters should be interpreted literally. Therefore it is necessary to either enclose the string in double quotes or escape those characters with character ^ as it can be seen in code above, otherwise command line interpreter exits batch execution because of a syntax error.

And it is not possible to call a file with extension MSI. A *.msi file is not an executable. On double clicking on a MSI file, Windows looks in registry which application is associated with this file extension for opening action. And the application to use is msiexec with the command line option /i to install the application inside MSI package.

Run msiexec.exe /? to get in a GUI window the available options or look at Msiexec (command-line options).

I have added already /quiet additionally to required option /i for a silent installation.

In batch code above command start is used with option /wait to start Windows application msiexec.exe and hold execution of batch file until installation finished (or aborted).

How to switch to other branch in Source Tree to commit the code?

  1. Go to the log view (to be able to go here go to View -> log view).
  2. Double click on the line with the branch label stating that branch. Automatically, it will switch branch. (A prompt will dropdown and say switching branch.)
  3. If you have two or more branches on the same line, it will ask you via prompt which branch you want to switch. Choose the specific branch from the dropdown and click ok.

To determine which branch you are now on, look at the side bar, under BRANCHES, you are in the branch that is in BOLD LETTERS.

Force uninstall of Visual Studio

So Soumyaansh's Revo Uninstaller Pro fix worked for me :) ( After 2 days of troubleshooting other options {screams internally 😀} ).

I did run into the an issue with his method though, "Could not find a suitable SDK to target" even though I selected to install Visual Studio with custom settings and selected the SDK I wanted to install. You may need to download the Windows 10 Standalone SDK to resolved this, in order to develop UWP apps if you see this same error after reinstalling Visual Studio.

To do this

  1. Uninstall any Windows 10 SDKs that me on the system (the naming schem for them looks like Windows 10 SDK (WINDOWS_VERSION_NUMBER_HERE) -> Windows 10 SDK (14393) etc . . .). If there are no SDKs on your system go to step 2!
  2. All that's left is to download the SDKs you want by Checking out the SDK Archive for all available SDKs and you should be good to go in developing for the UWP!

Save matplotlib file to a directory

Here is a simple example for saving to a directory(external usb drive) using Python version 2.7.10 with Sublime Text 2 editor:

import numpy as np 
import matplotlib.pyplot as plt

X = np.linspace(-np.pi, np.pi, 256, endpoint = True)
C, S = np.cos(X), np.sin(X)

plt.plot(X, C, color = "blue", linewidth = 1.0, linestyle = "-")
plt.plot(X, S, color = "red", linewidth = 1.0, linestyle = "-")

plt.savefig("/Volumes/seagate/temp_swap/sin_cos_2.png", dpi = 72)

Create a Bitmap/Drawable from file path

Well, using the static Drawable.createFromPath(String pathName) seems a bit more straightforward to me than decoding it yourself... :-)

If your mImg is a simple ImageView, you don't even need it, use mImg.setImageUri(Uri uri) directly.

Chrome doesn't delete session cookies

Google chrome has a problem if you set and unset cookie improper way. This is php code. Thought this will give you idea.

Set cookie

setcookie('userLoggedIn', 1, 0, PATH);

Wrong way and will not work (notice PATH is missing)

setcookie('userLoggedIn', 0, time()-3600);

Correct way fixes issue on google chrome

setcookie('userLoggedIn', 0, time()-3600, PATH);

Recover unsaved SQL query scripts

I use the free file searching program Everything, search for *.sql files across my C: drive, and then sort by Last Modified, and then browse by the date I think it was probably last executed.

It usually brings up loads of autorecovery files from a variety of locations. And you don't have to worry where the latest version of SSMS/VS is saving the backup files this version.

enter image description here

Context.startForegroundService() did not then call Service.startForeground()

So many answer but none worked in my case.

I have started service like this.

if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
    startForegroundService(intent);
} else {
    startService(intent);
}

And in my service in onStartCommand

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
        Notification.Builder builder = new Notification.Builder(this, ANDROID_CHANNEL_ID)
                .setContentTitle(getString(R.string.app_name))
                .setContentText("SmartTracker Running")
                .setAutoCancel(true);
        Notification notification = builder.build();
        startForeground(NOTIFICATION_ID, notification);
    } else {
        NotificationCompat.Builder builder = new NotificationCompat.Builder(this)
                .setContentTitle(getString(R.string.app_name))
                .setContentText("SmartTracker is Running...")
                .setPriority(NotificationCompat.PRIORITY_DEFAULT)
                .setAutoCancel(true);
        Notification notification = builder.build();
        startForeground(NOTIFICATION_ID, notification);
    }

And don't forgot to set NOTIFICATION_ID non zero

private static final String ANDROID_CHANNEL_ID = "com.xxxx.Location.Channel";
private static final int NOTIFICATION_ID = 555;

SO everything was perfect but still crashing on 8.1 so cause was as below.

     if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
            stopForeground(true);
        } else {
            stopForeground(true);
        }

I have called stop foreground with remove notificaton but once notification removed service become background and background service can not run in android O from background. started after push received.

So magical word is

   stopSelf();

So far so any reason your service is crashing follow all above steps and enjoy.

Bundle ID Suffix? What is it?

If you don't have a company, leave your name, it doesn't matter as long as both bundle id in info.plist file and the one you've submitted in iTunes Connect match.

In Bundle ID Suffix you should write full name of bundle ID.

Example:

Bundle ID suffix = thebestapp (NOT CORRECT!!!!)

Bundle ID suffix = com.awesomeapps.thebestapp (CORRECT!!)

The reason for this is explained in the Developer Portal:

The App ID string contains two parts separated by a period (.) — an App ID Prefix (your Team ID by default, e.g. ABCDE12345), and an App ID Suffix (a Bundle ID search string, e.g. com.mycompany.appname). [emphasis added]

So in this case the suffix is the full string com.awesomeapps.thebestapp.

Angular.js and HTML5 date input value -- how to get Firefox to show a readable date value in a date input?

I've used ng-change:

_x000D_
_x000D_
Date.prototype.addDays = function(days) {_x000D_
  var dat = new Date(this.valueOf());_x000D_
  dat.setDate(dat.getDate() + days);_x000D_
  return dat;_x000D_
}_x000D_
_x000D_
var app = angular.module('myApp', []);_x000D_
_x000D_
app.controller('DateController', ['$rootScope', '$scope',_x000D_
  function($rootScope, $scope) {_x000D_
    function init() {_x000D_
      $scope.startDate = new Date();_x000D_
      $scope.endDate = $scope.startDate.addDays(14);_x000D_
    }_x000D_
_x000D_
_x000D_
    function load() {_x000D_
      alert($scope.startDate);_x000D_
      alert($scope.endDate);_x000D_
    }_x000D_
_x000D_
    init();_x000D_
    // public methods_x000D_
    $scope.load = load;_x000D_
    $scope.setStart = function(date) {_x000D_
      $scope.startDate = date;_x000D_
    };_x000D_
    $scope.setEnd = function(date) {_x000D_
      $scope.endDate = date;_x000D_
    };_x000D_
_x000D_
  }_x000D_
]);
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.2.23/angular.min.js"></script>_x000D_
<div data-ng-controller="DateController">_x000D_
  <label class="item-input"> <span class="input-label">Start</span>_x000D_
    <input type="date" data-ng-model="startDate" ng-change="setStart(startDate)" required validatedateformat calendar>_x000D_
  </label>_x000D_
  <label class="item-input"> <span class="input-label">End</span>_x000D_
    <input type="date" data-ng-model="endDate" ng-change="setEnd(endDate)" required validatedateformat calendar>_x000D_
  </label>_x000D_
  <button button="button" ng-disabled="planningForm.$invalid" ng-click="load()" class="button button-positive">_x000D_
    Run_x000D_
  </button>_x000D_
</div <label class="item-input"> <span class="input-label">Start</span>_x000D_
<input type="date" data-ng-model="startDate" ng-change="setStart(startDate)" required validatedateformat calendar>_x000D_
</label>_x000D_
<label class="item-input"> <span class="input-label">End</span>_x000D_
  <input type="date" data-ng-model="endDate" ng-change="setEnd(endDate)" required validatedateformat calendar>_x000D_
</label>
_x000D_
_x000D_
_x000D_

JavaScript - XMLHttpRequest, Access-Control-Allow-Origin errors

I think you've missed the point of access control.

A quick recap on why CORS exists: Since JS code from a website can execute XHR, that site could potentially send requests to other sites, masquerading as you and exploiting the trust those sites have in you(e.g. if you have logged in, a malicious site could attempt to extract information or execute actions you never wanted) - this is called a CSRF attack. To prevent that, web browsers have very stringent limitations on what XHR you can send - you are generally limited to just your domain, and so on.

Now, sometimes it's useful for a site to allow other sites to contact it - sites that provide APIs or services, like the one you're trying to access, would be prime candidates. CORS was developed to allow site A(e.g. paste.ee) to say "I trust site B, so you can send XHR from it to me". This is specified by site A sending "Access-Control-Allow-Origin" headers in its responses.

In your specific case, it seems that paste.ee doesn't bother to use CORS. Your best bet is to contact the site owner and find out why, if you want to use paste.ee with a browser script. Alternatively, you could try using an extension(those should have higher XHR privileges).

How do I get the current date and time in PHP?

The best way to get the current time and date is by the date function in PHP:

$date = date('FORMAT'); // FORMAT E.g.: Y-m-d H:i:s

$current_date = date('Y-m-d H:i:s');

With the Unix timestamp:

$now_date = date('FORMAT', time()); // FORMAT Eg : Y-m-d H:i:s

To set the server time zone:

date_default_timezone_set('Asia/Calcutta');

A different time zone list is here.

How to read until EOF from cin in C++

After researching KeithB's solution using std::istream_iterator, I discovered the std:istreambuf_iterator.

Test program to read all piped input into a string, then write it out again:

#include <iostream>
#include <iterator>
#include <string>

int main()
{
  std::istreambuf_iterator<char> begin(std::cin), end;
  std::string s(begin, end);
  std::cout << s;
}

Practical uses for AtomicInteger

For example, I have a library that generates instances of some class. Each of these instances must have a unique integer ID, as these instances represent commands being sent to a server, and each command must have a unique ID. Since multiple threads are allowed to send commands concurrently, I use an AtomicInteger to generate those IDs. An alternative approach would be to use some sort of lock and a regular integer, but that's both slower and less elegant.

Python class input argument

Python Classes

class name:
    def __init__(self, name):
        self.name = name
        print("name: "+name)

Somewhere else:

john = name("john")

Output:
name: john

Regular expression for matching HH:MM time format

Try the following

^([0-2][0-3]:[0-5][0-9])|(0?[0-9]:[0-5][0-9])$

Note: I was assuming the javascript regex engine. If it's different than that please let me know.

RestTemplate: How to send URL and query parameters together

String url = "http://test.com/Services/rest/{id}/Identifier";
Map<String, String> params = new HashMap<String, String>();
params.put("id", "1234");
URI uri = UriComponentsBuilder.fromUriString(url)
        .buildAndExpand(params)
        .toUri();
uri = UriComponentsBuilder
        .fromUri(uri)
        .queryParam("name", "myName")
        .build()
        .toUri();
restTemplate.exchange(uri , HttpMethod.PUT, requestEntity, class_p);

The safe way is to expand the path variables first, and then add the query parameters:

For me this resulted in duplicated encoding, e.g. a space was decoded to %2520 (space -> %20 -> %25).

I solved it by:

String url = "http://test.com/Services/rest/{id}/Identifier";
Map<String, String> params = new HashMap<String, String>();
params.put("id", "1234");
UriComponentsBuilder uriComponentsBuilder = UriComponentsBuilder.fromUriString(url);
uriComponentsBuilder.uriVariables(params);
Uri uri = uriComponentsBuilder.queryParam("name", "myName");
        .build()
        .toUri();
restTemplate.exchange(uri , HttpMethod.PUT, requestEntity, class_p);

Essentially I am using uriComponentsBuilder.uriVariables(params); to add path parameters. The documentation says:

... In contrast to UriComponents.expand(Map) or buildAndExpand(Map), this method is useful when you need to supply URI variables without building the UriComponents instance just yet, or perhaps pre-expand some shared default values such as host and port. ...

Source: https://docs.spring.io/spring-framework/docs/current/javadoc-api/org/springframework/web/util/UriComponentsBuilder.html#uriVariables-java.util.Map-

A valid provisioning profile for this executable was not found for debug mode

I faced same issue there may some other reasons too:

While testing i set my date to some future date and profile got expired. As result this issue was generated.

But i solved by setting date of iphone to current date as a result profile was not expired. 

Why can't DateTime.Parse parse UTC date

You need to specify the format:

DateTime date = DateTime.ParseExact(
    "Tue, 1 Jan 2008 00:00:00 UTC", 
    "ddd, d MMM yyyy HH:mm:ss UTC", 
    CultureInfo.InvariantCulture);

When to use RabbitMQ over Kafka?

I'll provide an objective answer based on my experience with both, I'll also skip the theory behind them, assuming you already know it and/or other answers has already provided enough.

RabbitMQ: I'd pick this one if my requirements are simple enough to deal with system communication through channels/queues, retention and streaming is not a requirement. For e.g. When the manufacture system built the asset it does notify the agreement system to configure the contracts and so on.

Kafka: Event sourcing requirement mainly, when you may need to deal with streams (sometimes infinite), huge amount of data at once properly balanced, replay offsets in order to ensure a given state and so on. Keep in mind that this architecture brings more complexity as well, since it does include concepts such as topics/partitions/brokers/tombstone messages, etc. as a first class importance.

What's the best way to validate an XML file against an XSD file?

I had to validate an XML against XSD just one time, so I tried XMLFox. I found it to be very confusing and weird. The help instructions didn't seem to match the interface.

I ended up using LiquidXML Studio 2008 (v6) which was much easier to use and more immediately familiar (the UI is very similar to Visual Basic 2008 Express, which I use frequently). The drawback: the validation capability is not in the free version, so I had to use the 30 day trial.

Using %f with strftime() in Python to get microseconds

You can also get microsecond precision from the time module using its time() function.
(time.time() returns the time in seconds since epoch. Its fractional part is the time in microseconds, which is what you want.)

>>> from time import time
>>> time()
... 1310554308.287459   # the fractional part is what you want.


# comparision with strftime -
>>> from datetime import datetime
>>> from time import time
>>> datetime.now().strftime("%f"), time()
... ('287389', 1310554310.287459)

What's the difference between xsd:include and xsd:import?

Another difference is that <import> allows importing by referring to another namespace. <include> only allows importing by referring to a URI of intended include schema. That is definitely another difference than inter-intra namespace importing.

For example, the xml schema validator may already know the locations of all schemas by namespace already. Especially considering that referring to XML namespaces by URI may be problematic on different systems where classpath:// means nothing, or where http:// isn't allowed, or where some URI doesn't point to the same thing as it does on another system.

Code sample of valid and invalid imports and includes:

Valid:

<xsd:import namespace="some/name/space"/>
<xsd:import schemaLocation="classpath://mine.xsd"/>

<xsd:include schemaLocation="classpath://mine.xsd"/>

Invalid:

<xsd:include namespace="some/name/space"/>

What is the inclusive range of float and double in Java?

Binary floating-point numbers have interesting precision characteristics, since the value is stored as a binary integer raised to a binary power. When dealing with sub-integer values (that is, values between 0 and 1), negative powers of two "round off" very differently than negative powers of ten.

For example, the number 0.1 can be represented by 1 x 10-1, but there is no combination of base-2 exponent and mantissa that can precisely represent 0.1 -- the closest you get is 0.10000000000000001.

So if you have an application where you are working with values like 0.1 or 0.01 a great deal, but where small (less than 0.000000000000001%) errors cannot be tolerated, then binary floating-point numbers are not for you.

Conversely, if powers of ten are not "special" to your application (powers of ten are important in currency calculations, but not in, say, most applications of physics), then you are actually better off using binary floating-point, since it's usually at least an order of magnitude faster, and it is much more memory efficient.

The article from the Python documentation on floating point issues and limitations does an excellent job of explaining this issue in an easy to understand form. Wikipedia also has a good article on floating point that explains the math behind the representation.

How to move from one fragment to another fragment on click of an ImageView in Android?

you can move to another fragment by using the FragmentManager transactions. Fragment can not be called like activities,. Fragments exists on the existance of activities.

You can call another fragment by writing the code below:

        FragmentTransaction t = this.getFragmentManager().beginTransaction();
        Fragment mFrag = new MyFragment();
        t.replace(R.id.content_frame, mFrag);
        t.commit();

here "R.id.content_frame" is the id of the layout on which you want to replace the fragment.

you can also add the other fragment incase of replace.

How to add minutes to my Date

Once you have you date parsed, I use this utility function to add hours, minutes or seconds:

public class DateTimeUtils {
    private static final long ONE_HOUR_IN_MS = 3600000;
    private static final long ONE_MIN_IN_MS = 60000;
    private static final long ONE_SEC_IN_MS = 1000;

    public static Date sumTimeToDate(Date date, int hours, int mins, int secs) {
        long hoursToAddInMs = hours * ONE_HOUR_IN_MS;
        long minsToAddInMs = mins * ONE_MIN_IN_MS;
        long secsToAddInMs = secs * ONE_SEC_IN_MS;
        return new Date(date.getTime() + hoursToAddInMs + minsToAddInMs + secsToAddInMs);
    }
}

Be careful when adding long periods of time, 1 day is not always 24 hours (daylight savings-type adjustments, leap seconds and so on), Calendar is recommended for that.

Map and Reduce in .NET

Since I never can remember that LINQ calls it Where, Select and Aggregate instead of Filter, Map and Reduce so I created a few extension methods you can use:

IEnumerable<string> myStrings = new List<string>() { "1", "2", "3", "4", "5" };
IEnumerable<int> convertedToInts = myStrings.Map(s => int.Parse(s));
IEnumerable<int> filteredInts = convertedToInts.Filter(i => i <= 3); // Keep 1,2,3
int sumOfAllInts = filteredInts.Reduce((sum, i) => sum + i); // Sum up all ints
Assert.Equal(6, sumOfAllInts); // 1+2+3 is 6

Here are the 3 methods (from https://github.com/cs-util-com/cscore/blob/master/CsCore/PlainNetClassLib/src/Plugins/CsCore/com/csutil/collections/IEnumerableExtensions.cs ):

public static IEnumerable<R> Map<T, R>(this IEnumerable<T> self, Func<T, R> selector) {
    return self.Select(selector);
}

public static T Reduce<T>(this IEnumerable<T> self, Func<T, T, T> func) {
    return self.Aggregate(func);
}

public static IEnumerable<T> Filter<T>(this IEnumerable<T> self, Func<T, bool> predicate) {
    return self.Where(predicate);
}

Some more details from https://github.com/cs-util-com/cscore#ienumerable-extensions :

enter image description here

'True' and 'False' in Python

From 6.11. Boolean operations:

In the context of Boolean operations, and also when expressions are used by control flow statements, the following values are interpreted as false: False, None, numeric zero of all types, and empty strings and containers (including strings, tuples, lists, dictionaries, sets and frozensets). All other values are interpreted as true.

The key phrasing here that I think you are misunderstanding is "interpreted as false" or "interpreted as true". This does not mean that any of those values are identical to True or False, or even equal to True or False.

The expression '/bla/bla/bla' will be treated as true where a Boolean expression is expected (like in an if statement), but the expressions '/bla/bla/bla' is True and '/bla/bla/bla' == True will evaluate to False for the reasons in Ignacio's answer.

How to fix a locale setting warning from Perl

For Debian users, I have this problem after modifying my locale to change machine's language. This is what I did:

  1. Modify .bashrc:

    export LANG=fr_FR.UTF-8
    export LC_ALL=fr_FR.UTF-8
    
  2. Uncomment line fr_FR.UTF-8 in file etc/locale.gen -> sudo locale-gen to generate the missing package

  3. sudo update-locale

  4. sudo dpkg-reconfigure locales to configure my locale to fr_FR.UTF-8

  5. Add extra lines to the etc/default/locale file:

    LANGUAGE=en_US.UTF-8
    LC_ALL=en_US.UTF-8
    LANG=en_US.UTF-8
    LC_TYPE=en_US.UTF-8
    
  6. Reboot my computer and everything works fine

Splitting a string into separate variables

It is important to note the following difference between the two techniques:

$Str="This is the<BR />source string<BR />ALL RIGHT"
$Str.Split("<BR />")
This
is
the
(multiple blank lines)
source
string
(multiple blank lines)
ALL
IGHT
$Str -Split("<BR />")
This is the
source string
ALL RIGHT 

From this you can see that the string.split() method:

  • performs a case sensitive split (note that "ALL RIGHT" his split on the "R" but "broken" is not split on the "r")
  • treats the string as a list of possible characters to split on

While the -split operator:

  • performs a case-insensitive comparison
  • only splits on the whole string

Android Gradle Apache HttpClient does not exist?

I suggest you replace the deprecated apache HttpClient with the new HttpURLConnection.

That's a cleaner solution, it's quite easy to migrate, and generally it's better to stick to the latest SDK changes than trying to hack/patch/workaround: you usually regret it later :)

Step 1

HttpGet httpGet = new HttpGet(url);

becomes:

URL urlObj = new URL(url);

Step 2

HttpClient httpClient = new DefaultHttpClient();
HttpContext localContext = new BasicHttpContext();
HttpResponse response = httpClient.execute(httpGet, localContext);
InputStream is = response.getEntity().getContent();

becomes:

HttpURLConnection urlConnection = (HttpURLConnection) urlObj.openConnection();
InputStream is = urlConnection.getInputStream();

Step 2 bis

int status = response.getStatusLine().getStatusCode();

becomes:

int status = urlConnection.getResponseCode();

How to convert a currency string to a double with jQuery or Javascript?

var parseCurrency = function (e) {
    if (typeof (e) === 'number') return e;
    if (typeof (e) === 'string') {
        var str = e.trim();
        var value = Number(e.replace(/[^0-9.-]+/g, ""));
        return str.startsWith('(') && str.endsWith(')') ? -value: value;
    }

    return e;
} 

How to safely upgrade an Amazon EC2 instance from t1.micro to large?

From my experience, the way I do it is create a snapshot of your current image, then once its done you'll see it as an option when launching new instances. Simply launch it as a large instance at that point.

This is my approach if I do not want any downtime(i.e. production server) because this solution only takes a server offline only after the new one is up and running(I also use it to add new machines to my clusters by using this approach to only add new machines). If Downtime is acceptable then see Marcel Castilho's answer.

javascript filter array of objects

_x000D_
_x000D_
var nameList = [_x000D_
{name:'x', age:20, email:'[email protected]'},_x000D_
{name:'y', age:60, email:'[email protected]'},_x000D_
{name:'Joe', age:22, email:'[email protected]'},_x000D_
{name:'Abc', age:40, email:'[email protected]'}_x000D_
];_x000D_
_x000D_
var filteredValue = nameList.filter(function (item) {_x000D_
      return item.name == "Joe" && item.age < 30;_x000D_
});_x000D_
_x000D_
//To See Output Result as Array_x000D_
console.log(JSON.stringify(filteredValue));
_x000D_
_x000D_
_x000D_

You can simply use javascript :)

How to remove element from an array in JavaScript?

You can use the ES6 Destructuring Assignment feature with a rest operator. A comma indicates where you want to remove the element and the rest (...arr) operator to give you the remaining elements of the array.

_x000D_
_x000D_
const source = [1,2,3,5,6];_x000D_
_x000D_
function removeFirst(list) {_x000D_
   var  [, ...arr] = list;_x000D_
   return arr;_x000D_
}_x000D_
const arr = removeFirst(source);_x000D_
console.log(arr); // [2, 3, 5, 6]_x000D_
console.log(source); // [1, 2, 3, 5, 6]
_x000D_
_x000D_
_x000D_

Paging with LINQ for objects

   ( for o in objects
    where ...
    select new
   {
     A=o.a,
     B=o.b
   })
.Skip((page-1)*pageSize)
.Take(pageSize)

What is the best way to know if all the variables in a Class are null?

Another non-reflective solution for Java 8, in the line of paxdiabo's answer but without using a series of if's, would be to stream all fields and check for nullness:

return Stream.of(id, name)
        .allMatch(Objects::isNull);

This remains quite easy to maintain while avoiding the reflection hammer.

Get all table names of a particular database by SQL query?

USE dbName;

SELECT TABLE_NAME
FROM INFORMATION_SCHEMA.TABLES
WHERE (TABLE_SCHEMA = 'dbName' OR TABLE_SCHEMA = 'schemaName')
ORDER BY TABLE_NAME

If you are working with multiple schemata on an MS SQL server, then SELECT-ing TABLE_NAME without also simultaneously selecting TABLE_SCHEMA might be of limited benefit, so I have assumed we are interested in the tables belonging to a known schema when using MS SQL Server.

I have tested the query above with SQL Server Management Studio using an SQL Server database of mine and with MySQL Workbench using a MySQL database, and in both cases it gives the table names.

The query bodges Michael Baylon's two different queries into one that can then run on either database type. The first part of the WHERE clause works on MySQL databases and the second part (after the OR) works on MS SQL Server databases. It is ugly and logically a little incorrect as it supposes that there is no undesired schema with the same name as the database. This might help someone who is looking for one single query that can run on either database server.

What is the difference between “int” and “uint” / “long” and “ulong”?

uint and ulong are the unsigned versions of int and long. That means they can't be negative. Instead they have a larger maximum value.

Type    Min                           Max                           CLS-compliant
int     -2,147,483,648                2,147,483,647                 Yes
uint    0                             4,294,967,295                 No
long    –9,223,372,036,854,775,808    9,223,372,036,854,775,807     Yes
ulong   0                             18,446,744,073,709,551,615    No

To write a literal unsigned int in your source code you can use the suffix u or U for example 123U.

You should not use uint and ulong in your public interface if you wish to be CLS-Compliant.

Read the documentation for more information:

By the way, there is also short and ushort and byte and sbyte.

What is the difference between Swing and AWT?

AWT is a Java interface to native system GUI code present in your OS. It will not work the same on every system, although it tries.

Swing is a more-or-less pure-Java GUI. It uses AWT to create an operating system window and then paints pictures of buttons, labels, text, checkboxes, etc., into that window and responds to all of your mouse-clicks, key entries, etc., deciding for itself what to do instead of letting the operating system handle it. Thus Swing is 100% portable and is the same across platforms (although it is skinnable and has a "pluggable look and feel" that can make it look more or less like how the native windows and widgets would look).

These are vastly different approaches to GUI toolkits and have a lot of consequences. A full answer to your question would try to explore all of those. :) Here are a couple:

AWT is a cross-platform interface, so even though it uses the underlying OS or native GUI toolkit for its functionality, it doesn't provide access to everything that those toolkits can do. Advanced or newer AWT widgets that might exist on one platform might not be supported on another. Features of widgets that aren't the same on every platform might not be supported, or worse, they might work differently on each platform. People used to invest lots of effort to get their AWT applications to work consistently across platforms - for instance, they may try to make calls into native code from Java.

Because AWT uses native GUI widgets, your OS knows about them and handles putting them in front of each other, etc., whereas Swing widgets are meaningless pixels within a window from your OS's point of view. Swing itself handles your widgets' layout and stacking. Mixing AWT and Swing is highly unsupported and can lead to ridiculous results, such as native buttons that obscure everything else in the dialog box in which they reside because everything else was created with Swing.

Because Swing tries to do everything possible in Java other than the very raw graphics routines provided by a native GUI window, it used to incur quite a performance penalty compared to AWT. This made Swing unfortunately slow to catch on. However, this has shrunk dramatically over the last several years due to more optimized JVMs, faster machines, and (I presume) optimization of the Swing internals. Today a Swing application can run fast enough to be serviceable or even zippy, and almost indistinguishable from an application using native widgets. Some will say it took far too long to get to this point, but most will say that it is well worth it.

Finally, you might also want to check out SWT (the GUI toolkit used for Eclipse, and an alternative to both AWT and Swing), which is somewhat of a return to the AWT idea of accessing native Widgets through Java.

Go / golang time.Now().UnixNano() convert to milliseconds?

I think it's better to round the time to milliseconds before the division.

func makeTimestamp() int64 {
    return time.Now().Round(time.Millisecond).UnixNano() / (int64(time.Millisecond)/int64(time.Nanosecond))
}

Here is an example program:

package main

import (
        "fmt"
        "time"
)

func main() {
        fmt.Println(unixMilli(time.Unix(0, 123400000)))
        fmt.Println(unixMilli(time.Unix(0, 123500000)))
        m := makeTimestampMilli()
        fmt.Println(m)
        fmt.Println(time.Unix(m/1e3, (m%1e3)*int64(time.Millisecond)/int64(time.Nanosecond)))
}

func unixMilli(t time.Time) int64 {
        return t.Round(time.Millisecond).UnixNano() / (int64(time.Millisecond) / int64(time.Nanosecond))
}

func makeTimestampMilli() int64 {
        return unixMilli(time.Now())
}

The above program printed the result below on my machine:

123
124
1472313624305
2016-08-28 01:00:24.305 +0900 JST

Source file 'Properties\AssemblyInfo.cs' could not be found

This can also happen if you have a solution containing the project open in Visual Studio, then use your source control software to change to an older commit that does not contain that project. Normally, this would be obvious as all the project files would disappear as well. But, if it's a new project with very few or no files at all, it could be puzzling to see that just this one file, AssemblyInfo.cs, is missing. And, it's more likely you'd be messing about with an AssemblyInfo.cs when a project is new, so might miss that another file or two is also missing.

The cure is to do any of the following:

  • Fetch the missing AssemblyInfo.cs and any other missing files from another commit, taking care to manage and save your .csproj file so the referenced files don't vanish from the project—perhaps by adding and removing a random .cs file to cause changes to need to be saved (since visual studio thinks the .csproj file has been saved when it hasn't).
  • Close and reopen Visual Studio without saving (if the project file isn't really saved) or remove the project. Removing makes sense if you didn't actually want the project created yet, since it will be created in the later commit.
  • Recreate the AssemblyInfo.cs file manually. Just copy another project, and change the details, especially the GUID so it matches the one from the .sln file.

Rotating a Vector in 3D Space

If you want to rotate a vector you should construct what is known as a rotation matrix.

Rotation in 2D

Say you want to rotate a vector or a point by ?, then trigonometry states that the new coordinates are

    x' = x cos ? - y sin ?
    y' = x sin ? + y cos ?

To demo this, let's take the cardinal axes X and Y; when we rotate the X-axis 90° counter-clockwise, we should end up with the X-axis transformed into Y-axis. Consider

    Unit vector along X axis = <1, 0>
    x' = 1 cos 90 - 0 sin 90 = 0
    y' = 1 sin 90 + 0 cos 90 = 1
    New coordinates of the vector, <x', y'> = <0, 1>  ?  Y-axis

When you understand this, creating a matrix to do this becomes simple. A matrix is just a mathematical tool to perform this in a comfortable, generalized manner so that various transformations like rotation, scale and translation (moving) can be combined and performed in a single step, using one common method. From linear algebra, to rotate a point or vector in 2D, the matrix to be built is

    |cos ?   -sin ?| |x| = |x cos ? - y sin ?| = |x'|
    |sin ?    cos ?| |y|   |x sin ? + y cos ?|   |y'|

Rotation in 3D

That works in 2D, while in 3D we need to take in to account the third axis. Rotating a vector around the origin (a point) in 2D simply means rotating it around the Z-axis (a line) in 3D; since we're rotating around Z-axis, its coordinate should be kept constant i.e. 0° (rotation happens on the XY plane in 3D). In 3D rotating around the Z-axis would be

    |cos ?   -sin ?   0| |x|   |x cos ? - y sin ?|   |x'|
    |sin ?    cos ?   0| |y| = |x sin ? + y cos ?| = |y'|
    |  0       0      1| |z|   |        z        |   |z'|

around the Y-axis would be

    | cos ?    0   sin ?| |x|   | x cos ? + z sin ?|   |x'|
    |   0      1       0| |y| = |         y        | = |y'|
    |-sin ?    0   cos ?| |z|   |-x sin ? + z cos ?|   |z'|

around the X-axis would be

    |1     0           0| |x|   |        x        |   |x'|
    |0   cos ?    -sin ?| |y| = |y cos ? - z sin ?| = |y'|
    |0   sin ?     cos ?| |z|   |y sin ? + z cos ?|   |z'|

Note 1: axis around which rotation is done has no sine or cosine elements in the matrix.

Note 2: This method of performing rotations follows the Euler angle rotation system, which is simple to teach and easy to grasp. This works perfectly fine for 2D and for simple 3D cases; but when rotation needs to be performed around all three axes at the same time then Euler angles may not be sufficient due to an inherent deficiency in this system which manifests itself as Gimbal lock. People resort to Quaternions in such situations, which is more advanced than this but doesn't suffer from Gimbal locks when used correctly.

I hope this clarifies basic rotation.

Rotation not Revolution

The aforementioned matrices rotate an object at a distance r = v(x² + y²) from the origin along a circle of radius r; lookup polar coordinates to know why. This rotation will be with respect to the world space origin a.k.a revolution. Usually we need to rotate an object around its own frame/pivot and not around the world's i.e. local origin. This can also be seen as a special case where r = 0. Since not all objects are at the world origin, simply rotating using these matrices will not give the desired result of rotating around the object's own frame. You'd first translate (move) the object to world origin (so that the object's origin would align with the world's, thereby making r = 0), perform the rotation with one (or more) of these matrices and then translate it back again to its previous location. The order in which the transforms are applied matters. Combining multiple transforms together is called concatenation or composition.

Composition

I urge you to read about linear and affine transformations and their composition to perform multiple transformations in one shot, before playing with transformations in code. Without understanding the basic maths behind it, debugging transformations would be a nightmare. I found this lecture video to be a very good resource. Another resource is this tutorial on transformations that aims to be intuitive and illustrates the ideas with animation (caveat: authored by me!).

Rotation around Arbitrary Vector

A product of the aforementioned matrices should be enough if you only need rotations around cardinal axes (X, Y or Z) like in the question posted. However, in many situations you might want to rotate around an arbitrary axis/vector. The Rodrigues' formula (a.k.a. axis-angle formula) is a commonly prescribed solution to this problem. However, resort to it only if you’re stuck with just vectors and matrices. If you're using Quaternions, just build a quaternion with the required vector and angle. Quaternions are a superior alternative for storing and manipulating 3D rotations; it's compact and fast e.g. concatenating two rotations in axis-angle representation is fairly expensive, moderate with matrices but cheap in quaternions. Usually all rotation manipulations are done with quaternions and as the last step converted to matrices when uploading to the rendering pipeline. See Understanding Quaternions for a decent primer on quaternions.

Can linux cat command be used for writing text to file?

The Solution to your problem is :

echo " Some Text Goes Here " > filename.txt

But you can use cat command if you want to redirect the output of a file to some other file or if you want to append the output of a file to another file :

cat filename > newfile -- To redirect output of filename to newfile

cat filename >> newfile -- To append the output of filename to newfile

Twitter bootstrap collapse: change display of toggle button

You do like this. the function return the old text.

$('button').click(function(){ 
        $(this).text(function(i,old){
            return old=='Read More' ?  'Read Less' : 'Read More';
        });
    });

redirect to current page in ASP.Net

Why Server.Transfer? Response.Redirect(Request.RawUrl) would get you what you need.

Spark - repartition() vs coalesce()

Also another difference is taking into consideration a situation where there is a skew join and you have to coalesce on top of it. A repartition will solve the skew join in most cases, then you can do the coalesce.

Another situation is, suppose you have saved a medium/large volume of data in a data frame and you have to produce to Kafka in batches. A repartition helps to collectasList before producing to Kafka in certain cases. But, when the volume is really high, the repartition will likely cause serious performance impact. In that case, producing to Kafka directly from dataframe would help.

side notes: Coalesce does not avoid data movement as in full data movement between workers. It does reduce the number of shuffles happening though. I think that's what the book means.

How do I load an HTML page in a <div> using JavaScript?

When using

$("#content").load("content.html");

Then remember that you can not "debug" in chrome locally, because XMLHttpRequest cannot load -- This does NOT mean that it does not work, it just means that you need to test your code on same domain aka. your server

SQLAlchemy equivalent to SQL "LIKE" statement

try this code

output = dbsession.query(<model_class>).filter(<model_calss>.email.ilike('%' + < email > + '%'))

PHP 7 RC3: How to install missing MySQL PDO

I'll start with the answer then context NOTE this fix was logged above, I'm just re-stating it for anyone googling.

  1. Download the source code of php 7 and extract it.
  2. open your terminal
  3. swim to the ext/pdo_mysql directory
  4. use commands:

    phpize

    ./configure

    make

    make install (as root)

  5. enable extension=mysqli.so in your php.ini file

This is logged as an answer from here (please upvote it if it helped you too): https://stackoverflow.com/a/39277373/3912517

Context: I'm trying to add LimeSurvey to the standard WordPress Docker. The single point holding me back is "PHP PDO driver library" which is "None found"

php -i | grep PDO                                                                                  
PHP Warning:  PHP Startup: Unable to load dynamic library 'pdo_odbc' (tried: /usr/local/lib/php/extensions/no-debug-non-zts-20170718/pdo_odbc (/usr/local/lib/php/extensions/no-debug-non-zts-20170718/pdo_odbc: cannot open shared object file: No such file or directory), /usr/local/lib/php/extensions/no-debug-non-zts-20170718/pdo_odbc.so (/usr/local/lib/php/extensions/no-debug-non-zts-20170718/pdo_odbc.so: cannot open shared object file: No such file or directory)) in Unknown on line 0
PHP Warning:  Module 'mysqli' already loaded in Unknown on line 0
PDO
PDO support => enabled
PDO drivers => sqlite
PDO Driver for SQLite 3.x => enabled

Ubuntu 16 (Ubuntu 7.3.0)

apt-get install php7.0-mysql

Result:

Package 'php7.0-mysql' has no installation candidate

Get instructions saying all I have to do is run this:

add-apt-repository -y ppa:ondrej/apache2

But then I get this:

UnicodeDecodeError: 'ascii' codec can't decode byte 0xc5 in position 223: ordinal not in range(128)

So I try and force some type of UTF: LC_ALL=C.UTF-8 add-apt-repository -y ppa:ondrej/apache2 and I get this: no valid OpenPGP data found.

Follow some other instructions to run this: apt-get update and I get this: Err:14 http://ppa.launchpad.net/ondrej/apache2/ubuntu cosmic/main amd64 Packages 404 Not Found Err:15 http://ppa.launchpad.net/ondrej/php/ubuntu cosmic/main amd64 Packages 404 Not Found and - I think because of that - I then get:

The repository 'http://ppa.launchpad.net/ondrej/apache2/ubuntu cosmic Release' does not have a Release file.

By this stage, I'm still getting this on apt-get update:

Package 'php7.0-mysql' has no installation candidate.

I start trying to add in php libraries, got Unicode issues, tried to get around that and.... you get the idea... whack-a-mole. I gave up and looked to see if I could compile it and I found the answer I started with.

You might be wondering why I wrote so much? So that anyone googling can find this solution (including me!).

Case insensitive string compare in LINQ-to-SQL

If you pass a string that is case-insensitive into LINQ-to-SQL it will get passed into the SQL unchanged and the comparison will happen in the database. If you want to do case-insensitive string comparisons in the database all you need to to do is create a lambda expression that does the comparison and the LINQ-to-SQL provider will translate that expression into a SQL query with your string intact.

For example this LINQ query:

from user in Users
where user.Email == "[email protected]"
select user

gets translated to the following SQL by the LINQ-to-SQL provider:

SELECT [t0].[Email]
FROM [User] AS [t0]
WHERE [t0].[Email] = @p0
-- note that "@p0" is defined as nvarchar(11)
-- and is passed my value of "[email protected]"

As you can see, the string parameter will be compared in SQL which means things ought to work just the way you would expect them to.

Output a NULL cell value in Excel

I've been frustrated by this problem as well. Find/Replace can be helpful though, because if you don't put anything in the "replace" field it will replace with an -actual- NULL. So the steps would be something along the lines of:

1: Place some unique string in your formula in place of the NULL output (i like to use a password-like string)

2: Run your formula

3: Open Find/Replace, and fill in the unique string as the search value. Leave "replace with" blank

4: Replace All

Obviously, this has limitations. It only works when the context allows you to do a find/replace, so for more dynamic formulas this won't help much. But, I figured I'd put it up here anyway.

ActiveMQ or RabbitMQ or ZeroMQ or

If you are also interested in commercial implementations, you should take a look at Nirvana from my-channels.

Nirvana is used heavily within the Financial Services industry for large scale low-latency trading and price distribution platforms.

There is support for a wide range of client programming languages across the enterprise, web and mobile domains.

The clustering capabilities are extremely advanced and worth a look if transparent HA or load balancing is important for you.

Nirvana is free to download for development purposes.

Angular 4/5/6 Global Variables

You can access Globals entity from any point of your App via Angular dependency injection. If you want to output Globals.role value in some component's template, you should inject Globals through the component's constructor like any service:

// hello.component.ts
import { Component } from '@angular/core';
import { Globals } from './globals';

@Component({
  selector: 'hello',
  template: 'The global role is {{globals.role}}',
  providers: [ Globals ] // this depends on situation, see below
})

export class HelloComponent {
  constructor(public globals: Globals) {}
}

I provided Globals in the HelloComponent, but instead it could be provided in some HelloComponent's parent component or even in AppModule. It will not matter until your Globals has only static data that could not be changed (say, constants only). But if it's not true and for example different components/services might want to change that data, then the Globals must be a singleton. In that case it should be provided in the topmost level of the hierarchy where it is going to be used. Let's say this is AppModule:

import { Globals } from './globals'

@NgModule({
  // ... imports, declarations etc
  providers: [
    // ... other global providers
    Globals // so do not provide it into another components/services if you want it to be a singleton
  ]
})

Also, it's impossible to use var the way you did, it should be

// globals.ts
import { Injectable } from '@angular/core';

@Injectable()
export class Globals {
  role: string = 'test';
}

Update

At last, I created a simple demo on stackblitz, where single Globals is being shared between 3 components and one of them can change the value of Globals.role.

How do I get a Cron like scheduler in Python?

I don't know if something like that already exists. It would be easy to write your own with time, datetime and/or calendar modules, see http://docs.python.org/library/time.html

The only concern for a python solution is that your job needs to be always running and possibly be automatically "resurrected" after a reboot, something for which you do need to rely on system dependent solutions.

Error: allowDefinition='MachineToApplication' beyond application level

Clean your project Remove the /obj folder (probably using publish and deploy? - there is a bug in it)

C/C++ macro string concatenation

Hint: The STRINGIZE macro above is cool, but if you make a mistake and its argument isn't a macro - you had a typo in the name, or forgot to #include the header file - then the compiler will happily put the purported macro name into the string with no error.

If you intend that the argument to STRINGIZE is always a macro with a normal C value, then

#define STRINGIZE(A) ((A),STRINGIZE_NX(A))

will expand it once and check it for validity, discard that, and then expand it again into a string.

It took me a while to figure out why STRINGIZE(ENOENT) was ending up as "ENOENT" instead of "2"... I hadn't included errno.h.

How can I grep for a string that begins with a dash/hyphen?

If you're using another utility that passes a single argument to grep, you can use:

'[-]X'

in a "using" block is a SqlConnection closed on return or exception?

In your first example, the C# compiler will actually translate the using statement to the following:

SqlConnection connection = new SqlConnection(connectionString));

try
{
    connection.Open();

    string storedProc = "GetData";
    SqlCommand command = new SqlCommand(storedProc, connection);
    command.CommandType = CommandType.StoredProcedure;
    command.Parameters.Add(new SqlParameter("@EmployeeID", employeeID));

    return (byte[])command.ExecuteScalar();
}
finally
{
    connection.Dispose();
}

Finally statements will always get called before a function returns and so the connection will be always closed/disposed.

So, in your second example the code will be compiled to the following:

try
{
    try
    {
        connection.Open();

        string storedProc = "GetData";
        SqlCommand command = new SqlCommand(storedProc, connection);
        command.CommandType = CommandType.StoredProcedure;
        command.Parameters.Add(new SqlParameter("@EmployeeID", employeeID));

        return (byte[])command.ExecuteScalar();
    }
    finally
    {
        connection.Dispose();
    }
}
catch (Exception)
{
}

The exception will be caught in the finally statement and the connection closed. The exception will not be seen by the outer catch clause.

Comparison of full text search engine - Lucene, Sphinx, Postgresql, MySQL?

I would add mnoGoSearch to the list. Extremely performant and flexible solution, which works as Google : indexer fetches data from multiple sites, You could use basic criterias, or invent Your own hooks to have maximal search quality. Also it could fetch the data directly from the database.

The solution is not so known today, but it feets maximum needs. You could compile and install it or on standalone server, or even on Your principal server, it doesn't need so much ressources as Solr, as it's written in C and runs perfectly even on small servers.

In the beginning You need to compile it Yourself, so it requires some knowledge. I made a tiny script for Debian, which could help. Any adjustments are welcome.

As You are using Django framework, You could use or PHP client in the middle, or find a solution in Python, I saw some articles.

And, of course mnoGoSearch is open source, GNU GPL.

How to add new elements to an array?

As tangens said, the size of an array is fixed. But you have to instantiate it first, else it will be only a null reference.

String[] where = new String[10];

This array can contain only 10 elements. So you can append a value only 10 times. In your code you're accessing a null reference. That's why it doesnt work. In order to have a dynamically growing collection, use the ArrayList.

How to use the 'main' parameter in package.json?

To answer your first question, the way you load a module is depending on the module entry point and the main parameter of the package.json.

Let's say you have the following file structure:

my-npm-module
|-- lib
|   |-- module.js
|-- package.json

Without main parameter in the package.json, you have to load the module by giving the module entry point: require('my-npm-module/lib/module.js').

If you set the package.json main parameter as follows "main": "lib/module.js", you will be able to load the module this way: require('my-npm-module').

How to convert java.lang.Object to ArrayList?

This only results in null if obj2 was already null before the cast, so your problem is earlier than you think. (Also, you need not construct a new ArrayList to initialize al1 if you're going to assign to it immediately. Just say ArrayList al1 = (ArrayList) obj2;.)

maxReceivedMessageSize and maxBufferSize in app.config

binding name="BindingName" 
maxReceivedMessageSize="2097152" 
maxBufferSize="2097152" 
maxBufferPoolSize="2097152" 

on client side and server side

Parameterize an SQL IN clause

Here is another answer to this problem.

(new version posted on 6/4/13).

    private static DataSet GetDataSet(SqlConnectionStringBuilder scsb, string strSql, params object[] pars)
    {
        var ds = new DataSet();
        using (var sqlConn = new SqlConnection(scsb.ConnectionString))
        {
            var sqlParameters = new List<SqlParameter>();
            var replacementStrings = new Dictionary<string, string>();
            if (pars != null)
            {
                for (int i = 0; i < pars.Length; i++)
                {
                    if (pars[i] is IEnumerable<object>)
                    {
                        List<object> enumerable = (pars[i] as IEnumerable<object>).ToList();
                        replacementStrings.Add("@" + i, String.Join(",", enumerable.Select((value, pos) => String.Format("@_{0}_{1}", i, pos))));
                        sqlParameters.AddRange(enumerable.Select((value, pos) => new SqlParameter(String.Format("@_{0}_{1}", i, pos), value ?? DBNull.Value)).ToArray());
                    }
                    else
                    {
                        sqlParameters.Add(new SqlParameter(String.Format("@{0}", i), pars[i] ?? DBNull.Value));
                    }
                }
            }
            strSql = replacementStrings.Aggregate(strSql, (current, replacementString) => current.Replace(replacementString.Key, replacementString.Value));
            using (var sqlCommand = new SqlCommand(strSql, sqlConn))
            {
                if (pars != null)
                {
                    sqlCommand.Parameters.AddRange(sqlParameters.ToArray());
                }
                else
                {
                    //Fail-safe, just in case a user intends to pass a single null parameter
                    sqlCommand.Parameters.Add(new SqlParameter("@0", DBNull.Value));
                }
                using (var sqlDataAdapter = new SqlDataAdapter(sqlCommand))
                {
                    sqlDataAdapter.Fill(ds);
                }
            }
        }
        return ds;
    }

Cheers.

How to remove elements from a generic list while iterating over it?

There is an option that hasn't been mentioned here.

If you don't mind adding a bit of code somewhere in your project, you can add and extension to List to return an instance of a class that does iterate through the list in reverse.

You would use it like this :

foreach (var elem in list.AsReverse())
{
    //Do stuff with elem
    //list.Remove(elem); //Delete it if you want
}

And here is what the extension looks like:

public static class ReverseListExtension
{
    public static ReverseList<T> AsReverse<T>(this List<T> list) => new ReverseList<T>(list);

    public class ReverseList<T> : IEnumerable
    {
        List<T> list;
        public ReverseList(List<T> list){ this.list = list; }

        public IEnumerator GetEnumerator()
        {
            for (int i = list.Count - 1; i >= 0; i--)
                yield return list[i];
            yield break;
        }
    }
}

This is basically list.Reverse() without the allocation.

Like some have mentioned you still get the drawback of deleting elements one by one, and if your list is massively long some of the options here are better. But I think there is a world where someone would want the simplicity of list.Reverse(), without the memory overhead.