Programs & Examples On #Der

Distinguished Encoding Rules (DER) certificate encoding is a method of turning ASN.1 attributes and values into a machine-friendly format.

How to get .pem file from .key and .crt files?

Your keys may already be in PEM format, but just named with .crt or .key.

If the file's content begins with -----BEGIN and you can read it in a text editor:

The file uses base64, which is readable in ASCII, not binary format. The certificate is already in PEM format. Just change the extension to .pem.

If the file is in binary:

For the server.crt, you would use

openssl x509 -inform DER -outform PEM -in server.crt -out server.crt.pem

For server.key, use openssl rsa in place of openssl x509.

The server.key is likely your private key, and the .crt file is the returned, signed, x509 certificate.

If this is for a Web server and you cannot specify loading a separate private and public key:

You may need to concatenate the two files. For this use:

cat server.crt server.key > server.includesprivatekey.pem

I would recommend naming files with "includesprivatekey" to help you manage the permissions you keep with this file.

How to convert .crt to .pem

I found the OpenSSL answer given above didn't work for me, but the following did, working with a CRT file sourced from windows.

openssl x509 -inform DER -in yourdownloaded.crt -out outcert.pem -text

Append integer to beginning of list in Python

Another way of doing the same,

list[0:0] = [a]

How to get the current URL within a Django template?

In Django 3, you want to use url template tag:

{% url 'name-of-your-user-profile-url' possible_context_variable_parameter %}

For an example, see the documentation

Selenium Finding elements by class name in python

Use nth-child, for example: http://www.w3schools.com/cssref/sel_nth-child.asp

driver.find_element(By.CSS_SELECTOR, 'p.content:nth-child(1)')

or http://www.w3schools.com/cssref/sel_firstchild.asp

driver.find_element(By.CSS_SELECTOR, 'p.content:first-child')

How to change resolution (DPI) of an image?

It's simply a matter of scaling the image width and height up by the correct ratio. Not all images formats support a DPI metatag, and when they do, all they're telling your graphics software to do is divide the image by the ratio supplied.

For example, if you export a 300dpi image from Photoshop to a JPEG, the image will appear to be very large when viewed in your picture viewing software. This is because the DPI information isn't supported in JPEG and is discarded when saved. This means your picture viewer doesn't know what ratio to divide the image by and instead displays the image at at 1:1 ratio.

To get the ratio you need to scale the image by, see the code below. Just remember, this will stretch the image, just like it would in Photoshop. You're essentially quadrupling the size of the image so it's going to stretch and may produce artifacts.

Pseudo code

ratio = 300.0 / 72.0   // 4.167
image.width * ratio
image.height * ratio

ElasticSearch, Sphinx, Lucene, Solr, Xapian. Which fits for which usage?

Try indextank.

As the case of elastic search, it was conceived to be much easier to use than lucene/solr. It also includes very flexible scoring system that can be tweaked without reindexing.

Prevent wrapping of span or div

As mentioned you can use:

overflow: scroll;

If you only want the scroll bar to appear when necessary, you can use the "auto" option:

overflow: auto;

I don't think you should be using the "float" property with "overflow", but I'd have to try out your example first.

Google Chrome display JSON AJAX response as tree and not as a plain text

I've found the answer:

You MUST encode your json like this: {"c":21001,"m":"p"} but not {c:21001,m:"p"} or {'c':21001,'m':'p'}

Thus, the key of a dict must be wrapped in double quotes:", then chrome will preview it as json rather than plain text.

What is the difference between public, private, and protected?

You use:

  • public scope to make that property/method available from anywhere, other classes and instances of the object.

  • private scope when you want your property/method to be visible in its own class only.

  • protected scope when you want to make your property/method visible in all classes that extend current class including the parent class.

If you don't use any visibility modifier, the property / method will be public.

More: (For comprehensive information)

Changing color of Twitter bootstrap Nav-Pills

Step 1: Define a class named applycolor which can be used to apply the color you choose.

Step 2: Define what actions happens to it when it hovers. If your form background is white, then you must make sure that on hover the tab does not turn white. To achieve this use the !important clause to force this feature on hover property. We are doing this to override Bootstrap's default behavior.

Step 3: Apply the class to the Tabs which you are targetting.

CSS section:

<style>
    .nav-pills > li.active > a, .nav-pills > li.active > a:hover, .nav-pills > li.active > a:focus {
        color: #fff;
        background-color: #337ab7 !important;
    }

    .nav > li > a:hover, .nav > li > a:focus {
        text-decoration: none;
        background-color: none !important;
    }

    .applycolor {
        background-color: #efefef;
        text-decoration: none;
        color: #fff;
    }

    .applycolor:hover {
        background-color: #337ab7;
        text-decoration: none;
        color: #fff;
    }
</style>

Tab Section :

<section class="form-toolbar row">
    <div class="form-title col-sm-12" id="tabs">
        <ul class="nav nav-pills nav-justified">
            <li class="applycolor"><a data-toggle="pill" href="#instance" style="font-size: 1.8rem; font-weight: 800;">My Apps</a></li>
            <li class="active applycolor"><a data-toggle="pill" href="#application" style="font-size: 1.8rem; font-weight: 800;">Apps Collection</a></li>
        </ul>
    </div>
</section>

Dynamically generating a QR code with PHP

The easiest way to generate QR codes with PHP is the phpqrcode library.

Latex Remove Spaces Between Items in List

It's easier with the enumitem package:

\documentclass{article}
\usepackage{enumitem}
\begin{document}
Less space:
\begin{itemize}[noitemsep]
  \item foo
  \item bar
  \item baz
\end{itemize}

Even more compact:
\begin{itemize}[noitemsep,nolistsep]
  \item foo
  \item bar
  \item baz
\end{itemize}
\end{document}

example

The enumitem package provides a lot of features to customize bullets, numbering and lengths.

The paralist package provides very compact lists: compactitem, compactenum and even lists within paragraphs like inparaenum and inparaitem.

jQuery Keypress Arrow Keys

Please refer the link from JQuery

http://api.jquery.com/keypress/

It says

The keypress event is sent to an element when the browser registers keyboard input. This is similar to the keydown event, except that modifier and non-printing keys such as Shift, Esc, and delete trigger keydown events but not keypress events. Other differences between the two events may arise depending on platform and browser.

That means you can not use keypress in case of arrows.

What is referencedColumnName used for in JPA?

Quoting API on referencedColumnName:

The name of the column referenced by this foreign key column.

Default (only applies if single join column is being used): The same name as the primary key column of the referenced table.

Q/A

Where this would be used?

When there is a composite PK in referenced table, then you need to specify column name you are referencing.

How do I use floating-point division in bash?

You can't. bash only does integers; you must delegate to a tool such as bc.

Get data from file input in JQuery

Html:

<input type="file" name="input-file" id="input-file">

jQuery:

var fileToUpload = $('#input-file').prop('files')[0];

We want to get first element only, because prop('files') returns array.

How to get values from selected row in DataGrid for Windows Form Application?

Description

Assuming i understand your question.

You can get the selected row using the DataGridView.SelectedRows Collection. If your DataGridView allows only one selected, have a look at my sample.

DataGridView.SelectedRows Gets the collection of rows selected by the user.

Sample

if (dataGridView1.SelectedRows.Count != 0)
{
    DataGridViewRow row = this.dataGridView1.SelectedRows[0];
    row.Cells["ColumnName"].Value
}

More Information

Correct way to handle conditional styling in React

instead of this:

style={{
  textDecoration: completed ? 'line-through' : 'none'
}}

you could try the following using short circuiting:

style={{
  textDecoration: completed && 'line-through'
}}

https://codeburst.io/javascript-short-circuit-conditionals-bbc13ac3e9eb

key bit of information from the link:

Short circuiting means that in JavaScript when we are evaluating an AND expression (&&), if the first operand is false, JavaScript will short-circuit and not even look at the second operand.

It's worth noting that this would return false if the first operand is false, so might have to consider how this would affect your style.

The other solutions might be more best practice, but thought it would be worth sharing.

Angular CLI - Please add a @NgModule annotation when using latest

In my case, I created a new ChildComponent in Parentcomponent whereas both in the same module but Parent is registered in a shared module so I created ChildComponent using CLI which registered Child in the current module but my parent was registered in the shared module.

So register the ChildComponent in Shared Module manually.

Avoiding "resource is out of sync with the filesystem"

You can enable this in Window - Preferences - General - Workspace - Refresh Automatically (called Refresh using native hooks or polling in newer builds)

Eclipse Preferences "Refresh using native hooks or polling" - Screenshot

The only reason I can think why this isn't enabled by default is performance related.

For example, refreshing source folders automatically might trigger a build of the workspace. Perhaps some people want more control over this.

There is also an article on the Eclipse site regarding auto refresh.

Basically, there is no external trigger that notifies Eclipse of files changed outside the workspace. Rather a background thread is used by Eclipse to monitor file changes that can possibly lead to performance issues with large workspaces.

Getting hold of the outer class object from the inner class object

You could (but you shouldn't) use reflection for the job:

import java.lang.reflect.Field;

public class Outer {
    public class Inner {
    }

    public static void main(String[] args) throws Exception {

        // Create the inner instance
        Inner inner = new Outer().new Inner();

        // Get the implicit reference from the inner to the outer instance
        // ... make it accessible, as it has default visibility
        Field field = Inner.class.getDeclaredField("this$0");
        field.setAccessible(true);

        // Dereference and cast it
        Outer outer = (Outer) field.get(inner);
        System.out.println(outer);
    }
}

Of course, the name of the implicit reference is utterly unreliable, so as I said, you shouldn't :-)

OpenCV & Python - Image too big to display

The other answers perform a fixed (width, height) resize. If you wanted to resize to a specific size while maintaining aspect ratio, use this

def ResizeWithAspectRatio(image, width=None, height=None, inter=cv2.INTER_AREA):
    dim = None
    (h, w) = image.shape[:2]

    if width is None and height is None:
        return image
    if width is None:
        r = height / float(h)
        dim = (int(w * r), height)
    else:
        r = width / float(w)
        dim = (width, int(h * r))

    return cv2.resize(image, dim, interpolation=inter)

Example

image = cv2.imread('img.png')
resize = ResizeWithAspectRatio(image, width=1280) # Resize by width OR
# resize = ResizeWithAspectRatio(image, height=1280) # Resize by height 

cv2.imshow('resize', resize)
cv2.waitKey()

Create a directory if it does not exist and then create the files in that directory as well

code:

// Create Directory if not exist then Copy a file.


public static void copyFile_Directory(String origin, String destDir, String destination) throws IOException {

    Path FROM = Paths.get(origin);
    Path TO = Paths.get(destination);
    File directory = new File(String.valueOf(destDir));

    if (!directory.exists()) {
        directory.mkdir();
    }
        //overwrite the destination file if it exists, and copy
        // the file attributes, including the rwx permissions
     CopyOption[] options = new CopyOption[]{
                StandardCopyOption.REPLACE_EXISTING,
                StandardCopyOption.COPY_ATTRIBUTES

        };
        Files.copy(FROM, TO, options);


}

PostgreSQL DISTINCT ON with different ORDER BY

You can also done this by using group by clause

   SELECT purchases.address_id, purchases.* FROM "purchases"
    WHERE "purchases"."product_id" = 1 GROUP BY address_id,
purchases.purchased_at ORDER purchases.purchased_at DESC

How to use the "required" attribute with a "radio" input field

TL;DR: Set the required attribute for at least one input of the radio group.


Setting required for all inputs is more clear, but not necessary (unless dynamically generating radio-buttons).

To group radio buttons they must all have the same name value. This allows only one to be selected at a time and applies required to the whole group.

_x000D_
_x000D_
<form>_x000D_
  Select Gender:<br>_x000D_
_x000D_
  <label>_x000D_
    <input type="radio" name="gender" value="male" required>_x000D_
    Male_x000D_
  </label><br>_x000D_
_x000D_
  <label>_x000D_
    <input type="radio" name="gender" value="female">_x000D_
    Female_x000D_
  </label><br>_x000D_
_x000D_
  <label>_x000D_
    <input type="radio" name="gender" value="other">_x000D_
    Other_x000D_
  </label><br>_x000D_
_x000D_
  <input type="submit">_x000D_
</form>
_x000D_
_x000D_
_x000D_

Also take note of:

To avoid confusion as to whether a radio button group is required or not, authors are encouraged to specify the attribute on all the radio buttons in a group. Indeed, in general, authors are encouraged to avoid having radio button groups that do not have any initially checked controls in the first place, as this is a state that the user cannot return to, and is therefore generally considered a poor user interface.

Source

Execute CMD command from code

How about you creat a batch file with the command you want, and call it with Process.Start

dir.bat content:

dir

then call:

Process.Start("dir.bat");

Will call the bat file and execute the dir

Git - fatal: Unable to create '/path/my_project/.git/index.lock': File exists

I was having the same problem. I tried

rm -f ./.git/index.lock 

and the console gave me an error message. Then, I tried

rm --force ./.git/index.lock

and that worked.

Good Luck! This works super

How to change the port number for Asp.Net core app?

If you want to run on a specific port 60535 while developing locally but want to run app on port 80 in stage/prod environment servers, this does it.

Add to environmentVariables section in launchSettings.json

"ASPNETCORE_DEVELOPER_OVERRIDES": "Developer-Overrides",

and then modify Program.cs to

public static IHostBuilder CreateHostBuilder(string[] args) =>
            Host.CreateDefaultBuilder(args)
                .ConfigureWebHostDefaults(webBuilder =>
                {
                    webBuilder.UseKestrel(options =>
                    {
                        var devOverride = Environment.GetEnvironmentVariable("ASPNETCORE_DEVELOPER_OVERRIDES");
                        if (!string.IsNullOrWhiteSpace(devOverride))
                        {
                            options.ListenLocalhost(60535);
                        }
                        else
                        {
                            options.ListenAnyIP(80);
                        }
                    })
                    .UseStartup<Startup>()
                    .UseNLog();                   
                });

AND/OR in Python?

For the updated question, you can replace what you want with something like:

someList = filter(lambda x: x not in ("a", "á", "à", "ã", "â"), someList)

filter evaluates every element of the list by passing it to the lambda provided. In this lambda we check if the element is not one of the characters provided, because these should stay in the list.

Alternatively, if the items in someList should be unique, you can make someList a set and do something like this:

someList = list(set(someList)-set(("a", "á", "à", "ã", "â")))

This essentially takes the difference between the sets, which does what you want, but also makes sure every element occurs only once, which is different from a list. Note you could store someList as a set from the beginning in this case, it will optimize things a bit.

Axios Delete request with body and headers?

Actually, axios.delete supports a request body.
It accepts two parameters: a URL and an optional config. That is...

axios.delete(url: string, config?: AxiosRequestConfig | undefined)

You can do the following to set the response body for the delete request:

let config = { 
    headers: {
        Authorization: authToken
    },
    data: { //! Take note of the `data` keyword. This is the request body.
        key: value,
        ... //! more `key: value` pairs as desired.
    } 
}

axios.delete(url, config)

I hope this helps someone!

Jenkins Pipeline Wipe Out Workspace

In my case, I want to clear out old files at the beginning of the build, but this is problematic since the source code has been checked out.

My solution is to ask git to clean out any files (from the last build) that it doesn't know about:

    sh "git clean -x -f"

That way I can start the build out clean, and if it fails, the workspace isn't cleaned out and therefore easily debuggable.

How can I generate Javadoc comments in Eclipse?

At a place where you want javadoc, type in /**<NEWLINE> and it will create the template.

Turning error reporting off php

Does this work?

display_errors = Off

Also, what version of php are you using?

Link a photo with the cell in excel

There is a much simpler way. Put your picture in a comment box within the description cell. That way you only have one column and when you sort the picture will always stay with the description. Okay... Right click the cell containing the description... Insert comment...right click the outer border... Format comment...colours and lines tab... Colour drop down...Fill effects...Picture tab...select picture...browse for your picture (it might be best to keep all pictures in one folder for ease of placement)...ok... you will probably need to go to the size tab and frig around with the height and width. Done... You now only need to mouse over the red in the top right corner of the cell and the picture will appear...like magic.

This method means that the row height can be kept to a minimum and the pictures can be as big as you like.

What's the best way to break from nested loops in JavaScript?

I'm a little late to the party but the following is a language-agnostic approach which doesn't use GOTO/labels or function wrapping:

for (var x = Set1.length; x > 0; x--)
{
   for (var y = Set2.length; y > 0; y--)
   {
      for (var z = Set3.length; z > 0; z--)
      {
          z = y = -1; // terminates second loop
          // z = y = x = -1; // terminate first loop
      }
   }
}

On the upside it flows naturally which should please the non-GOTO crowd. On the downside, the inner loop needs to complete the current iteration before terminating so it might not be applicable in some scenarios.

Node.js Error: Cannot find module express

Check if you have installed express module. If not, use this command:

npm install express

and if your node_modules directory is in another place, set NODE_PATH envirnment variable:

set NODE_PATH=your\directory\to\node_modules;%NODE_PATH%

Commenting in a Bash script inside a multiline command

This will have some overhead, but technically it does answer your question:

echo abc `#Put your comment here` \
     def `#Another chance for a comment` \
     xyz, etc.

And for pipelines specifically, there is a clean solution with no overhead:

echo abc |        # Normal comment OK here
     tr a-z A-Z | # Another normal comment OK here
     sort |       # The pipelines are automatically continued
     uniq         # Final comment

See Stack Overflow question How to Put Line Comment for a Multi-line Command.

How to get the element clicked (for the whole document)?

You can find the target element in event.target:

$(document).click(function(event) {
    console.log($(event.target).text());
});

References:

Javascript Error Null is not an Object

Put the code so it executes after the elements are defined, either with a DOM ready callback or place the source under the elements in the HTML.

document.getElementById() returns null if the element couldn't be found. Property assignment can only occur on objects. null is not an object (contrary to what typeof says).

How do you find all subclasses of a given class in Java?

This is not possible to do using only the built-in Java Reflections API.

A project exists that does the necessary scanning and indexing of your classpath so you can get access this information...

Reflections

A Java runtime metadata analysis, in the spirit of Scannotations

Reflections scans your classpath, indexes the metadata, allows you to query it on runtime and may save and collect that information for many modules within your project.

Using Reflections you can query your metadata for:

  • get all subtypes of some type
  • get all types annotated with some annotation
  • get all types annotated with some annotation, including annotation parameters matching
  • get all methods annotated with some

(disclaimer: I have not used it, but the project's description seems to be an exact fit for your needs.)

How to read appSettings section in the web.config file?

    using System.Configuration;

    /// <summary>
    /// For read one setting
    /// </summary>
    /// <param name="key">Key correspondent a your setting</param>
    /// <returns>Return the String contains the value to setting</returns>
    public string ReadSetting(string key)
    {
        var appSettings = ConfigurationManager.AppSettings;
        return appSettings[key] ?? string.Empty;
    }

    /// <summary>
    /// Read all settings for output Dictionary<string,string> 
    /// </summary>        
    /// <returns>Return the Dictionary<string,string> contains all settings</returns>
    public Dictionary<string, string> ReadAllSettings()
    {
        var result = new Dictionary<string, string>();
        foreach (var key in ConfigurationManager.AppSettings.AllKeys)
            result.Add(key, ConfigurationManager.AppSettings[key]);
        return result;
    }

Disabling and enabling a html input button

the disable attribute only has one parameter. if you want to reenable it you have to remove the whole thing, not just change the value.

Bash script to check running process

This trick works for me. Hope this could help you. Let's save the followings as checkRunningProcess.sh

#!/bin/bash
ps_out=`ps -ef | grep $1 | grep -v 'grep' | grep -v $0`
result=$(echo $ps_out | grep "$1")
if [[ "$result" != "" ]];then
    echo "Running"
else
    echo "Not Running"
fi

Make the checkRunningProcess.sh executable.And then use it.
Example to use.

20:10 $ checkRunningProcess.sh proxy.py
Running
20:12 $ checkRunningProcess.sh abcdef
Not Running

Windows Scipy Install: No Lapack/Blas Resources Found

The solution to the absence of BLAS/LAPACK libraries for SciPy installations on Windows 7 64-bit is described here:

http://www.scipy.org/scipylib/building/windows.html

Installing Anaconda is much easier, but you still don't get Intel MKL or GPU support without paying for it (they are in the MKL Optimizations and Accelerate add-ons for Anaconda - I'm not sure if they use PLASMA and MAGMA either). With MKL optimization, numpy has outperformed IDL on large matrix computations by 10-fold. MATLAB uses the Intel MKL library internally and supports GPU computing, so one might as well use that for the price if they're a student ($50 for MATLAB + $10 for the Parallel Computing Toolbox). If you get the free trial of Intel Parallel Studio, it comes with the MKL library, as well as C++ and FORTRAN compilers that will come in handy if you want to install BLAS and LAPACK from MKL or ATLAS on Windows:

http://icl.cs.utk.edu/lapack-for-windows/lapack/

Parallel Studio also comes with the Intel MPI library, useful for cluster computing applications and their latest Xeon processsors. While the process of building BLAS and LAPACK with MKL optimization is not trivial, the benefits of doing so for Python and R are quite large, as described in this Intel webinar:

https://software.intel.com/en-us/articles/powered-by-mkl-accelerating-numpy-and-scipy-performance-with-intel-mkl-python

Anaconda and Enthought have built businesses out of making this functionality and a few other things easier to deploy. However, it is freely available to those willing to do a little work (and a little learning).

For those who use R, you can now get MKL optimized BLAS and LAPACK for free with R Open from Revolution Analytics.

EDIT: Anaconda Python now ships with MKL optimization, as well as support for a number of other Intel library optimizations through the Intel Python distribution. However, GPU support for Anaconda in the Accelerate library (formerly known as NumbaPro) is still over $10k USD! The best alternatives for that are probably PyCUDA and scikit-cuda, as copperhead (essentially a free version of Anaconda Accelerate) unfortunately ceased development five years ago. It can be found here if anybody wants to pick up where they left off.

Clear form after submission with jQuery

Better way to reset your form with jQuery is Simply trigger a reset event on your form.

$("#btn1").click(function () {
        $("form").trigger("reset");
    });

OSError [Errno 22] invalid argument when use open() in Python

for folder, subs, files in os.walk(unicode(docs_dir, 'utf-8')):
    for filename in files:
        if not filename.startswith('.'):
            file_path = os.path.join(folder, filename)

Click a button with XPath containing partial id and title in Selenium IDE

Now that you have provided your HTML sample, we're able to see that your XPath is slightly wrong. While it's valid XPath, it's logically wrong.

You've got:

//*[contains(@id, 'ctl00_btnAircraftMapCell')]//*[contains(@title, 'Select Seat')]

Which translates into:

Get me all the elements that have an ID that contains ctl00_btnAircraftMapCell. Out of these elements, get any child elements that have a title that contains Select Seat.

What you actually want is:

//a[contains(@id, 'ctl00_btnAircraftMapCell') and contains(@title, 'Select Seat')]

Which translates into:

Get me all the anchor elements that have both: an id that contains ctl00_btnAircraftMapCell and a title that contains Select Seat.

Mac OS X and multiple Java versions

I find this Java version manager called Jabba recently and the usage is very similar to version managers of other languages like rvm(ruby), nvm(node), pyenv(python), etc. Also it's cross platform so definitely it can be used on Mac.

After installation, it will create a dir in ~/.jabba to put all the Java versions you install. It "Supports installation of Oracle JDK (default) / Server JRE, Zulu OpenJDK (since 0.3.0), IBM SDK, Java Technology Edition (since 0.6.0) and from custom URLs.".

Basic usage is listed on their Github. A quick summary to start:

curl -sL https://github.com/shyiko/jabba/raw/master/install.sh | bash && . ~/.jabba/jabba.sh

# install Oracle JDK
jabba install 1.8 # "jabba use 1.8" will be called automatically  
jabba install 1.7 # "jabba use 1.7" will be called automatically 

# list all installed JDK's
jabba ls

# switch to a different version of JDK
jabba use 1.8

Remove Backslashes from Json Data in JavaScript

You need to deserialize the JSON once before returning it as response. Please refer below code. This works for me:

JavaScriptSerializer jss = new JavaScriptSerializer();
Object finalData = jss.DeserializeObject(str);

Firebase (FCM) how to get token

You can use these 2 methods to get device token with firebase but the second one method is more efficient way..

FirebaseInstallations.getInstance().getToken(false).addOnCompleteListener(new OnCompleteListener<InstallationTokenResult>() {
        @Override
        public void onComplete(@NonNull Task<InstallationTokenResult> task) {
            if(!task.isSuccessful()){
                return;
            }
            // Get new Instance ID token
            DeviceToken = task.getResult().getToken();

        }
    });

Second method : you can also use this one

 FirebaseMessaging.getInstance().getToken().addOnCompleteListener(new OnCompleteListener<String>() {
        @Override
        public void onComplete(@NonNull Task<String> task) {
            DeviceToken= task.getResult();
        }
    });

Javascript - How to extract filename from a file input control

To split the string ({filepath}/{filename}) and get the file name you could use something like this:

str.split(/(\\|\/)/g).pop()

"The pop method removes the last element from an array and returns that value to the caller."
Mozilla Developer Network

Example:

from: "/home/user/file.txt".split(/(\\|\/)/g).pop()

you get: "file.txt"

How to mock void methods with Mockito

Take a look at the Mockito API docs. As the linked document mentions (Point # 12) you can use any of the doThrow(),doAnswer(),doNothing(),doReturn() family of methods from Mockito framework to mock void methods.

For example,

Mockito.doThrow(new Exception()).when(instance).methodName();

or if you want to combine it with follow-up behavior,

Mockito.doThrow(new Exception()).doNothing().when(instance).methodName();

Presuming that you are looking at mocking the setter setState(String s) in the class World below is the code uses doAnswer method to mock the setState.

World mockWorld = mock(World.class); 
doAnswer(new Answer<Void>() {
    public Void answer(InvocationOnMock invocation) {
      Object[] args = invocation.getArguments();
      System.out.println("called with arguments: " + Arrays.toString(args));
      return null;
    }
}).when(mockWorld).setState(anyString());

$(document).on('click', '#id', function() {}) vs $('#id').on('click', function(){})

The first example demonstrates event delegation. The event handler is bound to an element higher up the DOM tree (in this case, the document) and will be executed when an event reaches that element having originated on an element matching the selector.

This is possible because most DOM events bubble up the tree from the point of origin. If you click on the #id element, a click event is generated that will bubble up through all of the ancestor elements (side note: there is actually a phase before this, called the 'capture phase', when the event comes down the tree to the target). You can capture the event on any of those ancestors.

The second example binds the event handler directly to the element. The event will still bubble (unless you prevent that in the handler) but since the handler is bound to the target, you won't see the effects of this process.

By delegating an event handler, you can ensure it is executed for elements that did not exist in the DOM at the time of binding. If your #id element was created after your second example, your handler would never execute. By binding to an element that you know is definitely in the DOM at the time of execution, you ensure that your handler will actually be attached to something and can be executed as appropriate later on.

'profile name is not valid' error when executing the sp_send_dbmail command

You need to grant the user or group rights to use the profile. They need to be added to the msdb database and then you will see them available in the mail wizard when you are maintaining security for mail.

Read up the security here: http://msdn.microsoft.com/en-us/library/ms175887.aspx

See a listing of mail procedures here: http://msdn.microsoft.com/en-us/library/ms177580.aspx

Example script for 'TestUser' to use the profile named 'General Admin Mail'.


USE [msdb]
GO
CREATE USER [TestUser] FOR LOGIN [testuser]
GO
USE [msdb]
GO
EXEC sp_addrolemember N'DatabaseMailUserRole', N'TestUser'
GO

EXECUTE msdb.dbo.sysmail_add_principalprofile_sp
    @profile_name = 'General Admin Mail',
    @principal_name = 'TestUser',
    @is_default = 1 ;

How to set entire application in portrait mode only?

Add android:screenOrientation="portrait" to the activity in the AndroidManifest.xml. For example:

<activity android:name=".SomeActivity"
    android:label="@string/app_name"
    android:screenOrientation="portrait">

Best practices for API versioning?

This is a good and a tricky question. The topic of URI design is at the same time the most prominent part of a REST API and, therefore, a potentially long-term commitment towards the users of that API.

Since evolution of an application and, to a lesser extent, its API is a fact of life and that it's even similar to the evolution of a seemingly complex product like a programming language, the URI design should have less natural constraints and it should be preserved over time. The longer the application's and API's lifespan, the greater the commitment to the users of the application and API.

On the other hand, another fact of life is that it is hard to foresee all the resources and their aspects that would be consumed through the API. Luckily, it is not necessary to design the entire API which will be used until Apocalypse. It is sufficient to correctly define all the resource end-points and the addressing scheme of every resource and resource instance.

Over time you may need to add new resources and new attributes to each particular resource, but the method that API users follow to access a particular resources should not change once a resource addressing scheme becomes public and therefore final.

This method applies to HTTP verb semantics (e.g. PUT should always update/replace) and HTTP status codes that are supported in earlier API versions (they should continue to work so that API clients that have worked without human intervention should be able to continue to work like that).

Furthermore, since embedding of API version into the URI would disrupt the concept of hypermedia as the engine of application state (stated in Roy T. Fieldings PhD dissertation) by having a resource address/URI that would change over time, I would conclude that API versions should not be kept in resource URIs for a long time meaning that resource URIs that API users can depend on should be permalinks.

Sure, it is possible to embed API version in base URI but only for reasonable and restricted uses like debugging a API client that works with the the new API version. Such versioned APIs should be time-limited and available to limited groups of API users (like during closed betas) only. Otherwise, you commit yourself where you shouldn't.

A couple of thoughts regarding maintenance of API versions that have expiration date on them. All programming platforms/languages commonly used to implement web services (Java, .NET, PHP, Perl, Rails, etc.) allow easy binding of web service end-point(s) to a base URI. This way it's easy to gather and keep a collection of files/classes/methods separate across different API versions.

From the API users POV, it's also easier to work with and bind to a particular API version when it's this obvious but only for limited time, i.e. during development.

From the API maintainer's POV, it's easier to maintain different API versions in parallel by using source control systems that predominantly work on files as the smallest unit of (source code) versioning.

However, with API versions clearly visible in URI there's a caveat: one might also object this approach since API history becomes visible/aparent in the URI design and therefore is prone to changes over time which goes against the guidelines of REST. I agree!

The way to go around this reasonable objection, is to implement the latest API version under versionless API base URI. In this case, API client developers can choose to either:

  • develop against the latest one (committing themselves to maintain the application protecting it from eventual API changes that might break their badly designed API client).

  • bind to a specific version of the API (which becomes apparent) but only for a limited time

For example, if API v3.0 is the latest API version, the following two should be aliases (i.e. behave identically to all API requests):

http://shonzilla/api/customers/1234
http://shonzilla/api/v3.0/customers/1234
http://shonzilla/api/v3/customers/1234

In addition, API clients that still try to point to the old API should be informed to use the latest previous API version, if the API version they're using is obsolete or not supported anymore. So accessing any of the obsolete URIs like these:

http://shonzilla/api/v2.2/customers/1234
http://shonzilla/api/v2.0/customers/1234
http://shonzilla/api/v2/customers/1234
http://shonzilla/api/v1.1/customers/1234
http://shonzilla/api/v1/customers/1234

should return any of the 30x HTTP status codes that indicate redirection that are used in conjunction with Location HTTP header that redirects to the appropriate version of resource URI which remain to be this one:

http://shonzilla/api/customers/1234

There are at least two redirection HTTP status codes that are appropriate for API versioning scenarios:

  • 301 Moved permanently indicating that the resource with a requested URI is moved permanently to another URI (which should be a resource instance permalink that does not contain API version info). This status code can be used to indicate an obsolete/unsupported API version, informing API client that a versioned resource URI been replaced by a resource permalink.

  • 302 Found indicating that the requested resource temporarily is located at another location, while requested URI may still supported. This status code may be useful when the version-less URIs are temporarily unavailable and that a request should be repeated using the redirection address (e.g. pointing to the URI with APi version embedded) and we want to tell clients to keep using it (i.e. the permalinks).

  • other scenarios can be found in Redirection 3xx chapter of HTTP 1.1 specification

Forbidden You don't have permission to access /wp-login.php on this server

Sometimes if you are using some simple login info like this: username: 'admin' and pass: 'admin', the hosting is seeing you as a potential Brute Force Attack through WP login file, and blocks you IP address or that particularly file.

I had that issue with ixwebhosting and just got that info from their support guy. They must unban your IP in this situation. And you must change your WP admin login info to something more secure.

That solved my problem.

Android: How to add R.raw to project?

  • You need to right-click on res->new->Android resource directory. Make sure you select directory and not file.

  • Select raw in resource type and it automatically selects raw as the directory name.

  • Drag and drop your .mp3 music file inside the res folder. Make sure that it starts with a small letter.

Unable to use Intellij with a generated sources folder

The fix

Go to Project Structure - Modules - Source Folders and find the target/generated-sources/antlr4/com/mycompany - click Edit properties and set Package prefix to com.mycompany.

This is exactly the reason why we can set Package prefix on source dirs.


Different but related problem here

How to transfer data from JSP to servlet when submitting HTML form

Well, there are plenty of database tutorials online for java (what you're looking for is called JDBC). But if you are using plain servlets, you will have a class that extends HttpServlet and inside it you will have two methods that look like

public void doPost(HttpServletRequest req, HttpServletResponse resp){

}

and

public void doGet(HttpServletRequest req, HttpServletResponse resp){

}

One of them is called to handle GET operations and another is used to handle POST operations. You will then use the HttpServletRequest object to get the parameters that were passed as part of the form like so:

String name = req.getParameter("name");

Then, once you have the data from the form, it's relatively easy to add it to a database using a JDBC tutorial that is widely available on the web. I also suggest searching for a basic Java servlet tutorial to get you started. It's very easy, although there are a number of steps that need to be configured correctly.

LaTeX: Multiple authors in a two-column article

I put together a little test here:

\documentclass[10pt,twocolumn]{article}

\title{Article Title}
\author{
    First Author\\
    Department\\
    school\\
    email@edu
  \and
    Second Author\\
    Department\\
    school\\
    email@edu
    \and
    Third Author\\
    Department\\
    school\\
    email@edu
    \and
    Fourth Author\\
    Department\\
    school\\
    email@edu
}
\date{\today}

\begin{document}

\maketitle

\begin{abstract}
\ldots
\end{abstract}

\section{Introduction}
\ldots

\end{document}

Things to note, the title, author and date fields are declared before \begin{document}. Also, the multicol package is likely unnecessary in this case since you have declared twocolumn in the document class.

This example puts all four authors on the same line, but if your authors have longer names, departments or emails, this might cause it to flow over onto another line. You might be able to change the font sizes around a little bit to make things fit. This could be done by doing something like {\small First Author}. Here's a more detailed article on \LaTeX font sizes:

https://engineering.purdue.edu/ECN/Support/KB/Docs/LaTeXChangingTheFont

To italicize you can use {\it First Name} or \textit{First Name}.

Be careful though, if the document is meant for publication often times journals or conference proceedings have their own formatting guidelines so font size trickery might not be allowed.

Make header and footer files to be included in multiple html pages

I've been working in C#/Razor and since I don't have IIS setup on my home laptop I looked for a javascript solution to load in views while creating static markup for our project.

I stumbled upon a website explaining methods of "ditching jquery," it demonstrates a method on the site does exactly what you're after in plain Jane javascript (reference link at the bottom of post). Be sure to investigate any security vulnerabilities and compatibility issues if you intend to use this in production. I am not, so I never looked into it myself.

JS Function

var getURL = function (url, success, error) {
    if (!window.XMLHttpRequest) return;
    var request = new XMLHttpRequest();
    request.onreadystatechange = function () {
        if (request.readyState === 4) {
            if (request.status !== 200) {
                if (error && typeof error === 'function') {
                    error(request.responseText, request);
                }
                return;
            }
            if (success && typeof success === 'function') {
                success(request.responseText, request);
            }
        }
    };
    request.open('GET', url);
    request.send();
};

Get the content

getURL(
    '/views/header.html',
    function (data) {
        var el = document.createElement(el);
        el.innerHTML = data;
        var fetch = el.querySelector('#new-header');
        var embed = document.querySelector('#header');
        if (!fetch || !embed) return;
        embed.innerHTML = fetch.innerHTML;

    }
);

index.html

<!-- This element will be replaced with #new-header -->
<div id="header"></div>

views/header.html

<!-- This element will replace #header -->
<header id="new-header"></header>

The source is not my own, I'm merely referencing it as it's a good vanilla javascript solution to the OP. Original code lives here: http://gomakethings.com/ditching-jquery#get-html-from-another-page

On Windows, running "import tensorflow" generates No module named "_pywrap_tensorflow" error

my answer is for windows 10 users only as I have tried the following on windows 10. Extending some of the answers above I suggest this : If you are using anaconda then you can avoid everything and simply install anaconda-navigator using the command

conda install -c anaconda anaconda-navigator

Then you can launch the navigator from command prompt using the command

anaconda-navigator

On running this command you get a simple gui where you can create an virtual environment, create the environment with python=3.5.2 and install module tensorflow-gpu or tensorflow by searching the module in the search box using gui, it will also take care of installing correct cuda files for you. Using anaconda navigator is the simplest solution.

If you are not using anaconda then take care about the following

tensorflow-gpu 1.3 requires python 3.5.2, cuda development kit 8.0 and cudaDNN 6.0, hence when installing make sure you run the command

pip install tensorflow-gpu==1.3

tensorflow-gpu 1.2.1 or less requires python 3.5.2, cuda development kit 8.0 and cudaDNN 5.1 hence when installing make sure you run the command

pip install tensorflow-gpu==1.2.1

Below are the steps you need to follow for both of the above processes Setting up you path variables You must have the following system variables

CUDA_HOME = "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0"
CUDA_PATH = "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0"
CUDA_PATH_V8.0 = "C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0"

You PATHTEXT must include ".DLL" along with other extensions

".COM;.EXE;.BAT;.CMD;.VBS;.VBE;.JS;.JSE;.WSF;.WSH;.MSC;.PY;.DLL"

Also Add the following to you path

C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0\lib\x64
C:\Program Files\NVIDIA GPU Computing Toolkit\CUDA\v8.0\extras\CUPTI\libx64;
C:\Windows\SysWOW64;
C:\Windows\System32        

If you are getting errors you can download the run the below code by mrry, this code will check your setup and tell you if something is wrong https://gist.github.com/mrry/ee5dbcfdd045fa48a27d56664411d41c

References : http://blog.nitishmutha.com/tensorflow/2017/01/22/TensorFlow-with-gpu-for-windows.html

The above reference is very useful. Please comment for improvements to this answer. Hope this helps, Thanks.

How do I preserve line breaks when getting text from a textarea?

You could set width of div using Javascript and add white-space:pre-wrap to p tag, this break your textarea content at end of each line.

_x000D_
_x000D_
document.querySelector("button").onclick = function gt(){_x000D_
var card = document.createElement('div');_x000D_
card.style.width = "160px";_x000D_
card.style.background = "#eee";_x000D_
var post = document.createElement('p');_x000D_
var postText = document.getElementById('post-text').value;_x000D_
post.style.whiteSpace = "pre-wrap";_x000D_
card.append(post);_x000D_
post.append(postText);_x000D_
document.body.append(card);_x000D_
}
_x000D_
<textarea id="post-text" class="form-control" rows="3" placeholder="What's up?" required>_x000D_
Group Schedule:_x000D_
_x000D_
Tuesday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Thursday practice @ 5th floor (8pm - 11 pm)_x000D_
_x000D_
Sunday practice @ (9pm - 12 am)</textarea>_x000D_
<br><br>_x000D_
<button>Copy!!</button>
_x000D_
_x000D_
_x000D_

What is the meaning of 'No bundle URL present' in react-native?

It's because your client cannot reach your packager server.

If you are a Chinese Coder just as I am, I think you might using VPN get through the GFW. When your VPN tool is in 'Global Mode', all your request will travel through the world and cannot get localhost

Try 'Auto Proxy Mode'.

If you are not come from China, or your VPN setting is already 'Auto Proxy Mode', I suggest you shut down your packager server and try again.

Save modifications in place with awk

just a little hack that works

echo "$(awk '{awk code}' file)" > file

Is it possible to use jQuery .on and hover?

If you need it to have as a condition in an other event, I solved it this way:

$('.classname').hover(
     function(){$(this).data('hover',true);},
     function(){$(this).data('hover',false);}
);

Then in another event, you can easily use it:

 if ($(this).data('hover')){
      //...
 }

(I see some using is(':hover') to solve this. But this is not (yet) a valid jQuery selector and does not work in all compatible browsers)

What is the difference between __dirname and ./ in node.js?

The gist

In Node.js, __dirname is always the directory in which the currently executing script resides (see this). So if you typed __dirname into /d1/d2/myscript.js, the value would be /d1/d2.

By contrast, . gives you the directory from which you ran the node command in your terminal window (i.e. your working directory) when you use libraries like path and fs. Technically, it starts out as your working directory but can be changed using process.chdir().

The exception is when you use . with require(). The path inside require is always relative to the file containing the call to require.

For example...

Let's say your directory structure is

/dir1
  /dir2
    pathtest.js

and pathtest.js contains

var path = require("path");
console.log(". = %s", path.resolve("."));
console.log("__dirname = %s", path.resolve(__dirname));

and you do

cd /dir1/dir2
node pathtest.js

you get

. = /dir1/dir2
__dirname = /dir1/dir2

Your working directory is /dir1/dir2 so that's what . resolves to. Since pathtest.js is located in /dir1/dir2 that's what __dirname resolves to as well.

However, if you run the script from /dir1

cd /dir1
node dir2/pathtest.js

you get

. = /dir1
__dirname = /dir1/dir2

In that case, your working directory was /dir1 so that's what . resolved to, but __dirname still resolves to /dir1/dir2.

Using . inside require...

If inside dir2/pathtest.js you have a require call into include a file inside dir1 you would always do

require('../thefile')

because the path inside require is always relative to the file in which you are calling it. It has nothing to do with your working directory.

How do I initialise all entries of a matrix with a specific value?

It is easy to assign repeated values to an array:

x(1:10) = 5;

If you want to generate the array of elements inline in a statement try something like this:

ones(1,10) * 5

or with repmat

repmat(5, 1, 10)

how do I create an array in jquery?

You may be confusing Javascript arrays with PHP arrays. In PHP, arrays are very flexible. They can either be numerically indexed or associative, or even mixed.

array('Item 1', 'Item 2', 'Items 3')  // numerically indexed array
array('first' => 'Item 1', 'second' => 'Item 2')  // associative array
array('first' => 'Item 1', 'Item 2', 'third' => 'Item 3')

Other languages consider these two to be different things, Javascript being among them. An array in Javascript is always numerically indexed:

['Item 1', 'Item 2', 'Item 3']  // array (numerically indexed)

An "associative array", also called Hash or Map, technically an Object in Javascript*, works like this:

{ first : 'Item 1', second : 'Item 2' }  // object (a.k.a. "associative array")

They're not interchangeable. If you need "array keys", you need to use an object. If you don't, you make an array.


* Technically everything is an Object in Javascript, please put that aside for this argument. ;)

Automatically set appsettings.json for dev and release environments in asp.net core?

Just an update for .NET core 2.0 users, you can specify application configuration after the call to CreateDefaultBuilder:

public class Program
{
   public static void Main(string[] args)
   {
      BuildWebHost(args).Run();
   }

   public static IWebHost BuildWebHost(string[] args) =>
      WebHost.CreateDefaultBuilder(args)
             .ConfigureAppConfiguration(ConfigConfiguration)
             .UseStartup<Startup>()
             .Build();

   static void ConfigConfiguration(WebHostBuilderContext ctx, IConfigurationBuilder config)
   {
            config.SetBasePath(Directory.GetCurrentDirectory())
                .AddJsonFile("config.json", optional: false, reloadOnChange: true)
                .AddJsonFile($"config.{ctx.HostingEnvironment.EnvironmentName}.json", optional: true, reloadOnChange: true);

   }
 }

Fitting a density curve to a histogram in R

If I understand your question correctly, then you probably want a density estimate along with the histogram:

X <- c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4))
hist(X, prob=TRUE)            # prob=TRUE for probabilities not counts
lines(density(X))             # add a density estimate with defaults
lines(density(X, adjust=2), lty="dotted")   # add another "smoother" density

Edit a long while later:

Here is a slightly more dressed-up version:

X <- c(rep(65, times=5), rep(25, times=5), rep(35, times=10), rep(45, times=4))
hist(X, prob=TRUE, col="grey")# prob=TRUE for probabilities not counts
lines(density(X), col="blue", lwd=2) # add a density estimate with defaults
lines(density(X, adjust=2), lty="dotted", col="darkgreen", lwd=2) 

along with the graph it produces:

enter image description here

psql: command not found Mac

Mojave, Postgres was installed via

brew install https://raw.githubusercontent.com/lembacon/homebrew-core/bede8a46dea462769466f606f86f82511949066f/Formula/[email protected]

How to get psql in your path:

brew link [email protected] --force

How can I convert an Int to a CString?

If you want something more similar to your example try _itot_s. On Microsoft compilers _itot_s points to _itoa_s or _itow_s depending on your Unicode setting:

CString str;
_itot_s( 15, str.GetBufferSetLength( 40 ), 40, 10 );
str.ReleaseBuffer();

it should be slightly faster since it doesn't need to parse an input format.

Does Java support default parameter values?

There are several ways to simulate default parameters in Java:

  1. Method overloading.

    void foo(String a, Integer b) {
        //...
    }
    
    void foo(String a) {
        foo(a, 0); // here, 0 is a default value for b
    }
    
    foo("a", 2);
    foo("a");
    

    One of the limitations of this approach is that it doesn't work if you have two optional parameters of the same type and any of them can be omitted.

  2. Varargs.

    a) All optional parameters are of the same type:

    void foo(String a, Integer... b) {
        Integer b1 = b.length > 0 ? b[0] : 0;
        Integer b2 = b.length > 1 ? b[1] : 0;
        //...
    }
    
    foo("a");
    foo("a", 1, 2);
    

    b) Types of optional parameters may be different:

    void foo(String a, Object... b) {
        Integer b1 = 0;
        String b2 = "";
        if (b.length > 0) {
          if (!(b[0] instanceof Integer)) { 
              throw new IllegalArgumentException("...");
          }
          b1 = (Integer)b[0];
        }
        if (b.length > 1) {
            if (!(b[1] instanceof String)) { 
                throw new IllegalArgumentException("...");
            }
            b2 = (String)b[1];
            //...
        }
        //...
    }
    
    foo("a");
    foo("a", 1);
    foo("a", 1, "b2");
    

    The main drawback of this approach is that if optional parameters are of different types you lose static type checking. Furthermore, if each parameter has different meaning you need some way to distinguish them.

  3. Nulls. To address the limitations of the previous approaches you can allow null values and then analyse each parameter in a method body:

    void foo(String a, Integer b, Integer c) {
        b = b != null ? b : 0;
        c = c != null ? c : 0;
        //...
    }
    
    foo("a", null, 2);
    

    Now all arguments values must be provided, but the default ones may be null.

  4. Optional class. This approach is similar to nulls, but uses Java 8 Optional class for parameters that have a default value:

    void foo(String a, Optional<Integer> bOpt) {
        Integer b = bOpt.isPresent() ? bOpt.get() : 0;
        //...
    }
    
    foo("a", Optional.of(2));
    foo("a", Optional.<Integer>absent());
    

    Optional makes a method contract explicit for a caller, however, one may find such signature too verbose.

  5. Builder pattern. The builder pattern is used for constructors and is implemented by introducing a separate Builder class:

     class Foo {
         private final String a; 
         private final Integer b;
    
         Foo(String a, Integer b) {
           this.a = a;
           this.b = b;
         }
    
         //...
     }
    
     class FooBuilder {
       private String a = ""; 
       private Integer b = 0;
    
       FooBuilder setA(String a) {
         this.a = a;
         return this;
       }
    
       FooBuilder setB(Integer b) {
         this.b = b;
         return this;
       }
    
       Foo build() {
         return new Foo(a, b);
       }
     }
    
     Foo foo = new FooBuilder().setA("a").build();
    
  6. Maps. When the number of parameters is too large and for most of them default values are usually used, you can pass method arguments as a map of their names/values:

    void foo(Map<String, Object> parameters) {
        String a = ""; 
        Integer b = 0;
        if (parameters.containsKey("a")) { 
            if (!(parameters.get("a") instanceof Integer)) { 
                throw new IllegalArgumentException("...");
            }
            a = (String)parameters.get("a");
        } else if (parameters.containsKey("b")) { 
            //... 
        }
        //...
    }
    
    foo(ImmutableMap.<String, Object>of(
        "a", "a",
        "b", 2, 
        "d", "value")); 
    

Please note that you can combine any of these approaches to achieve a desirable result.

How to make the background image to fit into the whole page without repeating using plain css?

You can't resize background images with CSS2.

What you can do is have a container that resizes:

<div style='position:absolute;z-index:0;left:0;top:0;width:100%;height:100%'>
  <img src='whatever.jpg' style='width:100%;height:100%' alt='[]' />
</div>

This way, the div will sit behind the page and take up the whole space, while resizing as needed. The img inside will automatically resize to fit the div.

What is causing ERROR: there is no unique constraint matching given keys for referenced table?

when you do UNIQUE as a table level constraint as you have done then what your defining is a bit like a composite primary key see ddl constraints, here is an extract

"This specifies that the *combination* of values in the indicated columns is unique across the whole table, though any one of the columns need not be (and ordinarily isn't) unique."

this means that either field could possibly have a non unique value provided the combination is unique and this does not match your foreign key constraint.

most likely you want the constraint to be at column level. so rather then define them as table level constraints, 'append' UNIQUE to the end of the column definition like name VARCHAR(60) NOT NULL UNIQUE or specify indivdual table level constraints for each field.

SQL: parse the first, middle and last name from a fullname field

Subject to the caveats that have already been raised regarding spaces in names and other anomalies, the following code will at least handle 98% of names. (Note: messy SQL because I don't have a regex option in the database I use.)

**Warning: messy SQL follows:

create table parsname (fullname char(50), name1 char(30), name2 char(30), name3 char(30), name4 char(40));
insert into parsname (fullname) select fullname from ImportTable;
update parsname set name1 = substring(fullname, 1, locate(' ', fullname)),
 fullname = ltrim(substring(fullname, locate(' ', fullname), length(fullname)))
 where locate(' ', rtrim(fullname)) > 0;
update parsname set name2 = substring(fullname, 1, locate(' ', fullname)),
 fullname = ltrim(substring(fullname, locate(' ', fullname), length(fullname)))
 where locate(' ', rtrim(fullname)) > 0;
update parsname set name3 = substring(fullname, 1, locate(' ', fullname)),
 fullname = ltrim(substring(fullname, locate(' ', fullname), length(fullname)))
 where locate(' ', rtrim(fullname)) > 0;
update parsname set name4 = substring(fullname, 1, locate(' ', fullname)),
 fullname = ltrim(substring(fullname, locate(' ', fullname), length(fullname)))
 where locate(' ', rtrim(fullname)) > 0;
// fullname now contains the last word in the string.
select fullname as FirstName, '' as MiddleName, '' as LastName from parsname where fullname is not null and name1 is null and name2 is null
union all
select name1 as FirstName, name2 as MiddleName, fullname as LastName from parsname where name1 is not null and name3 is null

The code works by creating a temporary table (parsname) and tokenizing the fullname by spaces. Any names ending up with values in name3 or name4 are non-conforming and will need to be dealt with differently.

Why is there no multiple inheritance in Java, but implementing multiple interfaces is allowed?

in simple manner we all know, we can inherit(extends) one class but we can implements so many interfaces.. that is because in interfaces we don't give an implementation just say the functionality. suppose if java can extends so many classes and those have same methods.. in this point if we try to invoke super class method in the sub class what method suppose to run??, compiler get confused example:- try to multiple extends but in interfaces those methods don't have bodies we should implement those in sub class.. try to multiple implements so no worries..

MySQL ERROR 1045 (28000): Access denied for user 'bill'@'localhost' (using password: YES)

When you ran

mysql -u bill -p

and got this error

ERROR 1045 (28000): Access denied for user 'bill'@'localhost' (using password: YES)

mysqld is expecting you to connect as bill@localhost

Try creating bill@localhost

CREATE USER bill@localhost IDENTIFIED BY 'passpass';
grant all privileges on *.* to bill@localhost with grant option;

If you want to connect remotely, you must specify either the DNS name, the public IP, or 127.0.0.1 using TCP/IP:

mysql -u bill -p [email protected]
mysql -u bill -p -h10.1.2.30
mysql -u bill -p -h127.0.0.1 --protocol=TCP

Once you login, please run this

SELECT USER(),CURRENT_USER();

USER() reports how you attempted to authenticate in MySQL

CURRENT_USER() reports how you were allowed to authenticate in MySQL from the mysql.user table

This will give you a better view of how and why you were allowed to login to mysql. Why is this view important to know? It has to do with the user authentication ordering protocol.

Here is an example: I will create an anonymous user on my desktop MySQL

mysql> select user,host from mysql.user;
+---------+-----------+
| user    | host      |
+---------+-----------+
| lwdba   | %         |
| mywife  | %         |
| lwdba   | 127.0.0.1 |
| root    | 127.0.0.1 |
| lwdba   | localhost |
| root    | localhost |
| vanilla | localhost |
+---------+-----------+
7 rows in set (0.00 sec)

mysql> grant all on *.* to x@'%';
Query OK, 0 rows affected (0.02 sec)

mysql> select user,host from mysql.user;
+---------+-----------+
| user    | host      |
+---------+-----------+
| lwdba   | %         |
| mywife  | %         |
| x       | %         |
| lwdba   | 127.0.0.1 |
| root    | 127.0.0.1 |
| lwdba   | localhost |
| root    | localhost |
| vanilla | localhost |
+---------+-----------+
8 rows in set (0.00 sec)

mysql> update mysql.user set user='' where user='x';
Query OK, 1 row affected (0.00 sec)
Rows matched: 1  Changed: 1  Warnings: 0

mysql> flush privileges;
Query OK, 0 rows affected (0.01 sec)

mysql> select user,host from mysql.user;
+---------+-----------+
| user    | host      |
+---------+-----------+
|         | %         |
| lwdba   | %         |
| mywife  | %         |
| lwdba   | 127.0.0.1 |
| root    | 127.0.0.1 |
| lwdba   | localhost |
| root    | localhost |
| vanilla | localhost |
+---------+-----------+
8 rows in set (0.00 sec)

mysql>

OK watch me login as anonymous user:

C:\MySQL_5.5.12>mysql -urol -Dtest -h127.0.0.1 --protocol=TCP
Welcome to the MySQL monitor.  Commands end with ; or \g.
Your MySQL connection id is 12
Server version: 5.5.12-log MySQL Community Server (GPL)

Copyright (c) 2000, 2010, Oracle and/or its affiliates. All rights reserved.

Oracle is a registered trademark of Oracle Corporation and/or its
affiliates. Other names may be trademarks of their respective
owners.

Type 'help;' or '\h' for help. Type '\c' to clear the current input statement.

mysql> select user(),current_user();
+---------------+----------------+
| user()        | current_user() |
+---------------+----------------+
| rol@localhost | @%             |
+---------------+----------------+
1 row in set (0.00 sec)

mysql>

Authentication ordering is very strict. It checks from the most specific to the least. I wrote about this authentiation style in the DBA StackExchange.

Don't forget to explicitly call for TCP as the protocol for mysql client when necessary.

Convert a String to a byte array and then back to the original String

import java.io.FileInputStream; import java.io.ByteArrayOutputStream;

public class FileHashStream { // write a new method that will provide a new Byte array, and where this generally reads from an input stream

public static byte[] read(InputStream is) throws Exception
{
    String path = /* type in the absolute path for the 'commons-codec-1.10-bin.zip' */;

    // must need a Byte buffer

    byte[] buf = new byte[1024 * 16]

    // we will use 16 kilobytes

    int len = 0;

    // we need a new input stream

    FileInputStream is = new FileInputStream(path);

    // use the buffer to update our "MessageDigest" instance

    while(true)
    {
        len = is.read(buf);
        if(len < 0) break;
        md.update(buf, 0, len);
    }

    // close the input stream

    is.close();

    // call the "digest" method for obtaining the final hash-result

    byte[] ret = md.digest();

    System.out.println("Length of Hash: " + ret.length);

    for(byte b : ret)
    {
        System.out.println(b + ", ");
    }

    String compare = "49276d206b696c6c696e6720796f757220627261696e206c696b65206120706f69736f6e6f7573206d757368726f6f6d";

    String verification = Hex.encodeHexString(ret);

    System.out.println();

    System.out.println("===")

    System.out.println(verification);

    System.out.println("Equals? " + verification.equals(compare));

}

}

IndentationError expected an indented block

If you are using a mac and sublime text 3, this is what you do.

Go to your /Packages/User/ and create a file called Python.sublime-settings.

Typically /Packages/User is inside your ~/Library/Application Support/Sublime Text 3/Packages/User/Python.sublime-settings if you are using mac os x.

Then you put this in the Python.sublime-settings.

{
    "tab_size": 4,
    "translate_tabs_to_spaces": false
}

Credit goes to Mark Byer's answer, sublime text 3 docs and python style guide.

This answer is mostly for readers who had the same issue and stumble upon this and are using sublime text 3 on Mac OS X.

Why can't I enter a string in Scanner(System.in), when calling nextLine()-method?

Scanner's buffer full when we take a input string through scan.nextLine(); so it skips the input next time . So solution is that we can create a new object of Scanner , the name of the object can be same as previous object......

How do I align spans or divs horizontally?

You can use

.floatybox {
     display: inline-block;
     width: 123px;
}

If you only need to support browsers that have support for inline blocks. Inline blocks can have width, but are inline, like button elements.

Oh, and you might wnat to add vertical-align: top on the elements to make sure things line up

Date minus 1 year?

You can use strtotime:

$date = strtotime('2010-01-01 -1 year');

The strtotime function returns a unix timestamp, to get a formatted string you can use date:

echo date('Y-m-d', $date); // echoes '2009-01-01'

Extract Number from String in Python

If the format is that simple (a space separates the number from the rest) then

int(str1.split()[0])

would do it

How to make a shape with left-top round rounded corner and left-bottom rounded corner?

While this question has been answered already (it's a bug that causes bottomLeftRadius and bottomRightRadius to be reversed), the bug has been fixed in android 3.1 (api level 12 - tested on the emulator).

So to make sure your drawables look correct on all platforms, you should put "corrected" versions of the drawables (i.e. where bottom left/right radii are actually correct in the xml) in the res/drawable-v12 folder of your app. This way all devices using an android version >= 12 will use the correct drawable files, while devices using older versions of android will use the "workaround" drawables that are located in the res/drawables folder.

Ruby on Rails form_for select field with class

You can see in here: http://apidock.com/rails/ActionView/Helpers/FormBuilder/select

Or here: http://apidock.com/rails/ActionView/Helpers/FormOptionsHelper/select

Select tag has maximun 4 agrument, and last agrument is html option, it mean you can put class, require, selection option in here.

= f.select :sms_category_id, @sms_category_collect, {}, {class: 'form-control', required: true, selected: @set}

Batch file to restart a service. Windows

net stop <your service> && net start <your service>

No net restart, unfortunately.

How do I set an un-selectable default description in a select (drop-down) menu in HTML?

If none of the options in the select have a selected attribute, the first option will be the one selected.

In order to select a default option that is not the first, add a selected attribute to that option:

<option selected="selected">Select a language</option>

You can read the HTML 4.01 spec regarding defaults in select element.

I suggest reading a good HTML book if you need to learn HTML basics like this - I recommend Head First HTML.

How to preserve request url with nginx proxy_pass

nginx also provides the $http_host variable which will pass the port for you. its a concatenation of host and port.

So u just need to do:

proxy_set_header Host $http_host;

Unexpected end of file error

Change the Platform of your C++ project to "x64" (or whichever platform you are targeting) instead of "Win32". This can be found in Visual Studio under Build -> Configuration Manager. Find your project in the list and change the Platform column. Don't forget to do this for all solution configurations.

Parsing GET request parameters in a URL that contains another URL

if (isset($_SERVER['HTTPS'])){
    echo "https://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]$_SERVER[QUERY_STRING]";
}else{
    echo "http://$_SERVER[HTTP_HOST]$_SERVER[REQUEST_URI]$_SERVER[QUERY_STRING]";
}

Oracle SQL Developer - tables cannot be seen

The identity used to create the connection defines what tables you can see in Oracle. Did you provide different credentials when setting up the connection for the new version?

How to get the current logged in user Id in ASP.NET Core

Make sure that you have enable windows authentication. If you have anonymous authentication enabled you may be getting a null string.

https://docs.microsoft.com/en-us/aspnet/core/security/authentication/windowsauth?view=aspnetcore-3.1&tabs=visual-studio

IntelliJ: Never use wildcard imports

If non of above works for you, then it is worth to check if you have any packages under Preference > Editor > Code Style > Java > Imports > Packages to Use Import with "*"

How do I remove files saying "old mode 100755 new mode 100644" from unstaged changes in Git?

The accepted answer to set git config core.filemode false, works, but with consequences. Setting core.filemode to false tells git to ignore any executable bit changes on the filesystem so it won't view this as a change. If you do need to stage an executable bit change for this repository anytime in the future, you would have to do it manually, or set core.filemode back to true.

A less consequential alternative, if all the modified files should have mode 100755, is to do something like

chmod 100755 $(git ls-files --modified)

which just does exactly the change in mode, no more, no less, without additional implications.

(in my case, it was due to a OneDrive sync with my filesystem on MacOS; by not changing core.filemode, I'm leaving the possibility open that the mode change might happen again in the future; in my case, I'd like to know if it happens again, and changing core.filemode will hide it from me, which I don't want)

how to get rid of notification circle in right side of the screen?

This stuff comes from ES file explorer

Just go into this app > settings

Then there is an option that says logging floating window, you just need to disable that and you will get rid of this infernal bubble for good

Using C++ filestreams (fstream), how can you determine the size of a file?

You can open the file using the ios::ate flag (and ios::binary flag), so the tellg() function will give you directly the file size:

ifstream file( "example.txt", ios::binary | ios::ate);
return file.tellg();

Remove all items from a FormArray in Angular

I am very late but I found some other way where you don't need to have loops. you can reset array by setting array control to empty.

Below code will reset your array.

this.form.setControl('name', this.fb.array([]))

Convert Java Date to UTC String

Well if you want to use java.util.Date only, here is a small trick you can use:

String dateString = Long.toString(Date.UTC(date.getYear(), date.getMonth(), date.getDate(), date.getHours(), date.getMinutes(), date.getSeconds()));

C# 'or' operator?

Also worth mentioning, in C# the OR operator is short-circuiting. In your example, Close seems to be a property, but if it were a method, it's worth noting that:

if (ActionsLogWriter.Close() || ErrorDumpWriter.Close())

is fundamentally different from

if (ErrorDumpWriter.Close() || ActionsLogWriter.Close())

In C#, if the first expression returns true, the second expression will not be evaluated at all. Just be aware of this. It actually works to your advantage most of the time.

Array vs. Object efficiency in JavaScript

It depends on usage. If the case is lookup objects is very faster.

Here is a Plunker example to test performance of array and object lookups.

https://plnkr.co/edit/n2expPWVmsdR3zmXvX4C?p=preview

You will see that; Looking up for 5.000 items in 5.000 length array collection, take over 3000 milisecons

However Looking up for 5.000 items in object has 5.000 properties, take only 2 or 3 milisecons

Also making object tree don't make huge difference

Multiple file extensions in OpenFileDialog

This is from MSDN sample:

(*.bmp, *.jpg)|*.bmp;*.jpg

So for your case

openFileDialog1.Filter = "JPG (*.jpg,*.jpeg)|*.jpg;*.jpeg|TIFF (*.tif,*.tiff)|*.tif;*.tiff"

Determine a string's encoding in C#

Another option, very late in coming, sorry:

http://www.architectshack.com/TextFileEncodingDetector.ashx

This small C#-only class uses BOMS if present, tries to auto-detect possible unicode encodings otherwise, and falls back if none of the Unicode encodings is possible or likely.

It sounds like UTF8Checker referenced above does something similar, but I think this is slightly broader in scope - instead of just UTF8, it also checks for other possible Unicode encodings (UTF-16 LE or BE) that might be missing a BOM.

Hope this helps someone!

Angular no provider for NameService

In Angular 2 there are three places you can "provide" services:

  1. bootstrap
  2. root component
  3. other components or directives

"The bootstrap provider option is intended for configuring and overriding Angular's own preregistered services, such as its routing support." -- reference

If you only want one instance of NameService across your entire app (i.e., Singleton), then include it in the providers array of your root component:

@Component({
   providers: [NameService],
   ...
)}
export class AppComponent { ... }

Plunker

If you would rather have one instance per component, use the providers array in the component's configuration object instead:

@Component({
   providers: [NameService],
   ...
)}
export class SomeOtherComponentOrDirective { ... }

See the Hierarchical Injectors doc for more info.

callback to handle completion of pipe

Here's a solution that handles errors in requests and calls a callback after the file is written:

request(opts)
    .on('error', function(err){ return callback(err)})
    .pipe(fs.createWriteStream(filename))
    .on('finish', function (err) {
        return callback(err);
    });

Inserting a value into all possible locations in a list

If l is your list and X is your value:

for i in range(len(l) + 1):
    print l[:i] + [X] + l[i:]

Array.Add vs +=

The most common idiom for creating an array without using the inefficient += is something like this, from the output of a loop:

$array = foreach($i in 1..10) { 
  $i
}
$array

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

The most useful thing you can do here is display/i $pc, before using stepi as already suggested in R Samuel Klatchko's answer. This tells gdb to disassemble the current instruction just before printing the prompt each time; then you can just keep hitting Enter to repeat the stepi command.

(See my answer to another question for more detail - the context of that question was different, but the principle is the same.)

Business logic in MVC

Q1:

Business logics can be considered in two categories:

  1. Domain logics like controls on an email address (uniqueness, constraints, etc.), obtaining the price of a product for invoice, or, calculating the shoppingCart's total price based of its product objects.

  2. More broad and complicated workflows which are called business processes, like controlling the registration process for the student (which usually includes several steps and needs different checks and has more complicated constraints).

The first category goes into model and the second one belongs to controller. This is because the cases in the second category are broad application logics and putting them in the model may mix the model's abstraction (for example, it is not clear if we need to put those decisions in one model class or another, since they are related to both!).

See this answer for a specific distinction between model and controller, this link for very exact definitions and also this link for a nice Android example.

The point is that the notes mentioned by "Mud" and "Frank" above both can be true as well as "Pete"'s (business logic can be put in model, or controller, according to the type of business logic).

Finally, note that MVC differs from context to context. For example, in Android applications, some alternative definitions are suggested that differs from web-based ones (see this post for example).


Q2:

Business logic is more general and (as "decyclone" mentioned above) we have the following relation between them:

business rules ? business logics

VBA check if object is set

If obj Is Nothing Then
    ' need to initialize obj: '
    Set obj = ...
Else
    ' obj already set / initialized. '
End If

Or, if you prefer it the other way around:

If Not obj Is Nothing Then
    ' obj already set / initialized. '
Else
    ' need to initialize obj: '
    Set obj = ...
End If

Does VBScript have a substring() function?

Yes, Mid.

Dim sub_str
sub_str = Mid(source_str, 10, 5)

The first parameter is the source string, the second is the start index, and the third is the length.

@bobobobo: Note that VBScript strings are 1-based, not 0-based. Passing 0 as an argument to Mid results in "invalid procedure call or argument Mid".

How do I split an int into its digits?

Reversed order digit extractor (eg. for 23 will be 3 and 2):

while (number > 0)
{
    int digit = number%10;
    number /= 10;
    //print digit
}

Normal order digit extractor (eg. for 23 will be 2 and 3):

std::stack<int> sd;

while (number > 0)
{
    int digit = number%10;
    number /= 10;
    sd.push(digit);
}

while (!sd.empty())
{
    int digit = sd.top();
    sd.pop();
    //print digit
}

Format JavaScript date as yyyy-mm-dd

_x000D_
_x000D_
const today = new Date(); // or whatever _x000D_
_x000D_
const yearFirstFormater = (date): string => {_x000D_
    const modifiedDate = new Date(date).toISOString().slice(0, 10);_x000D_
    return `${modifiedDate.split('-')[0]}/${modifiedDate.split('-')[1]}/${modifiedDate.split('-')[2]}`;_x000D_
}_x000D_
_x000D_
const monthFirstFormater = (date): string => {_x000D_
    const modifiedDate = new Date(date).toISOString().slice(0, 10);_x000D_
    return `${modifiedDate.split('-')[1]}/${modifiedDate.split('-')[2]}/${modifiedDate.split('-')[0]}`;_x000D_
}_x000D_
_x000D_
const dayFirstFormater = (date): string => {_x000D_
    const modifiedDate = new Date(date).toISOString().slice(0, 10);_x000D_
    return `${modifiedDate.split('-')[2]}/${modifiedDate.split('-')[1]}/${modifiedDate.split('-')[0]}`;_x000D_
}_x000D_
_x000D_
console.log(yearFirstFormater(today));_x000D_
console.log(monthFirstFormater(today));_x000D_
console.log(dayFirstFormater(today));
_x000D_
_x000D_
_x000D_

C# importing class into another class doesn't work

MyClass is a class not a namespace. So this code is wrong:

using MyClass //THIS CODE IS NOT CORRECT

You should check the namespace of the MyClass (e.g: MyNamespace). Then call it in a proper way:

MyNamespace.MyClass myClass =new MyNamespace.MyClass();

How to tell if a file is git tracked (by shell exit code)?

EDIT

If you need to use git from bash there is --porcelain option to git status:

--porcelain

Give the output in a stable, easy-to-parse format for scripts. Currently this is identical to --short output, but is guaranteed not to change in the future, making it safe for scripts.

Output looks like this:

> git status --porcelain
 M starthudson.sh
?? bla

Or if you do only one file at a time:

> git status --porcelain bla
?? bla

ORIGINAL

do:

git status

You will see report stating which files were updated and which ones are untracked.

You can see bla.sh is tracked and modified and newbla is not tracked:

# On branch master
# Changed but not updated:
#   (use "git add <file>..." to update what will be committed)
#
#       modified:   bla.sh
#
# Untracked files:
#   (use "git add <file>..." to include in what will be committed)
#
#       newbla
no changes added to commit (use "git add" and/or "git commit -a")

Proper way to renew distribution certificate for iOS

As of January 2020 and Xcode 11.3.1 -

  • Open Xcode
  • Open Xcode Preferences (Xcode->Preferences or Cmd-,)
  • Click on Accounts
  • At the left, click on your developer ID
  • At the bottom right, click on Manage Certificates...
  • In the lower left corner, click the arrow to the right of the + (plus)
  • Select Apple Distribution from the menu

Xcode will automatically create an Apple Distribution certificate, install it in Keychain Access, and update Xcode's signing information

(Note: the single Apple Distribution certificate is now provided instead of the previous iOS Distribution certificate and equivalents.)

Python 3.4.0 with MySQL database

There is a Ubuntu solution available either through the Ubuntu Software Center or through the Synaptic Package Manager. This will connect Python version 3.4.0 to MySQL. Download "python3-mysql.connector" version 1.1.6-1.

Note that the connection syntax does not use "MySQLdb". Instead read: Connecting to MySQL Using Connector/Python

How to check if an element exists in the xml using xpath?

Use:

boolean(/*/*[@subjectIdentifier="Primary"]/*/*/*/*
                           [name()='AttachedXml' 
                          and 
                            namespace-uri()='http://xml.mycompany.com/XMLSchema'
                           ]
       )

How to set ssh timeout?

ssh -o ConnectTimeout=10  <hostName>

Where 10 is time in seconds. This Timeout applies only to the creation of the connection.

Why is JsonRequestBehavior needed?

You do not need it.

If your action has the HttpPost attribute, then you do not need to bother with setting the JsonRequestBehavior and use the overload without it. There is an overload for each method without the JsonRequestBehavior enum. Here they are:

Without JsonRequestBehavior

protected internal JsonResult Json(object data);
protected internal JsonResult Json(object data, string contentType);
protected internal virtual JsonResult Json(object data, string contentType, Encoding contentEncoding);

With JsonRequestBehavior

protected internal JsonResult Json(object data, JsonRequestBehavior behavior);
protected internal JsonResult Json(object data, string contentType, 
                                   JsonRequestBehavior behavior);
protected internal virtual JsonResult Json(object data, string contentType, 
    Encoding contentEncoding, JsonRequestBehavior behavior);

Operation Not Permitted when on root - El Capitan (rootless disabled)

Nvm. For anyone else having this problem you need to reboot your mac and press ?+R when booting up. Then go into Utilities > Terminal and type the following commands:

csrutil disable
reboot 

This is a result of System Integrity Protection. More info here.

EDIT

If you know what you are doing and are used to running Linux, you should use the above solution as many of the SIP restrictions are a complete pain in the ass.

However, if you are a tinkerer/noob/"poweruser" and don't know what you are doing, this can be very dangerous and you are better off using the answer below.

How to check command line parameter in ".bat" file?

In addition to the other answers, which I subscribe, you may consider using the /I switch of the IF command.

... the /I switch, if specified, says to do case insensitive string compares.

it may be of help if you want to give case insensitive flexibility to your users to specify the parameters.

IF /I "%1"=="-b" GOTO SPECIFIC

Oracle SQL Query for listing all Schemas in a DB

SELECT username FROM all_users ORDER BY username;

How can I join multiple SQL tables using the IDs?

You have not joined TableD, merely selected the TableD FIELD (dID) from one of the tables.

Converting Milliseconds to Minutes and Seconds?

Below code does the work for converting ms to min:secs with [m:ss] format

int seconds;
int minutes;
String Sec;
long Mills = ...;  // Milliseconds goes here
minutes = (int)(Mills / 1000)  / 60;
seconds = (int)((Mills / 1000) % 60);
Sec = seconds+"";

TextView.setText(minutes+":"+Sec);//Display duration [3:40]

What is the best regular expression to check if a string is a valid URL?

A simple check for URL is

^(ftp|http|https):\/\/[^ "]+$

In a Bash script, how can I exit the entire script if a certain condition occurs?

Use set -e

#!/bin/bash

set -e

/bin/command-that-fails
/bin/command-that-fails2

The script will terminate after the first line that fails (returns nonzero exit code). In this case, command-that-fails2 will not run.

If you were to check the return status of every single command, your script would look like this:

#!/bin/bash

# I'm assuming you're using make

cd /project-dir
make
if [[ $? -ne 0 ]] ; then
    exit 1
fi

cd /project-dir2
make
if [[ $? -ne 0 ]] ; then
    exit 1
fi

With set -e it would look like:

#!/bin/bash

set -e

cd /project-dir
make

cd /project-dir2
make

Any command that fails will cause the entire script to fail and return an exit status you can check with $?. If your script is very long or you're building a lot of stuff it's going to get pretty ugly if you add return status checks everywhere.

Address in mailbox given [] does not comply with RFC 2822, 3.6.2. when email is in a variable

Data variables ($email, $subject) seems to be global. And globals cannot be read inside functions. You must pass them as parameters (the recommended way) or declare them as global.

Try this way:

Mail::send('emails.activation', $data, function($message, $email, $subject){
        $message->to($email)->subject($subject);
    });
            ->with('title', "Registered Successfully.");

ffprobe or avprobe not found. Please install one

You can install them by

sudo apt-get install -y libav-tools

Build Android Studio app via command line

note, you can also do this within Android Studio by clicking the gradle window, and then the 'elephant' button. This will open a new window called "run anything" (can also be found by searching for that name in 'search everywhere') where you can manually type any gradle command you want in. Not "quite" command line, but often provides more of what I need than windows command line.

This allows you to give optional params to gradle tasks, etc.

Is it possible to import modules from all files in a directory, using a wildcard?

You can use async import():

import fs = require('fs');

and then:

fs.readdir('./someDir', (err, files) => {
 files.forEach(file => {
  const module = import('./' + file).then(m =>
    m.callSomeMethod();
  );
  // or const module = await import('file')
  });
});

How to squash all git commits into one?

This answer improves on a couple above (please vote them up), assuming that in addition to creating the one commit (no-parents no-history), you also want to retain all of the commit-data of that commit:

  • Author (name and email)
  • Authored date
  • Commiter (name and email)
  • Committed date
  • Commmit log message

Of course the commit-SHA of the new/single commit will change, because it represents a new (non-)history, becoming a parentless/root-commit.

This can be done by reading git log and setting some variables for git commit-tree. Assuming that you want to create a single commit from master in a new branch one-commit, retaining the commit-data above:

git checkout -b one-commit master ## create new branch to reset
git reset --hard \
$(eval "$(git log master -n1 --format='\
COMMIT_MESSAGE="%B" \
GIT_AUTHOR_NAME="%an" \
GIT_AUTHOR_EMAIL="%ae" \
GIT_AUTHOR_DATE="%ad" \
GIT_COMMITTER_NAME="%cn" \
GIT_COMMITTER_EMAIL="%ce" \
GIT_COMMITTER_DATE="%cd"')" 'git commit-tree master^{tree} <<COMMITMESSAGE
$COMMIT_MESSAGE
COMMITMESSAGE
')

@import vs #import - iOS 7

History:

#include => #import => .pch => @import

[#include vs #import]
[.pch - Precompiled header]

Module - @import

Product Name == Product Module Name 

@import module declaration says to compiler to load a precompiled binary of framework which decrease a building time. Modular Framework contains .modulemap[About]

If module feature is enabled in Xcode project #include and #import directives are automatically converted to @import that brings all advantages

enter image description here

Using the value in a cell as a cell reference in a formula?

Use INDIRECT()

=SUM(INDIRECT(<start cell here> & ":" & <end cell here>))

How to create a multi line body in C# System.Net.Mail.MailMessage

Try using a StringBuilder object and use the appendline method. That might work.

How can I detect when the mouse leaves the window?

None of these answers worked for me. I'm now using:

document.addEventListener('dragleave', function(e){

    var top = e.pageY;
    var right = document.body.clientWidth - e.pageX;
    var bottom = document.body.clientHeight - e.pageY;
    var left = e.pageX;

    if(top < 10 || right < 20 || bottom < 10 || left < 10){
        console.log('Mouse has moved out of window');
    }

});

I'm using this for a drag and drop file uploading widget. It's not absolutely accurate, being triggered when the mouse gets to a certain distance from the edge of the window.

How can I avoid running ActiveRecord callbacks?

If the goal is to simply insert a record without callbacks or validations, and you would like to do it without resorting to additional gems, adding conditional checks, using RAW SQL, or futzing with your exiting code in any way, consider using a "shadow object" pointing to your existing db table. Like so:

class ImportedPerson < ActiveRecord::Base
  self.table_name = 'people'
end

This works with every version of Rails, is threadsafe, and completely eliminates all validations and callbacks with no modifications to your existing code. You can just toss that class declaration in right before your actual import, and you should be good to go. Just remember to use your new class to insert the object, like:

ImportedPerson.new( person_attributes )

Getting the "real" Facebook profile picture URL from graph API

For Android:

According to latest Facebook SDK,

First you need to call GraphRequest API for getting all the details of user in which API also gives URL of current Profile Picture.

Bundle params = new Bundle();
params.putString("fields", "id,email,gender,cover,picture.type(large)");
new GraphRequest(token, "me", params, HttpMethod.GET,
        new GraphRequest.Callback() {
            @Override
            public void onCompleted(GraphResponse response) {
                if (response != null) {
                    try {
                        JSONObject data = response.getJSONObject();
                        if (data.has("picture")) {
                            String profilePicUrl = data.getJSONObject("picture").getJSONObject("data").getString("url");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
}).executeAsync();

React JS onClick event handler

Here is how you define a react onClick event handler, which was answering the question title... using es6 syntax

import React, { Component } from 'react';

export default class Test extends Component {
  handleClick(e) {
    e.preventDefault()
    console.log(e.target)
  }

  render() {
    return (
      <a href='#' onClick={e => this.handleClick(e)}>click me</a>
    )
  }
}

VBA - Select columns using numbers?

I was looking for a similar thing. My problem was to find the last column based on row 5 and then select 3 columns before including the last column.

Dim lColumn As Long

lColumn = ActiveSheet.Cells(5,Columns.Count).End(xlToLeft).Column
MsgBox ("The last used column is: " & lColumn)
Range(Columns(lColumn - 3), Columns(lColumn)).Select

Message box is optional as it is more of a control check. If you want to select the columns after the last column then you simply reverse the range selection

Dim lColumn As Long

lColumn = ActiveSheet.Cells(5,Columns.Count).End(xlToLeft).Column
MsgBox ("The last used column is: " & lColumn)
Range(Columns(lColumn), Columns(lColumn + 3)).Select

Access localhost from the internet

use your ip address or a service like noip.com if you need something more practical. Then eventually configure your router properly so incoming connection will be forwarded to the machine with the server running.

What is a serialVersionUID and why should I use it?

'serialVersionUID' is a 64 bit number used to uniquely identify a class during deserialization process. When you serialize an object, serialVersionUID of the class also written to the file. Whenever you deserialize this object, java run time extract this serialVersionUID value from the serialized data and compare the same value associate with the class. If both do not match, then 'java.io.InvalidClassException' will be thrown.

If a serializable class do not explicitly declare a serialVersionUID, then serialization runtime will calculate serialVersionUID value for that class based on various aspects of the class like fields, methods etc.,, You can refer this link for demo application.

Plugin org.apache.maven.plugins:maven-clean-plugin:2.5 or one of its dependencies could not be resolved

Think to change JDK used in your project. For me I changed JDK from 1.6 to 1.8 and I updated maven.

Position Relative vs Absolute?

Both “relative” and “absolute” positioning are really relative, just with different framework. “Absolute” positioning is relative to the position of another, enclosing element. “Relative” positioning is relative to the position that the element itself would have without positioning.

It depends on your needs and goals which one you use. “Relative” position is suitable when you wish to displace an element from the position it would otherwise have in the flow of elements, e.g. to make some characters appear in a superscript position. “Absolute” positioning is suitable for placing an element in some system of coordinates set by another element, e.g. to “overprint” an image with some text.

As a special, use “relative” positioning with no displacement (just setting position: relative) to make an element a frame of reference, so that you can use “absolute” positioning for elements that are inside it (in markup).

How to set DataGrid's row Background, based on a property value using data bindings

The same can be done without DataTrigger too:

 <DataGrid.RowStyle>
     <Style TargetType="DataGridRow">
         <Setter Property="Background" >
             <Setter.Value>
                 <Binding Path="State" Converter="{StaticResource BooleanToBrushConverter}">
                     <Binding.ConverterParameter>
                         <x:Array Type="SolidColorBrush">
                             <SolidColorBrush Color="{StaticResource RedColor}"/>
                             <SolidColorBrush Color="{StaticResource TransparentColor}"/>
                         </x:Array>
                     </Binding.ConverterParameter>
                 </Binding>
             </Setter.Value>
         </Setter>
     </Style>
 </DataGrid.RowStyle>

Where BooleanToBrushConverter is the following class:

public class BooleanToBrushConverter : IValueConverter
{
    public object Convert(object value, Type targetType, object parameter, CultureInfo culture)
    {
        if (value == null)
            return Brushes.Transparent;

        Brush[] brushes = parameter as Brush[];
        if (brushes == null)
            return Brushes.Transparent;

        bool isTrue;
        bool.TryParse(value.ToString(), out isTrue);

        if (isTrue)
        {
            var brush =  (SolidColorBrush)brushes[0];
            return brush ?? Brushes.Transparent;
        }
        else
        {
            var brush = (SolidColorBrush)brushes[1];
            return brush ?? Brushes.Transparent;
        }
    }

    public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture)
    {
        throw new NotImplementedException();
    }
}

PHP, display image with Header()

if you know the file name, but don't know the file extention you can use this function:

public function showImage($name)
    {

         $types = [
             'gif'=> 'image/gif',
             'png'=> 'image/png',
             'jpeg'=> 'image/jpeg',
             'jpg'=> 'image/jpeg',
         ];
         $root_path  = '/var/www/my_app'; //use your framework to get this properly ..
         foreach($types as $type=>$meta){
             if(file_exists($root_path .'/uploads/'.$name  .'.'. $type)){
                 header('Content-type: ' . $meta);
                 readfile($root_path .'/uploads/'.$name .'.'. $type);
                 return;
             }
         }
    }

Note: the correct content-type for JPG files is image/jpeg.

Split string into string array of single characters

Try this:

var charArray = "this is a test".ToCharArray().Select(c=>c.ToString());

CSS3 animate border color

If you need the transition to run infinitely, try the below example:

_x000D_
_x000D_
#box {_x000D_
  position: relative;_x000D_
  width: 100px;_x000D_
  height: 100px;_x000D_
  background-color: gray;_x000D_
  border: 5px solid black;_x000D_
  display: block;_x000D_
}_x000D_
_x000D_
#box:hover {_x000D_
  border-color: red;_x000D_
  animation-name: flash_border;_x000D_
  animation-duration: 2s;_x000D_
  animation-timing-function: linear;_x000D_
  animation-iteration-count: infinite;_x000D_
  -webkit-animation-name: flash_border;_x000D_
  -webkit-animation-duration: 2s;_x000D_
  -webkit-animation-timing-function: linear;_x000D_
  -webkit-animation-iteration-count: infinite;_x000D_
  -moz-animation-name: flash_border;_x000D_
  -moz-animation-duration: 2s;_x000D_
  -moz-animation-timing-function: linear;_x000D_
  -moz-animation-iteration-count: infinite;_x000D_
}_x000D_
_x000D_
@keyframes flash_border {_x000D_
  0% {_x000D_
    border-color: red;_x000D_
  }_x000D_
  50% {_x000D_
    border-color: black;_x000D_
  }_x000D_
  100% {_x000D_
    border-color: red;_x000D_
  }_x000D_
}_x000D_
_x000D_
@-webkit-keyframes flash_border {_x000D_
  0% {_x000D_
    border-color: red;_x000D_
  }_x000D_
  50% {_x000D_
    border-color: black;_x000D_
  }_x000D_
  100% {_x000D_
    border-color: red;_x000D_
  }_x000D_
}_x000D_
_x000D_
@-moz-keyframes flash_border {_x000D_
  0% {_x000D_
    border-color: red;_x000D_
  }_x000D_
  50% {_x000D_
    border-color: black;_x000D_
  }_x000D_
  100% {_x000D_
    border-color: red;_x000D_
  }_x000D_
}
_x000D_
<div id="box">roll over me</div>
_x000D_
_x000D_
_x000D_

Add padding to HTML text input field

padding-right works for me in Firefox/Chrome on Windows but not in IE. Welcome to the wonderful world of IE standards non-compliance.

See: http://jsfiddle.net/SfPju/466/

HTML

<input type="text" class="foo" value="abcdefghijklmnopqrstuvwxyz"/>

CSS

.foo
{
    padding-right: 20px;
}

How to remove all files from directory without removing directory in Node.js

Yes, there is a module fs-extra. There is a method .emptyDir() inside this module which does the job. Here is an example:

const fsExtra = require('fs-extra')

fsExtra.emptyDirSync(fileDir)

There is also an asynchronous version of this module too. Anyone can check out the link.

How to find length of dictionary values

Sure. In this case, you'd just do:

length_key = len(d['key'])  # length of the list stored at `'key'` ...

It's hard to say why you actually want this, but, perhaps it would be useful to create another dict that maps the keys to the length of values:

length_dict = {key: len(value) for key, value in d.items()}
length_key = length_dict['key']  # length of the list stored at `'key'` ...

How do I set a Windows scheduled task to run in the background?

As noted by Mattias Nordqvist in the comments below, you can also select the radio button option "Run whether user is logged on or not". When saving the task, you will be prompted once for the user password. bambams noted that this wouldn't grant System permissions to the process, and also seems to hide the command window.


It's not an obvious solution, but to make a Scheduled Task run in the background, change the User running the task to "SYSTEM", and nothing will appear on your screen.

enter image description here

enter image description here

enter image description here

Simple Pivot Table to Count Unique Values

My approach to this problem was a little different than what I see here, so I'll share.

  1. (Make a copy of your data first)
  2. Concatenate the columns
  3. Remove duplicates on the concatenated column
  4. Last - pivot on the resulting set

Note: I would like to include images to make this even easier to understand but cant because this is my first post ;)

Shell script to send email

sendmail works for me on the mac (10.6.8)

echo "Hello" | sendmail -f [email protected] [email protected]

How to pass object with NSNotificationCenter

You'll have to use the "userInfo" variant and pass a NSDictionary object that contains the messageTotal integer:

NSDictionary* userInfo = @{@"total": @(messageTotal)};

NSNotificationCenter* nc = [NSNotificationCenter defaultCenter];
[nc postNotificationName:@"eRXReceived" object:self userInfo:userInfo];

On the receiving end you can access the userInfo dictionary as follows:

-(void) receiveTestNotification:(NSNotification*)notification
{
    if ([notification.name isEqualToString:@"TestNotification"])
    {
        NSDictionary* userInfo = notification.userInfo;
        NSNumber* total = (NSNumber*)userInfo[@"total"];
        NSLog (@"Successfully received test notification! %i", total.intValue);
    }
}

Get all child elements

Yes, you can use find_elements_by_ to retrieve children elements into a list. See the python bindings here: http://selenium-python.readthedocs.io/locating-elements.html

Example HTML:

<ul class="bar">
    <li>one</li>
    <li>two</li>
    <li>three</li>
</ul>

You can use the find_elements_by_ like so:

parentElement = driver.find_element_by_class_name("bar")
elementList = parentElement.find_elements_by_tag_name("li")

If you want help with a specific case, you can edit your post with the HTML you're looking to get parent and children elements from.

python-How to set global variables in Flask?

With:

global index_add_counter

You are not defining, just declaring so it's like saying there is a global index_add_counter variable elsewhere, and not create a global called index_add_counter. As you name don't exists, Python is telling you it can not import that name. So you need to simply remove the global keyword and initialize your variable:

index_add_counter = 0

Now you can import it with:

from app import index_add_counter

The construction:

global index_add_counter

is used inside modules' definitions to force the interpreter to look for that name in the modules' scope, not in the definition one:

index_add_counter = 0
def test():
  global index_add_counter # means: in this scope, use the global name
  print(index_add_counter)

What port is used by Java RMI connection?

All the answers so far are incorrect. The Registry normally uses port 1099, but you can change it. But that's not the end of the story. Remote objects also use ports, and not necessarily 1099.

If you don't specify a port when exporting, RMI uses a random port. The solution is therefore to specify a port number when exporting. And this is a port that needs opening in the firewall, if any.

  • In the case where your remote object extends UnicastRemoteObject, have its constructor call super(port) with some non-zero port number.

  • In the case where it doesn't extend UnicastRemoteObject, provide a non-zero port number to UnicastRemoteObject.exportObject().

There are several wrinkles to this.

  • If you aren't using socket factories, and you provide a non-zero port number when exporting your first remote object, RMI will automatically share that port with subsequently exported remote objects without specified port numbers, or specifying zero. That first remote object includes a Registry created with LocateRegistry.createRegistry(). So if you create a Registry on port 1099, all other objects exported from that JVM can share port 1099.

  • If you are using socket factories, your RMIServerSocketFactory must have a sensible implementation of equals() for port sharing to work, i.e. one that doesn't just rely on object identity via == or Object.equals().

  • If either you don't provide a server socket factory, or you do provide one with a sensible equals() method, but not both, you can use the same non-zero explicit port number for all remote objects, e.g. createRegistry(1099) followed by any number of super(1099) or exportObject(..., 1099) calls.

How can I set / change DNS using the command-prompt at windows 8

To change DNS to automatic via command, you can run the following command:

netsh interface ip set dns "Local Area Connection" dhcp

HTML Code for text checkbox '?'

Use the Unicode Character

&#10004;   =   ✔


Visual Studio Post Build Event - Copy to Relative Directory Location

Would it not make sense to use msbuild directly? If you are doing this with every build, then you can add a msbuild task at the end? If you would just like to see if you can’t find another macro value that is not showed on the Visual Studio IDE, you could switch on the msbuild options to diagnostic and that will show you all of the variables that you could use, as well as their current value.

To switch this on in visual studio, go to Tools/Options then scroll down the tree view to the section called Projects and Solutions, expand that and click on Build and Run, at the right their is a drop down that specify the build output verbosity, setting that to diagnostic, will show you what other macro values you could use.

Because I don’t quite know to what level you would like to go, and how complex you want your build to be, this might give you some idea. I have recently been doing build scripts, that even execute SQL code as part of the build. If you would like some more help or even some sample build scripts, let me know, but if it is just a small process you want to run at the end of the build, the perhaps going the full msbuild script is a bit of over kill.

Hope it helps Rihan

I am getting "java.lang.ClassNotFoundException: com.google.gson.Gson" error even though it is defined in my classpath

Well for me the problem got resolved by adding the jars in my APACHE/TOMCAT/lib folder ! .

Wait for a void async method

I know this is an old question, but this is still a problem I keep walking into, and yet there is still no clear solution to do this correctly when using async/await in an async void signature method.

However, I noticed that .Wait() is working properly inside the void method.

and since async void and void have the same signature, you might need to do the following.

void LoadBlahBlah()
{
    blah().Wait(); //this blocks
}

Confusingly enough async/await does not block on the next code.

async void LoadBlahBlah()
{
    await blah(); //this does not block
}

When you decompile your code, my guess is that async void creates an internal Task (just like async Task), but since the signature does not support to return that internal Tasks

this means that internally the async void method will still be able to "await" internally async methods. but externally unable to know when the internal Task is complete.

So my conclusion is that async void is working as intended, and if you need feedback from the internal Task, then you need to use the async Task signature instead.

hopefully my rambling makes sense to anybody also looking for answers.

Edit: I made some example code and decompiled it to see what is actually going on.

static async void Test()
{
    await Task.Delay(5000);
}

static async Task TestAsync()
{
    await Task.Delay(5000);
}

Turns into (edit: I know that the body code is not here but in the statemachines, but the statemachines was basically identical, so I didn't bother adding them)

private static void Test()
{
    <Test>d__1 stateMachine = new <Test>d__1();
    stateMachine.<>t__builder = AsyncVoidMethodBuilder.Create();
    stateMachine.<>1__state = -1;
    AsyncVoidMethodBuilder <>t__builder = stateMachine.<>t__builder;
    <>t__builder.Start(ref stateMachine);
}
private static Task TestAsync()
{
    <TestAsync>d__2 stateMachine = new <TestAsync>d__2();
    stateMachine.<>t__builder = AsyncTaskMethodBuilder.Create();
    stateMachine.<>1__state = -1;
    AsyncTaskMethodBuilder <>t__builder = stateMachine.<>t__builder;
    <>t__builder.Start(ref stateMachine);
    return stateMachine.<>t__builder.Task;
}

neither AsyncVoidMethodBuilder or AsyncTaskMethodBuilder actually have any code in the Start method that would hint of them to block, and would always run asynchronously after they are started.

meaning without the returning Task, there would be no way to check if it is complete.

as expected, it only starts the Task running async, and then it continues in the code. and the async Task, first it starts the Task, and then it returns it.

so I guess my answer would be to never use async void, if you need to know when the task is done, that is what async Task is for.

How to Set Opacity (Alpha) for View in Android

I guess you may have already found the answer, but if not (and for other developers), you can do it like this:

btnMybutton.getBackground().setAlpha(45);

Here I have set the opacity to 45. You can basically set it from anything between 0(fully transparent) to 255 (completely opaque)

How to suppress warnings globally in an R Script

I have replaced the printf calls with calls to warning in the C-code now. It will be effective in the version 2.17.2 which should be available tomorrow night. Then you should be able to avoid the warnings with suppressWarnings() or any of the other above mentioned methods.

suppressWarnings({ your code })

How can I make sticky headers in RecyclerView? (Without external lib)

you can get sticky header functionality by copying these 2 files into your project. i had no issues with this implementation:

  • can interact with the sticy header (tap/long press/swipe)
  • the sticky header hides and reveals itself properly...even if each view holder has a different height (some other answers here don't handle that properly, causing the wrong headers to show, or the headers to jump up and down)

see an example of the 2 files being used in this small github project i whipped up

Get current time as formatted string in Go?

https://golang.org/src/time/format.go specified For parsing time 15 is used for Hours, 04 is used for minutes, 05 for seconds.

For parsing Date 11, Jan, January is for months, 02, Mon, Monday for Day of the month, 2006 for year and of course MST for zone

But you can use this layout as well, which I find very simple. "Mon Jan 2 15:04:05 MST 2006"

    const layout = "Mon Jan 2 15:04:05 MST 2006"
    userTimeString := "Fri Dec 6 13:05:05 CET 2019"

    t, _ := time.Parse(layout, userTimeString)
    fmt.Println("Server: ", t.Format(time.RFC850))
    //Server:  Friday, 06-Dec-19 13:05:05 CET

    mumbai, _ := time.LoadLocation("Asia/Kolkata")
    mumbaiTime := t.In(mumbai)
    fmt.Println("Mumbai: ", mumbaiTime.Format(time.RFC850))
    //Mumbai:  Friday, 06-Dec-19 18:35:05 IST

DEMO

Add querystring parameters to link_to

In case you want to pass in a block, say, for a glyphicon button, as in the following:

<%= link_to my_url, class: "stuff" do %>
  <i class="glyphicon glyphicon-inbox></i> Nice glyph-button
<% end %>

Then passing querystrings params could be accomplished through:

<%= link_to url_for(params.merge(my_params: "value")), class: "stuff" do %>
  <i class="glyphicon glyphicon-inbox></i> Nice glyph-button
<% end %>

Regular expression negative lookahead

A negative lookahead says, at this position, the following regex can not match.

Let's take a simplified example:

a(?!b(?!c))

a      Match: (?!b) succeeds
ac     Match: (?!b) succeeds
ab     No match: (?!b(?!c)) fails
abe    No match: (?!b(?!c)) fails
abc    Match: (?!b(?!c)) succeeds

The last example is a double negation: it allows a b followed by c. The nested negative lookahead becomes a positive lookahead: the c should be present.

In each example, only the a is matched. The lookahead is only a condition, and does not add to the matched text.

Why use prefixes on member variables in C++ classes

Lately I have been tending to prefer m_ prefix instead of having no prefix at all, the reasons isn't so much that its important to flag member variables, but that it avoids ambiguity, say you have code like:

void set_foo(int foo) { foo = foo; }

That of cause doesn't work, only one foo allowed. So your options are:

  • this->foo = foo;

    I don't like it, as it causes parameter shadowing, you no longer can use g++ -Wshadow warnings, its also longer to type then m_. You also still run into naming conflicts between variables and functions when you have a int foo; and a int foo();.

  • foo = foo_; or foo = arg_foo;

    Been using that for a while, but it makes the argument lists ugly, documentation shouldn't have do deal with name disambiguity in the implementation. Naming conflicts between variables and functions also exist here.

  • m_foo = foo;

    API Documentation stays clean, you don't get ambiguity between member functions and variables and its shorter to type then this->. Only disadvantage is that it makes POD structures ugly, but as POD structures don't suffer from the name ambiguity in the first place, one doesn't need to use it with them. Having a unique prefix also makes a few search&replace operations easier.

  • foo_ = foo;

    Most of the advantages of m_ apply, but I reject it for aesthetic reasons, a trailing or leading underscore just makes the variable look incomplete and unbalanced. m_ just looks better. Using m_ is also more extendable, as you can use g_ for globals and s_ for statics.

PS: The reason why you don't see m_ in Python or Ruby is because both languages enforce the their own prefix, Ruby uses @ for member variables and Python requires self..

Uninstall Eclipse under OSX?

BTW. AppZapper is a great OSX tool for uninstalling apps and their preferences.

It sometimes comes a part of MacHeist

Android - Package Name convention

The package name is used for unique identification for your application.
Android uses the package name to determine if the application has been installed or not.
The general naming is:

com.companyname.applicationname

eg:

com.android.Camera

Get Month name from month number

You can get this in following way,

DateTimeFormatInfo mfi = new DateTimeFormatInfo();
string strMonthName = mfi.GetMonthName(8).ToString(); //August

Now, get first three characters

string shortMonthName = strMonthName.Substring(0, 3); //Aug

CSS: How to have position:absolute div inside a position:relative div not be cropped by an overflow:hidden on a container

I don't really see a way to do this as-is. I think you might need to remove the overflow:hidden from div#1 and add another div within div#1 (ie as a sibling to div#2) to hold your unspecified 'content' and add the overflow:hidden to that instead. I don't think that overflow can be (or should be able to be) over-ridden.

Check if a path represents a file or a folder

To check if a string represents a path or a file programatically, you should use API methods such as isFile(), isDirectory().

How does system understand whether there's a file or a folder?

I guess, the file and folder entries are kept in a data structure and it's managed by the file system.

How do I get the Back Button to work with an AngularJS ui-router state machine?

Can be solved using a simple directive "go-back-history", this one is also closing window in case of no previous history.

Directive usage

<a data-go-back-history>Previous State</a>

Angular directive declaration

.directive('goBackHistory', ['$window', function ($window) {
    return {
        restrict: 'A',
        link: function (scope, elm, attrs) {
            elm.on('click', function ($event) {
                $event.stopPropagation();
                if ($window.history.length) {
                    $window.history.back();
                } else {
                    $window.close();  
                }
            });
        }
    };
}])

Note: Working using ui-router or not.

VBA test if cell is in a range

From the Help:

Set isect = Application.Intersect(Range("rg1"), Range("rg2"))
If isect Is Nothing Then
    MsgBox "Ranges do not intersect"
Else
    isect.Select
End If

Hex transparency in colors

enter image description here

This might be very late answer. But this chart kills it.

All percentage values are mapped to the hexadecimal values.

http://online.sfsu.edu/chrism/hexval.html

unix - count of columns in file

If you have python installed you could try:

python -c 'import sys;f=open(sys.argv[1]);print len(f.readline().split("|"))' \
    stores.dat

How can I do an asc and desc sort using underscore.js?

You can use .sortBy, it will always return an ascending list:

_.sortBy([2, 3, 1], function(num) {
    return num;
}); // [1, 2, 3]

But you can use the .reverse method to get it descending:

var array = _.sortBy([2, 3, 1], function(num) {
    return num;
});

console.log(array); // [1, 2, 3]
console.log(array.reverse()); // [3, 2, 1]

Or when dealing with numbers add a negative sign to the return to descend the list:

_.sortBy([-3, -2, 2, 3, 1, 0, -1], function(num) {
    return -num;
}); // [3, 2, 1, 0, -1, -2, -3]

Under the hood .sortBy uses the built in .sort([handler]):

// Default is ascending:
[2, 3, 1].sort(); // [1, 2, 3]

// But can be descending if you provide a sort handler:
[2, 3, 1].sort(function(a, b) {
    // a = current item in array
    // b = next item in array
    return b - a;
});

Finding the last index of an array

Array starts from index 0 and ends at n-1.

static void Main(string[] args)
{
    int[] arr = { 1, 2, 3, 4, 5 };
    int length = arr.Length - 1;   // starts from 0 to n-1

    Console.WriteLine(length);     // this will give the last index.
    Console.Read();
}

How can I remove jenkins completely from linux

First - stop Jenkins service:

sudo service jenkins stop

Next - delete:

sudo apt-get remove --purge jenkins

If you used separate server for Jenkins, some GCP or AWS - just delete this server. Here is a video how to uninstall Jenkins from GCP Compute Engine https://youtu.be/D2HUFAc_Trw

Is it possible to style a select box?

This seems old but here a very interesting plugin - http://uniformjs.com

apache mod_rewrite is not working or not enabled

Please try

sudo a2enmod rewrite

or use correct apache restart command

sudo /etc/init.d/apache2 restart 

How to redirect output to a file and stdout

tee is perfect for this, but this will also do the job

ls -lr / > output | cat output

How to merge a list of lists with same type of items to a single list of items?

Do you mean this?

var listOfList = new List<List<int>>() {
    new List<int>() { 1, 2 },
    new List<int>() { 3, 4 },
    new List<int>() { 5, 6 }
};
var list = new List<int> { 9, 9, 9 };
var result = list.Concat(listOfList.SelectMany(x => x));

foreach (var x in result) Console.WriteLine(x);

Results in: 9 9 9 1 2 3 4 5 6

How to put an image in div with CSS?

With Javascript/Jquery:

  • load image with hidden img
  • when image has been loaded, get width and height
  • dynamically create a div and set width, height and background
  • remove the original img

      $(document).ready(function() {
        var image = $("<img>");
        var div = $("<div>")
        image.load(function() {
          div.css({
            "width": this.width,
            "height": this.height,
            "background-image": "url(" + this.src + ")"
          });
          $("#container").append(div);
        });
        image.attr("src", "test0.png");
      });
    

Eclipse won't compile/run java file

right click somewhere on the file or in project explorer and choose 'run as'->'java application'

Best way to unselect a <select> in jQuery?

Oh jquery.

Since there is yet a native javascript approach, I feel the need to provide one.

var select = document.querySelector('select'); //hopefully you'll use a better selector query
select.selectedIndex = 0; // or -1, 0 sets it to first option, -1 selects no options

And just to show you how much faster this is: benchmark

Convert integer into its character equivalent, where 0 => a, 1 => b, etc

Use String.fromCharCode. This returns a string from a Unicode value, which matches the first 128 characters of ASCII.

var a = String.fromCharCode(97);

Pandas - replacing column values

You can also try using apply with get method of dictionary, seems to be little faster than replace:

data['sex'] = data['sex'].apply({1:'Male', 0:'Female'}.get)

Testing with timeit:

%%timeit
data['sex'].replace([0,1],['Female','Male'],inplace=True)

Result:

The slowest run took 5.83 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 510 µs per loop

Using apply:

%%timeit
data['sex'] = data['sex'].apply({1:'Male', 0:'Female'}.get)

Result:

The slowest run took 5.92 times longer than the fastest. This could mean that an intermediate result is being cached.
1000 loops, best of 3: 331 µs per loop

Note: apply with dictionary should be used if all the possible values of the columns in the dataframe are defined in the dictionary else, it will have empty for those not defined in dictionary.

Could not load file or assembly 'EntityFramework' after downgrading EF 5.0.0.0 --> 4.3.1.0

After failed attempts to find references to EntityFramework in repositories.config and elsewhere, I stumbled upon a reference in Web.config as I was editing it to help with my diagnosis.

The bindingRedirect referenced 5.0.0.0 which was no longer installed and this appeared to be the source of the exception. Honestly, I did not add this reference to Web.config and, after trying to duplicate the error in a separate project, discovered that it is not added by the NuGet package installer so, I don't know why it was there but something added it.

<dependentAssembly>
  <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" culture="neutral" />
  <bindingRedirect oldVersion="0.0.0.0-5.0.0.0" newVersion="5.0.0.0" />
</dependentAssembly>

I decided to replace this with the equivalent element from a working project. NB the references to 5.0.0.0 are replaced with 4.3.1.0 in the following:

<dependentAssembly>
  <assemblyIdentity name="EntityFramework" publicKeyToken="b77a5c561934e089" culture="neutral" />
  <bindingRedirect oldVersion="0.0.0.0-4.3.1.0" newVersion="4.3.1.0" />
</dependentAssembly>

This worked!

I then decided to remove the dependentAssembly reference for the EntityFramework in its entirety.

It still worked!

So, I'm posting this here as a self-answered question in the hope that it helps someone else. If anyone can explain to me:

  • What added the dependentAssembly for EntityFramework to my Web.config
  • Any consequence(s) of removing these references

I'd be interested to learn.

Why is Git better than Subversion?

A few answers have alluded to these, but I want to make 2 points explicit:

1) The ability to do selective commits (for example, git add --patch). If your working directory contains multiple changes that are not part of the same logical change, Git makes it very easy to make a commit that includes only a portion of the changes. With Subversion, it is difficult.

2) The ability to commit without making the change public. In Subversion, any commit is immediately public, and thus irrevocable. This greatly limits the ability of the developer to "commit early, commit often".

Git is more than just a VCS; it's also a tool for developing patches. Subversion is merely a VCS.

CSS: transition opacity on mouse-out?

You're applying transitions only to the :hover pseudo-class, and not to the element itself.

.item {   
  height:200px;
  width:200px;
  background:red; 
  -webkit-transition: opacity 1s ease-in-out;
  -moz-transition: opacity 1s ease-in-out;
  -ms-transition: opacity 1s ease-in-out;
  -o-transition: opacity 1s ease-in-out;
  transition: opacity 1s ease-in-out;
}

.item:hover {
  zoom: 1;
  filter: alpha(opacity=50);
  opacity: 0.5;
}

Demo: http://jsfiddle.net/7uR8z/6/

If you don't want the transition to affect the mouse-over event, but only mouse-out, you can turn transitions off for the :hover state :

.item:hover {
  -webkit-transition: none;
  -moz-transition: none;
  -ms-transition: none;
  -o-transition: none;
  transition: none;
  zoom: 1;
  filter: alpha(opacity=50);
  opacity: 0.5;
}

Demo: http://jsfiddle.net/7uR8z/3/

How to save a Seaborn plot into a file

This works for me

import seaborn as sns
import matplotlib.pyplot as plt
%matplotlib inline

sns.factorplot(x='holiday',data=data,kind='count',size=5,aspect=1)
plt.savefig('holiday-vs-count.png')

About catching ANY exception

Apart from a bare except: clause (which as others have said you shouldn't use), you can simply catch Exception:

import traceback
import logging

try:
    whatever()
except Exception as e:
    logging.error(traceback.format_exc())
    # Logs the error appropriately. 

You would normally only ever consider doing this at the outermost level of your code if for example you wanted to handle any otherwise uncaught exceptions before terminating.

The advantage of except Exception over the bare except is that there are a few exceptions that it wont catch, most obviously KeyboardInterrupt and SystemExit: if you caught and swallowed those then you could make it hard for anyone to exit your script.

How to configure encoding in Maven?

This would be in addition to previous, if someone meets a problem with scandic letters that isn't solved with the solution above.

If the java source files contain scandic letters they need to be interpreted correctly by the Java used for compiling. (e.g. scandic letters used in constants)

Even that the files are stored in UTF-8 and the Maven is configured to use UTF-8, the System Java used by the Maven will still use the system default (eg. in Windows: cp1252).

This will be visible only running the tests via maven (possibly printing the values of these constants in tests. The printed scandic letters would show as '< ?>') If not tested properly, this would corrupt the class files as compile result and be left unnoticed.

To prevent this, you have to set the Java used for compiling to use UTF-8 encoding. It is not enough to have the encoding settings in the maven pom.xml, you need to set the environment variable: JAVA_TOOL_OPTIONS = -Dfile.encoding=UTF8

Also, if using Eclipse in Windows, you may need to set the encoding used in addition to this (if you run individual test via eclipse).

How to recursively find the latest modified file in a directory?

Instead of sorting the results and keeping only the last modified ones, you could use awk to print only the one with greatest modification time (in unix time):

find . -type f -printf "%T@\0%p\0" | awk '
    {
        if ($0>max) {
            max=$0; 
            getline mostrecent
        } else 
            getline
    } 
    END{print mostrecent}' RS='\0'

This should be a faster way to solve your problem if the number of files is big enough.

I have used the NUL character (i.e. '\0') because, theoretically, a filename may contain any character (including space and newline) but that.

If you don't have such pathological filenames in your system you can use the newline character as well:

find . -type f -printf "%T@\n%p\n" | awk '
    {
        if ($0>max) {
            max=$0; 
            getline mostrecent
        } else 
            getline
    } 
    END{print mostrecent}' RS='\n'

In addition, this works in mawk too.

How to query nested objects?

db.messages.find( { headers : { From: "[email protected]" } } )

This queries for documents where headers equals { From: ... }, i.e. contains no other fields.


db.messages.find( { 'headers.From': "[email protected]" } )

This only looks at the headers.From field, not affected by other fields contained in, or missing from, headers.


Dot-notation docs