Programs & Examples On #Form designer

Format a Go string without printing?

1. Simple strings

For "simple" strings (typically what fits into a line) the simplest solution is using fmt.Sprintf() and friends (fmt.Sprint(), fmt.Sprintln()). These are analogous to the functions without the starter S letter, but these Sxxx() variants return the result as a string instead of printing them to the standard output.

For example:

s := fmt.Sprintf("Hi, my name is %s and I'm %d years old.", "Bob", 23)

The variable s will be initialized with the value:

Hi, my name is Bob and I'm 23 years old.

Tip: If you just want to concatenate values of different types, you may not automatically need to use Sprintf() (which requires a format string) as Sprint() does exactly this. See this example:

i := 23
s := fmt.Sprint("[age:", i, "]") // s will be "[age:23]"

For concatenating only strings, you may also use strings.Join() where you can specify a custom separator string (to be placed between the strings to join).

Try these on the Go Playground.

2. Complex strings (documents)

If the string you're trying to create is more complex (e.g. a multi-line email message), fmt.Sprintf() becomes less readable and less efficient (especially if you have to do this many times).

For this the standard library provides the packages text/template and html/template. These packages implement data-driven templates for generating textual output. html/template is for generating HTML output safe against code injection. It provides the same interface as package text/template and should be used instead of text/template whenever the output is HTML.

Using the template packages basically requires you to provide a static template in the form of a string value (which may be originating from a file in which case you only provide the file name) which may contain static text, and actions which are processed and executed when the engine processes the template and generates the output.

You may provide parameters which are included/substituted in the static template and which may control the output generation process. Typical form of such parameters are structs and map values which may be nested.

Example:

For example let's say you want to generate email messages that look like this:

Hi [name]!

Your account is ready, your user name is: [user-name]

You have the following roles assigned:
[role#1], [role#2], ... [role#n]

To generate email message bodies like this, you could use the following static template:

const emailTmpl = `Hi {{.Name}}!

Your account is ready, your user name is: {{.UserName}}

You have the following roles assigned:
{{range $i, $r := .Roles}}{{if $i}}, {{end}}{{.}}{{end}}
`

And provide data like this for executing it:

data := map[string]interface{}{
    "Name":     "Bob",
    "UserName": "bob92",
    "Roles":    []string{"dbteam", "uiteam", "tester"},
}

Normally output of templates are written to an io.Writer, so if you want the result as a string, create and write to a bytes.Buffer (which implements io.Writer). Executing the template and getting the result as string:

t := template.Must(template.New("email").Parse(emailTmpl))
buf := &bytes.Buffer{}
if err := t.Execute(buf, data); err != nil {
    panic(err)
}
s := buf.String()

This will result in the expected output:

Hi Bob!

Your account is ready, your user name is: bob92

You have the following roles assigned:
dbteam, uiteam, tester

Try it on the Go Playground.

Also note that since Go 1.10, a newer, faster, more specialized alternative is available to bytes.Buffer which is: strings.Builder. Usage is very similar:

builder := &strings.Builder{}
if err := t.Execute(builder, data); err != nil {
    panic(err)
}
s := builder.String()

Try this one on the Go Playground.

Note: you may also display the result of a template execution if you provide os.Stdout as the target (which also implements io.Writer):

t := template.Must(template.New("email").Parse(emailTmpl))
if err := t.Execute(os.Stdout, data); err != nil {
    panic(err)
}

This will write the result directly to os.Stdout. Try this on the Go Playground.

Parse Json string in C#

json:
[{"ew":"vehicles","hws":["car","van","bike","plane","bus"]},{"ew":"countries","hws":["America","India","France","Japan","South Africa"]}]

c# code: to take only a single value, for example the word "bike".

//res=[{"ew":"vehicles","hws":["car","van","bike","plane","bus"]},{"ew":"countries","hws":["America","India","France","Japan","South Africa"]}]

         dynamic stuff1 = Newtonsoft.Json.JsonConvert.DeserializeObject(res);
         string Text = stuff1[0].hws[2];
         Console.WriteLine(Text);

output:

bike

How to check Spark Version

You can get the spark version by using the following command:

spark-submit --version

spark-shell --version

spark-sql --version

You can visit the below site to know the spark-version used in CDH 5.7.0

http://www.cloudera.com/documentation/enterprise/release-notes/topics/cdh_rn_new_in_cdh_57.html#concept_m3k_rxh_1v

App crashing when trying to use RecyclerView on android 5.0

I had this problem when using Butterknife library. I had:

View rootView = inflater.inflate
                (R.layout.fragment_recipe_detail_view, container, false);
ButterKnife.bind(rootView);

But the correct version is:

View rootView = inflater.inflate
                (R.layout.fragment_recipe_detail_view, container, false);
ButterKnife.bind(this, rootView);

Upload files with HTTPWebrequest (multipart/form-data)

I wrote a class using WebClient way back when to do multipart form upload.

http://ferozedaud.blogspot.com/2010/03/multipart-form-upload-helper.html

/// 
/// MimePart
/// Abstract class for all MimeParts
/// 

abstract class MimePart
{
    public string Name { get; set; }

    public abstract string ContentDisposition { get; }

    public abstract string ContentType { get; }

    public abstract void CopyTo(Stream stream);

    public String Boundary
    {
        get;
        set;
    }
}

class NameValuePart : MimePart
{
    private NameValueCollection nameValues;

    public NameValuePart(NameValueCollection nameValues)
    {
        this.nameValues = nameValues;
    }

    public override void CopyTo(Stream stream)
    {
        string boundary = this.Boundary;
        StringBuilder sb = new StringBuilder();

        foreach (object element in this.nameValues.Keys)
        {
            sb.AppendFormat("--{0}", boundary);
            sb.Append("\r\n");
            sb.AppendFormat("Content-Disposition: form-data; name=\"{0}\";", element);
            sb.Append("\r\n");
            sb.Append("\r\n");
            sb.Append(this.nameValues[element.ToString()]);

            sb.Append("\r\n");

        }

        sb.AppendFormat("--{0}", boundary);
        sb.Append("\r\n");

        //Trace.WriteLine(sb.ToString());
        byte [] data = Encoding.ASCII.GetBytes(sb.ToString());
        stream.Write(data, 0, data.Length);
    }

    public override string ContentDisposition
    {
        get { return "form-data"; }
    }

    public override string ContentType
    {
        get { return String.Empty; }
    }
} 

class FilePart : MimePart

{

    private Stream input;

    private String contentType;



    public FilePart(Stream input, String name, String contentType)

    {

        this.input = input;

        this.contentType = contentType;

        this.Name = name;

    }



    public override void CopyTo(Stream stream)

    {

        StringBuilder sb = new StringBuilder();

        sb.AppendFormat("Content-Disposition: {0}", this.ContentDisposition);

        if (this.Name != null)

            sb.Append("; ").AppendFormat("name=\"{0}\"", this.Name);

        if (this.FileName != null)

            sb.Append("; ").AppendFormat("filename=\"{0}\"", this.FileName);

        sb.Append("\r\n");

        sb.AppendFormat(this.ContentType);

        sb.Append("\r\n");

        sb.Append("\r\n");



    // serialize the header data.

    byte[] buffer = Encoding.ASCII.GetBytes(sb.ToString());

    stream.Write(buffer, 0, buffer.Length);



    // send the stream.

    byte[] readBuffer = new byte[1024];

    int read = input.Read(readBuffer, 0, readBuffer.Length);

    while (read > 0)

    {

        stream.Write(readBuffer, 0, read);

        read = input.Read(readBuffer, 0, readBuffer.Length);

    }



    // write the terminating boundary

    sb.Length = 0;

    sb.Append("\r\n");

    sb.AppendFormat("--{0}", this.Boundary);

    sb.Append("\r\n");

    buffer = Encoding.ASCII.GetBytes(sb.ToString());

    stream.Write(buffer, 0, buffer.Length);



}

 public override string ContentDisposition
 {
      get { return "file"; }
 }



 public override string ContentType
 {
    get { 
       return String.Format("content-type: {0}", this.contentType); 
     }
 }

 public String FileName { get; set; }

}

    /// 
    /// Helper class that encapsulates all file uploads
    /// in a mime part.
    /// 

    class FilesCollection : MimePart
    {
        private List files;

        public FilesCollection()
        {
            this.files = new List();
            this.Boundary = MultipartHelper.GetBoundary();
        }

        public int Count
        {
            get { return this.files.Count; }
        }

        public override string ContentDisposition
        {
            get
            {
                return String.Format("form-data; name=\"{0}\"", this.Name);
            }
        }

        public override string ContentType
        {
            get { return String.Format("multipart/mixed; boundary={0}", this.Boundary); }
        }

        public override void CopyTo(Stream stream)
        {
            // serialize the headers
            StringBuilder sb = new StringBuilder(128);
            sb.Append("Content-Disposition: ").Append(this.ContentDisposition).Append("\r\n");
            sb.Append("Content-Type: ").Append(this.ContentType).Append("\r\n");
            sb.Append("\r\n");
            sb.AppendFormat("--{0}", this.Boundary).Append("\r\n");

            byte[] headerBytes = Encoding.ASCII.GetBytes(sb.ToString());
            stream.Write(headerBytes, 0, headerBytes.Length);
            foreach (FilePart part in files)
            {
                part.Boundary = this.Boundary;
                part.CopyTo(stream);
            }
        }

        public void Add(FilePart part)
        {
            this.files.Add(part);
        }
    }

/// 
/// Helper class to aid in uploading multipart
/// entities to HTTP web endpoints.
/// 

class MultipartHelper
{
    private static Random random = new Random(Environment.TickCount);

    private List formData = new List();
    private FilesCollection files = null;
    private MemoryStream bufferStream = new MemoryStream();
    private string boundary;

    public String Boundary { get { return boundary; } }

    public static String GetBoundary()
    {
        return Environment.TickCount.ToString("X");
    }

    public MultipartHelper()
    {
        this.boundary = MultipartHelper.GetBoundary();
    }

    public void Add(NameValuePart part)
    {
        this.formData.Add(part);
        part.Boundary = boundary;
    }

    public void Add(FilePart part)
    {
        if (files == null)
        {
            files = new FilesCollection();
        }
        this.files.Add(part);
    }

    public void Upload(WebClient client, string address, string method)
    {
        // set header
        client.Headers.Add(HttpRequestHeader.ContentType, "multipart/form-data; boundary=" + this.boundary);
        Trace.WriteLine("Content-Type: multipart/form-data; boundary=" + this.boundary + "\r\n");

        // first, serialize the form data
        foreach (NameValuePart part in this.formData)
        {
            part.CopyTo(bufferStream);
        }

        // serialize the files.
        this.files.CopyTo(bufferStream);

        if (this.files.Count > 0)
        {
            // add the terminating boundary.
            StringBuilder sb = new StringBuilder();
            sb.AppendFormat("--{0}", this.Boundary).Append("\r\n");
            byte [] buffer = Encoding.ASCII.GetBytes(sb.ToString());
            bufferStream.Write(buffer, 0, buffer.Length);
        }

        bufferStream.Seek(0, SeekOrigin.Begin);

        Trace.WriteLine(Encoding.ASCII.GetString(bufferStream.ToArray()));
        byte [] response = client.UploadData(address, method, bufferStream.ToArray());
        Trace.WriteLine("----- RESPONSE ------");
        Trace.WriteLine(Encoding.ASCII.GetString(response));
    }

    /// 
    /// Helper class that encapsulates all file uploads
    /// in a mime part.
    /// 

    class FilesCollection : MimePart
    {
        private List files;

        public FilesCollection()
        {
            this.files = new List();
            this.Boundary = MultipartHelper.GetBoundary();
        }

        public int Count
        {
            get { return this.files.Count; }
        }

        public override string ContentDisposition
        {
            get
            {
                return String.Format("form-data; name=\"{0}\"", this.Name);
            }
        }

        public override string ContentType
        {
            get { return String.Format("multipart/mixed; boundary={0}", this.Boundary); }
        }

        public override void CopyTo(Stream stream)
        {
            // serialize the headers
            StringBuilder sb = new StringBuilder(128);
            sb.Append("Content-Disposition: ").Append(this.ContentDisposition).Append("\r\n");
            sb.Append("Content-Type: ").Append(this.ContentType).Append("\r\n");
            sb.Append("\r\n");
            sb.AppendFormat("--{0}", this.Boundary).Append("\r\n");

            byte[] headerBytes = Encoding.ASCII.GetBytes(sb.ToString());
            stream.Write(headerBytes, 0, headerBytes.Length);
            foreach (FilePart part in files)
            {
                part.Boundary = this.Boundary;
                part.CopyTo(stream);
            }
        }

        public void Add(FilePart part)
        {
            this.files.Add(part);
        }
    }
}

class Program
{
    static void Main(string[] args)
    {
        Trace.Listeners.Add(new ConsoleTraceListener());
        try
        {
            using (StreamWriter sw = new StreamWriter("testfile.txt", false))
            {
                sw.Write("Hello there!");
            }

            using (Stream iniStream = File.OpenRead(@"c:\platform.ini"))
            using (Stream fileStream = File.OpenRead("testfile.txt"))
            using (WebClient client = new WebClient())
            {
                MultipartHelper helper = new MultipartHelper();

                NameValueCollection props = new NameValueCollection();
                props.Add("fname", "john");
                props.Add("id", "acme");
                helper.Add(new NameValuePart(props));

                FilePart filepart = new FilePart(fileStream, "pics1", "text/plain");
                filepart.FileName = "1.jpg";
                helper.Add(filepart);

                FilePart ini = new FilePart(iniStream, "pics2", "text/plain");
                ini.FileName = "inifile.ini";
                helper.Add(ini);

                helper.Upload(client, "http://localhost/form.aspx", "POST");
            }
        }
        catch (Exception e)
        {
            Trace.WriteLine(e);
        }
    }
}

This will work with all versions of the .NET framework.

Allowed memory size of 262144 bytes exhausted (tried to allocate 24576 bytes)

I was trying to up the limit Wordpress sets on media uploads. I followed advice from some blog I’m not going to mention to raise the limit from 64MB to 2GB.

I did the following:

Created a (php.ini) file in WP ADMIN with the following integers:

upload_max_filesize = 2000MB
post_max_size = 2100MV
memory_limit = 2300MB

I immediately received this error when trying to log into my Wordpress dashboard to check if it worked:

“Allowed memory size of 262144 bytes exhausted (tried to allocate 24576 bytes)"

The above information in this chain helped me tremendously. (Stack usually does BTW)

I modified the PHP.ini file to the following:

upload_max_filesize = 2000M
post_max_size = 2100M
memory_limit = 536870912M

The major difference was only use M, not MB, and set that memory limit high.

As soon as I saved the changed the PHP.ini file, I saved it, went to login again and the login screen reappeared.

I went in and checked media uploads, ands bang:

Image showing twordpress media folder “Add New” box, with limits stated as “MAXIMUM UPLOAD FILE SIZE: 2 GB”

I haven't restarted Apache yet… but all looks good.

Thanks everyone.

Getting URL hash location, and using it in jQuery

Editor's note: the approach below has serious security implications and, depending upon the version of jQuery you are using, may expose your users to XSS attacks. For more detail, see the discussion of the possible attack in the comments on this answer or this explanation on Security Stack Exchange.

You can use the location.hash property to grab the hash of the current page:

var hash = window.location.hash;
$('ul'+hash+':first').show();

Note that this property already contains the # symbol at the beginning.

Actually you don't need the :first pseudo-selector since you are using the ID selector, is assumed that IDs are unique within the DOM.

In case you want to get the hash from an URL string, you can use the String.substring method:

var url = "http://example.com/file.htm#foo";
var hash = url.substring(url.indexOf('#')); // '#foo'

Advice: Be aware that the user can change the hash as he wants, injecting anything to your selector, you should check the hash before using it.

What's the most elegant way to cap a number to a segment?

This expands the ternary option into if/else which minified is equivalent to the ternary option but doesn't sacrifice readability.

const clamp = (value, min, max) => {
  if (value < min) return min;
  if (value > max) return max;
  return value;
}

Minifies to 35b (or 43b if using function):

const clamp=(c,a,l)=>c<a?a:c>l?l:c;

Also, depending on what perf tooling or browser you use you get various outcomes of whether the Math based implementation or ternary based implementation is faster. In the case of roughly the same performance, I would opt for readability.

Difference between variable declaration syntaxes in Javascript (including global variables)?

Keeping it simple :

a = 0

The code above gives a global scope variable

var a = 0;

This code will give a variable to be used in the current scope, and under it

window.a = 0;

This generally is same as the global variable.

LINQ to SQL - Left Outer Join with multiple join conditions

You need to introduce your join condition before calling DefaultIfEmpty(). I would just use extension method syntax:

from p in context.Periods
join f in context.Facts on p.id equals f.periodid into fg
from fgi in fg.Where(f => f.otherid == 17).DefaultIfEmpty()
where p.companyid == 100
select f.value

Or you could use a subquery:

from p in context.Periods
join f in context.Facts on p.id equals f.periodid into fg
from fgi in (from f in fg
             where f.otherid == 17
             select f).DefaultIfEmpty()
where p.companyid == 100
select f.value

How can I add C++11 support to Code::Blocks compiler?

The answer with screenshots (put the checkbox as in the second pic, then press OK):

enter image description here enter image description here

How to run a script file remotely using SSH

I don't know if it's possible to run it just like that.

I usually first copy it with scp and then log in to run it.

scp foo.sh user@host:~
ssh user@host
./foo.sh

Difference between array_push() and $array[] =

both are the same, but array_push makes a loop in it's parameter which is an array and perform $array[]=$element

"Object doesn't support this property or method" error in IE11

We were also facing this issue when using IE version 11 to access our React app (create-react-app with react version 16.0.0 with jQuery v3.1.1) on the enterprise intranet. To solve it, i simply followed the directions at this url which are also listed below:

  1. Make sure to set the DOCTYPE to standards mode by making sure the first line of the master file is: <!DOCTYPE html>

  2. Force IE 11 to use the latest internal version by including the following meta tag in the head tag: <meta http-equiv="X-UA-Compatible" content="IE=edge;" />

NOTE: I did not face the problem when using IE to access the app in development mode on my local machine (localhost:3000). The problem occurred only when accessing the app deployed to the DEV server on the company Intranet, probably because of some company wide Windows OS policy settings and/or IE Internet Options.

How can I access iframe elements with Javascript?

If you have the HTML

<form name="formname" .... id="form-first">
    <iframe id="one" src="iframe2.html">
    </iframe>
</form>

and JavaScript

function iframeRef( frameRef ) {
    return frameRef.contentWindow
        ? frameRef.contentWindow.document
        : frameRef.contentDocument
}

var inside = iframeRef( document.getElementById('one') )

inside is now a reference to the document, so you can do getElementsByTagName('textarea') and whatever you like, depending on what's inside the iframe src.

CSS styling in Django forms

Write your form like:

    class MyForm(forms.Form):
         name = forms.CharField(widget=forms.TextInput(attr={'class':'name'}),label="Your Name")
         message = forms.CharField(widget=forms.Textarea(attr={'class':'message'}), label="Your Message")

In your HTML field do something like:

{% for field in form %}
      <div class="row">
        <label for="{{ field.name}}">{{ field.label}}</label>{{ field }}
     </div>
{% endfor %}

Then in your CSS write something like:

.name{
      /* you already have this class so create it's style form here */
}
.message{
      /* you already have this class so create it's style form here */
}
label[for='message']{
      /* style for label */
}

Hope this answer is worth a try! Note you must have written your views to render the HTML file that contains the form.

Confirmation dialog on ng-click - AngularJS

If you don't mind not using ng-click, it works OK. You can just rename it to something else and still read the attribute, while avoiding the click handler being triggered twice problem there is at the moment.

http://plnkr.co/edit/YWr6o2?p=preview

I think the problem is terminal instructs other directives not to run. Data-binding with {{ }} is just an alias for the ng-bind directive, which is presumably cancelled by terminal.

Can I convert a boolean to Yes/No in a ASP.NET GridView

I use this code for VB:

<asp:TemplateField HeaderText="Active" SortExpression="Active">
    <ItemTemplate><%#IIf(Boolean.Parse(Eval("Active").ToString()), "Yes", "No")%></ItemTemplate>
</asp:TemplateField>

And this should work for C# (untested):

<asp:TemplateField HeaderText="Active" SortExpression="Active">
    <ItemTemplate><%# (Boolean.Parse(Eval("Active").ToString())) ? "Yes" : "No" %></ItemTemplate>
</asp:TemplateField>

How can a Javascript object refer to values in itself?

This can be achieved by using constructor function instead of literal

var o = new function() {
  this.foo = "it";
  this.bar = this.foo + " works"
}

alert(o.bar)

Breaking to a new line with inline-block?

Set the items into display: inline and use :after:

.text span { display: inline }
.break-after:after { content: '\A'; white-space:pre; }

and add the class into your html spans:

<span class="medium break-after">We</span>

How do JavaScript closures work?

A closure is a pairing of:

  1. A function, and
  2. A reference to that function's outer scope (lexical environment)

A lexical environment is part of every execution context (stack frame) and is a map between identifiers (ie. local variable names) and values.

Every function in JavaScript maintains a reference to its outer lexical environment. This reference is used to configure the execution context created when a function is invoked. This reference enables code inside the function to "see" variables declared outside the function, regardless of when and where the function is called.

If a function was called by a function, which in turn was called by another function, then a chain of references to outer lexical environments is created. This chain is called the scope chain.

In the following code, inner forms a closure with the lexical environment of the execution context created when foo is invoked, closing over variable secret:

_x000D_
_x000D_
function foo() {
  const secret = Math.trunc(Math.random()*100)
  return function inner() {
    console.log(`The secret number is ${secret}.`)
  }
}
const f = foo() // `secret` is not directly accessible from outside `foo`
f() // The only way to retrieve `secret`, is to invoke `f`
_x000D_
_x000D_
_x000D_

In other words: in JavaScript, functions carry a reference to a private "box of state", to which only they (and any other functions declared within the same lexical environment) have access. This box of the state is invisible to the caller of the function, delivering an excellent mechanism for data-hiding and encapsulation.

And remember: functions in JavaScript can be passed around like variables (first-class functions), meaning these pairings of functionality and state can be passed around your program: similar to how you might pass an instance of a class around in C++.

If JavaScript did not have closures, then more states would have to be passed between functions explicitly, making parameter lists longer and code noisier.

So, if you want a function to always have access to a private piece of state, you can use a closure.

...and frequently we do want to associate the state with a function. For example, in Java or C++, when you add a private instance variable and a method to a class, you are associating state with functionality.

In C and most other common languages, after a function returns, all the local variables are no longer accessible because the stack-frame is destroyed. In JavaScript, if you declare a function within another function, then the local variables of the outer function can remain accessible after returning from it. In this way, in the code above, secret remains available to the function object inner, after it has been returned from foo.

Uses of Closures

Closures are useful whenever you need a private state associated with a function. This is a very common scenario - and remember: JavaScript did not have a class syntax until 2015, and it still does not have a private field syntax. Closures meet this need.

Private Instance Variables

In the following code, the function toString closes over the details of the car.

_x000D_
_x000D_
function Car(manufacturer, model, year, color) {
  return {
    toString() {
      return `${manufacturer} ${model} (${year}, ${color})`
    }
  }
}
const car = new Car('Aston Martin','V8 Vantage','2012','Quantum Silver')
console.log(car.toString())
_x000D_
_x000D_
_x000D_

Functional Programming

In the following code, the function inner closes over both fn and args.

_x000D_
_x000D_
function curry(fn) {
  const args = []
  return function inner(arg) {
    if(args.length === fn.length) return fn(...args)
    args.push(arg)
    return inner
  }
}

function add(a, b) {
  return a + b
}

const curriedAdd = curry(add)
console.log(curriedAdd(2)(3)()) // 5
_x000D_
_x000D_
_x000D_

Event-Oriented Programming

In the following code, function onClick closes over variable BACKGROUND_COLOR.

_x000D_
_x000D_
const $ = document.querySelector.bind(document)
const BACKGROUND_COLOR = 'rgba(200,200,242,1)'

function onClick() {
  $('body').style.background = BACKGROUND_COLOR
}

$('button').addEventListener('click', onClick)
_x000D_
<button>Set background color</button>
_x000D_
_x000D_
_x000D_

Modularization

In the following example, all the implementation details are hidden inside an immediately executed function expression. The functions tick and toString close over the private state and functions they need to complete their work. Closures have enabled us to modularise and encapsulate our code.

_x000D_
_x000D_
let namespace = {};

(function foo(n) {
  let numbers = []
  function format(n) {
    return Math.trunc(n)
  }
  function tick() {
    numbers.push(Math.random() * 100)
  }
  function toString() {
    return numbers.map(format)
  }
  n.counter = {
    tick,
    toString
  }
}(namespace))

const counter = namespace.counter
counter.tick()
counter.tick()
console.log(counter.toString())
_x000D_
_x000D_
_x000D_

Examples

Example 1

This example shows that the local variables are not copied in the closure: the closure maintains a reference to the original variables themselves. It is as though the stack-frame stays alive in memory even after the outer function exits.

_x000D_
_x000D_
function foo() {
  let x = 42
  let inner  = function() { console.log(x) }
  x = x+1
  return inner
}
var f = foo()
f() // logs 43
_x000D_
_x000D_
_x000D_

Example 2

In the following code, three methods log, increment, and update all close over the same lexical environment.

And every time createObject is called, a new execution context (stack frame) is created and a completely new variable x, and a new set of functions (log etc.) are created, that close over this new variable.

_x000D_
_x000D_
function createObject() {
  let x = 42;
  return {
    log() { console.log(x) },
    increment() { x++ },
    update(value) { x = value }
  }
}

const o = createObject()
o.increment()
o.log() // 43
o.update(5)
o.log() // 5
const p = createObject()
p.log() // 42
_x000D_
_x000D_
_x000D_

Example 3

If you are using variables declared using var, be careful you understand which variable you are closing over. Variables declared using var are hoisted. This is much less of a problem in modern JavaScript due to the introduction of let and const.

In the following code, each time around the loop, a new function inner is created, which closes over i. But because var i is hoisted outside the loop, all of these inner functions close over the same variable, meaning that the final value of i (3) is printed, three times.

_x000D_
_x000D_
function foo() {
  var result = []
  for (var i = 0; i < 3; i++) {
    result.push(function inner() { console.log(i) } )
  }
  return result
}

const result = foo()
// The following will print `3`, three times...
for (var i = 0; i < 3; i++) {
  result[i]() 
}
_x000D_
_x000D_
_x000D_

Final points:

  • Whenever a function is declared in JavaScript closure is created.
  • Returning a function from inside another function is the classic example of closure, because the state inside the outer function is implicitly available to the returned inner function, even after the outer function has completed execution.
  • Whenever you use eval() inside a function, a closure is used. The text you eval can reference local variables of the function, and in the non-strict mode, you can even create new local variables by using eval('var foo = …').
  • When you use new Function(…) (the Function constructor) inside a function, it does not close over its lexical environment: it closes over the global context instead. The new function cannot reference the local variables of the outer function.
  • A closure in JavaScript is like keeping a reference (NOT a copy) to the scope at the point of function declaration, which in turn keeps a reference to its outer scope, and so on, all the way to the global object at the top of the scope chain.
  • A closure is created when a function is declared; this closure is used to configure the execution context when the function is invoked.
  • A new set of local variables is created every time a function is called.

Links

Best way to do Version Control for MS Excel

There is also a program called Beyond Compare that has a quite nice Excel file compare. I found a screenshot in chinese that briefly shows this:

Beyond Compare - comparing two excel files (Chinese)
Original image source

There is a 30 day trial on their page

Form inside a table

If you want a "editable grid" i.e. a table like structure that allows you to make any of the rows a form, use CSS that mimics the TABLE tag's layout: display:table, display:table-row, and display:table-cell.

There is no need to wrap your whole table in a form and no need to create a separate form and table for each apparent row of your table.

Try this instead:

<style>
DIV.table 
{
    display:table;
}
FORM.tr, DIV.tr
{
    display:table-row;
}
SPAN.td
{
    display:table-cell;
}
</style>
...
<div class="table">
    <form class="tr" method="post" action="blah.html">
        <span class="td"><input type="text"/></span>
        <span class="td"><input type="text"/></span>
    </form>
    <div class="tr">
        <span class="td">(cell data)</span>
        <span class="td">(cell data)</span>
    </div>
    ...
</div>

The problem with wrapping the whole TABLE in a FORM is that any and all form elements will be sent on submit (maybe that is desired but probably not). This method allows you to define a form for each "row" and send only that row of data on submit.

The problem with wrapping a FORM tag around a TR tag (or TR around a FORM) is that it's invalid HTML. The FORM will still allow submit as usual but at this point the DOM is broken. Note: Try getting the child elements of your FORM or TR with JavaScript, it can lead to unexpected results.

Note that IE7 doesn't support these CSS table styles and IE8 will need a doctype declaration to get it into "standards" mode: (try this one or something equivalent)

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">

Any other browser that supports display:table, display:table-row and display:table-cell should display your css data table the same as it would if you were using the TABLE, TR and TD tags. Most of them do.

Note that you can also mimic THEAD, TBODY, TFOOT by wrapping your row groups in another DIV with display: table-header-group, table-row-group and table-footer-group respectively.

NOTE: The only thing you cannot do with this method is colspan.

Check out this illustration: http://jsfiddle.net/ZRQPP/

__init__() missing 1 required positional argument

The problem is with, you

def __init__(self, data):

when you create object from DHT class you should pass parameter the data should be dict type, like

data={'one':1,'two':2,'three':3}
dhtObj=DHT(data)

But in your code youshould to change is

data={'one':1,'two':2,'three':3}
if __name__ == '__main__': DHT(data).showData()

Or

if __name__ == '__main__': DHT({'one':1,'two':2,'three':3}).showData()

How should I escape commas and speech marks in CSV files so they work in Excel?

Below are the rules if you believe it's random. A utility function can be created on the basis of these rules.

  1. If the value contains a comma, newline or double quote, then the String value should be returned enclosed in double quotes.

  2. Any double quote characters in the value should be escaped with another double quote.

  3. If the value does not contain a comma, newline or double quote, then the String value should be returned unchanged.

How to store arbitrary data for some HTML tags

At my previous employer, we used custom HTML tags all the time to hold info about the form elements. The catch: We knew that the user was forced to use IE.

It didn't work well for FireFox at the time. I don't know if FireFox has changed this or not, but be aware that adding your own attributes to HTML elements may or may-not be supported by your reader's browser.

If you can control which browser your reader is using (i.e. an internal web applet for a corporation), then by all means, try it. What can it hurt, right?

How to create my json string by using C#?

The json is kind of odd, it's like the students are properties of the "GetQuestion" object, it should be easy to be a List.....

About the libraries you could use are.

And there could be many more, but that are what I've used

About the json I don't now maybe something like this

public class GetQuestions
{
    public List<Student> Questions { get; set; }
}

public class Student
{
    public string Code { get; set; }
    public string Questions { get; set; }
}

void Main()
{
    var gq = new GetQuestions
    {
        Questions = new List<Student>
        {
            new Student {Code = "s1", Questions = "Q1,Q2"},
            new Student {Code = "s2", Questions = "Q1,Q2,Q3"},
            new Student {Code = "s3", Questions = "Q1,Q2,Q4"},
            new Student {Code = "s4", Questions = "Q1,Q2,Q5"},
        }
    };

    //Using Newtonsoft.json. Dump is an extension method of [Linqpad][4]
    JsonConvert.SerializeObject(gq).Dump();
}

Linqpad

and the result is this

{
     "Questions":[
        {"Code":"s1","Questions":"Q1,Q2"},
        {"Code":"s2","Questions":"Q1,Q2,Q3"},
        {"Code":"s3","Questions":"Q1,Q2,Q4"},
        {"Code":"s4","Questions":"Q1,Q2,Q5"}
      ]
 }

Yes I know the json is different, but the json that you want with dictionary.

void Main()
{
    var f = new Foo
    {
        GetQuestions = new Dictionary<string, string>
                {
                    {"s1", "Q1,Q2"},
                    {"s2", "Q1,Q2,Q3"},
                    {"s3", "Q1,Q2,Q4"},
                    {"s4", "Q1,Q2,Q4,Q6"},
                }
    };

    JsonConvert.SerializeObject(f).Dump();
}

class Foo
{
    public Dictionary<string, string> GetQuestions { get; set; }
}

And with Dictionary is as you want it.....

{
      "GetQuestions":
       {
              "s1":"Q1,Q2",
              "s2":"Q1,Q2,Q3",
              "s3":"Q1,Q2,Q4",
              "s4":"Q1,Q2,Q4,Q6"
       }
 }

Get ID of element that called a function

i also want this to happen , so just pass the id of the element in the called function and used in my js file :

function copy(i,n)
{
 var range = document.createRange();
range.selectNode(document.getElementById(i));
window.getSelection().removeAllRanges();
window.getSelection().addRange(range); 
document.execCommand('copy');
window.getSelection().removeAllRanges();
document.getElementById(n).value = "Copied";
}

select count(*) from table of mysql in php

Please start using PDO.

mysql_* is deprecated as of PHP 5.5.0 and will be removed entirely in 7. Let's make it easier to upgrade and start using it now.

$dbh = new \PDO($dsn, $user, $password);
$sth = $dbh->prepare('SELECT count(*) as total from Students');
$sth->execute();
print_r($sth->fetchColumn());

Writing files in Node.js

You may write to a file using fs (file system) module.

Here is an example of how you may do it:

const fs = require('fs');

const writeToFile = (fileName, callback) => {
  fs.open(fileName, 'wx', (error, fileDescriptor) => {
    if (!error && fileDescriptor) {
      // Do something with the file here ...
      fs.writeFile(fileDescriptor, newData, (error) => {
        if (!error) {
          fs.close(fileDescriptor, (error) => {
            if (!error) {
              callback(false);
            } else {
              callback('Error closing the file');
            }
          });
        } else {
          callback('Error writing to new file');
        }
      });
    } else {
      callback('Could not create new file, it may already exists');
    }
  });
};

You might also want to get rid of this callback-inside-callback code structure by useing Promises and async/await statements. This will make asynchronous code structure much more flat. For doing that there is a handy util.promisify(original) function might be utilized. It allows us to switch from callbacks to promises. Take a look at the example with fs functions below:

// Dependencies.
const util = require('util');
const fs = require('fs');

// Promisify "error-back" functions.
const fsOpen = util.promisify(fs.open);
const fsWrite = util.promisify(fs.writeFile);
const fsClose = util.promisify(fs.close);

// Now we may create 'async' function with 'await's.
async function doSomethingWithFile(fileName) {
  const fileDescriptor = await fsOpen(fileName, 'wx');

  // Do something with the file here...

  await fsWrite(fileDescriptor, newData);
  await fsClose(fileDescriptor);
}

MySQL/SQL: Group by date only on a Datetime column

I found that I needed to group by the month and year so neither of the above worked for me. Instead I used date_format

SELECT date
FROM blog 
GROUP BY DATE_FORMAT(date, "%m-%y")
ORDER BY YEAR(date) DESC, MONTH(date) DESC 

plot data from CSV file with matplotlib

According to the docs numpy.loadtxt is

a fast reader for simply formatted files. The genfromtxt function provides more sophisticated handling of, e.g., lines with missing values.

so there are only a few options to handle more complicated files. As mentioned numpy.genfromtxt has more options. So as an example you could use

import numpy as np
data = np.genfromtxt('e:\dir1\datafile.csv', delimiter=',', skip_header=10,
                     skip_footer=10, names=['x', 'y', 'z'])

to read the data and assign names to the columns (or read a header line from the file with names=True) and than plot it with

ax1.plot(data['x'], data['y'], color='r', label='the data')

I think numpy is quite well documented now. You can easily inspect the docstrings from within ipython or by using an IDE like spider if you prefer to read them rendered as HTML.

Travel/Hotel API's?

Check out api.hotelsbase.org - its a free xml hotel api No images as of yet though

Changing text color of menu item in navigation drawer

More options:

you can also change the group title by overriding "textColorSecondary"

In your styles.xml

<style name="AppTheme.NavigationView">
    <item name="android:textColorSecondary">#FFFFFF</item>
</style>

In your layout

<android.support.design.widget.NavigationView
    android:id="@+id/nav_view"
    android:layout_width="wrap_content"
    android:layout_height="match_parent"
    android:layout_gravity="start"
    android:fitsSystemWindows="true"
    app:menu="@menu/activity_main_menu_drawer_drawer"
    android:theme="@style/AppTheme.NavigationView"
    app:itemIconTint="@color/colorPrimary"
    app:itemTextColor="@color/white"/>

Node.js fs.readdir recursive directory search

Standalone promise implementation

I am using the when.js promise library in this example.

var fs = require('fs')
, path = require('path')
, when = require('when')
, nodefn = require('when/node/function');

function walk (directory, includeDir) {
    var results = [];
    return when.map(nodefn.call(fs.readdir, directory), function(file) {
        file = path.join(directory, file);
        return nodefn.call(fs.stat, file).then(function(stat) {
            if (stat.isFile()) { return results.push(file); }
            if (includeDir) { results.push(file + path.sep); }
            return walk(file, includeDir).then(function(filesInDir) {
                results = results.concat(filesInDir);
            });
        });
    }).then(function() {
        return results;
    });
};

walk(__dirname).then(function(files) {
    console.log(files);
}).otherwise(function(error) {
    console.error(error.stack || error);
});

I've included an optional parameter includeDir which will include directories in the file listing if set to true.

how to change class name of an element by jquery

$('.IsBestAnswer').addClass('bestanswer').removeClass('IsBestAnswer');

Case in method names is important, so no addclass.

jQuery addClass()
jQuery removeClass()

Server cannot set status after HTTP headers have been sent IIS7.5

How about checking this before doing the redirect:

if (!Response.IsRequestBeingRedirected)
{
   //do the redirect
}

How can I get the current date and time in UTC or GMT in Java?

This worked for me, returns the timestamp in GMT!

    Date currDate;
    SimpleDateFormat dateFormatGmt = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");
    dateFormatGmt.setTimeZone(TimeZone.getTimeZone("GMT"));
    SimpleDateFormat dateFormatLocal = new SimpleDateFormat("yyyy-MMM-dd HH:mm:ss");

    long currTime = 0;
    try {

        currDate = dateFormatLocal.parse( dateFormatGmt.format(new Date()) );
        currTime = currDate.getTime();
    } catch (ParseException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }

Why is char[] preferred over String for passwords?

To quote an official document, the Java Cryptography Architecture guide says this about char[] vs. String passwords (about password-based encryption, but this is more generally about passwords of course):

It would seem logical to collect and store the password in an object of type java.lang.String. However, here's the caveat: Objects of type String are immutable, i.e., there are no methods defined that allow you to change (overwrite) or zero out the contents of a String after usage. This feature makes String objects unsuitable for storing security sensitive information such as user passwords. You should always collect and store security sensitive information in a char array instead.

Guideline 2-2 of the Secure Coding Guidelines for the Java Programming Language, Version 4.0 also says something similar (although it is originally in the context of logging):

Guideline 2-2: Do not log highly sensitive information

Some information, such as Social Security numbers (SSNs) and passwords, is highly sensitive. This information should not be kept for longer than necessary nor where it may be seen, even by administrators. For instance, it should not be sent to log files and its presence should not be detectable through searches. Some transient data may be kept in mutable data structures, such as char arrays, and cleared immediately after use. Clearing data structures has reduced effectiveness on typical Java runtime systems as objects are moved in memory transparently to the programmer.

This guideline also has implications for implementation and use of lower-level libraries that do not have semantic knowledge of the data they are dealing with. As an example, a low-level string parsing library may log the text it works on. An application may parse an SSN with the library. This creates a situation where the SSNs are available to administrators with access to the log files.

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

Updated for Apache 2.4, for non-systemd (e.g., CentOS 6.x, Amazon Linux AMI) and for systemd (e.g., CentOS 7.x):

There are two ways of having the apache process reload the configuration, depending on what you want done with its current threads, either advise to exit when idle, or killing them directly.

Note that Apache recommends using apachectl -k as the command, and for systemd, the command is replaced by httpd -k

apachectl -k graceful or httpd -k graceful

Apache will advise its threads to exit when idle, and then apache reloads the configuration (it doesn't exit itself), this means statistics are not reset.

apachectl -k restart or httpd -k restart

This is similar to stop, in that the process kills off its threads, but then the process reloads the configuration file, rather than killing itself.

Source: https://httpd.apache.org/docs/2.4/stopping.html

I want to use CASE statement to update some records in sql server 2005

Add a WHERE clause

UPDATE dbo.TestStudents  
SET     LASTNAME =  CASE  
                        WHEN LASTNAME = 'AAA' THEN 'BBB' 
                        WHEN LASTNAME = 'CCC' THEN 'DDD' 
                        WHEN LASTNAME = 'EEE' THEN 'FFF' 
                        ELSE LASTNAME
                    END 
WHERE   LASTNAME IN ('AAA', 'CCC', 'EEE')

Can not deserialize instance of java.util.ArrayList out of VALUE_STRING

For people that find this question by searching for the error message, you can also see this error if you make a mistake in your @JsonProperty annotations such that you annotate a List-typed property with the name of a single-valued field:

@JsonProperty("someSingleValuedField") // Oops, should have been "someMultiValuedField"
public List<String> getMyField() { // deserialization fails - single value into List
  return myField;
}

What is the difference between Google App Engine and Google Compute Engine?

In addition to the App Engine vs Compute Engine notes above the list here also includes a comparison with Google Kubernete Engine and some notes based on experience with a wide range of apps from small to very large. For more points see the Google Cloud Platform documentation high level description of features in App Engine Standard and Flex on the page Choosing an App Engine Environment. For another comparison of deployment of App Engine and Kubernetes see the post by Daz Wilkin App Engine Flex or Kubernetes Engine.

App Engine Standard

Pros

  • Very economical for low traffic apps in terms of direct costs and also the cost of maintaining the app.
  • Auto scaling is fast. Autoscaling in App Engine is based on lightweight instance classes F1-F4.
  • Version management and traffic splitting are fast and convenient. These features are built into App Engine (both Standard and Flex) natively.
  • Minimal management, developers need focus only on their app. Developers do not need to worry about managing VMs in a reliable, as in GCE, or learning about clusters, as with GKE.
  • Access to Datastore is fast. When App Engine was first released, the runtime was co-located with Datastore. Later Datastore was split out as the standalone product Cloud Datastore but the co-location of App Engine Standard serving with Datastore remains.
  • Access to Memcache is supported.
  • The App Engine sandbox is very secure. Compared with development on GCE or other virtual machines, where you need to do your own diligence to prevent the virtual machine from being taken over at the operating system level, the App Engine Standard sandbox is relatively secure by default.

Cons

  • Generally more constrained than other environments Instances are smaller. Although this is good for rapid autoscaling, many apps can benefit from larger instances, such as GCE instance sizes up to 96 cores.
  • Networking is not integrated with GCE
  • Cannot put App Engine behind a Google Cloud Load Balancer. Limited to supported runtimes: Python 2.7, Java 7 and 8, Go 1.6-1.9, and PHP 5.5. In Java, there is some support for Servlets but not the full J2EE standard.

App Engine Flex

Pros

  • Can use a custom runtime
  • Native integration with GCE networking
  • Version and traffic management is convenient, same as Standard
  • The larger instance sizes may be more suitable to to large complex applications, especially Java applications that can use a lot of memory

Cons

  • Network integration is not perfect - no integration with internal load balancers or Shared Virtual Private Clouds
  • Access to managed Memcache not generally available

Google Kubernetes Engine

Pros

  • Native integration with containers allows custom runtimes and greater control over cluster configuration.
  • Embodies many best practices working with virtual machines, such as immutable runtime environments and easy ability to roll back to previous versions
  • Provides a consistent and repeatable deployment framework
  • Based on open standards, notably Kubernetes, for portability between clouds and on-premises.
  • Version management can accomplished with Docker containers and the Google Container Registry

Cons

  • Traffic splitting and management is do-it-yourself, possibly leveraging Istio and Envoy
  • Some management overhead
  • Some time to ramp up on Kubernetes concepts, such as pods, deployments, services, ingress, and namespaces
  • Need to expose some public IPs unless using Private Clusters, now in beta, eliminate that need but you still need to provide access to locations where kubectl commands will be run from.
  • Monitoring integration not perfect
  • While L3 internal load balancing is supported natively on Kubernetes Engine, L7 internal load balancing is do-it-yourself, possibly leveraging Envoy

Compute Engine

Pros

  • Easy to ramp up - no need to ramp up on Kubernetes or App Engine, just reuse whatever you know from previous experience. This is probably the main reason for using Compute Engine directly.
  • Complete control - you can leverage many Compute Engine features directly and install the latest of all your favorite stuff to stay on the bleeding edge.
  • No need for public IPs. Some legacy software may be too hard to lock down if anything is exposed on public IPs.
  • You can leverage the Container-Optimized OS for running Docker containers

Cons

  • Mostly do-it-yourself, which can be challenging to do adequately for reliability and security, although you can reuse solutions from various places, including the Cloud Launcher.
  • More management overhead. There are many management tools for Compute Engine but they will not necessarily understand how you have deployed your application, like the App Engine and Kubernetes Engine monitoring tools do
  • Autoscaling is based on GCE instances, which can be slower than App Engine
  • Tendency is to install software on snowflake GCE instances, which can be some effort to maintain

Trim a string in C

You can use the standard isspace() function in ctype.h to achieve this. Simply compare the beginning and end characters of your character array until both ends no longer have spaces.

"spaces" include:

' ' (0x20) space (SPC)

'\t' (0x09) horizontal tab (TAB)

'\n' (0x0a) newline (LF)

'\v' (0x0b) vertical tab (VT)

'\f' (0x0c) feed (FF)

'\r' (0x0d) carriage return (CR)

although there is no function which will do all of the work for you, you will have to roll your own solution to compare each side of the given character array repeatedly until no spaces remain.

Edit:

Since you have access to C++, Boost has a trim implementation waiting for you to make your life a lot easier.

How can I call a method in Objective-C?

[self score]; instead of @selector(score)

Does VBA contain a comment block syntax?

There is no syntax for block quote in VBA. The work around is to use the button to quickly block or unblock multiple lines of code.

Show/hide forms using buttons and JavaScript

There's the global attribute called hidden. But I'm green to all this and maybe there was a reason it wasn't mentioned yet?

_x000D_
_x000D_
var someCondition = true;_x000D_
_x000D_
if (someCondition == true){_x000D_
    document.getElementById('hidden div').hidden = false;_x000D_
}
_x000D_
<div id="hidden div" hidden>_x000D_
    stuff hidden by default_x000D_
</div>
_x000D_
_x000D_
_x000D_

https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/hidden

How to create a new text file using Python

    file = open("path/of/file/(optional)/filename.txt", "w") #a=append,w=write,r=read
    any_string = "Hello\nWorld"
    file.write(any_string)
    file.close()

How to make a HTTP PUT request?

How to use PUT method using WebRequest.

    //JsonResultModel class
    public class JsonResultModel
    {
       public string ErrorMessage { get; set; }
       public bool IsSuccess { get; set; }
       public string Results { get; set; }
    }
    // HTTP_PUT Function
    public static JsonResultModel HTTP_PUT(string Url, string Data)
    {
        JsonResultModel model = new JsonResultModel();
        string Out = String.Empty;
        string Error = String.Empty;
        System.Net.WebRequest req = System.Net.WebRequest.Create(Url);

        try
        {
            req.Method = "PUT";
            req.Timeout = 100000;
            req.ContentType = "application/json";
            byte[] sentData = Encoding.UTF8.GetBytes(Data);
            req.ContentLength = sentData.Length;

            using (System.IO.Stream sendStream = req.GetRequestStream())
            {
                sendStream.Write(sentData, 0, sentData.Length);
                sendStream.Close();

            }

            System.Net.WebResponse res = req.GetResponse();
            System.IO.Stream ReceiveStream = res.GetResponseStream();
            using (System.IO.StreamReader sr = new 
            System.IO.StreamReader(ReceiveStream, Encoding.UTF8))
            {

                Char[] read = new Char[256];
                int count = sr.Read(read, 0, 256);

                while (count > 0)
                {
                    String str = new String(read, 0, count);
                    Out += str;
                    count = sr.Read(read, 0, 256);
                }
            }
        }
        catch (ArgumentException ex)
        {
            Error = string.Format("HTTP_ERROR :: The second HttpWebRequest object has raised an Argument Exception as 'Connection' Property is set to 'Close' :: {0}", ex.Message);
        }
        catch (WebException ex)
        {
            Error = string.Format("HTTP_ERROR :: WebException raised! :: {0}", ex.Message);
        }
        catch (Exception ex)
        {
            Error = string.Format("HTTP_ERROR :: Exception raised! :: {0}", ex.Message);
        }

        model.Results = Out;
        model.ErrorMessage = Error;
        if (!string.IsNullOrWhiteSpace(Out))
        {
            model.IsSuccess = true;
        }
        return model;
    }

Check if string ends with certain pattern

I tried all the different things mentioned here to get the index of the . character in a filename that ends with .[0-9][0-9]*, e.g. srcfile.1, srcfile.12, etc. Nothing worked. Finally, the following worked: int dotIndex = inputfilename.lastIndexOf(".");

Weird! This is with java -version:

openjdk version "1.8.0_131"
OpenJDK Runtime Environment (build 1.8.0_131-8u131-b11-0ubuntu1.16.10.2-b11)
OpenJDK 64-Bit Server VM (build 25.131-b11, mixed mode)

Also, the official Java doc page for regex (from which there is a quote in one of the answers above) does not seem to specify how to look for the . character. Because \., \\., and [.] did not work for me, and I don't see any other options specified apart from these.

How can I shrink the drawable on a button?

I am doing it as below. This creates a 100x100 size image in the button independent of the input image.

drawable.bounds = Rect(0,0,100,100)
button.setCompoundDrawables(drawable, null, null, null)

Not using ScaleDrawable either. Not using button.setCompoundDrawablesRelativeWithIntrinsicBounds() solved my problem, as that seems to use intrinsic bounds (source image size) instead of the bounds you just set.

Batch file to map a drive when the folder name contains spaces

I just created some directories, shared them and mapped using:

net use y: "\\mycomputername\folder with spaces"

So this solution gets "works on my machine" certificate. What error code do you get?

HTTP Request in Kotlin

I think using okhttp is the easiest solution. Here you can see an example for POST method, sending a json, and with auth.

val url = "https://example.com/endpoint"

val client = OkHttpClient()

val JSON = MediaType.get("application/json; charset=utf-8")
val body = RequestBody.create(JSON, "{\"data\":\"$data\"}")
val request = Request.Builder()
        .addHeader("Authorization", "Bearer $token")
        .url(url)
        .post(body)
        .build()

val  response = client . newCall (request).execute()

println(response.request())
println(response.body()!!.string())

Remember to add this dependency to your project https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp

UPDATE: July 7th, 2019 I'm gonna give two examples using latest Kotlin (1.3.41), OkHttp (4.0.0) and Jackson (2.9.9).

UPDATE: January 25th, 2021 Everything is okay with the most updated versions.

<!-- https://mvnrepository.com/artifact/com.fasterxml.jackson.module/jackson-module-kotlin -->
        <dependency>
            <groupId>com.fasterxml.jackson.module</groupId>
            <artifactId>jackson-module-kotlin</artifactId>
            <version>2.12.1</version>
        </dependency>

<!-- https://mvnrepository.com/artifact/com.squareup.okhttp3/okhttp -->
        <dependency>
            <groupId>com.squareup.okhttp3</groupId>
            <artifactId>okhttp</artifactId>
            <version>4.9.0</version>
        </dependency>

Get Method

fun get() {
    val client = OkHttpClient()
    val url = URL("https://reqres.in/api/users?page=2")

    val request = Request.Builder()
            .url(url)
            .get()
            .build()

    val response = client.newCall(request).execute()

    val responseBody = response.body!!.string()

    //Response
    println("Response Body: " + responseBody)

    //we could use jackson if we got a JSON
    val mapperAll = ObjectMapper()
    val objData = mapperAll.readTree(responseBody)

    objData.get("data").forEachIndexed { index, jsonNode ->
        println("$index $jsonNode")
    }
}

POST Method

fun post() {
    val client = OkHttpClient()
    val url = URL("https://reqres.in/api/users")

    //just a string
    var jsonString = "{\"name\": \"Rolando\", \"job\": \"Fakeador\"}"

    //or using jackson
    val mapperAll = ObjectMapper()
    val jacksonObj = mapperAll.createObjectNode()
    jacksonObj.put("name", "Rolando")
    jacksonObj.put("job", "Fakeador")
    val jacksonString = jacksonObj.toString()

    val mediaType = "application/json; charset=utf-8".toMediaType()
    val body = jacksonString.toRequestBody(mediaType)

    val request = Request.Builder()
            .url(url)
            .post(body)
            .build()

    val response = client.newCall(request).execute()

    val responseBody = response.body!!.string()

    //Response
    println("Response Body: " + responseBody)

    //we could use jackson if we got a JSON
    val objData = mapperAll.readTree(responseBody)

    println("My name is " + objData.get("name").textValue() + ", and I'm a " + objData.get("job").textValue() + ".")
}

'and' (boolean) vs '&' (bitwise) - Why difference in behavior with lists vs numpy arrays?

Good question. Similar to the observation you have about examples 1 and 4 (or should I say 1 & 4 :) ) over logical and bitwise & operators, I experienced on sum operator. The numpy sum and py sum behave differently as well. For example:

Suppose "mat" is a numpy 5x5 2d array such as:

array([[ 1,  2,  3,  4,  5],
       [ 6,  7,  8,  9, 10],
       [11, 12, 13, 14, 15],
       [16, 17, 18, 19, 20],
       [21, 22, 23, 24, 25]])

Then numpy.sum(mat) gives total sum of the entire matrix. Whereas the built-in sum from Python such as sum(mat) totals along the axis only. See below:

np.sum(mat)  ## --> gives 325
sum(mat)     ## --> gives array([55, 60, 65, 70, 75])

The Network Adapter could not establish the connection when connecting with Oracle DB

Take a look at this post on Java Ranch:

http://www.coderanch.com/t/300287/JDBC/java/Io-Exception-Network-Adapter-could

"The solution for my "Io exception: The Network Adapter could not establish the connection" exception was to replace the IP of the database server to the DNS name."

How to upgrade Angular CLI project?

Solution that worked for me:

  • Delete node_modules and dist folder
  • (in cmd)>> ng update --all --force
  • (in cmd)>> npm install typescript@">=3.4.0 and <3.5.0" --save-dev --save-exact
  • (in cmd)>> npm install --save core-js
  • Commenting import 'core-js/es7/reflect'; in polyfill.ts
  • (in cmd)>> ng serve

How do I determine k when using k-means clustering?

I worked on a Python package kneed (Kneedle algorithm). It finds cluster numbers dynamically as the point where the curve starts to flatten. Given a set of x and y values, kneed will return the knee point of the function. The knee joint is the point of maximum curvature. Here is the sample code.

y = [7342.1301373073857, 6881.7109460930769, 6531.1657905495022,  
6356.2255554679778, 6209.8382535595829, 6094.9052166741121, 
5980.0191582610196, 5880.1869867848218, 5779.8957906367368, 
5691.1879324562778, 5617.5153566271356, 5532.2613232619951, 
5467.352265375117, 5395.4493783888756, 5345.3459908298091, 
5290.6769823693812, 5243.5271656371888, 5207.2501206569532, 
5164.9617535255456]

x = range(1, len(y)+1)

from kneed import KneeLocator
kn = KneeLocator(x, y, curve='convex', direction='decreasing')

print(kn.knee)

An invalid XML character (Unicode: 0xc) was found

Today, I've got a similar error:

Servlet.service() for servlet [remoting] in context with path [/***] threw exception [Request processing failed; nested exception is java.lang.RuntimeException: buildDocument failed.] with root cause org.xml.sax.SAXParseException; lineNumber: 19; columnNumber: 91; An invalid XML character (Unicode: 0xc) was found in the value of attribute "text" and element is "label".


After my first encouter with the error, I had re-typed the entire line by hand, so that there was no way for a special character to creep in, and Notepad++ didn't show any non-printable characters (black on white), nevertheless I got the same error over and over.

When I looked up what I've done different than my predecessors, it turned out it was one additional space just before the closing /> (as I've heard was recommended for older parsers, but it shouldn't make any difference anyway, by the XML standards):

<label text="this label's text" layout="cell 0 0, align left" />

When I removed the space:

<label text="this label's text" layout="cell 0 0, align left"/>

everything worked just fine.


So it's definitely a misleading error message.

What EXACTLY is meant by "de-referencing a NULL pointer"?

A NULL pointer points to memory that doesn't exist, and will raise Segmentation fault. There's an easier way to de-reference a NULL pointer, take a look.

int main(int argc, char const *argv[])
{
    *(int *)0 = 0; // Segmentation fault (core dumped)
    return 0;
}

Since 0 is never a valid pointer value, a fault occurs.

SIGSEGV {si_signo=SIGSEGV, si_code=SEGV_MAPERR, si_addr=NULL}

How do I generate a constructor from class fields using Visual Studio (and/or ReSharper)?

Here's JMarsh's Visual Studio macro modified to generate a constructor based on the fields and properties in the class.

Imports System
Imports EnvDTE
Imports EnvDTE80
Imports EnvDTE90
Imports EnvDTE100
Imports System.Diagnostics
Imports System.Collections.Generic

Public Module ConstructorEditor

    Public Sub AddConstructorFromFields()

        Dim classInfo As CodeClass2 = GetClassElement()
        If classInfo Is Nothing Then
            System.Windows.Forms.MessageBox.Show("No class was found surrounding the cursor.  Make sure that this file compiles and try again.", "Error")
            Return
        End If

        ' Setting up undo context. One Ctrl+Z undoes everything
        Dim closeUndoContext As Boolean = False
        If DTE.UndoContext.IsOpen = False Then
            closeUndoContext = True
            DTE.UndoContext.Open("AddConstructorFromFields", False)
        End If

        Try
            Dim dataMembers As List(Of DataMember) = GetDataMembers(classInfo)
            AddConstructor(classInfo, dataMembers)
        Finally
            If closeUndoContext Then
                DTE.UndoContext.Close()
            End If
        End Try

    End Sub

    Private Function GetClassElement() As CodeClass2
        ' Returns a CodeClass2 element representing the class that the cursor is within, or null if there is no class
        Try
            Dim selection As TextSelection = DTE.ActiveDocument.Selection
            Dim fileCodeModel As FileCodeModel2 = DTE.ActiveDocument.ProjectItem.FileCodeModel
            Dim element As CodeElement2 = fileCodeModel.CodeElementFromPoint(selection.TopPoint, vsCMElement.vsCMElementClass)
            Return element
        Catch
            Return Nothing
        End Try
    End Function

    Private Function GetDataMembers(ByVal classInfo As CodeClass2) As System.Collections.Generic.List(Of DataMember)

        Dim dataMembers As List(Of DataMember) = New List(Of DataMember)
        Dim prop As CodeProperty2
        Dim v As CodeVariable2

        For Each member As CodeElement2 In classInfo.Members

            prop = TryCast(member, CodeProperty2)
            If Not prop Is Nothing Then
                dataMembers.Add(DataMember.FromProperty(prop.Name, prop.Type))
            End If

            v = TryCast(member, CodeVariable2)
            If Not v Is Nothing Then
                If v.Name.StartsWith("_") And Not v.IsConstant Then
                    dataMembers.Add(DataMember.FromPrivateVariable(v.Name, v.Type))
                End If
            End If

        Next

        Return dataMembers

    End Function

    Private Sub AddConstructor(ByVal classInfo As CodeClass2, ByVal dataMembers As List(Of DataMember))

        ' Put constructor after the data members
        Dim position As Object = dataMembers.Count

        ' Add new constructor
        Dim ctor As CodeFunction2 = classInfo.AddFunction(classInfo.Name, vsCMFunction.vsCMFunctionConstructor, vsCMTypeRef.vsCMTypeRefVoid, position, vsCMAccess.vsCMAccessPublic)

        For Each dataMember As DataMember In dataMembers
            ctor.AddParameter(dataMember.NameLocal, dataMember.Type, -1)
        Next

        ' Assignments
        Dim startPoint As TextPoint = ctor.GetStartPoint(vsCMPart.vsCMPartBody)
        Dim point As EditPoint = startPoint.CreateEditPoint()
        For Each dataMember As DataMember In dataMembers
            point.Insert("            " + dataMember.Name + " = " + dataMember.NameLocal + ";" + Environment.NewLine)
        Next

    End Sub

    Class DataMember

        Public Name As String
        Public NameLocal As String
        Public Type As Object

        Private Sub New(ByVal name As String, ByVal nameLocal As String, ByVal type As Object)
            Me.Name = name
            Me.NameLocal = nameLocal
            Me.Type = type
        End Sub

        Shared Function FromProperty(ByVal name As String, ByVal type As Object)

            Dim nameLocal As String
            If Len(name) > 1 Then
                nameLocal = name.Substring(0, 1).ToLower + name.Substring(1)
            Else
                nameLocal = name.ToLower()
            End If

            Return New DataMember(name, nameLocal, type)

        End Function

        Shared Function FromPrivateVariable(ByVal name As String, ByVal type As Object)

            If Not name.StartsWith("_") Then
                Throw New ArgumentException("Expected private variable name to start with underscore.")
            End If

            Dim nameLocal As String = name.Substring(1)

            Return New DataMember(name, nameLocal, type)

        End Function

    End Class

End Module

jQuery UI Tabs - How to Get Currently Selected Tab Index

If you're using JQuery UI version 1.9.0 or above, you can access ui.newTab.index() inside your function and get what you need.

For earlier versions use ui.index.

Create parameterized VIEW in SQL Server 2008

Try creating an inline table-valued function. Example:

CREATE FUNCTION dbo.fxnExample (@Parameter1 INTEGER)
RETURNS TABLE
AS
RETURN
(
    SELECT Field1, Field2
    FROM SomeTable
    WHERE Field3 = @Parameter1
)

-- Then call like this, just as if it's a table/view just with a parameter
SELECT * FROM dbo.fxnExample(1)

If you view the execution plan for the SELECT you will not see a mention of the function at all and will actually just show you the underlying tables being queried. This is good as it means statistics on the underlying tables will be used when generating an execution plan for the query.

The thing to avoid would be a multi-statement table valued function as underlying table statistics will not be used and can result in poor performance due to a poor execution plan.
Example of what to avoid:

CREATE FUNCTION dbo.fxnExample (@Parameter1 INTEGER)
    RETURNS @Results TABLE(Field1 VARCHAR(10), Field2 VARCHAR(10))
AS
BEGIN
    INSERT @Results
    SELECT Field1, Field2
    FROM SomeTable
    WHERE Field3 = @Parameter1

    RETURN
END

Subtly different, but with potentially big differences in performance when the function is used in a query.

Executing JavaScript without a browser?

I use Ubuntu 12.10 and js from commandline

It is available with my installation of java:

el@apollo:~/foo$ java -version
java version "1.6.0_27"
el@apollo:~/foo$ which js
/usr/bin/js

Some examples:

el@apollo:~/foo$ js
> 5
5

> console.log("hello");
hello
undefined

> var f = function(){ console.log("derp"); };
undefined
> f();
derp

> var mybool = new Boolean();
undefined
> mybool
{}
> mybool == true
false
> mybool == false
true

> var myobj = {};
undefined
> myobj.skipper = "on my mark, engage!"
'on my mark, engage!'
> myobj.skipper.split(" ");
[ 'on',
  'my',
  'mark,',
  'engage!' ]

The sky is the limit, then keep right on going.

Update Fragment from ViewPager

I implement a app demo following Sajmon's answer. Just for anyone else who search this question.

You can access source code on GitHub

enter image description here

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

From the docs:

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

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

Edit: Further reading led me here:

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

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

Input button target="_blank" isn't causing the link to load in a new window/tab

An input element does not support the target attribute. The target attribute is for a tags and that is where it should be used.

virtualenvwrapper and Python 3

If you already have python3 installed as well virtualenvwrapper the only thing you would need to do to use python3 with the virtual environment is creating an environment using:

which python3 #Output: /usr/bin/python3
mkvirtualenv --python=/usr/bin/python3 nameOfEnvironment

Or, (at least on OSX using brew):

mkvirtualenv --python=`which python3` nameOfEnvironment

Start using the environment and you'll see that as soon as you type python you'll start using python3

how to get 2 digits after decimal point in tsql?

DECLARE @i AS FLOAT = 2 SELECT @i / 3 SELECT cast(@i / cast(3 AS DECIMAL(18,2))as decimal (18,2))

Both factor and result requires casting to be considered as decimals.

How does EL empty operator work in JSF?

From EL 2.2 specification (get the one below "Click here to download the spec for evaluation"):

1.10 Empty Operator - empty A

The empty operator is a prefix operator that can be used to determine if a value is null or empty.

To evaluate empty A

  • If A is null, return true
  • Otherwise, if A is the empty string, then return true
  • Otherwise, if A is an empty array, then return true
  • Otherwise, if A is an empty Map, return true
  • Otherwise, if A is an empty Collection, return true
  • Otherwise return false

So, considering the interfaces, it works on Collection and Map only. In your case, I think Collection is the best option. Or, if it's a Javabean-like object, then Map. Either way, under the covers, the isEmpty() method is used for the actual check. On interface methods which you can't or don't want to implement, you could throw UnsupportedOperationException.

How do I pass named parameters with Invoke-Command?

My solution to this was to write the script block dynamically with [scriptblock]:Create:

# Or build a complex local script with MARKERS here, and do substitutions
# I was sending install scripts to the remote along with MSI packages
# ...for things like Backup and AV protection etc.

$p1 = "good stuff"; $p2 = "better stuff"; $p3 = "best stuff"; $etc = "!"
$script = [scriptblock]::Create("MyScriptOnRemoteServer.ps1 $p1 $p2 $etc")
#strings get interpolated/expanded while a direct scriptblock does not

# the $parms are now expanded in the script block itself
# ...so just call it:
$result = invoke-command $computer -script $script

Passing arguments was very frustrating, trying various methods, e.g.,
-arguments, $using:p1, etc. and this just worked as desired with no problems.

Since I control the contents and variable expansion of the string which creates the [scriptblock] (or script file) this way, there is no real issue with the "invoke-command" incantation.

(It shouldn't be that hard. :) )

How to "crop" a rectangular image into a square with CSS?

I had a similar issue and could not "compromise" with background images. I came up with this.

<div class="container">
    <img src="http://lorempixel.com/800x600/nature">
</div>

.container {
    position: relative;
    width: 25%; /* whatever width you want. I was implementing this in a 4 tile grid pattern. I used javascript to set height equal to width */
    border: 2px solid #fff; /* just to separate the images */
    overflow: hidden; /* "crop" the image */
    background: #000; /* incase the image is wider than tall/taller than wide */
}

.container img {
    position: absolute;
    display: block;
    height: 100%; /* all images at least fill the height */
    top: 50%; /* top, left, transform trick to vertically and horizontally center image */
    left: 50%;
    transform: translate3d(-50%,-50%,0);
}

//assuming you're using jQuery
var h = $('.container').outerWidth();
$('.container').css({height: h + 'px'});

Hope this helps!

Example: https://jsfiddle.net/cfbuwxmr/1/

Parse error: syntax error, unexpected T_ECHO in

Missing ; after var_dump($row)

Check if a time is between two times (time DataType)

WITH CTE as
(
SELECT CAST(ShiftStart AS DATETIME) AS ShiftStart, 
CASE WHEN ShiftStart > ShiftEnd THEN CAST(ShiftEnd AS DATETIME) +1
ELSE CAST(ShiftEnd AS DATETIME) END AS ShiftEnd
FROM **TABLE_NAME**
)
SELECT * FROM CTE
WHERE 
CAST('11:00:00' AS DATETIME) BETWEEN ShiftStart AND ShiftEnd -- Start of Shift
OR CAST('23:00:00' AS DATETIME) BETWEEN ShiftStart AND ShiftEnd -- End of Shift

Get current scroll position of ScrollView in React Native

Try.

<ScrollView onScroll={this.handleScroll} />

And then:

handleScroll: function(event: Object) {
 console.log(event.nativeEvent.contentOffset.y);
},

jQuery, simple polling example

function poll(){
    $("ajax.php", function(data){
        //do stuff  
    }); 
}

setInterval(function(){ poll(); }, 5000);

Convert dictionary to list collection in C#

If you want to pass the Dictionary keys collection into one method argument.

List<string> lstKeys = Dict.Keys;
Methodname(lstKeys);
-------------------
void MethodName(List<String> lstkeys)
{
    `enter code here`
    //Do ur task
}

How to mount the android img file under linux?

See the answer at: http://omappedia.org/wiki/Android_eMMC_Booting#Modifying_.IMG_Files

First you need to "uncompress" userdata.img with simg2img, then you can mount it via the loop device.

How can I add a space in between two outputs?

+"\n" + can be added in print command to display the code block after it in next line

E.g. System.out.println ("a" + "\n" + "b") outputs a in first line and b in second line.

Creating a byte array from a stream

I get a compile time error with Bob's (i.e. the questioner's) code. Stream.Length is a long whereas BinaryReader.ReadBytes takes an integer parameter. In my case, I do not expect to be dealing with Streams large enough to require long precision, so I use the following:

Stream s;
byte[] b;

if (s.Length > int.MaxValue) {
  throw new Exception("This stream is larger than the conversion algorithm can currently handle.");
}

using (var br = new BinaryReader(s)) {
  b = br.ReadBytes((int)s.Length);
}

How to save CSS changes of Styles panel of Chrome Developer Tools?

DevTools tech writer and developer advocate here.

Starting in Chrome 65, Local Overrides is a new, lightweight way to do this. This is a different feature than Workspaces.

Set up Overrides

  1. Go to Sources panel.
  2. Go to Overrides tab.
  3. Click Select Folder For Overrides.
  4. Select which directory you want to save your changes to.
  5. At the top of your viewport, click Allow to give DevTools read and write access to the directory.
  6. Make your changes. In the GIF below, you can see that the background:rosybrown change persists across page loads.

overrides demo

How overrides work

When you make a change in DevTools, DevTools saves the change to a modified copy of the file on your computer. When you reload the page, DevTools serves the modified file, rather than the network resource.

The difference between overrides and workspaces

Workspaces is designed to let you use DevTools as your IDE. It maps your repository code to the network code, using source maps. The real benefit is if you're minifying your code, or using code that needs to get transpiled, like SCSS, then the changes you make in DevTools (usually) get mapped back into your original source code. Overrides, on the other hand, let you modify and save any file on the web. It's a good solution if you just want to quickly experiment with changes, and save those changes across page loads.

How can I remove "\r\n" from a string in C#? Can I use a regular expression?

You could use a regex, yes, but a simple string.Replace() will probably suffice.

 myString = myString.Replace("\r\n", string.Empty);

JPA or JDBC, how are they different?

Main difference between JPA and JDBC is level of abstraction.

JDBC is a low level standard for interaction with databases. JPA is higher level standard for the same purpose. JPA allows you to use an object model in your application which can make your life much easier. JDBC allows you to do more things with the Database directly, but it requires more attention. Some tasks can not be solved efficiently using JPA, but may be solved more efficiently with JDBC.

how to query for a list<String> in jdbctemplate

Use following code

List data = getJdbcTemplate().queryForList(query,String.class)

How do I implement a progress bar in C#?

This will Helpfull.Easy to implement,100% tested.

for(int i=1;i<linecount;i++)
{
 progressBar1.Value = i * progressBar1.Maximum / linecount;  //show process bar counts
 LabelTotal.Text = i.ToString() + " of " + linecount; //show number of count in lable
 int presentage = (i * 100) / linecount;
 LabelPresentage.Text = presentage.ToString() + " %"; //show precentage in lable
 Application.DoEvents(); keep form active in every loop
}

How to add an element to the beginning of an OrderedDict?

EDIT (2019-02-03) Note that the following answer only works on older versions of Python. More recently, OrderedDict has been rewritten in C. In addition this does touch double-underscore attributes which is frowned upon.

I just wrote a subclass of OrderedDict in a project of mine for a similar purpose. Here's the gist.

Insertion operations are also constant time O(1) (they don't require you to rebuild the data structure), unlike most of these solutions.

>>> d1 = ListDict([('a', '1'), ('b', '2')])
>>> d1.insert_before('a', ('c', 3))
>>> d1
ListDict([('c', 3), ('a', '1'), ('b', '2')])

What file uses .md extension and how should I edit them?

Extension '.md' refers to Markdown files.

If you don't want to install an app to read them in that format, you can simply use TextEdit or Xcode itself to open it on Mac.

On any other OS, you should be able to open it using any text editor, though as expected, you will not see it in Markdown format.

Android : change button text and background color

I think doing this way is much simpler:

button.setBackgroundColor(Color.BLACK);

And you need to import android.graphics.Color; not: import android.R.color;

Or you can just write the 4-byte hex code (not 3-byte) 0xFF000000 where the first byte is setting the alpha.

How to install Boost on Ubuntu

You can install boost on ubuntu by using the following commands:

sudo apt update

sudo apt install libboost-all-dev

AngularJS - Attribute directive input value change

There's a great example in the AngularJS docs.

It's very well commented and should get you pointed in the right direction.

A simple example, maybe more so what you're looking for is below:

jsfiddle


HTML

<div ng-app="myDirective" ng-controller="x">
    <input type="text" ng-model="test" my-directive>
</div>

JavaScript

angular.module('myDirective', [])
    .directive('myDirective', function () {
    return {
        restrict: 'A',
        link: function (scope, element, attrs) {
            scope.$watch(attrs.ngModel, function (v) {
                console.log('value changed, new value is: ' + v);
            });
        }
    };
});

function x($scope) {
    $scope.test = 'value here';
}


Edit: Same thing, doesn't require ngModel jsfiddle:

JavaScript

angular.module('myDirective', [])
    .directive('myDirective', function () {
    return {
        restrict: 'A',
        scope: {
            myDirective: '='
        },
        link: function (scope, element, attrs) {
            // set the initial value of the textbox
            element.val(scope.myDirective);
            element.data('old-value', scope.myDirective);

            // detect outside changes and update our input
            scope.$watch('myDirective', function (val) {
                element.val(scope.myDirective);
            });

            // on blur, update the value in scope
            element.bind('propertychange keyup paste', function (blurEvent) {
                if (element.data('old-value') != element.val()) {
                    console.log('value changed, new value is: ' + element.val());
                    scope.$apply(function () {
                        scope.myDirective = element.val();
                        element.data('old-value', element.val());
                    });
                }
            });
        }
    };
});

function x($scope) {
    $scope.test = 'value here';
}

How to set Spring profile from system variable?

If you are using docker to deploy the spring boot app, you can set the profile using the flag e:

docker run -e "SPRING_PROFILES_ACTIVE=prod" -p 8080:8080 -t r.test.co/myapp:latest

Generating 8-character only UUIDs

You can try RandomStringUtils class from apache.commons:

import org.apache.commons.lang3.RandomStringUtils;

final int SHORT_ID_LENGTH = 8;

// all possible unicode characters
String shortId = RandomStringUtils.random(SHORT_ID_LENGTH);

Please keep in mind, that it will contain all possible characters which is neither URL nor human friendly.

So check out other methods too:

// HEX: 0-9, a-f. For example: 6587fddb, c0f182c1
shortId = RandomStringUtils.random(8, "0123456789abcdef"); 

// a-z, A-Z. For example: eRkgbzeF, MFcWSksx
shortId = RandomStringUtils.randomAlphabetic(8); 

// 0-9. For example: 76091014, 03771122
shortId = RandomStringUtils.randomNumeric(8); 

// a-z, A-Z, 0-9. For example: WRMcpIk7, s57JwCVA
shortId = RandomStringUtils.randomAlphanumeric(8); 

As others said probability of id collision with smaller id can be significant. Check out how birthday problem applies to your case. You can find nice explanation how to calculate approximation in this answer.

Python "extend" for a dictionary

a.update(b)

Will add keys and values from b to a, overwriting if there's already a value for a key.

Responsive Images with CSS

the best way i found was to set the image you want to view responsively as a background image and sent a css property for the div as cover.

background-image : url('YOUR URL');
background-size : cover

Converting a pointer into an integer

'size_t' and 'ptrdiff_t' are required to match your architecture (whatever it is). Therefore, I think rather than using 'int', you should be able to use 'size_t', which on a 64 bit system should be a 64 bit type.

This discussion unsigned int vs size_t goes into a bit more detail.

Cannot create JDBC driver of class ' ' for connect URL 'null' : I do not understand this exception

If you're using an embedded driver, the connectString is just

jdbc:derby:databaseName 

(whith options like;create=true;user=xxx etc).

If you're using client driver, the connect string can be left as is, but if changing the driver gives no result... excuse the question, but are you 100% sure you have started the Derby Network Server as per the Derby Tutorial?

Floating point exception

It's caused by n % x where x = 0 in the first loop iteration. You can't calculate a modulus with respect to 0.

MySQL DELETE FROM with subquery as condition

You cannot specify target table for delete.

A workaround

create table term_hierarchy_backup (tid int(10)); <- check data type

insert into term_hierarchy_backup 
SELECT DISTINCT(th1.tid)
FROM term_hierarchy AS th1
INNER JOIN term_hierarchy AS th2 ON (th1.tid = th2.tid AND th2.parent != 1015)
WHERE th1.parent = 1015;

DELETE FROM term_hierarchy AS th
WHERE th.parent = 1015 AND th.tid IN (select tid from term_hierarchy_backup);

What is INSTALL_PARSE_FAILED_NO_CERTIFICATES error?

In my case, I could build and run release builds, but got the INSTALL_PARSE_FAILED_NO_CERTIFICATES error when trying to do a debug build.

The solution was to delete my debug.keystore file and let ADT recreate it. It had apparently expired.

A better long-term solution is to explicitly create a debug.keystore that does not expire after only a year, instead of letting ADT create it. Here is the command to do that:

keytool -genkey -v -keystore debug.keystore -alias androiddebugkey -storepass android -keypass android -keyalg RSA -validity 14000

When prompted, enter these values:

  • First and last name: Android Debug
  • Organizational unit: Android
  • Name of organization: Unknown
  • City or Locality: Unknown
  • State or Province: Unknown
  • Country code: US

Gunicorn worker timeout error

timeout is a key parameter to this problem.

however it's not suit for me.

i found there is not gunicorn timeout error when i set workers=1.

when i look though my code, i found some socket connect (socket.send & socket.recv) in server init.

socket.recv will block my code and that's why it always timeout when workers>1

hope to give some ideas to the people who have some problem with me

jQuery's .click - pass parameters to user function

You need to use an anonymous function like this:

$('.leadtoscore').click(function() {
  add_event('shot')
});

You can call it like you have in the example, just a function name without parameters, like this:

$('.leadtoscore').click(add_event);

But the add_event method won't get 'shot' as it's parameter, but rather whatever click passes to it's callback, which is the event object itself...so it's not applicable in this case, but works for many others. If you need to pass parameters, use an anonymous function...or, there's one other option, use .bind() and pass data, like this:

$('.leadtoscore').bind('click', { param: 'shot' }, add_event);

And access it in add_event, like this:

function add_event(event) {
  //event.data.param == "shot", use as needed
}

Implement paging (skip / take) functionality with this query

OFFSET     10 ROWS       -- skip 10 rows
FETCH NEXT 10 ROWS ONLY; -- take 10 rows

use this in the end of your select syntax. =)

What does the symbol \0 mean in a string-literal?

sizeof str is 7 - five bytes for the "Hello" text, plus the explicit NUL terminator, plus the implicit NUL terminator.

strlen(str) is 5 - the five "Hello" bytes only.

The key here is that the implicit nul terminator is always added - even if the string literal just happens to end with \0. Of course, strlen just stops at the first \0 - it can't tell the difference.

There is one exception to the implicit NUL terminator rule - if you explicitly specify the array size, the string will be truncated to fit:

char str[6] = "Hello\0"; // strlen(str) = 5, sizeof(str) = 6 (with one NUL)
char str[7] = "Hello\0"; // strlen(str) = 5, sizeof(str) = 7 (with two NULs)
char str[8] = "Hello\0"; // strlen(str) = 5, sizeof(str) = 8 (with three NULs per C99 6.7.8.21)

This is, however, rarely useful, and prone to miscalculating the string length and ending up with an unterminated string. It is also forbidden in C++.

Internal Error 500 Apache, but nothing in the logs?

Check that the version of php you're running matches your codebase. For example, your local environment may be running php 5.4 (and things run fine) and maybe you're testing your code on a new machine that has php 5.3 installed. If you are using 5.4 syntax such as [] for array() then you'll get the situation you described above.

How to set underline text on textview?

I believe that you need to use CharSequence. You can find an example here.

String Concatenation in EL

1.The +(operator) has not effect to that in using EL. 2.so this is the way,to use that

<c:set var="enabled" value="${value} enabled" />


<c:out value="${empty value ? 'none' : enabled}" />

is this helpful to You ?

Recommended website resolution (width and height)?

Whatever your target browser size, make sure to include space for browser toolbars, status bars, and scroll bars as above. Internet Explorer (IME) often has over 100px of vertical space in toolbars and status bars. Typically, if I'm shooting for 1024 x 768, I would try to create a design of around 960 - 980px wide and 600px high to be safe. That way you accomodate scrolling if necessary and some nice white space (if the design requires it). I highly recommend YUI grids for instances where you need to target specific sizes:

YUI Grid

Android: set view style programmatically

the simple way is passing through constructor

RadioButton radioButton = new RadioButton(this,null,R.style.radiobutton_material_quiz);

How to remove button shadow (android)

the @Alt-Cat answer work for me!

R.attr.borderlessButtonStyle doesn't contain shadow.

and the document of button is great.

Also, you can set this style on your custom button, in second constructor.

    public CustomButton(Context context, AttributeSet attrs) {
        this(context, attrs, R.attr.borderlessButtonStyle);
    }

How does DISTINCT work when using JPA and Hibernate

I agree with kazanaki's answer, and it helped me. I wanted to select the whole entity, so I used

 select DISTINCT(c) from Customer c

In my case I have many-to-many relationship, and I want to load entities with collections in one query.

I used LEFT JOIN FETCH and at the end I had to make the result distinct.

Node.js version on the command line? (not the REPL)

You can simply do

node --version

or short form would also do

node -v

If above commands does not work, you have done something wrong in installation, reinstall the node.js and try.

Position Absolute + Scrolling

You need to wrap the text in a div element and include the absolutely positioned element inside of it.

<div class="container">
    <div class="inner">
        <div class="full-height"></div>
        [Your text here]
    </div>
</div>

Css:

.inner: { position: relative; height: auto; }
.full-height: { height: 100%; }

Setting the inner div's position to relative makes the absolutely position elements inside of it base their position and height on it rather than on the .container div, which has a fixed height. Without the inner, relatively positioned div, the .full-height div will always calculate its dimensions and position based on .container.

_x000D_
_x000D_
* {_x000D_
  box-sizing: border-box;_x000D_
}_x000D_
_x000D_
.container {_x000D_
  position: relative;_x000D_
  border: solid 1px red;_x000D_
  height: 256px;_x000D_
  width: 256px;_x000D_
  overflow: auto;_x000D_
  float: left;_x000D_
  margin-right: 16px;_x000D_
}_x000D_
_x000D_
.inner {_x000D_
  position: relative;_x000D_
  height: auto;_x000D_
}_x000D_
_x000D_
.full-height {_x000D_
  position: absolute;_x000D_
  top: 0;_x000D_
  left: 0;_x000D_
  right: 128px;_x000D_
  bottom: 0;_x000D_
  height: 100%;_x000D_
  background: blue;_x000D_
}
_x000D_
<div class="container">_x000D_
  <div class="full-height">_x000D_
  </div>_x000D_
</div>_x000D_
_x000D_
<div class="container">_x000D_
  <div class="inner">_x000D_
    <div class="full-height">_x000D_
    </div>_x000D_
_x000D_
    Lorem ipsum dolor sit amet, consectetur adipisicing elit. Aspernatur mollitia maxime facere quae cumque perferendis cum atque quia repellendus rerum eaque quod quibusdam incidunt blanditiis possimus temporibus reiciendis deserunt sequi eveniet necessitatibus_x000D_
    maiores quas assumenda voluptate qui odio laboriosam totam repudiandae? Doloremque dignissimos voluptatibus eveniet rem quasi minus ex cumque esse culpa cupiditate cum architecto! Facilis deleniti unde suscipit minima obcaecati vero ea soluta odio_x000D_
    cupiditate placeat vitae nesciunt quis alias dolorum nemo sint facere. Deleniti itaque incidunt eligendi qui nemo corporis ducimus beatae consequatur est iusto dolorum consequuntur vero debitis saepe voluptatem impedit sint ea numquam quia voluptate_x000D_
    quidem._x000D_
  </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

http://jsfiddle.net/M5cTN/

Fast way to discover the row count of a table in PostgreSQL

For SQL Server (2005 or above) a quick and reliable method is:

SELECT SUM (row_count)
FROM sys.dm_db_partition_stats
WHERE object_id=OBJECT_ID('MyTableName')   
AND (index_id=0 or index_id=1);

Details about sys.dm_db_partition_stats are explained in MSDN

The query adds rows from all parts of a (possibly) partitioned table.

index_id=0 is an unordered table (Heap) and index_id=1 is an ordered table (clustered index)

Even faster (but unreliable) methods are detailed here.

How to return string value from the stored procedure

change your

return @str1+'present in the string' ;

to

set @r = @str1+'present in the string' 

Can I use an HTML input type "date" to collect only a year?

There is input type month in HTML5 which allows to select month and year. Month selector works with autocomplete.

Check the example in JSFiddle.

<!DOCTYPE html>
<html>
<body>
    <header>
        <h1>Select a month below</h1>
    </header>
    Month example
    <input type="month" />
</body>
</html>

Wait until an HTML5 video loads

You don't really need jQuery for this as there is a Media API that provides you with all you need.

var video = document.getElementById('myVideo');
video.src = 'my_video_' + value + '.ogg';
video.load();

The Media API also contains a load() method which: "Causes the element to reset and start selecting and loading a new media resource from scratch."

(Ogg isn't the best format to use, as it's only supported by a limited number of browsers. I'd suggest using WebM and MP4 to cover all major browsers - you can use the canPlayType() function to decide on which one to play).

You can then wait for either the loadedmetadata or loadeddata (depending on what you want) events to fire:

video.addEventListener('loadeddata', function() {
   // Video is loaded and can be played
}, false);

When to use static methods

Static methods can be used if

  • One does not want to perform an action on an instance (utility methods)

    As mentioned in few of above answers in this post, converting miles to kilometers, or calculating temperature from Fahrenheit to Celsius and vice-versa. With these examples using static method, it does not need to instantiate whole new object in heap memory. Consider below

    1. new ABCClass(double farenheit).convertFarenheitToCelcium() 
    2. ABCClass.convertFarenheitToCelcium(double farenheit)
    

    the former creates a new class footprint for every method invoke, Performance, Practical. Examples are Math and Apache-Commons library StringUtils class below:

    Math.random()
    Math.sqrt(double)
    Math.min(int, int)
    StringUtils.isEmpty(String)
    StringUtils.isBlank(String)
    
  • One wants to use as a simple function. Inputs are explictly passed, and getting the result data as return value. Inheritence, object instanciation does not come into picture. Concise, Readable.

NOTE: Few folks argue against testability of static methods, but static methods can be tested too! With jMockit, one can mock static methods. Testability. Example below:

new MockUp<ClassName>() {
    @Mock
    public int doSomething(Input input1, Input input2){
        return returnValue;
    }
};

How can I get date and time formats based on Culture Info?

Use a CultureInfo like this, from MSDN:

// Creates a CultureInfo for German in Germany.
CultureInfo ci = new CultureInfo("de-DE");

// Displays dt, formatted using the CultureInfo
Console.WriteLine(dt.ToString(ci));

More info on MSDN. Here is a link of all different cultures.

What is the best way to measure execution time of a function?

I would definitely advise you to have a look at System.Diagnostics.Stopwatch

And when I looked around for more about Stopwatch I found this site;

Beware of the stopwatch

There mentioned another possibility

Process.TotalProcessorTime

Changing the "tick frequency" on x or y axis in matplotlib?

You could explicitly set where you want to tick marks with plt.xticks:

plt.xticks(np.arange(min(x), max(x)+1, 1.0))

For example,

import numpy as np
import matplotlib.pyplot as plt

x = [0,5,9,10,15]
y = [0,1,2,3,4]
plt.plot(x,y)
plt.xticks(np.arange(min(x), max(x)+1, 1.0))
plt.show()

(np.arange was used rather than Python's range function just in case min(x) and max(x) are floats instead of ints.)


The plt.plot (or ax.plot) function will automatically set default x and y limits. If you wish to keep those limits, and just change the stepsize of the tick marks, then you could use ax.get_xlim() to discover what limits Matplotlib has already set.

start, end = ax.get_xlim()
ax.xaxis.set_ticks(np.arange(start, end, stepsize))

The default tick formatter should do a decent job rounding the tick values to a sensible number of significant digits. However, if you wish to have more control over the format, you can define your own formatter. For example,

ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f'))

Here's a runnable example:

import numpy as np
import matplotlib.pyplot as plt
import matplotlib.ticker as ticker

x = [0,5,9,10,15]
y = [0,1,2,3,4]
fig, ax = plt.subplots()
ax.plot(x,y)
start, end = ax.get_xlim()
ax.xaxis.set_ticks(np.arange(start, end, 0.712123))
ax.xaxis.set_major_formatter(ticker.FormatStrFormatter('%0.1f'))
plt.show()

How to import Maven dependency in Android Studio/IntelliJ?

I am using the springframework android artifact as an example

open build.gradle

Then add the following at the same level as apply plugin: 'android'

apply plugin: 'android'

repositories {
    mavenCentral()
}

dependencies {
   compile group: 'org.springframework.android', name: 'spring-android-rest-template', version: '1.0.1.RELEASE'
}

you can also use this notation for maven artifacts

compile 'org.springframework.android:spring-android-rest-template:1.0.1.RELEASE'

Your IDE should show the jar and its dependencies under 'External Libraries' if it doesn't show up try to restart the IDE (this happened to me quite a bit)

here is the example that you provided that works

buildscript { 
    repositories { 
        maven { 
            url 'repo1.maven.org/maven2'; 
        } 
    } 
    dependencies { 
        classpath 'com.android.tools.build:gradle:0.4' 
    } 
} 
apply plugin: 'android'

repositories {
    mavenCentral()
}

dependencies { 
    compile files('libs/android-support-v4.jar') 
    compile group:'com.squareup.picasso', name:'picasso', version:'1.0.1' 
} 
android { 
    compileSdkVersion 17 
    buildToolsVersion "17.0.0" 
    defaultConfig { 
        minSdkVersion 14 
        targetSdkVersion 17 
    } 
} 

How to check if android checkbox is checked within its onClick method (declared in XML)?

@BindView(R.id.checkbox_id) // if you are using Butterknife
CheckBox yourCheckBox;

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.your_activity); 
    yourCheckBox = (CheckBox)findViewById(R.id.checkbox_id);// If your are not using Butterknife (the traditional way)

    yourCheckBox.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            yourObject.setYourProperty(yourCheckBox.isChecked()); //yourCheckBox.isChecked() is the method to know if the checkBox is checked
            Log.d(TAG, "onClick: yourCheckBox = " + yourObject.getYourProperty() );
        }
    });
}

Obviously you have to make your XML with the id of your checkbox :

<CheckBox
    android:id="@+id/checkbox_id"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="Your label"
    />

So, the method to know if the check box is checked is : (CheckBox) yourCheckBox.isChecked() it returns true if the check box is checked.

Is there a simple way to use button to navigate page as a link does in angularjs

For me, best solution is to use Angular router native directives with ui-sref like:

<button ui-sref="state.name">Go!!</button>

To understand that directive and get more options visit ui-router docs at:

https://ui-router.github.io/docs/0.3.1/#/api/ui.router.state.directive:ui-sref

: )

Delete dynamically-generated table row using jQuery

  $(document.body).on('click', 'buttontrash', function () { // <-- changes
    alert("aa");
   /$(this).closest('tr').remove();
    return false;
});

This works perfectly, take not of document.body

Return zero if no record is found

You could:

SELECT COALESCE(SUM(columnA), 0) FROM my_table WHERE columnB = 1
INTO res;

This happens to work, because your query has an aggregate function and consequently always returns a row, even if nothing is found in the underlying table.

Plain queries without aggregate would return no row in such a case. COALESCE would never be called and couldn't save you. While dealing with a single column we can wrap the whole query instead:

SELECT COALESCE( (SELECT columnA FROM my_table WHERE ID = 1), 0)
INTO res;

Works for your original query as well:

SELECT COALESCE( (SELECT SUM(columnA) FROM my_table WHERE columnB = 1), 0)
INTO res;

More about COALESCE() in the manual.
More about aggregate functions in the manual.
More alternatives in this later post:

How to get the selected date value while using Bootstrap Datepicker?

For bootstrap datepicker you can use:

$("#inputWithDatePicer").data('datepicker').getFormattedDate('yyyy-mm-dd');

Padding or margin value in pixels as integer using jQuery

Parse int

parseInt(canvas.css("margin-left")); 

returns 0 for 0px

Caesar Cipher Function in Python

The code is very large, but easy to understand. I think it fits your situation.

alphabet = "abcdefghijklmnopqrstuvwxyzabcdefghijklmnopqrstuvwxyz"
class CaesarCipher(object):    
    def __init__(self, shift):
        self.shift = shift
    def encode(self, str):
        encode = ''
        str = str.lower()
        for i in str:
            if i in alphabet:
                encode += alphabet[alphabet.index(i) + self.shift]
            else:
                encode += i
    
        return encode.upper()


    def decode(self, str):
        decode = ''
        str = str.lower()
        for i in str:
            if i in alphabet:
                decode += alphabet[alphabet.index(i) - self.shift]
            else:
                decode += i
        return decode.upper()
    

How to change the buttons text using javascript

innerText is the current correct answer for this. The other answers are outdated and incorrect.

document.getElementById('ShowButton').innerText = 'Show filter';

innerHTML also works, and can be used to insert HTML.

Change first commit of project with Git?

As mentioned by ecdpalma below, git 1.7.12+ (August 2012) has enhanced the option --root for git rebase:

"git rebase [-i] --root $tip" can now be used to rewrite all the history leading to "$tip" down to the root commit.

That new behavior was initially discussed here:

I personally think "git rebase -i --root" should be made to just work without requiring "--onto" and let you "edit" even the first one in the history.
It is understandable that nobody bothered, as people are a lot less often rewriting near the very beginning of the history than otherwise.

The patch followed.


(original answer, February 2010)

As mentioned in the Git FAQ (and this SO question), the idea is:

  1. Create new temporary branch
  2. Rewind it to the commit you want to change using git reset --hard
  3. Change that commit (it would be top of current HEAD, and you can modify the content of any file)
  4. Rebase branch on top of changed commit, using:

    git rebase --onto <tmp branch> <commit after changed> <branch>`
    

The trick is to be sure the information you want to remove is not reintroduced by a later commit somewhere else in your file. If you suspect that, then you have to use filter-branch --tree-filter to make sure the content of that file does not contain in any commit the sensible information.

In both cases, you end up rewriting the SHA1 of every commit, so be careful if you have already published the branch you are modifying the contents of. You probably shouldn’t do it unless your project isn’t yet public and other people haven’t based work off the commits you’re about to rewrite.

How can I return the current action in an ASP.NET MVC view?

Use the ViewContext and look at the RouteData collection to extract both the controller and action elements. But I think setting some data variable that indicates the application context (e.g., "editmode" or "error") rather than controller/action reduces the coupling between your views and controllers.

Decimal to Hexadecimal Converter in Java

The following converts decimal to Hexa Decimal with Time Complexity : O(n) Linear Time with out any java inbuilt function

private static String decimalToHexaDecimal(int N) {
    char hexaDecimals[] = { '0', '1', '2', '3', '4', '5', '6', '7', '8', '9', 'A', 'B', 'C', 'D', 'E', 'F' };
    StringBuilder builder = new StringBuilder();
    int base= 16;
    while (N != 0) {
        int reminder = N % base;
        builder.append(hexaDecimals[reminder]);
        N = N / base;
    }

    return builder.reverse().toString();
}

How to comment a block in Eclipse?

Eclipse Oxygen with CDT, PyDev:

Block comments under Source menu

Add Comment Block Ctrl + 4

Add Single Comment Block Ctrl+Shift+4

Remove Comment Block Ctrl + 5

Ternary operator in PowerShell

The closest PowerShell construct I've been able to come up with to emulate that is:

@({'condition is false'},{'condition is true'})[$condition]

How to pass multiple parameters to a get method in ASP.NET Core

To add some more detail about the overloading that you asked about in your comment after another answer, here is a summary. The comments in the ApiController show which action will be called with each GET query:

public class ValuesController : ApiController
{
    // EXPLANATION: See the view for the buttons which call these WebApi actions. For WebApi controllers, 
    //          there can only be one action for a given HTTP verb (GET, POST, etc) which has the same method signature, (even if the param names differ) so
    //          you can't have Get(string height) and Get(string width), but you can have Get(int height) and Get(string width).
    //          It isn't a particularly good idea to do that, but it is true. The key names in the query string must match the
    //          parameter names in the action, and the match is NOT case sensitive. This demo app allows you to test each of these
    //          rules, as follows:
    // 
    // When you send an HTTP GET request with no parameters (/api/values) then the Get() action will be called.
    // When you send an HTTP GET request with a height parameter (/api/values?height=5) then the Get(int height) action will be called.
    // When you send an HTTP GET request with a width parameter (/api/values?width=8) then the Get(string width) action will be called.
    // When you send an HTTP GET request with height and width parameters (/api/values?height=3&width=7) then the 
    //          Get(string height, string width) action will be called.
    // When you send an HTTP GET request with a depth parameter (/api/values?depth=2) then the Get() action will be called
    //          and the depth parameter will be obtained from Request.GetQueryNameValuePairs().
    // When you send an HTTP GET request with height and depth parameters (/api/values?height=4&depth=5) then the Get(int height) 
    //          action will be called, and the depth parameter would need to be obtained from Request.GetQueryNameValuePairs().
    // When you send an HTTP GET request with width and depth parameters (/api/values?width=3&depth=5) then the Get(string width) 
    //          action will be called, and the depth parameter would need to be obtained from Request.GetQueryNameValuePairs().
    // When you send an HTTP GET request with height, width and depth parameters (/api/values?height=7&width=2&depth=9) then the 
    //          Get(string height, string width) action will be called, and the depth parameter would need to be obtained from 
    //          Request.GetQueryNameValuePairs().
    // When you send an HTTP GET request with a width parameter, but with the first letter of the parameter capitalized (/api/values?Width=8) 
    //          then the Get(string width) action will be called because the case does NOT matter.
    // NOTE: If you were to uncomment the Get(string height) action below, then you would get an error about there already being  
    //          a member named Get with the same parameter types. The same goes for Get(int id).
    //
    // ANOTHER NOTE: Using the nullable operator (e.g. string? paramName) you can make optional parameters. It would work better to
    //          demonstrate this in another ApiController, since using nullable params and having a lot of signatures is a recipe
    //          for confusion.

    // GET api/values
    public IEnumerable<string> Get()
    {
        return Request.GetQueryNameValuePairs().Select(pair => "Get() => " + pair.Key + ": " + pair.Value);
        //return new string[] { "value1", "value2" };
    }

    //// GET api/values/5
    //public IEnumerable<string> Get(int id)
    //{
    //    return new string[] { "Get(height) => height: " + id };
    //}

    // GET api/values?height=5
    public IEnumerable<string> Get(int height) // int id)
    {
        return new string[] { "Get(height) => height: " + height };
    }

    // GET api/values?height=3
    public IEnumerable<string> Get(string height)
    {
        return new string[] { "Get(height) => height: " + height };
    }

    //// GET api/values?width=3
    //public IEnumerable<string> Get(string width)
    //{
    //    return new string[] { "Get(width) => width: " + width };
    //}

    // GET api/values?height=4&width=3
    public IEnumerable<string> Get(string height, string width)
    {
        return new string[] { "Get(height, width) => height: " + height + ", width: " + width };
    }
}

You would only need a single route for this, in case you wondered:

    config.Routes.MapHttpRoute(
        name: "DefaultApi",
        routeTemplate: "api/{controller}/{id}",
        defaults: new { id = RouteParameter.Optional }
    );

and you could test it all with this MVC view, or something simlar. Yes, I know you aren't supposed to mix JavaScript with markup and I'm not using bootstrap like you would normally, but this is for demo purposes only.

<div class="jumbotron">
    <h1>Multiple parameters test</h1>
    <p class="lead">Click a link below, which will send an HTTP GET request with parameters to a WebAPI controller.</p>
</div>
<script language="javascript">
    function passNothing() {
        $.get("/api/values", function (data) { alert(data); });
    }

    function passHeight(height) {
        $.get("/api/values?height=" + height, function (data) { alert(data); });
    }

    function passWidth(width) {
        $.get("/api/values?width=" + width, function (data) { alert(data); });
    }

    function passHeightAndWidth(height, width) {
        $.get("/api/values?height=" + height + "&width=" + width, function (data) { alert(data); });
    }

    function passDepth(depth) {
        $.get("/api/values?depth=" + depth, function (data) { alert(data); });
    }

    function passHeightAndDepth(height, depth) {
        $.get("/api/values?height=" + height + "&depth=" + depth, function (data) { alert(data); });
    }

    function passWidthAndDepth(width, depth) {
        $.get("/api/values?width=" + width + "&depth=" + depth, function (data) { alert(data); });
    }

    function passHeightWidthAndDepth(height, width, depth) {
        $.get("/api/values?height=" + height + "&width=" + width + "&depth=" + depth, function (data) { alert(data); });
    }

    function passWidthWithPascalCase(width) {
        $.get("/api/values?Width=" + width, function (data) { alert(data); });
    }
</script>
<div class="row">
    <button class="btn" onclick="passNothing();">Pass Nothing</button>
    <button class="btn" onclick="passHeight(5);">Pass Height of 5</button>
    <button class="btn" onclick="passWidth(8);">Pass Width of 8</button>
    <button class="btn" onclick="passHeightAndWidth(3, 7);">Pass Height of 3 and Width of 7</button>
    <button class="btn" onclick="passDepth(2);">Pass Depth of 2</button>
    <button class="btn" onclick="passHeightAndDepth(4, 5);">Pass Height of 4 and Depth of 5</button>
    <button class="btn" onclick="passWidthAndDepth(3, 5);">Pass Width of 3 and Depth of 5</button>
    <button class="btn" onclick="passHeightWidthAndDepth(7, 2, 9);">Pass Height of 7, Width of 2 and Depth of 9</button>
    <button class="btn" onclick="passHeightWidthAndDepth(7, 2, 9);">Pass Height of 7, Width of 2 and Depth of 9</button>
    <button class="btn" onclick="passWidthWithPascalCase(8);">Pass Width of 8, but with Pascal case</button>
</div>

What is getattr() exactly and how do I use it?

For me, getattr is easiest to explain this way:

It allows you to call methods based on the contents of a string instead of typing the method name.

For example, you cannot do this:

obj = MyObject()
for x in ['foo', 'bar']:
    obj.x()

because x is not of the type builtin, but str. However, you CAN do this:

obj = MyObject()
for x in ['foo', 'bar']:
    getattr(obj, x)()

It allows you to dynamically connect with objects based on your input. I've found it useful when dealing with custom objects and modules.

version `CXXABI_1.3.8' not found (required by ...)

GCC 4.9 introduces a newer C++ ABI version than your system libstdc++ has, so you need to tell the loader to use this newer version of the library by adding that path to LD_LIBRARY_PATH. Unfortunately, I cannot tell you straight off where the libstdc++ so for your GCC 4.9 installation is located, as this depends on how you configured GCC. So you need something in the style of:

export LD_LIBRARY_PATH=/home/user/lib/gcc-4.9.0/lib:/home/user/lib/boost_1_55_0/stage/lib:$LD_LIBRARY_PATH

Note the actual path may be different (there might be some subdirectory hidden under there, like `x86_64-unknown-linux-gnu/4.9.0´ or similar).

Ignore self-signed ssl cert using Jersey Client

For Jersey 2.* (Tested on 2.7) and java 8:

import java.security.cert.CertificateException; 
import java.security.cert.X509Certificate; 
import javax.net.ssl.SSLContext; 
import javax.net.ssl.TrustManager; 
import javax.net.ssl.X509TrustManager; 

public static Client ignoreSSLClient() throws Exception {

    SSLContext sslcontext = SSLContext.getInstance("TLS");

    sslcontext.init(null, new TrustManager[]{new X509TrustManager() {
        public void checkClientTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
        public void checkServerTrusted(X509Certificate[] arg0, String arg1) throws CertificateException {}
        public X509Certificate[] getAcceptedIssuers() { return new X509Certificate[0]; }
    }}, new java.security.SecureRandom());

    return ClientBuilder.newBuilder()
                        .sslContext(sslcontext)
                        .hostnameVerifier((s1, s2) -> true)
                        .build();
}

How to create strings containing double quotes in Excel formulas?

Use chr(34) Code:

    Joe = "Hi there, " & Chr(34) & "Joe" & Chr(34)
    ActiveCell.Value = Joe

Result:

    Hi there, "joe"

Anaconda site-packages

You can import the module and check the module.__file__ string. It contains the path to the associated source file.

Alternatively, you can read the File tag in the the module documentation, which can be accessed using help(module), or module? in IPython.

How to change values in a tuple?

You can change the value of tuple using copy by reference

>>> tuple1=[20,30,40]

>>> tuple2=tuple1

>>> tuple2
    [20, 30, 40]

>>> tuple2[1]=10

>>> print(tuple2)
    [20, 10, 40]

>>> print(tuple1)
    [20, 10, 40]

Padding between ActionBar's home icon and title

This is a common question in Material Design as you may want to line your toolbars title with the content in the fragment below. To do this, you can override the default padding of "12dp" by using the attribute contentInsetStart="72dp" in your toolbar.xml layout as shown below

toolbar.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.Toolbar
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/toolbar"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:background="@color/app_theme_color"
    app:contentInsetStart="72dp"/>

Then in your activity, call

Toolbar toolbar = (Toolbar) activity.findViewById(R.id.toolbar);
toolbar.setTitle("Title Goes Here");

And you end up with this:

Toolbar

Changing cell color using apache poi

I believe it is because cell.getCellStyle initially returns the default cell style which you then change.

Create styles like this and apply them to cells:

cellStyle = (XSSFCellStyle) cell.getSheet().getWorkbook().createCellStyle();

Although as the previous poster noted try and create styles and reuse them.

There is also some utility class in the XSSF library that will avoid the code I have provided and automatically try and reuse styles. Can't remember the class 0ff hand.

The source was not found, but some or all event logs could not be searched. Inaccessible logs: Security

Use NetworkService as Identity value in the application pool advanced settings when you are debugging in Visual Studio. ApplicationPoolIdentity is working if you open the site directly from the browser (or go to virtual directory in IIS and use Browse option at right).

Vue-router redirect on page not found (404)

@mani's response is now slightly outdated as using catch-all '*' routes is no longer supported when using Vue 3 onward. If this is no longer working for you, try replacing the old catch-all path with

{ path: '/:pathMatch(.*)*', component: PathNotFound },

Essentially, you should be able to replace the '*' path with '/:pathMatch(.*)*' and be good to go!

Reason: Vue Router doesn't use path-to-regexp anymore, instead it implements its own parsing system that allows route ranking and enables dynamic routing. Since we usually add one single catch-all route per project, there is no big benefit in supporting a special syntax for *.

(from https://next.router.vuejs.org/guide/migration/#removed-star-or-catch-all-routes)

How to debug ORA-01775: looping chain of synonyms?

For me, the table name and the synonym both existed but under different owner names. I re-created the tables under the owner name that matched the owner name in synonyms.

I used the queries posted by @Mahi_0707

How to extract the substring between two markers?

With sed it is possible to do something like this with a string:

echo "$STRING" | sed -e "s|.*AAA\(.*\)ZZZ.*|\1|"

And this will give me 1234 as a result.

You could do the same with re.sub function using the same regex.

>>> re.sub(r'.*AAA(.*)ZZZ.*', r'\1', 'gfgfdAAA1234ZZZuijjk')
'1234'

In basic sed, capturing group are represented by \(..\), but in python it was represented by (..).

Which "href" value should I use for JavaScript links, "#" or "javascript:void(0)"?

I tried both in google chrome with the developer tools, and the id="#" took 0.32 seconds. While the javascript:void(0) method took only 0.18 seconds. So in google chrome, javascript:void(0) works better and faster.

The definitive guide to form-based website authentication

First, a strong caveat that this answer is not the best fit for this exact question. It should definitely not be the top answer!

I will go ahead and mention Mozilla’s proposed BrowserID (or perhaps more precisely, the Verified Email Protocol) in the spirit of finding an upgrade path to better approaches to authentication in the future.

I’ll summarize it this way:

  1. Mozilla is a nonprofit with values that align well with finding good solutions to this problem.
  2. The reality today is that most websites use form-based authentication
  3. Form-based authentication has a big drawback, which is an increased risk of phishing. Users are asked to enter sensitive information into an area controlled by a remote entity, rather than an area controlled by their User Agent (browser).
  4. Since browsers are implicitly trusted (the whole idea of a User Agent is to act on behalf of the User), they can help improve this situation.
  5. The primary force holding back progress here is deployment deadlock. Solutions must be decomposed into steps which provide some incremental benefit on their own.
  6. The simplest decentralized method for expressing an identity that is built into the internet infrastructure is the domain name.
  7. As a second level of expressing identity, each domain manages its own set of accounts.
  8. The form “account@domain” is concise and supported by a wide range of protocols and URI schemes. Such an identifier is, of course, most universally recognized as an email address.
  9. Email providers are already the de-facto primary identity providers online. Current password reset flows usually let you take control of an account if you can prove that you control that account’s associated email address.
  10. The Verified Email Protocol was proposed to provide a secure method, based on public key cryptography, for streamlining the process of proving to domain B that you have an account on domain A.
  11. For browsers that don’t support the Verified Email Protocol (currently all of them), Mozilla provides a shim which implements the protocol in client-side JavaScript code.
  12. For email services that don’t support the Verified Email Protocol, the protocol allows third parties to act as a trusted intermediary, asserting that they’ve verified a user’s ownership of an account. It is not desirable to have a large number of such third parties; this capability is intended only to allow an upgrade path, and it is much preferred that email services provide these assertions themselves.
  13. Mozilla offers their own service to act like such a trusted third party. Service Providers (that is, Relying Parties) implementing the Verified Email Protocol may choose to trust Mozilla's assertions or not. Mozilla’s service verifies users’ account ownership using the conventional means of sending an email with a confirmation link.
  14. Service Providers may, of course, offer this protocol as an option in addition to any other method(s) of authentication they might wish to offer.
  15. A big user interface benefit being sought here is the “identity selector”. When a user visits a site and chooses to authenticate, their browser shows them a selection of email addresses (“personal”, “work”, “political activism”, etc.) they may use to identify themselves to the site.
  16. Another big user interface benefit being sought as part of this effort is helping the browser know more about the user’s session – who they’re signed in as currently, primarily – so it may display that in the browser chrome.
  17. Because of the distributed nature of this system, it avoids lock-in to major sites like Facebook, Twitter, Google, etc. Any individual can own their own domain and therefore act as their own identity provider.

This is not strictly “form-based authentication for websites”. But it is an effort to transition from the current norm of form-based authentication to something more secure: browser-supported authentication.

Creating an Arraylist of Objects

If you want to allow a user to add a bunch of new MyObjects to the list, you can do it with a for loop: Let's say I'm creating an ArrayList of Rectangle objects, and each Rectangle has two parameters- length and width.

//here I will create my ArrayList:

ArrayList <Rectangle> rectangles= new ArrayList <>(3); 

int length;
int width;

for(int index =0; index <3;index++)
{JOptionPane.showMessageDialog(null, "Rectangle " + (index + 1));
 length = JOptionPane.showInputDialog("Enter length");
 width = JOptionPane.showInputDialog("Enter width");

 //Now I will create my Rectangle and add it to my rectangles ArrayList:

 rectangles.add(new Rectangle(length,width));

//This passes the length and width values to the rectangle constructor,
  which will create a new Rectangle and add it to the ArrayList.

}

How to disable anchor "jump" when loading a page?

None of answers do not work good enough for me, I see page jumping to anchor and then to top for some solutions, some answers do not work at all, may be things changed for years. Hope my function will help to someone.

/**
 * Prevent automatic scrolling of page to anchor by browser after loading of page.
 * Do not call this function in $(...) or $(window).on('load', ...),
 * it should be called earlier, as soon as possible.
 */
function preventAnchorScroll() {
    var scrollToTop = function () {
        $(window).scrollTop(0);
    };
    if (window.location.hash) {
        // handler is executed at most once
        $(window).one('scroll', scrollToTop);
    }

    // make sure to release scroll 1 second after document readiness
    // to avoid negative UX
    $(function () {
        setTimeout(
            function () {
                $(window).off('scroll', scrollToTop);
            },
            1000
        );
    });
}

Safe width in pixels for printing web pages?

For printing I don't set any width and remove any obstacles which keep your print layout from having a dynamic width. Meaning if you make your browser window smaller and smaller, no content is cut/hidden but the document just gets longer. Like this, you can be sure that the rest will be handled by the printer/pdf-creator.

What about elements with a fixed width such as images or tables?

Images

Options I can think of:

  • scale images down in your print CSS to a width which you can assume will fit in any case, use pt not px (but print will need more points/unit anyways, so this should hardly be a problem)
  • exclude from being printed

Tables

  • remove the fixed width
  • use landscape if you really have tables with loads of information
  • don't use tables for layout purposes
  • exclude from being printed
  • extract content, print it as paragraphs

http://www.intensivstation.ch/en/css/print/

or any other google result for combinations of: CSS, print, media, layout

Passing ArrayList through Intent

In your receiving intent you need to do:

Intent i = getIntent();  
stock_list = i.getStringArrayListExtra("stock_list");

The way you have it you've just created a new empty intent without any extras.

If you only have a single extra you can condense this down to:

stock_list = getIntent().getStringArrayListExtra("stock_list");

How to Update/Drop a Hive Partition?

You can update a Hive partition by, for example:

ALTER TABLE logs PARTITION(year = 2012, month = 12, day = 18) 
SET LOCATION 'hdfs://user/darcy/logs/2012/12/18';

This command does not move the old data, nor does it delete the old data. It simply sets the partition to the new location.

To drop a partition, you can do

ALTER TABLE logs DROP IF EXISTS PARTITION(year = 2012, month = 12, day = 18);

Hope it helps!

Does JavaScript have the interface type (such as Java's 'interface')?

There's no notion of "this class must have these functions" (that is, no interfaces per se), because:

  1. JavaScript inheritance is based on objects, not classes. That's not a big deal until you realize:
  2. JavaScript is an extremely dynamically typed language -- you can create an object with the proper methods, which would make it conform to the interface, and then undefine all the stuff that made it conform. It'd be so easy to subvert the type system -- even accidentally! -- that it wouldn't be worth it to try and make a type system in the first place.

Instead, JavaScript uses what's called duck typing. (If it walks like a duck, and quacks like a duck, as far as JS cares, it's a duck.) If your object has quack(), walk(), and fly() methods, code can use it wherever it expects an object that can walk, quack, and fly, without requiring the implementation of some "Duckable" interface. The interface is exactly the set of functions that the code uses (and the return values from those functions), and with duck typing, you get that for free.

Now, that's not to say your code won't fail halfway through, if you try to call some_dog.quack(); you'll get a TypeError. Frankly, if you're telling dogs to quack, you have slightly bigger problems; duck typing works best when you keep all your ducks in a row, so to speak, and aren't letting dogs and ducks mingle together unless you're treating them as generic animals. In other words, even though the interface is fluid, it's still there; it's often an error to pass a dog to code that expects it to quack and fly in the first place.

But if you're sure you're doing the right thing, you can work around the quacking-dog problem by testing for the existence of a particular method before trying to use it. Something like

if (typeof(someObject.quack) == "function")
{
    // This thing can quack
}

So you can check for all the methods you can use before you use them. The syntax is kind of ugly, though. There's a slightly prettier way:

Object.prototype.can = function(methodName)
{
     return ((typeof this[methodName]) == "function");
};

if (someObject.can("quack"))
{
    someObject.quack();
}

This is standard JavaScript, so it should work in any JS interpreter worth using. It has the added benefit of reading like English.

For modern browsers (that is, pretty much any browser other than IE 6-8), there's even a way to keep the property from showing up in for...in:

Object.defineProperty(Object.prototype, 'can', {
    enumerable: false,
    value: function(method) {
        return (typeof this[method] === 'function');
    }
}

The problem is that IE7 objects don't have .defineProperty at all, and in IE8, it allegedly only works on host objects (that is, DOM elements and such). If compatibility is an issue, you can't use .defineProperty. (I won't even mention IE6, because it's rather irrelevant anymore outside of China.)

Another issue is that some coding styles like to assume that everyone writes bad code, and prohibit modifying Object.prototype in case someone wants to blindly use for...in. If you care about that, or are using (IMO broken) code that does, try a slightly different version:

function can(obj, methodName)
{
     return ((typeof obj[methodName]) == "function");
}

if (can(someObject, "quack"))
{
    someObject.quack();
}

Given an RGB value, how do I create a tint (or shade)?

Among several options for shading and tinting:

  • For shades, multiply each component by 1/4, 1/2, 3/4, etc., of its previous value. The smaller the factor, the darker the shade.

  • For tints, calculate (255 - previous value), multiply that by 1/4, 1/2, 3/4, etc. (the greater the factor, the lighter the tint), and add that to the previous value (assuming each.component is a 8-bit integer).

Note that color manipulations (such as tints and other shading) should be done in linear RGB. However, RGB colors specified in documents or encoded in images and video are not likely to be in linear RGB, in which case a so-called inverse transfer function needs to be applied to each of the RGB color's components. This function varies with the RGB color space. For example, in the sRGB color space (which can be assumed if the RGB color space is unknown), this function is roughly equivalent to raising each sRGB color component (ranging from 0 through 1) to a power of 2.2. (Note that "linear RGB" is not an RGB color space.)

See also Violet Giraffe's comment about "gamma correction".

How to get out of while loop in java with Scanner method "hasNext" as condition?

Modify the while loop as below. Declare s1 as String s1; one time outside the loop. To end the loop, simply use ctrl+z.

  while (sc.hasNext())
  {    
    s1 = sc.next();
    System.out.println(s1);
    System.out.print("Enter your sentence: ");
  }

jquery equivalent for JSON.stringify

There is no such functionality in jQuery. Use JSON.stringify or alternatively any jQuery plugin with similar functionality (e.g jquery-json).

Difference between Running and Starting a Docker container

Explanation with an example:

Consider you have a game (iso) image in your computer.

When you run (mount your image as a virtual drive), a virtual drive is created with all the game contents in the virtual drive and the game installation file is automatically launched. [Running your docker image - creating a container and then starting it.]

But when you stop (similar to docker stop) it, the virtual drive still exists but stopping all the processes. [As the container exists till it is not deleted]

And when you do start (similar to docker start), from the virtual drive the games files start its execution. [starting the existing container]

In this example - The game image is your Docker image and virtual drive is your container.

Greater than and less than in one statement

If this is really bothering you, why not write your own method isBetween(orderBean.getFiles().size(),0,5)?

Another option is to use isEmpty as it is a tad clearer:

if(!orderBean.getFiles().isEmpty() && orderBean.getFiles().size() < 5)

QuotaExceededError: Dom exception 22: An attempt was made to add something to storage that exceeded the quota

Here is an expanded solution based on DrewT's answer above that uses cookies if localStorage is not available. It uses Mozilla's docCookies library:

function localStorageGet( pKey ) {
    if( localStorageSupported() ) {
        return localStorage[pKey];
    } else {
        return docCookies.getItem( 'localstorage.'+pKey );
    }
}

function localStorageSet( pKey, pValue ) {
    if( localStorageSupported() ) {
        localStorage[pKey] = pValue;
    } else {
        docCookies.setItem( 'localstorage.'+pKey, pValue );
    }
}

// global to cache value
var gStorageSupported = undefined;
function localStorageSupported() {
    var testKey = 'test', storage = window.sessionStorage;
    if( gStorageSupported === undefined ) {
        try {
            storage.setItem(testKey, '1');
            storage.removeItem(testKey);
            gStorageSupported = true;
        } catch (error) {
            gStorageSupported = false;
        }
    }
    return gStorageSupported;
}

In your source, just use:

localStorageSet( 'foobar', 'yes' );
...
var foo = localStorageGet( 'foobar' );
...

Search all tables, all columns for a specific value SQL Server

I've just updated my blog post to correct the error in the script that you were having Jeff, you can see the updated script here: Search all fields in SQL Server Database

As requested, here's the script in case you want it but I'd recommend reviewing the blog post as I do update it from time to time

DECLARE @SearchStr nvarchar(100)
SET @SearchStr = '## YOUR STRING HERE ##'
 
 
-- Copyright © 2002 Narayana Vyas Kondreddi. All rights reserved.
-- Purpose: To search all columns of all tables for a given search string
-- Written by: Narayana Vyas Kondreddi
-- Site: http://vyaskn.tripod.com
-- Updated and tested by Tim Gaunt
-- http://www.thesitedoctor.co.uk
-- http://blogs.thesitedoctor.co.uk/tim/2010/02/19/Search+Every+Table+And+Field+In+A+SQL+Server+Database+Updated.aspx
-- Tested on: SQL Server 7.0, SQL Server 2000, SQL Server 2005 and SQL Server 2010
-- Date modified: 03rd March 2011 19:00 GMT
CREATE TABLE #Results (ColumnName nvarchar(370), ColumnValue nvarchar(3630))
 
SET NOCOUNT ON
 
DECLARE @TableName nvarchar(256), @ColumnName nvarchar(128), @SearchStr2 nvarchar(110)
SET  @TableName = ''
SET @SearchStr2 = QUOTENAME('%' + @SearchStr + '%','''')
 
WHILE @TableName IS NOT NULL
 
BEGIN
    SET @ColumnName = ''
    SET @TableName = 
    (
        SELECT MIN(QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME))
        FROM     INFORMATION_SCHEMA.TABLES
        WHERE         TABLE_TYPE = 'BASE TABLE'
            AND    QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME) > @TableName
            AND    OBJECTPROPERTY(
                    OBJECT_ID(
                        QUOTENAME(TABLE_SCHEMA) + '.' + QUOTENAME(TABLE_NAME)
                         ), 'IsMSShipped'
                           ) = 0
    )
 
    WHILE (@TableName IS NOT NULL) AND (@ColumnName IS NOT NULL)
         
    BEGIN
        SET @ColumnName =
        (
            SELECT MIN(QUOTENAME(COLUMN_NAME))
            FROM     INFORMATION_SCHEMA.COLUMNS
            WHERE         TABLE_SCHEMA    = PARSENAME(@TableName, 2)
                AND    TABLE_NAME    = PARSENAME(@TableName, 1)
                AND    DATA_TYPE IN ('char', 'varchar', 'nchar', 'nvarchar', 'int', 'decimal')
                AND    QUOTENAME(COLUMN_NAME) > @ColumnName
        )
 
        IF @ColumnName IS NOT NULL
         
        BEGIN
            INSERT INTO #Results
            EXEC
            (
                'SELECT ''' + @TableName + '.' + @ColumnName + ''', LEFT(' + @ColumnName + ', 3630) FROM ' + @TableName + ' (NOLOCK) ' +
                ' WHERE ' + @ColumnName + ' LIKE ' + @SearchStr2
            )
        END
    END   
END
 
SELECT ColumnName, ColumnValue FROM #Results
 
DROP TABLE #Results

What is an HttpHandler in ASP.NET

An ASP.NET HTTP handler is the process (frequently referred to as the "endpoint") that runs in response to a request made to an ASP.NET Web application. The most common handler is an ASP.NET page handler that processes .aspx files. When users request an .aspx file, the request is processed by the page via the page handler.

The ASP.NET page handler is only one type of handler. ASP.NET comes with several other built-in handlers such as the Web service handler for .asmx files.

You can create custom HTTP handlers when you want special handling that you can identify using file name extensions in your application. For example, the following scenarios would be good uses of custom HTTP handlers:

RSS feeds To create an RSS feed for a site, you can create a handler that emits RSS-formatted XML. You can then bind the .rss extension (for example) in your application to the custom handler. When users send a request to your site that ends in .rss, ASP.NET will call your handler to process the request.

Image server If you want your Web application to serve images in a variety of sizes, you can write a custom handler to resize images and then send them back to the user as the handler's response.

HTTP handlers have access to the application context, including the requesting user's identity (if known), application state, and session information. When an HTTP handler is requested, ASP.NET calls the ProcessRequest method on the appropriate handler. The handler's ProcessRequest method creates a response, which is sent back to the requesting browser. As with any page request, the response goes through any HTTP modules that have subscribed to events that occur after the handler has run.

AngularJS : When to use service instead of factory

There is nothing a Factory cannot do or does better in comparison with a Service. And vice verse. Factory just seems to be more popular. The reason for that is its convenience in handling private/public members. Service would be more clumsy in this regard. When coding a Service you tend to make your object members public via “this” keyword and may suddenly find out that those public members are not visible to private methods (ie inner functions).

var Service = function(){

  //public
  this.age = 13;

  //private
  function getAge(){

    return this.age; //private does not see public

  }

  console.log("age: " + getAge());

};

var s = new Service(); //prints 'age: undefined'

Angular uses the “new” keyword to create a service for you, so the instance Angular passes to the controller will have the same drawback. Of course you may overcome the problem by using this/that:

var Service = function(){

  var that = this;

  //public
  this.age = 13;

  //private
  function getAge(){

    return that.age;

  }

  console.log("age: " + getAge());

};

var s = new Service();// prints 'age: 13'  

But with a large Service constant this\that-ing would make the code poorly readable. Moreover, the Service prototypes will not see private members – only public will be available to them:

var Service = function(){

  var name = "George";

};

Service.prototype.getName = function(){

  return this.name; //will not see a private member

};

var s = new Service();
console.log("name: " + s.getName());//prints 'name: undefined'

Summing it up, using Factory is more convenient. As Factory does not have these drawbacks. I would recommend using it by default.

Confusing error in R: Error in scan(file, what, nmax, sep, dec, quote, skip, nlines, na.strings, : line 1 did not have 42 elements)

To read characters try

scan("/PathTo/file.csv", "")

If you're reading numeric values, then just use

scan("/PathTo/file.csv")

scan by default will use white space as separator. The type of the second arg defines 'what' to read (defaults to double()).

How to get DATE from DATETIME Column in SQL?

Try this:

SELECT SUM(transaction_amount) FROM TransactionMaster WHERE Card_No ='123' AND CONVERT(VARCHAR(10),GETDATE(),111)

The GETDATE() function returns the current date and time from the SQL Server.

Unpacking a list / tuple of pairs into two lists / tuples

list1 = (x[0] for x in source_list)
list2 = (x[1] for x in source_list)

How to get integer values from a string in Python?

With python 3.6, these two lines return a list (may be empty)

>>[int(x) for x in re.findall('\d+', your_string)]

Similar to

>>list(map(int, re.findall('\d+', your_string))

How can I find the last element in a List<>?

Independent of your original question, you will get better performance if you capture references to local variables rather than index into your list multiple times:

AllIntegerIDs ids = new AllIntegerIDs();
ids.m_MessageID = (int)IntegerIDsSubstring[IntOffset];
ids.m_MessageType = (int)IntegerIDsSubstring[IntOffset + 1];
ids.m_ClassID = (int)IntegerIDsSubstring[IntOffset + 2];
ids.m_CategoryID = (int)IntegerIDsSubstring[IntOffset + 3];
ids.m_MessageText = MessageTextSubstring;
integerList.Add(ids);

And in your for loop:

for (int cnt3 = 0 ; cnt3 < integerList.Count ; cnt3++) //<----PROBLEM HERE
{
   AllIntegerIDs ids = integerList[cnt3];
   Console.WriteLine("{0}\t{1}\t{2}\t{3}\t{4}\n",
      ids.m_MessageID,ids.m_MessageType,ids.m_ClassID,ids.m_CategoryID, ids.m_MessageText);
}

Default port for SQL Server

The default, unnamed instance always gets port 1433 for TCP. UDP port 1434 is used by the SQL Browser service to allow named instances to be located. In SQL Server 2000 the first instance to be started took this role.

Non-default instances get their own dynamically-allocated port, by default. If necessary, for example to configure a firewall, you can set them explicitly. If you don't want to enable or allow access to SQL Browser, you have to either include the instance's port number in the connection string, or set it up with the Alias tab in cliconfg (SQL Server Client Network Utility) on each client machine.

For more information see SQL Server Browser Service on MSDN.

Java AES encryption and decryption

If for a block cipher you're not going to use a Cipher transformation that includes a padding scheme, you need to have the number of bytes in the plaintext be an integral multiple of the block size of the cipher.

So either pad out your plaintext to a multiple of 16 bytes (which is the AES block size), or specify a padding scheme when you create your Cipher objects. For example, you could use:

Cipher cipher = Cipher.getInstance("AES/CBC/PKCS5Padding");

Unless you have a good reason not to, use a padding scheme that's already part of the JCE implementation. They've thought out a number of subtleties and corner cases you'll have to realize and deal with on your own otherwise.


Ok, your second problem is that you are using String to hold the ciphertext.

In general,

String s = new String(someBytes);
byte[] retrievedBytes = s.getBytes();

will not have someBytes and retrievedBytes being identical.

If you want/have to hold the ciphertext in a String, base64-encode the ciphertext bytes first and construct the String from the base64-encoded bytes. Then when you decrypt you'll getBytes() to get the base64-encoded bytes out of the String, then base64-decode them to get the real ciphertext, then decrypt that.

The reason for this problem is that most (all?) character encodings are not capable of mapping arbitrary bytes to valid characters. So when you create your String from the ciphertext, the String constructor (which applies a character encoding to turn the bytes into characters) essentially has to throw away some of the bytes because it can make no sense of them. Thus, when you get bytes out of the string, they are not the same bytes you put into the string.

In Java (and in modern programming in general), you cannot assume that one character = one byte, unless you know absolutely you're dealing with ASCII. This is why you need to use base64 (or something like it) if you want to build strings from arbitrary bytes.

Remove duplicates from an array of objects in JavaScript

I had this exact same requirement, to remove duplicate objects in a array, based on duplicates on a single field. I found the code here: Javascript: Remove Duplicates from Array of Objects

So in my example, I'm removing any object from the array that has a duplicate licenseNum string value.

var arrayWithDuplicates = [
    {"type":"LICENSE", "licenseNum": "12345", state:"NV"},
    {"type":"LICENSE", "licenseNum": "A7846", state:"CA"},
    {"type":"LICENSE", "licenseNum": "12345", state:"OR"},
    {"type":"LICENSE", "licenseNum": "10849", state:"CA"},
    {"type":"LICENSE", "licenseNum": "B7037", state:"WA"},
    {"type":"LICENSE", "licenseNum": "12345", state:"NM"}
];

function removeDuplicates(originalArray, prop) {
     var newArray = [];
     var lookupObject  = {};

     for(var i in originalArray) {
        lookupObject[originalArray[i][prop]] = originalArray[i];
     }

     for(i in lookupObject) {
         newArray.push(lookupObject[i]);
     }
      return newArray;
 }

var uniqueArray = removeDuplicates(arrayWithDuplicates, "licenseNum");
console.log("uniqueArray is: " + JSON.stringify(uniqueArray));

The results:

uniqueArray is:

[{"type":"LICENSE","licenseNum":"10849","state":"CA"},
{"type":"LICENSE","licenseNum":"12345","state":"NM"},
{"type":"LICENSE","licenseNum":"A7846","state":"CA"},
{"type":"LICENSE","licenseNum":"B7037","state":"WA"}]

How find out which process is using a file in Linux?

@jim's answer is correct -- fuser is what you want.

Additionally (or alternately), you can use lsof to get more information including the username, in case you need permission (without having to run an additional command) to kill the process. (THough of course, if killing the process is what you want, fuser can do that with its -k option. You can have fuser use other signals with the -s option -- check the man page for details.)

For example, with a tail -F /etc/passwd running in one window:

ghoti@pc:~$ lsof | grep passwd
tail      12470    ghoti    3r      REG  251,0     2037 51515911 /etc/passwd

Note that you can also use lsof to find out what processes are using particular sockets. An excellent tool to have in your arsenal.

How to set x axis values in matplotlib python?

The scaling on your example figure is a bit strange but you can force it by plotting the index of each x-value and then setting the ticks to the data points:

import matplotlib.pyplot as plt
x = [0.00001,0.001,0.01,0.1,0.5,1,5]
# create an index for each tick position
xi = list(range(len(x)))
y = [0.945,0.885,0.893,0.9,0.996,1.25,1.19]
plt.ylim(0.8,1.4)
# plot the index for the x-values
plt.plot(xi, y, marker='o', linestyle='--', color='r', label='Square') 
plt.xlabel('x')
plt.ylabel('y') 
plt.xticks(xi, x)
plt.title('compare')
plt.legend() 
plt.show()

Changing default shell in Linux

You can change the passwd file directly for the particular user or use the below command

chsh -s /usr/local/bin/bash username

Then log out and log in

How to add parameters into a WebRequest?

I have a feeling that the username and password that you are sending should be part of the Authorization Header. So the code below shows you how to create the Base64 string of the username and password. I also included an example of sending the POST data. In my case it was a phone_number parameter.

string credentials = Convert.ToBase64String(Encoding.ASCII.GetBytes(_username + ":" + _password));

HttpWebRequest webRequest = (HttpWebRequest)WebRequest.Create(Request);
webRequest.Headers.Add("Authorization", string.Format("Basic {0}", credentials));
webRequest.ContentType = "application/x-www-form-urlencoded";
webRequest.Method = WebRequestMethods.Http.Post;
webRequest.AllowAutoRedirect = true;
webRequest.Proxy = null;

string data = "phone_number=19735559042"; 
byte[] dataStream = Encoding.UTF8.GetBytes(data);

request.ContentLength = dataStream.Length;
Stream newStream = webRequest.GetRequestStream();
newStream.Write(dataStream, 0, dataStream.Length);
newStream.Close();

HttpWebResponse response = (HttpWebResponse)webRequest.GetResponse();
Stream stream = response.GetResponseStream();
StreamReader streamreader = new StreamReader(stream);
string s = streamreader.ReadToEnd();

Shrink a YouTube video to responsive width

You can make YouTube videos responsive with CSS. Wrap the iframe in a div with the class of "videowrapper" and apply the following styles:

.videowrapper {
    float: none;
    clear: both;
    width: 100%;
    position: relative;
    padding-bottom: 56.25%;
    padding-top: 25px;
    height: 0;
}
.videowrapper iframe {
    position: absolute;
    top: 0;
    left: 0;
    width: 100%;
    height: 100%;
}

The .videowrapper div should be inside a responsive element. The padding on the .videowrapper is necessary to keep the video from collapsing. You may have to tweak the numbers depending upon your layout.

blur vs focusout -- any real differences?

The documentation for focusout says (emphasis mine):

The focusout event is sent to an element when it, or any element inside of it, loses focus. This is distinct from the blur event in that it supports detecting the loss of focus on descendant elements (in other words, it supports event bubbling).

The same distinction exists between the focusin and focus events.

Exception : AAPT2 error: check logs for details

I fixed the ERROR with three steps
1. I checked for the problem SOURCE
2. Provided the correct string/text, because it was the CAUSE
3. I cleaned the project, you ll see it under BUILD.

enter image description here

@Resource vs @Autowired

With @Resource you can do bean self-injection, it might be needed in order to run all extra logic added by bean post processors like transactional or security related stuff.

With Spring 4.3+ @Autowired is also capable of doing this.

Search all of Git history for a string?

git rev-list --all | (
    while read revision; do
        git grep -F 'password' $revision
    done
)

Removing highcharts.com credits link

It's said here that you should be able to add the following to your chart config:

  credits: {
    enabled: false
  },

that will remove the "Highcharts.com" text from the bottom of the chart.

How to display raw html code in PRE or something like it but without escaping it

Cheap and cheerful answer:

<textarea>Some raw content</textarea>

The textarea will handle tabs, multiple spaces, newlines, line wrapping all verbatim. It copies and pastes nicely and its valid HTML all the way. It also allows the user to resize the code box. You don't need any CSS, JS, escaping, encoding.

You can alter the appearance and behaviour as well. Here's a monospace font, editing disabled, smaller font, no border:

<textarea
    style="width:100%; font-family: Monospace; font-size:10px; border:0;"
    rows="30" disabled
>Some raw content</textarea>

This solution is probably not semantically correct. So if you need that, it might be best to choose a more sophisticated answer.

Babel command not found

When I found this question, I was looking for

$ npm install -g babel-cli

Twitter Bootstrap modal on mobile devices

For me just $('[data-toggle="modal"]').click(function(){}); is working fine.

Format Date/Time in XAML in Silverlight

<TextBlock Text="{Binding Date, StringFormat='{}{0:MM/dd/yyyy a\\t h:mm tt}'}" />

will return you

04/07/2011 at 1:28 PM (-04)

How do I format {{$timestamp}} as MM/DD/YYYY in Postman?

Use Pre-request script tab to write javascript to get and save the date into a variable:

const dateNow= new Date();
pm.environment.set('currentDate', dateNow.toISOString());

and then use it in the request body as follows:

"currentDate": "{{currentDate}}"

One DbContext per web request... why?

Not a single answer here actually answers the question. The OP did not ask about a singleton/per-application DbContext design, he asked about a per-(web)request design and what potential benefits could exist.

I'll reference http://mehdi.me/ambient-dbcontext-in-ef6/ as Mehdi is a fantastic resource:

Possible performance gains.

Each DbContext instance maintains a first-level cache of all the entities its loads from the database. Whenever you query an entity by its primary key, the DbContext will first attempt to retrieve it from its first-level cache before defaulting to querying it from the database. Depending on your data query pattern, re-using the same DbContext across multiple sequential business transactions may result in a fewer database queries being made thanks to the DbContext first-level cache.

It enables lazy-loading.

If your services return persistent entities (as opposed to returning view models or other sorts of DTOs) and you'd like to take advantage of lazy-loading on those entities, the lifetime of the DbContext instance from which those entities were retrieved must extend beyond the scope of the business transaction. If the service method disposed the DbContext instance it used before returning, any attempt to lazy-load properties on the returned entities would fail (whether or not using lazy-loading is a good idea is a different debate altogether which we won't get into here). In our web application example, lazy-loading would typically be used in controller action methods on entities returned by a separate service layer. In that case, the DbContext instance that was used by the service method to load these entities would need to remain alive for the duration of the web request (or at the very least until the action method has completed).

Keep in mind there are cons as well. That link contains many other resources to read on the subject.

Just posting this in case someone else stumbles upon this question and doesn't get absorbed in answers that don't actually address the question.

Can't push to remote branch, cannot be resolved to branch

I just had this issue as well and my normal branches start with pb-3.1-12345/namebranch but I accidental capitalized the first 2 letters PB-3.1/12345/namebranch. After renaming the branch to use lower case letters I could create the branch.

How to write Unicode characters to the console?

Console.OutputEncoding Property

https://docs.microsoft.com/en-us/dotnet/api/system.console.outputencoding

Note that successfully displaying Unicode characters to the console requires the following:

  • The console must use a TrueType font, such as Lucida Console or Consolas, to display characters.

Netbeans - class does not have a main method

in Project window right click on your project and select properties go to Run and set Main Class ( you can brows it) . this manual work if you have static main in some class :

public class Someclass
{

    /**
     * @param args the command line arguments
     */
    public static void main(String[] args)
    {
        //your code
    }
}

Netbeans doesn't have any conflict with W7 and you can use version 6.8 .

Vertical Align Center in Bootstrap 4

Vertical align Using this bootstrap 4 classes:

parent: d-table

AND

child: d-table-cell & align-middle & text-center

eg:

<div class="tab-icon-holder d-table bg-light">
   <div class="d-table-cell align-middle text-center">
     <img src="assets/images/devices/Xl.png" height="30rem">
   </div>
</div>

and if you want parent be circle:

<div class="tab-icon-holder d-table bg-light rounded-circle">
   <div class="d-table-cell align-middle text-center">
     <img src="assets/images/devices/Xl.png" height="30rem">
   </div>
</div>

which two custom css classes are as follow:

.tab-icon-holder {
  width: 3.5rem;
  height: 3.5rem;
 }
.rounded-circle {
  border-radius: 50% !important
}

Final usage can be like for example:

<div class="col-md-5 mx-auto text-center">
    <div class="d-flex justify-content-around">
     <div class="tab-icon-holder d-table bg-light rounded-circle">
       <div class="d-table-cell align-middle text-center">
         <img src="assets/images/devices/Xl.png" height="30rem">
       </div>
     </div>

     <div class="tab-icon-holder d-table bg-light rounded-circle">
       <div class="d-table-cell align-middle text-center">
         <img src="assets/images/devices/Lg.png" height="30rem">
       </div>
     </div>

     ...

    </div>
</div>

Also in some cases you can use following code:

parent: h-100 d-table mx-auto

AND

child: d-table-cell & align-middle

Python ImportError: No module named wx

Ubuntu:

sudo apt-get install python-wxtools

Reading and displaying data from a .txt file

If your file is strictly text, I prefer to use the java.util.Scanner class.

You can create a Scanner out of a file by:

Scanner fileIn = new Scanner(new File(thePathToYourFile));

Then, you can read text from the file using the methods:

fileIn.nextLine(); // Reads one line from the file
fileIn.next(); // Reads one word from the file

And, you can check if there is any more text left with:

fileIn.hasNext(); // Returns true if there is another word in the file
fileIn.hasNextLine(); // Returns true if there is another line to read from the file

Once you have read the text, and saved it into a String, you can print the string to the command line with:

System.out.print(aString);
System.out.println(aString);

The posted link contains the full specification for the Scanner class. It will be helpful to assist you with what ever else you may want to do.

How can I check that two objects have the same set of property names?

If you are using underscoreJs then you can simply use _.isEqual function and it compares all keys and values at each and every level of hierarchy like below example.

var object = {"status":"inserted","id":"5799acb792b0525e05ba074c","data":{"workout":[{"set":[{"setNo":1,"exercises":[{"name":"hjkh","type":"Reps","category":"Cardio","set":{"reps":5}}],"isLastSet":false,"index":0,"isStart":true,"startDuration":1469689001989,"isEnd":true,"endDuration":1469689003323,"speed":"00:00:01"}],"setType":"Set","isSuper":false,"index":0}],"time":"2016-07-28T06:56:52.800Z"}};

var object1 = {"status":"inserted","id":"5799acb792b0525e05ba074c","data":{"workout":[{"set":[{"setNo":1,"exercises":[{"name":"hjkh","type":"Reps","category":"Cardio","set":{"reps":5}}],"isLastSet":false,"index":0,"isStart":true,"startDuration":1469689001989,"isEnd":true,"endDuration":1469689003323,"speed":"00:00:01"}],"setType":"Set","isSuper":false,"index":0}],"time":"2016-07-28T06:56:52.800Z"}};

console.log(_.isEqual(object, object1));//return true

If all the keys and values for those keys are same in both the objects then it will return true, otherwise return false.

"Cannot allocate an object of abstract type" error

You must have some virtual function declared in one of the parent classes and never implemented in any of the child classes. Make sure that all virtual functions are implemented somewhere in the inheritence chain. If a class's definition includes a pure virtual function that is never implemented, an instance of that class cannot ever be constructed.

Remove all child nodes from a parent?

You can use .empty(), like this:

$("#foo").empty();

From the docs:

Remove all child nodes of the set of matched elements from the DOM.

Remove the last character in a string in T-SQL?

Try It :

  DECLARE @String NVARCHAR(100)
    SET @String = '12354851'
    SELECT LEFT(@String, NULLIF(LEN(@String)-1,-1))

Using BufferedReader to read Text File

you can store it in array and then use whichever line you want.. this is the code snippet that i have used to read line from file and store it in a string array, hope this will be useful for you :)

public class user {
 public static void main(String x[]) throws IOException{
  BufferedReader b=new BufferedReader(new FileReader("<path to file>"));
  String[] user=new String[30];
  String line="";
  while ((line = b.readLine()) != null) {
   user[i]=line; 
   System.out.println(user[1]);
   i++;  
   }

 }
}