Programs & Examples On #Line count

Count number of lines in a git repository

The best solution, to me anyway, is buried in the comments of @ephemient's answer. I am just pulling it up here so that it doesn't go unnoticed. The credit for this should go to @FRoZeN (and @ephemient).

git diff --shortstat `git hash-object -t tree /dev/null`

returns the total of files and lines in the working directory of a repo, without any additional noise. As a bonus, only the source code is counted - binary files are excluded from the tally.

The command above works on Linux and OS X. The cross-platform version of it is

git diff --shortstat 4b825dc642cb6eb9a060e54bf8d69288fbee4904

That works on Windows, too.

For the record, the options for excluding blank lines,

  • -w/--ignore-all-space,
  • -b/--ignore-space-change,
  • --ignore-blank-lines,
  • --ignore-space-at-eol

don't have any effect when used with --shortstat. Blank lines are counted.

Eclipse count lines of code

I created a Eclipse plugin, which can count the lines of source code. It support Kotlin, Java, Java Script, JSP, XML, C/C++, C#, and many other file types.

Please take a look at it. Any feedback would be appreciated!

the git-hub repository is here

How to get line count of a large file cheaply in Python?

Kyle's answer

num_lines = sum(1 for line in open('my_file.txt'))

is probably best, an alternative for this is

num_lines =  len(open('my_file.txt').read().splitlines())

Here is the comparision of performance of both

In [20]: timeit sum(1 for line in open('Charts.ipynb'))
100000 loops, best of 3: 9.79 µs per loop

In [21]: timeit len(open('Charts.ipynb').read().splitlines())
100000 loops, best of 3: 12 µs per loop

How to make a text box have rounded corners?

You could use CSS to do that, but it wouldn't be supported in IE8-. You can use some site like http://borderradius.com to come up with actual CSS you'd use, which would look something like this (again, depending on how many browsers you're trying to support):

-webkit-border-radius: 5px;
-moz-border-radius: 5px;
border-radius: 5px;

How do I create a user with the same privileges as root in MySQL/MariaDB?

% mysql --user=root mysql
CREATE USER 'monty'@'localhost' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'localhost' WITH GRANT OPTION;
CREATE USER 'monty'@'%' IDENTIFIED BY 'some_pass';
GRANT ALL PRIVILEGES ON *.* TO 'monty'@'%' WITH GRANT OPTION;
CREATE USER 'admin'@'localhost';
GRANT RELOAD,PROCESS ON *.* TO 'admin'@'localhost';
CREATE USER 'dummy'@'localhost';
FLUSH PRIVILEGES;

What is the regular expression to allow uppercase/lowercase (alphabetical characters), periods, spaces and dashes only?

The regex you're looking for is ^[A-Za-z.\s_-]+$

  • ^ asserts that the regular expression must match at the beginning of the subject
  • [] is a character class - any character that matches inside this expression is allowed
  • A-Z allows a range of uppercase characters
  • a-z allows a range of lowercase characters
  • . matches a period rather than a range of characters
  • \s matches whitespace (spaces and tabs)
  • _ matches an underscore
  • - matches a dash (hyphen); we have it as the last character in the character class so it doesn't get interpreted as being part of a character range. We could also escape it (\-) instead and put it anywhere in the character class, but that's less clear
  • + asserts that the preceding expression (in our case, the character class) must match one or more times
  • $ Finally, this asserts that we're now at the end of the subject

When you're testing regular expressions, you'll likely find a tool like regexpal helpful. This allows you to see your regular expression match (or fail to match) your sample data in real time as you write it.

C++ IDE for Macs

If you are looking for a full-fledged IDE like Visual Studio, I think Eclipse might be your best bet.

Eclipse is also highly extensible and configurable.

See here: http://www.eclipse.org/downloads/

How to round a numpy array?

If you want the output to be

array([1.6e-01, 9.9e-01, 3.6e-04])

the problem is not really a missing feature of NumPy, but rather that this sort of rounding is not a standard thing to do. You can make your own rounding function which achieves this like so:

def my_round(value, N):
    exponent = np.ceil(np.log10(value))
    return 10**exponent*np.round(value*10**(-exponent), N)

For a general solution handling 0 and negative values as well, you can do something like this:

def my_round(value, N):
    value = np.asarray(value).copy()
    zero_mask = (value == 0)
    value[zero_mask] = 1.0
    sign_mask = (value < 0)
    value[sign_mask] *= -1
    exponent = np.ceil(np.log10(value))
    result = 10**exponent*np.round(value*10**(-exponent), N)
    result[sign_mask] *= -1
    result[zero_mask] = 0.0
    return result

ALTER TABLE to add a composite primary key

ALTER TABLE provider ADD PRIMARY KEY(person,place,thing);

If a primary key already exists then you want to do this

ALTER TABLE provider DROP PRIMARY KEY, ADD PRIMARY KEY(person, place, thing);

getting the X/Y coordinates of a mouse click on an image with jQuery

You can use pageX and pageY to get the position of the mouse in the window. You can also use jQuery's offset to get the position of an element.

So, it should be pageX - offset.left for how far from the left of the image and pageY - offset.top for how far from the top of the image.

Here is an example:

$(document).ready(function() {
  $('img').click(function(e) {
    var offset = $(this).offset();
    alert(e.pageX - offset.left);
    alert(e.pageY - offset.top);
  });
});

I've made a live example here and here is the source.

To calculate how far from the bottom or right, you would have to use jQuery's width and height methods.

Add a tooltip to a div

Okay, here's all of your bounty requirements met:

  • No jQuery
  • Instant appearing
  • No dissapearing until the mouse leaves the area
  • Fade in/out effect incorporated
  • And lastly.. simple solution

Here's a demo and link to my code (JSFiddle)

Here are the features that I've incorporated into this purely JS, CSS and HTML5 fiddle:

  • You can set the speed of the fade.
  • You can set the text of the tooltip with a simple variable.

HTML:

<div id="wrapper">
    <div id="a">Hover over this div to see a cool tool tip!</div>
</div>

CSS:

#a{
    background-color:yellow;
    padding:10px;
    border:2px solid red;    
}

.tooltip{
    background:black;
    color:white;
    padding:5px;
    box-shadow:0 0 10px 0 rgba(0, 0, 0, 1);
    border-radius:10px;
    opacity:0;
}

JavaScript:

var div = document.getElementById('wrapper');
var a = document.getElementById("a");
var fadeSpeed = 25; // a value between 1 and 1000 where 1000 will take 10
                    // seconds to fade in and out and 1 will take 0.01 sec.
var tipMessage = "The content of the tooltip...";

var showTip = function(){    
    var tip = document.createElement("span");
    tip.className = "tooltip";
    tip.id = "tip";
    tip.innerHTML = tipMessage;
    div.appendChild(tip);
    tip.style.opacity="0"; // to start with...
    var intId = setInterval(function(){
        newOpacity = parseFloat(tip.style.opacity)+0.1;
        tip.style.opacity = newOpacity.toString();
        if(tip.style.opacity == "1"){
            clearInterval(intId);
        }
    }, fadeSpeed);
};
var hideTip = function(){
    var tip = document.getElementById("tip");
    var intId = setInterval(function(){
        newOpacity = parseFloat(tip.style.opacity)-0.1;
        tip.style.opacity = newOpacity.toString();
        if(tip.style.opacity == "0"){
            clearInterval(intId);
            tip.remove();
        }
    }, fadeSpeed);
    tip.remove();
};

a.addEventListener("mouseover", showTip, false);
a.addEventListener("mouseout", hideTip, false);

How to get a list of MySQL views?

If you created any view in Mysql databases then you can simply see it as you see your all tables in your particular database.

write:

--mysql> SHOW TABLES;

you will see list of tables and views of your database.

java.util.MissingResourceException: Can't find bundle for base name 'property_file name', locale en_US

just right click on the project file in eclipse and in build path select "Use as source folder"...It worked for me

jQuery Select first and second td

$(".location table tbody tr td:first-child").addClass("black");
$(".location table tbody tr td:nth-child(2)").addClass("black");

http://jsfiddle.net/68wbx/1/

.NET Excel Library that can read/write .xls files

I'd recommend NPOI. NPOI is FREE and works exclusively with .XLS files. It has helped me a lot.

Detail: you don't need to have Microsoft Office installed on your machine to work with .XLS files if you use NPOI.

Check these blog posts:

Creating Excel spreadsheets .XLS and .XLSX in C#

NPOI with Excel Table and dynamic Chart

[UPDATE]

NPOI 2.0 added support for XLSX and DOCX.

You can read more about it here:

NPOI 2.0 series of posts scheduled

Removing leading and trailing spaces from a string

string trim(const string & sStr)
{
    int nSize = sStr.size();
    int nSPos = 0, nEPos = 1, i;
    for(i = 0; i< nSize; ++i) {
        if( !isspace( sStr[i] ) ) {
            nSPos = i ;
            break;
        }
    }
    for(i = nSize -1 ; i >= 0 ; --i) {
        if( !isspace( sStr[i] ) ) {
            nEPos = i;
            break;
        }
    }
    return string(sStr, nSPos, nEPos - nSPos + 1);
}

Setting the focus to a text field

I have had a similar scenario where I needed to set the focus on a text box within a panel when the panel was shown. The panel was loaded on application startup, so I couldn't set the focus in the constructor. As the panel wasn't being loaded or being given focus on show, this meant that I had no event to fire the focus request from.

To solve this, I added a global method to my main that called a method in the panel that invoked requestFocusInWindow() on the text area. I put the call to the global method in the button that showed the panel, after the call to show. This meant that the panel would be shown and then the text area assigned the focus after showing the panel. Hope that makes sense and helps!

Also, you can edit most of the auto-generated code by right clicking on the object in design view and selecting customize code, however I don't think that it allows you to edit panels.

Comparing mongoose _id and strings

The accepted answers really limit what you can do with your code. For example, you would not be able to search an array of Object Ids by using the equals method. Instead, it would make more sense to always cast to string and compare the keys.

Here's an example answer in case if you need to use indexOf() to check within an array of references for a specific id. assume query is a query you are executing, assume someModel is a mongo model for the id you are looking for, and finally assume results.idList is the field you are looking for your object id in.

query.exec(function(err,results){
   var array = results.idList.map(function(v){ return v.toString(); });
   var exists = array.indexOf(someModel._id.toString()) >= 0;
   console.log(exists);
});

How should I do integer division in Perl?

Hope it works

int(9/4) = 2.

Thanks Manojkumar

Generate war file from tomcat webapp folder

You can create .war file back from your existing folder.

Using this command

cd /to/your/folder/location
jar -cvf my_web_app.war *

preg_match(); - Unknown modifier '+'

This happened to me because I put a variable in the regex and sometimes its string value included a slash. Solution: preg_quote.

Shall we always use [unowned self] inside closure in Swift

Update 11/2016

I wrote an article on this extending this answer (looking into SIL to understand what ARC does), check it out here.

Original answer

The previous answers don't really give straightforward rules on when to use one over the other and why, so let me add a few things.

The unowned or weak discussion boils down to a question of lifetime of the variable and the closure that references it.

swift weak vs unowned

Scenarios

You can have two possible scenarios:

  1. The closure have the same lifetime of the variable, so the closure will be reachable only until the variable is reachable. The variable and the closure have the same lifetime. In this case you should declare the reference as unowned. A common example is the [unowned self] used in many example of small closures that do something in the context of their parent and that not being referenced anywhere else do not outlive their parents.

  2. The closure lifetime is independent from the one of the variable, the closure could still be referenced when the variable is not reachable anymore. In this case you should declare the reference as weak and verify it's not nil before using it (don't force unwrap). A common example of this is the [weak delegate] you can see in some examples of closure referencing a completely unrelated (lifetime-wise) delegate object.

Actual Usage

So, which will/should you actually use most of the times?

Quoting Joe Groff from twitter:

Unowned is faster and allows for immutability and nonoptionality.

If you don't need weak, don't use it.

You'll find more about unowned* inner workings here.

* Usually also referred to as unowned(safe) to indicate that runtime checks (that lead to a crash for invalid references) are performed before accessing the unowned reference.

How can I increase a scrollbar's width using CSS?

Yes.

If the scrollbar is not the browser scrollbar, then it will be built of regular HTML elements (probably divs and spans) and can thus be styled (or will be Flash, Java, etc and can be customized as per those environments).

The specifics depend on the DOM structure used.

NULL values inside NOT IN clause

Query A is the same as:

select 'true' where 3 = 1 or 3 = 2 or 3 = 3 or 3 = null

Since 3 = 3 is true, you get a result.

Query B is the same as:

select 'true' where 3 <> 1 and 3 <> 2 and 3 <> null

When ansi_nulls is on, 3 <> null is UNKNOWN, so the predicate evaluates to UNKNOWN, and you don't get any rows.

When ansi_nulls is off, 3 <> null is true, so the predicate evaluates to true, and you get a row.

Where does the iPhone Simulator store its data?

Found it:

~/Library/Application Support/iPhone Simulator/User/

Configuring ObjectMapper in Spring

To configure a message converter in plain spring-web, in this case to enable the Java 8 JSR-310 JavaTimeModule, you first need to implement WebMvcConfigurer in your @Configuration class and then override the configureMessageConverters method:

@Override
public void configureMessageConverters(List<HttpMessageConverter<?>> converters) {
    ObjectMapper objectMapper = Jackson2ObjectMapperBuilder.json().modules(new JavaTimeModule(), new Jdk8Module()).build()
            .configure(SerializationFeature.WRITE_DATES_AS_TIMESTAMPS, false);
    converters.add(new MappingJackson2HttpMessageConverter(objectMapper));
}

Like this you can register any custom defined ObjectMapper in a Java-based Spring configuration.

Response::json() - Laravel 5.1

From a controller you can also return an Object/Array and it will be sent as a JSON response (including the correct HTTP headers).

public function show($id)
{
    return Customer::find($id);
}

Combine :after with :hover

in scss

&::after{
content: url(images/RelativeProjectsArr.png);
margin-left:30px;
}

&:hover{
    background-color:$turkiz;
    color:#e5e7ef;

    &::after{
    content: url(images/RelativeProjectsArrHover.png);
    }
}

How to make Java Set?

Like this:

import java.util.*;
Set<Integer> a = new HashSet<Integer>();
a.add( 1);
a.add( 2);
a.add( 3);

Or adding from an Array/ or multiple literals; wrap to a list, first.

Integer[] array = new Integer[]{ 1, 4, 5};
Set<Integer> b = new HashSet<Integer>();
b.addAll( Arrays.asList( b));         // from an array variable
b.addAll( Arrays.asList( 8, 9, 10));  // from literals

To get the intersection:

// copies all from A;  then removes those not in B.
Set<Integer> r = new HashSet( a);
r.retainAll( b);
// and print;   r.toString() implied.
System.out.println("A intersect B="+r);

Hope this answer helps. Vote for it!

What is the difference between float and double?

  • A double is 64 and single precision (float) is 32 bits.
  • The double has a bigger mantissa (the integer bits of the real number).
  • Any inaccuracies will be smaller in the double.

An error occurred while collecting items to be installed (Access is denied)

Installig Eclispe ADT from market place solved this problem for me.

Format date in a specific timezone

A couple of answers already mention that moment-timezone is the way to go with named timezone. I just want to clarify something about this library that was pretty confusing to me. There is a difference between these two statements:

moment.tz(date, format, timezone)

moment(date, format).tz(timezone)

Assuming that a timezone is not specified in the date passed in:

The first code takes in the date and assumes the timezone is the one passed in. The second one will take date, assume the timezone from the browser and then change the time and timezone according to the timezone passed in.

Example:

moment.tz('2018-07-17 19:00:00', 'YYYY-MM-DD HH:mm:ss', 'UTC').format() // "2018-07-17T19:00:00Z"

moment('2018-07-17 19:00:00', 'YYYY-MM-DD HH:mm:ss').tz('UTC').format() // "2018-07-18T00:00:00Z"

My timezone is +5 from utc. So in the first case it does not change and it sets the date and time to have utc timezone.

In the second case, it assumes the date passed in is in -5, then turns it into UTC, and that's why it spits out the date "2018-07-18T00:00:00Z"

NOTE: The format parameter is really important. If omitted moment might fall back to the Date class which can unpredictable behaviors


Assuming the timezone is specified in the date passed in:

In this case they both behave equally


Even though now I understand why it works that way, I thought this was a pretty confusing feature and worth explaining.

What is the fastest way to compare two sets in Java?

If you simply want to know if the sets are equal, the equals method on AbstractSet is implemented roughly as below:

    public boolean equals(Object o) {
        if (o == this)
            return true;
        if (!(o instanceof Set))
            return false;
        Collection c = (Collection) o;
        if (c.size() != size())
            return false;
        return containsAll(c);
    }

Note how it optimizes the common cases where:

  • the two objects are the same
  • the other object is not a set at all, and
  • the two sets' sizes are different.

After that, containsAll(...) will return false as soon as it finds an element in the other set that is not also in this set. But if all elements are present in both sets, it will need to test all of them.

The worst case performance therefore occurs when the two sets are equal but not the same objects. That cost is typically O(N) or O(NlogN) depending on the implementation of this.containsAll(c).

And you get close-to-worst case performance if the sets are large and only differ in a tiny percentage of the elements.


UPDATE

If you are willing to invest time in a custom set implementation, there is an approach that can improve the "almost the same" case.

The idea is that you need to pre-calculate and cache a hash for the entire set so that you could get the set's current hashcode value in O(1). Then you can compare the hashcode for the two sets as an acceleration.

How could you implement a hashcode like that? Well if the set hashcode was:

  • zero for an empty set, and
  • the XOR of all of the element hashcodes for a non-empty set,

then you could cheaply update the set's cached hashcode each time you added or removed an element. In both cases, you simply XOR the element's hashcode with the current set hashcode.

Of course, this assumes that element hashcodes are stable while the elements are members of sets. It also assumes that the element classes hashcode function gives a good spread. That is because when the two set hashcodes are the same you still have to fall back to the O(N) comparison of all elements.


You could take this idea a bit further ... at least in theory.

WARNING - This is highly speculative. A "thought experiment" if you like.

Suppose that your set element class has a method to return a crypto checksums for the element. Now implement the set's checksums by XORing the checksums returned for the elements.

What does this buy us?

Well, if we assume that nothing underhand is going on, the probability that any two unequal set elements have the same N-bit checksums is 2-N. And the probability 2 unequal sets have the same N-bit checksums is also 2-N. So my idea is that you can implement equals as:

    public boolean equals(Object o) {
        if (o == this)
            return true;
        if (!(o instanceof Set))
            return false;
        Collection c = (Collection) o;
        if (c.size() != size())
            return false;
        return checksums.equals(c.checksums);
    }

Under the assumptions above, this will only give you the wrong answer once in 2-N time. If you make N large enough (e.g. 512 bits) the probability of a wrong answer becomes negligible (e.g. roughly 10-150).

The downside is that computing the crypto checksums for elements is very expensive, especially as the number of bits increases. So you really need an effective mechanism for memoizing the checksums. And that could be problematic.

And the other downside is that a non-zero probability of error may be unacceptable no matter how small the probability is. (But if that is the case ... how do you deal with the case where a cosmic ray flips a critical bit? Or if it simultaneously flips the same bit in two instances of a redundant system?)

What's the difference between lists enclosed by square brackets and parentheses in Python?

Comma-separated items enclosed by ( and ) are tuples, those enclosed by [ and ] are lists.

How do I add options to a DropDownList using jQuery?

You may want to clear your DropDown first $('#DropDownQuality').empty();

I had my controller in MVC return a select list with only one item.

$('#DropDownQuality').append(
        $('<option></option>').val(data[0].Value).html(data[0].Text));    

How to remove word wrap from textarea?

This question seems to be the most popular one for disabling textarea wrap. However, as of April 2017 I find that IE 11 (11.0.9600) will not disable word wrap with any of the above solutions.

The only solution which does work for IE 11 is wrap="off". wrap="soft" and/or the various CSS attributes like white-space: pre alter where IE 11 chooses to wrap but it still wraps somewhere. Note that I have tested this with or without Compatibility View. IE 11 is pretty HTML 5 compatible, but not in this case.

Thus, to achieve lines which retain their whitespace and go off the right-hand side I am using:

<textarea style="white-space: pre; overflow: scroll;" wrap="off">

Fortuitously this does seem to work in Chrome & Firefox too. I am not defending the use of pre-HTML 5 wrap="off", just saying that it seems to be required for IE 11.

What is the theoretical maximum number of open TCP connections that a modern Linux box can have

If you are thinking of running a server and trying to decide how many connections can be served from one machine, you may want to read about the C10k problem and the potential problems involved in serving lots of clients simultaneously.

ORA-03113: end-of-file on communication channel after long inactivity in ASP.Net app

ORA-03113: end-of-file on communication channel

Is the database letting you know that the network connection is no more. This could be because:

  1. A network issue - faulty connection, or firewall issue
  2. The server process on the database that is servicing you died unexpectedly.

For 1) (firewall) search tahiti.oracle.com for SQLNET.EXPIRE_TIME. This is a sqlnet.ora parameter that will regularly send a network packet at a configurable interval ie: setting this will make the firewall believe that the connection is live.

For 1) (network) speak to your network admin (connection could be unreliable)

For 2) Check the alert.log for errors. If the server process failed there will be an error message. Also a trace file will have been written to enable support to identify the issue. The error message will reference the trace file.

Support issues can be raised at metalink.oracle.com with a suitable Customer Service Identifier (CSI)

Clicking at coordinates without identifying element

I used the Actions Class like many listed above, but what I found helpful was if I need find a relative position from the element I used Firefox Add-On Measurit to get the relative coordinates. For example:

        IWebDriver driver = new FirefoxDriver();
        driver.Url = @"https://scm.commerceinterface.com/accounts/login/?next=/remittance_center/";
        var target = driver.FindElement(By.Id("loginAsEU"));
        Actions builder = new Actions(driver);            
        builder.MoveToElement(target , -375  , -436).Click().Build().Perform();

I got the -375, -436 from clicking on an element and then dragging backwards until I reached the point I needed to click. The coordinates that MeasureIT said I just subtracted. In my example above, the only element I had on the page that was clickable was the "loginAsEu" link. So I started from there.

Breaking up long strings on multiple lines in Ruby without stripping newlines

You can use \ to indicate that any line of Ruby continues on the next line. This works with strings too:

string = "this is a \
string that spans lines"

puts string.inspect

will output "this is a string that spans lines"

Vertical dividers on horizontal UL menu

A simpler solution would be to just add #navigation ul li~li { border-left: 1px solid #857D7A; }

How do I get the path of the current executed file in Python?

I was running into a similar problem, and I think this might solve the problem:

def module_path(local_function):
   ''' returns the module path without the use of __file__.  Requires a function defined
   locally in the module.
   from http://stackoverflow.com/questions/729583/getting-file-path-of-imported-module'''
   return os.path.abspath(inspect.getsourcefile(local_function))

It works for regular scripts and in idle. All I can say is try it out for others!

My typical usage:

from toolbox import module_path
def main():
   pass # Do stuff

global __modpath__
__modpath__ = module_path(main)

Now I use __modpath__ instead of __file__.

How to change webservice url endpoint?

I wouldn't go so far as @Femi to change the existing address property. You can add new services to the definitions section easily.

<wsdl:service name="serviceMethodName_2">
  <wsdl:port binding="tns:serviceMethodNameSoapBinding" name="serviceMethodName">
    <soap:address location="http://new_end_point_adress"/>
  </wsdl:port>
</wsdl:service>

This doesn't require a recompile of the WSDL to Java and making updates isn't any more difficult than if you used the BindingProvider option (which didn't work for me btw).

Better way to generate array of all letters in the alphabet

Check this once I'm sure you will get a to z alphabets:

for (char c = 'a'; c <= 'z'; c++) {
    al.add(c);
}
System.out.println(al);'

What are Java command line options to set to allow JVM to be remotely debugged?

-agentlib:jdwp=transport=dt_socket,server=y,suspend=y,address=PORT_NUMBER

Here we just use a Socket Attaching Connector, which is enabled by default when the dt_socket transport is configured and the VM is running in the server debugging mode.

For more details u can refer to : https://stackify.com/java-remote-debugging/

mysql: see all open connections to a given database?

If you're running a *nix system, also consider mytop.

To limit the results to one database, press "d" when it's running then type in the database name.

Regex allow digits and a single dot

My try is combined solution.

string = string.replace(',', '.').replace(/[^\d\.]/g, "").replace(/\./, "x").replace(/\./g, "").replace(/x/, ".");
string = Math.round( parseFloat(string) * 100) / 100;

First line solution from here: regex replacing multiple periods in floating number . It replaces comma "," with dot "." ; Replaces first comma with x; Removes all dots and replaces x back to dot.

Second line cleans numbers after dot.

How to fix Subversion lock error

Go to the metadata directory as below

your workspace>projectname>.metadata

inside this metada directory, there will be a lock file. Delete this lock file.

Restart eclipse and rebuild project. It worked for me !

How do CSS triangles work?

If you want to play around with border-size, width and height and see how those can create different shapes, try this:

_x000D_
_x000D_
const sizes = [32, 32, 32, 32];_x000D_
const triangle = document.getElementById('triangle');_x000D_
_x000D_
function update({ target }) {_x000D_
  let index = null;_x000D_
  _x000D_
  if (target) {_x000D_
    index = parseInt(target.id);_x000D_
_x000D_
    if (!isNaN(index)) {_x000D_
      sizes[index] = target.value;_x000D_
    }_x000D_
  }_x000D_
  _x000D_
  window.requestAnimationFrame(() => {_x000D_
    triangle.style.borderWidth = sizes.map(size => `${ size }px`).join(' ');_x000D_
    _x000D_
    if (isNaN(index)) {_x000D_
      triangle.style[target.id] = `${ target.value }px`;_x000D_
    }_x000D_
  });_x000D_
}_x000D_
_x000D_
document.querySelectorAll('input').forEach(input => {_x000D_
  input.oninput = update;_x000D_
});_x000D_
_x000D_
update({});
_x000D_
body {_x000D_
  margin: 0;_x000D_
  min-height: 100vh;_x000D_
  display: flex;_x000D_
  justify-content: center;_x000D_
  align-items: center;_x000D_
  overflow: hidden;_x000D_
}_x000D_
_x000D_
#triangle {_x000D_
    border-style: solid;_x000D_
    border-color: yellow magenta blue black;_x000D_
    background: cyan;_x000D_
    height: 0px;_x000D_
    width: 0px;_x000D_
}_x000D_
_x000D_
#controls {_x000D_
  position: fixed;_x000D_
  bottom: 0;_x000D_
  left: 0;_x000D_
  right: 0;_x000D_
  background: white;_x000D_
  display: flex;_x000D_
  box-shadow: 0 0 32px rgba(0, 0, 0, .125);_x000D_
}_x000D_
_x000D_
#controls > div {_x000D_
  position: relative;_x000D_
  width: 25%;_x000D_
  padding: 8px;_x000D_
  box-sizing: border-box;_x000D_
  display: flex;_x000D_
}_x000D_
_x000D_
input {_x000D_
  margin: 0;_x000D_
  width: 100%;_x000D_
  position: relative;_x000D_
}
_x000D_
<div id="triangle" style="border-width: 32px 32px 32px 32px;"></div>_x000D_
_x000D_
<div id="controls">_x000D_
  <div><input type="range" min="0" max="128" value="32" id="0" /></div>_x000D_
  <div><input type="range" min="0" max="128" value="32" id="1" /></div>_x000D_
  <div><input type="range" min="0" max="128" value="32" id="2" /></div>_x000D_
  <div><input type="range" min="0" max="128" value="32" id="3" /></div>_x000D_
  <div><input type="range" min="0" max="128" value="0" id="width" /></div>_x000D_
  <div><input type="range" min="0" max="128" value="0" id="height" /></div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

How can I explicitly free memory in Python?

Unfortunately (depending on your version and release of Python) some types of objects use "free lists" which are a neat local optimization but may cause memory fragmentation, specifically by making more and more memory "earmarked" for only objects of a certain type and thereby unavailable to the "general fund".

The only really reliable way to ensure that a large but temporary use of memory DOES return all resources to the system when it's done, is to have that use happen in a subprocess, which does the memory-hungry work then terminates. Under such conditions, the operating system WILL do its job, and gladly recycle all the resources the subprocess may have gobbled up. Fortunately, the multiprocessing module makes this kind of operation (which used to be rather a pain) not too bad in modern versions of Python.

In your use case, it seems that the best way for the subprocesses to accumulate some results and yet ensure those results are available to the main process is to use semi-temporary files (by semi-temporary I mean, NOT the kind of files that automatically go away when closed, just ordinary files that you explicitly delete when you're all done with them).

Check whether a string contains a substring

Case Insensitive Substring Example

This is an extension of Eugene's answer, which converts the strings to lower case before checking for the substring:

if (index(lc($str), lc($substr)) != -1) {
    print "$str contains $substr\n";
} 

How to send emails from my Android application?

simple try this one

 public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);

    buttonSend = (Button) findViewById(R.id.buttonSend);
    textTo = (EditText) findViewById(R.id.editTextTo);
    textSubject = (EditText) findViewById(R.id.editTextSubject);
    textMessage = (EditText) findViewById(R.id.editTextMessage);

    buttonSend.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

            String to = textTo.getText().toString();
            String subject = textSubject.getText().toString();
            String message = textMessage.getText().toString();

            Intent email = new Intent(Intent.ACTION_SEND);
            email.putExtra(Intent.EXTRA_EMAIL, new String[] { to });
            // email.putExtra(Intent.EXTRA_CC, new String[]{ to});
            // email.putExtra(Intent.EXTRA_BCC, new String[]{to});
            email.putExtra(Intent.EXTRA_SUBJECT, subject);
            email.putExtra(Intent.EXTRA_TEXT, message);

            // need this to prompts email client only
            email.setType("message/rfc822");

            startActivity(Intent.createChooser(email, "Choose an Email client :"));

        }
    });
}

How do I authenticate a WebClient request?

You need to give the WebClient object the credentials. Something like this...

 WebClient client = new WebClient();
 client.Credentials = new NetworkCredential("username", "password");

Adding horizontal spacing between divs in Bootstrap 3

Do you mean something like this? JSFiddle

Attribute used:

margin-left: 50px;

How do I create 7-Zip archives with .NET?

EggCafe 7Zip cookie example This is an example (zipping cookie) with the DLL of 7Zip.

CodePlex Wrapper This is an open source project that warp zipping function of 7z.

7Zip SDK The official SDK for 7zip (C, C++, C#, Java) <---My suggestion

.Net zip library by SharpDevelop.net

CodeProject example with 7zip

SharpZipLib Many zipping

Get each line from textarea

Use PHP DOM to parse and add <br/> in it. Like this:

$html = '<textarea> put returns between paragraphs
for linebreak add 2 spaces at end
indent code by 4 spaces
quote by placing > at start of line
</textarea>';

//parsing begins here:
$doc = new DOMDocument();
@$doc->loadHTML($html);
$nodes = $doc->getElementsByTagName('textarea');

//get text and add <br/> then remove last <br/>
$lines = $nodes->item(0)->nodeValue;

//split it by newlines
$lines = explode("\n", $lines);

//add <br/> at end of each line
foreach($lines as $line)
    $output .= $line . "<br/>";

//remove last <br/>
$output = rtrim($output, "<br/>");

//display it
var_dump($output);

This outputs:

string ' put returns between paragraphs
<br/>for linebreak add 2 spaces at end
<br/>indent code by 4 spaces
<br/>quote by placing > at start of line
' (length=141)

Does React Native styles support gradients?

Not at the moment. You should use the library you linked; they recently added Android support and it is by one of the main contributors of react-native.

how to change text in Android TextView

I just posted this answer in the android-discuss google group

If you are just trying to add text to the view so that it displays "Step One: blast egg Step Two: fry egg" Then consider using t.appendText("Step Two: fry egg"); instead of t.setText("Step Two: fry egg");

If you want to completely change what is in the TextView so that it says "Step One: blast egg" on startup and then it says "Step Two: fry egg" at a time later you can always use a

Runnable example sadboy gave

Good luck

Is it possible only to declare a variable without assigning any value in Python?

You look like you're trying to write C in Python. If you want to find something in a sequence, Python has builtin functions to do that, like

value = sequence.index(blarg)

JavaScript, Node.js: is Array.forEach asynchronous?

No, it is blocking. Have a look at the specification of the algorithm.

However a maybe easier to understand implementation is given on MDN:

if (!Array.prototype.forEach)
{
  Array.prototype.forEach = function(fun /*, thisp */)
  {
    "use strict";

    if (this === void 0 || this === null)
      throw new TypeError();

    var t = Object(this);
    var len = t.length >>> 0;
    if (typeof fun !== "function")
      throw new TypeError();

    var thisp = arguments[1];
    for (var i = 0; i < len; i++)
    {
      if (i in t)
        fun.call(thisp, t[i], i, t);
    }
  };
}

If you have to execute a lot of code for each element, you should consider to use a different approach:

function processArray(items, process) {
    var todo = items.concat();

    setTimeout(function() {
        process(todo.shift());
        if(todo.length > 0) {
            setTimeout(arguments.callee, 25);
        }
    }, 25);
}

and then call it with:

processArray([many many elements], function () {lots of work to do});

This would be non-blocking then. The example is taken from High Performance JavaScript.

Another option might be web workers.

How to get current date in jquery?

//convert month to 2 digits<p>
var twoDigitMonth = ((fullDate.getMonth().length+1) === 1)? (fullDate.getMonth()+1) : '0' + (fullDate.getMonth()+1);

var currentDate =  fullDate.getFullYear()+ "/" + twoDigitMonth + "/" + fullDate.getDate();
console.log(currentDate);<br>
//2011/05/19

What is a serialVersionUID and why should I use it?

To understand the significance of field serialVersionUID, one should understand how Serialization/Deserialization works.

When a Serializable class object is serialized Java Runtime associates a serial version no.(called as serialVersionUID) with this serialized object. At the time when you deserialize this serialized object Java Runtime matches the serialVersionUID of serialized object with the serialVersionUID of the class. If both are equal then only it proceeds with the further process of deserialization else throws InvalidClassException.

So we conclude that to make Serialization/Deserialization process successful the serialVersionUID of serialized object must be equivalent to the serialVersionUID of the class. In case if programmer specifies the serialVersionUID value explicitly in the program then the same value will be associated with the serialized object and the class, irrespective of the serialization and deserialzation platform(for ex. serialization might be done on platform like windows by using sun or MS JVM and Deserialization might be on different platform Linux using Zing JVM).

But in case if serialVersionUID is not specified by programmer then while doing Serialization\DeSerialization of any object, Java runtime uses its own algorithm to calculate it. This serialVersionUID calculation algorithm varies from one JRE to another. It is also possible that the environment where the object is serialized is using one JRE (ex: SUN JVM) and the environment where deserialzation happens is using Linux Jvm(zing). In such cases serialVersionUID associated with serialized object will be different than the serialVersionUID of class calculated at deserialzation environment. In turn deserialization will not be successful. So to avoid such situations/issues programmer must always specify serialVersionUID of Serializable class.

Git's famous "ERROR: Permission to .git denied to user"

In step 18, I assume you mean ssh-add ~/.ssh/id_rsa? If so, that explains this:

I also suspect some local ssh caching weirdness because if i mv ~/.ssh/id_rsa KAKA and mv ~/.ssh/id_rsa.pub POOPOO, and do ssh [email protected] -v, it still Authenticates me and says it serves my /home/meder/.ssh/id_rsa when I renamed it?! It has to be cached?!

... since the ssh-agent is caching your key.

If you look on GitHub, there is a mederot account. Are you sure that this is nothing to do with you? GitHub shouldn't allow the same SSH public key to be added to two accounts, since when you are using the [email protected]:... URLs it's identifying the user based on the SSH key. (That this shouldn't be allowed is confirmed here.)

So, I suspect (in decreasing order of likelihood) that one of the following is the case:

  1. You created the mederot account previously and added your SSH key to it.
  2. Someone else has obtained a copy of your public key and added it to the mederot GitHub account.
  3. There's a horrible bug in GitHub.

If 1 isn't the case then I would report this to GitHub, so they can check about 2 or 3.

More :

ssh-add -l check if there is more than one identify exists if yes, remove it by ssh-add -d "that key file"

React component initialize state from props

You don't need to call setState in a Component's constructor - it's idiomatic to set this.state directly:

class FirstComponent extends React.Component {

  constructor(props) {
    super(props);

    this.state = {
      x: props.initialX
    };
  }
  // ...
}

See React docs - Adding Local State to a Class.

There is no advantage to the first method you describe. It will result in a second update immediately before mounting the component for the first time.

Rails Object to hash

Swanand's answer is great.

if you are using FactoryGirl, you can use its build method to generate the attribute hash without the key id. e.g.

build(:post).attributes

jQuery: get data attribute

Change IDs and data attributes as you wish!

  <select id="selectVehicle">
       <option value="1" data-year="2011">Mazda</option>
       <option value="2" data-year="2015">Honda</option>
       <option value="3" data-year="2008">Mercedes</option>
       <option value="4" data-year="2005">Toyota</option>
  </select>

$("#selectVehicle").change(function () {
     alert($(this).find(':selected').data("year"));
});

Here is the working example: https://jsfiddle.net/ed5axgvk/1/

'Framework not found' in Xcode

Besides from removing the framework from the Podfile and Linked Frameworks and Libraries, I also had to remove the reference to the framework in Other Linker Flags.

How to get pip to work behind a proxy server

On Ubuntu, you can set proxy by using

export http_proxy=http://username:password@proxy:port
export https_proxy=http://username:password@proxy:port

or if you are having SOCKS error use

export all_proxy=http://username:password@proxy:port

Then run pip

sudo -E pip3 install {packageName}

Warning: mysqli_connect(): (HY000/1045): Access denied for user 'username'@'localhost' (using password: YES)

The same issue faced me with XAMPP 7 and opencart Arabic 3. Replacing localhost by the actual machine name reslove the issue.

how to change background image of button when clicked/focused?

You just need to set background and give previous.xml file in background of button in your layout file.

<Button
 android:id="@+id/button1"
 android:background="@drawable/previous"
 android:layout_width="200dp"
 android:layout_height="126dp"
 android:text="Hello" />

and done.Edit Following is previous.xml file in drawable directory

<?xml version="1.0" encoding="utf-8"?>

<item android:drawable="@drawable/onclick" android:state_selected="true"></item>
<item android:drawable="@drawable/onclick" android:state_pressed="true"></item>
<item android:drawable="@drawable/normal"></item>

POST: sending a post request in a url itself

It is not possible to send POST parameters in the url in a starightforward manner. POST request in itself means sending information in the body.

I found a fairly simple way to do this. Use Postman by Google, which allows you to specify the content-type(a header field) as application/json and then provide name-value pairs as parameters.

You can find clear directions at [2020-09-04: broken link - see comment] http://docs.brightcove.com/en/video-cloud/player-management/guides/postman.html

Just use your url in the place of theirs.

Hope it helps

How to call a function after delay in Kotlin?

If you are in a fragment with viewModel scope you can use Kotlin coroutines:

    myViewModel.viewModelScope.launch {
        delay(2000)
        // DoSomething()
    }

Ruby send JSON request

real life example, notify Airbrake API about new deployment via NetHttps

require 'uri'
require 'net/https'
require 'json'

class MakeHttpsRequest
  def call(url, hash_json)
    uri = URI.parse(url)
    req = Net::HTTP::Post.new(uri.to_s)
    req.body = hash_json.to_json
    req['Content-Type'] = 'application/json'
    # ... set more request headers 

    response = https(uri).request(req)

    response.body
  end

  private

  def https(uri)
    Net::HTTP.new(uri.host, uri.port).tap do |http|
      http.use_ssl = true
      http.verify_mode = OpenSSL::SSL::VERIFY_NONE
    end
  end
end

project_id = 'yyyyyy'
project_key = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxxxxxx'
url = "https://airbrake.io/api/v4/projects/#{project_id}/deploys?key=#{project_key}"
body_hash = {
  "environment":"production",
  "username":"tomas",
  "repository":"https://github.com/equivalent/scrapbook2",
  "revision":"live-20160905_0001",
  "version":"v2.0"
}

puts MakeHttpsRequest.new.call(url, body_hash)

Notes:

in case you doing authentication via Authorisation header set header req['Authorization'] = "Token xxxxxxxxxxxx" or http://api.rubyonrails.org/classes/ActionController/HttpAuthentication/Token.html

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.

AngularJs - ng-model in a SELECT

You can also put the item with the default value selected out of the ng-repeat like follow :

<div ng-app="app" ng-controller="myCtrl">
    <select class="form-control" ng-change="unitChanged()" ng-model="data.unit">
        <option value="yourDefaultValue">Default one</option>
        <option ng-selected="data.unit == item.id" ng-repeat="item in units" ng-value="item.id">{{item.label}}</option>
    </select>
</div>

and don't forget the value atribute if you leave it blank you will have the same issue.

PHP - iterate on string characters

// Unicode Codepoint Escape Syntax in PHP 7.0
$str = "cat!\u{1F431}";

// IIFE (Immediately Invoked Function Expression) in PHP 7.0
$gen = (function(string $str) {
    for ($i = 0, $len = mb_strlen($str); $i < $len; ++$i) {
        yield mb_substr($str, $i, 1);
    }
})($str);

var_dump(
    true === $gen instanceof Traversable,
    // PHP 7.1
    true === is_iterable($gen)
);

foreach ($gen as $char) {
    echo $char, PHP_EOL;
}

Send mail via CMD console

A couple more command-line mailer programs:

Both support SSL too.

unexpected T_ENCAPSED_AND_WHITESPACE, expecting T_STRING or T_VARIABLE or T_NUM_STRING error

In my case, heredoc caused the issue. There is no problem with PHP version 7.3 up. Howerver, it error with PHP 7.0.33 if you use heredoc with space.

My example code

$rexpenditure = <<<Expenditure
                  <tr>
                      <td>$row->payment_referencenumber</td>
                      <td>$row->payment_requestdate</td>
                      <td>$row->payment_description</td>
                      <td>$row->payment_fundingsource</td>
                      <td>$row->payment_agencyulo</td>
                      <td>$row->payment_agencyproject</td>
                      <td>$$row->payment_disbustment</td>
                      <td>$row->payment_payeename</td>
                      <td>$row->payment_processpayment</td>
                  </tr>
Expenditure;

It will error if there is a space on PHP 7.0.33.

JS search in object values

MAKE SIMPLE

const objects = [
     {
     "foo" : "bar",
     "bar" : "sit",
     "date":"2020-12-20"
     },
     {
     "foo" : "lorem",
     "bar" : "ipsum",
     "date":"2018-07-02"
     },
     {
     "foo" : "dolor",
     "bar" : "amet",
     "date":"2003-10-08"
     },
     {
     "foo" : "lolor",
     "bar" : "amet",
     "date":"2003-10-08"
     }
     ];
     
     
     
     const filter = objects.filter(item => {
     const obj = Object.values(item)
     return obj.join("").indexOf('2003') !== -1
     })
     
     console.log(filter)

Error 330 (net::ERR_CONTENT_DECODING_FAILED):

It happens when your HTTP request's headers claim that the content is gzip encoded, but it isn't. Turn off gzip encoding setting or make sure the content is in fact encoded.

Renaming columns in Pandas

It is real simple. Just use:

df.columns = ['Name1', 'Name2', 'Name3'...]

And it will assign the column names by the order you put them in.

m2eclipse not finding maven dependencies, artifacts not found

It sounds like your m2eclipse install is using the embedded Maven, which has its own repository (located under user home) and settings.

If you open up the Maven preferences (Window->Preferences->Maven->Installations, you can add your Maven installation by selecting Add... then browsing to the M2_HOME directory.

Preferences screenshot
(source: sonatype.com)

For more details see the m2eclipse book

PHP get domain name

Similar question has been asked in stackoverflow before.

See here: PHP $_SERVER['HTTP_HOST'] vs. $_SERVER['SERVER_NAME'], am I understanding the man pages correctly?

Also see this article: http://shiflett.org/blog/2006/mar/server-name-versus-http-host

Recommended using HTTP_HOST, and falling back on SERVER_NAME only if HTTP_HOST was not set. He said that SERVER_NAME could be unreliable on the server for a variety of reasons, including:

  • no DNS support
  • misconfigured
  • behind load balancing software

Source: http://discussion.dreamhost.com/thread-4388.html

Module 'tensorflow' has no attribute 'contrib'

I used tensorflow 1.8 to train my model and there is no problem for now. Tensorflow 2.0 alpha is not suitable with object detection API

cURL error 60: SSL certificate: unable to get local issuer certificate

Have you tried..

curl_setopt($process, CURLOPT_SSL_VERIFYPEER, false);

If you are consuming a trusted source you can skip the verify.

How to set Java SDK path in AndroidStudio?

Go to File> Project Structure (or press Ctrl+Alt+Shift+S), A popup will open now go to SDK Location Tab you will find JDK Location there refer this image to be more clear. enter image description here

how do you insert null values into sql server

INSERT INTO atable (x,y,z) VALUES ( NULL,NULL,NULL)

How do I count the number of rows and columns in a file using bash?

Following code will do the job and will allow you to specify field delimiter. This is especially useful for files containing more than 20k lines.

awk 'BEGIN { 
  FS="|"; 
  min=10000; 
}
{ 
  if( NF > max ) max = NF; 
  if( NF < min ) min = NF;
} 
END { 
  print "Max=" max; 
  print "Min=" min; 
} ' myPipeDelimitedFile.dat

Check if ADODB connection is open

This is an old topic, but in case anyone else is still looking...

I was having trouble after an undock event. An open db connection saved in a global object would error, even after reconnecting to the network. This was due to the TCP connection being forcibly terminated by remote host. (Error -2147467259: TCP Provider: An existing connection was forcibly closed by the remote host.)

However, the error would only show up after the first transaction was attempted. Up to that point, neither Connection.State nor Connection.Version (per solutions above) would reveal any error.

So I wrote the small sub below to force the error - hope it's useful.

Performance testing on my setup (Access 2016, SQL Svr 2008R2) was approx 0.5ms per call.

Function adoIsConnected(adoCn As ADODB.Connection) As Boolean

    '----------------------------------------------------------------
    '#PURPOSE: Checks whether the supplied db connection is alive and
    '          hasn't had it's TCP connection forcibly closed by remote
    '          host, for example, as happens during an undock event
    '#RETURNS: True if the supplied db is connected and error-free, 
    '          False otherwise
    '#AUTHOR:  Belladonna
    '----------------------------------------------------------------

    Dim i As Long
    Dim cmd As New ADODB.Command

    'Set up SQL command to return 1
    cmd.CommandText = "SELECT 1"
    cmd.ActiveConnection = adoCn

    'Run a simple query, to test the connection
    On Error Resume Next
    i = cmd.Execute.Fields(0)
    On Error GoTo 0

    'Tidy up
    Set cmd = Nothing

    'If i is 1, connection is open
    If i = 1 Then
        adoIsConnected = True
    Else
        adoIsConnected = False
    End If

End Function

How can I edit a .jar file?

Here's what I did:

  • Extracted the files using WinRAR
  • Made my changes to the extracted files
  • Opened the original JAR file with WinRAR
  • Used the ADD button to replace the files that I modified

That's it. I have tested it with my Nokia and it's working for me.

What is the difference between 'my' and 'our' in Perl?

Let us think what an interpreter actually is: it's a piece of code that stores values in memory and lets the instructions in a program that it interprets access those values by their names, which are specified inside these instructions. So, the big job of an interpreter is to shape the rules of how we should use the names in those instructions to access the values that the interpreter stores.

On encountering "my", the interpreter creates a lexical variable: a named value that the interpreter can access only while it executes a block, and only from within that syntactic block. On encountering "our", the interpreter makes a lexical alias of a package variable: it binds a name, which the interpreter is supposed from then on to process as a lexical variable's name, until the block is finished, to the value of the package variable with the same name.

The effect is that you can then pretend that you're using a lexical variable and bypass the rules of 'use strict' on full qualification of package variables. Since the interpreter automatically creates package variables when they are first used, the side effect of using "our" may also be that the interpreter creates a package variable as well. In this case, two things are created: a package variable, which the interpreter can access from everywhere, provided it's properly designated as requested by 'use strict' (prepended with the name of its package and two colons), and its lexical alias.

Sources:

Find maximum value of a column and return the corresponding row values using Pandas

In order to print the Country and Place with maximum value, use the following line of code.

print(df[['Country', 'Place']][df.Value == df.Value.max()])

How is Docker different from a virtual machine?

In my opinion it depends, it can be seen from the needs of your application, why decide to deploy to Docker because Docker breaks the application into small parts according to its function, this becomes effective because when one application / function is an error it has no effect on other applications , in contrast to using full vm, it will be slower and more complex in configuration, but in some ways safer than docker

EL access a map value by Integer key

Initial answer (EL 2.1, May 2009)

As mentioned in this java forum thread:

Basically autoboxing puts an Integer object into the Map. ie:

map.put(new Integer(0), "myValue")

EL (Expressions Languages) evaluates 0 as a Long and thus goes looking for a Long as the key in the map. ie it evaluates:

map.get(new Long(0))

As a Long is never equal to an Integer object, it does not find the entry in the map.
That's it in a nutshell.


Update since May 2009 (EL 2.2)

Dec 2009 saw the introduction of EL 2.2 with JSP 2.2 / Java EE 6, with a few differences compared to EL 2.1.
It seems ("EL Expression parsing integer as long") that:

you can call the method intValue on the Long object self inside EL 2.2:

<c:out value="${map[(1).intValue()]}"/>

That could be a good workaround here (also mentioned below in Tobias Liefke's answer)


Original answer:

EL uses the following wrappers:

Terms                  Description               Type
null                   null value.               -
123                    int value.                java.lang.Long
123.00                 real value.               java.lang.Double
"string" ou 'string'   string.                   java.lang.String
true or false          boolean.                  java.lang.Boolean

JSP page demonstrating this:

 <%@ taglib prefix="c" uri="http://java.sun.com/jsp/jstl/core"%>

 <%@ page import="java.util.*" %>

 <h2> Server Info</h2>
Server info = <%= application.getServerInfo() %> <br>
Servlet engine version = <%=  application.getMajorVersion() %>.<%= application.getMinorVersion() %><br>
Java version = <%= System.getProperty("java.vm.version") %><br>
<%
  Map map = new LinkedHashMap();
  map.put("2", "String(2)");
  map.put(new Integer(2), "Integer(2)");
  map.put(new Long(2), "Long(2)");
  map.put(42, "AutoBoxedNumber");

  pageContext.setAttribute("myMap", map);  
  Integer lifeInteger = new Integer(42);
  Long lifeLong = new Long(42);  
%>
  <h3>Looking up map in JSTL - integer vs long </h3>

  This page demonstrates how JSTL maps interact with different types used for keys in a map.
  Specifically the issue relates to autoboxing by java using map.put(1, "MyValue") and attempting to display it as ${myMap[1]}
  The map "myMap" consists of four entries with different keys: A String, an Integer, a Long and an entry put there by AutoBoxing Java 5 feature.       

  <table border="1">
    <tr><th>Key</th><th>value</th><th>Key Class</th></tr>
    <c:forEach var="entry" items="${myMap}" varStatus="status">
    <tr>      
      <td>${entry.key}</td>
      <td>${entry.value}</td>
      <td>${entry.key.class}</td>
    </tr>
    </c:forEach>
</table>

    <h4> Accessing the map</h4>    
    Evaluating: ${"${myMap['2']}"} = <c:out value="${myMap['2']}"/><br>
    Evaluating: ${"${myMap[2]}"}   = <c:out value="${myMap[2]}"/><br>    
    Evaluating: ${"${myMap[42]}"}   = <c:out value="${myMap[42]}"/><br>    

    <p>
    As you can see, the EL Expression for the literal number retrieves the value against the java.lang.Long entry in the map.
    Attempting to access the entry created by autoboxing fails because a Long is never equal to an Integer
    <p>

    lifeInteger = <%= lifeInteger %><br/>
    lifeLong = <%= lifeLong %><br/>
    lifeInteger.equals(lifeLong) : <%= lifeInteger.equals(lifeLong) %> <br>

How to use terminal commands with Github?

git add myfile.h
git commit -m "your commit message"
git push -u origin master

if you don't remember all the files you need to update, use

git status

org.hibernate.NonUniqueResultException: query did not return a unique result: 2?

It means that the query you wrote returns more than one element(result) while your code expects a single result.

Why does printf not flush after the call unless a newline is in the format string?

stdout is buffered, so will only output after a newline is printed.

To get immediate output, either:

  1. Print to stderr.
  2. Make stdout unbuffered.

Importing variables from another file?

Marc response is correct. Actually, you can print the memory address for the variables print(hex(id(libvar)) and you can see the addresses are different.

# mylib.py
libvar = None
def lib_method():
    global libvar
    print(hex(id(libvar)))

# myapp.py
from mylib import libvar, lib_method
import mylib

lib_method()
print(hex(id(libvar)))
print(hex(id(mylib.libvar)))

Single quotes vs. double quotes in Python

I use double quotes because I have been doing so for years in most languages (C++, Java, VB…) except Bash, because I also use double quotes in normal text and because I'm using a (modified) non-English keyboard where both characters require the shift key.

How to convert milliseconds into human readable form?

Here is more precise method in JAVA , I have implemented this simple logic , hope this will help you:

    public String getDuration(String _currentTimemilliSecond)
    {
        long _currentTimeMiles = 1;         
        int x = 0;
        int seconds = 0;
        int minutes = 0;
        int hours = 0;
        int days = 0;
        int month = 0;
        int year = 0;

        try 
        {
            _currentTimeMiles = Long.parseLong(_currentTimemilliSecond);
            /**  x in seconds **/   
            x = (int) (_currentTimeMiles / 1000) ; 
            seconds = x ;

            if(seconds >59)
            {
                minutes = seconds/60 ;

                if(minutes > 59)
                {
                    hours = minutes/60;

                    if(hours > 23)
                    {
                        days = hours/24 ;

                        if(days > 30)
                        {
                            month = days/30;

                            if(month > 11)
                            {
                                year = month/12;

                                Log.d("Year", year);
                                Log.d("Month", month%12);
                                Log.d("Days", days % 30);
                                Log.d("hours ", hours % 24);
                                Log.d("Minutes ", minutes % 60);
                                Log.d("Seconds  ", seconds % 60);   

                                return "Year "+year + " Month "+month%12 +" Days " +days%30 +" hours "+hours%24 +" Minutes "+minutes %60+" Seconds "+seconds%60;
                            }
                            else
                            {
                                Log.d("Month", month);
                                Log.d("Days", days % 30);
                                Log.d("hours ", hours % 24);
                                Log.d("Minutes ", minutes % 60);
                                Log.d("Seconds  ", seconds % 60);   

                                return "Month "+month +" Days " +days%30 +" hours "+hours%24 +" Minutes "+minutes %60+" Seconds "+seconds%60;
                            }

                        }
                        else
                        {
                            Log.d("Days", days );
                            Log.d("hours ", hours % 24);
                            Log.d("Minutes ", minutes % 60);
                            Log.d("Seconds  ", seconds % 60);   

                            return "Days " +days +" hours "+hours%24 +" Minutes "+minutes %60+" Seconds "+seconds%60;
                        }

                    }
                    else
                    {
                        Log.d("hours ", hours);
                        Log.d("Minutes ", minutes % 60);
                        Log.d("Seconds  ", seconds % 60);

                        return "hours "+hours+" Minutes "+minutes %60+" Seconds "+seconds%60;
                    }
                }
                else
                {
                    Log.d("Minutes ", minutes);
                    Log.d("Seconds  ", seconds % 60);

                    return "Minutes "+minutes +" Seconds "+seconds%60;
                }
            }
            else
            {
                Log.d("Seconds ", x);
                return " Seconds "+seconds;
            }
        }
        catch (Exception e) 
        {
            Log.e(getClass().getName().toString(), e.toString());
        }
        return "";
    }

    private Class Log
    {
        public static void d(String tag , int value)
        {
            System.out.println("##### [ Debug ]  ## "+tag +" :: "+value);
        }
    }

How to store custom objects in NSUserDefaults

On your Player class, implement the following two methods (substituting calls to encodeObject with something relevant to your own object):

- (void)encodeWithCoder:(NSCoder *)encoder {
    //Encode properties, other class variables, etc
    [encoder encodeObject:self.question forKey:@"question"];
    [encoder encodeObject:self.categoryName forKey:@"category"];
    [encoder encodeObject:self.subCategoryName forKey:@"subcategory"];
}

- (id)initWithCoder:(NSCoder *)decoder {
    if((self = [super init])) {
        //decode properties, other class vars
        self.question = [decoder decodeObjectForKey:@"question"];
        self.categoryName = [decoder decodeObjectForKey:@"category"];
        self.subCategoryName = [decoder decodeObjectForKey:@"subcategory"];
    }
    return self;
}

Reading and writing from NSUserDefaults:

- (void)saveCustomObject:(MyObject *)object key:(NSString *)key {
    NSData *encodedObject = [NSKeyedArchiver archivedDataWithRootObject:object];
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    [defaults setObject:encodedObject forKey:key];
    [defaults synchronize];

}

- (MyObject *)loadCustomObjectWithKey:(NSString *)key {
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    NSData *encodedObject = [defaults objectForKey:key];
    MyObject *object = [NSKeyedUnarchiver unarchiveObjectWithData:encodedObject];
    return object;
}

Code shamelessly borrowed from: saving class in nsuserdefaults

How do you open an SDF file (SQL Server Compact Edition)?

Download and install LINQPad, it works for SQL Server, MySQL, SQLite and also SDF (SQL CE 4.0).

Steps for open SDF Files:

  1. Click Add Connection

  2. Select Build data context automatically and Default (LINQ to SQL), then Next.

  3. Under Provider choose SQL CE 4.0.

  4. Under Database with Attach database file selected, choose Browse to select your .sdf file.

  5. Click OK.

Updating the list view when the adapter data changes

invalidate(); calls the list view to invalidate itself (ie. background color)
invalidateViews(); calls all of its children to be invalidated. allowing you to update the children views

I assume its some type of efficiency thing preventing all of the items to constantly have to be redraw if not necessary.

AttributeError: 'dict' object has no attribute 'predictors'

#Try without dot notation
sample_dict = {'name': 'John', 'age': 29}
print(sample_dict['name']) # John
print(sample_dict['age']) # 29

Svn switch from trunk to branch

  • Short version of (correct) tzaman answer will be (for fresh SVN)

    svn switch ^/branches/v1p2p3
    
  • --relocate switch is deprecated anyway, when it needed you'll have to use svn relocate command

  • Instead of creating snapshot-branch (ReadOnly) you can use tags (conventional RO labels for history)

On Windows, the caret character (^) must be escaped:

svn switch ^^/branches/v1p2p3

How to store .pdf files into MySQL as BLOBs using PHP?

EDITED TO ADD: The following code is outdated and won't work in PHP 7. See the note towards the bottom of the answer for more details.


Assuming a table structure of an integer ID and a blob DATA column, and assuming MySQL functions are being used to interface with the database, you could probably do something like this:

$result = mysql_query 'INSERT INTO table (
    data
) VALUES (
    \'' . mysql_real_escape_string (file_get_contents ('/path/to/the/file/to/store.pdf')) . '\'
);';

A word of warning though, storing blobs in databases is generally not considered to be the best idea as it can cause table bloat and has a number of other problems associated with it. A better approach would be to move the file somewhere in the filesystem where it can be retrieved, and store the path to the file in the database instead of the file itself.

Also, using mysql_* function calls is discouraged as those methods are effectively deprecated and aren't really built with versions of MySQL newer than 4.x in mind. You should switch to mysqli or PDO instead.

UPDATE: mysql_* functions are deprecated in PHP 5.x and are REMOVED COMPLETELY IN PHP 7! You now have no choice but to switch to a more modern Database Abstraction (MySQLI, PDO). I've decided to leave the original answer above intact for historical reasons but don't actually use it

Here's how to do it with mysqli in procedural mode:

$result = mysqli_query ($db, 'INSERT INTO table (
    data
) VALUES (
    \'' . mysqli_real_escape_string (file_get_contents ('/path/to/the/file/to/store.pdf'), $db) . '\'
);');

The ideal way of doing it is with MySQLI/PDO prepared statements.

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

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

import java.lang.reflect.Field;

public class Outer {
    public class Inner {
    }

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

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

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

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

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

How to create empty constructor for data class in Kotlin Android

Along with @miensol answer, let me add some details:

If you want a Java-visible empty constructor using data classes, you need to define it explicitely.

Using default values + constructor specifier is quite easy:

data class Activity(
    var updated_on: String = "",
    var tags: List<String> = emptyList(),
    var description: String = "",
    var user_id: List<Int> = emptyList(),
    var status_id: Int = -1,
    var title: String = "",
    var created_at: String = "",
    var data: HashMap<*, *> = hashMapOf<Any, Any>(),
    var id: Int = -1,
    var counts: LinkedTreeMap<*, *> = LinkedTreeMap<Any, Any>()
) {
    constructor() : this(title = "") // this constructor is an explicit
                                     // "empty" constructor, as seen by Java.
}

This means that with this trick you can now serialize/deserialize this object with the standard Java serializers (Jackson, Gson etc).

Can a JSON value contain a multiline string

I'm not sure of your exact requirement but one possible solution to improve 'readability' is to store it as an array.

{
  "testCases" :
  {
    "case.1" :
    {
      "scenario" : "this the case 1.",
      "result" : ["this is a very long line which is not easily readble.",
                  "so i would like to write it in multiple lines.",
                  "but, i do NOT require any new lines in the output."]
    }
  }
}

}

The join in back again whenever required with

result.join(" ")

Adding Jar files to IntellijIdea classpath

Go to File-> Project Structure-> Libraries and click green "+" to add the directory folder that has the JARs to CLASSPATH. Everything in that folder will be added to CLASSPATH.

Update:

It's 2018. It's a better idea to use a dependency manager like Maven and externalize your dependencies. Don't add JAR files to your project in a /lib folder anymore.

Screenshot

Capturing count from an SQL query

You'll get converting errors with:

cmd.CommandText = "SELECT COUNT(*) FROM table_name";
Int32 count = (Int32) cmd.ExecuteScalar();

Use instead:

string stm = "SELECT COUNT(*) FROM table_name WHERE id="+id+";";
MySqlCommand cmd = new MySqlCommand(stm, conn);
Int32 count = Convert.ToInt32(cmd.ExecuteScalar());
if(count > 0){
    found = true; 
} else {
    found = false; 
}

load Js file in HTML

I had the same problem, and found the answer. If you use node.js with express, you need to give it its own function in order for the js file to be reached. For example:

const script = path.join(__dirname, 'script.js');
const server = express().get('/', (req, res) => res.sendFile(script))

Closing a Userform with Unload Me doesn't work

As specified by the top answer, I used the following in the code behind the button control.

Private Sub btnClose_Click()
    Unload Me
End Sub

In doing so, it will not attempt to unload a control, but rather will unload the user form where the button control resides. The "Me" keyword refers to the user form object even when called from a control on the user form. If you are getting errors with this technique, there are a couple of possible reasons.

  1. You could be entering the code in the wrong place (such as a separate module)

  2. You might be using an older version of Office. I'm using Office 2013. I've noticed that VBA changes over time.

From my experience, the use of the the DoCmd.... method is more specific to the macro features in MS Access, but not commonly used in Excel VBA.

Under normal (out of the box) conditions, the code above should work just fine.

How to redirect from one URL to another URL?

Since you tagged the question with javascript and html...

For a purely HTML solution, you can use a meta tag in the header to "refresh" the page, specifying a different URL:

<meta HTTP-EQUIV="REFRESH" content="0; url=http://www.yourdomain.com/somepage.html">

If you can/want to use JavaScript, you can set the location.href of the window:

<script type="text/javascript">
    window.location.href = "http://www.yourdomain.com/somepage.html";
</script>

Why es6 react component works only with "export default"?

Add { } while importing and exporting: export { ... }; | import { ... } from './Template';

exportimport { ... } from './Template'

export defaultimport ... from './Template'


Here is a working example:

// ExportExample.js
import React from "react";

function DefaultExport() {
  return "This is the default export";
}

function Export1() {
  return "Export without default 1";
}

function Export2() {
  return "Export without default 2";
}

export default DefaultExport;
export { Export1, Export2 };

// App.js
import React from "react";
import DefaultExport, { Export1, Export2 } from "./ExportExample";

export default function App() {
  return (
    <>
      <strong>
        <DefaultExport />
      </strong>
      <br />
      <Export1 />
      <br />
      <Export2 />
    </>
  );
}

??Working sandbox to play around: https://codesandbox.io/s/export-import-example-react-jl839?fontsize=14&hidenavigation=1&theme=dark

PHP - Move a file into a different folder on the server

Some solution is first to copy() the file (as mentioned above) and when the destination file exists - unlink() file from previous localization. Additionally you can validate the MD5 checksum before unlinking to be sure

How do I get the classes of all columns in a data frame?

You can use purrr as well, which is similar to apply family functions:

as.data.frame(purrr::map_chr(mtcars, class))
purrr::map_df(mtcars, class)

Android Studio - local path doesn't exist

Restart the IDE. I restarted Android Studio. The error went away.

Is it possible to reference one CSS rule within another?

You can't unless you're using some kind of extended CSS such as SASS. However it is very reasonable to apply those two extra classes to .someDiv.

If .someDiv is unique I would also choose to give it an id and referencing it in css using the id.

Direct casting vs 'as' operator?

'as' is based on 'is', which is a keyword that checks at runtime if the object is polimorphycally compatible (basically if a cast can be made) and returns null if the check fails.

These two are equivalent:

Using 'as':

string s = o as string;

Using 'is':

if(o is string) 
    s = o;
else
    s = null;

On the contrary, the c-style cast is made also at runtime, but throws an exception if the cast cannot be made.

Just to add an important fact:

The 'as' keyword only works with reference types. You cannot do:

// I swear i is an int
int number = i as int;

In those cases you have to use casting.

res.sendFile absolute path

The express.static middleware is separate from res.sendFile, so initializing it with an absolute path to your public directory won't do anything to res.sendFile. You need to use an absolute path directly with res.sendFile. There are two simple ways to do it:

  1. res.sendFile(path.join(__dirname, '../public', 'index1.html'));
  2. res.sendFile('index1.html', { root: path.join(__dirname, '../public') });

Note: __dirname returns the directory that the currently executing script is in. In your case, it looks like server.js is in app/. So, to get to public, you'll need back out one level first: ../public/index1.html.

Note: path is a built-in module that needs to be required for the above code to work: var path = require('path');

Error while installing json gem 'mkmf.rb can't find header files for ruby'

Xcode 11 / macOS Catalina

On Xcode 11 / macOS Catalina, the header files are no longer in the old location and the old /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg file is no longer available.

Instead, the headers are now installed to the /usr/include directory of the current SDK path:

/Applications/Xcode.app/Contents/Developer/Platforms/MacOSX.platform/Developer/SDKs/MacOSX.sdk/usr/include

Most of this directory can be found by using the output of xcrun --show-sdk-path. And if you add this path to the CPATH environment variable, then build scripts (including those called via bundle) will generally be able to find it.

I resolved this by setting my CPATH in my .zshrc file:

export CPATH="$(xcrun --show-sdk-path)/usr/include"

After opening a new shell (or running source .zshrc), I no longer receive the error message mkmf.rb can't find header files for ruby at /usr/lib/ruby/ruby.h and the rubygems install properly.

Note on Building to Non-macOS Platforms

If you are building to non-macOS platforms, such as iOS/tvOS/watchOS, this change will attempt to include the macOS SDK in those platforms, causing build errors. To resolve, either don't set CPATH environment variable on login, or temporarily set it to blank when running xcodebuild like so:

CPATH="" xcodebuild --some-args

Find closest previous element jQuery

see http://api.jquery.com/prev/

var link = $("#me").parent("div").prev("h3").find("b");
alert(link.text());

see http://jsfiddle.net/gBwLq/

Open a facebook link by native Facebook app on iOS

I did this in MonoTouch in the following method, I'm sure a pure Obj-C based approach wouldn't be too different. I used this inside a class which had changing URLs at times which is why I just didn't put it in a if/elseif statement.

NSString *myUrls = @"fb://profile/100000369031300|http://www.facebook.com/ytn3rd";
NSArray *urls = [myUrls componentsSeparatedByString:@"|"];
for (NSString *url in urls){
    NSURL *nsurl = [NSURL URLWithString:url];
    if ([[UIApplication sharedApplication] canOpenURL:nsurl]){
        [[UIApplication sharedApplication] openURL:nsurl];
        break;
    }
}

The break is not always called before your app changes to Safari/Facebook. I assume your program will halt there and call it when you come back to it.

Display Back Arrow on Toolbar

Simple and easy way to show back button on toolbar

Paste this code in onCreate method

 if (getSupportActionBar() != null){

            getSupportActionBar().setDisplayHomeAsUpEnabled(true);
            getSupportActionBar().setDisplayShowHomeEnabled(true);
        }

Paste this override method outside the onCreate method

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    if(item.getItemId()== android.R.id.home) {

        finish();
    }
    return super.onOptionsItemSelected(item);
}

How to get the list of properties of a class?

You can use Reflection to do this: (from my library - this gets the names and values)

public static Dictionary<string, object> DictionaryFromType(object atype)
{
    if (atype == null) return new Dictionary<string, object>();
    Type t = atype.GetType();
    PropertyInfo[] props = t.GetProperties();
    Dictionary<string, object> dict = new Dictionary<string, object>();
    foreach (PropertyInfo prp in props)
    {
        object value = prp.GetValue(atype, new object[]{});
        dict.Add(prp.Name, value);
    }
    return dict;
}

This thing will not work for properties with an index - for that (it's getting unwieldy):

public static Dictionary<string, object> DictionaryFromType(object atype, 
     Dictionary<string, object[]> indexers)
{
    /* replace GetValue() call above with: */
    object value = prp.GetValue(atype, ((indexers.ContainsKey(prp.Name)?indexers[prp.Name]:new string[]{});
}

Also, to get only public properties: (see MSDN on BindingFlags enum)

/* replace */
PropertyInfo[] props = t.GetProperties();
/* with */
PropertyInfo[] props = t.GetProperties(BindingFlags.Public)

This works on anonymous types, too!
To just get the names:

public static string[] PropertiesFromType(object atype)
{
    if (atype == null) return new string[] {};
    Type t = atype.GetType();
    PropertyInfo[] props = t.GetProperties();
    List<string> propNames = new List<string>();
    foreach (PropertyInfo prp in props)
    {
        propNames.Add(prp.Name);
    }
    return propNames.ToArray();
}

And it's just about the same for just the values, or you can use:

GetDictionaryFromType().Keys
// or
GetDictionaryFromType().Values

But that's a bit slower, I would imagine.

JavaScript equivalent of PHP’s die

You can only break a block scope if you label it. For example:

myBlock: {
  var a = 0;
  break myBlock;
  a = 1; // this is never run
};
a === 0;

You cannot break a block scope from within a function in the scope. This means you can't do stuff like:

foo: { // this doesn't work
  (function() {
    break foo;
  }());
}

You can do something similar though with functions:

function myFunction() {myFunction:{
  // you can now use break myFunction; instead of return;
}}

What's a concise way to check that environment variables are set in a Unix shell script?

Parameter Expansion

The obvious answer is to use one of the special forms of parameter expansion:

: ${STATE?"Need to set STATE"}
: ${DEST:?"Need to set DEST non-empty"}

Or, better (see section on 'Position of double quotes' below):

: "${STATE?Need to set STATE}"
: "${DEST:?Need to set DEST non-empty}"

The first variant (using just ?) requires STATE to be set, but STATE="" (an empty string) is OK — not exactly what you want, but the alternative and older notation.

The second variant (using :?) requires DEST to be set and non-empty.

If you supply no message, the shell provides a default message.

The ${var?} construct is portable back to Version 7 UNIX and the Bourne Shell (1978 or thereabouts). The ${var:?} construct is slightly more recent: I think it was in System III UNIX circa 1981, but it may have been in PWB UNIX before that. It is therefore in the Korn Shell, and in the POSIX shells, including specifically Bash.

It is usually documented in the shell's man page in a section called Parameter Expansion. For example, the bash manual says:

${parameter:?word}

Display Error if Null or Unset. If parameter is null or unset, the expansion of word (or a message to that effect if word is not present) is written to the standard error and the shell, if it is not interactive, exits. Otherwise, the value of parameter is substituted.

The Colon Command

I should probably add that the colon command simply has its arguments evaluated and then succeeds. It is the original shell comment notation (before '#' to end of line). For a long time, Bourne shell scripts had a colon as the first character. The C Shell would read a script and use the first character to determine whether it was for the C Shell (a '#' hash) or the Bourne shell (a ':' colon). Then the kernel got in on the act and added support for '#!/path/to/program' and the Bourne shell got '#' comments, and the colon convention went by the wayside. But if you come across a script that starts with a colon, now you will know why.


Position of double quotes

blong asked in a comment:

Any thoughts on this discussion? https://github.com/koalaman/shellcheck/issues/380#issuecomment-145872749

The gist of the discussion is:

… However, when I shellcheck it (with version 0.4.1), I get this message:

In script.sh line 13:
: ${FOO:?"The environment variable 'FOO' must be set and non-empty"}
  ^-- SC2086: Double quote to prevent globbing and word splitting.

Any advice on what I should do in this case?

The short answer is "do as shellcheck suggests":

: "${STATE?Need to set STATE}"
: "${DEST:?Need to set DEST non-empty}"

To illustrate why, study the following. Note that the : command doesn't echo its arguments (but the shell does evaluate the arguments). We want to see the arguments, so the code below uses printf "%s\n" in place of :.

$ mkdir junk
$ cd junk
$ > abc
$ > def
$ > ghi
$ 
$ x="*"
$ printf "%s\n" ${x:?You must set x}    # Careless; not recommended
abc
def
ghi
$ unset x
$ printf "%s\n" ${x:?You must set x}    # Careless; not recommended
bash: x: You must set x
$ printf "%s\n" "${x:?You must set x}"  # Careful: should be used
bash: x: You must set x
$ x="*"
$ printf "%s\n" "${x:?You must set x}"  # Careful: should be used
*
$ printf "%s\n" ${x:?"You must set x"}  # Not quite careful enough
abc
def
ghi
$ x=
$ printf "%s\n" ${x:?"You must set x"}  # Not quite careful enough
bash: x: You must set x
$ unset x
$ printf "%s\n" ${x:?"You must set x"}  # Not quite careful enough
bash: x: You must set x
$ 

Note how the value in $x is expanded to first * and then a list of file names when the overall expression is not in double quotes. This is what shellcheck is recommending should be fixed. I have not verified that it doesn't object to the form where the expression is enclosed in double quotes, but it is a reasonable assumption that it would be OK.

Send FormData with other field in AngularJS

This never gonna work, you can't stringify your FormData object.

You should do this:

this.uploadFileToUrl = function(file, title, text, uploadUrl){
   var fd = new FormData();
   fd.append('title', title);
   fd.append('text', text);
   fd.append('file', file);

     $http.post(uploadUrl, obj, {
       transformRequest: angular.identity,
       headers: {'Content-Type': undefined}
     })
  .success(function(){
    blockUI.stop();
  })
  .error(function(error){
    toaster.pop('error', 'Errore', error);
  });
}

Ways to implement data versioning in MongoDB

I worked through this solution that accommodates a published, draft and historical versions of the data:

{
  published: {},
  draft: {},
  history: {
    "1" : {
      metadata: <value>,
      document: {}
    },
    ...
  }
}

I explain the model further here: http://software.danielwatrous.com/representing-revision-data-in-mongodb/

For those that may implement something like this in Java, here's an example:

http://software.danielwatrous.com/using-java-to-work-with-versioned-data/

Including all the code that you can fork, if you like

https://github.com/dwatrous/mongodb-revision-objects

How do I search for names with apostrophe in SQL Server?

SELECT *   FROM Header  WHERE userID LIKE '%' + CHAR(39) + '%' 

Check if null Boolean is true results in exception

If you don't like extra null checks:

if (Boolean.TRUE.equals(value)) {...}

Get file size, image width and height before upload

Demo

Not sure if it is what you want, but just simple example:

var input = document.getElementById('input');

input.addEventListener("change", function() {
    var file  = this.files[0];
    var img = new Image();

    img.onload = function() {
        var sizes = {
            width:this.width,
            height: this.height
        };
        URL.revokeObjectURL(this.src);

        console.log('onload: sizes', sizes);
        console.log('onload: this', this);
    }

    var objectURL = URL.createObjectURL(file);

    console.log('change: file', file);
    console.log('change: objectURL', objectURL);
    img.src = objectURL;
});

How to get base64 encoded data from html image

You can also use the FileReader class :

    var reader = new FileReader();
    reader.onload = function (e) {
        var data = this.result;
    }
    reader.readAsDataURL( file );

How to find out if a Python object is a string?

If one wants to stay away from explicit type-checking (and there are good reasons to stay away from it), probably the safest part of the string protocol to check is:

str(maybe_string) == maybe_string

It won't iterate through an iterable or iterator, it won't call a list-of-strings a string and it correctly detects a stringlike as a string.

Of course there are drawbacks. For example, str(maybe_string) may be a heavy calculation. As so often, the answer is it depends.

EDIT: As @Tcll points out in the comments, the question actually asks for a way to detect both unicode strings and bytestrings. On Python 2 this answer will fail with an exception for unicode strings that contain non-ASCII characters, and on Python 3 it will return False for all bytestrings.

How do I set up Eclipse/EGit with GitHub?

Make sure your refs for pushing are correct. This tutorial is pretty great, right from the documentation:

http://wiki.eclipse.org/EGit/User_Guide#GitHub_Tutorial

You can clone directly from GitHub, you choose where you clone that repository. And when you import that repository to Eclipse, you choose what refspec to push into upstream.

Click on the Git Repository workspace view, and make sure your remote refs are valid. Make sure you are pointing to the right local branch and pushing to the correct remote branch.

Is there a /dev/null on Windows?

I think you want NUL, at least within a command prompt or batch files.

For example:

type c:\autoexec.bat > NUL

doesn't create a file.

(I believe the same is true if you try to create a file programmatically, but I haven't tried it.)

In PowerShell, you want $null:

echo 1 > $null

Crop image to specified size and picture location

You would need to do something like this. I am typing this off the top of my head, so this may not be 100% correct.

CGColorSpaceRef colorSpace = CGColorSpaceCreateDeviceRGB(); CGContextRef context = CGBitmapContextCreate(NULL, 640, 360, 8, 4 * width, colorSpace, kCGImageAlphaPremultipliedFirst); CGColorSpaceRelease(colorSpace);  CGContextDrawImage(context, CGRectMake(0,-160,640,360), cgImgFromAVCaptureSession);  CGImageRef image = CGBitmapContextCreateImage(context); UIImage* myCroppedImg = [UIImage imageWithCGImage:image]; CGContextRelease(context);       

Check if a string is html or not

zzzzBov's answer above is good, but it does not account for stray closing tags, like for example:

/<[a-z][\s\S]*>/i.test('foo </b> bar'); // false

A version that also catches closing tags could be this:

/<[a-z/][\s\S]*>/i.test('foo </b> bar'); // true

How to display binary data as image - extjs 4

In ExtJs, you can use

xtype: 'image'

to render a image.

Here is a fiddle showing rendering of binary data with extjs.

atob -- > converts ascii to binary

btoa -- > converts binary to ascii

Ext.application({
    name: 'Fiddle',

    launch: function () {
        var srcBase64 = "data:image/jpeg;base64," + btoa(atob("iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAYAAAAfFcSJAAAADUlEQVR42mP8H8hYDwAFegHS8+X7mgAAAABJRU5ErkJggg=="));

        Ext.create("Ext.panel.Panel", {
            title: "Test",
            renderTo: Ext.getBody(),
            height: 400,
            items: [{
                xtype: 'image',
                width: 100,
                height: 100,
                src: srcBase64
            }]
        })
    }
});

https://fiddle.sencha.com/#view/editor&fiddle/28h0

R multiple conditions in if statement

Read this thread R - boolean operators && and ||.

Basically, the & is vectorized, i.e. it acts on each element of the comparison returning a logical array with the same dimension as the input. && is not, returning a single logical.

How do I join two SQLite tables in my Android application?

"Ambiguous column" usually means that the same column name appears in at least two tables; the database engine can't tell which one you want. Use full table names or table aliases to remove the ambiguity.

Here's an example I happened to have in my editor. It's from someone else's problem, but should make sense anyway.

select P.* 
from product_has_image P
inner join highest_priority_images H 
        on (H.id_product = P.id_product and H.priority = p.priority)

const char* concatenation

Using std::string:

#include <string>

std::string result = std::string(one) + std::string(two);

Show hide fragment in android

Don't mess with the visibility flags of the container - FragmentTransaction.hide/show does that internally for you.

So the correct way to do this is:

FragmentManager fm = getFragmentManager();
fm.beginTransaction()
          .setCustomAnimations(android.R.animator.fade_in, android.R.animator.fade_out)
          .show(somefrag)
          .commit();

OR if you are using android.support.v4.app.Fragment

 FragmentManager fm = getSupportFragmentManager();
 fm.beginTransaction()
          .setCustomAnimations(android.R.anim.fade_in, android.R.anim.fade_out)
          .show(somefrag)
          .commit();

How to darken a background using CSS?

This is the easiest way I found

  background: black;
  opacity: 0.5;

Java equivalent to JavaScript's encodeURIComponent that produces identical output?

for me this worked:

import org.apache.http.client.utils.URIBuilder;

String encodedString = new URIBuilder()
  .setParameter("i", stringToEncode)
  .build()
  .getRawQuery() // output: i=encodedString
  .substring(2);

or with a different UriBuilder

import javax.ws.rs.core.UriBuilder;

String encodedString = UriBuilder.fromPath("")
  .queryParam("i", stringToEncode)
  .toString()   // output: ?i=encodedString
  .substring(3);

In my opinion using a standard library is a better idea rather than post processing manually. Also @Chris answer looked good, but it doesn't work for urls, like "http://a+b c.html"

How to add a line break in an Android TextView?

You could also use the String-Editor of Android Studio, it automatically generates line brakes and stuff like that...

How do I serialize a C# anonymous type to a JSON string?

Try the JavaScriptSerializer instead of the DataContractJsonSerializer

JavaScriptSerializer serializer = new JavaScriptSerializer();
var output = serializer.Serialize(your_anon_object);

How to retrieve a recursive directory and file list from PowerShell excluding some files and folders?

Here's another option, which is less efficient but more concise. It's how I generally handle this sort of problem:

Get-ChildItem -Recurse .\targetdir -Exclude *.log |
  Where-Object { $_.FullName -notmatch '\\excludedir($|\\)' }

The \\excludedir($|\\)' expression allows you to exclude the directory and its contents at the same time.

Update: Please check the excellent answer from msorens for an edge case flaw with this approach, and a much more fleshed out solution overall.

How do you create a Distinct query in HQL

I had some problems with result transformers combined with HQL queries. When I tried

final ResultTransformer trans = new DistinctRootEntityResultTransformer();
qry.setResultTransformer(trans);

it didn't work. I had to transform manually like this:

final List found = trans.transformList(qry.list());

With Criteria API transformers worked just fine.

Have Excel formulas that return 0, make the result blank

=IF(INDEX(a,b,c)="0","", INDEX(a,b,c)) worked for me with a minor modification. Excluding the 0 and no spaces in between quotations: =IF(INDEX(a,b,c)="","", INDEX(a,b,c))

Excel function to make SQL-like queries on worksheet data?

If you want run formula on worksheet by function that execute SQL statement then use Add-in A-Tools

Example, function BS_SQL("SELECT ..."):

enter image description here

HTTP Headers for File Downloads

Acoording to RFC 2046 (Multipurpose Internet Mail Extensions):

The recommended action for an implementation that receives an
"application/octet-stream" entity is to simply offer to put the data in a file

So I'd go for that one.

Java SSLException: hostname in certificate didn't match

I had similar problem. I was using Android's DefaultHttpClient. I have read that HttpsURLConnection can handle this kind of exception. So I created custom HostnameVerifier which uses the verifier from HttpsURLConnection. I also wrapped the implementation to custom HttpClient.

public class CustomHttpClient extends DefaultHttpClient {

public CustomHttpClient() {
    super();
    SSLSocketFactory socketFactory = SSLSocketFactory.getSocketFactory();
    socketFactory.setHostnameVerifier(new CustomHostnameVerifier());
    Scheme scheme = (new Scheme("https", socketFactory, 443));
    getConnectionManager().getSchemeRegistry().register(scheme);
}

Here is the CustomHostnameVerifier class:

public class CustomHostnameVerifier implements org.apache.http.conn.ssl.X509HostnameVerifier {

@Override
public boolean verify(String host, SSLSession session) {
    HostnameVerifier hv = HttpsURLConnection.getDefaultHostnameVerifier();
    return hv.verify(host, session);
}

@Override
public void verify(String host, SSLSocket ssl) throws IOException {
}

@Override
public void verify(String host, X509Certificate cert) throws SSLException {

}

@Override
public void verify(String host, String[] cns, String[] subjectAlts) throws SSLException {

}

}

What's the difference between getPath(), getAbsolutePath(), and getCanonicalPath() in Java?

I find I rarely have need to use getCanonicalPath() but, if given a File with a filename that is in DOS 8.3 format on Windows, such as the java.io.tmpdir System property returns, then this method will return the "full" filename.

What is http multipart request?

A HTTP multipart request is a HTTP request that HTTP clients construct to send files and data over to a HTTP Server. It is commonly used by browsers and HTTP clients to upload files to the server.

Efficient evaluation of a function at every cell of a NumPy array

I believe I have found a better solution. The idea to change the function to python universal function (see documentation), which can exercise parallel computation under the hood.

One can write his own customised ufunc in C, which surely is more efficient, or by invoking np.frompyfunc, which is built-in factory method. After testing, this is more efficient than np.vectorize:

f = lambda x, y: x * y
f_arr = np.frompyfunc(f, 2, 1)
vf = np.vectorize(f)
arr = np.linspace(0, 1, 10000)

%timeit f_arr(arr, arr) # 307ms
%timeit f_arr(arr, arr) # 450ms

I have also tested larger samples, and the improvement is proportional. For comparison of performances of other methods, see this post

Git: How to check if a local repo is up to date?

You'll need to issue two commands:

  1. git fetch origin
  2. git status

How do I rotate the Android emulator display?

Device Start-up Configuration -- Via the GUI

To start-up the device in Landscape mode, modifications be made in the Android Virtual Device (AVD) Manager. Open the Virtual Device Manager, and click the Edit pencil:

AVD Manager

Then, under Startup size and orientation, select Landscape:

Configure AVD

.. and click Finish.

Device Start-up Configuration -- Via the config file

Despite the seemingly easy way to configure this, in practice this didn't work for me. So there's a way to edit the device's configuration file instead to force it to start-up in Landscape mode.

It involves manually switching the width and height in the hardware-qemui.ini file.

To do so, open this file for edit in a text editor:

C:\Users\<user>\.android\avd\<deviceName>.avd\hardware-qemu.ini

Switch the values of the width and height, so that the width is longer than the height:

hw.lcd.width = 800
hw.lcd.height = 480

The AVD now boots in Landscape mode. The orientation may still be changed with shortcut keys.

How to convert a Scikit-learn dataset to a Pandas dataset?

This snippet is only syntactic sugar built upon what TomDLT and rolyat have already contributed and explained. The only differences would be that load_iris will return a tuple instead of a dictionary and the columns names are enumerated.

df = pd.DataFrame(np.c_[load_iris(return_X_y=True)])

Strange Characters in database text: Ã, Ã, ¢, â‚ €,

This is surely an encoding problem. You have a different encoding in your database and in your website and this fact is the cause of the problem. Also if you ran that command you have to change the records that are already in your tables to convert those character in UTF-8.

Update: Based on your last comment, the core of the problem is that you have a database and a data source (the CSV file) which use different encoding. Hence you can convert your database in UTF-8 or, at least, when you get the data that are in the CSV, you have to convert them from UTF-8 to latin1.

You can do the convertion following this articles:

Quickest way to compare two generic lists for differences

Not for this Problem, but here's some code to compare lists for equal and not! identical objects:

public class EquatableList<T> : List<T>, IEquatable<EquatableList<T>> where    T : IEquatable<T>

/// <summary>
/// True, if this contains element with equal property-values
/// </summary>
/// <param name="element">element of Type T</param>
/// <returns>True, if this contains element</returns>
public new Boolean Contains(T element)
{
    return this.Any(t => t.Equals(element));
}

/// <summary>
/// True, if list is equal to this
/// </summary>
/// <param name="list">list</param>
/// <returns>True, if instance equals list</returns>
public Boolean Equals(EquatableList<T> list)
{
    if (list == null) return false;
    return this.All(list.Contains) && list.All(this.Contains);
}

SSL handshake fails with - a verisign chain certificate - that contains two CA signed certificates and one self-signed certificate

When you see "Verify return code: 19 (self signed certificate in certificate chain)", then, either the servers is really trying to use a self-signed certificate (which a client is never going to be able to verify), or OpenSSL hasn't got access to the necessary root but the server is trying to provide it itself (which it shouldn't do because it's pointless - a client can never trust a server to supply the root corresponding to the server's own certificate).

Again, adding -showcerts will help you diagnose which.

Bootstrap - dropdown menu not working?

This is a Rails specific answer, but I had this same problem with Bootstrap dropdown menus in my Rails app. What fixed it was adding this to app/assets/javascripts/application.js:

//= require bootstrap

Hope that helps someone.

Floating Div Over An Image

Never fails, once I post the question to SO, I get some enlightening "aha" moment and figure it out. The solution:

_x000D_
_x000D_
    .container {_x000D_
       border: 1px solid #DDDDDD;_x000D_
       width: 200px;_x000D_
       height: 200px;_x000D_
       position: relative;_x000D_
    }_x000D_
    .tag {_x000D_
       float: left;_x000D_
       position: absolute;_x000D_
       left: 0px;_x000D_
       top: 0px;_x000D_
       z-index: 1000;_x000D_
       background-color: #92AD40;_x000D_
       padding: 5px;_x000D_
       color: #FFFFFF;_x000D_
       font-weight: bold;_x000D_
    }
_x000D_
<div class="container">_x000D_
       <div class="tag">Featured</div>_x000D_
       <img src="http://www.placehold.it/200x200">_x000D_
</div>
_x000D_
_x000D_
_x000D_

The key is the container has to be positioned relative and the tag positioned absolute.

How to try convert a string to a Guid

This will get you pretty close, and I use it in production and have never had a collision. However, if you look at the constructor for a guid in reflector, you will see all of the checks it makes.

 public static bool GuidTryParse(string s, out Guid result)
    {
        if (!String.IsNullOrEmpty(s) && guidRegEx.IsMatch(s))
        {
            result = new Guid(s);
            return true;
        }

        result = default(Guid);
        return false;
    }

    static Regex guidRegEx = new Regex("^[A-Fa-f0-9]{32}$|" +
                          "^({|\\()?[A-Fa-f0-9]{8}-([A-Fa-f0-9]{4}-){3}[A-Fa-f0-9]{12}(}|\\))?$|" +
                          "^({)?[0xA-Fa-f0-9]{3,10}(, {0,1}[0xA-Fa-f0-9]{3,6}){2}, {0,1}({)([0xA-Fa-f0-9]{3,4}, {0,1}){7}[0xA-Fa-f0-9]{3,4}(}})$", RegexOptions.Compiled);

How to make java delay for a few seconds?

move the System.out statement to finally block.

When to catch java.lang.Error?

An Error usually shouldn't be caught, as it indicates an abnormal condition that should never occur.

From the Java API Specification for the Error class:

An Error is a subclass of Throwable that indicates serious problems that a reasonable application should not try to catch. Most such errors are abnormal conditions. [...]

A method is not required to declare in its throws clause any subclasses of Error that might be thrown during the execution of the method but not caught, since these errors are abnormal conditions that should never occur.

As the specification mentions, an Error is only thrown in circumstances that are Chances are, when an Error occurs, there is very little the application can do, and in some circumstances, the Java Virtual Machine itself may be in an unstable state (such as VirtualMachineError)

Although an Error is a subclass of Throwable which means that it can be caught by a try-catch clause, but it probably isn't really needed, as the application will be in an abnormal state when an Error is thrown by the JVM.

There's also a short section on this topic in Section 11.5 The Exception Hierarchy of the Java Language Specification, 2nd Edition.

Deep copy of a dict in python

A simpler (in my view) solution is to create a new dictionary and update it with the contents of the old one:

my_dict={'a':1}

my_copy = {}

my_copy.update( my_dict )

my_dict['a']=2

my_dict['a']
Out[34]: 2

my_copy['a']
Out[35]: 1

The problem with this approach is it may not be 'deep enough'. i.e. is not recursively deep. good enough for simple objects but not for nested dictionaries. Here is an example where it may not be deep enough:

my_dict1={'b':2}

my_dict2={'c':3}

my_dict3={ 'b': my_dict1, 'c':my_dict2 }

my_copy = {}

my_copy.update( my_dict3 )

my_dict1['b']='z'

my_copy
Out[42]: {'b': {'b': 'z'}, 'c': {'c': 3}}

By using Deepcopy() I can eliminate the semi-shallow behavior, but I think one must decide which approach is right for your application. In most cases you may not care, but should be aware of the possible pitfalls... final example:

import copy

my_copy2 = copy.deepcopy( my_dict3 )

my_dict1['b']='99'

my_copy2
Out[46]: {'b': {'b': 'z'}, 'c': {'c': 3}}

How to set DialogFragment's width and height?

When I need to make the DialogFragment a bit wider I'm setting minWidth:

<LinearLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:minWidth="320dp"
    ... />

Adding asterisk to required fields in Bootstrap 3

I modified the css, as i am using bootstrap 3.3.6

.form-group.required label:after{   
color: #d00;   
font-family: 'FontAwesome'; 
font-weight: normal;
font-size: 10px;
content: "\f069"; 
top:4px;   
position: absolute;   
 margin-left: 8px;
}

the HTML

<div class="form-group required">
 <label for="return_notes"><?= _lang('notes') ?></label>
 <textarea class="form-control" name="return_notes" id="return_notes"  required="required"></textarea>
</div>

What is an application binary interface (ABI)?

The term ABI is used to refer to two distinct but related concepts.

When talking about compilers it refers to the rules used to translate from source-level constructs to binary constructs. How big are the data types? how does the stack work? how do I pass parameters to functions? which registers should be saved by the caller vs the callee?

When talking about libraries it refers to the binary interface presented by a compiled library. This interface is the result of a number of factors including the source code of the library, the rules used by the compiler and in some cases definitions picked up from other libraries.

Changes to a library can break the ABI without breaking the API. Consider for example a library with an interface like.

void initfoo(FOO * foo)
int usefoo(FOO * foo, int bar)
void cleanupfoo(FOO * foo)

and the application programmer writes code like

int dostuffwithfoo(int bar) {
  FOO foo;
  initfoo(&foo);
  int result = usefoo(&foo,bar)
  cleanupfoo(&foo);
  return result;
}

The application programmer doesn't care about the size or layout of FOO, but the application binary ends up with a hardcoded size of foo. If the library programmer adds an extra field to foo and someone uses the new library binary with the old application binary then the library may make out of bounds memory accesses.

OTOH if the library author had designed their API like.

FOO * newfoo(void)
int usefoo(FOO * foo, int bar)
void deletefoo((FOO * foo, int bar))

and the application programmer writes code like

int dostuffwithfoo(int bar) {
  FOO * foo;
  foo = newfoo();
  int result = usefoo(foo,bar)
  deletefoo(foo);
  return result;
}

Then the application binary does not need to know anything about the structure of FOO, that can all be hidden inside the library. The price you pay for that though is that heap operations are involved.

Change the background color in a twitter bootstrap modal?

CSS

If this doesn't work:

.modal-backdrop {
   background-color: red;
}

try this:

.modal { 
   background-color: red !important; 
}

comparing strings in vb

If String.Compare(string1,string2,True) Then

    'perform operation

EndIf

Getting Chrome to accept self-signed localhost certificate

WINDOWS JUN/2017 Windows Server 2012

I followed @Brad Parks answer. On Windows you should import rootCA.pem in Trusted Root Certificates Authorities store.

I did the following steps:

openssl genrsa -out rootCA.key 4096
openssl req -x509 -new -nodes -key rootCA.key -newkey rsa:4096 -sha256 -days 1024 -out rootCA.pem
openssl req -new -newkey rsa:4096 -sha256 -nodes -keyout device.key -out device.csr
openssl x509 -req -in device.csr -CA rootCA.pem -CAkey rootCA.key -CAcreateserial -out device.crt -days 2000 -sha256 -extfile v3.ext

Where v3.ext is:

authorityKeyIdentifier=keyid,issuer
basicConstraints=CA:FALSE
keyUsage = digitalSignature, nonRepudiation, keyEncipherment, dataEncipherment
subjectAltName = @alt_names

[alt_names]
DNS.1 = localhost
IP.1 = 192.168.0.2
IP.2 = 127.0.0.1

Then, in my case I have a self hosted web app, so I need to bind certificate with IP address and port, certificate should be on MY store with private key information, so I exported to pfx format.

openssl pkcs12 -export -out device.pfx -inkey device.key -in device.crt

With mmc console (File/Add or Remove Snap-ins/Certificates/Add/Computert Account/LocalComputer/OK) I imported pfx file in Personal store.

Later I used this command to bind certificate (you could also use HttpConfig tool):

netsh http add sslcert ipport=0.0.0.0:12345 certhash=b02de34cfe609bf14efd5c2b9be72a6cb6d6fe54 appid={BAD76723-BF4D-497F-A8FE-F0E28D3052F4}

certhash=Certificate Thumprint

appid=GUID (your choice)

First I tried to import the certificate "device.crt" on Trusted Root Certificates Authorities in different ways but I'm still getting same error:

enter image description here

But I realized that I should import certificate of root authority not certificate for domain. So I used mmc console (File/Add or Remove Snap-ins/Certificates/Add/Computert Account/LocalComputer/OK) I imported rootCA.pem in Trusted Root Certificates Authorities store.

enter image description here

Restart Chrome and et voilà it works.

With localhost:

enter image description here

Or with IP address:

enter image description here

The only thing I could not achieve is that, it has obsolete cipher (red square on picture). Help is appreciated on this point.

With makecert it is not possible add SAN information. With New-SelfSignedCertificate (Powershell) you could add SAN information, it also works.

Sort a single String in Java

Question: sort a string in java

public class SortAStringInJava {
    public static void main(String[] args) {

        String str = "Protijayi";
// Method 1
        str = str.chars() // IntStream
                .sorted().collect(StringBuilder::new, StringBuilder::appendCodePoint, StringBuilder::append).toString();

        System.out.println(str);
        // Method 2
        str = Stream.of(str.split(" ")).sorted().collect(Collectors.joining());
        System.out.println(str);
    }
}

VBA error 1004 - select method of range class failed

Removing the range select before the copy worked for me. Thanks for the posts.

Invoking a static method using reflection

// String.class here is the parameter type, that might not be the case with you
Method method = clazz.getMethod("methodName", String.class);
Object o = method.invoke(null, "whatever");

In case the method is private use getDeclaredMethod() instead of getMethod(). And call setAccessible(true) on the method object.

wait() or sleep() function in jquery?

There is an function, but it's extra: http://docs.jquery.com/Cookbook/wait

This little snippet allows you to wait:

$.fn.wait = function(time, type) {
    time = time || 1000;
    type = type || "fx";
    return this.queue(type, function() {
        var self = this;
        setTimeout(function() {
            $(self).dequeue();
        }, time);
    });
};

CSS values using HTML5 data attribute

There is, indeed, prevision for such feature, look http://www.w3.org/TR/css3-values/#attr-notation

This fiddle should work like what you need, but will not for now.

Unfortunately, it's still a draft, and isn't fully implemented on major browsers.

It does work for content on pseudo-elements, though.

How to detect when WIFI Connection has been established in Android?

I used this code:

public class MainActivity extends Activity
    {
    .
    .
    .
    @Override
    protected void onCreate(Bundle savedInstanceState)
        {
        super.onCreate(savedInstanceState);
        .
        .
        .
        }

    @Override
    protected void onResume()
        {
        super.onResume();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION);
        registerReceiver(broadcastReceiver, intentFilter);  
        }

    @Override
    protected void onPause()
        {
        super.onPause();
        unregisterReceiver(broadcastReceiver);
        }

    private final BroadcastReceiver broadcastReceiver = new BroadcastReceiver()
        {
        @Override
        public void onReceive(Context context, Intent intent)
            {
            final String action = intent.getAction();
            if (action.equals(WifiManager.SUPPLICANT_CONNECTION_CHANGE_ACTION))
                {
                if (intent.getBooleanExtra(WifiManager.EXTRA_SUPPLICANT_CONNECTED, false))
                    {
                    // wifi is enabled
                    }
                else
                    {
                    // wifi is disabled
                    }
                }
            }
        };
    }

show all tables in DB2 using the LIST command

Run this command line on your preferred shell session:

db2 "select tabname from syscat.tables where owner = 'DB2INST1'"

Maybe you'd like to modify the owner name, and need to check the list of current owners?

db2 "select distinct owner from syscat.tables"

Doctrine query builder using inner join with conditions

I'm going to answer my own question.

  1. innerJoin should use the keyword "WITH" instead of "ON" (Doctrine's documentation [13.2.6. Helper methods] is inaccurate; [13.2.5. The Expr class] is correct)
  2. no need to link foreign keys in join condition as they're already specified in the entity mapping.

Therefore, the following works for me

$qb->select('c')
    ->innerJoin('c.phones', 'p', 'WITH', 'p.phone = :phone')
    ->where('c.username = :username');

or

$qb->select('c')
    ->innerJoin('c.phones', 'p', Join::WITH, $qb->expr()->eq('p.phone', ':phone'))
    ->where('c.username = :username');

Write to custom log file from a Bash script

@chepner make a good point that logger is dedicated to logging messages.

I do need to mention that @Thomas Haratyk simply inquired why I didn't simply use echo.

At the time, I didn't know about echo, as I'm learning shell-scripting, but he was right.

My simple solution is now this:

#!/bin/bash
echo "This logs to where I want, but using echo" > /var/log/mycustomlog

The example above will overwrite the file after the >

So, I can append to that file with this:

#!/bin/bash
echo "I will just append to my custom log file" >> /var/log/customlog

Thanks guys!

  • on a side note, it's simply my personal preference to keep my personal logs in /var/log/, but I'm sure there are other good ideas out there. And since I didn't create a daemon, /var/log/ probably isn't the best place for my custom log file. (just saying)

How does one create an InputStream from a String?

Java 7+

It's possible to take advantage of the StandardCharsets JDK class:

String str=...
InputStream is = new ByteArrayInputStream(StandardCharsets.UTF_16.encode(str).array());

Creating a list of objects in Python

To fill a list with seperate instances of a class, you can use a for loop in the declaration of the list. The * multiply will link each copy to the same instance.

instancelist = [ MyClass() for i in range(29)]

and then access the instances through the index of the list.

instancelist[5].attr1 = 'whamma'

libxml/tree.h no such file or directory

You also need to add /usr/include/libxml2 to your include path.

C - function inside struct

It can't be done directly, but you can emulate the same thing using function pointers and explicitly passing the "this" parameter:

typedef struct client_t client_t, *pno;
struct client_t
{
        pid_t pid;
        char password[TAM_MAX]; // -> 50 chars
        pno next;

        pno (*AddClient)(client_t *);    
};

pno client_t_AddClient(client_t *self) { /* code */ }

int main()
{

    client_t client;
    client.AddClient = client_t_AddClient; // probably really done in some init fn

    //code ..

    client.AddClient(&client);

}

It turns out that doing this, however, doesn't really buy you an awful lot. As such, you won't see many C APIs implemented in this style, since you may as well just call your external function and pass the instance.

Create list of single item repeated N times

Create List of Single Item Repeated n Times in Python

Depending on your use-case, you want to use different techniques with different semantics.

Multiply a list for Immutable items

For immutable items, like None, bools, ints, floats, strings, tuples, or frozensets, you can do it like this:

[e] * 4

Note that this is usually only used with immutable items (strings, tuples, frozensets, ) in the list, because they all point to the same item in the same place in memory. I use this frequently when I have to build a table with a schema of all strings, so that I don't have to give a highly redundant one to one mapping.

schema = ['string'] * len(columns)

Multiply the list where we want the same item repeated

Multiplying a list gives us the same elements over and over. The need for this is rare:

[iter(iterable)] * 4

This is sometimes used to map an iterable into a list of lists:

>>> iterable = range(12)
>>> a_list = [iter(iterable)] * 4
>>> [[next(l) for l in a_list] for i in range(3)]
[[0, 1, 2, 3], [4, 5, 6, 7], [8, 9, 10, 11]]

We can see that a_list contains the same range iterator four times:

>>> a_list
[<range_iterator object at 0x7fde73a5da20>, <range_iterator object at 0x7fde73a5da20>, <range_iterator object at 0x7fde73a5da20>, <range_iterator object at 0x7fde73a5da20>]

Mutable items

I've used Python for a long time now, and I have seen very few use-cases where I would do the above with mutable objects.

Instead, to get, say, a mutable empty list, set, or dict, you should do something like this:

list_of_lists = [[] for _ in columns]

The underscore is simply a throwaway variable name in this context.

If you only have the number, that would be:

list_of_lists = [[] for _ in range(4)]

The _ is not really special, but your coding environment style checker will probably complain if you don't intend to use the variable and use any other name.


Caveats for using the immutable method with mutable items:

Beware doing this with mutable objects, when you change one of them, they all change because they're all the same object:

foo = [[]] * 4
foo[0].append('x')

foo now returns:

[['x'], ['x'], ['x'], ['x']]

But with immutable objects, you can make it work because you change the reference, not the object:

>>> l = [0] * 4
>>> l[0] += 1
>>> l
[1, 0, 0, 0]

>>> l = [frozenset()] * 4
>>> l[0] |= set('abc')
>>> l
[frozenset(['a', 'c', 'b']), frozenset([]), frozenset([]), frozenset([])]

But again, mutable objects are no good for this, because in-place operations change the object, not the reference:

l = [set()] * 4
>>> l[0] |= set('abc')    
>>> l
[set(['a', 'c', 'b']), set(['a', 'c', 'b']), set(['a', 'c', 'b']), set(['a', 'c', 'b'])]

How to insert default values in SQL table?

Try it like this

INSERT INTO table1 (field1, field3) VALUES (5,10)

Then field2 and field4 should have default values.

How to clear the interpreter console?

here something handy that is a little more cross-platform

import os

def cls():
    os.system('cls' if os.name=='nt' else 'clear')

# now, to clear the screen
cls()

Get value of multiselect box using jQuery or pure JS

According to the widget's page, it should be:

var myDropDownListValues = $("#myDropDownList").multiselect("getChecked").map(function()
{
    return this.value;    
}).get();

It works for me :)

Count all duplicates of each value

You'd want the COUNT operator.

SELECT NUMBER, COUNT(*) 
FROM T_NAME
GROUP BY NUMBER
ORDER BY NUMBER ASC

need to test if sql query was successful

if you're not using the -> format, you can do this:

$a = "SQL command...";
if ($b = mysqli_query($con,$a)) {
  // results was successful
} else {
  // result was not successful
}

Peak-finding algorithm for Python/SciPy

There is a function in scipy named scipy.signal.find_peaks_cwt which sounds like is suitable for your needs, however I don't have experience with it so I cannot recommend..

http://docs.scipy.org/doc/scipy/reference/generated/scipy.signal.find_peaks_cwt.html

How to access random item in list?

I have been using this ExtensionMethod for a while:

public static IEnumerable<T> GetRandom<T>(this IEnumerable<T> list, int count)
{
    if (count <= 0)
      yield break;
    var r = new Random();
    int limit = (count * 10);
    foreach (var item in list.OrderBy(x => r.Next(0, limit)).Take(count))
      yield return item;
}

How could I put a border on my grid control in WPF?

This is a later answer that works for me, if it may be of use to anyone in the future. I wanted a simple border around all four sides of the grid and I achieved it like so...

<DataGrid x:Name="dgDisplay" Margin="5" BorderBrush="#1266a7" BorderThickness="1"...

Detect if Android device has Internet connection

You can do this using the ConnectivityManager API for android. It allows you to check whether you are connected to the internet and the type of internet connection you are connected to. Basically, Metered or Un-metered.

To check for internet connection.

ConnectivityManager cm = (ConnectivityManager)context.getSystemService(Context.CONNECTIVITY_SERVICE);
NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
boolean isConnected = activeNetwork != null && activeNetwork.isConnectedOrConnecting();

Documentation link: https://developer.android.com/training/monitoring-device-state/connectivity-status-type

Xml Parsing in C#

First add an Enrty and Category class:

public class Entry {     public string Id { get; set; }     public string Title { get; set; }     public string Updated { get; set; }     public string Summary { get; set; }     public string GPoint { get; set; }     public string GElev { get; set; }     public List<string> Categories { get; set; } }  public class Category {     public string Label { get; set; }     public string Term { get; set; } } 

Then use LINQ to XML

XDocument xDoc = XDocument.Load("path");          List<Entry> entries = (from x in xDoc.Descendants("entry")             select new Entry()             {                 Id = (string) x.Element("id"),                 Title = (string)x.Element("title"),                 Updated = (string)x.Element("updated"),                 Summary = (string)x.Element("summary"),                 GPoint = (string)x.Element("georss:point"),                 GElev = (string)x.Element("georss:elev"),                 Categories = (from c in x.Elements("category")                                   select new Category                                   {                                       Label = (string)c.Attribute("label"),                                       Term = (string)c.Attribute("term")                                   }).ToList();             }).ToList();