Programs & Examples On #Number sequence

How can I find the dimensions of a matrix in Python?

As Ayman farhat mentioned you can use the simple method len(matrix) to get the length of rows and get the length of the first row to get the no. of columns using len(matrix[0]) :

>>> a=[[1,5,6,8],[1,2,5,9],[7,5,6,2]]
>>> len(a)
3
>>> len(a[0])
4

Also you can use a library that helps you with matrices "numpy":

>>> import numpy 
>>> numpy.shape(a)
(3,4)

How to duplicate a whole line in Vim?

Normal mode: see other answers.

The Ex way:

  • :t. will duplicate the line,
  • :t 7 will copy it after line 7,
  • :,+t0 will copy current and next line at the beginning of the file (,+ is a synonym for the range .,.+1),
  • :1,t$ will copy lines from beginning till cursor position to the end (1, is a synonym for the range 1,.).

If you need to move instead of copying, use :m instead of :t.

This can be really powerful if you combine it with :g or :v:

  • :v/foo/m$ will move all lines not matching the pattern “foo” to the end of the file.
  • :+,$g/^\s*class\s\+\i\+/t. will copy all subsequent lines of the form class xxx right after the cursor.

Reference: :help range, :help :t, :help :g, :help :m and :help :v

Get Date Object In UTC format in Java

final Date currentTime = new Date();
final SimpleDateFormat sdf = new SimpleDateFormat("EEE, MMM d, yyyy hh:mm:ss a z");
sdf.setTimeZone(TimeZone.getTimeZone("UTC"));
System.out.println("UTC time: " + sdf.format(currentTime));

Retrieve specific commit from a remote Git repository

Starting with Git version 2.5+ (Q2 2015), fetching a single commit (without cloning the full repo) is actually possible.

See commit 68ee628 by Fredrik Medley (moroten), 21 May 2015.
(Merged by Junio C Hamano -- gitster -- in commit a9d3493, 01 Jun 2015)

You now have a new config (on the server side)

uploadpack.allowReachableSHA1InWant

Allow upload-pack to accept a fetch request that asks for an object that is reachable from any ref tip. However, note that calculating object reachability is computationally expensive.
Defaults to false.

If you combine that server-side configuration with a shallow clone (git fetch --depth=1), you can ask for a single commit (see t/t5516-fetch-push.sh:

git fetch --depth=1 ../testrepo/.git $SHA1

You can use the git cat-file command to see that the commit has been fetched:

git cat-file commit $SHA1

"git upload-pack" that serves "git fetch" can be told to serve commits that are not at the tip of any ref, as long as they are reachable from a ref, with uploadpack.allowReachableSHA1InWant configuration variable.


The full documentation is:

upload-pack: optionally allow fetching reachable sha1

With uploadpack.allowReachableSHA1InWant configuration option set on the server side, "git fetch" can make a request with a "want" line that names an object that has not been advertised (likely to have been obtained out of band or from a submodule pointer).
Only objects reachable from the branch tips, i.e. the union of advertised branches and branches hidden by transfer.hideRefs, will be processed.
Note that there is an associated cost of having to walk back the history to check the reachability.

This feature can be used when obtaining the content of a certain commit, for which the sha1 is known, without the need of cloning the whole repository, especially if a shallow fetch is used.

Useful cases are e.g.

  • repositories containing large files in the history,
  • fetching only the needed data for a submodule checkout,
  • when sharing a sha1 without telling which exact branch it belongs to and in Gerrit, if you think in terms of commits instead of change numbers.
    (The Gerrit case has already been solved through allowTipSHA1InWant as every Gerrit change has a ref.)

Git 2.6 (Q3 2015) will improve that model.
See commit 2bc31d1, commit cc118a6 (28 Jul 2015) by Jeff King (peff).
(Merged by Junio C Hamano -- gitster -- in commit 824a0be, 19 Aug 2015)

refs: support negative transfer.hideRefs

If you hide a hierarchy of refs using the transfer.hideRefs config, there is no way to later override that config to "unhide" it.
This patch implements a "negative" hide which causes matches to immediately be marked as unhidden, even if another match would hide it.
We take care to apply the matches in reverse-order from how they are fed to us by the config machinery, as that lets our usual "last one wins" config precedence work (and entries in .git/config, for example, will override /etc/gitconfig).

So you can now do:

git config --system transfer.hideRefs refs/secret
git config transfer.hideRefs '!refs/secret/not-so-secret'

to hide refs/secret in all repos, except for one public bit in one specific repo.


Git 2.7 (Nov/Dec 2015) will improve again:

See commit 948bfa2, commit 00b293e (05 Nov 2015), commit 78a766a, commit 92cab49, commit 92cab49, commit 92cab49 (03 Nov 2015), commit 00b293e, commit 00b293e (05 Nov 2015), and commit 92cab49, commit 92cab49, commit 92cab49, commit 92cab49 (03 Nov 2015) by Lukas Fleischer (lfos).
Helped-by: Eric Sunshine (sunshineco).
(Merged by Jeff King -- peff -- in commit dbba85e, 20 Nov 2015)

config.txt: document the semantics of hideRefs with namespaces

Right now, there is no clear definition of how transfer.hideRefs should behave when a namespace is set.
Explain that hideRefs prefixes match stripped names in that case. This is how hideRefs patterns are currently handled in receive-pack.

hideRefs: add support for matching full refs

In addition to matching stripped refs, one can now add hideRefs patterns that the full (unstripped) ref is matched against.
To distinguish between stripped and full matches, those new patterns must be prefixed with a circumflex (^).

Hence the new documentation:

transfer.hideRefs:

If a namespace is in use, the namespace prefix is stripped from each reference before it is matched against transfer.hiderefs patterns.
For example, if refs/heads/master is specified in transfer.hideRefs and the current namespace is foo, then refs/namespaces/foo/refs/heads/master is omitted from the advertisements but refs/heads/master and refs/namespaces/bar/refs/heads/master are still advertised as so-called "have" lines.
In order to match refs before stripping, add a ^ in front of the ref name. If you combine ! and ^, ! must be specified first.


R.. mentions in the comments the config uploadpack.allowAnySHA1InWant, which allows upload-pack to accept a fetch request that asks for any object at all. (Defaults to false).

See commit f8edeaa (Nov. 2016, Git v2.11.1) by David "novalis" Turner (novalis):

upload-pack: optionally allow fetching any sha1

It seems a little silly to do a reachabilty check in the case where we trust the user to access absolutely everything in the repository.

Also, it's racy in a distributed system -- perhaps one server advertises a ref, but another has since had a force-push to that ref, and perhaps the two HTTP requests end up directed to these different servers.

Android Bluetooth Example

I have also used following link as others have suggested you for bluetooth communication.

http://developer.android.com/guide/topics/connectivity/bluetooth.html

The thing is all you need is a class BluetoothChatService.java

this class has following threads:

  1. Accept
  2. Connecting
  3. Connected

Now when you call start function of the BluetoothChatService like:

mChatService.start();

It starts accept thread which means it will start looking for connection.

Now when you call

mChatService.connect(<deviceObject>,false/true);

Here first argument is device object that you can get from paired devices list or when you scan for devices you will get all the devices in range you can pass that object to this function and 2nd argument is a boolean to make secure or insecure connection.

connect function will start connecting thread which will look for any device which is running accept thread.

When such a device is found both accept thread and connecting thread will call connected function in BluetoothChatService:

connected(mmSocket, mmDevice, mSocketType);

this method starts connected thread in both the devices: Using this socket object connected thread obtains the input and output stream to the other device. And calls read function on inputstream in a while loop so that it's always trying read from other device so that whenever other device send a message this read function returns that message.

BluetoothChatService also has a write method which takes byte[] as input and calls write method on connected thread.

mChatService.write("your message".getByte());

write method in connected thread just write this byte data to outputsream of the other device.

public void write(byte[] buffer) {
   try {
       mmOutStream.write(buffer);
    // Share the sent message back to the UI Activity
    // mHandler.obtainMessage(
    // BluetoothGameSetupActivity.MESSAGE_WRITE, -1, -1,
    // buffer).sendToTarget();
    } catch (IOException e) {
    Log.e(TAG, "Exception during write", e);
     }
}

Now to communicate between two devices just call write function on mChatService and handle the message that you will receive on the other device.

How do I solve the INSTALL_FAILED_DEXOPT error?

One reason is that classes.dex is not found in the root of the .apk-package. Either

  • this file is missing in the apk-package or
  • it is located in a subfolder within the .apk file.

Both situations cause the termination because Android supposedly searches only in the root of the apk file. The confusion is because the build run of the .apk file was without an error message.

Core reasons for that error may be:

  • The dx tool need classes.dex in the current main working folder. But in reality classes.dex is located somewhere other.
  • aapt have a wrong information for the location for classes.dex. For example with aapt.exe add ... bin/classes.dex. Thats would be wrong because classes.dex is in a subfolder /bin of the created .apk file.

How do I update the GUI from another thread?

This is the classic way you should do this:

using System;
using System.Windows.Forms;
using System.Threading;

namespace Test
{
    public partial class UIThread : Form
    {
        Worker worker;

        Thread workerThread;

        public UIThread()
        {
            InitializeComponent();

            worker = new Worker();
            worker.ProgressChanged += new EventHandler<ProgressChangedArgs>(OnWorkerProgressChanged);
            workerThread = new Thread(new ThreadStart(worker.StartWork));
            workerThread.Start();
        }

        private void OnWorkerProgressChanged(object sender, ProgressChangedArgs e)
        {
            // Cross thread - so you don't get the cross-threading exception
            if (this.InvokeRequired)
            {
                this.BeginInvoke((MethodInvoker)delegate
                {
                    OnWorkerProgressChanged(sender, e);
                });
                return;
            }

            // Change control
            this.label1.Text = e.Progress;
        }
    }

    public class Worker
    {
        public event EventHandler<ProgressChangedArgs> ProgressChanged;

        protected void OnProgressChanged(ProgressChangedArgs e)
        {
            if(ProgressChanged!=null)
            {
                ProgressChanged(this,e);
            }
        }

        public void StartWork()
        {
            Thread.Sleep(100);
            OnProgressChanged(new ProgressChangedArgs("Progress Changed"));
            Thread.Sleep(100);
        }
    }


    public class ProgressChangedArgs : EventArgs
    {
        public string Progress {get;private set;}
        public ProgressChangedArgs(string progress)
        {
            Progress = progress;
        }
    }
}

Your worker thread has an event. Your UI thread starts off another thread to do the work and hooks up that worker event so you can display the state of the worker thread.

Then in the UI you need to cross threads to change the actual control... like a label or a progress bar.

Hibernate: How to fix "identifier of an instance altered from X to Y"?

Faced the same Issue. I had an assosciation between 2 beans. In bean A I had defined the variable type as Integer and in bean B I had defined the same variable as Long. I changed both of them to Integer. This solved my issue.

How to check if a value exists in an object using JavaScript

Try:

_x000D_
_x000D_
var obj = {
   "a": "test1",
   "b": "test2"
};

Object.keys(obj).forEach(function(key) {
  if (obj[key] == 'test1') {
    alert('exists');
  }
});
_x000D_
_x000D_
_x000D_

Or

_x000D_
_x000D_
var obj = {
   "a": "test1",
   "b": "test2"
};

var found = Object.keys(obj).filter(function(key) {
  return obj[key] === 'test1';
});

if (found.length) {
   alert('exists');
}
_x000D_
_x000D_
_x000D_

This will not work for NaN and -0 for those values. You can use (instead of ===) what is new in ECMAScript 6:

 Object.is(obj[key], value);

With modern browsers you can also use:

_x000D_
_x000D_
var obj = {
   "a": "test1",
   "b": "test2"
};

if (Object.values(obj).includes('test1')) {
  alert('exists');
}
_x000D_
_x000D_
_x000D_

A method to count occurrences in a list

How about something like this ...

var l1 = new List<int>() { 1,2,3,4,5,2,2,2,4,4,4,1 };

var g = l1.GroupBy( i => i );

foreach( var grp in g )
{
  Console.WriteLine( "{0} {1}", grp.Key, grp.Count() );
}

Edit per comment: I will try and do this justice. :)

In my example, it's a Func<int, TKey> because my list is ints. So, I'm telling GroupBy how to group my items. The Func takes a int and returns the the key for my grouping. In this case, I will get an IGrouping<int,int> (a grouping of ints keyed by an int). If I changed it to (i => i.ToString() ) for example, I would be keying my grouping by a string. You can imagine a less trivial example than keying by "1", "2", "3" ... maybe I make a function that returns "one", "two", "three" to be my keys ...

private string SampleMethod( int i )
{
  // magically return "One" if i == 1, "Two" if i == 2, etc.
}

So, that's a Func that would take an int and return a string, just like ...

i =>  // magically return "One" if i == 1, "Two" if i == 2, etc. 

But, since the original question called for knowing the original list value and it's count, I just used an integer to key my integer grouping to make my example simpler.

C++/CLI Converting from System::String^ to std::string

This worked for me:

#include <stdlib.h>
#include <string.h>
#include <msclr\marshal_cppstd.h>
//..
using namespace msclr::interop;
//..
System::String^ clrString = (TextoDeBoton);
std::string stdString = marshal_as<std::string>(clrString); //String^ to std
//System::String^ myString = marshal_as<System::String^>(MyBasicStirng); //std to String^
prueba.CopyInfo(stdString); //MyMethod
//..
//Where: String^ = TextoDeBoton;
//and stdString is a "normal" string;

How to use LINQ to select object with minimum or maximum property value

I was looking for something similar myself, preferably without using a library or sorting the entire list. My solution ended up similar to the question itself, just simplified a bit.

var firstBorn = People.FirstOrDefault(p => p.DateOfBirth == People.Min(p2 => p2.DateOfBirth));

Insert string at specified position

Simple and another way to solve :

function stringInsert($str,$insertstr,$pos)
{
  $count_str=strlen($str);
  for($i=0;$i<$pos;$i++)
    {
    $new_str .= $str[$i];
    }

    $new_str .="$insertstr";

   for($i=$pos;$i<$count_str;$i++)
    {
    $new_str .= $str[$i];
    }

  return $new_str;

}  

How to save a dictionary to a file?

file_name = open("data.json", "w")
json.dump(test_response, file_name)
file_name.close()

or use context manager, which is better:

with open("data.json", "w") as file_name:
    json.dump(test_response, file_name)

Call a React component method from outside

method 1 using ChildRef:

public childRef: any = React.createRef<Hello>();

public onButtonClick= () => {
    console.log(this.childRef.current); // this will have your child reference
}

<Hello ref = { this.childRef }/>
<button onclick="onButtonClick()">Click me!</button>

Method 2: using window register

public onButtonClick= () => {
    console.log(window.yourRef); // this will have your child reference
}

<Hello ref = { (ref) => {window.yourRef = ref} }/>`
<button onclick="onButtonClick()">Click me!</button>

Bootstrap: Position of dropdown menu relative to navbar item

Based on Bootstrap doc:

As of v3.1.0, .pull-right is deprecated on dropdown menus. use .dropdown-menu-right

eg:

<ul class="dropdown-menu dropdown-menu-right" role="menu" aria-labelledby="dLabel">

Regular expression: zero or more occurrences of optional character /

/*

If your delimiters are slash-based, escape it:

\/*

* means "0 or more of the previous repeatable pattern", which can be a single character, a character class or a group.

javax.validation.ValidationException: HV000183: Unable to load 'javax.el.ExpressionFactory'

If you are using tomcat as your server runtime and you get this error in tests (because tomcat runtime is not available during tests) than it makes make sense to include tomcat el runtime instead of the one from glassfish). This would be:

    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-el-api</artifactId>
        <version>8.5.14</version>
        <scope>test</scope>
    </dependency>
    <dependency>
        <groupId>org.apache.tomcat</groupId>
        <artifactId>tomcat-jasper-el</artifactId>
        <version>8.5.14</version>
        <scope>test</scope>
    </dependency>

HTML anchor link - href and onclick both?

When doing a clean HTML Structure, you can use this.

_x000D_
_x000D_
//Jquery Code_x000D_
$('a#link_1').click(function(e){_x000D_
  e . preventDefault () ;_x000D_
  var a = e . target ;_x000D_
  window . open ( '_top' , a . getAttribute ('href') ) ;_x000D_
});_x000D_
_x000D_
//Normal Code_x000D_
element = document . getElementById ( 'link_1' ) ;_x000D_
element . onClick = function (e) {_x000D_
  e . preventDefault () ;_x000D_
  _x000D_
  window . open ( '_top' , element . getAttribute ('href') ) ;_x000D_
} ;
_x000D_
<a href="#Foo" id="link_1">Do it!</a>
_x000D_
_x000D_
_x000D_

Android: adb: Permission Denied

The reason for "permission denied" is because your Android machine has not been correctly rooted. Did you see $ after you started adb shell? If you correctly rooted your machine, you would have seen # instead.

If you see the $, try entering Super User mode by typing su. If Root is enabled, you will see the # - without asking for password.

Android Reading from an Input stream efficiently

Reading one line of text at a time, and appending said line to a string individually is time-consuming both in extracting each line and the overhead of so many method invocations.

I was able to get better performance by allocating a decent-sized byte array to hold the stream data, and which is iteratively replaced with a larger array when needed, and trying to read as much as the array could hold.

For some reason, Android repeatedly failed to download the entire file when the code used the InputStream returned by HTTPUrlConnection, so I had to resort to using both a BufferedReader and a hand-rolled timeout mechanism to ensure I would either get the whole file or cancel the transfer.

private static  final   int         kBufferExpansionSize        = 32 * 1024;
private static  final   int         kBufferInitialSize          = kBufferExpansionSize;
private static  final   int         kMillisecondsFactor         = 1000;
private static  final   int         kNetworkActionPeriod        = 12 * kMillisecondsFactor;

private String loadContentsOfReader(Reader aReader)
{
    BufferedReader  br = null;
    char[]          array = new char[kBufferInitialSize];
    int             bytesRead;
    int             totalLength = 0;
    String          resourceContent = "";
    long            stopTime;
    long            nowTime;

    try
    {
        br = new BufferedReader(aReader);

        nowTime = System.nanoTime();
        stopTime = nowTime + ((long)kNetworkActionPeriod * kMillisecondsFactor * kMillisecondsFactor);
        while(((bytesRead = br.read(array, totalLength, array.length - totalLength)) != -1)
        && (nowTime < stopTime))
        {
            totalLength += bytesRead;
            if(totalLength == array.length)
                array = Arrays.copyOf(array, array.length + kBufferExpansionSize);
            nowTime = System.nanoTime();
        }

        if(bytesRead == -1)
            resourceContent = new String(array, 0, totalLength);
    }
    catch(Exception e)
    {
        e.printStackTrace();
    }

    try
    {
        if(br != null)
            br.close();
    }
    catch(IOException e)
    {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
}

EDIT: It turns out that if you don't need to have the content re-encoded (ie, you want the content AS IS) you shouldn't use any of the Reader subclasses. Just use the appropriate Stream subclass.

Replace the beginning of the preceding method with the corresponding lines of the following to speed it up an extra 2 to 3 times.

String  loadContentsFromStream(Stream aStream)
{
    BufferedInputStream br = null;
    byte[]              array;
    int                 bytesRead;
    int                 totalLength = 0;
    String              resourceContent;
    long                stopTime;
    long                nowTime;

    resourceContent = "";
    try
    {
        br = new BufferedInputStream(aStream);
        array = new byte[kBufferInitialSize];

Install apk without downloading

For this your android application must have uploaded into the android market. when you upload it on the android market then use the following code to open the market with your android application.

    Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("market://details?id=<packagename>"));
startActivity(intent);

If you want it to download and install from your own server then use the following code

Intent intent = new Intent(Intent.ACTION_VIEW,Uri.parse("http://www.example.com/sample/test.apk"));
    startActivity(intent);

Get the value of a dropdown in jQuery

Another option:

$("#<%=dropDownId.ClientID%>").children("option:selected").val();

Another Repeated column in mapping for entity error

This means you are mapping a column twice in your entity class. Explaining with an example...

    @Column(name = "column1")
    private String object1;

    @ManyToOne(fetch = FetchType.EAGER)
    @JoinColumn(name = "column1", referencedColumnName = "column1")
    private TableClass object2;

The problem in the above code snippet is we are repeating mapping...

Solution

Since mapping is an important part, you don't want to remove that. Instead, you will remove

    @Column(name = "column1")
    private String uniqueId;

You can still pass the value of object1 by creating a object of TableClass and assign the String value of Object1 in it.

This works 100%. I have tested this with Postgres and Oracle database.

Add a link to an image in a css style sheet

I stumbled upon this old listing pondering this same question. My band-aid for this same question was to make my header text into a link. I then changed the color and removed text decoration with CSS. Now to make the entire header picture a link, I expanded the padding of the anchor tag until it reached close to the edge of the header image.... This worked to my satisfaction, and I figured i would share.

Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine

I found a solution for this problem. The issue I described in my question occured basically due to the incompatibility of the Microsoft.Jet.OLEDB.4.0 driver in 64 bit OS.

So if we are using Microsoft.Jet.OLEDB.4.0 driver in a 64 bit server, we have to force our application to build in in 32 bit mode (This is the answer I found when I did an extensive search for this known issue) and that causes other part of my code to break.

Fortunately, now Microsoft has released a 64 bit compatible 2010 Office System Driver which can be used as replacement for the traditional Microsoft.Jet.OLEDB.4.0 driver. It works both in 32 bit as well as 64 bit servers. I have used it for Excel file manipulation and it worked fine for me in both the environments. But this driver is in BETA.

You can download this driver from Microsoft Access Database Engine 2010 Redistributable

How to create and show common dialog (Error, Warning, Confirmation) in JavaFX 2.0?

To make an example of Clairton Luz work, you need to run in the FXApplicationThread and insert into Platform.runLater method your code snippet:

  Platform.runLater(() -> {
                        Alert alert = new Alert(Alert.AlertType.ERROR);
                        alert.setTitle("Error Dialog");
                        alert.setHeaderText("No information.");

                        alert.showAndWait();
                    }
            );

Otherwise, you'll get: java.lang.IllegalStateException: Not on FX application thread

Get an element by index in jQuery

There is another way of getting an element by index in jQuery using CSS :nth-of-type pseudo-class:

<script>
    // css selector that describes what you need:
    // ul li:nth-of-type(3)
    var selector = 'ul li:nth-of-type(' + index + ')';
    $(selector).css({'background-color':'#343434'});
</script>

There are other selectors that you may use with jQuery to match any element that you need.

Matplotlib subplots_adjust hspace so titles and xlabels don't overlap?

The link posted by Jose has been updated and pylab now has a tight_layout() function that does this automatically (in matplotlib version 1.1.0).

http://matplotlib.org/api/pyplot_api.html#matplotlib.pyplot.tight_layout

http://matplotlib.org/users/tight_layout_guide.html#plotting-guide-tight-layout

Modify property value of the objects in list using Java 8 streams

You can use peek to do that.

List<Fruit> newList = fruits.stream()
    .peek(f -> f.setName(f.getName() + "s"))
    .collect(Collectors.toList());

How to use if-else option in JSTL

In addition with skaffman answer, simple if-else you can use ternary operator like this

<c:set value="34" var="num"/>
<c:out value="${num % 2 eq 0 ? 'even': 'odd'}"/>

How to get first N elements of a list in C#?

In case anyone is interested (even if the question does not ask for this version), in C# 2 would be: (I have edited the answer, following some suggestions)

myList.Sort(CLASS_FOR_COMPARER);
List<string> fiveElements = myList.GetRange(0, 5);

LINQ Using Max() to select a single row

I don't see why you are grouping here.

Try this:

var maxValue = table.Max(x => x.Status)
var result = table.First(x => x.Status == maxValue);

An alternate approach that would iterate table only once would be this:

var result = table.OrderByDescending(x => x.Status).First();

This is helpful if table is an IEnumerable<T> that is not present in memory or that is calculated on the fly.

form with no action and where enter does not reload page

Simply add this event to your text field. It will prevent a submission on pressing Enter, and you're free to add a submit button or call form.submit() as required:

onKeyPress="if (event.which == 13) return false;"

For example:

<input id="txt" type="text" onKeyPress="if (event.which == 13) return false;"></input>

What is cURL in PHP?

cURL is a way you can hit a URL from your code to get a HTML response from it. It's used for command line cURL from the PHP language.

<?php
// Step 1
$cSession = curl_init(); 
// Step 2
curl_setopt($cSession,CURLOPT_URL,"http://www.google.com/search?q=curl");
curl_setopt($cSession,CURLOPT_RETURNTRANSFER,true);
curl_setopt($cSession,CURLOPT_HEADER, false); 
// Step 3
$result=curl_exec($cSession);
// Step 4
curl_close($cSession);
// Step 5
echo $result;
?> 

Step 1: Initialize a curl session using curl_init().

Step 2: Set option for CURLOPT_URL. This value is the URL which we are sending the request to. Append a search term curl using parameter q=. Set option for CURLOPT_RETURNTRANSFER. True will tell curl to return the string instead of print it out. Set option for CURLOPT_HEADER, false will tell curl to ignore the header in the return value.

Step 3: Execute the curl session using curl_exec().

Step 4: Close the curl session we have created.

Step 5: Output the return string.

public function curlCall($apiurl, $auth, $rflag)
{
    $ch = curl_init($apiurl);
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);

    if($auth == 'auth') { 
        curl_setopt($ch, CURLOPT_USERPWD, "passw:passw");
    } else {
        curl_setopt($ch, CURLOPT_USERPWD, "ss:ss1");
    }
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    $dt = curl_exec($ch);        
    curl_close($ch);
    if($rflag != 1) {
        $dt = json_decode($dt,true);        
    }
    return $dt;
}

This is also used for authentication. We can also set the username and password for authentication.

For more functionality, see the user manual or the following tutorial:

http://php.net/manual/en/ref.curl.php
http://www.startutorial.com/articles/view/php-curl

How to get the anchor from the URL using jQuery?

You can use the .indexOf() and .substring(), like this:

var url = "www.aaa.com/task1/1.3.html#a_1";
var hash = url.substring(url.indexOf("#")+1);

You can give it a try here, if it may not have a # in it, do an if(url.indexOf("#") != -1) check like this:

var url = "www.aaa.com/task1/1.3.html#a_1", idx = url.indexOf("#");
var hash = idx != -1 ? url.substring(idx+1) : "";

If this is the current page URL, you can just use window.location.hash to get it, and replace the # if you wish.

jQuery - multiple $(document).ready ...?

Execution is top-down. First come, first served.

If execution sequence is important, combine them.

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

You can leverage Conditional Formatting as follows.

  1. In cell H8 select Format > Conditional Formatting...
  2. In Condition1, select Formula Is in first drop down menu
  3. In the next textbox type =I8="Elementary"
  4. Select Format... and select the color you want etc.
  5. Select Add>> and repeat steps 1 to 4

Note that you can only have (in excel 2003) three separate conditions so you will only be able to have different formatting for three items in the drop down menu. If the idea is to make them visually distinct then (maybe) having no color for one of the selections is not a problem?

If the cell is never blank, you can use format (not conditional) to get 4 distinct visuals.

How can I generate a list of consecutive numbers?

import numpy as np

myList = np.linspace(0, 100, 1000) #Generates 1000 numbers from 0 to 100 in equal intervals

Tracking CPU and Memory usage per process

maybe you can use this. It should work for you and will report processor time for the specified process.

@echo off
: Rich Kreider <[email protected]>
: report processor time for given process until process exits (could be expanded to use a PID to be more
: precise)
: Depends:  typeperf
: Usage:  foo.cmd <processname>

set process=%~1
echo Press CTRL-C To Stop...
:begin
for /f "tokens=2 delims=," %%c in ('typeperf "\Process(%process%)\%% Processor Time" -si 1 -sc 1 ^| find /V "\\"') do (
if %%~c==-1 (
goto :end
) else (
echo %%~c%%
goto begin
)
)

:end
echo Process seems to have terminated.

Converting Select results into Insert script - SQL Server

You can use this Q2C.SSMSPlugin, which is free and open source. You can right click and select "Execute Query To Command... -> Query To Insert...". Enjoy)

Run ssh and immediately execute command

ssh -t 'command; bash -l'

will execute the command and then start up a login shell when it completes. For example:

ssh -t [email protected] 'cd /some/path; bash -l'

Failed to enable constraints. One or more rows contain values violating non-null, unique, or foreign-key constraints

            using (var tbl = new DataTable())
            using (var rdr = cmd.ExecuteReader())
            {
                tbl.BeginLoadData();

                try
                {
                    tbl.Load(rdr);
                }
                catch (ConstraintException ex)
                {
                    rdr.Close();
                    tbl.Clear();

                    // clear constraints, source of exceptions
                    // note: column schema already loaded!
                    tbl.Constraints.Clear();
                    tbl.Load(cmd.ExecuteReader());
                }
                finally
                {
                    tbl.EndLoadData();
                }
            }

Calculate percentage Javascript

For percent increase and decrease, using 2 different methods:

_x000D_
_x000D_
const a = 541
const b = 394

// Percent increase 
console.log(
  `Increase (from ${b} to ${a}) => `,
  (((a/b)-1) * 100).toFixed(2) + "%",
)

// Percent decrease
console.log(
  `Decrease (from ${a} to ${b}) => `,
  (((b/a)-1) * 100).toFixed(2) + "%",
)

// Alternatives, using .toLocaleString() 
console.log(
  `Increase (from ${b} to ${a}) => `,
  ((a/b)-1).toLocaleString('fullwide', {maximumFractionDigits:2, style:'percent'}),
)

console.log(
  `Decrease (from ${a} to ${b}) => `,
  ((b/a)-1).toLocaleString('fullwide', {maximumFractionDigits:2, style:'percent'}),
)
_x000D_
_x000D_
_x000D_

PHP function overloading

PHP does not support overloading for now. Hope this will be implemented in the other versions like other programming languages.

Checkout this library, This will allow you to use PHP Overloading in terms of closures. https://github.com/Sahil-Gulati/Overloading

How to Select Top 100 rows in Oracle?

As Moneer Kamal said, you can do that simply:

SELECT id, client_id FROM order 
WHERE rownum <= 100
ORDER BY create_time DESC;

Notice that the ordering is done after getting the 100 row. This might be useful for who does not want ordering.

How to search a specific value in all tables (PostgreSQL)?

to search every column of every table for a particular value

This does not define how to match exactly.
Nor does it define what to return exactly.

Assuming:

  • Find any row with any column containing the given value in its text representation - as opposed to equaling the given value.
  • Return the table name (regclass) and the tuple ID (ctid), because that's simplest.

Here is a dead simple, fast and slightly dirty way:

CREATE OR REPLACE FUNCTION search_whole_db(_like_pattern text)
  RETURNS TABLE(_tbl regclass, _ctid tid) AS
$func$
BEGIN
   FOR _tbl IN
      SELECT c.oid::regclass
      FROM   pg_class c
      JOIN   pg_namespace n ON n.oid = relnamespace
      WHERE  c.relkind = 'r'                           -- only tables
      AND    n.nspname !~ '^(pg_|information_schema)'  -- exclude system schemas
      ORDER BY n.nspname, c.relname
   LOOP
      RETURN QUERY EXECUTE format(
         'SELECT $1, ctid FROM %s t WHERE t::text ~~ %L'
       , _tbl, '%' || _like_pattern || '%')
      USING _tbl;
   END LOOP;
END
$func$  LANGUAGE plpgsql;

Call:

SELECT * FROM search_whole_db('mypattern');

Provide the search pattern without enclosing %.

Why slightly dirty?

If separators and decorators for the row in text representation can be part of the search pattern, there can be false positives:

  • column separator: , by default
  • whole row is enclosed in parentheses:()
  • some values are enclosed in double quotes "
  • \ may be added as escape char

And the text representation of some columns may depend on local settings - but that ambiguity is inherent to the question, not to my solution.

Each qualifying row is returned once only, even when it matches multiple times (as opposed to other answers here).

This searches the whole DB except for system catalogs. Will typically take a long time to finish. You might want to restrict to certain schemas / tables (or even columns) like demonstrated in other answers. Or add notices and a progress indicator, also demonstrated in another answer.

The regclass object identifier type is represented as table name, schema-qualified where necessary to disambiguate according to the current search_path:

What is the ctid?

You might want to escape characters with special meaning in the search pattern. See:

Default values and initialization in Java

I wrote following function to return a default representation 0 or false of a primitive or Number:

/**
 * Retrieves the default value 0 / false for any primitive representative or
 * {@link Number} type.
 *
 * @param type
 *
 * @return
 */
@SuppressWarnings("unchecked")
public static <T> T getDefault(final Class<T> type)
{
    if (type.equals(Long.class) || type.equals(Long.TYPE))
        return (T) new Long(0);
    else if (type.equals(Integer.class) || type.equals(Integer.TYPE))
        return (T) new Integer(0);
    else if (type.equals(Double.class) || type.equals(Double.TYPE))
        return (T) new Double(0);
    else if (type.equals(Float.class) || type.equals(Float.TYPE))
        return (T) new Float(0);
    else if (type.equals(Short.class) || type.equals(Short.TYPE))
        return (T) new Short((short) 0);
    else if (type.equals(Byte.class) || type.equals(Byte.TYPE))
        return (T) new Byte((byte) 0);
    else if (type.equals(Character.class) || type.equals(Character.TYPE))
        return (T) new Character((char) 0);
    else if (type.equals(Boolean.class) || type.equals(Boolean.TYPE))
        return (T) new Boolean(false);
    else if (type.equals(BigDecimal.class))
        return (T) BigDecimal.ZERO;
    else if (type.equals(BigInteger.class))
        return (T) BigInteger.ZERO;
    else if (type.equals(AtomicInteger.class))
        return (T) new AtomicInteger();
    else if (type.equals(AtomicLong.class))
        return (T) new AtomicLong();
    else if (type.equals(DoubleAdder.class))
        return (T) new DoubleAdder();
    else
        return null;
}

I use it in hibernate ORM projection queries when the underlying SQL query returns null instead of 0.

/**
 * Retrieves the unique result or zero, <code>false</code> if it is
 * <code>null</code> and represents a number
 *
 * @param criteria
 *
 * @return zero if result is <code>null</code>
 */
public static <T> T getUniqueResultDefault(final Class<T> type, final Criteria criteria)
{
    final T result = (T) criteria.uniqueResult();

    if (result != null)
        return result;
    else
        return Utils.getDefault(type);
}

One of the many unnecessary complex things about Java making it unintuitive to use. Why instance variables are initialized with default 0 but local are not is not logical. Similar why enums dont have built in flag support and many more options. Java lambda is a nightmare compared to C# and not allowing class extension methods is also a big problem.

Java ecosystem comes up with excuses why its not possible but me as the user / developer i dont care about their excuses. I want easy approach and if they dont fix those things they will loose big in the future since C# and other languages are not waiting to make life of developers more simple. Its just sad to see the decline in the last 10 years since i work daily with Java.

JPA: difference between @JoinColumn and @PrimaryKeyJoinColumn?

What happens if I promote the column to be a/the PK, too (a.k.a. identifying relationship)? As the column is now the PK, I must tag it with @Id (...).

This enhanced support of derived identifiers is actually part of the new stuff in JPA 2.0 (see the section 2.4.1 Primary Keys Corresponding to Derived Identities in the JPA 2.0 specification), JPA 1.0 doesn't allow Id on a OneToOne or ManyToOne. With JPA 1.0, you'd have to use PrimaryKeyJoinColumn and also define a Basic Id mapping for the foreign key column.

Now the question is: are @Id + @JoinColumn the same as just @PrimaryKeyJoinColumn?

You can obtain a similar result but using an Id on OneToOne or ManyToOne is much simpler and is the preferred way to map derived identifiers with JPA 2.0. PrimaryKeyJoinColumn might still be used in a JOINED inheritance strategy. Below the relevant section from the JPA 2.0 specification:

11.1.40 PrimaryKeyJoinColumn Annotation

The PrimaryKeyJoinColumn annotation specifies a primary key column that is used as a foreign key to join to another table.

The PrimaryKeyJoinColumn annotation is used to join the primary table of an entity subclass in the JOINED mapping strategy to the primary table of its superclass; it is used within a SecondaryTable annotation to join a secondary table to a primary table; and it may be used in a OneToOne mapping in which the primary key of the referencing entity is used as a foreign key to the referenced entity[108].

...

If no PrimaryKeyJoinColumn annotation is specified for a subclass in the JOINED mapping strategy, the foreign key columns are assumed to have the same names as the primary key columns of the primary table of the superclass.

...

Example: Customer and ValuedCustomer subclass

@Entity
@Table(name="CUST")
@Inheritance(strategy=JOINED)
@DiscriminatorValue("CUST")
public class Customer { ... }

@Entity
@Table(name="VCUST")
@DiscriminatorValue("VCUST")
@PrimaryKeyJoinColumn(name="CUST_ID")
public class ValuedCustomer extends Customer { ... }

[108] The derived id mechanisms described in section 2.4.1.1 are now to be preferred over PrimaryKeyJoinColumn for the OneToOne mapping case.

See also


This source http://weblogs.java.net/blog/felipegaucho/archive/2009/10/24/jpa-join-table-additional-state states that using @ManyToOne and @Id works with JPA 1.x. Who's correct now?

The author is using a pre release JPA 2.0 compliant version of EclipseLink (version 2.0.0-M7 at the time of the article) to write an article about JPA 1.0(!). This article is misleading, the author is using something that is NOT part of JPA 1.0.

For the record, support of Id on OneToOne and ManyToOne has been added in EclipseLink 1.1 (see this message from James Sutherland, EclipseLink comitter and main contributor of the Java Persistence wiki book). But let me insist, this is NOT part of JPA 1.0.

hexadecimal string to byte array in python

A good one liner is:

byte_list = map(ord, hex_string)

This will iterate over each char in the string and run it through the ord() function. Only tested on python 2.6, not too sure about 3.0+.

-Josh

How to embed YouTube videos in PHP?

You can simply create a php input form for Varchar date,give it a varchar length of lets say 300. Then ask the users to copy and paste the Embed code.When you view the records, you will view the streamed video.

What is the syntax meaning of RAISERROR()

It is the severity level of the error. The levels are from 11 - 20 which throw an error in SQL. The higher the level, the more severe the level and the transaction should be aborted.

You will get the syntax error when you do:

RAISERROR('Cannot Insert where salary > 1000').

Because you have not specified the correct parameters (severity level or state).

If you wish to issue a warning and not an exception, use levels 0 - 10.

From MSDN:

severity

Is the user-defined severity level associated with this message. When using msg_id to raise a user-defined message created using sp_addmessage, the severity specified on RAISERROR overrides the severity specified in sp_addmessage. Severity levels from 0 through 18 can be specified by any user. Severity levels from 19 through 25 can only be specified by members of the sysadmin fixed server role or users with ALTER TRACE permissions. For severity levels from 19 through 25, the WITH LOG option is required.

state

Is an integer from 0 through 255. Negative values or values larger than 255 generate an error. If the same user-defined error is raised at multiple locations, using a unique state number for each location can help find which section of code is raising the errors. For detailed description here

Python append() vs. + operator on lists, why do these give different results?

append is appending an element to a list. if you want to extend the list with the new list you need to use extend.

>>> c = [1, 2, 3]
>>> c.extend(c)
>>> c
[1, 2, 3, 1, 2, 3]

Connect to SQL Server 2012 Database with C# (Visual Studio 2012)

Try:

SqlConnection myConnection = new SqlConnection("Database=testDB;Server=Paul-PC\\SQLEXPRESS;Integrated Security=True;connect timeout = 30");

How do I pull files from remote without overwriting local files?

So you have committed your local changes to your local repository. Then in order to get remote changes to your local repository without making changes to your local files, you can use git fetch. Actually git pull is a two step operation: a non-destructive git fetch followed by a git merge. See What is the difference between 'git pull' and 'git fetch'? for more discussion.

Detailed example:

Suppose your repository is like this (you've made changes test2:

* ed0bcb2 - (HEAD, master) test2
* 4942854 - (origin/master, origin/HEAD) first

And the origin repository is like this (someone else has committed test1):

* 5437ca5 - (HEAD, master) test1
* 4942854 - first

At this point of time, git will complain and ask you to pull first if you try to push your test2 to remote repository. If you want to see what test1 is without modifying your local repository, run this:

$ git fetch

Your result local repository would be like this:

* ed0bcb2 - (HEAD, master) test2 
| * 5437ca5 - (origin/master, origin/HEAD) test1 
|/  
* 4942854 - first 

Now you have the remote changes in another branch, and you keep your local files intact.

Then what's next? You can do a git merge, which will be the same effect as git pull (when combined with the previous git fetch), or, as I would prefer, do a git rebase origin/master to apply your change on top of origin/master, which gives you a cleaner history.

What is ViewModel in MVC?

If you have properties specific to the view, and not related to the DB/Service/Data store, it is a good practice to use ViewModels. Say, you want to leave a checkbox selected based on a DB field (or two) but the DB field itself isn't a boolean. While it is possible to create these properties in the Model itself and keep it hidden from the binding to data, you may not want to clutter the Model depending on the amount of such fields and transactions.

If there are too few view-specific data and/or transformations, you can use the Model itself

" netsh wlan start hostednetwork " command not working no matter what I try

First of all go to the device manager now go to View>>select Show hidden devices....Then go to network adapters and find out Microsoft Hosted network Virual Adapter ....Press right click and enable the option....

Then go to command prompt with administrative privileges and enter the following commands:

netsh wlan set hostednetwork mode=allow
netsh wlan start hostednetwork

Your Hostednetwork will work without any problems.

What's the difference between the Window.Loaded and Window.ContentRendered events

If you're using data binding, then you need to use the ContentRendered event.

For the code below, the Header is NULL when the Loaded event is raised. However, Header gets its value when the ContentRendered event is raised.

<MenuItem Header="{Binding NewGame_Name}" Command="{Binding NewGameCommand}" />

ASP.NET MVC Dropdown List From SelectList

You are missing setting what field is the Text and Value in the SelectList itself. That is why it does a .ToString() on each object in the list. You could think that given it is a list of SelectListItem it should be smart enough to detect this... but it is not.

u.UserTypeOptions = new SelectList(
    new List<SelectListItem>
    {
        new SelectListItem { Selected = true, Text = string.Empty, Value = "-1"},
        new SelectListItem { Selected = false, Text = "Homeowner", Value = ((int)UserType.Homeowner).ToString()},
        new SelectListItem { Selected = false, Text = "Contractor", Value = ((int)UserType.Contractor).ToString()},
    }, "Value" , "Text", 1);

BTW, you can use a list of array of any type... and then just set the name of the properties that will act as Text and Value.

I think it is better to do it like this:

u.UserTypeOptions = new SelectList(
    new List<SelectListItem>
    {
        new SelectListItem { Text = "Homeowner", Value = ((int)UserType.Homeowner).ToString()},
        new SelectListItem { Text = "Contractor", Value = ((int)UserType.Contractor).ToString()},
    }, "Value" , "Text");

I removed the -1 item, and the setting of each items selected true/false.

Then, in your view:

@Html.DropDownListFor(m => m.UserType, Model.UserTypeOptions, "Select one")

This way, if you set the "Select one" item, and you don't set one item as selected in the SelectList, the UserType will be null (the UserType need to be int? ).

If you need to set one of the SelectList items as selected, you can use:

u.UserTypeOptions = new SelectList(options, "Value" , "Text", userIdToBeSelected);

How to find out what character key is pressed?

More recent and much cleaner: use event.key. No more arbitrary number codes!

NOTE: The old properties (.keyCode and .which) are Deprecated.

node.addEventListener('keydown', function(event) {
    const key = event.key; // "a", "1", "Shift", etc.
});

If you want to make sure only single characters are entered, check key.length === 1, or that it is one of the characters you expect.

Mozilla Docs

Supported Browsers

How to get a list of programs running with nohup

When I started with $ nohup storm dev-zookeper ,

METHOD1 : using jobs,

prayagupd@prayagupd:/home/vmfest# jobs -l
[1]+ 11129 Running                 nohup ~/bin/storm/bin/storm dev-zookeeper &

METHOD2 : using ps command.

$ ps xw
PID  TTY      STAT   TIME COMMAND
1031 tty1     Ss+    0:00 /sbin/getty -8 38400 tty1
10582 ?        S      0:01 [kworker/0:0]
10826 ?        Sl     0:18 java -server -Dstorm.options= -Dstorm.home=/root/bin/storm -Djava.library.path=/usr/local/lib:/opt/local/lib:/usr/lib -Dsto
10853 ?        Ss     0:00 sshd: vmfest [priv] 

TTY column with ? => nohup running programs.

Description

  • TTY column = the terminal associated with the process
  • STAT column = state of a process
    • S = interruptible sleep (waiting for an event to complete)
    • l = is multi-threaded (using CLONE_THREAD, like NPTL pthreads do)

Reference

$ man ps # then search /PROCESS STATE CODES

How to view transaction logs in SQL Server 2008

I accidentally deleted a whole bunch of data in the wrong environment and this post was one of the first ones I found.

Because I was simultaneously panicking and searching for a solution, I went for the first thing I saw - ApexSQL Logs, which was $2000 which was an acceptable cost.

However, I've since found out that Toad for Sql Server can generate undo scripts from transaction logs and it is only $655.

Lastly, found an even cheaper option SysToolsGroup Log Analyzer and it is only $300.

Razor Views not seeing System.Web.Mvc.HtmlHelper

I came across several answers in SO and at the end I realized that my error was that I had misspelled "Html.TextBoxFor." In my case what I wrote was "Html.TextboxFor." I did not uppercase the B in TextBoxFor. Fixed that and voilà. Problem solved. I hope this helps someone.

Copy struct to struct in C

For simple structures you can either use memcpy like you do, or just assign from one to the other:

RTCclk = RTCclkBuffert;

The compiler will create code to copy the structure for you.


An important note about the copying: It's a shallow copy, just like with memcpy. That means if you have e.g. a structure containing pointers, it's only the actual pointers that will be copied and not what they point to, so after the copy you will have two pointers pointing to the same memory.

Capture HTML Canvas as gif/jpg/png/pdf?

function exportCanvasAsPNG(id, fileName) {

    var canvasElement = document.getElementById(id);

    var MIME_TYPE = "image/png";

    var imgURL = canvasElement.toDataURL(MIME_TYPE);

    var dlLink = document.createElement('a');
    dlLink.download = fileName;
    dlLink.href = imgURL;
    dlLink.dataset.downloadurl = [MIME_TYPE, dlLink.download, dlLink.href].join(':');

    document.body.appendChild(dlLink);
    dlLink.click();
    document.body.removeChild(dlLink);
}

What is the command to truncate a SQL Server log file?

For SQL Server 2008, the command is:

ALTER DATABASE ExampleDB SET RECOVERY SIMPLE
DBCC SHRINKFILE('ExampleDB_log', 0, TRUNCATEONLY)
ALTER DATABASE ExampleDB SET RECOVERY FULL

This reduced my 14GB log file down to 1MB.

This table does not contain a unique column. Grid edit, checkbox, Edit, Copy and Delete features are not available

Adding this in the config.inc.php file worked for me (under the last $cfg line):

$cfg['RowActionLinksWithoutUnique'] = 'true';

The file should be located in the phpMyAdmin folder on your local computer

Compress files while reading data from STDIN

Yes, gzip will let you do this. If you simply run gzip > foo.gz, it will compress STDIN to the file foo.gz. You can also pipe data into it, like some_command | gzip > foo.gz.

Difference between volatile and synchronized in Java

It's important to understand that there are two aspects to thread safety.

  1. execution control, and
  2. memory visibility

The first has to do with controlling when code executes (including the order in which instructions are executed) and whether it can execute concurrently, and the second to do with when the effects in memory of what has been done are visible to other threads. Because each CPU has several levels of cache between it and main memory, threads running on different CPUs or cores can see "memory" differently at any given moment in time because threads are permitted to obtain and work on private copies of main memory.

Using synchronized prevents any other thread from obtaining the monitor (or lock) for the same object, thereby preventing all code blocks protected by synchronization on the same object from executing concurrently. Synchronization also creates a "happens-before" memory barrier, causing a memory visibility constraint such that anything done up to the point some thread releases a lock appears to another thread subsequently acquiring the same lock to have happened before it acquired the lock. In practical terms, on current hardware, this typically causes flushing of the CPU caches when a monitor is acquired and writes to main memory when it is released, both of which are (relatively) expensive.

Using volatile, on the other hand, forces all accesses (read or write) to the volatile variable to occur to main memory, effectively keeping the volatile variable out of CPU caches. This can be useful for some actions where it is simply required that visibility of the variable be correct and order of accesses is not important. Using volatile also changes treatment of long and double to require accesses to them to be atomic; on some (older) hardware this might require locks, though not on modern 64 bit hardware. Under the new (JSR-133) memory model for Java 5+, the semantics of volatile have been strengthened to be almost as strong as synchronized with respect to memory visibility and instruction ordering (see http://www.cs.umd.edu/users/pugh/java/memoryModel/jsr-133-faq.html#volatile). For the purposes of visibility, each access to a volatile field acts like half a synchronization.

Under the new memory model, it is still true that volatile variables cannot be reordered with each other. The difference is that it is now no longer so easy to reorder normal field accesses around them. Writing to a volatile field has the same memory effect as a monitor release, and reading from a volatile field has the same memory effect as a monitor acquire. In effect, because the new memory model places stricter constraints on reordering of volatile field accesses with other field accesses, volatile or not, anything that was visible to thread A when it writes to volatile field f becomes visible to thread B when it reads f.

-- JSR 133 (Java Memory Model) FAQ

So, now both forms of memory barrier (under the current JMM) cause an instruction re-ordering barrier which prevents the compiler or run-time from re-ordering instructions across the barrier. In the old JMM, volatile did not prevent re-ordering. This can be important, because apart from memory barriers the only limitation imposed is that, for any particular thread, the net effect of the code is the same as it would be if the instructions were executed in precisely the order in which they appear in the source.

One use of volatile is for a shared but immutable object is recreated on the fly, with many other threads taking a reference to the object at a particular point in their execution cycle. One needs the other threads to begin using the recreated object once it is published, but does not need the additional overhead of full synchronization and it's attendant contention and cache flushing.

// Declaration
public class SharedLocation {
    static public SomeObject someObject=new SomeObject(); // default object
    }

// Publishing code
// Note: do not simply use SharedLocation.someObject.xxx(), since although
//       someObject will be internally consistent for xxx(), a subsequent 
//       call to yyy() might be inconsistent with xxx() if the object was 
//       replaced in between calls.
SharedLocation.someObject=new SomeObject(...); // new object is published

// Using code
private String getError() {
    SomeObject myCopy=SharedLocation.someObject; // gets current copy
    ...
    int cod=myCopy.getErrorCode();
    String txt=myCopy.getErrorText();
    return (cod+" - "+txt);
    }
// And so on, with myCopy always in a consistent state within and across calls
// Eventually we will return to the code that gets the current SomeObject.

Speaking to your read-update-write question, specifically. Consider the following unsafe code:

public void updateCounter() {
    if(counter==1000) { counter=0; }
    else              { counter++; }
    }

Now, with the updateCounter() method unsynchronized, two threads may enter it at the same time. Among the many permutations of what could happen, one is that thread-1 does the test for counter==1000 and finds it true and is then suspended. Then thread-2 does the same test and also sees it true and is suspended. Then thread-1 resumes and sets counter to 0. Then thread-2 resumes and again sets counter to 0 because it missed the update from thread-1. This can also happen even if thread switching does not occur as I have described, but simply because two different cached copies of counter were present in two different CPU cores and the threads each ran on a separate core. For that matter, one thread could have counter at one value and the other could have counter at some entirely different value just because of caching.

What's important in this example is that the variable counter was read from main memory into cache, updated in cache and only written back to main memory at some indeterminate point later when a memory barrier occurred or when the cache memory was needed for something else. Making the counter volatile is insufficient for thread-safety of this code, because the test for the maximum and the assignments are discrete operations, including the increment which is a set of non-atomic read+increment+write machine instructions, something like:

MOV EAX,counter
INC EAX
MOV counter,EAX

Volatile variables are useful only when all operations performed on them are "atomic", such as my example where a reference to a fully formed object is only read or written (and, indeed, typically it's only written from a single point). Another example would be a volatile array reference backing a copy-on-write list, provided the array was only read by first taking a local copy of the reference to it.

MomentJS getting JavaScript Date in UTC

Calling toDate will create a copy (the documentation is down-right wrong about it not being a copy), of the underlying JS Date object. JS Date object is stored in UTC and will always print to eastern time. Without getting into whether .utc() modifies the underlying object that moment wraps use the code below.

You don't need moment for this.

new Date().getTime()

This works, because JS Date at its core is in UTC from the Unix Epoch. It's extraordinarily confusing and I believe a big flaw in the interface to mix local and UTC times like this with no descriptions in the methods.

Add a user control to a wpf window

This is how I got it to work:

User Control WPF

<UserControl x:Class="App.ProcessView"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             xmlns:mc="http://schemas.openxmlformats.org/markup-compatibility/2006" 
             xmlns:d="http://schemas.microsoft.com/expression/blend/2008" 
             mc:Ignorable="d" 
             d:DesignHeight="300" d:DesignWidth="300">
    <Grid>

    </Grid>
</UserControl>

User Control C#

namespace App {
    /// <summary>
    /// Interaction logic for ProcessView.xaml
    /// </summary>
    public partial class ProcessView : UserControl // My custom User Control
    {
        public ProcessView()
        {
            InitializeComponent();
        }
    } }

MainWindow WPF

<Window x:Name="RootWindow" x:Class="App.MainWindow"
        xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
        xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
        xmlns:app="clr-namespace:App"
        Title="Some Title" Height="350" Width="525" Closing="Window_Closing_1" Icon="bouncer.ico">
    <Window.Resources>
        <app:DateConverter x:Key="dateConverter"/>
    </Window.Resources>
    <Grid>
        <ListView x:Name="listView" >
            <ListView.ItemTemplate>
                <DataTemplate>
                    <app:ProcessView />
                </DataTemplate>
            </ListView.ItemTemplate>
        </ListView>
    </Grid>
</Window>

List all column except for one in R

In addition to tcash21's numeric indexing if OP may have been looking for negative indexing by name. Here's a few ways I know, some are risky than others to use:

mtcars[, -which(names(mtcars) == "carb")]  #only works on a single column
mtcars[, names(mtcars) != "carb"]          #only works on a single column
mtcars[, !names(mtcars) %in% c("carb", "mpg")] 
mtcars[, -match(c("carb", "mpg"), names(mtcars))] 
mtcars2 <- mtcars; mtcars2$hp <- NULL         #lost column (risky)


library(gdata) 
remove.vars(mtcars2, names=c("mpg", "carb"), info=TRUE) 

Generally I use:

mtcars[, !names(mtcars) %in% c("carb", "mpg")] 

because I feel it's safe and efficient.

Jquery resizing image

You can resize image with this piece of code

    var maxWidth = 600;
    $("img").each(function () {
      var imageWidth = $(this).width();
      var imageHeight = $(this).height();
        if (imageWidth > maxWidth) {
          var percentdiff = (imageWidth - maxWidth) / imageWidth * 100;
          $(this).width(maxWidth);
          $(this).height(imageHeight - (imageHeight * percentdiff / 100));
        }
   });

When do I need a fb:app_id or fb:admins?

To use the Like Button and have the Open Graph inspect your website, you need an application.

So you need to associate the Like Button with a fb:app_id

If you want other users to see the administration page for your website on Facebook you add fb:admins. So if you are the developer of the application and the website owner there is no need to add fb:admins

.NET Global exception handler in console application

What you are trying should work according to the MSDN doc's for .Net 2.0. You could also try a try/catch right in main around your entry point for the console app.

static void Main(string[] args)
{
    try
    {
        // Start Working
    }
    catch (Exception ex)
    {
        // Output/Log Exception
    }
    finally
    {
        // Clean Up If Needed
    }
}

And now your catch will handle anything not caught (in the main thread). It can be graceful and even restart where it was if you want, or you can just let the app die and log the exception. You woul add a finally if you wanted to do any clean up. Each thread will require its own high level exception handling similar to the main.

Edited to clarify the point about threads as pointed out by BlueMonkMN and shown in detail in his answer.

Get Character value from KeyCode in JavaScript... then trim

I know this is an old question, but I came across it today searching for a pre-packaged solution to this problem, and found nothing that really met my needs.

Here is a solution (English only) that correctly supports Upper Case (shifted), Lower Case, punctuation, number keypad, etc.

It also allows for simple and straight-forward identification of - and reaction to - non-printable keys, like ESC, Arrows, Function keys, etc.

https://jsfiddle.net/5hhu896g/1/

keyboardCharMap and keyboardNameMap are the key to making this work

Thanks to DaveAlger for saving me some typing - and much discovery! - by providing the Named Key Array.

Populating a ListView using an ArrayList?

You need to do it through an ArrayAdapter which will adapt your ArrayList (or any other collection) to your items in your layout (ListView, Spinner etc.).

This is what the Android developer guide says:

A ListAdapter that manages a ListView backed by an array of arbitrary objects. By default this class expects that the provided resource id references a single TextView. If you want to use a more complex layout, use the constructors that also takes a field id. That field id should reference a TextView in the larger layout resource.

However the TextView is referenced, it will be filled with the toString() of each object in the array. You can add lists or arrays of custom objects. Override the toString() method of your objects to determine what text will be displayed for the item in the list.

To use something other than TextViews for the array display, for instance ImageViews, or to have some of data besides toString() results fill the views, override getView(int, View, ViewGroup) to return the type of view you want.

So your code should look like:

public class YourActivity extends Activity {

    private ListView lv;

    public void onCreate(Bundle saveInstanceState) {
         setContentView(R.layout.your_layout);

         lv = (ListView) findViewById(R.id.your_list_view_id);

         // Instanciating an array list (you don't need to do this, 
         // you already have yours).
         List<String> your_array_list = new ArrayList<String>();
         your_array_list.add("foo");
         your_array_list.add("bar");

         // This is the array adapter, it takes the context of the activity as a 
         // first parameter, the type of list view as a second parameter and your 
         // array as a third parameter.
         ArrayAdapter<String> arrayAdapter = new ArrayAdapter<String>(
                 this, 
                 android.R.layout.simple_list_item_1,
                 your_array_list );

         lv.setAdapter(arrayAdapter); 
    }
}

Python TypeError: not enough arguments for format string

I got the same error when using % as a percent character in my format string. The solution to this is to double up the %%.

Dynamically add script tag with src that may include document.write

I tried it by recursively appending each script

Note If your scripts are dependent one after other, then position will need to be in sync.

Major Dependency should be in last in array so that initial scripts can use it

_x000D_
_x000D_
const scripts = ['https://www.gstatic.com/firebasejs/6.2.0/firebase-storage.js', 'https://www.gstatic.com/firebasejs/6.2.0/firebase-firestore.js', 'https://www.gstatic.com/firebasejs/6.2.0/firebase-app.js']_x000D_
let count = 0_x000D_
_x000D_
  _x000D_
 const recursivelyAddScript = (script, cb) => {_x000D_
  const el = document.createElement('script')_x000D_
  el.src = script_x000D_
  if(count < scripts.length) {_x000D_
    count ++_x000D_
    el.onload = recursivelyAddScript(scripts[count])_x000D_
    document.body.appendChild(el)_x000D_
  } else {_x000D_
    console.log('All script loaded')_x000D_
    return_x000D_
  }_x000D_
}_x000D_
 _x000D_
  recursivelyAddScript(scripts[count])
_x000D_
_x000D_
_x000D_

How to initialize const member variable in a class?

In C++ you cannot initialize any variables directly while the declaration. For this we've to use the concept of constructors.
See this example:-

#include <iostream>

using namespace std;

class A
{
    public:
  const int x;  
  
  A():x(0) //initializing the value of x to 0
  {
      //constructor
  }
};

int main()
{
    A a; //creating object
   cout << "Value of x:- " <<a.x<<endl; 
   
   return 0;
}

Hope it would help you!

How to dynamically create a class?

You want to look at CodeDOM. It allows defining code elements and compiling them. Quoting MSDN:

...This object graph can be rendered as source code using a CodeDOM code generator for a supported programming language. The CodeDOM can also be used to compile source code into a binary assembly.

Failed to find 'ANDROID_HOME' environment variable

You may want to confirm that your development environment has been set correctly.

Quoting from spring.io:

Set up the Android development environment

Before you can build Android applications, you must install the Android SDK. Installing the Android SDK also installs the AVD Manager, a graphical user interface for creating and managing Android Virtual Devices (AVDs).

  1. From the Android web site, download the correct version of the Android SDK for your operating system.

  2. Unzip the archive to a location of your choosing. For example, on Linux or Mac, you can place it in the root of your user directory. See the Android Developers web site for additional installation details.

  3. Configure the ANDROID_HOME environment variable based on the location of the Android SDK. Additionally, consider adding ANDROID_HOME/tools, and ANDROID_HOME/platform-tools to your PATH.

Mac OS X

export ANDROID_HOME=/<installation location>/android-sdk-macosx
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

Linux

export ANDROID_HOME=/<installation location>/android-sdk-linux
export PATH=${PATH}:$ANDROID_HOME/tools:$ANDROID_HOME/platform-tools

Windows

set ANDROID_HOME=C:\<installation location>\android-sdk-windows
set PATH=%PATH%;%ANDROID_HOME%\tools;%ANDROID_HOME%\platform-tools

The Android SDK download does not include specific Android platforms. To run the code in this guide, you need to download and install the latest SDK platform. You do this by using the Android SDK and AVD Manager that you installed in the previous section.

  1. Open the Android SDK Manager window:

    android
    

    Note: If this command does not open the Android SDK Manager, then your path is not configured correctly.

  2. Select the Tools checkbox.

  3. Select the checkbox for the latest Android SDK.

  4. From the Extras folder, select the checkbox for the Android Support Library.

  5. Click the Install packages... button to complete the download and installation.

    Note: You may want to install all the available updates, but be aware it will take longer, as each API level is a large download.

Load an image from a url into a PictureBox

If you are trying to load the image at your form_load, it's a better idea to use the code

pictureBox1.LoadAsync(@"http://google.com/test.png");

not only loading from web but also no lag in your form loading.

How do you detect the clearing of a "search" HTML5 input?

2021 - keep it simple!

Wow, there are some really complicated answers in here for a really simple problem.

Simply add a listener for 'input' on your search input which will capture when the user types something in the input or clicks on the clear icon.

_x000D_
_x000D_
document.getElementById('searchInput').addEventListener('input', (e) => {
  console.log(`Input value: "${e.currentTarget.value}"`);
})
_x000D_
<input id="searchInput" type="search" placeholder="Search" />
_x000D_
_x000D_
_x000D_

If you can't use ES6+ then here is the converted code for you:

document.getElementById('searchInput').addEventListener('input', function(e) { 
  // Yay! You make it in here when a user types or clicks the clear icon
})` 

Is System.nanoTime() completely useless?

This doesn't seem to be a problem on a Core 2 Duo running Windows XP and JRE 1.5.0_06.

In a test with three threads I don't see System.nanoTime() going backwards. The processors are both busy, and threads go to sleep occasionally to provoke moving threads around.

[EDIT] I would guess that it only happens on physically separate processors, i.e. that the counters are synchronized for multiple cores on the same die.

Output (echo/print) everything from a PHP Array

Similar to karim's, but with print_r which has a much small output and I find is usually all you need:

function PrintR($var) {
    echo '<pre>';
    print_r($var);
    echo '</pre>';
}

Unable to add window -- token android.os.BinderProxy is not valid; is your activity running?

For me it was fixed by just removing the static property in the DialogHelper.class methods (resposble for creating & hiding the dialog), as I have properties related to Window in those methods

Removing white space around a saved image in matplotlib

For anyone who wants to work in pixels rather than inches this will work.

Plus the usual you will also need

from matplotlib.transforms import Bbox

Then you can use the following:

my_dpi = 100 # Good default - doesn't really matter

# Size of output in pixels
h = 224
w = 224

fig, ax = plt.subplots(1, figsize=(w/my_dpi, h/my_dpi), dpi=my_dpi)

ax.set_position([0, 0, 1, 1]) # Critical!

# Do some stuff
ax.imshow(img)
ax.imshow(heatmap) # 4-channel RGBA
ax.plot([50, 100, 150], [50, 100, 150], color="red")

ax.axis("off")

fig.savefig("saved_img.png",
            bbox_inches=Bbox([[0, 0], [w/my_dpi, h/my_dpi]]),
            dpi=my_dpi)

enter image description here

Difference between application/x-javascript and text/javascript content types

text/javascript is obsolete, and application/x-javascript was experimental (hence the x- prefix) for a transitional period until application/javascript could be standardised.

You should use application/javascript. This is documented in the RFC.

As far a browsers are concerned, there is no difference (at least in HTTP headers). This was just a change so that the text/* and application/* MIME type groups had a consistent meaning where possible. (text/* MIME types are intended for human readable content, JavaScript is not designed to directly convey meaning to humans).

Note that using application/javascript in the type attribute of a script element will cause the script to be ignored (as being in an unknown language) in some older browsers. Either continue to use text/javascript there or omit the attribute entirely (which is permitted in HTML 5).

This isn't a problem in HTTP headers as browsers universally (as far as I'm aware) either ignore the HTTP content-type of scripts entirely, or are modern enough to recognise application/javascript.

2D array values C++

Like this:

int main()
{
    int arr[2][5] =
    {
        {1,8,12,20,25},
        {5,9,13,24,26}
    };
}

This should be covered by your C++ textbook: which one are you using?

Anyway, better, consider using std::vector or some ready-made matrix class e.g. from Boost.

How to succinctly write a formula with many variables from a data frame?

I build this solution, reformulate does not take care if variable names have white spaces.

add_backticks = function(x) {
    paste0("`", x, "`")
}

x_lm_formula = function(x) {
    paste(add_backticks(x), collapse = " + ")
}

build_lm_formula = function(x, y){
    if (length(y)>1){
        stop("y needs to be just one variable")
    }
    as.formula(        
        paste0("`",y,"`", " ~ ", x_lm_formula(x))
    )
}

# Example
df <- data.frame(
    y = c(1,4,6), 
    x1 = c(4,-1,3), 
    x2 = c(3,9,8), 
    x3 = c(4,-4,-2)
    )

# Model Specification
columns = colnames(df)
y_cols = columns[1]
x_cols = columns[2:length(columns)]
formula = build_lm_formula(x_cols, y_cols)
formula
# output
# "`y` ~ `x1` + `x2` + `x3`"

# Run Model
lm(formula = formula, data = df)
# output
Call:
    lm(formula = formula, data = df)

Coefficients:
    (Intercept)           x1           x2           x3  
        -5.6316       0.7895       1.1579           NA  

```

Iterating through a string word by word

for word in string.split():
    print word

VT-x is disabled in the BIOS for both all CPU modes (VERR_VMX_MSR_ALL_VMX_DISABLED)

If you're on 32-bit machine don't allow more than 3584 MB of RAM and it will run.

Move view with keyboard using Swift

I see all answers are moving the view itself by the value of the keyboard height. Well, I have an elaborate answer, which could be useful if you are using constraints i.e autolayout, that moves a view by changing its constraint value (bottom or top constraints for example) by a predefined value or you can use keyboard size value.

In this example, I use bottom constraint from the textfield to Bottom Layout View with initial value of 175.

@IBOutlet weak var bottomConstraint: NSLayoutConstraint!

override func viewDidLoad() {
    super.viewDidLoad()        
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillShow:"), name:UIKeyboardWillShowNotification, object: nil);
    NSNotificationCenter.defaultCenter().addObserver(self, selector: Selector("keyboardWillHide:"), name:UIKeyboardWillHideNotification, object: nil);
}

func keyboardWillShow(notification: NSNotification) {
    //To retrieve keyboard size, uncomment following line
    //let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue()
    bottomConstraint.constant = 260
    UIView.animateWithDuration(0.3) {
        self.view.layoutIfNeeded()
    }
}

func keyboardWillHide(notification: NSNotification) {
    //To retrieve keyboard size, uncomment following line
    //let keyboardSize = (notification.userInfo?[UIKeyboardFrameBeginUserInfoKey] as? NSValue)?.CGRectValue()
    bottomConstraint.constant = 175
    UIView.animateWithDuration(0.3) {
        self.view.layoutIfNeeded()
    }
}

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

AFAIK, RTSP does not transmit streams at all, it is just an out-of-band control protocol with functions like PLAY and STOP.

Raw UDP or RTP over UDP are transmission protocols for streams just like raw TCP or HTTP over TCP.

To be able to stream a certain program over the given transmission protocol, an encapsulation method has to be defined for your container format. For example TS container can be transmitted over UDP but Matroska can not.

Pretty much everything can be transported through TCP though.

(The fact that which codec do you use also matters indirectly as it restricts the container formats you can use.)

How can I override inline styles with external CSS?

used !important in CSS property

<div style="color: red;">
    Hello World, How Can I Change The Color To Blue?
</div>

div {
        color: blue !important;
    }

Is it possible to hide the cursor in a webpage using CSS or Javascript?

Pointer Lock API

While the cursor: none CSS solution is definitely a solid and easy workaround, if your actual goal is to remove the default cursor while your web application is being used, or implement your own interpretation of raw mouse movement (for FPS games, for example), you might want to consider using the Pointer Lock API instead.

You can use requestPointerLock on an element to remove the cursor, and redirect all mousemove events to that element (which you may or may not handle):

document.body.requestPointerLock();

To release the lock, you can use exitPointerLock:

document.exitPointerLock();

Additional notes

No cursor, for real

This is a very powerful API call. It not only renders your cursor invisible, but it actually removes your operating system's native cursor. You won't be able to select text, or do anything with your mouse (except listening to some mouse events in your code) until the pointer lock is released (either by using exitPointerLock or pressing ESC in some browsers).

That is, you cannot leave the window with your cursor for it to show again, as there is no cursor.

Restrictions

As mentioned above, this is a very powerful API call, and is thus only allowed to be made in response to some direct user-interaction on the web, such as a click; for example:

document.addEventListener("click", function () {
    document.body.requestPointerLock();
});

Also, requestPointerLock won't work from a sandboxed iframe unless the allow-pointer-lock permission is set.

User-notifications

Some browsers will prompt the user for a confirmation before the lock is engaged, some will simply display a message. This means pointer lock might not activate right away after the call. However, the actual activation of pointer locking can be listened to by listening to the pointerchange event on the element on which requestPointerLock was called:

document.body.addEventListener("pointerlockchange", function () {
    if (document.pointerLockElement === document.body) {
        // Pointer is now locked to <body>.
    }
});

Most browsers will only display the message once, but Firefox will occasionally spam the message on every single call. AFAIK, this can only be worked around by user-settings, see Disable pointer-lock notification in Firefox.

Listening to raw mouse movement

The Pointer Lock API not only removes the mouse, but instead redirects raw mouse movement data to the element requestPointerLock was called on. This can be listened to simply by using the mousemove event, then accessing the movementX and movementY properties on the event object:

document.body.addEventListener("mousemove", function (e) {
    console.log("Moved by " + e.movementX + ", " + e.movementY);
});

How to get hex color value rather than RGB value?

Function that returns background color of an element in hex.

function getBgColorHex(elem){
    var color = elem.css('background-color')
    var hex;
    if(color.indexOf('#')>-1){
        //for IE
        hex = color;
    } else {
        var rgb = color.match(/\d+/g);
        hex = '#'+ ('0' + parseInt(rgb[0], 10).toString(16)).slice(-2) + ('0' + parseInt(rgb[1], 10).toString(16)).slice(-2) + ('0' + parseInt(rgb[2], 10).toString(16)).slice(-2);
    }
    return hex;
}

usage example:

$('#div1').click(function(){
   alert(getBgColorHex($(this));
}

jsfiddle

Forward declaring an enum in C++

Forward declaration of enums is possible since C++11. Previously, the reason enum types couldn't be forward declared is because the size of the enumeration depends on its contents. As long as the size of the enumeration is specified by the application, it can be forward declared:

enum Enum1;                   //Illegal in C++ and C++0x; no size is explicitly specified.
enum Enum2 : unsigned int;    //Legal in C++0x.
enum class Enum3;             //Legal in C++0x, because enum class declarations have a default type of "int".
enum class Enum4: unsigned int; //Legal C++0x.
enum Enum2 : unsigned short;  //Illegal in C++0x, because Enum2 was previously declared with a different type.

How to create an email form that can send email using html

As many answers in this thread already suggest it is not possible to send a mail from a static HTML page without using PHP or JS. I just wanted to add that there a some great solutions which will take your HTTP Post request generated by your form and create a mail from it. Those solutions are especially useful in case you do not want to add JS or PHP to your website.

Those servers basically can be configured with a mail-server which is responsible for then sending the email. The receiver, subject, body etc. is received by the server from your HTTP(S) post and then stuffed into the mail you want to send. So technically speaking it is still not possible to send mails from your HTML form but the outcome is the same.

Some of these solutions can be bought as SaaS solution or you can host them by yourself. I'll just name a few but I'm sure there are plenty in case anyone is interested in the technology or the service itself.

How do I add my new User Control to the Toolbox or a new Winform?

One way to get this error is trying to add a usercontrol to a form while the project is set to compile as x64. Visual Studio throws the unhelpful: "Failed to load toolbox item . It will be removed from the toolbox."

Workaround is to design with "Any CPU" and compile to x64 as necessary.

Reference: https://support.microsoft.com/en-us/kb/963017

Color text in discord

Discord doesn't allow colored text. Though, currently, you have two options to "mimic" colored text.

Option #1 (Markdown code-blocks)

Discord supports Markdown and uses highlight.js to highlight code-blocks. Some programming languages have specific color outputs from highlight.js and can be used to mimic colored output.

To use code-blocks, send a normal message in this format (Which follows Markdown's standard format).

```language
message
```

Languages that currently reproduce nice colors: prolog (red/orange), css (yellow).

Option #2 (Embeds)

Discord now supports Embeds and Webhooks, which can be used to display colored blocks, they also support markdown. For documentation on how to use Embeds, please read your lib's documentation.

(Embed Cheat-sheet)
Embed Cheat-sheet

Error when deploying an artifact in Nexus

I had this exact problem today and the problem was that the version I was trying to release:perform was already in the Nexus repo.

In my case this was likely due to a network disconnect during an earlier invocation of release:perform. Even though I lost my connection, it appears the release succeeded.

How to select the row with the maximum value in each group

Another data.table option:

library(data.table)
setDT(group)
group[group[order(-pt), .I[1L], Subject]$V1]

Or another (less readable but slightly faster):

group[group[, rn := .I][order(Subject, -pt), {
    rn[c(1L, 1L + which(diff(Subject)>0L))]
}]]

timing code:

library(data.table)
nr <- 1e7L
ng <- nr/4L
set.seed(0L)
DT <- data.table(Subject=sample(ng, nr, TRUE), pt=1:nr)#rnorm(nr))
DT2 <- copy(DT)


microbenchmark::microbenchmark(times=3L,
    mtd0 = {a0 <- DT[DT[, .I[which.max(pt)], by=Subject]$V1]},
    mtd1 = {a1 <- DT[DT[order(-pt), .I[1L], Subject]$V1]},
    mtd2 = {a2 <- DT2[DT2[, rn := .I][
        order(Subject, -pt), rn[c(TRUE, diff(Subject)>0L)]
    ]]},
    mtd3 = {a3 <- unique(DT[order(Subject, -pt)], by="Subject")}
)
fsetequal(a0[order(Subject)], a1[order(Subject)])
#[1] TRUE
fsetequal(a0[order(Subject)], a2[, rn := NULL][order(Subject)])
#[1] TRUE
fsetequal(a0[order(Subject)], a3[order(Subject)])
#[1] TRUE

timings:

Unit: seconds
 expr      min       lq     mean   median       uq      max neval
 mtd0 3.256322 3.335412 3.371439 3.414502 3.428998 3.443493     3
 mtd1 1.733162 1.748538 1.786033 1.763915 1.812468 1.861022     3
 mtd2 1.136307 1.159606 1.207009 1.182905 1.242359 1.301814     3
 mtd3 1.123064 1.166161 1.228058 1.209257 1.280554 1.351851     3

C++ Pass A String

print(string ("Yo!"));

You need to make a (temporary) std::string object out of it.

Is it possible to run .APK/Android apps on iPad/iPhone devices?

Apple users can download your .apk file, however they cannot run it. It is a different file format than iPhone apps (.ipa)

Expand div to max width when float:left is set

Hi there is an easy way with overflow hidden method on right element.

_x000D_
_x000D_
    .content .left {_x000D_
        float:left;_x000D_
        width:100px;_x000D_
        background-color:green;_x000D_
      }_x000D_
      .content .right {_x000D_
        overflow: hidden;_x000D_
        background-color:red;_x000D_
      }
_x000D_
<!DOCTYPE html>   _x000D_
<html lang="en">     _x000D_
    <head>      _x000D_
           _x000D_
        <title>Content Menu</title>         _x000D_
          _x000D_
    </head>_x000D_
    <body>    _x000D_
    <div class="content">_x000D_
      <div class="left">_x000D_
        <p>Hi, Flo! I am Left</p>_x000D_
      </div>_x000D_
      <div class="right">  _x000D_
        <p>is</p>_x000D_
        <p>this</p>_x000D_
        <p>what</p>_x000D_
        <p>you are looking for?</p>_x000D_
        <p> It done with overflow hidden and result is same.</p>_x000D_
      </div>_x000D_
    </div>_x000D_
    </body>_x000D_
</html> 
_x000D_
_x000D_
_x000D_

How do I filter date range in DataTables?

Using other posters code with some tweaks:

<table id="MainContent_tbFilterAsp" style="margin-top:-15px;">
        <tbody>
            <tr>
                <td style="vertical-align:initial;"><label for="datepicker_from" id="MainContent_datepicker_from_lbl" style="margin-top:7px;">From date:</label>&nbsp;
                </td>
                
                <td style="padding-right: 20px;"><input name="ctl00$MainContent$datepicker_from" type="text" id="datepicker_from" class="datepick form-control hasDatepicker" autocomplete="off" style="cursor:pointer; background-color: #FFFFFF">&nbsp;&nbsp;&nbsp;
                </td>
                
                <td style="vertical-align:initial"><label for="datepicker_to" id="MainContent_datepicker_to_lbl" style="margin-top:7px;">To date:</label>&nbsp;
                </td>
                
                <td style="padding-right: 20px;"><input name="ctl00$MainContent$datepicker_to" type="text" id="datepicker_to" class="datepick form-control hasDatepicker" autocomplete="off" style="cursor:pointer; background-color: #FFFFFF">&nbsp;&nbsp;&nbsp;                        
                </td>
                
                <td style="vertical-align:initial"><a onclick="$('#datepicker_from').val(''); $('#datepicker_to').val(''); return false;" id="datepicker_clear_lnk" style="margin-top:7px;">Clear</a></td>
            </tr>
        </tbody>
    </table>
    
    <script>
        $(document).ready(function() {
            $(function() {
                var oTable = $('#tbAD').DataTable({
                "oLanguage": {
                    "sSearch": "Filter Data"
                },
                "iDisplayLength": -1,
                "sPaginationType": "full_numbers",
                "pageLength": 50, 
                });

                $("#datepicker_from").datepicker();
                $("#datepicker_to").datepicker();

                $('#datepicker_from').change(function (e) {
                    oTable.draw();
                });
                $('#datepicker_to').change(function (e) {
                    oTable.draw();
                });
                $('#datepicker_clear_lnk').click(function (e) {
                    oTable.draw();
                });
            });   

            $.fn.dataTable.ext.search.push(
                function (settings, data, dataIndex) {
                var min = $('#datepicker_from').datepicker("getDate") == null ? null : $('#datepicker_from').datepicker("getDate").setHours(0,0,0,0);
                var max = $('#datepicker_to').datepicker("getDate") == null ? null : $('#datepicker_to').datepicker("getDate").setHours(0,0,0,0);
                var startDate = new Date(data[9]).setHours(0,0,0,0);
                if (min == null && max == null) { return true; }
                if (min == null && startDate <= max) { return true; }
                if (max == null && startDate >= min) { return true; }
                if (startDate <= max && startDate >= min) { return true; }                    
                return false;
                }
            );
        });
</script>

Fragment pressing back button

What I do in this cases is I implement the onBackPressed() function from the Activity:

@Override
public void onBackPressed() {
   super.onBackPressed();
   FragmentManager fm = getSupportFragmentManager();
   MyFragment myFragment = (MyFragment) fm.findFragmentById(R.id.my_fragment);

   if((myFragmen.isVisible()){
      //Do what you want to do
   }
}

How this works for you too.

How do I declare and use variables in PL/SQL like I do in T-SQL?

In Oracle PL/SQL, if you are running a query that may return multiple rows, you need a cursor to iterate over the results. The simplest way is with a for loop, e.g.:

declare
  myname varchar2(20) := 'tom';
begin
  for result_cursor in (select * from mytable where first_name = myname) loop
    dbms_output.put_line(result_cursor.first_name);
    dbms_output.put_line(result_cursor.other_field);
  end loop;
end;

If you have a query that returns exactly one row, then you can use the select...into... syntax, e.g.:

declare 
  myname varchar2(20);
begin
  select first_name into myname 
    from mytable 
    where person_id = 123;
end;

Alternative to iFrames with HTML5

No, there isn't an equivalent. The <iframe> element is still valid in HTML5. Depending on what exact interaction you need there might be different APIs. For example there's the postMessage method which allows you to achieve cross domain javascript interaction. But if you want to display cross domain HTML contents (styled with CSS and made interactive with javascript) iframe stays as a good way to do.

Passing array in GET for a REST call

Instead of using http GET, use http POST. And JSON. Or XML

This is how your request stream to the server would look like.

POST /appointments HTTP/1.0
Content-Type: application/json
Content-Length: (calculated by your utility)

{users: [user:{id:id1}, user:{id:id2}]}

Or in XML,

POST /appointments HTTP/1.0
Content-Type: application/json
Content-Length: (calculated by your utility)

<users><user id='id1'/><user id='id2'/></users>

You could certainly continue using GET as you have proposed, as it is certainly simpler.

/appointments?users=1d1,1d2

Which means you would have to keep your data structures very simple.

However, if/when your data structure gets more complex, http GET and without JSON, your programming and ability to recognise the data gets very difficult.

Therefore,unless you could keep your data structure simple, I urge you adopt a data transfer framework. If your requests are browser based, the industry usual practice is JSON. If your requests are server-server, than XML is the most convenient framework.

JQuery

If your client is a browser and you are not using GWT, you should consider using jquery REST. Google on RESTful services with jQuery.

Enabling refreshing for specific html elements only

Try creating a javascript function which runs this:

document.getElementById("youriframeid").contentWindow.location.reload(true);

Or maybe use an HTML workaround:

<html>
<body>
<center>
      <a href="pagename.htm" target="middle">Refresh iframe</a>
      <p>
        <iframe src="pagename.htm" name="middle">
      </p>
</center>
</body>
</html>

Both might be what you're looking for...

Is it necessary to assign a string to a variable before comparing it to another?

Brian, also worth throwing in here - the others are of course correct that you don't need to declare a string variable. However, next time you want to declare a string you don't need to do the following:

NSString *myString = [[NSString alloc] initWithFormat:@"SomeText"];

Although the above does work, it provides a retained NSString variable which you will then need to explicitly release after you've finished using it.

Next time you want a string variable you can use the "@" symbol in a much more convenient way:

NSString *myString = @"SomeText";

This will be autoreleased when you've finished with it so you'll avoid memory leaks too...

Hope that helps!

How to uncheck checkbox using jQuery Uniform library

checkbox that act like radio btn

$(".checkgroup").live('change',function() { var previous=this.checked; $(".checkgroup).attr("checked", false); $(this).attr("checked", previous); });

NGINX - No input file specified. - php Fast/CGI

I solved it by replacing

fastcgi_param SCRIPT_FILENAME $document_root$fastcgi_script_name;

$document_root with C:\MyWebSite\www\

fastcgi_param SCRIPT_FILENAME C:\MyWebSite\www\$fastcgi_script_name;

How to upgrade pip3?

The Problem

You use pip (the Python 2 one). Now you want to upgrade pip (the Python 3 one). After that, pip is the Python 3 one.

The solution

Use pip2 and pip3. This way it is explicit.

If you want to use pip, just check where it is (which pip) and change the link. For example:

$ which pip
/usr/local/bin/pip

$ pip --version
pip 9.0.1 from /usr/local/lib/python3.5/dist-packages (python 3.5)

$ which pip2
/usr/local/bin/pip2

$ sudo rm /usr/local/bin/pip
$ sudo ln -s /usr/local/bin/pip2 /usr/local/bin/pip

$ pip --version
pip 9.0.1 from /usr/local/lib/python2.7/dist-packages (python 2.7)

Css pseudo classes input:not(disabled)not:[type="submit"]:focus

You have a few typos in your select. It should be: input:not([disabled]):not([type="submit"]):focus

See this jsFiddle for a proof of concept. On a sidenote, if I removed the "background-color" property, then the box shadow no longer works. Not sure why.

"Unable to locate tools.jar" when running ant

The order of items in the PATH matters. If there are multiple entries for various java installations, the first one in your PATH will be used.

I have had similar issues after installing a product, like Oracle, that puts it's JRE at the beginning of the PATH.

Ensure that the JDK you want to be loaded is the first entry in your PATH (or at least that it appears before C:\Program Files\Java\jre6\bin appears).

How to Exit a Method without Exiting the Program?

@John, Earlz and Nathan. The way I learned it at uni is: functions return values, methods don't. In some languages the syntax is/was actually different. Example (no specific language):

Method SetY(int y) ...
Function CalculateY(int x) As Integer ...

Most languages now use the same syntax for both versions, using void as a return type to say there actually isn't a return type. I assume it's because the syntax is more consistent and easier to change from method to function, and vice versa.

Using Math.round to round to one decimal place?

A neat alternative that is much more readable in my opinion, however, arguably a tad less efficient due to the conversions between double and String:

double num = 540.512;
double sum = 1978.8;

// NOTE: This does take care of rounding
String str = String.format("%.1f", (num/sum) * 100.0); 

If you want the answer as a double, you could of course convert it back:

double ans = Double.parseDouble(str);

How to execute Python scripts in Windows?

Simply run the command:

C:>python .\file_name.py

Assuming the file name is within same folder and Python has already been added to environment variables.

How to get JS variable to retain value after page refresh?

In addition to cookies and localStorage, there's at least one other place you can store "semi-persistent" client data: window.name. Any string value you assign to window.name will stay there until the window is closed.

To test it out, just open the console and type window.name = "foo", then refresh the page and type window.name; it should respond with foo.

This is a bit of a hack, but if you don't want cookies filled with unnecessary data being sent to the server with every request, and if you can't use localStorage for whatever reason (legacy clients), it may be an option to consider.

window.name has another interesting property: it's visible to windows served from other domains; it's not subject to the same-origin policy like nearly every other property of window. So, in addition to storing "semi-persistent" data there while the user navigates or refreshes the page, you can also use it for CORS-free cross-domain communication.

Note that window.name can only store strings, but with the wide availability of JSON, this shouldn't be much of an issue even for complex data.

IOS: verify if a point is inside a rect

In objective c you can use CGRectContainsPoint(yourview.frame, touchpoint)

-(void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event{
UITouch* touch = [touches anyObject];
CGPoint touchpoint = [touch locationInView:self.view];
if( CGRectContainsPoint(yourview.frame, touchpoint) ) {

}else{

}}

In swift 3 yourview.frame.contains(touchpoint)

 override func touchesBegan(_ touches: Set<UITouch>, with event: UIEvent?) {
    let touch:UITouch = touches.first!
    let touchpoint:CGPoint = touch.location(in: self.view)
    if wheel.frame.contains(touchpoint)  {

    }else{

    }

}

How to subtract 30 days from the current datetime in mysql?

To anyone who doesn't want to use DATE_SUB, use CURRENT_DATE:

SELECT CURRENT_DATE - INTERVAL 30 DAY

How to generate Javadoc from command line

The answers given were not totally complete if multiple sourcepath and subpackages have to be processed.

The following command line will process all the packages under com and LOR (lord of the rings) located into /home/rudy/IdeaProjects/demo/src/main/java and /home/rudy/IdeaProjects/demo/src/test/java/

Please note:

  • it is Linux and the paths and packages are separated by ':'.
  • that I made usage of private and wanted all the classes and members to be documented.

rudy@rudy-ThinkPad-T590:~$ javadoc -d /home/rudy/IdeaProjects/demo_doc
-sourcepath /home/rudy/IdeaProjects/demo/src/main/java/
:/home/rudy/IdeaProjects/demo/src/test/java/
-subpackages com:LOR 
-private

rudy@rudy-ThinkPad-T590:~/IdeaProjects/demo/src/main/java$ ls -R 
.: com LOR
./com: example
./com/example: demo
./com/example/demo: DemowApplication.java
./LOR: Race.java TolkienCharacter.java

rudy@rudy-ThinkPad-T590:~/IdeaProjects/demo/src/test/java$ ls -R 
.: com
./com: example
./com/example: demo
./com/example/demo: AssertJTest.java DemowApplicationTests.java

How to declare a variable in SQL Server and use it in the same Stored Procedure

CREATE PROCEDURE AddBrand
@BrandName nvarchar(50) = null,
@CategoryID int = null
AS    
BEGIN

DECLARE @BrandID int = null
SELECT @BrandID = BrandID FROM tblBrand 
WHERE BrandName = @BrandName

INSERT INTO tblBrandinCategory (CategoryID, BrandID) 
       VALUES (@CategoryID, @BrandID)

END

EXEC AddBrand @BrandName = 'BMW', @CategoryId = 1

Append values to a set in Python

You can also use the | operator to concatenate two sets (union in set theory):

>>> my_set = {1}
>>> my_set = my_set | {2}
>>> my_set
{1, 2}

Or a shorter form using |=:

>>> my_set = {1}
>>> my_set |= {2}
>>> my_set
{1, 2}

Note: In versions prior to Python 2.7, use set([...]) instead of {...}.

how to loop through json array in jquery?

var data = [ 
 {"Id": 10004, "PageName": "club"}, 
 {"Id": 10040, "PageName": "qaz"}, 
 {"Id": 10059, "PageName": "jjjjjjj"}
];

$.each(data, function(i, item) {
   alert(data[i].PageName);
});?

$.each(data, function(i, item) {
  alert(item.PageName);
});?

Or else You can try this method

var data = jQuery.parseJSON(response);
$.each(data, function(key,value) {
   alert(value.Id);    //It will shows the Id values
}); 

How can I tell what edition of SQL Server runs on the machine?

SELECT  CASE WHEN SERVERPROPERTY('EditionID') = -1253826760 THEN 'Desktop'
         WHEN SERVERPROPERTY('EditionID') = -1592396055 THEN 'Express'
         WHEN SERVERPROPERTY('EditionID') = -1534726760 THEN 'Standard'
         WHEN SERVERPROPERTY('EditionID') = 1333529388 THEN 'Workgroup'
         WHEN SERVERPROPERTY('EditionID') = 1804890536 THEN 'Enterprise'
         WHEN SERVERPROPERTY('EditionID') = -323382091 THEN 'Personal'
         WHEN SERVERPROPERTY('EditionID') = -2117995310  THEN 'Developer'
         WHEN SERVERPROPERTY('EditionID') = 610778273  THEN 'Windows Embedded SQL'
         WHEN SERVERPROPERTY('EditionID') = 4161255391   THEN 'Express with Advanced Services'
    END AS 'Edition'; 

How to download files using axios

A more general solution

axios({
  url: 'http://api.dev/file-download', //your url
  method: 'GET',
  responseType: 'blob', // important
}).then((response) => {
   const url = window.URL.createObjectURL(new Blob([response.data]));
   const link = document.createElement('a');
   link.href = url;
   link.setAttribute('download', 'file.pdf'); //or any other extension
   document.body.appendChild(link);
   link.click();
});

Check out the quirks at https://gist.github.com/javilobo8/097c30a233786be52070986d8cdb1743

Full credits to: https://gist.github.com/javilobo8

what is Ljava.lang.String;@

According to the Java Virtual Machine Specification (Java SE 8), JVM §4.3.2. Field Descriptors:

FieldType term | Type      | Interpretation
-------------- | --------- | --------------
L ClassName ;  | reference | an instance of class ClassName
[              | reference | one array dimension
...            | ...       | ...

the expression [Ljava.lang.String;@45a877 means this is an array ( [ ) of class java.lang.String ( Ljava.lang.String; ). And @45a877 is the address where the String object is stored in memory.

How to calculate a Mod b in Casio fx-991ES calculator

As far as I know, that calculator does not offer mod functions. You can however computer it by hand in a fairly straightforward manner. Ex.

(1)50 mod 3

(2)50/3 = 16.66666667

(3)16.66666667 - 16 = 0.66666667

(4)0.66666667 * 3 = 2

Therefore 50 mod 3 = 2

Things to Note: On line 3, we got the "minus 16" by looking at the result from line (2) and ignoring everything after the decimal. The 3 in line (4) is the same 3 from line (1).

Hope that Helped.

Edit As a result of some trials you may get x.99991 which you will then round up to the number x+1.

Converting a Date object to a calendar object

it's so easy...converting a date to calendar like this:

Calendar cal=Calendar.getInstance();
DateFormat format=new SimpleDateFormat("yyyy/mm/dd");
format.format(date);
cal=format.getCalendar();

How to source virtualenv activate in a Bash script

Although it doesn't add the "(.env)" prefix to the shell prompt, I found this script works as expected.

#!/bin/bash
script_dir=`dirname $0`
cd $script_dir
/bin/bash -c ". ../.env/bin/activate; exec /bin/bash -i"

e.g.

user@localhost:~/src$ which pip
/usr/local/bin/pip
user@localhost:~/src$ which python
/usr/bin/python
user@localhost:~/src$ ./shell
user@localhost:~/src$ which pip
~/.env/bin/pip
user@localhost:~/src$ which python
~/.env/bin/python
user@localhost:~/src$ exit
exit

How can I multiply and divide using only bit shifting and adding?

it is basically multiplying and dividing with the base power 2

shift left = x * 2 ^ y

shift right = x / 2 ^ y

shl eax,2 = 2 * 2 ^ 2 = 8

shr eax,3 = 2 / 2 ^ 3 = 1/4

Check if record exists from controller in Rails

In this case I like to use the exists? method provided by ActiveRecord:

Business.exists? user_id: current_user.id

Set specific precision of a BigDecimal

Try this code ...

    Integer perc = 5;
    BigDecimal spread = BigDecimal.ZERO; 
    BigDecimal perc = spread.setScale(perc,BigDecimal.ROUND_HALF_UP);
    System.out.println(perc);

Result: 0.00000

how to add the missing RANDR extension

I am seeing this error message when I run Firefox headless through selenium using xvfb. It turns out that the message was a red herring for me. The message is only a warning, not an error. It is not why Firefox was not starting correctly.

The reason that Firefox was not starting for me was that it had been updated to a version that was no longer compatible with the Selenium drivers that I was using. I upgraded the selenium drivers to the latest and Firefox starts up fine again (even with this warning message about RANDR).

New releases of Firefox are often only compatible with one or two versions of Selenium. Occasionally Firefox is released with NO compatible version of Selenium. When that happens, it may take a week or two for a new version of Selenium to get released. Because of this, I now keep a version of Firefox that is known to work with the version of Selenium that I have installed. In addition to the version of Firefox that is kept up to date by my package manager, I have a version installed in /opt/ (eg /opt/firefox31/). The Selenium Java API takes an argument for the location of the Firefox binary to be used. The downside is that older versions of Firefox have known security vulnerabilities and shouldn't be used with untrusted content.

How can I recover the return value of a function passed to multiprocessing.Process?

A simple solution:

import multiprocessing

output=[]
data = range(0,10)

def f(x):
    return x**2

def handler():
    p = multiprocessing.Pool(64)
    r=p.map(f, data)
    return r

if __name__ == '__main__':
    output.append(handler())

print(output[0])

Output:

[0, 1, 4, 9, 16, 25, 36, 49, 64, 81]

sed: print only matching group

grep is the right tool for extracting.

using your example and your regex:

kent$  echo 'foo bar <foo> bla 1 2 3.4'|grep -o '[0-9][0-9]*[\ \t][0-9.]*[\ \t]*$'
2 3.4

Decimal values in SQL for dividing results

CAST( ROUND(columnA *1.00 / columnB, 2) AS FLOAT)

How to change current Theme at runtime in Android

If you want to change theme of an already existing activity, call recreate() after setTheme().

Note: don't call recreate if you change theme in onCreate(), to avoid infinite loop.

Div Background Image Z-Index Issue

Set your header and footer position to "absolute" and that should do the trick. Hope it helps and good luck with your project!

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

Right-click, then "Open link in new tab"

edit : you can also double-click, it has the same effect

Count the number of occurrences of a string in a VARCHAR field?

SELECT 
id,
jsondata,    
ROUND (   
    (
        LENGTH(jsondata)
        - LENGTH( REPLACE ( jsondata, "sonal", "") ) 
    ) / LENGTH("sonal")        
)
+
ROUND (   
    (
        LENGTH(jsondata)
        - LENGTH( REPLACE ( jsondata, "khunt", "") ) 
    ) / LENGTH("khunt")        
)
AS count1    FROM test ORDER BY count1 DESC LIMIT 0, 2

Thanks Yannis, your solution worked for me and here I'm sharing same solution for multiple keywords with order and limit.

Swift: Sort array of objects alphabetically

With Swift 3, you can choose one of the following ways to solve your problem.


1. Using sorted(by:?) with a Movie class that does not conform to Comparable protocol

If your Movie class does not conform to Comparable protocol, you must specify in your closure the property on which you wish to use Array's sorted(by:?) method.

Movie class declaration:

import Foundation

class Movie: CustomStringConvertible {

    let name: String
    var date: Date
    var description: String { return name }

    init(name: String, date: Date = Date()) {
        self.name = name
        self.date = date
    }

}

Usage:

let avatarMovie = Movie(name: "Avatar")
let titanicMovie = Movie(name: "Titanic")
let piranhaMovie = Movie(name: "Piranha II: The Spawning")

let movies = [avatarMovie, titanicMovie, piranhaMovie]
let sortedMovies = movies.sorted(by: { $0.name < $1.name })
// let sortedMovies = movies.sorted { $0.name < $1.name } // also works

print(sortedMovies)

/*
prints: [Avatar, Piranha II: The Spawning, Titanic]
*/

2. Using sorted(by:?) with a Movie class that conforms to Comparable protocol

However, by making your Movie class conform to Comparable protocol, you can have a much concise code when you want to use Array's sorted(by:?) method.

Movie class declaration:

import Foundation

class Movie: CustomStringConvertible, Comparable {

    let name: String
    var date: Date
    var description: String { return name }

    init(name: String, date: Date = Date()) {
        self.name = name
        self.date = date
    }

    static func ==(lhs: Movie, rhs: Movie) -> Bool {
        return lhs.name == rhs.name
    }

    static func <(lhs: Movie, rhs: Movie) -> Bool {
        return lhs.name < rhs.name
    }

}

Usage:

let avatarMovie = Movie(name: "Avatar")
let titanicMovie = Movie(name: "Titanic")
let piranhaMovie = Movie(name: "Piranha II: The Spawning")

let movies = [avatarMovie, titanicMovie, piranhaMovie]
let sortedMovies = movies.sorted(by: { $0 < $1 })
// let sortedMovies = movies.sorted { $0 < $1 } // also works
// let sortedMovies = movies.sorted(by: <) // also works

print(sortedMovies)

/*
 prints: [Avatar, Piranha II: The Spawning, Titanic]
 */

3. Using sorted() with a Movie class that conforms to Comparable protocol

By making your Movie class conform to Comparable protocol, you can use Array's sorted() method as an alternative to sorted(by:?).

Movie class declaration:

import Foundation

class Movie: CustomStringConvertible, Comparable {

    let name: String
    var date: Date
    var description: String { return name }

    init(name: String, date: Date = Date()) {
        self.name = name
        self.date = date
    }

    static func ==(lhs: Movie, rhs: Movie) -> Bool {
        return lhs.name == rhs.name
    }

    static func <(lhs: Movie, rhs: Movie) -> Bool {
        return lhs.name < rhs.name
    }

}

Usage:

let avatarMovie = Movie(name: "Avatar")
let titanicMovie = Movie(name: "Titanic")
let piranhaMovie = Movie(name: "Piranha II: The Spawning")

let movies = [avatarMovie, titanicMovie, piranhaMovie]
let sortedMovies = movies.sorted()

print(sortedMovies)

/*
 prints: [Avatar, Piranha II: The Spawning, Titanic]
 */

Apache redirect to another port

If you don't have to use a proxy to JBoss and mydomain.com:8080 can be "exposed" to the world, then I would do this.

<VirtualHost *:80>
  ServerName mydomain.com
  Redirect 301 / http://mydomain.com:8080/
</VirtualHost>

PHP unable to load php_curl.dll extension

Solution:

Step1: Uncomment the php_curl.dll from php.ini

Step2: Copy the following three files from php installed directory.i.e "C:\\php7".

libeay32.dll,
libssh2.dll,
ssleay32.dll

Step3: Paste the files under two place

httpd.conf's ServerRoot directive. i.e "C\Apache24"
apache bin directory. i.e "C\Apache24\bin"

Step4: Restart apache.

That's all. I solve the problem by this way.Hope it might work for you.

The solution is given here. https://abcofcomputing.blogspot.com/2017/06/php7-unable-to-load-phpcurldll.html

Java, return if trimmed String in List contains String

Try this:

for(String str: myList) {
    if(str.trim().equals("A"))
       return true;
}
return false;

You need to use str.equals or str.equalsIgnoreCase instead of contains because contains in string works not the same as contains in List

List<String> s = Arrays.asList("BAB", "SAB", "DAS");
s.contains("A"); // false
"BAB".contains("A"); // true

Bash Script : what does #!/bin/bash mean?

That is called a shebang, it tells the shell what program to interpret the script with, when executed.

In your example, the script is to be interpreted and run by the bash shell.

Some other example shebangs are:

(From Wikipedia)

#!/bin/sh — Execute the file using sh, the Bourne shell, or a compatible shell
#!/bin/csh — Execute the file using csh, the C shell, or a compatible shell
#!/usr/bin/perl -T — Execute using Perl with the option for taint checks
#!/usr/bin/php — Execute the file using the PHP command line interpreter
#!/usr/bin/python -O — Execute using Python with optimizations to code
#!/usr/bin/ruby — Execute using Ruby

and a few additional ones I can think off the top of my head, such as:

#!/bin/ksh
#!/bin/awk
#!/bin/expect

In a script with the bash shebang, for example, you would write your code with bash syntax; whereas in a script with expect shebang, you would code it in expect syntax, and so on.

Response to updated portion:

It depends on what /bin/sh actually points to on your system. Often it is just a symlink to /bin/bash. Sometimes portable scripts are written with #!/bin/sh just to signify that it's a shell script, but it uses whichever shell is referred to by /bin/sh on that particular system (maybe it points to /bin/bash, /bin/ksh or /bin/zsh)

C++11 introduced a standardized memory model. What does it mean? And how is it going to affect C++ programming?

I will just give the analogy with which I understand memory consistency models (or memory models, for short). It is inspired by Leslie Lamport's seminal paper "Time, Clocks, and the Ordering of Events in a Distributed System". The analogy is apt and has fundamental significance, but may be overkill for many people. However, I hope it provides a mental image (a pictorial representation) that facilitates reasoning about memory consistency models.

Let’s view the histories of all memory locations in a space-time diagram in which the horizontal axis represents the address space (i.e., each memory location is represented by a point on that axis) and the vertical axis represents time (we will see that, in general, there is not a universal notion of time). The history of values held by each memory location is, therefore, represented by a vertical column at that memory address. Each value change is due to one of the threads writing a new value to that location. By a memory image, we will mean the aggregate/combination of values of all memory locations observable at a particular time by a particular thread.

Quoting from "A Primer on Memory Consistency and Cache Coherence"

The intuitive (and most restrictive) memory model is sequential consistency (SC) in which a multithreaded execution should look like an interleaving of the sequential executions of each constituent thread, as if the threads were time-multiplexed on a single-core processor.

That global memory order can vary from one run of the program to another and may not be known beforehand. The characteristic feature of SC is the set of horizontal slices in the address-space-time diagram representing planes of simultaneity (i.e., memory images). On a given plane, all of its events (or memory values) are simultaneous. There is a notion of Absolute Time, in which all threads agree on which memory values are simultaneous. In SC, at every time instant, there is only one memory image shared by all threads. That's, at every instant of time, all processors agree on the memory image (i.e., the aggregate content of memory). Not only does this imply that all threads view the same sequence of values for all memory locations, but also that all processors observe the same combinations of values of all variables. This is the same as saying all memory operations (on all memory locations) are observed in the same total order by all threads.

In relaxed memory models, each thread will slice up address-space-time in its own way, the only restriction being that slices of each thread shall not cross each other because all threads must agree on the history of every individual memory location (of course, slices of different threads may, and will, cross each other). There is no universal way to slice it up (no privileged foliation of address-space-time). Slices do not have to be planar (or linear). They can be curved and this is what can make a thread read values written by another thread out of the order they were written in. Histories of different memory locations may slide (or get stretched) arbitrarily relative to each other when viewed by any particular thread. Each thread will have a different sense of which events (or, equivalently, memory values) are simultaneous. The set of events (or memory values) that are simultaneous to one thread are not simultaneous to another. Thus, in a relaxed memory model, all threads still observe the same history (i.e., sequence of values) for each memory location. But they may observe different memory images (i.e., combinations of values of all memory locations). Even if two different memory locations are written by the same thread in sequence, the two newly written values may be observed in different order by other threads.

[Picture from Wikipedia] Picture from Wikipedia

Readers familiar with Einstein’s Special Theory of Relativity will notice what I am alluding to. Translating Minkowski’s words into the memory models realm: address space and time are shadows of address-space-time. In this case, each observer (i.e., thread) will project shadows of events (i.e., memory stores/loads) onto his own world-line (i.e., his time axis) and his own plane of simultaneity (his address-space axis). Threads in the C++11 memory model correspond to observers that are moving relative to each other in special relativity. Sequential consistency corresponds to the Galilean space-time (i.e., all observers agree on one absolute order of events and a global sense of simultaneity).

The resemblance between memory models and special relativity stems from the fact that both define a partially-ordered set of events, often called a causal set. Some events (i.e., memory stores) can affect (but not be affected by) other events. A C++11 thread (or observer in physics) is no more than a chain (i.e., a totally ordered set) of events (e.g., memory loads and stores to possibly different addresses).

In relativity, some order is restored to the seemingly chaotic picture of partially ordered events, since the only temporal ordering that all observers agree on is the ordering among “timelike” events (i.e., those events that are in principle connectible by any particle going slower than the speed of light in a vacuum). Only the timelike related events are invariantly ordered. Time in Physics, Craig Callender.

In C++11 memory model, a similar mechanism (the acquire-release consistency model) is used to establish these local causality relations.

To provide a definition of memory consistency and a motivation for abandoning SC, I will quote from "A Primer on Memory Consistency and Cache Coherence"

For a shared memory machine, the memory consistency model defines the architecturally visible behavior of its memory system. The correctness criterion for a single processor core partitions behavior between “one correct result” and “many incorrect alternatives”. This is because the processor’s architecture mandates that the execution of a thread transforms a given input state into a single well-defined output state, even on an out-of-order core. Shared memory consistency models, however, concern the loads and stores of multiple threads and usually allow many correct executions while disallowing many (more) incorrect ones. The possibility of multiple correct executions is due to the ISA allowing multiple threads to execute concurrently, often with many possible legal interleavings of instructions from different threads.

Relaxed or weak memory consistency models are motivated by the fact that most memory orderings in strong models are unnecessary. If a thread updates ten data items and then a synchronization flag, programmers usually do not care if the data items are updated in order with respect to each other but only that all data items are updated before the flag is updated (usually implemented using FENCE instructions). Relaxed models seek to capture this increased ordering flexibility and preserve only the orders that programmers “require” to get both higher performance and correctness of SC. For example, in certain architectures, FIFO write buffers are used by each core to hold the results of committed (retired) stores before writing the results to the caches. This optimization enhances performance but violates SC. The write buffer hides the latency of servicing a store miss. Because stores are common, being able to avoid stalling on most of them is an important benefit. For a single-core processor, a write buffer can be made architecturally invisible by ensuring that a load to address A returns the value of the most recent store to A even if one or more stores to A are in the write buffer. This is typically done by either bypassing the value of the most recent store to A to the load from A, where “most recent” is determined by program order, or by stalling a load of A if a store to A is in the write buffer. When multiple cores are used, each will have its own bypassing write buffer. Without write buffers, the hardware is SC, but with write buffers, it is not, making write buffers architecturally visible in a multicore processor.

Store-store reordering may happen if a core has a non-FIFO write buffer that lets stores depart in a different order than the order in which they entered. This might occur if the first store misses in the cache while the second hits or if the second store can coalesce with an earlier store (i.e., before the first store). Load-load reordering may also happen on dynamically-scheduled cores that execute instructions out of program order. That can behave the same as reordering stores on another core (Can you come up with an example interleaving between two threads?). Reordering an earlier load with a later store (a load-store reordering) can cause many incorrect behaviors, such as loading a value after releasing the lock that protects it (if the store is the unlock operation). Note that store-load reorderings may also arise due to local bypassing in the commonly implemented FIFO write buffer, even with a core that executes all instructions in program order.

Because cache coherence and memory consistency are sometimes confused, it is instructive to also have this quote:

Unlike consistency, cache coherence is neither visible to software nor required. Coherence seeks to make the caches of a shared-memory system as functionally invisible as the caches in a single-core system. Correct coherence ensures that a programmer cannot determine whether and where a system has caches by analyzing the results of loads and stores. This is because correct coherence ensures that the caches never enable new or different functional behavior (programmers may still be able to infer likely cache structure using timing information). The main purpose of cache coherence protocols is maintaining the single-writer-multiple-readers (SWMR) invariant for every memory location. An important distinction between coherence and consistency is that coherence is specified on a per-memory location basis, whereas consistency is specified with respect to all memory locations.

Continuing with our mental picture, the SWMR invariant corresponds to the physical requirement that there be at most one particle located at any one location but there can be an unlimited number of observers of any location.

How to display length of filtered ng-repeat data

For Angular 1.3+ (credits to @Tom)

Use an alias expression (Docs: Angular 1.3.0: ngRepeat, scroll down to the Arguments section):

<div ng-repeat="person in data | filter:query as filtered">
</div>

For Angular prior to 1.3

Assign the results to a new variable (e.g. filtered) and access it:

<div ng-repeat="person in filtered = (data | filter: query)">
</div>

Display the number of results:

Showing {{filtered.length}} Persons

Fiddle a similar example. Credits go to Pawel Kozlowski

How can I break from a try/catch block without throwing an exception in Java

Various ways:

  • return
  • break or continue when in a loop
  • break to label when in a labeled statement (see @aioobe's example)
  • break when in a switch statement.

...

  • System.exit() ... though that's probably not what you mean.

In my opinion, "break to label" is the most natural (least contorted) way to do this if you just want to get out of a try/catch. But it could be confusing to novice Java programmers who have never encountered that Java construct.

But while labels are obscure, in my opinion wrapping the code in a do ... while (false) so that you can use a break is a worse idea. This will confuse non-novices as well as novices. It is better for novices (and non-novices!) to learn about labeled statements.


By the way, return works in the case where you need to break out of a finally. But you should avoid doing a return in a finally block because the semantics are a bit confusing, and liable to give the reader a headache.

R barplot Y-axis scale too short

barplot(data)

enter image description here

barplot(data, yaxp=c(0, max(data), 5))

enter image description here

yaxp=c(minY-axis, maxY-axis, Interval)

Java - checking if parseInt throws exception

instead of trying & catching expressions.. its better to run regex on the string to ensure that it is a valid number..

How to read a text-file resource into Java unit test?

First make sure that abc.xml is being copied to your output directory. Then you should use getResourceAsStream():

InputStream inputStream = 
    Thread.currentThread().getContextClassLoader().getResourceAsStream("test/resources/abc.xml");

Once you have the InputStream, you just need to convert it into a string. This resource spells it out: http://www.kodejava.org/examples/266.html. However, I'll excerpt the relevent code:

public String convertStreamToString(InputStream is) throws IOException {
    if (is != null) {
        Writer writer = new StringWriter();

        char[] buffer = new char[1024];
        try {
            Reader reader = new BufferedReader(
                    new InputStreamReader(is, "UTF-8"));
            int n;
            while ((n = reader.read(buffer)) != -1) {
                writer.write(buffer, 0, n);
            }
        } finally {
            is.close();
        }
        return writer.toString();
    } else {        
        return "";
    }
}

Setting a div's height in HTML with CSS

_x000D_
_x000D_
.rightfloat {_x000D_
  color: red;_x000D_
  background-color: #BBBBBB;_x000D_
  float: right;_x000D_
  width: 200px;_x000D_
}_x000D_
_x000D_
.left {_x000D_
  font-size: 20pt;_x000D_
}_x000D_
_x000D_
.separator {_x000D_
  clear: both;_x000D_
  width: 100%;_x000D_
  border-top: 1px solid black;_x000D_
}
_x000D_
<div class="separator">_x000D_
  <div class="rightfloat">_x000D_
    Some really short content._x000D_
  </div>_x000D_
  <div class="left"> _x000D_
    Some really really really really really really_x000D_
    really really really really big content_x000D_
  </div>_x000D_
</div>_x000D_
<div class="separator">_x000D_
  <div class="rightfloat">_x000D_
    Some more short content._x000D_
  </div>_x000D_
  <div class="left"> _x000D_
    Some really really really really really really_x000D_
    really really really really big content_x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Golang append an item to a slice

In your example the slice argument of the Test function receives a copy of the variable a in the caller's scope.

Since a slice variable holds a "slice descriptor" which merely references an underlying array, in your Test function you modify the slice descriptor held in the slice variable several times in a row, but this does not affect the caller and its a variable.

Inside the Test function, the first append reallocates the backing array under the slice variable, copies its original contents over, appends 100 to it, and that's what you're observing. Upon exiting from Test, the slice variable goes out of scope and so does the (new) underlying array that slice references. (Jeff Lee is correct about that it's not what really happens, so the updated version follows; as he correctly states, this answer is correct, if maybe a bit too terse.)

Outside the Test function, a slice of length 7 and capacity 8 is allocated, and its 7 elements filled.
Inside the Test function, the first append sees the that the slice's capacity is still one element larger than its length — in other words, there is room for one more element to add without reallocation. So it "eats up" that remaining element and places 100 to it, after which it adjusts the length in the copy of the slice descriptor to become equal to the slice's capaticy. This does not affect the slice descriptor's in the caller's scope.

And that's what you're observing. Upon exiting from Test, the slice variable goes out of scope and so does the (new) underlying array that slice references.

If you want to make Test behave like append, you have to return the new slice from it — just like append does — and require the callers of Test to use it in the same way they would use append:

func Test(slice []int) []int {
    slice = append(slice, 100)

    fmt.Println(slice)

    return slice
}

a = Test(a)

Please read this article thoroughly as it basically shows you how to implement append by hand, after explaining how slices are working internally. Then read this.

How to maintain state after a page refresh in React.js?

Load state from localStorage if exist:

constructor(props) {
    super(props);           
    this.state = JSON.parse(localStorage.getItem('state'))
        ? JSON.parse(localStorage.getItem('state'))
        : initialState

override this.setState to automatically save state after each update :

const orginial = this.setState;     
this.setState = function() {
    let arguments0 = arguments[0];
    let arguments1 = () => (arguments[1], localStorage.setItem('state', JSON.stringify(this.state)));
    orginial.bind(this)(arguments0, arguments1);
};

Setting the User-Agent header for a WebClient request

const string ua = "Mozilla/5.0 (compatible; MSIE 9.0; Windows NT 6.1; WOW64; Trident/5.0)";
Request.Headers["User-Agent"] = ua;
var httpWorkerRequestField = Request.GetType().GetField("_wr", BindingFlags.Instance | BindingFlags.NonPublic);
if (httpWorkerRequestField != null)
{
    var httpWorkerRequest = httpWorkerRequestField.GetValue(Request);
    var knownRequestHeadersField = httpWorkerRequest.GetType().GetField("_knownRequestHeaders", BindingFlags.Instance | BindingFlags.NonPublic);
    if (knownRequestHeadersField != null)
    {
        string[] knownRequestHeaders = (string[])knownRequestHeadersField.GetValue(httpWorkerRequest);
                    knownRequestHeaders[39] = ua;
    }
}

Detect click outside React component

To extend on the accepted answer made by Ben Bud, if you are using styled-components, passing refs that way will give you an error such as "this.wrapperRef.contains is not a function".

The suggested fix, in the comments, to wrap the styled component with a div and pass the ref there, works. Having said that, in their docs they already explain the reason for this and the proper use of refs within styled-components:

Passing a ref prop to a styled component will give you an instance of the StyledComponent wrapper, but not to the underlying DOM node. This is due to how refs work. It's not possible to call DOM methods, like focus, on our wrappers directly. To get a ref to the actual, wrapped DOM node, pass the callback to the innerRef prop instead.

Like so:

<StyledDiv innerRef={el => { this.el = el }} />

Then you can access it directly within the "handleClickOutside" function:

handleClickOutside = e => {
    if (this.el && !this.el.contains(e.target)) {
        console.log('clicked outside')
    }
}

This also applies for the "onBlur" approach:

componentDidMount(){
    this.el.focus()
}
blurHandler = () => {
    console.log('clicked outside')
}
render(){
    return(
        <StyledDiv
            onBlur={this.blurHandler}
            tabIndex="0"
            innerRef={el => { this.el = el }}
        />
    )
}

Python slice first and last element in list

One way:

some_list[::len(some_list)-1]

A better way (Doesn't use slicing, but is easier to read):

[some_list[0], some_list[-1]]

push object into array

can be done like this too.

       let data_array = [];
    
       let my_object = {}; 

       my_object.name = "stack";
       my_object.age = 20;
       my_object.hair_color = "red";
       my_object.eye_color = "green";
        
       data_array.push(my_object);

How to check if character is a letter in Javascript?

It's possible to know if the character is a letter or not by using a standard builtin function isNaN or Number.isNaN() from ES6:

isNaN('s') // true
isNaN('-') // true
isNaN('32') // false, '32' is converted to the number 32 which is not NaN

It retruns true if the given value is not a number, otherwise false.

Reading JSON from a file?

This works for me.

json.load() accepts file object, parses the JSON data, populates a Python dictionary with the data and returns it back to you.

Suppose JSON file is like this:

{
   "emp_details":[
                 {
                "emp_name":"John",
                "emp_emailId":"[email protected]"  
                  },
                {
                 "emp_name":"Aditya",
                 "emp_emailId":"[email protected]"
                }
              ] 
}


import json 

# Opening JSON file 
f = open('data.json',) 

# returns JSON object as  
# a dictionary 
data = json.load(f) 

# Iterating through the json 
# list 
for i in data['emp_details']: 
    print(i) 

# Closing file 
f.close()

#Output:
{'emp_name':'John','emp_emailId':'[email protected]'}
{'emp_name':'Aditya','emp_emailId':'[email protected]'}

Post form data using HttpWebRequest

You are encoding the form incorrectly. You should only encode the values:

StringBuilder postData = new StringBuilder();
postData.Append("username=" + HttpUtility.UrlEncode(uname) + "&");
postData.Append("password=" + HttpUtility.UrlEncode(pword) + "&");
postData.Append("url_success=" + HttpUtility.UrlEncode(urlSuccess) + "&");
postData.Append("url_failed=" + HttpUtility.UrlEncode(urlFailed));

edit

I was incorrect. According to RFC1866 section 8.2.1 both names and values should be encoded.

But for the given example, the names do not have any characters that needs to be encoded, so in this case my code example is correct ;)

The code in the question is still incorrect as it would encode the equal sign which is the reason to why the web server cannot decode it.

A more proper way would have been:

StringBuilder postData = new StringBuilder();
postData.AppendUrlEncoded("username", uname);
postData.AppendUrlEncoded("password", pword);
postData.AppendUrlEncoded("url_success", urlSuccess);
postData.AppendUrlEncoded("url_failed", urlFailed);

//in an extension class
public static void AppendUrlEncoded(this StringBuilder sb, string name, string value)
{
    if (sb.Length != 0)
        sb.Append("&");
    sb.Append(HttpUtility.UrlEncode(name));
    sb.Append("=");
    sb.Append(HttpUtility.UrlEncode(value));
}

How to print all session variables currently set?

echo '<pre>';
var_dump($_SESSION);
echo '</pre>';

Or you can use print_r if you don't care about types. If you use print_r, you can make the second argument TRUE so it will return instead of echo, useful for...

echo '<pre>' . print_r($_SESSION, TRUE) . '</pre>';

Expansion of variables inside single quotes in a command in Bash

The repo command can't care what kind of quotes it gets. If you need parameter expansion, use double quotes. If that means you wind up having to backslash a lot of stuff, use single quotes for most of it, and then break out of them and go into doubles for the part where you need the expansion to happen.

repo forall -c 'literal stuff goes here; '"stuff with $parameters here"' more literal stuff'

Explanation follows, if you're interested.

When you run a command from the shell, what that command receives as arguments is an array of null-terminated strings. Those strings may contain absolutely any non-null character.

But when the shell is building that array of strings from a command line, it interprets some characters specially; this is designed to make commands easier (indeed, possible) to type. For instance, spaces normally indicate the boundary between strings in the array; for that reason, the individual arguments are sometimes called "words". But an argument may nonetheless have spaces in it; you just need some way to tell the shell that's what you want.

You can use a backslash in front of any character (including space, or another backslash) to tell the shell to treat that character literally. But while you can do something like this:

echo \”That\'ll\ be\ \$4.96,\ please,\"\ said\ the\ cashier

...it can get tiresome. So the shell offers an alternative: quotation marks. These come in two main varieties.

Double-quotation marks are called "grouping quotes". They prevent wildcards and aliases from being expanded, but mostly they're for including spaces in a word. Other things like parameter and command expansion (the sorts of thing signaled by a $) still happen. And of course if you want a literal double-quote inside double-quotes, you have to backslash it:

echo "\"That'll be \$4.96, please,\" said the cashier"

Single-quotation marks are more draconian. Everything between them is taken completely literally, including backslashes. There is absolutely no way to get a literal single quote inside single quotes.

Fortunately, quotation marks in the shell are not word delimiters; by themselves, they don't terminate a word. You can go in and out of quotes, including between different types of quotes, within the same word to get the desired result:

echo '"That'\''ll be $4.96, please," said the cashier'

So that's easier - a lot fewer backslashes, although the close-single-quote, backslashed-literal-single-quote, open-single-quote sequence takes some getting used to.

Modern shells have added another quoting style not specified by the POSIX standard, in which the leading single quotation mark is prefixed with a dollar sign. Strings so quoted follow similar conventions to string literals in the ANSI standard version of the C programming language, and are therefore sometimes called "ANSI strings" and the $'...' pair "ANSI quotes". Within such strings, the above advice about backslashes being taken literally no longer applies. Instead, they become special again - not only can you include a literal single quotation mark or backslash by prepending a backslash to it, but the shell also expands the ANSI C character escapes (like \n for a newline, \t for tab, and \xHH for the character with hexadecimal code HH). Otherwise, however, they behave as single-quoted strings: no parameter or command substitution takes place:

echo $'"That\'ll be $4.96, please," said the cashier'

The important thing to note is that the single string received as the argument to the echo command is exactly the same in all of these examples. After the shell is done parsing a command line, there is no way for the command being run to tell what was quoted how. Even if it wanted to.

runOnUiThread in fragment

Try this: getActivity().runOnUiThread(new Runnable...

It's because:

1) the implicit this in your call to runOnUiThread is referring to AsyncTask, not your fragment.

2) Fragment doesn't have runOnUiThread.

However, Activity does.

Note that Activity just executes the Runnable if you're already on the main thread, otherwise it uses a Handler. You can implement a Handler in your fragment if you don't want to worry about the context of this, it's actually very easy:

// A class instance
private Handler mHandler = new Handler(Looper.getMainLooper());

// anywhere else in your code
mHandler.post(<your runnable>);
// ^ this will always be run on the next run loop on the main thread.

EDIT: @rciovati is right, you are in onPostExecute, that's already on the main thread.

Extract public/private key from PKCS12 file for later use in SSH-PK-Authentication

Update: I noticed that my answer was just a poor duplicate of a well explained question on https://unix.stackexchange.com/... by BryKKan

Here is an extract from it:

openssl pkcs12 -in <filename.pfx> -nocerts -nodes | sed -ne '/-BEGIN PRIVATE KEY-/,/-END PRIVATE KEY-/p' > <clientcert.key>

openssl pkcs12 -in <filename.pfx> -clcerts -nokeys | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > <clientcert.cer>

openssl pkcs12 -in <filename.pfx> -cacerts -nokeys -chain | sed -ne '/-BEGIN CERTIFICATE-/,/-END CERTIFICATE-/p' > <cacerts.cer>

How to add double quotes to a string that is inside a variable?

Using string interpolation with working example:

var title = "Title between quotes";
var string1 = $@"<div>""{title}""</div>";  //Note the order of the $@
Console.WriteLine (string1);

Output

<div>"Title between quotes"</div>

Text on image mouseover?

For people coming from the future, you can now do this purely in CSS.

_x000D_
_x000D_
.tooltip {
  position: relative;
  display: inline-block;
  border-bottom: 1px dotted black; 
  margin: 5rem;
}

/* Tooltip text */
.tooltip .tooltiptext {
  visibility: hidden;
  background-color: black;
  color: #fff;
  text-align: center;
  padding: 5px 0;
  border-radius: 6px;

  width: 120px;
  bottom: 100%;
  left: 50%;
  margin-left: -60px;

  position: absolute;
  z-index: 1;
}

/* Show the tooltip text when you mouse over the tooltip container */
.tooltip:hover .tooltiptext {
  visibility: visible;
}
_x000D_
<div class="tooltip">Hover over me
  <span class="tooltiptext">Tooltip text</span>
</div>
_x000D_
_x000D_
_x000D_

How to loop through an associative array and get the key?

If you use array_keys(), PHP will give you an array filled with just the keys:

$keys = array_keys($arr);
foreach($keys as $key) {
    echo($key);
}

Alternatively, you can do this:

foreach($arr as $key => $value) {
    echo($key);
}

How create table only using <div> tag and Css

This is an old thread, but I thought I should post my solution. I faced the same problem recently and the way I solved it is by following a three-step approach as outlined below which is very simple without any complex CSS.

(NOTE : Of course, for modern browsers, using the values of table or table-row or table-cell for display CSS attribute would solve the problem. But the approach I used will work equally well in modern and older browsers since it does not use these values for display CSS attribute.)

3-STEP SIMPLE APPROACH

For table with divs only so you get cells and rows just like in a table element use the following approach.

  1. Replace table element with a block div (use a .table class)
  2. Replace each tr or th element with a block div (use a .row class)
  3. Replace each td element with an inline block div (use a .cell class)

_x000D_
_x000D_
.table {display:block; }_x000D_
.row { display:block;}_x000D_
.cell {display:inline-block;}
_x000D_
    <h2>Table below using table element</h2>_x000D_
    <table cellspacing="0" >_x000D_
       <tr>_x000D_
          <td>Mike</td>_x000D_
          <td>36 years</td>_x000D_
          <td>Architect</td>_x000D_
       </tr>_x000D_
       <tr>_x000D_
          <td>Sunil</td>_x000D_
          <td>45 years</td>_x000D_
          <td>Vice President aas</td>_x000D_
       </tr>_x000D_
       <tr>_x000D_
          <td>Jason</td>_x000D_
          <td>27 years</td>_x000D_
          <td>Junior Developer</td>_x000D_
       </tr>_x000D_
    </table>_x000D_
    <h2>Table below is using Divs only</h2>_x000D_
    <div class="table">_x000D_
       <div class="row">_x000D_
          <div class="cell">_x000D_
             Mike_x000D_
          </div>_x000D_
          <div class="cell">_x000D_
             36 years_x000D_
          </div>_x000D_
          <div class="cell">_x000D_
             Architect_x000D_
          </div>_x000D_
       </div>_x000D_
       <div class="row">_x000D_
          <div class="cell">_x000D_
             Sunil_x000D_
          </div>_x000D_
          <div class="cell">_x000D_
             45 years_x000D_
          </div>_x000D_
          <div class="cell">_x000D_
             Vice President_x000D_
          </div>_x000D_
       </div>_x000D_
       <div class="row">_x000D_
          <div class="cell">_x000D_
             Jason_x000D_
          </div>_x000D_
          <div class="cell">_x000D_
             27 years_x000D_
          </div>_x000D_
          <div class="cell">_x000D_
             Junior Developer_x000D_
          </div>_x000D_
       </div>_x000D_
    </div>
_x000D_
_x000D_
_x000D_

UPDATE 1

To get around the effect of same width not being maintained across all cells of a column as mentioned by thatslch in a comment, one could adopt either of the two approaches below.

  • Specify a width for cell class

    cell {display:inline-block; width:340px;}

  • Use CSS of modern browsers as below.

    .table {display:table; } .row { display:table-row;} .cell {display:table-cell;}

jQuery click event not working after adding class

.live() is deprecated.When you want to use for delegated elements then use .on() wiht the following syntax

$(document).on('click', "a.tabclick", function() {

This syntax will work for delegated events

.on()

how to create and call scalar function in sql server 2008

Or you can simply use PRINT command instead of SELECT command. Try this,

PRINT dbo.fn_HomePageSlider(9, 3025)

Multiple FROMs - what it means

As of May 2017, multiple FROMs can be used in a single Dockerfile.
See "Builder pattern vs. Multi-stage builds in Docker" (by Alex Ellis) and PR 31257 by Tõnis Tiigi.

The general syntax involves adding FROM additional times within your Dockerfile - whichever is the last FROM statement is the final base image. To copy artifacts and outputs from intermediate images use COPY --from=<base_image_number>.

FROM golang:1.7.3 as builder
WORKDIR /go/src/github.com/alexellis/href-counter/
RUN go get -d -v golang.org/x/net/html  
COPY app.go    .
RUN CGO_ENABLED=0 GOOS=linux go build -a -installsuffix cgo -o app .

FROM alpine:latest  
RUN apk --no-cache add ca-certificates
WORKDIR /root/
COPY --from=builder /go/src/github.com/alexellis/href-counter/app    .
CMD ["./app"]  

The result would be two images, one for building, one with just the resulting app (much, much smaller)

REPOSITORY          TAG                 IMAGE ID            CREATED             SIZE

multi               latest              bcbbf69a9b59        6 minutes ago       10.3MB  
golang              1.7.3               ef15416724f6        4 months ago        672MB  

what is a base image?

A set of files, plus EXPOSE'd ports, ENTRYPOINT and CMD.
You can add files and build a new image based on that base image, with a new Dockerfile starting with a FROM directive: the image mentioned after FROM is "the base image" for your new image.

does it mean that if I declare neo4j/neo4j in a FROM directive, that when my image is run the neo database will automatically run and be available within the container on port 7474?

Only if you don't overwrite CMD and ENTRYPOINT.
But the image in itself is enough: you would use a FROM neo4j/neo4j if you had to add files related to neo4j for your particular usage of neo4j.

Most efficient way to remove special characters from string

public static string RemoveSpecialCharacters(string str)
{
    char[] buffer = new char[str.Length];
    int idx = 0;

    foreach (char c in str)
    {
        if ((c >= '0' && c <= '9') || (c >= 'A' && c <= 'Z')
            || (c >= 'a' && c <= 'z') || (c == '.') || (c == '_'))
        {
            buffer[idx] = c;
            idx++;
        }
    }

    return new string(buffer, 0, idx);
}

In HTML5, should the main navigation be inside or outside the <header> element?

To expand on what @JoshuaMaddox said, in the MDN Learning Area, under the "Introduction to HTML" section, the Document and website structure sub-section says (bold/emphasis is by me):

Header

Usually a big strip across the top with a big heading and/or logo. This is where the main common information about a website usually stays from one webpage to another.

Navigation bar

Links to the site's main sections; usually represented by menu buttons, links, or tabs. Like the header, this content usually remains consistent from one webpage to another — having an inconsistent navigation on your website will just lead to confused, frustrated users. Many web designers consider the navigation bar to be part of the header rather than a individual component, but that's not a requirement; in fact some also argue that having the two separate is better for accessibility, as screen readers can read the two features better if they are separate.

Free Online Team Foundation Server

You can use Visual Studio Team Services for free. Also you can import a TFS repo to this cloud space.

Copy/duplicate database without using mysqldump

If you are using Linux, you can use this bash script: (it perhaps needs some additional code cleaning but it works ... and it's much faster then mysqldump|mysql)

#!/bin/bash

DBUSER=user
DBPASSWORD=pwd
DBSNAME=sourceDb
DBNAME=destinationDb
DBSERVER=db.example.com

fCreateTable=""
fInsertData=""
echo "Copying database ... (may take a while ...)"
DBCONN="-h ${DBSERVER} -u ${DBUSER} --password=${DBPASSWORD}"
echo "DROP DATABASE IF EXISTS ${DBNAME}" | mysql ${DBCONN}
echo "CREATE DATABASE ${DBNAME}" | mysql ${DBCONN}
for TABLE in `echo "SHOW TABLES" | mysql $DBCONN $DBSNAME | tail -n +2`; do
        createTable=`echo "SHOW CREATE TABLE ${TABLE}"|mysql -B -r $DBCONN $DBSNAME|tail -n +2|cut -f 2-`
        fCreateTable="${fCreateTable} ; ${createTable}"
        insertData="INSERT INTO ${DBNAME}.${TABLE} SELECT * FROM ${DBSNAME}.${TABLE}"
        fInsertData="${fInsertData} ; ${insertData}"
done;
echo "$fCreateTable ; $fInsertData" | mysql $DBCONN $DBNAME

How to decode jwt token in javascript without using a library?

You can use jwt-decode, so then you could write:

import jwt_decode from 'jwt-decode';

var token = 'eyJ0eXAiO.../// jwt token';

var decoded = jwt_decode(token);
console.log(decoded);
/*{exp: 10012016 name: john doe, scope:['admin']}*/

What is the 'dynamic' type in C# 4.0 used for?

An example of use :

You consume many classes that have a commun property 'CreationDate' :

public class Contact
{
    // some properties

    public DateTime CreationDate { get; set; }        
}

public class Company
{
    // some properties

    public DateTime CreationDate { get; set; }

}

public class Opportunity
{
    // some properties

    public DateTime CreationDate { get; set; }

}

If you write a commun method that retrieves the value of the 'CreationDate' Property, you'd have to use reflection:

    static DateTime RetrieveValueOfCreationDate(Object item)
    {
        return (DateTime)item.GetType().GetProperty("CreationDate").GetValue(item);
    }

With the 'dynamic' concept, your code is much more elegant :

    static DateTime RetrieveValueOfCreationDate(dynamic item)
    {
        return item.CreationDate;
    }

Is it possible to insert multiple rows at a time in an SQLite database?

in mysql lite you cannot insert multiple values, but you can save time by opening connection only one time and then doing all insertions and then closing connection. It saves a lot of time

html table cell width for different rows

As far as i know that is impossible and that makes sense since what you are trying to do is against the idea of tabular data presentation. You could however put the data in multiple tables and remove any padding and margins in between them to achieve the same result, at least visibly. Something along the lines of:

_x000D_
_x000D_
<html>_x000D_
_x000D_
<head>_x000D_
  <style type="text/css">_x000D_
    .mytable {_x000D_
      border-collapse: collapse;_x000D_
      width: 100%;_x000D_
      background-color: white;_x000D_
    }_x000D_
    .mytable-head {_x000D_
      border: 1px solid black;_x000D_
      margin-bottom: 0;_x000D_
      padding-bottom: 0;_x000D_
    }_x000D_
    .mytable-head td {_x000D_
      border: 1px solid black;_x000D_
    }_x000D_
    .mytable-body {_x000D_
      border: 1px solid black;_x000D_
      border-top: 0;_x000D_
      margin-top: 0;_x000D_
      padding-top: 0;_x000D_
      margin-bottom: 0;_x000D_
      padding-bottom: 0;_x000D_
    }_x000D_
    .mytable-body td {_x000D_
      border: 1px solid black;_x000D_
      border-top: 0;_x000D_
    }_x000D_
    .mytable-footer {_x000D_
      border: 1px solid black;_x000D_
      border-top: 0;_x000D_
      margin-top: 0;_x000D_
      padding-top: 0;_x000D_
    }_x000D_
    .mytable-footer td {_x000D_
      border: 1px solid black;_x000D_
      border-top: 0;_x000D_
    }_x000D_
  </style>_x000D_
</head>_x000D_
_x000D_
<body>_x000D_
  <table class="mytable mytable-head">_x000D_
    <tr>_x000D_
      <td width="25%">25</td>_x000D_
      <td width="50%">50</td>_x000D_
      <td width="25%">25</td>_x000D_
    </tr>_x000D_
  </table>_x000D_
  <table class="mytable mytable-body">_x000D_
    <tr>_x000D_
      <td width="50%">50</td>_x000D_
      <td width="30%">30</td>_x000D_
      <td width="20%">20</td>_x000D_
    </tr>_x000D_
  </table>_x000D_
  <table class="mytable mytable-body">_x000D_
    <tr>_x000D_
      <td width="16%">16</td>_x000D_
      <td width="68%">68</td>_x000D_
      <td width="16%">16</td>_x000D_
    </tr>_x000D_
  </table>_x000D_
  <table class="mytable mytable-footer">_x000D_
    <tr>_x000D_
      <td width="20%">20</td>_x000D_
      <td width="30%">30</td>_x000D_
      <td width="50%">50</td>_x000D_
    </tr>_x000D_
  </table>_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

JSFIDDLE

I don't know your requirements but i'm sure there's a more elegant solution.

How do I use regular expressions in bash scripts?

It was changed between 3.1 and 3.2:

This is a terse description of the new features added to bash-3.2 since the release of bash-3.1.

Quoting the string argument to the [[ command's =~ operator now forces string matching, as with the other pattern-matching operators.

So use it without the quotes thus:

i="test"
if [[ $i =~ 200[78] ]] ; then
    echo "OK"
else
    echo "not OK"
fi

How to get height of entire document with JavaScript?

Document sizes are a browser compatibility nightmare because, although all browsers expose clientHeight and scrollHeight properties, they don't all agree how the values are calculated.

There used to be a complex best-practice formula around for how you tested for correct height/width. This involved using document.documentElement properties if available or falling back on document properties and so on.

The simplest way to get correct height is to get all height values found on document, or documentElement, and use the highest one. This is basically what jQuery does:

var body = document.body,
    html = document.documentElement;

var height = Math.max( body.scrollHeight, body.offsetHeight, 
                       html.clientHeight, html.scrollHeight, html.offsetHeight );

A quick test with Firebug + jQuery bookmarklet returns the correct height for both cited pages, and so does the code example.

Note that testing the height of the document before the document is ready will always result in a 0. Also, if you load more stuff in, or the user resizes the window, you may need to re-test. Use onload or a document ready event if you need this at load time, otherwise just test whenever you need the number.

insert datetime value in sql database with c#

using (SqlConnection conn = new SqlConnection())
using (SqlCommand cmd = conn.CreateCommand())
{
    cmd.CommandText = "INSERT INTO <table> (<date_column>) VALUES ('2010-01-01 12:00')";
    cmd.ExecuteNonQuery();
}

It's been awhile since I wrote this stuff, so this may not be perfect. but the general idea is there.

WARNING: this is unsanitized. You should use parameters to avoid injection attacks.

EDIT: Since Jon insists.

Is there a way to retrieve the view definition from a SQL Server using plain ADO?

This example:Views Collection, CommandText Property Example (VB) Shows how to use ADOX to maintain VIEWS by changing COMMAND related to VIEW. But instead using it like this:

 Set cmd = cat.Views("AllCustomers").Command  

' Update the CommandText of the command.  
cmd.CommandText = _  
"Select CustomerId, CompanyName, ContactName From Customers"  

just try to use this way:

Set CommandText = cat.Views("AllCustomers").Command.CommandText

Bootstrap datetimepicker is not a function

The problem is that you have not included bootstrap.min.css. Also, the sequence of imports could be causing issue. Please try rearranging your resources as following:

<link rel="stylesheet" href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/css/bootstrap.min.css" />
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/css/bootstrap-datetimepicker.min.css" />

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script>
<script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.5/js/bootstrap.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.10.6/moment.min.js"></script>                       
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-datetimepicker/4.17.37/js/bootstrap-datetimepicker.min.js"></script>

DEMO

Bootstrap $('#myModal').modal('show') is not working

<script src="https://ajax.googleapis.com/ajax/libs/jquery/1.11.3/jquery.min.js"></script><script type="text/javascript" src="//code.jquery.com/jquery-1.11.3.min.js"></script>

the first googleapis script is not working now a days use this second scripe given by jquery

What are C++ functors and their uses?

For the newbies like me among us: after a little research I figured out what the code jalf posted did.

A functor is a class or struct object which can be "called" like a function. This is made possible by overloading the () operator. The () operator (not sure what its called) can take any number of arguments. Other operators only take two i.e. the + operator can only take two values (one on each side of the operator) and return whatever value you have overloaded it for. You can fit any number of arguments inside a () operator which is what gives it its flexibility.

To create a functor first you create your class. Then you create a constructor to the class with a parameter of your choice of type and name. This is followed in the same statement by an initializer list (which uses a single colon operator, something I was also new to) which constructs the class member objects with the previously declared parameter to the constructor. Then the () operator is overloaded. Finally you declare the private objects of the class or struct you have created.

My code (I found jalf's variable names confusing)

class myFunctor
{ 
    public:
        /* myFunctor is the constructor. parameterVar is the parameter passed to
           the constructor. : is the initializer list operator. myObject is the
           private member object of the myFunctor class. parameterVar is passed
           to the () operator which takes it and adds it to myObject in the
           overloaded () operator function. */
        myFunctor (int parameterVar) : myObject( parameterVar ) {}

        /* the "operator" word is a keyword which indicates this function is an 
           overloaded operator function. The () following this just tells the
           compiler that () is the operator being overloaded. Following that is
           the parameter for the overloaded operator. This parameter is actually
           the argument "parameterVar" passed by the constructor we just wrote.
           The last part of this statement is the overloaded operators body
           which adds the parameter passed to the member object. */
        int operator() (int myArgument) { return myObject + myArgument; }

    private: 
        int myObject; //Our private member object.
}; 

If any of this is inaccurate or just plain wrong feel free to correct me!

typecast string to integer - Postgres

The only way I succeed to not having an error because of NULL, or special characters or empty string is by doing this:

SELECT REGEXP_REPLACE(COALESCE(<column>::character varying, '0'), '[^0-9]*' ,'0')::integer FROM table

Android: Getting a file URI from a content URI?

Try this....

get File from a content uri

fun fileFromContentUri(context: Context, contentUri: Uri): File {
    // Preparing Temp file name
    val fileExtension = getFileExtension(context, contentUri)
    val fileName = "temp_file" + if (fileExtension != null) ".$fileExtension" else ""

    // Creating Temp file
    val tempFile = File(context.cacheDir, fileName)
    tempFile.createNewFile()

    try {
        val oStream = FileOutputStream(tempFile)
        val inputStream = context.contentResolver.openInputStream(contentUri)

        inputStream?.let {
            copy(inputStream, oStream)
        }

        oStream.flush()
    } catch (e: Exception) {
        e.printStackTrace()
    }

    return tempFile
}

private fun getFileExtension(context: Context, uri: Uri): String? {
    val fileType: String? = context.contentResolver.getType(uri)
    return MimeTypeMap.getSingleton().getExtensionFromMimeType(fileType)
}

@Throws(IOException::class)
private fun copy(source: InputStream, target: OutputStream) {
    val buf = ByteArray(8192)
    var length: Int
    while (source.read(buf).also { length = it } > 0) {
        target.write(buf, 0, length)
    }
}

Can I open a dropdownlist using jQuery

As has been stated, you can't programmatically open a <select> using JavaScript.

However, you could write your own <select> managing the entire look and feel yourself. Something like what you see for the autocomplete search terms on Google or Yahoo! or the Search for Location box at The Weather Network.

I found one for jQuery here. I have no idea whether it would meet your needs, but even if it doesn't completely meet your needs, it should be possible to modify it so it would open as the result of some other action or event. This one actually looks more promising.

How to test if a string contains one of the substrings in a list, in pandas?

You can use str.contains alone with a regex pattern using OR (|):

s[s.str.contains('og|at')]

Or you could add the series to a dataframe then use str.contains:

df = pd.DataFrame(s)
df[s.str.contains('og|at')] 

Output:

0 cat
1 hat
2 dog
3 fog 

How do you dismiss the keyboard when editing a UITextField

Anyone looking for Swift 3

1) Make sure your UITextField's Delegate is wired to your ViewController in the Storyboard

2) Implement UITextFieldDelegate in your ViewController.Swift file (e.g class ViewController: UIViewController, UITextFieldDelegate { )

3) Use the delegate method below

func textFieldShouldReturn(textField: UITextField) -> Bool { 
   textField.resignFirstResponder()  
return false }