Programs & Examples On #Icepdf

Questions related to ICEpdf, an open source Java PDF engine for viewing, printing, and manipulating PDF documents. The ICEpdf API is 100% Java-based, lightweight, fast, efficient, and very easy to use.

Python-equivalent of short-form "if" in C++

While a = 'foo' if True else 'bar' is the more modern way of doing the ternary if statement (python 2.5+), a 1-to-1 equivalent of your version might be:

a = (b == True and "123" or "456" )

... which in python should be shortened to:

a = b is True and "123" or "456"

... or if you simply want to test the truthfulness of b's value in general...

a = b and "123" or "456"

? : can literally be swapped out for and or

How do I pass along variables with XMLHTTPRequest

Yes that's the correct method to do it with a GET request.

However, please remember that multiple query string parameters should be separated with &

eg. ?variable1=value1&variable2=value2

bootstrap responsive table content wrapping

Fine then. You can use CSS word wrap property. Something like this :

td.test /* Give whatever class name you want */
{
width:11em; /* Give whatever width you want */
word-wrap:break-word;
}

JVM heap parameters

To summarize the information found after the link: The JVM allocates the amount specified by -Xms but the OS usually does not allocate real pages until they are needed. So the JVM allocates virtual memory as specified by Xms but only allocates physical memory as is needed.

You can see this by using Process Explorer by Sysinternals instead of task manager on windows.

So there is a real difference between using -Xms64M and -Xms512M. But I think the most important difference is the one you already pointed out: the garbage collector will run more often if you really need the 512MB but only started with 64MB.

How to initailize byte array of 100 bytes in java with all 0's

byte[] bytes = new byte[100];

Initializes all byte elements with default values, which for byte is 0. In fact, all elements of an array when constructed, are initialized with default values for the array element's type.

Doctrine - How to print out the real sql, not just the prepared statement?

More clear solution:

 /**
 * Get string query 
 * 
 * @param Doctrine_Query $query
 * @return string
 */
public function getDqlWithParams(Doctrine_Query $query){
    $vals = $query->getFlattenedParams();
    $sql = $query->getDql();
    $sql = str_replace('?', '%s', $sql);
    return vsprintf($sql, $vals);
}

Display HTML snippets in HTML

Ultimately the best (though annoying) answer is "escape the text".

There are however a lot of text editors -- or even stand-alone mini utilities -- that can do this automatically. So you never should have to escape it manually if you don't want to (Unless it's a mix of escaped and un-escaped code...)

Quick Google search shows me this one, for example: http://malektips.com/zzee-text-utility-html-escape-regular-expression.html

mysqli_fetch_array() expects parameter 1 to be mysqli_result, boolean given in

That query is failing and returning false.

Put this after mysqli_query() to see what's going on.

if (!$check1_res) {
    printf("Error: %s\n", mysqli_error($con));
    exit();
}

For more information:

http://www.php.net/manual/en/mysqli.error.php

JavaScript string with new line - but not using \n

you can use the following function:

  function nl2br (str, is_xhtml) {
     var breakTag = (is_xhtml || typeof is_xhtml === 'undefined') ? '<br />' : '<br>';
     return (str + '').replace(/([^>\r\n]?)(\r\n|\n\r|\r|\n)/g, '$1' + breakTag + '$2');
  } 

like so:

var mystr="line\nanother line\nanother line";
mystr=nl2br(mystr);
alert(mystr);

this should alert line<br>another line<br>another line

the source of the function is from here: http://phpjs.org/functions/nl2br:480

this imitates the nl2br function in php...

Why is “while ( !feof (file) )” always wrong?

I'd like to provide an abstract, high-level perspective.

Concurrency and simultaneity

I/O operations interact with the environment. The environment is not part of your program, and not under your control. The environment truly exists "concurrently" with your program. As with all things concurrent, questions about the "current state" don't make sense: There is no concept of "simultaneity" across concurrent events. Many properties of state simply don't exist concurrently.

Let me make this more precise: Suppose you want to ask, "do you have more data". You could ask this of a concurrent container, or of your I/O system. But the answer is generally unactionable, and thus meaningless. So what if the container says "yes" – by the time you try reading, it may no longer have data. Similarly, if the answer is "no", by the time you try reading, data may have arrived. The conclusion is that there simply is no property like "I have data", since you cannot act meaningfully in response to any possible answer. (The situation is slightly better with buffered input, where you might conceivably get a "yes, I have data" that constitutes some kind of guarantee, but you would still have to be able to deal with the opposite case. And with output the situation is certainly just as bad as I described: you never know if that disk or that network buffer is full.)

So we conclude that it is impossible, and in fact unreasonable, to ask an I/O system whether it will be able to perform an I/O operation. The only possible way we can interact with it (just as with a concurrent container) is to attempt the operation and check whether it succeeded or failed. At that moment where you interact with the environment, then and only then can you know whether the interaction was actually possible, and at that point you must commit to performing the interaction. (This is a "synchronisation point", if you will.)

EOF

Now we get to EOF. EOF is the response you get from an attempted I/O operation. It means that you were trying to read or write something, but when doing so you failed to read or write any data, and instead the end of the input or output was encountered. This is true for essentially all the I/O APIs, whether it be the C standard library, C++ iostreams, or other libraries. As long as the I/O operations succeed, you simply cannot know whether further, future operations will succeed. You must always first try the operation and then respond to success or failure.

Examples

In each of the examples, note carefully that we first attempt the I/O operation and then consume the result if it is valid. Note further that we always must use the result of the I/O operation, though the result takes different shapes and forms in each example.

  • C stdio, read from a file:

      for (;;) {
          size_t n = fread(buf, 1, bufsize, infile);
          consume(buf, n);
          if (n == 0) { break; }
      }
    

The result we must use is n, the number of elements that were read (which may be as little as zero).

  • C stdio, scanf:

      for (int a, b, c; scanf("%d %d %d", &a, &b, &c) == 3; ) {
          consume(a, b, c);
      }
    

The result we must use is the return value of scanf, the number of elements converted.

  • C++, iostreams formatted extraction:

      for (int n; std::cin >> n; ) {
          consume(n);
      }
    

The result we must use is std::cin itself, which can be evaluated in a boolean context and tells us whether the stream is still in the good() state.

  • C++, iostreams getline:

      for (std::string line; std::getline(std::cin, line); ) {
          consume(line);
      }
    

The result we must use is again std::cin, just as before.

  • POSIX, write(2) to flush a buffer:

      char const * p = buf;
      ssize_t n = bufsize;
      for (ssize_t k = bufsize; (k = write(fd, p, n)) > 0; p += k, n -= k) {}
      if (n != 0) { /* error, failed to write complete buffer */ }
    

The result we use here is k, the number of bytes written. The point here is that we can only know how many bytes were written after the write operation.

  • POSIX getline()

      char *buffer = NULL;
      size_t bufsiz = 0;
      ssize_t nbytes;
      while ((nbytes = getline(&buffer, &bufsiz, fp)) != -1)
      {
          /* Use nbytes of data in buffer */
      }
      free(buffer);
    

    The result we must use is nbytes, the number of bytes up to and including the newline (or EOF if the file did not end with a newline).

    Note that the function explicitly returns -1 (and not EOF!) when an error occurs or it reaches EOF.

You may notice that we very rarely spell out the actual word "EOF". We usually detect the error condition in some other way that is more immediately interesting to us (e.g. failure to perform as much I/O as we had desired). In every example there is some API feature that could tell us explicitly that the EOF state has been encountered, but this is in fact not a terribly useful piece of information. It is much more of a detail than we often care about. What matters is whether the I/O succeeded, more-so than how it failed.

  • A final example that actually queries the EOF state: Suppose you have a string and want to test that it represents an integer in its entirety, with no extra bits at the end except whitespace. Using C++ iostreams, it goes like this:

      std::string input = "   123   ";   // example
    
      std::istringstream iss(input);
      int value;
      if (iss >> value >> std::ws && iss.get() == EOF) {
          consume(value);
      } else {
          // error, "input" is not parsable as an integer
      }
    

We use two results here. The first is iss, the stream object itself, to check that the formatted extraction to value succeeded. But then, after also consuming whitespace, we perform another I/O/ operation, iss.get(), and expect it to fail as EOF, which is the case if the entire string has already been consumed by the formatted extraction.

In the C standard library you can achieve something similar with the strto*l functions by checking that the end pointer has reached the end of the input string.

The answer

while(!feof) is wrong because it tests for something that is irrelevant and fails to test for something that you need to know. The result is that you are erroneously executing code that assumes that it is accessing data that was read successfully, when in fact this never happened.

how to check if a datareader is null or empty

This

Example:

objCar.StrDescription = (objSqlDataReader["fieldDescription"].GetType() != typeof(DBNull)) ? (String)objSqlDataReader["fieldDescription"] : "";

How to get an isoformat datetime string including the default timezone?

You need to make your datetime objects timezone aware. from the datetime docs:

There are two kinds of date and time objects: “naive” and “aware”. This distinction refers to whether the object has any notion of time zone, daylight saving time, or other kind of algorithmic or political time adjustment. Whether a naive datetime object represents Coordinated Universal Time (UTC), local time, or time in some other timezone is purely up to the program, just like it’s up to the program whether a particular number represents metres, miles, or mass. Naive datetime objects are easy to understand and to work with, at the cost of ignoring some aspects of reality.

When you have an aware datetime object, you can use isoformat() and get the output you need.

To make your datetime objects aware, you'll need to subclass tzinfo, like the second example in here, or simpler - use a package that does it for you, like pytz or python-dateutil

Using pytz, this would look like:

import datetime, pytz
datetime.datetime.now(pytz.timezone('US/Central')).isoformat()

You can also control the output format, if you use strftime with the '%z' format directive like

datetime.datetime.now(pytz.timezone('US/Central')).strftime('%Y-%m-%dT%H:%M:%S.%f%z')

Replace Line Breaks in a String C#

Use replace with Environment.NewLine

myString = myString.Replace(System.Environment.NewLine, "replacement text"); //add a line terminating ;

As mentioned in other posts, if the string comes from another environment (OS) then you'd need to replace that particular environments implementation of new line control characters.

Turning off some legends in a ggplot

You can use guide=FALSE in scale_..._...() to suppress legend.

For your example you should use scale_colour_continuous() because length is continuous variable (not discrete).

(p3 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
   scale_colour_continuous(guide = FALSE) +
   geom_point()
)

Or using function guides() you should set FALSE for that element/aesthetic that you don't want to appear as legend, for example, fill, shape, colour.

p0 <- ggplot(mov, aes(year, rating, colour = length, shape = mpaa)) +
  geom_point()    
p0+guides(colour=FALSE)

UPDATE

Both provided solutions work in new ggplot2 version 2.0.0 but movies dataset is no longer present in this library. Instead you have to use new package ggplot2movies to check those solutions.

library(ggplot2movies)
data(movies)
mov <- subset(movies, length != "")

jQuery Ajax error handling, show custom exception messages

This is what I did and it works so far in a MVC 5 application.

Controller's return type is ContentResult.

public ContentResult DoSomething()
{
    if(somethingIsTrue)
    {
        Response.StatusCode = 500 //Anything other than 2XX HTTP status codes should work
        Response.Write("My Message");
        return new ContentResult();
    }

    //Do something in here//
    string json = "whatever json goes here";

    return new ContentResult{Content = json, ContentType = "application/json"};
}

And on client side this is what ajax function looks like

$.ajax({
    type: "POST",
    url: URL,
    data: DATA,
    dataType: "json",
    success: function (json) {
        //Do something with the returned json object.
    },
    error: function (xhr, status, errorThrown) {
        //Here the status code can be retrieved like;
        xhr.status;

        //The message added to Response object in Controller can be retrieved as following.
        xhr.responseText;
    }
});

What are good message queue options for nodejs?

How about Azure ServiceBus? It supports nodejs.

Youtube iframe wmode issue

Try adding ?wmode=transparent to the end of the URL. Worked for me.

How to detect Windows 64-bit platform with .NET?

I found this to be the best way to check for the platform of the system and the process:

bool 64BitSystem = Environment.Is64BitOperatingSystem;
bool 64BitProcess = Environment.Is64BitProcess;

The first property returns true for 64-bit system, and false for 32-bit. The second property returns true for 64-bit process, and false for 32-bit.

The need for these two properties is because you can run 32-bit processes on 64-bit system, so you will need to check for both the system and the process.

Makefiles with source files in different directories

I was looking for something like this and after some tries and falls i create my own makefile, I know that's not the "idiomatic way" but it's a begining to understand make and this works for me, maybe you could try in your project.

PROJ_NAME=mono

CPP_FILES=$(shell find . -name "*.cpp")

S_OBJ=$(patsubst %.cpp, %.o, $(CPP_FILES))

CXXFLAGS=-c \
         -g \
        -Wall

all: $(PROJ_NAME)
    @echo Running application
    @echo
    @./$(PROJ_NAME)

$(PROJ_NAME): $(S_OBJ)
    @echo Linking objects...
    @g++ -o $@ $^

%.o: %.cpp %.h
    @echo Compiling and generating object $@ ...
    @g++ $< $(CXXFLAGS) -o $@

main.o: main.cpp
    @echo Compiling and generating object $@ ...
    @g++ $< $(CXXFLAGS)

clean:
    @echo Removing secondary things
    @rm -r -f objects $(S_OBJ) $(PROJ_NAME)
    @echo Done!

I know that's simple and for some people my flags are wrong, but as i said this is my first Makefile to compile my project in multiple dirs and link all of then together to create my bin.

I'm accepting sugestions :D

How to check if a process id (PID) exists

The best way is:

if ps -p $PID > /dev/null
then
   echo "$PID is running"
   # Do something knowing the pid exists, i.e. the process with $PID is running
fi

The problem with:

kill -0 $PID

is the exit code will be non-zero even if the pid is running and you dont have permission to kill it. For example:

kill -0 1

and

kill -0 $non-running-pid

have an indistinguishable (non-zero) exit code for a normal user, but the init process (PID 1) is certainly running.

DISCUSSION

The answers discussing kill and race conditions are exactly right if the body of the test is a "kill". I came looking for the general "how do you test for a PID existence in bash".

The /proc method is interesting, but in some sense breaks the spirit of the "ps" command abstraction, i.e. you dont need to go looking in /proc because what if Linus decides to call the "exe" file something else?

anaconda - graphviz - can't import after installation

You can actually install both packages at the same time. For me:

conda install -c anaconda graphviz python-graphviz

did the trick.

Can you control how an SVG's stroke-width is drawn?

The solution from Xavier Ho of doubling the width of the stroke and changing the paint-order is brilliant, although only works if the fill is a solid color, with no transparency.

I have developed other approach, more complicated but works for any fill. It also works in ellipses or paths (with the later there are some corner cases with strange behaviour, for example open paths that crosses theirselves, but not much).

The trick is to display the shape in two layers. One without stroke (only fill), and another one only with stroke at double width (transparent fill) and passed through a mask that shows the whole shape, but hides the original shape without stroke.

  <svg width="240" height="240" viewBox="0 0 1024 1024">
  <defs>
    <path id="ld" d="M256,0 L0,512 L384,512 L128,1024 L1024,384 L640,384 L896,0 L256,0 Z"/>
    <mask id="mask">
      <use xlink:href="#ld" stroke="#FFFFFF" stroke-width="160" fill="#FFFFFF"/>
      <use xlink:href="#ld" fill="#000000"/>
    </mask>
  </defs>
  <g>
    <use xlink:href="#ld" fill="#00D2B8"/>
    <use xlink:href="#ld" stroke="#0081C6" stroke-width="160" fill="red" mask="url(#mask)"/>
  </g>
  </svg>

ASP.NET Web API : Correct way to return a 401/unauthorised response

You should be throwing a HttpResponseException from your API method, not HttpException:

throw new HttpResponseException(HttpStatusCode.Unauthorized);

Or, if you want to supply a custom message:

var msg = new HttpResponseMessage(HttpStatusCode.Unauthorized) { ReasonPhrase = "Oops!!!" };
throw new HttpResponseException(msg);

Removing body margin in CSS

This should help you get rid of body margins and default top margin of <h1> tag

body{
        margin: 0px;
        padding: 0px;
    }

h1 {
        margin-top: 0px;
    }

Custom li list-style with font-awesome icon

Now that the ::marker element is available in evergreen browsers, this is how you could use it, including using :hover to change the marker. As you can see, now you can use any Unicode character you want as a list item marker and even use custom counters.

_x000D_
_x000D_
@charset "UTF-8";
@counter-style fancy {
  system: fixed;
  symbols:   ;
  suffix: " ";
}

p {
  margin-left: 8em;
}

p.note {
  display: list-item;
  counter-increment: note-counter;
}

p.note::marker {
  content: "Note " counter(note-counter) ":";
}

ol {
  margin-left: 8em;
  padding-left: 0;
}

ol li {
  list-style-type: lower-roman;
}

ol li::marker {
  color: blue;
  font-weight: bold;
}

ul {
  margin-left: 8em;
  padding-left: 0;
}

ul.happy li::marker {
  content: "";
}

ul.happy li:hover {
  color: blue;
}

ul.happy li:hover::marker {
  content: "";
}

ul.fancy {
  list-style: fancy;
}
_x000D_
<p>This is the first paragraph in this document.</p>
<p class="note">This is a very short document.</p>
<ol>
  <li>This is the first item.
    <li>This is the second item.
      <li>This is the third item.
</ol>
<p>This is the end.</p>

<ul class="happy">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>

<ul class="fancy">
  <li>Item 1</li>
  <li>Item 2</li>
  <li>Item 3</li>
</ul>
_x000D_
_x000D_
_x000D_

What is a file with extension .a?

.a files are static libraries typically generated by the archive tool. You usually include the header files associated with that static library and then link to the library when you are compiling.

In c# what does 'where T : class' mean?

Here T refers to a Class.It can be a reference type.

Proper use of mutexes in Python

This is the solution I came up with:

import time
from threading import Thread
from threading import Lock

def myfunc(i, mutex):
    mutex.acquire(1)
    time.sleep(1)
    print "Thread: %d" %i
    mutex.release()


mutex = Lock()
for i in range(0,10):
    t = Thread(target=myfunc, args=(i,mutex))
    t.start()
    print "main loop %d" %i

Output:

main loop 0
main loop 1
main loop 2
main loop 3
main loop 4
main loop 5
main loop 6
main loop 7
main loop 8
main loop 9
Thread: 0
Thread: 1
Thread: 2
Thread: 3
Thread: 4
Thread: 5
Thread: 6
Thread: 7
Thread: 8
Thread: 9

Java: recommended solution for deep cloning/copying an instance

For deep cloning implement Serializable on every class you want to clone like this

public static class Obj implements Serializable {
    public int a, b;
    public Obj(int a, int b) {
        this.a = a;
        this.b = b;
    }
}

And then use this function:

public static Object deepClone(Object object) {
    try {
        ByteArrayOutputStream baOs = new ByteArrayOutputStream();
        ObjectOutputStream oOs = new ObjectOutputStream(baOs);
        oOs.writeObject(object);
        ByteArrayInputStream baIs = new ByteArrayInputStream(baOs.toByteArray());
        ObjectInputStream oIs = new ObjectInputStream(baIs);
        return oIs.readObject();
    }
    catch (Exception e) {
        e.printStackTrace();
        return null;
    }
}

like this: Obj newObject = (Obj)deepClone(oldObject);

Efficiently updating database using SQLAlchemy ORM

There are several ways to UPDATE using sqlalchemy

1) for c in session.query(Stuff).all():
       c.foo += 1
   session.commit()

2) session.query().\
       update({"foo": (Stuff.foo + 1)})
   session.commit()

3) conn = engine.connect()
   stmt = Stuff.update().\
       values(Stuff.foo = (Stuff.foo + 1))
   conn.execute(stmt)

no pg_hba.conf entry for host

For those who have the similar problem trying to connect to local db and trying like
con = psycopg2.connect(database="my_db", user="my_name", password="admin"), try to pass the additional parameter, so the following saved me a day:
con = psycopg2.connect(database="my_db", user="my_name", password="admin", host="localhost")

Openssl : error "self signed certificate in certificate chain"

The solution for the error is to add this line at the top of the code:

process.env.NODE_TLS_REJECT_UNAUTHORIZED = "0";

Closure in Java 7

According to Tom Hawtin

A closure is a block of code that can be referenced (and passed around) with access to the variables of the enclosing scope.

Now I'm trying to emulate the JavaScript closure example on Wikipedia, with a "straigth" translation to Java, in the hope to be useful:

//ECMAScript
var f, g;
function foo() {
  var x = 0;
  f = function() { return ++x; };
  g = function() { return --x; };
  x = 1;
  print('inside foo, call to f(): ' + f()); // "2"  
}
foo();
print('call to g(): ' + g()); // "1"
print('call to f(): ' + f()); // "2"

Now the java part: Function1 is "Functor" interface with arity 1 (one argument). Closure is the class implementing the Function1, a concrete Functor that acts as function (int -> int). In the main() method I just instantiate foo as a Closure object, replicating the calls from the JavaScript example. The IntBox class is just a simple container, it behave like an array of 1 int:

int a[1] = {0}

interface Function1   {
    public final IntBag value = new IntBag();
    public int apply();
}

class Closure implements Function1 {
   private IntBag x = value;
   Function1 f;
   Function1 g;

   @Override
   public int apply()  {
    // print('inside foo, call to f(): ' + f()); // "2"
    // inside apply, call to f.apply()
       System.out.println("inside foo, call to f.apply(): " + f.apply());
       return 0;
   }

   public Closure() {
       f = new Function1() {
           @Override
           public int apply()  {
               x.add(1);
                return x.get();
           }
       };
       g = new Function1() {
           @Override
           public int apply()  {
               x.add(-1);
               return x.get();
           }
       };
    // x = 1;
       x.set(1);
   }
}
public class ClosureTest {
    public static void main(String[] args) {
        // foo()
        Closure foo = new Closure();
        foo.apply();
        // print('call to g(): ' + g()); // "1"
        System.out.println("call to foo.g.apply(): " + foo.g.apply());
        // print('call to f(): ' + f()); // "2"
        System.out.println("call to foo.f.apply(): " + foo.f.apply());

    }
}

It prints:

inside foo, call to f.apply(): 2
call to foo.g.apply(): 1
call to foo.f.apply(): 2 

What's the difference between lists and tuples?

It's been mentioned that the difference is largely semantic: people expect a tuple and list to represent different information. But this goes further than a guideline; some libraries actually behave differently based on what they are passed. Take NumPy for example (copied from another post where I ask for more examples):

>>> import numpy as np
>>> a = np.arange(9).reshape(3,3)
>>> a
array([[0, 1, 2],
       [3, 4, 5],
       [6, 7, 8]])
>>> idx = (1,1)
>>> a[idx]
4
>>> idx = [1,1]
>>> a[idx]
array([[3, 4, 5],
       [3, 4, 5]])

The point is, while NumPy may not be part of the standard library, it's a major Python library, and within NumPy lists and tuples are completely different things.

Angularjs prevent form submission when input validation fails

Just to add to the answers above,

I was having a 2 regular buttons as shown below. (No type="submit"anywhere)

<button ng-click="clearAll();" class="btn btn-default">Clear Form</button>
<button ng-disabled="form.$invalid" ng-click="submit();"class="btn btn-primary pull-right">Submit</button>

No matter how much i tried, pressing enter once the form was valid, the "Clear Form" button was called, clearing the entire form.

As a workaround,

I had to add a dummy submit button which was disabled and hidden. And This dummy button had to be on top of all the other buttons as shown below.

<button type="submit" ng-hide="true" ng-disabled="true">Dummy</button>

<button ng-click="clearAll();" class="btn btn-default">Clear Form</button>

<button ng-disabled="form.$invalid" ng-click="submit();"class="btn btn-primary pull-right">Submit</button>

Well, my intention was never to submit on Enter, so the above given hack just works fine.

How to declare string constants in JavaScript?

You can use freeze method of Object to create a constant. For example:

var configObj ={timeOut :36000};
Object.freeze(configObj);

In this way you can not alter the configObj.

Get nth character of a string in Swift programming language

Swift 2.2 Solution:

The following extension works in Xcode 7, this is a combination of this solution and Swift 2.0 syntax conversion.

extension String {
    subscript(integerIndex: Int) -> Character {
        let index = startIndex.advancedBy(integerIndex)
        return self[index]
    }

    subscript(integerRange: Range<Int>) -> String {
        let start = startIndex.advancedBy(integerRange.startIndex)
        let end = startIndex.advancedBy(integerRange.endIndex)
        let range = start..<end
        return self[range]
    }
}

React JS onClick event handler

You can make use of the React.createClone method. Create your element, than create a clone of it. During the clone's creation, you can inject props. Inject an onClick : method prop like this

{ onClick : () => this.changeColor(originalElement, index) }

the changeColor method will set the state with the duplicate, allowing you sto set the color in the process.

_x000D_
_x000D_
render()_x000D_
  {_x000D_
    return(_x000D_
      <ul>_x000D_
_x000D_
        {this.state.items.map((val, ind) => {_x000D_
          let item = <li key={ind}>{val}</li>;_x000D_
          let props = { _x000D_
            onClick: () => this.Click(item, ind),_x000D_
            key : ind,_x000D_
            ind_x000D_
          }_x000D_
          let clone = React.cloneElement(item, props, [val]);_x000D_
          return clone;_x000D_
        })}_x000D_
_x000D_
      </ul>_x000D_
    )_x000D_
  }
_x000D_
_x000D_
_x000D_

Unloading classes in java?

The only way that a Class can be unloaded is if the Classloader used is garbage collected. This means, references to every single class and to the classloader itself need to go the way of the dodo.

One possible solution to your problem is to have a Classloader for every jar file, and a Classloader for each of the AppServers that delegates the actual loading of classes to specific Jar classloaders. That way, you can point to different versions of the jar file for every App server.

This is not trivial, though. The OSGi platform strives to do just this, as each bundle has a different classloader and dependencies are resolved by the platform. Maybe a good solution would be to take a look at it.

If you don't want to use OSGI, one possible implementation could be to use one instance of JarClassloader class for every JAR file.

And create a new, MultiClassloader class that extends Classloader. This class internally would have an array (or List) of JarClassloaders, and in the defineClass() method would iterate through all the internal classloaders until a definition can be found, or a NoClassDefFoundException is thrown. A couple of accessor methods can be provided to add new JarClassloaders to the class. There is several possible implementations on the net for a MultiClassLoader, so you might not even need to write your own.

If you instanciate a MultiClassloader for every connection to the server, in principle it is possible that every server uses a different version of the same class.

I've used the MultiClassloader idea in a project, where classes that contained user-defined scripts had to be loaded and unloaded from memory and it worked quite well.

Angularjs simple file download causes router to redirect

in template

<md-button class="md-fab md-mini md-warn md-ink-ripple" ng-click="export()" aria-label="Export">
<md-icon class="material-icons" alt="Export" title="Export" aria-label="Export">
    system_update_alt
</md-icon></md-button>

in controller

     $scope.export = function(){ $window.location.href = $scope.export; };

Get a file name from a path

The simplest solution is to use something like boost::filesystem. If for some reason this isn't an option...

Doing this correctly will require some system dependent code: under Windows, either '\\' or '/' can be a path separator; under Unix, only '/' works, and under other systems, who knows. The obvious solution would be something like:

std::string
basename( std::string const& pathname )
{
    return std::string( 
        std::find_if( pathname.rbegin(), pathname.rend(),
                      MatchPathSeparator() ).base(),
        pathname.end() );
}

, with MatchPathSeparator being defined in a system dependent header as either:

struct MatchPathSeparator
{
    bool operator()( char ch ) const
    {
        return ch == '/';
    }
};

for Unix, or:

struct MatchPathSeparator
{
    bool operator()( char ch ) const
    {
        return ch == '\\' || ch == '/';
    }
};

for Windows (or something still different for some other unknown system).

EDIT: I missed the fact that he also wanted to suppress the extention. For that, more of the same:

std::string
removeExtension( std::string const& filename )
{
    std::string::const_reverse_iterator
                        pivot
            = std::find( filename.rbegin(), filename.rend(), '.' );
    return pivot == filename.rend()
        ? filename
        : std::string( filename.begin(), pivot.base() - 1 );
}

The code is a little bit more complex, because in this case, the base of the reverse iterator is on the wrong side of where we want to cut. (Remember that the base of a reverse iterator is one behind the character the iterator points to.) And even this is a little dubious: I don't like the fact that it can return an empty string, for example. (If the only '.' is the first character of the filename, I'd argue that you should return the full filename. This would require a little bit of extra code to catch the special case.) }

How to rename uploaded file before saving it into a directory?

You can Try this,

$newfilename= date('dmYHis').str_replace(" ", "", basename($_FILES["file"]["name"]));

move_uploaded_file($_FILES["file"]["tmp_name"], "../img/imageDirectory/" . $newfilename);

Is it possible to set a number to NaN or infinity?

Yes, you can use numpy for that.

import numpy as np
a = arange(3,dtype=float)

a[0] = np.nan
a[1] = np.inf
a[2] = -np.inf

a # is now [nan,inf,-inf]

np.isnan(a[0]) # True
np.isinf(a[1]) # True
np.isinf(a[2]) # True

link with target="_blank" does not open in new tab in Chrome

If you use React this should work:

_x000D_
_x000D_
<a href="#" onClick={()=>window.open("https://...")}</a>
_x000D_
_x000D_
_x000D_

Running unittest with typical test directory structure

From the article you linked to:

Create a test_modulename.py file and put your unittest tests in it. Since the test modules are in a separate directory from your code, you may need to add your module’s parent directory to your PYTHONPATH in order to run them:

$ cd /path/to/googlemaps

$ export PYTHONPATH=$PYTHONPATH:/path/to/googlemaps/googlemaps

$ python test/test_googlemaps.py

Finally, there is one more popular unit testing framework for Python (it’s that important!), nose. nose helps simplify and extend the builtin unittest framework (it can, for example, automagically find your test code and setup your PYTHONPATH for you), but it is not included with the standard Python distribution.

Perhaps you should look at nose as it suggests?

Android M - check runtime permission - how to determine if the user checked "Never ask again"?

Instead you will receive callback on onRequestPermissionsResult() as PERMISSION_DENIED when you request permission again while falling in false condition of shouldShowRequestPermissionRationale()

From Android doc:

When the system asks the user to grant a permission, the user has the option of telling the system not to ask for that permission again. In that case, any time an app uses requestPermissions() to ask for that permission again, the system immediately denies the request. The system calls your onRequestPermissionsResult() callback method and passes PERMISSION_DENIED, the same way it would if the user had explicitly rejected your request again. This means that when you call requestPermissions(), you cannot assume that any direct interaction with the user has taken place.

Postgres: How to do Composite keys?

The error you are getting is in line 3. i.e. it is not in

CONSTRAINT no_duplicate_tag UNIQUE (question_id, tag_id)

but earlier:

CREATE TABLE tags
     (
              (question_id, tag_id) NOT NULL,

Correct table definition is like pilcrow showed.

And if you want to add unique on tag1, tag2, tag3 (which sounds very suspicious), then the syntax is:

CREATE TABLE tags (
    question_id INTEGER NOT NULL,
    tag_id SERIAL NOT NULL,
    tag1 VARCHAR(20),
    tag2 VARCHAR(20),
    tag3 VARCHAR(20),
    PRIMARY KEY(question_id, tag_id),
    UNIQUE (tag1, tag2, tag3)
);

or, if you want to have the constraint named according to your wish:

CREATE TABLE tags (
    question_id INTEGER NOT NULL,
    tag_id SERIAL NOT NULL,
    tag1 VARCHAR(20),
    tag2 VARCHAR(20),
    tag3 VARCHAR(20),
    PRIMARY KEY(question_id, tag_id),
    CONSTRAINT some_name UNIQUE (tag1, tag2, tag3)
);

How to find difference between two Joda-Time DateTimes in minutes

Something like...

DateTime today = new DateTime();
DateTime yesterday = today.minusDays(1);

Duration duration = new Duration(yesterday, today);
System.out.println(duration.getStandardDays());
System.out.println(duration.getStandardHours());
System.out.println(duration.getStandardMinutes());

Which outputs

1
24
1440

or

System.out.println(Minutes.minutesBetween(yesterday, today).getMinutes());

Which is probably more what you're after

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

In my case,the problem exists beacause I have not set permission for drive "C:\" and when I change my path to other drive like "F:\" my problem resolved.

How to Convert Datetime to Date in dd/MM/yyyy format

You need to use convert in order by as well:

SELECT  Convert(varchar,A.InsertDate,103) as Tran_Date
order by Convert(varchar,A.InsertDate,103)

Spring 3 MVC resources and tag <mvc:resources />

I also met this problem before. My situation was I didn't put all the 62 spring framework jars into the lib file (spring-framework-4.1.2.RELEASE edition), it did work. And then I also changed the 3.0.xsd into 2.5 or 3.1 for test, it all worked out. Of course, there are also other factors to affect your result.

Storing image in database directly or as base64 data?

I contend that images (files) are NOT usually stored in a database base64 encoded. Instead, they are stored in their raw binary form in a binary (blob) column (or file).

Base64 is only used as a transport mechanism, not for storage. For example, you can embed a base64 encoded image into an XML document or an email message.

Base64 is also stream friendly. You can encode and decode on the fly (without knowing the total size of the data).

While base64 is fine for transport, do not store your images base64 encoded.

Base64 provides no checksum or anything of any value for storage.

Base64 encoding increases the storage requirement by 33% over a raw binary format. It also increases the amount of data that must be read from persistent storage, which is still generally the largest bottleneck in computing. It's generally faster to read less bytes and encode them on the fly. Only if your system is CPU bound instead of IO bound, and you're regularly outputting the image in base64, then consider storing in base64.

Inline images (base64 encoded images embedded in HTML) are a bottleneck themselves--you're sending 33% more data over the wire, and doing it serially (the web browser has to wait on the inline images before it can finish downloading the page HTML).

If you still wish to store images base64 encoded, please, whatever you do, make sure you don't store base64 encoded data in a UTF8 column then index it.

Correct way to handle conditional styling in React

The best way to handle styling is by using classes with set of css properties.

example:

<Component className={this.getColor()} />

getColor() {
    let class = "badge m2";
    class += this.state.count===0 ? "warning" : danger;
    return class;
}

How to remove a key from Hash and get the remaining hash in Ruby/Rails?

Hash#except (Ruby 3.0+)

Starting from Ruby 3.0, Hash#except is a build-in method.

As a result, there is no more need to depend on ActiveSupport or write monkey-patches in order to use it.

h = { a: 1, b: 2, c: 3 }
p h.except(:a) #=> {:b=>2, :c=>3}

Sources:

C# : Out of Memory exception

You should not try to bring all the list at once, te size of the elements in the database is not the same that the one it takes into memory. If you want to process the elements you should use a for each loop and take advantage of entity framework lazy loading so you dont bring all the elements into memory at once. In case you want to show the list use pagination (.Skip() and .take() )

Free XML Formatting tool

Try http://prettydiff.com/ The algorithm is similar to HTML Tidy, but is more complete. The program is written entirely in JavaScript, so you don't have to install anything.

Get clicked element using jQuery on event?

The conventional way of handling this doesn't play well with ES6. You can do this instead:

$('.delete').on('click', event => {
  const clickedElement = $(event.target);

  this.delete(clickedElement.data('id'));
});

Note that the event target will be the clicked element, which may not be the element you want (it could be a child that received the event). To get the actual element:

$('.delete').on('click', event => {
  const clickedElement = $(event.target);
  const targetElement = clickedElement.closest('.delete');

  this.delete(targetElement.data('id'));
});

Changing the page title with Jquery

_x000D_
_x000D_
 var isOldTitle = true;_x000D_
        var oldTitle = document.title;_x000D_
        var newTitle = "New Title";_x000D_
        var interval = null;_x000D_
        function changeTitle() {_x000D_
            document.title = isOldTitle ? oldTitle : newTitle;_x000D_
            isOldTitle = !isOldTitle;_x000D_
        }_x000D_
        interval = setInterval(changeTitle, 700);_x000D_
_x000D_
        $(window).focus(function () {_x000D_
            clearInterval(interval);_x000D_
            $("title").text(oldTitle);_x000D_
        });
_x000D_
_x000D_
_x000D_

Convert varchar dd/mm/yyyy to dd/mm/yyyy datetime

You can do like this:

SELECT convert(datetime, convert(date, '27-09-2013', 103), 103) 

SQL - The conversion of a varchar data type to a datetime data type resulted in an out-of-range value

Slightly unusual cause for this issue but just in case anyone needs it. The code I was working on was using:

java.text.DateFormat.getDateTimeInstance()

to get a date formatter. The formatting pattern returned by this call changed from Java 8 to Java 9 as described in this bug report: https://bugs.openjdk.java.net/browse/JDK-8152154 apparently the formatting it was returning for me wasn't suitable for the database. The solution was to this instead:

DateTimeFormatter.ISO_LOCAL_DATE_TIME

Is it safe to shallow clone with --depth 1, create commits, and pull updates again?

Note that Git 1.9/2.0 (Q1 2014) has removed that limitation.
See commit 82fba2b, from Nguy?n Thái Ng?c Duy (pclouds):

Now that git supports data transfer from or to a shallow clone, these limitations are not true anymore.

The documentation now reads:

--depth <depth>::

Create a 'shallow' clone with a history truncated to the specified number of revisions.

That stems from commits like 0d7d285, f2c681c, and c29a7b8 which support clone, send-pack /receive-pack with/from shallow clones.
smart-http now supports shallow fetch/clone too.

All the details are in "shallow.c: the 8 steps to select new commits for .git/shallow".

Update June 2015: Git 2.5 will even allow for fetching a single commit!
(Ultimate shallow case)


Update January 2016: Git 2.8 (Mach 2016) now documents officially the practice of getting a minimal history.
See commit 99487cf, commit 9cfde9e (30 Dec 2015), commit 9cfde9e (30 Dec 2015), commit bac5874 (29 Dec 2015), and commit 1de2e44 (28 Dec 2015) by Stephen P. Smith (``).
(Merged by Junio C Hamano -- gitster -- in commit 7e3e80a, 20 Jan 2016)

This is "Documentation/user-manual.txt"

A <<def_shallow_clone,shallow clone>> is created by specifying the git-clone --depth switch.
The depth can later be changed with the git-fetch --depth switch, or full history restored with --unshallow.

Merging inside a <<def_shallow_clone,shallow clone>> will work as long as a merge base is in the recent history.
Otherwise, it will be like merging unrelated histories and may have to result in huge conflicts.
This limitation may make such a repository unsuitable to be used in merge based workflows.

Update 2020:

  • git 2.11.1 introduced option git fetch --shallow-exclude= to prevent fetching all history
  • git 2.11.1 introduced option git fetch --shallow-since= to prevent fetching old commits.

For more on the shallow clone update process, see "How to update a git shallow clone?".


As commented by Richard Michael:

to backfill history: git pull --unshallow

And Olle Härstedt adds in the comments:

To backfill part of the history: git fetch --depth=100.

Why does my favicon not show up?

Favicons only work when served from a web-server which sets mime-types correctly for served content. Loading from a local file might not work in chromium. Loading from an incorrectly configured web-server will not work.

Web-servers such as lighthttpd must be configured manually to set the mime type correctly.

Because of the likelihood that mimetype assignment will not work in all environments, I would suggest you use an inline base64 encoded ico file instead. This will load faster as well, as it reduces the number of http requests sent to the server.

On POSIX based systems you can base64 encode a file with the base64 command.

To create a base64 encoded ico line use the command:

$ base64 favicon.ico --wrap 0

And insert the output into the line:

<link href="data:image/x-icon;base64,HERE" rel="icon" type="image/x-icon" />

Replacing the word HERE like so:

<link href="data:image/x-icon;base64,AAABAAEAEBAQAAEABAAoAQAAFgAAACgAAAAQAAAAIAAAAAEABAAAAAAAgAAAAAAAAAAAAAAAEAAAAAAAAAAAAAAA////AERpOgA5cCcA7vDtAF6jSABllFcAuuCvAK2trQAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAFjMzMzMzNxARYzMzMzVBEEERYzMzNhERZxRGMzZxQEA2FER3cRSAgTNxgEEREIQBMzFIARERFEEzNhERARFAATMzYREBEAhBMzMzEYEBFEEzMzNhEQQRQDMzMzcRgEAAMzMzNhERgIEzMzMyERgEQDMzMzMRAEgEMzMzMxERAEEAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA" rel="icon" type="image/x-icon" />

Referring to the null object in Python

Per Truth value testing, 'None' directly tests as FALSE, so the simplest expression will suffice:

if not foo:

How to avoid installing "Unlimited Strength" JCE policy files when deploying an application?

Bouncy Castle still requires jars installed as far as I can tell.

I did a little test and it seemed to confirm this:

http://www.bouncycastle.org/wiki/display/JA1/Frequently+Asked+Questions

Javascript change font color

Try like this:

var clr = 'green';
var html = '<font color="' + clr + '">' + onlineff + ' </font>';

This being said, you should avoid using the <font> tag. It is now deprecated. Use CSS to change the style (color) of a given element in your markup.

Algorithm/Data Structure Design Interview Questions

When interviewing recently, I was often asked to implement a data structure, usually LinkedList or HashMap. Both of these are easy enough to be doable in a short time, and difficult enough to eliminate the clueless.

VBA copy rows that meet criteria to another sheet

You need to specify workseet. Change line

If Worksheet.Cells(i, 1).Value = "X" Then

to

If Worksheets("Sheet2").Cells(i, 1).Value = "X" Then

UPD:

Try to use following code (but it's not the best approach. As @SiddharthRout suggested, consider about using Autofilter):

Sub LastRowInOneColumn()
   Dim LastRow As Long
   Dim i As Long, j As Long

   'Find the last used row in a Column: column A in this example
   With Worksheets("Sheet2")
      LastRow = .Cells(.Rows.Count, "A").End(xlUp).Row
   End With

   MsgBox (LastRow)
   'first row number where you need to paste values in Sheet1'
   With Worksheets("Sheet1")
      j = .Cells(.Rows.Count, "A").End(xlUp).Row + 1
   End With 

   For i = 1 To LastRow
       With Worksheets("Sheet2")
           If .Cells(i, 1).Value = "X" Then
               .Rows(i).Copy Destination:=Worksheets("Sheet1").Range("A" & j)
               j = j + 1
           End If
       End With
   Next i
End Sub

Spring Boot Configure and Use Two DataSources

Update 2018-01-07 with Spring Boot 1.5.8.RELEASE

Most answers do not provide how to use them (as datasource itself and as transaction), only how to config them.

You can see the runnable example and some explanation in https://www.surasint.com/spring-boot-with-multiple-databases-example/

I copied some code here.

First you have to set application.properties like this

#Database
database1.datasource.url=jdbc:mysql://localhost/testdb
database1.datasource.username=root
database1.datasource.password=root
database1.datasource.driver-class-name=com.mysql.jdbc.Driver

database2.datasource.url=jdbc:mysql://localhost/testdb2
database2.datasource.username=root
database2.datasource.password=root
database2.datasource.driver-class-name=com.mysql.jdbc.Driver

Then define them as providers (@Bean) like this:

@Bean(name = "datasource1")
@ConfigurationProperties("database1.datasource")
@Primary
public DataSource dataSource(){
    return DataSourceBuilder.create().build();
}

@Bean(name = "datasource2")
@ConfigurationProperties("database2.datasource")
public DataSource dataSource2(){
    return DataSourceBuilder.create().build();
}

Note that I have @Bean(name="datasource1") and @Bean(name="datasource2"), then you can use it when we need datasource as @Qualifier("datasource1") and @Qualifier("datasource2") , for example

@Qualifier("datasource1")
@Autowired
private DataSource dataSource;

If you do care about transaction, you have to define DataSourceTransactionManager for both of them, like this:

@Bean(name="tm1")
@Autowired
@Primary
DataSourceTransactionManager tm1(@Qualifier ("datasource1") DataSource datasource) {
    DataSourceTransactionManager txm  = new DataSourceTransactionManager(datasource);
    return txm;
}

@Bean(name="tm2")
@Autowired
DataSourceTransactionManager tm2(@Qualifier ("datasource2") DataSource datasource) {
    DataSourceTransactionManager txm  = new DataSourceTransactionManager(datasource);
    return txm;
}

Then you can use it like

@Transactional //this will use the first datasource because it is @primary

or

@Transactional("tm2")

This should be enough. See example and detail in the link above.

error running apache after xampp install

I got the same error when xampp was installed on windows 10.

www.example.com:443:0 server certificate does NOT include an ID which matches the server name

So I opened httpd-ssl.conf file in xampp folder and changed the following line

ServerName www.example.com:443

To

ServerName localhost

And the problem was fixed.

Formatting Phone Numbers in PHP

I know the OP is requesting a 123-456-7890 format, but, based on John Dul's answer, I modified it to return the phone number in parentheses format, e.g. (123) 456-7890. This one only handles 7 and 10 digit numbers.

function format_phone_string( $raw_number ) {

    // remove everything but numbers
    $raw_number = preg_replace( '/\D/', '', $raw_number );

    // split each number into an array
    $arr_number = str_split($raw_number);

    // add a dummy value to the beginning of the array
    array_unshift( $arr_number, 'dummy' );

    // remove the dummy value so now the array keys start at 1
    unset($arr_number[0]);

    // get the number of numbers in the number
    $num_number = count($arr_number);

    // loop through each number backward starting at the end
    for ( $x = $num_number; $x >= 0; $x-- ) {

        if ( $x === $num_number - 4 ) {
            // before the fourth to last number

            $phone_number = "-" . $phone_number;
        }
        else if ( $x === $num_number - 7 && $num_number > 7 ) {
            // before the seventh to last number
            // and only if the number is more than 7 digits

            $phone_number = ") " . $phone_number;
        }
        else if ( $x === $num_number - 10 ) {
            // before the tenth to last number

            $phone_number = "(" . $phone_number;
        }

        // concatenate each number (possibly with modifications) back on
        $phone_number = $arr_number[$x] . $phone_number;
    }

    return $phone_number;
}

set default schema for a sql query

SETUSER could work, having a user, even an orphaned user in the DB with the default schema needed. But SETUSER is on the legacy not supported for ever list. So a similar alternative would be to setup an application role with the needed default schema, as long as no cross DB access is needed, this should work like a treat.

Batch Extract path and filename from a variable

You can only extract path and filename from (1) a parameter of the BAT itself %1, or (2) the parameter of a CALL %1 or (3) a local FOR variable %%a.


in HELP CALL or HELP FOR you may find more detailed information:

%~1 - expands %1 removing any surrounding quotes (")
%~f1 - expands %1 to a fully qualified path name
%~d1 - expands %1 to a drive letter only
%~p1 - expands %1 to a path only
%~n1 - expands %1 to a file name only
%~x1 - expands %1 to a file extension only
%~s1 - expanded path contains short names only
%~a1 - expands %1 to file attributes
%~t1 - expands %1 to date/time of file
%~z1 - expands %1 to size of file


And then try the following:

Either pass the string to be parsed as a parameter to a CALL

call :setfile ..\Desktop\fs.cfg
echo %file% = %filepath% + %filename%
goto :eof

:setfile
set file=%~f1
set filepath=%~dp1
set filename=%~nx1
goto :eof

or the equivalent, pass the filename as a local FOR variable

for %%a in (..\Desktop\fs.cfg) do (
    set file=%%~fa
    set filepath=%%~dpa
    set filename=%%~nxa
)    
echo %file% = %filepath% + %filename%

Order of items in classes: Fields, Properties, Constructors, Methods

Rather than grouping by visibility or by type of item (field, property, method, etc.), how about grouping by functionality?

Convert RGB values to Integer

int rgb = ((r&0x0ff)<<16)|((g&0x0ff)<<8)|(b&0x0ff);

If you know that your r, g, and b values are never > 255 or < 0 you don't need the &0x0ff

Additionaly

int red = (rgb>>16)&0x0ff;
int green=(rgb>>8) &0x0ff;
int blue= (rgb)    &0x0ff;

No need for multipling.

time data does not match format

I had a case where solution was hard to figure out. This is not exactly relevant to particular question, but might help someone looking to solve a case with same error message when strptime is fed with timezone information. In my case, the reason for throwing

ValueError: time data '2016-02-28T08:27:16.000-07:00' does not match format '%Y-%m-%dT%H:%M:%S.%f%z'

was presence of last colon in the timezone part. While in some locales (Russian one, for example) code was able to execute well, in another (English one) it was failing. Removing the last colon helped remedy my situation.

How to set child process' environment variable in Makefile

I only needed the environment variables locally to invoke my test command, here's an example setting multiple environment vars in a bash shell, and escaping the dollar sign in make.

SHELL := /bin/bash

.PHONY: test tests
test tests:
    PATH=./node_modules/.bin/:$$PATH \
    JSCOVERAGE=1 \
    nodeunit tests/

How to plot time series in python

Convert your x-axis data from text to datetime.datetime, use datetime.strptime:

>>> from datetime import datetime
>>> datetime.strptime("2012-may-31 19:00", "%Y-%b-%d %H:%M")
 datetime.datetime(2012, 5, 31, 19, 0)

This is an example of how to plot data once you have an array of datetimes:

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

x = np.array([datetime.datetime(2013, 9, 28, i, 0) for i in range(24)])
y = np.random.randint(100, size=x.shape)

plt.plot(x,y)
plt.show()

enter image description here

How to make a Java Generic method static?

the only thing you can do is to change your signature to

public static <E> E[] appendToArray(E[] array, E item)

Important details:

Generic expressions preceding the return value always introduce (declare) a new generic type variable.

Additionally, type variables between types (ArrayUtils) and static methods (appendToArray) never interfere with each other.

So, what does this mean: In my answer <E> would hide the E from ArrayUtils<E> if the method wouldn't be static. AND <E> has nothing to do with the E from ArrayUtils<E>.

To reflect this fact better, a more correct answer would be:

public static <I> I[] appendToArray(I[] array, I item)

PostgreSQL return result set as JSON array?

Also if you want selected field from table and aggregated then as array .

SELECT json_agg(json_build_object('data_a',a,
                                  'data_b',b,
))  from t;

The result will come .

 [{'data_a':1,'data_b':'value1'}
  {'data_a':2,'data_b':'value2'}]

How to parse XML and count instances of a particular node attribute?

Python has an interface to the expat XML parser.

xml.parsers.expat

It's a non-validating parser, so bad XML will not be caught. But if you know your file is correct, then this is pretty good, and you'll probably get the exact info you want and you can discard the rest on the fly.

stringofxml = """<foo>
    <bar>
        <type arg="value" />
        <type arg="value" />
        <type arg="value" />
    </bar>
    <bar>
        <type arg="value" />
    </bar>
</foo>"""
count = 0
def start(name, attr):
    global count
    if name == 'type':
        count += 1

p = expat.ParserCreate()
p.StartElementHandler = start
p.Parse(stringofxml)

print count # prints 4

Text File Parsing with Python

From the accepted answer, it looks like your desired behaviour is to turn

skip 0
skip 1
skip 2
skip 3
"2012-06-23 03:09:13.23",4323584,-1.911224,-0.4657288,-0.1166382,-0.24823,0.256485,"NAN",-0.3489428,-0.130449,-0.2440527,-0.2942413,0.04944348,0.4337797,-1.105218,-1.201882,-0.5962594,-0.586636

into

2012,06,23,03,09,13.23,4323584,-1.911224,-0.4657288,-0.1166382,-0.24823,0.256485,NAN,-0.3489428,-0.130449,-0.2440527,-0.2942413,0.04944348,0.4337797,-1.105218,-1.201882,-0.5962594,-0.586636

If that's right, then I think something like

import csv

with open("test.dat", "rb") as infile, open("test.csv", "wb") as outfile:
    reader = csv.reader(infile)
    writer = csv.writer(outfile, quoting=False)
    for i, line in enumerate(reader):
        if i < 4: continue
        date = line[0].split()
        day = date[0].split('-')
        time = date[1].split(':')
        newline = day + time + line[1:]
        writer.writerow(newline)

would be a little simpler than the reps stuff.

Modify SVG fill color when being served as Background-Image

One way to do this is to serve your svg from some server side mechanism. Simply create a resource server side that outputs your svg according to GET parameters, and you serve it on a certain url.

Then you just use that url in your css.

Because as a background img, it isn't part of the DOM and you can't manipulate it. Another possibility would be to use it regularly, embed it in a page in a normal way, but position it absolutely, make it full width & height of a page and then use z-index css property to put it behind all the other DOM elements on a page.

About catching ANY exception

There are multiple ways to do this in particular with Python 3.0 and above

Approach 1

This is simple approach but not recommended because you would not know exactly which line of code is actually throwing the exception:

def bad_method():
    try:
        sqrt = 0**-1
    except Exception as e:
        print(e)

bad_method()

Approach 2

This approach is recommended because it provides more detail about each exception. It includes:

  • Line number for your code
  • File name
  • The actual error in more verbose way

The only drawback is tracback needs to be imported.

import traceback

def bad_method():
    try:
        sqrt = 0**-1
    except Exception:
        print(traceback.print_exc())

bad_method()

How to use Javascript to read local text file and read line by line?

Without jQuery:

document.getElementById('file').onchange = function(){

  var file = this.files[0];

  var reader = new FileReader();
  reader.onload = function(progressEvent){
    // Entire file
    console.log(this.result);

    // By lines
    var lines = this.result.split('\n');
    for(var line = 0; line < lines.length; line++){
      console.log(lines[line]);
    }
  };
  reader.readAsText(file);
};

HTML:

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

Remember to put your javascript code after the file field is rendered.

Select Multiple Fields from List in Linq

var result = listObject.Select( i => new{ i.category_name, i.category_id } )

This uses anonymous types so you must the var keyword, since the resulting type of the expression is not known in advance.

What is the difference between localStorage, sessionStorage, session and cookies?

The Web Storage API provides mechanisms by which browsers can securely store key/value pairs, in a much more intuitive fashion than using cookies. The Web Storage API extends the Window object with two new properties — Window.sessionStorage and Window.localStorage. — invoking one of these will create an instance of the Storage object, through which data items can be set, retrieved, and removed. A different Storage object is used for the sessionStorage and localStorage for each origin (domain).

Storage objects are simple key-value stores, similar to objects, but they stay intact through page loads.

localStorage.colorSetting = '#a4509b';
localStorage['colorSetting'] = '#a4509b';
localStorage.setItem('colorSetting', '#a4509b');

The keys and the values are always strings. To store any type convert it to String and then store it. It's always recommended to use Storage interface methods.

var testObject = { 'one': 1, 'two': 2, 'three': 3 };
// Put the object into storage
localStorage.setItem('testObject', JSON.stringify(testObject));
// Retrieve the object from storage
var retrievedObject = localStorage.getItem('testObject');
console.log('Converting String to Object: ', JSON.parse(retrievedObject));

The two mechanisms within Web Storage are as follows:

  • sessionStorage maintains a separate storage area for each given originSame-origin policy that's available for the duration of the page session (as long as the browser is open, including page reloads and restores).
  • localStorage does the same thing, but persists even when the browser is closed and reopened.

Storage « Local storage writes the data to the disk, while session storage writes the data to the memory only. Any data written to the session storage is purged when your app exits.

The maximum storage available is different per browser, but most browsers have implemented at least the w3c recommended maximum storage limit of 5MB.

+----------------+--------+---------+-----------+--------+
|                | Chrome | Firefox | Safari    |  IE    |
+----------------+--------+---------+-----------+--------+
| LocalStorage   | 10MB   | 10MB    | 5MB       | 10MB   |
+----------------+--------+---------+-----------+--------+
| SessionStorage | 10MB   | 10MB    | Unlimited | 10MB   |
+----------------+--------+---------+-----------+--------+

Always catch LocalStorage security and quota exceeded errors

StorageEvent « The storage event is fired on a document's Window object when a storage area changes. When a user agent is to send a storage notification for a Document, the user agent must queue a task to fire an event named storage at the Document object's Window object, using StorageEvent.

Note: For a real world example, see Web Storage Demo. check out the source code

Listen to the storage event on dom/Window to catch changes in the storage. fiddle.


Cookies (web cookie, browser cookie) Cookies are data, stored in small text files as name-value pairs, on your computer.

JavaScript access using Document.cookie

New cookies can also be created via JavaScript using the Document.cookie property, and if the HttpOnly flag is not set, existing cookies can be accessed from JavaScript as well.

document.cookie = "yummy_cookie=choco"; 
document.cookie = "tasty_cookie=strawberry"; 
console.log(document.cookie); 
// logs "yummy_cookie=choco; tasty_cookie=strawberry"

Secure and HttpOnly cookies HTTP State Management Mechanism

Cookies are often used in web application to identify a user and their authenticated session

When receiving an HTTP request, a server can send a Set-Cookie header with the response. The cookie is usually stored by the browser, and then the cookie is sent with requests made to the same server inside a Cookie HTTP header.

Set-Cookie: <cookie-name>=<cookie-value> 
Set-Cookie: <cookie-name>=<cookie-value>; Expires=<date>

Session cookies will get removed when the client is shut down. They don't specify the Expires or Max-Age directives.

Set-Cookie: sessionid=38afes7a8; HttpOnly; Path=/

Permanent cookies expire at a specific date (Expires) or after a specific length of time (Max-Age).

Set-Cookie: id=a3fWa; Expires=Wed, 21 Oct 2015 07:28:00 GMT; Secure; HttpOnly

The Cookie HTTP request header contains stored HTTP cookies previously sent by the server with the Set-Cookie header. HTTP-only cookies aren't accessible via JavaScript through the Document.cookie property, the XMLHttpRequest and Request APIs to mitigate attacks against cross-site scripting (XSS).

Cookies are mainly used for three purposes:

  • Session management « Logins, shopping carts, game scores, or anything else the server should remember
  • Personalization « User preferences, themes, and other settings
  • Tracking (Recording and analyzing user behavior) « Cookies have a domain associated to them. If this domain is the same as the domain of the page you are on, the cookies is said to be a first-party cookie. If the domain is different, it is said to be a third-party cookie. While first-party cookies are sent only to the server setting them, a web page may contain images or other components stored on servers in other domains (like ad banners). Cookies that are sent through these third-party components are called third-party cookies and are mainly used for advertising and tracking across the web.

Cookies were invented to solve the problem "how to remember information about the user":

  • When a user visits a web page, his name can be stored in a cookie.
  • Next time the user visits the page, cookies belonging to the page is added to the request. This way the server gets the necessary data to "remember" information about users.

GitHubGist Example


As summary,

  • localStorage persists over different tabs or windows, and even if we close the browser, accordingly with the domain security policy and user choices about quota limit.
  • sessionStorage object does not persist if we close the tab (top-level browsing context) as it does not exists if we surf via another tab or window.
  • Web Storage (session, local) allows us to save a large amount of key/value pairs and lots of text, something impossible to do via cookie.
  • Cookies that are used for sensitive actions should have a short lifetime only.
  • Cookies mainly used for advertising and tracking across the web. See for example the types of cookies used by Google.
  • Cookies are sent with every request, so they can worsen performance (especially for mobile data connections). Modern APIs for client storage are the Web storage API (localStorage and sessionStorage) and IndexedDB.

Can someone explain __all__ in Python?

I'm just adding this to be precise:

All other answers refer to modules. The original question explicitely mentioned __all__ in __init__.py files, so this is about python packages.

Generally, __all__ only comes into play when the from xxx import * variant of the import statement is used. This applies to packages as well as to modules.

The behaviour for modules is explained in the other answers. The exact behaviour for packages is described here in detail.

In short, __all__ on package level does approximately the same thing as for modules, except it deals with modules within the package (in contrast to specifying names within the module). So __all__ specifies all modules that shall be loaded and imported into the current namespace when us use from package import *.

The big difference is, that when you omit the declaration of __all__ in a package's __init__.py, the statement from package import * will not import anything at all (with exceptions explained in the documentation, see link above).

On the other hand, if you omit __all__ in a module, the "starred import" will import all names (not starting with an underscore) defined in the module.

Relative frequencies / proportions with dplyr

@Henrik's is better for usability as this will make the column character and no longer numeric but matches what you asked for...

mtcars %>%
  group_by (am, gear) %>%
  summarise (n=n()) %>%
  mutate(rel.freq = paste0(round(100 * n/sum(n), 0), "%"))

##   am gear  n rel.freq
## 1  0    3 15      79%
## 2  0    4  4      21%
## 3  1    4  8      62%
## 4  1    5  5      38%

EDIT Because Spacedman asked for it :-)

as.rel_freq <- function(x, rel_freq_col = "rel.freq", ...) {
    class(x) <- c("rel_freq", class(x))
    attributes(x)[["rel_freq_col"]] <- rel_freq_col
    x
}

print.rel_freq <- function(x, ...) {
    freq_col <- attributes(x)[["rel_freq_col"]]
    x[[freq_col]] <- paste0(round(100 * x[[freq_col]], 0), "%")   
    class(x) <- class(x)[!class(x)%in% "rel_freq"]
    print(x)
}

mtcars %>%
  group_by (am, gear) %>%
  summarise (n=n()) %>%
  mutate(rel.freq = n/sum(n)) %>%
  as.rel_freq()

## Source: local data frame [4 x 4]
## Groups: am
## 
##   am gear  n rel.freq
## 1  0    3 15      79%
## 2  0    4  4      21%
## 3  1    4  8      62%
## 4  1    5  5      38%

Bash array with spaces in elements

If you aren't stuck on using bash, different handling of spaces in file names is one of the benefits of the fish shell. Consider a directory which contains two files: "a b.txt" and "b c.txt". Here's a reasonable guess at processing a list of files generated from another command with bash, but it fails due to spaces in file names you experienced:

# bash
$ for f in $(ls *.txt); { echo $f; }
a
b.txt
b
c.txt

With fish, the syntax is nearly identical, but the result is what you'd expect:

# fish
for f in (ls *.txt); echo $f; end
a b.txt
b c.txt

It works differently because fish splits the output of commands on newlines, not spaces.

If you have a case where you do want to split on spaces instead of newlines, fish has a very readable syntax for that:

for f in (ls *.txt | string split " "); echo $f; end

"call to undefined function" error when calling class method

you need to call the function like this

$this->assign()

instead of just assign()

How to convert a HTMLElement to a string

The element outerHTML property (note: supported by Firefox after version 11) returns the HTML of the entire element.

Example

<div id="new-element-1">Hello world.</div>

<script type="text/javascript"><!--

var element = document.getElementById("new-element-1");
var elementHtml = element.outerHTML;
// <div id="new-element-1">Hello world.</div>

--></script>

Similarly, you can use innerHTML to get the HTML contained within a given element, or innerText to get the text inside an element (sans HTML markup).

See Also

  1. outerHTML - Javascript Property
  2. Javascript Reference - Elements

How to use enums in C++

You can use a trick to use scopes as you wish, just declare enum in such way:

struct Days 
{
   enum type
   {
      Saturday,Sunday,Tuesday,Wednesday,Thursday,Friday
   };
};

Days::type day = Days::Saturday;
if (day == Days::Saturday)

Implement a simple factory pattern with Spring 3 annotations

Why not add the interface FactoryBean to MyServiceFactory (to tell Spring that it's a factory), add a register(String service, MyService instance) then, have each of the services call:

@Autowired
MyServiceFactory serviceFactory;

@PostConstruct
public void postConstruct() {
    serviceFactory.register(myName, this);
}

This way, you can separate each service provider into modules if necessary, and Spring will automagically pick up any deployed and available service providers.

Is it valid to define functions in JSON results?

Nope, definitely not.

If you use a decent JSON serializer, it won't let you serialize a function like that. It's a valid OBJECT, but not valid JSON. Whatever that website's intent, it's not sending valid JSON.

How to use ADB to send touch events to device using sendevent command?

Building on top of Tomas's answer, this is the best approach of finding the location tap position as an integer I found:

adb shell getevent -l | grep ABS_MT_POSITION --line-buffered | awk '{a = substr($0,54,8); sub(/^0+/, "", a); b = sprintf("0x%s",a); printf("%d\n",strtonum(b))}'

Use adb shell getevent -l to get a list of events, the using grep for ABS_MT_POSITION (gets the line with touch events in hex) and finally use awk to get the relevant hex values, strip them of zeros and convert hex to integer. This continuously prints the x and y coordinates in the terminal only when you press on the device.

You can then use this adb shell command to send the command:

adb shell input tap x y

How can I get column names from a table in SQL Server?

You can use sp_help in SQL Server 2008.

sp_help <table_name>;

Keyboard shortcut for the above command: select table name (i.e highlight it) and press ALT+F1.

What is difference between monolithic and micro kernel?

Microkernel:

Moves as much from the kernel into “user” space.

Communication takes place between user modules using message passing.

Benefits:

1-Easier to extend a microkernel

2-Easier to port the operating system to new architectures

3-More reliable (less code is running in kernel mode)

4-More secure

Detriments:

1-Performance overhead of user space to kernel space communication

how to use XPath with XDocument?

XPath 1.0, which is what MS implements, does not have the idea of a default namespace. So try this:

XDocument xdoc = XDocument.Load(@"C:\SampleXML.xml");
XmlNamespaceManager xnm = new XmlNamespaceManager(new NameTable()); 
xnm.AddNamespace("x", "http://demo.com/2011/demo-schema");
Console.WriteLine(xdoc.XPathSelectElement("/x:Report/x:ReportInfo/x:Name", xnm) == null);

Key Shortcut for Eclipse Imports

Ctrl + Shift + O (<-- an 'O' not a zero)

Note: This shortcut also removes unused imports.

Remove leading zeros from a number in Javascript

regexp:

"014".replace(/^0+/, '')

simple Jquery hover enlarge

If you have more than 1 image on the page that you like to enlarge, name the id's for instance "content1", "content2", "content3", etc. Then extend the script with this, like so:

$(document).ready(function() {
    $("[id^=content]").hover(function() {
        $(this).addClass('transition');
    }, function() {
        $(this).removeClass('transition');
    });
});

Edit: Change the "#content" CSS to: img[id^=content] to remain having the transition effects.

Add image in title bar

That method will not work. The <title> only supports plain text. You will need to create an .ico image with the filename of favicon.ico and save it into the root folder of your site (where your default page is).

Alternatively, you can save the icon where ever you wish and call it whatever you want, but simply insert the following code into the <head> section of your HTML and reference your icon:

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

You can use Photoshop (with a plug in) or GIMP (free) to create an .ico file, or you can just use IcoFX, which is my personal favourite as it is really easy to use and does a great job (you can get an older version of the software for free from download.com).

Update 1: You can also use a number of online tools to create favicons such as ConvertIcon, which I've used successfully. There are other free online tools available now too, which do the same (accessible by a simple Google search), but also generate other icons such as the Windows 8/10 Start Menu icons and iOS App Icons.

Update 2: You can also use .png images as icons providing IE11 is the only version of IE you need to support. You just need to reference them using the HTML code above. Note that IE10 and older still require .ico files.

Update 3: You can now use Emoji characters in the title field. On Windows 10, it should generally fall back and use the Segoe UI Emoji font and display nicely, however you'll need to test and see how other systems support and display your chosen emoji, as not all devices may have the same Emoji available.

SVN - Checksum mismatch while updating

I had a the same error but for one file. In IntelliJ IDEA I was able to make a copy of the file, then go into the project and delete the file in question, then commit successfully. Then, I made a new file with the same name and copy the contents back into it. I guess you would lose the revision history but it does work.

How to install lxml on Ubuntu

For Ubuntu 12.04.3 LTS (Precise Pangolin) I had to do:

apt-get install libxml2-dev libxslt1-dev

(Note the "1" in libxslt1-dev)

Then I just installed lxml with pip/easy_install.

What is the Ruby <=> (spaceship) operator?

Since this operator reduces comparisons to an integer expression, it provides the most general purpose way to sort ascending or descending based on multiple columns/attributes.

For example, if I have an array of objects I can do things like this:

# `sort!` modifies array in place, avoids duplicating if it's large...

# Sort by zip code, ascending
my_objects.sort! { |a, b| a.zip <=> b.zip }

# Sort by zip code, descending
my_objects.sort! { |a, b| b.zip <=> a.zip }
# ...same as...
my_objects.sort! { |a, b| -1 * (a.zip <=> b.zip) }

# Sort by last name, then first
my_objects.sort! { |a, b| 2 * (a.last <=> b.last) + (a.first <=> b.first) }

# Sort by zip, then age descending, then last name, then first
# [Notice powers of 2 make it work for > 2 columns.]
my_objects.sort! do |a, b|
      8 * (a.zip   <=> b.zip) +
     -4 * (a.age   <=> b.age) +
      2 * (a.last  <=> b.last) +
          (a.first <=> b.first)
end

This basic pattern can be generalized to sort by any number of columns, in any permutation of ascending/descending on each.

typeof !== "undefined" vs. != null

if (input == undefined) { ... }

works just fine. It is of course not a null comparison, but I usually find that if I need to distinguish between undefined and null, I actually rather need to distinguish between undefined and just any false value, so

else if (input) { ... }

does it.

If a program redefines undefined it is really braindead anyway.

The only reason I can think of was for IE4 compatibility, it did not understand the undefined keyword (which is not actually a keyword, unfortunately), but of course values could be undefined, so you had to have this:

var undefined;

and the comparison above would work just fine.

In your second example, you probably need double parentheses to make lint happy?

The communication object, System.ServiceModel.Channels.ServiceChannel, cannot be used for communication

This error can be triggered by your own computer too, and not just an unhandled exception. If your server/computer has its clock time off by too many minutes, many .NET web services will reject your request with an unhandled error. It's handled from their point of view, but unhandled from your point. Check to make sure your receiving server's clock time is correct. If it needs to be fixed, you'll have to reset your service or reboot before the channel reopens.

I experienced this issue on a server where the firewall blocked the Internet time update, and the server got off time for some reason. All the 3rd party .NET web services went into fault because they rejected any web service request. Digging into the Event Viewer helped identify the problem, but adjusting the clock solved it. The error was on our end even though we received the Faulted State error message for future web service calls.

In Angular, how to add Validator to FormControl after control is created?

You simply pass the FormControl an array of validators.

Here's an example showing how you can add validators to an existing FormControl:

this.form.controls["firstName"].setValidators([Validators.minLength(1), Validators.maxLength(30)]);

Note, this will reset any existing validators you added when you created the FormControl.

What is the difference between partitioning and bucketing a table in Hive ?

Using Partitions in Hive table is highly recommended for below reason -

  • Insert into Hive table should be faster ( as it uses multiple threads to write data to partitions )
  • Query from Hive table should be efficient with low latency.

Example :-

Assume that Input File (100 GB) is loaded into temp-hive-table and it contains bank data from across different geographies.

Hive table without Partition

Insert into Hive table Select * from temp-hive-table

/hive-table-path/part-00000-1  (part size ~ hdfs block size)
/hive-table-path/part-00000-2
....
/hive-table-path/part-00000-n

Problem with this approach is - It will scan whole data for any query you run on this table. Response time will be high compare to other approaches where partitioning and Bucketing are used.

Hive table with Partition

Insert into Hive table partition(country) Select * from temp-hive-table

/hive-table-path/country=US/part-00000-1       (file size ~ 10 GB)
/hive-table-path/country=Canada/part-00000-2   (file size ~ 20 GB)
....
/hive-table-path/country=UK/part-00000-n       (file size ~ 5 GB)

Pros - Here one can access data faster when it comes to querying data for specific geography transactions. Cons - Inserting/querying data can further be improved by splitting data within each partition. See Bucketing option below.

Hive table with Partition and Bucketing

Note: Create hive table ..... with "CLUSTERED BY(Partiton_Column) into 5 buckets

Insert into Hive table partition(country) Select * from temp-hive-table

/hive-table-path/country=US/part-00000-1       (file size ~ 2 GB)
/hive-table-path/country=US/part-00000-2       (file size ~ 2 GB)
/hive-table-path/country=US/part-00000-3       (file size ~ 2 GB)
/hive-table-path/country=US/part-00000-4       (file size ~ 2 GB)
/hive-table-path/country=US/part-00000-5       (file size ~ 2 GB)

/hive-table-path/country=Canada/part-00000-1   (file size ~ 4 GB)
/hive-table-path/country=Canada/part-00000-2   (file size ~ 4 GB)
/hive-table-path/country=Canada/part-00000-3   (file size ~ 4 GB)
/hive-table-path/country=Canada/part-00000-4   (file size ~ 4 GB)
/hive-table-path/country=Canada/part-00000-5   (file size ~ 4 GB)

....
/hive-table-path/country=UK/part-00000-1       (file size ~ 1 GB)
/hive-table-path/country=UK/part-00000-2       (file size ~ 1 GB)
/hive-table-path/country=UK/part-00000-3       (file size ~ 1 GB)
/hive-table-path/country=UK/part-00000-4       (file size ~ 1 GB)
/hive-table-path/country=UK/part-00000-5       (file size ~ 1 GB)

Pros - Faster Insert. Faster Query.

Cons - Bucketing will creating more files. There could be issue with many small files in some specific cases

Hope this will help !!

Changing button color programmatically

I believe you want bgcolor. Something like this:

document.getElementById("button").bgcolor="#ffffff";

Here are a couple of demos that might help:

Background Color

Background Color Changer

Laravel-5 'LIKE' equivalent (Eloquent)

$data = DB::table('borrowers')
        ->join('loans', 'borrowers.id', '=', 'loans.borrower_id')
        ->select('borrowers.*', 'loans.*')   
        ->where('loan_officers', 'like', '%' . $officerId . '%')
        ->where('loans.maturity_date', '<', date("Y-m-d"))
        ->get();

Clear text field value in JQuery

you can clear it by using this line

$('#TextBoxID').val("");

Best way to define private methods for a class in Objective-C

There isn't really a "private method" in Objective-C, if the runtime can work out which implementation to use it will do it. But that's not to say that there aren't methods which aren't part of the documented interface. For those methods I think that a category is fine. Rather than putting the @interface at the top of the .m file like your point 2, I'd put it into its own .h file. A convention I follow (and have seen elsewhere, I think it's an Apple convention as Xcode now gives automatic support for it) is to name such a file after its class and category with a + separating them, so @interface GLObject (PrivateMethods) can be found in GLObject+PrivateMethods.h. The reason for providing the header file is so that you can import it in your unit test classes :-).

By the way, as far as implementing/defining methods near the end of the .m file is concerned, you can do that with a category by implementing the category at the bottom of the .m file:

@implementation GLObject(PrivateMethods)
- (void)secretFeature;
@end

or with a class extension (the thing you call an "empty category"), just define those methods last. Objective-C methods can be defined and used in any order in the implementation, so there's nothing to stop you putting the "private" methods at the end of the file.

Even with class extensions I will often create a separate header (GLObject+Extension.h) so that I can use those methods if required, mimicking "friend" or "protected" visibility.

Since this answer was originally written, the clang compiler has started doing two passes for Objective-C methods. This means you can avoid declaring your "private" methods completely, and whether they're above or below the calling site they'll be found by the compiler.

How to manually set REFERER header in Javascript?

Above solution does not work for me , I have tried following and it is working in all browsers.

simply made a fake ajax call, it will make a entry into referer header.

var request;
if (window.XMLHttpRequest) { // Mozilla, Safari, ...
    request = new XMLHttpRequest();
} else if (window.ActiveXObject) { // IE
    try {
        request = new ActiveXObject('Msxml2.XMLHTTP');
    } catch (e) {
        try {
            request = new ActiveXObject('Microsoft.XMLHTTP');
        } catch (e) {}
    }
}
request.open("GET", url, true);
request.send();

How can I install a previous version of Python 3 in macOS using homebrew?

As an update, when doing

brew unlink python # If you have installed (with brew) another version of python
brew install https://raw.githubusercontent.com/Homebrew/homebrew-core/f2a764ef944b1080be64bd88dca9a1d80130c558/Formula/python.rb

You may encounter

Error: python contains a recursive dependency on itself:
  python depends on sphinx-doc
  sphinx-doc depends on python

To bypass it, add the --ignore-dependencies argument to brew install.

brew unlink python # If you have installed (with brew) another version of python
brew install --ignore-dependencies https://raw.githubusercontent.com/Homebrew/homebrew-core/f2a764ef944b1080be64bd88dca9a1d80130c558/Formula/python.rb

What are the "standard unambiguous date" formats for string-to-date conversion in R?

In other words, is there a better solution than needing to specify the format?

Yes, there is now (ie in late 2016), thanks to anytime::anydate from the anytime package.

See the following for some examples from above:

R> anydate(c("01 Jan 2000", "01/01/2000", "2015/10/10"))
[1] "2000-01-01" "2000-01-01" "2015-10-10"
R> 

As you said, these are in fact unambiguous and should just work. And via anydate() they do. Without a format.

javascript create empty array of a given size

We use Array.from({length: 500}) since 2017.

What to do on TransactionTooLargeException

You have clear your old InstanceState from onSaveInstanceState method, and it will work well. I am using FragmentStatePagerAdapter for my viewpager so I keep below Override method into my parent activity for clear InstanceState.

@Override
protected void onSaveInstanceState(Bundle InstanceState) {
             super.onSaveInstanceState(InstanceState);
             InstanceState.clear();
}

I found this solution from here android.os.TransactionTooLargeException on Nougat

Python Matplotlib figure title overlaps axes label when using twiny

ax.set_title('My Title\n', fontsize="15", color="red")
plt.imshow(myfile, origin="upper")

If you put '\n' right after your title string, the plot is drawn just below the title. That might be a fast solution too.

Creating SVG graphics using Javascript?

This answer is from 2009. Now a community wiki in case anybody cares to bring it up-to-date.

IE needs a plugin to display SVG. Most common is the one available for download by Adobe; however, Adobe no longer supports or develops it. Firefox, Opera, Chrome, Safari, will all display basic SVG fine but will run into quirks if advanced features are used, as support is incomplete. Firefox has no support for declarative animation.

SVG elements can be created with javascript as follows:

// "circle" may be any tag name
var shape = document.createElementNS("http://www.w3.org/2000/svg", "circle");
// Set any attributes as desired
shape.setAttribute("cx", 25);
shape.setAttribute("cy", 25);
shape.setAttribute("r",  20);
shape.setAttribute("fill", "green");
// Add to a parent node; document.documentElement should be the root svg element.
// Acquiring a parent element with document.getElementById() would be safest.
document.documentElement.appendChild(shape);

The SVG specification describes the DOM interfaces for all SVG elements. For example, the SVGCircleElement, which is created above, has cx, cy, and r attributes for the center point and radius, which can be directly accessed. These are the SVGAnimatedLength attributes, which have a baseVal property for the normal value, and an animVal property for the animated value. Browsers at the moment are not reliably supporting the animVal property. baseVal is an SVGLength, whose value is set by the value property.

Hence, for script animations, one can also set these DOM properties to control SVG. The following code should be equivalent to the above code:

var shape = document.createElementNS("http://www.w3.org/2000/svg", "circle");
shape.cx.baseVal.value = 25;
shape.cy.baseVal.value = 25;
shape.r.baseVal.value = 20;
shape.setAttribute("fill", "green");
document.documentElement.appendChild(shape);

Is there a way to list open transactions on SQL Server 2000 database?

For all databases query sys.sysprocesses

SELECT * FROM sys.sysprocesses WHERE open_tran = 1

For the current database use:

DBCC OPENTRAN

Convert a CERT/PEM certificate to a PFX certificate

I created .pfx file from .key and .pem files.

Like this openssl pkcs12 -inkey rootCA.key -in rootCA.pem -export -out rootCA.pfx

That's not the direct answer but still maybe it helps out someone else.

1 = false and 0 = true?

I suspect it's just following the Linux / Unix standard for returning 0 on success.

Does it really say "1" is false and "0" is true?

Setting href attribute at runtime

In jQuery 1.6+ it's better to use:

$(selector).prop('href',"http://www...") to set the value, and

$(selector).prop('href') to get the value

In short, .prop gets and sets values on the DOM object, and .attr gets and sets values in the HTML. This makes .prop a little faster and possibly more reliable in some contexts.

HTML: Changing colors of specific words in a string of text

You could use the longer boringer way

_x000D_
_x000D_
<p style="font-size:14px; color:#538b01; font-weight:bold; font-style:italic;">Enter the competition by</p><p style="font-size:14px; color:#ff00; font-weight:bold; font-style:italic;">summer</p> 
_x000D_
_x000D_
_x000D_

you get the point for the rest

Asp.net Hyperlink control equivalent to <a href="#"></a>

If you need to access this as a server-side control (e.g. you want to add data attributes to a link, as I did), then there is a way to do what you want; however, you don't use the Hyperlink or HtmlAnchor controls to do it. Create a literal control and then add in "Your Text" as the text for the literal control (or whatever else you need to do that way). It's hacky, but it works.

How can you make a custom keyboard in Android?

Here is a sample project for a soft keyboard.

https://developer.android.com/guide/topics/text/creating-input-method.html

Your's should be in the same lines with a different layout.

Edit: If you need the keyboard only in your application, its very simple! Create a linear layout with vertical orientation, and create 3 linear layouts inside it with horizontal orientation. Then place the buttons of each row in each of those horizontal linear layouts, and assign the weight property to the buttons. Use android:layout_weight=1 for all of them, so they get equally spaced.

This will solve. If you didn't get what was expected, please post the code here, and we are here to help you!

How to execute an oracle stored procedure?

Oracle 10g Express Edition ships with Oracle Application Express (Apex) built-in. You're running this in its SQL Commands window, which doesn't support SQL*Plus syntax.

That doesn't matter, because (as you have discovered) the BEGIN...END syntax does work in Apex.

HTML/CSS font color vs span style

1st preference external style sheet.

<span class="myClass">test</span>

css

.myClass
{
color:red;
}

2nd preference inline style

<span style="color:red">test</span>

<font> as mentioned is deprecated.

pythonw.exe or python.exe?

I was struggling to get this to work for a while. Once you change the extension to .pyw, make sure that you open properties of the file and direct the "open with" path to pythonw.exe.

Convert text to columns in Excel using VBA

Try this

Sub Txt2Col()
    Dim rng As Range

    Set rng = [C7]
    Set rng = Range(rng, Cells(Rows.Count, rng.Column).End(xlUp))

    rng.TextToColumns Destination:=rng, DataType:=xlDelimited, ' rest of your settings

Update: button click event to act on another sheet

Private Sub CommandButton1_Click()
    Dim rng As Range
    Dim sh As Worksheet

    Set sh = Worksheets("Sheet2")
    With sh
        Set rng = .[C7]
        Set rng = .Range(rng, .Cells(.Rows.Count, rng.Column).End(xlUp))

        rng.TextToColumns Destination:=rng, DataType:=xlDelimited, _
        TextQualifier:=xlDoubleQuote,  _
        ConsecutiveDelimiter:=False, _
        Tab:=False, _
        Semicolon:=False, _
        Comma:=True, 
        Space:=False, 
        Other:=False, _
        FieldInfo:=Array(Array(1, xlGeneralFormat), Array(2, xlGeneralFormat), Array(3, xlGeneralFormat)), _
        TrailingMinusNumbers:=True
    End With
End Sub

Note the .'s (eg .Range) they refer to the With statement object

What is the T-SQL To grant read and write access to tables in a database in SQL Server?

From SQLServer 2012 more elegant alter role:

use mydb
go

ALTER ROLE db_datareader
  ADD MEMBER MYUSER 
go
ALTER ROLE db_datawriter
  ADD MEMBER MYUSER 
go

Remove Backslashes from Json Data in JavaScript

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

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

Python threading. How do I lock a thread?

You can see that your locks are pretty much working as you are using them, if you slow down the process and make them block a bit more. You had the right idea, where you surround critical pieces of code with the lock. Here is a small adjustment to your example to show you how each waits on the other to release the lock.

import threading
import time
import inspect

class Thread(threading.Thread):
    def __init__(self, t, *args):
        threading.Thread.__init__(self, target=t, args=args)
        self.start()

count = 0
lock = threading.Lock()

def incre():
    global count
    caller = inspect.getouterframes(inspect.currentframe())[1][3]
    print "Inside %s()" % caller
    print "Acquiring lock"
    with lock:
        print "Lock Acquired"
        count += 1  
        time.sleep(2)  

def bye():
    while count < 5:
        incre()

def hello_there():
    while count < 5:
        incre()

def main():    
    hello = Thread(hello_there)
    goodbye = Thread(bye)


if __name__ == '__main__':
    main()

Sample output:

...
Inside hello_there()
Acquiring lock
Lock Acquired
Inside bye()
Acquiring lock
Lock Acquired
...

How do you resize a form to fit its content automatically?

You could calculate the required height of the TreeView, by figuring out the height of a node, multiplying it by the number of nodes, then setting the form's MinimumSize property accordingly.

// assuming the treeview is populated!
nodeHeight = treeview1.Nodes[0].Bounds.Height;

this.MaximumSize = new Size(someMaximumWidth, someMaximumHeight);

int requiredFormHeight = (treeView1.GetNodeCount(true) * nodeHeight);

this.MinimumSize = new Size(this.Width, requiredFormHeight);

NB. This assumes though that the treeview1 is the only control on the form. When setting the requiredFormHeight variable you'll need to allow for other controls and height requirements surrounding the treeview, such as the tabcontrol you mentioned.

(I would however agree with @jgauffin and assess the rationale behind the requirement to resize a form everytime it loads without the user's consent - maybe let the user position and size the form and remember that instead??)

Importing data from a JSON file into R

jsonlite will import the JSON into a data frame. It can optionally flatten nested objects. Nested arrays will be data frames.

> library(jsonlite)
> winners <- fromJSON("winners.json", flatten=TRUE)
> colnames(winners)
[1] "winner" "votes" "startPrice" "lastVote.timestamp" "lastVote.user.name" "lastVote.user.user_id"
> winners[,c("winner","startPrice","lastVote.user.name")]
    winner startPrice lastVote.user.name
1 68694999          0              Lamur
> winners[,c("votes")]
[[1]]
                            ts user.name user.user_id
1 Thu Mar 25 03:13:01 UTC 2010     Lamur     68694999
2 Thu Mar 25 03:13:08 UTC 2010     Lamur     68694999

How to effectively work with multiple files in Vim

I use the same .vimrc file for gVim and the command line Vim. I tend to use tabs in gVim and buffers in the command line Vim, so I have my .vimrc set up to make working with both of them easier:

" Movement between tabs OR buffers
nnoremap L :call MyNext()<CR>
nnoremap H :call MyPrev()<CR>

" MyNext() and MyPrev(): Movement between tabs OR buffers
function! MyNext()
    if exists( '*tabpagenr' ) && tabpagenr('$') != 1
        " Tab support && tabs open
        normal gt
    else
        " No tab support, or no tabs open
        execute ":bnext"
    endif
endfunction
function! MyPrev()
    if exists( '*tabpagenr' ) && tabpagenr('$') != '1'
        " Tab support && tabs open
        normal gT
    else
        " No tab support, or no tabs open
        execute ":bprev"
    endif
endfunction

This clobbers the existing mappings for H and L, but it makes switching between files extremely fast and easy. Just hit H for next and L for previous; whether you're using tabs or buffers, you'll get the intended results.

Insert text into textarea with jQuery

This is similar to the answer given by @panchicore with a minor bug fixed.

function insertText(element, value) 
{
   var element_dom = document.getElementsByName(element)[0];
   if (document.selection) 
   {
      element_dom.focus();
      sel = document.selection.createRange();
      sel.text = value;
      return;
    } 
   if (element_dom.selectionStart || element_dom.selectionStart == "0") 
   {
     var t_start = element_dom.selectionStart;
     var t_end = element_dom.selectionEnd;
     var val_start = element_dom.value.substring(value, t_start);
     var val_end = element_dom.value.substring(t_end, element_dom.value.length);
     element_dom.value = val_start + value + val_end;
   } 
   else
   {
      element_dom.value += value;
   }
}

What is stdClass in PHP?

Its also worth noting that by using Casting you do not actually need to create an object as in the answer given by @Bandula. Instead you can simply cast your array to an object and the stdClass is returned. For example:

$array = array(
    'Property1'=>'hello',
    'Property2'=>'world',
    'Property3'=>'again',
);

$obj = (object) $array;
echo $obj->Property3;

Output: again

jQuery: Currency Format Number

function converter()
{

var number = $(.number).text();

var number = 'Rp. '+number;

s(.number).val(number);
}

What "wmic bios get serialnumber" actually retrieves?

run cmd

Enter wmic baseboard get product,version,serialnumber

Press the enter key. The result you see under serial number column is your motherboard serial number

Replace Both Double and Single Quotes in Javascript String

mystring = mystring.replace(/["']/g, "");

Making interface implementations async

Better solution is to introduce another interface for async operations. New interface must inherit from original interface.

Example:

interface IIO
{
    void DoOperation();
}

interface IIOAsync : IIO
{
    Task DoOperationAsync();
}


class ClsAsync : IIOAsync
{
    public void DoOperation()
    {
        DoOperationAsync().GetAwaiter().GetResult();
    }

    public async Task DoOperationAsync()
    {
        //just an async code demo
        await Task.Delay(1000);
    }
}


class Program
{
    static void Main(string[] args)
    {
        IIOAsync asAsync = new ClsAsync();
        IIO asSync = asAsync;

        Console.WriteLine(DateTime.Now.Second);

        asAsync.DoOperation();
        Console.WriteLine("After call to sync func using Async iface: {0}", 
            DateTime.Now.Second);

        asAsync.DoOperationAsync().GetAwaiter().GetResult();
        Console.WriteLine("After call to async func using Async iface: {0}", 
            DateTime.Now.Second);

        asSync.DoOperation();
        Console.WriteLine("After call to sync func using Sync iface: {0}", 
            DateTime.Now.Second);

        Console.ReadKey(true);
    }
}

P.S. Redesign your async operations so they return Task instead of void, unless you really must return void.

Which SchemaType in Mongoose is Best for Timestamp?

new mongoose.Schema({ description: { type: String, required: true, trim: true }, completed: { type: Boolean, default: false }, owner: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User' } }, { timestamps: true });

How to change the DataTable Column Name?

Rename the Column by doing the following:

dataTable.Columns["ColumnName"].ColumnName = "newColumnName";

Method with a bool return

     public bool roomSelected()
    {
        int a = 0;
        foreach (RadioButton rb in GroupBox1.Controls)
        {
            if (rb.Checked == true)
            {
                a = 1;
            }
        }
        if (a == 1)
        {
            return true;
        }
        else
        {
            return false;
        }
    }

this how I solved my problem

How to loop through key/value object in Javascript?

for (var key in data) {
    alert("User " + data[key] + " is #" + key); // "User john is #234"
}

Get min and max value in PHP Array

For the people using PHP 5.5+ this can be done a lot easier with array_column. Not need for those ugly array_maps anymore.

How to get a max value:

$highest_weight = max(array_column($details, 'Weight'));

How to get the min value

$lowest_weight = min(array_column($details, 'Weight'));

'node' is not recognized as an internal or external command

Everytime I install node.js it needs a reboot and then the path is recognized.

Create a date from day month and year with T-SQL

Or using just a single dateadd function:

DECLARE @day int, @month int, @year int
SELECT @day = 4, @month = 3, @year = 2011

SELECT dateadd(mm, (@year - 1900) * 12 + @month - 1 , @day - 1)

How do you remove a Cookie in a Java Servlet

Keep in mind that a cookie is actually defined by the tuple of it's name, path, and domain. If any one of those three is different, or there is more than one cookie of the same name, but defined with paths/domains that may still be visible for the URL in question, you'll still see that cookie passed on the request. E.g. if the url is "http://foo.bar.com/baz/index.html", you'll see any cookies defined on bar.com or foo.bar.com, or with a path of "/" or "/baz".

Thus, what you have looks like it should work, as long as there's only one cookie defined in the client, with the name "SSO_COOKIE_NAME", domain "SSO_DOMAIN", and path "/". If there are any cookies with different path or domain, you'll still see the cookie sent to the client.

To debug this, go into Firefox's preferences -> Security tab, and search for all cookies with the SSO_COOKIE_NAME. Click on each to see the domain and path. I'm betting you'll find one in there that's not quite what you're expecting.

typescript - cloning object

Try this:

let copy = (JSON.parse(JSON.stringify(objectToCopy)));

It is a good solution until you are using very large objects or your object has unserializable properties.

In order to preserve type safety you could use a copy function in the class you want to make copies from:

getCopy(): YourClassName{
    return (JSON.parse(JSON.stringify(this)));
}

or in a static way:

static createCopy(objectToCopy: YourClassName): YourClassName{
    return (JSON.parse(JSON.stringify(objectToCopy)));
}

Postgresql - change the size of a varchar column to lower length

if you put the alter into a transaction the table should not be locked:

BEGIN;
  ALTER TABLE "public"."mytable" ALTER COLUMN "mycolumn" TYPE varchar(40);
COMMIT;

this worked for me blazing fast, few seconds on a table with more than 400k rows.

How to display a readable array - Laravel

actually a much easier way to get a readable array of what you (probably) want to see, is instead of using

dd($users); 

or

dd(User::all());

use this

dd($users->toArray());

or

 dd(User::all()->toArray());

which is a lot nicer to debug with.

EDIT - additional, this also works nicely in your views / templates so if you pass the get all users to your template, you can then dump it into your blade template

{{ dd($users->toArray()) }}

vertical divider between two columns in bootstrap

If you are still seeking for the best solution in 2018, I found the way this works perfectly if you have at least one free pseudo element( ::after or ::before ).

You just have to add class to your row like this: <div class="row vertical-divider ">

And add this to your CSS:

.row.vertical-divider [class*='col-']:not(:last-child)::after {
  background: #e0e0e0;
  width: 1px;
  content: "";
  display:block;
  position: absolute;
  top:0;
  bottom: 0;
  right: 0;
  min-height: 70px;
}

Any row with this class will now have vertical divider between all of the columns it contains...

You can see how this works in this example.

Using Axios GET with Authorization Header in React-Native App

For anyone else that comes across this post and might find it useful... There is actually nothing wrong with my code. I made the mistake of requesting client_credentials type access code instead of password access code (#facepalms). FYI I am using urlencoded post hence the use of querystring.. So for those that may be looking for some example code.. here is my full request

Big thanks to @swapnil for trying to help me debug this.

   const data = {
      grant_type: USER_GRANT_TYPE,
      client_id: CLIENT_ID,
      client_secret: CLIENT_SECRET,
      scope: SCOPE_INT,
      username: DEMO_EMAIL,
      password: DEMO_PASSWORD
    };



  axios.post(TOKEN_URL, Querystring.stringify(data))   
   .then(response => {
      console.log(response.data);
      USER_TOKEN = response.data.access_token;
      console.log('userresponse ' + response.data.access_token); 
    })   
   .catch((error) => {
      console.log('error ' + error);   
   });



const AuthStr = 'Bearer '.concat(USER_TOKEN); 
axios.get(URL, { headers: { Authorization: AuthStr } })
 .then(response => {
     // If request is good...
     console.log(response.data);
  })
 .catch((error) => {
     console.log('error ' + error);
  });

Can't access RabbitMQ web management interface after fresh install

Something that just happened to me and caused me some headaches:

I have set up a new Linux RabbitMQ server and used a shell script to set up my own custom users (not guest!).

The script had several of those "code" blocks:

rabbitmqctl add_user test test
rabbitmqctl set_user_tags test administrator
rabbitmqctl set_permissions -p / test ".*" ".*" ".*"

Very similar to the one in Gabriele's answer, so I take his code and don't need to redact passwords.

Still I was not able to log in in the management console. Then I noticed that I had created the setup script in Windows (CR+LF line ending) and converted the file to Linux (LF only), then reran the setup script on my Linux server.

... and was still not able to log in, because it took another 15 minutes until I realized that calling add_user over and over again would not fix the broken passwords (which probably ended with a CR character). I had to call change_password for every user to fix my earlier mistake:

rabbitmqctl change_password test test

(Another solution would have been to delete all users and then call the script again)

ASP.NET Core Dependency Injection error: Unable to resolve service for type while attempting to activate

ohh, Thank @kimbaudi, i followed this tuts

https://dotnettutorials.net/lesson/generic-repository-pattern-csharp-mvc/

and got the same error as your. But after read your code i found out my solution was adding

services.AddScoped(IGenericRepository, GenericRepository);

into ConfigureServices method in StartUp.cs file =))

What is difference between INNER join and OUTER join

INNER JOIN: Returns all rows when there is at least one match in BOTH tables

LEFT JOIN: Return all rows from the left table, and the matched rows from the right table

RIGHT JOIN: Return all rows from the right table, and the matched rows from the left table

FULL JOIN: Return all rows when there is a match in ONE of the tables

What does the "static" modifier after "import" mean?

The static modifier after import is for retrieving/using static fields of a class. One area in which I use import static is for retrieving constants from a class. We can also apply import static on static methods. Make sure to type import static because static import is wrong.

What is static import in Java - JavaRevisited - A very good resource to know more about import static.

How to add constraints programmatically using Swift

This is one way to adding constraints programmatically

override func viewDidLoad() {
            super.viewDidLoad()


let myLabel = UILabel()
        myLabel.labelFrameUpdate(label: myLabel, text: "Welcome User", font: UIFont(name: "times new roman", size: 40)!, textColor: UIColor.red, textAlignment: .center, numberOfLines: 0, borderWidth: 2.0, BorderColor: UIColor.red.cgColor)
        self.view.addSubview(myLabel)


         let myLabelhorizontalConstraint = NSLayoutConstraint(item: myLabel, attribute: NSLayoutAttribute.centerX, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerX, multiplier: 1, constant: 0)
        let myLabelverticalConstraint = NSLayoutConstraint(item: myLabel, attribute: NSLayoutAttribute.centerY, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.centerY, multiplier: 1, constant: 0)
        let mylabelLeading = NSLayoutConstraint(item: myLabel, attribute: NSLayoutAttribute.leading, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.leading, multiplier: 1, constant: 10)
        let mylabelTrailing = NSLayoutConstraint(item: myLabel, attribute: NSLayoutAttribute.trailing, relatedBy: NSLayoutRelation.equal, toItem: self.view, attribute: NSLayoutAttribute.trailing, multiplier: 1, constant: -10)
        let myLabelheightConstraint = NSLayoutConstraint(item: myLabel, attribute: NSLayoutAttribute.height, relatedBy: NSLayoutRelation.equal, toItem: nil, attribute: NSLayoutAttribute.notAnAttribute, multiplier: 1, constant: 50)
        NSLayoutConstraint.activate(\[myLabelhorizontalConstraint, myLabelverticalConstraint, myLabelheightConstraint,mylabelLeading,mylabelTrailing\])
}

extension UILabel
{
    func labelFrameUpdate(label:UILabel,text:String = "This is sample Label",font:UIFont = UIFont(name: "times new roman", size: 20)!,textColor:UIColor = UIColor.red,textAlignment:NSTextAlignment = .center,numberOfLines:Int = 0,borderWidth:CGFloat = 2.0,BorderColor:CGColor = UIColor.red.cgColor){
        label.translatesAutoresizingMaskIntoConstraints = false
        label.text = text
        label.font = font
        label.textColor = textColor
        label.textAlignment = textAlignment
        label.numberOfLines = numberOfLines
        label.layer.borderWidth = borderWidth
        label.layer.borderColor = UIColor.red.cgColor
    }
}

enter image description here

How do I test for an empty JavaScript object?

I just ran into a similar situation. I didn't want to use JQuery, and wanted to do this using pure Javascript.

And what I did was, used the following condition, and it worked for me.

var obj = {};
if(JSON.stringify(obj) === '{}') { //This will check if the object is empty
   //Code here..
}

For not equal to, use this : JSON.stringify(obj) !== '{}'

Check out this JSFiddle

How to add an onchange event to a select box via javascript?

replace:

transport_select.onChange = function(){toggleSelect(transport_select_id);};

with:

transport_select.onchange = function(){toggleSelect(transport_select_id);};

on'C'hange >> on'c'hange


You can use addEventListener too.

200 PORT command successful. Consider using PASV. 425 Failed to establish connection

Actually your Windows firewall is blocking the connection. You need to enter these commands into cmd.exe from Administrator.

netsh advfirewall firewall add rule name="FTP" dir=in action=allow program=%SystemRoot%\System32\ftp.exe enable=yes protocol=tcp
netsh advfirewall firewall add rule name="FTP" dir=in action=allow program=%SystemRoot%\System32\ftp.exe enable=yes protocol=udp

In case something goes wrong then you can revert by this:

netsh advfirewall firewall delete rule name="FTP" program=%SystemRoot%\System32\ftp.exe

Clear the form field after successful submission of php form

You can check this also

_x000D_
_x000D_
<form id="form1" method="post">
<label class="w">Plan :</label>
<select autofocus="" name="plan" required="required">
    <option value="">Select One</option>
    <option value="FREE Account">FREE Account</option>
    <option value="Premium Account Monthly">Premium Account Monthly</option>
    <option value="Premium Account Yearly">Premium Account Yearly</option>
</select>
<br>
<label class="w">First Name :</label><input name="firstname" type="text" placeholder="First Name" required="required" ><br>
<label class="w">Last Name :</label><input name="lastname" type="text" placeholder="Last Name" required="required" ><br>
<label class="w">E-mail ID :</label><input name="email" type="email" placeholder="Enter Email" required="required" ><br>
<label class="w">Password :</label><input name="password" type="password" placeholder="********" required="required"><br>
<label class="w">Re-Enter Password :</label><input name="confirmpassword" type="password" placeholder="********" required="required"><br>
<label class="w">Street Address 1 :</label><input name="strtadd1" type="text" placeholder="street address first" required="required"><br>
<label class="w">Street Address 2 :</label><input name="strtadd2" type="text" placeholder="street address second" ><br>
<label class="w">City :</label>
<input name="city" type="text" placeholder="City" required="required"><br>
<label class="w">Country :</label>
<select autofocus id="a1_txtBox1" name="country" required="required" placeholder="select one">
<option>Select One</option>
<option>UK</option>
<option>US</option>
</select>
<br>
<br>
<input type="reset" value="Submit" />

</form>
_x000D_
_x000D_
_x000D_

Memory address of variables in Java

This is not memory address This is classname@hashcode
Which is the default implementation of Object.toString()

public String toString() {
    return getClass().getName() + "@" + Integer.toHexString(hashCode());
}

where

Class name = full qualified name or absolute name (ie package name followed by class name) hashcode = hexadecimal format (System.identityHashCode(obj) or obj.hashCode() will give you hashcode in decimal format).

Hint:
The confusion root cause is that the default implementation of Object.hashCode() use the internal address of the object into an integer

This is typically implemented by converting the internal address of the object into an integer, but this implementation technique is not required by the Java™ programming language.

And of course, some classes can override both default implementations either for toString() or hashCode()

If you need the default implementation value of hashcode() for a object which overriding it,
You can use the following method System.identityHashCode(Object x)

SyntaxError: JSON.parse: unexpected character at line 1 column 1 of the JSON data

Try using MYSQLI_ASSOC instead MYSQL_ASSOC... usually the problem is solved changing that

Good luck!

How To Get The Current Year Using Vba

Try =Year(Now()) and format the cell as General.

"X-UA-Compatible" content="IE=9; IE=8; IE=7; IE=EDGE"

In certain cases, it might be necessary to restrict the display of a webpage to a document mode supported by an earlier version of Internet Explorer. You can do this by serving the page with an x-ua-compatible header. For more info, see Specifying legacy document modes.
- https://msdn.microsoft.com/library/cc288325

Thus this tag is used to future proof the webpage, such that the older / compatible engine is used to render it the same way as intended by the creator.

Make sure that you have checked it to work properly with the IE version you specify.

How do I keep two side-by-side divs the same height?

You can use Jquery's Equal Heights Plugin to accomplish, this plugins makes all the div of exact same height as other. If one of them grows and other will also grow.

Here a sample of implementation

Usage: $(object).equalHeights([minHeight], [maxHeight]);

Example 1: $(".cols").equalHeights(); 
           Sets all columns to the same height.

Example 2: $(".cols").equalHeights(400); 
           Sets all cols to at least 400px tall.

Example 3: $(".cols").equalHeights(100,300); 
           Cols are at least 100 but no more than 300 pixels tall. Elements with too much content will gain a scrollbar.

Here is the link

http://www.cssnewbie.com/equalheights-jquery-plugin/

How to list all the files in a commit?

I thought I would share a summary of my alias.. also I find using 'zsh' great with git it chroma keys everything nicely and tells you want branch are in all of the time by changing the command prompt.

For those covering from SVN you will find this useful: (this is a combination of ideas from different threads, I only take credit of knowing how to use copy/paste)

.gitconfig:
        ls = log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)%an%Creset' --abbrev-commit --date=relative --name-status

>>git ls
* 99f21a6 - (HEAD -> swift) New Files from xcode 7 (11 hours ago) Jim Zucker| 
| A     icds.xcodeproj/project.pbxproj
| A     icds.xcodeproj/project.xcworkspace/contents.xcworkspacedata
| A     icds/AppDelegate.m
| A     icds/Assets.xcassets/AppIcon.appiconset/Contents.json

* e0a1bb6 - Move everything to old (11 hours ago) Jim Zucker| 
| D     Classes/AppInfoViewControler.h
| D     Classes/AppInfoViewControler.m
| D     Classes/CurveInstrument.h


.gitconfig: 
       lt = log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)%an%Creset' --abbrev-commit --date=relative

>>git lt
* 99f21a6 - (HEAD -> swift) New Files from xcode 7 (11 hours ago) Jim Zucker
* e0a1bb6 - Move everything to old (11 hours ago) Jim Zucker
* 778bda6 - Cleanup for new project (11 hours ago) Jim Zucker
* 7373b5e - clean up files from old version (11 hours ago) Jim Zucker
* 14a8d53 - (tag: 1.x, origin/swift, origin/master, master) Initial Commit (16 hours ago) Jim Zucker


.gitconfig
lt = log --graph --pretty=format:'%Cred%h%Creset -%C(yellow)%d%Creset %s %Cgreen(%cr) %C(bold blue)%an%Creset' --abbrev-commit --date=relative

>> git lt

commit 99f21a61de832bad7b2bdb74066a08cac3d0bf3c
Author: Jim Zucker <[email protected]>
Date:   Tue Dec 1 22:23:10 2015 -0800

    New Files from xcode 7

A       icds.xcodeproj/project.pbxproj
A       icds.xcodeproj/project.xcworkspace/contents.xcworkspacedata


commit e0a1bb6b59ed6a4f9147e894d7f7fe00283fce8d
Author: Jim Zucker <[email protected]>
Date:   Tue Dec 1 22:17:00 2015 -0800

    Move everything to old

D       Classes/AppInfoViewControler.h
D       Classes/AppInfoViewControler.m
D       Classes/CurveInstrument.h
D       Classes/CurveInstrument.m

What is reflection and why is it useful?

Reflection is to let object to see their appearance. This argument seems nothing to do with reflection. In fact, this is the "self-identify" ability.

Reflection itself is a word for such languages that lack the capability of self-knowledge and self-sensing as Java and C#. Because they do not have the capability of self-knowledge, when we want to observe how it looks like, we must have another thing to reflect on how it looks like. Excellent dynamic languages such as Ruby and Python can perceive the reflection of their own without the help of other individuals. We can say that the object of Java cannot perceive how it looks like without a mirror, which is an object of the reflection class, but an object in Python can perceive it without a mirror. So that's why we need reflection in Java.

How to read a text file into a list or an array with Python

You can also use numpy loadtxt like

from numpy import loadtxt
lines = loadtxt("filename.dat", comments="#", delimiter=",", unpack=False)

How to get the IP address of the docker host from inside a docker container

For those running Docker in AWS, the instance meta-data for the host is still available from inside the container.

curl http://169.254.169.254/latest/meta-data/local-ipv4

For example:

$ docker run alpine /bin/sh -c "apk update ; apk add curl ; curl -s http://169.254.169.254/latest/meta-data/local-ipv4 ; echo"
fetch http://dl-cdn.alpinelinux.org/alpine/v3.3/main/x86_64/APKINDEX.tar.gz
fetch http://dl-cdn.alpinelinux.org/alpine/v3.3/community/x86_64/APKINDEX.tar.gz
v3.3.1-119-gb247c0a [http://dl-cdn.alpinelinux.org/alpine/v3.3/main]
v3.3.1-59-g48b0368 [http://dl-cdn.alpinelinux.org/alpine/v3.3/community]
OK: 5855 distinct packages available
(1/4) Installing openssl (1.0.2g-r0)
(2/4) Installing ca-certificates (20160104-r2)
(3/4) Installing libssh2 (1.6.0-r1)
(4/4) Installing curl (7.47.0-r0)
Executing busybox-1.24.1-r7.trigger
Executing ca-certificates-20160104-r2.trigger
OK: 7 MiB in 15 packages
172.31.27.238

$ ifconfig eth0 | grep -oP 'inet addr:\K\S+'
172.31.27.238

WinError 2 The system cannot find the file specified (Python)

Popen expect a list of strings for non-shell calls and a string for shell calls.

Call subprocess.Popen with shell=True:

process = subprocess.Popen(command, stdout=tempFile, shell=True)

Hopefully this solves your issue.

This issue is listed here: https://bugs.python.org/issue17023

How do I connect to mongodb with node.js (and authenticate)?

Everyone should use this source link:

http://mongodb.github.com/node-mongodb-native/contents.html

Answer to the question:

var Db = require('mongodb').Db,
    MongoClient = require('mongodb').MongoClient,
    Server = require('mongodb').Server,
    ReplSetServers = require('mongodb').ReplSetServers,
    ObjectID = require('mongodb').ObjectID,
    Binary = require('mongodb').Binary,
    GridStore = require('mongodb').GridStore,
    Code = require('mongodb').Code,
    BSON = require('mongodb').pure().BSON,
    assert = require('assert');

var db = new Db('integration_tests', new Server("127.0.0.1", 27017,
 {auto_reconnect: false, poolSize: 4}), {w:0, native_parser: false});

// Establish connection to db
db.open(function(err, db) {
  assert.equal(null, err);

  // Add a user to the database
  db.addUser('user', 'name', function(err, result) {
    assert.equal(null, err);

    // Authenticate
    db.authenticate('user', 'name', function(err, result) {
      assert.equal(true, result);

      db.close();
    });
  });
});

Copy all values in a column to a new column in a pandas dataframe

You can simply assign the B to the new column , Like -

df['D'] = df['B']

Example/Demo -

In [1]: import pandas as pd

In [2]: df = pd.DataFrame([['a.1','b.1','c.1'],['a.2','b.2','c.2'],['a.3','b.3','c.3']],columns=['A','B','C'])

In [3]: df
Out[3]:
     A    B    C
0  a.1  b.1  c.1
1  a.2  b.2  c.2
2  a.3  b.3  c.3

In [4]: df['D'] = df['B']                  #<---What you want.

In [5]: df
Out[5]:
     A    B    C    D
0  a.1  b.1  c.1  b.1
1  a.2  b.2  c.2  b.2
2  a.3  b.3  c.3  b.3

In [6]: df.loc[0,'D'] = 'd.1'

In [7]: df
Out[7]:
     A    B    C    D
0  a.1  b.1  c.1  d.1
1  a.2  b.2  c.2  b.2
2  a.3  b.3  c.3  b.3

how to stop a running script in Matlab

if you are running your matlab on linux, you can terminate the matlab by command in linux consule. first you should find the PID number of matlab by this code:

top

then you can use this code to kill matlab: kill

example: kill 58056

Wildcards in jQuery selectors

Try the jQuery starts-with

selector, '^=', eg

[id^="jander"]

I have to ask though, why don't you want to do this using classes?

Order by in Inner Join

Avoid SELECT * in your main query.

Avoid duplicate columns: the JOIN condition ensures One.One_Name and two.One_Name will be equal therefore you don't need to return both in the SELECT clause.

Avoid duplicate column names: rename One.ID and Two.ID using 'aliases'.

Add an ORDER BY clause using the column names ('alises' where applicable) from the SELECT clause.

Suggested re-write:

SELECT T1.ID AS One_ID, T1.One_Name, 
       T2.ID AS Two_ID, T2.Two_name
  FROM One AS T1
       INNER JOIN two AS T2
          ON T1.One_Name = T2.One_Name
 ORDER 
    BY One_ID;

Add image to layout in ruby on rails

simple just use the img tag helper. Rails knows to look in the images folder in the asset pipeline, you can use it like this

<%= image_tag "image.jpg" %>

Extracting text OpenCV

You can try this method that is developed by Chucai Yi and Yingli Tian.

They also share a software (which is based on Opencv-1.0 and it should run under Windows platform.) that you can use (though no source code available). It will generate all the text bounding boxes (shown in color shadows) in the image. By applying to your sample images, you will get the following results:

Note: to make the result more robust, you can further merge adjacent boxes together.


Update: If your ultimate goal is to recognize the texts in the image, you can further check out gttext, which is an OCR free software and Ground Truthing tool for Color Images with Text. Source code is also available.

With this, you can get recognized texts like:

Android emulator doesn't take keyboard input - SDK tools rev 20

In Android Studio, open AVD Manager (Tools > Android > AVD Manager). Tap the Edit button of the emulator: enter image description here

Select "Show Advanced Settings" enter image description here

Check "Enable keyboard input" enter image description here

Click Finish and start the emulator to enjoy the keyboard input.

Rock, Paper, Scissors Game Java

I would recommend making Rock, Paper and Scissors objects. The objects would have the logic of both translating to/from Strings and also "knowing" what beats what. The Java enum is perfect for this.

public enum Type{

  ROCK, PAPER, SCISSOR;

  public static Type parseType(String value){
     //if /else logic here to return either ROCK, PAPER or SCISSOR

     //if value is not either, you can return null
  }
}

The parseType method can return null if the String is not a valid type. And you code can check if the value is null and if so, print "invalid try again" and loop back to re-read the Scanner.

Type person=null;

 while(person==null){
      System.out.println("Enter your play: "); 
      person= Type.parseType(scan.next());
      if(person ==null){
         System.out.println("invalid try again");
      }
 }

Furthermore, your type enum can determine what beats what by having each Type object know:

public enum Type{

    //...

    //each type will implement this method differently
    public abstract boolean beats(Type other);


}

each type will implement this method differently to see what beats what:

ROCK{

   @Override
   public boolean beats(Type other){            
        return other ==  SCISSOR;

   }
}

 ...

Then in your code

 Type person, computer;
   if (person.equals(computer)) 
   System.out.println("It's a tie!");
  }else if(person.beats(computer)){
     System.out.println(person+ " beats " + computer + "You win!!"); 
  }else{
     System.out.println(computer + " beats " + person+ "You lose!!");
  }

JavaScript string and number conversion

Step (1) Concatenate "1", "2", "3" into "123"

 "1" + "2" + "3"

or

 ["1", "2", "3"].join("")

The join method concatenates the items of an array into a string, putting the specified delimiter between items. In this case, the "delimiter" is an empty string ("").


Step (2) Convert "123" into 123

 parseInt("123")

Prior to ECMAScript 5, it was necessary to pass the radix for base 10: parseInt("123", 10)


Step (3) Add 123 + 100 = 223

 123 + 100


Step (4) Covert 223 into "223"

 (223).toString() 


Put It All Togther

 (parseInt("1" + "2" + "3") + 100).toString()

or

 (parseInt(["1", "2", "3"].join("")) + 100).toString()

How can I force a long string without any blank to be wrapped?

for block elements:

_x000D_
_x000D_
<textarea style="width:100px; word-wrap:break-word;">_x000D_
  ACTGATCGAGCTGAAGCGCAGTGCGATGCTTCGATGATGCTGACGATGCTACGATGCGAGCATCTACGATCAGTC_x000D_
</textarea>
_x000D_
_x000D_
_x000D_

for inline elements:

_x000D_
_x000D_
<span style="width:100px; word-wrap:break-word; display:inline-block;"> _x000D_
   ACTGATCGAGCTGAAGCGCAGTGCGATGCTTCGATGATGCTGACGATGCTACGATGCGAGCATCTACGATCAGTC_x000D_
</span>
_x000D_
_x000D_
_x000D_

HTTP Request in Kotlin

Have a look at Fuel library, a sample GET request

"https://httpbin.org/get"
  .httpGet()
  .responseString { request, response, result ->
    when (result) {
      is Result.Failure -> {
        val ex = result.getException()
      }
      is Result.Success -> {
        val data = result.get()
      }
    }
  }

// You can also use Fuel.get("https://httpbin.org/get").responseString { ... }
// You can also use FuelManager.instance.get("...").responseString { ... }

A sample POST request

Fuel.post("https://httpbin.org/post")
    .jsonBody("{ \"foo\" : \"bar\" }")
    .also { println(it) }
    .response { result -> }

Their documentation can be found here ?

How to get the HTML's input element of "file" type to only accept pdf files?

Not with the HTML file control, no. A flash file uploader can do that for you though. You could use some client-side code to check for the PDF extension after they select, but you cannot directly control what they can select.

Applying function with multiple arguments to create a new pandas column

Alternatively, you can use numpy underlying function:

>>> import numpy as np
>>> df = pd.DataFrame({"A": [10,20,30], "B": [20, 30, 10]})
>>> df['new_column'] = np.multiply(df['A'], df['B'])
>>> df
    A   B  new_column
0  10  20         200
1  20  30         600
2  30  10         300

or vectorize arbitrary function in general case:

>>> def fx(x, y):
...     return x*y
...
>>> df['new_column'] = np.vectorize(fx)(df['A'], df['B'])
>>> df
    A   B  new_column
0  10  20         200
1  20  30         600
2  30  10         300

Rails 4 LIKE query - ActiveRecord adds quotes

.find(:all, where: "value LIKE product_%", params: { limit: 20, page: 1 })

What is the difference between Release and Debug modes in Visual Studio?

The main difference is when compiled in debug mode, pdb files are also created which allow debugging (so you can step through the code when its running). This however means that the code isn't optimized as much.

PHP: Update multiple MySQL fields in single query

Comma separate the values:

UPDATE settings SET postsPerPage = $postsPerPage, style = $style WHERE id = '1'"

Export to csv in jQuery

By using just jQuery, you cannot avoid a server call.

However, to achieve this result, I'm using Downloadify, which lets me save files without having to make another server call. Doing this reduces server load and makes a good user experience.

To get a proper CSV you just have to take out all the unnecessary tags and put a ',' between the data.

Return JSON for ResponseEntity<String>

The root of the problem is that Spring (via ResponseEntity, RestController, and/or ResponseBody) will use the contents of the string as the raw response value, rather than treating the string as JSON value to be encoded. This is true even when the controller method uses produces = MediaType.APPLICATION_JSON_VALUE, as in the question here.

It's essentially like the difference between the following:

// yields: This is a String
System.out.println("This is a String");

// yields: "This is a String"
System.out.println("\"This is a String\"");

The first output cannot be parsed as JSON, but the second output can.

Something like '"'+myString+'"' is probably not a good idea however, as that won't handle proper escaping of double-quotes within the string and will not produce valid JSON for any such string.

One way to handle this would be to embed your string inside an object or list, so that you're not passing a raw string to Spring. However, that changes the format of your output, and really there's no good reason not to be able to return a properly-encoded JSON string if that's what you want to do. If that's what you want, the best way to handle it is via a JSON formatter such as Json or Google Gson. Here's how it might look with Gson:

import com.google.gson.Gson;

@RestController
public class MyController

    private static final Gson gson = new Gson();

    @RequestMapping(value = "so", method = RequestMethod.GET, produces = MediaType.APPLICATION_JSON_VALUE)
    ResponseEntity<String> so() {
        return ResponseEntity.ok(gson.toJson("This is a String"));
    }
}

Subset a dataframe by multiple factor levels

Here's another:

data[data$Code == "A" | data$Code == "B", ]

It's also worth mentioning that the subsetting factor doesn't have to be part of the data frame if it matches the data frame rows in length and order. In this case we made our data frame from this factor anyway. So,

data[Code == "A" | Code == "B", ]

also works, which is one of the really useful things about R.

Is it possible to make desktop GUI application in .NET Core?

Windows Forms (and its visual designer) have been available for .NET Core (as a preview) since Visual Studio 2019 16.6. It's quite good, although sometimes I need to open Visual Studio 2019 16.7 Preview to get around annoying bugs.

See this blog post: Windows Forms Designer for .NET Core Released

Also, Windows Forms is now open source: https://github.com/dotnet/winforms

Fit image to table cell [Pure HTML]

It's all about display: block :)

Updated:

Ok so you have the table, tr and td tags:

<table>
  <tr>
    <td>
      <!-- your image goes here -->
    </td>
  </tr>
</table>

Lets say your table or td (whatever define your width) has property width: 360px;. Now, when you try to replace the html comment with the actual image and set that image property for example width: 100%; which should fully fill out the td cell you will face the problem.

The problem is that your table cell (td) isn't properly filled with the image. You'll notice the space at the bottom of the cell which your image doesn't cover (it's like 5px of padding).

How to solve this in a simpliest way?

You are working with the tables, right? You just need to add the display property to your image so that it has the following:

img {
  width: 100%;
  display: block;
}