Programs & Examples On #Interrogative programming

In what situations would AJAX long/short polling be preferred over HTML5 WebSockets?

XHR polling vs SSE vs WebSockets

  • XHR polling A Request is answered when the event occurs (could be straight away, or after a delay). Subsequent requests will need to made to receive further events.

    The browser makes an asynchronous request of the server, which may wait for data to be available before responding. The response can contain encoded data (typically XML or JSON) or Javascript to be executed by the client. At the end of the processing of the response, the browser creates and sends another XHR, to await the next event. Thus the browser always keeps a request outstanding with the server, to be answered as each event occurs. Wikipedia

  • Server Sent Events Client sends request to server. Server sends new data to webpage at any time.

    Traditionally, a web page has to send a request to the server to receive new data; that is, the page requests data from the server. With server-sent events, it's possible for a server to send new data to a web page at any time, by pushing messages to the web page. These incoming messages can be treated as Events + data inside the web page. Mozilla

  • WebSockets After the initial handshake (via HTTP protocol). Communication is done bidirectionally using the WebSocket protocol.

    The handshake starts with an HTTP request/response, allowing servers to handle HTTP connections as well as WebSocket connections on the same port. Once the connection is established, communication switches to a bidirectional binary protocol which does not conform to the HTTP protocol. Wikipedia

Javascript string/integer comparisons

Checking that strings are integers is separate to comparing if one is greater or lesser than another. You should always compare number with number and string with string as the algorithm for dealing with mixed types not easy to remember.

'00100' < '1' // true

as they are both strings so only the first zero of '00100' is compared to '1' and because it's charCode is lower, it evaluates as lower.

However:

'00100' < 1 // false

as the RHS is a number, the LHS is converted to number before the comparision.

A simple integer check is:

function isInt(n) {
  return /^[+-]?\d+$/.test(n);
}

It doesn't matter if n is a number or integer, it will be converted to a string before the test.

If you really care about performance, then:

var isInt = (function() {
  var re = /^[+-]?\d+$/;

  return function(n) {
    return re.test(n);
  }
}());

Noting that numbers like 1.0 will return false. If you want to count such numbers as integers too, then:

var isInt = (function() {
  var re = /^[+-]?\d+$/;
  var re2 = /\.0+$/;

  return function(n) {
    return re.test((''+ n).replace(re2,''));
  }
}());

Once that test is passed, converting to number for comparison can use a number of methods. I don't like parseInt() because it will truncate floats to make them look like ints, so all the following will be "equal":

parseInt(2.9) == parseInt('002',10) == parseInt('2wewe')

and so on.

Once numbers are tested as integers, you can use the unary + operator to convert them to numbers in the comparision:

if (isInt(a) && isInt(b)) {
  if (+a < +b) {
    // a and b are integers and a is less than b
  }
}

Other methods are:

Number(a); // liked by some because it's clear what is happening
a * 1      // Not really obvious but it works, I don't like it

python numpy machine epsilon

It will already work, as David pointed out!

>>> def machineEpsilon(func=float):
...     machine_epsilon = func(1)
...     while func(1)+func(machine_epsilon) != func(1):
...         machine_epsilon_last = machine_epsilon
...         machine_epsilon = func(machine_epsilon) / func(2)
...     return machine_epsilon_last
... 
>>> machineEpsilon(float)
2.220446049250313e-16
>>> import numpy
>>> machineEpsilon(numpy.float64)
2.2204460492503131e-16
>>> machineEpsilon(numpy.float32)
1.1920929e-07

How to rename HTML "browse" button of an input type=file?

No, you can't change file upload input's text. But there are some tricks to overlay an image over the button.

Maven 3 warnings about build.plugins.plugin.version

Maven 3 is more restrictive with the POM-Structure. You have to set versions of Plugins for instance.

With maven 3.1 these warnings may break you build. There are more changes between maven2 and maven3: https://cwiki.apache.org/confluence/display/MAVEN/Maven+3.x+Compatibility+Notes

How to extract the decimal part from a floating point number in C?

Suppose A is your integer then (int)A, means casting the number to an integer and will be the integer part, the other is (A - (int)A)*10^n, here n is the number of decimals to keep.

Can you style an html radio button to look like a checkbox?

In CSS3:

input[type=radio] {content:url(mycheckbox.png)}
input[type=radio]:checked {content:url(mycheckbox-checked.png)}

In reality:

<span class=fakecheckbox><input type=radio><img src="checkbox.png" alt=""></span>

@media screen {.fakecheckbox img {display:none}}
@media print {.fakecheckbox input {display:none;}}

and you'll need Javascript to keep <img> and radios in sync (and ideally insert them there in a first place).

I've used <img>, because browsers are usually configured not to print background-image. It's better to use image than another control, because image is non-interactive and less likely to cause problems.

Visual Studio "Could not copy" .... during build

I didn't realize I still had my debugger attached and was trying to build in the same Visual Studio instance. Once I stopped the debugger I was able to build.

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

Here an other suggestion to get a GMT Timestamp object:

import java.sql.Timestamp;
import java.util.Calendar;

...

private static Timestamp getGMT() {
   Calendar cal = Calendar.getInstance();
   return new Timestamp(cal.getTimeInMillis()
                       -cal.get(Calendar.ZONE_OFFSET)
                       -cal.get(Calendar.DST_OFFSET));
}

Difference between ApiController and Controller in ASP.NET MVC

Use Controller to render your normal views. ApiController action only return data that is serialized and sent to the client.

here is the link

Quote:

Note If you have worked with ASP.NET MVC, then you are already familiar with controllers. They work similarly in Web API, but controllers in Web API derive from the ApiController class instead of Controller class. The first major difference you will notice is that actions on Web API controllers do not return views, they return data.

ApiControllers are specialized in returning data. For example, they take care of transparently serializing the data into the format requested by the client. Also, they follow a different routing scheme by default (as in: mapping URLs to actions), providing a REST-ful API by convention.

You could probably do anything using a Controller instead of an ApiController with the some(?) manual coding. In the end, both controllers build upon the ASP.NET foundation. But having a REST-ful API is such a common requirement today that WebAPI was created to simplify the implementation of a such an API.

It's fairly simple to decide between the two: if you're writing an HTML based web/internet/intranet application - maybe with the occasional AJAX call returning json here and there - stick with MVC/Controller. If you want to provide a data driven/REST-ful interface to a system, go with WebAPI. You can combine both, of course, having an ApiController cater AJAX calls from an MVC page.

To give a real world example: I'm currently working with an ERP system that provides a REST-ful API to its entities. For this API, WebAPI would be a good candidate. At the same time, the ERP system provides a highly AJAX-ified web application that you can use to create queries for the REST-ful API. The web application itself could be implemented as an MVC application, making use of the WebAPI to fetch meta-data etc.

How to close the current fragment by using Button like the back button?

Try this:

ft.addToBackStack(null);   // ft is FragmentTransaction

So, when you press back-key, the current activity (which holds multiple fragments) will load previous fragment rather than finishing itself.

HttpClient.GetAsync(...) never returns when using await/async

These two schools are not really excluding.

Here is the scenario where you simply have to use

   Task.Run(() => AsyncOperation()).Wait(); 

or something like

   AsyncContext.Run(AsyncOperation);

I have a MVC action that is under database transaction attribute. The idea was (probably) to roll back everything done in the action if something goes wrong. This does not allow context switching, otherwise transaction rollback or commit is going to fail itself.

The library I need is async as it is expected to run async.

The only option. Run it as a normal sync call.

I am just saying to each its own.

Volley - POST/GET parameters

Dealing with GET parameters I iterated on Andrea Motto' solution. The problem was that Volley called GetUrl several times and his solution, using an Iterator, destroyed original Map object. The subsequent Volley internal calls had an empty params object.

I added also the encode of parameters.

This is an inline usage (no subclass).

public void GET(String url, Map<String, String> params, Response.Listener<String> response_listener, Response.ErrorListener error_listener, String API_KEY, String stringRequestTag) {
    final Map<String, String> mParams = params;
    final String mAPI_KEY = API_KEY;
    final String mUrl = url;

    StringRequest stringRequest = new StringRequest(
            Request.Method.GET,
            mUrl,
            response_listener,
            error_listener
    ) {
        @Override
        protected Map<String, String> getParams() {
            return mParams;
        }

        @Override
        public String getUrl() {
            StringBuilder stringBuilder = new StringBuilder(mUrl);
            int i = 1;
            for (Map.Entry<String,String> entry: mParams.entrySet()) {
                String key;
                String value;
                try {
                    key = URLEncoder.encode(entry.getKey(), "UTF-8");
                    value = URLEncoder.encode(entry.getValue(), "UTF-8");
                    if(i == 1) {
                        stringBuilder.append("?" + key + "=" + value);
                    } else {
                        stringBuilder.append("&" + key + "=" + value);
                    }
                } catch (UnsupportedEncodingException e) {
                    e.printStackTrace();
                }
                i++;

            }
            String url = stringBuilder.toString();

            return url;
        }

        @Override
        public Map<String, String> getHeaders() {
            Map<String, String> headers = new HashMap<>();
            if (!(mAPI_KEY.equals(""))) {
                headers.put("X-API-KEY", mAPI_KEY);
            }
            return headers;
        }
    };

    if (stringRequestTag != null) {
        stringRequest.setTag(stringRequestTag);
    }

    mRequestQueue.add(stringRequest);
}

This function uses headers to pass an APIKEY and sets a TAG to the request useful to cancel it before its completion.

Hope this helps.

Read Variable from Web.Config

If you want the basics, you can access the keys via:

string myKey = System.Configuration.ConfigurationManager.AppSettings["myKey"].ToString();
string imageFolder = System.Configuration.ConfigurationManager.AppSettings["imageFolder"].ToString();

To access my web config keys I always make a static class in my application. It means I can access them wherever I require and I'm not using the strings all over my application (if it changes in the web config I'd have to go through all the occurrences changing them). Here's a sample:

using System.Configuration;

public static class AppSettingsGet
{    
    public static string myKey
    {
        get { return ConfigurationManager.AppSettings["myKey"].ToString(); }
    }

    public static string imageFolder
    {
        get { return ConfigurationManager.AppSettings["imageFolder"].ToString(); }
    }

    // I also get my connection string from here
    public static string ConnectionString
    {
       get { return ConfigurationManager.ConnectionStrings["ConnectionString"].ConnectionString; }
    }
}

setting min date in jquery datepicker

Try like this

<script>

  $(document).ready(function(){
          $("#order_ship_date").datepicker({
           changeMonth:true,
           changeYear:true,           
            dateFormat:"yy-mm-dd",
            minDate: +2,
        });
  }); 


</script>

html code is given below

<input id="order_ship_date"  type="text" class="input" style="width:80px;"  />

C# find biggest number

using System;
using System.Linq;

class Program
{
    static void Main(string[] args)
    {
        int[] numbers = { 3, 9, 5 };
        int biggestNumber = numbers.Max();
        Console.WriteLine(biggestNumber);
        Console.ReadLine();
    }
}

select a value where it doesn't exist in another table

select ID from A where ID not in (select ID from B);

or

select ID from A except select ID from B;

Your second question:

delete from A where ID not in (select ID from B);

How to disable editing of elements in combobox for c#?

I tried ComboBox1_KeyPress but it allows to delete the character & you can also use copy paste command. My DropDownStyle is set to DropDownList but still no use. So I did below step to avoid combobox text editing.

  • Below code handles delete & backspace key. And also disables combination with control key (e.g. ctr+C or ctr+X)

     Private Sub CmbxInType_KeyDown(sender As Object, e As KeyEventArgs) Handles CmbxInType.KeyDown
        If e.KeyCode = Keys.Delete Or e.KeyCode = Keys.Back Then 
            e.SuppressKeyPress = True
        End If
    
        If Not (e.Control AndAlso e.KeyCode = Keys.C) Then
            e.SuppressKeyPress = True
        End If
    End Sub
    
  • In form load use below line to disable right click on combobox control to avoid cut/paste via mouse click.

    CmbxInType.ContextMenu = new ContextMenu()
    

How to align checkboxes and their labels consistently cross-browsers

This works well for me:

_x000D_
_x000D_
fieldset {_x000D_
  text-align:left;_x000D_
  border:none_x000D_
}_x000D_
fieldset ol, fieldset ul {_x000D_
  padding:0;_x000D_
  list-style:none_x000D_
}_x000D_
fieldset li {_x000D_
  padding-bottom:1.5em;_x000D_
  float:none;_x000D_
  clear:left_x000D_
}_x000D_
label {_x000D_
  float:left;_x000D_
  width:7em;_x000D_
  margin-right:1em_x000D_
}_x000D_
fieldset.checkboxes li {_x000D_
  clear:both;_x000D_
  padding:.75em_x000D_
}_x000D_
fieldset.checkboxes label {_x000D_
  margin:0 0 0 1em;_x000D_
  width:20em_x000D_
}_x000D_
fieldset.checkboxes input {_x000D_
  float:left_x000D_
}
_x000D_
<form>_x000D_
  <fieldset class="checkboxes">_x000D_
    <ul>_x000D_
      <li>_x000D_
        <input type="checkbox" name="happy" value="yep" id="happy" />_x000D_
        <label for="happy">Happy?</label>_x000D_
      </li>_x000D_
      <li>_x000D_
        <input type="checkbox" name="hungry" value="yep" id="hungry" />_x000D_
        <label for="hungry">Hungry?</label>_x000D_
      </li>_x000D_
    </ul>_x000D_
  </fieldset>_x000D_
</form>
_x000D_
_x000D_
_x000D_

Changing Fonts Size in Matlab Plots

Jonas's answer does not change the font size of the axes. Sergeyf's answer does not work when there are multiple subplots.

Here is a modification of their answers that works for me when I have multiple subplots:

set(findall(gcf,'type','axes'),'fontsize',30)
set(findall(gcf,'type','text'),'fontSize',30) 

String MinLength and MaxLength validation don't work (asp.net mvc)

Try using this attribute, for example for password min length:

[StringLength(100, ErrorMessage = "???????????? ????? ?????? 20 ????????", MinimumLength = User.PasswordMinLength)]

remove item from array using its name / value

Created a handy function for this..

function findAndRemove(array, property, value) {
  array.forEach(function(result, index) {
    if(result[property] === value) {
      //Remove from array
      array.splice(index, 1);
    }    
  });
}

//Checks countries.result for an object with a property of 'id' whose value is 'AF'
//Then removes it ;p
findAndRemove(countries.results, 'id', 'AF');

How to retrieve an Oracle directory path?

select directory_path from dba_directories where upper(directory_name) = 'CSVDIR'

IEnumerable<object> a = new IEnumerable<object>(); Can I do this?

It's a pretty old question, but for the sake of newcomers, this is how we can protect an IEnumerable<T> from a null exception. Another word, to create an empty instance of a variable of type IEnumerable<T>

public IEnumerable<T> MyPropertyName { get; set; } = Enumerable.Empty<T>();

https://docs.microsoft.com/en-us/dotnet/api/system.linq.enumerable.empty?view=net-5.0

Cheers.

Using reCAPTCHA on localhost

Yes, this an older question but this may be helping all the users having problems with reCaptcha on localhost. Google indeed says "By default, all keys work on 'localhost' (or '127.0.0.1')" but for real using reCaptcha on localhost may cause problems. In my case I solved mine using secure token

I posted a WORKING SOLUTION for PHP here

How to change a package name in Eclipse?

  1. Change the Package Name in Manifest.
  2. A warning box will be said to change into workspace ,press "yes"
  3. then right click on src-> refactor -> rename paste your package name
  4. select package name and sub package name both

  5. press "save" a warning pop ups , press "continue"

name changed successfully

Make the console wait for a user input to close

You can just use nextLine(); as pause

import java.util.Scanner
//
//
Scanner scan = new Scanner(System.in);

void Read()
{
     System.out.print("Press any key to continue . . . ");
     scan.nextLine();
}

However any button you press except Enter means you will have to press Enter after that but I found it better than scan.next();

How to invoke a Linux shell command from Java

exec does not execute a command in your shell

try

Process p = Runtime.getRuntime().exec(new String[]{"csh","-c","cat /home/narek/pk.txt"});

instead.

EDIT:: I don't have csh on my system so I used bash instead. The following worked for me

Process p = Runtime.getRuntime().exec(new String[]{"bash","-c","ls /home/XXX"});

Is it possible to change javascript variable values while debugging in Google Chrome?

Why is this answer still getting upvotes?

Per Mikaël Mayer's answer, this is no longer a problem, and my answer is obsolete (go() now returns 30 after mucking with the console). This was fixed in July 2013, according to the bug report linked above in gabrielmaldi's comment. It alarms me that I'm still getting upvotes - makes me think the upvoter doesn't understand either the question or my answer.

I'll leave my original answer here for historical reasons, but go upvote Mikaël's answer instead.


The trick is that you can't change a local variable directly, but you can modify the properties of an object. You can also modify the value of a global variable:

var g_n = 0;
function go()
{
    var n = 0;
    var o = { n: 0 };
    return g_n + n + o.n;  // breakpoint here
}

console:

> g_n = 10
  10
> g_n
  10
> n = 10
  10
> n
  0
> o.n = 10
  10
> o.n
  10

Check the result of go() after setting the breakpoint and running those calls in the console, and you'll find that the result is 20, rather than 0 (but sadly, not 30).

Splitting comma separated string in a PL/SQL stored proc

create or replace procedure pro_ss(v_str varchar2) as
v_str1 varchar2(100); 
v_comma_pos number := 0;    
v_start_pos number := 1;
begin             
    loop        
    v_comma_pos := instr(v_str,',',v_start_pos);   
    if  v_comma_pos = 0 then     
      v_str1 := substr(v_str,v_start_pos);  
      dbms_output.put_line(v_str1);    
      exit;
      end if;    
    v_str1 := substr(v_str,v_start_pos,(v_comma_pos - v_start_pos)); 
    dbms_output.put_line(v_str1);       
    v_start_pos := v_comma_pos + 1;    
    end loop; 
end;
/

call pro_ss('aa,bb,cc,dd,ee,ff,gg,hh,ii,jj');

outout: aa bb cc dd ee ff gg hh ii jj

Fatal error: iostream: No such file or directory in compiling C program using GCC

Neither <iostream> nor <iostream.h> are standard C header files. Your code is meant to be C++, where <iostream> is a valid header. Use g++ (and a .cpp file extension) for C++ code.

Alternatively, this program uses mostly constructs that are available in C anyway. It's easy enough to convert the entire program to compile using a C compiler. Simply remove #include <iostream> and using namespace std;, and replace cout << endl; with putchar('\n');... I advise compiling using C99 (eg. gcc -std=c99)

python global name 'self' is not defined

It should be something like:

class Person:
   def setavalue(self, name):         
      self.myname = name      
   def printaname(self):         
      print "Name", self.myname           

def main():
   p = Person()
   p.setavalue("harry")
   p.printaname()  

pip install - locale.Error: unsupported locale setting

Someone may find it useful. You could put those locale settings in .bashrc file, which usually located in the home directory.
Just add this command in .bashrc:
export LC_ALL=C
then type source .bashrc
Now you don't need to call this command manually every time, when you connecting via ssh for example.

Save file Javascript with file name

function saveAs(uri, filename) {
    var link = document.createElement('a');
    if (typeof link.download === 'string') {
        document.body.appendChild(link); // Firefox requires the link to be in the body
        link.download = filename;
        link.href = uri;
        link.click();
        document.body.removeChild(link); // remove the link when done
    } else {
        location.replace(uri);
    }
}

Count number of rows within each group

If your trying the aggregate solutions above and you get the error:

invalid type (list) for variable

Because you're using date or datetime stamps, try using as.character on the variables:

aggregate(x ~ as.character(Year) + Month, data = df, FUN = length)

On one or both of the variables.

paint() and repaint() in Java

It's not necessary to call repaint unless you need to render something specific onto a component. "Something specific" meaning anything that isn't provided internally by the windowing toolkit you're using.

Semi-transparent color layer over background-image?

I've used this as a way to both apply colour tints as well as gradients to images to make dynamic overlaying text easier to style for legibility when you can't control image colour profiles. You don't have to worry about z-index.

HTML

<div class="background-image"></div>

SASS

.background-image {
  background: url('../img/bg/diagonalnoise.png') repeat;
  &:before {
    content: '';
    position: absolute;
    top: 0;
    left: 0;
    right: 0;
    bottom: 0;
    background: rgba(248, 247, 216, 0.7);
  }
}

CSS

.background-image {
  background: url('../img/bg/diagonalnoise.png') repeat;
}

.background-image:before {
    content: '';
    position: absolute;
    top: 0;
    bottom: 0;
    right: 0;
    left: 0;
    background: rgba(248, 247, 216, 0.7);
  }

Hope it helps

Java string replace and the NUL (NULL, ASCII 0) character?

Should be probably changed to

firstName = firstName.trim().replaceAll("\\.", "");

WELD-001408: Unsatisfied dependencies for type Customer with qualifiers @Default

Your Customer class has to be discovered by CDI as a bean. For that you have two options:

  1. Put a bean defining annotation on it. As @Model is a stereotype it's why it does the trick. A qualifier like @Named is not a bean defining annotation, reason why it doesn't work

  2. Change the bean discovery mode in your bean archive from the default "annotated" to "all" by adding a beans.xml file in your jar.

Keep in mind that @Named has only one usage : expose your bean to the UI. Other usages are for bad practice or compatibility with legacy framework.

Why do I get TypeError: can't multiply sequence by non-int of type 'float'?

The problem is that salesAmount is being set to a string. If you enter the variable in the python interpreter and hit enter, you'll see the value entered surrounded by quotes. For example, if you entered 56.95 you'd see:

>>> sales_amount = raw_input("[Insert sale amount]: ")
[Insert sale amount]: 56.95
>>> sales_amount
'56.95'

You'll want to convert the string into a float before multiplying it by sales tax. I'll leave that for you to figure out. Good luck!

Python xml ElementTree from a string source?

You can parse the text as a string, which creates an Element, and create an ElementTree using that Element.

import xml.etree.ElementTree as ET
tree = ET.ElementTree(ET.fromstring(xmlstring))

I just came across this issue and the documentation, while complete, is not very straightforward on the difference in usage between the parse() and fromstring() methods.

How to execute a stored procedure inside a select query

Functions are easy to call inside a select loop, but they don't let you run inserts, updates, deletes, etc. They are only useful for query operations. You need a stored procedure to manipulate the data.

So, the real answer to this question is that you must iterate through the results of a select statement via a "cursor" and call the procedure from within that loop. Here's an example:

DECLARE @myId int;
DECLARE @myName nvarchar(60);
DECLARE myCursor CURSOR FORWARD_ONLY FOR
    SELECT Id, Name FROM SomeTable;
OPEN myCursor;
FETCH NEXT FROM myCursor INTO @myId, @myName;
WHILE @@FETCH_STATUS = 0 BEGIN
    EXECUTE dbo.myCustomProcedure @myId, @myName;
    FETCH NEXT FROM myCursor INTO @myId, @myName;
END;
CLOSE myCursor;
DEALLOCATE myCursor;

Note that @@FETCH_STATUS is a standard variable which gets updated for you. The rest of the object names here are custom.

Angular 2 execute script after template render

Actually ngAfterViewInit() will initiate only once when the component initiate.

If you really want a event triggers after the HTML element renter on the screen then you can use ngAfterViewChecked()

Convert JsonNode into POJO

If you're using org.codehaus.jackson, this has been possible since 1.6. You can convert a JsonNode to a POJO with ObjectMapper#readValue: http://jackson.codehaus.org/1.9.4/javadoc/org/codehaus/jackson/map/ObjectMapper.html#readValue(org.codehaus.jackson.JsonNode, java.lang.Class)


    ObjectMapper mapper = new ObjectMapper();
    JsonParser jsonParser = mapper.getJsonFactory().createJsonParser("{\"foo\":\"bar\"}");
    JsonNode tree = jsonParser.readValueAsTree();
    // Do stuff to the tree
    mapper.readValue(tree, Foo.class);

FileNotFoundException while getting the InputStream object from HttpURLConnection

I don't know about your Spring/JAXB combination, but the average REST webservice won't return a response body on POST/PUT, just a response status. You'd like to determine it instead of the body.

Replace

InputStream response = con.getInputStream();

by

int status = con.getResponseCode();

All available status codes and their meaning are available in the HTTP spec, as linked before. The webservice itself should also come along with some documentation which overviews all status codes supported by the webservice and their special meaning, if any.

If the status starts with 4nn or 5nn, you'd like to use getErrorStream() instead to read the response body which may contain the error details.

InputStream error = con.getErrorStream();

Two's Complement in Python

This will give you the two's complement efficiently using bitwise logic:

def twos_complement(value, bitWidth):
    if value >= 2**bitWidth:
        # This catches when someone tries to give a value that is out of range
        raise ValueError("Value: {} out of range of {}-bit value.".format(value, bitWidth))
    else:
        return value - int((value << 1) & 2**bitWidth)

How it works:

First, we make sure that the user has passed us a value that is within the range of the supplied bit range (e.g. someone gives us 0xFFFF and specifies 8 bits) Another solution to that problem would be to bitwise AND (&) the value with (2**bitWidth)-1

To get the result, the value is shifted by 1 bit to the left. This moves the MSB of the value (the sign bit) into position to be anded with 2**bitWidth. When the sign bit is '0' the subtrahend becomes 0 and the result is value - 0. When the sign bit is '1' the subtrahend becomes 2**bitWidth and the result is value - 2**bitWidth

Example 1: If the parameters are value=0xFF (255d, b11111111) and bitWidth=8

  1. 0xFF - int((0xFF << 1) & 2**8)
  2. 0xFF - int((0x1FE) & 0x100)
  3. 0xFF - int(0x100)
  4. 255 - 256
  5. -1

Example 2: If the parameters are value=0x1F (31d, b11111) and bitWidth=6

  1. 0x1F - int((0x1F << 1) & 2**6)
  2. 0x1F - int((0x3E) & 0x40)
  3. 0x1F - int(0x00)
  4. 31 - 0
  5. 31

Example 3: value = 0x80, bitWidth = 7

ValueError: Value: 128 out of range of 7-bit value.

Example 4: value = 0x80, bitWitdh = 8

  1. 0x80 - int((0x80 << 1) & 2**8)
  2. 0x80 - int((0x100) & 0x100)
  3. 0x80 - int(0x100)
  4. 128 - 256
  5. -128

Now, using what others have already posted, pass your bitstring into int(bitstring,2) and pass to the twos_complement method's value parameter.

What is the height of Navigation Bar in iOS 7?

I got this answer from the book Programming iOS 7, section Bar Position and Bar Metrics

If a navigation bar or toolbar — or a search bar (discussed earlier in this chapter) — is to occupy the top of the screen, the iOS 7 convention is that its height should be increased to underlap the transparent status bar. To make this possible, iOS 7 introduces the notion of a bar position.

UIBarPositionTopAttached

Specifies that the bar is at the top of the screen, as well as its containing view. Bars with this position draw their background extended upwards, allowing their background content to show through the status bar. Available in iOS 7.0 and later.

Windows Scipy Install: No Lapack/Blas Resources Found

For python27 1?Install numpy + mkl(download link:http://www.lfd.uci.edu/~gohlke/pythonlibs/) 2?install scipy (the same site) OK!

Automatically get loop index in foreach loop in Perl

autobox::Core provides, among many more things, a handy for method:

use autobox::Core;

['a'..'z']->for( sub{
    my ($index, $value) = @_;
    say "$index => $value";
});

Alternatively, have a look at an iterator module, for example: Array::Iterator

use Array::Iterator;

my $iter = Array::Iterator->new( ['a'..'z'] );
while ($iter->hasNext) {
    $iter->getNext;
    say $iter->currentIndex . ' => ' . $iter->current;
}

Also see:

How to calculate probability in a normal distribution given mean & standard deviation?

There's one in scipy.stats:

>>> import scipy.stats
>>> scipy.stats.norm(0, 1)
<scipy.stats.distributions.rv_frozen object at 0x928352c>
>>> scipy.stats.norm(0, 1).pdf(0)
0.3989422804014327
>>> scipy.stats.norm(0, 1).cdf(0)
0.5
>>> scipy.stats.norm(100, 12)
<scipy.stats.distributions.rv_frozen object at 0x928352c>
>>> scipy.stats.norm(100, 12).pdf(98)
0.032786643008494994
>>> scipy.stats.norm(100, 12).cdf(98)
0.43381616738909634
>>> scipy.stats.norm(100, 12).cdf(100)
0.5

[One thing to beware of -- just a tip -- is that the parameter passing is a little broad. Because of the way the code is set up, if you accidentally write scipy.stats.norm(mean=100, std=12) instead of scipy.stats.norm(100, 12) or scipy.stats.norm(loc=100, scale=12), then it'll accept it, but silently discard those extra keyword arguments and give you the default (0,1).]

How do I prevent mails sent through PHP mail() from going to spam?

$fromMail = 'set your from mail';
$boundary = str_replace(" ", "", date('l jS \of F Y h i s A'));
$subjectMail = "New design submitted by " . $userDisplayName;


$contentHtml = '<div>Dear Admin<br /><br />The following design is submitted by '. $userName .'.<br /><br /><a href="'.$sdLink.'"><b>Click here</b></a> to check the design.</div>';
$contentHtml .= '<div><a href="'.$imageUrl.'"><img src="'.$imageUrl.'" width="250" height="95" border="0" alt="my picture"></a></div>';
$contentHtml .= '<div>Name : '.$name.'<br />Description : '. $description .'</div>';

$headersMail = '';
$headersMail .= 'From: ' . $fromMail . "\r\n" . 'Reply-To: ' . $fromMail . "\r\n";
$headersMail .= 'Return-Path: ' . $fromMail . "\r\n";
$headersMail .= 'MIME-Version: 1.0' . "\r\n";
$headersMail .= "Content-Type: multipart/alternative; boundary = \"" . $boundary . "\"\r\n\r\n";
$headersMail .= '--' . $boundary . "\r\n";
$headersMail .= 'Content-Type: text/html; charset=ISO-8859-1' . "\r\n";
$headersMail .= 'Content-Transfer-Encoding: base64' . "\r\n\r\n";
$headersMail .= rtrim(chunk_split(base64_encode($contentHtml)));

try {
    if (mail($toMail, $subjectMail, "", $headersMail)) {
        $status = 'success';
        $msg = 'Mail sent successfully.';
    } else {
        $status = 'failed';
        $msg = 'Unable to send mail.';
    }
} catch(Exception $e) {
    $msg = $e->getMessage();
}

This works fine for me.It includes mail with image and a link and works for all sorts of mail ids. The clue is to use all the header perfectly.

If you are testing it from localhost, then set the below before checking:

How to set mail send from localhost xampp:

  1. comment everything in D:/xampp/sendmail/sendmail.ini and mention the below under

    [sendmail]

    smtp_server=smtp.gmail.com smtp_port=587 error_logfile=error.log debug_logfile=debug.log [email protected] auth_password=your-mail-password [email protected]

  2. In D:/xampp/php/php.ini a. Under

    [mail function]

    SMTP = smtp.gmail.com smtp_port = 587

b. set sendmail_from = [email protected] c. uncomment sendmail_path = "\"D:\xamp\sendmail\sendmail.exe\" -t" Hence it should be look like below

sendmail_path = "\"D:\xamp\sendmail\sendmail.exe\" -t"

d. comment sendmail_path="D:\xamp\mailtodisk\mailtodisk.exe" Hence it should be look like below

;sendmail_path="D:\xamp\mailtodisk\mailtodisk.exe"

e. mail.add_x_header=Off

Combination of async function + await + setTimeout

setTimeout is not an async function, so you can't use it with ES7 async-await. But you could implement your sleep function using ES6 Promise:

function sleep (fn, par) {
  return new Promise((resolve) => {
    // wait 3s before calling fn(par)
    setTimeout(() => resolve(fn(par)), 3000)
  })
}

Then you'll be able to use this new sleep function with ES7 async-await:

var fileList = await sleep(listFiles, nextPageToken)

Please, note that I'm only answering your question about combining ES7 async/await with setTimeout, though it may not help solve your problem with sending too many requests per second.


Update: Modern node.js versions has a buid-in async timeout implementation, accessible via util.promisify helper:

const {promisify} = require('util');
const setTimeoutAsync = promisify(setTimeout);

Make a link in the Android browser start up my app?

I think you'll want to look at the <intent-filter> element of your Mainfest file. Specifically, take a look at the documentation for the <data> sub-element.

Basically, what you'll need to do is define your own scheme. Something along the lines of:

<intent-filter>
    <data android:scheme="anton" />
    <action android:name="android.intent.action.VIEW" />
    <category android:name="android.intent.category.DEFAULT" />
    <category android:name="android.intent.category.BROWSABLE" /> <--Not positive if this one is needed
    ...
</intent-filter>

Then you should be able to launch your app with links that begin with the anton: URI scheme.

Format date to MM/dd/yyyy in JavaScript

ISO compliant dateString

If your dateString is RFC282 and ISO8601 compliant:
pass your string into the Date Constructor:

const dateString = "2020-10-30T12:52:27+05:30"; // ISO8601 compliant dateString
const D = new Date(dateString);                 // {object Date}

from here you can extract the desired values by using Date Getters:

D.getMonth() + 1  // 10 (PS: +1 since Month is 0-based)
D.getDate()       // 30
D.getFullYear()   // 2020

Non-standard date string

If you use a non standard date string:
destructure the string into known parts, and than pass the variables to the Date Constructor:

new Date(year, monthIndex [, day [, hours [, minutes [, seconds [, milliseconds]]]]])

const dateString = "30/10/2020 12:52:27";
const [d, M, y, h, m, s] = dateString.match(/\d+/g);

// PS: M-1 since Month is 0-based
const D = new Date(y, M-1, d, h, m, s);  // {object Date}


D.getMonth() + 1  // 10 (PS: +1 since Month is 0-based)
D.getDate()       // 30
D.getFullYear()   // 2020

Is it not possible to stringify an Error using JSON.stringify?

There is a great Node.js package for that: serialize-error.

npm install serialize-error

It handles well even nested Error objects.

import {serializeError} from 'serialize-error';

JSON.stringify(serializeError(error));

Docs: https://www.npmjs.com/package/serialize-error

Setting a timeout for socket operations

You could use the following solution:

SocketAddress sockaddr = new InetSocketAddress(ip, port);
// Create your socket
Socket socket = new Socket();
// Connect with 10 s timeout
socket.connect(sockaddr, 10000);

Hope it helps!

Difference between View and Request scope in managed beans

A @ViewScoped bean lives exactly as long as a JSF view. It usually starts with a fresh new GET request, or with a navigation action, and will then live as long as the enduser submits any POST form in the view to an action method which returns null or void (and thus navigates back to the same view). Once you refresh the page, or return a non-null string (even an empty string!) navigation outcome, then the view scope will end.

A @RequestScoped bean lives exactly as long a HTTP request. It will thus be garbaged by end of every request and recreated on every new request, hereby losing all changed properties.

A @ViewScoped bean is thus particularly more useful in rich Ajax-enabled views which needs to remember the (changed) view state across Ajax requests. A @RequestScoped one would be recreated on every Ajax request and thus fail to remember all changed view state. Note that a @ViewScoped bean does not share any data among different browser tabs/windows in the same session like as a @SessionScoped bean. Every view has its own unique @ViewScoped bean.

See also:

Powershell 2 copy-item which creates a folder if doesn't exist

  $filelist | % {
    $file = $_
    mkdir -force (Split-Path $dest) | Out-Null
    cp $file $dest
  } 

How to open a page in a new window or tab from code-behind

Try this one

string redirect = "<script>window.open('http://www.google.com');</script>"; 
Response.Write(redirect);

Simple way to repeat a string

If speed is your concern, then you should use as less memory copying as possible. Thus it is required to work with arrays of chars.

public static String repeatString(String what, int howmany) {
    char[] pattern = what.toCharArray();
    char[] res = new char[howmany * pattern.length];
    int length = pattern.length;
    for (int i = 0; i < howmany; i++)
        System.arraycopy(pattern, 0, res, i * length, length);
    return new String(res);
}

To test speed, a similar optimal method using StirngBuilder is like this:

public static String repeatStringSB(String what, int howmany) {
    StringBuilder out = new StringBuilder(what.length() * howmany);
    for (int i = 0; i < howmany; i++)
        out.append(what);
    return out.toString();
}

and the code to test it:

public static void main(String... args) {
    String res;
    long time;

    for (int j = 0; j < 1000; j++) {
        res = repeatString("123", 100000);
        res = repeatStringSB("123", 100000);
    }

    time = System.nanoTime();
    res = repeatString("123", 1000000);
    time = System.nanoTime() - time;
    System.out.println("elapsed repeatString: " + time);

    time = System.nanoTime();
    res = repeatStringSB("123", 1000000);
    time = System.nanoTime() - time;
    System.out.println("elapsed repeatStringSB: " + time);

}

And here the run results from my system:

elapsed repeatString: 6006571
elapsed repeatStringSB: 9064937

Note that the test for loop is to kick in JIT and have optimal results.

How to write asynchronous functions for Node.js

You seem to be confusing asynchronous IO with asynchronous functions. node.js uses asynchronous non-blocking IO because non blocking IO is better. The best way to understand it is to go watch some videos by ryan dahl.

How do I write asynchronous functions for Node?

Just write normal functions, the only difference is that they are not executed immediately but passed around as callbacks.

How should I implement error event handling correctly

Generally API's give you a callback with an err as the first argument. For example

database.query('something', function(err, result) {
  if (err) handle(err);
  doSomething(result);
});

Is a common pattern.

Another common pattern is on('error'). For example

process.on('uncaughtException', function (err) {
  console.log('Caught exception: ' + err);
});

Edit:

var async_function = function(val, callback){
    process.nextTick(function(){
        callback(val);
    });
};

The above function when called as

async_function(42, function(val) {
  console.log(val)
});
console.log(43);

Will print 42 to the console asynchronously. In particular process.nextTick fires after the current eventloop callstack is empty. That call stack is empty after async_function and console.log(43) have run. So we print 43 followed by 42.

You should probably do some reading on the event loop.

Change onClick attribute with javascript

You are not actually changing the function.

onClick is assigned to a function (Which is a reference to something, a function pointer in this case). The values passed to it don't matter and cannot be utilised in any manner.

Another problem is your variable color seems out of nowhere.

Ideally, inside the function you should put this logic and let it figure out what to write. (on/off etc etc)

When to use async false and async true in ajax function in jquery

It's not relative to performance...

You set async to false, when you need that ajax request to be completed before the browser passes to other codes:

<script>
    // ...
    $.ajax(... async: false ...); // Hey browser! first complete this request, 
                                  // then go for other codes

    $.ajax(...); // Executed after the completion of the previous async:false request.
</script>

setting request headers in selenium

check this out: chrome_options = Options()

chrome_options.add_argument('--headless')
chrome_options.add_argument('user-agent="Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_4) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/73.0.3683.103 Safari/537.36"')

Problem solved!

Maximum packet size for a TCP connection

According to http://en.wikipedia.org/wiki/Maximum_segment_size, the default largest size for a IPV4 packet on a network is 536 octets (bytes of size 8 bits). See RFC 879

instanceof Vs getClass( )

The reason that the performance of instanceof and getClass() == ... is different is that they are doing different things.

  • instanceof tests whether the object reference on the left-hand side (LHS) is an instance of the type on the right-hand side (RHS) or some subtype.

  • getClass() == ... tests whether the types are identical.

So the recommendation is to ignore the performance issue and use the alternative that gives you the answer that you need.

Is using the instanceOf operator bad practice ?

Not necessarily. Overuse of either instanceOf or getClass() may be "design smell". If you are not careful, you end up with a design where the addition of new subclasses results in a significant amount of code reworking. In most situations, the preferred approach is to use polymorphism.

However, there are cases where these are NOT "design smell". For example, in equals(Object) you need to test the actual type of the argument, and return false if it doesn't match. This is best done using getClass().


Terms like "best practice", "bad practice", "design smell", "antipattern" and so on should be used sparingly and treated with suspicion. They encourage black-or-white thinking. It is better to make your judgements in context, rather than based purely on dogma; e.g. something that someone said is "best practice". I recommend that everyone read No Best Practices if they haven't already done so.

Stop floating divs from wrapping

The CSS property display: inline-block was designed to address this need. You can read a bit about it here: http://robertnyman.com/2010/02/24/css-display-inline-block-why-it-rocks-and-why-it-sucks/

Below is an example of its use. The key elements are that the row element has white-space: nowrap and the cell elements have display: inline-block. This example should work on most major browsers; a compatibility table is available here: http://caniuse.com/#feat=inline-block

<html>
<body>
<style>

.row {
    float:left;
    border: 1px solid yellow;
    width: 100%;
    overflow: auto;
    white-space: nowrap;
}

.cell {
    display: inline-block;
    border: 1px solid red;
    width: 200px;
    height: 100px;
}
</style>

<div class="row">
    <div class="cell">a</div>
    <div class="cell">b</div>
    <div class="cell">c</div>
</div>


</body>
</html>

How do I get the last word in each line with bash

You can do something like this in awk:

awk '{ print $NF }'

Edit: To avoid empty line :

awk 'NF{ print $NF }'

How to show current user name in a cell?

if you don't want to create a UDF in VBA or you can't, this could be an alternative.

=Cell("Filename",A1) this will give you the full file name, and from this you could get the user name with something like this:

=Mid(A1,Find("\",A1,4)+1;Find("\";A1;Find("\";A1;4))-2)


This Formula runs only from a workbook saved earlier.

You must start from 4th position because of the first slash from the drive.

fatal: 'origin' does not appear to be a git repository

$HOME/.gitconfig is your global config for git.
There are three levels of config files.

 cat $(git rev-parse --show-toplevel)/.git/config

(mentioned by bereal) is your local config, local to the repo you have cloned.

you can also type from within your repo:

git remote -v

And see if there is any remote named 'origin' listed in it.

If not, if that remote (which is created by default when cloning a repo) is missing, you can add it again:

git remote add origin url/to/your/fork

The OP mentions:

Doing git remote -v gives:

upstream git://git.moodle.org/moodle.git (fetch) 
upstream git://git.moodle.org/moodle.git (push)

So 'origin' is missing: the reference to your fork.
See "What is the difference between origin and upstream in github"

enter image description here

Python dictionary replace values

via dict.update() function

In case you need a declarative solution, you can use dict.update() to change values in a dict.

Either like this:

my_dict.update({'key1': 'value1', 'key2': 'value2'})

or like this:

my_dict.update(key1='value1', key2='value2')

via dictionary unpacking

Since Python 3.5 you can also use dictionary unpacking for this:

my_dict = { **my_dict, 'key1': 'value1', 'key2': 'value2'}

Note: This creates a new dictionary.

via merge operator or update operator

Since Python 3.9 you can also use the merge operator on dictionaries:

my_dict = my_dict | {'key1': 'value1', 'key2': 'value2'}

Note: This creates a new dictionary.

Or you can use the update operator:

my_dict |= {'key1': 'value1', 'key2': 'value2'}

"Cannot open include file: 'config-win.h': No such file or directory" while installing mysql-python

For me the following approach solved the issue (Python 3.5.2; mysqlclient 1.3.9):

  1. Dowload latest MySQL C Connector http://dev.mysql.com/downloads/connector/c/ (for me was Windows (x86, 64-bit), MSI Installer)
  2. Copy c:\Program Files\MySQL\MySQL Connector C 6.0.2\ directory to c:\Program Files (x86)\MySQL\MySQL Connector C 6.1\
  3. Run pip install mysqlclient
  4. [optional] delete c:\Program Files (x86)\MySQL\MySQL Connector C 6.1\

The issue here is only for x64 bit installation owners, since build script is trying to locate C connector includes in x86 program files directory.

What certificates are trusted in truststore?

Trust store generally (actually should only contain root CAs but this rule is violated in general) contains the certificates that of the root CAs (public CAs or private CAs). You can verify the list of certs in trust store using

keytool -list -v -keystore truststore.jks

Python exit commands - why so many and when should each be used?

sys.exit is the canonical way to exit.

Internally sys.exit just raises SystemExit. However, calling sys.exitis more idiomatic than raising SystemExit directly.

os.exit is a low-level system call that exits directly without calling any cleanup handlers.

quit and exit exist only to provide an easy way out of the Python prompt. This is for new users or users who accidentally entered the Python prompt, and don't want to know the right syntax. They are likely to try typing exit or quit. While this will not exit the interpreter, it at least issues a message that tells them a way out:

>>> exit
Use exit() or Ctrl-D (i.e. EOF) to exit
>>> exit()
$

This is essentially just a hack that utilizes the fact that the interpreter prints the __repr__ of any expression that you enter at the prompt.

How can I write a heredoc to a file in Bash script?

As instance you could use it:

First(making ssh connection):

while read pass port user ip files directs; do
    sshpass -p$pass scp -o 'StrictHostKeyChecking no' -P $port $files $user@$ip:$directs
done <<____HERE
    PASS    PORT    USER    IP    FILES    DIRECTS
      .      .       .       .      .         .
      .      .       .       .      .         .
      .      .       .       .      .         .
    PASS    PORT    USER    IP    FILES    DIRECTS
____HERE

Second(executing commands):

while read pass port user ip; do
    sshpass -p$pass ssh -p $port $user@$ip <<ENDSSH1
    COMMAND 1
    .
    .
    .
    COMMAND n
ENDSSH1
done <<____HERE
    PASS    PORT    USER    IP
      .      .       .       .
      .      .       .       .
      .      .       .       .
    PASS    PORT    USER    IP    
____HERE

Third(executing commands):

Script=$'
#Your commands
'

while read pass port user ip; do
    sshpass -p$pass ssh -o 'StrictHostKeyChecking no' -p $port $user@$ip "$Script"

done <<___HERE
PASS    PORT    USER    IP
  .      .       .       .
  .      .       .       .
  .      .       .       .
PASS    PORT    USER    IP  
___HERE

Forth(using variables):

while read pass port user ip fileoutput; do
    sshpass -p$pass ssh -o 'StrictHostKeyChecking no' -p $port $user@$ip fileinput=$fileinput 'bash -s'<<ENDSSH1
    #Your command > $fileinput
    #Your command > $fileinput
ENDSSH1
done <<____HERE
    PASS    PORT    USER    IP      FILE-OUTPUT
      .      .       .       .          .
      .      .       .       .          .
      .      .       .       .          .
    PASS    PORT    USER    IP      FILE-OUTPUT
____HERE

XPath to fetch SQL XML value

Update

My recomendation would be to shred the XML into relations and do searches and joins on the resulted relation, in a set oriented fashion, rather than the procedural fashion of searching specific nodes in the XML. Here is a simple XML query that shreds out the nodes and attributes of interest:

select x.value(N'../../../../@stepId', N'int') as StepID
  , x.value(N'../../@id', N'int') as ComponentID
  , x.value(N'@nom',N'nvarchar(100)') as Nom
  , x.value(N'@valeur', N'nvarchar(100)') as Valeur
from @x.nodes(N'/xml/box/components/component/variables/variable') t(x)

However, if you must use an XPath that retrieves exactly the value of interest:

select x.value(N'@valeur', N'nvarchar(100)') as Valeur
from @x.nodes(N'/xml/box[@stepId=sql:variable("@stepID")]/
    components/component[@id = sql:variable("@componentID")]/
       variables/variable[@nom="Enabled"]') t(x)

If the stepID and component ID are columns, not variables, the you should use sql:column() instead of sql:variable in the XPath filters. See Binding Relational Data Inside XML Data.

And finaly if all you need is to check for existance you can use the exist() XML method:

select @x.exist(
  N'/xml/box[@stepId=sql:variable("@stepID")]/
    components/component[@id = sql:variable("@componentID")]/
      variables/variable[@nom="Enabled" and @valeur="Yes"]') 

programmatically add column & rows to WPF Datagrid

If you already have the databinding in place John Myczek answer is complete. If not you have at least 2 options I know of if you want to specify the source of your data. (However I am not sure whether or not this is in line with most guidelines, like MVVM)

Then you just bind to Users collections and columns are autogenerated as you speficy them. Strings passed to property descriptors are names for column headers. At runtime you can add more PropertyDescriptors to 'Users' add another column to the grid.

Automatic HTTPS connection/redirect with node.js/express

I use the solution proposed by Basarat but I also need to overwrite the port because I used to have 2 different ports for HTTP and HTTPS protocols.

res.writeHead(301, { "Location": "https://" + req.headers['host'].replace(http_port,https_port) + req.url });

I prefer also to use not standard port so to start nodejs without root privileges. I like 8080 and 8443 because I came from lots of years of programming on tomcat.

My complete file become

var fs = require('fs');
var http = require('http');
var http_port    =   process.env.PORT || 8080; 
var app = require('express')();

// HTTPS definitions
var https = require('https');
var https_port    =   process.env.PORT_HTTPS || 8443; 
var options = {
   key  : fs.readFileSync('server.key'),
   cert : fs.readFileSync('server.crt')
};

app.get('/', function (req, res) {
   res.send('Hello World!');
});

https.createServer(options, app).listen(https_port, function () {
   console.log('Magic happens on port ' + https_port); 
});

// Redirect from http port to https
http.createServer(function (req, res) {
    res.writeHead(301, { "Location": "https://" + req.headers['host'].replace(http_port,https_port) + req.url });
    console.log("http request, will go to >> ");
    console.log("https://" + req.headers['host'].replace(http_port,https_port) + req.url );
    res.end();
}).listen(http_port);

Then I use iptable for forwording 80 and 443 traffic on my HTTP and HTTPS ports.

sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 80 -j REDIRECT --to-port 8080
sudo iptables -t nat -A PREROUTING -i eth0 -p tcp --dport 443 -j REDIRECT --to-port 8443

Does PHP have threading?

From the PHP manual for the pthreads extension:

pthreads is an Object Orientated API that allows user-land multi-threading in PHP. It includes all the tools you need to create multi-threaded applications targeted at the Web or the Console. PHP applications can create, read, write, execute and synchronize with Threads, Workers and Stackables.

As unbelievable as this sounds, it's entirely true. Today, PHP can multi-thread for those wishing to try it.

The first release of PHP4, 22 May 2000, PHP was shipped with a thread safe architecture - a way for it to execute multiple instances of it's interpreter in separate threads in multi-threaded SAPI ( Server API ) environments. Over the last 13 years, the design of this architecture has been maintained and advanced: It has been in production use on the worlds largest websites ever since.

Threading in user land was never a concern for the PHP team, and it remains as such today. You should understand that in the world where PHP does it's business, there's already a defined method of scaling - add hardware. Over the many years PHP has existed, hardware has got cheaper and cheaper and so this became less and less of a concern for the PHP team. While it was getting cheaper, it also got much more powerful; today, our mobile phones and tablets have dual and quad core architectures and plenty of RAM to go with it, our desktops and servers commonly have 8 or 16 cores, 16 and 32 gigabytes of RAM, though we may not always be able to have two within budget and having two desktops is rarely useful for most of us.

Additionally, PHP was written for the non-programmer, it is many hobbyists native tongue. The reason PHP is so easily adopted is because it is an easy language to learn and write. The reason PHP is so reliable today is because of the vast amount of work that goes into it's design, and every single decision made by the PHP group. It's reliability and sheer greatness keep it in the spot light, after all these years; where it's rivals have fallen to time or pressure.

Multi-threaded programming is not easy for most, even with the most coherent and reliable API, there are different things to think about, and many misconceptions. The PHP group do not wish for user land multi-threading to be a core feature, it has never been given serious attention - and rightly so. PHP should not be complex, for everyone.

All things considered, there are still benefits to be had from allowing PHP to utilize it's production ready and tested features to allow a means of making the most out of what we have, when adding more isn't always an option, and for a lot of tasks is never really needed.

pthreads achieves, for those wishing to explore it, an API that does allow a user to multi-thread PHP applications. It's API is very much a work in progress, and designated a beta level of stability and completeness.

It is common knowledge that some of the libraries PHP uses are not thread safe, it should be clear to the programmer that pthreads cannot change this, and does not attempt to try. However, any library that is thread safe is useable, as in any other thread safe setup of the interpreter.

pthreads utilizes Posix Threads ( even in Windows ), what the programmer creates are real threads of execution, but for those threads to be useful, they must be aware of PHP - able to execute user code, share variables and allow a useful means of communication ( synchronization ). So every thread is created with an instance of the interpreter, but by design, it's interpreter is isolated from all other instances of the interpreter - just like multi-threaded Server API environments. pthreads attempts to bridge the gap in a sane and safe way. Many of the concerns of the programmer of threads in C just aren't there for the programmer of pthreads, by design, pthreads is copy on read and copy on write ( RAM is cheap ), so no two instances ever manipulate the same physical data, but they can both affect data in another thread. The fact that PHP may use thread unsafe features in it's core programming is entirely irrelevant, user threads, and it's operations are completely safe.

Why copy on read and copy on write:

public function run() {
    ...
    (1) $this->data = $data;
    ...
    (2) $this->other = someOperation($this->data);
    ...
}

(3) echo preg_match($pattern, $replace, $thread->data);

(1) While a read, and write lock are held on the pthreads object data store, data is copied from its original location in memory to the object store. pthreads does not adjust the refcount of the variable, Zend is able to free the original data if there are no further references to it.

(2) The argument to someOperation references the object store, the original data stored, which it itself a copy of the result of (1), is copied again for the engine into a zval container, while this occurs a read lock is held on the object store, the lock is released and the engine can execute the function. When the zval is created, it has a refcount of 0, enabling the engine to free the copy on completion of the operation, because no other references to it exist.

(3) The last argument to preg_match references the data store, a read lock is obtained, the data set in (1) is copied to a zval, again with a refcount of 0. The lock is released, The call to preg_match operates on a copy of data, that is itself a copy of the original data.

Things to know:

  • The object store's hash table where data is stored, thread safe, is
    based on the TsHashTable shipped with PHP, by Zend.

  • The object store has a read and write lock, an additional access lock is provided for the TsHashTable such that if requires ( and it does, var_dump/print_r, direct access to properties as the PHP engine wants to reference them ) pthreads can manipulate the TsHashTable outside of the defined API.

  • The locks are only held while the copying operations occur, when the copies have been made the locks are released, in a sensible order.

This means:

  • When a write occurs, not only are a read and write lock held, but an additional access lock. The table itself is locked down, there is no possible way another context can lock, read, write or affect it.

  • When a read occurs, not only is the read lock held, but the additional access lock too, again the table is locked down.

No two contexts can physically nor concurrently access the same data from the object store, but writes made in any context with a reference will affect the data read in any context with a reference.

This is shared nothing architecture and the only way to exist is co-exist. Those a bit savvy will see that, there's a lot of copying going on here, and they will wonder if that is a good thing. Quite a lot of copying goes on within a dynamic runtime, that's the dynamics of a dynamic language. pthreads is implemented at the level of the object, because good control can be gained over one object, but methods - the code the programmer executes - have another context, free of locking and copies - the local method scope. The object scope in the case of a pthreads object should be treated as a way to share data among contexts, that is it's purpose. With this in mind you can adopt techniques to avoid locking the object store unless it's necessary, such as passing local scope variables to other methods in a threaded object rather than having them copy from the object store upon execution.

Most of the libraries and extensions available for PHP are thin wrappers around 3rd parties, PHP core functionality to a degree is the same thing. pthreads is not a thin wrapper around Posix Threads; it is a threading API based on Posix Threads. There is no point in implementing Threads in PHP that it's users do not understand or cannot use. There's no reason that a person with no knowledge of what a mutex is or does should not be able to take advantage of all that they have, both in terms of skill, and resources. An object functions like an object, but wherever two contexts would otherwise collide, pthreads provides stability and safety.

Anyone who has worked in java will see the similarities between a pthreads object and threading in java, those same people will have no doubt seen an error called ConcurrentModificationException - as it sounds an error raised by the java runtime if two threads write the same physical data concurrently. I understand why it exists, but it baffles me that with resources as cheap as they are, coupled with the fact the runtime is able to detect the concurrency at the exact and only time that safety could be achieved for the user, that it chooses to throw a possibly fatal error at runtime rather than manage the execution and access to the data.

No such stupid errors will be emitted by pthreads, the API is written to make threading as stable, and compatible as is possible, I believe.

Multi-threading isn't like using a new database, close attention should be paid to every word in the manual and examples shipped with pthreads.

Lastly, from the PHP manual:

pthreads was, and is, an experiment with pretty good results. Any of its limitations or features may change at any time; that is the nature of experimentation. It's limitations - often imposed by the implementation - exist for good reason; the aim of pthreads is to provide a useable solution to multi-tasking in PHP at any level. In the environment which pthreads executes, some restrictions and limitations are necessary in order to provide a stable environment.

What are the rules about using an underscore in a C++ identifier?

The rules (which did not change in C++11):

  • Reserved in any scope, including for use as implementation macros:
    • identifiers beginning with an underscore followed immediately by an uppercase letter
    • identifiers containing adjacent underscores (or "double underscore")
  • Reserved in the global namespace:
    • identifiers beginning with an underscore
  • Also, everything in the std namespace is reserved. (You are allowed to add template specializations, though.)

From the 2003 C++ Standard:

17.4.3.1.2 Global names [lib.global.names]

Certain sets of names and function signatures are always reserved to the implementation:

  • Each name that contains a double underscore (__) or begins with an underscore followed by an uppercase letter (2.11) is reserved to the implementation for any use.
  • Each name that begins with an underscore is reserved to the implementation for use as a name in the global namespace.165

165) Such names are also reserved in namespace ::std (17.4.3.1).

Because C++ is based on the C standard (1.1/2, C++03) and C99 is a normative reference (1.2/1, C++03) these also apply, from the 1999 C Standard:

7.1.3 Reserved identifiers

Each header declares or defines all identifiers listed in its associated subclause, and optionally declares or defines identifiers listed in its associated future library directions subclause and identifiers which are always reserved either for any use or for use as file scope identifiers.

  • All identifiers that begin with an underscore and either an uppercase letter or another underscore are always reserved for any use.
  • All identifiers that begin with an underscore are always reserved for use as identifiers with file scope in both the ordinary and tag name spaces.
  • Each macro name in any of the following subclauses (including the future library directions) is reserved for use as specified if any of its associated headers is included; unless explicitly stated otherwise (see 7.1.4).
  • All identifiers with external linkage in any of the following subclauses (including the future library directions) are always reserved for use as identifiers with external linkage.154
  • Each identifier with file scope listed in any of the following subclauses (including the future library directions) is reserved for use as a macro name and as an identifier with file scope in the same name space if any of its associated headers is included.

No other identifiers are reserved. If the program declares or defines an identifier in a context in which it is reserved (other than as allowed by 7.1.4), or defines a reserved identifier as a macro name, the behavior is undefined.

If the program removes (with #undef) any macro definition of an identifier in the first group listed above, the behavior is undefined.

154) The list of reserved identifiers with external linkage includes errno, math_errhandling, setjmp, and va_end.

Other restrictions might apply. For example, the POSIX standard reserves a lot of identifiers that are likely to show up in normal code:

  • Names beginning with a capital E followed a digit or uppercase letter:
    • may be used for additional error code names.
  • Names that begin with either is or to followed by a lowercase letter
    • may be used for additional character testing and conversion functions.
  • Names that begin with LC_ followed by an uppercase letter
    • may be used for additional macros specifying locale attributes.
  • Names of all existing mathematics functions suffixed with f or l are reserved
    • for corresponding functions that operate on float and long double arguments, respectively.
  • Names that begin with SIG followed by an uppercase letter are reserved
    • for additional signal names.
  • Names that begin with SIG_ followed by an uppercase letter are reserved
    • for additional signal actions.
  • Names beginning with str, mem, or wcs followed by a lowercase letter are reserved
    • for additional string and array functions.
  • Names beginning with PRI or SCN followed by any lowercase letter or X are reserved
    • for additional format specifier macros
  • Names that end with _t are reserved
    • for additional type names.

While using these names for your own purposes right now might not cause a problem, they do raise the possibility of conflict with future versions of that standard.


Personally I just don't start identifiers with underscores. New addition to my rule: Don't use double underscores anywhere, which is easy as I rarely use underscore.

After doing research on this article I no longer end my identifiers with _t as this is reserved by the POSIX standard.

The rule about any identifier ending with _t surprised me a lot. I think that is a POSIX standard (not sure yet) looking for clarification and official chapter and verse. This is from the GNU libtool manual, listing reserved names.

CesarB provided the following link to the POSIX 2004 reserved symbols and notes 'that many other reserved prefixes and suffixes ... can be found there'. The POSIX 2008 reserved symbols are defined here. The restrictions are somewhat more nuanced than those above.

Change jsp on button click

You have several options, I'll start from the easiest:

1- Change the input buttons to links, you can style them with css so they look like buttons:

<a href="CreateCourse.jsp">Creazione Nuovo Corso</a>

instead of

<input type="button" value="Creazione Nuovo Corso" name="CreateCourse" />

2- Use javascript to change the action of the form depending on the button you click:

<input type="button" value="Creazione Nuovo Corso" name="CreateCourse" 
onclick="document.forms[0].action = 'CreateCourse.jsp'; return true;" />

3- Use a servlet or JSP to handle the request and redirect or forward to the appropriate JSP page.

How do I use Linq to obtain a unique list of properties from a list of objects?

Using straight Linq, with the Distinct() extension:

var idList = (from x in yourList select x.ID).Distinct();

How to determine if a point is in a 2D triangle?

I just want to use some simple vector math to explain the barycentric coordinates solution which Andreas had given, it will be way easier to understand.

  1. Area A is defined as any vector given by s * v02 + t * v01, with condition s >= 0 and t >= 0. If any point inside the triangle v0, v1, v2, it must be inside Area A.

enter image description here

  1. If further restrict s, and t belongs to [0, 1]. We get Area B which contains all vectors of s * v02 + t * v01, with condition s, t belongs to [0, 1]. It is worth to note that the low part of the Area B is the mirror of Triangle v0, v1, v2. The problem comes to if we can give certain condition of s, and t, to further excluding the low part of Area B.

enter image description here

  1. Assume we give a value s, and t is changing in [0, 1]. In the following pic, point p is on the edge of v1v2. All the vectors of s * v02 + t * v01 which are along the dash line by simple vector sum. At v1v2 and dash line cross point p, we have:

(1-s)|v0v2| / |v0v2| = tp|v0v1| / |v0v1|

we get 1 - s = tp, then 1 = s + tp. If any t > tp, which 1 < s + t where is on the double dash line, the vector is outside the triangle, any t <= tp, which 1 >= s + t where is on single dash line, the vector is inside the triangle.

Then if we given any s in [0, 1], the corresponding t must meet 1 >= s + t, for the vector inside triangle.

enter image description here

So finally we get v = s * v02 + t * v01, v is inside triangle with condition s, t, s+t belongs to [0, 1]. Then translate to point, we have

p - p0 = s * (p1 - p0) + t * (p2 - p0), with s, t, s + t in [0, 1]

which is the same as Andreas' solution to solve equation system p = p0 + s * (p1 - p0) + t * (p2 - p0), with s, t, s + t belong to [0, 1].

Java: Add elements to arraylist with FOR loop where element name has increasing number

why you need a for-loop for this? the solution is very obvious:

answers.add(answer1);
answers.add(answer2);
answers.add(answer3);

that's it. no for-loop needed.

Definitive way to trigger keypress events with jQuery

console.log( String.fromCharCode(event.charCode) );

no need to map character i guess.

how to implement a long click listener on a listview

You have to set setOnItemLongClickListener() in the ListView:

lv.setOnItemLongClickListener(new OnItemLongClickListener() {
            @Override
            public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
                    int pos, long id) {
                // TODO Auto-generated method stub

                Log.v("long clicked","pos: " + pos);

                return true;
            }
        }); 

The XML for each item in the list (should you use a custom XML) must have android:longClickable="true" as well (or you can use the convenience method lv.setLongClickable(true);). This way you can have a list with only some items responding to longclick.

Hope this will help you.

How to delay the .keyup() handler until the user stops typing?

Use the bindWithDelay jQuery plugin:

element.bindWithDelay(eventType, [ eventData ], handler(eventObject), timeout, throttle)

How to insert element into arrays at specific position?

In case you are just looking to insert an item into an array at a certain position (based on @clausvdb answer):

function array_insert($arr, $insert, $position) {
    $i = 0;
    $ret = array();
    foreach ($arr as $key => $value) {
            if ($i == $position) {
                $ret[] = $insert;
            }
            $ret[] = $value;
            $i++;
    }
    return $ret;
}

How do I view the Explain Plan in Oracle Sql developer?

We use Oracle PL/SQL Developer(Version 12.0.7). And we use F5 button to view the explain plan.

Java code for getting current time

Just to inform for furthers developers, and thankfully to Basil Bourque, I just wanna add my stone to this topic.

If you want simply get the HH:MM:SS format then do this:

LocalTime hour = ZonedDateTime.now().toLocalTime().truncatedTo(ChronoUnit.SECONDS);

Cheers.

P.S.: This will work only at least with Java 8 !

Bootstrap Modal Backdrop Remaining

Workaround is to hide the backdrop entirely if you don't need one like this: data-backdrop=""

<div class="modal fade preview-modal" data-backdrop="" id="preview-modal"  role="dialog" aria-labelledby="preview-modal" aria-hidden="true">

biggest integer that can be stored in a double

9007199254740992 (that's 9,007,199,254,740,992) with no guarantees :)

Program

#include <math.h>
#include <stdio.h>

int main(void) {
  double dbl = 0; /* I started with 9007199254000000, a little less than 2^53 */
  while (dbl + 1 != dbl) dbl++;
  printf("%.0f\n", dbl - 1);
  printf("%.0f\n", dbl);
  printf("%.0f\n", dbl + 1);
  return 0;
}

Result

9007199254740991
9007199254740992
9007199254740992

How to make a JSON call to a url?

It seems they offer a js option for the format parameter, which will return JSONP. You can retrieve JSONP like so:

function getJSONP(url, success) {

    var ud = '_' + +new Date,
        script = document.createElement('script'),
        head = document.getElementsByTagName('head')[0] 
               || document.documentElement;

    window[ud] = function(data) {
        head.removeChild(script);
        success && success(data);
    };

    script.src = url.replace('callback=?', 'callback=' + ud);
    head.appendChild(script);

}

getJSONP('http://soundcloud.com/oembed?url=http%3A//soundcloud.com/forss/flickermood&format=js&callback=?', function(data){
    console.log(data);
});  

CSS: Center block, but align contents to the left

First, create a parent div that centers its child content with text-align: center. Next, create a child div that uses display: inline-block to adapt to the width of its children and text-align: left to make the content it holds align to the left as desired.

_x000D_
_x000D_
<div style="text-align: center;">_x000D_
    <div style="display: inline-block; text-align: left;">_x000D_
        Centered<br />_x000D_
        Content<br />_x000D_
        That<br />_x000D_
        Is<br />_x000D_
        Left<br />_x000D_
        Aligned_x000D_
    </div>_x000D_
</div>
_x000D_
_x000D_
_x000D_

Switch role after connecting to database

--create a user that you want to use the database as:

create role neil;

--create the user for the web server to connect as:

create role webgui noinherit login password 's3cr3t';

--let webgui set role to neil:

grant neil to webgui; --this looks backwards but is correct.

webgui is now in the neil group, so webgui can call set role neil . However, webgui did not inherit neil's permissions.

Later, login as webgui:

psql -d some_database -U webgui
(enter s3cr3t as password)

set role neil;

webgui does not need superuser permission for this.

You want to set role at the beginning of a database session and reset it at the end of the session. In a web app, this corresponds to getting a connection from your database connection pool and releasing it, respectively. Here's an example using Tomcat's connection pool and Spring Security:

public class SetRoleJdbcInterceptor extends JdbcInterceptor {

    @Override
    public void reset(ConnectionPool connectionPool, PooledConnection pooledConnection) {

        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();

        if(authentication != null) {
            try {

                /* 
                  use OWASP's ESAPI to encode the username to avoid SQL Injection. Can't use parameters with SET ROLE. Need to write PG codec.

                  Or use a whitelist-map approach
                */
                String username = ESAPI.encoder().encodeForSQL(MY_CODEC, authentication.getName());

                Statement statement = pooledConnection.getConnection().createStatement();
                statement.execute("set role \"" + username + "\"");
                statement.close();
            } catch(SQLException exp){
                throw new RuntimeException(exp);
            }
        }
    }

    @Override
    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {

        if("close".equals(method.getName())){
            Statement statement = ((Connection)proxy).createStatement();
            statement.execute("reset role");
            statement.close();
        }

        return super.invoke(proxy, method, args);
    }
}

How to change the color of a button?

The RIGHT way...

The following methods actually work.

if you wish - using a theme
By default a buttons color is android:colorAccent. So, if you create a style like this...

<style name="Button.White" parent="ThemeOverlay.AppCompat">
    <item name="colorAccent">@android:color/white</item>
</style>

You can use it like this...

<Button
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:theme="@style/Button.White"
    />

alternatively - using a tint
You can simply add android:backgroundTint for API Level 21 and higher, or app:backgroundTint for API Level 7 and higher.

For more information, see this blog.

The problem with the accepted answer...

If you replace the background with a color you will loose the effect of the button, and the color will be applied to the entire area of the button. It will not respect the padding, shadow, and corner radius.

How to upgrade PostgreSQL from version 9.6 to version 10.1 without losing data?

I think this is best link for your solution to update postgres to 9.6

https://sandymadaan.wordpress.com/2017/02/21/upgrade-postgresql9-3-9-6-in-ubuntu-retaining-the-databases/

Can't install any package with node npm

I had this issue, and doing npm cache clean solved it.

Python: List vs Dict for look up table

You want a dict.

For (unsorted) lists in Python, the "in" operation requires O(n) time---not good when you have a large amount of data. A dict, on the other hand, is a hash table, so you can expect O(1) lookup time.

As others have noted, you might choose a set (a special type of dict) instead, if you only have keys rather than key/value pairs.

Related:

  • Python wiki: information on the time complexity of Python container operations.
  • SO: Python container operation time and memory complexities

Forbidden You don't have permission to access / on this server

WORKING Method { if there is no problem other than configuration }

By Default Appache is not restricting access from ipv4. (common external ip)

What may restrict is the configurations in 'httpd.conf' (or 'apache2.conf' depending on your apache configuration)

Solution:

Replace all:

<Directory />
     AllowOverride none
    Require all denied

</Directory>

with

<Directory />
     AllowOverride none
#    Require all denied

</Directory>

hence removing out all restriction given to Apache

Replace Require local with Require all granted at C:/wamp/www/ directory

<Directory "c:/wamp/www/">
    Options Indexes FollowSymLinks
    AllowOverride all
    Require all granted
#   Require local
</Directory>

Check for false

You can use something simpler:

if(!var){
    console.log('var is false'); 
}

Remove specific characters from a string in Python

line = line.translate(None, " ?.!/;:")

How can I get Maven to stop attempting to check for updates for artifacts from a certain group from maven-central-repo?

I had some trouble similar to this,

<repository>
    <id>java.net</id>
    <url>https://maven-repository.dev.java.net/nonav/repository</url>
    <layout>legacy</layout>
</repository>
<repository>
    <id>java.net2</id>
    <url>https://maven2-repository.dev.java.net/nonav/repository</url>
</repository>

Setting the updatePolicy to "never" did not work. Removing these repo was the way I solved it. ps: I was following this tutorial about web services (btw, probably the best tutorial for ws for java)

scp copy directory to another server with private key auth

Covert .ppk to id_rsa using tool PuttyGen, (http://mydailyfindingsit.blogspot.in/2015/08/create-keys-for-your-linux-machine.html) and

scp -C -i ./id_rsa -r /var/www/* [email protected]:/var/www

it should work !

Java - Abstract class to contain variables?

Sure.. Why not?
Abstract base classes are just a convenience to house behavior and data common to 2 or more classes in a single place for efficiency of storage and maintenance. Its an implementation detail.
Take care however that you are not using an abstract base class where you should be using an interface. Refer to Interface vs Base class

Migration: Cannot add foreign key constraint

Be aware: when Laravel sets up a table using

$table->increments('id');

which is standard in most migrations, this will set up an unsigned integer field. Therefore when making a foreign reference from another table to this field, ensure that in the referencing table, you set the field to UnsignedInteger and not (what I'd assumed to be an) UnsignedBigInteger field.

For example: in the migration file 2018_12_12_123456_create_users_table.php:

Schema::create('users', function (Blueprint $table){
    $table->increments('id');
    $table->string('name');
    $table->timestamps();

Then in the migration file 2018_12_12_18000000_create_permissions_table.php, which sets up the foreign reference back to users:

Schema::create('permissions', function (Blueprint $table){
    $table->increments('id');
    $table->UnsignedInteger('user_id'); // UnsignedInteger = "increments" in users table
    $table->boolean('admin');
    $table->boolean('enabled');
    $table->timestamps();

    // set up relationship
    $table->foreign('user_id')->reference('id')->on('users')->onDelete('cascade');
}

Check if url contains string with JQuery

Use Window.location.href to take the url in javascript. it's a property that will tell you the current URL location of the browser. Setting the property to something different will redirect the page.

if (window.location.href.indexOf("?added-to-cart=555") > -1) {
    alert("found it");
}

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

replace:

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

with:

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

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


You can use addEventListener too.

How to unzip a list of tuples into individual lists?

If you want a list of lists:

>>> [list(t) for t in zip(*l)]
[[1, 3, 8], [2, 4, 9]]

If a list of tuples is OK:

>>> zip(*l)
[(1, 3, 8), (2, 4, 9)]

Width of input type=text element

The visible width of an element is width + padding + border + outline, so it seems that you are forgetting about the border on the input element. That is, to say, that the default border width for an input element on most (some?) browsers is actually calculated as 2px, not one. Hence your input is appearing as 2px wider. Try explicitly setting the border-width on the input, or making your div wider.

Convert to date format dd/mm/yyyy

If your date is in the format of a string use the explode function

    array explode ( string $delimiter , string $string [, int $limit ] )
//In the case of your code

$length = strrpos($oldDate," ");
$newDate = explode( "-" , substr($oldDate,$length));
$output = $newDate[2]."/".$newDate[1]."/".$newDate[0];

Hope the above works now

How to develop Android app completely using python?

To answer your first question: yes it is feasible to develop an android application in pure python, in order to achieve this I suggest you use BeeWare, which is just a suite of python tools, that work together very well and they enable you to develop platform native applications in python.

checkout this video by the creator of BeeWare that perfectly explains and demonstrates it's application

How it works

Android's preferred language of implementation is Java - so if you want to write an Android application in Python, you need to have a way to run your Python code on a Java Virtual Machine. This is what VOC does. VOC is a transpiler - it takes Python source code, compiles it to CPython Bytecode, and then transpiles that bytecode into Java-compatible bytecode. The end result is that your Python source code files are compiled directly to a Java .class file, which can be packaged into an Android application.

VOC also allows you to access native Java objects as if they were Python objects, implement Java interfaces with Python classes, and subclass Java classes with Python classes. Using this, you can write an Android application directly against the native Android APIs.

Once you've written your native Android application, you can use Briefcase to package your Python code as an Android application.

Briefcase is a tool for converting a Python project into a standalone native application. You can package projects for:

  • Mac
  • Windows
  • Linux
  • iPhone/iPad
  • Android
  • AppleTV
  • tvOS.

You can check This native Android Tic Tac Toe app written in Python, using the BeeWare suite. on GitHub

in addition to the BeeWare tools, you'll need to have a JDK and Android SDK installed to test run your application.

and to answer your second question: a good environment can be anything you are comfortable with be it a text editor and a command line, or an IDE, if you're looking for a good python IDE I would suggest you try Pycharm, it has a community edition which is free, and it has a similar environment as android studio, due to to the fact that were made by the same company.

I hope this has been helpful

Eclipse No tests found using JUnit 5 caused by NoClassDefFoundError for LauncherFactory

adding org.junit.platform to your pom and build it. Next, you need to go to "Run Configuration" of your TEST FILE and add JUNIT in the classpath, APPLY->RUN will resolve the issue.

What could cause java.lang.reflect.InvocationTargetException?

The exception is thrown if

InvocationTargetException - if the underlying method throws an exception.

So if the method, that has been invoked with reflection API, throws an exception (runtime exception for example), the reflection API will wrap the exception into an InvocationTargetException.

SSH -L connection successful, but localhost port forwarding not working "channel 3: open failed: connect failed: Connection refused"

Just replace localhost with 127.0.0.1.

(The answer is based on answers of other people on this page.)

Passing base64 encoded strings in URL

Its a base64url encode you can try out, its just extension of joeshmo's code above.

function base64url_encode($data) {
return rtrim(strtr(base64_encode($data), '+/', '-_'), '=');
}

function base64url_decode($data) {
return base64_decode(str_pad(strtr($data, '-_', '+/'), strlen($data) % 4, '=', STR_PAD_RIGHT));
}

How do I deal with installing peer dependencies in Angular CLI?

You can ignore the peer dependency warnings by using the --force flag with Angular cli when updating dependencies.

ng update @angular/cli @angular/core --force

For a full list of options, check the docs: https://angular.io/cli/update

How to stop INFO messages displaying on spark console?

Adding the following to the PySpark did the job for me:

self.spark.sparkContext.setLogLevel("ERROR")

self.spark is the spark session (self.spark = spark_builder.getOrCreate())

Bootstrap datepicker disabling past dates without current date

_x000D_
_x000D_
var nowDate = new Date();_x000D_
var today = new Date(nowDate.getFullYear(), nowDate.getMonth(), nowDate.getDate(), 0, 0, 0, 0);_x000D_
 $('#date').datetimepicker({_x000D_
  startDate: today_x000D_
 });
_x000D_
_x000D_
_x000D_

subtract time from date - moment js

Michael Richardson's solution is great. If you would like to subtract dates (because Google will point you here if you search for it), you could also say:

var date1 = moment( "2014-06-07 00:03:00" );
var date2 = moment( "2014-06-07 09:22:00" );

differenceInMs = date2.diff(date1); // diff yields milliseconds
duration = moment.duration(differenceInMs); // moment.duration accepts ms
differenceInMinutes = duration.asMinutes(); // if you would like to have the output 559

Best way to retrieve variable values from a text file?

The other solutions posted here didn't work for me, because:

  • i just needed parameters from a file for a normal script
  • import * didn't work for me, as i need a way to override them by choosing another file
  • Just a file with a dict wasn't fine, as I needed comments in it.

So I ended up using Configparser and globals().update()

Test file:

#File parametertest.cfg:
[Settings]
#Comments are no Problem
test= True
bla= False    #Here neither

#that neither

And that's my demo script:

import ConfigParser

cfg = ConfigParser.RawConfigParser()
cfg.read('parametertest.cfg')       # Read file

#print cfg.getboolean('Settings','bla') # Manual Way to acess them

par=dict(cfg.items("Settings"))
for p in par:
    par[p]=par[p].split("#",1)[0].strip() # To get rid of inline comments

globals().update(par)  #Make them availible globally

print bla

It's just for a file with one section now, but that will be easy to adopt.

Hope it will be helpful for someone :)

Undefined reference to pthread_create in Linux

In Anjuta, go to the Build menu, then Configure Project. In the Configure Options box, add:

LDFLAGS='-lpthread'

Hope it'll help somebody too...

Change Bootstrap input focus blue glow

For Bootstrap v4.0.0 beta release you will need the following added to a stylesheet that overrides Bootstrap (either add in after CDN/local link to bootstrap v4.0.0 beta or add !important to the stylings:

.form-control:focus {
  border-color: #6265e4 !important;
  box-shadow: 0 0 5px rgba(98, 101, 228, 1) !important;
}

Replace the border-color and the rgba on the box-shadow with which ever colour style you'd like*.

Cast Object to Generic Type for returning

I stumble upon this question and it grabbed my interest. The accepted answer is completely correct, but I thought I do provide my findings at JVM byte code level to explain why the OP encounter the ClassCastException.

I have the code which is pretty much the same as OP's code:

public static <T> T convertInstanceOfObject(Object o) {
    try {
       return (T) o;
    } catch (ClassCastException e) {
        return null;
    }
}

public static void main(String[] args) {
    String k = convertInstanceOfObject(345435.34);
    System.out.println(k);
}

and the corresponding byte code is:

public static <T> T convertInstanceOfObject(java.lang.Object);
    Code:
       0: aload_0
       1: areturn
       2: astore_1
       3: aconst_null
       4: areturn
    Exception table:
       from    to  target type
           0     1     2   Class java/lang/ClassCastException

  public static void main(java.lang.String[]);
    Code:
       0: ldc2_w        #3                  // double 345435.34d
       3: invokestatic  #5                  // Method java/lang/Double.valueOf:(D)Ljava/lang/Double;
       6: invokestatic  #6                  // Method convertInstanceOfObject:(Ljava/lang/Object;)Ljava/lang/Object;
       9: checkcast     #7                  // class java/lang/String
      12: astore_1
      13: getstatic     #8                  // Field java/lang/System.out:Ljava/io/PrintStream;
      16: aload_1
      17: invokevirtual #9                  // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      20: return

Notice that checkcast byte code instruction happens in the main method not the convertInstanceOfObject and convertInstanceOfObject method does not have any instruction that can throw ClassCastException. Because the main method does not catch the ClassCastException hence when you execute the main method you will get a ClassCastException and not the expectation of printing null.

Now I modify the code to the accepted answer:

public static <T> T convertInstanceOfObject(Object o, Class<T> clazz) {
        try {
            return clazz.cast(o);
        } catch (ClassCastException e) {
            return null;
        }
    }
    public static void main(String[] args) {
        String k = convertInstanceOfObject(345435.34, String.class);
        System.out.println(k);
    }

The corresponding byte code is:

public static <T> T convertInstanceOfObject(java.lang.Object, java.lang.Class<T>);
    Code:
       0: aload_1
       1: aload_0
       2: invokevirtual #2                  // Method java/lang/Class.cast:(Ljava/lang/Object;)Ljava/lang/Object;
       5: areturn
       6: astore_2
       7: aconst_null
       8: areturn
    Exception table:
       from    to  target type
           0     5     6   Class java/lang/ClassCastException

  public static void main(java.lang.String[]);
    Code:
       0: ldc2_w        #4                  // double 345435.34d
       3: invokestatic  #6                  // Method java/lang/Double.valueOf:(D)Ljava/lang/Double;
       6: ldc           #7                  // class java/lang/String
       8: invokestatic  #8                  // Method convertInstanceOfObject:(Ljava/lang/Object;Ljava/lang/Class;)Ljava/lang/Object;
      11: checkcast     #7                  // class java/lang/String
      14: astore_1
      15: getstatic     #9                  // Field java/lang/System.out:Ljava/io/PrintStream;
      18: aload_1
      19: invokevirtual #10                 // Method java/io/PrintStream.println:(Ljava/lang/String;)V
      22: return

Notice that there is an invokevirtual instruction in the convertInstanceOfObject method that calls Class.cast() method which throws ClassCastException which will be catch by the catch(ClassCastException e) bock and return null; hence, "null" is printed to console without any exception.

How do you change text to bold in Android?

in file .xml, set

android:textStyle="bold" 

will set text type is bold.

kubectl apply vs kubectl create?

kubectl create can work with one object configuration file at a time. This is also known as imperative management

kubectl create -f filename|url

kubectl apply works with directories and its sub directories containing object configuration yaml files. This is also known as declarative management. Multiple object configuration files from directories can be picked up. kubectl apply -f directory/

Details :
https://kubernetes.io/docs/tasks/manage-kubernetes-objects/declarative-config/ https://kubernetes.io/docs/tasks/manage-kubernetes-objects/imperative-config/

Adding a collaborator to my free GitHub account?

2020 update

It's called Manage access now.

Go to your private repo, click the Settings tab, and choose Manage access from the menu on the left. You are allowed up to three collaborators with the free plan.

Note: If the account is an individual account you can still add collaborators that can do a variety of tasks, but a collaborator can't (as far as I know) sign the app in Xcode and submit it to the app store. You need an organization account for that kind of collaborator.

jQuery first child of "this"

element.children().first();

Find all children and get first of them.

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

I had the same problem as you. After a long time spent Googling, I found out my error was caused by multiple users that had added the same key in their accounts.

So, here is my solution: delete the wrong-user's ssh-key (I can do it because the wrong-user is also my account). If the wrong-user isn't your account, you may need to change your ssh-key, but I don't think this gonna happen.

And I think your problem may be caused by a mistyping error in your accounts name.

MySQL string replace

You can simply use replace() function,

with where clause-

update tabelName set columnName=REPLACE(columnName,'from','to') where condition;

without where clause-

update tabelName set columnName=REPLACE(columnName,'from','to');

Note: The above query if for update records directly in table, if you want on select query and the data should not be affected in table then can use the following query-

select REPLACE(columnName,'from','to') as updateRecord;

Plotting time in Python with Matplotlib

I had trouble with this using matplotlib version: 2.0.2. Running the example from above I got a centered stacked set of bubbles.

graph with centered stack of bubbles

I "fixed" the problem by adding another line:

plt.plot([],[])

The entire code snippet becomes:

import datetime
import random
import matplotlib.pyplot as plt
import matplotlib.dates as mdates


# make up some data
x = [datetime.datetime.now() + datetime.timedelta(minutes=i) for i in range(12)]
y = [i+random.gauss(0,1) for i,_ in enumerate(x)]

# plot
plt.plot([],[])
plt.scatter(x,y)

# beautify the x-labels
plt.gcf().autofmt_xdate()
myFmt = mdates.DateFormatter('%H:%M')
plt.gca().xaxis.set_major_formatter(myFmt)

plt.show()
plt.close()

This produces an image with the bubbles distributed as desired.

graph with bubbles distributed over time

How to call getClass() from a static method in Java?

As for the code example in the question, the standard solution is to reference the class explicitly by its name, and it is even possible to do without getClassLoader() call:

class MyClass {
  public static void startMusic() {
    URL songPath = MyClass.class.getResource("background.midi");
  }
}

This approach still has a back side that it is not very safe against copy/paste errors in case you need to replicate this code to a number of similar classes.

And as for the exact question in the headline, there is a trick posted in the adjacent thread:

Class currentClass = new Object() { }.getClass().getEnclosingClass();

It uses a nested anonymous Object subclass to get hold of the execution context. This trick has a benefit of being copy/paste safe...

Caution when using this in a Base Class that other classes inherit from:

It is also worth noting that if this snippet is shaped as a static method of some base class then currentClass value will always be a reference to that base class rather than to any subclass that may be using that method.

Is calling destructor manually always a sign of bad design?

No, Depends on the situation, sometimes it is legitimate and good design.

To understand why and when you need to call destructors explicitly, let's look at what happening with "new" and "delete".

To created an object dynamically, T* t = new T; under the hood: 1. sizeof(T) memory is allocated. 2. T's constructor is called to initialize the allocated memory. The operator new does two things: allocation and initialization.

To destroy the object delete t; under the hood: 1. T's destructor is called. 2. memory allocated for that object is released. the operator delete also does two things: destruction and deallocation.

One writes the constructor to do initialization, and destructor to do destruction. When you explicitly call the destructor, only the destruction is done, but not the deallocation.

A legitimate use of explicitly calling destructor, therefore, could be, "I only want to destruct the object, but I don't (or can't) release the memory allocation (yet)."

A common example of this, is pre-allocating memory for a pool of certain objects which otherwise have to be allocated dynamically.

When creating a new object, you get the chunk of memory from the pre-allocated pool and do a "placement new". After done with the object, you may want to explicitly call the destructor to finish the cleanup work, if any. But you won't actually deallocate the memory, as the operator delete would have done. Instead, you return the chunk to the pool for reuse.

How to get first character of string?

charAt do not work if it has a parent prop
ex parent.child.chartAt(0)
use parent.child.slice(0, 1)

Random number between 0 and 1 in python

You can use random.uniform

import random
random.uniform(0, 1)

Can we make unsigned byte in Java

Although it may seem annoying (coming from C) that Java did not include unsigned byte in the language it really is no big deal since a simple "b & 0xFF" operation yields the unsigned value for (signed) byte b in the (rare) situations that it is actually needed. The bits don't actually change -- just the interpretation (which is important only when doing for example some math operations on the values).

How to cin to a vector

#include<iostream>
#include<vector>
#include<string>
using namespace std;
int main()
{
    vector<string>V;
    int num;
    cin>>num;
    string input;
    while (cin>>input && num != 0) //enter any non-integer to end the loop!
{
    //cin>>input;
   V.push_back(input);
   num--;
   if(num==0)
   {
   vector<string>::iterator it;
    for(it=V.begin();it!=V.end();it++)
        cout<<*it<<endl;
   };

}
return 0;

};

Getting absolute URLs using ASP.NET Core

I just discovered you can do it with this call:

Url.Action(new UrlActionContext
{
    Protocol = Request.Scheme,
    Host = Request.Host.Value,
    Action = "Action"
})

This will maintain the scheme, host, port, everything.

Correctly Parsing JSON in Swift 3

I built quicktype exactly for this purpose. Just paste your sample JSON and quicktype generates this type hierarchy for your API data:

struct Forecast {
    let hourly: Hourly
    let daily: Daily
    let currently: Currently
    let flags: Flags
    let longitude: Double
    let latitude: Double
    let offset: Int
    let timezone: String
}

struct Hourly {
    let icon: String
    let data: [Currently]
    let summary: String
}

struct Daily {
    let icon: String
    let data: [Datum]
    let summary: String
}

struct Datum {
    let precipIntensityMax: Double
    let apparentTemperatureMinTime: Int
    let apparentTemperatureLowTime: Int
    let apparentTemperatureHighTime: Int
    let apparentTemperatureHigh: Double
    let apparentTemperatureLow: Double
    let apparentTemperatureMaxTime: Int
    let apparentTemperatureMax: Double
    let apparentTemperatureMin: Double
    let icon: String
    let dewPoint: Double
    let cloudCover: Double
    let humidity: Double
    let ozone: Double
    let moonPhase: Double
    let precipIntensity: Double
    let temperatureHigh: Double
    let pressure: Double
    let precipProbability: Double
    let precipIntensityMaxTime: Int
    let precipType: String?
    let sunriseTime: Int
    let summary: String
    let sunsetTime: Int
    let temperatureMax: Double
    let time: Int
    let temperatureLow: Double
    let temperatureHighTime: Int
    let temperatureLowTime: Int
    let temperatureMin: Double
    let temperatureMaxTime: Int
    let temperatureMinTime: Int
    let uvIndexTime: Int
    let windGust: Double
    let uvIndex: Int
    let windBearing: Int
    let windGustTime: Int
    let windSpeed: Double
}

struct Currently {
    let precipProbability: Double
    let humidity: Double
    let cloudCover: Double
    let apparentTemperature: Double
    let dewPoint: Double
    let ozone: Double
    let icon: String
    let precipIntensity: Double
    let temperature: Double
    let pressure: Double
    let precipType: String?
    let summary: String
    let uvIndex: Int
    let windGust: Double
    let time: Int
    let windBearing: Int
    let windSpeed: Double
}

struct Flags {
    let sources: [String]
    let isdStations: [String]
    let units: String
}

It also generates dependency-free marshaling code to coax the return value of JSONSerialization.jsonObject into a Forecast, including a convenience constructor that takes a JSON string so you can quickly parse a strongly typed Forecast value and access its fields:

let forecast = Forecast.from(json: jsonString)!
print(forecast.daily.data[0].windGustTime)

You can install quicktype from npm with npm i -g quicktype or use the web UI to get the complete generated code to paste into your playground.

How do I make a self extract and running installer

It's simple with open source 7zip SFX-Packager - easy way to just "Drag & drop" folders onto it, and it creates a portable/self-extracting package.

Extract matrix column values by matrix column name

> myMatrix <- matrix(1:10, nrow=2)
> rownames(myMatrix) <- c("A", "B")
> colnames(myMatrix) <- c("A", "B", "C", "D", "E")

> myMatrix
  A B C D  E
A 1 3 5 7  9
B 2 4 6 8 10

> myMatrix["A", "A"]
[1] 1

> myMatrix["A", ]
A B C D E 
1 3 5 7 9 

> myMatrix[, "A"]
A B 
1 2 

Moment JS start and end of given month

When you use .endOf() you are mutating the object it's called on, so startDate becomes Sep 30

You should use .clone() to make a copy of it instead of changing it

var startDate = moment(year + '-' + month + '-' + 01 + ' 00:00:00');
            var endDate = startDate.clone().endOf('month');
            console.log(startDate.toDate());
            console.log(endDate.toDate());

Mon Sep 01 2014 00:00:00 GMT+0700 (ICT) 
Tue Sep 30 2014 23:59:59 GMT+0700 (ICT) 

Using curl to upload POST data with files

You need to use the -F option:
-F/--form <name=content> Specify HTTP multipart POST data (H)

Try this:

curl \
  -F "userid=1" \
  -F "filecomment=This is an image file" \
  -F "image=@/home/user1/Desktop/test.jpg" \
  localhost/uploader.php

How to sort an array in descending order in Ruby

Just a quick thing, that denotes the intent of descending order.

descending = -1
a.sort_by { |h| h[:bar] * descending }

(Will think of a better way in the mean time) ;)


a.sort_by { |h| h[:bar] }.reverse!

How to upload (FTP) files to server in a bash script?

#/bin/bash
# $1 is the file name
# usage: this_script  <filename>
IP_address="xx.xxx.xx.xx"
username="username"
domain=my.ftp.domain
password=password

echo "
 verbose
 open $IP_address
 USER $username $password
 put $1
 bye
" | ftp -n > ftp_$$.log

window.history.pushState refreshing the browser

As others have suggested, you are not clearly explaining your problem, what you are trying to do, or what your expectations are as to what this function is actually supposed to do.

If I have understood correctly, then you are expecting this function to refresh the page for you (you actually use the term "reloads the browser").

But this function is not intended to reload the browser.

All the function does, is to add (push) a new "state" onto the browser history, so that in future, the user will be able to return to this state that the web-page is now in.

Normally, this is used in conjunction with AJAX calls (which refresh only a part of the page).

For example, if a user does a search "CATS" in one of your search boxes, and the results of the search (presumably cute pictures of cats) are loaded back via AJAX, into the lower-right of your page -- then your page state will not be changed. In other words, in the near future, when the user decides that he wants to go back to his search for "CATS", he won't be able to, because the state doesn't exist in his history. He will only be able to click back to your blank search box.

Hence the need for the function

history.pushState({},"Results for `Cats`",'url.html?s=cats');

It is intended as a way to allow the programmer to specifically define his search into the user's history trail. That's all it is intended to do.

When the function is working properly, the only thing you should expect to see, is the address in your browser's address-bar change to whatever you specify in your URL.

If you already understand this, then sorry for this long preamble. But it sounds from the way you pose the question, that you have not.

As an aside, I have also found some contradictions between the way that the function is described in the documentation, and the way it works in reality. I find that it is not a good idea to use blank or empty values as parameters.

See my answer to this SO question. So I would recommend putting a description in your second parameter. From memory, this is the description that the user sees in the drop-down, when he clicks-and-holds his mouse over "back" button.

Android basics: running code in the UI thread

As of Android P you can use getMainExecutor():

getMainExecutor().execute(new Runnable() {
  @Override public void run() {
    // Code will run on the main thread
  }
});

From the Android developer docs:

Return an Executor that will run enqueued tasks on the main thread associated with this context. This is the thread used to dispatch calls to application components (activities, services, etc).

From the CommonsBlog:

You can call getMainExecutor() on Context to get an Executor that will execute its jobs on the main application thread. There are other ways of accomplishing this, using Looper and a custom Executor implementation, but this is simpler.

How to unescape a Java string literal in Java?

Java 13 added a method which does this: String#translateEscapes.

It was a preview feature in Java 13 and 14, but was promoted to a full feature in Java 15.

How to loop through elements of forms with JavaScript?

A modern ES6 approach. Select the form with any method you like. Use the spread operator to convert HTMLFormControlsCollection to an Array, then the forEach method is available. [...form.elements].forEach

Update: Array.from is a nicer alternative to spread Array.from(form.elements) it's slightly clearer behaviour.


An example below iterates over every input in the form. You can filter out certain input types by checking input.type != "submit"

_x000D_
_x000D_
const forms = document.querySelectorAll('form');
const form = forms[0];

Array.from(form.elements).forEach((input) => {
  console.log(input);
});
_x000D_
<div>
  <h1>Input Form Selection</h1>
  <form>
    <label>
      Foo
      <input type="text" placeholder="Foo" name="Foo" />
    </label>
    <label>
      Password
      <input type="password" placeholder="Password" />
    </label>
    <label>
      Foo
      <input type="text" placeholder="Bar" name="Bar" />
    </label>
    <span>Ts &amp; Cs</span>
    <input type="hidden" name="_id" />
    <input type="submit" name="_id" />
  </form>
</div>
_x000D_
_x000D_
_x000D_

String Comparison in Java

Comparing sequencially the letters that have the same position against each other.. more like how you order words in a dictionary

Is there a difference between using a dict literal and a dict constructor?

the dict() literal is nice when you are copy pasting values from something else (none python) For example a list of environment variables. if you had a bash file, say

FOO='bar'
CABBAGE='good'

you can easily paste then into a dict() literal and add comments. It also makes it easier to do the opposite, copy into something else. Whereas the {'FOO': 'bar'} syntax is pretty unique to python and json. So if you use json a lot, you might want to use {} literals with double quotes.

How do I convert a file path to a URL in ASP.NET

I've accepted Fredriks answer as it appears to solve the problem with the least amount of effort however the Request object doesn't appear to conatin the ResolveUrl method. This can be accessed through the Page object or an Image control object:

myImage.ImageUrl = Page.ResolveUrl(photoURL);
myImage.ImageUrl = myImage.ResolveUrl(photoURL);

An alternative, if you are using a static class as I am, is to use the VirtualPathUtility:

myImage.ImageUrl = VirtualPathUtility.ToAbsolute(photoURL);

What is :: (double colon) in Python when subscripting sequences?

Python sequence slice addresses can be written as a[start:end:step] and any of start, stop or end can be dropped. a[::3] is every third element of the sequence.

How do you execute an arbitrary native command from a string?

The accepted answer wasn't working for me when trying to parse the registry for uninstall strings, and execute them. Turns out I didn't need the call to Invoke-Expression after all.

I finally came across this nice template for seeing how to execute uninstall strings:

$path = 'HKLM:\SOFTWARE\Wow6432Node\Microsoft\Windows\CurrentVersion\Uninstall'
$app = 'MyApp'
$apps= @{}
Get-ChildItem $path | 
    Where-Object -FilterScript {$_.getvalue('DisplayName') -like $app} | 
    ForEach-Object -process {$apps.Set_Item(
        $_.getvalue('UninstallString'),
        $_.getvalue('DisplayName'))
    }

foreach ($uninstall_string in $apps.GetEnumerator()) {
    $uninstall_app, $uninstall_arg = $uninstall_string.name.split(' ')
    & $uninstall_app $uninstall_arg
}

This works for me, namely because $app is an in house application that I know will only have two arguments. For more complex uninstall strings you may want to use the join operator. Also, I just used a hash-map, but really, you'd probably want to use an array.

Also, if you do have multiple versions of the same application installed, this uninstaller will cycle through them all at once, which confuses MsiExec.exe, so there's that too.

How to Sort Multi-dimensional Array by Value?

Use array_multisort(), array_map()

array_multisort(array_map(function($element) {
      return $element['order'];
  }, $array), SORT_ASC, $array);

print_r($array);

DEMO

zsh compinit: insecure directories

I got the same warnings when I sudo -i starting a root shell, @chakrit's solution didn't work for me.

But I found -u switch of compinit works, e.g. in your .zshrc/zshenv or where you called compinit

compinit -u

NB: Not recommended for production system

See also http://zsh.sourceforge.net/Doc/Release/Completion-System.html#Initialization

DevTools failed to load SourceMap: Could not load content for chrome-extension

You need to open chrome in developper mode : select more tools then extensions and select developper mode

What is an application binary interface (ABI)?

One easy way to understand "ABI" is to compare it to "API".

You are already familiar with the concept of an API. If you want to use the features of, say, some library or your OS, you will program against an API. The API consists of data types/structures, constants, functions, etc that you can use in your code to access the functionality of that external component.

An ABI is very similar. Think of it as the compiled version of an API (or as an API on the machine-language level). When you write source code, you access the library through an API. Once the code is compiled, your application accesses the binary data in the library through the ABI. The ABI defines the structures and methods that your compiled application will use to access the external library (just like the API did), only on a lower level. Your API defines the order in which you pass arguments to a function. Your ABI defines the mechanics of how these arguments are passed (registers, stack, etc.). Your API defines which functions are part of your library. Your ABI defines how your code is stored inside the library file, so that any program using your library can locate the desired function and execute it.

ABIs are important when it comes to applications that use external libraries. Libraries are full of code and other resources, but your program has to know how to locate what it needs inside the library file. Your ABI defines how the contents of a library are stored inside the file, and your program uses the ABI to search through the file and find what it needs. If everything in your system conforms to the same ABI, then any program is able to work with any library file, no matter who created them. Linux and Windows use different ABIs, so a Windows program won't know how to access a library compiled for Linux.

Sometimes, ABI changes are unavoidable. When this happens, any programs that use that library will not work unless they are re-compiled to use the new version of the library. If the ABI changes but the API does not, then the old and new library versions are sometimes called "source compatible". This implies that while a program compiled for one library version will not work with the other, source code written for one will work for the other if re-compiled.

For this reason, developers tend to try to keep their ABI stable (to minimize disruption). Keeping an ABI stable means not changing function interfaces (return type and number, types, and order of arguments), definitions of data types or data structures, defined constants, etc. New functions and data types can be added, but existing ones must stay the same. If, for instance, your library uses 32-bit integers to indicate the offset of a function and you switch to 64-bit integers, then already-compiled code that uses that library will not be accessing that field (or any following it) correctly. Accessing data structure members gets converted into memory addresses and offsets during compilation and if the data structure changes, then these offsets will not point to what the code is expecting them to point to and the results are unpredictable at best.

An ABI isn't necessarily something you will explicitly provide unless you are doing very low-level systems design work. It isn't language-specific either, since (for example) a C application and a Pascal application can use the same ABI after they are compiled.

Edit: Regarding your question about the chapters regarding the ELF file format in the SysV ABI docs: The reason this information is included is because the ELF format defines the interface between operating system and application. When you tell the OS to run a program, it expects the program to be formatted in a certain way and (for example) expects the first section of the binary to be an ELF header containing certain information at specific memory offsets. This is how the application communicates important information about itself to the operating system. If you build a program in a non-ELF binary format (such as a.out or PE), then an OS that expects ELF-formatted applications will not be able to interpret the binary file or run the application. This is one big reason why Windows apps cannot be run directly on a Linux machine (or vice versa) without being either re-compiled or run inside some type of emulation layer that can translate from one binary format to another.

IIRC, Windows currently uses the Portable Executable (or, PE) format. There are links in the "external links" section of that Wikipedia page with more information about the PE format.

Also, regarding your note about C++ name mangling: When locating a function in a library file, the function is typically looked up by name. C++ allows you to overload function names, so name alone is not sufficient to identify a function. C++ compilers have their own ways of dealing with this internally, called name mangling. An ABI can define a standard way of encoding the name of a function so that programs built with a different language or compiler can locate what they need. When you use extern "c" in a C++ program, you're instructing the compiler to use a standardized way of recording names that's understandable by other software.

What is the maximum possible length of a query string?

RFC 2616 (Hypertext Transfer Protocol — HTTP/1.1) states there is no limit to the length of a query string (section 3.2.1). RFC 3986 (Uniform Resource Identifier — URI) also states there is no limit, but indicates the hostname is limited to 255 characters because of DNS limitations (section 2.3.3).

While the specifications do not specify any maximum length, practical limits are imposed by web browser and server software. Based on research which is unfortunately no longer available on its original site (it leads to a shady seeming loan site) but which can still be found at Internet Archive Of Boutell.com:

  • Microsoft Internet Explorer (Browser)
    Microsoft states that the maximum length of a URL in Internet Explorer is 2,083 characters, with no more than 2,048 characters in the path portion of the URL. Attempts to use URLs longer than this produced a clear error message in Internet Explorer.

  • Microsoft Edge (Browser)
    The limit appears to be around 81578 characters. See URL Length limitation of Microsoft Edge

  • Chrome
    It stops displaying the URL after 64k characters, but can serve more than 100k characters. No further testing was done beyond that.

  • Firefox (Browser)
    After 65,536 characters, the location bar no longer displays the URL in Windows Firefox 1.5.x. However, longer URLs will work. No further testing was done after 100,000 characters.

  • Safari (Browser)
    At least 80,000 characters will work. Testing was not tried beyond that.

  • Opera (Browser)
    At least 190,000 characters will work. Stopped testing after 190,000 characters. Opera 9 for Windows continued to display a fully editable, copyable and pasteable URL in the location bar even at 190,000 characters.

  • Apache (Server)
    Early attempts to measure the maximum URL length in web browsers bumped into a server URL length limit of approximately 4,000 characters, after which Apache produces a "413 Entity Too Large" error. The current up to date Apache build found in Red Hat Enterprise Linux 4 was used. The official Apache documentation only mentions an 8,192-byte limit on an individual field in a request.

  • Microsoft Internet Information Server (Server)
    The default limit is 16,384 characters (yes, Microsoft's web server accepts longer URLs than Microsoft's web browser). This is configurable.

  • Perl HTTP::Daemon (Server)
    Up to 8,000 bytes will work. Those constructing web application servers with Perl's HTTP::Daemon module will encounter a 16,384 byte limit on the combined size of all HTTP request headers. This does not include POST-method form data, file uploads, etc., but it does include the URL. In practice this resulted in a 413 error when a URL was significantly longer than 8,000 characters. This limitation can be easily removed. Look for all occurrences of 16x1024 in Daemon.pm and replace them with a larger value. Of course, this does increase your exposure to denial of service attacks.

Select2() is not a function

In my case, I was getting this error in my rails app when both webpacker and sprockets were trying to import jQuery. I didn't notice it until my code editor automatically tried to import jQuery into a webpacker module.

How to use "not" in xpath?

None of these answers worked for me for python. I solved by this

a[not(@id='XX')]

Also you can use or condition in your xpath by | operator. Such as

a[not(@id='XX')]|a[not(@class='YY')]

Sometimes we want element which has no class. So you can do like

a[not(@class)]

C# DLL config file

if you want to read settings from the DLL's config file but not from the the root applications web.config or app.config use below code to read configuration in the dll.

var appConfig = ConfigurationManager.OpenExeConfiguration(Assembly.GetExecutingAssembly().Location);
string dllConfigData = appConfig.AppSettings.Settings["dllConfigData"].Value;

Ruby: How to iterate over a range, but in set increments?

Here's another, perhaps more familiar-looking way to do it:

for i in (0..10).step(2) do
    puts i
end

Test only if variable is not null in if statement

I don't believe the expression is sensical as it is.

Elvis means "if truthy, use the value, else use this other thing."

Your "other thing" is a closure, and the value is status != null, neither of which would seem to be what you want. If status is null, Elvis says true. If it's not, you get an extra layer of closure.

Why can't you just use:

(it.description == desc) && ((status == null) || (it.status == status))

Even if that didn't work, all you need is the closure to return the appropriate value, right? There's no need to create two separate find calls, just use an intermediate variable.

How to convert a structure to a byte array in C#?

You can use Marshal (StructureToPtr, ptrToStructure), and Marshal.copy but this is plataform dependent.


Serialization includes Functions to Custom Serialization.

public virtual void GetObjectData(SerializationInfo info, StreamingContext context)
Protected Sub New(ByVal info As SerializationInfo, ByVal context As StreamingContext) 

SerializationInfo include functions to serialize each member.


BinaryWriter and BinaryReader also contains methods to Save / Load to Byte Array (Stream).

Note that you can create a MemoryStream from a Byte Array or a Byte Array from a MemoryStream.

You can create a method Save and a method New on your structure:

   Save(Bw as BinaryWriter)
   New (Br as BinaryReader)

Then you select members to Save / Load to Stream -> Byte Array.

Error java.lang.OutOfMemoryError: GC overhead limit exceeded

Rebooting my MacBook fixed this issue for me.

How to stop PHP code execution?

Please see the following information from user Pekka ?

According to the manual, destructors are executed even if the script gets terminated using die() or exit():

The destructor will be called even if script execution is stopped using exit(). Calling exit() in a destructor will prevent the remaining shutdown routines from executing.
According to this PHP: destructor vs register_shutdown_function, the destructor does not get executed when PHP's execution time limit is reached (Confirmed on Apache 2, PHP 5.2 on Windows 7).

The destructor also does not get executed when the script terminates because the memory limit was reached. (Just tested)

The destructor does get executed on fatal errors (Just tested) Update: The OP can't confirm this - there seem to be fatal errors where things are different

It does not get executed on parse errors (because the whole script won't be interpreted)

The destructor will certainly not be executed if the server process crashes or some other exception out of PHP's control occurs.

Referenced in this question Are there any instances when the destructor in PHP is NOT called?

MySQL SELECT LIKE or REGEXP to match multiple words in one record

Assuming that your search is stylus photo 2100. Try the following example is using RLIKE.

SELECT * FROM `buckets` WHERE `bucketname` RLIKE REPLACE('stylus photo 2100', ' ', '+.*');

EDIT

Another way is to use FULLTEXT index on bucketname and MATCH ... AGAINST syntax in your SELECT statement. So to re-write the above example...

SELECT * FROM `buckets` WHERE MATCH(`bucketname`) AGAINST (REPLACE('stylus photo 2100', ' ', ','));

How to check whether a select box is empty using JQuery/Javascript

Another correct way to get selected value would be using this selector:

$("option[value="0"]:selected")

Best for you!

how to replace characters in hive?

select translate(description,'\\t','') from myTable;

Translates the input string by replacing the characters present in the from string with the corresponding characters in the to string. This is similar to the translate function in PostgreSQL. If any of the parameters to this UDF are NULL, the result is NULL as well. (Available as of Hive 0.10.0, for string types)

Char/varchar support added as of Hive 0.14.0

How can I disable a button in a jQuery dialog from a function?

I got this working with the method .dialog("widget") which returns the dialog DIV itself. If you're in the dialog methods:

$(this)
.dialog("widget")
.find("button")
.addClass("ui-state-disabled") // for the style
.attr("disabled", true);

Changing the row height of a datagridview

You also need to change the resizable property to true

    dataGridView1.RowTemplate.Resizable = DataGridViewTriState.True;
    dataGridView1.RowTemplate.Height = 50;

Share data between html pages

possibly if you want to just transfer data to be used by JavaScript then you can use Hash Tags like this

http://localhost/project/index.html#exist

so once when you are done retriving the data show the message and change the window.location.hash to a suitable value.. now whenever you ll refresh the page the hashtag wont be present
NOTE: when you will use this instead ot query strings the data being sent cannot be retrived/read by the server

Reloading a ViewController

Reinitialise the view controller

YourViewController *vc = [[YourViewController alloc] initWithNibName:@"YourViewControllerIpad" bundle:nil];
[self.navigationController vc animated:NO];

CSS: transition opacity on mouse-out?

$(window).scroll(function() {    
    $('.logo_container, .slogan').css({
        "opacity" : ".1",
        "transition" : "opacity .8s ease-in-out"
    });
});

Check the fiddle: http://jsfiddle.net/2k3hfwo0/2/

Git: "Corrupt loose object"

Looks like you have a corrupt tree object. You will need to get that object from someone else. Hopefully they will have an uncorrupted version.

You could actually reconstruct it if you can't find a valid version from someone else by guessing at what files should be there. You may want to see if the dates & times of the objects match up to it. Those could be the related blobs. You could infer the structure of the tree object from those objects.

Take a look at Scott Chacon's Git Screencasts regarding git internals. This will show you how git works under the hood and how to go about doing this detective work if you are really stuck and can't get that object from someone else.

Get filename from file pointer

You can get the path via fp.name. Example:

>>> f = open('foo/bar.txt')
>>> f.name
'foo/bar.txt'

You might need os.path.basename if you want only the file name:

>>> import os
>>> f = open('foo/bar.txt')
>>> os.path.basename(f.name)
'bar.txt'

File object docs (for Python 2) here.

how to open *.sdf files?

If you simply need to view the table and run queries on it you can use this third party sdf viewer. It is a lightweight viewer that has all the basic functionalities and is ready to use after install.

and ofcourse, its Free.

In Node.js, how do I "include" functions from my other files?

say we wants to call function ping() and add(30,20) which is in lib.js file from main.js

main.js

lib = require("./lib.js")

output = lib.ping();
console.log(output);

//Passing Parameters
console.log("Sum of A and B = " + lib.add(20,30))

lib.js

this.ping=function ()
{
    return  "Ping Success"
}
//Functions with parameters
this.add=function(a,b)
    {
        return a+b
    }

Call an angular function inside html

Yep, just add parenthesis (calling the function). Make sure the function is in scope and actually returns something.

<ul class="ui-listview ui-radiobutton" ng-repeat="meter in meters">
  <li class = "ui-divider">
    {{ meter.DESCRIPTION }}
    {{ htmlgeneration() }}
  </li>
</ul>

How to convert list of key-value tuples into dictionary?

>>> dict([('A', 1), ('B', 2), ('C', 3)])
{'A': 1, 'C': 3, 'B': 2}

How to disable Google Chrome auto update?

For latest versions, use following steps:

  1. Go to "msconfig" from Win+R
  2. Go to Service tab
  3. Uncheck both "Google Update Service" boxes.
  4. Click OK and Restart computer to save changes.

Blade if(isset) is not working Laravel

{{ $usersType or '' }} is working fine. The problem here is your foreach loop:

@foreach( $usersType as $type )
    <input type="checkbox" class='default-checkbox'> <span>{{ $type->type }}</span> &nbsp; 
@endforeach

I suggest you put this in an @if():

@if(isset($usersType))
    @foreach( $usersType as $type )
        <input type="checkbox" class='default-checkbox'> <span>{{ $type->type }}</span> &nbsp; 
    @endforeach
@endif

You can also use @forelse. Simple and easy.

@forelse ($users as $user)
   <li>{{ $user->name }}</li>
@empty
   <p>No users</p>
@endforelse

How to add not null constraint to existing column in MySQL

Would like to add:

After update, such as

ALTER TABLE table_name modify column_name tinyint(4) NOT NULL;

If you get

ERROR 1138 (22004): Invalid use of NULL value

Make sure you update the table first to have values in the related column (so it's not null)

How to install pandas from pip on windows cmd?

pip install pandas make sure, this is 'pandas' not 'panda'

If you are not able to access pip, then got to C:\Python37\Scripts and run pip.exe install pandas.

Alternatively, you can add C:\Python37\Scripts in the env variables for windows machines. Hope this helps.

How do you get the cursor position in a textarea?

Here's a cross browser function I have in my standard library:

function getCursorPos(input) {
    if ("selectionStart" in input && document.activeElement == input) {
        return {
            start: input.selectionStart,
            end: input.selectionEnd
        };
    }
    else if (input.createTextRange) {
        var sel = document.selection.createRange();
        if (sel.parentElement() === input) {
            var rng = input.createTextRange();
            rng.moveToBookmark(sel.getBookmark());
            for (var len = 0;
                     rng.compareEndPoints("EndToStart", rng) > 0;
                     rng.moveEnd("character", -1)) {
                len++;
            }
            rng.setEndPoint("StartToStart", input.createTextRange());
            for (var pos = { start: 0, end: len };
                     rng.compareEndPoints("EndToStart", rng) > 0;
                     rng.moveEnd("character", -1)) {
                pos.start++;
                pos.end++;
            }
            return pos;
        }
    }
    return -1;
}

Use it in your code like this:

var cursorPosition = getCursorPos($('#myTextarea')[0])

Here's its complementary function:

function setCursorPos(input, start, end) {
    if (arguments.length < 3) end = start;
    if ("selectionStart" in input) {
        setTimeout(function() {
            input.selectionStart = start;
            input.selectionEnd = end;
        }, 1);
    }
    else if (input.createTextRange) {
        var rng = input.createTextRange();
        rng.moveStart("character", start);
        rng.collapse();
        rng.moveEnd("character", end - start);
        rng.select();
    }
}

http://jsfiddle.net/gilly3/6SUN8/

Git undo changes in some files

Why can't you simply mark what changes you want to have in a commit using "git add <file>" (or even "git add --interactive", or "git gui" which has option for interactive comitting), and then use "git commit" instead of "git commit -a"?

In your situation (for your example) it would be:

prompt> git add B
prompt> git commit

Only changes to file B would be comitted, and file A would be left "dirty", i.e. with those print statements in the working area version. When you want to remove those print statements, it would be enought to use

prompt> git reset A

or

prompt> git checkout HEAD -- A

to revert to comitted version (version from HEAD, i.e. "git show HEAD:A" version).

Convert date time string to epoch in Bash

For Linux Run this command

date -d '06/12/2012 07:21:22' +"%s"

For mac OSX run this command

date -j -u -f "%a %b %d %T %Z %Y" "Tue Sep 28 19:35:15 EDT 2010" "+%s"

Core dump file analysis

You just need a binary (with debugging symbols included) that is identical to the one that generated the core dump file. Then you can run gdb path/to/the/binary path/to/the/core/dump/file to debug it.

When it starts up, you can use bt (for backtrace) to get a stack trace from the time of the crash. In the backtrace, each function invocation is given a number. You can use frame number (replacing number with the corresponding number in the stack trace) to select a particular stack frame.

You can then use list to see code around that function, and info locals to see the local variables. You can also use print name_of_variable (replacing "name_of_variable" with a variable name) to see its value.

Typing help within GDB will give you a prompt that will let you see additional commands.

How do I generate random number for each row in a TSQL Select?

Update my_table set my_field = CEILING((RAND(CAST(NEWID() AS varbinary)) * 10))

Number between 1 and 10.

How should the ViewModel close the form?

You could have the ViewModel expose an event that the View registers to. Then, when the ViewModel decides its time to close the view, it fires that event which causes the view to close. If you want a specific result value passed back, then you would have a property in the ViewModel for that.

Razor Views not seeing System.Web.Mvc.HtmlHelper

I ran into this issue with a Web Application - my .cshtml files got stuck on the System.Web.WebPages.WebViewPage base class when I needed the System.Web.Mvc.WebViewPage.

First, ensure your ~/Views/web.config file has the correct pageBaseType. In my case, I set to System.Web.Mvc.WebViewPage.

<configuration>
  <system.web.webPages.razor>
    <pages pageBaseType="System.Web.Mvc.WebViewPage">
      <!-- ... -->
    </pages>
  </system.web.webPages.razor>
</configuration>

Then, importantly, some people have found this is key if the above is already good:

  1. Run a clean on the solution
  2. Unload the project with the issues
  3. Delete the .user file that Visual Studio generated next to the project.
  4. Reload the project with the issues
  5. Build the solution

For VS2015, the .user and .sln files have moved to the .vs hidden folder that is created next to the .sln file. However, from comments below, the error messages imply to me that the tooling is using the wrong version of MVC entirely, and deleting this folder does not fix the issue. To my knowledge, there is not a known solution.

get enum name from enum value

What you can do is

RelationActiveEnum ae = Enum.valueOf(RelationActiveEnum.class,
                                     RelationActiveEnum.ACTIVE.name();

or

RelationActiveEnum ae = RelationActiveEnum.valueOf(
                                     RelationActiveEnum.ACTIVE.name();

or

// not recommended as the ordinal might not match the value
RelationActiveEnum ae = RelationActiveEnum.values()[
                                     RelationActiveEnum.ACTIVE.value];

By if you want to lookup by a field of an enum you need to construct a collection such as a List, an array or a Map.

public enum RelationActiveEnum {
    Invited(0),
    Active(1),
    Suspended(2);

    private final int code;

    private RelationActiveEnum(final int code) {
        this.code = code;
    }

    private static final Map<Integer, RelationActiveEnum> BY_CODE_MAP = new LinkedHashMap<>();
    static {
        for (RelationActiveEnum rae : RelationActiveEnum.values()) {
            BY_CODE_MAP.put(rae.code, rae);
        }
    }

    public static RelationActiveEnum forCode(int code) {
        return BY_CODE_MAP.get(code);
    }
}

allows you to write

String name = RelationActiveEnum.forCode(RelationActiveEnum.ACTIVE.code).name();

System.Net.WebException HTTP status code

I'm not sure if there is but if there was such a property it wouldn't be considered reliable. A WebException can be fired for reasons other than HTTP error codes including simple networking errors. Those have no such matching http error code.

Can you give us a bit more info on what you're trying to accomplish with that code. There may be a better way to get the information you need.

Batch files - number of command line arguments

The last answer was two years ago now, but I needed a version for more than nine command line arguments. May be another one also does...

@echo off
setlocal

set argc_=1
set arg0_=%0
set argv_=

:_LOOP
set arg_=%1
if defined arg_ (
  set arg%argc_%_=%1
  set argv_=%argv_% %1
  set /a argc_+=1
  shift
  goto _LOOP
)
::dont count arg0
set /a argc_-=1
echo %argc_% arg(s)

for /L %%i in (0,1,%argc_%) do (
  call :_SHOW_ARG arg%%i_ %%arg%%i_%%
)

echo converted to local args
call :_LIST_ARGS %argv_%
exit /b


:_LIST_ARGS
setlocal
set argc_=0
echo arg0=%0

:_LOOP_LIST_ARGS
set arg_=%1
if not defined arg_ exit /b
set /a argc_+=1
call :_SHOW_ARG arg%argc_% %1
shift
goto _LOOP_LIST_ARGS


:_SHOW_ARG
echo %1=%2
exit /b

The solution is the first 19 lines and converts all arguments to variables in a c-like style. All other stuff just probes the result and shows conversion to local args. You can reference arguments by index in any function.

How to pass password automatically for rsync SSH command?

If you can't use a public/private keys, you can use expect:

#!/usr/bin/expect
spawn rsync SRC DEST
expect "password:"
send "PASS\n"
expect eof
if [catch wait] {
    puts "rsync failed"
    exit 1
}
exit 0

You will need to replace SRC and DEST with your normal rsync source and destination parameters, and replace PASS with your password. Just make sure this file is stored securely!

What is callback in Android?

It was discussed before here.

In computer programming, a callback is a piece of executable code that is passed as an argument to other code, which is expected to call back (execute) the argument at some convenient time. The invocation may be immediate as in a synchronous callback or it might happen at later time, as in an asynchronous callback.

Changing Java Date one hour back

Use Calendar.

Calendar cal = Calendar.getInstance();

cal.setTime(new Date());
cal.set(Calendar.HOUR, cal.get(Calendar.HOUR) - 1);

Send a ping to each IP on a subnet

Under linux, I think ping -b 192.168.1.255 will work (192.168.1.255 is the broadcast address for 192.168.1.*) however IIRC that doesn't work under windows.