Programs & Examples On #Qsub

Qsub is a job submission command for high performance computing jobs.

How to fix symbol lookup error: undefined symbol errors in a cluster environment

After two dozens of comments to understand the situation, it was found that the libhdf5.so.7 was actually a symlink (with several levels of indirection) to a file that was not shared between the queued processes and the interactive processes. This means even though the symlink itself lies on a shared filesystem, the contents of the file do not and as a result the process was seeing different versions of the library.

For future reference: other than checking LD_LIBRARY_PATH, it's always a good idea to check a library with nm -D to see if the symbols actually exist. In this case it was found that they do exist in interactive mode but not when run in the queue. A quick md5sum revealed that the files were actually different.

set environment variable in python script

Compact solution (provided you don't need other environment variables):

call('sqsub -np {} /homedir/anotherdir/executable'.format(var1).split(),
      env=dict(LD_LIBRARY_PATH=my_path))

Using the env command line tool:

call('env LD_LIBRARY_PATH=my_path sqsub -np {} /homedir/anotherdir/executable'.format(var1).split())

How can I mix LaTeX in with Markdown?

Have you tried with Pandoc?

EDIT:

Although the documentation has become a bit complex, pandoc has supported inline LaTeX and LaTeX templates for 10 years.

Documents like the following one can be written in Markdown:

---
title: Just say hello!
author: My Friend
header-includes: |
    \usepackage{tikz,pgfplots}
    \usepackage{fancyhdr}
    \pagestyle{fancy}
    \fancyhead[CO,CE]{This is fancy}
    \fancyfoot[CO,CE]{So is this}
    \fancyfoot[LE,RO]{\thepage}
abstract: This is a pandoc test with Markdown + inline LaTeX
---

Just say hello!
===============

This could be a good example or inlined \LaTeX:

\begin{tikzpicture}
\begin{axis}
\addplot[color=red]{exp(x)};
\end{axis}
\end{tikzpicture}
%Here ends the furst plot
\hskip 5pt
%Here begins the 3d plot
\begin{tikzpicture}
\begin{axis}
\addplot3[
    surf,
]
{exp(-x^2-y^2)*x};
\end{axis}
\end{tikzpicture}

And now, just a few words to terminate:

> Goodbye folks!

Which can be converted to LaTeX using commands like this: pandoc -s -i Hello.md -o Hello.tex

Following is an image of the converted Hello.md to Hello.pdf file using MiKTeX as LaTeX processor with the command: pandoc -s -i Hello.md -o Hello.pdf

enter image description here

Finally, there are some open source LaTeX templates like this one: https://github.com/Wandmalfarbe/pandoc-latex-template, that can be used for better formatting.

As always, the reader should dig deeper if he has less trivial use cases than presented here.

Effective swapping of elements of an array in Java

Use Collections.swap and Arrays.asList:

Collections.swap(Arrays.asList(arr), i, j);

Get and Set Screen Resolution

in Winforms, there is a Screen class you can use to get data about screen dimensions and color depth for all displays connected to the computer. Here's the docs page: http://msdn.microsoft.com/en-us/library/system.windows.forms.screen.aspx

CHANGING the screen resolution is trickier. There is a Resolution third party class that wraps the native code you'd otherwise hook into. Use its CResolution nested class to set the screen resolution to a new height and width; but understand that doing this will only work for height/width combinations the display actually supports (800x600, 1024x768, etc, not 817x435).

How to generate a HTML page dynamically using PHP?

I was wondering if/how I can 'create' a html page for each database row?

You just need to create one php file that generate an html template, what changes is the text based content on that page. In that page is where you can get a parameter (eg. row id) via POST or GET and then get the info form the database.

I'm assuming this would be better for SEO?

Search Engine as Google interpret that example.php?id=33 and example.php?id=44 are different pages, and yes, this way is better than single listing page from the SEO point of view, so you just need two php files at least (listing.php and single.php), because is better link this pages from the listing.php.

Extra advice:

example.php?id=33 is really ugly and not very seo friendly, maybe you need some url rewriting code. Something like example/properties/property-name is better ;)

Search and replace part of string in database

Update database and Set fieldName=Replace (fieldName,'FindString','ReplaceString')

How to add a line to a multiline TextBox?

@Casperah pointed out that i'm thinking about it wrong:

  • A TextBox doesn't have lines
  • it has text
  • that text can be split on the CRLF into lines, if requested
  • but there is no notion of lines

The question then is how to accomplish what i want, rather than what WinForms lets me.

There are subtle bugs in the other given variants:

  • textBox1.AppendText("Hello" + Environment.NewLine);
  • textBox1.AppendText("Hello" + "\r\n");
  • textBox1.Text += "Hello\r\n"
  • textbox1.Text += System.Environment.NewLine + "brown";

They either append or prepend a newline when one (might) not be required.

So, extension helper:

public static class WinFormsExtensions
{
   public static void AppendLine(this TextBox source, string value)
   {
      if (source.Text.Length==0)
         source.Text = value;
      else
         source.AppendText("\r\n"+value);
   }
}

So now:

textBox1.Clear();
textBox1.AppendLine("red");
textBox1.AppendLine("green");
textBox1.AppendLine("blue");

and

textBox1.AppendLine(String.Format("Processing file {0}", filename));

Note: Any code is released into the public domain. No attribution required.

import dat file into R

The dat file has some lines of extra information before the actual data. Skip them with the skip argument:

read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat", 
           header=TRUE, skip=3)

An easy way to check this if you are unfamiliar with the dataset is to first use readLines to check a few lines, as below:

readLines("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat", 
          n=10)
# [1] "Ozone data from CZ03 2009"   "Local time: GMT + 0"        
# [3] ""                            "Date        Hour      Value"
# [5] "01.01.2009 00:00       34.3" "01.01.2009 01:00       31.9"
# [7] "01.01.2009 02:00       29.9" "01.01.2009 03:00       28.5"
# [9] "01.01.2009 04:00       32.9" "01.01.2009 05:00       20.5"

Here, we can see that the actual data starts at [4], so we know to skip the first three lines.

Update

If you really only wanted the Value column, you could do that by:

as.vector(
    read.table("http://www.nilu.no/projects/ccc/onlinedata/ozone/CZ03_2009.dat",
               header=TRUE, skip=3)$Value)

Again, readLines is useful for helping us figure out the actual name of the columns we will be importing.

But I don't see much advantage to doing that over reading the whole dataset in and extracting later.

Convert double to string

a = 0.000006;
b = 6;
c = a/b;

textbox.Text = c.ToString("0.000000");

As you requested:

textbox.Text = c.ToString("0.######");

This will only display out to the 6th decimal place if there are 6 decimals to display.

How to add a Hint in spinner in XML

Step 1:

Your array looks like. last item your hint

Ex : private String[] yourArray = new String[] {"Staff", "Student","Your Hint"};

Step 2:

Create HintAdpater.java (Just copy & paste)

This class not return last item.. So your Hint not displays.

HintAdapter.java

package ajax.com.vvcoe.utils;

import android.content.Context;
import android.widget.ArrayAdapter;

import java.util.List;


public class HintAdapter  extends ArrayAdapter<String> {


public HintAdapter(Context context, int resource) {
    super(context, resource);
}

public HintAdapter(Context context, int resource, int textViewResourceId) {
    super(context, resource, textViewResourceId);
}

public HintAdapter(Context context, int resource, String[] objects) {
    super(context, resource, objects);
}

public HintAdapter(Context context, int resource, int textViewResourceId, String[] objects) {
    super(context, resource, textViewResourceId, objects);
}

public HintAdapter(Context context, int resource, List<String> objects) {
    super(context, resource, objects);
}

public HintAdapter(Context context, int resource, int textViewResourceId, List<String> objects) {
    super(context, resource, textViewResourceId, objects);
}

@Override
public int getCount() {
    // don't display last item. It is used as hint.
    int count = super.getCount();
    return count > 0 ? count - 1 : count;
}
}

Step 3:

Set spinner adapter like this

    HintAdapter hintAdapter=new HintAdapter(this,android.R.layout.simple_list_item_1,yourArray);
    yourSpinner.setAdapter(hintAdapter);
    // show hint
    yourSpinner.setSelection(hintAdapter.getCount());

Credit goes to @Yakiv Mospan from this answer - https://stackoverflow.com/a/22774285/3879847

I modify some changes only..

How do I get the web page contents from a WebView?

You also need to annotate the method with @JavascriptInterface if your targetSdkVersion is >= 17 - because there is new security requirements in SDK 17, i.e. all javascript methods must be annotated with @JavascriptInterface. Otherwise you will see error like: Uncaught TypeError: Object [object Object] has no method 'processHTML' at null:1

Exception thrown in catch and finally clause

Finally clause is executed even when exception is thrown from anywhere in try/catch block.

Because it's the last to be executed in the main and it throws an exception, that's the exception that the callers see.

Hence the importance of making sure that the finally clause does not throw anything, because it can swallow exceptions from the try block.

Array functions in jQuery

The Visual jQuery site has some great examples of jQuery's array functionality. (Click "Utilities" on the left-hand tab, and then "Array and Object operations".)

Error "can't use subversion command line client : svn" when opening android project checked out from svn

I use the IDE Phpstorm,but I think it maybe the same as AS.

1.You should reinstall the svn. And choose option modify. enter image description here

And next step,you can see the command line client tools.

Let's choose first one: Will be installed on local hard drive. enter image description here

2.Now restart you computer.

Go to the svn location,all the time it will be C:\Program Files\TortoiseSVN\bin.

If you see the svn.exe in C:\Program Files\TortoiseSVN\bin,it proved that we reinstall command line client successfully. Copy C:\Program Files\TortoiseSVN\bin\svn.exe into the IDE.

enter image description here

3.Restart you IDE.It is ok!

How to connect to a MS Access file (mdb) using C#?

You should use "Microsoft OLE DB Provider for ODBC Drivers" to get to access to Microsoft Access. Here is the sample tutorial on using it

http://msdn.microsoft.com/en-us/library/aa288452(v=vs.71).aspx

Run function in script from command line (Node JS)

If your file just contains your function, for example:

myFile.js:

function myMethod(someVariable) {
    console.log(someVariable)
}

Calling it from the command line like this nothing will happen:

node myFile.js

But if you change your file:

myFile.js:

myMethod("Hello World");

function myMethod(someVariable) {
    console.log(someVariable)
}

Now this will work from the command line:

node myFile.js

enum - getting value of enum on string conversion

I implemented access using the following

class D(Enum):
    x = 1
    y = 2

    def __str__(self):
        return '%s' % self.value

now I can just do

print(D.x) to get 1 as result.

You can also use self.name in case you wanted to print x instead of 1.

How can you customize the numbers in an ordered list?

The other answers are better from a conceptual point of view. However, you can just left-pad the numbers with the appropriate number of '&ensp;' to make them line up.

* Note: I did not at first recognize that a numbered list was being used. I thought the list was being explicitly generated.

What is the cleanest way to ssh and run multiple commands in Bash?

For anyone stumbling over here like me - I had success with escaping the semicolon and the newline:

First step: the semicolon. This way, we do not break the ssh command:

ssh <host> echo test\;ls
                    ^ backslash!

Listed the remote hosts /home directory (logged in as root), whereas

ssh <host> echo test;ls
                    ^ NO backslash

listed the current working directory.

Next step: breaking up the line:

                      v another backslash!
ssh <host> echo test\;\
ls

This again listed the remote working directory - improved formatting:

ssh <host>\
  echo test\;\
  ls

If really nicer than here document or quotes around broken lines - well, not me to decide...

(Using bash, Ubuntu 14.04 LTS.)

How to select where ID in Array Rails ActiveRecord without exception

To avoid exceptions killing your app you should catch those exceptions and treat them the way you wish, defining the behavior for you app on those situations where the id is not found.

begin
  current_user.comments.find(ids)
rescue
  #do something in case of exception found
end

Here's more info on exceptions in ruby.

Web scraping with Python

You can use urllib2 to make the HTTP requests, and then you'll have web content.

You can get it like this:

import urllib2
response = urllib2.urlopen('http://example.com')
html = response.read()

Beautiful Soup is a python HTML parser that is supposed to be good for screen scraping.

In particular, here is their tutorial on parsing an HTML document.

Good luck!

Set Label Text with JQuery

I would just query for the for attribute instead of repetitively recursing the DOM tree.

$("input:checkbox").on("change", function() {
    $("label[for='"+this.id+"']").text("TESTTTT");
});

How to count objects in PowerShell?

This will get you count:

get-alias | measure

You can work with the result as with object:

$m = get-alias | measure
$m.Count

And if you would like to have aliases in some variable also, you can use Tee-Object:

$m = get-alias | tee -Variable aliases | measure
$m.Count
$aliases

Some more info on Measure-Object cmdlet is on Technet.

Do not confuse it with Measure-Command cmdlet which is for time measuring. (again on Technet)

Pipe output and capture exit status in Bash

By combining PIPESTATUS[0] and the result of executing the exit command in a subshell, you can directly access the return value of your initial command:

command | tee ; ( exit ${PIPESTATUS[0]} )

Here's an example:

# the "false" shell built-in command returns 1
false | tee ; ( exit ${PIPESTATUS[0]} )
echo "return value: $?"

will give you:

return value: 1

How to get all options of a select using jQuery?

If you're looking for all options with some selected text then the below code will work.

$('#test').find("select option:contains('B')").filter(":selected");

java.text.ParseException: Unparseable date

Your pattern does not correspond to the input string at all... It is not surprising that it does not work. This would probably work better:

SimpleDateFormat sdf = new SimpleDateFormat("EE MMM dd HH:mm:ss z yyyy",
                                            Locale.ENGLISH);

Then to print with your required format you need a second SimpleDateFormat:

Date parsedDate = sdf.parse(date);
SimpleDateFormat print = new SimpleDateFormat("MMM d, yyyy HH:mm:ss");
System.out.println(print.format(parsedDate));

Notes:

  • you should include the locale as if your locale is not English, the day name might not be recognised
  • IST is ambiguous and can lead to problems so you should use the proper time zone name if possible in your input.

Edit and replay XHR chrome/firefox etc?

Updating/completing zszep answer:

After copying the request as cUrl (bash), simply import it in the Postman App:

enter image description here

Deserialize JSON into C# dynamic object?

Try this:

  var units = new { Name = "Phone", Color= "White" };
    var jsonResponse = JsonConvert.DeserializeAnonymousType(json, units);

How to center a checkbox in a table cell?

_x000D_
_x000D_
<link href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
_x000D_
<table class="table table-bordered">_x000D_
  <thead>_x000D_
    <tr>_x000D_
      <th></th>_x000D_
      <th class="text-center">Left</th>_x000D_
      <th class="text-center">Center</th>_x000D_
      <th class="text-center">Right</th>_x000D_
    </tr>_x000D_
  </thead>_x000D_
  <tbody>_x000D_
    <tr>_x000D_
      <th>_x000D_
        <span>Bootstrap (class="text-left")</span>_x000D_
      </th>_x000D_
      <td class="text-left">_x000D_
        <input type="checkbox" />_x000D_
      </td>_x000D_
      <td class="text-center">_x000D_
        <input type="checkbox" checked />_x000D_
      </td>_x000D_
      <td class="text-right">_x000D_
        <input type="checkbox" />_x000D_
      </td>_x000D_
    </tr>_x000D_
    <tr>_x000D_
      <th>_x000D_
        <span>HTML attribute (align="left")</span>_x000D_
      </th>_x000D_
      <td align="left">_x000D_
        <input type="checkbox" />_x000D_
      </td>_x000D_
      <td align="center">_x000D_
        <input type="checkbox" checked />_x000D_
      </td>_x000D_
      <td align="right">_x000D_
        <input type="checkbox" />_x000D_
      </td>_x000D_
    </tr>_x000D_
  </tbody>_x000D_
</table>
_x000D_
_x000D_
_x000D_

How to Sign an Already Compiled Apk

create a key using

keytool -genkey -v -keystore my-release-key.keystore -alias alias_name -keyalg RSA -keysize 2048 -validity 10000

then sign the apk using :

jarsigner -verbose -sigalg SHA1withRSA -digestalg SHA1 -keystore my-release-key.keystore my_application.apk alias_name

check here for more info

MVC 4 client side validation not working

I created this html <form action="/StudentInfo/Edit/2" method="post" novalidate="novalidate"> where the novalidate="novalidate" was preventing the client-side jQuery from executing, when I removed novalidate="novalidate", client-side jQuery was enabled and stared working.

Mockito How to mock and assert a thrown exception?

Unrelated to mockito, one can catch the exception and assert its properties. To verify that the exception did happen, assert a false condition within the try block after the statement that throws the exception.

How to format column to number format in Excel sheet?

This will format column A as text, B as General, C as a number.

Sub formatColumns()
 Columns(1).NumberFormat = "@"
 Columns(2).NumberFormat = "General"
 Columns(3).NumberFormat = "0"
End Sub

Android Activity without ActionBar

Please find the default theme in styles.xml

<!-- Base application theme. -->
    <style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
        <!-- Customize your theme here. -->
        <item name="colorPrimary">@color/colorPrimary</item>
        <item name="colorPrimaryDark">@color/colorPrimaryDark</item>
        <item name="colorAccent">@color/colorAccent</item>
    </style>

And change parent this way

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">

How to represent a fix number of repeats in regular expression?

The finite repetition syntax uses {m,n} in place of star/plus/question mark.

From java.util.regex.Pattern:

X{n}      X, exactly n times
X{n,}     X, at least n times
X{n,m}    X, at least n but not more than m times

All repetition metacharacter have the same precedence, so just like you may need grouping for *, +, and ?, you may also for {n,m}.

  • ha* matches e.g. "haaaaaaaa"
  • ha{3} matches only "haaa"
  • (ha)* matches e.g. "hahahahaha"
  • (ha){3} matches only "hahaha"

Also, just like *, +, and ?, you can add the ? and + reluctant and possessive repetition modifiers respectively.

    System.out.println(
        "xxxxx".replaceAll("x{2,3}", "[x]")
    ); "[x][x]"

    System.out.println(
        "xxxxx".replaceAll("x{2,3}?", "[x]")
    ); "[x][x]x"

Essentially anywhere a * is a repetition metacharacter for "zero-or-more", you can use {...} repetition construct. Note that it's not true the other way around: you can use finite repetition in a lookbehind, but you can't use * because Java doesn't officially support infinite-length lookbehind.

References

Related questions

Adding a stylesheet to asp.net (using Visual Studio 2010)

Add your style here:

<%@ Master Language="C#" AutoEventWireup="true" CodeBehind="Site.master.cs" Inherits="BSC.SiteMaster" %>

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Strict//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-strict.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="en">
<head runat="server">
    <title></title>
    <link href="~/Styles/Site.css" rel="stylesheet" type="text/css" />
    <link href="~/Styles/NewStyle.css" rel="stylesheet" type="text/css" />

    <asp:ContentPlaceHolder ID="HeadContent" runat="server">
    </asp:ContentPlaceHolder>
</head>

Then in the page:

<asp:Table CssClass=NewStyleExampleClass runat="server" >

Use component from another module

Whatever you want to use from another module, just put it in the export array. Like this-

 @NgModule({
  declarations: [TaskCardComponent],
  exports: [TaskCardComponent],
  imports: [MdCardModule]
})

How to programmatically set the SSLContext of a JAX-WS client?

I tried the following and it didn't work on my environment:

bindingProvider.getRequestContext().put("com.sun.xml.internal.ws.transport.https.client.SSLSocketFactory", getCustomSocketFactory());

But different property worked like a charm:

bindingProvider.getRequestContext().put(JAXWSProperties.SSL_SOCKET_FACTORY, getCustomSocketFactory());

The rest of the code was taken from the first reply.

Absolute positioning ignoring padding of parent

First, let's see why this is happening.

The reason is that, surprisingly, when a box has position: absolute its containing box is the parent's padding box (that is, the box around its padding). This is surprising because usually (that is, when using static or relative positioning) the containing box is the parent's content box.

Here is the relevant part of the CSS specification:

In the case that the ancestor is an inline element, the containing block is the bounding box around the padding boxes of the first and the last inline boxes generated for that element.... Otherwise, the containing block is formed by the padding edge of the ancestor.

The simplest approach—as suggested in Winter's answer—is to use padding: inherit on the absolutely positioned div. It only works, though, if you don't want the absolutely positioned div to have any additional padding of its own. I think the most general-purpose solutions (in that both elements can have their own independent padding) are:

  1. Add an extra relatively positioned div (with no padding) around the absolutely positioned div. That new div will respect the padding of its parent, and the absolutely positioned div will then fill it.

    The downside, of course, is that you're messing with the HTML simply for presentational purposes.

  2. Repeat the padding (or add to it) on the absolutely positioned element.

    The downside here is that you have to repeat the values in your CSS, which is brittle if you're writing the CSS directly. However, if you're using a pre-processing tool like SASS or LESS you can avoid that problem by using a variable. This is the method I personally use.

git am error: "patch does not apply"

git format-patch also has the -B flag.

The description in the man page leaves much to be desired, but in simple language it's the threshold format-patch will abide to before doing a total re-write of the file (by a single deletion of everything old, followed by a single insertion of everything new).

This proved very useful for me when manual editing was too cumbersome, and the source was more authoritative than my destination.

An example:

git format-patch -B10% --stdout my_tag_name > big_patch.patch
git am -3 -i < big_patch.patch

Remove duplicates from dataframe, based on two columns A,B, keeping row with max value in another column C

You can do this simply by using pandas drop duplicates function

df.drop_duplicates(['A','B'],keep= 'last')

How to generate random positive and negative numbers in Java

(Math.floor((Math.random() * 2)) > 0 ? 1 : -1) * Math.floor((Math.random() * 32767))

mysql query result in php variable

$query="SELECT * FROM contacts";
$result=mysql_query($query);

Clear all fields in a form upon going back with browser back button

I came across this post while searching for a way to clear the entire form related to the BFCache (back/forward button cache) in Chrome.

In addition to what Sim supplied, my use case required that the details needed to be combined with Clear Form on Back Button?.

I found that the best way to do this is in allow the form to behave as it expects, and to trigger an event:

$(window).bind("pageshow", function() {
    var form = $('form'); 
    // let the browser natively reset defaults
    form[0].reset();
});

If you are not handling the input events to generate an object in JavaScript, or something else for that matter, then you are done. However, if you are listening to the events, then at least in Chrome you need to trigger a change event yourself (or whatever event you care to handle, including a custom one):

form.find(':input').not(':button,:submit,:reset,:hidden').trigger('change');

That must be added after the reset to do any good.

Prevent double curly brace notation from displaying momentarily before angular.js compiles/interpolates document

You also can use ng-attr-src="{{variable}}" instead of src="{{variable}}" and the attribute will only be generated once the compiler compiled the templates. This is mentioned here in the documentation: https://docs.angularjs.org/guide/directive#-ngattr-attribute-bindings

sub and gsub function?

That won't work if the string contains more than one match... try this:

echo "/x/y/z/x" | awk '{ gsub("/", "_") ; system( "echo "  $0) }'

or better (if the echo isn't a placeholder for something else):

echo "/x/y/z/x" | awk '{ gsub("/", "_") ; print $0 }'

In your case you want to make a copy of the value before changing it:

echo "/x/y/z/x" | awk '{ c=$0; gsub("/", "_", c) ; system( "echo " $0 " " c )}'

@Scope("prototype") bean scope not creating new bean

You can create static class inside your controller like this :

    @Controller
    public class HomeController {
        @Autowired
        private LoginServiceConfiguration loginServiceConfiguration;

        @RequestMapping(value = "/view", method = RequestMethod.GET)
        public ModelAndView display(HttpServletRequest req) {
            ModelAndView mav = new ModelAndView("home");
            mav.addObject("loginAction", loginServiceConfiguration.loginAction());
            return mav;
        }


        @Configuration
        public static class LoginServiceConfiguration {

            @Bean(name = "loginActionBean")
            @Scope("prototype")
            public LoginAction loginAction() {
                return new LoginAction();
            }
        }
}

"The certificate chain was issued by an authority that is not trusted" when connecting DB in VM Role from Azure website

I ran into this error trying to run the profiler, even though my connection had Trust server certificate checked and I added TrustServerCertificate=True in the Advanced Section. I changed to an instance of SSMS running as administrator and the profiler started with no problem. (I previously had found that when my connections even to local took a long time to connect, running as administrator helped).

How to use onResume()?

onResume() is one of the methods called throughout the activity lifecycle. onResume() is the counterpart to onPause() which is called anytime an activity is hidden from view, e.g. if you start a new activity that hides it. onResume() is called when the activity that was hidden comes back to view on the screen.

You're question asks abou what method is used to restart an activity. onCreate() is called when the activity is first created. In practice, most activities persist in the background through a series of onPause() and onResume() calls. An activity is only really "restarted" by onRestart() if it is first fully stopped by calling onStop() and then brought back to life. Thus if you are not actually stopping activities with onStop() it is most likley you will be using onResume().

Read the android doc in the above link to get a better understanding of the relationship between the different lifestyle methods. Regardless of which lifecycle method you end up using the general format is the same. You must override the standard method and include your code, i.e. what you want the activity to do at that point, in the commented section.

@Override
public void onResume(){
 //will be executed onResume
}

Differences between unique_ptr and shared_ptr

unique_ptr
is a smart pointer which owns an object exclusively.

shared_ptr
is a smart pointer for shared ownership. It is both copyable and movable. Multiple smart pointer instances can own the same resource. As soon as the last smart pointer owning the resource goes out of scope, the resource will be freed.

Regular Expression Match to test for a valid year

In theory the 4 digit option is right. But in practice it might be better to have 1900-2099 range.

Additionally it need to be non-capturing group. Many comments and answers propose capturing grouping which is not proper IMHO. Because for matching it might work, but for extracting matches using regex it will extract 4 digit numbers and two digit (19 and 20) numbers also because of paranthesis.

This will work for exact matching using non-capturing groups:

(?:19|20)\d{2}

Format numbers to strings in Python

You can use C style string formatting:

"%d:%d:d" % (hours, minutes, seconds)

See here, especially: https://web.archive.org/web/20120415173443/http://diveintopython3.ep.io/strings.html

How to get the current working directory using python 3?

It seems that IDLE changes its current working dir to location of the script that is executed, while when running the script using cmd doesn't do that and it leaves CWD as it is.

To change current working dir to the one containing your script you can use:

import os
os.chdir(os.path.dirname(__file__))
print(os.getcwd())

The __file__ variable is available only if you execute script from file, and it contains path to the file. More on it here: Python __file__ attribute absolute or relative?

How to execute an .SQL script file using c#

I managed to work out the answer by reading the manual :)

This extract from the MSDN

The code example avoids a deadlock condition by calling p.StandardOutput.ReadToEnd before p.WaitForExit. A deadlock condition can result if the parent process calls p.WaitForExit before p.StandardOutput.ReadToEnd and the child process writes enough text to fill the redirected stream. The parent process would wait indefinitely for the child process to exit. The child process would wait indefinitely for the parent to read from the full StandardOutput stream.

There is a similar issue when you read all text from both the standard output and standard error streams. For example, the following C# code performs a read operation on both streams.

Turns the code into this;

Process p = new Process();
p.StartInfo.UseShellExecute = false;
p.StartInfo.RedirectStandardOutput = true;
p.StartInfo.FileName = "sqlplus";
p.StartInfo.Arguments = string.Format("xxx/xxx@{0} @{1}", in_database, s);

bool started = p.Start();
// important ... read stream input before waiting for exit.
// this avoids deadlock.
string output = p.StandardOutput.ReadToEnd();

p.WaitForExit();

Console.WriteLine(output);

if (p.ExitCode != 0)
{
    Console.WriteLine( string.Format("*** Failed : {0} - {1}",s,p.ExitCode));
    break;
}

Which now exits correctly.

How to use sed/grep to extract text between two words?

You can use two s commands

$ echo "Here is a String" | sed 's/.*Here//; s/String.*//'
 is a 

Also works

$ echo "Here is a StringHere is a String" | sed 's/.*Here//; s/String.*//'
 is a

$ echo "Here is a StringHere is a StringHere is a StringHere is a String" | sed 's/.*Here//; s/String.*//'
 is a 

Default property value in React component using TypeScript

Default props with class component

Using static defaultProps is correct. You should also be using interfaces, not classes, for the props and state.

Update 2018/12/1: TypeScript has improved the type-checking related to defaultProps over time. Read on for latest and greatest usage down to older usages and issues.

For TypeScript 3.0 and up

TypeScript specifically added support for defaultProps to make type-checking work how you'd expect. Example:

interface PageProps {
  foo: string;
  bar: string;
}

export class PageComponent extends React.Component<PageProps, {}> {
    public static defaultProps = {
        foo: "default"
    };

    public render(): JSX.Element {
        return (
            <span>Hello, { this.props.foo.toUpperCase() }</span>
        );
    }
}

Which can be rendered and compile without passing a foo attribute:

<PageComponent bar={ "hello" } />

Note that:

  • foo is not marked optional (ie foo?: string) even though it's not required as a JSX attribute. Marking as optional would mean that it could be undefined, but in fact it never will be undefined because defaultProps provides a default value. Think of it similar to how you can mark a function parameter optional, or with a default value, but not both, yet both mean the call doesn't need to specify a value. TypeScript 3.0+ treats defaultProps in a similar way, which is really cool for React users!
  • The defaultProps has no explicit type annotation. Its type is inferred and used by the compiler to determine which JSX attributes are required. You could use defaultProps: Pick<PageProps, "foo"> to ensure defaultProps matches a sub-set of PageProps. More on this caveat is explained here.
  • This requires @types/react version 16.4.11 to work properly.

For TypeScript 2.1 until 3.0

Before TypeScript 3.0 implemented compiler support for defaultProps you could still make use of it, and it worked 100% with React at runtime, but since TypeScript only considered props when checking for JSX attributes you'd have to mark props that have defaults as optional with ?. Example:

interface PageProps {
    foo?: string;
    bar: number;
}

export class PageComponent extends React.Component<PageProps, {}> {
    public static defaultProps: Partial<PageProps> = {
        foo: "default"
    };

    public render(): JSX.Element {
        return (
            <span>Hello, world</span>
        );
    }
}

Note that:

  • It's a good idea to annotate defaultProps with Partial<> so that it type-checks against your props, but you don't have to supply every required property with a default value, which makes no sense since required properties should never need a default.
  • When using strictNullChecks the value of this.props.foo will be possibly undefined and require a non-null assertion (ie this.props.foo!) or type-guard (ie if (this.props.foo) ...) to remove undefined. This is annoying since the default prop value means it actually will never be undefined, but TS didn't understand this flow. That's one of the main reasons TS 3.0 added explicit support for defaultProps.

Before TypeScript 2.1

This works the same but you don't have Partial types, so just omit Partial<> and either supply default values for all required props (even though those defaults will never be used) or omit the explicit type annotation completely.

Default props with Functional Components

You can use defaultProps on function components as well, but you have to type your function to the FunctionComponent (StatelessComponent in @types/react before version 16.7.2) interface so that TypeScript knows about defaultProps on the function:

interface PageProps {
  foo?: string;
  bar: number;
}

const PageComponent: FunctionComponent<PageProps> = (props) => {
  return (
    <span>Hello, {props.foo}, {props.bar}</span>
  );
};

PageComponent.defaultProps = {
  foo: "default"
};

Note that you don't have to use Partial<PageProps> anywhere because FunctionComponent.defaultProps is already specified as a partial in TS 2.1+.

Another nice alternative (this is what I use) is to destructure your props parameters and assign default values directly:

const PageComponent: FunctionComponent<PageProps> = ({foo = "default", bar}) => {
  return (
    <span>Hello, {foo}, {bar}</span>
  );
};

Then you don't need the defaultProps at all! Be aware that if you do provide defaultProps on a function component it will take precedence over default parameter values, because React will always explicitly pass the defaultProps values (so the parameters are never undefined, thus the default parameter is never used.) So you'd use one or the other, not both.

Detect Scroll Up & Scroll down in ListView

My solution works perfectly giving the exact value for each scroll direction. distanceFromFirstCellToTop contains the exact distance from the first cell to the top of the parent View. I save this value in previousDistanceFromFirstCellToTop and as I scroll I compare it with the new value. If it's lower then I scrolled up, else, I scrolled down.

private int previousDistanceFromFirstCellToTop;

listview.setOnScrollListener(new OnScrollListener() {

    @Override
    public void onScrollStateChanged(AbsListView view, int scrollState) {

    }

    @Override
    public void onScroll(AbsListView view, int firstVisibleItem, int visibleItemCount, int totalItemCount) {
        View firstCell = listview.getChildAt(0);
        int distanceFromFirstCellToTop = listview.getFirstVisiblePosition() * firstCell.getHeight() - firstCell.getTop();

        if(distanceFromFirstCellToTop < previousDistanceFromFirstCellToTop)
        {
           //Scroll Up
        }
        else if(distanceFromFirstCellToTop  > previousDistanceFromFirstCellToTop)
        {
           //Scroll Down
        }
        previousDistanceFromFirstCellToTop = distanceFromFirstCellToTop;
    }
});

For Xamarin developers, the solution is the following:

Note: don't forget to run on UI thread

listView.Scroll += (o, e) =>
{
    View firstCell = listView.GetChildAt(0);
    int distanceFromFirstCellToTop = listView.FirstVisiblePosition * firstCell.Height - firstCell.Top;

    if (distanceFromFirstCellToTop < previousDistanceFromFirstCellToTop)
    {
        //Scroll Up
    }
    else if (distanceFromFirstCellToTop > previousDistanceFromFirstCellToTop)
    {
        //Scroll Down
    }
    previousDistanceFromFirstCellToTop = distanceFromFirstCellToTop;
};

Running a command as Administrator using PowerShell?

You can also force the application to open as administrator, if you have an administrator account, of course.

enter image description here

Locate the file, right click > properties > Shortcut > Advanced and check Run as Administrator

Then Click OK.

How to delete stuff printed to console by System.out.println()?

Just to add to BalusC's anwswer...

Invoking System.out.print("\b \b") repeatedly with a delay gives an exact same behavior as when we hit backspaces in {Windows 7 command console / Java 1.6}

Output data from all columns in a dataframe in pandas

In ipython, I use this to print a part of the dataframe that works quite well (prints the first 100 rows):

print paramdata.head(100).to_string()

jQuery multiselect drop down menu

Are you looking to do something like this http://jsfiddle.net/robert/xhHkG/

$('#transactionType').attr({
    'multiple': true,
    'size' : 10
});

Put that in a $(function() {...}) or some other onload

Edit

Reread your question, you're not really looking for a multiple select... but a dropdown box that allows you to select multiple. Yeah, probably best to use a plugin for that or write it from the ground up, it's not a "quick answer" type deal though.

Facebook API error 191

Something I'd like to add, since this is error 191 first question on google:

When redirecting to facebook instead of your own site for a signed request, you might experience this error if the user has secure browsing on and your app does redirect to facebook without SSL.

How to find the statistical mode?

Adding in raster::modal() as an option, although note that raster is a hefty package and may not be worth installing if you don't do geospatial work.

The source code could be pulled out of https://github.com/rspatial/raster/blob/master/src/modal.cpp and https://github.com/rspatial/raster/blob/master/R/modal.R into a personal R package, for those who are particularly keen.

export html table to csv

Using just jQuery, vanilla Javascript, and the table2CSV library:

export-to-html-table-as-csv-file-using-jquery

Put this code into a script to be loaded in the head section:

 $(document).ready(function () {
    $('table').each(function () {
        var $table = $(this);

        var $button = $("<button type='button'>");
        $button.text("Export to spreadsheet");
        $button.insertAfter($table);

        $button.click(function () {
            var csv = $table.table2CSV({
                delivery: 'value'
            });
            window.location.href = 'data:text/csv;charset=UTF-8,' 
            + encodeURIComponent(csv);
        });
    });
})

Notes:

Requires jQuery and table2CSV: Add script references to both libraries before the script above.

The table selector is used as an example, and can be adjusted to suit your needs.

It only works in browsers with full Data URI support: Firefox, Chrome and Opera, not in IE, which only supports Data URIs for embedding binary image data into a page.

For full browser compatibility you would have to use a slightly different approach that requires a server side script to echo the CSV.

Importing a long list of constants to a Python file

Python isn't preprocessed. You can just create a file myconstants.py:

MY_CONSTANT = 50

And importing them will just work:

import myconstants
print myconstants.MY_CONSTANT * 2

Get all parameters from JSP page

The fastest way should be:

<%@ page import="java.util.Map" %>
Map<String, String[]> parameters = request.getParameterMap();
for (Map.Entry<String, String[]> entry : parameters.entrySet()) {
    if (entry.getKey().startsWith("question")) {
        String[] values = entry.getValue();
        // etc.

Note that you can't do:

for (Map.Entry<String, String[]> entry : 
     request.getParameterMap().entrySet()) { // WRONG!

for reasons explained here.

Python FileNotFound

try block should be around open. Not around prompt.

while True:
    prompt = input("\n Hello to Sudoku valitator,"
    "\n \n Please type in the path to your file and press 'Enter': ")
    try:
        sudoku = open(prompt, 'r').readlines()
    except FileNotFoundError:
        print("Wrong file or file path")
    else:
        break

Using a dispatch_once singleton model in Swift

From Apple Docs (Swift 3.0.1),

You can simply use a static type property, which is guaranteed to be lazily initialized only once, even when accessed across multiple threads simultaneously:

class Singleton {
    static let sharedInstance = Singleton()
}

If you need to perform additional setup beyond initialization, you can assign the result of the invocation of a closure to the global constant:

class Singleton {
    static let sharedInstance: Singleton = {
        let instance = Singleton()
        // setup code
        return instance
    }()
}

Return rows in random order

The usual method is to use the NEWID() function, which generates a unique GUID. So,

SELECT * FROM dbo.Foo ORDER BY NEWID();

How to create the branch from specific commit in different branch

You have the arguments in the wrong order:

git branch <branch-name> <commit>

and for that, it doesn't matter what branch is checked out; it'll do what you say. (If you omit the commit argument, it defaults to creating a branch at the same place as the current one.)

If you want to check out the new branch as you create it:

git checkout -b <branch> <commit>

with the same behavior if you omit the commit argument.

How to select a record and update it, with a single queryset in Django?

This answer compares the above two approaches. If you want to update many objects in a single line, go for:

# Approach 1
MyModel.objects.filter(field1='Computer').update(field2='cool')

Otherwise you would have to iterate over the query set and update individual objects:

#Approach 2    
objects = MyModel.objects.filter(field1='Computer')
for obj in objects:
    obj.field2 = 'cool'
    obj.save()
  1. Approach 1 is faster because, it makes only one database query, compared to approach 2 which makes 'n+1' database queries. (For n items in the query set)

  2. Fist approach makes one db query ie UPDATE, the second one makes two: SELECT and then UPDATE.

  3. The tradeoff is that, suppose you have any triggers, like updating updated_on or any such related fields, it will not be triggered on direct update ie approach 1.

  4. Approach 1 is used on a queryset, so it is possible to update multiple objects at once, not in the case of approach 2.

jQuery, checkboxes and .is(":checked")

Most fastest and easy way:

$('#myCheckbox').change(function(){
    alert(this.checked);
});

$el[0].checked;

$el - is jquery element of selection.

Enjoy!

Select Last Row in the Table

be aware that last(), latest() are not deterministic if you are looking for a sequential or event/ordered record. The last/recent records can have the exact same created_at timestamp, and which you get back is not deterministic. So do orderBy(id|foo)->first(). Other ideas/suggestions on how to be deterministic are welcome.

Photoshop text tool adds punctuation to the beginning of text

Select all text afected by this issue:

Window -> Character, click the icon next to hide the Character Window, Middle Western Features and select Left-to-right character direction.

How to handle configuration in Go

Just use standard go flags with iniflags.

Standard go flags have the following benefits:

  • Idiomatic.
  • Easy to use. Flags can be easily added and scattered across arbitrary packages your project uses.
  • Flags have out-of-the-box support for default values and description.
  • Flags provide standard 'help' output with default values and description.

The only drawback standard go flags have - is management problems when the number of flags used in your app becomes too large.

Iniflags elegantly solves this problem: just modify two lines in your main package and it magically gains support for reading flag values from ini file. Flags from ini files can be overriden by passing new values in command-line.

See also https://groups.google.com/forum/#!topic/golang-nuts/TByzyPgoAQE for details.

PostgreSQL next value of the sequences?

I tried this and it works perfectly

@Entity
public class Shipwreck {
  @Id
  @GeneratedValue(strategy = GenerationType.SEQUENCE, generator = "seq")
  @Basic(optional = false)
  @SequenceGenerator(name = "seq", sequenceName = "shipwreck_seq", allocationSize = 1)
  Long id;

....

CREATE SEQUENCE public.shipwreck_seq
    INCREMENT 1
    START 110
    MINVALUE 1
    MAXVALUE 9223372036854775807
    CACHE 1;

How to square all the values in a vector in R?

This is another simple way:

sq_data <- data**2

How to plot vectors in python using matplotlib

All nice solutions, borrowing and improvising for special case -> If you want to add a label near the arrowhead:


    arr = [2,3]
    txt = “Vector X”
    ax.annotate(txt, arr)
    ax.arrow(0, 0, *arr, head_width=0.05, head_length=0.1)

Installing Git on Eclipse

egit was included in Indigo (2011) and should be there in all future Eclipse versions after that.

Just go to ![(Help->Install New Software)]

Then Work with: --All Available Sites--

Then type egit underneath and wait (may take a while) ! Then click the checkbox and install.

What's the difference between a null pointer and a void pointer?

Void refers to the type. Basically the type of data that it points to is unknown.

Null refers to the value. It's essentially a pointer to nothing, and is invalid to use.

In PowerShell, how do I define a function in a file and call it from the PowerShell commandline?

Try this on the PowerShell command line:

. .\MyFunctions.ps1
A1

The dot operator is used for script include.

Pass Javascript variable to PHP via ajax

Pass the data like this to the ajax call (http://api.jquery.com/jQuery.ajax/):

data: { userID : userID }

And in your PHP do this:

if(isset($_POST['userID']))
{
    $uid = $_POST['userID'];

    // Do whatever you want with the $uid
}

isset() function's purpose is to check wheter the given variable exists, not to get its value.

Cannot deserialize instance of object out of START_ARRAY token in Spring Webservice

Taking for granted that the JSON you posted is actually what you are seeing in the browser, then the problem is the JSON itself.

The JSON snippet you have posted is malformed.

You have posted:

[{
        "name" : "shopqwe",
        "mobiles" : [],
        "address" : {
            "town" : "city",
            "street" : "streetqwe",
            "streetNumber" : "59",
            "cordX" : 2.229997,
            "cordY" : 1.002539
        },
        "shoe"[{
                "shoeName" : "addidas",
                "number" : "631744030",
                "producent" : "nike",
                "price" : 999.0,
                "sizes" : [30.0, 35.0, 38.0]
            }]

while the correct JSON would be:

[{
        "name" : "shopqwe",
        "mobiles" : [],
        "address" : {
            "town" : "city",
            "street" : "streetqwe",
            "streetNumber" : "59",
            "cordX" : 2.229997,
            "cordY" : 1.002539
        },
        "shoe" : [{
                "shoeName" : "addidas",
                "number" : "631744030",
                "producent" : "nike",
                "price" : 999.0,
                "sizes" : [30.0, 35.0, 38.0]
            }
        ]
    }
]

HTML form with two submit buttons and two "target" attributes

This might help someone:

Use the formtarget attribute

<html>
  <body>
    <form>
      <!--submit on a new window-->
      <input type="submit" formatarget="_blank" value="Submit to first" />
      <!--submit on the same window-->
      <input type="submit" formaction="_self" value="Submit to second" />
    </form>
  </body>
</html>

Setting PATH environment variable in OSX permanently

You have to add it to /etc/paths.

Reference (which works for me) : Here

Writing Python lists to columns in csv

You can use izip to combine your lists, and then iterate them

for val in itertools.izip(l1,l2,l3,l4,l5):
    writer.writerow(val)

how to convert date to a format `mm/dd/yyyy`

Use:

select convert(nvarchar(10), CREATED_TS, 101)

or

select format(cast(CREATED_TS as date), 'MM/dd/yyyy') -- MySQL 3.23 and above

What is the difference between match_parent and fill_parent?

For compatibility sake it's better to stick to fill_parent, i.e, when supporting below API 8 devices. But if your app targets API 8 and upwards, you should use match_parent instead.

Using generic std::function objects with member functions in one class

Unfortunately, C++ does not allow you to directly get a callable object referring to an object and one of its member functions. &Foo::doSomething gives you a "pointer to member function" which refers to the member function but not the associated object.

There are two ways around this, one is to use std::bind to bind the "pointer to member function" to the this pointer. The other is to use a lambda that captures the this pointer and calls the member function.

std::function<void(void)> f = std::bind(&Foo::doSomething, this);
std::function<void(void)> g = [this](){doSomething();};

I would prefer the latter.

With g++ at least binding a member function to this will result in an object three-pointers in size, assigning this to an std::function will result in dynamic memory allocation.

On the other hand, a lambda that captures this is only one pointer in size, assigning it to an std::function will not result in dynamic memory allocation with g++.

While I have not verified this with other compilers, I suspect similar results will be found there.

Detect if the device is iPhone X

I had to solve the same issue recently. And while this question is definitively answered ("No"), this may help others who need iPhone X specific layout behaviour.

I wasn't really interested in whether the device was iPhone X. I was interested in whether the device had a notched display.

private static var hasNotchedDisplay: Bool {
    if let window = UIApplication.shared.keyWindow {
        return (window.compatibleSafeAreaInsets.top > 20.0 || window.compatibleSafeAreaInsets.left > 0.0 || window.compatibleSafeAreaInsets.right > 0.0)
    }

    return false
}

You could also write a hasOnScreenHomeIndicator variable along the same lines (though check the bottom safe area, maybe?).

The above uses my extension on UIView for convenient access to the safe area insets on iOS 10 and earlier.

@objc public extension UIView {
    @objc public var compatibleSafeAreaInsets: UIEdgeInsets {
        if #available(iOS 11.0, *) {
            return safeAreaInsets
        } else {
            return .zero
        }
    }

    @objc public var compatibleSafeAreaLayoutGuide: UILayoutGuide {
        if #available(iOS 11.0, *) {
            return safeAreaLayoutGuide
        } else {
            return layoutMarginsGuide
        }
    }
}

What is http multipart request?

As the official specification says, "one or more different sets of data are combined in a single body". So when photos and music are handled as multipart messages as mentioned in the question, probably there is some plain text metadata associated as well, thus making the request containing different types of data (binary, text), which implies the usage of multipart.

Changing position of the Dialog on screen android

I used this code to show the dialog at the bottom of the screen:

Dialog dlg = <code to create custom dialog>;

Window window = dlg.getWindow();
WindowManager.LayoutParams wlp = window.getAttributes();

wlp.gravity = Gravity.BOTTOM;
wlp.flags &= ~WindowManager.LayoutParams.FLAG_DIM_BEHIND;
window.setAttributes(wlp);

This code also prevents android from dimming the background of the dialog, if you need it. You should be able to change the gravity parameter to move the dialog about


private void showPictureialog() {
    final Dialog dialog = new Dialog(this,
            android.R.style.Theme_Translucent_NoTitleBar);

    // Setting dialogview
    Window window = dialog.getWindow();
    window.setGravity(Gravity.CENTER);

    window.setLayout(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
    dialog.setTitle(null);
    dialog.setContentView(R.layout.selectpic_dialog);
    dialog.setCancelable(true);

    dialog.show();
}

you can customize you dialog based on gravity and layout parameters change gravity and layout parameter on the basis of your requirenment

How do pointer-to-pointer's work in C? (and when might you use them?)

You have a variable that contains an address of something. That's a pointer.

Then you have another variable that contains the address of the first variable. That's a pointer to pointer.

Using $window or $location to Redirect in AngularJS

I believe the way to do this is $location.url('/RouteTo/Login');

Edit for Clarity

Say my route for my login view was /Login, I would say $location.url('/Login') to navigate to that route.

For locations outside of the Angular app (i.e. no route defined), plain old JavaScript will serve:

window.location = "http://www.my-domain.com/login"

How to compile .c file with OpenSSL includes?

Use the -I flag to gcc properly.

gcc -I/path/to/openssl/ -o Opentest -lcrypto Opentest.c

The -I should point to the directory containing the openssl folder.

How can I remove all objects but one from the workspace in R?

I think another option is to open workspace in RStudio and then change list to grid at the top right of the environment(image below). Then tick the objects you want to clear and finally click on clear.

enter image description here

Accessing JSON object keys having spaces

The answer of Pardeep Jain can be useful for static data, but what if we have an array in JSON?

For example, we have i values and get the value of id field

alert(obj[i].id); //works!

But what if we need key with spaces?

In this case, the following construction can help (without point between [] blocks):

alert(obj[i]["No. of interfaces"]); //works too!

How to initialize a struct in accordance with C programming language standards

void function(void) {
  MY_TYPE a;
  a.flag = true;
  a.value = 15;
  a.stuff = 0.123;
}

Object creation on the stack/heap?

C++ offers three different ways to create objects:

  1. Stack-based such as temporary objects
  2. Heap-based by using new
  3. Static memory allocation such as global variables and namespace-scope objects

Consider your case,

Object* o;
o = new Object();

and:

Object* o = new Object();

Both forms are the same. This means that a pointer variable o is created on the stack (assume your variables does not belong to the 3 category above) and it points to a memory in the heap, which contains the object.

How to declare a variable in a template in Angular

It is much simpler, no need for anything additional. In my example I declare variable "open" and then use it.

   <mat-accordion class="accord-align" #open>
      <mat-expansion-panel hideToggle="true" (opened)="open.value=true" (closed)="open.value=false">
        <mat-expansion-panel-header>
          <span class="accord-title">Review Policy Summary</span>
          <span class="spacer"></span>
          <a *ngIf="!open.value" class="f-accent">SHOW</a>
          <a *ngIf="open.value" class="f-accent">HIDE</a>
        </mat-expansion-panel-header>
        <mat-divider></mat-divider>
        <!-- Quote Details Component -->
        <quote-details [quote]="quote"></quote-details>
      </mat-expansion-panel>
    </mat-accordion>

Python Matplotlib Y-Axis ticks on Right Side of Plot

For right labels use ax.yaxis.set_label_position("right"), i.e.:

f = plt.figure()
ax = f.add_subplot(111)
ax.yaxis.tick_right()
ax.yaxis.set_label_position("right")
plt.plot([2,3,4,5])
ax.set_xlabel("$x$ /mm")
ax.set_ylabel("$y$ /mm")
plt.show()

How to securely save username/password (local)?

This only works on Windows, so if you are planning to use dotnet core cross-platform, you'll have to look elsewhere. See https://github.com/dotnet/corefx/blob/master/Documentation/architecture/cross-platform-cryptography.md

How to delete rows from a pandas DataFrame based on a conditional expression

You can assign the DataFrame to a filtered version of itself:

df = df[df.score > 50]

This is faster than drop:

%%timeit
test = pd.DataFrame({'x': np.random.randn(int(1e6))})
test = test[test.x < 0]
# 54.5 ms ± 2.02 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit
test = pd.DataFrame({'x': np.random.randn(int(1e6))})
test.drop(test[test.x > 0].index, inplace=True)
# 201 ms ± 17.9 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

%%timeit
test = pd.DataFrame({'x': np.random.randn(int(1e6))})
test = test.drop(test[test.x > 0].index)
# 194 ms ± 7.03 ms per loop (mean ± std. dev. of 7 runs, 10 loops each)

Refresh a page using JavaScript or HTML

simply use..

location.reload(true/false);

If false, the page will be reloaded from cache, else from the server.

Get the element with the highest occurrence in an array

This function is generic function for every type of info. It counts the occurrence of the elements and then returns array with maximum occurring elements.

function mode () {
  var arr = [].slice.call(arguments);
  if ((args.length == 1) && (typeof args[0] === "object")) {
    args = args[0].mode();
  }

  var obj = {};
  for(var i = 0; i < arr.length; i++) {
    if(obj[arr[i]] === undefined) obj[arr[i]] = 1;
    else obj[arr[i]]++;
  }

  var max = 0;
  for (w in obj) {
    if (obj[w] > max) max = obj[w];
  }

  ret_val = [];
  for (w in obj) {
    if (obj[w] == max) ret_val.push(w);
  }

  return ret_val;
}

Pass array to ajax request in $.ajax()

info = [];
info[0] = 'hi';
info[1] = 'hello';


$.ajax({
   type: "POST",
   data: {info:info},
   url: "index.php",
   success: function(msg){
     $('.answer').html(msg);
   }
});

How to wrap text in textview in Android

In Android Studio 2.2.3 under the inputType property there is a property called textMultiLine. Selecting this option sorted out a similar problem for me. I hope that helps.

How to copy data from one HDFS to another HDFS?

distcp command use for copying from one cluster to another cluster in parallel. You have to set the path for namenode of src and path for namenode of dst, internally it use mapper.

Example:

$ hadoop distcp <src> <dst>

there few options you can set for distcp

-m for no. of mapper for copying data this will increase speed of copying.

-atomic for auto commit the data.

-update will only update data that is in old version.

There are generic command for copying files in hadoop are -cp and -put but they are use only when the data volume is less.

Bootstrap 3 scrollable div for table

You can use too

style="overflow-y: scroll; height:150px; width: auto;"

It's works for me

How to use jQuery to call an ASP.NET web service?

I don't know about that specific SharePoint web service, but you can decorate a page method or a web service with <WebMethod()> (in VB.NET) to ensure that it serializes to JSON. You can probably just wrap the method that webservice.asmx uses internally, in your own web service.

Dave Ward has a nice walkthrough on this.

How to get the HTML for a DOM element in javascript

old question but for newcomers that come around :

document.querySelector('div').outerHTML

Exception: Serialization of 'Closure' is not allowed

As already stated: closures, out of the box, cannot be serialized.

However, using the __sleep(), __wakeup() magic methods and reflection u CAN manually make closures serializable. For more details see extending-php-5-3-closures-with-serialization-and-reflection

This makes use of reflection and the php function eval. Do note this opens up the possibility of CODE injection, so please take notice of WHAT you are serializing.

jQuery Uncaught TypeError: Property '$' of object [object Window] is not a function

This is a syntax issue, the jQuery library included with WordPress loads in "no conflict" mode. This is to prevent compatibility problems with other javascript libraries that WordPress can load. In "no-confict" mode, the $ shortcut is not available and the longer jQuery is used, i.e.

jQuery(document).ready(function ($) {

By including the $ in parenthesis after the function call you can then use this shortcut within the code block.

For full details see WordPress Codex

How to Specify Eclipse Proxy Authentication Credentials?

For eclipse Mar1 : - Window > Preferences > General > Network connections. Choose "Manual" from drop down. Double click "HTTP" option and enter the Host, Port, Username and Password. Apply and Finish,,it will work as expected...

html5 <input type="file" accept="image/*" capture="camera"> display as image rather than "choose file" button

You have to use Javascript Filereader for this. (Introduction into filereader-api: http://www.html5rocks.com/en/tutorials/file/dndfiles/)

Once the user have choose a image you can read the file-path of the chosen image and place it into your html.

Example:

<form id="form1" runat="server">
    <input type='file' id="imgInp" />
    <img id="blah" src="#" alt="your image" />
</form>

Javascript:

function readURL(input) {
    if (input.files && input.files[0]) {
        var reader = new FileReader();

        reader.onload = function (e) {
            $('#blah').attr('src', e.target.result);
        }

        reader.readAsDataURL(input.files[0]);
    }
}

$("#imgInp").change(function(){
    readURL(this);
});

How to edit my Excel dropdown list?

Attribute_Brands is a named range.

On any worksheet (tab) press F5 and type Attribute_Brands into the reference box and click on the OK button.

This will take you to the named range.

The data in it can be updated by typing new values into the cells.

The named range can be altered via the 'Insert - Name - Define' menu.

No Persistence provider for EntityManager named

Had the same issue, but this actually worked for me :

mvn install -e  -Dmaven.repo.local=$WORKSPACE/.repository.

NB : The maven command above will reinstall all your project dependencies from scratch. Your console will be loaded with verbose logs due to the network request maven is making.

Auto-center map with multiple markers in Google Maps API v3

This work for me in Angular 9:

  import {GoogleMap, GoogleMapsModule} from "@angular/google-maps";
  @ViewChild('Map') Map: GoogleMap; /* Element Map */

  locations = [
   { lat: 7.423568, lng: 80.462287 },
   { lat: 7.532321, lng: 81.021187 },
   { lat: 6.117010, lng: 80.126269 }
  ];

  constructor() {
   var bounds = new google.maps.LatLngBounds();
    setTimeout(() => {
     for (let u in this.locations) {
      var marker = new google.maps.Marker({
       position: new google.maps.LatLng(this.locations[u].lat, 
       this.locations[u].lng),
      });
      bounds.extend(marker.getPosition());
     }

     this.Map.fitBounds(bounds)
    }, 200)
  }

And it automatically centers the map according to the indicated positions.

Result:

enter image description here

Printing out all the objects in array list

Override toString() method in Student class as below:

   @Override
   public String toString() {
        return ("StudentName:"+this.getStudentName()+
                    " Student No: "+ this.getStudentNo() +
                    " Email: "+ this.getEmail() +
                    " Year : " + this.getYear());
   }

A SELECT statement that assigns a value to a variable must not be combined with data-retrieval operations

declare @cur cursor
declare @idx int       
declare @Approval_No varchar(50) 

declare @ReqNo varchar(100)
declare @M_Id  varchar(100)
declare @Mail_ID varchar(100)
declare @temp  table
(
val varchar(100)
)
declare @temp2  table
(
appno varchar(100),
mailid varchar(100),
userod varchar(100)
)


    declare @slice varchar(8000)       
    declare @String varchar(100)
    --set @String = '1200096,1200095,1200094,1200093,1200092,1200092'
set @String = '20131'


    select @idx = 1       
        if len(@String)<1 or @String is null  return       

    while @idx!= 0       
    begin       
        set @idx = charindex(',',@String)       
        if @idx!=0       
            set @slice = left(@String,@idx - 1)       
        else       
            set @slice = @String

            --select @slice       
            insert into @temp values(@slice)
        set @String = right(@String,len(@String) - @idx)       
        if len(@String) = 0 break


    end
    -- select distinct(val) from @temp


SET @cur = CURSOR FOR select distinct(val) from @temp


--open cursor    
OPEN @cur    
--fetchng id into variable    
FETCH NEXT    
    FROM @cur into @Approval_No 

      --
    --loop still the end    
     while @@FETCH_STATUS = 0  
    BEGIN   


select distinct(Approval_Sr_No) as asd, @ReqNo=Approval_Sr_No,@M_Id=AM_ID,@Mail_ID=Mail_ID from WFMS_PRAO,WFMS_USERMASTER where  WFMS_PRAO.AM_ID=WFMS_USERMASTER.User_ID
and Approval_Sr_No=@Approval_No

   insert into @temp2 values(@ReqNo,@M_Id,@Mail_ID)  

FETCH NEXT    
      FROM @cur into @Approval_No    
 end  
    --close cursor    
    CLOSE @cur    

select * from @tem

html5 localStorage error with Safari: "QUOTA_EXCEEDED_ERR: DOM Exception 22: An attempt was made to add something to storage that exceeded the quota."

As mentioned in other answers, you'll always get the QuotaExceededError in Safari Private Browser Mode on both iOS and OS X when localStorage.setItem (or sessionStorage.setItem) is called.

One solution is to do a try/catch or Modernizr check in each instance of using setItem.

However if you want a shim that simply globally stops this error being thrown, to prevent the rest of your JavaScript from breaking, you can use this:

https://gist.github.com/philfreo/68ea3cd980d72383c951

// Safari, in Private Browsing Mode, looks like it supports localStorage but all calls to setItem
// throw QuotaExceededError. We're going to detect this and just silently drop any calls to setItem
// to avoid the entire page breaking, without having to do a check at each usage of Storage.
if (typeof localStorage === 'object') {
    try {
        localStorage.setItem('localStorage', 1);
        localStorage.removeItem('localStorage');
    } catch (e) {
        Storage.prototype._setItem = Storage.prototype.setItem;
        Storage.prototype.setItem = function() {};
        alert('Your web browser does not support storing settings locally. In Safari, the most common cause of this is using "Private Browsing Mode". Some settings may not save or some features may not work properly for you.');
    }
}

How to prune local tracking branches that do not exist on remote anymore

Based on the answers above I came with this one line solution:

git remote prune origin; git branch -r | awk '{print $1}' | egrep -v -f /dev/fd/0 <(git branch -vv | grep origin) | awk '{print $1}' | xargs git branch -d

Serialize object to query string in JavaScript/jQuery

Another option might be node-querystring.

It's available in both npm and bower, which is why I have been using it.

What Content-Type value should I send for my XML sitemap?

Other answers here address the general question of what the proper Content-Type for an XML response is, and conclude (as with What's the difference between text/xml vs application/xml for webservice response) that both text/xml and application/xml are permissible. However, none address whether there are any rules specific to sitemaps.

Answer: there aren't. The sitemap spec is https://www.sitemaps.org, and using Google site: searches you can confirm that it does not contain the words or phrases mime, mimetype, content-type, application/xml, or text/xml anywhere. In other words, it is entirely silent on the topic of what Content-Type should be used for serving sitemaps.

In the absence of any commentary in the sitemap spec directly addressing this question, we can safely assume that the same rules apply as when choosing the Content-Type of any other XML document - i.e. that it may be either text/xml or application/xml.

Invert match with regexp

Based on Daniel's answer, I think I've got something that works:

^(.(?!test))*$

The key is that you need to make the negative assertion on every character in the string

How to catch SQLServer timeout exceptions

When a client sends ABORT, no transactions are rolled back. To avoid this behavior we have to use SET_XACT_ABORT ON https://docs.microsoft.com/en-us/sql/t-sql/statements/set-xact-abort-transact-sql?view=sql-server-ver15

Creating SolidColorBrush from hex color value

using System.Windows.Media;

byte R = Convert.ToByte(color.Substring(1, 2), 16);
byte G = Convert.ToByte(color.Substring(3, 2), 16);
byte B = Convert.ToByte(color.Substring(5, 2), 16);
SolidColorBrush scb = new SolidColorBrush(Color.FromRgb(R, G, B));
//applying the brush to the background of the existing Button btn:
btn.Background = scb;

How can I get input radio elements to horizontally align?

In your case, you just need to remove the line breaks (<br> tags) between the elements - input elements are inline-block by default (in Chrome at least). (updated example).

<input type="radio" name="editList" value="always">Always
<input type="radio" name="editList" value="never">Never
<input type="radio" name="editList" value="costChange">Cost Change

I'd suggest using <label> elements, though. In doing so, clicking on the label will check the element too. Either associate the <label>'s for attribute with the <input>'s id: (example)

<input type="radio" name="editList" id="always" value="always"/>
<label for="always">Always</label>

<input type="radio" name="editList" id="never" value="never"/>
<label for="never">Never</label>

<input type="radio" name="editList" id="change" value="costChange"/>
<label for="change">Cost Change</label>

..or wrap the <label> elements around the <input> elements directly: (example)

<label>
    <input type="radio" name="editList" value="always"/>Always
</label>
<label>
    <input type="radio" name="editList" value="never"/>Never
</label>
<label>
    <input type="radio" name="editList" value="costChange"/>Cost Change
</label>

You can also get fancy and use the :checked pseudo class.

How to permanently remove few commits from remote branch

Simplifying from pctroll's answer, similarly based on this blog post.

# look up the commit id in git log or on github, e.g. 42480f3, then do
git checkout master
git checkout your_branch
git revert 42480f3
# a text editor will open, close it with ctrl+x (editor dependent)
git push origin your_branch
# or replace origin with your remote

Most efficient way to concatenate strings?

From Chinh Do - StringBuilder is not always faster:

Rules of Thumb

  • When concatenating three dynamic string values or less, use traditional string concatenation.

  • When concatenating more than three dynamic string values, use StringBuilder.

  • When building a big string from several string literals, use either the @ string literal or the inline + operator.

Most of the time StringBuilder is your best bet, but there are cases as shown in that post that you should at least think about each situation.

How to iterate over the file in python

This is probably because an empty line at the end of your input file.

Try this:

for x in f:
    try:
        print int(x.strip(),16)
    except ValueError:
        print "Invalid input:", x

Are there any naming convention guidelines for REST APIs?

No. REST has nothing to do with URI naming conventions. If you include these conventions as part of your API, out-of-band, instead of only via hypertext, then your API is not RESTful.

For more information, see http://roy.gbiv.com/untangled/2008/rest-apis-must-be-hypertext-driven

How to set custom favicon in Express?

If you want a solution that does not involve external files, and does not use express.static (for example, a super-light one file webserver and site) you can use serve-favicon and encode your favicon.ico file as Base64. Like this:

const favicon = require('serve-favicon');
const imgBuffer = new Buffer.from('IMAGE_AS_BASE64_STRING_GOES_HERE', 'base64');
// assuming app is already defined
app.use(favicon(imgBuffer));

Replace IMAGE_AS_BASE64_STRING_GOES_HERE with the result of encoding your favicon file as Base64. There are lots of sites that can do that online, have a search.

Note you may need to restart the server and/or browser to see it working on localhost, and a hard refresh/clear browser cache to see it working on the web.

What are Keycloak's OAuth2 / OpenID Connect endpoints?

After much digging around we were able to scrape the info more or less (mainly from Keycloak's own JS client lib):

  • Authorization Endpoint: /auth/realms/{realm}/tokens/login
  • Token Endpoint: /auth/realms/{realm}/tokens/access/codes

As for OpenID Connect UserInfo, right now (1.1.0.Final) Keycloak doesn't implement this endpoint, so it is not fully OpenID Connect compliant. However, there is already a patch that adds that as of this writing should be included in 1.2.x.

But - Ironically Keycloak does send back an id_token in together with the access token. Both the id_token and the access_token are signed JWTs, and the keys of the token are OpenID Connect's keys, i.e:

"iss":  "{realm}"
"sub":  "5bf30443-0cf7-4d31-b204-efd11a432659"
"name": "Amir Abiri"
"email: "..."

So while Keycloak 1.1.x is not fully OpenID Connect compliant, it does "speak" in OpenID Connect language.

Getting key with maximum value in dictionary?

I have tested MANY variants, and this is the fastest way to return the key of dict with the max value:

def keywithmaxval(d):
     """ a) create a list of the dict's keys and values; 
         b) return the key with the max value"""  
     v=list(d.values())
     k=list(d.keys())
     return k[v.index(max(v))]

To give you an idea, here are some candidate methods:

def f1():  
     v=list(d1.values())
     k=list(d1.keys())
     return k[v.index(max(v))]

def f2():
    d3={v:k for k,v in d1.items()}
    return d3[max(d3)]

def f3():
    return list(filter(lambda t: t[1]==max(d1.values()), d1.items()))[0][0]    

def f3b():
    # same as f3 but remove the call to max from the lambda
    m=max(d1.values())
    return list(filter(lambda t: t[1]==m, d1.items()))[0][0]        

def f4():
    return [k for k,v in d1.items() if v==max(d1.values())][0]    

def f4b():
    # same as f4 but remove the max from the comprehension
    m=max(d1.values())
    return [k for k,v in d1.items() if v==m][0]        

def f5():
    return max(d1.items(), key=operator.itemgetter(1))[0]    

def f6():
    return max(d1,key=d1.get)     

def f7():
     """ a) create a list of the dict's keys and values; 
         b) return the key with the max value"""    
     v=list(d1.values())
     return list(d1.keys())[v.index(max(v))]    

def f8():
     return max(d1, key=lambda k: d1[k])     

tl=[f1,f2, f3b, f4b, f5, f6, f7, f8, f4,f3]     
cmpthese.cmpthese(tl,c=100) 

The test dictionary:

d1={1: 1, 2: 2, 3: 8, 4: 3, 5: 6, 6: 9, 7: 17, 8: 4, 9: 20, 10: 7, 11: 15, 
    12: 10, 13: 10, 14: 18, 15: 18, 16: 5, 17: 13, 18: 21, 19: 21, 20: 8, 
    21: 8, 22: 16, 23: 16, 24: 11, 25: 24, 26: 11, 27: 112, 28: 19, 29: 19, 
    30: 19, 3077: 36, 32: 6, 33: 27, 34: 14, 35: 14, 36: 22, 4102: 39, 38: 22, 
    39: 35, 40: 9, 41: 110, 42: 9, 43: 30, 44: 17, 45: 17, 46: 17, 47: 105, 48: 12, 
    49: 25, 50: 25, 51: 25, 52: 12, 53: 12, 54: 113, 1079: 50, 56: 20, 57: 33, 
    58: 20, 59: 33, 60: 20, 61: 20, 62: 108, 63: 108, 64: 7, 65: 28, 66: 28, 67: 28, 
    68: 15, 69: 15, 70: 15, 71: 103, 72: 23, 73: 116, 74: 23, 75: 15, 76: 23, 77: 23, 
    78: 36, 79: 36, 80: 10, 81: 23, 82: 111, 83: 111, 84: 10, 85: 10, 86: 31, 87: 31, 
    88: 18, 89: 31, 90: 18, 91: 93, 92: 18, 93: 18, 94: 106, 95: 106, 96: 13, 9232: 35, 
    98: 26, 99: 26, 100: 26, 101: 26, 103: 88, 104: 13, 106: 13, 107: 101, 1132: 63, 
    2158: 51, 112: 21, 113: 13, 116: 21, 118: 34, 119: 34, 7288: 45, 121: 96, 122: 21, 
    124: 109, 125: 109, 128: 8, 1154: 32, 131: 29, 134: 29, 136: 16, 137: 91, 140: 16, 
    142: 104, 143: 104, 146: 117, 148: 24, 149: 24, 152: 24, 154: 24, 155: 86, 160: 11, 
    161: 99, 1186: 76, 3238: 49, 167: 68, 170: 11, 172: 32, 175: 81, 178: 32, 179: 32, 
    182: 94, 184: 19, 31: 107, 188: 107, 190: 107, 196: 27, 197: 27, 202: 27, 206: 89, 
    208: 14, 214: 102, 215: 102, 220: 115, 37: 22, 224: 22, 226: 14, 232: 22, 233: 84, 
    238: 35, 242: 97, 244: 22, 250: 110, 251: 66, 1276: 58, 256: 9, 2308: 33, 262: 30, 
    263: 79, 268: 30, 269: 30, 274: 92, 1300: 27, 280: 17, 283: 61, 286: 105, 292: 118, 
    296: 25, 298: 25, 304: 25, 310: 87, 1336: 71, 319: 56, 322: 100, 323: 100, 325: 25, 
    55: 113, 334: 69, 340: 12, 1367: 40, 350: 82, 358: 33, 364: 95, 376: 108, 
    377: 64, 2429: 46, 394: 28, 395: 77, 404: 28, 412: 90, 1438: 53, 425: 59, 430: 103, 
    1456: 97, 433: 28, 445: 72, 448: 23, 466: 85, 479: 54, 484: 98, 485: 98, 488: 23, 
    6154: 37, 502: 67, 4616: 34, 526: 80, 538: 31, 566: 62, 3644: 44, 577: 31, 97: 119, 
    592: 26, 593: 75, 1619: 48, 638: 57, 646: 101, 650: 26, 110: 114, 668: 70, 2734: 41, 
    700: 83, 1732: 30, 719: 52, 728: 96, 754: 65, 1780: 74, 4858: 47, 130: 29, 790: 78, 
    1822: 43, 2051: 38, 808: 29, 850: 60, 866: 29, 890: 73, 911: 42, 958: 55, 970: 99, 
    976: 24, 166: 112}

And the test results under Python 3.2:

    rate/sec       f4      f3    f3b     f8     f5     f2    f4b     f6     f7     f1
f4       454       --   -2.5% -96.9% -97.5% -98.6% -98.6% -98.7% -98.7% -98.9% -99.0%
f3       466     2.6%      -- -96.8% -97.4% -98.6% -98.6% -98.6% -98.7% -98.9% -99.0%
f3b   14,715  3138.9% 3057.4%     -- -18.6% -55.5% -56.0% -56.4% -58.3% -63.8% -68.4%
f8    18,070  3877.3% 3777.3%  22.8%     -- -45.4% -45.9% -46.5% -48.8% -55.5% -61.2%
f5    33,091  7183.7% 7000.5% 124.9%  83.1%     --  -1.0%  -2.0%  -6.3% -18.6% -29.0%
f2    33,423  7256.8% 7071.8% 127.1%  85.0%   1.0%     --  -1.0%  -5.3% -17.7% -28.3%
f4b   33,762  7331.4% 7144.6% 129.4%  86.8%   2.0%   1.0%     --  -4.4% -16.9% -27.5%
f6    35,300  7669.8% 7474.4% 139.9%  95.4%   6.7%   5.6%   4.6%     -- -13.1% -24.2%
f7    40,631  8843.2% 8618.3% 176.1% 124.9%  22.8%  21.6%  20.3%  15.1%     -- -12.8%
f1    46,598 10156.7% 9898.8% 216.7% 157.9%  40.8%  39.4%  38.0%  32.0%  14.7%     --

And under Python 2.7:

    rate/sec       f3       f4     f8    f3b     f6     f5     f2    f4b     f7     f1
f3       384       --    -2.6% -97.1% -97.2% -97.9% -97.9% -98.0% -98.2% -98.5% -99.2%
f4       394     2.6%       -- -97.0% -97.2% -97.8% -97.9% -98.0% -98.1% -98.5% -99.1%
f8    13,079  3303.3%  3216.1%     --  -5.6% -28.6% -29.9% -32.8% -38.3% -49.7% -71.2%
f3b   13,852  3504.5%  3412.1%   5.9%     -- -24.4% -25.8% -28.9% -34.6% -46.7% -69.5%
f6    18,325  4668.4%  4546.2%  40.1%  32.3%     --  -1.8%  -5.9% -13.5% -29.5% -59.6%
f5    18,664  4756.5%  4632.0%  42.7%  34.7%   1.8%     --  -4.1% -11.9% -28.2% -58.8%
f2    19,470  4966.4%  4836.5%  48.9%  40.6%   6.2%   4.3%     --  -8.1% -25.1% -57.1%
f4b   21,187  5413.0%  5271.7%  62.0%  52.9%  15.6%  13.5%   8.8%     -- -18.5% -53.3%
f7    26,002  6665.8%  6492.4%  98.8%  87.7%  41.9%  39.3%  33.5%  22.7%     -- -42.7%
f1    45,354 11701.5% 11399.0% 246.8% 227.4% 147.5% 143.0% 132.9% 114.1%  74.4%     -- 

You can see that f1 is the fastest under Python 3.2 and 2.7 (or, more completely, keywithmaxval at the top of this post)

How do I change the ID of a HTML element with JavaScript?

It does work in Firefox (including 2.0.0.20). See http://jsbin.com/akili (add /edit to the url to edit):

<p id="one">One</p>
<a href="#" onclick="document.getElementById('one').id = 'two'; return false">Link2</a>

The first click changes the id to "two", the second click errors because the element with id="one" now can't be found!

Perhaps you have another element already with id="two" (FYI you can't have more than one element with the same id).

JComboBox Selection Change Listener?

It should respond to ActionListeners, like this:

combo.addActionListener (new ActionListener () {
    public void actionPerformed(ActionEvent e) {
        doSomething();
    }
});

@John Calsbeek rightly points out that addItemListener() will work, too. You may get 2 ItemEvents, though, one for the deselection of the previously selected item, and another for the selection of the new item. Just don't use both event types!

How to convert DATE to UNIX TIMESTAMP in shell script on MacOS

date +%s

This works fine for me on OS X Lion.

How to read/process command line arguments?

There is also argparse stdlib module (an "impovement" on stdlib's optparse module). Example from the introduction to argparse:

# script.py
import argparse

if __name__ == '__main__':
    parser = argparse.ArgumentParser()
    parser.add_argument(
        'integers', metavar='int', type=int, choices=range(10),
         nargs='+', help='an integer in the range 0..9')
    parser.add_argument(
        '--sum', dest='accumulate', action='store_const', const=sum,
        default=max, help='sum the integers (default: find the max)')

    args = parser.parse_args()
    print(args.accumulate(args.integers))

Usage:

$ script.py 1 2 3 4
4

$ script.py --sum 1 2 3 4
10

Constructors in JavaScript objects

In most cases you have to somehow declare the property you need before you can call a method that passes in this information. If you do not have to initially set a property you can just call a method within the object like so. Probably not the most pretty way of doing this but this still works.

var objectA = {
    color: ''; 
    callColor : function(){
        console.log(this.color);
    }
    this.callColor(); 
}
var newObject = new objectA(); 

Shell Script — Get all files modified after <date>

well under linux try reading man page of the find command

man find

something like this should

 find . -type f -mtime -7 -print -exec cat {} \; | tar cf - | gzip -9

and you have it

Regex AND operator

Example of a Boolean (AND) plus Wildcard search, which I'm using inside a javascript Autocomplete plugin:

String to match: "my word"

String to search: "I'm searching for my funny words inside this text"

You need the following regex: /^(?=.*my)(?=.*word).*$/im

Explaining:

^ assert position at start of a line

?= Positive Lookahead

.* matches any character (except newline)

() Groups

$ assert position at end of a line

i modifier: insensitive. Case insensitive match (ignores case of [a-zA-Z])

m modifier: multi-line. Causes ^ and $ to match the begin/end of each line (not only begin/end of string)

Test the Regex here: https://regex101.com/r/iS5jJ3/1

So, you can create a javascript function that:

  1. Replace regex reserved characters to avoid errors
  2. Split your string at spaces
  3. Encapsulate your words inside regex groups
  4. Create a regex pattern
  5. Execute the regex match

Example:

_x000D_
_x000D_
function fullTextCompare(myWords, toMatch){_x000D_
    //Replace regex reserved characters_x000D_
    myWords=myWords.replace(/[-\/\\^$*+?.()|[\]{}]/g, '\\$&');_x000D_
    //Split your string at spaces_x000D_
    arrWords = myWords.split(" ");_x000D_
    //Encapsulate your words inside regex groups_x000D_
    arrWords = arrWords.map(function( n ) {_x000D_
        return ["(?=.*"+n+")"];_x000D_
    });_x000D_
    //Create a regex pattern_x000D_
    sRegex = new RegExp("^"+arrWords.join("")+".*$","im");_x000D_
    //Execute the regex match_x000D_
    return(toMatch.match(sRegex)===null?false:true);_x000D_
}_x000D_
_x000D_
//Using it:_x000D_
console.log(_x000D_
    fullTextCompare("my word","I'm searching for my funny words inside this text")_x000D_
);_x000D_
_x000D_
//Wildcards:_x000D_
console.log(_x000D_
    fullTextCompare("y wo","I'm searching for my funny words inside this text")_x000D_
);
_x000D_
_x000D_
_x000D_

if (select count(column) from table) > 0 then

You cannot directly use a SQL statement in a PL/SQL expression:

SQL> begin
  2     if (select count(*) from dual) >= 1 then
  3        null;
  4     end if;
  5  end;
  6  /
        if (select count(*) from dual) >= 1 then
            *
ERROR at line 2:
ORA-06550: line 2, column 6:
PLS-00103: Encountered the symbol "SELECT" when expecting one of the following:
...
...

You must use a variable instead:

SQL> set serveroutput on
SQL>
SQL> declare
  2     v_count number;
  3  begin
  4     select count(*) into v_count from dual;
  5
  6     if v_count >= 1 then
  7             dbms_output.put_line('Pass');
  8     end if;
  9  end;
 10  /
Pass

PL/SQL procedure successfully completed.

Of course, you may be able to do the whole thing in SQL:

update my_table
set x = y
where (select count(*) from other_table) >= 1;

It's difficult to prove that something is not possible. Other than the simple test case above, you can look at the syntax diagram for the IF statement; you won't see a SELECT statement in any of the branches.

Split list into smaller lists (split in half)

#for python 3
    A = [0,1,2,3,4,5]
    l = len(A)/2
    B = A[:int(l)]
    C = A[int(l):]       

Can I write native iPhone apps using Python?

It seems this is now something developers are allowed to do: the iOS Developer Agreement was changed yesterday and appears to have been ammended in a such a way as to make embedding a Python interpretter in your application legal:

SECTION 3.3.2 — INTERPRETERS

Old:

3.3.2 An Application may not itself install or launch other executable code by any means, including without limitation through the use of a plug-in architecture, calling other frameworks, other APIs or otherwise. Unless otherwise approved by Apple in writing, no interpreted code may be downloaded or used in an Application except for code that is interpreted and run by Apple’s Documented APIs and built-in interpreter(s). Notwithstanding the foregoing, with Apple’s prior written consent, an Application may use embedded interpreted code in a limited way if such use is solely for providing minor features or functionality that are consistent with the intended and advertised purpose of the Application.

New:

3.3.2 An Application may not download or install executable code. Interpreted code may only be used in an Application if all scripts, code and interpreters are packaged in the Application and not downloaded. The only exception to the foregoing is scripts and code downloaded and run by Apple’s built-in WebKit framework.

Arrays in type script

A cleaner way to do this:

class Book {
    public Title: string;
    public Price: number;
    public Description: string;

    constructor(public BookId: number, public Author: string){}
}

Then

var bks: Book[] = [
    new Book(1, "vamsee")
];

Create a simple Login page using eclipse and mysql

You Can simply Use One Jsp Page To accomplish the task.

<%@page contentType="text/html" pageEncoding="UTF-8"%>
<%@page import="java.sql.*"%>
<!DOCTYPE html>
<html>
   <head>
    <meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
    <title>JSP Page</title>
</head>
<body>
    <%
        String username=request.getParameter("user_name");
        String password=request.getParameter("password");
        String role=request.getParameter("role");
        try
        {
            Class.forName("com.mysql.jdbc.Driver");
            Connection con=DriverManager.getConnection("jdbc:mysql://localhost:3306/t_fleet","root","root");
            Statement st=con.createStatement();
            String query="select * from tbl_login where user_name='"+username+"' and password='"+password+"' and role='"+role+"'";
            ResultSet rs=st.executeQuery(query);
            while(rs.next())
            {
                session.setAttribute( "user_name",rs.getString(2));
                session.setMaxInactiveInterval(3000);
                response.sendRedirect("homepage.jsp");
            }
            %>



        <%}
        catch(Exception e)
        {
            out.println(e);
        }
    %>

</body>

I have use username, password and role to get into the system. One more thing to implement is you can do page permission checking through jsp and javascript function.

Python 3 Float Decimal Points/Precision

The simple way to do this is by using the round buit-in.

round(2.6463636263,2) would be displayed as 2.65.

python tuple to dict

If there are multiple values for the same key, the following code will append those values to a list corresponding to their key,

d = dict()
for x,y in t:
    if(d.has_key(y)):
        d[y].append(x)
    else:
        d[y] = [x]

Exit Shell Script Based on Process Exit Code

For Bash:

# This will trap any errors or commands with non-zero exit status
# by calling function catch_errors()
trap catch_errors ERR;

#
# ... the rest of the script goes here
#

function catch_errors() {
   # Do whatever on errors
   #
   #
   echo "script aborted, because of errors";
   exit 0;
}

Cast to generic type in C#

Please see if following solution works for you. The trick is to define a base processor interface which takes a base type of message.

interface IMessage
{
}

class LoginMessage : IMessage
{
}

class LogoutMessage : IMessage
{
}

class UnknownMessage : IMessage
{
}

interface IMessageProcessor
{
    void PrcessMessageBase(IMessage msg);
}

abstract class MessageProcessor<T> : IMessageProcessor where T : IMessage
{
    public void PrcessMessageBase(IMessage msg)
    {
        ProcessMessage((T)msg);
    }

    public abstract void ProcessMessage(T msg);

}

class LoginMessageProcessor : MessageProcessor<LoginMessage>
{
    public override void ProcessMessage(LoginMessage msg)
    {
        System.Console.WriteLine("Handled by LoginMsgProcessor");
    }
}

class LogoutMessageProcessor : MessageProcessor<LogoutMessage>
{
    public override void ProcessMessage(LogoutMessage msg)
    {
        System.Console.WriteLine("Handled by LogoutMsgProcessor");
    }
}

class MessageProcessorTest
{
    /// <summary>
    /// IMessage Type and the IMessageProcessor which would process that type.
    /// It can be further optimized by keeping IMessage type hashcode
    /// </summary>
    private Dictionary<Type, IMessageProcessor> msgProcessors = 
                                new Dictionary<Type, IMessageProcessor>();
    bool processorsLoaded = false;

    public void EnsureProcessorsLoaded()
    {
        if(!processorsLoaded)
        {
            var processors =
                from processorType in Assembly.GetExecutingAssembly().GetTypes()
                where processorType.IsClass && !processorType.IsAbstract &&
                      processorType.GetInterface(typeof(IMessageProcessor).Name) != null
                select Activator.CreateInstance(processorType);

            foreach (IMessageProcessor msgProcessor in processors)
            {
                MethodInfo processMethod = msgProcessor.GetType().GetMethod("ProcessMessage");
                msgProcessors.Add(processMethod.GetParameters()[0].ParameterType, msgProcessor);
            }

            processorsLoaded = true;
        }
    }

    public void ProcessMessages()
    {
        List<IMessage> msgList = new List<IMessage>();
        msgList.Add(new LoginMessage());
        msgList.Add(new LogoutMessage());
        msgList.Add(new UnknownMessage());

        foreach (IMessage msg in msgList)
        {
            ProcessMessage(msg);
        }
    }

    public void ProcessMessage(IMessage msg)
    {
        EnsureProcessorsLoaded();
        IMessageProcessor msgProcessor = null;
        if(msgProcessors.TryGetValue(msg.GetType(), out msgProcessor))
        {
            msgProcessor.PrcessMessageBase(msg);
        }
        else
        {
            System.Console.WriteLine("Processor not found");
        }
    }

    public static void Test()
    {
        new MessageProcessorTest().ProcessMessages();
    }
}

How to add "active" class to Html.ActionLink in ASP.NET MVC

Most of the solutions on this question all require you to specify the 'page' on both the li and the a (via HtmlHelper) tag. Both @Wolles and @Crush's answers eliminated this duplication, which was nice, but they were using HtmlHelper extension methods instead of TagHelpers. And I wanted to use a TagHelper and support Razor Pages.

You can read my full post here (and get the source code), but the gist of it is:

<bs-menu-link asp-page="/Events/Index" menu-text="Events"></bs-menu-link>

Would render (if the link was active obviously):

<li class="active"><a href="/Events">Events</a></li>

My TagHelper leverages the AnchorTagHelper internally (thus supporting asp-page, asp-controller, asp-action, etc. attributes). The 'checks' for active or not is similar to many of the answers to this post.

How to reset sequence in postgres and fill id column with new data?

Both provided solutions did not work for me;

> SELECT setval('seq', 0);
ERROR:  setval: value 0 is out of bounds for sequence "seq" (1..9223372036854775807)

setval('seq', 1) starts the numbering with 2, and ALTER SEQUENCE seq START 1 starts the numbering with 2 as well, because seq.is_called is true (Postgres version 9.0.4)

The solution that worked for me is:

> ALTER SEQUENCE seq RESTART WITH 1;
> UPDATE foo SET id = DEFAULT;

How to view file diff in git before commit

To check for local differences:

git diff myfile.txt

or you can use a diff tool (in case you'd like to revert some changes):

git difftool myfile.txt

To use git difftool more efficiently, install and use your favourite GUI tool such as Meld, DiffMerge or OpenDiff.

Note: You can also use . (instead of filename) to see current dir changes.

In order to check changes per each line, use: git blame which will display which line was commited in which commit.


To view the actual file before the commit (where master is your branch), run:

git show master:path/my_file

Assigning strings to arrays of characters

What I would use is

char *s = "abcd";

Java "user.dir" property - what exactly does it mean?

Typically this is the directory where your app (java) was started (working dir). "Typically" because it can be changed, eg when you run an app with Runtime.exec(String[] cmdarray, String[] envp, File dir)

How to troubleshoot an "AttributeError: __exit__" in multiproccesing in Python?

The reason behind this error is : Flask app is already running, hasn't shut down and in middle of that we try to start another instance by: with app.app_context(): #Code Before we use this with statement we need to make sure that scope of the previous running app is closed.

How to create many labels and textboxes dynamically depending on the value of an integer variable?

Suppose you have a button that when pressed sets n to 5, you could then generate labels and textboxes on your form like so.

var n = 5;
for (int i = 0; i < n; i++)
{
    //Create label
    Label label = new Label();
    label.Text = String.Format("Label {0}", i);
    //Position label on screen
    label.Left = 10;
    label.Top = (i + 1) * 20;
    //Create textbox
    TextBox textBox = new TextBox();
    //Position textbox on screen
    textBox.Left = 120;
    textBox.Top = (i + 1) * 20;
    //Add controls to form
    this.Controls.Add(label);
    this.Controls.Add(textBox);
}

This will not only add them to the form but position them decently as well.

how to change default python version?

On Mac OS X using the python.org installer as you apparently have, you need to invoke Python 3 with python3, not python. That is currently reserved for Python 2 versions. You could also use python3.2 to specifically invoke that version.

$ which python
/usr/bin/python
$ which python3
/Library/Frameworks/Python.framework/Versions/3.2/bin/python3
$ cd /Library/Frameworks/Python.framework/Versions/3.2/bin/
$ ls -l
total 384
lrwxr-xr-x  1 root  admin      8 Apr 28 15:51 2to3@ -> 2to3-3.2
-rwxrwxr-x  1 root  admin    140 Feb 20 11:14 2to3-3.2*
lrwxr-xr-x  1 root  admin      7 Apr 28 15:51 idle3@ -> idle3.2
-rwxrwxr-x  1 root  admin    138 Feb 20 11:14 idle3.2*
lrwxr-xr-x  1 root  admin      8 Apr 28 15:51 pydoc3@ -> pydoc3.2
-rwxrwxr-x  1 root  admin    123 Feb 20 11:14 pydoc3.2*
-rwxrwxr-x  2 root  admin  25624 Feb 20 11:14 python3*
lrwxr-xr-x  1 root  admin     12 Apr 28 15:51 python3-32@ -> python3.2-32
lrwxr-xr-x  1 root  admin     16 Apr 28 15:51 python3-config@ -> python3.2-config
-rwxrwxr-x  2 root  admin  25624 Feb 20 11:14 python3.2*
-rwxrwxr-x  1 root  admin  13964 Feb 20 11:14 python3.2-32*
lrwxr-xr-x  1 root  admin     17 Apr 28 15:51 python3.2-config@ -> python3.2m-config
-rwxrwxr-x  1 root  admin  25784 Feb 20 11:14 python3.2m*
-rwxrwxr-x  1 root  admin   1865 Feb 20 11:14 python3.2m-config*
lrwxr-xr-x  1 root  admin     10 Apr 28 15:51 pythonw3@ -> pythonw3.2
lrwxr-xr-x  1 root  admin     13 Apr 28 15:51 pythonw3-32@ -> pythonw3.2-32
-rwxrwxr-x  1 root  admin  25624 Feb 20 11:14 pythonw3.2*
-rwxrwxr-x  1 root  admin  13964 Feb 20 11:14 pythonw3.2-32*

If you also installed a Python 2 from python.org, it would have a similar framework bin directory with no overlapping file names (except for 2to3).

$ open /Applications/Python\ 2.7/Update\ Shell\ Profile.command
$ sh -l
$ echo $PATH
/Library/Frameworks/Python.framework/Versions/2.7/bin:/Library/Frameworks/Python.framework/Versions/3.2/bin:/usr/bin:/bin:/usr/sbin:/sbin:/usr/local/bin
$ which python3
/Library/Frameworks/Python.framework/Versions/3.2/bin/python3
$ which python
/Library/Frameworks/Python.framework/Versions/2.7/bin/python
$ cd /Library/Frameworks/Python.framework/Versions/2.7/bin
$ ls -l
total 288
-rwxrwxr-x  1 root  admin    150 Jul  3  2010 2to3*
lrwxr-x---  1 root  admin      7 Nov  8 23:14 idle@ -> idle2.7
-rwxrwxr-x  1 root  admin    138 Jul  3  2010 idle2.7*
lrwxr-x---  1 root  admin      8 Nov  8 23:14 pydoc@ -> pydoc2.7
-rwxrwxr-x  1 root  admin    123 Jul  3  2010 pydoc2.7*
lrwxr-x---  1 root  admin      9 Nov  8 23:14 python@ -> python2.7
lrwxr-x---  1 root  admin     16 Nov  8 23:14 python-config@ -> python2.7-config
-rwxrwxr-x  1 root  admin  33764 Jul  3  2010 python2.7*
-rwxrwxr-x  1 root  admin   1663 Jul  3  2010 python2.7-config*
lrwxr-x---  1 root  admin     10 Nov  8 23:14 pythonw@ -> pythonw2.7
-rwxrwxr-x  1 root  admin  33764 Jul  3  2010 pythonw2.7*
lrwxr-x---  1 root  admin     11 Nov  8 23:14 smtpd.py@ -> smtpd2.7.py
-rwxrwxr-x  1 root  admin  18272 Jul  3  2010 smtpd2.7.py*

Show week number with Javascript?

I was coding in the dark (a challenge) and couldn't lookup or test my code.

I forgot what round up was called (Math.celi) So I wanted to be extra sure i got it right and came up with this code.

_x000D_
_x000D_
var elm = document.createElement('input')_x000D_
elm.type = 'week'_x000D_
elm.valueAsDate = new Date()_x000D_
var week = elm.value.split('W').pop()_x000D_
_x000D_
console.log(week)
_x000D_
_x000D_
_x000D_ Just a proof of concept of how you can get the week in any other way

But still i recommend any other solution that isn't required by the DOM.

How to compare arrays in JavaScript?

I needed something similar, comparing two arrays containing identifiers but in random order. In my case: "does this array contain at least one identifier from the other list?" The code is quite simple, using the reduce-function.

function hasFullOverlap(listA, listB){ 
   return listA.reduce((allIdsAreFound, _id) => {
         // We return true until an ID has not been found in the other list
          return listB.includes(_id) && allIdsAreFound;
        }, true);
}

if(hasFullOverlap(listA, listB) && hasFullOverlap(listB, listA)){
   // Both lists contain all the values
}

How to check if a function exists on a SQL database

I tend to use the Information_Schema:

IF EXISTS ( SELECT  1
            FROM    Information_schema.Routines
            WHERE   Specific_schema = 'dbo'
                    AND specific_name = 'Foo'
                    AND Routine_Type = 'FUNCTION' ) 

for functions, and change Routine_Type for stored procedures

IF EXISTS ( SELECT  1
            FROM    Information_schema.Routines
            WHERE   Specific_schema = 'dbo'
                    AND specific_name = 'Foo'
                    AND Routine_Type = 'PROCEDURE' ) 

Display HTML form values in same page after submit using Ajax

_x000D_
_x000D_
var tasks = [];_x000D_
var descs = [];_x000D_
_x000D_
// Get the modal_x000D_
var modal = document.getElementById('myModal');_x000D_
_x000D_
// Get the button that opens the modal_x000D_
var btn = document.getElementById("myBtn");_x000D_
_x000D_
// Get the <span> element that closes the modal_x000D_
var span = document.getElementsByClassName("close")[0];_x000D_
_x000D_
// When the user clicks the button, open the modal _x000D_
btn.onclick = function() {_x000D_
  modal.style.display = "block";_x000D_
}_x000D_
_x000D_
// When the user clicks on <span> (x), close the modal_x000D_
span.onclick = function() {_x000D_
  modal.style.display = "none";_x000D_
}_x000D_
_x000D_
// When the user clicks anywhere outside of the modal, close it_x000D_
window.onclick = function(event) {_x000D_
  if (event.target == modal) {_x000D_
    modal.style.display = "none";_x000D_
  }_x000D_
}_x000D_
var rowCount = 1;_x000D_
_x000D_
function addTasks() {_x000D_
  var temp = 'style .fa fa-trash';_x000D_
  tasks.push(document.getElementById("taskname").value);_x000D_
  descs.push(document.getElementById("taskdesc").value);_x000D_
  var table = document.getElementById("tasksTable");_x000D_
  var row = table.insertRow(rowCount);_x000D_
  var cell1 = row.insertCell(0);_x000D_
  var cell2 = row.insertCell(1);_x000D_
  var cell3 = row.insertCell(2);_x000D_
  var cell4 = row.insertCell(3);_x000D_
  cell1.innerHTML = tasks[rowCount - 1];_x000D_
  cell2.innerHTML = descs[rowCount - 1];_x000D_
  cell3.innerHTML = getDate();_x000D_
  cell4.innerHTML = '<td class="fa fa-trash"></td>';_x000D_
  rowCount++;_x000D_
  modal.style.display = "none";_x000D_
}_x000D_
_x000D_
_x000D_
function getDate() {_x000D_
  var today = new Date();_x000D_
  var dd = today.getDate();_x000D_
  var mm = today.getMonth() + 1; //January is 0!_x000D_
_x000D_
  var yyyy = today.getFullYear();_x000D_
_x000D_
  if (dd < 10) {_x000D_
    dd = '0' + dd;_x000D_
  }_x000D_
  if (mm < 10) {_x000D_
    mm = '0' + mm;_x000D_
  }_x000D_
  var today = dd + '-' + mm + '-' + yyyy.toString().slice(2);_x000D_
  return today;_x000D_
}
_x000D_
<html>_x000D_
_x000D_
<body>_x000D_
  <!-- Trigger/Open The Modal -->_x000D_
  <div style="background-color:#0F0F8C ;height:45px">_x000D_
    <h2 style="color: white">LOGO</h2>_x000D_
  </div>_x000D_
  <div>_x000D_
    <button id="myBtn">&emsp;+ Add Task &emsp;</button>_x000D_
  </div>_x000D_
  <div>_x000D_
    <table id="tasksTable">_x000D_
      <thead>_x000D_
        <tr style="background-color:rgba(201, 196, 196, 0.86)">_x000D_
          <th style="width: 150px;">Name</th>_x000D_
          <th style="width: 250px;">Desc</th>_x000D_
          <th style="width: 120px">Date</th>_x000D_
          <th style="width: 120px class=fa fa-trash"></th>_x000D_
        </tr>_x000D_
_x000D_
      </thead>_x000D_
      <tbody></tbody>_x000D_
    </table>_x000D_
  </div>_x000D_
  <!-- The Modal -->_x000D_
  <div id="myModal" class="modal">_x000D_
_x000D_
    <!-- Modal content -->_x000D_
    <div class="modal-content">_x000D_
_x000D_
      <div class="modal-header">_x000D_
_x000D_
        <span class="close">&times;</span>_x000D_
        <h3> Add Task</h3>_x000D_
      </div>_x000D_
_x000D_
      <div class="modal-body">_x000D_
        <table style="padding: 28px 50px">_x000D_
          <tr>_x000D_
            <td style="width:150px">Name:</td>_x000D_
            <td><input type="text" name="name" id="taskname" style="width: -webkit-fill-available"></td>_x000D_
          </tr>_x000D_
          <tr>_x000D_
            <td>_x000D_
              Desc:_x000D_
            </td>_x000D_
            <td>_x000D_
              <textarea name="desc" id="taskdesc" cols="60" rows="10"></textarea>_x000D_
            </td>_x000D_
          </tr>_x000D_
        </table>_x000D_
      </div>_x000D_
_x000D_
      <div class="modal-footer">_x000D_
        <button type="submit" value="submit" style="float: right;" onclick="addTasks()">SUBMIT</button>_x000D_
        <br>_x000D_
        <br>_x000D_
        <br>_x000D_
      </div>_x000D_
_x000D_
    </div>_x000D_
  </div>_x000D_
_x000D_
_x000D_
_x000D_
</body>_x000D_
_x000D_
</html>
_x000D_
_x000D_
_x000D_

How can I find out which server hosts LDAP on my windows domain?

If the machine you are on is part of the AD domain, it should have its name servers set to the AD name servers (or hopefully use a DNS server path that will eventually resolve your AD domains). Using your example of dc=domain,dc=com, if you look up domain.com in the AD name servers it will return a list of the IPs of each AD Controller. Example from my company (w/ the domain name changed, but otherwise it's a real example):

    mokey 0 /home/jj33 > nslookup example.ad
    Server:         172.16.2.10
    Address:        172.16.2.10#53

    Non-authoritative answer:
    Name:   example.ad
    Address: 172.16.6.2
    Name:   example.ad
    Address: 172.16.141.160
    Name:   example.ad
    Address: 172.16.7.9
    Name:   example.ad
    Address: 172.19.1.14
    Name:   example.ad
    Address: 172.19.1.3
    Name:   example.ad
    Address: 172.19.1.11
    Name:   example.ad
    Address: 172.16.3.2

Note I'm actually making the query from a non-AD machine, but our unix name servers know to send queries for our AD domain (example.ad) over to the AD DNS servers.

I'm sure there's a super-slick windowsy way to do this, but I like using the DNS method when I need to find the LDAP servers from a non-windows server.

405 method not allowed Web API

I was having exactly the same problem. I looked for two hours what was wrong with no luck until I realize my POST method was private instead of public .

Funny now seeing that error message is kind of generic. Hope it helps!

Javascript communication between browser tabs/windows

For a more modern solution check out https://stackoverflow.com/a/12514384/270274

Quote:

I'm sticking to the shared local data solution mentioned in the question using localStorage. It seems to be the best solution in terms of reliability, performance, and browser compatibility.

localStorage is implemented in all modern browsers.

The storage event fires when other tabs makes changes to localStorage. This is quite handy for communication purposes.

Reference:
http://dev.w3.org/html5/webstorage/
http://dev.w3.org/html5/webstorage/#the-storage-event

How to set time to 24 hour format in Calendar

You can set the calendar to use only AM or PM using

calendar.set(Calendar.AM_PM, int);

0 = AM

1 = PM

Hope this helps

How can I convert radians to degrees with Python?

I like this method,use sind(x) or cosd(x)

import math

def sind(x):
    return math.sin(math.radians(x))

def cosd(x):
    return math.cos(math.radians(x))

Access-Control-Allow-Origin Multiple Origin Domains?

For multiple domains, in your .htaccess:

<IfModule mod_headers.c>
    SetEnvIf Origin "http(s)?://(www\.)?(domain1.example|domain2.example)$" AccessControlAllowOrigin=$0$1
    Header add Access-Control-Allow-Origin %{AccessControlAllowOrigin}e env=AccessControlAllowOrigin
    Header set Access-Control-Allow-Credentials true
</IfModule>

How to set Android camera orientation properly?

From the Javadocs for setDisplayOrientation(int) (Requires API level 9):

 public static void setCameraDisplayOrientation(Activity activity,
         int cameraId, android.hardware.Camera camera) {
     android.hardware.Camera.CameraInfo info =
             new android.hardware.Camera.CameraInfo();
     android.hardware.Camera.getCameraInfo(cameraId, info);
     int rotation = activity.getWindowManager().getDefaultDisplay()
             .getRotation();
     int degrees = 0;
     switch (rotation) {
         case Surface.ROTATION_0: degrees = 0; break;
         case Surface.ROTATION_90: degrees = 90; break;
         case Surface.ROTATION_180: degrees = 180; break;
         case Surface.ROTATION_270: degrees = 270; break;
     }

     int result;
     if (info.facing == Camera.CameraInfo.CAMERA_FACING_FRONT) {
         result = (info.orientation + degrees) % 360;
         result = (360 - result) % 360;  // compensate the mirror
     } else {  // back-facing
         result = (info.orientation - degrees + 360) % 360;
     }
     camera.setDisplayOrientation(result);
 }

Collections sort(List<T>,Comparator<? super T>) method example

You probably want something like this:

Collections.sort(students, new Comparator<Student>() {
                     public int compare(Student s1, Student s2) {
                           if(s1.getName() != null && s2.getName() != null && s1.getName().comareTo(s1.getName()) != 0) {
                               return s1.getName().compareTo(s2.getName());
                           } else {
                             return s1.getAge().compareTo(s2.getAge());
                          }
                      }
);

This sorts the students first by name. If a name is missing, or two students have the same name, they are sorted by their age.

Adb Devices can't find my phone

I did the following to get my Mac to see the devices again:

  • Run android update adb
  • Run adb kill-server
  • Run adb start-server

At this point, calling adb devices started returning devices again. Now run or debug your project to test it on your device.

Combining two expressions (Expression<Func<T, bool>>)

I needed to achieve the same results, but using something more generic (as the type was not known). Thanks to marc's answer I finally figured out what I was trying to achieve:

    public static LambdaExpression CombineOr(Type sourceType, LambdaExpression exp, LambdaExpression newExp) 
    {
        var parameter = Expression.Parameter(sourceType);

        var leftVisitor = new ReplaceExpressionVisitor(exp.Parameters[0], parameter);
        var left = leftVisitor.Visit(exp.Body);

        var rightVisitor = new ReplaceExpressionVisitor(newExp.Parameters[0], parameter);
        var right = rightVisitor.Visit(newExp.Body);

        var delegateType = typeof(Func<,>).MakeGenericType(sourceType, typeof(bool));
        return Expression.Lambda(delegateType, Expression.Or(left, right), parameter);
    }

Using .Select and .Where in a single LINQ statement

Did you add the Select() after the Where() or before?

You should add it after, because of the concurrency logic:

 1 Take the entire table  
 2 Filter it accordingly  
 3 Select only the ID's  
 4 Make them distinct.  

If you do a Select first, the Where clause can only contain the ID attribute because all other attributes have already been edited out.

Update: For clarity, this order of operators should work:

db.Items.Where(x=> x.userid == user_ID).Select(x=>x.Id).Distinct();

Probably want to add a .toList() at the end but that's optional :)

What is INSTALL_PARSE_FAILED_NO_CERTIFICATES error?

I found this was caused by my JDK version.

I was having this problem with 'ant' and it was due to this CAUTION mentioned in the documentation:

http://developer.android.com/guide/publishing/app-signing.html#signapp

Caution: As of JDK 7, the default signing algorithim has changed, requiring you to specify the signature and digest algorithims (-sigalg and -digestalg) when you sign an APK.

I have JDK 7. In my Ant log, I used -v for verbose and it showed

$ ant -Dadb.device.arg=-d -v release install
[signjar] Executing 'C:\Program Files\Java\jdk1.7.0_03\bin\jarsigner.exe' with arguments:
[signjar] '-keystore'
[signjar] 'C:\cygwin\home\Chloe\pairfinder\release.keystore'
[signjar] '-signedjar'
[signjar] 'C:\cygwin\home\Chloe\pairfinder\bin\PairFinder-release-unaligned.apk'
[signjar] 'C:\cygwin\home\Chloe\pairfinder\bin\PairFinder-release-unsigned.apk'
[signjar] 'mykey'
 [exec]     pkg: /data/local/tmp/PairFinder-release.apk
 [exec] Failure [INSTALL_PARSE_FAILED_NO_CERTIFICATES]

I signed the JAR manually and zipaligned it, but it gave a slightly different error:

$ "$JAVA_HOME"/bin/jarsigner -sigalg MD5withRSA -digestalg SHA1 -keystore release.keystore -signedjar bin/PairFinder-release-unaligned.apk bin/PairFinder-release-unsigned.apk mykey
$ zipalign -v -f 4 bin/PairFinder-release-unaligned.apk bin/PairFinder-release.apk
$ adb -d install -r bin/PairFinder-release.apk
        pkg: /data/local/tmp/PairFinder-release.apk
Failure [INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES]
641 KB/s (52620 bytes in 0.080s)

I found that answered here.

How to deal with INSTALL_PARSE_FAILED_INCONSISTENT_CERTIFICATES without uninstallation

I only needed to uninstall it and then it worked!

$ adb -d uninstall com.kizbit.pairfinder
Success
$ adb -d install -r bin/PairFinder-release.apk
        pkg: /data/local/tmp/PairFinder-release.apk
Success
641 KB/s (52620 bytes in 0.080s)

Now I only need modify the build.xml to use those options when signing!

Ok here it is: C:\Program Files\Java\android-sdk\tools\ant\build.xml

            <signjar
                    sigalg="MD5withRSA"
                    digestalg="SHA1"
                    jar="${out.packaged.file}"
                    signedjar="${out.unaligned.file}"
                    keystore="${key.store}"
                    storepass="${key.store.password}"
                    alias="${key.alias}"
                    keypass="${key.alias.password}"
                    verbose="${verbose}" />

Getting Error - ORA-01858: a non-numeric character was found where a numeric was expected

You can solve the problem by checking if your date matches a REGEX pattern. If not, then NULL (or something else you prefer).

In my particular case it was necessary because I have >20 DATE columns saved as CHAR, so I don't know from which column the error is coming from.

Returning to your query:

1. Declare a REGEX pattern.
It is usually a very long string which will certainly pollute your code (you may want to reuse it as well).

define REGEX_DATE = "'your regex pattern goes here'"

Don't forget a single quote inside a double quote around your Regex :-)

A comprehensive thread about Regex date validation you'll find here.

2. Use it as the first CASE condition:

To use Regex validation in the SELECT statement, you cannot use REGEXP_LIKE (it's only valid in WHERE. It took me a long time to understand why my code was not working. So it's certainly worth a note.

Instead, use REGEXP_INSTR
For entries not found in the pattern (your case) use REGEXP_INSTR (variable, pattern) = 0 .

    DEFINE REGEX_DATE = "'your regex pattern goes here'"

    SELECT   c.contract_num,
         CASE
            WHEN REGEXP_INSTR(c.event_dt, &REGEX_DATE) = 0 THEN NULL
            WHEN   (  MAX (TO_CHAR (TO_DATE (c.event_dt, 'YYYY-MM-DD'), 'MMDD'))
                    - MIN (TO_CHAR (TO_DATE (c.event_dt, 'YYYY-MM-DD'), 'MMDD')))
                 / COUNT (c.event_occurrence) < 32
            THEN
              'Monthly'
            WHEN       (  MAX (
                            TO_CHAR (TO_DATE (c.event_dt, 'YYYY-MM-DD'), 'MMDD'))
                        - MIN (
                            TO_CHAR (TO_DATE (c.event_dt, 'YYYY-MM-DD'), 'MMDD')))
                     / COUNT (c.event_occurrence) >= 32
                 AND   (  MAX (
                            TO_CHAR (TO_DATE (c.event_dt, 'YYYY-MM-DD'), 'MMDD'))
                        - MIN (
                            TO_CHAR (TO_DATE (c.event_dt, 'YYYY-MM-DD'), 'MMDD')))
                     / COUNT (c.event_occurrence) < 91
            THEN
              'Quarterley'
            ELSE
              'Yearly'
         END
FROM     ps_ca_bp_events c
GROUP BY c.contract_num;

MySQL: can't access root account

You can use the init files. Check the MySQL official documentation on How to Reset the Root Password (including comments for alternative solutions).

So basically using init files, you can add any SQL queries that you need for fixing your access (such as GRAND, CREATE, FLUSH PRIVILEGES, etc.) into init file (any file).

Here is my example of recovering root account:

echo "CREATE USER 'root'@'localhost' IDENTIFIED BY 'root';" > your_init_file.sql
echo "GRANT ALL PRIVILEGES ON *.* TO 'root'@'localhost' WITH GRANT OPTION;" >> your_init_file.sql 
echo "FLUSH PRIVILEGES;" >> your_init_file.sql

and after you've created your file, you can run:

killall mysqld
mysqld_safe --init-file=$PWD/your_init_file.sql

then to check if this worked, press Ctrl+Z and type: bg to run the process from the foreground into the background, then verify your access by:

mysql -u root -proot
mysql> show grants;
+-------------------------------------------------------------------------------------------------------------+
| Grants for root@localhost                                                                                   |
+-------------------------------------------------------------------------------------------------------------+
| GRANT USAGE ON *.* TO 'root'@'localhost' IDENTIFIED BY PASSWORD '*81F5E21E35407D884A6CD4A731AEBFB6AF209E1B' |

See also:

How to set the locale inside a Debian/Ubuntu Docker container?

Tip: Browse the container documentation forums, like the Docker Forum.

Here's a solution for debian & ubuntu, add the following to your Dockerfile:

RUN apt-get update && apt-get install -y locales && rm -rf /var/lib/apt/lists/* \
    && localedef -i en_US -c -f UTF-8 -A /usr/share/locale/locale.alias en_US.UTF-8
ENV LANG en_US.UTF-8

Calculate distance in meters when you know longitude and latitude in java

Based on another question on stackoverflow, I got this code.. This calculates the result in meters, not in miles :)

 public static float distFrom(float lat1, float lng1, float lat2, float lng2) {
    double earthRadius = 6371000; //meters
    double dLat = Math.toRadians(lat2-lat1);
    double dLng = Math.toRadians(lng2-lng1);
    double a = Math.sin(dLat/2) * Math.sin(dLat/2) +
               Math.cos(Math.toRadians(lat1)) * Math.cos(Math.toRadians(lat2)) *
               Math.sin(dLng/2) * Math.sin(dLng/2);
    double c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
    float dist = (float) (earthRadius * c);

    return dist;
    }

Why is this program erroneously rejected by three C++ compilers?

Your < and >, ( and ), { and } don't seem to match very well; Try drawing them better.

How to insert double and float values to sqlite?

actually I think your code is just fine.. you can save those values as strings (TEXT) just like you did.. (if you want to)

and you probably get the error for the System.currentTimeMillis() that might be too big for INTEGER

Run two async tasks in parallel and collect results in .NET 4.5

To answer this point:

I want Sleep to be an async method so it can await other methods

you can maybe rewrite the Sleep function like this:

private static async Task<int> Sleep(int ms)
{
    Console.WriteLine("Sleeping for " + ms);
    var task = Task.Run(() => Thread.Sleep(ms));
    await task;
    Console.WriteLine("Sleeping for " + ms + "END");
    return ms;
}

static void Main(string[] args)
{
    Console.WriteLine("Starting");

    var task1 = Sleep(2000);
    var task2 = Sleep(1000);

    int totalSlept = task1.Result +task2.Result;

    Console.WriteLine("Slept for " + totalSlept + " ms");
    Console.ReadKey();
}

running this code will output :

Starting
Sleeping for 2000
Sleeping for 1000
*(one second later)*
Sleeping for 1000END
*(one second later)*
Sleeping for 2000END
Slept for 3000 ms

Select data between a date/time range

You need to update the date format:

select * from hockey_stats 
where game_date between '2012-03-11 00:00:00' and '2012-05-11 23:59:00' 
order by game_date desc;

Simple int to char[] conversion

Use this. Beware of i's larger than 9, as these will require a char array with more than 2 elements to avoid a buffer overrun.

char c[2];
int i=1;
sprintf(c, "%d", i);

Why does my favicon not show up?

  1. Is it really a .ico, or is it just named ".ico"?
  2. What browser are you testing in?

The absolutely easiest way to have a favicon is to place an icon called "favicon.ico" in the root folder. That just works everywhere, no code needed at all.

If you must have it in a subdirectory, use:

<link rel="shortcut icon" href="/img/favicon.ico" />

Note the / before img to ensure it is anchored to the root folder.

C++ Matrix Class

There is no "canonical" way to do the matrix in C++, STL does not provide classes like "matrix". However there are some 3rd party libraries that do. You are encouraged to use them or write your own implementation. You can try my implementation derived from some public implementation found on the internet.

How do I set the default value for an optional argument in Javascript?

You can also do this with ArgueJS:

function (){
  arguments = __({nodebox: undefined, str: [String: "hai"]})

  // and now on, you can access your arguments by
  //   arguments.nodebox and arguments.str
}

sorting dictionary python 3

I like python numpy for this kind of stuff! eg:

r=readData()
nsorted = np.lexsort((r.calls, r.slow_requests, r.very_slow_requests, r.stalled_requests))

I have an example of importing CSV data into a numpy and ordering by column priorities. https://github.com/unixunion/toolbox/blob/master/python/csv-numpy.py

Kegan

character count using jquery

For length including white-space:

$("#id").val().length

For length without white-space:

$("#id").val().replace(/ /g,'').length

For removing only beginning and trailing white-space:

$.trim($("#test").val()).length

For example, the string " t e s t " would evaluate as:

//" t e s t "
$("#id").val(); 

//Example 1
$("#id").val().length; //Returns 9
//Example 2
$("#id").val().replace(/ /g,'').length; //Returns 4
//Example 3
$.trim($("#test").val()).length; //Returns 7

Here is a demo using all of them.

Resizable table columns with jQuery

I've done my own jquery ui widget, just thinking if it's good enough.

https://github.com/OnekO/colresizable

Permission denied (publickey). fatal: The remote end hung up unexpectedly while pushing back to git repository

Googled "Permission denied (publickey). fatal: The remote end hung up unexpectedly", first result an exact SO dupe:

GitHub: Permission denied (publickey). fatal: The remote end hung up unexpectedly which links here in the accepted answer (from the original poster, no less): http://help.github.com/linux-set-up-git/

How do I use vim registers?

Registers in Vim let you run actions or commands on text stored within them. To access a register, you type "a before a command, where a is the name of a register. If you want to copy the current line into register k, you can type

"kyy

Or you can append to a register by using a capital letter

"Kyy

You can then move through the document and paste it elsewhere using

"kp

To paste from system clipboard on Linux

"+p

To paste from system clipboard on Windows (or from "mouse highlight" clipboard on Linux)

"*p

To access all currently defined registers type

:reg

Cannot implicitly convert type 'System.Linq.IQueryable' to 'System.Collections.Generic.IList'

You can use the .ToList() method to convert the IQueryable result returned to an IList, as shown below, after the linq query.

   public DzieckoAndOpiekunCollection GetChildAndOpiekunByFirstnameLastname(string firstname, string lastname)
{
    DataTransfer.ChargeInSchoolEntities db = new DataTransfer.ChargeInSchoolEntities();
    DzieckoAndOpiekunCollection result = new DzieckoAndOpiekunCollection();
    if (firstname == null && lastname != null)
    {
        IList<DzieckoAndOpiekun> resultV = from p in db.Dziecko
                      where lastname == p.Nazwisko
                      **select** new DzieckoAndOpiekun(
                     p.Imie,
                     p.Nazwisko,
                     p.Opiekun.Imie,
                     p.Opiekun.Nazwisko).ToList()
                  ;
        result.AddRange(resultV);
    }
    return result;
}

Iterate through 2 dimensional array

Just change the indexes. i and j....in the loop, plus if you're dealing with Strings you have to use concat and initialize the variable to an empty Strong otherwise you'll get an exception.

String string="";
for (int i = 0; i<array.length; i++){
    for (int j = 0; j<array[i].length; j++){
        string = string.concat(array[j][i]);
    } 
}
System.out.println(string)

Escape double quotes in Java

For a String constant you have no choice other than escaping via backslash.

Maybe you find the MyBatis project interesting. It is a thin layer over JDBC where you can externalize your SQL queries in XML configuration files without the need to escape double quotes.

Display help message with python argparse when script is called without any arguments

If you have arguments that must be specified for the script to run - use the required parameter for ArgumentParser as shown below:-

parser.add_argument('--foo', required=True)

parse_args() will report an error if the script is run without any arguments.

Converting bytes to megabytes

Divide by 2 to the power of 20, (1024*1024) bytes = 1 megabyte

1024*1024 = 1,048,576   
2^20 = 1,048,576
1,048,576/1,048,576 = 1  

It is the same thing.

Getting time difference between two times in PHP

You can also use DateTime class:

$time1 = new DateTime('09:00:59');
$time2 = new DateTime('09:01:00');
$interval = $time1->diff($time2);
echo $interval->format('%s second(s)');

Result:

1 second(s)