Programs & Examples On #Ethernet

Ethernet is a set of networking technologies widely used to interconnect computers.

Hook up Raspberry Pi via Ethernet to laptop without router?

No router + no screen + regular Ethernet cable + RPI 2 + Raspbian Lite 2018-11-13 + Ubuntu 18.10

First we must enable the SSH server on the Pi, which is disabled by default for security.

If you already have a shell on the Pi through a non-SSH method such as screen + keyboard or UART (see below), just run:

sudo systemctl enable ssh
sudo service sshd start

as explained at: https://raspberrypi.stackexchange.com/questions/58478/ssh-not-working-with-fresh-install This persists across boots.

Otherwise, insert he SD card on your host, and create a magic empty file named ssh file in the boot/ partition.

On Ubuntu hosts, it gets mounted automatically and you can do just:

sudo touch /media/$USER/boot/ssh

which you can confirm with:

lsblk

which contains:

mmcblk0     179:0    0  14.4G  0 disk
+-mmcblk0p1 179:1    0  43.9M  0 part /media/ciro/boot
+-mmcblk0p2 179:2    0  14.4G  0 part /media/ciro/rootfs

If you don't enable the SSHD daemon on the Pi then SSH connection will fail with:

ssh: connect to host 10.42.0.160 port 22: Connection refused

when we try it later on.

After enabling the SSH server

Next, boot the Pi, and link an Ethernet cable from your laptop directly to the Pi:

enter image description here

On Ubuntu 17.04 to work around this bug as mentioned on this answer you first need:

sudo apt-get install dnsmasq-base

On the host, open the network manager:

nm-connection-editor

And go:

  1. + sign (Add a new connection)
  2. Ethernet
  3. Create
  4. IPv4 Settings
  5. Method: Shared to other computers
  6. Set a good name for it
  7. Save

enter image description here

Find the IP of the Pi on host:

cat /var/lib/misc/dnsmasq.leases

outputs something like:

1532204957 b8:27:eb:0c:1f:69 10.42.0.160 raspberrypi 01:b8:27:eb:0c:1f:69

10.42.0.160 is the IP, then as usual:

ssh [email protected]

I also have the following in my .bashrc:

piip() ( cat /var/lib/misc/dnsmasq.leases | cut -d ' ' -f 3; )
pissh() ( sshpass -p raspberry ssh "pi@$(piip)"; )

From inside the Pi, notice that it can access the internet normally through your host's other interfaces:

ping google.com

For example on my laptop, the Pi takes up the Ethernet, but the host is also connected to the internet through WiFi.

The crossover cable is not required if the host network card supports Auto MDI-X. This is the case for most recent hardware, including for example the 2012 Lenovo T430 I tested with, which has an "Intel® 82579LM Gigabit Network Connection" which documents support for Auto MDI-X.

Now you can also:

UART serial USB converter

This is an alternative to SSH if you just want to get a shell on the Pi: https://en.wikipedia.org/wiki/Serial_port

This does not use SSH or networking itself, but rather the older, simpler, more direct, more reliable, lower bandwidth, lower distance serial interface. The Pi won't have access to the Internet with this method.

Desktop computers still have a serial port which you can connect directly wire to wire with the Pi, but these are hidden in most laptops, and so we need to buy a cheap USB adapter. Here I've used: https://www.amazon.co.uk/gp/product/B072K3Z3TL See also: https://unix.stackexchange.com/questions/307390/what-is-the-difference-between-ttys0-ttyusb0-and-ttyama0-in-linux/367882#367882

First plug the SD card on the host, and edit the config.txt file present in the first partition to add:

enable_uart=1

as explained at: https://www.raspberrypi.org/forums/viewtopic.php?f=28&t=141195

This first partition contains the bootloader, its configuration files and the (Linux / your) kernel, config.txt being one of them. The second partition contains the actual Linux root filesystem.

Now connect your computer to the Pi as:

enter image description here

You only need to attach 3 cables:

  • Ground to Ground
  • Tx on Pi to Rx on the USB to serial port
  • Rx on Pi to Tx on tye USB to serial port

This is also documented at: https://www.raspberrypi.org/documentation/usage/gpio/README.md

Be careful not to link the Ground to the 5V, I've already burned 2 UART to USB chips and a RPI UART by doing that!

You don't need to connect the 5V to the 5V at all. I think you can power your Pi like that, but I've read that this is a bad idea, just use the usual USB power source.

Finally, plug the USB side of the connector to your host computer, and get a shell with:

sudo apt install screen
sudo usermod -a -G dialout $USER
screen /dev/ttyUSB0 115200

Exit with Ctrl-A \.

Here is a video by Adafruit showing it: https://www.youtube.com/watch?v=zUBPeoLW16Q

See also

Similar question on RPI SE: https://raspberrypi.stackexchange.com/questions/3867/ssh-to-rpi-without-a-network-connection

Difference between links and depends_on in docker_compose.yml

The post needs an update after the links option is deprecated.

Basically, links is no longer needed because its main purpose, making container reachable by another by adding environment variable, is included implicitly with network. When containers are placed in the same network, they are reachable by each other using their container name and other alias as host.

For docker run, --link is also deprecated and should be replaced by a custom network.

docker network create mynet
docker run -d --net mynet --name container1 my_image
docker run -it --net mynet --name container1 another_image

depends_on expresses start order (and implicitly image pulling order), which was a good side effect of links.

Is there a list of Pytz Timezones?

You can list all the available timezones with pytz.all_timezones:

In [40]: import pytz
In [41]: pytz.all_timezones
Out[42]: 
['Africa/Abidjan',
 'Africa/Accra',
 'Africa/Addis_Ababa',
 ...]

There is also pytz.common_timezones:

In [45]: len(pytz.common_timezones)
Out[45]: 403

In [46]: len(pytz.all_timezones)
Out[46]: 563

How to prompt for user input and read command-line arguments

Use 'raw_input' for input from a console/terminal.

if you just want a command line argument like a file name or something e.g.

$ python my_prog.py file_name.txt

then you can use sys.argv...

import sys
print sys.argv

sys.argv is a list where 0 is the program name, so in the above example sys.argv[1] would be "file_name.txt"

If you want to have full on command line options use the optparse module.

Pev

Finding the number of non-blank columns in an Excel sheet using VBA

Your example code gets the row number of the last non-blank cell in the current column, and can be rewritten as follows:

Dim lastRow As Long
lastRow = Sheet1.Cells(Rows.Count, 1).End(xlUp).Row
MsgBox lastRow

It is then easy to see that the equivalent code to get the column number of the last non-blank cell in the current row is:

Dim lastColumn As Long
lastColumn = Sheet1.Cells(1, Columns.Count).End(xlToLeft).Column
MsgBox lastColumn

This may also be of use to you:

With Sheet1.UsedRange
    MsgBox .Rows.Count & " rows and " & .Columns.Count & " columns"
End With

but be aware that if column A and/or row 1 are blank, then this will not yield the same result as the other examples above. For more, read up on the UsedRange property.

How to initialize an array in one step using Ruby?

You can do

array = ['1', '2', '3']

As others have noted, you can also initialize an array with %w notation like so:

array = %w(1 2 3)

or

array = %w[1 2 3]

Please note that in both cases each element is a string, rather than an integer. So if you want an array whose elements are integers, you should not wrap each element with apostrophes:

array_of_integers = [1, 2, 3]

Also, you don't need to put comma in between the elements (which is necessary when creating an array without this %w notation). If you do this (which I often did by mistake), as in:

wrong_array = %w(1, 2, 3)

its elements will be three strings ---- "1,", "2,", "3". So if you do:

puts wrong_array

the output will be:

1,
2,
3
=>nil

which is not what we want here.

Hope this helps to clarify the point!

java.io.FileNotFoundException: class path resource cannot be opened because it does not exist

The file location/path has to relative to your classpath locations. If resources directory is in your classpath you just need "app-context.xml" as file location.

Why do we always prefer using parameters in SQL statements?

In addition to other answers need to add that parameters not only helps prevent sql injection but can improve performance of queries. Sql server caching parameterized query plans and reuse them on repeated queries execution. If you not parameterized your query then sql server would compile new plan on each query(with some exclusion) execution if text of query would differ.

More information about query plan caching

Why do you need to invoke an anonymous function on the same line?

In summary of the previous comments:

function() {
  alert("hello");
}();

when not assigned to a variable, yields a syntax error. The code is parsed as a function statement (or definition), which renders the closing parentheses syntactically incorrect. Adding parentheses around the function portion tells the interpreter (and programmer) that this is a function expression (or invocation), as in

(function() {
  alert("hello");
})();

This is a self-invoking function, meaning it is created anonymously and runs immediately because the invocation happens in the same line where it is declared. This self-invoking function is indicated with the familiar syntax to call a no-argument function, plus added parentheses around the name of the function: (myFunction)();.

There is a good SO discussion JavaScript function syntax.

What is the best way to implement constants in Java?

What is the difference

1.

public interface MyGlobalConstants {
    public static final int TIMEOUT_IN_SECS = 25;
}

2.

public class MyGlobalConstants {
    private MyGlobalConstants () {} // Prevents instantiation
    public static final int TIMEOUT_IN_SECS = 25;
}

and using MyGlobalConstants.TIMEOUT_IN_SECS wherever we need this constant. I think both are same.

How can I get date in application run by node.js?

_x000D_
_x000D_
    var datetime = new Date();_x000D_
    console.log(datetime.toISOString().slice(0,10));
_x000D_
_x000D_
_x000D_

Deserializing JSON Object Array with Json.net

Using the accepted answer you have to access each record by using Customers[i].customer, and you need an extra CustomerJson class, which is a little annoying. If you don't want to do that, you can use the following:

public class CustomerList
{
    [JsonConverter(typeof(MyListConverter))]
    public List<Customer> customer { get; set; }
}

Note that I'm using a List<>, not an Array. Now create the following class:

class MyListConverter : JsonConverter
{
    public override object ReadJson(JsonReader reader, Type objectType, object existingValue, JsonSerializer serializer)
    {
        var token = JToken.Load(reader);
        var list = Activator.CreateInstance(objectType) as System.Collections.IList;
        var itemType = objectType.GenericTypeArguments[0];
        foreach (var child in token.Values())
        {
            var childToken = child.Children().First();
            var newObject = Activator.CreateInstance(itemType);
            serializer.Populate(childToken.CreateReader(), newObject);
            list.Add(newObject);
        }
        return list;
    }

    public override bool CanConvert(Type objectType)
    {
        return objectType.IsGenericType && (objectType.GetGenericTypeDefinition() == typeof(List<>));
    }
    public override bool CanWrite => false;
    public override void WriteJson(JsonWriter writer, object value, JsonSerializer serializer) => throw new NotImplementedException();
}

"SetPropertiesRule" warning message when starting Tomcat from Eclipse

The solution to this problem is very simple. Double click on your tomcat server. It will open the server configuration. Under server options check ‘Publish module contents to separate XML files’ checkbox. Restart your server. This time your page will come without any issues.

How to change the spinner background in Android?

Android Studio has a pre-defined code, you can directly use it. android:popupBackground="HEX COLOR CODE"

Creating an Instance of a Class with a variable in Python

Let's say you have three classes: Enemy1, Enemy2, Enemy3. This is how you instantiate them directly:

Enemy1()
Enemy2()
Enemy3()

but this will also work:

x = Enemy1
x()
x = Enemy2
x()
x = Enemy3
x()

Is this what you meant?

How can I create a marquee effect?

The following should do what you want.

@keyframes marquee {
    from  { text-indent:  100% }
    to    { text-indent: -100% }
}

Simple file write function in C++

This is a place in which C++ has a strange rule. Before being able to compile a call to a function the compiler must know the function name, return value and all parameters. This can be done by adding a "prototype". In your case this simply means adding before main the following line:

int writeFile();

this tells the compiler that there exist a function named writeFile that will be defined somewhere, that returns an int and that accepts no parameters.

Alternatively you can define first the function writeFile and then main because in this case when the compiler gets to main already knows your function.

Note that this requirement of knowing in advance the functions being called is not always applied. For example for class members defined inline it's not required...

struct Foo {
    void bar() {
        if (baz() != 99) {
            std::cout << "Hey!";
        }
    }

    int baz() {
        return 42;
    }
};

In this case the compiler has no problem analyzing the definition of bar even if it depends on a function baz that is declared later in the source code.

What is the difference between \r and \n?

\r used for carriage return. (ASCII value is 13) \n used for new line. (ASCII value is 10)

checked = "checked" vs checked = true

checked attribute is a boolean value so "checked" value of other "string" except boolean false converts to true.

Any string value will be true. Also presence of attribute make it true:

<input type="checkbox" checked>

You can make it uncheked only making boolean change in DOM using JS.

So the answer is: they are equal.

w3c

Can you overload controller methods in ASP.NET MVC?

There is only one public signature allowed for each controller method. If you try to overload it, it will compile, but you're getting the run-time error you've experienced.

If you're not willing to use different verbs (like the [HttpGet] and [HttpPost] attributes) to differentiate overloaded methods (which will work), or change the routing, then what remains is that you can either provide another method with a different name, or you can dispatch inside of the existing method. Here's how I did it:

I once came into a situation where I had to maintain backwards compatibility. The original method expected two parameters, but the new one had only one. Overloading the way I expected did not work because MVC didn't find the entry point any more.

To solve that, I did the following:

  1. Changed the 2 overloaded action methods from public to private
  2. Created one new public method which contained "just" 2 string parameters. That one acted as a dispatcher, i.e.:

    public ActionResult DoSomething(string param1, string param2)
    {
        if (string.IsNullOrEmpty(param2))
        {
            return DoSomething(ProductName: param1);
        }
        else
        {
            int oldId = int.Parse(param1);
            return DoSomething(OldParam: param1, OldId: oldId);
        }
    }
    
    
    private ActionResult DoSomething(string OldParam, int OldId)
    {
        // some code here
        return Json(result);
    }
    
    
    private ActionResult DoSomething(string ProductName)
    {
        // some code here
        return Json(result);
    }
    

Of course, this is a hack and should be refactored later. But for the time being, it worked for me.

You can also create a dispatcher like:

public ActionResult DoSomething(string action, string param1, string param2)
{
    switch (action)
    {
        case "update":
            return UpdateAction(param1, param2);
        case "remove":
            return DeleteAction(param1);
    }
}

You can see, that UpdateAction needs 2 parameters, while DeleteAction just needs one.

How to show an empty view with a RecyclerView?

Since Kevin's answer is not complete.
This is more correct answer if you use RecyclerAdapter's notifyItemInserted and notifyItemRemoved to update dataset. See the Kotlin version another user added below.

Java:

mAdapter.registerAdapterDataObserver(new RecyclerView.AdapterDataObserver() {

    @Override
    public void onChanged() {
        super.onChanged();
        checkEmpty();
    }

    @Override
    public void onItemRangeInserted(int positionStart, int itemCount) {
        super.onItemRangeInserted(positionStart, itemCount);
        checkEmpty();
    }

    @Override
    public void onItemRangeRemoved(int positionStart, int itemCount) {
        super.onItemRangeRemoved(positionStart, itemCount);
        checkEmpty();
    }

    void checkEmpty() {
        mEmptyView.setVisibility(mAdapter.getItemCount() == 0 ? View.VISIBLE : View.GONE);
    }
});

Kotlin

adapter.registerAdapterDataObserver(object : RecyclerView.AdapterDataObserver() {
    override fun onChanged() {
        super.onChanged()
        checkEmpty()
    }

    override fun onItemRangeInserted(positionStart: Int, itemCount: Int) {
        super.onItemRangeInserted(positionStart, itemCount)
        checkEmpty()
    }

    override fun onItemRangeRemoved(positionStart: Int, itemCount: Int) {
        super.onItemRangeRemoved(positionStart, itemCount)
        checkEmpty()
    }

    fun checkEmpty() {
        empty_view.visibility = (if (adapter.itemCount == 0) View.VISIBLE else View.GONE)
    }
})

Any way to clear python's IDLE window?

"command + L" for MAC OS X.

"control + L" for Ubuntu

Clears the last line on the interactive session

Inserting Image Into BLOB Oracle 10g

You cannot access a local directory from pl/sql. If you use bfile, you will setup a directory (create directory) on the server where Oracle is running where you will need to put your images.

If you want to insert a handful of images from your local machine, you'll need a client side app to do this. You can write your own, but I typically use Toad for this. In schema browser, click onto the table. Click the data tab, and hit + sign to add a row. Double click the BLOB column, and a wizard opens. The far left icon will load an image into the blob:

enter image description here

SQL Developer has a similar feature. See the "Load" link below:

enter image description here

If you need to pull images over the wire, you can do it using pl/sql, but its not straight forward. First, you'll need to setup ACL list access (for security reasons) to allow a user to pull over the wire. See this article for more on ACL setup.

Assuming ACL is complete, you'd pull the image like this:

declare
    l_url varchar2(4000) := 'http://www.oracleimg.com/us/assets/12_c_navbnr.jpg';
    l_http_request   UTL_HTTP.req;
    l_http_response  UTL_HTTP.resp;
    l_raw RAW(2000);
    l_blob BLOB;
begin
   -- Important: setup ACL access list first!

    DBMS_LOB.createtemporary(l_blob, FALSE);

    l_http_request  := UTL_HTTP.begin_request(l_url);
    l_http_response := UTL_HTTP.get_response(l_http_request);

  -- Copy the response into the BLOB.
  BEGIN
    LOOP
      UTL_HTTP.read_raw(l_http_response, l_raw, 2000);
      DBMS_LOB.writeappend (l_blob, UTL_RAW.length(l_raw), l_raw);
    END LOOP;
  EXCEPTION
    WHEN UTL_HTTP.end_of_body THEN
      UTL_HTTP.end_response(l_http_response);
  END;

  insert into my_pics (pic_id, pic) values (102, l_blob);
  commit;

  DBMS_LOB.freetemporary(l_blob); 
end;

Hope that helps.

How to destroy a JavaScript object?

Structure your code so that all your temporary objects are located inside closures instead of global namespace / global object properties and go out of scope when you've done with them. GC will take care of the rest.

How to remove stop words using nltk or python

To exclude all type of stop-words including nltk stop-words, you could do something like this:

from stop_words import get_stop_words
from nltk.corpus import stopwords

stop_words = list(get_stop_words('en'))         #About 900 stopwords
nltk_words = list(stopwords.words('english')) #About 150 stopwords
stop_words.extend(nltk_words)

output = [w for w in word_list if not w in stop_words]

Parse query string into an array

If you're having a problem converting a query string to an array because of encoded ampersands

&amp;

then be sure to use html_entity_decode

Example:

// Input string //
$input = 'pg_id=2&amp;parent_id=2&amp;document&amp;video';

// Parse //
parse_str(html_entity_decode($input), $out);

// Output of $out //
array(
  'pg_id' => 2,
  'parent_id' => 2,
  'document' => ,
  'video' =>
)

Gridview get Checkbox.Checked value

You want an independent for loop for all the rows in grid view, then refer the below link

http://nikhilsreeni.wordpress.com/asp-net/checkbox/

Select all checkbox in Gridview

CheckBox cb = default(CheckBox);
for (int i = 0; i <= grdforumcomments.Rows.Count – 1; i++)
{
    cb = (CheckBox)grdforumcomments.Rows[i].Cells[0].FindControl(“cbSel”);

    cb.Checked = ((CheckBox)sender).Checked;
}

Select checked rows to a dataset; For gridview multiple edit

CheckBox cb = default(CheckBox);

foreach (GridViewRow row in grdforumcomments.Rows)
{
    cb = (CheckBox)row.FindControl("cbsel");
    if (cb.Checked)
    {
        drArticleCommentsUpdates = dtArticleCommentsUpdates.NewRow();
        drArticleCommentsUpdates["Id"] = dgItem.Cells[0].Text;
        drArticleCommentsUpdates["Date"] = System.DateTime.Now;dtArticleCommentsUpdates.Rows.Add(drArticleCommentsUpdates);
    }
}

Android : How to read file in bytes?

Since the accepted BufferedInputStream#read isn't guaranteed to read everything, rather than keeping track of the buffer sizes myself, I used this approach:

    byte bytes[] = new byte[(int) file.length()];
    BufferedInputStream bis = new BufferedInputStream(new FileInputStream(file));
    DataInputStream dis = new DataInputStream(bis);
    dis.readFully(bytes);

Blocks until a full read is complete, and doesn't require extra imports.

Custom Authentication in ASP.Net-Core

Creating custom authentication in ASP.NET Core can be done in a variety of ways. If you want to build off existing components (but don't want to use identity), checkout the "Security" category of docs on docs.asp.net. https://docs.asp.net/en/latest/security/index.html

Some articles you might find helpful:

Using Cookie Middleware without ASP.NET Identity

Custom Policy-Based Authorization

And of course, if that fails or docs aren't clear enough, the source code is at https://github.com/dotnet/aspnetcore/tree/master/src/Security which includes some samples.

Angular HttpClient "Http failure during parsing"

I had the same problem and the cause was That at time of returning a string in your backend (spring) you might be returning as return "spring used"; But this isn't parsed right according to spring. Instead use return "\" spring used \""; -Peace out

Select <a> which href ends with some string

   $('a[href$="ABC"]')...

Selector documentation can be found at http://docs.jquery.com/Selectors

For attributes:

= is exactly equal
!= is not equal
^= is starts with
$= is ends with
*= is contains
~= is contains word
|= is starts with prefix (i.e., |= "prefix" matches "prefix-...")

Junit - run set up method once

If you don't want to force a declaration of a variable that is set and checked on each subtest, then adding this to a SuperTest could do:

public abstract class SuperTest {

    private static final ConcurrentHashMap<Class, Boolean> INITIALIZED = new ConcurrentHashMap<>();
    protected final boolean initialized() {
        final boolean[] absent = {false};
        INITIALIZED.computeIfAbsent(this.getClass(), (klass)-> {
            return absent[0] = true;
        });
        return !absent[0];
    }
}



public class SubTest extends SuperTest {
    @Before
    public void before() {
        if ( super.initialized() ) return;

         ... magic ... 
    }

}

JSON order mixed up

The main intention here is to send an ordered JSON object as response. We don't need javax.json.JsonObject to achieve that. We could create the ordered json as a string. First create a LinkedHashMap with all key value pairs in required order. Then generate the json in string as shown below. Its much easier with Java 8.

public Response getJSONResponse() {
    Map<String, String> linkedHashMap = new LinkedHashMap<>();
    linkedHashMap.put("A", "1");
    linkedHashMap.put("B", "2");
    linkedHashMap.put("C", "3");

    String jsonStr = linkedHashMap.entrySet().stream()
            .map(x -> "\"" + x.getKey() + "\":\"" + x.getValue() + "\"")
            .collect(Collectors.joining(",", "{", "}"));
    return Response.ok(jsonStr).build();
}

The response return by this function would be following: {"A":"1","B":"2","C":"3"}

Cannot hide status bar in iOS7

In Info Plist file Add a row for following property

Property Name : View controller-based status bar appearance

Value : NO

Correct MIME Type for favicon.ico?

I have noticed that when using type="image/vnd.microsoft.icon", the favicon fails to appear when the browser is not connected to the internet. But type="image/x-icon" works whether the browser can connect to the internet, or not. When developing, at times I am not connected to the internet.

How to delete an instantiated object Python?

What do you mean by delete? In Python, removing a reference (or a name) can be done with the del keyword, but if there are other names to the same object that object will not be deleted.

--> test = 3
--> print(test)
3
--> del test
--> print(test)
Traceback (most recent call last):
  File "<stdin>", line 1, in <module>
NameError: name 'test' is not defined

compared to:

--> test = 5
--> other is test  # check that both name refer to the exact same object
True
--> del test       # gets rid of test, but the object is still referenced by other
--> print(other)
5

No suitable records were found verify your bundle identifier is correct

Make sure this is included in your Info.plist:

<key>CFBundlePackageType</key>
<string>APPL</string>

I had APPL misspelled as AAPL. Once I fixed that and signed into Application Loader and Xcode with the same Apple ID, everything worked.

Compiler error: memset was not declared in this scope

You should include <string.h> (or its C++ equivalent, <cstring>).

Explicitly calling return in a function or not

I think of return as a trick. As a general rule, the value of the last expression evaluated in a function becomes the function's value -- and this general pattern is found in many places. All of the following evaluate to 3:

local({
1
2
3
})

eval(expression({
1
2
3
}))

(function() {
1
2
3
})()

What return does is not really returning a value (this is done with or without it) but "breaking out" of the function in an irregular way. In that sense, it is the closest equivalent of GOTO statement in R (there are also break and next). I use return very rarely and never at the end of a function.

 if(a) {
   return(a)
 } else {
   return(b)
 }

... this can be rewritten as if(a) a else b which is much better readable and less curly-bracketish. No need for return at all here. My prototypical case of use of "return" would be something like ...

ugly <- function(species, x, y){
   if(length(species)>1) stop("First argument is too long.")
   if(species=="Mickey Mouse") return("You're kidding!")
   ### do some calculations 
   if(grepl("mouse", species)) {
      ## do some more calculations
      if(species=="Dormouse") return(paste0("You're sleeping until", x+y))
      ## do some more calculations
      return(paste0("You're a mouse and will be eating for ", x^y, " more minutes."))
      }
   ## some more ugly conditions
   # ...
   ### finally
   return("The end")
   }

Generally, the need for many return's suggests that the problem is either ugly or badly structured.

[EDIT]

return doesn't really need a function to work: you can use it to break out of a set of expressions to be evaluated.

getout <- TRUE 
# if getout==TRUE then the value of EXP, LOC, and FUN will be "OUTTA HERE"
# .... if getout==FALSE then it will be `3` for all these variables    

EXP <- eval(expression({
   1
   2
   if(getout) return("OUTTA HERE")
   3
   }))

LOC <- local({
   1
   2
   if(getout) return("OUTTA HERE")
   3
   })

FUN <- (function(){
   1
   2
   if(getout) return("OUTTA HERE")
   3
   })()

identical(EXP,LOC)
identical(EXP,FUN)

Parse JSON response using jQuery

I was hanging out on Google, then I found your question and it's very simple to parse JSON response into normal HTML. Just use this little JavaScript code:

<!DOCTYPE html>
<html>
<body>

<h2>Create Object from JSON String</h2>

<p id="demo"></p>

<script>

var obj = JSON.parse('{ "name":"John", "age":30, "city":"New York"}');
document.getElementById("demo").innerHTML = obj.name + ", " + obj.age;

</script>

</body>
</html>

Ruby 'require' error: cannot load such file

I just tried and it works with require "./tokenizer". Hope this helps.

Flask ImportError: No Module Named Flask

This is what worked for me when I got a similar error in Windows; 1. Install virtualenv

pip install virtualenve
  1. Create a virtualenv

    virtualenv flask

  2. Navigate to Scripts and activate the virtualenv

    activate

  3. Install Flask

    python -m pip install flask

  4. Check if flask is installed

    python -m pip list

Accessing AppDelegate from framework?

If you're creating a framework the whole idea is to make it portable. Tying a framework to the app delegate defeats the purpose of building a framework. What is it you need the app delegate for?

How to modify PATH for Homebrew?

open your /etc/paths file, put /usr/local/bin on top of /usr/bin

$ sudo vi /etc/paths
/usr/local/bin
/usr/local/sbin
/usr/bin
/bin
/usr/sbin
/sbin

and Restart the terminal, @mmel

How to make a UILabel clickable?

SWIFT 4 Update

 @IBOutlet weak var tripDetails: UILabel!

 override func viewDidLoad() {
    super.viewDidLoad()

    let tap = UITapGestureRecognizer(target: self, action: #selector(GameViewController.tapFunction))
    tripDetails.isUserInteractionEnabled = true
    tripDetails.addGestureRecognizer(tap)
}

@objc func tapFunction(sender:UITapGestureRecognizer) {

    print("tap working")
}

Printing *s as triangles in Java?

Find the following , it will help you to print the complete triangle.

package com.raju.arrays;

public class CompleteTriange {

public static void main(String[] args) {
    int nuberOfRows = 10;
      for(int row = 0; row<nuberOfRows;row++){

          for(int leftspace =0;leftspace<(nuberOfRows-row);leftspace++){
              System.out.print(" ");
          }
          for(int star = 0;star<2*row+1;star++){
              System.out.print("*");
          }
          for(int rightSpace =0;rightSpace<(nuberOfRows-row);rightSpace++){
              System.out.print(" ");
          }
          System.out.println("");
      }

}

}

          *          
     ***         
    *****        
   *******       
  *********      
 ***********     
*************    



One-liner if statements, how to convert this if-else-statement

If expression returns a boolean, you can just return the result of it.

Example

 return (a > b)

Vertically aligning text next to a radio button

Used to this

    input[type="radio"]{
    vertical-align:top;
    }
p{
    font-size:10px;line-height: 18px;
}

Demo

GIT fatal: ambiguous argument 'HEAD': unknown revision or path not in the working tree

Jacob Helwig mentions in his answer that:

It looks like rev-parse is being used without sufficient error checking before-hand

Commit 62f162f from Jeff King (peff) should improve the robustness of git rev-parse in Git 1.9/2.0 (Q1 2014) (in addition of commit 1418567):

For cases where we do not match (e.g., "doesnotexist..HEAD"), we would then want to try to treat the argument as a filename.
try_difference() gets this right, and always unmunges in this case.
However, try_parent_shorthand() never unmunges, leading to incorrect error messages, or even incorrect results:

$ git rev-parse foobar^@
foobar
fatal: ambiguous argument 'foobar': unknown revision or path not in the working tree.
Use '--' to separate paths from revisions, like this:
'git <command> [<revision>...] -- [<file>...]'

Div 100% height works on Firefox but not in IE

I think "works fine in Firefox" is in the Quirks mode rendering only. In the Standard mode rendering, that might not work fine in Firefox too.

percentage depends on "containing block", instead of viewport.

CSS Specification says

The percentage is calculated with respect to the height of the generated box's containing block. If the height of the containing block is not specified explicitly (i.e., it depends on content height), and this element is not absolutely positioned, the value computes to 'auto'.

so

#container { height: auto; }
#container #mainContentsWrapper { height: n%; }
#container #sidebarWrapper { height: n%; }

means

#container { height: auto; }
#container #mainContentsWrapper { height: auto; }
#container #sidebarWrapper { height: auto; }

To stretch to 100% height of viewport, you need to specify the height of the containing block (in this case, it's #container). Moreover, you also need to specify the height to body and html, because initial Containing Block is "UA-dependent".

All you need is...

html, body { height:100%; }
#container { height:100%; }

Saving to CSV in Excel loses regional date format

A not so scalable fix that I used for this is to copy the data to a plain text editor, convert the cells to text and then copy the data back to the spreadsheet.

React Modifying Textarea Values

As a newbie in React world, I came across a similar issues where I could not edit the textarea and struggled with binding. It's worth knowing about controlled and uncontrolled elements when it comes to react.

The value of the following uncontrolled textarea cannot be changed because of value

 <textarea type="text" value="some value"
    onChange={(event) => this.handleOnChange(event)}></textarea>

The value of the following uncontrolled textarea can be changed because of use of defaultValue or no value attribute

<textarea type="text" defaultValue="sample" 
    onChange={(event) => this.handleOnChange(event)}></textarea>

<textarea type="text" 
   onChange={(event) => this.handleOnChange(event)}></textarea>

The value of the following controlled textarea can be changed because of how value is mapped to a state as well as the onChange event listener

<textarea value={this.state.textareaValue} 
onChange={(event) => this.handleOnChange(event)}></textarea>

Here is my solution using different syntax. I prefer the auto-bind than manual binding however, if I were to not use {(event) => this.onXXXX(event)} then that would cause the content of textarea to be not editable OR the event.preventDefault() does not work as expected. Still a lot to learn I suppose.

class Editor extends React.Component {
  constructor(props) {
    super(props)
    this.state = {
      textareaValue: ''
    }
  }
  handleOnChange(event) {
    this.setState({
      textareaValue: event.target.value
    })
  }
  handleOnSubmit(event) {
    event.preventDefault();
    this.setState({
      textareaValue: this.state.textareaValue + ' [Saved on ' + (new Date()).toLocaleString() + ']'
    })
  }
  render() {
    return <div>
        <form onSubmit={(event) => this.handleOnSubmit(event)}>
          <textarea rows={10} cols={30} value={this.state.textareaValue} 
            onChange={(event) => this.handleOnChange(event)}></textarea>
          <br/>
          <input type="submit" value="Save"/>
        </form>
      </div>
  }
}
ReactDOM.render(<Editor />, document.getElementById("content"));

The versions of libraries are

"babel-cli": "6.24.1",
"babel-preset-react": "6.24.1"
"React & ReactDOM v15.5.4" 

What is the difference between for and foreach?

simple difference between for and foreach

  for loop is working with values.it must have condition then increment and intialization also.you have to knowledge about 'how many times loop repeated'.

 foreach is working with objects and enumaretors. no need to knowledge how many times loop repeated.

Sending POST data in Android

You can POST an HttpRequest using WebServer class and track the response in its listener interface.

WebServer server=new WebServer(getApplicationContext());

server.setOnServerStatusListner(new WebServer.OnServerStatusListner() {
    @Override
    public void onServerResponded(String responce) {

    }

    @Override
    public void onServerRevoked() {

    }
});

Now create a DataRack to bind your data

List<DataRack> racks=new ArrayList<DataRack>();
racks.add(new DataRack("name","Simon"));
racks.add(new DataRack("age","40"));
racks.add(new DataRack("location","Canada"));

Now simply send the POST request with that rack

server.connectWithPOST(MainActivity.this,"http://sangeethnandakumar.esy.es/PROJECTS/PUBLIC_SERVICE/posttest.php",racks);

You need to include my library for this. Documentations here

Ignore self-signed ssl cert using Jersey Client

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

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

public static Client ignoreSSLClient() throws Exception {

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

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

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

C linked list inserting node at the end

This code will work. The answer from samplebias is almost correct, but you need a third change:

int addNodeBottom(int val, node *head){

    //create new node
    node *newNode = (node*)malloc(sizeof(node));

    if(newNode == NULL){
        fprintf(stderr, "Unable to allocate memory for new node\n");
        exit(-1);
    }

    newNode->value = val;
    newNode->next = NULL;  // Change 1

    //check for first insertion
    if(head->next == NULL){
        head->next = newNode;
        printf("added at beginning\n");
    }

    else
    {
        //else loop through the list and find the last
        //node, insert next to it
        node *current = head;
        while (true) { // Change 2
            if(current->next == NULL)
            {
                current->next = newNode;
                printf("added later\n");
                break; // Change 3
            }
            current = current->next;
        };
    }
    return 0;
}

Change 1: newNode->next must be set to NULL so we don't insert invalid pointers at the end of the list.

Change 2/3: The loop is changed to an endless loop that will be jumped out with break; when we found the last element. Note how while(current->next != NULL) contradicted if(current->next == NULL) before.

EDIT: Regarding the while loop, this way it is much better:

  node *current = head;
  while (current->next != NULL) {
    current = current->next;
  }
  current->next = newNode;
  printf("added later\n");

Async image loading from url inside a UITableView cell - image changes to wrong image while scrolling

You can just pass your URL,

NSURL *url = [NSURL URLWithString:@"http://www.myurl.com/1.png"];
NSURLSessionTask *task = [[NSURLSession sharedSession] dataTaskWithURL:url completionHandler:^(NSData * _Nullable data,    NSURLResponse * _Nullable response, NSError * _Nullable error) {
    if (data) {
        UIImage *image = [UIImage imageWithData:data];
        if (image) {
            dispatch_async(dispatch_get_main_queue(), ^{
                    yourimageview.image = image;
            });
        }
    }
}];
[task resume];

SVG Positioning

As mentioned in the other comment, the transform attribute on the g element is what you want. Use transform="translate(x,y)" to move the g around and things within the g will move in relation to the g.

Converting a char to ASCII?

Uhm, what's wrong with this:

#include <iostream>

using namespace std;

int main(int, char **)
{
    char c = 'A';

    int x = c; // Look ma! No cast!

    cout << "The character '" << c << "' has an ASCII code of " << x << endl;

    return 0;
}

Convert a Map<String, String> to a POJO

Well, you can achieve that with Jackson, too. (and it seems to be more comfortable since you were considering using jackson).

Use ObjectMapper's convertValue method:

final ObjectMapper mapper = new ObjectMapper(); // jackson's objectmapper
final MyPojo pojo = mapper.convertValue(map, MyPojo.class);

No need to convert into JSON string or something else; direct conversion does much faster.

Can't connect Nexus 4 to adb: unauthorized

For my Samsung S3, I had to go into Developer Options on the phone, untick the "USB debugging" checkbox, then re-tick it.

Then the dialog will appear, asking if you want to allow USB Debugging.

Once I'd done this, the "adb devices" command no longer showed "unauthorized" as my device name.

(Several months later..)

Actually, the same was true for connecting my Galaxy Tab S device, and the menu options were in slightly different places with Android 4.4.2:

enter image description here

How do I use arrays in C++?

Assignment

For no particular reason, arrays cannot be assigned to one another. Use std::copy instead:

#include <algorithm>

// ...

int a[8] = {2, 3, 5, 7, 11, 13, 17, 19};
int b[8];
std::copy(a + 0, a + 8, b);

This is more flexible than what true array assignment could provide because it is possible to copy slices of larger arrays into smaller arrays. std::copy is usually specialized for primitive types to give maximum performance. It is unlikely that std::memcpy performs better. If in doubt, measure.

Although you cannot assign arrays directly, you can assign structs and classes which contain array members. That is because array members are copied memberwise by the assignment operator which is provided as a default by the compiler. If you define the assignment operator manually for your own struct or class types, you must fall back to manual copying for the array members.

Parameter passing

Arrays cannot be passed by value. You can either pass them by pointer or by reference.

Pass by pointer

Since arrays themselves cannot be passed by value, usually a pointer to their first element is passed by value instead. This is often called "pass by pointer". Since the size of the array is not retrievable via that pointer, you have to pass a second parameter indicating the size of the array (the classic C solution) or a second pointer pointing after the last element of the array (the C++ iterator solution):

#include <numeric>
#include <cstddef>

int sum(const int* p, std::size_t n)
{
    return std::accumulate(p, p + n, 0);
}

int sum(const int* p, const int* q)
{
    return std::accumulate(p, q, 0);
}

As a syntactic alternative, you can also declare parameters as T p[], and it means the exact same thing as T* p in the context of parameter lists only:

int sum(const int p[], std::size_t n)
{
    return std::accumulate(p, p + n, 0);
}

You can think of the compiler as rewriting T p[] to T *p in the context of parameter lists only. This special rule is partly responsible for the whole confusion about arrays and pointers. In every other context, declaring something as an array or as a pointer makes a huge difference.

Unfortunately, you can also provide a size in an array parameter which is silently ignored by the compiler. That is, the following three signatures are exactly equivalent, as indicated by the compiler errors:

int sum(const int* p, std::size_t n)

// error: redefinition of 'int sum(const int*, size_t)'
int sum(const int p[], std::size_t n)

// error: redefinition of 'int sum(const int*, size_t)'
int sum(const int p[8], std::size_t n)   // the 8 has no meaning here

Pass by reference

Arrays can also be passed by reference:

int sum(const int (&a)[8])
{
    return std::accumulate(a + 0, a + 8, 0);
}

In this case, the array size is significant. Since writing a function that only accepts arrays of exactly 8 elements is of little use, programmers usually write such functions as templates:

template <std::size_t n>
int sum(const int (&a)[n])
{
    return std::accumulate(a + 0, a + n, 0);
}

Note that you can only call such a function template with an actual array of integers, not with a pointer to an integer. The size of the array is automatically inferred, and for every size n, a different function is instantiated from the template. You can also write quite useful function templates that abstract from both the element type and from the size.

How to Check byte array empty or not?

Just do

if (Attachment != null  && Attachment.Length > 0)

From && Operator

The conditional-AND operator (&&) performs a logical-AND of its bool operands, but only evaluates its second operand if necessary.

JQuery show/hide when hover

jquery:

$('div.animalcontent').hide();
$('div').hide();
$('p.animal').bind('mouseover', function() {
    $('div.animalcontent').fadeOut();
    $('#'+$(this).attr('id')+'content').fadeIn();
});  

html:

<p class='animal' id='dog'>dog url</p><div id='dogcontent' class='animalcontent'>Doggiecontent!</div>
<p class='animal' id='cat'>cat url</p><div id='catcontent' class='animalcontent'>Pussiecontent!</div>
<p class='animal' id='snake'>snake url</p><div id='snakecontent'class='animalcontent'>Snakecontent!</div>

-edit-

yeah sure, here you go -- JSFiddle

calling Jquery function from javascript

Yes you can (this is how I understand the original question). Here is how I did it. Just tie it into outside context. For example:

//javascript

my_function = null;

//jquery 
 $(function() { 

        function my_fun(){ 
               /.. some operations ../ 
        }  
        my_function = my_fun;
 }) 

 //just js 
 function js_fun () {  
       my_function(); //== call jquery function - just Reference is globally defined not function itself
}

I encountered this same problem when trying to access methods of the object, that was instantiated on DOM object ready only. Works. My example:

MyControl.prototype = {
   init:   function { 
        // init something
   }
   update: function () {
           // something useful, like updating the list items of control or etc.         
   }
}

MyCtrl = null;

// create jquery plug-in
$.fn.aControl = function () {
    var control = new MyControl(this);
    control.init();
    MyCtrl = control; // here is the trick
    return control;
}

now you can use something simple like:

function() = {
   MyCtrl.update(); // yes!
}

Convert a JSON string to object in Java ME?

Use google GSON library for this

public static <T> T getObject(final String jsonString, final Class<T> objectClass) {  
    Gson gson = new Gson();  
    return gson.fromJson(jsonString, objectClass);  
}

http://iandjava.blogspot.in/2014/01/java-object-to-json-and-json-to-java.html

jquery datatables default sort

You can use the fnSort function, see the details here:

http://datatables.net/api#fnSort

Missing include "bits/c++config.h" when cross compiling 64 bit program on 32 bit in Ubuntu

While compiling in RHEL 6.2 (x86_64), I installed both 32bit and 64bit libstdc++-dev packages, but I had the "c++config.h no such file or directory" problem.

Resolution:

The directory /usr/include/c++/4.4.6/x86_64-redhat-linux was missing.

I did the following:

cd /usr/include/c++/4.4.6/
mkdir x86_64-redhat-linux
cd x86_64-redhat-linux
ln -s ../i686-redhat-linux 32

I'm now able to compile 32bit binaries on a 64bit OS.

log4j:WARN No appenders could be found for logger (running jar file, not web app)

put the folder which has the properties file for log in java build path source. You can add it by right clicking the project ----> build path -----> configure build path ------> add t

Dynamically add item to jQuery Select2 control that uses AJAX

This is a lot easier to do starting in select2 v4. You can create a new Option, and append it to the select element directly. See my codepen or the example below:

_x000D_
_x000D_
$(document).ready(function() {_x000D_
    $("#state").select2({_x000D_
      tags: true_x000D_
    });_x000D_
      _x000D_
    $("#btn-add-state").on("click", function(){_x000D_
      var newStateVal = $("#new-state").val();_x000D_
      // Set the value, creating a new option if necessary_x000D_
      if ($("#state").find("option[value=" + newStateVal + "]").length) {_x000D_
        $("#state").val(newStateVal).trigger("change");_x000D_
      } else { _x000D_
        // Create the DOM option that is pre-selected by default_x000D_
        var newState = new Option(newStateVal, newStateVal, true, true);_x000D_
        // Append it to the select_x000D_
        $("#state").append(newState).trigger('change');_x000D_
      } _x000D_
    });  _x000D_
});
_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/css/bootstrap.min.css" rel="stylesheet"/>_x000D_
<link href="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/css/select2.min.css" rel="stylesheet"/>_x000D_
_x000D_
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/twitter-bootstrap/3.3.6/js/bootstrap.min.js"></script>_x000D_
<script src="https://cdnjs.cloudflare.com/ajax/libs/select2/4.0.1/js/select2.min.js"></script>_x000D_
_x000D_
_x000D_
<select id="state" class="js-example-basic-single" type="text" style="width:90%">_x000D_
  <option value="AL">Alabama</option>_x000D_
  <option value="WY">Wyoming</option>_x000D_
</select>_x000D_
<br>_x000D_
<br>_x000D_
<input id="new-state" type="text" />_x000D_
<button type="button" id="btn-add-state">Set state value</button>
_x000D_
_x000D_
_x000D_

Hint: try entering existing values into the text box, like "AL" or "WY". Then try adding some new values.

Apache is not running from XAMPP Control Panel ( Error: Apache shutdown unexpectedly. This may be due to a blocked port)

Use any method for which the server is working after that you can use this address to open the page on browser (if you've replaced the port 80 with 81 )

http://localhost:81/phpmyadmin/

How to redirect to a 404 in Rails?

To test the error handling, you can do something like this:

feature ErrorHandling do
  before do
    Rails.application.config.consider_all_requests_local = false
    Rails.application.config.action_dispatch.show_exceptions = true
  end

  scenario 'renders not_found template' do
    visit '/blah'
    expect(page).to have_content "The page you were looking for doesn't exist."
  end
end

Animate visibility modes, GONE and VISIBLE

You can use the expandable list view explained in API demos to show groups

http://developer.android.com/resources/samples/ApiDemos/src/com/example/android/apis/view/ExpandableList1.html.

To animate the list items motion, you will have to override the getView method and apply translate animation on each list item. The values for animation depend on the position of each list item. This was something which i tried on a simple list view long time back.

How can I fix the form size in a C# Windows Forms application and not to let user change its size?

Properties -> FormBorderStyle -> FixedSingle

if you can not find your Properties tool. Go to View -> Properties Window

No function matches the given name and argument types

In my particular case the function was actually missing. The error message is the same. I am using the Postgresql plugin PostGIS and I had to reinstall that for whatever reason.

python pandas: Remove duplicates by columns A, keeping the row with the highest value in column B

The top answer is doing too much work and looks to be very slow for larger data sets. apply is slow and should be avoided if possible. ix is deprecated and should be avoided as well.

df.sort_values('B', ascending=False).drop_duplicates('A').sort_index()

   A   B
1  1  20
3  2  40
4  3  10

Or simply group by all the other columns and take the max of the column you need. df.groupby('A', as_index=False).max()

Python send POST with header

To make POST request instead of GET request using urllib2, you need to specify empty data, for example:

import urllib2
req = urllib2.Request("http://am.domain.com:8080/openam/json/realms/root/authenticate?authIndexType=Module&authIndexValue=LDAP")
req.add_header('X-OpenAM-Username', 'demo')
req.add_data('')
r = urllib2.urlopen(req)

sending email via php mail function goes to spam

The problem is simple that the PHP-Mail function is not using a well configured SMTP Server.

Nowadays Email-Clients and Servers perform massive checks on the emails sending server, like Reverse-DNS-Lookups, Graylisting and whatevs. All this tests will fail with the php mail() function. If you are using a dynamic ip, its even worse.

Use the PHPMailer-Class and configure it to use smtp-auth along with a well configured, dedicated SMTP Server (either a local one, or a remote one) and your problems are gone.

https://github.com/PHPMailer/PHPMailer

Get combobox value in Java swing

If the string is empty, comboBox.getSelectedItem().toString() will give a NullPointerException. So better to typecast by (String).

Adding devices to team provisioning profile

After adding UDID in developer.apple.com, do the following steps:

1, Go to Xcode, open Preferences (cmd + ,) -> Accounts -> Click your Apple ID -> View Details enter image description here

2, In the new window, click on "Refresh", then "Request" enter image description here

3, Now try to run your app on the new device, if you get an error saying "unfound provisioning profile", keep reading

4, Click on your project enter image description here

6, Find "Fix It" button in Identity section, click it enter image description here

7, Now try to run again, it should work

How to round down to nearest integer in MySQL?

It can be done in the following two ways:

  • select floor(desired_field_value) from table
  • select round(desired_field_value-0.5) from table

The 2nd-way explanation: Assume 12345.7344 integer. So, 12345.7344 - 0.5 = 12345.2344 and rounding off the result will be 12345.

how to use #ifdef with an OR condition?

Like this

#if defined(LINUX) || defined(ANDROID)

How to make modal dialog in WPF?

Given a Window object myWindow, myWindow.Show() will open it modelessly and myWindow.ShowDialog() will open it modally. However, even the latter doesn't block, from what I remember.

Text that shows an underline on hover

You just need to specify text-decoration: underline; with pseudo-class :hover.

HTML

<span class="underline-on-hover">Hello world</span>

CSS

.underline-on-hover:hover {
    text-decoration: underline;
}

I have whipped up a working Code Pen Demo.

Get model's fields in Django

Now there is special method - get_fields()

    >>> from django.contrib.auth.models import User
    >>> User._meta.get_fields()

It accepts two parameters that can be used to control which fields are returned:

  • include_parents

    True by default. Recursively includes fields defined on parent classes. If set to False, get_fields() will only search for fields declared directly on the current model. Fields from models that directly inherit from abstract models or proxy classes are considered to be local, not on the parent.

  • include_hidden

    False by default. If set to True, get_fields() will include fields that are used to back other field’s functionality. This will also include any fields that have a related_name (such as ManyToManyField, or ForeignKey) that start with a “+”

What is the point of WORKDIR on Dockerfile?

Beware of using vars as the target directory name for WORKDIR - doing that appears to result in a "cannot normalize nothing" fatal error. IMO, it's also worth pointing out that WORKDIR behaves in the same way as mkdir -p <path> i.e. all elements of the path are created if they don't exist already.

UPDATE: I encountered the variable related problem (mentioned above) whilst running a multi-stage build - it now appears that using a variable is fine - if it (the variable) is "in scope" e.g. in the following, the 2nd WORKDIR reference fails ...

FROM <some image>
ENV varname varval
WORKDIR $varname

FROM <some other image>
WORKDIR $varname

whereas, it succeeds in this ...

FROM <some image>
ENV varname varval
WORKDIR $varname

FROM <some other image>
ENV varname varval
WORKDIR $varname

.oO(Maybe it's in the docs & I've missed it)

How to force a script reload and re-execute?

Have you tried removing it from the DOM, then inserting it back again?

I just did, that doesn't work. However, creating a new script tag and copying the contents of the existing script tag, then adding it, works well.

See my example http://jsfiddle.net/mendesjuan/LPFYB/

var scriptTag = document.createElement('script');
scriptTag.innerText = "document.body.innerHTML += 'Here again ---<BR>';";
var head = document.getElementsByTagName('head')[0];
head.appendChild(scriptTag);

setInterval(function() {
    head.removeChild(scriptTag);
    var newScriptTag = document.createElement('script');
    newScriptTag.innerText = scriptTag.innerText;
    head.appendChild(newScriptTag);
    scriptTag = newScriptTag;    
}, 1000);

This won't work if you expect the script to change every time, which I believe is your case. You should follow Kelly's suggestion, just remove the old script tag (just to keep the DOM slim, it won't affect the outcome) and reinsert a new script tag with the same src, plus a cachebuster.

PHP-FPM and Nginx: 502 Bad Gateway

You should see the error log. By default, its location is in /var/log/nginx/error.log

In my case, 502 get way because of:

GET /app_dev.php HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm.sock:", host: "symfony2.local"
2016/05/25 11:57:28 [error] 22889#22889: *3 upstream sent too big header while reading response header from upstream, client: 127.0.0.1, server: symfony2.local, request: "GET /app_dev.php HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm.sock:", host: "symfony2.local"
2016/05/25 11:57:29 [error] 22889#22889: *3 upstream sent too big header while reading response header from upstream, client: 127.0.0.1, server: symfony2.local, request: "GET /app_dev.php HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm.sock:", host: "symfony2.local"
2016/05/25 11:57:29 [error] 22889#22889: *3 upstream sent too big header while reading response header from upstream, client: 127.0.0.1, server: symfony2.local, request: "GET /app_dev.php HTTP/1.1", upstream: "fastcgi://unix:/run/php/php7.0-fpm.sock:", host: "symfony2.local"

When we know exactly what is wrong, then fix it. For these error, just modify the buffer:

fastcgi_buffers 16 512k; 
fastcgi_buffer_size 512k;

Difference between a script and a program?

Typically, a script is a lightweight, quickly constructed, possibly single-use tool. It's usually interpreted, not compiled. Python and bash are examples of languages used to build scripts.

A program is constructed in a compiled language, like C or C++, and usually runs more quickly than a script for that reason. Larger tools are often written as "programs" rather than scripts - smaller tools are more easily developed as scripts, but scripts can get unwieldy as they get larger. Application and system languages (those used to build programs/applications) have tools to make that growth easier to manage.

You can usually view a script in a text editor to see what it does. You can't do that with an executable program - the latter's instructions have been compiled into bytecode or machine language that makes it very difficult for humans to understand, without specialized tools.

Note the number of "oftens" and "usuallys" above - the terms are nebulous, and cross over sometimes.

How do I vertically center text with CSS?

Set it within button instead of div if you don't care about its little visual 3D effect.

_x000D_
_x000D_
#box_x000D_
{_x000D_
  height: 120px;_x000D_
  width: 300px;_x000D_
  background: #000;_x000D_
  font-size: 48px;_x000D_
  font-style: oblique;_x000D_
  color: #FFF;_x000D_
}
_x000D_
<button Id="box" disabled>_x000D_
  Lorem ipsum dolor sit amet, consectetur adipiscing elit._x000D_
</button>
_x000D_
_x000D_
_x000D_

PHP: Read Specific Line From File

If you use PHP on Linux, you may try the following to read text for example between 74th and 159th lines:

$text = shell_exec("sed -n '74,159p' path/to/file.log");

This solution is good if your file is large.

PHP 5.4 Call-time pass-by-reference - Easy fix available?

For anyone who, like me, reads this because they need to update a giant legacy project to 5.6: as the answers here point out, there is no quick fix: you really do need to find each occurrence of the problem manually, and fix it.

The most convenient way I found to find all problematic lines in a project (short of using a full-blown static code analyzer, which is very accurate but I don't know any that take you to the correct position in the editor right away) was using Visual Studio Code, which has a nice PHP linter built in, and its search feature which allows searching by Regex. (Of course, you can use any IDE/Code editor for this that does PHP linting and Regex searches.)

Using this regex:

^(?!.*function).*(\&\$)

it is possible to search project-wide for the occurrence of &$ only in lines that are not a function definition.

This still turns up a lot of false positives, but it does make the job easier.

VSCode's search results browser makes walking through and finding the offending lines super easy: you just click through each result, and look out for those that the linter underlines red. Those you need to fix.

Converting Go struct to JSON

Struct values encode as JSON objects. Each exported struct field becomes a member of the object unless:

  • the field's tag is "-", or
  • the field is empty and its tag specifies the "omitempty" option.

The empty values are false, 0, any nil pointer or interface value, and any array, slice, map, or string of length zero. The object's default key string is the struct field name but can be specified in the struct field's tag value. The "json" key in the struct field's tag value is the key name, followed by an optional comma and options.

Error 1920 service failed to start. Verify that you have sufficient privileges to start system services

Check service dependencies if they are disabled.

Set those dependencies to Automatic, Start them and it should work.

Tab space instead of multiple non-breaking spaces ("nbsp")?

If you're looking to just indent the first sentence in a paragraph, you could do that with a small CSS trick:

p:first-letter {
    margin-left: 5em;
}

Reload parent window from child window

You can reload parent window location using :

window.opener.location.href = window.opener.location.href;

Inner Joining three tables

select *
from
    tableA a
        inner join
    tableB b
        on a.common = b.common
        inner join 
    TableC c
        on b.common = c.common

Generate a random letter in Python

>>>def random_char(y):
       return ''.join(random.choice(string.ascii_letters) for x in range(y))

>>>print (random_char(5))
>>>fxkea

to generate y number of random characters

Floating point exception

http://en.wikipedia.org/wiki/Division_by_zero

http://en.wikipedia.org/wiki/Unix_signal#SIGFPE

This should give you a really good idea. Since a modulus is, in its basic sense, division with a remainder, something % 0 IS division by zero and as such, will trigger a SIGFPE being thrown.

Jquery bind double click and single click separately

Same as the above answer but allows for triple click. (Delay 500) http://jsfiddle.net/luenwarneke/rV78Y/1/

    var DELAY = 500,
    clicks = 0,
    timer = null;

$(document).ready(function() {
    $("a")
    .on("click", function(e){
        clicks++;  //count clicks
        timer = setTimeout(function() {
        if(clicks === 1) {
           alert('Single Click'); //perform single-click action
        } else if(clicks === 2) {
           alert('Double Click'); //perform single-click action
        } else if(clicks >= 3) {
           alert('Triple Click'); //perform Triple-click action
        }
         clearTimeout(timer);
         clicks = 0;  //after action performed, reset counter
       }, DELAY);
    })
    .on("dblclick", function(e){
        e.preventDefault();  //cancel system double-click event
    });
});

How can I escape a single quote?

As you’re in the context of HTML, you need to use HTML to represent that character. And for HTML you need to use a numeric character reference &#39; (&#x27; hexadecimal):

<input type='text' id='abc' value='hel&#39;lo'>

How to execute a shell script in PHP?

You might have disabled the exec privileges, most of the LAMP packages have those disabled. Check your php.ini for this line:

disable_functions = exec

And remove the exec, shell_exec entries if there are there.

Good Luck!

How to make a JTable non-editable

You can use a TableModel.

Define a class like this:

public class MyModel extends AbstractTableModel{
    //not necessary
}

actually isCellEditable() is false by default so you may omit it. (see: http://docs.oracle.com/javase/6/docs/api/javax/swing/table/AbstractTableModel.html)

Then use the setModel() method of your JTable.

JTable myTable = new JTable();
myTable.setModel(new MyModel());

MySQL - DATE_ADD month interval

DATE_ADD works correctly. 1 January plus 6 months is 1 July, just like 1 January plus 1 month is 1 of February.

Between operation is inclusive. So, you are getting everything up to, and including, 1 July. (see also MySQL "between" clause not inclusive?)

What you need to do is subtract 1 day or use < operator instead of between.

Sending email with attachments from C#, attachments arrive as Part 1.2 in Thunderbird

private void btnSent_Click(object sender, EventArgs e)
{
    try
    {
        MailMessage mail = new MailMessage();
        SmtpClient SmtpServer = new SmtpClient("smtp.gmail.com");

        mail.From = new MailAddress(txtAcc.Text);
        mail.To.Add(txtToAdd.Text);
        mail.Subject = txtSub.Text;
        mail.Body = txtContent.Text;
        System.Net.Mail.Attachment attachment;
        attachment = new System.Net.Mail.Attachment(txtAttachment.Text);
        mail.Attachments.Add(attachment);

        SmtpServer.Port = 587;
        SmtpServer.Credentials = new System.Net.NetworkCredential(txtAcc.Text, txtPassword.Text);

        SmtpServer.EnableSsl = true;

        SmtpServer.Send(mail);
        MessageBox.Show("mail send");
    }
    catch (Exception ex)
    {
        MessageBox.Show(ex.ToString());
    }
}

private void button1_Click(object sender, EventArgs e)
{
    MailMessage mail = new MailMessage();
    openFileDialog1.ShowDialog();
    System.Net.Mail.Attachment attachment;
    attachment = new System.Net.Mail.Attachment(openFileDialog1.FileName);
    mail.Attachments.Add(attachment);
    txtAttachment.Text =Convert.ToString (openFileDialog1.FileName);
}

How do I set response headers in Flask?

This work for me

from flask import Flask
from flask import Response

app = Flask(__name__)

@app.route("/")
def home():
    return Response(headers={'Access-Control-Allow-Origin':'*'})

if __name__ == "__main__":
    app.run()

How to get the element clicked (for the whole document)?

Here's a solution that uses a jQuery selector so you can easily target tags of any class, ID, type etc.

jQuery('div').on('click', function(){
    var node = jQuery(this).get(0);
    var range = document.createRange();
    range.selectNodeContents( node );
    window.getSelection().removeAllRanges();
    window.getSelection().addRange( range );
});

Why doesn't CSS ellipsis work in table cell?

If you don't want to set max-width to td (like in this answer), you can set max-width to div:

function so_hack(){}

function so_hack(){} http://jsfiddle.net/fd3Zx/754/ function so_hack(){}

function so_hack(){}

Note: 100% doesn't work, but 99% does the trick in FF. Other modern browsers doesn't need silly div hacks.

td {
  border: 1px solid black;
    padding-left:5px;
    padding-right:5px;
}
td>div{
    max-width: 99%;
    overflow: hidden;
    text-overflow: ellipsis;
    white-space: nowrap;

}

How can I change the Java Runtime Version on Windows (7)?

Go to control panel --> Java You can select the active version here

ASP.NET MVC: Html.EditorFor and multi-line text boxes

Another way

@Html.TextAreaFor(model => model.Comments[0].Comment)

And in your css do this

textarea
{
    font-family: inherit;
    width: 650px;
    height: 65px;
}

That DataType dealie allows carriage returns in the data, not everybody likes those.

File 'app/hero.ts' is not a module error in the console, where to store interfaces files in directory structure with angular2?

Try Restarting the editor in which you are writing the code(VS code or Sublime). Compile and Run it again. I have done the same and it worked.

This happens when you add a new class outside from your editor or keep running your angular cli 'ng serve'. Actually your editor or the 'ng serve' command may not able to find the newly created files.

Split string using a newline delimiter with Python

data = """a,b,c
d,e,f
g,h,i
j,k,l"""

print(data.split())       # ['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']

str.split, by default, splits by all the whitespace characters. If the actual string has any other whitespace characters, you might want to use

print(data.split("\n"))   # ['a,b,c', 'd,e,f', 'g,h,i', 'j,k,l']

Or as @Ashwini Chaudhary suggested in the comments, you can use

print(data.splitlines())

What exceptions should be thrown for invalid or unexpected parameters in .NET?

ArgumentException:

ArgumentException is thrown when a method is invoked and at least one of the passed arguments does not meet the parameter specification of the called method. All instances of ArgumentException should carry a meaningful error message describing the invalid argument, as well as the expected range of values for the argument.

A few subclasses also exist for specific types of invalidity. The link has summaries of the subtypes and when they should apply.

How to automatically reload a page after a given period of inactivity

And finally the most simple solution:

With alert confirmation:

<script type="text/javascript">
    // Set timeout variables.
    var timoutWarning = 3000; // Display warning in 1Mins.
    var timoutNow = 4000; // Timeout in 2 mins.

    var warningTimer;
    var timeoutTimer;

    // Start timers.
    function StartTimers() {
        warningTimer = setTimeout("IdleWarning()", timoutWarning);
        timeoutTimer = setTimeout("IdleTimeout()", timoutNow);
    }

    // Reset timers.
    function ResetTimers() {
        clearTimeout(warningTimer);
        clearTimeout(timeoutTimer);
        StartTimers();
        $("#timeout").dialog('close');
    }

    // Show idle timeout warning dialog.
    function IdleWarning() {
        var answer = confirm("Session About To Timeout\n\n       You will be automatically logged out.\n       Confirm to remain logged in.")
            if (answer){

                ResetTimers();
            }
            else{
                IdleTimeout();
            }
    }       

    // Logout the user and auto reload or use this window.open('http://www.YourPageAdress.com', '_self'); to auto load a page.
    function IdleTimeout() {
        window.open(self.location,'_top');
    }
</script>

Without alert confirmation:

<script type="text/javascript">
    // Set timeout variables.
    var timoutWarning = 3000; // Display warning in 1Mins.
    var timoutNow = 4000; // Timeout in 2 mins.

    var warningTimer;
    var timeoutTimer;

    // Start timers.
    function StartTimers() {
        warningTimer = setTimeout(timoutWarning);
        timeoutTimer = setTimeout("IdleTimeout()", timoutNow);
    }

    // Reset timers.
    function ResetTimers() {
        clearTimeout(warningTimer);
        clearTimeout(timeoutTimer);
        StartTimers();
        $("#timeout").dialog('close');
    }

    // Logout the user and auto reload or use this window.open('http://www.YourPageAdress.com', '_self'); to auto load a page.
    function IdleTimeout() {
        window.open(self.location,'_top');
    }
</script>

Body code is the SAME for both solutions

<body onload="StartTimers();" onmousemove="ResetTimers();" onKeyPress="ResetTimers();">

Modifying list while iterating

I guess this is what you want:

l  = range(100)  
index = 0                       
for i in l:                         
    print i,              
    try:
        print l.pop(index+1),                  
        print l.pop(index+1)
    except:
        pass
    index += 1

It is quite handy to code when the number of item to be popped is a run time decision. But it runs with very a bad efficiency and the code is hard to maintain.

Returning a boolean value in a JavaScript function

You could simplify this a lot:

  • Check whether one is not empty
  • Check whether they are equal

This will result in this, which will always return a boolean. Your function also should always return a boolean, but you can see it does a little better if you simplify your code:

function validatePassword()
{
   var password = document.getElementById("password");
   var confirm_password = document.getElementById("password_confirm");

   return password.value !== "" && password.value === confirm_password.value;
       //       not empty       and              equal
}

Can't compile C program on a Mac after upgrade to Mojave

When you

  • updated to Mojave 10.14.6
  • your /usr/include was deleted again
  • the package mentioned in @Jonathan-lefflers answer doesn't exist anymore The file /Library/Developer/CommandLineTools/Packages/macOS_SDK_headers_for_macOS_10.14.pkg does not exist. and
  • Xcode complains that command line tools are already installed xcode-select --install xcode-select: error: command line tools are already installed, use "Software Update" to install updates

Then, what helped me recover the mentioned package, was deleting the whole CommandLineTools folder (sudo) rm -rf /Library/Developer/CommandLineTools and reinstall it xcode-select --install.

Change the mouse cursor on mouse over to anchor-like style

You actually don't need jQuery, just CSS. For example, here's some HTML:

<div class="special"></div>

And here's the CSS:

.special
{
    cursor: pointer;
}

reading from app.config file

Also add the key "StartingMonthColumn" in App.config that you run application from, for example in the App.config of the test project.

How to delete/remove nodes on Firebase

In case you are using axios and trying via a service call.

URL: https://react-16-demo.firebaseio.com/
Schema Name: todos
Key: -Lhu8a0uoSRixdmECYPE

axios.delete(`https://react-16-demo.firebaseio.com/todos/-Lhu8a0uoSRixdmECYPE.json`). then();

can help.

How do you perform address validation?

NAICS.com is coming out with an API that will add all kinds of key business data including street address. This would happen on the fly as your site's forms are processed. https://www.naics.com/business-intelligence-api/

HTTP Error 503. The service is unavailable. App pool stops on accessing website

Just to add to these Anniversary Update issues (thanks Microsoft) if the file you are missing is cgi.dll, ie your Event Viewer has

The Module DLL C:\WINDOWS\System32\inetsrv\cgi.dll failed to load.  The data is the error.

Then to fix this:

  1. Go to IIS Manager
  2. Select the very top row in the Connections panel (typically your PC name)
  3. At the very bottom of the right panel, under Management, you should have Web Platform Installer
  4. Once that loads, select Products
  5. In the search type in cgi then hit <Enter>
  6. Select IIS: CGI then click Add on the right and finally Install on the bottom
  7. After installing it should force you to restart your PC and you should be fixed.

Create a jTDS connection string

As detailed in the jTDS Frequenlty Asked Questions, the URL format for jTDS is:

jdbc:jtds:<server_type>://<server>[:<port>][/<database>][;<property>=<value>[;...]]

So, to connect to a database called "Blog" hosted by a MS SQL Server running on MYPC, you may end up with something like this:

jdbc:jtds:sqlserver://MYPC:1433/Blog;instance=SQLEXPRESS;user=sa;password=s3cr3t

Or, if you prefer to use getConnection(url, "sa", "s3cr3t"):

jdbc:jtds:sqlserver://MYPC:1433/Blog;instance=SQLEXPRESS

EDIT: Regarding your Connection refused error, double check that you're running SQL Server on port 1433, that the service is running and that you don't have a firewall blocking incoming connections.

No restricted globals

For me I had issues with history and location... As the accepted answer using window before history and location (i.e) window.history and window.location solved mine

How to scale a UIImageView proportionally?

Set your UIimageview by scale.........

enter image description here

Can I escape html special chars in javascript?

If you already use modules in your app, you can use escape-html module.

import escapeHtml from 'escape-html';
const unsafeString = '<script>alert("XSS");</script>';
const safeString = escapeHtml(unsafeString);

Quoting backslashes in Python string literals

What Harley said, except the last point - it's not actually necessary to change the '/'s into '\'s before calling open. Windows is quite happy to accept paths with forward slashes.

infile = open('c:/folder/subfolder/file.txt')

The only time you're likely to need the string normpathed is if you're passing to to another program via the shell (using os.system or the subprocess module).

What is the OR operator in an IF statement

See C# Operators for C# operators including OR which is ||

How to get the jQuery $.ajax error response text?

If you're not having a network error, and wanting to surface an error from the backend, for exmple insufficient privileges, server your response with a 200 and an error message. Then in your success handler check data.status == 'error'

Fatal error: Class 'PHPMailer' not found

Just download composer and install phpMailler autoloader.php

https://github.com/PHPMailer/PHPMailer/blob/master/composer.json

once composer is loaded use below code:

    require_once("phpMailer/class.phpmailer.php");
    require_once("phpMailer/PHPMailerAutoload.php");

    $mail = new PHPMailer(true); 
            $mail->SMTPDebug = true;
            $mail->SMTPSecure = "tls";
            $mail->SMTPAuth   = true;
            $mail->Username   = 'youremail id';
            $mail->Password   = 'youremail password';
            $mail_from        = "youremail id";
            $subject          = "Your Subject";
            $body             = "email body";
            $mail_to          = "receiver_email";
            $mail->IsSMTP(); 
            try {
                  $mail->Host= "smtp.your.com";
                  $mail->Port = "Your SMTP Port No";// ssl port :465, 
                  $mail->Debugoutput = 'html';
                  $mail->AddAddress($mail_to, "receiver_name");
                  $mail->SetFrom($mail_from,'AmpleChat Team'); 
                  $mail->Subject = $subject;
                  $mail->MsgHTML($body);
                  $mail->Send();
                 $emailreturn = 200;
                } catch (phpmailerException $e) {
                  $emailreturn = $e->errorMessage();             
                } catch (Exception $e) {
                 $emailreturn = $e->getMessage();
                }
    echo $emailreturn;

Hope this will work.

PostgreSQL: days/months/years between two dates

Here is a complete example with output. psql (10.1, server 9.5.10).

You get 58, not some value less than 30.
Remove age() function, solved the problem that previous post mentioned.

drop table t;
create table t(
    d1 date
);

insert into t values(current_date - interval '58 day');

select d1
, current_timestamp - d1::timestamp date_diff
, date_part('day', current_timestamp - d1::timestamp)
from t;

     d1     |        date_diff        | date_part
------------+-------------------------+-----------
 2018-05-21 | 58 days 21:41:07.992731 |        58

Async await in linq select

I prefer this as an extension method:

public static async Task<IEnumerable<T>> WhenAll<T>(this IEnumerable<Task<T>> tasks)
{
    return await Task.WhenAll(tasks);
}

So that it is usable with method chaining:

var inputs = await events
  .Select(async ev => await ProcessEventAsync(ev))
  .WhenAll()

SQL SERVER: Get total days between two dates

SELECT DATEDIFF(day, '2005-12-31 23:59:59.9999999', '2006-01-01 00:00:00.0000000');

How do I check if a string is unicode or ascii?

use:

import six
if isinstance(obj, six.text_type)

inside the six library it is represented as:

if PY3:
    string_types = str,
else:
    string_types = basestring,

Fill username and password using selenium in python

Use WebElement.send_keys method to simulate key typing.

name in the code (Username, Password) does not match actual name of the elements (username, password).


username = browser.find_element_by_name('username')
username.send_keys('user1')

password = browser.find_element_by_name('password')
password.send_keys('secret')

form = browser.find_element_by_id('loginForm')
form.submit()

# OR  browser.find_element_by_id('submit').click()

Iterating through a range of dates in Python

What about the following for doing a range incremented by days:

for d in map( lambda x: startDate+datetime.timedelta(days=x), xrange( (stopDate-startDate).days ) ):
  # Do stuff here
  • startDate and stopDate are datetime.date objects

For a generic version:

for d in map( lambda x: startTime+x*stepTime, xrange( (stopTime-startTime).total_seconds() / stepTime.total_seconds() ) ):
  # Do stuff here
  • startTime and stopTime are datetime.date or datetime.datetime object (both should be the same type)
  • stepTime is a timedelta object

Note that .total_seconds() is only supported after python 2.7 If you are stuck with an earlier version you can write your own function:

def total_seconds( td ):
  return float(td.microseconds + (td.seconds + td.days * 24 * 3600) * 10**6) / 10**6

Convert Json Array to normal Java list

I know that question is about JSONArray but here's example I've found useful where you don't need to use JSONArray to extract objects from JSONObject.

import org.json.simple.JSONObject;
import org.json.simple.JSONValue;

String jsonStr = "{\"types\":[1, 2]}";
JSONObject json = (JSONObject) JSONValue.parse(jsonStr);
List<Long> list = (List<Long>) json.get("types");
if (list != null) {
    for (Long s : list) {
        System.out.println(s);
    }
}

Works also with array of strings

How do I append text to a file?

cat >> filename
This is text, perhaps pasted in from some other source.
Or else entered at the keyboard, doesn't matter. 
^D

Essentially, you can dump any text you want into the file. CTRL-D sends an end-of-file signal, which terminates input and returns you to the shell.

How to find NSDocumentDirectory in Swift?

Xcode 8b4 Swift 3.0

let paths = NSSearchPathForDirectoriesInDomains(FileManager.SearchPathDirectory.documentDirectory, FileManager.SearchPathDomainMask.userDomainMask, true)

Java: get greatest common divisor

I used this method that I created when I was 14 years old.

    public static int gcd (int a, int b) {
        int s = 1;
        int ia = Math.abs(a);//<-- turns to absolute value
        int ib = Math.abs(b);
        if (a == b) {
            s = a;
        }else {
            while (ib != ia) {
                if (ib > ia) {
                    s = ib - ia;
                    ib = s;
                }else { 
                    s = ia - ib;
                    ia = s;
                }
            }
        }
        return s;
    }

Redis - Connect to Remote Server

  • if you downloaded redis yourself (not apt-get install redis-server) and then edited the redis.conf with the above suggestions, make sure your start redis with the config like so: ./src/redis-server redis.conf

    • also side note i am including a screenshot of virtual box setting to connect to redis, if you are on windows and connecting to a virtualbox vm.

enter image description here

How can I search for a commit message on GitHub?

Update (2017/01/05):

GitHub has published an update that allows you now to search within commit messages from within their UI. See blog post for more information.


I had the same question and contacted someone GitHub yesterday:

Since they switched their search engine to Elasticsearch it's not possible to search for commit messages using the GitHub UI. But that feature is on the team's wishlist.

Unfortunately there's no release date for that function right now.

Could not load file or assembly 'System.Web.Mvc'

I had the same problem with a bunch of assembly files after moving the project to another solution.

For me, the web.config file was trying to add this assembly:

<add assembly="System.Web.Helpers, Version=1.0.0.0, Culture=neutral, PublicKeyToken=31BF3856AD364E35"/>

Thought the reference in the project was pointing towards version 3.0.0.0 (click on the reference and scroll to the bottom of the properties). Hence I just changed the reference version in the web.config file.

I don´t know if this was just a bug of some sort. The problem with adding all the other references was that the references appeared in the config file but it wasn't actually referenced at all in the project (inside the solution explorer) and the needed files were not copied with the rest of the project files, probably due to not being "copy local = true"

Now, I wasn´t able to find these assemblies in the addable assemblies (by right clicking the reference and trying to add them from the assemblies or extensions). Instead I created a new MVC solution which added all the assemblies and references I needed, and finding them under the new projects references in the solution explorer and finding their path in the properties window for the reference.

Then I just copied the libraries I needed into the other project and referenced them.

Django TemplateDoesNotExist?

in your setting.py file replace DIRS in TEMPLATES array with this

'DIRS': []

to this

'DIRS': [os.path.join(BASE_DIR, 'templates')],

but 1 think u need to know is that you have to make a folder with name templates and it should on the root path otherwise u have to change the DIRS value

PivotTable's Report Filter using "greater than"

Maybe in your data source add a column which does a sumif over all rows. Not sure what your data looks like but something like =(sumif([column holding pivot row heads),[current row head value in row], probability column)>.2). This will give you a True when the pivot table will show >20%.
Then add a filter on your pivot table on this column for TRUE values

How to unzip a file in Powershell?

In PowerShell v5.1 this is slightly different compared to v5. According to MS documentation, it has to have a -Path parameter to specify the archive file path.

Expand-Archive -Path Draft.Zip -DestinationPath C:\Reference

Or else, this can be an actual path:

Expand-Archive -Path c:\Download\Draft.Zip -DestinationPath C:\Reference

Expand-Archive Doc

Are there any naming convention guidelines for REST APIs?

I have a list of guidelines at http://soaprobe.blogspot.co.uk/2012/10/soa-rest-service-naming-guideline.html which we have used in prod. Guidelines are always debatable... I think consistency is sometimes more important than getting things perfect (if there is such a thing).

One line ftp server in python

The answers above were all assuming your Python distribution would have some third-party libraries in order to achieve the "one liner python ftpd" goal, but that is not the case of what @zio was asking. Also, SimpleHTTPServer involves web broswer for downloading files, it's not quick enough.

Python can't do ftpd by itself, but you can use netcat, nc:

nc is basically a built-in tool from any UNIX-like systems (even embedded systems), so it's perfect for "quick and temporary way to transfer files".

Step 1, on the receiver side, run:

nc -l 12345 | tar -xf -

this will listen on port 12345, waiting for data.

Step 2, on the sender side:

tar -cf - ALL_FILES_YOU_WANT_TO_SEND ... | nc $RECEIVER_IP 12345

You can also put pv in the middle to monitor the progress of transferring:

tar -cf - ALL_FILES_YOU_WANT_TO_SEND ...| pv | nc $RECEIVER_IP 12345

After the transferring is finished, both sides of nc will quit automatically, and job done.

Multiple INNER JOIN SQL ACCESS

Thanks HansUp for your answer, it is very helpful and it works!

I found three patterns working in Access, yours is the best, because it works in all cases.

  • INNER JOIN, your variant. I will call it "closed set pattern". It is possible to join more than two tables to the same table with good performance only with this pattern.

    SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
    FROM
         ((class
           INNER JOIN person AS cr 
           ON class.C_P_ClassRep=cr.P_Nr
         )
         INNER JOIN person AS cr2
         ON class.C_P_ClassRep2nd=cr2.P_Nr
      )
    

    ;

  • INNER JOIN "chained-set pattern"

    SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
    FROM person AS cr
    INNER JOIN ( class 
       INNER JOIN ( person AS cr2
       ) ON class.C_P_ClassRep2nd=cr2.P_Nr
    ) ON class.C_P_ClassRep=cr.P_Nr
    ;
    
  • CROSS JOIN with WHERE

    SELECT C_Name, cr.P_FirstName+" "+cr.P_SurName AS ClassRepresentativ, cr2.P_FirstName+" "+cr2.P_SurName AS ClassRepresentativ2nd
    FROM class, person AS cr, person AS cr2
    WHERE class.C_P_ClassRep=cr.P_Nr AND class.C_P_ClassRep2nd=cr2.P_Nr
    ;
    

WPF Binding StringFormat Short Date String

Be aware of the single quotes for the string format. This doesn't work:

    Content="{Binding PlannedDateTime, StringFormat={}{0:yy.MM.dd HH:mm}}"

while this does:

    Content="{Binding PlannedDateTime, StringFormat='{}{0:yy.MM.dd HH:mm}'}"

PHP preg replace only allow numbers

This should do what you want:

preg_replace("/[^0-9]/", "",$c);

Arrays in type script

This is a very c# type of code:

var bks: Book[] = new Book[2];

In Javascript / Typescript you don't allocate memory up front like that, and that means something completely different. This is how you would do what you want to do:

var bks: Book[] = [];
bks.push(new Book());
bks[0].Author = "vamsee";
bks[0].BookId = 1;
return bks.length;

Now to explain what new Book[2]; would mean. This would actually mean that call the new operator on the value of Book[2]. e.g.:

Book[2] = function (){alert("hey");}
var foo = new Book[2]

and you should see hey. Try it

build-impl.xml:1031: The module has not been deployed

  • Close Netbeans.
  • Delete all libraries in the folder "yourprojectfolder"\build\web\WEB-INF\lib
  • Open Netbeans.
  • Clean and Build project.
  • Deploy project.

How to play only the audio of a Youtube video using HTML 5?

Embed the video player and use CSS to hide the video. If you do it properly you may even be able to hide only the video and not the controls below it.

However, I'd recommend against it, because it will be a violation of YouTube TOS. Use your own server instead if you really want to play only audio.

curl : (1) Protocol https not supported or disabled in libcurl

I just recompiled curl with configure options pointing to the openssl 1.0.2g library folder and include folder, and I still get this message. When I do ldd on curl, it does not show that it uses either libcrypt.so or libssl.so, so I assume this must mean that even though the make and make install succeeded without errors, nevertheless curl does not have HTTPS support? Configure and make was as follows:

./configure --prefix=/local/scratch/PACKAGES/local --with-ssl=/local/scratch/PACKAGES/local/openssl/openssl-1.0.2g --includedir=/local/scratch/PACKAGES/local/include/openssl/openssl-1.0.2g
make
make test
make install

I should mention that libssl.so.1 is in /local/scratch/PACKAGES/local/lib. It is unclear whether the --with-ssl option should point there or to the directory where the openssl install placed the openssl.cnf file. I chose the latter. But if it were supposed to be the former, the make should have failed with an error that it couldn't find the library.

Python constructors and __init__

There is no notion of method overloading in Python. But you can achieve a similar effect by specifying optional and keyword arguments

Get a Windows Forms control by name in C#

this.Controls.Find(name, searchAllChildren) doesn't find ToolStripItem because ToolStripItem is not a Control

  using SWF = System.Windows.Forms;
  using NUF = NUnit.Framework;
  namespace workshop.findControlTest {
     [NUF.TestFixture]
     public class FormTest {
        [NUF.Test]public void Find_menu() {
           // == prepare ==
           var fileTool = new SWF.ToolStripMenuItem();
           fileTool.Name = "fileTool";
           fileTool.Text = "File";

           var menuStrip = new SWF.MenuStrip();
           menuStrip.Items.Add(fileTool);

           var form = new SWF.Form();
           form.Controls.Add(menuStrip);

           // == execute ==
           var ctrl = form.Controls.Find("fileTool", true);

           // == not found! ==
           NUF.Assert.That(ctrl.Length, NUF.Is.EqualTo(0)); 
        }
     }
  }

Error HRESULT E_FAIL has been returned from a call to a COM component VS2012 when debugging

Steps to resolve the issue:

1.Open your solution/Web Application in VS 2012 in administrator mode.

2.Go to IIS and Note down the settings for your application (e.g.Virtual directory name, Physical Path, Authentication setting and App pool used).

3.Remove (right click and select Remove) your application from Default Web Site. Refresh IIS.

4.Go back to VS 2012 and open settings (right click and select properties) for your web application.

5.Select Web.In Servers section make sure you have selected "Use Local IIS Web Server".

6.In Project Url textbox enter your application path (http://localhost/Application Path). Click on Create Virtual Directory.

7.Go to IIS and apply settings noted in step 2. Refresh IIS.

8.Go to VS 2012 and set this project as startup Project with appropriate page as startup page.

9.Click run button to start project in debug mode.

This resolved issue for me for web application which was migrated from VS 2010 to 2012.Hope this helps anyone looking for specific issue.

My machine configuration is: IIS 7.5.7600.16385

VS 2012 Professional

Windows 7 Enterprise (Version 6.1 - Build 7601:Service Pack 1)

How to change time in DateTime?

one liner

var date = DateTime.Now.Date.Add(new TimeSpan(4, 30, 0));

would bring back todays date with a time of 4:30:00, replace DateTime.Now with any date object

SQL providerName in web.config

System.Data.SqlClient is the .NET Framework Data Provider for SQL Server. ie .NET library for SQL Server.

I don't know where providerName=SqlServer comes from. Could you be getting this confused with the provider keyword in your connection string? (I know I was :) )

In the web.config you should have the System.Data.SqlClient as the value of the providerName attribute. It is the .NET Framework Data Provider you are using.

<connectionStrings>
   <add 
      name="LocalSqlServer" 
      connectionString="data source=.\SQLEXPRESS;Integrated Security=SSPI;AttachDBFilename=|DataDirectory|aspnetdb.mdf;User Instance=true" 
      providerName="System.Data.SqlClient"
   />
</connectionStrings>

See http://msdn.microsoft.com/en-US/library/htw9h4z3(v=VS.80).aspx

Why is this jQuery click function not working?

I found the best solution for this problem by using ON with $(document).

 $(document).on('click', '#yourid', function() { alert("hello"); });

for id start with see below:

$(document).on('click', 'div[id^="start"]', function() {
alert ('hello'); });

finally after 1 week I not need to add onclick triger. I hope this will help many people

JDBC ODBC Driver Connection

Didn't work with ODBC-Bridge for me too. I got the way around to initialize ODBC connection using ODBC driver.

 import java.sql.*;  
 public class UserLogin
 {
     public static void main(String[] args)
     {
        try
        {    
            Class.forName("sun.jdbc.odbc.JdbcOdbcDriver");

            // C:\\databaseFileName.accdb" - location of your database 
           String url = "jdbc:odbc:Driver={Microsoft Access Driver (*.mdb, *.accdb)};DBQ=" + "C:\\emp.accdb";

            // specify url, username, pasword - make sure these are valid 
            Connection conn = DriverManager.getConnection(url, "username", "password");

            System.out.println("Connection Succesfull");
         } 
         catch (Exception e) 
         {
            System.err.println("Got an exception! ");
            System.err.println(e.getMessage());

          }
      }
  }

How to query a MS-Access Table from MS-Excel (2010) using VBA

Option Explicit

Const ConnectionStrngAccessPW As String = _"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Users\BARON\Desktop\Test_DB-PW.accdb;
Jet OLEDB:Database Password=123pass;"

Const ConnectionStrngAccess As String = _"Provider=Microsoft.ACE.OLEDB.12.0;
Data Source=C:\Users\BARON\Desktop\Test_DB.accdb;
Persist Security Info=False;"

'C:\Users\BARON\Desktop\Test.accdb

Sub ModifyingExistingDataOnAccessDB()

    Dim TableConn As ADODB.Connection
    Dim TableData As ADODB.Recordset


    Set TableConn = New ADODB.Connection
    Set TableData = New ADODB.Recordset

    TableConn.ConnectionString = ConnectionStrngAccess

    TableConn.Open

On Error GoTo CloseConnection

    With TableData
        .ActiveConnection = TableConn
        '.Source = "SELECT Emp_Age FROM Roster WHERE Emp_Age > 40;"
        .Source = "Roster"
        .LockType = adLockOptimistic
        .CursorType = adOpenForwardOnly
        .Open
        On Error GoTo CloseRecordset

            Do Until .EOF
                If .Fields("Emp_Age").Value > 40 Then
                    .Fields("Emp_Age").Value = 40
                    .Update
                End If
                .MoveNext
            Loop
            .MoveFirst

        MsgBox "Update Complete"
    End With


CloseRecordset:
    TableData.CancelUpdate
    TableData.Close

CloseConnection:
    TableConn.Close

    Set TableConn = Nothing
    Set TableData = Nothing

End Sub

Sub AddingDataToAccessDB()

    Dim TableConn As ADODB.Connection
    Dim TableData As ADODB.Recordset
    Dim r As Range

    Set TableConn = New ADODB.Connection
    Set TableData = New ADODB.Recordset

    TableConn.ConnectionString = ConnectionStrngAccess

    TableConn.Open

On Error GoTo CloseConnection

    With TableData
        .ActiveConnection = TableConn
        .Source = "Roster"
        .LockType = adLockOptimistic
        .CursorType = adOpenForwardOnly
        .Open
        On Error GoTo CloseRecordset

        Sheet3.Activate
        For Each r In Range("B3", Range("B3").End(xlDown))

            MsgBox "Adding " & r.Offset(0, 1)
            .AddNew
            .Fields("Emp_ID").Value = r.Offset(0, 0).Value
            .Fields("Emp_Name").Value = r.Offset(0, 1).Value
            .Fields("Emp_DOB").Value = r.Offset(0, 2).Value
            .Fields("Emp_SOD").Value = r.Offset(0, 3).Value
            .Fields("Emp_EOD").Value = r.Offset(0, 4).Value
            .Fields("Emp_Age").Value = r.Offset(0, 5).Value
            .Fields("Emp_Gender").Value = r.Offset(0, 6).Value
            .Update

        Next r

        MsgBox "Update Complete"
    End With


CloseRecordset:
    TableData.Close

CloseConnection:
    TableConn.Close

    Set TableConn = Nothing
    Set TableData = Nothing

End Sub

Using Panel or PlaceHolder

A panel expands to a span (or a div), with it's content within it. A placeholder is just that, a placeholder that's replaced by whatever you put in it.

jQuery .live() vs .on() method for adding a click event after loading dynamic html

Try this:

$('#parent').on('click', '#child', function() {
    // Code
});

From the $.on() documentation:

Event handlers are bound only to the currently selected elements; they must exist on the page at the time your code makes the call to .on().

Your #child element doesn't exist when you call $.on() on it, so the event isn't bound (unlike $.live()). #parent, however, does exist, so binding the event to that is fine.

The second argument in my code above acts as a 'filter' to only trigger if the event bubbled up to #parent from #child.

Can't find System.Windows.Media namespace?

You can add PresentationCore.dll more conveniently by editing the project file. Add the following code into your csproj file:

<ItemGroup>
   <FrameworkReference Include="Microsoft.WindowsDesktop.App" />
</ItemGroup>

In your solution explorer, you now should see this framework listed, now. With that, you then can also refer to the classes provided by PresentationCore.dll.

Tool for comparing 2 binary files in Windows

I prefer to use objcopy to convert to hex, then use diff.

How can I use threading in Python?

Since this question was asked in 2010, there has been real simplification in how to do simple multithreading with Python with map and pool.

The code below comes from an article/blog post that you should definitely check out (no affiliation) - Parallelism in one line: A Better Model for Day to Day Threading Tasks. I'll summarize below - it ends up being just a few lines of code:

from multiprocessing.dummy import Pool as ThreadPool
pool = ThreadPool(4)
results = pool.map(my_function, my_array)

Which is the multithreaded version of:

results = []
for item in my_array:
    results.append(my_function(item))

Description

Map is a cool little function, and the key to easily injecting parallelism into your Python code. For those unfamiliar, map is something lifted from functional languages like Lisp. It is a function which maps another function over a sequence.

Map handles the iteration over the sequence for us, applies the function, and stores all of the results in a handy list at the end.

Enter image description here


Implementation

Parallel versions of the map function are provided by two libraries:multiprocessing, and also its little known, but equally fantastic step child:multiprocessing.dummy.

multiprocessing.dummy is exactly the same as multiprocessing module, but uses threads instead (an important distinction - use multiple processes for CPU-intensive tasks; threads for (and during) I/O):

multiprocessing.dummy replicates the API of multiprocessing, but is no more than a wrapper around the threading module.

import urllib2
from multiprocessing.dummy import Pool as ThreadPool

urls = [
  'http://www.python.org',
  'http://www.python.org/about/',
  'http://www.onlamp.com/pub/a/python/2003/04/17/metaclasses.html',
  'http://www.python.org/doc/',
  'http://www.python.org/download/',
  'http://www.python.org/getit/',
  'http://www.python.org/community/',
  'https://wiki.python.org/moin/',
]

# Make the Pool of workers
pool = ThreadPool(4)

# Open the URLs in their own threads
# and return the results
results = pool.map(urllib2.urlopen, urls)

# Close the pool and wait for the work to finish
pool.close()
pool.join()

And the timing results:

Single thread:   14.4 seconds
       4 Pool:   3.1 seconds
       8 Pool:   1.4 seconds
      13 Pool:   1.3 seconds

Passing multiple arguments (works like this only in Python 3.3 and later):

To pass multiple arrays:

results = pool.starmap(function, zip(list_a, list_b))

Or to pass a constant and an array:

results = pool.starmap(function, zip(itertools.repeat(constant), list_a))

If you are using an earlier version of Python, you can pass multiple arguments via this workaround).

(Thanks to user136036 for the helpful comment.)

How can I display a tooltip on an HTML "option" tag?

Why use a dropdown at all? The only way the user will see your explanatory text is by blindly hovering over one of the options.

I think it would be preferable to use a radio button group, and next to each item, put a tooltip icon indicating additional information, as well as displaying it after selection (like you currently have it).

I realize this doesn't exactly solve your problem, but I don't see the point in struggling with an html element that's notorious for its inflexibility when you could just use one that's better suited in the first place.

Doctrine findBy 'does not equal'

I solved this rather easily (without adding a method) so i'll share:

use Doctrine\Common\Collections\Criteria;

$repository->matching( Criteria::create()->where( Criteria::expr()->neq('id', 1) ) );

By the way, i'm using the Doctrine ORM module from within Zend Framework 2 and i'm not sure whether this would be compatible in any other case.

In my case, i was using a form element configuration like this: to show all roles except "guest" in a radio button array.

$this->add(array(
    'type' => 'DoctrineModule\Form\Element\ObjectRadio',
        'name' => 'roles',
        'options' => array(
            'label' => _('Roles'),
            'object_manager' => $this->getEntityManager(),
            'target_class'   => 'Application\Entity\Role',
            'property' => 'roleId',
            'find_method'    => array(
                'name'   => 'matching',
                'params' => array(
                    'criteria' => Criteria::create()->where(
                        Criteria::expr()->neq('roleId', 'guest')
                ),
            ),
        ),
    ),
));

How to draw vectors (physical 2D/3D vectors) in MATLAB?

I agree with Aamir that the submission arrow.m from Erik Johnson on the MathWorks File Exchange is a very nice option. You can use it to illustrate the different methods of vector addition like so:

  • Tip-to-tail method:

    o = [0 0 0];  %# Origin
    a = [2 3 5];  %# Vector 1
    b = [1 1 0];  %# Vector 2
    c = a+b;      %# Resultant
    arrowStarts = [o; a; o];        %# Starting points for arrows
    arrowEnds = [a; c; c];          %# Ending points for arrows
    arrow(arrowStarts,arrowEnds);   %# Plot arrows
    
  • Parallelogram method:

    o = [0 0 0];  %# Origin
    a = [2 3 5];  %# Vector 1
    b = [1 1 0];  %# Vector 2
    c = a+b;      %# Resultant
    arrowStarts = [o; o; o];        %# Starting points for arrows
    arrowEnds = [a; b; c];          %# Ending points for arrows
    arrow(arrowStarts,arrowEnds);   %# Plot arrows
    hold on;
    lineX = [a(1) b(1); c(1) c(1)];  %# X data for lines
    lineY = [a(2) b(2); c(2) c(2)];  %# Y data for lines
    lineZ = [a(3) b(3); c(3) c(3)];  %# Z data for lines
    line(lineX,lineY,lineZ,'Color','k','LineStyle',':');  %# Plot lines
    

What is the difference between PUT, POST and PATCH?

Quite logical the difference between PUT & PATCH w.r.t sending full & partial data for replacing/updating respectively. However, just couple of points as below

  1. Sometimes POST is considered as for updates w.r.t PUT for create
  2. Does HTTP mandates/checks for sending full vs partial data in PATCH? Otherwise, PATCH may be quite same as update as in PUT/POST

Using NULL in C++?

I never use NULL in my C or C++ code. 0 works just fine, as does if (ptrname). Any competent C or C++ programmer should know what those do.

Mongoose: CastError: Cast to ObjectId failed for value "[object Object]" at path "_id"

If you are having this issue and you are performing a populate somewhere along the lines, see this Mongoose issue.

Update to Mongoose 4.0 and the issue has been fixed.

Passing HTML to template using Flask/Jinja2

the ideal way is to

{{ something|safe }}

than completely turning off auto escaping.

Directly assigning values to C Pointers

The problem is that you're not initializing the pointer. You've created a pointer to "anywhere you want"—which could be the address of some other variable, or the middle of your code, or some memory that isn't mapped at all.

You need to create an int variable somewhere in memory for the int * variable to point at.

Your second example does this, but it does other things that aren't relevant here. Here's the simplest thing you need to do:

int main(){
    int variable;
    int *ptr = &variable;
    *ptr = 20;
    printf("%d", *ptr);
    return 0;
}

Here, the int variable isn't initialized—but that's fine, because you're just going to replace whatever value was there with 20. The key is that the pointer is initialized to point to the variable. In fact, you could just allocate some raw memory to point to, if you want:

int main(){
    void *memory = malloc(sizeof(int));
    int *ptr = (int *)memory;
    *ptr = 20;
    printf("%d", *ptr);
    free(memory);
    return 0;
}

SqlException from Entity Framework - New transaction is not allowed because there are other threads running in the session

Indeed you cannot save changes inside a foreach loop in C# using Entity Framework.

context.SaveChanges() method acts like a commit on a regular database system (RDMS).

Just make all changes (which Entity Framework will cache) and then save all of them at once calling SaveChanges() after the loop (outside of it), like a database commit command.

This works if you can save all changes at once.

How to repeat a char using printf?

In c++ you could use std::string to get repeated character

printf("%s",std::string(count,char).c_str());

For example:

printf("%s",std::string(5,'a').c_str());

output:

aaaaa

Mobile website "WhatsApp" button to send message to a specific number

Format to send a WhatsApp message to a specific number (updated Nov 2018)

<a href="https://wa.me/whatsappphonenumber/?text=urlencodedtext"></a>

where

whatsappphonenumber is a full phone number in international format

urlencodedtext is the URL-encoded pre-filled message.


Example:

  1. Create a link with a pre-filled message that will automatically appear in the text field of a chat, to be sent to a specific number

    Send I am interested in your car for sale to +001-(555)1234567

    https://wa.me/15551234567?text=I%20am%20interested%20in%20your%20car%20for%20sale

    Note :

    Use: https://wa.me/15551234567

    Don't use: https://wa.me/+001-(555)1234567

  2. Create a link with just a pre-filled message that will automatically appear in the text field of a chat, number will be chosen by the user

    Send I am enquiring about the apartment listing

    https://wa.me/?text=I%20am%20enquiring%20about%20the%20apartment%20listing

    After clicking on the link, user will be shown a list of contacts they can send the pre-filled message to.

For more information, see https://www.whatsapp.com/faq/en/general/26000030

--

P.S : Older format (before updation) for reference

<a href="https://api.whatsapp.com/send?phone=whatsappphonenumber&text=urlencodedtext"></a>

Java - sending HTTP parameters via POST method easily

Try this pattern:

public static PricesResponse getResponse(EventRequestRaw request) {

    // String urlParameters  = "param1=a&param2=b&param3=c";
    String urlParameters = Piping.serialize(request);

    HttpURLConnection conn = RestClient.getPOSTConnection(endPoint, urlParameters);

    PricesResponse response = null;

    try {
        // POST
        OutputStreamWriter writer = new OutputStreamWriter(conn.getOutputStream());
        writer.write(urlParameters);
        writer.flush();

        // RESPONSE
        BufferedReader reader = new BufferedReader(new InputStreamReader((conn.getInputStream()), StandardCharsets.UTF_8));
        String json = Buffering.getString(reader);
        response = (PricesResponse) Piping.deserialize(json, PricesResponse.class);

        writer.close();
        reader.close();

    } catch (Exception e) {
        e.printStackTrace();
    }

    conn.disconnect();

    System.out.println("PricesClient: " + response.toString());

    return response;
}

public static HttpURLConnection getPOSTConnection(String endPoint, String urlParameters) {

    return RestClient.getConnection(endPoint, "POST", urlParameters);

}


public static HttpURLConnection getConnection(String endPoint, String method, String urlParameters) {

    System.out.println("ENDPOINT " + endPoint + " METHOD " + method);
    HttpURLConnection conn = null;

    try {
        URL url = new URL(endPoint);
        conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod(method);
        conn.setDoOutput(true);
        conn.setRequestProperty("Content-Type", "text/plain");

    } catch (IOException e) {
        e.printStackTrace();
    }

    return conn;
}

Detect whether Office is 32bit or 64bit via the registry

Outlook Bitness registry key does not exist on my machine.

One way to determine Outlook Bitness is by examining Outlook.exe, itself and determine if it is 32bit or 64bit.

Specifically, you can check the [IMAGE_FILE_HEADER.Machine][1] type and this will return a value indicating processor type.

For an excellent background of this discussion, on reading the PE Header of a file read this (outdated link), which states;

The IMAGE_NT_HEADERS structure is the primary location where specifics of the PE file are stored. Its offset is given by the e_lfanew field in the IMAGE_DOS_HEADER at the beginning of the file. There are actually two versions of the IMAGE_NT_HEADER structure, one for 32-bit executables and the other for 64-bit versions. The differences are so minor that I'll consider them to be the same for the purposes of this discussion. The only correct, Microsoft-approved way of differentiating between the two formats is via the value of the Magic field in the IMAGE_OPTIONAL_HEADER (described shortly).

An IMAGE_NT_HEADER is comprised of three fields:

typedef struct _IMAGE_NT_HEADERS { DWORD Signature; IMAGE_FILE_HEADER FileHeader; IMAGE_OPTIONAL_HEADER32 OptionalHeader; } IMAGE_NT_HEADERS32, *PIMAGE_NT_HEADERS32;

and you can get the c# code here.

The Magic field is at the start of the IMAGE_OPTIONAL_HEADER structure, 2 bytes at offset 24 from the start of the _IMAGE_NT_HEADERS. It has values of 0x10B for 32-bit and 0x20B for 64-bit.

Call php function from JavaScript

PHP is evaluated at the server; javascript is evaluated at the client/browser, thus you can't call a PHP function from javascript directly. But you can issue an HTTP request to the server that will activate a PHP function, with AJAX.

Auto-increment primary key in SQL tables

  1. Presumably you are in the design of the table. If not: right click the table name - "Design".
  2. Click the required column.
  3. In "Column properties" (at the bottom), scroll to the "Identity Specification" section, expand it, then toggle "(Is Identity)" to "Yes".

enter image description here

Getting an object array from an Angular service

Take a look at your code :

 getUsers(): Observable<User[]> {
        return Observable.create(observer => {
            this.http.get('http://users.org').map(response => response.json();
        })
    }

and code from https://angular.io/docs/ts/latest/tutorial/toh-pt6.html (BTW. really good tutorial, you should check it out)

 getHeroes(): Promise<Hero[]> {
    return this.http.get(this.heroesUrl)
               .toPromise()
               .then(response => response.json().data as Hero[])
               .catch(this.handleError);
  }

The HttpService inside Angular2 already returns an observable, sou don't need to wrap another Observable around like you did here:

   return Observable.create(observer => {
        this.http.get('http://users.org').map(response => response.json()

Try to follow the guide in link that I provided. You should be just fine when you study it carefully.

---EDIT----

First of all WHERE you log the this.users variable? JavaScript isn't working that way. Your variable is undefined and it's fine, becuase of the code execution order!

Try to do it like this:

  getUsers(): void {
        this.userService.getUsers()
            .then(users => {
               this.users = users
               console.log('this.users=' + this.users);
            });


    }

See where the console.log(...) is!

Try to resign from toPromise() it's seems to be just for ppl with no RxJs background.

Catch another link: https://scotch.io/tutorials/angular-2-http-requests-with-observables Build your service once again with RxJs observables.

Carriage Return\Line feed in Java

If I understand you right, we talk about a text file attachment. Thats unfortunate because if it was the email's message body, you could always use "\r\n", referring to http://www.faqs.org/rfcs/rfc822.html

But as it's an attachment, you must live with system differences. If I were in your shoes, I would choose one of those options:

a) only support windows clients by using "\r\n" as line end.

b) provide two attachment files, one with linux format and one with windows format.

c) I don't know if the attachment is to be read by people or machines, but if it is people I would consider attaching an HTML file instead of plain text. more portable and much prettier, too :)

Git: Installing Git in PATH with GitHub client for Windows

I installed GitHubDesktop on Windows 10 and git.exe is located there:

C:\Users\john\AppData\Local\GitHubDesktop\app-0.7.2\resources\app\git\cmd\git.exe

CSS property to pad text inside of div

Just use div { padding: 20px; } and substract 40px from your original div width.

Like Philip Wills pointed out, you can also use box-sizing instead of substracting 40px:

div {
    padding: 20px;
    -moz-box-sizing: border-box; 
    box-sizing: border-box;
}

The -moz-box-sizing is for Firefox.

Add a scrollbar to a <textarea>

like this

css

textarea {

overflow:scroll;
height:100px;
}

keypress, ctrl+c (or some combo like that)

I couldn't get it to work with .keypress(), but it worked with the .keydown() function like this:

$(document).keydown(function(e) {
    if(e.key == "c" && e.ctrlKey) {
        console.log('ctrl+c was pressed');
    }
});

How to set some xlim and ylim in Seaborn lmplot facetgrid

You need to get hold of the axes themselves. Probably the cleanest way is to change your last row:

lm = sns.lmplot('X','Y',df,col='Z',sharex=False,sharey=False)

Then you can get hold of the axes objects (an array of axes):

axes = lm.axes

After that you can tweak the axes properties

axes[0,0].set_ylim(0,)
axes[0,1].set_ylim(0,)

creates:

enter image description here

Simple way to count character occurrences in a string

you can also use a for each loop. I think it is simpler to read.

int occurrences = 0;
for(char c : yourString.toCharArray()){
   if(c == '$'){
      occurrences++;
   }
}

HTML-Tooltip position relative to mouse pointer

This CAN be done with pure html and css. It may not be the best way but we all have different limitations. There are 3 ways that could be useful depending on what your specific circumstances are.

  1. The first involves overlaying an invisible table over top of your link with a hover action on each cell that displays an image.

_x000D_
_x000D_
#imagehover td:hover::after{_x000D_
  content: "             ";_x000D_
  white-space: pre;_x000D_
  background-image: url("http://www.google.com/images/srpr/logo4w.png");_x000D_
  position: relative;_x000D_
  left: 5px;_x000D_
  top: 5px;_x000D_
  font-size: 20px;_x000D_
  background-color: transparent;_x000D_
  background-position: 0px 0px;_x000D_
  background-size: 60px 20px;_x000D_
  background-repeat: no-repeat;_x000D_
  _x000D_
}_x000D_
_x000D_
_x000D_
#imagehover table, #imagehover th, #imagehover td {_x000D_
  border: 0px;_x000D_
  border-spacing: 0px;_x000D_
}
_x000D_
<a href="https://www.google.com">_x000D_
<table id="imagehover" style="width:50px;height:10px;z-index:9999;position:absolute" cellspacing="0">_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
<tr><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td><td></td></tr>_x000D_
_x000D_
</table>_x000D_
Google</a>
_x000D_
_x000D_
_x000D_

  1. The second relies on being able to create your own cursor image

_x000D_
_x000D_
#googleLink{_x000D_
_x000D_
cursor: url(https://winter-bush-d06c.sto.workers.dev/cursor-extern.php?id=98272),url(https://9dc1a5c00e8109665645209c2d036b1c.cloudflareworkers.com/cursor-extern.php?id=98272),auto;_x000D_
_x000D_
}
_x000D_
<a href="https://www.google.com" id="googleLink">Google</a>
_x000D_
_x000D_
_x000D_

  1. While the normal title tooltip doesn't technically allow images it does allow any unicode characters including block letters and emojis which may suite your needs.

_x000D_
_x000D_
<a href="https://www.google.com" title="??" alt="??">Google</a>
_x000D_
_x000D_
_x000D_

How to get full path of a file?

Beside "readlink -f" , another commonly used command:

$find  /the/long/path/but/I/can/use/TAB/to/auto/it/to/ -name myfile
/the/long/path/but/I/can/use/TAB/to/auto/it/to/myfile
$

This also give the full path and file name at console

Off-topic: This method just gives relative links, not absolute. The readlink -f command is the right one.

Hide Text with CSS, Best Practice?

Add .hide-text class to your span that has the text

.hide-text{
display:none;
 }

or make the text transparent

.hide-text{
 color:rgba(0,0,0,0);
 }

use according to your use case.

What is a classpath and how do I set it?

The classpath in this context is exactly what it is in the general context: anywhere the VM knows it can find classes to be loaded, and resources as well (such as output.vm in your case).

I'd understand Velocity expects to find a file named output.vm anywhere in "no package". This can be a JAR, regular folder, ... The root of any of the locations in the application's classpath.

How to check string length with JavaScript

Leaving a reply (and an answer to the question title), For the future googlers...

You can use .length to get the length of a string.

var x = 'Mozilla'; var empty = '';

console.log('Mozilla is ' + x.length + ' code units long');

/*"Mozilla is 7 code units long" */

console.log('The empty string has a length of ' + empty.length);

/*"The empty string has a length of 0" */

If you intend to get the length of a textarea say id="txtarea" then you can use the following code.

txtarea = document.getElementById('txtarea');
console.log(txtarea.value.length);

You should be able to get away with using this with BMP Unicode symbols. If you want to support "non BMP Symbols" like (), then its an edge case, and you need to find some work around.

Table Naming Dilemma: Singular vs. Plural Names

If we look at MS SQL Server's system tables, their names as assigned by Microsoft are in plural.

The Oracle's system tables are named in singular. Although a few of them are plural. Oracle recommends plural for user-defined table names. That doesn't make much sense that they recommend one thing and follow another. That the architects at these two software giants have named their tables using different conventions, doesn't make much sense either... After all, what are these guys ... PhD's?

I do remember in academia, the recommendation was singular.

For example, when we say:

select OrderHeader.ID FROM OrderHeader WHERE OrderHeader.Reference = 'ABC123'

maybe b/c each ID is selected from a particular single row ...?

Where can I download IntelliJ IDEA Color Schemes?

I know I'm late to the party but just wanted to mention that the Jumpout II theme really is amazing.. I have a lot of themes and this one really is great for a # of reasons..

  1. it handles glare very well (yes even pure black on matte screens can produce glare, unfortunately my new matte monitor - has a more "glary" coating than my old one).. this is a grayish-black background

  2. it has enough colors that you can easily see read even dense code - some themes that look nice at first use too much of one color and it makes dense code harder to digest

  3. the comments are all gray, this is even better than dark green which is my 2nd favorite choice.. it really helps the code pop out..

so basically this is a great anti-glare, anti-dense-code theme

honorable mentions (I think these all can be found on that same site, although I'm not sure I spelled all of them correctly)

  1. Dark Flash Builder (really great but at first the use of red can be confusing, but it is really one of its strengths. I had to modify it to make my error text highlighting different - I settled on some bright red underlined text)
  2. Gedit Original Oblivion
  3. Leone Dark II
  4. Visual Studio 2013
  5. Retta (very halloweeny)

and for white / beige / blue (in that order)

  1. Oughsumm (wow best white ever, possibly the most legible theme I've ever seen - however, white is too bright for me in my current office situation, although occasionally I do switch to this when I want to quickly review a lot of code before a commit), also it is comfortably legible at 1 point smaller than all dark themes I've used.
  2. humane-ist
  3. rubyblue

p.s. please note I change the font of all the themes I use to Consolas 11 or 12 depending on the monitor. Consolas I find to be the best programming font out there. It looks great, easy to read and very well suited to LCD anti-aliasing. I tried so many programming fonts but I always come back to this one quickly. And it is not too narrow.. I'm not in the narrow camp, I believe narrow font aficionados don't program with ultra wide monitors - maybe program on a macbook or something just as bad :)

p.p.s I know solarized is supposed to be some kind of ultimate, magical, life-enhancing nirvana-inducing theme but I just don't get it.. I tried but failed to find it anything but annoying